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
b9d0086a8124d7ad368a48cdc6a3faf0cacbab88
7,645,041,787,459
9d83abd53919165c127631d5a0b2756c3746bf62
/app/src/main/java/com/example/gradetracker_pj1/EditAssignment.java
8a4b89308920f472c1e040104a39cdca796880f0
[]
no_license
raul676/GradeTrackerpj1
https://github.com/raul676/GradeTrackerpj1
edb1ec29a125e0018d1bf166ee35f7bc3e60ae1c
fa1cc0b21132081db7a9f9b17a9dac63bdc36ffd
refs/heads/master
2022-12-14T14:32:15.668000
2020-09-17T23:37:39
2020-09-17T23:37:39
292,146,365
0
2
null
false
2020-09-14T19:52:20
2020-09-02T01:21:26
2020-09-14T19:37:25
2020-09-14T19:52:19
270
0
1
0
Java
false
false
package com.example.gradetracker_pj1; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.gradetracker_pj1.model.Assignment; import com.example.gradetracker_pj1.model.GradeRoom; import java.util.List; public class EditAssignment extends AppCompatActivity { List <Assignment> assignmentList; public int asign =0; @Override protected void onCreate(Bundle saveInstanceState) { Log.d("LoginActivity", "onCreate called"); super.onCreate(saveInstanceState); setContentView(R.layout.editassignment_activity); Button edit_assignment= findViewById(R.id.enter_course_edit_button); edit_assignment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** A try to get the assignment Id and parse the assignment Id into an integer */ try { EditText assign_id = findViewById(R.id.edit_assignment_id); asign = Integer.parseInt(assign_id.getText().toString()); assignmentList = GradeRoom.getGradeRoom(EditAssignment.this).dao().searchAssignment(asign); /** If the assignment list is null the user is told the course can not be found */ if (assignmentList == null) { AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("No assignment found."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } /** A catch to throw an expection if the user enters an invalid assignment id */ }catch (Exception e){ AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Enter a valid Assignment ID."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); /**The Recycler view to see the user's current Assignments */ assignmentList = GradeRoom.getGradeRoom(EditAssignment.this).dao().searchAssignment(asign); Log.d("ViewCourseActivity", "EditAssignments" + assignmentList.size()); RecyclerView rv = findViewById(R.id.recycler_view_edit_assignment); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(new Adapter()); Button edit_assingment2 = findViewById(R.id.edit_assignment_button2); edit_assingment2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /**A try to allow users to edit assignment information, if the assignment list is null the user has to enter the assignment id, else * the assignment will update with edited information */ try { EditText detail = findViewById(R.id.edit_details); EditText date = findViewById(R.id.edit_due_date); String details = detail.getText().toString(); String due_date = date.getText().toString(); if (assignmentList == null) { AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Confirm Assignment ID first."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } else { assignmentList.get(0).setDetails(details); assignmentList.get(0).setDue_date(due_date); GradeRoom.getGradeRoom(EditAssignment.this).dao().updateAssignment(assignmentList); AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Assignment has been edited!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog dialog = builder.create(); dialog.show(); } /** A catch used to throw an exception if the user has an invaild Assignment */ }catch (Exception e){ AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Must search for valid hw assignment first!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); /** If the user clicks the back button they will be lead back to main menu */ Button back_button = findViewById(R.id.BackBtn_2); back_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /**The Adapter for the RecyclerView for ItemHolders, the constructor helps create the view * and the bind view binds the items to the holder */ private class Adapter extends RecyclerView.Adapter<ItemHolder> { @Override public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(EditAssignment.this); return new ItemHolder(layoutInflater, parent); } @Override public void onBindViewHolder(ItemHolder holder, int position) { holder.bind(assignmentList.get(position)); } @Override public int getItemCount() { return assignmentList.size(); } } private class ItemHolder extends RecyclerView.ViewHolder { public ItemHolder(LayoutInflater inflater, ViewGroup parent) { super(inflater.inflate(R.layout.item, parent, false)); } public void bind(Assignment f) { TextView item = itemView.findViewById(R.id.item_id); item.setText(f.toString()); } } }
UTF-8
Java
8,143
java
EditAssignment.java
Java
[]
null
[]
package com.example.gradetracker_pj1; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.gradetracker_pj1.model.Assignment; import com.example.gradetracker_pj1.model.GradeRoom; import java.util.List; public class EditAssignment extends AppCompatActivity { List <Assignment> assignmentList; public int asign =0; @Override protected void onCreate(Bundle saveInstanceState) { Log.d("LoginActivity", "onCreate called"); super.onCreate(saveInstanceState); setContentView(R.layout.editassignment_activity); Button edit_assignment= findViewById(R.id.enter_course_edit_button); edit_assignment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** A try to get the assignment Id and parse the assignment Id into an integer */ try { EditText assign_id = findViewById(R.id.edit_assignment_id); asign = Integer.parseInt(assign_id.getText().toString()); assignmentList = GradeRoom.getGradeRoom(EditAssignment.this).dao().searchAssignment(asign); /** If the assignment list is null the user is told the course can not be found */ if (assignmentList == null) { AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("No assignment found."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } /** A catch to throw an expection if the user enters an invalid assignment id */ }catch (Exception e){ AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Enter a valid Assignment ID."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); /**The Recycler view to see the user's current Assignments */ assignmentList = GradeRoom.getGradeRoom(EditAssignment.this).dao().searchAssignment(asign); Log.d("ViewCourseActivity", "EditAssignments" + assignmentList.size()); RecyclerView rv = findViewById(R.id.recycler_view_edit_assignment); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(new Adapter()); Button edit_assingment2 = findViewById(R.id.edit_assignment_button2); edit_assingment2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /**A try to allow users to edit assignment information, if the assignment list is null the user has to enter the assignment id, else * the assignment will update with edited information */ try { EditText detail = findViewById(R.id.edit_details); EditText date = findViewById(R.id.edit_due_date); String details = detail.getText().toString(); String due_date = date.getText().toString(); if (assignmentList == null) { AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Confirm Assignment ID first."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } else { assignmentList.get(0).setDetails(details); assignmentList.get(0).setDue_date(due_date); GradeRoom.getGradeRoom(EditAssignment.this).dao().updateAssignment(assignmentList); AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Assignment has been edited!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog dialog = builder.create(); dialog.show(); } /** A catch used to throw an exception if the user has an invaild Assignment */ }catch (Exception e){ AlertDialog.Builder builder = new AlertDialog.Builder(EditAssignment.this); builder.setTitle("Must search for valid hw assignment first!"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /**Closes alert Dialog after okay clicked*/ } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); /** If the user clicks the back button they will be lead back to main menu */ Button back_button = findViewById(R.id.BackBtn_2); back_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /**The Adapter for the RecyclerView for ItemHolders, the constructor helps create the view * and the bind view binds the items to the holder */ private class Adapter extends RecyclerView.Adapter<ItemHolder> { @Override public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(EditAssignment.this); return new ItemHolder(layoutInflater, parent); } @Override public void onBindViewHolder(ItemHolder holder, int position) { holder.bind(assignmentList.get(position)); } @Override public int getItemCount() { return assignmentList.size(); } } private class ItemHolder extends RecyclerView.ViewHolder { public ItemHolder(LayoutInflater inflater, ViewGroup parent) { super(inflater.inflate(R.layout.item, parent, false)); } public void bind(Assignment f) { TextView item = itemView.findViewById(R.id.item_id); item.setText(f.toString()); } } }
8,143
0.567113
0.565885
183
43.497269
31.995539
148
false
false
0
0
0
0
0
0
0.535519
false
false
12
edf17f7cbea430cbd44252a0d90d9f636c3e2dc1
30,279,519,483,654
6ba446e7f44735efee64c8af0a385a27b05f991f
/acl-biz/src/main/java/com/kingbo401/acl/dao/PermissionGroupRefDAO.java
a7cb908f3f47dba0d4b968f9ef45f1095d83c6a0
[]
no_license
kingbo401/ice-acl
https://github.com/kingbo401/ice-acl
3a706c425aa76fc8bbefaf023e4797c570164b82
1b6807b435da7b480db1f7350cb66500fc82c998
refs/heads/master
2022-07-05T14:50:22.427000
2020-06-27T13:10:56
2020-06-27T13:10:56
131,106,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kingbo401.acl.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.kingbo401.acl.model.entity.PermissionDO; import com.kingbo401.acl.model.entity.PermissionGroupRefDO; import com.kingbo401.acl.model.entity.param.PermissionGroupRefQueryParam; public interface PermissionGroupRefDAO { int batchCreate(@Param("list")List<PermissionGroupRefDO> list); int updateRefsStatus(@Param("groupId") long groupId, @Param("permissionIds") List<Long> permissionIds, @Param("status")Integer status); List<PermissionDO> listPermission(PermissionGroupRefQueryParam param); List<PermissionDO> pagePermission(PermissionGroupRefQueryParam param); long countPermission(PermissionGroupRefQueryParam param); }
UTF-8
Java
759
java
PermissionGroupRefDAO.java
Java
[]
null
[]
package com.kingbo401.acl.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.kingbo401.acl.model.entity.PermissionDO; import com.kingbo401.acl.model.entity.PermissionGroupRefDO; import com.kingbo401.acl.model.entity.param.PermissionGroupRefQueryParam; public interface PermissionGroupRefDAO { int batchCreate(@Param("list")List<PermissionGroupRefDO> list); int updateRefsStatus(@Param("groupId") long groupId, @Param("permissionIds") List<Long> permissionIds, @Param("status")Integer status); List<PermissionDO> listPermission(PermissionGroupRefQueryParam param); List<PermissionDO> pagePermission(PermissionGroupRefQueryParam param); long countPermission(PermissionGroupRefQueryParam param); }
759
0.805007
0.789196
21
35.142857
37.038315
139
false
false
0
0
0
0
0
0
0.619048
false
false
12
3e1fb7846e572f654ec835aecdcc2d28a89e00e1
32,925,219,308,296
18d414cc829f8408222c3fc1d4d4581e6f4a53a5
/shop2019101511/src/main/java/com/bawei/shop2019101511/view/AdderView.java
f0c61947f6531f096c3f011a611fcafb977cef66
[]
no_license
Yuchenlei0426/dimensionality-e-commerce
https://github.com/Yuchenlei0426/dimensionality-e-commerce
2f4831a179430a60ad1f23c908d2306e6524669d
d36b11128b808349d5f46936384cd2d342dc53d9
refs/heads/master
2020-09-08T15:02:49.532000
2019-11-12T11:08:11
2019-11-12T11:08:11
221,167,216
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bawei.shop2019101511.view; import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bawei.shop2019101511.R; public class AdderView extends LinearLayout { private TextView tv_number; public AdderView(Context context) { super(context); initView(context); } public AdderView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); initAttr(context,attrs); } public AdderView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); initAttr(context,attrs); } private void initAttr(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AdderView); String string = typedArray.getString(R.styleable.AdderView_text); tv_number.setText(string); } private void initView(Context context) { View view = LayoutInflater.from(context).inflate(R.layout.adder_subtractor, this, true); TextView but_minus = view.findViewById(R.id.but_minus); tv_number = view.findViewById(R.id.tv_number); TextView but_add = view.findViewById(R.id.but_add); but_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = tv_number.getText().toString(); if (!TextUtils.isEmpty(number)) { int num = Integer.parseInt(number); num++; tv_number.setText(num+""); if (onClicked!=null) { onClicked.onClicked(AdderView.this,num); } } } }); but_minus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = tv_number.getText().toString(); if (!TextUtils.isEmpty(number)) { int num = Integer.parseInt(number); if (num>1) { num--; tv_number.setText(num+""); if (onClicked!=null) { onClicked.onClicked(AdderView.this,num); } }else { Toast.makeText(context, "不能再减了", Toast.LENGTH_SHORT).show(); } } } }); } public void setCont(int cont){ tv_number.setText(String.valueOf(cont)); } onClicked onClicked; public void setOnClicked(AdderView.onClicked onClicked) { this.onClicked = onClicked; } public interface onClicked{ void onClicked(AdderView adderView,int now); } }
UTF-8
Java
3,128
java
AdderView.java
Java
[]
null
[]
package com.bawei.shop2019101511.view; import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bawei.shop2019101511.R; public class AdderView extends LinearLayout { private TextView tv_number; public AdderView(Context context) { super(context); initView(context); } public AdderView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); initAttr(context,attrs); } public AdderView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); initAttr(context,attrs); } private void initAttr(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AdderView); String string = typedArray.getString(R.styleable.AdderView_text); tv_number.setText(string); } private void initView(Context context) { View view = LayoutInflater.from(context).inflate(R.layout.adder_subtractor, this, true); TextView but_minus = view.findViewById(R.id.but_minus); tv_number = view.findViewById(R.id.tv_number); TextView but_add = view.findViewById(R.id.but_add); but_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = tv_number.getText().toString(); if (!TextUtils.isEmpty(number)) { int num = Integer.parseInt(number); num++; tv_number.setText(num+""); if (onClicked!=null) { onClicked.onClicked(AdderView.this,num); } } } }); but_minus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String number = tv_number.getText().toString(); if (!TextUtils.isEmpty(number)) { int num = Integer.parseInt(number); if (num>1) { num--; tv_number.setText(num+""); if (onClicked!=null) { onClicked.onClicked(AdderView.this,num); } }else { Toast.makeText(context, "不能再减了", Toast.LENGTH_SHORT).show(); } } } }); } public void setCont(int cont){ tv_number.setText(String.valueOf(cont)); } onClicked onClicked; public void setOnClicked(AdderView.onClicked onClicked) { this.onClicked = onClicked; } public interface onClicked{ void onClicked(AdderView adderView,int now); } }
3,128
0.581783
0.575048
95
31.821053
23.323347
96
false
false
0
0
0
0
0
0
0.652632
false
false
12
07a2795dbbdb75d016bbc597d69c5d411c9a038b
10,136,122,822,801
c1e3ee8269b3f8c6d4578e398c93c7719403ef73
/src/test/java/stepdefinition/StepDefinitions.java
d629c069e0d8c33cb72c96fc2ee53a47a7e199fc
[]
no_license
IrinaCh29/lesson
https://github.com/IrinaCh29/lesson
d662e7aa66c92e91d697815c102f9e25929fc1f1
1798af6d77b935ff47cf26d0794aaf0e5ef2510d
refs/heads/master
2022-12-24T03:52:34.131000
2020-09-11T19:47:59
2020-09-11T19:47:59
288,803,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stepdefinition; import com.google.common.io.Files; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.Scenario; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import pages.CreateIssueForm; import pages.HomePage; import pages.LoginPage; import utils.WebDriverFactory; import java.io.File; import java.io.IOException; public class StepDefinitions { @Before public void beforeCucumberScenario(Scenario scenario) { WebDriverFactory.createInstance("Chrome"); } @After public void afterCucumberScenario(Scenario scenario) { if (scenario.getStatus().toString().contains("FAILED")) { try { takeScreenshot(); } catch (IOException e) { e.printStackTrace(); } } WebDriverFactory.getDriver().close(); } public void takeScreenshot() throws IOException { File scrFile = ((TakesScreenshot) WebDriverFactory.getDriver()).getScreenshotAs(OutputType.FILE); File trgtFile = new File(System.getProperty("user.dir") + "//screenshots/screenshot.png"); System.out.println("SAVING Screenshot to " + trgtFile.getAbsolutePath()); trgtFile.getParentFile().mkdir(); trgtFile.createNewFile(); Files.copy(scrFile, trgtFile); } @Then("^I navigate to Jira Login Page$") public void navigateToLoginPage() { new LoginPage().navigateTo(); } @Then("^I enter user name - \"(.*?)\"$") public void enterUserName(String userName) { new LoginPage().enterUserName(userName); } @Then("^I enter password - \"(.*?)\"$") public void enterPassword(String password) { new LoginPage().enterPassword(password); } @Then("^I click on the login button$") public void clickLoginButton() { new LoginPage().clickLogin(); } @When("^I am on the Home Page$") public void atTheHomePage() { assert new HomePage().onPage(); } @When("^I debug$") public void debug() { int a = 0; } @When("^I click on Create button$") public void clickOnCreateButton() { new HomePage().clickCreateIssue(); } @Then("I see {string}") public void errorMessage(String message) { if (new LoginPage().errorMessageIsPresent(message)) { System.out.println("Test Pass"); } else { System.out.println("Test Failed"); } } @When("^I click Create button$") public void clickCreate() { new HomePage().clickCreateIssue(); } @Then("^I am in the Create Issue form$") public void projectFieldIsClickable() { new CreateIssueForm().projectFieldIsClickable(); } @When("^I fill Project field - \"(.*?)\"$") public void fillProjectField(String projectName) { new CreateIssueForm().projectFieldIsClickable(); new CreateIssueForm().clearProjectField(); new CreateIssueForm().enterProjectName(projectName); new CreateIssueForm().tabProjectName(); } @Then("^I fill Issue Type field - \"(.*?)\"$") public void fillIssueTypeField(String issueTypeName) { new CreateIssueForm().issueTypeFieldIsClickable(); new CreateIssueForm().clearIssueTypeField(); new CreateIssueForm().enterIssueTypeName(issueTypeName); new CreateIssueForm().tabIssueType(); } @Then("^I fill Summary field - \"(.*?)\"$") public void fillSummaryField(String summaryName) { new CreateIssueForm().summaryFieldIsClickable(); new CreateIssueForm().clearSummaryField(); new CreateIssueForm().enterSummaryName(summaryName); new CreateIssueForm().tabSummary(); } @Then("^I fill Reporter field - \"(.*?)\"$") public void fillReporterField(String reporterName) { new CreateIssueForm().reporterFieldIsClickable(); new CreateIssueForm().clearReporterField(); new CreateIssueForm().enterReporterName(reporterName); new CreateIssueForm().tabReporter(); } @When("^I click Submit button$") public void clickSubmit() { new CreateIssueForm().clickSubmit(); } @Then("^Pop up with number of created issue is shown$") public void popUpIsDisplayed() { new CreateIssueForm().popUpIssueName(); } }
UTF-8
Java
4,117
java
StepDefinitions.java
Java
[]
null
[]
package stepdefinition; import com.google.common.io.Files; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.Scenario; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import pages.CreateIssueForm; import pages.HomePage; import pages.LoginPage; import utils.WebDriverFactory; import java.io.File; import java.io.IOException; public class StepDefinitions { @Before public void beforeCucumberScenario(Scenario scenario) { WebDriverFactory.createInstance("Chrome"); } @After public void afterCucumberScenario(Scenario scenario) { if (scenario.getStatus().toString().contains("FAILED")) { try { takeScreenshot(); } catch (IOException e) { e.printStackTrace(); } } WebDriverFactory.getDriver().close(); } public void takeScreenshot() throws IOException { File scrFile = ((TakesScreenshot) WebDriverFactory.getDriver()).getScreenshotAs(OutputType.FILE); File trgtFile = new File(System.getProperty("user.dir") + "//screenshots/screenshot.png"); System.out.println("SAVING Screenshot to " + trgtFile.getAbsolutePath()); trgtFile.getParentFile().mkdir(); trgtFile.createNewFile(); Files.copy(scrFile, trgtFile); } @Then("^I navigate to Jira Login Page$") public void navigateToLoginPage() { new LoginPage().navigateTo(); } @Then("^I enter user name - \"(.*?)\"$") public void enterUserName(String userName) { new LoginPage().enterUserName(userName); } @Then("^I enter password - \"(.*?)\"$") public void enterPassword(String password) { new LoginPage().enterPassword(password); } @Then("^I click on the login button$") public void clickLoginButton() { new LoginPage().clickLogin(); } @When("^I am on the Home Page$") public void atTheHomePage() { assert new HomePage().onPage(); } @When("^I debug$") public void debug() { int a = 0; } @When("^I click on Create button$") public void clickOnCreateButton() { new HomePage().clickCreateIssue(); } @Then("I see {string}") public void errorMessage(String message) { if (new LoginPage().errorMessageIsPresent(message)) { System.out.println("Test Pass"); } else { System.out.println("Test Failed"); } } @When("^I click Create button$") public void clickCreate() { new HomePage().clickCreateIssue(); } @Then("^I am in the Create Issue form$") public void projectFieldIsClickable() { new CreateIssueForm().projectFieldIsClickable(); } @When("^I fill Project field - \"(.*?)\"$") public void fillProjectField(String projectName) { new CreateIssueForm().projectFieldIsClickable(); new CreateIssueForm().clearProjectField(); new CreateIssueForm().enterProjectName(projectName); new CreateIssueForm().tabProjectName(); } @Then("^I fill Issue Type field - \"(.*?)\"$") public void fillIssueTypeField(String issueTypeName) { new CreateIssueForm().issueTypeFieldIsClickable(); new CreateIssueForm().clearIssueTypeField(); new CreateIssueForm().enterIssueTypeName(issueTypeName); new CreateIssueForm().tabIssueType(); } @Then("^I fill Summary field - \"(.*?)\"$") public void fillSummaryField(String summaryName) { new CreateIssueForm().summaryFieldIsClickable(); new CreateIssueForm().clearSummaryField(); new CreateIssueForm().enterSummaryName(summaryName); new CreateIssueForm().tabSummary(); } @Then("^I fill Reporter field - \"(.*?)\"$") public void fillReporterField(String reporterName) { new CreateIssueForm().reporterFieldIsClickable(); new CreateIssueForm().clearReporterField(); new CreateIssueForm().enterReporterName(reporterName); new CreateIssueForm().tabReporter(); } @When("^I click Submit button$") public void clickSubmit() { new CreateIssueForm().clickSubmit(); } @Then("^Pop up with number of created issue is shown$") public void popUpIsDisplayed() { new CreateIssueForm().popUpIssueName(); } }
4,117
0.694195
0.693952
141
28.205673
21.754112
101
false
false
0
0
0
0
0
0
0.390071
false
false
12
d717e10e1079fb45fb405ea00addda52c399bbfb
24,017,457,128,857
e0c28830b2d297ba12bba75efd8f0cd6d6208005
/test/TesterVolvo240.java
16ed449da6146485f9b73c55b4e542bb4cdc7fb0
[]
no_license
Willeeez/F-rdig-Labb-1-a
https://github.com/Willeeez/F-rdig-Labb-1-a
8dc91ff0e540ec6c56769ed537bdddfee2e7af67
3ca96a1c7a1ceccb577222338445e8bc5c53702e
refs/heads/main
2023-01-13T17:11:17.756000
2020-11-11T07:56:27
2020-11-11T07:56:27
311,775,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; public class TesterVolvo240 extends Volvo240{ Volvo240 nyVolvo240 = new Volvo240(); @Test public void testStartEngineGivesCurrentSpeed() {// Should give a value of 0.1 nyVolvo240.startEngine(); assertEquals(0.1, nyVolvo240.getCurrentSpeed()); } @Test public void testIfSpeedFactorWorks() { nyVolvo240.enginePower = 10; nyVolvo240.speedFactor(); assertEquals(false, nyVolvo240.getCurrentSpeed() == nyVolvo240.speedFactor()); } @Test public void testIfIncrementSpeedWorks(){ // Should only allow inputs between 0 and 1 nyVolvo240.incrementSpeed(0.5); assertEquals(true, nyVolvo240.intervalChangeSpeed); } @Test public void testIfDecrementSpeedWorks(){ // Should only allow inputs between 0 and 1 nyVolvo240.decrementSpeed(0.5); assertEquals(true, nyVolvo240.intervalChangeSpeed); } @Test public void testIfBrakeIntervalWorks() { // Should only allow inputs between 0 and 1 nyVolvo240.startEngine(); nyVolvo240.brake(0.1); } @Test public void testIfCarMoves() { nyVolvo240.startEngine(); // Should give speed 0.1 nyVolvo240.move();// Which means that one move should get me -0.1 in the Y-direction since its headed south assertEquals(-0.1,nyVolvo240.getCurrentPositionY()); } }
UTF-8
Java
1,526
java
TesterVolvo240.java
Java
[]
null
[]
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; public class TesterVolvo240 extends Volvo240{ Volvo240 nyVolvo240 = new Volvo240(); @Test public void testStartEngineGivesCurrentSpeed() {// Should give a value of 0.1 nyVolvo240.startEngine(); assertEquals(0.1, nyVolvo240.getCurrentSpeed()); } @Test public void testIfSpeedFactorWorks() { nyVolvo240.enginePower = 10; nyVolvo240.speedFactor(); assertEquals(false, nyVolvo240.getCurrentSpeed() == nyVolvo240.speedFactor()); } @Test public void testIfIncrementSpeedWorks(){ // Should only allow inputs between 0 and 1 nyVolvo240.incrementSpeed(0.5); assertEquals(true, nyVolvo240.intervalChangeSpeed); } @Test public void testIfDecrementSpeedWorks(){ // Should only allow inputs between 0 and 1 nyVolvo240.decrementSpeed(0.5); assertEquals(true, nyVolvo240.intervalChangeSpeed); } @Test public void testIfBrakeIntervalWorks() { // Should only allow inputs between 0 and 1 nyVolvo240.startEngine(); nyVolvo240.brake(0.1); } @Test public void testIfCarMoves() { nyVolvo240.startEngine(); // Should give speed 0.1 nyVolvo240.move();// Which means that one move should get me -0.1 in the Y-direction since its headed south assertEquals(-0.1,nyVolvo240.getCurrentPositionY()); } }
1,526
0.690695
0.635649
46
32.173912
30.838503
115
false
false
0
0
0
0
0
0
0.5
false
false
12
4f808b000d8bef06cce75a3658752b8f1ea14cc8
27,633,819,588,277
c1cab5c7af3ea0ae6f3b4d620df16144b10f4628
/src/main/java/com/uniteproject/pojo/BannerUrl.java
7d528e7a6c3a58bfa304423d25c42e405b5c8ed3
[]
no_license
JiXiangLongBoy/unionPro
https://github.com/JiXiangLongBoy/unionPro
f08b41a29a9fd2f629960774e4aabb2a39129cb9
bf6eb91d9feb7d78d122d1e9171d9a937a8ed69e
refs/heads/master
2020-06-21T08:05:43.032000
2019-07-26T07:08:58
2019-07-26T07:08:58
197,390,086
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uniteproject.pojo; import com.fasterxml.jackson.annotation.JsonInclude; public class BannerUrl { @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl01; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl02; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl03; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl04; public String getBannerUrl01() { return bannerUrl01; } public void setBannerUrl01(String bannerUrl01) { this.bannerUrl01 = bannerUrl01; } public String getBannerUrl02() { return bannerUrl02; } public void setBannerUrl02(String bannerUrl02) { this.bannerUrl02 = bannerUrl02; } public String getBannerUrl03() { return bannerUrl03; } public void setBannerUrl03(String bannerUrl03) { this.bannerUrl03 = bannerUrl03; } public String getBannerUrl04() { return bannerUrl04; } public void setBannerUrl04(String bannerUrl04) { this.bannerUrl04 = bannerUrl04; } @Override public String toString() { return "BannerUrl{" + "bannerUrl01='" + bannerUrl01 + '\'' + ", bannerUrl02='" + bannerUrl02 + '\'' + ", bannerUrl03='" + bannerUrl03 + '\'' + ", bannerUrl04='" + bannerUrl04 + '\'' + '}'; } }
UTF-8
Java
1,449
java
BannerUrl.java
Java
[]
null
[]
package com.uniteproject.pojo; import com.fasterxml.jackson.annotation.JsonInclude; public class BannerUrl { @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl01; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl02; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl03; @JsonInclude(JsonInclude.Include.NON_NULL) private String bannerUrl04; public String getBannerUrl01() { return bannerUrl01; } public void setBannerUrl01(String bannerUrl01) { this.bannerUrl01 = bannerUrl01; } public String getBannerUrl02() { return bannerUrl02; } public void setBannerUrl02(String bannerUrl02) { this.bannerUrl02 = bannerUrl02; } public String getBannerUrl03() { return bannerUrl03; } public void setBannerUrl03(String bannerUrl03) { this.bannerUrl03 = bannerUrl03; } public String getBannerUrl04() { return bannerUrl04; } public void setBannerUrl04(String bannerUrl04) { this.bannerUrl04 = bannerUrl04; } @Override public String toString() { return "BannerUrl{" + "bannerUrl01='" + bannerUrl01 + '\'' + ", bannerUrl02='" + bannerUrl02 + '\'' + ", bannerUrl03='" + bannerUrl03 + '\'' + ", bannerUrl04='" + bannerUrl04 + '\'' + '}'; } }
1,449
0.623188
0.573499
59
23.559322
20.000229
56
false
false
0
0
0
0
0
0
0.305085
false
false
12
db094387670a2a065dce1a88170c8683ccc005b1
23,132,693,892,895
acd9c8e5fc347de3dbf11aae75f6d725a532e620
/src/main/java/kehao/emulator/EmulatorArena.java
635447defab19522d5a74216978aeea75cf56451
[]
no_license
v5kehao/kh
https://github.com/v5kehao/kh
3be90a768fadeeff52cb4cf7746f11db6a4d2f4f
f72a775c7b3f8d6d61f04b3edb07b8b8e863468e
refs/heads/master
2020-05-13T15:50:56.030000
2013-12-27T17:08:30
2013-12-27T17:08:30
12,743,556
1
3
null
false
2013-12-07T00:40:37
2013-09-11T00:05:05
2013-12-07T00:32:14
2013-12-07T00:31:35
1,687
0
2
1
Java
null
null
package kehao.emulator; import java.util.LinkedHashMap; import java.util.Map; import kehao.emulator.game.model.basic.ArenaCompetitors; import kehao.emulator.game.model.basic.BattleNormal; import kehao.emulator.game.model.basic.Thieves; import kehao.emulator.game.model.response.*; import kehao.exception.ServerNotAvailableException; import kehao.exception.WrongCredentialException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class EmulatorArena { @Autowired private UnknownErrorHandler unknownErrorHandler; @Autowired private EmulatorCore core; public ArenaCompetitors getCompetitors(String username) throws ServerNotAvailableException, WrongCredentialException { ArenaGetCompetitorsResponse response = core.gameDoAction(username, "arena.php", "GetCompetitors", null, ArenaGetCompetitorsResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } ArenaCompetitors competitors = response.getData(); return competitors; } public BattleNormal freeFight(String username, long competitor, boolean forChip) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); if(!forChip) { params.put("NoChip", Integer.toString(1)); } params.put("isManual", Integer.toString(0)); params.put("competitor", Long.toString(competitor)); ArenaFreeFightResponse response = core.gameDoAction(username, "arena.php", "FreeFight", params, ArenaFreeFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public BattleNormal rankFight(String username, int rank) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); params.put("CompetitorRank", Integer.toString(rank)); ArenaFreeFightResponse response = core.gameDoAction(username, "arena.php", "RankFight", params, ArenaFreeFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public Thieves getThieves(String username) throws ServerNotAvailableException, WrongCredentialException { ArenaGetThievesResponse response = core.gameDoAction(username, "arena.php", "GetThieves", null, ArenaGetThievesResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public BattleNormal thievesFight(String username, long id) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); params.put("UserThievesId", Long.toString(id)); ArenaThievesFightResponse response = core.gameDoAction(username, "arena.php", "ThievesFight", params, ArenaThievesFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } }
UTF-8
Java
3,504
java
EmulatorArena.java
Java
[]
null
[]
package kehao.emulator; import java.util.LinkedHashMap; import java.util.Map; import kehao.emulator.game.model.basic.ArenaCompetitors; import kehao.emulator.game.model.basic.BattleNormal; import kehao.emulator.game.model.basic.Thieves; import kehao.emulator.game.model.response.*; import kehao.exception.ServerNotAvailableException; import kehao.exception.WrongCredentialException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class EmulatorArena { @Autowired private UnknownErrorHandler unknownErrorHandler; @Autowired private EmulatorCore core; public ArenaCompetitors getCompetitors(String username) throws ServerNotAvailableException, WrongCredentialException { ArenaGetCompetitorsResponse response = core.gameDoAction(username, "arena.php", "GetCompetitors", null, ArenaGetCompetitorsResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } ArenaCompetitors competitors = response.getData(); return competitors; } public BattleNormal freeFight(String username, long competitor, boolean forChip) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); if(!forChip) { params.put("NoChip", Integer.toString(1)); } params.put("isManual", Integer.toString(0)); params.put("competitor", Long.toString(competitor)); ArenaFreeFightResponse response = core.gameDoAction(username, "arena.php", "FreeFight", params, ArenaFreeFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public BattleNormal rankFight(String username, int rank) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); params.put("CompetitorRank", Integer.toString(rank)); ArenaFreeFightResponse response = core.gameDoAction(username, "arena.php", "RankFight", params, ArenaFreeFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public Thieves getThieves(String username) throws ServerNotAvailableException, WrongCredentialException { ArenaGetThievesResponse response = core.gameDoAction(username, "arena.php", "GetThieves", null, ArenaGetThievesResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } public BattleNormal thievesFight(String username, long id) throws ServerNotAvailableException, WrongCredentialException { Map<String, String> params = new LinkedHashMap<>(); params.put("UserThievesId", Long.toString(id)); ArenaThievesFightResponse response = core.gameDoAction(username, "arena.php", "ThievesFight", params, ArenaThievesFightResponse.class); if(response.badRequest()) { unknownErrorHandler.print(username, response.getMessage()); } return response.getData(); } }
3,504
0.690639
0.690068
80
42.799999
39.022877
143
false
false
0
0
0
0
0
0
0.9875
false
false
12
81f7e13d5d1df997a67eaedef6d8d435fb330317
28,509,992,924,320
a0945abdaff02be65e4fe7af1b418e0eb4cbe1dd
/orgPg.java
7f386e462a52129ce4bdc1ec12318d686dfecd10
[]
no_license
twhite14/vado
https://github.com/twhite14/vado
a417a37727bc2a9dfab6e8e388976fed5d4da485
81d65e804c7bd3893f85876bc6dfee3da519c9af
refs/heads/master
2021-01-17T08:50:56.960000
2015-08-11T04:54:21
2015-08-11T04:54:21
33,163,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.michael.mainpage; /** * From Mike * This loads user info from organization page and puts the class into the array list * The list needs to be moved to the server and not in the Phone so we don't waste phone memory. * * End of Mike **/ import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import java.util.ArrayList; import android.widget.Button; public class orgPg extends ActionBarActivity { //for organization private String stringName; private String stringCategory = ""; private String stringWebsite =""; private String stringAddress =""; private String stringPhone =""; private String stringDescription = ""; private EditText nameOrg; private EditText categoryOrg; private EditText website; private EditText address; private EditText phone; private EditText description; //array list for orgs public ArrayList<org> Orgs = new ArrayList<org>(); //information for events made by organizations public ArrayList<event> happenings = new ArrayList<event>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_org_pg); } public void getInfoOrg(View v) { //bring info in from text filds set them to strings nameOrg = (EditText) findViewById(R.id.editText4); stringName = nameOrg.getText().toString(); categoryOrg = (EditText) findViewById(R.id.editText5); stringCategory = categoryOrg.getText().toString(); website = (EditText) findViewById(R.id.editText7); stringWebsite = website.getText().toString(); address = (EditText) findViewById(R.id.editText8); stringAddress = address.getText().toString(); phone = (EditText) findViewById(R.id.editText9); stringPhone = phone.getText().toString(); /* description = (EditText) findViewById(R.id.editText); stringDescription = description.getText().toString(); */ //make new class org club = new org(stringName, stringCategory,stringWebsite,stringAddress,stringPhone, stringDescription); Orgs.add(club); onClickOrg(v); } //takes user to main screen public void onClickOrg(View v) { //takes you to main class when finished with editing org Intent i = new Intent(getApplicationContext(),MainScreenStudent.class); startActivity(i); } //add events public void addEventOnClick() { event thing = new event(); happenings.add(thing); } @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_org_pg, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
3,519
java
orgPg.java
Java
[ { "context": "package com.example.michael.mainpage;\n\n/**\n * From Mike\n * This loads user info from organization page", "end": 52, "score": 0.7089419960975647, "start": 51, "tag": "NAME", "value": "M" } ]
null
[]
package com.example.michael.mainpage; /** * From Mike * This loads user info from organization page and puts the class into the array list * The list needs to be moved to the server and not in the Phone so we don't waste phone memory. * * End of Mike **/ import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import java.util.ArrayList; import android.widget.Button; public class orgPg extends ActionBarActivity { //for organization private String stringName; private String stringCategory = ""; private String stringWebsite =""; private String stringAddress =""; private String stringPhone =""; private String stringDescription = ""; private EditText nameOrg; private EditText categoryOrg; private EditText website; private EditText address; private EditText phone; private EditText description; //array list for orgs public ArrayList<org> Orgs = new ArrayList<org>(); //information for events made by organizations public ArrayList<event> happenings = new ArrayList<event>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_org_pg); } public void getInfoOrg(View v) { //bring info in from text filds set them to strings nameOrg = (EditText) findViewById(R.id.editText4); stringName = nameOrg.getText().toString(); categoryOrg = (EditText) findViewById(R.id.editText5); stringCategory = categoryOrg.getText().toString(); website = (EditText) findViewById(R.id.editText7); stringWebsite = website.getText().toString(); address = (EditText) findViewById(R.id.editText8); stringAddress = address.getText().toString(); phone = (EditText) findViewById(R.id.editText9); stringPhone = phone.getText().toString(); /* description = (EditText) findViewById(R.id.editText); stringDescription = description.getText().toString(); */ //make new class org club = new org(stringName, stringCategory,stringWebsite,stringAddress,stringPhone, stringDescription); Orgs.add(club); onClickOrg(v); } //takes user to main screen public void onClickOrg(View v) { //takes you to main class when finished with editing org Intent i = new Intent(getApplicationContext(),MainScreenStudent.class); startActivity(i); } //add events public void addEventOnClick() { event thing = new event(); happenings.add(thing); } @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_org_pg, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3,519
0.673771
0.672066
120
28.325001
25.306509
114
false
false
0
0
0
0
0
0
0.491667
false
false
12
3135b3961fad6a7b647e052434d43a649e70ad0d
22,153,441,353,179
8e22ab1cb2e3292166e5a2b5ed0a07d25f5b155c
/src/com/minos/design/pattern/creational/factorymethod/PythonVideo.java
3d29ace6d980aba0f5634a1bcd5ce44b3ce04e7b
[]
no_license
minos-ty/DesignPattern
https://github.com/minos-ty/DesignPattern
75eb043d1a1c2cc012abe02d6c63860927667ecc
621e63054e3e2aacdb7368a6c695c7431649e62d
refs/heads/master
2023-01-14T15:43:02.153000
2020-11-22T14:08:39
2020-11-22T14:08:39
314,828,567
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.minos.design.pattern.creational.factorymethod; /** * @Author: minos * @Date: 2020/11/21 23:24 */ public class PythonVideo extends Video{ @Override public void produce() { System.out.println("录制PYTHON学习视频"); } }
UTF-8
Java
260
java
PythonVideo.java
Java
[ { "context": "pattern.creational.factorymethod;\n\n/**\n * @Author: minos\n * @Date: 2020/11/21 23:24\n */\npublic class Pytho", "end": 81, "score": 0.9994959831237793, "start": 76, "tag": "USERNAME", "value": "minos" } ]
null
[]
package com.minos.design.pattern.creational.factorymethod; /** * @Author: minos * @Date: 2020/11/21 23:24 */ public class PythonVideo extends Video{ @Override public void produce() { System.out.println("录制PYTHON学习视频"); } }
260
0.665323
0.616935
13
18.076923
18.382523
58
false
false
0
0
0
0
0
0
0.153846
false
false
12
1848c1eae8fa2475b7c91b53f50edfc7ca21d39f
11,106,785,449,027
abb46fb506f4827ddbb910b75889ba8f15b250d2
/src/main/java/com/tripcaddie/frontend/trip/service/TripService.java
b1c86376792ccbcbc86cba0c097586143a860537
[]
no_license
jeevanmysore/tripacaddie
https://github.com/jeevanmysore/tripacaddie
023f13a5e3f0e2a54971816a649c7e3f04897121
abab7bfc8baf8f45467c335ecf0bcca6c171674c
refs/heads/master
2021-01-10T08:57:58.479000
2015-10-28T11:59:28
2015-10-28T11:59:28
45,109,131
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tripcaddie.frontend.trip.service; import java.util.ArrayList; import com.tripcaddie.backend.trip.model.TripMember; import com.tripcaddie.frontend.trip.dto.TripDto; import com.tripcaddie.frontend.trip.dto.TripLeaderDelegationDto; import com.tripcaddie.frontend.trip.dto.TripMemberDto; public interface TripService { public Integer createTrip(String tripName,String destination,String startDate,String message,String endDate,String promoCode,String annualTrip,String path) throws Exception; public ArrayList<TripDto> getTripsOfUser() throws Exception; public ArrayList<TripDto> getTripsOfUser(int userId) throws Exception; public TripDto getTrip(int tripId) throws Exception; public ArrayList<TripMemberDto> getTripMembers(int tripId) throws Exception; public ArrayList<TripMember> getTripMembersbyOrder(int tripId) throws Exception; public ArrayList<TripMemberDto> getTripMemberswithoutCurrentmember(int tripId) throws Exception; public void deleteTrip(int tripId) throws Exception; public TripMemberDto getTripMember(int memberId) throws Exception; public void addTripMember(int tripId,String email,String role) throws Exception; public void deleteTripMember(int memberId) throws Exception; public void editTrip(Integer tripId, String tripName,String courseId,String startDate,String message, String endDate,String promoCode,String annualTrip, String path)throws Exception; public boolean isExistTrip(String tripName,String userName) throws Exception; //For invitation public ArrayList<TripMemberDto> getTripInvitation(String email) throws Exception; public void acceptInvite(int memberId) throws Exception; public void declineInvite(int memberId) throws Exception; //For Trip Leader deegation public ArrayList<TripLeaderDelegationDto> getTripLeaderDelegations() throws Exception; public void changeTripMemberRole(int optionId,int memberId) throws Exception; }
UTF-8
Java
1,909
java
TripService.java
Java
[]
null
[]
package com.tripcaddie.frontend.trip.service; import java.util.ArrayList; import com.tripcaddie.backend.trip.model.TripMember; import com.tripcaddie.frontend.trip.dto.TripDto; import com.tripcaddie.frontend.trip.dto.TripLeaderDelegationDto; import com.tripcaddie.frontend.trip.dto.TripMemberDto; public interface TripService { public Integer createTrip(String tripName,String destination,String startDate,String message,String endDate,String promoCode,String annualTrip,String path) throws Exception; public ArrayList<TripDto> getTripsOfUser() throws Exception; public ArrayList<TripDto> getTripsOfUser(int userId) throws Exception; public TripDto getTrip(int tripId) throws Exception; public ArrayList<TripMemberDto> getTripMembers(int tripId) throws Exception; public ArrayList<TripMember> getTripMembersbyOrder(int tripId) throws Exception; public ArrayList<TripMemberDto> getTripMemberswithoutCurrentmember(int tripId) throws Exception; public void deleteTrip(int tripId) throws Exception; public TripMemberDto getTripMember(int memberId) throws Exception; public void addTripMember(int tripId,String email,String role) throws Exception; public void deleteTripMember(int memberId) throws Exception; public void editTrip(Integer tripId, String tripName,String courseId,String startDate,String message, String endDate,String promoCode,String annualTrip, String path)throws Exception; public boolean isExistTrip(String tripName,String userName) throws Exception; //For invitation public ArrayList<TripMemberDto> getTripInvitation(String email) throws Exception; public void acceptInvite(int memberId) throws Exception; public void declineInvite(int memberId) throws Exception; //For Trip Leader deegation public ArrayList<TripLeaderDelegationDto> getTripLeaderDelegations() throws Exception; public void changeTripMemberRole(int optionId,int memberId) throws Exception; }
1,909
0.837087
0.837087
37
50.594593
43.512321
183
false
false
0
0
0
0
0
0
1.891892
false
false
12
993e2dde5b43e03c0815b74eb7b10cf2c123835a
360,777,313,569
439b672d555b38788a130e1e52c532530421b196
/src/main/java/com/alatfa/gps/model/Chauffeur.java
b431de5fec8b092144ec237fef8aa461bf2c363b
[]
no_license
yassinejebli/alatfaGPS
https://github.com/yassinejebli/alatfaGPS
448b6f2a0a6cb4a1a4d41b93d1e440d6a4b5d24e
8c732048b250e142bfb67c338c04f8f7ac305990
refs/heads/master
2021-01-17T17:50:12.577000
2016-06-21T19:49:40
2016-06-21T19:49:40
60,814,295
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alatfa.gps.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.HashSet; import java.util.Set; @Document public class Chauffeur { @Id private String id; private String cin; private String name; private String email; private String tel; private Utilisateur utilisateur; public Utilisateur getUtilisateur() { return utilisateur; } public void setUtilisateur(Utilisateur utilisateur) { this.utilisateur = utilisateur; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCin() { return cin; } public void setCin(String cin) { this.cin = cin; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public Chauffeur() { } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UTF-8
Java
1,310
java
Chauffeur.java
Java
[]
null
[]
package com.alatfa.gps.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.HashSet; import java.util.Set; @Document public class Chauffeur { @Id private String id; private String cin; private String name; private String email; private String tel; private Utilisateur utilisateur; public Utilisateur getUtilisateur() { return utilisateur; } public void setUtilisateur(Utilisateur utilisateur) { this.utilisateur = utilisateur; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCin() { return cin; } public void setCin(String cin) { this.cin = cin; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public Chauffeur() { } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,310
0.617557
0.617557
77
16.012987
16.213264
62
false
false
0
0
0
0
0
0
0.311688
false
false
12
c3cbb6f63cd868953b3054923bac9c7f9c38798a
9,861,244,969,488
12604b12c67c6c037f402e514c5d77cea412ea98
/brainfuck4j.model/src/com/google/code/brainfuck4j/model/brainfuck/BrainfuckFactory.java
3a5eafef0ad7eb3a1d58c8952e7ed49e57c6f422
[]
no_license
jfbenckhuijsen/brainfuck4j
https://github.com/jfbenckhuijsen/brainfuck4j
a3bae7d71025fdaf62f55c36526c282c11ca4c96
3723f2f3c5cff64e457a890261f1f1939ded2bbd
refs/heads/master
2021-01-10T09:08:48.575000
2009-04-03T08:53:17
2009-04-03T08:53:17
45,494,840
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <copyright> * </copyright> * * $Id$ */ package com.google.code.brainfuck4j.model.brainfuck; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see com.google.code.brainfuck4j.model.brainfuck.BrainfuckPackage * @generated */ public interface BrainfuckFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ BrainfuckFactory eINSTANCE = com.google.code.brainfuck4j.model.brainfuck.impl.BrainfuckFactoryImpl.init(); /** * Returns a new object of class '<em>Program</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Program</em>'. * @generated */ Program createProgram(); /** * Returns a new object of class '<em>Program Header</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Program Header</em>'. * @generated */ ProgramHeader createProgramHeader(); /** * Returns a new object of class '<em>Unary Expression</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Unary Expression</em>'. * @generated */ UnaryExpression createUnaryExpression(); /** * Returns a new object of class '<em>Block Expression</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Block Expression</em>'. * @generated */ BlockExpression createBlockExpression(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ BrainfuckPackage getBrainfuckPackage(); } //BrainfuckFactory
UTF-8
Java
1,875
java
BrainfuckFactory.java
Java
[]
null
[]
/** * <copyright> * </copyright> * * $Id$ */ package com.google.code.brainfuck4j.model.brainfuck; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see com.google.code.brainfuck4j.model.brainfuck.BrainfuckPackage * @generated */ public interface BrainfuckFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ BrainfuckFactory eINSTANCE = com.google.code.brainfuck4j.model.brainfuck.impl.BrainfuckFactoryImpl.init(); /** * Returns a new object of class '<em>Program</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Program</em>'. * @generated */ Program createProgram(); /** * Returns a new object of class '<em>Program Header</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Program Header</em>'. * @generated */ ProgramHeader createProgramHeader(); /** * Returns a new object of class '<em>Unary Expression</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Unary Expression</em>'. * @generated */ UnaryExpression createUnaryExpression(); /** * Returns a new object of class '<em>Block Expression</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Block Expression</em>'. * @generated */ BlockExpression createBlockExpression(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ BrainfuckPackage getBrainfuckPackage(); } //BrainfuckFactory
1,875
0.6352
0.6336
73
24.684931
23.012728
107
false
false
0
0
0
0
0
0
0.753425
false
false
12
7d487b04ed4e1796b792dd3e2a2c9460b3ffec75
31,980,326,508,476
16a8a60010a22e1c3329aa21742e3ac299e89ae9
/Functions/FillInFunctions.java
90fbe2e126075ec694c5730221ca01226950dcb6
[]
no_license
nickazua/ProgramByDoing
https://github.com/nickazua/ProgramByDoing
b8cf13f4c0c95deae8bce5926b215b337ad2c990
c496dbe72ea7436c49e44d375f80b7c6547aab1f
refs/heads/master
2021-01-01T18:41:48.473000
2014-08-20T06:51:00
2014-08-20T06:51:00
22,519,120
15
11
null
null
null
null
null
null
null
null
null
null
null
null
null
// Fill-In Functions - Fix the broken functions and function calls. public class FillInFunctions { public static void main( String[] args ) { // Fill in the function calls where appropriate. System.out.println("Watch as we demonstrate functions."); System.out.println(); System.out.println("I'm going to get a random character from A-Z"); char c = randchar(); // randchar(); System.out.println("The character is: " + c ); System.out.println(); System.out.println("Now let's count from -10 to 10"); int begin, end; begin = -10; end = 10; counter(begin, end); System.out.println("How was that?"); System.out.println(); System.out.println("Now we take the absolute value of a number."); int x, y = 99; x = -10; y = abso(x); System.out.println("|" + x + "| = " + y ); System.out.println(); System.out.println("That's all. This program has been brought to you by:"); credits(); } public static void credits() // No parameters. { // displays some boilerplate text saying who wrote this program, etc. System.out.println(); System.out.println("programmed by Graham Mitchell"); System.out.println("modified by Nick Azua"); System.out.print("This code is distributed under the terms of the standard "); System.out.println("BSD license. Do with it as you wish."); } public static char randchar() // No parameters. { // chooses a random character in the range "A" to "Z" int numval; char charval; // pick a random number from 0 to 25 numval = (int)(Math.random()*26); // now add that offset to the value of the letter 'A' charval = (char) ('A' + numval); return charval; } public static void counter( int start, int stop ) // Parameters are: // int start; // int stop; { // counts from start to stop by ones int ctr; ctr = start; while ( ctr <= stop ) { System.out.print(ctr + " "); ctr = ctr+1; } } public static int abso( int value ) // Parameters are: // int value; { // finds the absolute value of the parameter int absval; if ( value < 0 ) absval = -value; else absval = value; return absval; } }
UTF-8
Java
2,161
java
FillInFunctions.java
Java
[ { "context": "out.println();\n\t\tSystem.out.println(\"programmed by Graham Mitchell\");\n\t\tSystem.out.println(\"modified by Nick Azua\");", "end": 1132, "score": 0.9998729825019836, "start": 1117, "tag": "NAME", "value": "Graham Mitchell" }, { "context": "aham Mitchell\");\n\t\tSystem.out.println(\"modified by Nick Azua\");\n\t\tSystem.out.print(\"This code is distributed u", "end": 1179, "score": 0.9998854994773865, "start": 1170, "tag": "NAME", "value": "Nick Azua" } ]
null
[]
// Fill-In Functions - Fix the broken functions and function calls. public class FillInFunctions { public static void main( String[] args ) { // Fill in the function calls where appropriate. System.out.println("Watch as we demonstrate functions."); System.out.println(); System.out.println("I'm going to get a random character from A-Z"); char c = randchar(); // randchar(); System.out.println("The character is: " + c ); System.out.println(); System.out.println("Now let's count from -10 to 10"); int begin, end; begin = -10; end = 10; counter(begin, end); System.out.println("How was that?"); System.out.println(); System.out.println("Now we take the absolute value of a number."); int x, y = 99; x = -10; y = abso(x); System.out.println("|" + x + "| = " + y ); System.out.println(); System.out.println("That's all. This program has been brought to you by:"); credits(); } public static void credits() // No parameters. { // displays some boilerplate text saying who wrote this program, etc. System.out.println(); System.out.println("programmed by <NAME>"); System.out.println("modified by <NAME>"); System.out.print("This code is distributed under the terms of the standard "); System.out.println("BSD license. Do with it as you wish."); } public static char randchar() // No parameters. { // chooses a random character in the range "A" to "Z" int numval; char charval; // pick a random number from 0 to 25 numval = (int)(Math.random()*26); // now add that offset to the value of the letter 'A' charval = (char) ('A' + numval); return charval; } public static void counter( int start, int stop ) // Parameters are: // int start; // int stop; { // counts from start to stop by ones int ctr; ctr = start; while ( ctr <= stop ) { System.out.print(ctr + " "); ctr = ctr+1; } } public static int abso( int value ) // Parameters are: // int value; { // finds the absolute value of the parameter int absval; if ( value < 0 ) absval = -value; else absval = value; return absval; } }
2,149
0.639519
0.630727
102
20.17647
21.370867
80
false
false
0
0
0
0
0
0
1.784314
false
false
12
49e2687aa23aed1f51f42643dbd45ebaa89abb50
21,157,008,953,759
d7c5bcd8edff1c07936869cca83069c227a45041
/src/test/java/com/zous/catmaster/controller/BaseControllerTest.java
9c9edb80c9b1c1f5da2f55025df8e5de436a8b43
[]
no_license
251687230/CatMasterServer
https://github.com/251687230/CatMasterServer
bbbf7050a92e09dea5999f89054228574bea537f
eb2fc6d14e609e64a49d09ca9dc860a8f576b1df
refs/heads/master
2022-04-09T02:04:59.064000
2020-02-09T15:57:39
2020-02-09T15:57:39
225,342,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zous.catmaster.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.zous.catmaster.CatmasterApplication; import com.zous.catmaster.utils.SecurityUtils; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.UUID; @RunWith(SpringRunner.class) @SpringBootTest(classes = CatmasterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests { protected MockMvc mvc; protected static String VERIFE_KEY = "zous.catmaster@2019"; protected final String USER_NAME = "13278820324"; protected final String PASSWORD = "123456"; Gson gson = new Gson(); @Autowired protected WebApplicationContext context; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) //.apply(springSecurity()) .build(); } protected void addHead(MockHttpServletRequestBuilder builder) throws NoSuchAlgorithmException { String random = UUID.randomUUID().toString(); String timeStamp = String.valueOf(Calendar.getInstance().getTimeInMillis()); builder.header("Random", random); builder.header("Timestamp",timeStamp); builder.header("EncoderStr", SecurityUtils.md5(timeStamp + random + VERIFE_KEY)); } }
UTF-8
Java
2,046
java
BaseControllerTest.java
Java
[ { "context": "vc mvc;\n protected static String VERIFE_KEY = \"zous.catmaster@2019\";\n protected final String USER_NAME = \"1327882", "end": 1236, "score": 0.979164719581604, "start": 1217, "tag": "KEY", "value": "zous.catmaster@2019" }, { "context": "78820324\";\n protected final String PASSWORD = \"123456\";\n Gson gson = new Gson();\n\n @Autowired\n ", "end": 1338, "score": 0.9993190169334412, "start": 1332, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package com.zous.catmaster.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.zous.catmaster.CatmasterApplication; import com.zous.catmaster.utils.SecurityUtils; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.UUID; @RunWith(SpringRunner.class) @SpringBootTest(classes = CatmasterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests { protected MockMvc mvc; protected static String VERIFE_KEY = "zous.catmaster@2019"; protected final String USER_NAME = "13278820324"; protected final String PASSWORD = "<PASSWORD>"; Gson gson = new Gson(); @Autowired protected WebApplicationContext context; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) //.apply(springSecurity()) .build(); } protected void addHead(MockHttpServletRequestBuilder builder) throws NoSuchAlgorithmException { String random = UUID.randomUUID().toString(); String timeStamp = String.valueOf(Calendar.getInstance().getTimeInMillis()); builder.header("Random", random); builder.header("Timestamp",timeStamp); builder.header("EncoderStr", SecurityUtils.md5(timeStamp + random + VERIFE_KEY)); } }
2,050
0.773705
0.760997
49
40.7551
28.867416
113
false
false
0
0
0
0
0
0
0.693878
false
false
12
42f21ae688852054a65a76fa02835efd8ae298d2
7,584,912,299,506
22b6eecadc8ee5bdf76fb4aa2a56c30d86f2251b
/JXiangCun/src/com/jxc/entity/Sequence.java
aa3d4597767eaa122c096b8a53880a51c3895924
[]
no_license
chrgu000/WanHeng
https://github.com/chrgu000/WanHeng
2c3048788739a9813c5e4c88b0de881a2ae02333
b2ff8b73ed3c5726b7b86962b6617a1ab196da7e
refs/heads/master
2020-05-23T13:59:05.208000
2018-09-19T06:15:26
2018-09-19T06:15:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jxc.entity; public class Sequence { private Integer id; private String sequence; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } @Override public String toString() { return "Sequence [id=" + id + ", sequence=" + sequence + "]"; } }
UTF-8
Java
409
java
Sequence.java
Java
[]
null
[]
package com.jxc.entity; public class Sequence { private Integer id; private String sequence; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } @Override public String toString() { return "Sequence [id=" + id + ", sequence=" + sequence + "]"; } }
409
0.701711
0.701711
23
16.782608
15.531054
62
false
false
0
0
0
0
0
0
0.608696
false
false
12
3f3b84c5053e3448eb2ed26e71339f339e7d8378
9,002,251,453,573
44f5a633b14b00e75e111c93d378395c7c087b68
/src/javafxmvc/model/domain/Cidade.java
502f5aa411aa5bd1e505ec2a8d117835ee254523
[]
no_license
jonatanbandeira/JAVAFX
https://github.com/jonatanbandeira/JAVAFX
5fc0f5dac65eeebda7ef78235cf93f308389e007
edc9a4e1e0967bba2da7a17ac5757ae9a9171b65
refs/heads/main
2023-06-11T10:54:28.025000
2021-06-30T02:17:53
2021-06-30T02:17:53
377,752,675
0
1
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 javafxmvc.model.domain; import java.io.Serializable; /** * * @author victor */ public class Cidade implements Serializable { private int cdCidade; private String nomeCidade; public Cidade() { } public Cidade(int cdCidade, String nomeCidade){ this.cdCidade = cdCidade; this.nomeCidade = nomeCidade; } public int getCdCidade() { return cdCidade; } public void setCdCidade(int cdCidade) { this.cdCidade = cdCidade; } public String getNomeCidade() { return nomeCidade; } public void setNomeCidade(String nomeCidade) { this.nomeCidade = nomeCidade; } @Override public String toString() { return this.nomeCidade; } }
UTF-8
Java
967
java
Cidade.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n *\n * @author victor\n */\npublic class Cidade implements Serializable {", "end": 272, "score": 0.8012875914573669, "start": 266, "tag": "USERNAME", "value": "victor" } ]
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 javafxmvc.model.domain; import java.io.Serializable; /** * * @author victor */ public class Cidade implements Serializable { private int cdCidade; private String nomeCidade; public Cidade() { } public Cidade(int cdCidade, String nomeCidade){ this.cdCidade = cdCidade; this.nomeCidade = nomeCidade; } public int getCdCidade() { return cdCidade; } public void setCdCidade(int cdCidade) { this.cdCidade = cdCidade; } public String getNomeCidade() { return nomeCidade; } public void setNomeCidade(String nomeCidade) { this.nomeCidade = nomeCidade; } @Override public String toString() { return this.nomeCidade; } }
967
0.633919
0.633919
46
20.043478
18.756977
79
false
false
0
0
0
0
0
0
0.326087
false
false
12
9325dfff59ea9a402dc02118cff335b478c73a09
38,732,015,084,725
af18180cf7acc6b0b1a470cdf75ebea2a995ea2b
/MyCustomView/app/src/main/java/com/keyc/mycustomview/adapter/ContactSortAdapter.java
a0618659fc2ef7da779e38c75d42372f0c155b16
[]
no_license
kcmars/html
https://github.com/kcmars/html
e72105df68d13a93b2f6218693f69e7cb1836a6c
7f950f3df66020adf5ae7b91a478078b1533146c
refs/heads/master
2022-12-13T13:55:29.678000
2021-01-18T01:49:27
2021-01-18T01:49:27
133,935,692
1
0
null
false
2022-12-08T06:05:55
2018-05-18T09:48:09
2021-01-18T01:54:18
2022-12-08T06:05:53
43,177
1
0
9
JavaScript
false
false
package com.keyc.mycustomview.adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.keyc.mycustomview.R; import com.keyc.mycustomview.bean.CountryCode; import com.keyc.mycustomview.listener.OnCountryItemClickListener; import java.util.List; /** * Created by keyC on 2019/6/13. */ public class ContactSortAdapter extends RecyclerView.Adapter<ContactSortAdapter.ViewHolder> { private List<CountryCode> mData; private OnCountryItemClickListener mListener; public ContactSortAdapter(List<CountryCode> mData, OnCountryItemClickListener mListener) { this.mData = mData; this.mListener = mListener; } @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_sort, parent, false); return new ContactSortAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ContactSortAdapter.ViewHolder holder, int position) { final CountryCode sortModel = mData.get(position); holder.mTvName.setText(sortModel.getChinese()); if (!compareSection(position)){ holder.mLlTopTitle.setVisibility(View.VISIBLE); holder.mTvLetter.setText(sortModel.getLetter()); holder.mLineView.setVisibility(View.GONE); }else{ holder.mLlTopTitle.setVisibility(View.GONE); holder.mLineView.setVisibility(View.VISIBLE); } holder.mTvName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onItemClick(sortModel); } } }); } // 获取当前位置的首字母(int表示ascii码) public String getSectionForPosition(int position) { return mData.get(position).getLetter(); } // 获取字母首次出现的位置 public int getPositionForSection(int section) { for (int i = 0; i < mData.size(); i++) { String s = mData.get(i).getLetter(); int firstChar = Integer.valueOf(s.toUpperCase()); if (firstChar == section) { return i; } } return -1; } private boolean compareSection(int position) { if (position == 0) { return false; } else { String current = getSectionForPosition(position); String previous = getSectionForPosition(position - 1); return current.equals(previous); } } @Override public int getItemCount() { if (mData != null) { return mData.size(); } return 0; } /** * 更新视图 * @param data */ public void notifyDataSetChanged(List<CountryCode> data) { this.mData = data; notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImg; public final TextView mTvName; public final View mLineView; public final LinearLayout mLlTopTitle; public final TextView mTvLetter; public ViewHolder(View view) { super(view); mView = view; mImg = view.findViewById(R.id.img); mTvName = view.findViewById(R.id.name); mLineView = view.findViewById(R.id.line_view); mLlTopTitle = view.findViewById(R.id.ll_top_title); mTvLetter = view.findViewById(R.id.tv_letter); } } }
UTF-8
Java
3,901
java
ContactSortAdapter.java
Java
[ { "context": "stener;\n\nimport java.util.List;\n\n/**\n * Created by keyC on 2019/6/13.\n */\n\npublic class ContactSortAdapte", "end": 517, "score": 0.9994727373123169, "start": 513, "tag": "USERNAME", "value": "keyC" } ]
null
[]
package com.keyc.mycustomview.adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.keyc.mycustomview.R; import com.keyc.mycustomview.bean.CountryCode; import com.keyc.mycustomview.listener.OnCountryItemClickListener; import java.util.List; /** * Created by keyC on 2019/6/13. */ public class ContactSortAdapter extends RecyclerView.Adapter<ContactSortAdapter.ViewHolder> { private List<CountryCode> mData; private OnCountryItemClickListener mListener; public ContactSortAdapter(List<CountryCode> mData, OnCountryItemClickListener mListener) { this.mData = mData; this.mListener = mListener; } @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_sort, parent, false); return new ContactSortAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ContactSortAdapter.ViewHolder holder, int position) { final CountryCode sortModel = mData.get(position); holder.mTvName.setText(sortModel.getChinese()); if (!compareSection(position)){ holder.mLlTopTitle.setVisibility(View.VISIBLE); holder.mTvLetter.setText(sortModel.getLetter()); holder.mLineView.setVisibility(View.GONE); }else{ holder.mLlTopTitle.setVisibility(View.GONE); holder.mLineView.setVisibility(View.VISIBLE); } holder.mTvName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onItemClick(sortModel); } } }); } // 获取当前位置的首字母(int表示ascii码) public String getSectionForPosition(int position) { return mData.get(position).getLetter(); } // 获取字母首次出现的位置 public int getPositionForSection(int section) { for (int i = 0; i < mData.size(); i++) { String s = mData.get(i).getLetter(); int firstChar = Integer.valueOf(s.toUpperCase()); if (firstChar == section) { return i; } } return -1; } private boolean compareSection(int position) { if (position == 0) { return false; } else { String current = getSectionForPosition(position); String previous = getSectionForPosition(position - 1); return current.equals(previous); } } @Override public int getItemCount() { if (mData != null) { return mData.size(); } return 0; } /** * 更新视图 * @param data */ public void notifyDataSetChanged(List<CountryCode> data) { this.mData = data; notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImg; public final TextView mTvName; public final View mLineView; public final LinearLayout mLlTopTitle; public final TextView mTvLetter; public ViewHolder(View view) { super(view); mView = view; mImg = view.findViewById(R.id.img); mTvName = view.findViewById(R.id.name); mLineView = view.findViewById(R.id.line_view); mLlTopTitle = view.findViewById(R.id.ll_top_title); mTvLetter = view.findViewById(R.id.tv_letter); } } }
3,901
0.631209
0.627828
123
30.260162
23.648111
95
false
false
0
0
0
0
0
0
0.495935
false
false
12
d546543149a416a94f7109981625278b3284220c
35,399,120,487,527
78a579d51d641da2cdd1d4994b4fa960075fafa5
/src/dao/UsuarioDAO.java
8d1ef994040096e41fde5db72fde1e2874f8d204
[]
no_license
BrunoCAF/space-invaders
https://github.com/BrunoCAF/space-invaders
bba064d5c1b2814d409e0196d43cf884472d8b35
5009a06a34b293f749ef013854877819ae2094af
refs/heads/main
2023-08-13T10:09:58.408000
2021-09-26T23:57:29
2021-09-26T23:57:29
410,688,452
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import connection.ConnectionFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import model.Usuario; public class UsuarioDAO { private final Connection con; public UsuarioDAO(){ this.con = new ConnectionFactory().getConnection(); } public void inserir(Usuario u){ String sql = "INSERT INTO usuario (email, nome, senha) VALUES (?,?,?)"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); stmt.setString(1, u.getEmail()); stmt.setString(2, u.getNome()); stmt.setString(3, u.getSenha()); stmt.execute(); stmt.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } } public boolean validateEmail(String email){ String sql = "SELECT email FROM usuario"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); ArrayList<String> emails = new ArrayList<>(); while(rs.next()){ String e = rs.getString("email"); emails.add(e); } stmt.close(); return !(emails.contains(email)); } catch (SQLException ex) { throw new RuntimeException(ex); } } public Usuario logar(Usuario u){ String sql = "SELECT * FROM usuario WHERE email = ?"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); stmt.setString(1, u.getEmail()); ResultSet rs = stmt.executeQuery(); Usuario user = new Usuario(); while(rs.next()){ user.setEmail(rs.getString("email")); user.setNome(rs.getString("nome")); user.setSenha(rs.getString("senha")); user.setPontos(0); user.setLogado(true); } stmt.close(); if(user.getSenha().equals(u.getSenha())){ return new Usuario(user); }else{ user.setLogado(false); return new Usuario(user); } } catch (SQLException ex) { throw new RuntimeException(ex); } } }
UTF-8
Java
2,534
java
UsuarioDAO.java
Java
[]
null
[]
package dao; import connection.ConnectionFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import model.Usuario; public class UsuarioDAO { private final Connection con; public UsuarioDAO(){ this.con = new ConnectionFactory().getConnection(); } public void inserir(Usuario u){ String sql = "INSERT INTO usuario (email, nome, senha) VALUES (?,?,?)"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); stmt.setString(1, u.getEmail()); stmt.setString(2, u.getNome()); stmt.setString(3, u.getSenha()); stmt.execute(); stmt.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } } public boolean validateEmail(String email){ String sql = "SELECT email FROM usuario"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); ArrayList<String> emails = new ArrayList<>(); while(rs.next()){ String e = rs.getString("email"); emails.add(e); } stmt.close(); return !(emails.contains(email)); } catch (SQLException ex) { throw new RuntimeException(ex); } } public Usuario logar(Usuario u){ String sql = "SELECT * FROM usuario WHERE email = ?"; PreparedStatement stmt; try { stmt = con.prepareStatement(sql); stmt.setString(1, u.getEmail()); ResultSet rs = stmt.executeQuery(); Usuario user = new Usuario(); while(rs.next()){ user.setEmail(rs.getString("email")); user.setNome(rs.getString("nome")); user.setSenha(rs.getString("senha")); user.setPontos(0); user.setLogado(true); } stmt.close(); if(user.getSenha().equals(u.getSenha())){ return new Usuario(user); }else{ user.setLogado(false); return new Usuario(user); } } catch (SQLException ex) { throw new RuntimeException(ex); } } }
2,534
0.51026
0.508287
83
28.554216
17.826643
79
false
false
0
0
0
0
0
0
0.638554
false
false
12
26cc1b3bac385d1a01ef659909e6fdaeb030c082
35,399,120,484,374
ee704ae01581a8c8a51fee839e2b38e3de0e9d93
/JavaClientMqtt/src/main/java/Test/Main.java
7aa82ae58edd4ee99b996380dac0a4203dabb112
[]
no_license
Kuerl/mqtt_protocol_demo_mobile_javaapp
https://github.com/Kuerl/mqtt_protocol_demo_mobile_javaapp
51cfbb7a2d9bbb9755723c1acea2020a521b184b
5e68eaf4e9b10317d003bfa04b3ef5fe604226d2
refs/heads/main
2023-02-04T10:56:42.239000
2020-12-28T08:17:02
2020-12-28T08:17:02
311,665,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Test; import org.eclipse.paho.client.mqttv3.MqttException; public class Main { public static void main(String[] args) throws MqttException { Sub testSubClient = new Sub("hcmiuiot.tech", "id/test"); testSubClient.subCore(); } }
UTF-8
Java
261
java
Main.java
Java
[]
null
[]
package Test; import org.eclipse.paho.client.mqttv3.MqttException; public class Main { public static void main(String[] args) throws MqttException { Sub testSubClient = new Sub("hcmiuiot.tech", "id/test"); testSubClient.subCore(); } }
261
0.689655
0.685824
10
25.1
25.10956
65
false
false
0
0
0
0
0
0
0.5
false
false
12
9a0c3c54787df83dea2a78392e32456270f50c0a
17,257,178,648,197
7089d0e74b9f7a09560d08ca404925e7ae362aee
/src/main/java/com/laborguru/action/store/StorePositionPrepareAction.java
2acf0a0fe127e460416c14bd63f95011737b77a1
[]
no_license
leonards-ar/LaborGuru_SPM
https://github.com/leonards-ar/LaborGuru_SPM
24b0e9b22f2c661bdb8e7662ec11757c2339fb86
9260c6d60eceab1b08833430ee1985ed73a9a1b3
refs/heads/master
2021-01-12T10:21:16.144000
2017-01-17T23:18:34
2017-01-17T23:18:34
76,428,599
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.laborguru.action.store; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import com.laborguru.action.SpmActionResult; import com.laborguru.exception.ErrorEnum; import com.laborguru.exception.SpmCheckedException; import com.laborguru.model.Position; import com.opensymphony.xwork2.Preparable; /** * * @author <a href="fbarrera@gmail.com">Federico Barrera Oro</a> * @version 1.0 * @since SPM 1.0 * */ @SuppressWarnings("serial") public class StorePositionPrepareAction extends StoreAdministrationBaseAction implements Preparable { private static Logger log = Logger.getLogger(StorePositionPrepareAction.class); private List<Position> positions; private List<Position> removePositions; private String newPositionName; private boolean newPositionManager; private boolean newPositionGuestService = true; /** * This property holds an empty position set by Spring containing * default values */ private Position position; private Integer index; /** * Prepare the data to be used on the page * * @throws Exception */ public void prepare() throws Exception { } /** * Prepare the data to be used on the edit page * * @throws Exception */ public void prepareEdit() throws Exception { } /** * Prepare the data to be used on the show page * * @throws Exception */ public void prepareShow() throws Exception { } /** * Shows the edit page * * @return */ public String edit() { loadPositions(); return SpmActionResult.EDIT.getResult(); } /** * Shows the list page * * @return */ public String show() { loadPositions(); return SpmActionResult.SHOW.getResult(); } /** * * @param id * @return */ private Position getPositionById(Integer id) { if(id != null) { for(Position storePosition: getStore().getPositions()){ if (id.equals(storePosition.getId())) { return storePosition; } } } return null; } /** * */ private void setStorePositionsName() throws SpmCheckedException{ if (!"".equals(getNewPositionName().trim())) { addNewPosition(); } // Add or update existing positions for (Position position : getPositions()) { Position storePosition = getPositionById(position.getId()); if (storePosition != null) { String positionName = position.getName(); if (!storePosition.getName().equals(positionName)) //Checking if the name is not repeted if (Collections.frequency(getPositions(), position) > 1){ String exMessage = "Position name " + positionName + " is duplicated"; log.error(exMessage); throw new SpmCheckedException(exMessage, ErrorEnum.DUPLICATED_POSITION, new String[]{positionName}); } storePosition.setName(position.getName()); storePosition.setManager(position.isManager()); storePosition.setGuestService(position.isGuestService()); storePosition.setPositionIndex(position.getPositionIndex()); } else { getStore().addPosition(position); } } // Delete positions for (Position position : getRemovePositions()) { position.setStore(getStore()); getStore().getPositions().remove(position); } } /** * Save the positions to the store. * @return */ public String save() { try{ setStorePositionsName(); }catch(SpmCheckedException e){ addActionError(e.getErrorMessage()); return SpmActionResult.INPUT.getResult(); } if(log.isDebugEnabled()) { log.debug("About to save store: " + getStore()); } this.saveStoreAndLoadItIntoSession(getStore()); if(log.isInfoEnabled()) { log.info("Store positions successfully updated for store with id [" + getStoreId() + "]"); } return SpmActionResult.SUCCESS.getResult(); } /** * load the store's position */ public void loadPositions() { if (getStore() != null) { setPositions(getStore().getPositions()); } } /** * Add a new position to the Position List; * @param name * @return */ private void addNewPosition() { Position newPosition = getPosition(); newPosition.setName(getNewPositionName()); newPosition.setPositionIndex(getPositions().size()); newPosition.setManager(isNewPositionManager()); newPosition.setGuestService(isNewPositionGuestService()); getPositions().add(newPosition); } /** * add a Position * * @return */ public String addPosition() { if(!"".equals(getNewPositionName().trim())){ addNewPosition(); setNewPositionName(null); setNewPositionManager(false); setNewPositionGuestService(true); } return SpmActionResult.EDIT.getResult(); } /** * Removes an element from Positions * * @return */ public String removePosition() { Position removePosition = getPositions().remove(getIndex().intValue()); if(removePosition.getId() != null) { getRemovePositions().add(removePosition); fixPositionIndex(); } return SpmActionResult.EDIT.getResult(); } /** * This method sets the index Position of the dayParts elements with the element index of list. */ private void fixPositionIndex(){ int i = 0; for (Position position: getPositions()){ position.setPositionIndex(i++); } } /** * Moves a Position up. * @return */ public String oneUp() { if (getIndex() != null && getIndex() > 0) { int indexAux = getIndex(); int indexPrev = indexAux - 1; swapPositions(indexAux, indexPrev); } return SpmActionResult.EDIT.getResult(); } /** * Moves a Position Down * @return */ public String oneDown() { if (getIndex() !=null && getIndex() < getPositions().size() - 1) { int indexAux = getIndex(); int indexNext = indexAux + 1; if(indexNext < getPositions().size()) { swapPositions(indexNext, indexAux); } } return SpmActionResult.EDIT.getResult(); } /** * This method swaps 2 positions on the positions list. * Indexes passed as parameter should be valid indexes. * * It also updates the index Positions on the dayParts references. * * @param index1 index of the dayPart to swap * @param index0 index of the dayPart to swap */ private void swapPositions(int index1, int index0) { Position positionAux = getPositions().get(index1); Position positionPrev = getPositions().get(index0); positionAux.setPositionIndex(index0); positionPrev.setPositionIndex(index1); positionAux = getPositions().set(index1, positionPrev); getPositions().set(index0, positionAux); } /** * @return the positions */ public List<Position> getPositions() { if(positions == null) { setPositions(new ArrayList<Position>()); } return positions; } /** * @param positions * the positions to set */ public void setPositions(List<Position> positions) { this.positions = positions; } /** * @return the removePositions */ public List<Position> getRemovePositions() { if(this.removePositions == null) { this.removePositions = new ArrayList<Position>(); } return removePositions; } /** * @param removePositions the removePositions to set */ public void setRemovePositions(List<Position> removePositions) { this.removePositions = removePositions; } /** * @return the newPositionName */ public String getNewPositionName() { return newPositionName; } /** * @param newPosition the newPosition to set */ public void setNewPositionName(String newPositionName) { this.newPositionName = newPositionName; } /** * @return the index */ public Integer getIndex() { if (index == null) { index = new Integer(-1); } return index; } /** * @param index * the index to set */ public void setIndex(Integer index) { this.index = index; } /** * @return the position */ public Position getPosition() { if(position == null) { position = new Position(); } return position; } /** * @param position the position to set */ public void setPosition(Position position) { this.position = position; } /** * @return the newPositionManager */ public boolean isNewPositionManager() { return newPositionManager; } /** * @param newPositionManager the newPositionManager to set */ public void setNewPositionManager(boolean newPositionManager) { this.newPositionManager = newPositionManager; } /** * @return the newPositionGuestService */ public boolean isNewPositionGuestService() { return newPositionGuestService; } /** * @param newPositionGuestService the newPositionGuestService to set */ public void setNewPositionGuestService(boolean newPositionGuestService) { this.newPositionGuestService = newPositionGuestService; } }
UTF-8
Java
9,095
java
StorePositionPrepareAction.java
Java
[ { "context": "ork2.Preparable;\r\n\r\n/**\r\n * \r\n * @author <a href=\"fbarrera@gmail.com\">Federico Barrera Oro</a>\r\n * @version 1.0\r\n * @s", "end": 434, "score": 0.9999279379844666, "start": 416, "tag": "EMAIL", "value": "fbarrera@gmail.com" }, { "context": "/**\r\n * \r\n * @author <a href=\"fbarrera@gmail.com\">Federico Barrera Oro</a>\r\n * @version 1.0\r\n * @since SPM 1.0\r\n * \r\n */", "end": 456, "score": 0.9998581409454346, "start": 436, "tag": "NAME", "value": "Federico Barrera Oro" } ]
null
[]
package com.laborguru.action.store; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import com.laborguru.action.SpmActionResult; import com.laborguru.exception.ErrorEnum; import com.laborguru.exception.SpmCheckedException; import com.laborguru.model.Position; import com.opensymphony.xwork2.Preparable; /** * * @author <a href="<EMAIL>"><NAME></a> * @version 1.0 * @since SPM 1.0 * */ @SuppressWarnings("serial") public class StorePositionPrepareAction extends StoreAdministrationBaseAction implements Preparable { private static Logger log = Logger.getLogger(StorePositionPrepareAction.class); private List<Position> positions; private List<Position> removePositions; private String newPositionName; private boolean newPositionManager; private boolean newPositionGuestService = true; /** * This property holds an empty position set by Spring containing * default values */ private Position position; private Integer index; /** * Prepare the data to be used on the page * * @throws Exception */ public void prepare() throws Exception { } /** * Prepare the data to be used on the edit page * * @throws Exception */ public void prepareEdit() throws Exception { } /** * Prepare the data to be used on the show page * * @throws Exception */ public void prepareShow() throws Exception { } /** * Shows the edit page * * @return */ public String edit() { loadPositions(); return SpmActionResult.EDIT.getResult(); } /** * Shows the list page * * @return */ public String show() { loadPositions(); return SpmActionResult.SHOW.getResult(); } /** * * @param id * @return */ private Position getPositionById(Integer id) { if(id != null) { for(Position storePosition: getStore().getPositions()){ if (id.equals(storePosition.getId())) { return storePosition; } } } return null; } /** * */ private void setStorePositionsName() throws SpmCheckedException{ if (!"".equals(getNewPositionName().trim())) { addNewPosition(); } // Add or update existing positions for (Position position : getPositions()) { Position storePosition = getPositionById(position.getId()); if (storePosition != null) { String positionName = position.getName(); if (!storePosition.getName().equals(positionName)) //Checking if the name is not repeted if (Collections.frequency(getPositions(), position) > 1){ String exMessage = "Position name " + positionName + " is duplicated"; log.error(exMessage); throw new SpmCheckedException(exMessage, ErrorEnum.DUPLICATED_POSITION, new String[]{positionName}); } storePosition.setName(position.getName()); storePosition.setManager(position.isManager()); storePosition.setGuestService(position.isGuestService()); storePosition.setPositionIndex(position.getPositionIndex()); } else { getStore().addPosition(position); } } // Delete positions for (Position position : getRemovePositions()) { position.setStore(getStore()); getStore().getPositions().remove(position); } } /** * Save the positions to the store. * @return */ public String save() { try{ setStorePositionsName(); }catch(SpmCheckedException e){ addActionError(e.getErrorMessage()); return SpmActionResult.INPUT.getResult(); } if(log.isDebugEnabled()) { log.debug("About to save store: " + getStore()); } this.saveStoreAndLoadItIntoSession(getStore()); if(log.isInfoEnabled()) { log.info("Store positions successfully updated for store with id [" + getStoreId() + "]"); } return SpmActionResult.SUCCESS.getResult(); } /** * load the store's position */ public void loadPositions() { if (getStore() != null) { setPositions(getStore().getPositions()); } } /** * Add a new position to the Position List; * @param name * @return */ private void addNewPosition() { Position newPosition = getPosition(); newPosition.setName(getNewPositionName()); newPosition.setPositionIndex(getPositions().size()); newPosition.setManager(isNewPositionManager()); newPosition.setGuestService(isNewPositionGuestService()); getPositions().add(newPosition); } /** * add a Position * * @return */ public String addPosition() { if(!"".equals(getNewPositionName().trim())){ addNewPosition(); setNewPositionName(null); setNewPositionManager(false); setNewPositionGuestService(true); } return SpmActionResult.EDIT.getResult(); } /** * Removes an element from Positions * * @return */ public String removePosition() { Position removePosition = getPositions().remove(getIndex().intValue()); if(removePosition.getId() != null) { getRemovePositions().add(removePosition); fixPositionIndex(); } return SpmActionResult.EDIT.getResult(); } /** * This method sets the index Position of the dayParts elements with the element index of list. */ private void fixPositionIndex(){ int i = 0; for (Position position: getPositions()){ position.setPositionIndex(i++); } } /** * Moves a Position up. * @return */ public String oneUp() { if (getIndex() != null && getIndex() > 0) { int indexAux = getIndex(); int indexPrev = indexAux - 1; swapPositions(indexAux, indexPrev); } return SpmActionResult.EDIT.getResult(); } /** * Moves a Position Down * @return */ public String oneDown() { if (getIndex() !=null && getIndex() < getPositions().size() - 1) { int indexAux = getIndex(); int indexNext = indexAux + 1; if(indexNext < getPositions().size()) { swapPositions(indexNext, indexAux); } } return SpmActionResult.EDIT.getResult(); } /** * This method swaps 2 positions on the positions list. * Indexes passed as parameter should be valid indexes. * * It also updates the index Positions on the dayParts references. * * @param index1 index of the dayPart to swap * @param index0 index of the dayPart to swap */ private void swapPositions(int index1, int index0) { Position positionAux = getPositions().get(index1); Position positionPrev = getPositions().get(index0); positionAux.setPositionIndex(index0); positionPrev.setPositionIndex(index1); positionAux = getPositions().set(index1, positionPrev); getPositions().set(index0, positionAux); } /** * @return the positions */ public List<Position> getPositions() { if(positions == null) { setPositions(new ArrayList<Position>()); } return positions; } /** * @param positions * the positions to set */ public void setPositions(List<Position> positions) { this.positions = positions; } /** * @return the removePositions */ public List<Position> getRemovePositions() { if(this.removePositions == null) { this.removePositions = new ArrayList<Position>(); } return removePositions; } /** * @param removePositions the removePositions to set */ public void setRemovePositions(List<Position> removePositions) { this.removePositions = removePositions; } /** * @return the newPositionName */ public String getNewPositionName() { return newPositionName; } /** * @param newPosition the newPosition to set */ public void setNewPositionName(String newPositionName) { this.newPositionName = newPositionName; } /** * @return the index */ public Integer getIndex() { if (index == null) { index = new Integer(-1); } return index; } /** * @param index * the index to set */ public void setIndex(Integer index) { this.index = index; } /** * @return the position */ public Position getPosition() { if(position == null) { position = new Position(); } return position; } /** * @param position the position to set */ public void setPosition(Position position) { this.position = position; } /** * @return the newPositionManager */ public boolean isNewPositionManager() { return newPositionManager; } /** * @param newPositionManager the newPositionManager to set */ public void setNewPositionManager(boolean newPositionManager) { this.newPositionManager = newPositionManager; } /** * @return the newPositionGuestService */ public boolean isNewPositionGuestService() { return newPositionGuestService; } /** * @param newPositionGuestService the newPositionGuestService to set */ public void setNewPositionGuestService(boolean newPositionGuestService) { this.newPositionGuestService = newPositionGuestService; } }
9,070
0.654426
0.651787
393
21.142494
21.508389
112
false
false
0
0
0
0
0
0
1.735369
false
false
12
cc98cab31f645d5058d14fc24a65962e494262a9
20,658,792,754,044
ca493f154e48d5a9481b938c0b2285ea8c5f5ac4
/Command/src/command/OnAircondition.java
3302097e9a9c5dbdc0917c6fc039ec5c1b02f4fe
[]
no_license
LanPeoplea/Pattern
https://github.com/LanPeoplea/Pattern
8ce71b9b724583d6db8e7607c0766da5e79a018f
f48d39df4cc63a29fb2b301c23cb9f4ffb657ad5
refs/heads/master
2022-09-23T00:11:04.486000
2020-06-01T08:26:50
2020-06-01T08:26:50
261,974,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package command; /** *一个打开空调命令类 */ public class OnAircondition implements Command{ Aircondition aircondition; public OnAircondition(Aircondition aircondition){ this.aircondition=aircondition; } @Override public void execute() { aircondition.on(); } }
UTF-8
Java
313
java
OnAircondition.java
Java
[]
null
[]
package command; /** *一个打开空调命令类 */ public class OnAircondition implements Command{ Aircondition aircondition; public OnAircondition(Aircondition aircondition){ this.aircondition=aircondition; } @Override public void execute() { aircondition.on(); } }
313
0.677966
0.677966
16
17.4375
16.944649
53
false
false
0
0
0
0
0
0
0.25
false
false
12
75866ebc28e4dcd3dbd05186c79d76fa4326b4ed
28,303,834,541,618
75d7ae4d24970b85842eaee66bd1fe20adb05a10
/Assn14/src/Assignment14.java
98f85e44ff4e14d565b28b723394aa703a288ed0
[]
no_license
JakeLandowski/JavaWork
https://github.com/JakeLandowski/JavaWork
d7bba5739886bcb84b9ce4d2218341fb7fc6f4fe
3cc5d52993886429d462a6ee007ea876f9722b7f
refs/heads/master
2021-01-23T04:28:30.263000
2017-04-03T13:39:29
2017-04-03T13:39:29
86,196,632
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Jacob Landowski, CS141, Winter 2017, Section 2751 // Programming Assignment #14, 2/12/17 // // This program reads a file of employee information // and loops through each line in the file and // extracts the data and calculates pay, then displays it. import java.io.*; import java.util.*; public class Assignment14 { // CONST FOR TAX % private static final double TAX = 25.00; public static void main(String[] args) throws FileNotFoundException { File employeeFile = new File("CS141 Assign14.txt"); Scanner fileRead = new Scanner(employeeFile); extractData(fileRead); } // LOOPS THROUGH FILE, CALLS METHOD TO EXTRACT DATA FROM LINE // THEN CALLS DISPLAY METHOD TO DISPLAY FORMATTED DATA public static void extractData(Scanner file) { while(file.hasNext()) { Scanner lineScan = new Scanner(file.nextLine()); Object data[] = decipherLine(lineScan); String name = (String) data[0]; double rate = (double) data[1]; int hours = (int) data[2]; displayInfo(name, rate, hours); } } // LOOP THROUGH A LINE, SUM THE HOURS, RETURN DATA public static Object[] decipherLine(Scanner line) { Object[] data = new Object[3]; data[0] = line.next(); data[1] = line.nextDouble(); int sum = 0; while(line.hasNext()) { sum += line.nextInt(); } data[2] = sum; return data; } // DISPLAY INFORMATION FORMATTED public static void displayInfo(String name, double rate, int hours) { System.out.printf(name + " worked for a total of " + hours + " hours at $%.2f an hour for " + "a gross pay of $%.2f%n", rate, (rate*hours)); System.out.printf("After %.0f%% taxes their total net " + "pay should be $%.2f%n", TAX, (rate*hours) * ((100-TAX)/100)); System.out.println("\n------------------------------------" + "--------------------------------------\n"); } }
UTF-8
Java
1,900
java
Assignment14.java
Java
[ { "context": "//\tJacob Landowski, CS141, Winter 2017, Section 2751\n//\tProgramming ", "end": 18, "score": 0.9996139407157898, "start": 3, "tag": "NAME", "value": "Jacob Landowski" } ]
null
[]
// <NAME>, CS141, Winter 2017, Section 2751 // Programming Assignment #14, 2/12/17 // // This program reads a file of employee information // and loops through each line in the file and // extracts the data and calculates pay, then displays it. import java.io.*; import java.util.*; public class Assignment14 { // CONST FOR TAX % private static final double TAX = 25.00; public static void main(String[] args) throws FileNotFoundException { File employeeFile = new File("CS141 Assign14.txt"); Scanner fileRead = new Scanner(employeeFile); extractData(fileRead); } // LOOPS THROUGH FILE, CALLS METHOD TO EXTRACT DATA FROM LINE // THEN CALLS DISPLAY METHOD TO DISPLAY FORMATTED DATA public static void extractData(Scanner file) { while(file.hasNext()) { Scanner lineScan = new Scanner(file.nextLine()); Object data[] = decipherLine(lineScan); String name = (String) data[0]; double rate = (double) data[1]; int hours = (int) data[2]; displayInfo(name, rate, hours); } } // LOOP THROUGH A LINE, SUM THE HOURS, RETURN DATA public static Object[] decipherLine(Scanner line) { Object[] data = new Object[3]; data[0] = line.next(); data[1] = line.nextDouble(); int sum = 0; while(line.hasNext()) { sum += line.nextInt(); } data[2] = sum; return data; } // DISPLAY INFORMATION FORMATTED public static void displayInfo(String name, double rate, int hours) { System.out.printf(name + " worked for a total of " + hours + " hours at $%.2f an hour for " + "a gross pay of $%.2f%n", rate, (rate*hours)); System.out.printf("After %.0f%% taxes their total net " + "pay should be $%.2f%n", TAX, (rate*hours) * ((100-TAX)/100)); System.out.println("\n------------------------------------" + "--------------------------------------\n"); } }
1,891
0.617895
0.593158
72
25.388889
21.788475
68
false
false
0
0
0
0
0
0
2.611111
false
false
12
111d33c9b19469da2e713d6e2542739c7c053543
33,440,615,408,347
ed9ae1286373ce72f36779d02176f961a3f84d65
/src/test/java/bitwise/O09_MissingOccurrenceTest.java
3dc6ae18233dfb2ad973c18417ef5d7d9f511073
[]
no_license
NaveenMathialagan/Data-Structures
https://github.com/NaveenMathialagan/Data-Structures
2c995ae0cbdcd4f4f2ac9c653319ba6a34ff1ce9
7f2ff9b485bc1971574906dff76d8fe3c38201ee
refs/heads/master
2022-04-20T06:27:02.080000
2022-04-20T05:00:24
2022-04-20T05:00:24
256,730,512
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bitwise; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class O09_MissingOccurrenceTest { @Test public void shouldReturnTheMissingOccurrenceInGivenSequence() { O09_MissingOccurrence missingOccurrence = new O09_MissingOccurrence(); int actual = missingOccurrence.findMissingOccurrence(new int[]{1, 3, 4}); assertEquals(2, actual); actual = missingOccurrence.findMissingOccurrence(new int[]{1}); assertEquals(2, actual); actual = missingOccurrence.findMissingOccurrence(new int[]{1,2,3}); assertEquals(4, actual); } }
UTF-8
Java
644
java
O09_MissingOccurrenceTest.java
Java
[]
null
[]
package bitwise; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class O09_MissingOccurrenceTest { @Test public void shouldReturnTheMissingOccurrenceInGivenSequence() { O09_MissingOccurrence missingOccurrence = new O09_MissingOccurrence(); int actual = missingOccurrence.findMissingOccurrence(new int[]{1, 3, 4}); assertEquals(2, actual); actual = missingOccurrence.findMissingOccurrence(new int[]{1}); assertEquals(2, actual); actual = missingOccurrence.findMissingOccurrence(new int[]{1,2,3}); assertEquals(4, actual); } }
644
0.715838
0.690994
19
32.947369
29.428724
81
false
false
0
0
0
0
0
0
0.894737
false
false
12
482a36a9ad988107144223d45de030ef69c26058
33,036,888,473,530
ccf82688f082e26cba5fc397c76c77cc007ab2e8
/Mage.Tests/src/test/java/org/mage/test/cards/asthough/AsThoughManaAndAITest.java
c1abed9f83a4e776e692fb4cbbcf6ec33c6467a0
[ "MIT" ]
permissive
magefree/mage
https://github.com/magefree/mage
3261a89320f586d698dd03ca759a7562829f247f
5dba61244c738f4a184af0d256046312ce21d911
refs/heads/master
2023-09-03T15:55:36.650000
2023-09-03T03:53:12
2023-09-03T03:53:12
4,158,448
1,803
1,133
MIT
false
2023-09-14T20:18:55
2012-04-27T13:18:34
2023-09-11T18:25:38
2023-09-14T20:18:55
801,396
1,632
712
1,307
Java
false
false
package org.mage.test.cards.asthough; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author JayDi85 */ public class AsThoughManaAndAITest extends CardTestPlayerBase { @Test public void test_AutoPaymentMustUseAsThoughMana() { // possible bug: AI auto-payment uses first mana ability from the mana source, so multi-colored lands can be broken // You may spend white mana as though it were red mana. addCard(Zone.BATTLEFIELD, playerA, "Sunglasses of Urza", 1); // // {T}: Add {U} or {W}. addCard(Zone.BATTLEFIELD, playerA, "Sea of Clouds", 1); addCard(Zone.HAND, playerA, "Lightning Bolt", 1); // {R} checkPlayableAbility("before", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", true); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Lightning Bolt", playerB); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertLife(playerB, 20 - 3); } }
UTF-8
Java
1,104
java
AsThoughManaAndAITest.java
Java
[ { "context": "erverside.base.CardTestPlayerBase;\n\n/**\n * @author JayDi85\n */\npublic class AsThoughManaAndAITest extends Ca", "end": 203, "score": 0.9996724128723145, "start": 196, "tag": "USERNAME", "value": "JayDi85" } ]
null
[]
package org.mage.test.cards.asthough; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author JayDi85 */ public class AsThoughManaAndAITest extends CardTestPlayerBase { @Test public void test_AutoPaymentMustUseAsThoughMana() { // possible bug: AI auto-payment uses first mana ability from the mana source, so multi-colored lands can be broken // You may spend white mana as though it were red mana. addCard(Zone.BATTLEFIELD, playerA, "Sunglasses of Urza", 1); // // {T}: Add {U} or {W}. addCard(Zone.BATTLEFIELD, playerA, "Sea of Clouds", 1); addCard(Zone.HAND, playerA, "Lightning Bolt", 1); // {R} checkPlayableAbility("before", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", true); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Lightning Bolt", playerB); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertLife(playerB, 20 - 3); } }
1,104
0.673007
0.663043
33
32.454544
32.499969
123
false
false
0
0
0
0
0
0
1.060606
false
false
12
9e9c0825099e95f66eb2866a6821bd2ef68812bf
27,393,301,448,831
d7d8d5ecbede1c1a2d0af8bedabe3419e5a00202
/src/main/java/com/acme/platform/health/bone/dao/BoneImage.java
2d725cc59ad2efd1aa6db5bd4b3c67be006367f4
[]
no_license
wgq017/test
https://github.com/wgq017/test
ec0f8a448fdc6715a99db6d66f69b4e6e15f286d
57816944033c5135a6bec891b15043a1e1113af0
refs/heads/master
2016-09-22T17:59:07.045000
2016-07-06T06:05:51
2016-07-06T06:05:51
62,611,029
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acme.platform.health.bone.dao; import java.util.Arrays; public class BoneImage { private String id; private byte[] image; @Override public String toString() { return "BoneImage [id=" + id + ", image=" + Arrays.toString(image) + "]"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
UTF-8
Java
497
java
BoneImage.java
Java
[]
null
[]
package com.acme.platform.health.bone.dao; import java.util.Arrays; public class BoneImage { private String id; private byte[] image; @Override public String toString() { return "BoneImage [id=" + id + ", image=" + Arrays.toString(image) + "]"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
497
0.609658
0.609658
28
15.75
15.880412
68
false
false
0
0
0
0
0
0
1.392857
false
false
12
11c0474857e3128cb9bf804f4c32ccdf2435d216
31,636,729,111,181
40fca6a95a2d2289481519f40513ff38916961d5
/module-1/oop/car-crash-skeleton/src/org/academiadecodigo/carcrash/cars/CarFactory.java
481761f7f7933c6aeaefc08b857724bc47f0accc
[]
no_license
vascoferraz/AcademiaDeCodigo
https://github.com/vascoferraz/AcademiaDeCodigo
7a9c125fdbddab523879350b3ebd994878e82447
c0862e73ad83e3db1ac52d7f2e5e14fe3845c590
refs/heads/master
2023-04-01T08:09:14.035000
2021-04-14T08:47:34
2021-04-14T08:47:34
331,267,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.academiadecodigo.carcrash.cars; public class CarFactory { public static Car getNewCar() { int carType = (int) (Math.random() * 2); Car car = new Fiat(); switch (carType) { case 0: return new Fiat(); case 1: return new Mustang(); } return car; } public static Car getNewTurret() { return new Turret(); } public static Car getNewRocket() { return new Rocket(); } }
UTF-8
Java
488
java
CarFactory.java
Java
[]
null
[]
package org.academiadecodigo.carcrash.cars; public class CarFactory { public static Car getNewCar() { int carType = (int) (Math.random() * 2); Car car = new Fiat(); switch (carType) { case 0: return new Fiat(); case 1: return new Mustang(); } return car; } public static Car getNewTurret() { return new Turret(); } public static Car getNewRocket() { return new Rocket(); } }
488
0.543033
0.536885
27
17.074074
16.939819
48
false
false
0
0
0
0
0
0
0.296296
false
false
12
1254c8750233f8825da08d4e4f5d83d7543a54f1
17,841,294,148,329
4fd08e736019049a838dec9efa74cc2190b6625f
/testdata/src/main/java/reflection/invocation/B.java
3ad5c0bcfdcce66511d7fa67d5c89b0a903bb977
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-other-permissive" ]
permissive
knighthunter09/spring-loaded
https://github.com/knighthunter09/spring-loaded
50a42cc41912ede861cae942e6458b79f2a6faa0
658a8678a672d24e9528fb63f70fa502ca7341ea
refs/heads/master
2020-08-03T17:47:45.312000
2016-06-25T00:10:51
2016-06-25T00:10:51
73,540,025
1
0
null
true
2016-11-12T08:04:24
2016-11-12T08:04:21
2016-11-12T08:03:54
2016-07-01T07:30:56
35,197
0
0
0
null
null
null
package reflection.invocation; /** * For invocation testing, we need a class hierarchy of some complexity to see if dispatching works right. * * Will be using a 3 deep hierarchy C extends B extends B. * * Further we will be adding methods with different modifiers * * @author kdvolder */ public class B extends A { public String pubEarly() { return "B.pubEarly()"; } @SuppressWarnings("unused") private String privEarly() { return "B.privEarly()"; } static String staticEarly() { return "B.staticEarly()"; } public String pubDeleted() { return "B.pubDeleted()"; } @SuppressWarnings("unused") private String privDeleted() { return "B.privDeleted()"; } static String staticDeleted() { return "B.staticDeleted()"; } }
UTF-8
Java
760
java
B.java
Java
[ { "context": "ng methods with different modifiers\n * \n * @author kdvolder\n */\npublic class B extends A {\n\n\tpublic String pu", "end": 295, "score": 0.9996922612190247, "start": 287, "tag": "USERNAME", "value": "kdvolder" } ]
null
[]
package reflection.invocation; /** * For invocation testing, we need a class hierarchy of some complexity to see if dispatching works right. * * Will be using a 3 deep hierarchy C extends B extends B. * * Further we will be adding methods with different modifiers * * @author kdvolder */ public class B extends A { public String pubEarly() { return "B.pubEarly()"; } @SuppressWarnings("unused") private String privEarly() { return "B.privEarly()"; } static String staticEarly() { return "B.staticEarly()"; } public String pubDeleted() { return "B.pubDeleted()"; } @SuppressWarnings("unused") private String privDeleted() { return "B.privDeleted()"; } static String staticDeleted() { return "B.staticDeleted()"; } }
760
0.688158
0.686842
40
18
21.452272
106
true
false
0
0
0
0
0
0
0.85
false
false
12
c39d33c2c5c9eefdc8128c4b5a0d2dc85ac6b8fd
21,655,225,119,895
0e668ac9d017c24c349b0ee41fbbb3cf238caac3
/lintcode-cli/lintcode-java/0834-remove-duplicate-letters.java
dc3918854a378798bae600855a664dc321edc217
[]
no_license
cc189/acm
https://github.com/cc189/acm
b90c856c9fe506543bfd4eeb30df7b68c59e3622
863303e8af0a710e1a0f00d3dbc6ee8a36e9c254
refs/heads/master
2018-09-09T07:35:34.612000
2018-09-08T07:29:13
2018-09-08T07:29:13
133,901,792
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { /** * @param s: a string * @return: return a string */ public String removeDuplicateLetters(String s) { // write your code here } } /** ### Problem remove-duplicate-letters https://www.lintcode.com/problem/remove-duplicate-letters/description ### Description Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. ### Example Given `"bcabc"` Return `"abc"` Given `"cbacdcbc"` Return `"acdb"` */
UTF-8
Java
630
java
0834-remove-duplicate-letters.java
Java
[]
null
[]
public class Solution { /** * @param s: a string * @return: return a string */ public String removeDuplicateLetters(String s) { // write your code here } } /** ### Problem remove-duplicate-letters https://www.lintcode.com/problem/remove-duplicate-letters/description ### Description Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. ### Example Given `"bcabc"` Return `"abc"` Given `"cbacdcbc"` Return `"acdb"` */
630
0.706349
0.706349
26
23.26923
43.716358
226
false
false
0
0
0
0
0
0
0.038462
false
false
12
b59484c7cf27996b8ea091a2abf5745ae8d8568c
25,039,659,362,336
4f91649129faf5a7573b9f77826a9cfdb3fc81ed
/CultureSpot/app/src/main/java/com/example/culturespot/FavoritesList.java
a3f171425094c2216695b8c8a3d560a03ee9adf2
[ "MIT" ]
permissive
Mahjoub-Adam/CultureSpot
https://github.com/Mahjoub-Adam/CultureSpot
157e6c81d59a74f6488f97acd7313de01a5a03cf
8df4ccf769f900b3e36e2dfb33085e887ba06264
refs/heads/main
2023-04-02T13:50:50.669000
2021-04-15T19:03:38
2021-04-15T19:03:38
349,231,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.culturespot; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import java.util.Map; public class FavoritesList { public static final List<Item> ITEMS = new ArrayList<Item>(); private static FirebaseAuth mAuth; public static class Item{ public final String id; public final String name; public Item(String id, String name) { this.id = id; this.name = name; } @Override public String toString() { return name; } } public static void remove(Item item){ Item temp=null; for(Item i : ITEMS){ // find and remove favorite if(i.id.equals(item.id)){ temp=i; break; } } ITEMS.remove(temp); } public static void getItems() { mAuth = FirebaseAuth.getInstance(); FirebaseUser user = mAuth.getCurrentUser(); DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users"); String userId=user.getUid(); reference.child(userId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { User userProfile1 = snapshot.getValue(User.class); // get favorites from firebase if (userProfile1 != null) { String first_name = userProfile1.first_name; String email = userProfile1.email; String surname = userProfile1.surname; String username = userProfile1.username; User userProfile = userProfile1.favorites == null ? new User(username, email, first_name, surname) : userProfile1; ITEMS.clear(); for (Map.Entry<String,String> entry : userProfile.favorites.entrySet()) { // get all new favorite ITEMS.add(new Item(entry.getKey(),entry.getValue())); } reference.child(userId).setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }
UTF-8
Java
2,971
java
FavoritesList.java
Java
[]
null
[]
package com.example.culturespot; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import java.util.Map; public class FavoritesList { public static final List<Item> ITEMS = new ArrayList<Item>(); private static FirebaseAuth mAuth; public static class Item{ public final String id; public final String name; public Item(String id, String name) { this.id = id; this.name = name; } @Override public String toString() { return name; } } public static void remove(Item item){ Item temp=null; for(Item i : ITEMS){ // find and remove favorite if(i.id.equals(item.id)){ temp=i; break; } } ITEMS.remove(temp); } public static void getItems() { mAuth = FirebaseAuth.getInstance(); FirebaseUser user = mAuth.getCurrentUser(); DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users"); String userId=user.getUid(); reference.child(userId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { User userProfile1 = snapshot.getValue(User.class); // get favorites from firebase if (userProfile1 != null) { String first_name = userProfile1.first_name; String email = userProfile1.email; String surname = userProfile1.surname; String username = userProfile1.username; User userProfile = userProfile1.favorites == null ? new User(username, email, first_name, surname) : userProfile1; ITEMS.clear(); for (Map.Entry<String,String> entry : userProfile.favorites.entrySet()) { // get all new favorite ITEMS.add(new Item(entry.getKey(),entry.getValue())); } reference.child(userId).setValue(userProfile).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }
2,971
0.585998
0.583305
76
37.092106
28.52108
134
false
false
0
0
0
0
0
0
0.578947
false
false
12
b669ee23749d2e3f2547c8b62a0033b36fae94e8
14,568,529,091,383
d71e879b3517cf4fccde29f7bf82cff69856cfcd
/ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/airbnb/lottie/ShapeContent.java
68141d862d5bcb64584d80cd9d2652bbd273b5bf
[ "MIT" ]
permissive
Andreas237/AndroidPolicyAutomation
https://github.com/Andreas237/AndroidPolicyAutomation
b8e949e072d08cf6c6166c3f15c9c63379b8f6ce
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
refs/heads/master
2020-04-10T02:14:08.789000
2019-05-16T19:29:11
2019-05-16T19:29:11
160,739,088
5
1
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) annotate safe package com.airbnb.lottie; import android.graphics.Path; import java.util.List; // Referenced classes of package com.airbnb.lottie: // PathContent, ShapePath, AnimatableShapeValue, BaseLayer, // BaseKeyframeAnimation, LottieDrawable, Utils, Content, // TrimPathContent class ShapeContent implements BaseKeyframeAnimation.AnimationListener, PathContent { ShapeContent(LottieDrawable lottiedrawable, BaseLayer baselayer, ShapePath shapepath) { // 0 0:aload_0 // 1 1:invokespecial #27 <Method void Object()> // 2 4:aload_0 // 3 5:new #29 <Class Path> // 4 8:dup // 5 9:invokespecial #30 <Method void Path()> // 6 12:putfield #32 <Field Path path> name = shapepath.getName(); // 7 15:aload_0 // 8 16:aload_3 // 9 17:invokevirtual #38 <Method String ShapePath.getName()> // 10 20:putfield #40 <Field String name> lottieDrawable = lottiedrawable; // 11 23:aload_0 // 12 24:aload_1 // 13 25:putfield #42 <Field LottieDrawable lottieDrawable> shapeAnimation = shapepath.getShapePath().createAnimation(); // 14 28:aload_0 // 15 29:aload_3 // 16 30:invokevirtual #46 <Method AnimatableShapeValue ShapePath.getShapePath()> // 17 33:invokevirtual #52 <Method BaseKeyframeAnimation AnimatableShapeValue.createAnimation()> // 18 36:putfield #54 <Field BaseKeyframeAnimation shapeAnimation> baselayer.addAnimation(shapeAnimation); // 19 39:aload_2 // 20 40:aload_0 // 21 41:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 22 44:invokevirtual #60 <Method void BaseLayer.addAnimation(BaseKeyframeAnimation)> shapeAnimation.addUpdateListener(((BaseKeyframeAnimation.AnimationListener) (this))); // 23 47:aload_0 // 24 48:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 25 51:aload_0 // 26 52:invokevirtual #66 <Method void BaseKeyframeAnimation.addUpdateListener(BaseKeyframeAnimation$AnimationListener)> // 27 55:return } private void invalidate() { isPathValid = false; // 0 0:aload_0 // 1 1:iconst_0 // 2 2:putfield #70 <Field boolean isPathValid> lottieDrawable.invalidateSelf(); // 3 5:aload_0 // 4 6:getfield #42 <Field LottieDrawable lottieDrawable> // 5 9:invokevirtual #75 <Method void LottieDrawable.invalidateSelf()> // 6 12:return } public String getName() { return name; // 0 0:aload_0 // 1 1:getfield #40 <Field String name> // 2 4:areturn } public Path getPath() { if(isPathValid) //* 0 0:aload_0 //* 1 1:getfield #70 <Field boolean isPathValid> //* 2 4:ifeq 12 { return path; // 3 7:aload_0 // 4 8:getfield #32 <Field Path path> // 5 11:areturn } else { path.reset(); // 6 12:aload_0 // 7 13:getfield #32 <Field Path path> // 8 16:invokevirtual #80 <Method void Path.reset()> path.set((Path)shapeAnimation.getValue()); // 9 19:aload_0 // 10 20:getfield #32 <Field Path path> // 11 23:aload_0 // 12 24:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 13 27:invokevirtual #84 <Method Object BaseKeyframeAnimation.getValue()> // 14 30:checkcast #29 <Class Path> // 15 33:invokevirtual #88 <Method void Path.set(Path)> path.setFillType(android.graphics.Path.FillType.EVEN_ODD); // 16 36:aload_0 // 17 37:getfield #32 <Field Path path> // 18 40:getstatic #94 <Field android.graphics.Path$FillType android.graphics.Path$FillType.EVEN_ODD> // 19 43:invokevirtual #98 <Method void Path.setFillType(android.graphics.Path$FillType)> Utils.applyTrimPathIfNeeded(path, trimPath); // 20 46:aload_0 // 21 47:getfield #32 <Field Path path> // 22 50:aload_0 // 23 51:getfield #100 <Field TrimPathContent trimPath> // 24 54:invokestatic #106 <Method void Utils.applyTrimPathIfNeeded(Path, TrimPathContent)> isPathValid = true; // 25 57:aload_0 // 26 58:iconst_1 // 27 59:putfield #70 <Field boolean isPathValid> return path; // 28 62:aload_0 // 29 63:getfield #32 <Field Path path> // 30 66:areturn } } public void onValueChanged() { invalidate(); // 0 0:aload_0 // 1 1:invokespecial #109 <Method void invalidate()> // 2 4:return } public void setContents(List list, List list1) { for(int i = 0; i < list.size(); i++) //* 0 0:iconst_0 //* 1 1:istore_3 //* 2 2:iload_3 //* 3 3:aload_1 //* 4 4:invokeinterface #117 <Method int List.size()> //* 5 9:icmpge 65 { list1 = ((List) ((Content)list.get(i))); // 6 12:aload_1 // 7 13:iload_3 // 8 14:invokeinterface #121 <Method Object List.get(int)> // 9 19:checkcast #123 <Class Content> // 10 22:astore_2 if(!(list1 instanceof TrimPathContent)) continue; // 11 23:aload_2 // 12 24:instanceof #125 <Class TrimPathContent> // 13 27:ifeq 58 list1 = ((List) ((TrimPathContent)list1)); // 14 30:aload_2 // 15 31:checkcast #125 <Class TrimPathContent> // 16 34:astore_2 if(((TrimPathContent) (list1)).getType() == ShapeTrimPath.Type.Simultaneously) //* 17 35:aload_2 //* 18 36:invokevirtual #129 <Method ShapeTrimPath$Type TrimPathContent.getType()> //* 19 39:getstatic #135 <Field ShapeTrimPath$Type ShapeTrimPath$Type.Simultaneously> //* 20 42:if_acmpne 58 { trimPath = ((TrimPathContent) (list1)); // 21 45:aload_0 // 22 46:aload_2 // 23 47:putfield #100 <Field TrimPathContent trimPath> trimPath.addListener(((BaseKeyframeAnimation.AnimationListener) (this))); // 24 50:aload_0 // 25 51:getfield #100 <Field TrimPathContent trimPath> // 26 54:aload_0 // 27 55:invokevirtual #138 <Method void TrimPathContent.addListener(BaseKeyframeAnimation$AnimationListener)> } } // 28 58:iload_3 // 29 59:iconst_1 // 30 60:iadd // 31 61:istore_3 //* 32 62:goto 2 // 33 65:return } private boolean isPathValid; private final LottieDrawable lottieDrawable; private final String name; private final Path path = new Path(); private final BaseKeyframeAnimation shapeAnimation; private TrimPathContent trimPath; }
UTF-8
Java
7,242
java
ShapeContent.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.9996140003204346, "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) annotate safe package com.airbnb.lottie; import android.graphics.Path; import java.util.List; // Referenced classes of package com.airbnb.lottie: // PathContent, ShapePath, AnimatableShapeValue, BaseLayer, // BaseKeyframeAnimation, LottieDrawable, Utils, Content, // TrimPathContent class ShapeContent implements BaseKeyframeAnimation.AnimationListener, PathContent { ShapeContent(LottieDrawable lottiedrawable, BaseLayer baselayer, ShapePath shapepath) { // 0 0:aload_0 // 1 1:invokespecial #27 <Method void Object()> // 2 4:aload_0 // 3 5:new #29 <Class Path> // 4 8:dup // 5 9:invokespecial #30 <Method void Path()> // 6 12:putfield #32 <Field Path path> name = shapepath.getName(); // 7 15:aload_0 // 8 16:aload_3 // 9 17:invokevirtual #38 <Method String ShapePath.getName()> // 10 20:putfield #40 <Field String name> lottieDrawable = lottiedrawable; // 11 23:aload_0 // 12 24:aload_1 // 13 25:putfield #42 <Field LottieDrawable lottieDrawable> shapeAnimation = shapepath.getShapePath().createAnimation(); // 14 28:aload_0 // 15 29:aload_3 // 16 30:invokevirtual #46 <Method AnimatableShapeValue ShapePath.getShapePath()> // 17 33:invokevirtual #52 <Method BaseKeyframeAnimation AnimatableShapeValue.createAnimation()> // 18 36:putfield #54 <Field BaseKeyframeAnimation shapeAnimation> baselayer.addAnimation(shapeAnimation); // 19 39:aload_2 // 20 40:aload_0 // 21 41:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 22 44:invokevirtual #60 <Method void BaseLayer.addAnimation(BaseKeyframeAnimation)> shapeAnimation.addUpdateListener(((BaseKeyframeAnimation.AnimationListener) (this))); // 23 47:aload_0 // 24 48:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 25 51:aload_0 // 26 52:invokevirtual #66 <Method void BaseKeyframeAnimation.addUpdateListener(BaseKeyframeAnimation$AnimationListener)> // 27 55:return } private void invalidate() { isPathValid = false; // 0 0:aload_0 // 1 1:iconst_0 // 2 2:putfield #70 <Field boolean isPathValid> lottieDrawable.invalidateSelf(); // 3 5:aload_0 // 4 6:getfield #42 <Field LottieDrawable lottieDrawable> // 5 9:invokevirtual #75 <Method void LottieDrawable.invalidateSelf()> // 6 12:return } public String getName() { return name; // 0 0:aload_0 // 1 1:getfield #40 <Field String name> // 2 4:areturn } public Path getPath() { if(isPathValid) //* 0 0:aload_0 //* 1 1:getfield #70 <Field boolean isPathValid> //* 2 4:ifeq 12 { return path; // 3 7:aload_0 // 4 8:getfield #32 <Field Path path> // 5 11:areturn } else { path.reset(); // 6 12:aload_0 // 7 13:getfield #32 <Field Path path> // 8 16:invokevirtual #80 <Method void Path.reset()> path.set((Path)shapeAnimation.getValue()); // 9 19:aload_0 // 10 20:getfield #32 <Field Path path> // 11 23:aload_0 // 12 24:getfield #54 <Field BaseKeyframeAnimation shapeAnimation> // 13 27:invokevirtual #84 <Method Object BaseKeyframeAnimation.getValue()> // 14 30:checkcast #29 <Class Path> // 15 33:invokevirtual #88 <Method void Path.set(Path)> path.setFillType(android.graphics.Path.FillType.EVEN_ODD); // 16 36:aload_0 // 17 37:getfield #32 <Field Path path> // 18 40:getstatic #94 <Field android.graphics.Path$FillType android.graphics.Path$FillType.EVEN_ODD> // 19 43:invokevirtual #98 <Method void Path.setFillType(android.graphics.Path$FillType)> Utils.applyTrimPathIfNeeded(path, trimPath); // 20 46:aload_0 // 21 47:getfield #32 <Field Path path> // 22 50:aload_0 // 23 51:getfield #100 <Field TrimPathContent trimPath> // 24 54:invokestatic #106 <Method void Utils.applyTrimPathIfNeeded(Path, TrimPathContent)> isPathValid = true; // 25 57:aload_0 // 26 58:iconst_1 // 27 59:putfield #70 <Field boolean isPathValid> return path; // 28 62:aload_0 // 29 63:getfield #32 <Field Path path> // 30 66:areturn } } public void onValueChanged() { invalidate(); // 0 0:aload_0 // 1 1:invokespecial #109 <Method void invalidate()> // 2 4:return } public void setContents(List list, List list1) { for(int i = 0; i < list.size(); i++) //* 0 0:iconst_0 //* 1 1:istore_3 //* 2 2:iload_3 //* 3 3:aload_1 //* 4 4:invokeinterface #117 <Method int List.size()> //* 5 9:icmpge 65 { list1 = ((List) ((Content)list.get(i))); // 6 12:aload_1 // 7 13:iload_3 // 8 14:invokeinterface #121 <Method Object List.get(int)> // 9 19:checkcast #123 <Class Content> // 10 22:astore_2 if(!(list1 instanceof TrimPathContent)) continue; // 11 23:aload_2 // 12 24:instanceof #125 <Class TrimPathContent> // 13 27:ifeq 58 list1 = ((List) ((TrimPathContent)list1)); // 14 30:aload_2 // 15 31:checkcast #125 <Class TrimPathContent> // 16 34:astore_2 if(((TrimPathContent) (list1)).getType() == ShapeTrimPath.Type.Simultaneously) //* 17 35:aload_2 //* 18 36:invokevirtual #129 <Method ShapeTrimPath$Type TrimPathContent.getType()> //* 19 39:getstatic #135 <Field ShapeTrimPath$Type ShapeTrimPath$Type.Simultaneously> //* 20 42:if_acmpne 58 { trimPath = ((TrimPathContent) (list1)); // 21 45:aload_0 // 22 46:aload_2 // 23 47:putfield #100 <Field TrimPathContent trimPath> trimPath.addListener(((BaseKeyframeAnimation.AnimationListener) (this))); // 24 50:aload_0 // 25 51:getfield #100 <Field TrimPathContent trimPath> // 26 54:aload_0 // 27 55:invokevirtual #138 <Method void TrimPathContent.addListener(BaseKeyframeAnimation$AnimationListener)> } } // 28 58:iload_3 // 29 59:iconst_1 // 30 60:iadd // 31 61:istore_3 //* 32 62:goto 2 // 33 65:return } private boolean isPathValid; private final LottieDrawable lottieDrawable; private final String name; private final Path path = new Path(); private final BaseKeyframeAnimation shapeAnimation; private TrimPathContent trimPath; }
7,232
0.580088
0.50718
189
37.317459
26.752535
129
false
false
0
0
0
0
0
0
1.433862
false
false
12
17eaf880ca5bfe64734fc1b48cffe3a644e8fd8b
10,299,331,580,976
27770949ff9233db6ec09025f350cfd105328998
/src/main/java/minecrafttransportsimulator/guis/instances/GUIRadio.java
8feeae0b77fbb605c0409bab6a26e486fa63e708
[]
no_license
HydrogenC/MinecraftTransportSimulator
https://github.com/HydrogenC/MinecraftTransportSimulator
d5801d20d262579b50d8b1e0cd07af2f93f196f0
4a2b3319c2df373e8a431e556fd95c2e21a3488a
refs/heads/master
2020-12-09T15:01:26.934000
2020-03-22T07:41:10
2020-03-22T07:41:10
233,341,933
0
0
null
true
2020-03-22T03:41:10
2020-01-12T05:13:51
2020-01-25T03:43:09
2020-03-22T03:41:10
11,879
0
0
0
Java
false
false
package minecrafttransportsimulator.guis.instances; import java.awt.Color; import java.net.URL; import java.util.ArrayList; import java.util.List; import minecrafttransportsimulator.MTS; import minecrafttransportsimulator.guis.components.AGUIBase; import minecrafttransportsimulator.guis.components.GUIComponentButton; import minecrafttransportsimulator.guis.components.GUIComponentTextBox; import minecrafttransportsimulator.radio.Radio; import minecrafttransportsimulator.radio.RadioContainer; import minecrafttransportsimulator.radio.RadioManager; public class GUIRadio extends AGUIBase{ //Buttons. private GUIComponentButton offButton; private GUIComponentButton localButton; private GUIComponentButton remoteButton; private GUIComponentButton serverButton; private GUIComponentButton randomButton; private GUIComponentButton orderedButton; private GUIComponentButton setButton; private GUIComponentButton volUpButton; private GUIComponentButton volDnButton; private List<GUIComponentButton> presetButtons = new ArrayList<GUIComponentButton>(); //Input boxes private GUIComponentTextBox stationDisplay; private GUIComponentTextBox volumeDisplay; //Runtime information. private final Radio radio; private static boolean localMode = true; private static boolean randomMode = false; private static boolean teachMode = false; public GUIRadio(RadioContainer container){ RadioManager.init(MTS.minecraftDir); radio = RadioManager.getRadio(container); } @Override public void setupComponents(int guiLeft, int guiTop){ addButton(offButton = new GUIComponentButton(guiLeft + 15, guiTop + 20, 45, "OFF"){ public void onClicked(){ presetButtons.get(radio.getPresetSelected()).enabled = true; radio.stopPlaying(); stationDisplay.setText(""); teachMode = false; } }); addButton(localButton = new GUIComponentButton(guiLeft + 15, guiTop + 40, 45, "FOLDER"){ public void onClicked(){ localMode = true; teachMode = false; if(radio.getPresetSelected() != -1){ offButton.onClicked(); } } }); addButton(remoteButton = new GUIComponentButton(guiLeft + 15, guiTop + 60, 45, "RADIO"){ public void onClicked(){ localMode = false; if(radio.getPresetSelected() != -1){ offButton.onClicked(); } } }); addButton(serverButton = new GUIComponentButton(guiLeft + 15, guiTop + 80, 45, "SERVER"){public void onClicked(){}}); addButton(randomButton = new GUIComponentButton(guiLeft + 80, guiTop + 30, 45, "RANDOM"){public void onClicked(){randomMode = true;}}); addButton(orderedButton = new GUIComponentButton(guiLeft + 80, guiTop + 50, 45, "SORTED"){public void onClicked(){randomMode = false;}}); addButton(setButton = new GUIComponentButton(guiLeft + 190, guiTop + 80, 45, "SET"){ public void onClicked(){ if(teachMode){ teachMode = false; stationDisplay.setText(""); }else{ teachMode = true; stationDisplay.setText("Type or paste a URL (CTRL+V).\nThen press press a preset button."); stationDisplay.focused = true; } } }); addButton(volUpButton = new GUIComponentButton(guiLeft + 205, guiTop + 20, 30, "UP"){public void onClicked(){radio.setVolume((byte) (radio.getVolume() + 1));}}); addButton(volDnButton = new GUIComponentButton(guiLeft + 205, guiTop + 40, 30, "DN"){public void onClicked(){radio.setVolume((byte) (radio.getVolume() - 1));}}); presetButtons.clear(); int x = 25; for(byte i=1; i<7; ++i){ presetButtons.add(new GUIComponentButton(guiLeft + x, guiTop + 155, 35, String.valueOf(i)){public void onClicked(){presetButtonClicked(this);}}); addButton(presetButtons.get(i-1)); x += 35; } addTextBox(stationDisplay = new GUIComponentTextBox(guiLeft + 20, guiTop + 105, 220, radio.getSource(), 45, Color.WHITE, Color.BLACK, 100)); addTextBox(volumeDisplay = new GUIComponentTextBox(guiLeft + 180, guiTop + 20, 25, "", 40, Color.WHITE, Color.BLACK, 32)); } @Override public void setStates(){ //Off button is enabled when radio is playing. offButton.enabled = radio.getPlayState() != -1; //Local-remote are toggles. Server is for future use and permanently disabled. localButton.enabled = !localMode; remoteButton.enabled = localMode; serverButton.enabled = false; //Random/ordered buttons are toggles, but only active when playing locally from folder. randomButton.enabled = !randomMode && localMode; orderedButton.enabled = randomMode && localMode; //Set button only works if not in local mode (playing from radio URL). //Once button is pressed, teach mode activates and stationDisplay becomes a station entry box. //Otherwise, it's just a box that displays what's playing. setButton.enabled = !localMode; stationDisplay.enabled = teachMode; if(!teachMode){ stationDisplay.setText(radio.getSource()); } //Set volume system states to current volume settings. volumeDisplay.enabled = false; volumeDisplay.setText("VOL " + String.valueOf(radio.getVolume())); volUpButton.enabled = radio.getVolume() < 10; volDnButton.enabled = radio.getVolume() > 0; } private void presetButtonClicked(GUIComponentButton buttonClicked){ int presetClicked = presetButtons.indexOf(buttonClicked); //Enable the last-selected button if needed. if(radio.getPresetSelected() != -1){ presetButtons.get(radio.getPresetSelected()).enabled = true; } if(teachMode){ RadioManager.setRadioStation(stationDisplay.getText(), presetClicked); stationDisplay.setText("Station set to preset " + (presetClicked + 1)); teachMode = false; }else if(localMode){ String directory = RadioManager.getMusicDirectories().get(presetClicked); if(!directory.isEmpty()){ stationDisplay.setText(directory); radio.playLocal(directory, presetClicked, !randomMode); buttonClicked.enabled = false; }else{ stationDisplay.setText("Fewer than " + (presetClicked + 1) + " folders in mts_music."); } }else{ String station = RadioManager.getRadioStations().get(presetClicked); if(station.isEmpty()){ stationDisplay.setText("Press SET to teach a station."); }else{ URL url = null; try{ url = new URL(station); }catch(Exception e){} if(url == null || !radio.playInternet(url, presetClicked)){ stationDisplay.setText("INVALID URL!"); RadioManager.setRadioStation("", presetClicked); }else{ stationDisplay.setText(station); buttonClicked.enabled = false; } } } } }
UTF-8
Java
6,487
java
GUIRadio.java
Java
[]
null
[]
package minecrafttransportsimulator.guis.instances; import java.awt.Color; import java.net.URL; import java.util.ArrayList; import java.util.List; import minecrafttransportsimulator.MTS; import minecrafttransportsimulator.guis.components.AGUIBase; import minecrafttransportsimulator.guis.components.GUIComponentButton; import minecrafttransportsimulator.guis.components.GUIComponentTextBox; import minecrafttransportsimulator.radio.Radio; import minecrafttransportsimulator.radio.RadioContainer; import minecrafttransportsimulator.radio.RadioManager; public class GUIRadio extends AGUIBase{ //Buttons. private GUIComponentButton offButton; private GUIComponentButton localButton; private GUIComponentButton remoteButton; private GUIComponentButton serverButton; private GUIComponentButton randomButton; private GUIComponentButton orderedButton; private GUIComponentButton setButton; private GUIComponentButton volUpButton; private GUIComponentButton volDnButton; private List<GUIComponentButton> presetButtons = new ArrayList<GUIComponentButton>(); //Input boxes private GUIComponentTextBox stationDisplay; private GUIComponentTextBox volumeDisplay; //Runtime information. private final Radio radio; private static boolean localMode = true; private static boolean randomMode = false; private static boolean teachMode = false; public GUIRadio(RadioContainer container){ RadioManager.init(MTS.minecraftDir); radio = RadioManager.getRadio(container); } @Override public void setupComponents(int guiLeft, int guiTop){ addButton(offButton = new GUIComponentButton(guiLeft + 15, guiTop + 20, 45, "OFF"){ public void onClicked(){ presetButtons.get(radio.getPresetSelected()).enabled = true; radio.stopPlaying(); stationDisplay.setText(""); teachMode = false; } }); addButton(localButton = new GUIComponentButton(guiLeft + 15, guiTop + 40, 45, "FOLDER"){ public void onClicked(){ localMode = true; teachMode = false; if(radio.getPresetSelected() != -1){ offButton.onClicked(); } } }); addButton(remoteButton = new GUIComponentButton(guiLeft + 15, guiTop + 60, 45, "RADIO"){ public void onClicked(){ localMode = false; if(radio.getPresetSelected() != -1){ offButton.onClicked(); } } }); addButton(serverButton = new GUIComponentButton(guiLeft + 15, guiTop + 80, 45, "SERVER"){public void onClicked(){}}); addButton(randomButton = new GUIComponentButton(guiLeft + 80, guiTop + 30, 45, "RANDOM"){public void onClicked(){randomMode = true;}}); addButton(orderedButton = new GUIComponentButton(guiLeft + 80, guiTop + 50, 45, "SORTED"){public void onClicked(){randomMode = false;}}); addButton(setButton = new GUIComponentButton(guiLeft + 190, guiTop + 80, 45, "SET"){ public void onClicked(){ if(teachMode){ teachMode = false; stationDisplay.setText(""); }else{ teachMode = true; stationDisplay.setText("Type or paste a URL (CTRL+V).\nThen press press a preset button."); stationDisplay.focused = true; } } }); addButton(volUpButton = new GUIComponentButton(guiLeft + 205, guiTop + 20, 30, "UP"){public void onClicked(){radio.setVolume((byte) (radio.getVolume() + 1));}}); addButton(volDnButton = new GUIComponentButton(guiLeft + 205, guiTop + 40, 30, "DN"){public void onClicked(){radio.setVolume((byte) (radio.getVolume() - 1));}}); presetButtons.clear(); int x = 25; for(byte i=1; i<7; ++i){ presetButtons.add(new GUIComponentButton(guiLeft + x, guiTop + 155, 35, String.valueOf(i)){public void onClicked(){presetButtonClicked(this);}}); addButton(presetButtons.get(i-1)); x += 35; } addTextBox(stationDisplay = new GUIComponentTextBox(guiLeft + 20, guiTop + 105, 220, radio.getSource(), 45, Color.WHITE, Color.BLACK, 100)); addTextBox(volumeDisplay = new GUIComponentTextBox(guiLeft + 180, guiTop + 20, 25, "", 40, Color.WHITE, Color.BLACK, 32)); } @Override public void setStates(){ //Off button is enabled when radio is playing. offButton.enabled = radio.getPlayState() != -1; //Local-remote are toggles. Server is for future use and permanently disabled. localButton.enabled = !localMode; remoteButton.enabled = localMode; serverButton.enabled = false; //Random/ordered buttons are toggles, but only active when playing locally from folder. randomButton.enabled = !randomMode && localMode; orderedButton.enabled = randomMode && localMode; //Set button only works if not in local mode (playing from radio URL). //Once button is pressed, teach mode activates and stationDisplay becomes a station entry box. //Otherwise, it's just a box that displays what's playing. setButton.enabled = !localMode; stationDisplay.enabled = teachMode; if(!teachMode){ stationDisplay.setText(radio.getSource()); } //Set volume system states to current volume settings. volumeDisplay.enabled = false; volumeDisplay.setText("VOL " + String.valueOf(radio.getVolume())); volUpButton.enabled = radio.getVolume() < 10; volDnButton.enabled = radio.getVolume() > 0; } private void presetButtonClicked(GUIComponentButton buttonClicked){ int presetClicked = presetButtons.indexOf(buttonClicked); //Enable the last-selected button if needed. if(radio.getPresetSelected() != -1){ presetButtons.get(radio.getPresetSelected()).enabled = true; } if(teachMode){ RadioManager.setRadioStation(stationDisplay.getText(), presetClicked); stationDisplay.setText("Station set to preset " + (presetClicked + 1)); teachMode = false; }else if(localMode){ String directory = RadioManager.getMusicDirectories().get(presetClicked); if(!directory.isEmpty()){ stationDisplay.setText(directory); radio.playLocal(directory, presetClicked, !randomMode); buttonClicked.enabled = false; }else{ stationDisplay.setText("Fewer than " + (presetClicked + 1) + " folders in mts_music."); } }else{ String station = RadioManager.getRadioStations().get(presetClicked); if(station.isEmpty()){ stationDisplay.setText("Press SET to teach a station."); }else{ URL url = null; try{ url = new URL(station); }catch(Exception e){} if(url == null || !radio.playInternet(url, presetClicked)){ stationDisplay.setText("INVALID URL!"); RadioManager.setRadioStation("", presetClicked); }else{ stationDisplay.setText(station); buttonClicked.enabled = false; } } } } }
6,487
0.728226
0.712194
170
37.158825
34.043461
163
false
false
0
0
0
0
0
0
3.147059
false
false
12
206b88f3abfe51a51d51a4c68050d77a1f5e4fec
2,284,922,608,290
72505428c14e83ff8777fa2019ab0cbad5a6080f
/hello-service-api/src/main/java/com/xzs/FuckService.java
5da8b5e302405fbec7da5026225352b07e16052e
[]
no_license
xzso3o/My-RPC-Framework
https://github.com/xzso3o/My-RPC-Framework
ef9b18a1770f94f349091fa13d2e555f52906fad
c8ce387ba3c4e4e2010c8f933809b93ef7389042
refs/heads/main
2023-06-14T09:13:45.045000
2021-07-12T15:16:00
2021-07-12T15:16:00
385,290,294
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xzs; public interface FuckService { String fuck(FuckObject fuckObject); }
UTF-8
Java
91
java
FuckService.java
Java
[]
null
[]
package com.xzs; public interface FuckService { String fuck(FuckObject fuckObject); }
91
0.758242
0.758242
5
17.200001
15.484185
39
false
false
0
0
0
0
0
0
0.4
false
false
12
83386480ca547ce61512e00f9fcb0824284420e1
32,169,305,059,328
2b42b62fe46103e474009cbaf7122c2dbca0388c
/app/src/main/java/ru/abr/dit/DAO/UPGDAO.java
77e310c578e1298be4798669d125c4bf60430691
[]
no_license
maximec2406/IKS
https://github.com/maximec2406/IKS
0635bd95d83231a300c7b7322be89486359cf15e
2cbba29c4dd2b6293e63d2bba1dc4ff26dd5b111
refs/heads/master
2023-01-10T14:12:53.998000
2019-11-08T15:00:07
2019-11-08T15:00:07
212,336,420
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.abr.dit.DAO; public class UPGDAO { private String host; private String port; private String login; private String pass; private String protocol; private String path; private String namespaceURI; private String namespace; private String servicename; private String sourceURI; public UPGDAO(String host, String port, String login, String pass, String protocol, String path, String namespaceURI, String namespace, String servicename) { this.host = host; this.port = port; this.login = login; this.pass = pass; this.protocol = protocol; this.path = path; this.namespaceURI = namespaceURI; this.namespace = namespace; this.servicename = servicename; this.sourceURI = protocol + host + ":" + port + path + "/" + servicename; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getNamespaceURI() { return namespaceURI; } public void setNamespaceURI(String namespaceURI) { this.namespaceURI = namespaceURI; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getServicename() { return servicename; } public void setServicename(String servicename) { this.servicename = servicename; } public String getSourceURI() { return sourceURI; } public void setSourceURI(String sourceURI) { this.sourceURI = sourceURI; } }
UTF-8
Java
2,355
java
UPGDAO.java
Java
[]
null
[]
package ru.abr.dit.DAO; public class UPGDAO { private String host; private String port; private String login; private String pass; private String protocol; private String path; private String namespaceURI; private String namespace; private String servicename; private String sourceURI; public UPGDAO(String host, String port, String login, String pass, String protocol, String path, String namespaceURI, String namespace, String servicename) { this.host = host; this.port = port; this.login = login; this.pass = pass; this.protocol = protocol; this.path = path; this.namespaceURI = namespaceURI; this.namespace = namespace; this.servicename = servicename; this.sourceURI = protocol + host + ":" + port + path + "/" + servicename; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getNamespaceURI() { return namespaceURI; } public void setNamespaceURI(String namespaceURI) { this.namespaceURI = namespaceURI; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getServicename() { return servicename; } public void setServicename(String servicename) { this.servicename = servicename; } public String getSourceURI() { return sourceURI; } public void setSourceURI(String sourceURI) { this.sourceURI = sourceURI; } }
2,355
0.604671
0.604671
117
19.128204
21.254879
161
false
false
0
0
0
0
0
0
0.418803
false
false
12
84667307c312b9755781e1ee2c4ce4ff983bbd86
25,108,378,819,647
ccc792147fad0672f549546e9dd83a84c37e621c
/app/src/main/java/com/example/mybook/utils/Rx.java
2b9a043231c9418e4fb29be9ffc70714907932d0
[]
no_license
tomycatbaby/MyBook
https://github.com/tomycatbaby/MyBook
4b452b09a31d55d0f0604a0b636c337688e8d9a1
eae26ca6057f1bf5e5caef101496e4c60f299179
refs/heads/master
2020-05-30T05:29:48.715000
2020-01-17T02:24:18
2020-01-17T02:24:18
189,561,641
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mybook.utils; import android.util.Log; import com.example.mybook.entity.UserInfo; import com.google.gson.JsonObject; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.Scheduler; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class Rx { private static final String TAG = "Rx"; public void test() { Observer<String> observer = new Observer<String>() { //一次性用品 private Disposable disposable; private int i; @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } @Override public void onSubscribe(Disposable d) { disposable = d; } @Override public void onNext(String s) { Log.d(TAG, "onNext: " + s); i++; if (i == 2) { Log.d(TAG, "dispose: "); disposable.dispose(); } } }; Flowable flowable = new Flowable() { @Override protected void subscribeActual(Subscriber s) { } }; Subscriber<String> subscriber = new Subscriber<String>() { @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } @Override public void onSubscribe(Subscription s) { } @Override public void onNext(String c) { Log.d(TAG, "onNext: " + c); } }; List<String> list = new ArrayList<>(); list.add("数学"); list.add("语文"); list.add("英语"); Student[] students = {new Student(list), new Student(list)}; /* Observable.fromArray(students) .flatMap(new Function<Student, ObservableSource<?>>() { @Override public ObservableSource<?> apply(Student student) throws Exception { return null; } }) .throttleFirst(500, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe();*/ Observable<String> observable1 = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> emitter) throws Exception { Log.d(TAG, "emitter: 1"); emitter.onNext("1"); Log.d(TAG, "emitter: 2"); emitter.onNext("2"); Log.d(TAG, "emitter: 3"); emitter.onNext("3"); } }); Observable<Integer> observable2 = Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(ObservableEmitter<Integer> emitter) throws Exception { Log.d(TAG, "emitter: 111"); emitter.onNext(11); Log.d(TAG, "emitter: 22"); emitter.onNext(22); } }); Observable.zip(observable1, observable2, new BiFunction<String, Integer, String>() { @Override public String apply(String s, Integer integer) throws Exception { return s + integer; } }).subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String o) { Log.d(TAG, "onNext: " + o); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); observable1.subscribe(); /* observable.subscribeOn(Schedulers.io())//指定subscribe发生在io线程 上游事件发送线程 .observeOn(AndroidSchedulers.mainThread())//指定subscribe的回调发生在主线程 下游事件处理线程 .subscribe();*/ } public void request() { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl("https://www.wanandroid.com/") .build(); WeatherService weatherService = retrofit.create(WeatherService.class); // weatherService.login("408","3") // .subscribeOn(Schedulers.newThread()) // .observeOn(Schedulers.io()) // .doOnNext(new Consumer<JsonObject>() { // @Override // public void accept(JsonObject jsonObject) throws Exception { // Log.d(TAG, "accept: "); // } // }).subscribe(new Observer<JsonObject>() { // @Override // public void onSubscribe(Disposable d) { // // } // // @Override // public void onNext(JsonObject jsonObject) { // Log.d(TAG, "onNext: "); // Log.d(TAG, "on: "+jsonObject.getAsJsonObject("data").get("curPage").getAsString()); // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError: "); // } // // @Override // public void onComplete() { // // } // }); Observable<JsonObject> observable1 = weatherService.login("408", "1") .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.io()) .doOnNext(new Consumer<JsonObject>() { @Override public void accept(JsonObject jsonObject) throws Exception { } }); observable1.subscribe(new Observer<JsonObject>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(JsonObject jsonObject) { Log.d(TAG, "onNext: "); } @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } }); // Observable<JsonObject> observable2 = weatherService.login("408", "2") // .subscribeOn(Schedulers.newThread()) // .observeOn(Schedulers.io()) // .doOnNext(new Consumer<JsonObject>() { // @Override // public void accept(JsonObject jsonObject) throws Exception { // // } // }); // // Observable.zip(observable1, observable2, new BiFunction<JsonObject, JsonObject, String>() { // @Override // public String apply(JsonObject jsonObject, JsonObject jsonObject2) throws Exception { // Log.d(TAG, "apply: "); // String s1 = jsonObject.getAsJsonObject("data").get("curPage").getAsString(); // String s2 = jsonObject2.getAsJsonObject("data").get("curPage").getAsString(); // // return s1 + s2; // } // }).subscribe(new Observer<String>() { // // @Override // public void onSubscribe(Disposable d) { // Log.d(TAG, "onSubscribe: "); // } // // @Override // public void onNext(String s) { // Log.d(TAG, "onNext: " + s); // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError: " + e.getMessage()); // } // // @Override // public void onComplete() { // Log.d(TAG, "onComplete: "); // } // }); } class Student { List<String> courses; public Student(List<String> courses) { this.courses = courses; } public List<String> getCourses() { return courses; } public void setCourses(List<String> courses) { this.courses = courses; } } }
UTF-8
Java
9,256
java
Rx.java
Java
[]
null
[]
package com.example.mybook.utils; import android.util.Log; import com.example.mybook.entity.UserInfo; import com.google.gson.JsonObject; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.Scheduler; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class Rx { private static final String TAG = "Rx"; public void test() { Observer<String> observer = new Observer<String>() { //一次性用品 private Disposable disposable; private int i; @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } @Override public void onSubscribe(Disposable d) { disposable = d; } @Override public void onNext(String s) { Log.d(TAG, "onNext: " + s); i++; if (i == 2) { Log.d(TAG, "dispose: "); disposable.dispose(); } } }; Flowable flowable = new Flowable() { @Override protected void subscribeActual(Subscriber s) { } }; Subscriber<String> subscriber = new Subscriber<String>() { @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } @Override public void onSubscribe(Subscription s) { } @Override public void onNext(String c) { Log.d(TAG, "onNext: " + c); } }; List<String> list = new ArrayList<>(); list.add("数学"); list.add("语文"); list.add("英语"); Student[] students = {new Student(list), new Student(list)}; /* Observable.fromArray(students) .flatMap(new Function<Student, ObservableSource<?>>() { @Override public ObservableSource<?> apply(Student student) throws Exception { return null; } }) .throttleFirst(500, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe();*/ Observable<String> observable1 = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> emitter) throws Exception { Log.d(TAG, "emitter: 1"); emitter.onNext("1"); Log.d(TAG, "emitter: 2"); emitter.onNext("2"); Log.d(TAG, "emitter: 3"); emitter.onNext("3"); } }); Observable<Integer> observable2 = Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(ObservableEmitter<Integer> emitter) throws Exception { Log.d(TAG, "emitter: 111"); emitter.onNext(11); Log.d(TAG, "emitter: 22"); emitter.onNext(22); } }); Observable.zip(observable1, observable2, new BiFunction<String, Integer, String>() { @Override public String apply(String s, Integer integer) throws Exception { return s + integer; } }).subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String o) { Log.d(TAG, "onNext: " + o); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); observable1.subscribe(); /* observable.subscribeOn(Schedulers.io())//指定subscribe发生在io线程 上游事件发送线程 .observeOn(AndroidSchedulers.mainThread())//指定subscribe的回调发生在主线程 下游事件处理线程 .subscribe();*/ } public void request() { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl("https://www.wanandroid.com/") .build(); WeatherService weatherService = retrofit.create(WeatherService.class); // weatherService.login("408","3") // .subscribeOn(Schedulers.newThread()) // .observeOn(Schedulers.io()) // .doOnNext(new Consumer<JsonObject>() { // @Override // public void accept(JsonObject jsonObject) throws Exception { // Log.d(TAG, "accept: "); // } // }).subscribe(new Observer<JsonObject>() { // @Override // public void onSubscribe(Disposable d) { // // } // // @Override // public void onNext(JsonObject jsonObject) { // Log.d(TAG, "onNext: "); // Log.d(TAG, "on: "+jsonObject.getAsJsonObject("data").get("curPage").getAsString()); // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError: "); // } // // @Override // public void onComplete() { // // } // }); Observable<JsonObject> observable1 = weatherService.login("408", "1") .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.io()) .doOnNext(new Consumer<JsonObject>() { @Override public void accept(JsonObject jsonObject) throws Exception { } }); observable1.subscribe(new Observer<JsonObject>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(JsonObject jsonObject) { Log.d(TAG, "onNext: "); } @Override public void onError(Throwable e) { Log.d(TAG, "onError: "); } @Override public void onComplete() { } }); // Observable<JsonObject> observable2 = weatherService.login("408", "2") // .subscribeOn(Schedulers.newThread()) // .observeOn(Schedulers.io()) // .doOnNext(new Consumer<JsonObject>() { // @Override // public void accept(JsonObject jsonObject) throws Exception { // // } // }); // // Observable.zip(observable1, observable2, new BiFunction<JsonObject, JsonObject, String>() { // @Override // public String apply(JsonObject jsonObject, JsonObject jsonObject2) throws Exception { // Log.d(TAG, "apply: "); // String s1 = jsonObject.getAsJsonObject("data").get("curPage").getAsString(); // String s2 = jsonObject2.getAsJsonObject("data").get("curPage").getAsString(); // // return s1 + s2; // } // }).subscribe(new Observer<String>() { // // @Override // public void onSubscribe(Disposable d) { // Log.d(TAG, "onSubscribe: "); // } // // @Override // public void onNext(String s) { // Log.d(TAG, "onNext: " + s); // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError: " + e.getMessage()); // } // // @Override // public void onComplete() { // Log.d(TAG, "onComplete: "); // } // }); } class Student { List<String> courses; public Student(List<String> courses) { this.courses = courses; } public List<String> getCourses() { return courses; } public void setCourses(List<String> courses) { this.courses = courses; } } }
9,256
0.514292
0.50851
303
29.250826
24.256668
101
false
false
0
0
0
0
0
0
0.419142
false
false
12
2cd79c34d5b54e739159066f6f3a1f31cfe27dad
3,925,600,125,602
14bafeecd463ce7e6d505fa8f82068202ae52858
/training-app-monolithic-v1/src/main/java/com/agileactors/domain/ContractType.java
4d7c3560e534474bc800770764759f85cc9b8c53
[]
no_license
christosperis/training-apps
https://github.com/christosperis/training-apps
88515e670bb52a91b84c0e6747d4c9d7c865cfe8
fb4e8b46dcd429a1ca53527b086bdb315f35b823
refs/heads/master
2020-04-21T16:59:05.871000
2019-02-01T12:30:43
2019-02-01T12:30:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.agileactors.domain; public enum ContractType { LIFE, VEHICLE }
UTF-8
Java
80
java
ContractType.java
Java
[]
null
[]
package com.agileactors.domain; public enum ContractType { LIFE, VEHICLE }
80
0.75
0.75
5
15
12.664912
31
false
false
0
0
0
0
0
0
0.4
false
false
12
f9043c494399c73eb856eb88519ae514cd3192d6
28,965,259,460,989
bd0a160ae9df2695d400080604f3bb944493e369
/src/main/java/com/enfernuz/quik/lua/rpc/serde/protobuf/GetInfoParamArgsPbSerializer.java
bc1bb4286b5b87e49192758aa14db3f43815bffb
[]
no_license
Enfernuz/quik-lua-rpc-java-client
https://github.com/Enfernuz/quik-lua-rpc-java-client
c2380301d31445fd671577cf1db8f82318af1fe7
7dbe225f60c671af91a08eb9ad02e94a5ce4e956
refs/heads/master
2023-06-22T02:24:40.449000
2022-04-04T03:37:22
2022-04-04T03:37:22
109,439,391
7
7
null
false
2023-06-14T22:51:31
2017-11-03T20:22:31
2023-05-08T19:30:00
2023-06-14T22:51:31
1,525
8
6
5
Java
false
false
package com.enfernuz.quik.lua.rpc.serde.protobuf; import com.enfernuz.quik.lua.rpc.api.messages.GetInfoParam; import com.enfernuz.quik.lua.rpc.serde.Serializer; import org.jetbrains.annotations.NotNull; enum GetInfoParamArgsPbSerializer implements Serializer<GetInfoParam.Args>, ToPbConverter<GetInfoParam.Args, qlua.rpc.GetInfoParam.Args> { INSTANCE; @Override public @NotNull byte[] serialize(@NotNull final GetInfoParam.Args args) { return convert(args).toByteArray(); } @Override public @NotNull qlua.rpc.GetInfoParam.Args convert(@NotNull final GetInfoParam.Args args) { return qlua.rpc.GetInfoParam.Args.newBuilder() .setParamName( args.getParamName() ) .build(); } }
UTF-8
Java
756
java
GetInfoParamArgsPbSerializer.java
Java
[]
null
[]
package com.enfernuz.quik.lua.rpc.serde.protobuf; import com.enfernuz.quik.lua.rpc.api.messages.GetInfoParam; import com.enfernuz.quik.lua.rpc.serde.Serializer; import org.jetbrains.annotations.NotNull; enum GetInfoParamArgsPbSerializer implements Serializer<GetInfoParam.Args>, ToPbConverter<GetInfoParam.Args, qlua.rpc.GetInfoParam.Args> { INSTANCE; @Override public @NotNull byte[] serialize(@NotNull final GetInfoParam.Args args) { return convert(args).toByteArray(); } @Override public @NotNull qlua.rpc.GetInfoParam.Args convert(@NotNull final GetInfoParam.Args args) { return qlua.rpc.GetInfoParam.Args.newBuilder() .setParamName( args.getParamName() ) .build(); } }
756
0.722222
0.722222
23
31.869566
35.723946
138
false
false
0
0
0
0
0
0
0.391304
false
false
12
f9d2712d92d9c4d372b4b98999722cd9dbf843b2
21,174,188,778,375
c48363cf799063361cf15b25319fa873aecad15e
/automapper/src/main/java/se/codepool/automapper/annotations/ViewModel.java
e857c1014db16cb36d4f35eeed66fef942ca38e6
[]
no_license
Niroda/AutoMapper
https://github.com/Niroda/AutoMapper
0580c0979484f2b2134a6c9f96dbd986ce64d1a7
dacd351e59f8a38dbb93fa96bc613328c2d1942d
refs/heads/master
2020-03-11T08:56:25.111000
2018-06-04T09:12:50
2018-06-04T09:12:50
129,896,665
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package se.codepool.automapper.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(TYPE) /** * An annotation used to select to which entity will current type be mapped. * @author Ali */ public @interface ViewModel { /** * Entity type to be mapped from * @return * Entity type to be mapped */ Class<?> entity(); }
UTF-8
Java
520
java
ViewModel.java
Java
[ { "context": "ich entity will current type be mapped.\n * @author Ali\n */\npublic @interface ViewModel {\n\t/**\n\t * Entity", "end": 376, "score": 0.9952671527862549, "start": 373, "tag": "NAME", "value": "Ali" } ]
null
[]
/** * */ package se.codepool.automapper.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(TYPE) /** * An annotation used to select to which entity will current type be mapped. * @author Ali */ public @interface ViewModel { /** * Entity type to be mapped from * @return * Entity type to be mapped */ Class<?> entity(); }
520
0.726923
0.726923
25
19.799999
20.778835
76
false
false
0
0
0
0
0
0
0.56
false
false
13
33caa4732028ea9cdbe9d7231ed11b7878d5f2ec
27,333,171,886,701
c8a2df66e878645a387cd4cbcd89368a0ec02ac4
/src/test/java/Impuestos/Datos_confImpuestos.java
623108f251a8793c9c6046c5b6151305d5476d04
[]
no_license
nicolasrioseco/ProyectCuore
https://github.com/nicolasrioseco/ProyectCuore
bdd613aac280a96d3da77218d68f459a155ac6ec
d4c9b8e3cfe576064765fb9cf44f392faead0ba6
refs/heads/master
2020-03-18T19:40:19.297000
2018-05-28T14:12:00
2018-05-28T14:12:00
135,169,064
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Impuestos; import java.util.ArrayList; import utility.ExcelUtils; public class Datos_confImpuestos { public static ArrayList<Integer> idProv = new ArrayList<Integer>(); public String setdatosImpuestos(int row) throws Exception { // Listado de Provincias e id: // 1-> Provincia de Buenos Aires, 2->CABA, 3-> Catamarca, 4 -> Chaco, 5 -> Chubut, 6 -> Córdoba, 7 -> Corrientes, 8 -> Entre Rios // 9 -> Formosa, 10 -> Jujuy, 11 -> La Pampa, 12 -> La Rioja, 13 -> Mendoza, 14 -> Misiones, 15 -> Neuquén, 16 -> Río Negro, // 17 -> Salta, 18 -> San Juan, 19 -> San Luis, 20 -> Santa Cruz, 21 -> Santa Fe, 22 -> Santiago del Estero, // 23 -> Tierra del Fuego, 24 -> Tucumán // Dadores e id: // TCC -> 1, COMAFI -> 2 // Periodicidad: // 15 -> Quincenal, 30 -> Mensual int i = row-3; idProv.add(i, (int) ExcelUtils.getCellDataint(row,7)); String provincia = ExcelUtils.getCellData(row,0); String dador = ExcelUtils.getCellData(row,1); int idDador = (int) ExcelUtils.getCellDataint(row,8); int periodicidad = (int) ExcelUtils.getCellDataint(row,2); String tipoAlicuota = "General";//esta versión solo va a configurar alicuotas generales double porcentaje = ExcelUtils.getCellDataint(row,3); String concepto = ExcelUtils.getCellData(row,4); //es el único vigente, corregir cuando se carge toda la parametría en la app ConfImpuestos datosImpuestos = new ConfImpuestos(); datosImpuestos.setconfImpuesto(idProv.get(i), provincia, dador, idDador, periodicidad, tipoAlicuota, porcentaje, concepto); String post = datosImpuestos.getconfImpuesto(); return post; } }
UTF-8
Java
1,634
java
Datos_confImpuestos.java
Java
[]
null
[]
package Impuestos; import java.util.ArrayList; import utility.ExcelUtils; public class Datos_confImpuestos { public static ArrayList<Integer> idProv = new ArrayList<Integer>(); public String setdatosImpuestos(int row) throws Exception { // Listado de Provincias e id: // 1-> Provincia de Buenos Aires, 2->CABA, 3-> Catamarca, 4 -> Chaco, 5 -> Chubut, 6 -> Córdoba, 7 -> Corrientes, 8 -> Entre Rios // 9 -> Formosa, 10 -> Jujuy, 11 -> La Pampa, 12 -> La Rioja, 13 -> Mendoza, 14 -> Misiones, 15 -> Neuquén, 16 -> Río Negro, // 17 -> Salta, 18 -> San Juan, 19 -> San Luis, 20 -> Santa Cruz, 21 -> Santa Fe, 22 -> Santiago del Estero, // 23 -> Tierra del Fuego, 24 -> Tucumán // Dadores e id: // TCC -> 1, COMAFI -> 2 // Periodicidad: // 15 -> Quincenal, 30 -> Mensual int i = row-3; idProv.add(i, (int) ExcelUtils.getCellDataint(row,7)); String provincia = ExcelUtils.getCellData(row,0); String dador = ExcelUtils.getCellData(row,1); int idDador = (int) ExcelUtils.getCellDataint(row,8); int periodicidad = (int) ExcelUtils.getCellDataint(row,2); String tipoAlicuota = "General";//esta versión solo va a configurar alicuotas generales double porcentaje = ExcelUtils.getCellDataint(row,3); String concepto = ExcelUtils.getCellData(row,4); //es el único vigente, corregir cuando se carge toda la parametría en la app ConfImpuestos datosImpuestos = new ConfImpuestos(); datosImpuestos.setconfImpuesto(idProv.get(i), provincia, dador, idDador, periodicidad, tipoAlicuota, porcentaje, concepto); String post = datosImpuestos.getconfImpuesto(); return post; } }
1,634
0.693915
0.66134
45
35.155556
38.837528
130
false
false
0
0
0
0
0
0
2.755556
false
false
13
c14d27a05e7c70dc67cd9135e0820626e6b88476
27,436,251,087,042
c3decddef0007ff6517167ad445c09af3007112c
/app/src/main/java/ru/drsk/progserega/inspectionsheet/services/EquipmentService.java
d297947b21270e7707263c38c26a2fd63e2ecb4c
[]
no_license
progserega/InspectionSheet
https://github.com/progserega/InspectionSheet
e57f648a3d46240c2dc2a531deb02d95c1c3026e
f8d353efcf6440f20e82d54b0332f28a788d16a8
refs/heads/master
2021-06-09T20:56:13.733000
2021-02-25T23:32:04
2021-02-25T23:32:04
140,659,378
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.drsk.progserega.inspectionsheet.services; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ru.drsk.progserega.inspectionsheet.entities.Equipment; import ru.drsk.progserega.inspectionsheet.entities.EquipmentType; import ru.drsk.progserega.inspectionsheet.entities.Line; import ru.drsk.progserega.inspectionsheet.entities.Substation; import ru.drsk.progserega.inspectionsheet.entities.TransformerSubstation; import ru.drsk.progserega.inspectionsheet.storages.ILineStorage; import ru.drsk.progserega.inspectionsheet.storages.ISubstationStorage; import ru.drsk.progserega.inspectionsheet.storages.ITransformerSubstationStorage; public class EquipmentService { public static final String FILTER_TYPE = "type"; public static final String FILTER_VOLTAGE = "voltage"; public static final String FILTER_NAME = "name"; public static final String FILTER_POSITION = "position"; public static final String FILTER_POSITION_RADIUS = "radius"; public static final String FILTER_ENTERPRISE = "enterprise"; public static final String FILTER_AREA = "area"; private Map<String, Object> filters; // private LinesService linesService; private ILineStorage lineStorage; //private ILocation location; private ISubstationStorage substationStorage; private ITransformerSubstationStorage transformerSubstationStorage; public EquipmentService(ILineStorage lineStorage, ISubstationStorage substationStorage, ITransformerSubstationStorage transformerSubstationStorage) { this.lineStorage = lineStorage; //this.location = location; this.substationStorage = substationStorage; this.transformerSubstationStorage = transformerSubstationStorage; this.filters = new HashMap<>(); } public Map<String, Object> getFilters() { return filters; } public void addFilter(String filterName, Object value) { this.filters.put(filterName, value); } public void removeFilter(String filterName) { this.filters.remove(filterName); } public void clearFilters(){ this.filters.clear(); } private List<Equipment> linesToEquipment(List<Line> lines) { List<Equipment> equipments = new ArrayList<>(); for (Line line : lines) { equipments.add((Equipment) line); } return equipments; } private List<Equipment> substationsToEquipment(List<Substation> substations) { List<Equipment> equipments = new ArrayList<>(); for (Substation substation : substations) { equipments.add((Equipment) substation); } return equipments; } private List<Equipment> transformerSubstationsToEquipment(List<TransformerSubstation> substations) { List<Equipment> equipments = new ArrayList<>(); for (TransformerSubstation substation : substations) { equipments.add((Equipment) substation); } return equipments; } public List<Equipment> getEquipments() { List<Equipment> equipments = new ArrayList<>(); if (filters.get(EquipmentService.FILTER_TYPE) == null) { //тип должен быть задан всегда return equipments; } if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.LINE) { List<Line> lines = lineStorage.getByFilters(this.filters); return linesToEquipment(lines); } else if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.SUBSTATION) { List<Substation> substations = substationStorage.getByFilters(this.filters); return substationsToEquipment(substations); } else if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.TP) { List<TransformerSubstation> substations = transformerSubstationStorage.getByFilters(this.filters); return transformerSubstationsToEquipment(substations); } else { //NOT IMPLEMENTED } return equipments; } public Line getLineById (long lineId){ return lineStorage.getById(lineId); } public Substation getSubstationById(long substationId){ return substationStorage.getById(substationId); } public TransformerSubstation getTransformerSubstationById(long id){ return transformerSubstationStorage.getById(id); } }
UTF-8
Java
4,539
java
EquipmentService.java
Java
[]
null
[]
package ru.drsk.progserega.inspectionsheet.services; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ru.drsk.progserega.inspectionsheet.entities.Equipment; import ru.drsk.progserega.inspectionsheet.entities.EquipmentType; import ru.drsk.progserega.inspectionsheet.entities.Line; import ru.drsk.progserega.inspectionsheet.entities.Substation; import ru.drsk.progserega.inspectionsheet.entities.TransformerSubstation; import ru.drsk.progserega.inspectionsheet.storages.ILineStorage; import ru.drsk.progserega.inspectionsheet.storages.ISubstationStorage; import ru.drsk.progserega.inspectionsheet.storages.ITransformerSubstationStorage; public class EquipmentService { public static final String FILTER_TYPE = "type"; public static final String FILTER_VOLTAGE = "voltage"; public static final String FILTER_NAME = "name"; public static final String FILTER_POSITION = "position"; public static final String FILTER_POSITION_RADIUS = "radius"; public static final String FILTER_ENTERPRISE = "enterprise"; public static final String FILTER_AREA = "area"; private Map<String, Object> filters; // private LinesService linesService; private ILineStorage lineStorage; //private ILocation location; private ISubstationStorage substationStorage; private ITransformerSubstationStorage transformerSubstationStorage; public EquipmentService(ILineStorage lineStorage, ISubstationStorage substationStorage, ITransformerSubstationStorage transformerSubstationStorage) { this.lineStorage = lineStorage; //this.location = location; this.substationStorage = substationStorage; this.transformerSubstationStorage = transformerSubstationStorage; this.filters = new HashMap<>(); } public Map<String, Object> getFilters() { return filters; } public void addFilter(String filterName, Object value) { this.filters.put(filterName, value); } public void removeFilter(String filterName) { this.filters.remove(filterName); } public void clearFilters(){ this.filters.clear(); } private List<Equipment> linesToEquipment(List<Line> lines) { List<Equipment> equipments = new ArrayList<>(); for (Line line : lines) { equipments.add((Equipment) line); } return equipments; } private List<Equipment> substationsToEquipment(List<Substation> substations) { List<Equipment> equipments = new ArrayList<>(); for (Substation substation : substations) { equipments.add((Equipment) substation); } return equipments; } private List<Equipment> transformerSubstationsToEquipment(List<TransformerSubstation> substations) { List<Equipment> equipments = new ArrayList<>(); for (TransformerSubstation substation : substations) { equipments.add((Equipment) substation); } return equipments; } public List<Equipment> getEquipments() { List<Equipment> equipments = new ArrayList<>(); if (filters.get(EquipmentService.FILTER_TYPE) == null) { //тип должен быть задан всегда return equipments; } if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.LINE) { List<Line> lines = lineStorage.getByFilters(this.filters); return linesToEquipment(lines); } else if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.SUBSTATION) { List<Substation> substations = substationStorage.getByFilters(this.filters); return substationsToEquipment(substations); } else if ((EquipmentType) filters.get(EquipmentService.FILTER_TYPE) == EquipmentType.TP) { List<TransformerSubstation> substations = transformerSubstationStorage.getByFilters(this.filters); return transformerSubstationsToEquipment(substations); } else { //NOT IMPLEMENTED } return equipments; } public Line getLineById (long lineId){ return lineStorage.getById(lineId); } public Substation getSubstationById(long substationId){ return substationStorage.getById(substationId); } public TransformerSubstation getTransformerSubstationById(long id){ return transformerSubstationStorage.getById(id); } }
4,539
0.704762
0.704762
132
33.204544
30.875788
153
false
false
0
0
0
0
0
0
0.469697
false
false
13
f9e52d5066dfdb34b12b1ccc9a54d33482d1569d
12,446,815,289,712
5ed504d34c147fd127b5336c99242365da3df86b
/src/com/salescrm/UpdateReminderTimeAPI.java
b4da42e65821b3d2e0134dbff0b3cab56b0623d5
[]
no_license
Arasu378/SalesCrmApi
https://github.com/Arasu378/SalesCrmApi
232212a652c7176993b877072500b62f7a9ab121
9b05db749909e7158560d597cfe1041921e1d4a0
refs/heads/master
2021-08-23T20:24:56.605000
2017-12-06T11:36:56
2017-12-06T11:36:56
102,078,944
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.salescrm; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import consumeclass.UpdateReminderTimeClass; import model.ReminderTimeModel; import response.ReminderTimeResponse; @Path("/updateReminderTime") public class UpdateReminderTimeAPI { @PUT @Secured @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ReminderTimeResponse updateData(ReminderTimeModel model){ return UpdateReminderTimeClass.updateReminderTime(model); } }
UTF-8
Java
589
java
UpdateReminderTimeAPI.java
Java
[]
null
[]
package com.salescrm; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import consumeclass.UpdateReminderTimeClass; import model.ReminderTimeModel; import response.ReminderTimeResponse; @Path("/updateReminderTime") public class UpdateReminderTimeAPI { @PUT @Secured @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ReminderTimeResponse updateData(ReminderTimeModel model){ return UpdateReminderTimeClass.updateReminderTime(model); } }
589
0.797963
0.797963
22
24.772728
18.493074
65
false
false
0
0
0
0
0
0
0.5
false
false
13
67e57f0bc1e0bdaef29a8a45812f9559f8dcfb74
30,571,577,215,360
40fb136cdfff8179abfb414c2715aeb8c4c903db
/getApetFx-project/src/main/java/at/htl/getAPet/model/likes/LikesRepository.java
ede3f4d8c8c1cc74d17e16c709dfba580943582f
[]
no_license
maximiliansteiger/getApet
https://github.com/maximiliansteiger/getApet
c54031ec3119600767c3b8a8fff5ce7a01e1ccfa
b7b2a2946bca3a5eb17335f7c4c25769304d8143
refs/heads/main
2023-06-05T20:13:50.241000
2021-06-24T07:36:45
2021-06-24T07:36:45
348,259,996
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.htl.getAPet.model.likes; import at.htl.getAPet.model.Animal.Animal; import at.htl.getAPet.model.User.User; import java.util.List; public interface LikesRepository { void insertInformation(User user, Animal animal); List<Integer> getLikesPerUser(User user); }
UTF-8
Java
282
java
LikesRepository.java
Java
[]
null
[]
package at.htl.getAPet.model.likes; import at.htl.getAPet.model.Animal.Animal; import at.htl.getAPet.model.User.User; import java.util.List; public interface LikesRepository { void insertInformation(User user, Animal animal); List<Integer> getLikesPerUser(User user); }
282
0.77305
0.77305
12
22.5
20.068632
53
false
false
0
0
0
0
0
0
0.583333
false
false
13
d024fd9b6b8a66be2fc836ab883da3515ecacc1c
19,877,108,648,624
eda1d495b15f2df896f4f81cbb0e4f1ab7c6f1a3
/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/state/ProcessingStateTest.java
02cbe491503d32adfd2dba3e45c4ddac30919a05
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
onap/policy-drools-pdp
https://github.com/onap/policy-drools-pdp
60d5b857b721d654f67b8f0db8b20bfd54db65e3
d6f6ebc925506cdf18b903df2cd3cbcef311082d
refs/heads/master
2023-09-04T11:11:09.123000
2023-08-28T16:32:18
2023-08-28T16:32:18
115,063,777
5
0
NOASSERTION
false
2021-06-29T19:07:00
2017-12-22T01:39:51
2021-06-28T14:45:34
2021-06-29T19:07:00
11,187
4
0
1
Java
false
false
/* * ============LICENSE_START======================================================= * ONAP * ================================================================================ * Copyright (C) 2018, 2020-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. * ============LICENSE_END========================================================= */ package org.onap.policy.drools.pooling.state; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.onap.policy.drools.pooling.message.BucketAssignments; import org.onap.policy.drools.pooling.message.Identification; import org.onap.policy.drools.pooling.message.Leader; import org.onap.policy.drools.pooling.message.Message; import org.onap.policy.drools.pooling.message.Query; import org.onap.policy.drools.pooling.state.ProcessingState.HostBucket; public class ProcessingStateTest extends SupportBasicStateTester { private ProcessingState state; private HostBucket hostBucket; /** * Setup. */ @Before public void setUp() throws Exception { super.setUp(); state = new ProcessingState(mgr, MY_HOST); hostBucket = new HostBucket(MY_HOST); } @Test public void testProcessQuery() { State next = mock(State.class); when(mgr.goQuery()).thenReturn(next); assertEquals(next, state.process(new Query())); Identification ident = captureAdminMessage(Identification.class); assertEquals(MY_HOST, ident.getSource()); assertEquals(ASGN3, ident.getAssignments()); } @Test public void testProcessingState() { /* * Null assignments should be OK. */ when(mgr.getAssignments()).thenReturn(null); state = new ProcessingState(mgr, LEADER); /* * Empty assignments should be OK. */ when(mgr.getAssignments()).thenReturn(EMPTY_ASGN); state = new ProcessingState(mgr, LEADER); assertEquals(MY_HOST, state.getHost()); assertEquals(LEADER, state.getLeader()); assertEquals(EMPTY_ASGN, state.getAssignments()); /* * Now try something with assignments. */ when(mgr.getAssignments()).thenReturn(ASGN3); state = new ProcessingState(mgr, LEADER); /* * Prove the state is attached to the manager by invoking getHost(), which * delegates to the manager. */ assertEquals(MY_HOST, state.getHost()); assertEquals(LEADER, state.getLeader()); assertEquals(ASGN3, state.getAssignments()); } @Test(expected = IllegalArgumentException.class) public void testProcessingState_NullLeader() { when(mgr.getAssignments()).thenReturn(EMPTY_ASGN); state = new ProcessingState(mgr, null); } @Test(expected = IllegalArgumentException.class) public void testProcessingState_ZeroLengthHostArray() { when(mgr.getAssignments()).thenReturn(new BucketAssignments(new String[] {})); state = new ProcessingState(mgr, LEADER); } @Test public void testGetAssignments() { // assignments from constructor assertEquals(ASGN3, state.getAssignments()); // null assignments - no effect state.setAssignments(null); assertEquals(ASGN3, state.getAssignments()); // empty assignments state.setAssignments(EMPTY_ASGN); assertEquals(EMPTY_ASGN, state.getAssignments()); // non-empty assignments state.setAssignments(ASGN3); assertEquals(ASGN3, state.getAssignments()); } @Test public void testSetAssignments() { state.setAssignments(null); verify(mgr, never()).startDistributing(any()); state.setAssignments(ASGN3); verify(mgr).startDistributing(ASGN3); } @Test public void testGetLeader() { // check value from constructor assertEquals(MY_HOST, state.getLeader()); state.setLeader(HOST2); assertEquals(HOST2, state.getLeader()); state.setLeader(HOST3); assertEquals(HOST3, state.getLeader()); } @Test public void testSetLeader() { state.setLeader(MY_HOST); assertEquals(MY_HOST, state.getLeader()); } @Test(expected = NullPointerException.class) public void testSetLeader_Null() { state.setLeader(null); } @Test public void testIsLeader() { state.setLeader(MY_HOST); assertTrue(state.isLeader()); state.setLeader(HOST2); assertFalse(state.isLeader()); } @Test public void testBecomeLeader() { State next = mock(State.class); when(mgr.goActive()).thenReturn(next); assertEquals(next, state.becomeLeader(sortHosts(MY_HOST, HOST2))); Leader msg = captureAdminMessage(Leader.class); verify(mgr).startDistributing(msg.getAssignments()); verify(mgr).goActive(); } @Test(expected = IllegalArgumentException.class) public void testBecomeLeader_NotFirstAlive() { // alive list contains something before my host name state.becomeLeader(sortHosts(PREV_HOST, MY_HOST)); } @Test public void testMakeLeader() throws Exception { state.becomeLeader(sortHosts(MY_HOST, HOST2)); Leader msg = captureAdminMessage(Leader.class); // need a channel before invoking checkValidity() msg.setChannel(Message.ADMIN); msg.checkValidity(); assertEquals(MY_HOST, msg.getSource()); assertNotNull(msg.getAssignments()); assertTrue(msg.getAssignments().hasAssignment(MY_HOST)); assertTrue(msg.getAssignments().hasAssignment(HOST2)); // this one wasn't in the list of hosts, so it should have been removed assertFalse(msg.getAssignments().hasAssignment(HOST1)); } @Test public void testMakeAssignments() throws Exception { state.becomeLeader(sortHosts(MY_HOST, HOST2)); captureAssignments().checkValidity(); } @Test public void testMakeBucketArray_NullAssignments() { when(mgr.getAssignments()).thenReturn(null); state = new ProcessingState(mgr, MY_HOST); state.becomeLeader(sortHosts(MY_HOST)); String[] arr = captureHostArray(); assertEquals(BucketAssignments.MAX_BUCKETS, arr.length); assertTrue(Arrays.asList(arr).stream().allMatch(host -> MY_HOST.equals(host))); } @Test public void testMakeBucketArray_ZeroAssignments() { // bucket assignment with a zero-length array state.setAssignments(new BucketAssignments(new String[0])); state.becomeLeader(sortHosts(MY_HOST)); String[] arr = captureHostArray(); assertEquals(BucketAssignments.MAX_BUCKETS, arr.length); assertTrue(Arrays.asList(arr).stream().allMatch(host -> MY_HOST.equals(host))); } @Test public void testMakeBucketArray() { /* * All hosts are still alive, so it should have the exact same assignments as it * had to start. */ state.setAssignments(ASGN3); state.becomeLeader(sortHosts(HOST_ARR3)); String[] arr = captureHostArray(); assertNotSame(HOST_ARR3, arr); assertEquals(Arrays.asList(HOST_ARR3), Arrays.asList(arr)); } @Test public void testRemoveExcessHosts() { /* * All hosts are still alive, plus some others. */ state.setAssignments(ASGN3); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2, HOST3, HOST4)); // assignments should be unchanged assertEquals(Arrays.asList(HOST_ARR3), captureHostList()); } @Test public void testAddIndicesToHostBuckets() { // some are null, some hosts are no longer alive String[] asgn = {null, MY_HOST, HOST3, null, HOST4, HOST1, HOST2}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2)); // every bucket should be assigned to one of the three hosts String[] expected = {MY_HOST, MY_HOST, HOST1, HOST2, MY_HOST, HOST1, HOST2}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testAssignNullBuckets() { /* * Ensure buckets are assigned to the host with the fewest buckets. */ String[] asgn = {MY_HOST, HOST1, MY_HOST, null, null, null, null, null, MY_HOST}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2)); String[] expected = {MY_HOST, HOST1, MY_HOST, HOST2, HOST1, HOST2, HOST1, HOST2, MY_HOST}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testRebalanceBuckets() { /* * Some are very lopsided. */ String[] asgn = {MY_HOST, HOST1, MY_HOST, MY_HOST, MY_HOST, MY_HOST, HOST1, HOST2, HOST1, HOST3}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2, HOST3)); String[] expected = {HOST2, HOST1, HOST3, MY_HOST, MY_HOST, MY_HOST, HOST1, HOST2, HOST1, HOST3}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testHostBucketRemove_testHostBucketAdd_testHostBucketSize() { assertEquals(0, hostBucket.size()); hostBucket.add(20); hostBucket.add(30); hostBucket.add(40); assertEquals(3, hostBucket.size()); assertEquals(20, hostBucket.remove().intValue()); assertEquals(30, hostBucket.remove().intValue()); assertEquals(1, hostBucket.size()); // add more before taking the last item hostBucket.add(50); hostBucket.add(60); assertEquals(3, hostBucket.size()); assertEquals(40, hostBucket.remove().intValue()); assertEquals(50, hostBucket.remove().intValue()); assertEquals(60, hostBucket.remove().intValue()); assertEquals(0, hostBucket.size()); // add more AFTER taking the last item hostBucket.add(70); assertEquals(70, hostBucket.remove().intValue()); assertEquals(0, hostBucket.size()); } @Test public void testHostBucketCompareTo() { HostBucket hb1 = new HostBucket(PREV_HOST); HostBucket hb2 = new HostBucket(MY_HOST); assertEquals(0, hb1.compareTo(hb1)); assertEquals(0, hb1.compareTo(new HostBucket(PREV_HOST))); // both empty assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); // hb1 has one bucket, so it should not be larger hb1.add(100); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // hb1 has two buckets, so it should still be larger hb1.add(200); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // hb1 has two buckets, hb2 has one, so hb1 should still be larger hb2.add(1000); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // same number of buckets, so hb2 should now be larger hb2.add(2000); assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); // hb2 has more buckets, it should still be larger hb2.add(3000); assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); } @Test(expected = UnsupportedOperationException.class) public void testHostBucketHashCode() { hostBucket.hashCode(); } @Test(expected = UnsupportedOperationException.class) public void testHostBucketEquals() { hostBucket.equals(hostBucket); } }
UTF-8
Java
12,892
java
ProcessingStateTest.java
Java
[]
null
[]
/* * ============LICENSE_START======================================================= * ONAP * ================================================================================ * Copyright (C) 2018, 2020-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. * ============LICENSE_END========================================================= */ package org.onap.policy.drools.pooling.state; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.onap.policy.drools.pooling.message.BucketAssignments; import org.onap.policy.drools.pooling.message.Identification; import org.onap.policy.drools.pooling.message.Leader; import org.onap.policy.drools.pooling.message.Message; import org.onap.policy.drools.pooling.message.Query; import org.onap.policy.drools.pooling.state.ProcessingState.HostBucket; public class ProcessingStateTest extends SupportBasicStateTester { private ProcessingState state; private HostBucket hostBucket; /** * Setup. */ @Before public void setUp() throws Exception { super.setUp(); state = new ProcessingState(mgr, MY_HOST); hostBucket = new HostBucket(MY_HOST); } @Test public void testProcessQuery() { State next = mock(State.class); when(mgr.goQuery()).thenReturn(next); assertEquals(next, state.process(new Query())); Identification ident = captureAdminMessage(Identification.class); assertEquals(MY_HOST, ident.getSource()); assertEquals(ASGN3, ident.getAssignments()); } @Test public void testProcessingState() { /* * Null assignments should be OK. */ when(mgr.getAssignments()).thenReturn(null); state = new ProcessingState(mgr, LEADER); /* * Empty assignments should be OK. */ when(mgr.getAssignments()).thenReturn(EMPTY_ASGN); state = new ProcessingState(mgr, LEADER); assertEquals(MY_HOST, state.getHost()); assertEquals(LEADER, state.getLeader()); assertEquals(EMPTY_ASGN, state.getAssignments()); /* * Now try something with assignments. */ when(mgr.getAssignments()).thenReturn(ASGN3); state = new ProcessingState(mgr, LEADER); /* * Prove the state is attached to the manager by invoking getHost(), which * delegates to the manager. */ assertEquals(MY_HOST, state.getHost()); assertEquals(LEADER, state.getLeader()); assertEquals(ASGN3, state.getAssignments()); } @Test(expected = IllegalArgumentException.class) public void testProcessingState_NullLeader() { when(mgr.getAssignments()).thenReturn(EMPTY_ASGN); state = new ProcessingState(mgr, null); } @Test(expected = IllegalArgumentException.class) public void testProcessingState_ZeroLengthHostArray() { when(mgr.getAssignments()).thenReturn(new BucketAssignments(new String[] {})); state = new ProcessingState(mgr, LEADER); } @Test public void testGetAssignments() { // assignments from constructor assertEquals(ASGN3, state.getAssignments()); // null assignments - no effect state.setAssignments(null); assertEquals(ASGN3, state.getAssignments()); // empty assignments state.setAssignments(EMPTY_ASGN); assertEquals(EMPTY_ASGN, state.getAssignments()); // non-empty assignments state.setAssignments(ASGN3); assertEquals(ASGN3, state.getAssignments()); } @Test public void testSetAssignments() { state.setAssignments(null); verify(mgr, never()).startDistributing(any()); state.setAssignments(ASGN3); verify(mgr).startDistributing(ASGN3); } @Test public void testGetLeader() { // check value from constructor assertEquals(MY_HOST, state.getLeader()); state.setLeader(HOST2); assertEquals(HOST2, state.getLeader()); state.setLeader(HOST3); assertEquals(HOST3, state.getLeader()); } @Test public void testSetLeader() { state.setLeader(MY_HOST); assertEquals(MY_HOST, state.getLeader()); } @Test(expected = NullPointerException.class) public void testSetLeader_Null() { state.setLeader(null); } @Test public void testIsLeader() { state.setLeader(MY_HOST); assertTrue(state.isLeader()); state.setLeader(HOST2); assertFalse(state.isLeader()); } @Test public void testBecomeLeader() { State next = mock(State.class); when(mgr.goActive()).thenReturn(next); assertEquals(next, state.becomeLeader(sortHosts(MY_HOST, HOST2))); Leader msg = captureAdminMessage(Leader.class); verify(mgr).startDistributing(msg.getAssignments()); verify(mgr).goActive(); } @Test(expected = IllegalArgumentException.class) public void testBecomeLeader_NotFirstAlive() { // alive list contains something before my host name state.becomeLeader(sortHosts(PREV_HOST, MY_HOST)); } @Test public void testMakeLeader() throws Exception { state.becomeLeader(sortHosts(MY_HOST, HOST2)); Leader msg = captureAdminMessage(Leader.class); // need a channel before invoking checkValidity() msg.setChannel(Message.ADMIN); msg.checkValidity(); assertEquals(MY_HOST, msg.getSource()); assertNotNull(msg.getAssignments()); assertTrue(msg.getAssignments().hasAssignment(MY_HOST)); assertTrue(msg.getAssignments().hasAssignment(HOST2)); // this one wasn't in the list of hosts, so it should have been removed assertFalse(msg.getAssignments().hasAssignment(HOST1)); } @Test public void testMakeAssignments() throws Exception { state.becomeLeader(sortHosts(MY_HOST, HOST2)); captureAssignments().checkValidity(); } @Test public void testMakeBucketArray_NullAssignments() { when(mgr.getAssignments()).thenReturn(null); state = new ProcessingState(mgr, MY_HOST); state.becomeLeader(sortHosts(MY_HOST)); String[] arr = captureHostArray(); assertEquals(BucketAssignments.MAX_BUCKETS, arr.length); assertTrue(Arrays.asList(arr).stream().allMatch(host -> MY_HOST.equals(host))); } @Test public void testMakeBucketArray_ZeroAssignments() { // bucket assignment with a zero-length array state.setAssignments(new BucketAssignments(new String[0])); state.becomeLeader(sortHosts(MY_HOST)); String[] arr = captureHostArray(); assertEquals(BucketAssignments.MAX_BUCKETS, arr.length); assertTrue(Arrays.asList(arr).stream().allMatch(host -> MY_HOST.equals(host))); } @Test public void testMakeBucketArray() { /* * All hosts are still alive, so it should have the exact same assignments as it * had to start. */ state.setAssignments(ASGN3); state.becomeLeader(sortHosts(HOST_ARR3)); String[] arr = captureHostArray(); assertNotSame(HOST_ARR3, arr); assertEquals(Arrays.asList(HOST_ARR3), Arrays.asList(arr)); } @Test public void testRemoveExcessHosts() { /* * All hosts are still alive, plus some others. */ state.setAssignments(ASGN3); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2, HOST3, HOST4)); // assignments should be unchanged assertEquals(Arrays.asList(HOST_ARR3), captureHostList()); } @Test public void testAddIndicesToHostBuckets() { // some are null, some hosts are no longer alive String[] asgn = {null, MY_HOST, HOST3, null, HOST4, HOST1, HOST2}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2)); // every bucket should be assigned to one of the three hosts String[] expected = {MY_HOST, MY_HOST, HOST1, HOST2, MY_HOST, HOST1, HOST2}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testAssignNullBuckets() { /* * Ensure buckets are assigned to the host with the fewest buckets. */ String[] asgn = {MY_HOST, HOST1, MY_HOST, null, null, null, null, null, MY_HOST}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2)); String[] expected = {MY_HOST, HOST1, MY_HOST, HOST2, HOST1, HOST2, HOST1, HOST2, MY_HOST}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testRebalanceBuckets() { /* * Some are very lopsided. */ String[] asgn = {MY_HOST, HOST1, MY_HOST, MY_HOST, MY_HOST, MY_HOST, HOST1, HOST2, HOST1, HOST3}; state.setAssignments(new BucketAssignments(asgn)); state.becomeLeader(sortHosts(MY_HOST, HOST1, HOST2, HOST3)); String[] expected = {HOST2, HOST1, HOST3, MY_HOST, MY_HOST, MY_HOST, HOST1, HOST2, HOST1, HOST3}; assertEquals(Arrays.asList(expected), captureHostList()); } @Test public void testHostBucketRemove_testHostBucketAdd_testHostBucketSize() { assertEquals(0, hostBucket.size()); hostBucket.add(20); hostBucket.add(30); hostBucket.add(40); assertEquals(3, hostBucket.size()); assertEquals(20, hostBucket.remove().intValue()); assertEquals(30, hostBucket.remove().intValue()); assertEquals(1, hostBucket.size()); // add more before taking the last item hostBucket.add(50); hostBucket.add(60); assertEquals(3, hostBucket.size()); assertEquals(40, hostBucket.remove().intValue()); assertEquals(50, hostBucket.remove().intValue()); assertEquals(60, hostBucket.remove().intValue()); assertEquals(0, hostBucket.size()); // add more AFTER taking the last item hostBucket.add(70); assertEquals(70, hostBucket.remove().intValue()); assertEquals(0, hostBucket.size()); } @Test public void testHostBucketCompareTo() { HostBucket hb1 = new HostBucket(PREV_HOST); HostBucket hb2 = new HostBucket(MY_HOST); assertEquals(0, hb1.compareTo(hb1)); assertEquals(0, hb1.compareTo(new HostBucket(PREV_HOST))); // both empty assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); // hb1 has one bucket, so it should not be larger hb1.add(100); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // hb1 has two buckets, so it should still be larger hb1.add(200); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // hb1 has two buckets, hb2 has one, so hb1 should still be larger hb2.add(1000); assertTrue(hb1.compareTo(hb2) > 0); assertTrue(hb2.compareTo(hb1) < 0); // same number of buckets, so hb2 should now be larger hb2.add(2000); assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); // hb2 has more buckets, it should still be larger hb2.add(3000); assertTrue(hb1.compareTo(hb2) < 0); assertTrue(hb2.compareTo(hb1) > 0); } @Test(expected = UnsupportedOperationException.class) public void testHostBucketHashCode() { hostBucket.hashCode(); } @Test(expected = UnsupportedOperationException.class) public void testHostBucketEquals() { hostBucket.equals(hostBucket); } }
12,892
0.635278
0.621083
393
31.804071
25.99794
105
false
false
0
0
0
0
81
0.012566
0.737913
false
false
13
9081fa569d46b9a75a6832b73daed47054b18042
19,275,813,293,095
e89c452bd0733813991d29e0af56bbb63caf93b2
/OOPS-1/Polynomial class.java
f017f965310d73c6f04deda7562e41c11dbcfe1c
[]
no_license
aparnakochar/Coding-Ninja-Data-Structure
https://github.com/aparnakochar/Coding-Ninja-Data-Structure
5f8d9fd8cfe56eda61cf5b4740bfedd431e2df9f
7018987a1acafcebb2c69584ffc56a437bc5b112
refs/heads/main
2023-05-11T21:48:59.584000
2021-06-07T05:13:26
2021-06-07T05:13:26
342,847,701
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Signature of four required functions is given in the code. You can create other functions as well if you need. * Also you should submit your code even if you are not done with all the functions. */ // Main used internally is shown here just for your reference. /*public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int degree1[] = new int[n]; for(int i = 0; i < n; i++){ degree1[i] = s.nextInt(); } int coeff1[] = new int[n]; for(int i = 0; i < n; i++){ coeff1[i] = s.nextInt(); } Polynomial first = new Polynomial(); for(int i = 0; i < n; i++){ first.setCoefficient(degree1[i],coeff1[i]); } n = s.nextInt(); int degree2[] = new int[n]; for(int i = 0; i < n; i++){ degree2[i] = s.nextInt(); } int coeff2[] = new int[n]; for(int i = 0; i < n; i++){ coeff2[i] = s.nextInt(); } Polynomial second = new Polynomial(); for(int i = 0; i < n; i++){ second.setCoefficient(degree2[i],coeff2[i]); } int choice = s.nextInt(); Polynomial result; switch(choice){ // Add case 1: result = first.add(second); result.print(); break; // Subtract case 2 : result = first.subtract(second); result.print(); break; // Multiply case 3 : result = first.multiply(second); result.print(); break; } } */ public class Polynomial { int degCoeff[]; Polynomial(){ degCoeff=new int[10]; } /* This function sets coefficient for a particular degree value, if degree is not there in the polynomial * then corresponding term(with specified degree and value is added int the polynomial. If the degree * is already present in the polynomial then previous coefficient is replaced by * new coefficient value passed as function argument */ public void setCoefficient(int degree, int coeff){ if(degree>degCoeff.length-1){ int temp[]=degCoeff; degCoeff=new int[degree+1]; for(int i=0;i<temp.length;i++) degCoeff[i]=temp[i]; } degCoeff[degree]=coeff; } // Prints all the terms(only terms with non zero coefficients are to be printed) in increasing order of degree. public void print(){ for(int i=0;i<degCoeff.length;i++){ if(degCoeff[i]!=0){ System.out.print(degCoeff[i]+"x"+i+" "); } } } // Adds two polynomials and returns a new polynomial which has result public Polynomial add(Polynomial p){ Polynomial ans=new Polynomial(); int plen1=this.degCoeff.length; int plen2=p.degCoeff.length; int len=Math.min(plen1,plen2); int i; for(i=0;i<len;i++){ ans.setCoefficient(i,this.degCoeff[i]+p.degCoeff[i]); } while(i<plen1){ ans.setCoefficient(i,this.degCoeff[i]); i++; } while(i<plen2){ ans.setCoefficient(i,p.degCoeff[i]); i++; } return ans; } // Subtracts two polynomials and returns a new polynomial which has result public Polynomial subtract(Polynomial p){ Polynomial ans=new Polynomial(); int plen1=this.degCoeff.length; int plen2=p.degCoeff.length; int len=Math.min(plen1,plen2); int i; for(i=0;i<len;i++){ ans.setCoefficient(i,this.degCoeff[i]-p.degCoeff[i]); } while(i<plen1){ ans.setCoefficient(i,this.degCoeff[i]); i++; } while(i<plen2){ ans.setCoefficient(i,-p.degCoeff[i]); i++; } return ans; } public int getCoeff(int degree){ if(degree<this.degCoeff.length){ return degCoeff[degree]; } else return 0; } // Multiply two polynomials and returns a new polynomial which has result public Polynomial multiply(Polynomial p){ Polynomial ans=new Polynomial(); for(int i=0;i<this.degCoeff.length;i++){ for(int j=0;j<p.degCoeff.length;j++){ int termDeg=i+j; int termCoeff=this.degCoeff[i]*p.degCoeff[j]; int oldCoeff=ans.getCoeff(termDeg); ans.setCoefficient(termDeg,termCoeff+oldCoeff); } } return ans; } }
UTF-8
Java
4,357
java
Polynomial class.java
Java
[]
null
[]
/* Signature of four required functions is given in the code. You can create other functions as well if you need. * Also you should submit your code even if you are not done with all the functions. */ // Main used internally is shown here just for your reference. /*public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int degree1[] = new int[n]; for(int i = 0; i < n; i++){ degree1[i] = s.nextInt(); } int coeff1[] = new int[n]; for(int i = 0; i < n; i++){ coeff1[i] = s.nextInt(); } Polynomial first = new Polynomial(); for(int i = 0; i < n; i++){ first.setCoefficient(degree1[i],coeff1[i]); } n = s.nextInt(); int degree2[] = new int[n]; for(int i = 0; i < n; i++){ degree2[i] = s.nextInt(); } int coeff2[] = new int[n]; for(int i = 0; i < n; i++){ coeff2[i] = s.nextInt(); } Polynomial second = new Polynomial(); for(int i = 0; i < n; i++){ second.setCoefficient(degree2[i],coeff2[i]); } int choice = s.nextInt(); Polynomial result; switch(choice){ // Add case 1: result = first.add(second); result.print(); break; // Subtract case 2 : result = first.subtract(second); result.print(); break; // Multiply case 3 : result = first.multiply(second); result.print(); break; } } */ public class Polynomial { int degCoeff[]; Polynomial(){ degCoeff=new int[10]; } /* This function sets coefficient for a particular degree value, if degree is not there in the polynomial * then corresponding term(with specified degree and value is added int the polynomial. If the degree * is already present in the polynomial then previous coefficient is replaced by * new coefficient value passed as function argument */ public void setCoefficient(int degree, int coeff){ if(degree>degCoeff.length-1){ int temp[]=degCoeff; degCoeff=new int[degree+1]; for(int i=0;i<temp.length;i++) degCoeff[i]=temp[i]; } degCoeff[degree]=coeff; } // Prints all the terms(only terms with non zero coefficients are to be printed) in increasing order of degree. public void print(){ for(int i=0;i<degCoeff.length;i++){ if(degCoeff[i]!=0){ System.out.print(degCoeff[i]+"x"+i+" "); } } } // Adds two polynomials and returns a new polynomial which has result public Polynomial add(Polynomial p){ Polynomial ans=new Polynomial(); int plen1=this.degCoeff.length; int plen2=p.degCoeff.length; int len=Math.min(plen1,plen2); int i; for(i=0;i<len;i++){ ans.setCoefficient(i,this.degCoeff[i]+p.degCoeff[i]); } while(i<plen1){ ans.setCoefficient(i,this.degCoeff[i]); i++; } while(i<plen2){ ans.setCoefficient(i,p.degCoeff[i]); i++; } return ans; } // Subtracts two polynomials and returns a new polynomial which has result public Polynomial subtract(Polynomial p){ Polynomial ans=new Polynomial(); int plen1=this.degCoeff.length; int plen2=p.degCoeff.length; int len=Math.min(plen1,plen2); int i; for(i=0;i<len;i++){ ans.setCoefficient(i,this.degCoeff[i]-p.degCoeff[i]); } while(i<plen1){ ans.setCoefficient(i,this.degCoeff[i]); i++; } while(i<plen2){ ans.setCoefficient(i,-p.degCoeff[i]); i++; } return ans; } public int getCoeff(int degree){ if(degree<this.degCoeff.length){ return degCoeff[degree]; } else return 0; } // Multiply two polynomials and returns a new polynomial which has result public Polynomial multiply(Polynomial p){ Polynomial ans=new Polynomial(); for(int i=0;i<this.degCoeff.length;i++){ for(int j=0;j<p.degCoeff.length;j++){ int termDeg=i+j; int termCoeff=this.degCoeff[i]*p.degCoeff[j]; int oldCoeff=ans.getCoeff(termDeg); ans.setCoefficient(termDeg,termCoeff+oldCoeff); } } return ans; } }
4,357
0.574478
0.56415
163
25.723927
23.424147
113
false
false
0
0
0
0
0
0
1.509202
false
false
13
8f372b6797501f6f91a58127ead78c2ce2a7f1d7
3,496,103,381,804
3577e92ac106da2fd504d18c6604e048b4b5aba7
/socialalert-app/src/test/java/com/bravson/socialalert/facades/ProfileFacadeTest.java
e1f9f5226e8f5848d54243fdc7e4cd9efdc6601b
[]
no_license
lgarin/socialalert-server
https://github.com/lgarin/socialalert-server
3591f10e38ae7499220cfd01f97a4d5bf70fd60f
9eceee2c8ba64fc5d70652a6ebc6952ccae1d722
refs/heads/master
2021-05-14T08:52:51.096000
2016-10-24T15:04:38
2016-10-24T15:04:38
116,310,789
0
0
null
false
2021-05-12T00:20:59
2018-01-04T21:45:40
2018-01-04T21:50:49
2021-05-12T00:20:59
16,063
0
0
12
JavaScript
false
false
package com.bravson.socialalert.facades; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.annotation.Resource; import javax.validation.ValidationException; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import com.bravson.socialalert.app.entities.AlertActivity; import com.bravson.socialalert.app.entities.AlertComment; import com.bravson.socialalert.app.entities.ApplicationUser; import com.bravson.socialalert.app.entities.ProfileLink; import com.bravson.socialalert.app.entities.ProfileStatistic; import com.bravson.socialalert.app.entities.UserProfile; import com.bravson.socialalert.app.exceptions.DataMissingException; import com.bravson.socialalert.common.domain.AbuseInfo; import com.bravson.socialalert.common.domain.AbuseReason; import com.bravson.socialalert.common.domain.AbuseStatus; import com.bravson.socialalert.common.domain.ActivityCount; import com.bravson.socialalert.common.domain.ActivityInfo; import com.bravson.socialalert.common.domain.ActivityType; import com.bravson.socialalert.common.domain.ProfileInfo; import com.bravson.socialalert.common.domain.ProfileStatisticInfo; import com.bravson.socialalert.common.domain.PublicProfileInfo; import com.bravson.socialalert.common.domain.QueryResult; import com.bravson.socialalert.common.domain.UserInfo; import com.bravson.socialalert.common.facade.ProfileFacade; import com.bravson.socialalert.common.facade.UserFacade; import com.bravson.socialalert.infrastructure.DataServiceTest; public class ProfileFacadeTest extends DataServiceTest { @Resource private ProfileFacade profileFacade; @Resource private UserFacade userFacade; @Before public void setUp() throws Exception { fullImport(ApplicationUser.class); fullImport(UserProfile.class); fullImport(ProfileStatistic.class); fullImport(AlertActivity.class); fullImport(ProfileLink.class); fullImport(AlertComment.class); SecurityContextHolder.clearContext(); } @Test(expected=AuthenticationCredentialsNotFoundException.class) public void getCurrentProfileWithoutLogin() throws IOException { profileFacade.getCurrentUserProfile(); } @Test public void getCurrentProfileWithActiveUser() throws IOException { userFacade.login("lucien@test.com", "123"); ProfileInfo info = profileFacade.getCurrentUserProfile(); assertNotNull(info); assertEquals("Garin", info.getLastname()); assertEquals("Lucien", info.getFirstname()); assertNull(info.getBirthdate()); assertNull(info.getImage()); } @Test(expected=AccessDeniedException.class) public void getCurrentProfileWithGuestUser() throws IOException { userFacade.login("unverified@test.com", "123"); profileFacade.getCurrentUserProfile(); } @Test(expected=AuthenticationCredentialsNotFoundException.class) public void updateProfileWithoutLogin() throws IOException { ProfileInfo info = new ProfileInfo(); profileFacade.updateProfile(info); } @Test public void updateProfileWithActiveUser() throws IOException { userFacade.login("lucien@test.com", "123"); ProfileInfo info1 = new ProfileInfo(); info1.setFirstname("Mister"); info1.setLastname("Mike"); ProfileInfo info2 = profileFacade.updateProfile(info1); assertNotNull(info2); assertEquals("Mister", info2.getFirstname()); assertEquals("Mike", info2.getLastname()); assertNull(info2.getBirthdate()); assertNull(info2.getImage()); } @Test(expected=ValidationException.class) public void updateProfileWithInvalidInput() throws IOException { userFacade.login("lucien@test.com", "123"); ProfileInfo info1 = new ProfileInfo(); info1.setFirstname("This is a very very long first name exceeding our upper limit"); profileFacade.updateProfile(info1); } @Test(expected=AccessDeniedException.class) public void updateProfileWithGuestUser() throws IOException { userFacade.login("unverified@test.com", "123"); ProfileInfo info = new ProfileInfo(); profileFacade.updateProfile(info); } @Test public void readExistingStatistic() throws IOException { userFacade.login("unverified@test.com", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); ProfileStatisticInfo info = profileFacade.getUserProfile(profileId); assertNotNull(info); assertEquals(1432, info.getHitCount()); assertEquals(42, info.getPictureCount()); assertEquals(67, info.getCommentCount()); assertEquals(560, info.getLikeCount()); assertEquals(10, info.getDislikeCount()); } @Test public void getProfileActivity() throws IOException { userFacade.login("unverified@test.com", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); QueryResult<ActivityInfo> result = profileFacade.getProfileActivity(profileId, 0, 10); assertNotNull(result); assertEquals(0, result.getPageNumber()); assertEquals(1, result.getPageCount()); List<ActivityInfo> list = result.getContent(); assertNotNull(list); assertEquals(3, list.size()); } @Test public void getNetworkedProfileActivity() throws IOException { userFacade.login("unverified@test.com", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); QueryResult<ActivityInfo> result = profileFacade.getNetworkedProfileActivity(profileId, 0, 10); assertNotNull(result); assertEquals(0, result.getPageNumber()); assertEquals(1, result.getPageCount()); List<ActivityInfo> list = result.getContent(); assertNotNull(list); assertEquals(4, list.size()); } // TODO add tests for claimProfilePicture @Test public void getFollowedProfiles() throws IOException { userFacade.login("lucien@test.com", "123"); QueryResult<PublicProfileInfo> result = profileFacade.getFollowedProfiles(0, 10); assertNotNull(result); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); PublicProfileInfo profile = result.getContent().get(0); assertEquals("test", profile.getNickname()); } @Test public void isFollowing() throws IOException { userFacade.login("lucien@test.com", "123"); assertNotNull(profileFacade.isFollowingSince(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test public void unfollow() throws IOException { userFacade.login("lucien@test.com", "123"); assertTrue(profileFacade.unfollow(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); assertNull(profileFacade.isFollowingSince(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test public void follow() throws IOException { userFacade.login("lucien@test.com", "123"); assertFalse(profileFacade.follow(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test(expected=DataMissingException.class) public void followNonExistingProfile() throws IOException { userFacade.login("lucien@test.com", "123"); profileFacade.follow(UUID.fromString("99d166ae-9b3f-4405-be0d-fa1567728593")); } @Test public void searchProfileWithNickname() throws IOException { userFacade.login("lucien@test.com", "123"); QueryResult<PublicProfileInfo> result = profileFacade.searchProfiles("sg33", 0, 10); assertNotNull(result); assertEquals(1, result.getPageCount()); assertEquals(0, result.getPageNumber()); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); PublicProfileInfo profile = result.getContent().get(0); assertNotNull(profile); assertEquals("sg33g5", profile.getNickname()); } @Test public void findNicknameSuggestion() throws IOException { userFacade.login("lucien@test.com", "123"); List<String> result = profileFacade.findNicknameSuggestions("sg33"); assertEquals(Arrays.asList("sg33g5"), result); } @Test public void getTopCreators() throws IOException { userFacade.login("lucien@test.com", "123"); QueryResult<ProfileStatisticInfo> result = profileFacade.getTopCreators(0, 100); assertNotNull(result); assertEquals(1, result.getPageCount()); assertEquals(0, result.getPageNumber()); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); } @Test public void getActivityStatistic() throws IOException { userFacade.login("lucien@test.com", "123"); List<ActivityCount> statistic = profileFacade.getRecentActivityStatistic(new DateTime(2000, 1, 1, 0, 0)); assertNotNull(statistic); assertEquals(1, statistic.size()); ActivityCount activity = statistic.get(0); assertEquals(1, activity.getCount()); assertEquals(ActivityType.LIKE_MEDIA, activity.getType()); } @Test public void createMediaReport() throws IOException { UserInfo user = userFacade.login("lucien@test.com", "123"); URI mediaUri = URI.create("20130716/f317f3c7918c83ff6ec24aabb6c017fd.jpg"); String country = "Switzerland"; AbuseInfo abuse = profileFacade.reportAbusiveMedia(mediaUri, country, AbuseReason.VIOLENCE); assertNotNull(abuse); assertEquals(user.getProfileId(), abuse.getProfileId()); assertEquals(mediaUri, abuse.getMediaUri()); assertNull(abuse.getCommentId()); assertEquals(AbuseReason.VIOLENCE, abuse.getReason()); assertEquals(AbuseStatus.NEW, abuse.getStatus()); assertEquals(country, abuse.getCountry()); assertNull(abuse.getMessage()); assertEquals(user.getNickname(), abuse.getCreator()); assertNotNull(abuse.getTimestamp()); } @Test(expected=DataMissingException.class) public void createReportForInvalidMedia() throws IOException { userFacade.login("lucien@test.com", "123"); URI mediaUri = URI.create("xyz.jpg"); String country = "Switzerland"; profileFacade.reportAbusiveMedia(mediaUri, country, AbuseReason.VIOLENCE); } @Test public void createCommentReport() throws IOException { UserInfo user = userFacade.login("lucien@test.com", "123"); UUID commentId = UUID.fromString("c95472c0-e0e6-11e2-a28f-0800200c9a33"); String country = "Switzerland"; AbuseInfo abuse = profileFacade.reportAbusiveComment(commentId, country, AbuseReason.VIOLENCE); assertNotNull(abuse); assertEquals(user.getProfileId(), abuse.getProfileId()); assertNull(abuse.getMediaUri()); assertEquals(commentId, abuse.getCommentId()); assertEquals(AbuseReason.VIOLENCE, abuse.getReason()); assertEquals(AbuseStatus.NEW, abuse.getStatus()); assertEquals(country, abuse.getCountry()); assertEquals("Hello 2", abuse.getMessage()); assertEquals(user.getNickname(), abuse.getCreator()); assertNotNull(abuse.getTimestamp()); } @Test(expected=DataMissingException.class) public void createReportForInvalidComment() throws IOException { userFacade.login("lucien@test.com", "123"); UUID commentId = UUID.fromString("c95472c0-e0e6-11e2-a28f-999999999999"); String country = "Switzerland"; profileFacade.reportAbusiveComment(commentId, country, AbuseReason.VIOLENCE); } }
UTF-8
Java
11,337
java
ProfileFacadeTest.java
Java
[ { "context": "eUser() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tProfileInfo info = profileFacade.get", "end": 2622, "score": 0.9999244213104248, "start": 2607, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "ofile();\r\n\t\tassertNotNull(info);\r\n\t\tassertEquals(\"Garin\", info.getLastname());\r\n\t\tassertEquals(\"Lucien\", ", "end": 2740, "score": 0.9997041821479797, "start": 2735, "tag": "NAME", "value": "Garin" }, { "context": "ls(\"Garin\", info.getLastname());\r\n\t\tassertEquals(\"Lucien\", info.getFirstname());\r\n\t\tassertNull(info.getBir", "end": 2787, "score": 0.9997931718826294, "start": 2781, "tag": "NAME", "value": "Lucien" }, { "context": "tUser() throws IOException {\r\n\t\tuserFacade.login(\"unverified@test.com\", \"123\");\r\n\t\tprofileFacade.getCurrentUserProfile(", "end": 3041, "score": 0.9999176859855652, "start": 3022, "tag": "EMAIL", "value": "unverified@test.com" }, { "context": "eUser() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tProfileInfo info1 = new ProfileInfo(", "end": 3426, "score": 0.9999273419380188, "start": 3411, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "info1 = new ProfileInfo();\r\n\t\tinfo1.setFirstname(\"Mister\");\r\n\t\tinfo1.setLastname(\"Mike\");\r\n\t\tProfileInfo i", "end": 3508, "score": 0.9997467994689941, "start": 3502, "tag": "NAME", "value": "Mister" }, { "context": "fo1.setFirstname(\"Mister\");\r\n\t\tinfo1.setLastname(\"Mike\");\r\n\t\tProfileInfo info2 = profileFacade.updatePro", "end": 3538, "score": 0.9998383522033691, "start": 3534, "tag": "NAME", "value": "Mike" }, { "context": "info1);\r\n\t\tassertNotNull(info2);\r\n\t\tassertEquals(\"Mister\", info2.getFirstname());\r\n\t\tassertEquals(\"Mike\", ", "end": 3649, "score": 0.9988317489624023, "start": 3643, "tag": "NAME", "value": "Mister" }, { "context": "\"Mister\", info2.getFirstname());\r\n\t\tassertEquals(\"Mike\", info2.getLastname());\r\n\t\tassertNull(info2.getBi", "end": 3696, "score": 0.9997878074645996, "start": 3692, "tag": "NAME", "value": "Mike" }, { "context": "Input() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tProfileInfo info1 = new ProfileInfo(", "end": 3945, "score": 0.9999265074729919, "start": 3930, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "tUser() throws IOException {\r\n\t\tuserFacade.login(\"unverified@test.com\", \"123\");\r\n\t\tProfileInfo info = new ProfileInfo()", "end": 4282, "score": 0.99992436170578, "start": 4263, "tag": "EMAIL", "value": "unverified@test.com" }, { "context": "istic() throws IOException {\r\n\t\tuserFacade.login(\"unverified@test.com\", \"123\");\r\n\t\tUUID profileId = UUID.fromString(\"a9", "end": 4485, "score": 0.9999154210090637, "start": 4466, "tag": "EMAIL", "value": "unverified@test.com" }, { "context": "ivity() throws IOException {\r\n\t\tuserFacade.login(\"unverified@test.com\", \"123\");\r\n\t\tUUID profileId = UUID.fromString(\"a9", "end": 5001, "score": 0.9999179840087891, "start": 4982, "tag": "EMAIL", "value": "unverified@test.com" }, { "context": "ivity() throws IOException {\r\n\t\tuserFacade.login(\"unverified@test.com\", \"123\");\r\n\t\tUUID profileId = UUID.fromString(\"a9", "end": 5519, "score": 0.9999223351478577, "start": 5500, "tag": "EMAIL", "value": "unverified@test.com" }, { "context": "files() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tQueryResult<PublicProfileInfo> resul", "end": 6082, "score": 0.9999223351478577, "start": 6067, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "owing() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tassertNotNull(profileFacade.isFollow", "end": 6500, "score": 0.9999229907989502, "start": 6485, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "llow() throws IOException {\r\n\t\t userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\t assertTrue(profileFacade.unfollow(U", "end": 6720, "score": 0.9999253749847412, "start": 6705, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "llow() throws IOException {\r\n\t\t userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\t assertFalse(profileFacade.follow(UU", "end": 7033, "score": 0.9999229311943054, "start": 7018, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "file() throws IOException {\r\n\t\t userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\t profileFacade.follow(UUID.fromStrin", "end": 7295, "score": 0.9999238848686218, "start": 7280, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "name() throws IOException {\r\n\t\t userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tQueryResult<PublicProfileInfo> resul", "end": 7507, "score": 0.9999229907989502, "start": 7492, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "stion() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tList<String> result = profileFacade.", "end": 8053, "score": 0.9999238848686218, "start": 8038, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "ators() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tQueryResult<ProfileStatisticInfo> re", "end": 8289, "score": 0.999924898147583, "start": 8274, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "istic() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tList<ActivityCount> statistic = prof", "end": 8695, "score": 0.9999204277992249, "start": 8680, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "OException {\r\n\t\tUserInfo user = userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tURI mediaUri = URI.create(\"20130716/", "end": 9153, "score": 0.9999223351478577, "start": 9138, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "Media() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tURI mediaUri = URI.create(\"xyz.jpg\")", "end": 9986, "score": 0.9999227523803711, "start": 9971, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "OException {\r\n\t\tUserInfo user = userFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tUUID commentId = UUID.fromString(\"c9", "end": 10275, "score": 0.9999223351478577, "start": 10260, "tag": "EMAIL", "value": "lucien@test.com" }, { "context": "mment() throws IOException {\r\n\t\tuserFacade.login(\"lucien@test.com\", \"123\");\r\n\t\tUUID commentId = UUID.fromString(\"c9", "end": 11125, "score": 0.999912440776825, "start": 11110, "tag": "EMAIL", "value": "lucien@test.com" } ]
null
[]
package com.bravson.socialalert.facades; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.annotation.Resource; import javax.validation.ValidationException; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import com.bravson.socialalert.app.entities.AlertActivity; import com.bravson.socialalert.app.entities.AlertComment; import com.bravson.socialalert.app.entities.ApplicationUser; import com.bravson.socialalert.app.entities.ProfileLink; import com.bravson.socialalert.app.entities.ProfileStatistic; import com.bravson.socialalert.app.entities.UserProfile; import com.bravson.socialalert.app.exceptions.DataMissingException; import com.bravson.socialalert.common.domain.AbuseInfo; import com.bravson.socialalert.common.domain.AbuseReason; import com.bravson.socialalert.common.domain.AbuseStatus; import com.bravson.socialalert.common.domain.ActivityCount; import com.bravson.socialalert.common.domain.ActivityInfo; import com.bravson.socialalert.common.domain.ActivityType; import com.bravson.socialalert.common.domain.ProfileInfo; import com.bravson.socialalert.common.domain.ProfileStatisticInfo; import com.bravson.socialalert.common.domain.PublicProfileInfo; import com.bravson.socialalert.common.domain.QueryResult; import com.bravson.socialalert.common.domain.UserInfo; import com.bravson.socialalert.common.facade.ProfileFacade; import com.bravson.socialalert.common.facade.UserFacade; import com.bravson.socialalert.infrastructure.DataServiceTest; public class ProfileFacadeTest extends DataServiceTest { @Resource private ProfileFacade profileFacade; @Resource private UserFacade userFacade; @Before public void setUp() throws Exception { fullImport(ApplicationUser.class); fullImport(UserProfile.class); fullImport(ProfileStatistic.class); fullImport(AlertActivity.class); fullImport(ProfileLink.class); fullImport(AlertComment.class); SecurityContextHolder.clearContext(); } @Test(expected=AuthenticationCredentialsNotFoundException.class) public void getCurrentProfileWithoutLogin() throws IOException { profileFacade.getCurrentUserProfile(); } @Test public void getCurrentProfileWithActiveUser() throws IOException { userFacade.login("<EMAIL>", "123"); ProfileInfo info = profileFacade.getCurrentUserProfile(); assertNotNull(info); assertEquals("Garin", info.getLastname()); assertEquals("Lucien", info.getFirstname()); assertNull(info.getBirthdate()); assertNull(info.getImage()); } @Test(expected=AccessDeniedException.class) public void getCurrentProfileWithGuestUser() throws IOException { userFacade.login("<EMAIL>", "123"); profileFacade.getCurrentUserProfile(); } @Test(expected=AuthenticationCredentialsNotFoundException.class) public void updateProfileWithoutLogin() throws IOException { ProfileInfo info = new ProfileInfo(); profileFacade.updateProfile(info); } @Test public void updateProfileWithActiveUser() throws IOException { userFacade.login("<EMAIL>", "123"); ProfileInfo info1 = new ProfileInfo(); info1.setFirstname("Mister"); info1.setLastname("Mike"); ProfileInfo info2 = profileFacade.updateProfile(info1); assertNotNull(info2); assertEquals("Mister", info2.getFirstname()); assertEquals("Mike", info2.getLastname()); assertNull(info2.getBirthdate()); assertNull(info2.getImage()); } @Test(expected=ValidationException.class) public void updateProfileWithInvalidInput() throws IOException { userFacade.login("<EMAIL>", "123"); ProfileInfo info1 = new ProfileInfo(); info1.setFirstname("This is a very very long first name exceeding our upper limit"); profileFacade.updateProfile(info1); } @Test(expected=AccessDeniedException.class) public void updateProfileWithGuestUser() throws IOException { userFacade.login("<EMAIL>", "123"); ProfileInfo info = new ProfileInfo(); profileFacade.updateProfile(info); } @Test public void readExistingStatistic() throws IOException { userFacade.login("<EMAIL>", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); ProfileStatisticInfo info = profileFacade.getUserProfile(profileId); assertNotNull(info); assertEquals(1432, info.getHitCount()); assertEquals(42, info.getPictureCount()); assertEquals(67, info.getCommentCount()); assertEquals(560, info.getLikeCount()); assertEquals(10, info.getDislikeCount()); } @Test public void getProfileActivity() throws IOException { userFacade.login("<EMAIL>", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); QueryResult<ActivityInfo> result = profileFacade.getProfileActivity(profileId, 0, 10); assertNotNull(result); assertEquals(0, result.getPageNumber()); assertEquals(1, result.getPageCount()); List<ActivityInfo> list = result.getContent(); assertNotNull(list); assertEquals(3, list.size()); } @Test public void getNetworkedProfileActivity() throws IOException { userFacade.login("<EMAIL>", "123"); UUID profileId = UUID.fromString("a95472c0-e0e6-11e2-a28f-0800200c9a77"); QueryResult<ActivityInfo> result = profileFacade.getNetworkedProfileActivity(profileId, 0, 10); assertNotNull(result); assertEquals(0, result.getPageNumber()); assertEquals(1, result.getPageCount()); List<ActivityInfo> list = result.getContent(); assertNotNull(list); assertEquals(4, list.size()); } // TODO add tests for claimProfilePicture @Test public void getFollowedProfiles() throws IOException { userFacade.login("<EMAIL>", "123"); QueryResult<PublicProfileInfo> result = profileFacade.getFollowedProfiles(0, 10); assertNotNull(result); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); PublicProfileInfo profile = result.getContent().get(0); assertEquals("test", profile.getNickname()); } @Test public void isFollowing() throws IOException { userFacade.login("<EMAIL>", "123"); assertNotNull(profileFacade.isFollowingSince(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test public void unfollow() throws IOException { userFacade.login("<EMAIL>", "123"); assertTrue(profileFacade.unfollow(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); assertNull(profileFacade.isFollowingSince(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test public void follow() throws IOException { userFacade.login("<EMAIL>", "123"); assertFalse(profileFacade.follow(UUID.fromString("e7d166ae-9b3f-4405-be0d-fa1567728593"))); } @Test(expected=DataMissingException.class) public void followNonExistingProfile() throws IOException { userFacade.login("<EMAIL>", "123"); profileFacade.follow(UUID.fromString("99d166ae-9b3f-4405-be0d-fa1567728593")); } @Test public void searchProfileWithNickname() throws IOException { userFacade.login("<EMAIL>", "123"); QueryResult<PublicProfileInfo> result = profileFacade.searchProfiles("sg33", 0, 10); assertNotNull(result); assertEquals(1, result.getPageCount()); assertEquals(0, result.getPageNumber()); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); PublicProfileInfo profile = result.getContent().get(0); assertNotNull(profile); assertEquals("sg33g5", profile.getNickname()); } @Test public void findNicknameSuggestion() throws IOException { userFacade.login("<EMAIL>", "123"); List<String> result = profileFacade.findNicknameSuggestions("sg33"); assertEquals(Arrays.asList("sg33g5"), result); } @Test public void getTopCreators() throws IOException { userFacade.login("<EMAIL>", "123"); QueryResult<ProfileStatisticInfo> result = profileFacade.getTopCreators(0, 100); assertNotNull(result); assertEquals(1, result.getPageCount()); assertEquals(0, result.getPageNumber()); assertNotNull(result.getContent()); assertEquals(1, result.getContent().size()); } @Test public void getActivityStatistic() throws IOException { userFacade.login("<EMAIL>", "123"); List<ActivityCount> statistic = profileFacade.getRecentActivityStatistic(new DateTime(2000, 1, 1, 0, 0)); assertNotNull(statistic); assertEquals(1, statistic.size()); ActivityCount activity = statistic.get(0); assertEquals(1, activity.getCount()); assertEquals(ActivityType.LIKE_MEDIA, activity.getType()); } @Test public void createMediaReport() throws IOException { UserInfo user = userFacade.login("<EMAIL>", "123"); URI mediaUri = URI.create("20130716/f317f3c7918c83ff6ec24aabb6c017fd.jpg"); String country = "Switzerland"; AbuseInfo abuse = profileFacade.reportAbusiveMedia(mediaUri, country, AbuseReason.VIOLENCE); assertNotNull(abuse); assertEquals(user.getProfileId(), abuse.getProfileId()); assertEquals(mediaUri, abuse.getMediaUri()); assertNull(abuse.getCommentId()); assertEquals(AbuseReason.VIOLENCE, abuse.getReason()); assertEquals(AbuseStatus.NEW, abuse.getStatus()); assertEquals(country, abuse.getCountry()); assertNull(abuse.getMessage()); assertEquals(user.getNickname(), abuse.getCreator()); assertNotNull(abuse.getTimestamp()); } @Test(expected=DataMissingException.class) public void createReportForInvalidMedia() throws IOException { userFacade.login("<EMAIL>", "123"); URI mediaUri = URI.create("xyz.jpg"); String country = "Switzerland"; profileFacade.reportAbusiveMedia(mediaUri, country, AbuseReason.VIOLENCE); } @Test public void createCommentReport() throws IOException { UserInfo user = userFacade.login("<EMAIL>", "123"); UUID commentId = UUID.fromString("c95472c0-e0e6-11e2-a28f-0800200c9a33"); String country = "Switzerland"; AbuseInfo abuse = profileFacade.reportAbusiveComment(commentId, country, AbuseReason.VIOLENCE); assertNotNull(abuse); assertEquals(user.getProfileId(), abuse.getProfileId()); assertNull(abuse.getMediaUri()); assertEquals(commentId, abuse.getCommentId()); assertEquals(AbuseReason.VIOLENCE, abuse.getReason()); assertEquals(AbuseStatus.NEW, abuse.getStatus()); assertEquals(country, abuse.getCountry()); assertEquals("Hello 2", abuse.getMessage()); assertEquals(user.getNickname(), abuse.getCreator()); assertNotNull(abuse.getTimestamp()); } @Test(expected=DataMissingException.class) public void createReportForInvalidComment() throws IOException { userFacade.login("<EMAIL>", "123"); UUID commentId = UUID.fromString("c95472c0-e0e6-11e2-a28f-999999999999"); String country = "Switzerland"; profileFacade.reportAbusiveComment(commentId, country, AbuseReason.VIOLENCE); } }
11,149
0.756373
0.721972
289
37.228374
25.754023
107
false
false
0
0
0
0
0
0
2.235294
false
false
13
d968256cef22134dc32d0483c0c0c80cbe7520bc
23,416,161,749,091
11693528a83f289a06c01971be89c2a86de97168
/storage-experiments/src/edu/uci/asterixdb/storage/experiments/feed/IFeedDriver.java
824ed8b8d708b5488829be8681aa2b8aee95edf4
[]
no_license
luochen01/storage-experiments
https://github.com/luochen01/storage-experiments
05bceaf29c7a5bd1b842af70692c8ca1f0a1811e
9e330c2b113f561d608dc52a10500e25a0f229d7
refs/heads/master
2022-12-06T12:43:46.255000
2021-07-10T18:51:36
2021-07-10T18:51:36
105,938,371
0
0
null
false
2022-11-16T05:45:20
2017-10-05T20:43:03
2021-07-10T18:51:42
2022-11-16T05:45:17
36,238
0
0
7
Java
false
false
package edu.uci.asterixdb.storage.experiments.feed; import java.io.IOException; import org.apache.commons.lang3.mutable.MutableBoolean; public interface IFeedDriver { public long getNextId(MutableBoolean isNew) throws IOException; }
UTF-8
Java
241
java
IFeedDriver.java
Java
[]
null
[]
package edu.uci.asterixdb.storage.experiments.feed; import java.io.IOException; import org.apache.commons.lang3.mutable.MutableBoolean; public interface IFeedDriver { public long getNextId(MutableBoolean isNew) throws IOException; }
241
0.813278
0.809129
10
23.1
25.315805
67
false
false
0
0
0
0
0
0
0.4
false
false
13
8f9a42768a19207cc666ae35f15bc2ac77883a80
28,355,374,091,485
b7099782b98a28aece288940ed465ef1f08774f8
/patrones-diseno/observador/original/src/main/java/curso/patrones/observador/Application.java
8f37365870ac0468215cb7f81a3928c5f67b1f2d
[]
no_license
escueladevhack/arquitectura-software
https://github.com/escueladevhack/arquitectura-software
68ae6b66e70115218026d99dcdf8955af657b9cc
beb649d88ebf344badc7aa5b5c5a8d6157ed983c
refs/heads/master
2020-04-11T05:21:24.096000
2018-12-18T16:49:45
2018-12-18T16:49:45
161,547,180
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package curso.patrones.observador; import curso.patrones.observador.entidades.Usuario; import curso.patrones.observador.negocio.ServicioUsuario; public class Application { public static void main(String[] args) { ServicioUsuario servicio = new ServicioUsuario(); //Crear observador y registrarlo en el servicio Usuario usuario = new Usuario("Jack", "Sparrow", "jack@pirate.com"); //La llamada a este método disparará el evento. servicio.actualizar(usuario); } }
UTF-8
Java
521
java
Application.java
Java
[ { "context": "servicio\n\n\n Usuario usuario = new Usuario(\"Jack\", \"Sparrow\", \"jack@pirate.com\");\n //La lla", "end": 381, "score": 0.5478788018226624, "start": 377, "tag": "USERNAME", "value": "Jack" }, { "context": "\n\n\n Usuario usuario = new Usuario(\"Jack\", \"Sparrow\", \"jack@pirate.com\");\n //La llamada a este", "end": 392, "score": 0.9791843891143799, "start": 385, "tag": "NAME", "value": "Sparrow" }, { "context": "Usuario usuario = new Usuario(\"Jack\", \"Sparrow\", \"jack@pirate.com\");\n //La llamada a este método disparará e", "end": 411, "score": 0.9999270439147949, "start": 396, "tag": "EMAIL", "value": "jack@pirate.com" } ]
null
[]
package curso.patrones.observador; import curso.patrones.observador.entidades.Usuario; import curso.patrones.observador.negocio.ServicioUsuario; public class Application { public static void main(String[] args) { ServicioUsuario servicio = new ServicioUsuario(); //Crear observador y registrarlo en el servicio Usuario usuario = new Usuario("Jack", "Sparrow", "<EMAIL>"); //La llamada a este método disparará el evento. servicio.actualizar(usuario); } }
513
0.709056
0.709056
21
23.714285
26.075245
76
false
false
0
0
0
0
0
0
0.380952
false
false
13
74e270eca806611fe6c993a59a541b5eb0e5d704
13,082,470,451,636
bac2cf35e7f618a1d4d06bc8671183febb7ba0db
/microservice_car/src/main/java/com/micro/car/service/CarService.java
bd0c8cd76671c46414f900816e2cb3bc238f8581
[ "MIT" ]
permissive
rafabc/microservice-full-environment
https://github.com/rafabc/microservice-full-environment
ecedcc391d431b7cf590b78287513af41e1271eb
26ba99f69f51c5795e5872584ec177d7d4a630e1
refs/heads/master
2021-05-04T03:36:55.217000
2016-12-10T00:50:59
2016-12-10T00:50:59
71,385,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.micro.car.service; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.stereotype.Service; import com.micro.car.dto.Car; @Service public class CarService { List<Car> cars; @PostConstruct public void init() { cars = new ArrayList<Car>(); cars.add(new Car("1", "For", "Mondeo", "Gris", "2015", "175")); cars.add(new Car("2", "Fiat", "Bravo", "Azul", "2001", "105")); cars.add(new Car("3", "Alfa Romeo", "159", "Negro", "2008", "150")); cars.add(new Car("4", "Ferrari", "GTO", "Rojo", "1995", "350")); cars.add(new Car("5", "Mercedes", "350", "Negro", "2005", "220")); cars.add(new Car("6", "Alfa Romeo", "147", "Negro", "2008", "105")); } public Car getCarById(String id) { return cars.get(Integer.valueOf(id) - 1); } public List<Car> getCars() { return cars; } }
UTF-8
Java
901
java
CarService.java
Java
[ { "context": "Azul\", \"2001\", \"105\"));\n\t\t cars.add(new Car(\"3\", \"Alfa Romeo\", \"159\", \"Negro\", \"2008\", \"150\"));\n\t\t cars.add(ne", "end": 507, "score": 0.9998049736022949, "start": 497, "tag": "NAME", "value": "Alfa Romeo" }, { "context": "egro\", \"2008\", \"150\"));\n\t\t cars.add(new Car(\"4\", \"Ferrari\", \"GTO\", \"Rojo\", \"1995\", \"350\"));\n\t\t cars.add(new", "end": 576, "score": 0.9453926086425781, "start": 569, "tag": "NAME", "value": "Ferrari" }, { "context": "Rojo\", \"1995\", \"350\"));\n\t\t cars.add(new Car(\"5\", \"Mercedes\", \"350\", \"Negro\", \"2005\", \"220\"));\n\t\t cars.add(ne", "end": 645, "score": 0.7986972332000732, "start": 637, "tag": "NAME", "value": "Mercedes" }, { "context": "egro\", \"2005\", \"220\"));\n\t\t cars.add(new Car(\"6\", \"Alfa Romeo\", \"147\", \"Negro\", \"2008\", \"105\"));\n\t}\n\t\n\tpublic C", "end": 717, "score": 0.9997982978820801, "start": 707, "tag": "NAME", "value": "Alfa Romeo" } ]
null
[]
package com.micro.car.service; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.stereotype.Service; import com.micro.car.dto.Car; @Service public class CarService { List<Car> cars; @PostConstruct public void init() { cars = new ArrayList<Car>(); cars.add(new Car("1", "For", "Mondeo", "Gris", "2015", "175")); cars.add(new Car("2", "Fiat", "Bravo", "Azul", "2001", "105")); cars.add(new Car("3", "<NAME>", "159", "Negro", "2008", "150")); cars.add(new Car("4", "Ferrari", "GTO", "Rojo", "1995", "350")); cars.add(new Car("5", "Mercedes", "350", "Negro", "2005", "220")); cars.add(new Car("6", "<NAME>", "147", "Negro", "2008", "105")); } public Car getCarById(String id) { return cars.get(Integer.valueOf(id) - 1); } public List<Car> getCars() { return cars; } }
893
0.612653
0.54828
42
20.452381
23.756907
71
false
false
0
0
0
0
0
0
2.023809
false
false
13
e48bb9bc6a2071b2fc7a171c89412a4e1f93dc66
13,082,470,453,554
c24da1532a5aff96dc6e5e76f1141ca4f92365e9
/src/main/java/com/fh/mapper/scanstron/StuScanstronTaskMapper.java
8fb0cd87ffd3e6d1c8a70e1558b480f52a9d04b4
[]
no_license
yinlongcong/test1
https://github.com/yinlongcong/test1
e2cbaf8ed0f0e088f4e6180de5b5df1bfa1afb76
0fe373ac0145e3a0f1adbb3f7f0fbea7c1eb0bac
refs/heads/master
2020-04-11T14:41:07.252000
2018-12-15T04:11:57
2018-12-15T04:11:57
161,864,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fh.mapper.scanstron; import com.fh.entity.Page; import com.fh.model.common.ScantronBackModel; import com.fh.model.common.ScantronInfoModel; import com.fh.model.scantask.*; import com.fh.model.school.StudentModel; import com.fh.util.PageData; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 学生答题卡识别数据保存,异常修复,自动批改后进入批改环节 */ public interface StuScanstronTaskMapper { /** 保存答题卡识别数据(不管正确与否) */ /** * 保存学生答题卡识别出来的概览(卡头,图片) * @param scantronRawModel */ void insertStuRawOverview(ScantronRawModel scantronRawModel); /** * 保存学生答题卡识别原始数据 * @param scantronRawV1Model * @return int */ Integer insertScantronV1Raw(ScantronRawV1Model scantronRawV1Model); /** * 获取阶段二的最大scanId * @return */ Integer getStuScantronLevel2MaxScanId(); /** * 扫描数据,从阶段一到阶段二 * @param scanId 阶段二中最大的scanId * @return 搬迁的条数 */ Integer saveStuScantronIntoLevel2(Integer scanId); /** * 保存学生答题卡识别出来的小题原始数据 * @param list */ // void insertStuRawPros(List list); /** * 根据ESId获取作业的学校、考试、小题类型,分数,答案,等等 * @param taskSubjectId * @return List */ List<ScanMockPaperStructure> getMixScantronByESId(Integer taskSubjectId); /** 修复答题卡异常(客观题异常,准考证号缺失,准考证号重复,缺考) */ /** 将数据推送入批改环节(客观题自动批改,教师批改任务更新,错误数据删除) */ /** 模拟学生答题,删除学生答题 */ /** * 查询该作业是否在该学校 * @param pageData * @return */ PageData getTaskSubjectStatusInSchool(PageData pageData); /** * 根据TId获取需修复客观题列表 * @param taskSubjectId * @return */ List<PageData> getScanTaskOptions(String taskSubjectId); /** * 根据id和taskSubjectId获取单个学生需修复客观题列表 * @param pageData id,taskSubjectId * @return */ PageData getStuScanTaskOptions(PageData pageData); /** * 修复客观题识别错误 * @param pageData answer、id * @return 更新的条目数 */ Integer updateScanOption(PageData pageData); /** * 根据taskSubjectId、 studentId、pageIndex、pageUid 获得单页扫描概览列表- * @param pageData taskSubjectId 、studentId(opt) pageIndex(opt)、pageUid(opt) * @return */ List<PageData> getAllStuScanByAdTNESId(PageData pageData); /** * 根据准考证号得到学生id和状态 * @param pageData * @return */ PageData getStuIdByAdT(PageData pageData); /** * 根据准考证号批量得到学生id和状态 * @param pageData * @return */ List<PageData> getBatchStuIdByAdT(PageData pageData); /** * 获取指定范围内参考学生 * @param page * @return */ List<PageData> getAbsenteeismlistPage(Page page); /** * 获取准考证重复列表 * @param pageData */ /*void getAdTRep(PageData pageData);*/ /** * 准考证重复列表(不含报废) * @param pageData taskSubjectId * @return */ List<ScantronAdtRepModel> getAdTErr(PageData pageData); /** * 准考证缺失列表(不含报废) * @param pageData taskSubjectId * @return */ List<ScanAdTicModel> getAdTMissing(PageData pageData); /** * 获取答题卡整张垮掉列表 * @param taskSubjectId * @return */ List<ScantronBeatModel> getStuScanBeat(String taskSubjectId); /** * 设置答题卡整张垮掉状态 * @param scantronBeatModel * @return */ Integer setStuScanBeat(ScantronBeatModel scantronBeatModel); /** * 获取未处理的扫描异常列表 (报废的不显示) * @param taskSubjectId * @return */ List<PageData> getStuScanErrList(String taskSubjectId); //void updateAdTicBug(List list); /** * 批量更新答题卡状态 根据id * @param list */ void updateBatchAdTicStatusById(List list); /** * 根据pageUid更新学生识别数据OverView,含status,errorType,admissionTicket,studentId * @param pageData */ Integer updateStuScantron(PageData pageData); /** * 根据ESId,获取答题卡试题结构表(图像识别版本) * @param taskSubjectId * @return */ List<ScantronBackModel> getScantronBackQuByESId(String taskSubjectId); /** * 根据ESId,获取答题卡基础属性 * @param pageData * @return */ ScantronInfoModel getScantronInfoByESId(String pageData); /** * 根据ESId,获取答题卡基础属性 * @param pageData * @return */ ScantronInfoModel getScantronInfoWithoutHtmlByESId(String pageData); /* void saveStuPsro(List list);*/ /** * 模拟专用接口 * @param list */ void saveStuQu(List list); /** * 保存待批改小题1 * @param list */ void saveStuPro1(List list); void saveStuQu2(List list); //PageData getRedundancy(PageData pageData); /** * 根据pageUid批量取出学生答题卡详情 * @param list * @return */ //List<PageData> getDetailByPageUids(List list); /** * 根据pageUid取出学生答题卡详情 * @param pageData * @return */ PageData getDetailByPageUid(PageData pageData); List<PageData> getProCandidateByESIdNStuId(PageData pageData); /** * 删除学生答题小题数据 * @param pageData taskSubjectId list(StudentId) */ void delMockStuPro(PageData pageData); /** * 删除学生答题小问数据 * @param pageData */ void delMockStuQu(PageData pageData); /** * 删除学生答题入库状态 * @param pageData * @return */ Integer saveStuScanJudgeStatus(PageData pageData); void delFinalJudgeTask(List list); void updateTeacherQuMarkedNum(PageData pageData); void updateTaskSubjectQuMarkedNum(PageData pageData); /** * 修改作业状态(0默认,1结束批改,2扫描或者批改阶段) * @param pageData status,taskSubjectId * @return 修改的条数 */ Integer updateTaskSubjectStatus(PageData pageData); /** * 获取扫描记录 * @param pageData * @return */ List<ScantronRecord> getScantronRecordByESId_listPage(Page pageData); /** * 根据taskSubjectId 和 studentId 获得学生答题卡原始数据 * @param pageData studentId taskSubjectId * @return list */ List<ScantronRawV2Model> getProByESIdAndStuId(PageData pageData); /** * 根据准考证号和准考证类型查出学生id,班级id,年级id * @param pageData schoolId sourceType(1学号 2身份证号) * @return */ List<PageData> getStuInfoByAdTic(PageData pageData); /** * 获取没有被预处理的level2 信息 * @return Id, SchoolId, AdmissionTicket,taskSubjectId */ List<PageData> getAllLevel2Candidate(); /** * 查询答题卡简单信息 * @param taskSubjectId * @return */ PageData getScantronSimInfoByESId(String taskSubjectId); /** * 获取所有重复的学号 * @return List<Id, ErrorType, Version, Confirmation> */ List<PageData> getAllLevel2DupsCandidate(); /** * 获取这场考试的准考证类型 * @param taskSubjectId * @return */ Integer getStuNumTypeByESId(String taskSubjectId); /** * 根据taskSubjectId查出参考班级,参考零散学生 * @param pageData * @return */ List<PageData> getTaskRangeClassOrGrade(PageData pageData); List<ScanQuFromPaperModel> getQuByESId(PageData pageData); void saveScantron(List list); void delScantronByESId(PageData pageData); List<ScantronModel> getScantronByESId(PageData pageData); /** * 根据esid获得答题卡页数和面数 * @param taskSubjectId * @return (10双面 或者 0单面) + 面数 */ Integer getTaskPageCntByESId(Integer taskSubjectId); /** * 根据pageUid对应studentId的所有合法的答题卡pageIndex和studentId * @param pageData * @return list{ studentId, pageIndex} */ List<PageData> getOverviewStatusByESIdAndPageUid(PageData pageData); /** * 测试用于获取作业,已经在批改的学生id * @param taskSubjectId * @return */ List<PageData> getStudentInTaskSubjectJudge(String taskSubjectId); //随机查询出最多500条未处理的答题卡数据 List<PageData> getScantronListByTaskSub(); //查询考试所包含的班级的Id的集合 List<Integer> findStudentIdByTaskSub(String taskSubjectId); void updateStuScantronV2(PageData pageData); //根据学号查询100个学生的处理过stage>0的学生的数据 List<ScantronRawV2Model> getScantronListByStudentId(); //根据学号来查询100个学生的stage=2的学生的数据 List<ScantronRawV2Model> getScantronRawListStage3(); //批量更新单个学生的stage=3数据 Integer updateScantronV2Batch(PageData pageData); List<StudentModel> findStudent(); void addClassStudent(PageData pd); ScantronRawV1Model findStuScanstronV1(Integer id); List<StudentModel> findStudentRandom(@Param("countStu") Integer countStu, @Param("schoolId") Integer schoolId); /** * 查询作业参考范围内的学生(从快照) * @param page * @return */ List<ScanStudent> dataGCTasklistPage(Page page); }
UTF-8
Java
10,046
java
StuScanstronTaskMapper.java
Java
[]
null
[]
package com.fh.mapper.scanstron; import com.fh.entity.Page; import com.fh.model.common.ScantronBackModel; import com.fh.model.common.ScantronInfoModel; import com.fh.model.scantask.*; import com.fh.model.school.StudentModel; import com.fh.util.PageData; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 学生答题卡识别数据保存,异常修复,自动批改后进入批改环节 */ public interface StuScanstronTaskMapper { /** 保存答题卡识别数据(不管正确与否) */ /** * 保存学生答题卡识别出来的概览(卡头,图片) * @param scantronRawModel */ void insertStuRawOverview(ScantronRawModel scantronRawModel); /** * 保存学生答题卡识别原始数据 * @param scantronRawV1Model * @return int */ Integer insertScantronV1Raw(ScantronRawV1Model scantronRawV1Model); /** * 获取阶段二的最大scanId * @return */ Integer getStuScantronLevel2MaxScanId(); /** * 扫描数据,从阶段一到阶段二 * @param scanId 阶段二中最大的scanId * @return 搬迁的条数 */ Integer saveStuScantronIntoLevel2(Integer scanId); /** * 保存学生答题卡识别出来的小题原始数据 * @param list */ // void insertStuRawPros(List list); /** * 根据ESId获取作业的学校、考试、小题类型,分数,答案,等等 * @param taskSubjectId * @return List */ List<ScanMockPaperStructure> getMixScantronByESId(Integer taskSubjectId); /** 修复答题卡异常(客观题异常,准考证号缺失,准考证号重复,缺考) */ /** 将数据推送入批改环节(客观题自动批改,教师批改任务更新,错误数据删除) */ /** 模拟学生答题,删除学生答题 */ /** * 查询该作业是否在该学校 * @param pageData * @return */ PageData getTaskSubjectStatusInSchool(PageData pageData); /** * 根据TId获取需修复客观题列表 * @param taskSubjectId * @return */ List<PageData> getScanTaskOptions(String taskSubjectId); /** * 根据id和taskSubjectId获取单个学生需修复客观题列表 * @param pageData id,taskSubjectId * @return */ PageData getStuScanTaskOptions(PageData pageData); /** * 修复客观题识别错误 * @param pageData answer、id * @return 更新的条目数 */ Integer updateScanOption(PageData pageData); /** * 根据taskSubjectId、 studentId、pageIndex、pageUid 获得单页扫描概览列表- * @param pageData taskSubjectId 、studentId(opt) pageIndex(opt)、pageUid(opt) * @return */ List<PageData> getAllStuScanByAdTNESId(PageData pageData); /** * 根据准考证号得到学生id和状态 * @param pageData * @return */ PageData getStuIdByAdT(PageData pageData); /** * 根据准考证号批量得到学生id和状态 * @param pageData * @return */ List<PageData> getBatchStuIdByAdT(PageData pageData); /** * 获取指定范围内参考学生 * @param page * @return */ List<PageData> getAbsenteeismlistPage(Page page); /** * 获取准考证重复列表 * @param pageData */ /*void getAdTRep(PageData pageData);*/ /** * 准考证重复列表(不含报废) * @param pageData taskSubjectId * @return */ List<ScantronAdtRepModel> getAdTErr(PageData pageData); /** * 准考证缺失列表(不含报废) * @param pageData taskSubjectId * @return */ List<ScanAdTicModel> getAdTMissing(PageData pageData); /** * 获取答题卡整张垮掉列表 * @param taskSubjectId * @return */ List<ScantronBeatModel> getStuScanBeat(String taskSubjectId); /** * 设置答题卡整张垮掉状态 * @param scantronBeatModel * @return */ Integer setStuScanBeat(ScantronBeatModel scantronBeatModel); /** * 获取未处理的扫描异常列表 (报废的不显示) * @param taskSubjectId * @return */ List<PageData> getStuScanErrList(String taskSubjectId); //void updateAdTicBug(List list); /** * 批量更新答题卡状态 根据id * @param list */ void updateBatchAdTicStatusById(List list); /** * 根据pageUid更新学生识别数据OverView,含status,errorType,admissionTicket,studentId * @param pageData */ Integer updateStuScantron(PageData pageData); /** * 根据ESId,获取答题卡试题结构表(图像识别版本) * @param taskSubjectId * @return */ List<ScantronBackModel> getScantronBackQuByESId(String taskSubjectId); /** * 根据ESId,获取答题卡基础属性 * @param pageData * @return */ ScantronInfoModel getScantronInfoByESId(String pageData); /** * 根据ESId,获取答题卡基础属性 * @param pageData * @return */ ScantronInfoModel getScantronInfoWithoutHtmlByESId(String pageData); /* void saveStuPsro(List list);*/ /** * 模拟专用接口 * @param list */ void saveStuQu(List list); /** * 保存待批改小题1 * @param list */ void saveStuPro1(List list); void saveStuQu2(List list); //PageData getRedundancy(PageData pageData); /** * 根据pageUid批量取出学生答题卡详情 * @param list * @return */ //List<PageData> getDetailByPageUids(List list); /** * 根据pageUid取出学生答题卡详情 * @param pageData * @return */ PageData getDetailByPageUid(PageData pageData); List<PageData> getProCandidateByESIdNStuId(PageData pageData); /** * 删除学生答题小题数据 * @param pageData taskSubjectId list(StudentId) */ void delMockStuPro(PageData pageData); /** * 删除学生答题小问数据 * @param pageData */ void delMockStuQu(PageData pageData); /** * 删除学生答题入库状态 * @param pageData * @return */ Integer saveStuScanJudgeStatus(PageData pageData); void delFinalJudgeTask(List list); void updateTeacherQuMarkedNum(PageData pageData); void updateTaskSubjectQuMarkedNum(PageData pageData); /** * 修改作业状态(0默认,1结束批改,2扫描或者批改阶段) * @param pageData status,taskSubjectId * @return 修改的条数 */ Integer updateTaskSubjectStatus(PageData pageData); /** * 获取扫描记录 * @param pageData * @return */ List<ScantronRecord> getScantronRecordByESId_listPage(Page pageData); /** * 根据taskSubjectId 和 studentId 获得学生答题卡原始数据 * @param pageData studentId taskSubjectId * @return list */ List<ScantronRawV2Model> getProByESIdAndStuId(PageData pageData); /** * 根据准考证号和准考证类型查出学生id,班级id,年级id * @param pageData schoolId sourceType(1学号 2身份证号) * @return */ List<PageData> getStuInfoByAdTic(PageData pageData); /** * 获取没有被预处理的level2 信息 * @return Id, SchoolId, AdmissionTicket,taskSubjectId */ List<PageData> getAllLevel2Candidate(); /** * 查询答题卡简单信息 * @param taskSubjectId * @return */ PageData getScantronSimInfoByESId(String taskSubjectId); /** * 获取所有重复的学号 * @return List<Id, ErrorType, Version, Confirmation> */ List<PageData> getAllLevel2DupsCandidate(); /** * 获取这场考试的准考证类型 * @param taskSubjectId * @return */ Integer getStuNumTypeByESId(String taskSubjectId); /** * 根据taskSubjectId查出参考班级,参考零散学生 * @param pageData * @return */ List<PageData> getTaskRangeClassOrGrade(PageData pageData); List<ScanQuFromPaperModel> getQuByESId(PageData pageData); void saveScantron(List list); void delScantronByESId(PageData pageData); List<ScantronModel> getScantronByESId(PageData pageData); /** * 根据esid获得答题卡页数和面数 * @param taskSubjectId * @return (10双面 或者 0单面) + 面数 */ Integer getTaskPageCntByESId(Integer taskSubjectId); /** * 根据pageUid对应studentId的所有合法的答题卡pageIndex和studentId * @param pageData * @return list{ studentId, pageIndex} */ List<PageData> getOverviewStatusByESIdAndPageUid(PageData pageData); /** * 测试用于获取作业,已经在批改的学生id * @param taskSubjectId * @return */ List<PageData> getStudentInTaskSubjectJudge(String taskSubjectId); //随机查询出最多500条未处理的答题卡数据 List<PageData> getScantronListByTaskSub(); //查询考试所包含的班级的Id的集合 List<Integer> findStudentIdByTaskSub(String taskSubjectId); void updateStuScantronV2(PageData pageData); //根据学号查询100个学生的处理过stage>0的学生的数据 List<ScantronRawV2Model> getScantronListByStudentId(); //根据学号来查询100个学生的stage=2的学生的数据 List<ScantronRawV2Model> getScantronRawListStage3(); //批量更新单个学生的stage=3数据 Integer updateScantronV2Batch(PageData pageData); List<StudentModel> findStudent(); void addClassStudent(PageData pd); ScantronRawV1Model findStuScanstronV1(Integer id); List<StudentModel> findStudentRandom(@Param("countStu") Integer countStu, @Param("schoolId") Integer schoolId); /** * 查询作业参考范围内的学生(从快照) * @param page * @return */ List<ScanStudent> dataGCTasklistPage(Page page); }
10,046
0.647017
0.642243
394
20.269035
20.866234
115
false
false
0
0
0
0
0
0
0.230964
false
false
13
5609be4cf17cdf7b30a9112cbaa51b0d118bd62a
21,680,994,963,691
038dffd30926652bcfc0dabd866b294d33c0a2a9
/WindowBuilder/src/robotBasic/BasicRobot.java
64aeb0e3ec812968a18d5600dce55a485c38a90e
[]
no_license
jmnie/FYP_Remote_Sensing_Demonstration_USING_EV3
https://github.com/jmnie/FYP_Remote_Sensing_Demonstration_USING_EV3
1ce61653fa218eca5f5c2a3298ba2f0fbaed322a
b2fee05e78232c0600f5e7acc93475847430e25c
refs/heads/master
2021-09-09T00:51:31.410000
2018-03-13T04:00:33
2018-03-13T04:00:33
89,575,129
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package robotBasic; import lejos.remote.ev3.RemoteRequestEV3; import lejos.remote.ev3.RemoteRequestPilot; import lejos.remote.ev3.RemoteRequestRegulatedMotor; import lejos.remote.ev3.RemoteRequestSampleProvider; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import lejos.hardware.lcd.LCD; import lejos.utility.Delay; import lejos.robotics.navigation.Move; public class BasicRobot implements Serializable{ /** * */ private static final long serialVersionUID = 788298558950251805L; // Test the part public ArrayList<Double> ranges = new ArrayList<Double>(); public double rangeDistance; public RemoteRequestSampleProvider ultrasonicSensor; // public static String address = "10.0.1.1"; RemoteRequestEV3 brick; /*---Sensor Motor and Other Motors---*/ public RemoteRequestRegulatedMotor motorL; public RemoteRequestRegulatedMotor motorR; public RemoteRequestRegulatedMotor SensorMotor; RemoteRequestPilot pilot; Move pilotMove; public int angle = 0; int fast_turn = 90; int slow_turn = 60; /*----Ultrasonic Sensor----*/ Ultrasonic_Sensor us; //float distance; String usPort = "S" + 1; int travel_speed = 5; // public boolean sensorRotate = false; // boolean has_pilot = false; protected boolean disconnected = false; public boolean connected = false; public boolean closed = false; public boolean straight = false; public void connect() throws Exception { try{ brick = new RemoteRequestEV3(address); this.connected = true; }catch(Exception e){ brick.disConnect(); throw e; } try{ us = new Ultrasonic_Sensor(brick, usPort); }catch(Exception e) { brick.disConnect(); throw e; } /*-----Sensor Motor-----*/ try{ SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'S'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'S'); motorR.setSpeed(90); motorL.setSpeed(90); SensorMotor.setSpeed(3); pilot = (RemoteRequestPilot) brick.createPilot(1, 2, "C", "B"); pilot.setLinearSpeed(1); }catch(Exception e) { brick.disConnect(); throw e; } /* SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'L'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'L'); motorR.setSpeed(200); motorL.setSpeed(200); pilot = (RemoteRequestPilot) brick.createPilot(4, 9, "C", "B"); */ this.connected = true; this.disconnected = false; } //Test Function & Method //Connect to Other Motors only public void newConnect() throws Exception { try{ brick = new RemoteRequestEV3(address); this.connected = true; }catch(Exception e){ brick.disConnect(); throw e; } try{ motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'S'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'S'); motorR.setSpeed(40); motorL.setSpeed(40); pilot = (RemoteRequestPilot) brick.createPilot(1, 2, "C", "B"); pilot.setLinearSpeed(2); }catch(Exception e) { brick.disConnect(); throw e; } } public void newDisconnect() { this.brick.disConnect(); } //Test Line Finished here public void distanceTravelled() { } public void motorClose() { motorR.close(); motorL.close(); SensorMotor.close(); } public void disConnect() { this.connected = false; this.motorR.close(); this.motorL.close(); this.SensorMotor.close(); this.us.close(); this.brick.disConnect(); } public void pilotStop() { pilot.stop(); } public boolean isConnected() { return connected; } public double ultrasonicDistance() throws Exception { //DecimalFormat df = new DecimalFormat("#.###"); //double distance = 100*us.distance(); double distance = us.distance(); //distance = Double.parseDouble(df.format(distance)); return distance; } public void closeRobot() { us.close(); } public void usClose() { us.close(); } public RemoteRequestEV3 getBrick() { return brick; } public void Hello(){ LCD.drawString("Hello World", 0, 4); Delay.msDelay(2000); LCD.clearDisplay(); } public void conntectToRobot() throws Exception { connect(); //connect to the robot } /*------The motor of the sensor ------*/ public void scare() { int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(60); SensorMotor.rotateTo(pos + 90); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos + 40); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos + 40); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); /*------------------------*/ //SensorMotor.waitComplete(); Delay.msDelay(10000); SensorMotor.rotateTo(pos - 80); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos - 60); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.close(); } public void rotate(int degree) { int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(200); SensorMotor.rotateTo(pos + degree); // SensorMotor.waitComplete(); } public void ToCertainPos(int pos) { SensorMotor.rotateTo(pos); } public void SensorToRight(int i) { int currentPos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(currentPos + i); SensorMotor.waitComplete(); SensorMotor.stop(); } public void SensorToLeft(int i) { int currentPos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(currentPos - i); SensorMotor.waitComplete(); SensorMotor.stop(); } //Just for test.java public void SensorRotate(int pos) { SensorMotor.setSpeed(200); SensorMotor.rotateTo(pos); //SensorMotor.waitComplete(); setSensorMotorStatus(false); SensorMotor.stop(); } public void SensorMotorRight() { SensorMotor.forward(); } public void SensorMotorLeft() { SensorMotor.backward(); } public void SensorMotorStop() { SensorMotor.stop(); } public void setSensorMotorStatus(boolean flag) { sensorRotate = flag; } //Loop Outside the program. public int InitialPosition() { return SensorMotor.getTachoCount(); } public double dataRotation(int degree) { int division = 5; int fractionTimes = (int) degree/division; int pos = SensorMotor.getTachoCount(); double distance = 0; SensorMotor.setSpeed(200); /*Rotate to 90 degrees and measure the distance*/ /*Direction: Right*/ for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); //double distance = us.distance(); // System.out.println(distance); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); distance = us.distance(); //System.out.println(distance); pos = SensorMotor.getTachoCount(); } /*Rotate to 90 degrees and measure the distance*/ /*Direction: Left*/ for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); // double distance = us.distance(); // System.out.println(distance); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); distance = us.distance(); //System.out.println(distance); pos = SensorMotor.getTachoCount(); } return distance; } //New Function Implements the Static Sweep Function /*The first function is to rotate the Sensor*/ public void StaticSweep() { int division = 5; int fractionTimes = 18; int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(200); /*Rotate to 90 degrees and measure the distance*/ /*Direction: Right*/ for(int i=0;i<fractionTimes;i++) { angle = i*5; SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { angle = 90 - i*5; SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } /*Rotate to 90 degrees and measure the distance*/ /*Direction: Left*/ for(int i=0;i<fractionTimes;i++) { angle = i*5; SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { angle = 90 - i*5; SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } } public void setSensorMotorSpeed(int i) { SensorMotor.setSpeed(i); } public int staticAngle() { return angle; } //------------------------------------------------------ public void closeMotorSensor() { us.close(); SensorMotor.close(); } /*-----------Below is the code of the robot moving-----------*/ public void setTravelSpeed(int travelSpeed) { travel_speed = travelSpeed; } public RemoteRequestRegulatedMotor getSensorMotor() { return SensorMotor; } public void forward() throws InterruptedException { pilot.forward(); } public void short_forward() { pilot.travel(1); } public void backward() { pilot.backward(); } public void short_backward() { pilot.travel(-1); } public void stop() { pilot.stop(); } public void left() { motorR.setSpeed(fast_turn); motorL.setSpeed(fast_turn); motorR.backward(); motorL.forward(); straight = false; } public void very_short_left() { pilot.setAngularSpeed(travel_speed); pilot.rotate(-30); straight = false; } public void short_left() { pilot.setAngularSpeed(travel_speed); pilot.rotate(-30); straight = false; } public void forward_left() { motorL.setSpeed(slow_turn); motorL.forward(); motorR.stop(); straight = false; } public void right() { motorR.setSpeed(fast_turn); motorL.setSpeed(fast_turn); motorR.forward(); motorL.backward(); straight = false; } public void short_right() { pilot.setAngularSpeed(travel_speed); pilot.rotate(90); straight = false; } public void very_short_right() { pilot.setAngularSpeed(fast_turn); pilot.rotate(30); straight = false; } public RemoteRequestPilot getPilot() { return pilot; } public void forward_right() { motorR.setSpeed(slow_turn); motorR.forward(); motorL.stop(); straight = false; } public Ultrasonic_Sensor getUS() { return us; } public void shutDown() { } public void DisplayRanges() { for(int i =0;i<ranges.size(); i++) { System.out.println(ranges.get(i)); } } public boolean isSensorMotorMoving() { return sensorRotate; } //Test Only public void sensorRotateTest() throws Exception { Thread t1 = new Thread(new SensorRotation()); Thread t2 = new Thread(new ReadDistance()); t1.start(); t2.start(); Thread.sleep(12000); t1.interrupt(); System.out.println(t1.isInterrupted()); if(t1.isInterrupted() == false) { //Thread.sleep(20); t2.interrupt(); } } public int getMotorSpeed() { return motorR.getSpeed(); } public class SensorRotation implements Runnable { public SensorRotation() { try{ SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); SensorMotor.setSpeed(40); }catch(Exception e) { throw e; } } public void start() { this.run(); } /* public SensorRotation(int newDegree) { this.degree = newDegree; } */ public void run() { int inipos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(-90); SensorMotor.rotateTo(inipos); SensorMotor.rotateTo(90); SensorMotor.rotateTo(inipos); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } SensorMotor.close(); System.out.println(" --- Sensor Rotation Leaving Normally ---"); } } public class ReadDistance implements Runnable { public void start() { this.run(); } public ReadDistance() throws Exception { try { String port = "S" + 1; ultrasonicSensor = (RemoteRequestSampleProvider) brick.createSampleProvider(port,"lejos.hardware.sensor.EV3UltrasonicSensor","Distance"); }catch(Exception e) { throw e; } } public void run() { try { while(!Thread.interrupted()) { float[] sample = new float[1]; ultrasonicSensor.fetchSample(sample, 0); if(sample[0] == Float.POSITIVE_INFINITY || sample[0] == Float.NEGATIVE_INFINITY) { sample[0] = (float) 2.499; } DecimalFormat df = new DecimalFormat("#.###"); double result = Double.parseDouble(df.format(sample[0])); double distance = result; ranges.add(distance); System.out.println(distance); Thread.sleep(25); } }catch(InterruptedException e) { ultrasonicSensor.close(); System.out.println("Read Distance Thread is over"); } System.out.println("Read Distance Thread is over !!!"); } } }
UTF-8
Java
16,582
java
BasicRobot.java
Java
[ { "context": "icSensor;\n\t //\n\t public static String address = \"10.0.1.1\";\n RemoteRequestEV3 brick;\n \n /*---", "end": 755, "score": 0.999608039855957, "start": 747, "tag": "IP_ADDRESS", "value": "10.0.1.1" } ]
null
[]
package robotBasic; import lejos.remote.ev3.RemoteRequestEV3; import lejos.remote.ev3.RemoteRequestPilot; import lejos.remote.ev3.RemoteRequestRegulatedMotor; import lejos.remote.ev3.RemoteRequestSampleProvider; import java.io.Serializable; import java.text.DecimalFormat; import java.util.ArrayList; import lejos.hardware.lcd.LCD; import lejos.utility.Delay; import lejos.robotics.navigation.Move; public class BasicRobot implements Serializable{ /** * */ private static final long serialVersionUID = 788298558950251805L; // Test the part public ArrayList<Double> ranges = new ArrayList<Double>(); public double rangeDistance; public RemoteRequestSampleProvider ultrasonicSensor; // public static String address = "10.0.1.1"; RemoteRequestEV3 brick; /*---Sensor Motor and Other Motors---*/ public RemoteRequestRegulatedMotor motorL; public RemoteRequestRegulatedMotor motorR; public RemoteRequestRegulatedMotor SensorMotor; RemoteRequestPilot pilot; Move pilotMove; public int angle = 0; int fast_turn = 90; int slow_turn = 60; /*----Ultrasonic Sensor----*/ Ultrasonic_Sensor us; //float distance; String usPort = "S" + 1; int travel_speed = 5; // public boolean sensorRotate = false; // boolean has_pilot = false; protected boolean disconnected = false; public boolean connected = false; public boolean closed = false; public boolean straight = false; public void connect() throws Exception { try{ brick = new RemoteRequestEV3(address); this.connected = true; }catch(Exception e){ brick.disConnect(); throw e; } try{ us = new Ultrasonic_Sensor(brick, usPort); }catch(Exception e) { brick.disConnect(); throw e; } /*-----Sensor Motor-----*/ try{ SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'S'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'S'); motorR.setSpeed(90); motorL.setSpeed(90); SensorMotor.setSpeed(3); pilot = (RemoteRequestPilot) brick.createPilot(1, 2, "C", "B"); pilot.setLinearSpeed(1); }catch(Exception e) { brick.disConnect(); throw e; } /* SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'L'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'L'); motorR.setSpeed(200); motorL.setSpeed(200); pilot = (RemoteRequestPilot) brick.createPilot(4, 9, "C", "B"); */ this.connected = true; this.disconnected = false; } //Test Function & Method //Connect to Other Motors only public void newConnect() throws Exception { try{ brick = new RemoteRequestEV3(address); this.connected = true; }catch(Exception e){ brick.disConnect(); throw e; } try{ motorR = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("B",'S'); motorL = (RemoteRequestRegulatedMotor) brick.createRegulatedMotor("C",'S'); motorR.setSpeed(40); motorL.setSpeed(40); pilot = (RemoteRequestPilot) brick.createPilot(1, 2, "C", "B"); pilot.setLinearSpeed(2); }catch(Exception e) { brick.disConnect(); throw e; } } public void newDisconnect() { this.brick.disConnect(); } //Test Line Finished here public void distanceTravelled() { } public void motorClose() { motorR.close(); motorL.close(); SensorMotor.close(); } public void disConnect() { this.connected = false; this.motorR.close(); this.motorL.close(); this.SensorMotor.close(); this.us.close(); this.brick.disConnect(); } public void pilotStop() { pilot.stop(); } public boolean isConnected() { return connected; } public double ultrasonicDistance() throws Exception { //DecimalFormat df = new DecimalFormat("#.###"); //double distance = 100*us.distance(); double distance = us.distance(); //distance = Double.parseDouble(df.format(distance)); return distance; } public void closeRobot() { us.close(); } public void usClose() { us.close(); } public RemoteRequestEV3 getBrick() { return brick; } public void Hello(){ LCD.drawString("Hello World", 0, 4); Delay.msDelay(2000); LCD.clearDisplay(); } public void conntectToRobot() throws Exception { connect(); //connect to the robot } /*------The motor of the sensor ------*/ public void scare() { int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(60); SensorMotor.rotateTo(pos + 90); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos + 40); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos + 40); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); /*------------------------*/ //SensorMotor.waitComplete(); Delay.msDelay(10000); SensorMotor.rotateTo(pos - 80); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.rotateTo(pos - 60); SensorMotor.rotateTo(pos); SensorMotor.waitComplete(); SensorMotor.close(); } public void rotate(int degree) { int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(200); SensorMotor.rotateTo(pos + degree); // SensorMotor.waitComplete(); } public void ToCertainPos(int pos) { SensorMotor.rotateTo(pos); } public void SensorToRight(int i) { int currentPos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(currentPos + i); SensorMotor.waitComplete(); SensorMotor.stop(); } public void SensorToLeft(int i) { int currentPos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(currentPos - i); SensorMotor.waitComplete(); SensorMotor.stop(); } //Just for test.java public void SensorRotate(int pos) { SensorMotor.setSpeed(200); SensorMotor.rotateTo(pos); //SensorMotor.waitComplete(); setSensorMotorStatus(false); SensorMotor.stop(); } public void SensorMotorRight() { SensorMotor.forward(); } public void SensorMotorLeft() { SensorMotor.backward(); } public void SensorMotorStop() { SensorMotor.stop(); } public void setSensorMotorStatus(boolean flag) { sensorRotate = flag; } //Loop Outside the program. public int InitialPosition() { return SensorMotor.getTachoCount(); } public double dataRotation(int degree) { int division = 5; int fractionTimes = (int) degree/division; int pos = SensorMotor.getTachoCount(); double distance = 0; SensorMotor.setSpeed(200); /*Rotate to 90 degrees and measure the distance*/ /*Direction: Right*/ for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); //double distance = us.distance(); // System.out.println(distance); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); distance = us.distance(); //System.out.println(distance); pos = SensorMotor.getTachoCount(); } /*Rotate to 90 degrees and measure the distance*/ /*Direction: Left*/ for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); // double distance = us.distance(); // System.out.println(distance); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); distance = us.distance(); //System.out.println(distance); pos = SensorMotor.getTachoCount(); } return distance; } //New Function Implements the Static Sweep Function /*The first function is to rotate the Sensor*/ public void StaticSweep() { int division = 5; int fractionTimes = 18; int pos = SensorMotor.getTachoCount(); SensorMotor.setSpeed(200); /*Rotate to 90 degrees and measure the distance*/ /*Direction: Right*/ for(int i=0;i<fractionTimes;i++) { angle = i*5; SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { angle = 90 - i*5; SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } /*Rotate to 90 degrees and measure the distance*/ /*Direction: Left*/ for(int i=0;i<fractionTimes;i++) { angle = i*5; SensorMotor.rotateTo(pos - division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } for(int i=0;i<fractionTimes;i++) { angle = 90 - i*5; SensorMotor.rotateTo(pos + division); SensorMotor.waitComplete(); pos = SensorMotor.getTachoCount(); } } public void setSensorMotorSpeed(int i) { SensorMotor.setSpeed(i); } public int staticAngle() { return angle; } //------------------------------------------------------ public void closeMotorSensor() { us.close(); SensorMotor.close(); } /*-----------Below is the code of the robot moving-----------*/ public void setTravelSpeed(int travelSpeed) { travel_speed = travelSpeed; } public RemoteRequestRegulatedMotor getSensorMotor() { return SensorMotor; } public void forward() throws InterruptedException { pilot.forward(); } public void short_forward() { pilot.travel(1); } public void backward() { pilot.backward(); } public void short_backward() { pilot.travel(-1); } public void stop() { pilot.stop(); } public void left() { motorR.setSpeed(fast_turn); motorL.setSpeed(fast_turn); motorR.backward(); motorL.forward(); straight = false; } public void very_short_left() { pilot.setAngularSpeed(travel_speed); pilot.rotate(-30); straight = false; } public void short_left() { pilot.setAngularSpeed(travel_speed); pilot.rotate(-30); straight = false; } public void forward_left() { motorL.setSpeed(slow_turn); motorL.forward(); motorR.stop(); straight = false; } public void right() { motorR.setSpeed(fast_turn); motorL.setSpeed(fast_turn); motorR.forward(); motorL.backward(); straight = false; } public void short_right() { pilot.setAngularSpeed(travel_speed); pilot.rotate(90); straight = false; } public void very_short_right() { pilot.setAngularSpeed(fast_turn); pilot.rotate(30); straight = false; } public RemoteRequestPilot getPilot() { return pilot; } public void forward_right() { motorR.setSpeed(slow_turn); motorR.forward(); motorL.stop(); straight = false; } public Ultrasonic_Sensor getUS() { return us; } public void shutDown() { } public void DisplayRanges() { for(int i =0;i<ranges.size(); i++) { System.out.println(ranges.get(i)); } } public boolean isSensorMotorMoving() { return sensorRotate; } //Test Only public void sensorRotateTest() throws Exception { Thread t1 = new Thread(new SensorRotation()); Thread t2 = new Thread(new ReadDistance()); t1.start(); t2.start(); Thread.sleep(12000); t1.interrupt(); System.out.println(t1.isInterrupted()); if(t1.isInterrupted() == false) { //Thread.sleep(20); t2.interrupt(); } } public int getMotorSpeed() { return motorR.getSpeed(); } public class SensorRotation implements Runnable { public SensorRotation() { try{ SensorMotor=(RemoteRequestRegulatedMotor)brick.createRegulatedMotor("D", 'M'); SensorMotor.setSpeed(40); }catch(Exception e) { throw e; } } public void start() { this.run(); } /* public SensorRotation(int newDegree) { this.degree = newDegree; } */ public void run() { int inipos = SensorMotor.getTachoCount(); SensorMotor.rotateTo(-90); SensorMotor.rotateTo(inipos); SensorMotor.rotateTo(90); SensorMotor.rotateTo(inipos); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } SensorMotor.close(); System.out.println(" --- Sensor Rotation Leaving Normally ---"); } } public class ReadDistance implements Runnable { public void start() { this.run(); } public ReadDistance() throws Exception { try { String port = "S" + 1; ultrasonicSensor = (RemoteRequestSampleProvider) brick.createSampleProvider(port,"lejos.hardware.sensor.EV3UltrasonicSensor","Distance"); }catch(Exception e) { throw e; } } public void run() { try { while(!Thread.interrupted()) { float[] sample = new float[1]; ultrasonicSensor.fetchSample(sample, 0); if(sample[0] == Float.POSITIVE_INFINITY || sample[0] == Float.NEGATIVE_INFINITY) { sample[0] = (float) 2.499; } DecimalFormat df = new DecimalFormat("#.###"); double result = Double.parseDouble(df.format(sample[0])); double distance = result; ranges.add(distance); System.out.println(distance); Thread.sleep(25); } }catch(InterruptedException e) { ultrasonicSensor.close(); System.out.println("Read Distance Thread is over"); } System.out.println("Read Distance Thread is over !!!"); } } }
16,582
0.534797
0.524062
687
23.131004
18.620245
145
false
false
0
0
0
0
0
0
1.305677
false
false
13
aa1bc60b3bdfccaccd09bc7922d6c7252c039faa
15,710,990,437,864
f589d725cd0a20a5167d18038d9dfbb85db33026
/src/main/java/slimeknights/tconstruct/library/tools/context/ToolAttackContext.java
687dea06f581a2e3e6397130b49cc3cc1ca38403
[ "MIT" ]
permissive
DimensionalDevelopment/TinkersConstruct
https://github.com/DimensionalDevelopment/TinkersConstruct
4ea3d83d9f805eaff41607810105326ac293aa2a
e665e7794dddc2c7d2f0824fef3c0066b2f66900
refs/heads/1.16-fabric
2023-08-06T00:03:32.840000
2021-07-28T06:48:18
2021-07-28T06:48:18
355,390,765
27
5
null
true
2021-07-28T06:51:07
2021-04-07T02:40:01
2021-07-28T06:09:54
2021-07-28T06:51:05
38,175
13
3
0
Java
false
false
package slimeknights.tconstruct.library.tools.context; import lombok.Data; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Hand; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Object for common context for weapon attack hooks */ @Data public class ToolAttackContext { /** Entity doing the attacking */ @Nonnull private final LivingEntity attacker; /** Player doing the attacking, null if not a player */ @Nullable private final PlayerEntity playerAttacker; /** Hand containing the tool */ @Nonnull private final Hand hand; /** Originally targeted entity, may be different from {@link #getTarget()} for multipart entities */ @Nonnull private final Entity target; /** Target entity */ @Nullable private final LivingEntity livingTarget; /** If true, attack is a critical hit */ private final boolean isCritical; /** Current attack cooldown */ private final float cooldown; /** If true, this is a secondary attack, such as for scythes */ private final boolean isExtraAttack; /** Returns true if this attack is fully charged */ public boolean isFullyCharged() { return getCooldown() > 0.9f; } }
UTF-8
Java
1,275
java
ToolAttackContext.java
Java
[]
null
[]
package slimeknights.tconstruct.library.tools.context; import lombok.Data; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Hand; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Object for common context for weapon attack hooks */ @Data public class ToolAttackContext { /** Entity doing the attacking */ @Nonnull private final LivingEntity attacker; /** Player doing the attacking, null if not a player */ @Nullable private final PlayerEntity playerAttacker; /** Hand containing the tool */ @Nonnull private final Hand hand; /** Originally targeted entity, may be different from {@link #getTarget()} for multipart entities */ @Nonnull private final Entity target; /** Target entity */ @Nullable private final LivingEntity livingTarget; /** If true, attack is a critical hit */ private final boolean isCritical; /** Current attack cooldown */ private final float cooldown; /** If true, this is a secondary attack, such as for scythes */ private final boolean isExtraAttack; /** Returns true if this attack is fully charged */ public boolean isFullyCharged() { return getCooldown() > 0.9f; } }
1,275
0.742745
0.741176
41
30.097561
20.970135
102
false
false
0
0
0
0
0
0
0.536585
false
false
13
6fefd445489b3b13a25eadf24ceb037befe3397e
20,255,065,831,439
1c53dbd683226fbb356c046fdbec4fd6072c716f
/BackFromTheBrink/Semester 2/src/payUpWildCard.java
cdd411ea62899b33ca16a7ba86f0978c92bec1a7
[]
no_license
cmcgarry5/csc2058-2021-g25
https://github.com/cmcgarry5/csc2058-2021-g25
154df326f72f445ae2f5c7e3bfcc410ed07192ac
522786a65b852056bd95618e561f5d6a2b8878c9
refs/heads/master
2023-03-19T10:34:05.775000
2021-03-09T17:29:27
2021-03-09T17:29:27
345,896,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class payUpWildCard extends WildCard{ private int feeToPayZoosAndParks; private int feeToPay; private boolean isMaintenance; public payUpWildCard(String cardName, boolean isMaint, int fee) { super(cardName); setFeeToPay(fee); setMaintenance(isMaint); } public void execute(Player player){ int countZoo = 0; int countPark = 0; if(getIsMaintenance()){ ArrayList<Biome> biomesOwned = player.getInventory().getBiomes(); for(int i = 0; i < biomesOwned.size(); i++){ Biome currentBiome = biomesOwned.get(i); for (int j = 0; j < currentBiome.getNumberOwnedHabitats()-1; j++){ if (currentBiome.getHabitats().get(j).hasNationalPark() != true){ countZoo += currentBiome.getHabitats().get(j).getNumberOfZoos(); } else{ countPark += 1; } } } setFeeToPayZoosAndParks((40*countZoo) + (75*countPark)); player.getInventory().deductPlayerMaterials(getFeeZoosAndParksAmount()); System.out.println(StdIO.printPlayerDecreasedMaterials(player, getFeeZoosAndParksAmount())); return; } player.getInventory().deductPlayerMaterials(getFeeAmount()); System.out.println(StdIO.printPlayerDecreasedMaterials(player, getFeeAmount())); } private void setMaintenance(boolean bool){ this.isMaintenance = bool; } private void setFeeToPay(int fee){ this.feeToPay = fee; } private void setFeeToPayZoosAndParks(int fee){ this.feeToPayZoosAndParks = fee; } public int getFeeAmount(){ return this.feeToPay; } public int getFeeZoosAndParksAmount(){ return this.feeToPayZoosAndParks; } public boolean getIsMaintenance(){ return this.isMaintenance; } }
UTF-8
Java
2,007
java
payUpWildCard.java
Java
[]
null
[]
import java.util.*; public class payUpWildCard extends WildCard{ private int feeToPayZoosAndParks; private int feeToPay; private boolean isMaintenance; public payUpWildCard(String cardName, boolean isMaint, int fee) { super(cardName); setFeeToPay(fee); setMaintenance(isMaint); } public void execute(Player player){ int countZoo = 0; int countPark = 0; if(getIsMaintenance()){ ArrayList<Biome> biomesOwned = player.getInventory().getBiomes(); for(int i = 0; i < biomesOwned.size(); i++){ Biome currentBiome = biomesOwned.get(i); for (int j = 0; j < currentBiome.getNumberOwnedHabitats()-1; j++){ if (currentBiome.getHabitats().get(j).hasNationalPark() != true){ countZoo += currentBiome.getHabitats().get(j).getNumberOfZoos(); } else{ countPark += 1; } } } setFeeToPayZoosAndParks((40*countZoo) + (75*countPark)); player.getInventory().deductPlayerMaterials(getFeeZoosAndParksAmount()); System.out.println(StdIO.printPlayerDecreasedMaterials(player, getFeeZoosAndParksAmount())); return; } player.getInventory().deductPlayerMaterials(getFeeAmount()); System.out.println(StdIO.printPlayerDecreasedMaterials(player, getFeeAmount())); } private void setMaintenance(boolean bool){ this.isMaintenance = bool; } private void setFeeToPay(int fee){ this.feeToPay = fee; } private void setFeeToPayZoosAndParks(int fee){ this.feeToPayZoosAndParks = fee; } public int getFeeAmount(){ return this.feeToPay; } public int getFeeZoosAndParksAmount(){ return this.feeToPayZoosAndParks; } public boolean getIsMaintenance(){ return this.isMaintenance; } }
2,007
0.597907
0.592925
66
29.40909
27.3601
104
false
false
0
0
0
0
0
0
0.5
false
false
13
7424fc60bcc4abdb9331ae8b2dde8b2337285787
16,793,322,148,344
6b10f27256c6753c2005dd9aea3fec75a2794d1c
/apollo-ws/service-skeletons/java/trunk/library-service/src/main/java/edu/pitt/apollo/libraryservice/methods/QueryLibraryMethod.java
cd70532cf37abf5b453a5bed7ff94b5577662eca
[ "Apache-2.0" ]
permissive
tectronics/apollo
https://github.com/tectronics/apollo
306b1d449ffb89be67eec5a00ff6f85c1576c596
ecfaa319c933809805a22a4387a029d293abfba0
refs/heads/master
2018-01-11T13:50:36.898000
2015-08-07T17:30:27
2015-08-07T17:30:27
43,488,660
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.pitt.apollo.libraryservice.methods; import edu.pitt.apollo.db.LibraryDbUtils; import edu.pitt.apollo.db.LibraryUserRoleTypeEnum; import edu.pitt.apollo.db.exceptions.ApolloDatabaseException; import edu.pitt.apollo.library_service_types.v3_0_0.QueryMessage; import edu.pitt.apollo.library_service_types.v3_0_0.QueryResult; import edu.pitt.apollo.services_common.v3_0_0.Authentication; import edu.pitt.apollo.services_common.v3_0_0.MethodCallStatus; import edu.pitt.apollo.services_common.v3_0_0.MethodCallStatusEnum; /** * * Author: Nick Millett * Email: nick.millett@gmail.com * Date: Nov 7, 2014 * Time: 2:12:51 PM * Class: QueryLibraryMethod */ public class QueryLibraryMethod { public static QueryResult queryLibrary(LibraryDbUtils dbUtils, LibraryDbUtils readOnlyDbUtils, QueryMessage message) { Authentication authentication = message.getAuthentication(); String query = message.getQuery(); QueryResult result = new QueryResult(); MethodCallStatus status = new MethodCallStatus(); try { boolean userAuthorized = dbUtils.authorizeUser(authentication, LibraryUserRoleTypeEnum.READONLY); if (userAuthorized) { result = readOnlyDbUtils.queryObjects(query); status.setStatus(MethodCallStatusEnum.COMPLETED); } else { status.setStatus(MethodCallStatusEnum.AUTHENTICATION_FAILURE); status.setMessage("You are not authorized to use queries."); } } catch (ApolloDatabaseException ex) { status.setStatus(MethodCallStatusEnum.FAILED); status.setMessage(ex.getMessage()); } result.setStatus(status); return result; } }
UTF-8
Java
1,596
java
QueryLibraryMethod.java
Java
[ { "context": "on.v3_0_0.MethodCallStatusEnum;\n\n/**\n *\n * Author: Nick Millett\n * Email: nick.millett@gmail.com\n * Date: Nov 7, ", "end": 560, "score": 0.9998242259025574, "start": 548, "tag": "NAME", "value": "Nick Millett" }, { "context": "tusEnum;\n\n/**\n *\n * Author: Nick Millett\n * Email: nick.millett@gmail.com\n * Date: Nov 7, 2014\n * Time: 2:12:51 PM\n * Class", "end": 593, "score": 0.9999294281005859, "start": 571, "tag": "EMAIL", "value": "nick.millett@gmail.com" } ]
null
[]
package edu.pitt.apollo.libraryservice.methods; import edu.pitt.apollo.db.LibraryDbUtils; import edu.pitt.apollo.db.LibraryUserRoleTypeEnum; import edu.pitt.apollo.db.exceptions.ApolloDatabaseException; import edu.pitt.apollo.library_service_types.v3_0_0.QueryMessage; import edu.pitt.apollo.library_service_types.v3_0_0.QueryResult; import edu.pitt.apollo.services_common.v3_0_0.Authentication; import edu.pitt.apollo.services_common.v3_0_0.MethodCallStatus; import edu.pitt.apollo.services_common.v3_0_0.MethodCallStatusEnum; /** * * Author: <NAME> * Email: <EMAIL> * Date: Nov 7, 2014 * Time: 2:12:51 PM * Class: QueryLibraryMethod */ public class QueryLibraryMethod { public static QueryResult queryLibrary(LibraryDbUtils dbUtils, LibraryDbUtils readOnlyDbUtils, QueryMessage message) { Authentication authentication = message.getAuthentication(); String query = message.getQuery(); QueryResult result = new QueryResult(); MethodCallStatus status = new MethodCallStatus(); try { boolean userAuthorized = dbUtils.authorizeUser(authentication, LibraryUserRoleTypeEnum.READONLY); if (userAuthorized) { result = readOnlyDbUtils.queryObjects(query); status.setStatus(MethodCallStatusEnum.COMPLETED); } else { status.setStatus(MethodCallStatusEnum.AUTHENTICATION_FAILURE); status.setMessage("You are not authorized to use queries."); } } catch (ApolloDatabaseException ex) { status.setStatus(MethodCallStatusEnum.FAILED); status.setMessage(ex.getMessage()); } result.setStatus(status); return result; } }
1,575
0.775689
0.760025
49
31.571428
28.726011
119
false
false
0
0
0
0
0
0
1.673469
false
false
13
7c9484bc127fe2fbec2c95e3c603bf931cd7a53d
27,066,883,920,824
37903e9a9e446b089aa1ae3acd440d03adc9c373
/Kinetise/src/com/kinetise/data/application/formdatautils/FormValidation.java
552273cf4a06aaf8944bc1254dec0c69ef9f32c8
[]
no_license
mobilechampion/Cieo-Home
https://github.com/mobilechampion/Cieo-Home
43b62cf1c499fd1446641b264629aac947d55740
d56c302e910c213bcb654092cda9de622f89a9bf
refs/heads/master
2020-06-25T04:59:41.784000
2017-06-10T07:33:44
2017-06-10T07:33:44
94,236,177
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kinetise.data.application.formdatautils; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class FormValidation { @SerializedName("dependencies") private List<String> dependencies; @SerializedName("rules") private List<FormValidationRule> rules; public FormValidation() { dependencies = new ArrayList<>(); rules = new ArrayList<>(); } public List<String> getDependencies() { return dependencies; } public void setDependencies(List<String> dependencies) { this.dependencies = dependencies; } public List<FormValidationRule> getRules() { return rules; } public void setRules(List<FormValidationRule> rules) { this.rules = rules; } public void addDependency(String dependency) { dependencies.add(dependency); } public void addRule(FormValidationRule rule) { rules.add(rule); } public FormValidation copy() { FormValidation copied = new FormValidation(); List<FormValidationRule> copiedRules = new ArrayList<>(); for (FormValidationRule rule : rules) { copiedRules.add(rule.copy()); } copied.setRules(copiedRules); copied.setDependencies(new ArrayList<>(dependencies)); return copied; } }
UTF-8
Java
1,382
java
FormValidation.java
Java
[]
null
[]
package com.kinetise.data.application.formdatautils; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class FormValidation { @SerializedName("dependencies") private List<String> dependencies; @SerializedName("rules") private List<FormValidationRule> rules; public FormValidation() { dependencies = new ArrayList<>(); rules = new ArrayList<>(); } public List<String> getDependencies() { return dependencies; } public void setDependencies(List<String> dependencies) { this.dependencies = dependencies; } public List<FormValidationRule> getRules() { return rules; } public void setRules(List<FormValidationRule> rules) { this.rules = rules; } public void addDependency(String dependency) { dependencies.add(dependency); } public void addRule(FormValidationRule rule) { rules.add(rule); } public FormValidation copy() { FormValidation copied = new FormValidation(); List<FormValidationRule> copiedRules = new ArrayList<>(); for (FormValidationRule rule : rules) { copiedRules.add(rule.copy()); } copied.setRules(copiedRules); copied.setDependencies(new ArrayList<>(dependencies)); return copied; } }
1,382
0.658466
0.658466
56
23.678572
20.957531
65
false
false
0
0
0
0
0
0
0.357143
false
false
13
a8f6bacd14338e5f6fa03b6cf165550671cda290
18,537,078,876,537
2fb6d3f64da22c0003cf298c50c63e8bf481da87
/kielet/venaja/numbers/NumberTest.java
d6264f07fab8d685f2d33084a4d4b1aab2024663
[ "MIT" ]
permissive
tkukka/VariousContent
https://github.com/tkukka/VariousContent
68c0b7b03bff02e54aba31fef6af94c250f21eeb
91b245fc9195ee6e8096e4f787d4ed29931a85f2
refs/heads/master
2023-04-09T13:03:25.279000
2023-03-21T11:15:01
2023-03-21T11:15:01
232,808,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class NumberTest { private int input; private String expected; @SuppressWarnings("boxing") @Parameters public static Collection<Object[]> data() { Object[][] o = new Object[][] { { 0, "ноль" }, { 1, "один" }, { 2, "два" }, { 3, "три" }, { 19, "девятнадцать" }, { 20, "двадцать" }, { 21, "двадцать один" }, { 29, "двадцать девять" }, { 30, "тридцать" }, { 31, "тридцать один" }, { 40, "сорок" }, { 50, "пятьдесят" }, { 52, "пятьдесят два" }, { 60, "шестьдесят" }, { 90, "девяносто" }, { 99, "девяносто девять" }, { 100, "сто" }, { 101, "сто один" }, { 110, "сто десять" }, { 119, "сто девятнадцать" }, { 120, "сто двадцать" }, { 121, "сто двадцать один" }, { 190, "сто девяносто" }, { 199, "сто девяносто девять" }, { 200, "двести" }, { 219, "двести девятнадцать" }, { 220, "двести двадцать" }, { 221, "двести двадцать один" }, { 299, "двести девяносто девять" }, { 300, "триста" }, { 400, "четыреста" }, { 500, "пятьсот" }, { 570, "пятьсот семьдесят" }, { 600, "шестьсот" }, { 700, "семьсот" }, { 800, "восемьсот" }, { 900, "девятьсот" }, { 901, "девятьсот один" }, { 911, "девятьсот одиннадцать" }, { 988, "девятьсот восемьдесят восемь" }, { 999, "девятьсот девяносто девять" }, { 1000, "одна тысяча" }, { 1001, "одна тысяча один" }, { 1002, "одна тысяча два" }, { 1099, "одна тысяча девяносто девять" }, { 1100, "одна тысяча сто" }, { 1101, "одна тысяча сто один" }, { 1125, "одна тысяча сто двадцать пять" }, { 2000, "две тысячи" }, { 2003, "две тысячи три" }, { 3003, "три тысячи три" }, { 5000, "пять тысяч" }, { 9999, "девять тысяч девятьсот девяносто девять" }, { 10000, "десять тысяч" }, { 19000, "девятнадцать тысяч" }, { 20000, "двадцать тысяч" }, { 20300, "двадцать тысяч триста" }, { 21000, "двадцать одна тысяча" }, { 22000, "двадцать две тысячи" }, { 23000, "двадцать три тысячи" }, { 25000, "двадцать пять тысяч" }, { 90000, "девяносто тысяч" }, { 100000, "сто тысяч" }, { 101000, "сто одна тысяча" }, { 102000, "сто две тысячи" }, { 105000, "сто пять тысяч" }, { 200000, "двести тысяч" }, { 291999, "двести девяносто одна тысяча девятьсот девяносто девять" }, { 299999, "двести девяносто девять тысяч девятьсот девяносто девять" }, { 300000, "триста тысяч" }, { 900000, "девятьсот тысяч" }, { 987000, "девятьсот восемьдесят семь тысяч" }, { 999999, "девятьсот девяносто девять тысяч девятьсот девяносто девять" }, { 1000000, "один миллион" }, { 1000001, "один миллион один" }, { 1002001, "один миллион две тысячи один" }, { 2000000, "два миллиона" }, { 2021019, "два миллиона двадцать одна тысяча девятнадцать" }, { 2021020, "два миллиона двадцать одна тысяча двадцать" }, { 2022045, "два миллиона двадцать две тысячи сорок пять" }, { 3000000, "три миллиона" }, { 3023045, "три миллиона двадцать три тысячи сорок пять" }, { 5000000, "пять миллионов" }, { 22000000, "двадцать два миллиона" }, { 23000000, "двадцать три миллиона" }, { 25000000, "двадцать пять миллионов" }, { 100000000, "сто миллионов" }, { 101000000, "сто один миллион" } }; return Arrays.asList(o); } public NumberTest(int in, String out) { input = in; expected = out; } @Test public void testDisplay() { assertEquals(expected, Number.Display(input)); } }
UTF-8
Java
6,389
java
NumberTest.java
Java
[]
null
[]
import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class NumberTest { private int input; private String expected; @SuppressWarnings("boxing") @Parameters public static Collection<Object[]> data() { Object[][] o = new Object[][] { { 0, "ноль" }, { 1, "один" }, { 2, "два" }, { 3, "три" }, { 19, "девятнадцать" }, { 20, "двадцать" }, { 21, "двадцать один" }, { 29, "двадцать девять" }, { 30, "тридцать" }, { 31, "тридцать один" }, { 40, "сорок" }, { 50, "пятьдесят" }, { 52, "пятьдесят два" }, { 60, "шестьдесят" }, { 90, "девяносто" }, { 99, "девяносто девять" }, { 100, "сто" }, { 101, "сто один" }, { 110, "сто десять" }, { 119, "сто девятнадцать" }, { 120, "сто двадцать" }, { 121, "сто двадцать один" }, { 190, "сто девяносто" }, { 199, "сто девяносто девять" }, { 200, "двести" }, { 219, "двести девятнадцать" }, { 220, "двести двадцать" }, { 221, "двести двадцать один" }, { 299, "двести девяносто девять" }, { 300, "триста" }, { 400, "четыреста" }, { 500, "пятьсот" }, { 570, "пятьсот семьдесят" }, { 600, "шестьсот" }, { 700, "семьсот" }, { 800, "восемьсот" }, { 900, "девятьсот" }, { 901, "девятьсот один" }, { 911, "девятьсот одиннадцать" }, { 988, "девятьсот восемьдесят восемь" }, { 999, "девятьсот девяносто девять" }, { 1000, "одна тысяча" }, { 1001, "одна тысяча один" }, { 1002, "одна тысяча два" }, { 1099, "одна тысяча девяносто девять" }, { 1100, "одна тысяча сто" }, { 1101, "одна тысяча сто один" }, { 1125, "одна тысяча сто двадцать пять" }, { 2000, "две тысячи" }, { 2003, "две тысячи три" }, { 3003, "три тысячи три" }, { 5000, "пять тысяч" }, { 9999, "девять тысяч девятьсот девяносто девять" }, { 10000, "десять тысяч" }, { 19000, "девятнадцать тысяч" }, { 20000, "двадцать тысяч" }, { 20300, "двадцать тысяч триста" }, { 21000, "двадцать одна тысяча" }, { 22000, "двадцать две тысячи" }, { 23000, "двадцать три тысячи" }, { 25000, "двадцать пять тысяч" }, { 90000, "девяносто тысяч" }, { 100000, "сто тысяч" }, { 101000, "сто одна тысяча" }, { 102000, "сто две тысячи" }, { 105000, "сто пять тысяч" }, { 200000, "двести тысяч" }, { 291999, "двести девяносто одна тысяча девятьсот девяносто девять" }, { 299999, "двести девяносто девять тысяч девятьсот девяносто девять" }, { 300000, "триста тысяч" }, { 900000, "девятьсот тысяч" }, { 987000, "девятьсот восемьдесят семь тысяч" }, { 999999, "девятьсот девяносто девять тысяч девятьсот девяносто девять" }, { 1000000, "один миллион" }, { 1000001, "один миллион один" }, { 1002001, "один миллион две тысячи один" }, { 2000000, "два миллиона" }, { 2021019, "два миллиона двадцать одна тысяча девятнадцать" }, { 2021020, "два миллиона двадцать одна тысяча двадцать" }, { 2022045, "два миллиона двадцать две тысячи сорок пять" }, { 3000000, "три миллиона" }, { 3023045, "три миллиона двадцать три тысячи сорок пять" }, { 5000000, "пять миллионов" }, { 22000000, "двадцать два миллиона" }, { 23000000, "двадцать три миллиона" }, { 25000000, "двадцать пять миллионов" }, { 100000000, "сто миллионов" }, { 101000000, "сто один миллион" } }; return Arrays.asList(o); } public NumberTest(int in, String out) { input = in; expected = out; } @Test public void testDisplay() { assertEquals(expected, Number.Display(input)); } }
6,389
0.447573
0.372878
131
37.221375
19.0797
90
false
false
0
0
0
0
0
0
1.458015
false
false
13
a01531cb266edd94021ad436554c59b576bde40d
12,506,944,806,171
cfc5ab6a71e8c81e09f9642c57f5012052f90f88
/app/src/main/java/br/com/desafioandroidconcrete/home/adapter/HomePresenterImplAdapter.java
2f31f6240e616e3f0e1b613c4f09c8275ddb5474
[]
no_license
Alison-Soldado/appGitHubApiJava
https://github.com/Alison-Soldado/appGitHubApiJava
0dc898995fee6711b391782bd6312c7900dc7f8b
301d8fff76904741827aa2bc54aaa9408608ea7f
refs/heads/master
2018-12-01T00:22:41.721000
2018-09-05T18:47:46
2018-09-05T18:47:46
111,001,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.desafioandroidconcrete.home.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import br.com.desafioandroidconcrete.R; import br.com.desafioandroidconcrete.home.adapter.viewHolder.HomeViewHolder; import br.com.desafioandroidconcrete.home.adapter.viewHolder.LoadingViewHolder; import br.com.desafioandroidconcrete.data.model.listRepository.Items; /** * Created by alison on 27/09/17. */ public class HomePresenterImplAdapter implements HomePresenterAdapter { private static final int ITEM = 0; private static final int LOADING = 1; private HomeViewAdapter homeViewAdapter; public HomePresenterImplAdapter(HomeViewAdapter homeViewAdapter) { this.homeViewAdapter = homeViewAdapter; } @Override public RecyclerView.ViewHolder switchViewHolderCreate(ViewGroup viewGroup, int viewType, LayoutInflater inflater, RecyclerView.ViewHolder viewHolder) { switch (viewType) { case ITEM: View viewItem = inflater.inflate(R.layout.item_home, viewGroup, false); viewHolder = new HomeViewHolder(viewItem); break; case LOADING: View viewLoading = inflater.inflate(R.layout.progress_footer, viewGroup, false); viewHolder = new LoadingViewHolder(viewLoading); break; } return viewHolder; } @Override public void switchHolderBind(RecyclerView.ViewHolder holder, int position, Items item) { switch (homeViewAdapter.getItemViewType(position)) { case ITEM: final HomeViewHolder homeViewHolder = (HomeViewHolder) holder; homeViewAdapter.setHomeViewHolder(homeViewHolder, item); break; case LOADING: LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder; homeViewAdapter.setLoadingViewHolder(loadingViewHolder); break; } } }
UTF-8
Java
2,067
java
HomePresenterImplAdapter.java
Java
[ { "context": "ata.model.listRepository.Items;\n\n/**\n * Created by alison on 27/09/17.\n */\n\npublic class HomePresenterImplA", "end": 487, "score": 0.9995375275611877, "start": 481, "tag": "USERNAME", "value": "alison" } ]
null
[]
package br.com.desafioandroidconcrete.home.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import br.com.desafioandroidconcrete.R; import br.com.desafioandroidconcrete.home.adapter.viewHolder.HomeViewHolder; import br.com.desafioandroidconcrete.home.adapter.viewHolder.LoadingViewHolder; import br.com.desafioandroidconcrete.data.model.listRepository.Items; /** * Created by alison on 27/09/17. */ public class HomePresenterImplAdapter implements HomePresenterAdapter { private static final int ITEM = 0; private static final int LOADING = 1; private HomeViewAdapter homeViewAdapter; public HomePresenterImplAdapter(HomeViewAdapter homeViewAdapter) { this.homeViewAdapter = homeViewAdapter; } @Override public RecyclerView.ViewHolder switchViewHolderCreate(ViewGroup viewGroup, int viewType, LayoutInflater inflater, RecyclerView.ViewHolder viewHolder) { switch (viewType) { case ITEM: View viewItem = inflater.inflate(R.layout.item_home, viewGroup, false); viewHolder = new HomeViewHolder(viewItem); break; case LOADING: View viewLoading = inflater.inflate(R.layout.progress_footer, viewGroup, false); viewHolder = new LoadingViewHolder(viewLoading); break; } return viewHolder; } @Override public void switchHolderBind(RecyclerView.ViewHolder holder, int position, Items item) { switch (homeViewAdapter.getItemViewType(position)) { case ITEM: final HomeViewHolder homeViewHolder = (HomeViewHolder) holder; homeViewAdapter.setHomeViewHolder(homeViewHolder, item); break; case LOADING: LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder; homeViewAdapter.setLoadingViewHolder(loadingViewHolder); break; } } }
2,067
0.694243
0.689889
57
35.263157
33.162823
155
false
false
0
0
0
0
0
0
0.631579
false
false
13
6b99c0b9315c6511823559b88e3257e28ca8cdb0
13,511,967,134,268
209f84e2a33c74fabd4589eb524dffa08d0209c0
/web.ui/src/test/java/collabware/web/cometd/CometdProtocolEndpointTest.java
b8b1946f6b74adf42f6454f330b9fd9a971a9be1
[ "MIT" ]
permissive
HotblackDesiato/collabware
https://github.com/HotblackDesiato/collabware
39fcd4dadd68a485a2f4d815d6ac3d132c5401c8
3fc4d6d9214d63cb6a9273720124e1fa0379601f
refs/heads/master
2016-09-05T23:04:17.035000
2014-04-06T13:29:09
2014-04-06T13:29:09
17,085,825
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package collabware.web.cometd; import static org.easymock.EasyMock.verify; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.cometd.bayeux.server.ServerMessage.Mutable; import org.cometd.bayeux.server.ServerSession; import org.cometd.server.ServerMessageImpl; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Ignore; import org.junit.Test; import collabware.api.operations.ComplexOperation; import collabware.collaboration.Collaboration; import collabware.collaboration.Participant; import collabware.model.ModifyableModel; import collabware.userManagement.User; import collabware.web.cometd.utils.ServerJsonProvider; import collabware.web.shared.OperationJsonizer; public class CometdProtocolEndpointTest extends AbstractCometdProtocolEndpointTest{ @Test public void joinNonexistingCollaboration() throws Exception { ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(false)); assertThat(message.getString("error"), is("No such collaboration.")); } }); server.join(remote, joinMessageForCollaboration("0815")); verify(remote); } @Test public void joinExistingCollaboration() throws Exception { final ModifyableModel model = modelFromLiteral("n1,n2,n1.foo=42,n1.bar->n2"); final Collaboration collaboration = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); assertThat(message.getJSONObject("initSequence"), reconstructs(model)); assertEquals(message.getJSONObject("localParticipant"), loggedInUser); assertEquals(message.getJSONArray("participants"), collaboration.getParticipants()); } }); server.join(remote, joinMessageForCollaboration(collaboration)); verify(remote); } private void assertEquals(JSONArray jsonAllParticipants, List<Participant> participants) throws JSONException { assertThat(jsonAllParticipants.length(), is(participants.size())); for (int i = 0; i < participants.size(); i++) { assertEquals(jsonAllParticipants.getJSONObject(i), participants.get(i).getUser()); } } private void assertEquals(JSONObject localParticipant, User user) throws JSONException { assertThat(localParticipant.getString("displayName"), is(user.getDisplayName())); assertThat(localParticipant.getString("id"), is(user.getUserName())); assertThat(localParticipant.getString("imageUrl"), is("/collabware/images/"+user.getUserName()+".png")); } @Test public void apply() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }} , new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }} ); server.join(remote, joinMessageForCollaboration(col)); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(remote); } @Test @Ignore public void applyWithoutJoin() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getBoolean("successful"), is(false)); assertThat(message.getString("error"), is("Join first.")); } }); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1")); verify(remote); } @Test public void multipleApply() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(2)); } }); server.join(remote, joinMessageForCollaboration(col)); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n3") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2,n3")); verify(remote); } @Test public void applyAndBroadcast() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n2") )).toString())); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Test public void multipleApplyAndBroadcast() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(2)); }}); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n2") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n3") )).toString())); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n3") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2,n3")); verify(activeRemote, passiveRemote); } @Test @Ignore public void applyConflictingOperation() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( id())).toString())); }}); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "attr", null, "42") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); } }); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "42") ) )); server.applyClientChange(passiveRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "foobar") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n1.attr='42'")); verify(activeRemote, passiveRemote); } @Test public void applyConcurrentOperations() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "foo", null, "bar") )).toString())); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "attr", null, "42") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "42") ) )); server.applyClientChange(passiveRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "foo", null, "bar") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n1.attr='42',n1.foo='bar'")); verify(activeRemote, passiveRemote); } protected JSONObject serialize(ComplexOperation complex) { OperationJsonizer<JSONObject,JSONArray> jsonizer = new OperationJsonizer<JSONObject,JSONArray>(new ServerJsonProvider()); return jsonizer.jsonize(complex); } @Test public void leaveCollaboration() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.leave(passiveRemote, leaveMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Test public void leaveCollaborationAfterTimeout() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.removed(passiveRemote, true); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Ignore @Test public void joinDifferentCollaborationsWithSameRemote() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col1 = createCollaborationWithModel(model); Collaboration col2 = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col1)); server.join(passiveRemote, joinMessageForCollaboration(col1)); server.join(passiveRemote, joinMessageForCollaboration(col2)); server.applyClientChange(activeRemote, messageWithOperation(col1.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col1.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } private Mutable leaveMessageForCollaboration(Collaboration col) { Mutable message = new ServerMessageImpl(); message.setChannel("/service/leave/" + col.getId()); return message; } }
UTF-8
Java
20,327
java
CometdProtocolEndpointTest.java
Java
[]
null
[]
package collabware.web.cometd; import static org.easymock.EasyMock.verify; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.cometd.bayeux.server.ServerMessage.Mutable; import org.cometd.bayeux.server.ServerSession; import org.cometd.server.ServerMessageImpl; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Ignore; import org.junit.Test; import collabware.api.operations.ComplexOperation; import collabware.collaboration.Collaboration; import collabware.collaboration.Participant; import collabware.model.ModifyableModel; import collabware.userManagement.User; import collabware.web.cometd.utils.ServerJsonProvider; import collabware.web.shared.OperationJsonizer; public class CometdProtocolEndpointTest extends AbstractCometdProtocolEndpointTest{ @Test public void joinNonexistingCollaboration() throws Exception { ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(false)); assertThat(message.getString("error"), is("No such collaboration.")); } }); server.join(remote, joinMessageForCollaboration("0815")); verify(remote); } @Test public void joinExistingCollaboration() throws Exception { final ModifyableModel model = modelFromLiteral("n1,n2,n1.foo=42,n1.bar->n2"); final Collaboration collaboration = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); assertThat(message.getJSONObject("initSequence"), reconstructs(model)); assertEquals(message.getJSONObject("localParticipant"), loggedInUser); assertEquals(message.getJSONArray("participants"), collaboration.getParticipants()); } }); server.join(remote, joinMessageForCollaboration(collaboration)); verify(remote); } private void assertEquals(JSONArray jsonAllParticipants, List<Participant> participants) throws JSONException { assertThat(jsonAllParticipants.length(), is(participants.size())); for (int i = 0; i < participants.size(); i++) { assertEquals(jsonAllParticipants.getJSONObject(i), participants.get(i).getUser()); } } private void assertEquals(JSONObject localParticipant, User user) throws JSONException { assertThat(localParticipant.getString("displayName"), is(user.getDisplayName())); assertThat(localParticipant.getString("id"), is(user.getUserName())); assertThat(localParticipant.getString("imageUrl"), is("/collabware/images/"+user.getUserName()+".png")); } @Test public void apply() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }} , new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }} ); server.join(remote, joinMessageForCollaboration(col)); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(remote); } @Test @Ignore public void applyWithoutJoin() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getBoolean("successful"), is(false)); assertThat(message.getString("error"), is("Join first.")); } }); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1")); verify(remote); } @Test public void multipleApply() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession remote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(2)); } }); server.join(remote, joinMessageForCollaboration(col)); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); server.applyClientChange(remote, messageWithOperation(col.getId(), complex( addNode("n3") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2,n3")); verify(remote); } @Test public void applyAndBroadcast() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n2") )).toString())); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Test public void multipleApplyAndBroadcast() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(2)); }}); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n2") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( addNode("n3") )).toString())); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n3") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2,n3")); verify(activeRemote, passiveRemote); } @Test @Ignore public void applyConflictingOperation() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( id())).toString())); }}); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "attr", null, "42") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); } }); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "42") ) )); server.applyClientChange(passiveRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "foobar") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n1.attr='42'")); verify(activeRemote, passiveRemote); } @Test public void applyConcurrentOperations() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "foo", null, "bar") )).toString())); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/update")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(0)); assertThat(message.getJSONObject(OPERATION).toString(), is(serialize(complex( updAttr("n1", "attr", null, "42") )).toString())); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(1)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "attr", null, "42") ) )); server.applyClientChange(passiveRemote, messageWithOperation(col.getId(), complex( updAttr("n1", "foo", null, "bar") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n1.attr='42',n1.foo='bar'")); verify(activeRemote, passiveRemote); } protected JSONObject serialize(ComplexOperation complex) { OperationJsonizer<JSONObject,JSONArray> jsonizer = new OperationJsonizer<JSONObject,JSONArray>(new ServerJsonProvider()); return jsonizer.jsonize(complex); } @Test public void leaveCollaboration() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.leave(passiveRemote, leaveMessageForCollaboration(col)); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Test public void leaveCollaborationAfterTimeout() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col)); server.join(passiveRemote, joinMessageForCollaboration(col)); server.removed(passiveRemote, true); server.applyClientChange(activeRemote, messageWithOperation(col.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } @Ignore @Test public void joinDifferentCollaborationsWithSameRemote() throws Exception { final ModifyableModel model = modelFromLiteral("n1"); Collaboration col1 = createCollaborationWithModel(model); Collaboration col2 = createCollaborationWithModel(model); ServerSession activeRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/acknowledge")); assertThat(message.getInt(SERVER_SEQUENCE_NUMBER), is(0)); assertThat(message.getInt(CLIENT_SEQUENCE_NUMBER), is(1)); } }); ServerSession passiveRemote = mockRemoteSession(new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}, new ExpectedMessage() { public void expect(String channel, JSONObject message) throws Exception { assertThat(channel, is("/initialize")); assertThat(message.getBoolean("successful"), is(true)); }}); server.join(activeRemote, joinMessageForCollaboration(col1)); server.join(passiveRemote, joinMessageForCollaboration(col1)); server.join(passiveRemote, joinMessageForCollaboration(col2)); server.applyClientChange(activeRemote, messageWithOperation(col1.getId(), complex( addNode("n2") ) )); assertCollaborationHasModel(col1.getId(), modelFromLiteral("n1,n2")); verify(activeRemote, passiveRemote); } private Mutable leaveMessageForCollaboration(Collaboration col) { Mutable message = new ServerMessageImpl(); message.setChannel("/service/leave/" + col.getId()); return message; } }
20,327
0.739657
0.733606
458
43.382095
32.057335
133
false
false
0
0
0
0
0
0
3.703057
false
false
13
82214cbd9d5a9dd2629d8ea1c29a2a4bb3ba0b03
26,920,855,051,496
0798fc85a4b123c1c53f6b4c34b49786163f8dea
/src/main/java/com/example/voter/model/CityMV.java
2d28c6a2fe59fb074b27b4cb64fadba514fb1582
[]
no_license
gauravjestha3/VoterEnrollment-Using-SpringJpa
https://github.com/gauravjestha3/VoterEnrollment-Using-SpringJpa
5dae8cf012be2e4e417b29cf34e280ee2f450216
5a4948831003163843da085c02d5333f69df2c21
refs/heads/master
2020-03-28T23:03:06.968000
2018-09-18T10:59:16
2018-09-18T10:59:16
149,273,391
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.voter.model; /** * @author gaurav * */ public class CityMV { private Long cityId; private String cityName; public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } }
UTF-8
Java
380
java
CityMV.java
Java
[ { "context": "package com.example.voter.model;\n\n/**\n * @author gaurav\n *\n */\npublic class CityMV {\n\tprivate Long cityId", "end": 55, "score": 0.8806774020195007, "start": 49, "tag": "USERNAME", "value": "gaurav" } ]
null
[]
package com.example.voter.model; /** * @author gaurav * */ public class CityMV { private Long cityId; private String cityName; public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } }
380
0.689474
0.689474
27
13.111111
13.403519
43
false
false
0
0
0
0
0
0
0.962963
false
false
13
841b9374d271ecca95d714a3908adc98a44d39e2
13,726,715,532,660
296b44cb25b9471cd2e623b1cab3be6b17e2dfa9
/consul/consul-name/src/main/java/com/wanzi/consul/NameController.java
f6a2f9be3a97cdcb7d4e39d8c9b08aceee4e5223
[]
no_license
zhangyuyu/Spring-Cloud
https://github.com/zhangyuyu/Spring-Cloud
315371e8434b3c64f536aaed17f3e3812b36a5e4
0f19458251acd00e3b5081b71efa39c91932ceb1
refs/heads/master
2020-12-25T18:52:07.508000
2017-06-26T12:33:30
2017-06-28T08:12:19
93,996,099
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wanzi.consul; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/wanzi") public class NameController { @GetMapping public String getName(@RequestParam String name) { return "Hi ,I'm " + name; } @GetMapping("/health") public String health() { return "OK"; } }
UTF-8
Java
544
java
NameController.java
Java
[]
null
[]
package com.wanzi.consul; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/wanzi") public class NameController { @GetMapping public String getName(@RequestParam String name) { return "Hi ,I'm " + name; } @GetMapping("/health") public String health() { return "OK"; } }
544
0.735294
0.735294
21
24.904762
21.913042
62
false
false
0
0
0
0
0
0
0.380952
false
false
13
6b562dadce08f6357a586ef72c6261c2b5b17336
30,520,037,654,251
0c65f879cdf8858b9e931bb9a3a914cc76307685
/src/main/java/ch/alpine/sophus/hs/sn/SnAction.java
100d5c4a2c33673ef2d37934f3c9226e5ddebe3b
[]
no_license
datahaki/sophus
https://github.com/datahaki/sophus
b9674f6e4068d907f8667fb546398fc0dbb5abc6
cedce627452a70beed13ee2031a1cf98a413c2a7
refs/heads/master
2023-08-16T23:45:40.252000
2023-08-09T17:46:17
2023-08-09T17:46:17
232,996,526
3
0
null
false
2022-06-08T22:39:06
2020-01-10T08:02:55
2021-11-27T15:17:50
2022-06-08T22:39:06
11,231
2
0
0
Java
false
false
// code by jph package ch.alpine.sophus.hs.sn; import ch.alpine.tensor.Tensor; import ch.alpine.tensor.api.TensorUnaryOperator; /** formula generalized from * "Rotation Between Two Vectors in R^3" * by Ethan Eade */ public class SnAction implements TensorUnaryOperator { private final Tensor g; public SnAction(Tensor g) { this.g = g; } @Override public Tensor apply(Tensor p) { return g.dot(p); } }
UTF-8
Java
426
java
SnAction.java
Java
[ { "context": "// code by jph\npackage ch.alpine.sophus.hs.sn;\n\nimport ch.alpine", "end": 14, "score": 0.9851722717285156, "start": 11, "tag": "USERNAME", "value": "jph" }, { "context": "rom\n * \"Rotation Between Two Vectors in R^3\"\n * by Ethan Eade */\npublic class SnAction implements TensorUnaryOp", "end": 216, "score": 0.9998980760574341, "start": 206, "tag": "NAME", "value": "Ethan Eade" } ]
null
[]
// code by jph package ch.alpine.sophus.hs.sn; import ch.alpine.tensor.Tensor; import ch.alpine.tensor.api.TensorUnaryOperator; /** formula generalized from * "Rotation Between Two Vectors in R^3" * by <NAME> */ public class SnAction implements TensorUnaryOperator { private final Tensor g; public SnAction(Tensor g) { this.g = g; } @Override public Tensor apply(Tensor p) { return g.dot(p); } }
422
0.706573
0.704225
21
19.285715
16.31868
54
false
false
0
0
0
0
0
0
0.285714
false
false
13
4a9fb2529690750ffb594345596a2a86f4112365
22,282,290,341,629
caac7d16de30402495d50b3eeec77436e5167c77
/SensoryTurtlesClient/src/it/framework/core/service/enums/ErrorTypeEnum.java
18ca563b0aa2ac00cbb99cf0c5e01d17a1096960
[]
no_license
faro1976/latartaruga
https://github.com/faro1976/latartaruga
f56643182cf13d6927ef8458b7ff3056bd3bd286
d677c76369a333d09da73c0bc2f1b29ddbc9dc96
refs/heads/master
2018-02-10T23:34:46.925000
2017-02-17T15:48:23
2017-02-17T15:48:23
61,433,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.framework.core.service.enums; public class ErrorTypeEnum { public static final String RUNTIME = "RUNTIME"; public static final String OPERATION = "OPERATION"; public static final String BUSINESS = "BUSINESS"; public static final String VALIDATION = "VALIDATION"; public static final String CONSTRAINT = "CONSTRAINT"; public static final String SECURITY = "SECURITY"; public static final String DATA_SOURCE = "DATA_SOURCE"; }
UTF-8
Java
455
java
ErrorTypeEnum.java
Java
[]
null
[]
package it.framework.core.service.enums; public class ErrorTypeEnum { public static final String RUNTIME = "RUNTIME"; public static final String OPERATION = "OPERATION"; public static final String BUSINESS = "BUSINESS"; public static final String VALIDATION = "VALIDATION"; public static final String CONSTRAINT = "CONSTRAINT"; public static final String SECURITY = "SECURITY"; public static final String DATA_SOURCE = "DATA_SOURCE"; }
455
0.753846
0.753846
11
39.363636
19.809423
56
false
false
0
0
0
0
0
0
1.363636
false
false
13
c1cfa59a0cac2062a0376527ce663b2c4a2e4aa5
29,411,936,104,257
a291b69b5f08e108cc5035bab41d9d3e8854132d
/src/main/java/com/firstline/repos/StudyRepository.java
162f59da87c88b07e2844ce1ca88bb92e8a15bfa
[]
no_license
AleksandrAbashin/procedureSchedulingWebApp
https://github.com/AleksandrAbashin/procedureSchedulingWebApp
3901047496a115d5f17cf16db92c629a891433a1
93d9b7916ab53930c1dc4c4872ad43f2355002f0
refs/heads/master
2021-10-08T10:33:03.386000
2018-12-11T08:55:00
2018-12-11T08:55:00
154,329,138
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.firstline.repos; import com.firstline.domain.Study; import org.springframework.data.jpa.repository.JpaRepository; public interface StudyRepository extends JpaRepository<Study, Long> { Study getById(Long id); }
UTF-8
Java
233
java
StudyRepository.java
Java
[]
null
[]
package com.firstline.repos; import com.firstline.domain.Study; import org.springframework.data.jpa.repository.JpaRepository; public interface StudyRepository extends JpaRepository<Study, Long> { Study getById(Long id); }
233
0.7897
0.7897
13
16.923077
23.905138
69
false
false
0
0
0
0
0
0
0.384615
false
false
13
fc27d6903a44159f0b8a04ba11074f88d9534c0a
18,545,668,818,052
ed11ba341c3daf67f5a1d07a8babe99917b9b790
/src/main/java/com/flow/enginehouse/service/impl/AppServiceImpl.java
5ece21a072e2e44b7434097a1fc2c8bb44b43891
[]
no_license
wobblewedge/engine-house
https://github.com/wobblewedge/engine-house
67f01009ca1d4a4379191b7d50f2b020a34543d5
ab4b3b081238c6c26e5e5a9bcefc339b2a077d37
refs/heads/master
2020-06-10T19:27:43.433000
2019-08-21T13:17:37
2019-08-21T13:17:37
193,722,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.flow.enginehouse.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.flowable.engine.runtime.ProcessInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import com.flow.enginehouse.converter.ApplicantConverter; import com.flow.enginehouse.dto.ApplicantDto; import com.flow.enginehouse.entity.Applicant; import com.flow.enginehouse.entity.ApplicantRepository; import com.flow.enginehouse.entity.ApplicationProcess; import com.flow.enginehouse.service.AppService; import com.flow.enginehouse.service.ProcessWorkflowService; @Service public class AppServiceImpl implements AppService { @Autowired ApplicantRepository applicantRepo; @Autowired private ProcessWorkflowService service; @Override public Map<String,Object> saveUser(ApplicantDto applicantDto) { Map<String,Object> details = new HashMap<>(); if(applicantDto==null) { throw new ResourceNotFoundException("Empty Request Body Not Allowed"); }else { Applicant applicant = applicantRepo.save(ApplicantConverter.dtoToEntity(applicantDto)); service.manageDeployment(); ProcessInstance instance = service.startProcess(applicant); //applicant.getApplications().add(new ApplicationProcess(instance.getProcessInstanceId())); Map<String,Object> vars = new HashMap<>(instance.getProcessVariables()); String applicantId = applicant.getUserId().toString(); applicant = applicantRepo.getOne(Long.valueOf(applicantId)); details.put("Applicant Info:" , applicant); return details; } } //NEED TO DO @Override public List<ApplicantDto> getAllUsers() { //stream all applicants in repo into a return applicantRepo.findAll().stream().map(ApplicantConverter::entityToDto).collect(Collectors.toList()); } @Override public ApplicantDto getApplicantById(Long id) { return ApplicantConverter.entityToDto(applicantRepo.getOne(id)); } }
UTF-8
Java
2,062
java
AppServiceImpl.java
Java
[]
null
[]
package com.flow.enginehouse.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.flowable.engine.runtime.ProcessInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import com.flow.enginehouse.converter.ApplicantConverter; import com.flow.enginehouse.dto.ApplicantDto; import com.flow.enginehouse.entity.Applicant; import com.flow.enginehouse.entity.ApplicantRepository; import com.flow.enginehouse.entity.ApplicationProcess; import com.flow.enginehouse.service.AppService; import com.flow.enginehouse.service.ProcessWorkflowService; @Service public class AppServiceImpl implements AppService { @Autowired ApplicantRepository applicantRepo; @Autowired private ProcessWorkflowService service; @Override public Map<String,Object> saveUser(ApplicantDto applicantDto) { Map<String,Object> details = new HashMap<>(); if(applicantDto==null) { throw new ResourceNotFoundException("Empty Request Body Not Allowed"); }else { Applicant applicant = applicantRepo.save(ApplicantConverter.dtoToEntity(applicantDto)); service.manageDeployment(); ProcessInstance instance = service.startProcess(applicant); //applicant.getApplications().add(new ApplicationProcess(instance.getProcessInstanceId())); Map<String,Object> vars = new HashMap<>(instance.getProcessVariables()); String applicantId = applicant.getUserId().toString(); applicant = applicantRepo.getOne(Long.valueOf(applicantId)); details.put("Applicant Info:" , applicant); return details; } } //NEED TO DO @Override public List<ApplicantDto> getAllUsers() { //stream all applicants in repo into a return applicantRepo.findAll().stream().map(ApplicantConverter::entityToDto).collect(Collectors.toList()); } @Override public ApplicantDto getApplicantById(Long id) { return ApplicantConverter.entityToDto(applicantRepo.getOne(id)); } }
2,062
0.799224
0.799224
60
33.366665
28.010693
108
false
false
0
0
0
0
0
0
1.383333
false
false
13
e4876016abb018ac6a776579911aefb5dd3fc3d1
17,179,869,208,183
76c568f65cc40f200680082a464b94cdb75accd6
/src/homework/MaxAndMin.java
7a4a068227c3081bd25ff5c1fe602cefc22cf06d
[]
no_license
allaivanova1989/homework15.09
https://github.com/allaivanova1989/homework15.09
6c0edcea635d015ddc4011cf8e23e70c168af113
9d63a99700f1ddd123c47e82206a8047678c6ca0
refs/heads/master
2023-07-29T03:12:10.357000
2021-09-15T09:19:27
2021-09-15T09:19:27
406,689,768
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package homework; public class MaxAndMin { public void searchMinAndMax() { int[] array = {6, -63, 55, -100, 0, 17, 201}; int min = array[0]; int max = array[0]; int sum = 0; for (int i = 0; i < array.length - 1; i++) { if (array[i + 1] < min) { min = array[i + 1]; } } for (int i = 0; i < array.length - 1; i++) { if (array[i + 1] > max) { max = array[i + 1]; } } sum += min + max; System.out.println(sum); } }
UTF-8
Java
582
java
MaxAndMin.java
Java
[]
null
[]
package homework; public class MaxAndMin { public void searchMinAndMax() { int[] array = {6, -63, 55, -100, 0, 17, 201}; int min = array[0]; int max = array[0]; int sum = 0; for (int i = 0; i < array.length - 1; i++) { if (array[i + 1] < min) { min = array[i + 1]; } } for (int i = 0; i < array.length - 1; i++) { if (array[i + 1] > max) { max = array[i + 1]; } } sum += min + max; System.out.println(sum); } }
582
0.393471
0.350515
24
23.25
16.525864
53
false
false
0
0
0
0
0
0
0.791667
false
false
13
473995687fd199c0dc2266cc50a1710ad44bda67
755,914,290,516
965caccaba5282205a38c55b192ce9a2be5c4623
/src/main/java/com/github/yftx/test/ui/TestAutoCompleteDemo.java
f22b2d788495f42f11dfd162fbae68d006e16c1e
[]
no_license
yftx/test4Android
https://github.com/yftx/test4Android
ba20378332d3ff6ffba1c6f0858f6bb1492b1682
a901d247891ab22f19bbd52cf17037bb013dcece
refs/heads/master
2021-01-01T18:11:47.963000
2013-01-27T16:28:16
2013-01-27T16:28:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.yftx.test.ui; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.*; import com.github.kevinsawicki.wishlist.ViewFinder; import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockActivity; import com.github.yftx.test.R; import com.github.yftx.test.utils.InfoUtils; import com.github.yftx.test.utils.LogUtils; import com.github.yftx.test.utils.task.GenericTask; import com.github.yftx.test.utils.task.TaskParams; import com.github.yftx.test.utils.task.TaskResult; import com.google.common.collect.Lists; import com.google.inject.Inject; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import roboguice.util.RoboAsyncTask; import java.util.List; /** * 演示自动提示输入框的使用 * * @author yftx.net@gmail.com */ @ContentView(R.layout.auto_complete_activity) public class TestAutoCompleteDemo extends RoboSherlockActivity { public static List<String> datas = Lists.newArrayList(); static { datas.add("a"); datas.add("ab"); datas.add("abc"); datas.add("abcd"); datas.add("abcdef"); datas.add("abcdefg"); datas.add("abcdefgh"); datas.add("abcdefghi"); datas.add("abcdefghijk"); datas.add("abcdefghijkl"); } @InjectView(R.id.act_one) AutoCompleteTextView actOne; @InjectView(R.id.act_two) AutoCompleteTextView actTwo; CustomAutoCompleteAdapter customAutoCompleteAdapter; @Inject InputMethodManager imm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //避免在AsyncTask 中提示sending message to a Handler on a dead thread 警告 //bug of AsyncTask //link: http://stackoverflow.com/questions/7320036/asynctask-in-broadcastreceiver-in-android-gives-sending-message-to-a-handler-on try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { } // 代码获取InputMethodManager的方式 // imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //检索本地内容 actOne.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, datas)); //检索网络上的内容 customAutoCompleteAdapter = new CustomAutoCompleteAdapter(getLayoutInflater(), this); actTwo.setAdapter(customAutoCompleteAdapter); actTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (imm.isActive()) { //隐藏软键盘,传入的windowToken需要为触发软件盘所在的view imm.hideSoftInputFromWindow(actTwo.getWindowToken(), 0); } String itemContent = (String) parent.getAdapter().getItem(position); InfoUtils.showMsgShort(itemContent); } }); } } class CustomAutoCompleteAdapter extends BaseAdapter implements Filterable { ViewFinder finder; CustomFilter customFilter; GetTipsTask getTipsTask; static class ViewHolder { TextView textView; } List<String> tempDatas = Lists.newArrayList(); private final LayoutInflater inflater; CustomAutoCompleteAdapter(LayoutInflater inflater, Context context) { this.inflater = inflater; } public void freshAdapterData(List<String> datas) { tempDatas.clear(); tempDatas.addAll(datas); notifyDataSetChanged(); } @Override public int getCount() { return tempDatas.size(); } @Override public Object getItem(int position) { return tempDatas.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View view; if (convertView != null) { view = convertView; holder = (ViewHolder) convertView.getTag(); } else { view = inflater.inflate(R.layout.auto_complete_item, null); finder = new ViewFinder(view); holder = new ViewHolder(); holder.textView = finder.find(R.id.tv_content); view.setTag(holder); } holder.textView.setText((String) getItem(position)); return view; } @Override public Filter getFilter() { if (customFilter == null) { customFilter = new CustomFilter(); } return customFilter; } private class CustomFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { LogUtils.debug("当前输入的字符为 --> " + prefix.toString()); if (getTipsTask != null && getTipsTask.getStatus().equals(AsyncTask.Status.RUNNING)) { getTipsTask.cancel(true); } getTipsTask = new GetTipsTask(prefix.toString()); getTipsTask.execute(); return null; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { } } private class GetTipsTask extends GenericTask { String prefix = ""; List<String> tempData = Lists.newArrayList(); private GetTipsTask(String prefix) { this.prefix = prefix; } @Override protected TaskResult _doInBackground(TaskParams... params) { try { Thread.sleep(500); } catch (InterruptedException e) { } for (int i = 0; i < 5; i++) { tempData.add(prefix + i); } return TaskResult.OK; } @Override protected void onPostExecute(TaskResult result) { freshAdapterData(tempData); } } }
UTF-8
Java
6,269
java
TestAutoCompleteDemo.java
Java
[ { "context": "ger;\nimport android.widget.*;\nimport com.github.kevinsawicki.wishlist.ViewFinder;\nimport com.github.rtyl", "end": 315, "score": 0.5955178141593933, "start": 311, "tag": "USERNAME", "value": "vins" }, { "context": "vinsawicki.wishlist.ViewFinder;\nimport com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockA", "end": 367, "score": 0.9571458697319031, "start": 361, "tag": "USERNAME", "value": "rtyley" }, { "context": "java.util.List;\n\n/**\n * 演示自动提示输入框的使用\n *\n * @author yftx.net@gmail.com\n */\n\n\n@ContentView(R.layout.auto_complete_activit", "end": 960, "score": 0.9999246597290039, "start": 942, "tag": "EMAIL", "value": "yftx.net@gmail.com" } ]
null
[]
package com.github.yftx.test.ui; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.*; import com.github.kevinsawicki.wishlist.ViewFinder; import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockActivity; import com.github.yftx.test.R; import com.github.yftx.test.utils.InfoUtils; import com.github.yftx.test.utils.LogUtils; import com.github.yftx.test.utils.task.GenericTask; import com.github.yftx.test.utils.task.TaskParams; import com.github.yftx.test.utils.task.TaskResult; import com.google.common.collect.Lists; import com.google.inject.Inject; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import roboguice.util.RoboAsyncTask; import java.util.List; /** * 演示自动提示输入框的使用 * * @author <EMAIL> */ @ContentView(R.layout.auto_complete_activity) public class TestAutoCompleteDemo extends RoboSherlockActivity { public static List<String> datas = Lists.newArrayList(); static { datas.add("a"); datas.add("ab"); datas.add("abc"); datas.add("abcd"); datas.add("abcdef"); datas.add("abcdefg"); datas.add("abcdefgh"); datas.add("abcdefghi"); datas.add("abcdefghijk"); datas.add("abcdefghijkl"); } @InjectView(R.id.act_one) AutoCompleteTextView actOne; @InjectView(R.id.act_two) AutoCompleteTextView actTwo; CustomAutoCompleteAdapter customAutoCompleteAdapter; @Inject InputMethodManager imm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //避免在AsyncTask 中提示sending message to a Handler on a dead thread 警告 //bug of AsyncTask //link: http://stackoverflow.com/questions/7320036/asynctask-in-broadcastreceiver-in-android-gives-sending-message-to-a-handler-on try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { } // 代码获取InputMethodManager的方式 // imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //检索本地内容 actOne.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, datas)); //检索网络上的内容 customAutoCompleteAdapter = new CustomAutoCompleteAdapter(getLayoutInflater(), this); actTwo.setAdapter(customAutoCompleteAdapter); actTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (imm.isActive()) { //隐藏软键盘,传入的windowToken需要为触发软件盘所在的view imm.hideSoftInputFromWindow(actTwo.getWindowToken(), 0); } String itemContent = (String) parent.getAdapter().getItem(position); InfoUtils.showMsgShort(itemContent); } }); } } class CustomAutoCompleteAdapter extends BaseAdapter implements Filterable { ViewFinder finder; CustomFilter customFilter; GetTipsTask getTipsTask; static class ViewHolder { TextView textView; } List<String> tempDatas = Lists.newArrayList(); private final LayoutInflater inflater; CustomAutoCompleteAdapter(LayoutInflater inflater, Context context) { this.inflater = inflater; } public void freshAdapterData(List<String> datas) { tempDatas.clear(); tempDatas.addAll(datas); notifyDataSetChanged(); } @Override public int getCount() { return tempDatas.size(); } @Override public Object getItem(int position) { return tempDatas.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View view; if (convertView != null) { view = convertView; holder = (ViewHolder) convertView.getTag(); } else { view = inflater.inflate(R.layout.auto_complete_item, null); finder = new ViewFinder(view); holder = new ViewHolder(); holder.textView = finder.find(R.id.tv_content); view.setTag(holder); } holder.textView.setText((String) getItem(position)); return view; } @Override public Filter getFilter() { if (customFilter == null) { customFilter = new CustomFilter(); } return customFilter; } private class CustomFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { LogUtils.debug("当前输入的字符为 --> " + prefix.toString()); if (getTipsTask != null && getTipsTask.getStatus().equals(AsyncTask.Status.RUNNING)) { getTipsTask.cancel(true); } getTipsTask = new GetTipsTask(prefix.toString()); getTipsTask.execute(); return null; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { } } private class GetTipsTask extends GenericTask { String prefix = ""; List<String> tempData = Lists.newArrayList(); private GetTipsTask(String prefix) { this.prefix = prefix; } @Override protected TaskResult _doInBackground(TaskParams... params) { try { Thread.sleep(500); } catch (InterruptedException e) { } for (int i = 0; i < 5; i++) { tempData.add(prefix + i); } return TaskResult.OK; } @Override protected void onPostExecute(TaskResult result) { freshAdapterData(tempData); } } }
6,258
0.635666
0.633219
211
28.042654
24.724319
138
false
false
0
0
0
0
0
0
0.473934
false
false
13
c2271fb0901f5fcb727854050a95218758518e92
12,008,728,605,477
28d16729c5080400cd8d804c571bdb4e22687147
/src/main/java/com/revature/quizzard/dtos/AccountRegisterDTO.java
e6405750390eb1860b9de584cb041bdfedd4c770
[]
no_license
LiquidPlummer/quizzard-api
https://github.com/LiquidPlummer/quizzard-api
54edf2b5c6e68e307127911e1589570c95869623
0f174b81a859c7d00be5141b84107954b4561907
refs/heads/main
2023-06-14T20:45:55.288000
2021-07-02T15:54:30
2021-07-02T15:54:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.revature.quizzard.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public @Data class AccountRegisterDTO { String username; String password; String email; String firstName; String lastName; }
UTF-8
Java
309
java
AccountRegisterDTO.java
Java
[]
null
[]
package com.revature.quizzard.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public @Data class AccountRegisterDTO { String username; String password; String email; String firstName; String lastName; }
309
0.779935
0.779935
15
19.6
11.757551
39
false
false
0
0
0
0
0
0
0.6
false
false
13
83e035cf31aac1bae81524792ab5550c5b0a0f8e
26,912,265,086,486
7b2e79662381a58319d65f70bf978368de36b383
/sleep/src/main/java/com/cz/yingpu/frame/util/ResourceUtils2.java
12c53733d07006823b50e2b484833d767642ebd7
[]
no_license
exceptiondc/sleep
https://github.com/exceptiondc/sleep
1e8efbc3226b56847bb8aa901be9c483762edd3e
928ccb1de24bf5bc416db4b325fe76054639eb67
refs/heads/master
2022-07-06T23:48:44.140000
2022-06-22T07:06:08
2022-06-22T07:06:08
130,443,892
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cz.yingpu.frame.util; import java.util.Properties; public class ResourceUtils2 { private static Properties Properties; public ResourceUtils2() { } /* static { Properties = new Properties(); try { Properties.load(new FileInputStream( ClassLoader.getSystemClassLoader().getResource("SystemComfig.properties").getPath())); } catch(Exception e) { e.printStackTrace(); } }*/ /** * 根据key获得对应的value * * @param strPropertyName * key * @return String */ public static String getString(String strPropertyName) { try { return Properties.getProperty(strPropertyName); } catch (Exception e) { return strPropertyName; } } public static void main(String[] args) { System.out.print(ResourceUtils2.getString("templatepath")); } }
UTF-8
Java
861
java
ResourceUtils2.java
Java
[]
null
[]
package com.cz.yingpu.frame.util; import java.util.Properties; public class ResourceUtils2 { private static Properties Properties; public ResourceUtils2() { } /* static { Properties = new Properties(); try { Properties.load(new FileInputStream( ClassLoader.getSystemClassLoader().getResource("SystemComfig.properties").getPath())); } catch(Exception e) { e.printStackTrace(); } }*/ /** * 根据key获得对应的value * * @param strPropertyName * key * @return String */ public static String getString(String strPropertyName) { try { return Properties.getProperty(strPropertyName); } catch (Exception e) { return strPropertyName; } } public static void main(String[] args) { System.out.print(ResourceUtils2.getString("templatepath")); } }
861
0.652893
0.649351
43
17.744186
20.280697
91
false
false
0
0
0
0
0
0
1.465116
false
false
13
4b206e7aab83afd5836653bb022d732319cd0713
13,176,959,699,293
a57cb56cc4e807041bbeb300a342f05e89072ab5
/modules/cpr/src/main/java/org/atmosphere/interceptor/TrackMessageSizeB64Interceptor.java
c52de6e07b8cd0f86f64783949602fa9196ffb81
[ "Apache-2.0" ]
permissive
blono/atmosphere
https://github.com/blono/atmosphere
703390787e699f29b3101c817225e5754d172f13
94de2526cf328373ea2f087fc510147da6d8a7c0
refs/heads/atmosphere-2.5.x
2020-05-15T01:25:43.924000
2019-04-18T06:41:43
2019-04-18T06:41:43
182,028,907
0
0
Apache-2.0
true
2019-05-28T06:53:07
2019-04-18T06:26:19
2019-04-18T06:41:52
2019-05-28T06:51:20
109,657
0
0
1
Java
false
false
/* * Copyright 2008-2019 Async-IO.org * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.interceptor; import org.atmosphere.cpr.*; import org.atmosphere.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import java.util.HashSet; import static org.atmosphere.cpr.ApplicationConfig.EXCLUDED_CONTENT_TYPES; /** * An {@link org.atmosphere.cpr.AtmosphereInterceptor} that adds message size and delimiter, and encodes the message in Base64. * This allows for broadcasting of messages containing the delimiter character. * <p/> * You can configure this class to exclude some response's content-type by using the {@link ApplicationConfig#EXCLUDED_CONTENT_TYPES} * * @author Jeanfrancois Arcand * @author Martin Mačura */ public class TrackMessageSizeB64Interceptor extends AtmosphereInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(TrackMessageSizeB64Interceptor.class); private static final String DELIMITER = "|"; private final static String OUT_ENCODING = "UTF-8"; public final static String SKIP_INTERCEPTOR = TrackMessageSizeB64Interceptor.class.getName() + ".skip"; private final HashSet<String> excludedContentTypes = new HashSet<String>(); private final Interceptor interceptor = new Interceptor(); @Override public void configure(AtmosphereConfig config) { String s = config.getInitParameter(EXCLUDED_CONTENT_TYPES); if (s != null) { excludedContentTypes.addAll(Arrays.asList(s.split(","))); } } /** * Excluse response's content-type from being processed by this class. * * @param excludedContentType the value of {@link AtmosphereResponseImpl#getContentType()} * @return this */ public TrackMessageSizeB64Interceptor excludedContentType(String excludedContentType) { excludedContentTypes.add(excludedContentType.toLowerCase()); return this; } @Override public Action inspect(final AtmosphereResource r) { if (Utils.webSocketMessage(r)) return Action.CONTINUE; final AtmosphereResponse response = r.getResponse(); super.inspect(r); AsyncIOWriter writer = response.getAsyncIOWriter(); if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor); } else { logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName()); } return Action.CONTINUE; } @Override public String toString() { return " Track Message Size Base64 Interceptor using " + DELIMITER; } private final class Interceptor extends AsyncIOInterceptorAdapter { @Override public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException { if (response.request().getAttribute(SKIP_INTERCEPTOR) == null && Boolean.valueOf(response.request().getHeader(HeaderConfig.X_ATMOSPHERE_TRACKMESSAGESIZE)) && (response.getContentType() == null || !excludedContentTypes.contains(response.getContentType().toLowerCase()))) { response.setCharacterEncoding(OUT_ENCODING); String s = Base64.getEncoder().encodeToString(responseDraft); StringBuilder sb = new StringBuilder(); sb.append(s.length()).append(DELIMITER).append(s); return sb.toString().getBytes(OUT_ENCODING); } else { return responseDraft; } } } }
UTF-8
Java
4,435
java
TrackMessageSizeB64Interceptor.java
Java
[ { "context": "tionConfig#EXCLUDED_CONTENT_TYPES}\r\n *\r\n * @author Jeanfrancois Arcand\r\n * @author Martin Mačura\r\n */\r\npublic class Trac", "end": 1358, "score": 0.9998812675476074, "start": 1339, "tag": "NAME", "value": "Jeanfrancois Arcand" }, { "context": "S}\r\n *\r\n * @author Jeanfrancois Arcand\r\n * @author Martin Mačura\r\n */\r\npublic class TrackMessageSizeB64Interceptor", "end": 1384, "score": 0.9998847842216492, "start": 1371, "tag": "NAME", "value": "Martin Mačura" } ]
null
[]
/* * Copyright 2008-2019 Async-IO.org * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.interceptor; import org.atmosphere.cpr.*; import org.atmosphere.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import java.util.HashSet; import static org.atmosphere.cpr.ApplicationConfig.EXCLUDED_CONTENT_TYPES; /** * An {@link org.atmosphere.cpr.AtmosphereInterceptor} that adds message size and delimiter, and encodes the message in Base64. * This allows for broadcasting of messages containing the delimiter character. * <p/> * You can configure this class to exclude some response's content-type by using the {@link ApplicationConfig#EXCLUDED_CONTENT_TYPES} * * @author <NAME> * @author <NAME> */ public class TrackMessageSizeB64Interceptor extends AtmosphereInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(TrackMessageSizeB64Interceptor.class); private static final String DELIMITER = "|"; private final static String OUT_ENCODING = "UTF-8"; public final static String SKIP_INTERCEPTOR = TrackMessageSizeB64Interceptor.class.getName() + ".skip"; private final HashSet<String> excludedContentTypes = new HashSet<String>(); private final Interceptor interceptor = new Interceptor(); @Override public void configure(AtmosphereConfig config) { String s = config.getInitParameter(EXCLUDED_CONTENT_TYPES); if (s != null) { excludedContentTypes.addAll(Arrays.asList(s.split(","))); } } /** * Excluse response's content-type from being processed by this class. * * @param excludedContentType the value of {@link AtmosphereResponseImpl#getContentType()} * @return this */ public TrackMessageSizeB64Interceptor excludedContentType(String excludedContentType) { excludedContentTypes.add(excludedContentType.toLowerCase()); return this; } @Override public Action inspect(final AtmosphereResource r) { if (Utils.webSocketMessage(r)) return Action.CONTINUE; final AtmosphereResponse response = r.getResponse(); super.inspect(r); AsyncIOWriter writer = response.getAsyncIOWriter(); if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor); } else { logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName()); } return Action.CONTINUE; } @Override public String toString() { return " Track Message Size Base64 Interceptor using " + DELIMITER; } private final class Interceptor extends AsyncIOInterceptorAdapter { @Override public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException { if (response.request().getAttribute(SKIP_INTERCEPTOR) == null && Boolean.valueOf(response.request().getHeader(HeaderConfig.X_ATMOSPHERE_TRACKMESSAGESIZE)) && (response.getContentType() == null || !excludedContentTypes.contains(response.getContentType().toLowerCase()))) { response.setCharacterEncoding(OUT_ENCODING); String s = Base64.getEncoder().encodeToString(responseDraft); StringBuilder sb = new StringBuilder(); sb.append(s.length()).append(DELIMITER).append(s); return sb.toString().getBytes(OUT_ENCODING); } else { return responseDraft; } } } }
4,414
0.681552
0.67456
111
37.945946
36.998379
151
false
false
0
0
0
0
0
0
0.432432
false
false
13
9320e83fee8fdd3596e808526559beaf872281e1
16,234,976,405,141
fe89046bd32e20d3534951208e4de40ca097746b
/src/gui/manager/OrLearning/parkingAreas.java
60d3bca092a942582da7ad3c86b7b656216a1ed2
[ "Apache-2.0" ]
permissive
markrey/SmartCity-ParkingManagement
https://github.com/markrey/SmartCity-ParkingManagement
f7a7ed1076a1ec1697e95ece3878c218ef4dc495
22d5ab5d506100ed206a491b4b47d8fe9624e120
refs/heads/master
2021-01-12T01:10:57.078000
2017-01-08T13:59:07
2017-01-08T13:59:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui.manager.OrLearning; import gui.manager.OrLearning.CreatingABasicWindow.Color; public class parkingAreas { private String name; private Color color; private int spots; //Constructors parkingAreas() { this.name=""; this.color=Color.GRAY; this.spots=0; } parkingAreas(String name, Color color, int spots) { this.name=name; this.color=color; this.spots=spots; } //Getters & Setters public String getName() { return this.name; } void setName(String name) { this.name=name; } public Color getColor() { return this.color; } void setColor(Color ¢) { this.color=¢; } public int getSpots() { return this.spots; } void setSpots(int spots) { this.spots=spots; } }
UTF-8
Java
723
java
parkingAreas.java
Java
[]
null
[]
package gui.manager.OrLearning; import gui.manager.OrLearning.CreatingABasicWindow.Color; public class parkingAreas { private String name; private Color color; private int spots; //Constructors parkingAreas() { this.name=""; this.color=Color.GRAY; this.spots=0; } parkingAreas(String name, Color color, int spots) { this.name=name; this.color=color; this.spots=spots; } //Getters & Setters public String getName() { return this.name; } void setName(String name) { this.name=name; } public Color getColor() { return this.color; } void setColor(Color ¢) { this.color=¢; } public int getSpots() { return this.spots; } void setSpots(int spots) { this.spots=spots; } }
723
0.687933
0.686546
44
15.386364
13.108317
57
false
false
0
0
0
0
0
0
1.568182
false
false
13
2c08f7d661c7297c112ac9d9df9b69168bd3ba00
16,234,976,403,238
abd50e5d913da5f2aa11b823af8cc742a54ae116
/manager_ads/src/manager/ADV01/logic/ADV01LogicIF.java
c7e887f8e428e9b79e4755bbc22d5c5545aa37c6
[]
no_license
duongbata/manager_ads
https://github.com/duongbata/manager_ads
c8d1cdfb4ea27675df0d97aa6e148e315d75ee98
d7835eaa24da067e63a2c4db4b1f8464f227aae8
refs/heads/master
2016-09-11T06:49:26.772000
2015-04-16T02:32:13
2015-04-16T02:32:13
32,072,293
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package manager.ADV01.logic; import java.io.IOException; import java.util.List; import java.util.Map; import manager.ADV01.bean.AdsBean; import manager.common.bean.UserBean; public interface ADV01LogicIF { List<AdsBean> listAds(UserBean user); AdsBean getAdsById(String appId); Map<Integer, String> getAllOs(); Map<Integer, String> getAllStatus(); Map<Integer, String> getAllAdNetwork(); void updateAds(AdsBean adsBean); void delAdsPubApp(String appId); void insertAdsApp(AdsBean adsBean, UserBean user); List<AdsBean> listAdsFromRedis()throws IOException; }
UTF-8
Java
615
java
ADV01LogicIF.java
Java
[]
null
[]
package manager.ADV01.logic; import java.io.IOException; import java.util.List; import java.util.Map; import manager.ADV01.bean.AdsBean; import manager.common.bean.UserBean; public interface ADV01LogicIF { List<AdsBean> listAds(UserBean user); AdsBean getAdsById(String appId); Map<Integer, String> getAllOs(); Map<Integer, String> getAllStatus(); Map<Integer, String> getAllAdNetwork(); void updateAds(AdsBean adsBean); void delAdsPubApp(String appId); void insertAdsApp(AdsBean adsBean, UserBean user); List<AdsBean> listAdsFromRedis()throws IOException; }
615
0.731707
0.721951
28
19.964285
17.76932
52
false
false
0
0
0
0
0
0
1.285714
false
false
13
14abcf0eca68d16e150e2cce2feddcdfbc7a393f
944,892,829,147
2850de89d7d690fa6404d5e323439faea202e0cb
/src/SV_support/Atom.java
7c51fef9ede125176abe071326021c793c4cdcb2
[]
no_license
WilliamLeaves/MolConstructor
https://github.com/WilliamLeaves/MolConstructor
21086463f5c664872b54520515b5dc1e210974aa
676eabc6a08adfa4c201dbf25d5a7501328b0387
refs/heads/master
2020-03-06T15:24:24.208000
2018-04-13T03:16:18
2018-04-13T03:16:18
126,955,369
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SV_support; public class Atom { public String element; public double innerX; public double innerY; public double innerZ; public Atom(String e, double x, double y, double z) { this.innerX = x; this.innerY = y; this.innerZ = z; this.element = e; } public void transCoordinate(double[] axisList) { if (axisList.length != 3) { return; } else { this.innerX += axisList[0]; this.innerY += axisList[1]; this.innerZ += axisList[2]; } } public boolean equal(Atom a) { if (a.innerX == this.innerX && a.innerY == this.innerY && a.innerZ == this.innerZ) { return true; } return false; } <<<<<<< HEAD public Object clone() { Atom a = null; try { a = (Atom) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return a; } public double calDistance(Atom atom) { return Math.pow(this.innerX - atom.innerX, 2) + Math.pow(this.innerY - atom.innerY, 2) + Math.pow(this.innerZ - atom.innerZ, 2); } public void mirror() { this.clockWiseRotateY(180); this.clockWiseRotateZ(180); } // rotate the Atom by theta degree along the Z-axis public void clockWiseRotateZ(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double x = this.innerX * Math.cos(p) + this.innerY * Math.sin(p); double y = this.innerY * Math.cos(p) - this.innerX * Math.sin(p); this.innerX = x; this.innerY = y; } } // rotate the Atom by theta degree along the Y-axis public void clockWiseRotateY(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double x = this.innerX * Math.cos(p) + this.innerZ * Math.sin(p); double z = this.innerZ * Math.cos(p) - this.innerX * Math.sin(p); this.innerX = x; this.innerZ = z; } } // rotate the Atom by theta degree along the X-axis public void clockWiseRotateX(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double z = this.innerZ * Math.cos(p) + this.innerY * Math.sin(p); double y = this.innerY * Math.cos(p) - this.innerZ * Math.sin(p); this.innerY = y; this.innerZ = z; } } ======= >>>>>>> parent of 130e820... 20180331-1 }
UTF-8
Java
2,289
java
Atom.java
Java
[]
null
[]
package SV_support; public class Atom { public String element; public double innerX; public double innerY; public double innerZ; public Atom(String e, double x, double y, double z) { this.innerX = x; this.innerY = y; this.innerZ = z; this.element = e; } public void transCoordinate(double[] axisList) { if (axisList.length != 3) { return; } else { this.innerX += axisList[0]; this.innerY += axisList[1]; this.innerZ += axisList[2]; } } public boolean equal(Atom a) { if (a.innerX == this.innerX && a.innerY == this.innerY && a.innerZ == this.innerZ) { return true; } return false; } <<<<<<< HEAD public Object clone() { Atom a = null; try { a = (Atom) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return a; } public double calDistance(Atom atom) { return Math.pow(this.innerX - atom.innerX, 2) + Math.pow(this.innerY - atom.innerY, 2) + Math.pow(this.innerZ - atom.innerZ, 2); } public void mirror() { this.clockWiseRotateY(180); this.clockWiseRotateZ(180); } // rotate the Atom by theta degree along the Z-axis public void clockWiseRotateZ(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double x = this.innerX * Math.cos(p) + this.innerY * Math.sin(p); double y = this.innerY * Math.cos(p) - this.innerX * Math.sin(p); this.innerX = x; this.innerY = y; } } // rotate the Atom by theta degree along the Y-axis public void clockWiseRotateY(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double x = this.innerX * Math.cos(p) + this.innerZ * Math.sin(p); double z = this.innerZ * Math.cos(p) - this.innerX * Math.sin(p); this.innerX = x; this.innerZ = z; } } // rotate the Atom by theta degree along the X-axis public void clockWiseRotateX(double theta) { if (theta < -360 || theta > 360) { return; } else { double p = (theta / 360) * 2 * Math.PI; double z = this.innerZ * Math.cos(p) + this.innerY * Math.sin(p); double y = this.innerY * Math.cos(p) - this.innerZ * Math.sin(p); this.innerY = y; this.innerZ = z; } } ======= >>>>>>> parent of 130e820... 20180331-1 }
2,289
0.619921
0.594583
94
23.351065
21.612499
88
false
false
0
0
0
0
0
0
2.234043
false
false
13
2d8fd84b791204428bd31ba3a4a4c766424b7f12
23,201,413,357,499
8960802e6038f24c3a1563d75f4e415c36822229
/src/test/java/com/eezy/logintest/StartNewPlanTest.java
956819d7d2ed718afc6fd87b6d5315878b0ece7e
[]
no_license
rexrayzx/Test
https://github.com/rexrayzx/Test
69ccb73349e560e27db2a2d71affa7d73c385321
9b8222e9701a06e7b0f72591a46406bbe2e839b8
refs/heads/master
2023-06-02T13:39:15.879000
2021-06-17T13:26:47
2021-06-17T13:26:47
362,380,591
0
0
null
false
2021-05-12T07:50:20
2021-04-28T07:40:16
2021-05-11T09:30:39
2021-05-12T07:50:20
26,684
0
0
1
HTML
false
false
package com.eezy.logintest; import org.testng.Assert; import org.testng.annotations.Test; import com.eezy.generics.BaseTest; import com.eezy.pages.LogInToeezyPage; import com.eezy.pages.LoginHomePage; import com.eezy.pages.MoreSignUpoptionPage; import com.eezy.pages.SignUpForeezyPage; import com.eezy.pages.UserProfilePage; import com.eezy.pages.WelcomeToeezyPage; public class StartNewPlanTest extends BaseTest{ @Test public void startNewPlan() throws Throwable { WelcomeToeezyPage setup=new WelcomeToeezyPage(driver); setup.getLoginBtn(driver).click(); SignUpForeezyPage singin=new SignUpForeezyPage(driver); singin.getMoreSignUpoptnLink(driver).click(); MoreSignUpoptionPage option=new MoreSignUpoptionPage(driver); option.getEmailSignUpoptnLink(driver).click(); LogInToeezyPage login=new LogInToeezyPage(driver); login.getLoginEmailtxb().sendKeys(file.getDataFromPropertFile("email")); login.getLoginPasswordtxb().sendKeys(file.getDataFromPropertFile("password")); login.getContinueBtn().click(); UserProfilePage profile=new UserProfilePage(driver); LoginHomePage loginHome=new LoginHomePage(driver); pageutil.waitToDisplay(driver, loginHome.getSkipbtn()); pageutil.tap(driver, .1, .1); profile.getYesBtn().click(); Assert.assertTrue(loginHome.getInspireMeBtn().isDisplayed()); } }
UTF-8
Java
1,325
java
StartNewPlanTest.java
Java
[]
null
[]
package com.eezy.logintest; import org.testng.Assert; import org.testng.annotations.Test; import com.eezy.generics.BaseTest; import com.eezy.pages.LogInToeezyPage; import com.eezy.pages.LoginHomePage; import com.eezy.pages.MoreSignUpoptionPage; import com.eezy.pages.SignUpForeezyPage; import com.eezy.pages.UserProfilePage; import com.eezy.pages.WelcomeToeezyPage; public class StartNewPlanTest extends BaseTest{ @Test public void startNewPlan() throws Throwable { WelcomeToeezyPage setup=new WelcomeToeezyPage(driver); setup.getLoginBtn(driver).click(); SignUpForeezyPage singin=new SignUpForeezyPage(driver); singin.getMoreSignUpoptnLink(driver).click(); MoreSignUpoptionPage option=new MoreSignUpoptionPage(driver); option.getEmailSignUpoptnLink(driver).click(); LogInToeezyPage login=new LogInToeezyPage(driver); login.getLoginEmailtxb().sendKeys(file.getDataFromPropertFile("email")); login.getLoginPasswordtxb().sendKeys(file.getDataFromPropertFile("password")); login.getContinueBtn().click(); UserProfilePage profile=new UserProfilePage(driver); LoginHomePage loginHome=new LoginHomePage(driver); pageutil.waitToDisplay(driver, loginHome.getSkipbtn()); pageutil.tap(driver, .1, .1); profile.getYesBtn().click(); Assert.assertTrue(loginHome.getInspireMeBtn().isDisplayed()); } }
1,325
0.806038
0.804528
34
37.970589
20.895376
80
false
false
0
0
0
0
0
0
1.882353
false
false
13
9de813a9c4ff66a5cf52324b4408e01b5157c22c
16,234,976,438,535
8dbab6ba11e4df4306c8bb968b4673d0e38425bd
/app/src/main/java/com/example/projectandroid/RegisterService.java
61ff2fbab27e5dc71a453c9014c7acca50a2d160
[]
no_license
AniqAsyraaf/Service-Platform-Application
https://github.com/AniqAsyraaf/Service-Platform-Application
5d63d23ebbd9b716defde2f383c822b235aa538d
335eb55c9c0b6e7923b5ac46eca6203ae29c55f3
refs/heads/master
2023-04-14T13:43:07.468000
2021-04-23T04:36:15
2021-04-23T04:36:15
360,760,051
3
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.projectandroid; import android.Manifest; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class RegisterService extends AppCompatActivity { DatabaseHelper myDb; Button btnSubmitData, btnLogo; Spinner editServiceType,state,area; EditText editBusinessName; EditText editContactNumber; EditText editEmail; EditText editPassword; ImageView imgLogo; final int REQUEST_CODE_GALLERY=999; ArrayAdapter<String> dataAdapter; ArrayAdapter<String> myAdapterstate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().hide(); setContentView(R.layout.register_service); myDb=new DatabaseHelper(this); editBusinessName=(EditText)findViewById(R.id.editTextTextPersonName3); editServiceType=(Spinner)findViewById(R.id.spinner1); editContactNumber=(EditText)findViewById(R.id.editTextTextPersonName6); editEmail=(EditText)findViewById(R.id.editTextTextEmailAddress); editPassword=(EditText)findViewById(R.id.editTextTextPersonName8); btnLogo=(Button)findViewById(R.id.logo); btnSubmitData=(Button)findViewById(R.id.button); imgLogo=(ImageView)findViewById(R.id.imageView8); ArrayAdapter<String> myAdapter=new ArrayAdapter<>(RegisterService.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.Service_Provider_Type)); myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); editServiceType.setAdapter(myAdapter); state=(Spinner)findViewById(R.id.state); area=(Spinner)findViewById(R.id.area); myAdapterstate=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.state)); myAdapterstate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); state.setAdapter(myAdapterstate); state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position==0) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.None)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==1) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Johor)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==2) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Melaka)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==3) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Negeri_Sembilan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==4) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Selangor)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==5) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Kedah)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==6) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Perlis)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==7) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Pulau_Pinang)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==8) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Perak)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==9) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Kelantan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==10) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Terengganu)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==11) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Pahang)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==12) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Sabah)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==13) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Sarawak)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==14) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Kuala_Lumpur)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==15) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Labuan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==16) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Putrajaya)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } area.setAdapter(dataAdapter); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); btnLogo.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ActivityCompat.requestPermissions(RegisterService.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_CODE_GALLERY); } }); SubmitData(); } private byte[] imageViewToByte(ImageView image) { Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap(); ByteArrayOutputStream stream=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100,stream); byte[] byteArray=stream.toByteArray(); return byteArray; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,int[] grantResults) { if (requestCode == REQUEST_CODE_GALLERY) { if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) { Intent intent=new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,REQUEST_CODE_GALLERY); } else { Toast.makeText(getApplicationContext(),"You don't have permissions to access file",Toast.LENGTH_SHORT); } return; } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode==REQUEST_CODE_GALLERY && resultCode==RESULT_OK && data!=null) { Uri uri=data.getData(); try { InputStream inputStream=getContentResolver().openInputStream(uri); Bitmap bitmap= BitmapFactory.decodeStream(inputStream); imgLogo.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } public Boolean validate(String state, String area) { boolean result=false; String businessname=editBusinessName.getText().toString(); String servicetype=editServiceType.getSelectedItem().toString(); String contactnum=editContactNumber.getText().toString(); String email=editEmail.getText().toString(); String password=editPassword.getText().toString(); if(businessname.isEmpty()||servicetype.equals("None")||contactnum.isEmpty()||email.isEmpty()||password.isEmpty()||state.equals("None")||area.equals("None")) { String show="is empty"; if(businessname.isEmpty()) { String tempstring=" business name "; show=tempstring+show; } if(servicetype.equals("None")) { String tempstring=" service type "; show=tempstring+show; } if(contactnum.isEmpty()) { String tempstring=" contact number "; show=tempstring+show; } if(email.isEmpty()) { String tempstring=" email "; show=tempstring+show; } if(password.isEmpty()) { String tempstring=" password "; show=tempstring+show; } if(state.equals("None")) { String tempstring=" state "; show=tempstring+show; } if(area.equals("None")) { String tempstring=" area "; show=tempstring+show; } Toast.makeText(RegisterService.this, show, Toast.LENGTH_SHORT).show(); } else { result=true; } return result; } public void SubmitData() { btnSubmitData.setOnClickListener( (view)->{ if(validate(state.getSelectedItem().toString(),area.getSelectedItem().toString())) { boolean isInserted = myDb.insertDataService(editBusinessName.getText().toString(), editServiceType.getSelectedItem().toString(), editContactNumber.getText().toString(), editEmail.getText().toString(), editPassword.getText().toString(), state.getSelectedItem().toString(), area.getSelectedItem().toString(),imageViewToByte(imgLogo)); if (isInserted) { Toast.makeText(RegisterService.this, "Register Successful, Please Login", Toast.LENGTH_SHORT).show(); imgLogo.setImageResource(R.mipmap.ic_launcher); } else Toast.makeText(RegisterService.this, "Register Not Successful", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterService.this, LoginService.class); startActivity(intent); } } ); } }
UTF-8
Java
14,352
java
RegisterService.java
Java
[]
null
[]
package com.example.projectandroid; import android.Manifest; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class RegisterService extends AppCompatActivity { DatabaseHelper myDb; Button btnSubmitData, btnLogo; Spinner editServiceType,state,area; EditText editBusinessName; EditText editContactNumber; EditText editEmail; EditText editPassword; ImageView imgLogo; final int REQUEST_CODE_GALLERY=999; ArrayAdapter<String> dataAdapter; ArrayAdapter<String> myAdapterstate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().hide(); setContentView(R.layout.register_service); myDb=new DatabaseHelper(this); editBusinessName=(EditText)findViewById(R.id.editTextTextPersonName3); editServiceType=(Spinner)findViewById(R.id.spinner1); editContactNumber=(EditText)findViewById(R.id.editTextTextPersonName6); editEmail=(EditText)findViewById(R.id.editTextTextEmailAddress); editPassword=(EditText)findViewById(R.id.editTextTextPersonName8); btnLogo=(Button)findViewById(R.id.logo); btnSubmitData=(Button)findViewById(R.id.button); imgLogo=(ImageView)findViewById(R.id.imageView8); ArrayAdapter<String> myAdapter=new ArrayAdapter<>(RegisterService.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.Service_Provider_Type)); myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); editServiceType.setAdapter(myAdapter); state=(Spinner)findViewById(R.id.state); area=(Spinner)findViewById(R.id.area); myAdapterstate=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.state)); myAdapterstate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); state.setAdapter(myAdapterstate); state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position==0) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.None)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==1) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Johor)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==2) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Melaka)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==3) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Negeri_Sembilan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==4) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Selangor)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==5) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Kedah)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==6) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Perlis)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==7) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Pulau_Pinang)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==8) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Perak)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==9) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Kelantan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==10) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Terengganu)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==11) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Pahang)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==12) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Sabah)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==13) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Sarawak)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==14) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Kuala_Lumpur)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==15) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Labuan)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } if (position==16) { dataAdapter = new ArrayAdapter<>(RegisterService.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.W_P_Putrajaya)); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } area.setAdapter(dataAdapter); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); btnLogo.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ActivityCompat.requestPermissions(RegisterService.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_CODE_GALLERY); } }); SubmitData(); } private byte[] imageViewToByte(ImageView image) { Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap(); ByteArrayOutputStream stream=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100,stream); byte[] byteArray=stream.toByteArray(); return byteArray; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,int[] grantResults) { if (requestCode == REQUEST_CODE_GALLERY) { if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) { Intent intent=new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,REQUEST_CODE_GALLERY); } else { Toast.makeText(getApplicationContext(),"You don't have permissions to access file",Toast.LENGTH_SHORT); } return; } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode==REQUEST_CODE_GALLERY && resultCode==RESULT_OK && data!=null) { Uri uri=data.getData(); try { InputStream inputStream=getContentResolver().openInputStream(uri); Bitmap bitmap= BitmapFactory.decodeStream(inputStream); imgLogo.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } public Boolean validate(String state, String area) { boolean result=false; String businessname=editBusinessName.getText().toString(); String servicetype=editServiceType.getSelectedItem().toString(); String contactnum=editContactNumber.getText().toString(); String email=editEmail.getText().toString(); String password=editPassword.getText().toString(); if(businessname.isEmpty()||servicetype.equals("None")||contactnum.isEmpty()||email.isEmpty()||password.isEmpty()||state.equals("None")||area.equals("None")) { String show="is empty"; if(businessname.isEmpty()) { String tempstring=" business name "; show=tempstring+show; } if(servicetype.equals("None")) { String tempstring=" service type "; show=tempstring+show; } if(contactnum.isEmpty()) { String tempstring=" contact number "; show=tempstring+show; } if(email.isEmpty()) { String tempstring=" email "; show=tempstring+show; } if(password.isEmpty()) { String tempstring=" password "; show=tempstring+show; } if(state.equals("None")) { String tempstring=" state "; show=tempstring+show; } if(area.equals("None")) { String tempstring=" area "; show=tempstring+show; } Toast.makeText(RegisterService.this, show, Toast.LENGTH_SHORT).show(); } else { result=true; } return result; } public void SubmitData() { btnSubmitData.setOnClickListener( (view)->{ if(validate(state.getSelectedItem().toString(),area.getSelectedItem().toString())) { boolean isInserted = myDb.insertDataService(editBusinessName.getText().toString(), editServiceType.getSelectedItem().toString(), editContactNumber.getText().toString(), editEmail.getText().toString(), editPassword.getText().toString(), state.getSelectedItem().toString(), area.getSelectedItem().toString(),imageViewToByte(imgLogo)); if (isInserted) { Toast.makeText(RegisterService.this, "Register Successful, Please Login", Toast.LENGTH_SHORT).show(); imgLogo.setImageResource(R.mipmap.ic_launcher); } else Toast.makeText(RegisterService.this, "Register Not Successful", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterService.this, LoginService.class); startActivity(intent); } } ); } }
14,352
0.614897
0.612179
344
40.723839
45.997242
356
false
false
0
0
0
0
0
0
0.686047
false
false
13
79402ac67ab55efd5a3e1dffba975b4f24c0d977
15,771,119,979,341
11dd74fd18dc9b16abe949448b839c04c81db03e
/src/main/java/com/assignment/schedule/creator/HostsFreeScheduleCreator.java
3a264f8a9df8cd25d6ad7f2216a90dbf96f36cb3
[]
no_license
eralmas7/EventCalendar
https://github.com/eralmas7/EventCalendar
28286642fa4d6bd80e90c62298c02aa922a32a35
be5274f892c4faa140dd5d2a16006cea96a1a882
refs/heads/master
2016-08-11T07:24:00.080000
2015-11-07T17:47:11
2015-11-07T17:47:11
44,920,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.assignment.schedule.creator; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.stream.LongStream; import com.assignment.model.Interval; import com.assignment.model.MeetingInput; import com.assignment.utils.DateTimeUtils; /** * A class responsible to create the free schedule of host. */ public class HostsFreeScheduleCreator implements ScheduleCreator { @Override public Map<Integer, Interval> createSchedule(final MeetingInput meetingInput) { final Map<Integer, Interval> intervalMap = new HashMap<>(meetingInput.getMeeting().getFreeWorkingTimes().size(), 1.f); final long scheduleStepInMillis = meetingInput.getMeeting().getDurationInMins() * 60 * 1000; final int key[] = {0}; meetingInput.getMeeting().getFreeWorkingTimes().stream().map( dateTime -> new Interval(DateTimeUtils.getZonedDateTime(dateTime.getDateFrom(), meetingInput.getMeeting().getTimezone()).toInstant(), DateTimeUtils.getZonedDateTime(dateTime.getDateTo(), meetingInput.getMeeting().getTimezone()).toInstant())).forEach( interval -> LongStream.iterate(interval.getFrom().toEpochMilli(), schedule -> schedule + scheduleStepInMillis).limit((interval.getTo().toEpochMilli() - interval.getFrom().toEpochMilli()) / scheduleStepInMillis).forEach( schedule -> intervalMap.put(key[0]++, new Interval(Instant.ofEpochMilli(schedule), Instant.ofEpochMilli(schedule + scheduleStepInMillis))))); return intervalMap; } }
UTF-8
Java
1,576
java
HostsFreeScheduleCreator.java
Java
[]
null
[]
package com.assignment.schedule.creator; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.stream.LongStream; import com.assignment.model.Interval; import com.assignment.model.MeetingInput; import com.assignment.utils.DateTimeUtils; /** * A class responsible to create the free schedule of host. */ public class HostsFreeScheduleCreator implements ScheduleCreator { @Override public Map<Integer, Interval> createSchedule(final MeetingInput meetingInput) { final Map<Integer, Interval> intervalMap = new HashMap<>(meetingInput.getMeeting().getFreeWorkingTimes().size(), 1.f); final long scheduleStepInMillis = meetingInput.getMeeting().getDurationInMins() * 60 * 1000; final int key[] = {0}; meetingInput.getMeeting().getFreeWorkingTimes().stream().map( dateTime -> new Interval(DateTimeUtils.getZonedDateTime(dateTime.getDateFrom(), meetingInput.getMeeting().getTimezone()).toInstant(), DateTimeUtils.getZonedDateTime(dateTime.getDateTo(), meetingInput.getMeeting().getTimezone()).toInstant())).forEach( interval -> LongStream.iterate(interval.getFrom().toEpochMilli(), schedule -> schedule + scheduleStepInMillis).limit((interval.getTo().toEpochMilli() - interval.getFrom().toEpochMilli()) / scheduleStepInMillis).forEach( schedule -> intervalMap.put(key[0]++, new Interval(Instant.ofEpochMilli(schedule), Instant.ofEpochMilli(schedule + scheduleStepInMillis))))); return intervalMap; } }
1,576
0.723985
0.718274
27
57.370369
70.593857
274
false
false
0
0
0
0
0
0
0.814815
false
false
13
7c3ea01598dc53e7f8d3ad9df992b5e76d4fd723
18,708,877,601,054
9e20c211652043350d5f9b550bd9b29b739db32d
/src/main/java/com/github/redouane59/topteamsapi/functions/evaluation/IRatingUpdatesCalculator.java
344f7f8a09c42e892eae8296a007d599321ac658
[]
no_license
redouane59/top-teams-api
https://github.com/redouane59/top-teams-api
74d13e961be916180e3c3d245d440f4fc0f43bce
df356f79d377a7c9d9f14c20619569c7c75fb8fc
refs/heads/master
2023-04-09T01:24:10.078000
2022-10-19T20:30:48
2022-10-19T20:30:48
166,547,217
3
0
null
false
2023-03-31T15:28:59
2019-01-19T13:02:02
2022-02-15T22:04:17
2023-03-31T15:28:59
133
3
0
1
Java
false
false
package com.github.redouane59.topteamsapi.functions.evaluation; import com.github.redouane59.topteamsapi.model.Game; import com.github.redouane59.topteamsapi.model.Player; import java.util.List; public interface IRatingUpdatesCalculator { List<Player> getUpdatedPlayers(Game game); }
UTF-8
Java
293
java
IRatingUpdatesCalculator.java
Java
[ { "context": "package com.github.redouane59.topteamsapi.functions.evaluation;\n\nimport com.git", "end": 29, "score": 0.9994769096374512, "start": 19, "tag": "USERNAME", "value": "redouane59" }, { "context": "teamsapi.functions.evaluation;\n\nimport com.github.redouane59.topteamsapi.model.Game;\nimport com.github.redouan", "end": 93, "score": 0.9995648264884949, "start": 83, "tag": "USERNAME", "value": "redouane59" }, { "context": "ouane59.topteamsapi.model.Game;\nimport com.github.redouane59.topteamsapi.model.Player;\nimport java.util.List;\n", "end": 146, "score": 0.9996029734611511, "start": 136, "tag": "USERNAME", "value": "redouane59" } ]
null
[]
package com.github.redouane59.topteamsapi.functions.evaluation; import com.github.redouane59.topteamsapi.model.Game; import com.github.redouane59.topteamsapi.model.Player; import java.util.List; public interface IRatingUpdatesCalculator { List<Player> getUpdatedPlayers(Game game); }
293
0.819113
0.798635
12
23.416666
24.931435
63
false
false
0
0
0
0
0
0
0.416667
false
false
13
c9a9de35032d80e660d2ce99179e3f8ef65d084e
8,203,387,549,108
a669e3cb136966fbb7d1d5a260af93971ecec6f0
/src/main/java/bd/BetTools.java
48eadb57ec0bc2ebd88cbc2eee8a518183b07690
[]
no_license
jordanupmc/betcoinServer
https://github.com/jordanupmc/betcoinServer
222ea252b5ea9aa220a4577481859abd2de4fbe7
7c2000e26c2f9d27f12910de4a1d05a775c17ff0
refs/heads/master
2020-03-31T08:51:28.218000
2018-11-23T15:25:15
2018-11-23T15:25:15
152,074,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bd; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.util.JSON; import org.bson.BsonDocument; import org.bson.BsonString; import org.bson.Document; import org.bson.conversions.Bson; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.net.URISyntaxException; import java.sql.*; import java.util.ArrayList; import java.util.List; import static bd.Database.getMongoCollection; import static bd.PoolTools.poolExist; import static com.mongodb.client.model.Filters.and; public class BetTools { // renvoi true si un joueur a un sodle suffisant pour parier un certain montant public static boolean hasEnoughCoin(String login,String ammount) throws SQLException, URISyntaxException { String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet result = pstmt.executeQuery(); result.next(); int solde = result.getInt(1); solde = solde - Integer.parseInt(ammount); if (solde < 0) { return false; } } return true; } /* renvois la liste des salons de pari encore actif */ public static JSONArray getListPoolsActive() { JSONArray ar = new JSONArray(); String query = "SELECT idbetpool, name, openingbet, closingbet, resultbet, cryptocurrency, pooltype FROM BetPool WHERE closingBet > NOW() AT TIME ZONE 'Europe/Paris' AND openingBet <= NOW() AT TIME ZONE 'Europe/Paris'"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query); ResultSet v = pstmt.executeQuery(); ) { JSONObject j = null; while (v.next()) { j = new JSONObject(); j.put("idbetpool", v.getInt(1)); j.put("name", v.getString(2)); j.put("openingbet", v.getTimestamp(3)); j.put("closingbet", v.getTimestamp(4)); j.put("resultbet", v.getTimestamp(5)); j.put("cryptocurrency", v.getString(6)); j.put("pooltype", v.getBoolean(7)); ar.put(j); } } catch (Exception e) { } finally { return ar; } } /* Permet aux utilisateurs d'ajouter un nouveau pari*/ public static boolean addBet(String idPool, String login, int betAmmount, double betValue) throws URISyntaxException, SQLException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); Timestamp tsp = new Timestamp(System.currentTimeMillis()+3600000); if (d == null) { Document newpool = new Document(); newpool.append("idBetPool", idPool); newpool.append("resultValue", 0.0); ArrayList<Document> bets = new ArrayList<>(); Document bet_obj = new Document(); bet_obj.append("gamblerLogin", login); bet_obj.append("betAmount", betAmmount); bet_obj.append("betValue", betValue); bet_obj.append("betDate", tsp.toString()); bets.add(bet_obj); newpool.append("bet", bets); collection.insertOne(newpool); d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); } else { d = collection.find(new BsonDocument().append("idBetPool", new BsonString(idPool))).first(); List<Document> list_bet = (List<Document>) d.get("bet"); Document bet_obj = new Document(); bet_obj.append("gamblerLogin", login); bet_obj.append("betAmount", betAmmount); bet_obj.append("betValue", betValue); bet_obj.append("betDate", tsp.toString()); list_bet.add(bet_obj); BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); collection.updateOne(filter, new Document("$set", new Document("bet", list_bet))); } String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet result = pstmt.executeQuery(); result.next(); int solde = result.getInt(1); solde = solde - betAmmount; query = "UPDATE USERS SET solde=? WHERE login=?"; try (PreparedStatement pstmt2 = c.prepareStatement(query)) { pstmt2.setInt(1, solde); pstmt2.setString(2, login); pstmt2.executeUpdate(); } } collection = getMongoCollection("Bet"); Document obj = new Document(); obj.append("gamblerLogin", login); obj.append("idBetPool", idPool); obj.append("betAmount", betAmmount); obj.append("betValue", betValue); obj.append("betDate", tsp.toString()); obj.append("haveCheckResult", false); collection.insertOne(obj); return true; } // Vérifie l'existance d'un pari public static boolean checkBetExist(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if (d != null) return true; return false; } /* Renvoi true si un pari est toujours annulable */ public static boolean betPoolOpen(String idPool) throws URISyntaxException, SQLException { String query = "SELECT * FROM BETPOOL WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if (res.next()) { if (res.getTimestamp("closingbet").after(new Timestamp(System.currentTimeMillis()))) { pstmt.close(); c.close(); return true; } } } return false; } /* Annule un bet*/ public static boolean cancelBet(String login, String idPool) throws URISyntaxException, SQLException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); if (d == null) { return false; } else { BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); List<Document> bets = (List<Document>) d.get("bet"); for (int i = 0; i < bets.size(); i++) { if (bets.get(i).get("gamblerLogin").equals(login)) { int toRefound = bets.get(i).getInteger("betAmount"); bets.remove(i); collection.updateOne(filter, new Document("$set", new Document("bet", bets))); Connection co = Database.getConnection(); String query = "UPDATE USERS SET solde=solde+? WHERE login=?"; PreparedStatement pstmt = co.prepareStatement(query); pstmt.setInt(1, toRefound); pstmt.setString(2, login); pstmt.executeUpdate(); pstmt.close(); collection = getMongoCollection("Bet"); d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if(d==null){ return false; } collection.deleteOne(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))); return true; } } return false; } } // Renvoi le montant gagné par un pari (ou 0 si le pari est perdu) public static int betWon(String login, String idPool) throws URISyntaxException, SQLException, IOException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d_tmp = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); double resultValue = d_tmp.getDouble("resultValue"); // On est la premiere personne a vérifier son pari, dans ce cas on va chercher la valeur du resultat dans l'API et on rempli notre BD avec ce resultat if(resultValue == 0){ resultValue = updateDBResultValue(idPool, login); if(resultValue == 0){ return -1; } } collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); double betValue = d.getDouble("betValue"); if(!setHaveCheckResultTrue(login, idPool)){ return -1; } if (betValue == resultValue) { String amount_s = d.get("betAmount").toString(); int amount_i = Integer.parseInt(amount_s); return updateAccountGoldWin(amount_i, idPool, login); } return 0; } // Marque un pari dans la BD afin de signaler que l'on a deja vérifié le résultat d'un pari private static boolean setHaveCheckResultTrue(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if (d == null) { return false; } Bson filter = and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login))); collection.updateOne(filter,new Document("$set", new Document("haveCheckResult", true))); return true; } // Met a jour le solde d'un joueur en fonction du montant parié et du multiplicateur de gains private static int updateAccountGoldWin(int ammountBet, String idPool, String login) throws URISyntaxException, SQLException { String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet res = pstmt.executeQuery(); if(res.next()) { int soldeAccount = res.getInt(1); res.close(); int amountWon = 0; boolean type; query = "SELECT pooltype FROM BETPOOL WHERE idbetpool=?"; try (PreparedStatement pstmt3 = c.prepareStatement(query);) { pstmt3.setInt(1, Integer.parseInt(idPool)); ResultSet restype = pstmt3.executeQuery(); if(restype.next()) { type = restype.getBoolean(1); restype.close(); if (type) { amountWon = ammountBet * 10; } else { amountWon = (int) Math.round(ammountBet * 1.5); } } } soldeAccount = soldeAccount + amountWon; query = "UPDATE USERS SET solde=? WHERE login=?"; try (PreparedStatement pstmt2 = c.prepareStatement(query);) { pstmt2.setInt(1, soldeAccount); pstmt2.setString(2, login); pstmt2.executeUpdate(); } return amountWon; } } return -1; } // Met a jour le resultat d'une pool, elle est faite 1 fois par pool (Apres que la date courrante soit supérieur a la date des resultats private static double updateDBResultValue(String idPool, String login) throws URISyntaxException, SQLException, IOException { String query = "SELECT * FROM betpool WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if(res.next()) { String crypt = res.getString("cryptocurrency"); Timestamp time = res.getTimestamp("resultbet"); Boolean poolType = res.getBoolean("pooltype"); double openingPrice = res.getDouble("openingprice"); res.close(); double resultValue = APITools.getPriceSpecificTime(getCryptNickname(crypt),"EUR",(time.getTime()/1000)+""); MongoCollection<Document> collection = getMongoCollection("L_Bet"); BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); if(poolType) { collection.updateOne(filter, new Document("$set", new Document("resultValue", resultValue))); }else{ collection.updateOne(filter, new Document("$set", new Document("resultValue", (resultValue > openingPrice)? 1.0 : -1.0))); } return resultValue; } } return 0; } // renvoi la liste des pari public static JSONArray getListBets(String login) { MongoCollection<Document> collection = getMongoCollection("Bet"); JSONArray array = new JSONArray(); try(MongoCursor<Document> d_tmp = collection .find(new BsonDocument().append("gamblerLogin", new BsonString(login))).iterator();) { while (d_tmp.hasNext()) { Document tmp = d_tmp.next(); array.put(tmp); } } return array; } // Renvoi les informations d'un pari public static Document getBet(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d_tmp = collection .find(and(new BsonDocument().append("gamblerLogin", new BsonString(login)), new BsonDocument().append("idBetPool", new BsonString(idPool)))) .first(); return d_tmp; } // Renvoi true si le résultat d'un pari est disponible, c'est a dire que la date corurante est après la date des résultats public static boolean betResultIsAvailable(String idPool) throws URISyntaxException, SQLException { String query = "SELECT * FROM BETPOOL WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if (res.next()) { if (res.getTimestamp("resultbet").before(new Timestamp(System.currentTimeMillis()))) { pstmt.close(); c.close(); return true; } } } return false; } // Renvoi true si un utilisateur a deja vérifier le résultat de son pari public static boolean haveCheckResultAlready(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d_tmp = collection .find(and(new BsonDocument().append("gamblerLogin", new BsonString(login)), new BsonDocument().append("idBetPool", new BsonString(idPool)))) .first(); return d_tmp.getBoolean("haveCheckResult"); } private static String getCryptNickname(String cryptFullName){ switch (cryptFullName){ case "Bitcoin": return "BTC"; case "Ethereum": return "ETH"; case "EthereumClassic": return "ETC"; case "LiteCoin": return "LTC"; case "BitcoinCash" : return "BCH"; case "ZCash": return "ZEC"; case "Dash": return "DASH"; default: return cryptFullName; } } }
UTF-8
Java
17,768
java
BetTools.java
Java
[]
null
[]
package bd; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.util.JSON; import org.bson.BsonDocument; import org.bson.BsonString; import org.bson.Document; import org.bson.conversions.Bson; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.net.URISyntaxException; import java.sql.*; import java.util.ArrayList; import java.util.List; import static bd.Database.getMongoCollection; import static bd.PoolTools.poolExist; import static com.mongodb.client.model.Filters.and; public class BetTools { // renvoi true si un joueur a un sodle suffisant pour parier un certain montant public static boolean hasEnoughCoin(String login,String ammount) throws SQLException, URISyntaxException { String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet result = pstmt.executeQuery(); result.next(); int solde = result.getInt(1); solde = solde - Integer.parseInt(ammount); if (solde < 0) { return false; } } return true; } /* renvois la liste des salons de pari encore actif */ public static JSONArray getListPoolsActive() { JSONArray ar = new JSONArray(); String query = "SELECT idbetpool, name, openingbet, closingbet, resultbet, cryptocurrency, pooltype FROM BetPool WHERE closingBet > NOW() AT TIME ZONE 'Europe/Paris' AND openingBet <= NOW() AT TIME ZONE 'Europe/Paris'"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query); ResultSet v = pstmt.executeQuery(); ) { JSONObject j = null; while (v.next()) { j = new JSONObject(); j.put("idbetpool", v.getInt(1)); j.put("name", v.getString(2)); j.put("openingbet", v.getTimestamp(3)); j.put("closingbet", v.getTimestamp(4)); j.put("resultbet", v.getTimestamp(5)); j.put("cryptocurrency", v.getString(6)); j.put("pooltype", v.getBoolean(7)); ar.put(j); } } catch (Exception e) { } finally { return ar; } } /* Permet aux utilisateurs d'ajouter un nouveau pari*/ public static boolean addBet(String idPool, String login, int betAmmount, double betValue) throws URISyntaxException, SQLException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); Timestamp tsp = new Timestamp(System.currentTimeMillis()+3600000); if (d == null) { Document newpool = new Document(); newpool.append("idBetPool", idPool); newpool.append("resultValue", 0.0); ArrayList<Document> bets = new ArrayList<>(); Document bet_obj = new Document(); bet_obj.append("gamblerLogin", login); bet_obj.append("betAmount", betAmmount); bet_obj.append("betValue", betValue); bet_obj.append("betDate", tsp.toString()); bets.add(bet_obj); newpool.append("bet", bets); collection.insertOne(newpool); d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); } else { d = collection.find(new BsonDocument().append("idBetPool", new BsonString(idPool))).first(); List<Document> list_bet = (List<Document>) d.get("bet"); Document bet_obj = new Document(); bet_obj.append("gamblerLogin", login); bet_obj.append("betAmount", betAmmount); bet_obj.append("betValue", betValue); bet_obj.append("betDate", tsp.toString()); list_bet.add(bet_obj); BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); collection.updateOne(filter, new Document("$set", new Document("bet", list_bet))); } String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet result = pstmt.executeQuery(); result.next(); int solde = result.getInt(1); solde = solde - betAmmount; query = "UPDATE USERS SET solde=? WHERE login=?"; try (PreparedStatement pstmt2 = c.prepareStatement(query)) { pstmt2.setInt(1, solde); pstmt2.setString(2, login); pstmt2.executeUpdate(); } } collection = getMongoCollection("Bet"); Document obj = new Document(); obj.append("gamblerLogin", login); obj.append("idBetPool", idPool); obj.append("betAmount", betAmmount); obj.append("betValue", betValue); obj.append("betDate", tsp.toString()); obj.append("haveCheckResult", false); collection.insertOne(obj); return true; } // Vérifie l'existance d'un pari public static boolean checkBetExist(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if (d != null) return true; return false; } /* Renvoi true si un pari est toujours annulable */ public static boolean betPoolOpen(String idPool) throws URISyntaxException, SQLException { String query = "SELECT * FROM BETPOOL WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if (res.next()) { if (res.getTimestamp("closingbet").after(new Timestamp(System.currentTimeMillis()))) { pstmt.close(); c.close(); return true; } } } return false; } /* Annule un bet*/ public static boolean cancelBet(String login, String idPool) throws URISyntaxException, SQLException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); if (d == null) { return false; } else { BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); List<Document> bets = (List<Document>) d.get("bet"); for (int i = 0; i < bets.size(); i++) { if (bets.get(i).get("gamblerLogin").equals(login)) { int toRefound = bets.get(i).getInteger("betAmount"); bets.remove(i); collection.updateOne(filter, new Document("$set", new Document("bet", bets))); Connection co = Database.getConnection(); String query = "UPDATE USERS SET solde=solde+? WHERE login=?"; PreparedStatement pstmt = co.prepareStatement(query); pstmt.setInt(1, toRefound); pstmt.setString(2, login); pstmt.executeUpdate(); pstmt.close(); collection = getMongoCollection("Bet"); d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if(d==null){ return false; } collection.deleteOne(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))); return true; } } return false; } } // Renvoi le montant gagné par un pari (ou 0 si le pari est perdu) public static int betWon(String login, String idPool) throws URISyntaxException, SQLException, IOException { MongoCollection<Document> collection = getMongoCollection("L_Bet"); Document d_tmp = collection .find(new BsonDocument().append("idBetPool", new BsonString(idPool))) .first(); double resultValue = d_tmp.getDouble("resultValue"); // On est la premiere personne a vérifier son pari, dans ce cas on va chercher la valeur du resultat dans l'API et on rempli notre BD avec ce resultat if(resultValue == 0){ resultValue = updateDBResultValue(idPool, login); if(resultValue == 0){ return -1; } } collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); double betValue = d.getDouble("betValue"); if(!setHaveCheckResultTrue(login, idPool)){ return -1; } if (betValue == resultValue) { String amount_s = d.get("betAmount").toString(); int amount_i = Integer.parseInt(amount_s); return updateAccountGoldWin(amount_i, idPool, login); } return 0; } // Marque un pari dans la BD afin de signaler que l'on a deja vérifié le résultat d'un pari private static boolean setHaveCheckResultTrue(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d = collection .find(and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login)))) .first(); if (d == null) { return false; } Bson filter = and(new BsonDocument().append("idBetPool", new BsonString(idPool)), new BsonDocument().append("gamblerLogin", new BsonString(login))); collection.updateOne(filter,new Document("$set", new Document("haveCheckResult", true))); return true; } // Met a jour le solde d'un joueur en fonction du montant parié et du multiplicateur de gains private static int updateAccountGoldWin(int ammountBet, String idPool, String login) throws URISyntaxException, SQLException { String query = "SELECT solde FROM USERS WHERE login=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setString(1, login); ResultSet res = pstmt.executeQuery(); if(res.next()) { int soldeAccount = res.getInt(1); res.close(); int amountWon = 0; boolean type; query = "SELECT pooltype FROM BETPOOL WHERE idbetpool=?"; try (PreparedStatement pstmt3 = c.prepareStatement(query);) { pstmt3.setInt(1, Integer.parseInt(idPool)); ResultSet restype = pstmt3.executeQuery(); if(restype.next()) { type = restype.getBoolean(1); restype.close(); if (type) { amountWon = ammountBet * 10; } else { amountWon = (int) Math.round(ammountBet * 1.5); } } } soldeAccount = soldeAccount + amountWon; query = "UPDATE USERS SET solde=? WHERE login=?"; try (PreparedStatement pstmt2 = c.prepareStatement(query);) { pstmt2.setInt(1, soldeAccount); pstmt2.setString(2, login); pstmt2.executeUpdate(); } return amountWon; } } return -1; } // Met a jour le resultat d'une pool, elle est faite 1 fois par pool (Apres que la date courrante soit supérieur a la date des resultats private static double updateDBResultValue(String idPool, String login) throws URISyntaxException, SQLException, IOException { String query = "SELECT * FROM betpool WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if(res.next()) { String crypt = res.getString("cryptocurrency"); Timestamp time = res.getTimestamp("resultbet"); Boolean poolType = res.getBoolean("pooltype"); double openingPrice = res.getDouble("openingprice"); res.close(); double resultValue = APITools.getPriceSpecificTime(getCryptNickname(crypt),"EUR",(time.getTime()/1000)+""); MongoCollection<Document> collection = getMongoCollection("L_Bet"); BsonDocument filter = new BsonDocument().append("idBetPool", new BsonString(idPool)); if(poolType) { collection.updateOne(filter, new Document("$set", new Document("resultValue", resultValue))); }else{ collection.updateOne(filter, new Document("$set", new Document("resultValue", (resultValue > openingPrice)? 1.0 : -1.0))); } return resultValue; } } return 0; } // renvoi la liste des pari public static JSONArray getListBets(String login) { MongoCollection<Document> collection = getMongoCollection("Bet"); JSONArray array = new JSONArray(); try(MongoCursor<Document> d_tmp = collection .find(new BsonDocument().append("gamblerLogin", new BsonString(login))).iterator();) { while (d_tmp.hasNext()) { Document tmp = d_tmp.next(); array.put(tmp); } } return array; } // Renvoi les informations d'un pari public static Document getBet(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d_tmp = collection .find(and(new BsonDocument().append("gamblerLogin", new BsonString(login)), new BsonDocument().append("idBetPool", new BsonString(idPool)))) .first(); return d_tmp; } // Renvoi true si le résultat d'un pari est disponible, c'est a dire que la date corurante est après la date des résultats public static boolean betResultIsAvailable(String idPool) throws URISyntaxException, SQLException { String query = "SELECT * FROM BETPOOL WHERE idbetpool=?"; try (Connection c = Database.getConnection(); PreparedStatement pstmt = c.prepareStatement(query);) { pstmt.setInt(1, Integer.parseInt(idPool)); ResultSet res = pstmt.executeQuery(); if (res.next()) { if (res.getTimestamp("resultbet").before(new Timestamp(System.currentTimeMillis()))) { pstmt.close(); c.close(); return true; } } } return false; } // Renvoi true si un utilisateur a deja vérifier le résultat de son pari public static boolean haveCheckResultAlready(String login, String idPool) { MongoCollection<Document> collection = getMongoCollection("Bet"); Document d_tmp = collection .find(and(new BsonDocument().append("gamblerLogin", new BsonString(login)), new BsonDocument().append("idBetPool", new BsonString(idPool)))) .first(); return d_tmp.getBoolean("haveCheckResult"); } private static String getCryptNickname(String cryptFullName){ switch (cryptFullName){ case "Bitcoin": return "BTC"; case "Ethereum": return "ETH"; case "EthereumClassic": return "ETC"; case "LiteCoin": return "LTC"; case "BitcoinCash" : return "BCH"; case "ZCash": return "ZEC"; case "Dash": return "DASH"; default: return cryptFullName; } } }
17,768
0.563447
0.559617
431
40.194897
33.124374
222
false
false
0
0
0
0
0
0
0.800464
false
false
13
68c9b3dd84ea1071ce3ccdd04344a33e35ae6176
20,005,957,732,987
26aca728ac0b9bafcd3ec3eaaa5aae9d352a55d8
/src/main/java/br/com/supercloud/dynamic/HowSum.java
acb453f6e4d738360d9a47e6f2086201fb86c73a
[ "MIT" ]
permissive
thiagotigaz/algorithms-solutions
https://github.com/thiagotigaz/algorithms-solutions
53dce39a74d8e0f5755f2ceb98687eb9482b18d8
abb32703f0beb200d78063bcfd0b1836a3e35a13
refs/heads/master
2021-11-13T21:22:32.017000
2021-10-28T20:14:57
2021-10-28T20:14:57
204,752,339
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.supercloud.dynamic; import java.util.*; public class HowSum { public static void main(String[] args) { System.out.println(howSumTabulation(7, new int[]{2, 3})); System.out.println(howSumTabulation(7, new int[]{5, 3, 4, 7})); System.out.println(howSumTabulation(7, new int[]{2, 4})); System.out.println(howSumTabulation(8, new int[]{2, 3, 5})); System.out.println(); System.out.println(howSum(7, new int[]{2, 3})); System.out.println(howSum(7, new int[]{5, 3, 4, 7})); System.out.println(howSum(7, new int[]{2, 4})); System.out.println(howSum(8, new int[]{2, 3, 5})); System.out.println(); // System.out.println(howSumWithMemo(7, new int[]{2, 3})); // System.out.println(howSumWithMemo(7, new int[]{5, 3, 4, 7})); // System.out.println(howSumWithMemo(7, new int[]{2, 4})); // System.out.println(howSumWithMemo(8, new int[]{2, 3, 5})); // System.out.println(howSumWithMemo(3000, new int[]{7, 14, 100})); } private static List<Integer> howSum(int targetSum, int[] numbers) { if (targetSum == 0) return new ArrayList<>(); if (targetSum < 0) return null; for (int num : numbers) { int remainder = targetSum - num; List<Integer> remainderResult = howSum(remainder, numbers); if (remainderResult != null) { remainderResult.add(num); return remainderResult; } } return null; } private static List<Integer> howSumWithMemo(int targetSum, int[] numbers) { return howSumWithMemo(targetSum, numbers, new HashMap<>()); } private static List<Integer> howSumWithMemo(int targetSum, int[] numbers, Map<Integer, List<Integer>> memo) { if (memo.containsKey(targetSum)) return memo.get(targetSum); if (targetSum == 0) return new LinkedList<>(); if (targetSum < 0) return null; for (int num : numbers) { int remainder = targetSum - num; List<Integer> remainderResult = howSumWithMemo(remainder, numbers, memo); if (remainderResult != null) { remainderResult.add(num); memo.put(targetSum, remainderResult); return remainderResult; } } memo.put(targetSum, null); return null; } private static List<Integer> howSumTabulation(int targetSum, int[] numbers) { ArrayList<Integer>[] result = new ArrayList[targetSum + 1]; result[0] = new ArrayList<>(); for (int i = 0; i <= targetSum; i++) { if (result[i] != null) { for (int n : numbers) { if (i + n < result.length) { ArrayList<Integer> newArr = new ArrayList<>(result[i].size() + 1); newArr.addAll(result[i]); newArr.add(n); result[i + n] = newArr; } } } } return result[targetSum]; } }
UTF-8
Java
3,102
java
HowSum.java
Java
[]
null
[]
package br.com.supercloud.dynamic; import java.util.*; public class HowSum { public static void main(String[] args) { System.out.println(howSumTabulation(7, new int[]{2, 3})); System.out.println(howSumTabulation(7, new int[]{5, 3, 4, 7})); System.out.println(howSumTabulation(7, new int[]{2, 4})); System.out.println(howSumTabulation(8, new int[]{2, 3, 5})); System.out.println(); System.out.println(howSum(7, new int[]{2, 3})); System.out.println(howSum(7, new int[]{5, 3, 4, 7})); System.out.println(howSum(7, new int[]{2, 4})); System.out.println(howSum(8, new int[]{2, 3, 5})); System.out.println(); // System.out.println(howSumWithMemo(7, new int[]{2, 3})); // System.out.println(howSumWithMemo(7, new int[]{5, 3, 4, 7})); // System.out.println(howSumWithMemo(7, new int[]{2, 4})); // System.out.println(howSumWithMemo(8, new int[]{2, 3, 5})); // System.out.println(howSumWithMemo(3000, new int[]{7, 14, 100})); } private static List<Integer> howSum(int targetSum, int[] numbers) { if (targetSum == 0) return new ArrayList<>(); if (targetSum < 0) return null; for (int num : numbers) { int remainder = targetSum - num; List<Integer> remainderResult = howSum(remainder, numbers); if (remainderResult != null) { remainderResult.add(num); return remainderResult; } } return null; } private static List<Integer> howSumWithMemo(int targetSum, int[] numbers) { return howSumWithMemo(targetSum, numbers, new HashMap<>()); } private static List<Integer> howSumWithMemo(int targetSum, int[] numbers, Map<Integer, List<Integer>> memo) { if (memo.containsKey(targetSum)) return memo.get(targetSum); if (targetSum == 0) return new LinkedList<>(); if (targetSum < 0) return null; for (int num : numbers) { int remainder = targetSum - num; List<Integer> remainderResult = howSumWithMemo(remainder, numbers, memo); if (remainderResult != null) { remainderResult.add(num); memo.put(targetSum, remainderResult); return remainderResult; } } memo.put(targetSum, null); return null; } private static List<Integer> howSumTabulation(int targetSum, int[] numbers) { ArrayList<Integer>[] result = new ArrayList[targetSum + 1]; result[0] = new ArrayList<>(); for (int i = 0; i <= targetSum; i++) { if (result[i] != null) { for (int n : numbers) { if (i + n < result.length) { ArrayList<Integer> newArr = new ArrayList<>(result[i].size() + 1); newArr.addAll(result[i]); newArr.add(n); result[i + n] = newArr; } } } } return result[targetSum]; } }
3,102
0.547711
0.527402
79
38.265823
26.686985
113
false
false
0
0
0
0
0
0
1.177215
false
false
13
2cb76e0636a11ce0a82b8d6050c15818da360d78
26,749,056,387,008
27bb9f4e0aed9a6056cfd1512d95e02ab67f6d7b
/examples/designpatterns/mvc/MVCExampleResults/src/main/java/nl/ddoa/example/dice/DobbelsteenSwingView.java
7a8ff6fa4acffc0b468080cc10e1134d0fbc3187
[ "MIT" ]
permissive
FrancescaWiegman/dea-code-examples
https://github.com/FrancescaWiegman/dea-code-examples
71ec96fe02acde0093e090d44e112a94c6c1e656
2794149ef61b24d70f2ed443f877186661c9f0e5
refs/heads/master
2020-04-07T14:35:47.446000
2018-03-12T15:09:06
2018-03-12T15:09:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.ddoa.example.dice; import java.awt.Container; import java.net.URL; import java.util.Observable; import java.util.Observer; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; @SuppressWarnings("serial") public class DobbelsteenSwingView extends JFrame implements Observer { private int dobbelwaarde; public DobbelsteenSwingView() { setLocation(500, 500); setSize(100, 100); setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void setDobbelwaarde(int waarde) { this.dobbelwaarde = waarde; } public void showMe() { Container ctr = this.getContentPane(); URL fileLoc = ClassLoader.getSystemResource(dobbelwaarde + ".jpg"); JLabel jl = new JLabel(new ImageIcon(fileLoc)); ctr.add(jl); validate(); } public void update(Observable o, Object arg) { if (arg instanceof Integer) { this.setDobbelwaarde(((Integer) arg).intValue()); this.showMe(); } } }
UTF-8
Java
1,094
java
DobbelsteenSwingView.java
Java
[]
null
[]
package nl.ddoa.example.dice; import java.awt.Container; import java.net.URL; import java.util.Observable; import java.util.Observer; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; @SuppressWarnings("serial") public class DobbelsteenSwingView extends JFrame implements Observer { private int dobbelwaarde; public DobbelsteenSwingView() { setLocation(500, 500); setSize(100, 100); setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void setDobbelwaarde(int waarde) { this.dobbelwaarde = waarde; } public void showMe() { Container ctr = this.getContentPane(); URL fileLoc = ClassLoader.getSystemResource(dobbelwaarde + ".jpg"); JLabel jl = new JLabel(new ImageIcon(fileLoc)); ctr.add(jl); validate(); } public void update(Observable o, Object arg) { if (arg instanceof Integer) { this.setDobbelwaarde(((Integer) arg).intValue()); this.showMe(); } } }
1,094
0.648995
0.638026
46
22.782608
19.949842
75
false
false
0
0
0
0
0
0
0.521739
false
false
13
8e5fd8352512066359e75978023c37749fa5bf3b
26,749,056,388,771
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes10.dex_source_from_JADX/com/facebook/payments/settings/model/PaymentSettingsPickerScreenData.java
1b2bf09f19a8d945ef2023a04547cdcb48961cef
[]
no_license
pxson001/facebook-app
https://github.com/pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758000
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.payments.settings.model; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable.Creator; import com.facebook.payments.paymentmethods.model.PaymentMethodsInfo; import com.facebook.payments.paymentmethods.picker.PickerScreenParams; import com.facebook.payments.paymentmethods.picker.model.PickerScreenData; import com.facebook.payments.shipping.model.MailingAddress; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @Immutable /* compiled from: location_ts */ public class PaymentSettingsPickerScreenData implements PickerScreenData { public static final Creator<PaymentSettingsPickerScreenData> CREATOR = new C12581(); public final PaymentMethodsInfo f8440a; public final ImmutableList<MailingAddress> f8441b; public final PickerScreenParams f8442c; /* compiled from: location_ts */ final class C12581 implements Creator<PaymentSettingsPickerScreenData> { C12581() { } public final Object createFromParcel(Parcel parcel) { return new PaymentSettingsPickerScreenData(parcel); } public final Object[] newArray(int i) { return new PaymentSettingsPickerScreenData[i]; } } public PaymentSettingsPickerScreenData(PaymentSettingsPickerScreenDataBuilder paymentSettingsPickerScreenDataBuilder) { this.f8440a = paymentSettingsPickerScreenDataBuilder.f8443a; this.f8441b = (ImmutableList) Preconditions.checkNotNull(paymentSettingsPickerScreenDataBuilder.f8444b); this.f8442c = (PickerScreenParams) Preconditions.checkNotNull(paymentSettingsPickerScreenDataBuilder.f8445c); } public PaymentSettingsPickerScreenData(Parcel parcel) { this.f8440a = (PaymentMethodsInfo) parcel.readParcelable(PaymentMethodsInfo.class.getClassLoader()); this.f8441b = ImmutableList.copyOf(parcel.readArrayList(MailingAddress.class.getClassLoader())); this.f8442c = (PickerScreenParams) parcel.readParcelable(PickerScreenParams.class.getClassLoader()); } public final PickerScreenParams m8370a() { return this.f8442c; } @Nullable public final Intent m8371b() { return null; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(this.f8440a, i); parcel.writeList(this.f8441b); parcel.writeParcelable(this.f8442c, i); } }
UTF-8
Java
2,587
java
PaymentSettingsPickerScreenData.java
Java
[]
null
[]
package com.facebook.payments.settings.model; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable.Creator; import com.facebook.payments.paymentmethods.model.PaymentMethodsInfo; import com.facebook.payments.paymentmethods.picker.PickerScreenParams; import com.facebook.payments.paymentmethods.picker.model.PickerScreenData; import com.facebook.payments.shipping.model.MailingAddress; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @Immutable /* compiled from: location_ts */ public class PaymentSettingsPickerScreenData implements PickerScreenData { public static final Creator<PaymentSettingsPickerScreenData> CREATOR = new C12581(); public final PaymentMethodsInfo f8440a; public final ImmutableList<MailingAddress> f8441b; public final PickerScreenParams f8442c; /* compiled from: location_ts */ final class C12581 implements Creator<PaymentSettingsPickerScreenData> { C12581() { } public final Object createFromParcel(Parcel parcel) { return new PaymentSettingsPickerScreenData(parcel); } public final Object[] newArray(int i) { return new PaymentSettingsPickerScreenData[i]; } } public PaymentSettingsPickerScreenData(PaymentSettingsPickerScreenDataBuilder paymentSettingsPickerScreenDataBuilder) { this.f8440a = paymentSettingsPickerScreenDataBuilder.f8443a; this.f8441b = (ImmutableList) Preconditions.checkNotNull(paymentSettingsPickerScreenDataBuilder.f8444b); this.f8442c = (PickerScreenParams) Preconditions.checkNotNull(paymentSettingsPickerScreenDataBuilder.f8445c); } public PaymentSettingsPickerScreenData(Parcel parcel) { this.f8440a = (PaymentMethodsInfo) parcel.readParcelable(PaymentMethodsInfo.class.getClassLoader()); this.f8441b = ImmutableList.copyOf(parcel.readArrayList(MailingAddress.class.getClassLoader())); this.f8442c = (PickerScreenParams) parcel.readParcelable(PickerScreenParams.class.getClassLoader()); } public final PickerScreenParams m8370a() { return this.f8442c; } @Nullable public final Intent m8371b() { return null; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(this.f8440a, i); parcel.writeList(this.f8441b); parcel.writeParcelable(this.f8442c, i); } }
2,587
0.755315
0.721299
67
37.611938
33.771824
123
false
false
0
0
0
0
0
0
0.492537
false
false
13
c3e1945cf72ed8ab608165a6f2a287f2b76e4625
7,292,854,472,106
b019866656147be4c4fa1b4a3d9e8867f722bf09
/src/main/java/com/codeteam/website/modules/about/dao/SiteAboutMapper.java
4a9af9cbaf8c07dc97f343c731c057934cdb2510
[]
no_license
AkaSiran/Website
https://github.com/AkaSiran/Website
9b61bd64803aec1793785b712865d6532040211e
24c3aa5d4209bd7ddbd0516bb643f318eaef2526
refs/heads/master
2023-06-19T05:35:13.269000
2021-07-23T02:31:46
2021-07-23T02:31:46
385,782,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codeteam.website.modules.about.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.codeteam.website.modules.about.entity.po.SiteAboutPo; /** * Created by Fyc on 2021-7-12. * 关于我们 */ public interface SiteAboutMapper extends BaseMapper<SiteAboutPo> { }
UTF-8
Java
296
java
SiteAboutMapper.java
Java
[ { "context": "es.about.entity.po.SiteAboutPo;\n\n/**\n * Created by Fyc on 2021-7-12.\n * 关于我们\n */\npublic interface SiteAb", "end": 192, "score": 0.996475338935852, "start": 189, "tag": "USERNAME", "value": "Fyc" } ]
null
[]
package com.codeteam.website.modules.about.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.codeteam.website.modules.about.entity.po.SiteAboutPo; /** * Created by Fyc on 2021-7-12. * 关于我们 */ public interface SiteAboutMapper extends BaseMapper<SiteAboutPo> { }
296
0.784722
0.760417
12
23
25.993589
64
false
false
0
0
0
0
0
0
0.25
false
false
13
25ad9f9fc254094c1379ba509039c80a5a66e1da
27,608,049,844,929
72ee1490b4a17b9c1fefa22d735ee6cf2648b4a8
/src/main/java/lab3/pass/SkiPassType.java
957b3036a30242240df7807588c2c9ce6601a744
[]
no_license
Sayuri/kpi-labs
https://github.com/Sayuri/kpi-labs
53bb55f515ac89f50ddb22d755f69fc9d45cfdfa
091ed36d2e48e7c7d0d5124fc310b67429534c0c
refs/heads/master
2022-09-05T00:04:22.233000
2020-05-29T06:22:04
2020-05-29T06:22:04
267,750,192
0
0
null
false
2020-05-29T06:22:05
2020-05-29T02:50:31
2020-05-29T06:17:25
2020-05-29T06:22:05
62
0
0
1
Java
false
false
package lab3.pass; public enum SkiPassType { BASIC, PREFERENTIAL, VIP; }
UTF-8
Java
86
java
SkiPassType.java
Java
[]
null
[]
package lab3.pass; public enum SkiPassType { BASIC, PREFERENTIAL, VIP; }
86
0.651163
0.639535
7
11.285714
8.547585
25
false
false
0
0
0
0
0
0
0.571429
false
false
13
39a739033dfa9558f16631026325b4cd2130838c
8,358,006,364,520
8f8129823a17086702cfb55965760b999059107f
/hlt/GameMap.java
62a035db4cf1a1962ee0b057e46cfe70fdf73a4f
[]
no_license
clbarrell/hatlite_17_bot
https://github.com/clbarrell/hatlite_17_bot
5b0b6417c00348eaf7f6513685ec90fade88ada5
7a314109e11c24ad97d8b9bcf661269418d58dae
refs/heads/master
2021-09-03T14:57:18.915000
2018-01-09T23:54:18
2018-01-09T23:54:18
116,882,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hlt; import java.util.*; public class GameMap { private final int width, height; private final int playerId; private final List<Player> players; private final List<Player> playersUnmodifiable; private final Map<Integer, Planet> planets; private final List<Ship> allShips; private final List<Ship> allShipsUnmodifiable; private final List<Ship> allEnemyShips; public List<ThrustMove> myMoves; // used only during parsing to reduce memory allocations private final List<Ship> currentShips = new ArrayList<>(); public GameMap(final int width, final int height, final int playerId) { this.width = width; this.height = height; this.playerId = playerId; players = new ArrayList<>(Constants.MAX_PLAYERS); playersUnmodifiable = Collections.unmodifiableList(players); planets = new TreeMap<>(); allShips = new ArrayList<>(); allEnemyShips = new ArrayList<>(); allShipsUnmodifiable = Collections.unmodifiableList(allShips); myMoves = new ArrayList<>(); } public int getHeight() { return height; } public int getWidth() { return width; } public boolean isMyEntity(Entity entity) { return this.playerId == entity.getOwner(); } public int getMyPlayerId() { return playerId; } public List<Player> getAllPlayers() { return playersUnmodifiable; } public List<Ship> getAllEnemyShips() { return allEnemyShips; } public Player getMyPlayer() { return getAllPlayers().get(getMyPlayerId()); } public Ship getShip(final int playerId, final int entityId) throws IndexOutOfBoundsException { return players.get(playerId).getShip(entityId); } public Planet getPlanet(final int entityId) { return planets.get(entityId); } public Map<Integer, Planet> getAllPlanets() { return planets; } public List<Ship> getAllShips() { return allShipsUnmodifiable; } public void addMove(ThrustMove newMove) { myMoves.add(newMove); } public List<ThrustMove> getMyMoves() { return myMoves; } public ArrayList<Entity> objectsBetween(Position start, Position target) { final ArrayList<Entity> entitiesFound = new ArrayList<>(); addEntitiesBetween(entitiesFound, start, target, planets.values()); addEntitiesBetween(entitiesFound, start, target, allShips); return entitiesFound; } private static void addEntitiesBetween(final List<Entity> entitiesFound, final Position start, final Position target, final Collection<? extends Entity> entitiesToCheck) { for (final Entity entity : entitiesToCheck) { if (entity.equals(start) || entity.equals(target)) { continue; } if (Collision.segmentCircleIntersect(start, target, entity, Constants.FORECAST_FUDGE_FACTOR)) { entitiesFound.add(entity); } } } public Map<Double, Entity> nearbyEntitiesByDistance(final Entity entity) { final Map<Double, Entity> entityByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { if (planet.equals(entity)) { continue; } entityByDistance.put(entity.getDistanceTo(planet), planet); } for (final Ship ship : allShips) { if (ship.equals(entity)) { continue; } entityByDistance.put(entity.getDistanceTo(ship), ship); } return entityByDistance; } public double nearbyShipDensity(final Ship entity) { // final Map<Double, Ship> nearbyShips = nearbyAllShipsByDistance(entity); double runningScore = 0; for (Ship otherShip : getAllShips()) { if (entity.getDistanceTo(otherShip) > (4 * entity.getRadius())) { break; } if (otherShip.getOwner() == getMyPlayerId()) { // my ship runningScore += 1; } else { // not my ship runningScore -= 1; } } entity.logMyAction("runningScore: " + runningScore); return runningScore; } public Map<Double, Ship> nearbyAllShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); for (Ship otherShip : getAllShips()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } return shipByDistance; } public ArrayList<Ship> nearbyMyShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); for (Ship otherShip : getMyPlayer().getShips().values()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } return new ArrayList<Ship>(shipByDistance.values()); } public ArrayList<Ship> nearbyShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); // Log.log("AllEnemyShips: " + getAllEnemyShips().size()); for (Ship otherShip : getAllEnemyShips()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } // Log.log("nearbyShipsByDistance: " + shipByDistance.size()); return new ArrayList<Ship>(shipByDistance.values()); //return shipByDistance; } public Map<Double, Planet> nearbyPlanetsByDistance(final Entity ship) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { planetByDistance.put(ship.getDistanceTo(planet), planet); } return planetByDistance; } public Map<Double, Planet> nearbyPlanetsByScore(final Entity ship, double maxRadius) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); double score; for (final Planet planet : planets.values()) { double radius = planet.getRadius() / maxRadius; double curve = curve(radius, CurveType.Linear, -1, 1, 1.5, 0); score = curve * ship.getDistanceTo(planet); // if ((ship.getId() % 5) == 0) { // Log.log("Planet ID: " + planet.getId() + " dist / radius / curve / score " + ship.getDistanceTo(planet) + " / " + radius + " / " + curve + " / " + score); // } planetByDistance.put(score, planet); } return planetByDistance; } private enum CurveType { Parabola, Linear, Logistic } // plots x value onto curve, returning value that is between 0-1 private double curve(double x, CurveType curve, double mSlope, double kExponent, double yShift, double xShift) { // m = slope, k = exponential, b = y shift, c = x shift double value = 1; switch(curve) { case Parabola: value = mSlope * Math.pow((x - xShift), kExponent) + yShift; break; case Linear: value = mSlope * (x - xShift) + yShift; // Log.log("Linear curved: " + value); break; case Logistic: double denom = 1 + Math.pow((Math.E * mSlope), (x*kExponent + xShift)); value = (1 / denom) + yShift; break; } return clamp(value, 0, 1); } // clamp will ensure that no value is beyond max or below min // preffered use is noramalise above public double clamp(double initialValue, double min, double max) { double fin = 1; if (initialValue >= min && initialValue <= max) { fin = initialValue; } else if (initialValue < min) { fin = min; } else if (initialValue > max) { fin = max; } // Log.log("Clamping: " + fin); return fin; } public Map<Double, Planet> nearbyKeyPlanetsByDistance(final Entity ship) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { if (planet.getRadius() > 10) { planetByDistance.put(ship.getDistanceTo(planet), planet); } } return planetByDistance; } public GameMap updateMap(final Metadata mapMetadata) { final int numberOfPlayers = MetadataParser.parsePlayerNum(mapMetadata); Log.log("Total moves was: " + myMoves.size()); players.clear(); planets.clear(); allShips.clear(); allEnemyShips.clear(); myMoves.clear(); // update players info for (int i = 0; i < numberOfPlayers; ++i) { currentShips.clear(); final Map<Integer, Ship> currentPlayerShips = new TreeMap<>(); final int playerId = MetadataParser.parsePlayerId(mapMetadata); final Player currentPlayer = new Player(playerId, currentPlayerShips); MetadataParser.populateShipList(currentShips, playerId, mapMetadata); allShips.addAll(currentShips); if (getMyPlayerId() != currentPlayer.getId()) { allEnemyShips.addAll(currentShips); } for (final Ship ship : currentShips) { currentPlayerShips.put(ship.getId(), ship); } players.add(currentPlayer); } final int numberOfPlanets = Integer.parseInt(mapMetadata.pop()); for (int i = 0; i < numberOfPlanets; ++i) { final List<Integer> dockedShips = new ArrayList<>(); final Planet planet = MetadataParser.newPlanetFromMetadata(dockedShips, mapMetadata); planets.put(planet.getId(), planet); } if (!mapMetadata.isEmpty()) { throw new IllegalStateException("Failed to parse data from Halite game engine. Please contact maintainers."); } Log.log("Total ships: " + allShips.size() + "... Enemy ships: " + allEnemyShips.size()); return this; } }
UTF-8
Java
10,159
java
GameMap.java
Java
[]
null
[]
package hlt; import java.util.*; public class GameMap { private final int width, height; private final int playerId; private final List<Player> players; private final List<Player> playersUnmodifiable; private final Map<Integer, Planet> planets; private final List<Ship> allShips; private final List<Ship> allShipsUnmodifiable; private final List<Ship> allEnemyShips; public List<ThrustMove> myMoves; // used only during parsing to reduce memory allocations private final List<Ship> currentShips = new ArrayList<>(); public GameMap(final int width, final int height, final int playerId) { this.width = width; this.height = height; this.playerId = playerId; players = new ArrayList<>(Constants.MAX_PLAYERS); playersUnmodifiable = Collections.unmodifiableList(players); planets = new TreeMap<>(); allShips = new ArrayList<>(); allEnemyShips = new ArrayList<>(); allShipsUnmodifiable = Collections.unmodifiableList(allShips); myMoves = new ArrayList<>(); } public int getHeight() { return height; } public int getWidth() { return width; } public boolean isMyEntity(Entity entity) { return this.playerId == entity.getOwner(); } public int getMyPlayerId() { return playerId; } public List<Player> getAllPlayers() { return playersUnmodifiable; } public List<Ship> getAllEnemyShips() { return allEnemyShips; } public Player getMyPlayer() { return getAllPlayers().get(getMyPlayerId()); } public Ship getShip(final int playerId, final int entityId) throws IndexOutOfBoundsException { return players.get(playerId).getShip(entityId); } public Planet getPlanet(final int entityId) { return planets.get(entityId); } public Map<Integer, Planet> getAllPlanets() { return planets; } public List<Ship> getAllShips() { return allShipsUnmodifiable; } public void addMove(ThrustMove newMove) { myMoves.add(newMove); } public List<ThrustMove> getMyMoves() { return myMoves; } public ArrayList<Entity> objectsBetween(Position start, Position target) { final ArrayList<Entity> entitiesFound = new ArrayList<>(); addEntitiesBetween(entitiesFound, start, target, planets.values()); addEntitiesBetween(entitiesFound, start, target, allShips); return entitiesFound; } private static void addEntitiesBetween(final List<Entity> entitiesFound, final Position start, final Position target, final Collection<? extends Entity> entitiesToCheck) { for (final Entity entity : entitiesToCheck) { if (entity.equals(start) || entity.equals(target)) { continue; } if (Collision.segmentCircleIntersect(start, target, entity, Constants.FORECAST_FUDGE_FACTOR)) { entitiesFound.add(entity); } } } public Map<Double, Entity> nearbyEntitiesByDistance(final Entity entity) { final Map<Double, Entity> entityByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { if (planet.equals(entity)) { continue; } entityByDistance.put(entity.getDistanceTo(planet), planet); } for (final Ship ship : allShips) { if (ship.equals(entity)) { continue; } entityByDistance.put(entity.getDistanceTo(ship), ship); } return entityByDistance; } public double nearbyShipDensity(final Ship entity) { // final Map<Double, Ship> nearbyShips = nearbyAllShipsByDistance(entity); double runningScore = 0; for (Ship otherShip : getAllShips()) { if (entity.getDistanceTo(otherShip) > (4 * entity.getRadius())) { break; } if (otherShip.getOwner() == getMyPlayerId()) { // my ship runningScore += 1; } else { // not my ship runningScore -= 1; } } entity.logMyAction("runningScore: " + runningScore); return runningScore; } public Map<Double, Ship> nearbyAllShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); for (Ship otherShip : getAllShips()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } return shipByDistance; } public ArrayList<Ship> nearbyMyShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); for (Ship otherShip : getMyPlayer().getShips().values()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } return new ArrayList<Ship>(shipByDistance.values()); } public ArrayList<Ship> nearbyShipsByDistance(final Entity ship) { Map<Double, Ship> shipByDistance = new TreeMap<>(); // Log.log("AllEnemyShips: " + getAllEnemyShips().size()); for (Ship otherShip : getAllEnemyShips()) { shipByDistance.put(otherShip.getDistanceTo(ship), otherShip); } // Log.log("nearbyShipsByDistance: " + shipByDistance.size()); return new ArrayList<Ship>(shipByDistance.values()); //return shipByDistance; } public Map<Double, Planet> nearbyPlanetsByDistance(final Entity ship) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { planetByDistance.put(ship.getDistanceTo(planet), planet); } return planetByDistance; } public Map<Double, Planet> nearbyPlanetsByScore(final Entity ship, double maxRadius) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); double score; for (final Planet planet : planets.values()) { double radius = planet.getRadius() / maxRadius; double curve = curve(radius, CurveType.Linear, -1, 1, 1.5, 0); score = curve * ship.getDistanceTo(planet); // if ((ship.getId() % 5) == 0) { // Log.log("Planet ID: " + planet.getId() + " dist / radius / curve / score " + ship.getDistanceTo(planet) + " / " + radius + " / " + curve + " / " + score); // } planetByDistance.put(score, planet); } return planetByDistance; } private enum CurveType { Parabola, Linear, Logistic } // plots x value onto curve, returning value that is between 0-1 private double curve(double x, CurveType curve, double mSlope, double kExponent, double yShift, double xShift) { // m = slope, k = exponential, b = y shift, c = x shift double value = 1; switch(curve) { case Parabola: value = mSlope * Math.pow((x - xShift), kExponent) + yShift; break; case Linear: value = mSlope * (x - xShift) + yShift; // Log.log("Linear curved: " + value); break; case Logistic: double denom = 1 + Math.pow((Math.E * mSlope), (x*kExponent + xShift)); value = (1 / denom) + yShift; break; } return clamp(value, 0, 1); } // clamp will ensure that no value is beyond max or below min // preffered use is noramalise above public double clamp(double initialValue, double min, double max) { double fin = 1; if (initialValue >= min && initialValue <= max) { fin = initialValue; } else if (initialValue < min) { fin = min; } else if (initialValue > max) { fin = max; } // Log.log("Clamping: " + fin); return fin; } public Map<Double, Planet> nearbyKeyPlanetsByDistance(final Entity ship) { final Map<Double, Planet> planetByDistance = new TreeMap<>(); for (final Planet planet : planets.values()) { if (planet.getRadius() > 10) { planetByDistance.put(ship.getDistanceTo(planet), planet); } } return planetByDistance; } public GameMap updateMap(final Metadata mapMetadata) { final int numberOfPlayers = MetadataParser.parsePlayerNum(mapMetadata); Log.log("Total moves was: " + myMoves.size()); players.clear(); planets.clear(); allShips.clear(); allEnemyShips.clear(); myMoves.clear(); // update players info for (int i = 0; i < numberOfPlayers; ++i) { currentShips.clear(); final Map<Integer, Ship> currentPlayerShips = new TreeMap<>(); final int playerId = MetadataParser.parsePlayerId(mapMetadata); final Player currentPlayer = new Player(playerId, currentPlayerShips); MetadataParser.populateShipList(currentShips, playerId, mapMetadata); allShips.addAll(currentShips); if (getMyPlayerId() != currentPlayer.getId()) { allEnemyShips.addAll(currentShips); } for (final Ship ship : currentShips) { currentPlayerShips.put(ship.getId(), ship); } players.add(currentPlayer); } final int numberOfPlanets = Integer.parseInt(mapMetadata.pop()); for (int i = 0; i < numberOfPlanets; ++i) { final List<Integer> dockedShips = new ArrayList<>(); final Planet planet = MetadataParser.newPlanetFromMetadata(dockedShips, mapMetadata); planets.put(planet.getId(), planet); } if (!mapMetadata.isEmpty()) { throw new IllegalStateException("Failed to parse data from Halite game engine. Please contact maintainers."); } Log.log("Total ships: " + allShips.size() + "... Enemy ships: " + allEnemyShips.size()); return this; } }
10,159
0.59494
0.592676
296
33.320946
29.036238
173
false
false
0
0
0
0
0
0
0.658784
false
false
13
1ab1a2e3580384a497ed06d86dc65c373c2f7be1
32,633,161,585,939
a2b699456c94eed6cc54bf8366d1fab91781aeca
/mars/mars-api/src/main/java/com/colourfulchina/mars/api/entity/sync/GiftAtvcodeVo.java
ebfd925c3afcfdda45b7bca2486665a0f67dce52
[]
no_license
elephant5/old-code
https://github.com/elephant5/old-code
8a35aa17163e87f506c6f12da032b1978b0c4ec3
bfb27297d5fcb6aaea8eac5a4032eba7d01cc7ee
refs/heads/master
2023-01-24T12:25:53.549000
2020-12-04T01:50:15
2020-12-04T01:50:15
318,364,156
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.colourfulchina.mars.api.entity.sync; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; /** * <p> * * </p> * * @author * @since 2019-12-11 */ @Data public class GiftAtvcodeVo implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "") private Integer shopId; @ApiModelProperty(value = "") private String code; @ApiModelProperty(value = "") private Integer state; @ApiModelProperty(value = "") private Integer orderId; @ApiModelProperty(value = "") private LocalDate bookDate; @ApiModelProperty(value = "") private String bookTime; @ApiModelProperty(value = "") private String name; @ApiModelProperty(value = "") private Integer people; @ApiModelProperty(value = "") private LocalDateTime createTime; @ApiModelProperty(value = "") private LocalDateTime usedTime; @ApiModelProperty(value = "") private BigDecimal amount; @ApiModelProperty(value = "") private Boolean ignoreTime; @ApiModelProperty(value = "") private String bank; @ApiModelProperty(value = "") private LocalDateTime roger; }
UTF-8
Java
1,313
java
GiftAtvcodeVo.java
Java
[]
null
[]
package com.colourfulchina.mars.api.entity.sync; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; /** * <p> * * </p> * * @author * @since 2019-12-11 */ @Data public class GiftAtvcodeVo implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "") private Integer shopId; @ApiModelProperty(value = "") private String code; @ApiModelProperty(value = "") private Integer state; @ApiModelProperty(value = "") private Integer orderId; @ApiModelProperty(value = "") private LocalDate bookDate; @ApiModelProperty(value = "") private String bookTime; @ApiModelProperty(value = "") private String name; @ApiModelProperty(value = "") private Integer people; @ApiModelProperty(value = "") private LocalDateTime createTime; @ApiModelProperty(value = "") private LocalDateTime usedTime; @ApiModelProperty(value = "") private BigDecimal amount; @ApiModelProperty(value = "") private Boolean ignoreTime; @ApiModelProperty(value = "") private String bank; @ApiModelProperty(value = "") private LocalDateTime roger; }
1,313
0.691546
0.684692
54
23.314816
14.885768
52
false
false
0
0
0
0
0
0
0.407407
false
false
13
52fc93d55665aa19897ec086eb60624a5c0e51bf
300,647,779,697
2b351788b80891e6d7b24787b9e5d8c9921978a5
/03_projects/logicalexp/01_src/main/java/org/isk/jvmhardcore/lexp/core/Expression.java
1009c08ed98a250257dfa91d0fe4034fa2efda98
[]
no_license
yohanbeschi/jvm_hardcore
https://github.com/yohanbeschi/jvm_hardcore
f05c38f856fe3ce15047723fddea1dce58572e5d
996d0759f821ac3c1e80ddc6676f4668dd5f8d93
refs/heads/master
2021-01-13T02:26:02.422000
2014-05-25T20:02:32
2014-05-25T20:02:32
11,667,723
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.isk.jvmhardcore.lexp.core; import org.isk.jvmhardcore.lexp.visitor.Visitable; public interface Expression extends Visitable { }
UTF-8
Java
143
java
Expression.java
Java
[]
null
[]
package org.isk.jvmhardcore.lexp.core; import org.isk.jvmhardcore.lexp.visitor.Visitable; public interface Expression extends Visitable { }
143
0.811189
0.811189
7
19.428572
22.398069
50
false
false
0
0
0
0
0
0
0.285714
false
false
13
67c832c98689b8c0dc62521f20c8978bce3c44af
34,102,040,367,211
ff49d0a58da6849f6d3d582cee2fb5c60845d46a
/guarantorsmng/src/main/java/cn/springmvc/model/GuaranteeBankCard.java
32ad3f502dfcdc31c6f0df78023fdb577a6f05bc
[]
no_license
moutainhigh/sxlc
https://github.com/moutainhigh/sxlc
08ed3d26c1ab0ccfd238731af6c7306ffa24978c
7c384d3c45ccefd29ba9da671c0ffcb62d657797
refs/heads/master
2021-06-01T04:21:49.706000
2016-05-30T12:59:58
2016-05-30T12:59:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.springmvc.model; /** * 会员银行卡 * @author 朱祖轶 * @Description: TODO * @since * @date 2016-4-25 下午5:29:55 */ public class GuaranteeBankCard { private long bankCardId;//银行卡信息id private long receiveCard;//会员银行卡信息id public long getReceiveCard() { return receiveCard; } public void setReceiveCard(long receiveCard) { this.receiveCard = receiveCard; } private int carType=1;//银行卡类型(借记卡) private String bankName;//,开户银行 private String bankCity;//,开户行城市, private String bankBranch;//开户行支行 private String bankNo;//,银行卡卡号 public long getBankCardId() { return bankCardId; } public void setBankCardId(long bankCardId) { this.bankCardId = bankCardId; } public int getCarType() { return carType; } public void setCarType(int carType) { this.carType = carType; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankCity() { return bankCity; } public void setBankCity(String bankCity) { this.bankCity = bankCity; } public String getBankBranch() { return bankBranch; } public void setBankBranch(String bankBranch) { this.bankBranch = bankBranch; } public String getBankNo() { return bankNo; } public void setBankNo(String bankNo) { this.bankNo = bankNo; } }
UTF-8
Java
1,486
java
GuaranteeBankCard.java
Java
[ { "context": ".springmvc.model; \r\n\r\n\r\n/** \r\n * 会员银行卡\r\n* @author 朱祖轶 \r\n* @Description: TODO \r\n* @since \r\n* @date 2016-", "end": 65, "score": 0.9998235702514648, "start": 62, "tag": "NAME", "value": "朱祖轶" } ]
null
[]
package cn.springmvc.model; /** * 会员银行卡 * @author 朱祖轶 * @Description: TODO * @since * @date 2016-4-25 下午5:29:55 */ public class GuaranteeBankCard { private long bankCardId;//银行卡信息id private long receiveCard;//会员银行卡信息id public long getReceiveCard() { return receiveCard; } public void setReceiveCard(long receiveCard) { this.receiveCard = receiveCard; } private int carType=1;//银行卡类型(借记卡) private String bankName;//,开户银行 private String bankCity;//,开户行城市, private String bankBranch;//开户行支行 private String bankNo;//,银行卡卡号 public long getBankCardId() { return bankCardId; } public void setBankCardId(long bankCardId) { this.bankCardId = bankCardId; } public int getCarType() { return carType; } public void setCarType(int carType) { this.carType = carType; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankCity() { return bankCity; } public void setBankCity(String bankCity) { this.bankCity = bankCity; } public String getBankBranch() { return bankBranch; } public void setBankBranch(String bankBranch) { this.bankBranch = bankBranch; } public String getBankNo() { return bankNo; } public void setBankNo(String bankNo) { this.bankNo = bankNo; } }
1,486
0.686773
0.677326
61
20.491804
14.802108
47
false
false
0
0
0
0
0
0
1.409836
false
false
13
d712f5e89f5bbd269dda2cecba3fb847f87853e6
39,015,482,944,419
5ac7b60ef19664b2a2dec5c0a4c52519a9ed6e96
/src/main/java/com/thinkgem/jeesite/modules/service/entity/technician/AppServiceTechnicianInfo.java
c482aae7ca1b8253586e045763b229ebaebf21af
[ "Apache-2.0" ]
permissive
wangyingjiao/apiservice
https://github.com/wangyingjiao/apiservice
ccf333503225ac82fda024a7f7db2f84d5544527
6261e593866be787d9ac016ce16824f8e8c805d7
refs/heads/master
2020-03-19T06:04:46.696000
2018-05-17T09:56:47
2018-05-17T09:56:47
135,988,833
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.service.entity.technician; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.thinkgem.jeesite.common.persistence.DataEntity; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; /** * 服务技师APP返回信息Entity * * @author a * @version 2017-11-16 */ public class AppServiceTechnicianInfo extends DataEntity<AppServiceTechnicianInfo> { private static final long serialVersionUID = 1L; private String token; private String stationName;//服务站名称 private String imgUrlHead;//头像 private String techPhone;//登陆账号 private String techName;//姓名 private String techSex;//性别 private Date techBirthDate;//出生日期 private String addrDetailInfo;//现住地址 private String techIdCard;//身份证号 private String imgUrlCard;//身份证照片 private String techEmail;//邮箱 private String techHeight;//身高 private String techWeight;//体重 private String techNativePlace;//籍贯 汉字 private String techNation;//民族 private String experDesc;//经验描述 private String imgUrlLife;//生活照 private String imgUrl;//app头像 private String techNativePlaceValue;//籍贯 private String techNationValue;//民族 code private String imgUrlCardAfter;//身份证背面照 private String imgUrlCardBefor;//身份证正面照 private String provinceCode; // 省_区号 private String cityCode; // 市_区号 private String areaCode; // 区_区号 private String provinceCodeName; // 省名 private String cityCodeName; // 市名 private String areaCodeName; // 区名 private String jobStatus; // 岗位状态(online:在职,leave:离职) private String jobNature; // 岗位性质(full_time:全职,part_time:兼职) public String getJobNature() { return jobNature; } public void setJobNature(String jobNature) { this.jobNature = jobNature; } public String getJobStatus() { return jobStatus; } public void setJobStatus(String jobStatus) { this.jobStatus = jobStatus; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getProvinceCodeName() { return provinceCodeName; } public void setProvinceCodeName(String provinceCodeName) { this.provinceCodeName = provinceCodeName; } public String getCityCodeName() { return cityCodeName; } public void setCityCodeName(String cityCodeName) { this.cityCodeName = cityCodeName; } public String getAreaCodeName() { return areaCodeName; } public void setAreaCodeName(String areaCodeName) { this.areaCodeName = areaCodeName; } public String getTechNativePlaceValue() { return techNativePlaceValue; } public void setTechNativePlaceValue(String techNativePlaceValue) { this.techNativePlaceValue = techNativePlaceValue; } public String getTechNationValue() { return techNationValue; } public void setTechNationValue(String techNationValue) { this.techNationValue = techNationValue; } public String getImgUrlCardAfter() { return imgUrlCardAfter; } public void setImgUrlCardAfter(String imgUrlCardAfter) { this.imgUrlCardAfter = imgUrlCardAfter; } public String getImgUrlCardBefor() { return imgUrlCardBefor; } public void setImgUrlCardBefor(String imgUrlCardBefor) { this.imgUrlCardBefor = imgUrlCardBefor; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } @JsonIgnore public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String password; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getStationName() { return stationName; } public void setStationName(String stationName) { this.stationName = stationName; } public String getImgUrlHead() { return imgUrlHead; } public void setImgUrlHead(String imgUrlHead) { this.imgUrlHead = imgUrlHead; } public String getTechPhone() { return techPhone; } public void setTechPhone(String techPhone) { this.techPhone = techPhone; } public String getTechName() { return techName; } public void setTechName(String techName) { this.techName = techName; } public String getTechSex() { return techSex; } public void setTechSex(String techSex) { this.techSex = techSex; } @JsonFormat(pattern = "yyyy-MM-dd") public Date getTechBirthDate() { return techBirthDate; } public void setTechBirthDate(Date techBirthDate) { this.techBirthDate = techBirthDate; } public String getAddrDetailInfo() { return addrDetailInfo; } public void setAddrDetailInfo(String addrDetailInfo) { this.addrDetailInfo = addrDetailInfo; } public String getTechIdCard() { return techIdCard; } public void setTechIdCard(String techIdCard) { this.techIdCard = techIdCard; } public String getImgUrlCard() { return imgUrlCard; } public void setImgUrlCard(String imgUrlCard) { this.imgUrlCard = imgUrlCard; } public String getTechEmail() { return techEmail; } public void setTechEmail(String techEmail) { this.techEmail = techEmail; } public String getTechHeight() { return techHeight; } public void setTechHeight(String techHeight) { this.techHeight = techHeight; } public String getTechWeight() { return techWeight; } public void setTechWeight(String techWeight) { this.techWeight = techWeight; } public String getTechNativePlace() { return techNativePlace; } public void setTechNativePlace(String techNativePlace) { this.techNativePlace = techNativePlace; } public String getTechNation() { return techNation; } public void setTechNation(String techNation) { this.techNation = techNation; } public String getExperDesc() { return experDesc; } public void setExperDesc(String experDesc) { this.experDesc = experDesc; } public String getImgUrlLife() { return imgUrlLife; } public void setImgUrlLife(String imgUrlLife) { this.imgUrlLife = imgUrlLife; } }
UTF-8
Java
7,541
java
AppServiceTechnicianInfo.java
Java
[ { "context": "ight &copy; 2012-2016 <a href=\"https://github.com/thinkgem/jeesite\">JeeSite</a> All rights reserved.\n */\npac", "end": 70, "score": 0.9986286163330078, "start": 62, "tag": "USERNAME", "value": "thinkgem" }, { "context": "util.List;\n\n/**\n * 服务技师APP返回信息Entity\n *\n * @author a\n * @version 2017-11-16\n */\npublic class AppServic", "end": 582, "score": 0.9971181154251099, "start": 581, "tag": "USERNAME", "value": "a" } ]
null
[]
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.service.entity.technician; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.thinkgem.jeesite.common.persistence.DataEntity; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; /** * 服务技师APP返回信息Entity * * @author a * @version 2017-11-16 */ public class AppServiceTechnicianInfo extends DataEntity<AppServiceTechnicianInfo> { private static final long serialVersionUID = 1L; private String token; private String stationName;//服务站名称 private String imgUrlHead;//头像 private String techPhone;//登陆账号 private String techName;//姓名 private String techSex;//性别 private Date techBirthDate;//出生日期 private String addrDetailInfo;//现住地址 private String techIdCard;//身份证号 private String imgUrlCard;//身份证照片 private String techEmail;//邮箱 private String techHeight;//身高 private String techWeight;//体重 private String techNativePlace;//籍贯 汉字 private String techNation;//民族 private String experDesc;//经验描述 private String imgUrlLife;//生活照 private String imgUrl;//app头像 private String techNativePlaceValue;//籍贯 private String techNationValue;//民族 code private String imgUrlCardAfter;//身份证背面照 private String imgUrlCardBefor;//身份证正面照 private String provinceCode; // 省_区号 private String cityCode; // 市_区号 private String areaCode; // 区_区号 private String provinceCodeName; // 省名 private String cityCodeName; // 市名 private String areaCodeName; // 区名 private String jobStatus; // 岗位状态(online:在职,leave:离职) private String jobNature; // 岗位性质(full_time:全职,part_time:兼职) public String getJobNature() { return jobNature; } public void setJobNature(String jobNature) { this.jobNature = jobNature; } public String getJobStatus() { return jobStatus; } public void setJobStatus(String jobStatus) { this.jobStatus = jobStatus; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getProvinceCodeName() { return provinceCodeName; } public void setProvinceCodeName(String provinceCodeName) { this.provinceCodeName = provinceCodeName; } public String getCityCodeName() { return cityCodeName; } public void setCityCodeName(String cityCodeName) { this.cityCodeName = cityCodeName; } public String getAreaCodeName() { return areaCodeName; } public void setAreaCodeName(String areaCodeName) { this.areaCodeName = areaCodeName; } public String getTechNativePlaceValue() { return techNativePlaceValue; } public void setTechNativePlaceValue(String techNativePlaceValue) { this.techNativePlaceValue = techNativePlaceValue; } public String getTechNationValue() { return techNationValue; } public void setTechNationValue(String techNationValue) { this.techNationValue = techNationValue; } public String getImgUrlCardAfter() { return imgUrlCardAfter; } public void setImgUrlCardAfter(String imgUrlCardAfter) { this.imgUrlCardAfter = imgUrlCardAfter; } public String getImgUrlCardBefor() { return imgUrlCardBefor; } public void setImgUrlCardBefor(String imgUrlCardBefor) { this.imgUrlCardBefor = imgUrlCardBefor; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } @JsonIgnore public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String password; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getStationName() { return stationName; } public void setStationName(String stationName) { this.stationName = stationName; } public String getImgUrlHead() { return imgUrlHead; } public void setImgUrlHead(String imgUrlHead) { this.imgUrlHead = imgUrlHead; } public String getTechPhone() { return techPhone; } public void setTechPhone(String techPhone) { this.techPhone = techPhone; } public String getTechName() { return techName; } public void setTechName(String techName) { this.techName = techName; } public String getTechSex() { return techSex; } public void setTechSex(String techSex) { this.techSex = techSex; } @JsonFormat(pattern = "yyyy-MM-dd") public Date getTechBirthDate() { return techBirthDate; } public void setTechBirthDate(Date techBirthDate) { this.techBirthDate = techBirthDate; } public String getAddrDetailInfo() { return addrDetailInfo; } public void setAddrDetailInfo(String addrDetailInfo) { this.addrDetailInfo = addrDetailInfo; } public String getTechIdCard() { return techIdCard; } public void setTechIdCard(String techIdCard) { this.techIdCard = techIdCard; } public String getImgUrlCard() { return imgUrlCard; } public void setImgUrlCard(String imgUrlCard) { this.imgUrlCard = imgUrlCard; } public String getTechEmail() { return techEmail; } public void setTechEmail(String techEmail) { this.techEmail = techEmail; } public String getTechHeight() { return techHeight; } public void setTechHeight(String techHeight) { this.techHeight = techHeight; } public String getTechWeight() { return techWeight; } public void setTechWeight(String techWeight) { this.techWeight = techWeight; } public String getTechNativePlace() { return techNativePlace; } public void setTechNativePlace(String techNativePlace) { this.techNativePlace = techNativePlace; } public String getTechNation() { return techNation; } public void setTechNation(String techNation) { this.techNation = techNation; } public String getExperDesc() { return experDesc; } public void setExperDesc(String experDesc) { this.experDesc = experDesc; } public String getImgUrlLife() { return imgUrlLife; } public void setImgUrlLife(String imgUrlLife) { this.imgUrlLife = imgUrlLife; } }
7,541
0.66571
0.663387
308
22.759741
20.367582
108
false
false
0
0
0
0
0
0
0.38961
false
false
13
cb423b1d7ebfbc66324d90c15b08cd7ba0a1d76f
34,926,674,095,650
e6e9741082dd028bc8fd004182baa502486495cd
/springbootshirodemo/src/main/java/com/example/springbootshirodemo/mapper/PermissionMapper.java
096df44322e7567110f49af7e687bd25f992e9a1
[]
no_license
Kevin-snow/springbootdemo
https://github.com/Kevin-snow/springbootdemo
ddfcd50ee7fac67994e79bae66e2abc9bbb24742
ee4ad41a48f0fc12cb005bbeca376fb11c1cacc4
refs/heads/master
2022-07-03T15:41:39.626000
2019-11-23T10:47:09
2019-11-23T10:47:09
171,965,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.springbootshirodemo.mapper; import com.example.springbootshirodemo.pojo.Permission; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * PermissionMapper * @author kevin * @date 2019/11/21 */ @Mapper public interface PermissionMapper { /** * <p> * 根据roleId, 查询权限 * </p> * @param roleId roleId * @return list */ List<Permission> selectPermissions(@Param("roleId") Integer roleId); }
UTF-8
Java
529
java
PermissionMapper.java
Java
[ { "context": "ava.util.List;\n\n/**\n * PermissionMapper\n * @author kevin\n * @date 2019/11/21\n */\n@Mapper\npublic interface ", "end": 259, "score": 0.9994490146636963, "start": 254, "tag": "USERNAME", "value": "kevin" } ]
null
[]
package com.example.springbootshirodemo.mapper; import com.example.springbootshirodemo.pojo.Permission; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * PermissionMapper * @author kevin * @date 2019/11/21 */ @Mapper public interface PermissionMapper { /** * <p> * 根据roleId, 查询权限 * </p> * @param roleId roleId * @return list */ List<Permission> selectPermissions(@Param("roleId") Integer roleId); }
529
0.688588
0.673114
25
19.68
19.297089
72
false
false
0
0
0
0
0
0
0.28
false
false
13
e5bf877832006da5e44d50b640509240b3d40f0a
27,565,100,170,144
40175bd20d0333d132439a20f1f46fac879f1f68
/core/src/main/java/com/axisframework/messaging/RollbackConfiguration.java
a256e9a2e482ead36ac214f8c85fcacda712b1bd
[]
no_license
lqbilbo/learning
https://github.com/lqbilbo/learning
ec95d5abcc6e96f3b137da243bae12f6d5bf8fee
7b38aa8cc14424bd745ce53e66ff81e7648811ae
refs/heads/master
2018-10-16T15:55:50.969000
2018-08-24T15:48:31
2018-08-24T15:48:31
139,966,799
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.axisframework.messaging; /** * 配置触发回滚的开关 * * @author luoqi * @since 1.0 */ public interface RollbackConfiguration { /** * 是否触发回滚 * @param throwable * @return */ boolean rollbackOn(Throwable throwable); }
UTF-8
Java
281
java
RollbackConfiguration.java
Java
[ { "context": "amework.messaging;\n\n/**\n * 配置触发回滚的开关\n *\n * @author luoqi\n * @since 1.0\n */\npublic interface RollbackConfig", "end": 74, "score": 0.9993574619293213, "start": 69, "tag": "USERNAME", "value": "luoqi" } ]
null
[]
package com.axisframework.messaging; /** * 配置触发回滚的开关 * * @author luoqi * @since 1.0 */ public interface RollbackConfiguration { /** * 是否触发回滚 * @param throwable * @return */ boolean rollbackOn(Throwable throwable); }
281
0.621514
0.613546
17
13.764706
13.709291
44
false
false
0
0
0
0
0
0
0.117647
false
false
13
774fb2a3759d47b60a11a7b42635dc7f0cb1075e
28,982,439,377,824
e2de057056220b1e6bae873db64058e45150beb3
/src/main/java/com/sunft/chapter03/StateTest.java
9f0fe5f01ab34cbc63cba1f8d5039d35c56e0ad3
[]
no_license
sunft/PracticeJavaConcurrency
https://github.com/sunft/PracticeJavaConcurrency
64d401c10a727fe56ccbaf3286dfccf731d6babf
9637b8e4a04e5a8b441a52e4002aed09bf1dcf02
refs/heads/master
2021-04-06T22:34:49.033000
2020-03-19T22:57:10
2020-03-19T22:57:10
248,620,531
0
0
null
false
2021-03-31T21:59:06
2020-03-19T22:50:51
2020-03-19T22:57:30
2021-03-31T21:59:05
4,618
0
0
3
Java
false
false
package com.sunft.chapter03; public class StateTest { }
UTF-8
Java
60
java
StateTest.java
Java
[]
null
[]
package com.sunft.chapter03; public class StateTest { }
60
0.733333
0.7
7
7.571429
11.709058
28
false
false
0
0
0
0
0
0
0.142857
false
false
13
170fced0efff750b5a6d0414df0a0a6feac546e2
32,615,981,680,319
42dbdde76abaa0050b64988acbee22846b29e704
/okhttpdemo/src/main/java/com/android/yangjw/okhttpdemo/DownloadActivity.java
ea3935b39ad1caf06130d504576f5a12d4786cc2
[]
no_license
yangjingwen2/ScrollFloatView
https://github.com/yangjingwen2/ScrollFloatView
99e1038e4a7509e603803bdcdeb9c060ba4de7e7
40fc0444ce9336bf2b13c6ed3c94a291fa21ec58
refs/heads/master
2016-09-13T02:49:50.084000
2016-04-27T03:42:10
2016-04-27T03:42:10
56,675,445
3
10
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.yangjw.okhttpdemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * 文件下载 * androidxx.cn * created by yangjw at 2016.4.12 */ public class DownloadActivity extends AppCompatActivity { private ProgressBar mProgressBar; //准备下载 public static final int BEGIN = 0; //正在下载 public static final int DOWNLOADING = 1; //结束下载 public static final int END = 2; //下载的进度 private static int progress; //是否停止下载 private boolean cancel ; OkHttpClient okHttpClient = new OkHttpClient(); MyHandler mHandler = new MyHandler(this); private ImageView mShowImage; ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mProgressBar = (ProgressBar) findViewById(R.id.down_progress_bar); mShowImage = (ImageView) findViewById(R.id.down_image); } public void click2(View view) { cancel = true; } public void click(View view) { cancel = false; new Thread(new Runnable() { @Override public void run() { //实例化Builder对象 Request.Builder builder = new Request.Builder(); //设置Url builder.url(Config.IMAGE_URL); //获取已经下载的大小 int size = baos.size(); //size表示已经下载的大小。如果不为0,则进行断点续传。 if (size > 0) { //设置断点续传的开始位置,格式bytes=123456- builder.header("Range", "bytes=" + size + "-"); //设置ProgressBar的当前进度从停止位置开始 progress = size; } //创建Request对象 Request request = builder.build(); try { //执行下载请求,并获得Response对象 Response response = okHttpClient.newCall(request).execute(); //请求成功 if (response.isSuccessful()) { //从Response对象中获取输入流对象 InputStream inputStream = response.body().byteStream(); //size==0表示第一次下载,非断点续传 if (size == 0) { //获取文件的大小 int contentLength = (int) response.body().contentLength(); //将文件总大小通过Handler传递到UI线程,设置ProgressBar的总进度值 mHandler.obtainMessage(BEGIN,contentLength,0).sendToTarget(); } int len = 0; byte[] buffer = new byte[1024]; //循环读取文件流,开始下载 while((len = inputStream.read(buffer)) != -1) { if (cancel) { //如果点击了停止按钮,cancel为true。则结束循环 break; } //将流写入缓存 baos.write(buffer,0,len); baos.flush(); //发送下载进度 mHandler.obtainMessage(DOWNLOADING,len,0).sendToTarget(); } //下载完成,结束请求,关闭body response.body().close(); //将字节转成Bitmap对象 byte[] bytes = baos.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); //下载完成通知更新试图 mHandler.obtainMessage(END,bitmap).sendToTarget(); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } static class MyHandler extends Handler { private WeakReference<DownloadActivity> activityWeakReference; public MyHandler(DownloadActivity activity) { this.activityWeakReference = new WeakReference<DownloadActivity>(activity); } @Override public void handleMessage(Message msg) { switch (msg.what) { case BEGIN: activityWeakReference.get().mProgressBar.setMax(msg.arg1); break; case DOWNLOADING: progress += msg.arg1; activityWeakReference.get().mProgressBar.setProgress(progress); break; case END: progress = 0; activityWeakReference.get().mShowImage.setImageBitmap((Bitmap)msg.obj); break; } } } }
UTF-8
Java
5,781
java
DownloadActivity.java
Java
[ { "context": "sponse;\n\n/**\n * 文件下载\n * androidxx.cn\n * created by yangjw at 2016.4.12\n */\npublic class DownloadActivity ex", "end": 735, "score": 0.9996241331100464, "start": 729, "tag": "USERNAME", "value": "yangjw" } ]
null
[]
package com.android.yangjw.okhttpdemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * 文件下载 * androidxx.cn * created by yangjw at 2016.4.12 */ public class DownloadActivity extends AppCompatActivity { private ProgressBar mProgressBar; //准备下载 public static final int BEGIN = 0; //正在下载 public static final int DOWNLOADING = 1; //结束下载 public static final int END = 2; //下载的进度 private static int progress; //是否停止下载 private boolean cancel ; OkHttpClient okHttpClient = new OkHttpClient(); MyHandler mHandler = new MyHandler(this); private ImageView mShowImage; ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mProgressBar = (ProgressBar) findViewById(R.id.down_progress_bar); mShowImage = (ImageView) findViewById(R.id.down_image); } public void click2(View view) { cancel = true; } public void click(View view) { cancel = false; new Thread(new Runnable() { @Override public void run() { //实例化Builder对象 Request.Builder builder = new Request.Builder(); //设置Url builder.url(Config.IMAGE_URL); //获取已经下载的大小 int size = baos.size(); //size表示已经下载的大小。如果不为0,则进行断点续传。 if (size > 0) { //设置断点续传的开始位置,格式bytes=123456- builder.header("Range", "bytes=" + size + "-"); //设置ProgressBar的当前进度从停止位置开始 progress = size; } //创建Request对象 Request request = builder.build(); try { //执行下载请求,并获得Response对象 Response response = okHttpClient.newCall(request).execute(); //请求成功 if (response.isSuccessful()) { //从Response对象中获取输入流对象 InputStream inputStream = response.body().byteStream(); //size==0表示第一次下载,非断点续传 if (size == 0) { //获取文件的大小 int contentLength = (int) response.body().contentLength(); //将文件总大小通过Handler传递到UI线程,设置ProgressBar的总进度值 mHandler.obtainMessage(BEGIN,contentLength,0).sendToTarget(); } int len = 0; byte[] buffer = new byte[1024]; //循环读取文件流,开始下载 while((len = inputStream.read(buffer)) != -1) { if (cancel) { //如果点击了停止按钮,cancel为true。则结束循环 break; } //将流写入缓存 baos.write(buffer,0,len); baos.flush(); //发送下载进度 mHandler.obtainMessage(DOWNLOADING,len,0).sendToTarget(); } //下载完成,结束请求,关闭body response.body().close(); //将字节转成Bitmap对象 byte[] bytes = baos.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); //下载完成通知更新试图 mHandler.obtainMessage(END,bitmap).sendToTarget(); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } static class MyHandler extends Handler { private WeakReference<DownloadActivity> activityWeakReference; public MyHandler(DownloadActivity activity) { this.activityWeakReference = new WeakReference<DownloadActivity>(activity); } @Override public void handleMessage(Message msg) { switch (msg.what) { case BEGIN: activityWeakReference.get().mProgressBar.setMax(msg.arg1); break; case DOWNLOADING: progress += msg.arg1; activityWeakReference.get().mProgressBar.setProgress(progress); break; case END: progress = 0; activityWeakReference.get().mShowImage.setImageBitmap((Bitmap)msg.obj); break; } } } }
5,781
0.526276
0.519118
155
33.251614
22.774233
94
false
false
0
0
0
0
0
0
0.516129
false
false
13
dd7b866c2bb307b53e13dbcc7f89cd65a4e71706
20,023,137,543,608
b4394f9f9bdd8454a6f109420b520188fb5c9f0d
/Unit12Lab3Test.java
c804fecd0aac2b1fcf1febdef429145195cdad47
[]
no_license
sohcahtoa08/APCS-2016
https://github.com/sohcahtoa08/APCS-2016
00185f4c42e9ee0e667893df710685494eb11a56
6e645f07335168181126c2fa23a6caf45d694db3
refs/heads/master
2021-07-24T22:39:26.067000
2017-11-04T18:54:33
2017-11-04T18:54:33
109,516,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This program tests the objects and methods associated with the classes * Contact and ContactList in coordination with maps and files. * * @author Pranshu Suri */ import java.util.*; import java.io.*; public class Test { public static void main(String[] args) { // Initialize & declare variables Scanner input = new Scanner(System.in); ContactList contactList = new ContactList(); int choice = -1; // Prompt user to enter file name System.out.print("Enter the file name: "); String fileName = input.next(); while (choice != 4) { // Ask user what he/she would like to do next System.out.print("\n1. Add a new contact\n2. Delete a contact\n" + "3. Display the contact list\n4. Quit\n\nWhat would you like" + " to do (1, 2, 3, 4)? "); choice = input.nextInt(); // Add a contact & update file if (choice == 1) { System.out.print("New Contact-\nFirst Name: "); String firstName = input.next(); System.out.print("Last Name: "); String lastName = input.next(); System.out.print("Phone Number: "); String phoneNumber = input.next(); System.out.print("Email Address: "); String emailAddress = input.next(); contactList.add(new Contact(lastName, firstName, phoneNumber, emailAddress)); updateFile(fileName, contactList); } // Delete a contact & update file else if (choice == 2) { System.out.print("Enter the first and last name of the contact" + " you would like to delete ('firstName lastName'): "); String firstName = input.next(); String lastName = input.next(); contactList.remove(lastName); updateFile(fileName, contactList); } // Display contacts & update file else if (choice == 3) { System.out.println(contactList); updateFile(fileName, contactList); } } } /* * PRE-CONDITIONS: 'list' must be initialized * POST-CONDITIONS: updates contents of file 'fileName' based on 'list' */ public static void updateFile(String fileName, ContactList list) { try { FileWriter fw = new FileWriter(fileName); BufferedWriter bw = new BufferedWriter(fw); // Write contents of 'list' onto file String finalList = list.toString(); bw.write(finalList); bw.close(); } catch(IOException e) { e.printStackTrace(); } } }
UTF-8
Java
2,382
java
Unit12Lab3Test.java
Java
[ { "context": "n coordination with maps and files.\n * \n * @author Pranshu Suri\n*/\n\nimport java.util.*;\nimport java.io.*;\n\npublic", "end": 169, "score": 0.9998742938041687, "start": 157, "tag": "NAME", "value": "Pranshu Suri" } ]
null
[]
/** * This program tests the objects and methods associated with the classes * Contact and ContactList in coordination with maps and files. * * @author <NAME> */ import java.util.*; import java.io.*; public class Test { public static void main(String[] args) { // Initialize & declare variables Scanner input = new Scanner(System.in); ContactList contactList = new ContactList(); int choice = -1; // Prompt user to enter file name System.out.print("Enter the file name: "); String fileName = input.next(); while (choice != 4) { // Ask user what he/she would like to do next System.out.print("\n1. Add a new contact\n2. Delete a contact\n" + "3. Display the contact list\n4. Quit\n\nWhat would you like" + " to do (1, 2, 3, 4)? "); choice = input.nextInt(); // Add a contact & update file if (choice == 1) { System.out.print("New Contact-\nFirst Name: "); String firstName = input.next(); System.out.print("Last Name: "); String lastName = input.next(); System.out.print("Phone Number: "); String phoneNumber = input.next(); System.out.print("Email Address: "); String emailAddress = input.next(); contactList.add(new Contact(lastName, firstName, phoneNumber, emailAddress)); updateFile(fileName, contactList); } // Delete a contact & update file else if (choice == 2) { System.out.print("Enter the first and last name of the contact" + " you would like to delete ('firstName lastName'): "); String firstName = input.next(); String lastName = input.next(); contactList.remove(lastName); updateFile(fileName, contactList); } // Display contacts & update file else if (choice == 3) { System.out.println(contactList); updateFile(fileName, contactList); } } } /* * PRE-CONDITIONS: 'list' must be initialized * POST-CONDITIONS: updates contents of file 'fileName' based on 'list' */ public static void updateFile(String fileName, ContactList list) { try { FileWriter fw = new FileWriter(fileName); BufferedWriter bw = new BufferedWriter(fw); // Write contents of 'list' onto file String finalList = list.toString(); bw.write(finalList); bw.close(); } catch(IOException e) { e.printStackTrace(); } } }
2,376
0.63644
0.630982
98
23.306122
21.194632
73
false
false
0
0
0
0
0
0
2.928571
false
false
13
1864432cc9ed7f4c31a620497947be4d44ed8a8b
13,666,585,987,100
455c67c9e2db131803bb6174bcd5b26fd85c0e1b
/src/com/javarush/test/level09/lesson11/bonus03/Solution.java
4d00899698f311ea33696a0204a0ff946ac75d10
[]
no_license
InvizzzZZ/JavaRushHomeWork
https://github.com/InvizzzZZ/JavaRushHomeWork
9a025133fa6b5f129fe73da7c1130fadf82d6371
0606830f88e9183e462ee219d30b7e6eaf4bdf73
refs/heads/master
2018-02-10T14:31:28.587000
2016-12-06T13:05:42
2016-12-06T13:05:42
52,995,204
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.test.level09.lesson11.bonus03; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /* Задача по алгоритмам Задача: Пользователь вводит с клавиатуры список слов (и чисел). Слова вывести в возрастающем порядке, числа - в убывающем. Пример ввода: Вишня 1 Боб 3 Яблоко 2 0 Арбуз Пример вывода: Арбуз 3 Боб 2 Вишня 1 0 Яблоко */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); ArrayList<String> list = new ArrayList<String>(); while (true) { String s = reader.readLine(); if (s.isEmpty()) break; list.add(s); } String[] array = list.toArray(new String[list.size()]); sort(array); for (String x : array) { System.out.println(x); } } public static void sort(String[] array) { //напишите тут ваш код ArrayList<String> words = new ArrayList<String>(); ArrayList<String> numbers = new ArrayList<String>(); ArrayList<String> temp = new ArrayList<String>(); int count = 0; int count2 = 0; for (int i = 0; i < array.length; i++) { if (isNumber(array[i])) { numbers.add(array[i]); temp.add("1"); } else { words.add(array[i]); temp.add("s"); } } for (int i = 0; i < words.size(); i++) { for (int i2 = 0; i2 < words.size(); i2++) { if (!isGreaterThan(words.get(i).toLowerCase(), words.get(i2).toLowerCase())) { String tmp = words.get(i); words.set(i, words.get(i2)); words.set(i2, tmp); } } } for (int i = 0; i < numbers.size(); i++) { for (int i2 = 0; i2 < numbers.size(); i2++) { int n = Integer.parseInt(numbers.get(i)); int n2 = Integer.parseInt(numbers.get(i2)); if (n > n2) { String tmp = numbers.get(i); numbers.set(i, numbers.get(i2)); numbers.set(i2, tmp); } } } for (int i = 0; i < temp.size(); i++) { if (temp.get(i).equals("1")) { array[i] = numbers.get(count); count++; } else { array[i] = words.get(count2); count2++; } } } //Метод для сравнения строк: 'а' больше чем 'b' public static boolean isGreaterThan(String a, String b) { return a.compareTo(b) > 0; } //строка - это на самом деле число? public static boolean isNumber(String s) { if (s.length() == 0) return false; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ((i != 0 && c == '-') //есть '-' внутри строки || (!Character.isDigit(c) && c != '-')) // не цифра и не начинается с '-' { return false; } } return true; } }
UTF-8
Java
3,562
java
Solution.java
Java
[]
null
[]
package com.javarush.test.level09.lesson11.bonus03; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /* Задача по алгоритмам Задача: Пользователь вводит с клавиатуры список слов (и чисел). Слова вывести в возрастающем порядке, числа - в убывающем. Пример ввода: Вишня 1 Боб 3 Яблоко 2 0 Арбуз Пример вывода: Арбуз 3 Боб 2 Вишня 1 0 Яблоко */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); ArrayList<String> list = new ArrayList<String>(); while (true) { String s = reader.readLine(); if (s.isEmpty()) break; list.add(s); } String[] array = list.toArray(new String[list.size()]); sort(array); for (String x : array) { System.out.println(x); } } public static void sort(String[] array) { //напишите тут ваш код ArrayList<String> words = new ArrayList<String>(); ArrayList<String> numbers = new ArrayList<String>(); ArrayList<String> temp = new ArrayList<String>(); int count = 0; int count2 = 0; for (int i = 0; i < array.length; i++) { if (isNumber(array[i])) { numbers.add(array[i]); temp.add("1"); } else { words.add(array[i]); temp.add("s"); } } for (int i = 0; i < words.size(); i++) { for (int i2 = 0; i2 < words.size(); i2++) { if (!isGreaterThan(words.get(i).toLowerCase(), words.get(i2).toLowerCase())) { String tmp = words.get(i); words.set(i, words.get(i2)); words.set(i2, tmp); } } } for (int i = 0; i < numbers.size(); i++) { for (int i2 = 0; i2 < numbers.size(); i2++) { int n = Integer.parseInt(numbers.get(i)); int n2 = Integer.parseInt(numbers.get(i2)); if (n > n2) { String tmp = numbers.get(i); numbers.set(i, numbers.get(i2)); numbers.set(i2, tmp); } } } for (int i = 0; i < temp.size(); i++) { if (temp.get(i).equals("1")) { array[i] = numbers.get(count); count++; } else { array[i] = words.get(count2); count2++; } } } //Метод для сравнения строк: 'а' больше чем 'b' public static boolean isGreaterThan(String a, String b) { return a.compareTo(b) > 0; } //строка - это на самом деле число? public static boolean isNumber(String s) { if (s.length() == 0) return false; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if ((i != 0 && c == '-') //есть '-' внутри строки || (!Character.isDigit(c) && c != '-')) // не цифра и не начинается с '-' { return false; } } return true; } }
3,562
0.486866
0.473122
121
26.057852
24.128889
122
false
false
0
0
0
0
0
0
0.512397
false
false
13
018648e5b3591ab48683ba6968698acd9f5d711b
24,446,953,899,611
5034fe38d1a395b06774b9fc9630d5787a8356f8
/src/main/java/mariot7/decorativestyles/blocks/WoodenStairs.java
b570fd7cbb4478bea3819e055eed45553789a7a7
[]
no_license
mariot7/Decorative-Styles
https://github.com/mariot7/Decorative-Styles
7fe41bd567998edd880385e35a7caa0d3bce1fef
1ef131f4bb2778f2eb481c9f6e81ed2838e2bf12
refs/heads/master
2021-01-18T23:44:58.124000
2016-09-27T22:18:21
2016-09-27T22:18:21
62,554,398
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mariot7.decorativestyles.blocks; import java.util.Collection; import com.google.common.collect.ImmutableMap; import mariot7.decorativestyles.Main; import mariot7.decorativestyles.init.BlockListds; import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; public class WoodenStairs extends BlockStairs{ public WoodenStairs(Block block) { this(block.getDefaultState()); } public WoodenStairs(Block block, int meta) { this(block.getStateFromMeta(meta)); } public WoodenStairs(IBlockState state) { super(state); this.setHardness(2.0F); this.setLightOpacity(0); this.setSoundType(SoundType.WOOD); this.useNeighborBrightness = true; } }
UTF-8
Java
865
java
WoodenStairs.java
Java
[]
null
[]
package mariot7.decorativestyles.blocks; import java.util.Collection; import com.google.common.collect.ImmutableMap; import mariot7.decorativestyles.Main; import mariot7.decorativestyles.init.BlockListds; import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; public class WoodenStairs extends BlockStairs{ public WoodenStairs(Block block) { this(block.getDefaultState()); } public WoodenStairs(Block block, int meta) { this(block.getStateFromMeta(meta)); } public WoodenStairs(IBlockState state) { super(state); this.setHardness(2.0F); this.setLightOpacity(0); this.setSoundType(SoundType.WOOD); this.useNeighborBrightness = true; } }
865
0.795376
0.788439
35
23.714285
18.89304
49
false
false
0
0
0
0
0
0
1.171429
false
false
13
08736fc9a1ab8e062f5fd396254a3b128f474e35
10,797,547,782,976
8e600a2b6c594f80709a9549f10f57ce957006a2
/COMP/COMP328/Tutorial Project/Tutorial Project/src/MySecondJava.java
30b805b185659cab1b74af80aca8d9a2520d8659
[]
no_license
Serkit/Education
https://github.com/Serkit/Education
9c27b8d54218e2e0a4f0cfbbbde5f2a01497e1c1
c3b7d1e524cb61c44c590f09ff423fd80ca0c92e
refs/heads/master
2018-02-07T16:57:38.634000
2018-01-26T05:17:30
2018-01-26T05:17:30
95,988,506
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @param args */ public class MySecondJava { public static void main(String[] args) { //Declare and initialize variables int sum = 0; int number = 0; while(number < 20) { number++; if(number % 2 == 0) continue; sum += number; } System.out.println("The sum of even numbers is " + sum); } }
UTF-8
Java
334
java
MySecondJava.java
Java
[]
null
[]
/* * @param args */ public class MySecondJava { public static void main(String[] args) { //Declare and initialize variables int sum = 0; int number = 0; while(number < 20) { number++; if(number % 2 == 0) continue; sum += number; } System.out.println("The sum of even numbers is " + sum); } }
334
0.580838
0.562874
24
12.958333
14.43514
58
false
false
0
0
0
0
0
0
1.791667
false
false
13
7ce7a4b78b23028af77fd0140994acf0f2ba6036
10,797,547,785,125
edf4dd084e5834113e050b29f85cc56a8e71daf0
/losningar/losning-labb-2/src/main/java/se/cag/routes/OrderTransformBean.java
aad01eaf66daa83248fa0cf509a529aace468162
[]
no_license
CAG-Contactor/apache-camel-lab
https://github.com/CAG-Contactor/apache-camel-lab
7cb61e6a6ed74101996f6924f816bdd14b43d0be
c7e540fa1478efa34c4f7ca02f4f5b586286642f
refs/heads/master
2021-08-19T19:07:56.715000
2017-11-27T06:56:56
2017-11-27T06:56:56
108,308,086
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.cag.routes; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.camel.Body; import org.apache.camel.Handler; import org.apache.camel.Message; import java.io.IOException; public class OrderTransformBean { @Handler public void transform(@Body Message message) throws IOException { ObjectMapper mapper = new ObjectMapper(); // Konvertera inkommande JSON-sträng från exchange till ett OpenNotifyIssPositionBean-objekt mha ObjectMapern OpenNotifyIssPositionBean openNotifyIssPositionBean = mapper.readValue(message.getBody(String.class), OpenNotifyIssPositionBean.class); // Sätt det nya objektet som body i exchange message.setBody(openNotifyIssPositionBean); } }
UTF-8
Java
719
java
OrderTransformBean.java
Java
[]
null
[]
package se.cag.routes; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.camel.Body; import org.apache.camel.Handler; import org.apache.camel.Message; import java.io.IOException; public class OrderTransformBean { @Handler public void transform(@Body Message message) throws IOException { ObjectMapper mapper = new ObjectMapper(); // Konvertera inkommande JSON-sträng från exchange till ett OpenNotifyIssPositionBean-objekt mha ObjectMapern OpenNotifyIssPositionBean openNotifyIssPositionBean = mapper.readValue(message.getBody(String.class), OpenNotifyIssPositionBean.class); // Sätt det nya objektet som body i exchange message.setBody(openNotifyIssPositionBean); } }
719
0.803073
0.803073
19
36.684212
36.36808
139
false
false
0
0
0
0
0
0
0.526316
false
false
13
800e2daf05b66acf7520edb892919d8374dc60eb
14,181,982,013,732
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_9155c4acfce39ff088e22cdf9eab13b36f6908e7/SpawnHeight/2_9155c4acfce39ff088e22cdf9eab13b36f6908e7_SpawnHeight_s.java
b81b0ac63e213d4c5533fb0771228d8c30e72375
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package com.nullblock.vemacs.spawnheight; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.plugin.java.JavaPlugin; public class SpawnHeight extends JavaPlugin implements Listener { public void onDisable() { } public void onEnable() { getServer().getPluginManager().registerEvents(this, this); this.saveDefaultConfig(); this.getLogger().info( "Starting SpawnHeight with max " + this.getConfig().getInt("max") + ", min " + this.getConfig().getInt("min") + " and probability " + Float.parseFloat(this.getConfig().getString("prob"))); } @EventHandler(priority = EventPriority.HIGHEST) public void onMobSpawn(CreatureSpawnEvent event) { if (((int) event.getLocation().getY() > this.getConfig().getInt("max") || (int) event .getLocation().getY() < this.getConfig().getInt("min")) && event.getSpawnReason().equals(SpawnReason.NATURAL)) { float f = Float.parseFloat(this.getConfig().getString("prob")); if (!canSpawn(f)) { event.setCancelled(true); } } } public boolean canSpawn(float f) { float compare = (float) Math.random(); if (compare <= f) { return true; } return false; } }
UTF-8
Java
1,392
java
2_9155c4acfce39ff088e22cdf9eab13b36f6908e7_SpawnHeight_s.java
Java
[]
null
[]
package com.nullblock.vemacs.spawnheight; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.plugin.java.JavaPlugin; public class SpawnHeight extends JavaPlugin implements Listener { public void onDisable() { } public void onEnable() { getServer().getPluginManager().registerEvents(this, this); this.saveDefaultConfig(); this.getLogger().info( "Starting SpawnHeight with max " + this.getConfig().getInt("max") + ", min " + this.getConfig().getInt("min") + " and probability " + Float.parseFloat(this.getConfig().getString("prob"))); } @EventHandler(priority = EventPriority.HIGHEST) public void onMobSpawn(CreatureSpawnEvent event) { if (((int) event.getLocation().getY() > this.getConfig().getInt("max") || (int) event .getLocation().getY() < this.getConfig().getInt("min")) && event.getSpawnReason().equals(SpawnReason.NATURAL)) { float f = Float.parseFloat(this.getConfig().getString("prob")); if (!canSpawn(f)) { event.setCancelled(true); } } } public boolean canSpawn(float f) { float compare = (float) Math.random(); if (compare <= f) { return true; } return false; } }
1,392
0.683908
0.683908
45
29.911112
24.235714
88
false
false
0
0
0
0
0
0
2.044445
false
false
13
addf903874a153270885ac2edd1826543d725a95
23,210,003,327,033
79006e9f432456421af7397d94dbc06b371a24c1
/pia/phyutility/src/jebl/evolution/sequences/GeneticCode.java
cd1cb203fe433e71a1d93dc777d7bc91059c88cc
[ "MIT", "GPL-3.0-only" ]
permissive
MartinGuehmann/PIA2
https://github.com/MartinGuehmann/PIA2
7e8b076978389f22be76bfec79975041fdc20afb
cebb4d0913b3f2d7cfe1edbc9980cdc9c7cc937d
refs/heads/master
2021-09-18T09:28:26.758000
2018-03-05T23:54:09
2018-03-05T23:54:09
244,445,337
0
0
MIT
true
2020-03-02T18:31:44
2020-03-02T18:31:44
2017-10-27T16:16:17
2018-03-05T23:54:22
14,436
0
0
0
null
false
false
/* * GeneticCode.java * * (c) 2002-2005 JEBL Development Core Team * * This package may be distributed under the * Lesser Gnu Public Licence (LGPL) */ package jebl.evolution.sequences; import java.util.*; /** * A set of standard genetic codes. * * @author Andrew Rambaut * @author Alexei Drummond * * @version $Id: GeneticCode.java 719 2007-05-31 04:46:40Z matt_kearse $ */ public final class GeneticCode { /** * Standard genetic code tables from GENBANK * Nucleotides go A, C, G, T - Note: this is not the order used by the Genbank web site * With the first codon position most significant (i.e. AAA, AAC, AAG, AAT, ACA, etc.). * * The codes for the individual amino acids can be found in AminoAcids.java; * For example, "*" stands for a stop codon (AminoAcids.STOP_STATE) */ private static final String[] GENETIC_CODE_TABLES = { // Universal "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Vertebrate Mitochondrial "KNKNTTTT*S*SMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Yeast "KNKNTTTTRSRSMIMIQHQHPPPPRRRRTTTTEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Mold Protozoan Mitochondrial "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Mycoplasma "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Invertebrate Mitochondrial "KNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Ciliate "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVQYQYSSSS*CWCLFLF", // Echinoderm Mitochondrial "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Euplotid Nuclear "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSCCWCLFLF", // Bacterial "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Alternative Yeast "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLSLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Ascidian Mitochondrial "KNKNTTTTGSGSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Flatworm Mitochondrial "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVYY*YSSSSWCWCLFLF", // Blepharisma Nuclear "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YQYSSSS*CWCLFLF" }; /** * Names of the standard genetic code tables from GENBANK */ private static final String[] GENETIC_CODE_NAMES = { "universal", "vertebrateMitochondrial", "yeast", "moldProtozoanMitochondrial", "mycoplasma", "invertebrateMitochondrial", "ciliate", "echinodermMitochondrial", "euplotidNuclear", "bacterial", "alternativeYeast", "ascidianMitochondrial", "flatwormMitochondrial", "blepharismaNuclear" }; /** * Descriptions of the standard genetic code tables from GENBANK */ private static final String[] GENETIC_CODE_DESCRIPTIONS = { "Universal", "Vertebrate Mitochondrial", "Yeast", "Mold Protozoan Mitochondrial", "Mycoplasma", "Invertebrate Mitochondrial", "Ciliate", "Echinoderm Mitochondrial", "Euplotid Nuclear", "Bacterial", "Alternative Yeast", "Ascidian Mitochondrial", "Flatworm Mitochondrial", "Blepharisma Nuclear" }; public static final GeneticCode UNIVERSAL = new GeneticCode(GeneticCode.UNIVERSAL_ID); public static final GeneticCode VERTEBRATE_MT = new GeneticCode(GeneticCode.VERTEBRATE_MT_ID); public static final GeneticCode YEAST = new GeneticCode(GeneticCode.YEAST_ID); public static final GeneticCode MOLD_PROTOZOAN_MT = new GeneticCode(GeneticCode.MOLD_PROTOZOAN_MT_ID); public static final GeneticCode MYCOPLASMA = new GeneticCode(GeneticCode.MYCOPLASMA_ID); public static final GeneticCode INVERTEBRATE_MT = new GeneticCode(GeneticCode.INVERTEBRATE_MT_ID); public static final GeneticCode CILIATE = new GeneticCode(GeneticCode.CILIATE_ID); public static final GeneticCode ECHINODERM_MT = new GeneticCode(GeneticCode.ECHINODERM_MT_ID); public static final GeneticCode EUPLOTID_NUC = new GeneticCode(GeneticCode.EUPLOTID_NUC_ID); public static final GeneticCode BACTERIAL = new GeneticCode(GeneticCode.BACTERIAL_ID); public static final GeneticCode ALT_YEAST = new GeneticCode(GeneticCode.ALT_YEAST_ID); public static final GeneticCode ASCIDIAN_MT = new GeneticCode(GeneticCode.ASCIDIAN_MT_ID); public static final GeneticCode FLATWORM_MT = new GeneticCode(GeneticCode.FLATWORM_MT_ID); public static final GeneticCode BLEPHARISMA_NUC = new GeneticCode(GeneticCode.BLEPHARISMA_NUC_ID); public static final GeneticCode[] GENETIC_CODES = { UNIVERSAL, VERTEBRATE_MT, YEAST, MOLD_PROTOZOAN_MT, MYCOPLASMA, INVERTEBRATE_MT, CILIATE, ECHINODERM_MT, EUPLOTID_NUC, BACTERIAL, ALT_YEAST, ASCIDIAN_MT, FLATWORM_MT, BLEPHARISMA_NUC }; private GeneticCode(int geneticCodeId) { this.geneticCodeId = geneticCodeId; String codeTable = GENETIC_CODE_TABLES[geneticCodeId]; Map<CodonState, AminoAcidState> translationMap = new TreeMap<CodonState, AminoAcidState>(); if (codeTable.length() != 64) { throw new IllegalArgumentException("Code Table length does not match number of codon states"); } for (int i = 0; i < codeTable.length(); i++) { CodonState codonState = Codons.CANONICAL_STATES[i]; AminoAcidState aminoAcidState = AminoAcids.getState(codeTable.substring(i, i+1)); translationMap.put(codonState, aminoAcidState); } translationMap.put(Codons.getGapState(), AminoAcids.getGapState()); translationMap.put(Codons.getUnknownState(), AminoAcids.getUnknownState()); this.translationMap = Collections.unmodifiableMap(translationMap); } /** * Returns the name of the genetic code */ public String getName() { return GENETIC_CODE_NAMES[geneticCodeId]; } /** * Returns the description of the genetic code */ public String getDescription() { return GENETIC_CODE_DESCRIPTIONS[geneticCodeId]; } /** * Returns the description of the genetic code */ public String getCodeTable() { return GENETIC_CODE_TABLES[geneticCodeId]; } /** * Returns the state associated with AminoAcid represented by codonState. * Note that the state is the canonical state (generated combinatorially) * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(CodonState codonState) { //System.out.println(codonState.getCode()); return translationMap.get(codonState); } /** * Returns the state associated with AminoAcid represented by the three nucleotides. * If one or more of the nucleotides are ambiguous, and all combinations translate to the * same protein, then this method will return that protein * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(NucleotideState nucleotide1, NucleotideState nucleotide2, NucleotideState nucleotide3){ CodonState translateState = null; if (nucleotide1.isGap() && nucleotide2.isGap() && nucleotide3.isGap()) { translateState = Codons.GAP_STATE; } if (nucleotide1.isAmbiguous() || nucleotide2.isAmbiguous() || nucleotide3.isAmbiguous()) { for(State a : nucleotide1.getCanonicalStates()){ for(State b : nucleotide2.getCanonicalStates()){ for(State c : nucleotide3.getCanonicalStates()){ //initial setup if(translateState == null) translateState = Codons.getState(a.getCode() + b.getCode() + c.getCode()); if(!translationMap.get(translateState).equals(translationMap.get(Codons.getState(a.getCode() + b.getCode() + c.getCode())))) return translationMap.get(Codons.UNKNOWN_STATE); } } } return translationMap.get(translateState); } String code = nucleotide1.getCode() + nucleotide2.getCode() + nucleotide3.getCode(); translateState = Codons.getState(code); return translationMap.get(translateState); } /** * Returns the state associated with AminoAcid represented by the three nucleotides. * If one or more of the nucleotides are ambiguous, and all combinations translate to the * same protein, then this method will return that protein * @param nucleotides a string consisting of exactly 3 residues in any case. * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(String nucleotides) { if (nucleotides.length()!=3) throw new IllegalArgumentException("getTranslation requires a nucleotide triplet. (given "+nucleotides.length()+" characters)"); NucleotideState n1=Nucleotides.getState(nucleotides.charAt(0)); NucleotideState n2=Nucleotides.getState(nucleotides.charAt(1)); NucleotideState n3=Nucleotides.getState(nucleotides.charAt(2)); return getTranslation(n1,n2,n3); } /** * Returns true if this is a start codon in this genetic code. * WARNING: I don't know how to implement this. It only returns true * for ATG currently. But according to Wikipedia, about 23% of E.Coli * start codons are not ATG! * @param codonState * @return true if this is a start codon. */ public boolean isStartCodon(CodonState codonState) { if (codonState==null) return false; // to handle codons generated from ambiguous residues where it returns null from Codons.getState() return codonState.getCode().equals("ATG"); } /** * Note that the state is the canonical state (generated combinatorially) * @return whether the codonState is a stop codon */ public boolean isStopCodon(CodonState codonState) { if (codonState==null) return false; // to handle codons generated from ambiguous residues where it returns null from Codons.getState() return (translationMap.get(codonState) == AminoAcids.STOP_STATE); } /** * @return all the possible codons for a given amino acid */ public Set<CodonState> getCodonsForAminoAcid(AminoAcidState aminoAcidState) { Set<CodonState> aaSet = new HashSet<CodonState>(); for (CodonState state : translationMap.keySet()) { if (translationMap.get(state) == aminoAcidState) { aaSet.add(state); } } return aaSet; } /** * @return the codon states of stops. */ public Set<CodonState> getStopCodons() { Set<CodonState> stopSet = new HashSet<CodonState>(); for (CodonState state : translationMap.keySet()) { if (isStopCodon(state)) { stopSet.add(state); } } return stopSet; } /** * Returns the number of terminator amino acids. */ public int getStopCodonCount() { int count = 0; for (AminoAcidState state : translationMap.values()) { if (state == AminoAcids.STOP_STATE) { count++; } } return count; } private final int geneticCodeId; private final Map<CodonState, AminoAcidState> translationMap; /** * Constants used to refer to the built in code tables */ private static final int UNIVERSAL_ID = 0; private static final int VERTEBRATE_MT_ID = 1; private static final int YEAST_ID = 2; private static final int MOLD_PROTOZOAN_MT_ID = 3; private static final int MYCOPLASMA_ID = 4; private static final int INVERTEBRATE_MT_ID = 5; private static final int CILIATE_ID = 6; private static final int ECHINODERM_MT_ID = 7; private static final int EUPLOTID_NUC_ID = 8; private static final int BACTERIAL_ID = 9; private static final int ALT_YEAST_ID = 10; private static final int ASCIDIAN_MT_ID = 11; private static final int FLATWORM_MT_ID = 12; private static final int BLEPHARISMA_NUC_ID = 13; public String toString() { return getDescription(); } }
UTF-8
Java
12,022
java
GeneticCode.java
Java
[ { "context": "\n * A set of standard genetic codes.\n *\n * @author Andrew Rambaut\n * @author Alexei Drummond\n *\n * @version $Id: Ge", "end": 283, "score": 0.9998205900192261, "start": 269, "tag": "NAME", "value": "Andrew Rambaut" }, { "context": "tic codes.\n *\n * @author Andrew Rambaut\n * @author Alexei Drummond\n *\n * @version $Id: GeneticCode.java 719 2007-05-", "end": 310, "score": 0.9998703002929688, "start": 295, "tag": "NAME", "value": "Alexei Drummond" } ]
null
[]
/* * GeneticCode.java * * (c) 2002-2005 JEBL Development Core Team * * This package may be distributed under the * Lesser Gnu Public Licence (LGPL) */ package jebl.evolution.sequences; import java.util.*; /** * A set of standard genetic codes. * * @author <NAME> * @author <NAME> * * @version $Id: GeneticCode.java 719 2007-05-31 04:46:40Z matt_kearse $ */ public final class GeneticCode { /** * Standard genetic code tables from GENBANK * Nucleotides go A, C, G, T - Note: this is not the order used by the Genbank web site * With the first codon position most significant (i.e. AAA, AAC, AAG, AAT, ACA, etc.). * * The codes for the individual amino acids can be found in AminoAcids.java; * For example, "*" stands for a stop codon (AminoAcids.STOP_STATE) */ private static final String[] GENETIC_CODE_TABLES = { // Universal "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Vertebrate Mitochondrial "KNKNTTTT*S*SMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Yeast "KNKNTTTTRSRSMIMIQHQHPPPPRRRRTTTTEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Mold Protozoan Mitochondrial "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Mycoplasma "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Invertebrate Mitochondrial "KNKNTTTTSSSSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Ciliate "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVQYQYSSSS*CWCLFLF", // Echinoderm Mitochondrial "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Euplotid Nuclear "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSCCWCLFLF", // Bacterial "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Alternative Yeast "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLSLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF", // Ascidian Mitochondrial "KNKNTTTTGSGSMIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSSWCWCLFLF", // Flatworm Mitochondrial "NNKNTTTTSSSSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVYY*YSSSSWCWCLFLF", // Blepharisma Nuclear "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*YQYSSSS*CWCLFLF" }; /** * Names of the standard genetic code tables from GENBANK */ private static final String[] GENETIC_CODE_NAMES = { "universal", "vertebrateMitochondrial", "yeast", "moldProtozoanMitochondrial", "mycoplasma", "invertebrateMitochondrial", "ciliate", "echinodermMitochondrial", "euplotidNuclear", "bacterial", "alternativeYeast", "ascidianMitochondrial", "flatwormMitochondrial", "blepharismaNuclear" }; /** * Descriptions of the standard genetic code tables from GENBANK */ private static final String[] GENETIC_CODE_DESCRIPTIONS = { "Universal", "Vertebrate Mitochondrial", "Yeast", "Mold Protozoan Mitochondrial", "Mycoplasma", "Invertebrate Mitochondrial", "Ciliate", "Echinoderm Mitochondrial", "Euplotid Nuclear", "Bacterial", "Alternative Yeast", "Ascidian Mitochondrial", "Flatworm Mitochondrial", "Blepharisma Nuclear" }; public static final GeneticCode UNIVERSAL = new GeneticCode(GeneticCode.UNIVERSAL_ID); public static final GeneticCode VERTEBRATE_MT = new GeneticCode(GeneticCode.VERTEBRATE_MT_ID); public static final GeneticCode YEAST = new GeneticCode(GeneticCode.YEAST_ID); public static final GeneticCode MOLD_PROTOZOAN_MT = new GeneticCode(GeneticCode.MOLD_PROTOZOAN_MT_ID); public static final GeneticCode MYCOPLASMA = new GeneticCode(GeneticCode.MYCOPLASMA_ID); public static final GeneticCode INVERTEBRATE_MT = new GeneticCode(GeneticCode.INVERTEBRATE_MT_ID); public static final GeneticCode CILIATE = new GeneticCode(GeneticCode.CILIATE_ID); public static final GeneticCode ECHINODERM_MT = new GeneticCode(GeneticCode.ECHINODERM_MT_ID); public static final GeneticCode EUPLOTID_NUC = new GeneticCode(GeneticCode.EUPLOTID_NUC_ID); public static final GeneticCode BACTERIAL = new GeneticCode(GeneticCode.BACTERIAL_ID); public static final GeneticCode ALT_YEAST = new GeneticCode(GeneticCode.ALT_YEAST_ID); public static final GeneticCode ASCIDIAN_MT = new GeneticCode(GeneticCode.ASCIDIAN_MT_ID); public static final GeneticCode FLATWORM_MT = new GeneticCode(GeneticCode.FLATWORM_MT_ID); public static final GeneticCode BLEPHARISMA_NUC = new GeneticCode(GeneticCode.BLEPHARISMA_NUC_ID); public static final GeneticCode[] GENETIC_CODES = { UNIVERSAL, VERTEBRATE_MT, YEAST, MOLD_PROTOZOAN_MT, MYCOPLASMA, INVERTEBRATE_MT, CILIATE, ECHINODERM_MT, EUPLOTID_NUC, BACTERIAL, ALT_YEAST, ASCIDIAN_MT, FLATWORM_MT, BLEPHARISMA_NUC }; private GeneticCode(int geneticCodeId) { this.geneticCodeId = geneticCodeId; String codeTable = GENETIC_CODE_TABLES[geneticCodeId]; Map<CodonState, AminoAcidState> translationMap = new TreeMap<CodonState, AminoAcidState>(); if (codeTable.length() != 64) { throw new IllegalArgumentException("Code Table length does not match number of codon states"); } for (int i = 0; i < codeTable.length(); i++) { CodonState codonState = Codons.CANONICAL_STATES[i]; AminoAcidState aminoAcidState = AminoAcids.getState(codeTable.substring(i, i+1)); translationMap.put(codonState, aminoAcidState); } translationMap.put(Codons.getGapState(), AminoAcids.getGapState()); translationMap.put(Codons.getUnknownState(), AminoAcids.getUnknownState()); this.translationMap = Collections.unmodifiableMap(translationMap); } /** * Returns the name of the genetic code */ public String getName() { return GENETIC_CODE_NAMES[geneticCodeId]; } /** * Returns the description of the genetic code */ public String getDescription() { return GENETIC_CODE_DESCRIPTIONS[geneticCodeId]; } /** * Returns the description of the genetic code */ public String getCodeTable() { return GENETIC_CODE_TABLES[geneticCodeId]; } /** * Returns the state associated with AminoAcid represented by codonState. * Note that the state is the canonical state (generated combinatorially) * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(CodonState codonState) { //System.out.println(codonState.getCode()); return translationMap.get(codonState); } /** * Returns the state associated with AminoAcid represented by the three nucleotides. * If one or more of the nucleotides are ambiguous, and all combinations translate to the * same protein, then this method will return that protein * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(NucleotideState nucleotide1, NucleotideState nucleotide2, NucleotideState nucleotide3){ CodonState translateState = null; if (nucleotide1.isGap() && nucleotide2.isGap() && nucleotide3.isGap()) { translateState = Codons.GAP_STATE; } if (nucleotide1.isAmbiguous() || nucleotide2.isAmbiguous() || nucleotide3.isAmbiguous()) { for(State a : nucleotide1.getCanonicalStates()){ for(State b : nucleotide2.getCanonicalStates()){ for(State c : nucleotide3.getCanonicalStates()){ //initial setup if(translateState == null) translateState = Codons.getState(a.getCode() + b.getCode() + c.getCode()); if(!translationMap.get(translateState).equals(translationMap.get(Codons.getState(a.getCode() + b.getCode() + c.getCode())))) return translationMap.get(Codons.UNKNOWN_STATE); } } } return translationMap.get(translateState); } String code = nucleotide1.getCode() + nucleotide2.getCode() + nucleotide3.getCode(); translateState = Codons.getState(code); return translationMap.get(translateState); } /** * Returns the state associated with AminoAcid represented by the three nucleotides. * If one or more of the nucleotides are ambiguous, and all combinations translate to the * same protein, then this method will return that protein * @param nucleotides a string consisting of exactly 3 residues in any case. * @see AminoAcids * @see Codons * @return '?' if codon unknown */ public AminoAcidState getTranslation(String nucleotides) { if (nucleotides.length()!=3) throw new IllegalArgumentException("getTranslation requires a nucleotide triplet. (given "+nucleotides.length()+" characters)"); NucleotideState n1=Nucleotides.getState(nucleotides.charAt(0)); NucleotideState n2=Nucleotides.getState(nucleotides.charAt(1)); NucleotideState n3=Nucleotides.getState(nucleotides.charAt(2)); return getTranslation(n1,n2,n3); } /** * Returns true if this is a start codon in this genetic code. * WARNING: I don't know how to implement this. It only returns true * for ATG currently. But according to Wikipedia, about 23% of E.Coli * start codons are not ATG! * @param codonState * @return true if this is a start codon. */ public boolean isStartCodon(CodonState codonState) { if (codonState==null) return false; // to handle codons generated from ambiguous residues where it returns null from Codons.getState() return codonState.getCode().equals("ATG"); } /** * Note that the state is the canonical state (generated combinatorially) * @return whether the codonState is a stop codon */ public boolean isStopCodon(CodonState codonState) { if (codonState==null) return false; // to handle codons generated from ambiguous residues where it returns null from Codons.getState() return (translationMap.get(codonState) == AminoAcids.STOP_STATE); } /** * @return all the possible codons for a given amino acid */ public Set<CodonState> getCodonsForAminoAcid(AminoAcidState aminoAcidState) { Set<CodonState> aaSet = new HashSet<CodonState>(); for (CodonState state : translationMap.keySet()) { if (translationMap.get(state) == aminoAcidState) { aaSet.add(state); } } return aaSet; } /** * @return the codon states of stops. */ public Set<CodonState> getStopCodons() { Set<CodonState> stopSet = new HashSet<CodonState>(); for (CodonState state : translationMap.keySet()) { if (isStopCodon(state)) { stopSet.add(state); } } return stopSet; } /** * Returns the number of terminator amino acids. */ public int getStopCodonCount() { int count = 0; for (AminoAcidState state : translationMap.values()) { if (state == AminoAcids.STOP_STATE) { count++; } } return count; } private final int geneticCodeId; private final Map<CodonState, AminoAcidState> translationMap; /** * Constants used to refer to the built in code tables */ private static final int UNIVERSAL_ID = 0; private static final int VERTEBRATE_MT_ID = 1; private static final int YEAST_ID = 2; private static final int MOLD_PROTOZOAN_MT_ID = 3; private static final int MYCOPLASMA_ID = 4; private static final int INVERTEBRATE_MT_ID = 5; private static final int CILIATE_ID = 6; private static final int ECHINODERM_MT_ID = 7; private static final int EUPLOTID_NUC_ID = 8; private static final int BACTERIAL_ID = 9; private static final int ALT_YEAST_ID = 10; private static final int ASCIDIAN_MT_ID = 11; private static final int FLATWORM_MT_ID = 12; private static final int BLEPHARISMA_NUC_ID = 13; public String toString() { return getDescription(); } }
12,005
0.69797
0.691649
298
39.342281
34.099396
165
false
false
0
0
0
0
0
0
0.983221
false
false
13
2b903c99ca75efab9fc6c39b17b7fd55046f9094
16,561,393,951,037
e6157a779514afb66e3db8333f30e16834338e82
/src/JavaAdvanced/MultidimensionalArrays/src/Exercises/_12_The_Matrix_2.java
88283733e399606568e72e9925617426b890d2d6
[]
no_license
kossyo/JavaAdvanced
https://github.com/kossyo/JavaAdvanced
e4021fa2709ba361babc79b5dcdab44a02a30652
e09c66cff08eb69f612dbfada36aa22e3cd0db2f
refs/heads/master
2021-03-20T23:39:22.726000
2020-03-14T09:03:37
2020-03-14T09:03:37
247,243,456
0
0
null
false
2020-10-13T20:21:13
2020-03-14T08:58:59
2020-03-14T09:03:47
2020-10-13T20:21:11
542
0
0
2
Java
false
false
package Exercises; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; public class _12_The_Matrix_2 { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { int[] dimensions = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); char[][] matrix = new char[dimensions[0]][dimensions[1]]; fillMatrix(matrix); char replaceChar = reader.readLine().charAt(0); int[] target = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); traverse(matrix, target, replaceChar); printMatrix(matrix); } private static void traverse(char[][] matrix, int[] target, char replaceChar) { Deque<Integer[]> stack = new ArrayDeque<>(); char originalChar = matrix[target[0]][target[1]]; int[] currentIndex = {target[0], target[1]}; while (true) { try { boolean hasUpper = false; boolean hasRight = false; if (matrix[currentIndex[0]][currentIndex[1]] == originalChar){ hasUpper = true; } if (matrix[currentIndex[0]][currentIndex[1] + 1] == originalChar){ hasRight = true; } if (hasUpper) { Integer[] node = {currentIndex[0], currentIndex[1], 0}; stack.push(node); currentIndex[0]--; } if(hasRight){ currentIndex[1]++; Integer[] node = {currentIndex[0], currentIndex[1], 0}; stack.push(node); } else { Integer[] node = stack.pop(); matrix[node[0]][node[1]] = replaceChar; } if (stack.isEmpty()){ break; } } catch (Exception e) { while (!stack.isEmpty()) { Integer[] node = stack.pop(); matrix[node[0]][node[1]] = replaceChar; } break; } } } private static void fillMatrix(char[][] matrix) throws IOException { for (int i = 0; i < matrix.length; i++) { matrix[i] = reader.readLine().replaceAll(" ", "").toCharArray(); } } private static void printMatrix(char[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j]); } System.out.println(); } } }
UTF-8
Java
2,993
java
_12_The_Matrix_2.java
Java
[]
null
[]
package Exercises; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; public class _12_The_Matrix_2 { static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { int[] dimensions = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); char[][] matrix = new char[dimensions[0]][dimensions[1]]; fillMatrix(matrix); char replaceChar = reader.readLine().charAt(0); int[] target = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); traverse(matrix, target, replaceChar); printMatrix(matrix); } private static void traverse(char[][] matrix, int[] target, char replaceChar) { Deque<Integer[]> stack = new ArrayDeque<>(); char originalChar = matrix[target[0]][target[1]]; int[] currentIndex = {target[0], target[1]}; while (true) { try { boolean hasUpper = false; boolean hasRight = false; if (matrix[currentIndex[0]][currentIndex[1]] == originalChar){ hasUpper = true; } if (matrix[currentIndex[0]][currentIndex[1] + 1] == originalChar){ hasRight = true; } if (hasUpper) { Integer[] node = {currentIndex[0], currentIndex[1], 0}; stack.push(node); currentIndex[0]--; } if(hasRight){ currentIndex[1]++; Integer[] node = {currentIndex[0], currentIndex[1], 0}; stack.push(node); } else { Integer[] node = stack.pop(); matrix[node[0]][node[1]] = replaceChar; } if (stack.isEmpty()){ break; } } catch (Exception e) { while (!stack.isEmpty()) { Integer[] node = stack.pop(); matrix[node[0]][node[1]] = replaceChar; } break; } } } private static void fillMatrix(char[][] matrix) throws IOException { for (int i = 0; i < matrix.length; i++) { matrix[i] = reader.readLine().replaceAll(" ", "").toCharArray(); } } private static void printMatrix(char[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j]); } System.out.println(); } } }
2,993
0.482125
0.471767
98
28.540817
26.904278
109
false
false
0
0
0
0
0
0
0.540816
false
false
13
f92d22537812aaff2cf7e342e9f2e41a0fc7bb92
14,937,896,264,711
1176e2212a13cf2f90d984c776a56295022d260d
/SZASServer/src/com/szas/server/gwt/client/router/RouteAction.java
147bb4291801d82c4a568a2e17fbef17b12ebf64
[ "Apache-2.0" ]
permissive
jacek-marchwicki/SZAS-form
https://github.com/jacek-marchwicki/SZAS-form
e65cb838c596596abc746af02fd46ea6107b9bfc
6ba54aee349fefc136ea72b04f44d1fcde6cb283
refs/heads/master
2020-04-06T06:55:34.849000
2011-06-13T01:39:36
2011-06-13T01:39:36
1,524,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szas.server.gwt.client.router; public interface RouteAction<T> { T run(String command, String params); }
UTF-8
Java
119
java
RouteAction.java
Java
[]
null
[]
package com.szas.server.gwt.client.router; public interface RouteAction<T> { T run(String command, String params); }
119
0.764706
0.764706
5
22.799999
18.432579
42
false
false
0
0
0
0
0
0
0.8
false
false
13
dbf51d9d4a1253cd9346429fd68972193a8b35ad
33,208,687,183,788
b39c05ea5c9c298bcdd1c1af6667eb1da01ba285
/Week 05/02-exponential-size-dfa-quiz.java
b6d9eb11984f52336a4b51c137909ddbd6c0164e
[]
no_license
raghav3112/Algorithms---Part-II
https://github.com/raghav3112/Algorithms---Part-II
fb31ba25a029fb0bc0f27500d2f3701fa30b45b0
16e29e61304dd3054e316dd279bb1a16b8d4749e
refs/heads/master
2022-01-25T14:46:44.374000
2019-06-23T13:30:05
2019-06-23T13:30:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Exponential-size DFA // Pseudo-code public class ExponentialSizeDFA { // Match transitions private char[] re; // Epsilon transition digraph private Digraph G; // Number of states private int M; // Helper function to build diagraph private Digraph buildDigraph() {} // Build exponential-size DFA public ExponentialSizeDFA(String regexp) {} // Tests public static void main(String[] args) {} }
UTF-8
Java
426
java
02-exponential-size-dfa-quiz.java
Java
[]
null
[]
// Exponential-size DFA // Pseudo-code public class ExponentialSizeDFA { // Match transitions private char[] re; // Epsilon transition digraph private Digraph G; // Number of states private int M; // Helper function to build diagraph private Digraph buildDigraph() {} // Build exponential-size DFA public ExponentialSizeDFA(String regexp) {} // Tests public static void main(String[] args) {} }
426
0.701878
0.701878
20
20.299999
14.550258
45
false
false
0
0
0
0
0
0
0.15
false
false
13
6b87727fafa4ba5d2e0ea2f5c5f257850d91cad3
5,102,421,162,851
651b21a6201fbca082be4a4596c13c14dd310bb0
/EngIII_Project/src/br/com/fatec2019/Strategy/IStrategy.java
aab5e28de0a140335ab846a13d6b9f449cf1c251
[]
no_license
eduardowmu/curso-git
https://github.com/eduardowmu/curso-git
82de91166f2b793403350cd4c9eb505b3db55f35
bfc2d7617064103bad62bab0affa0734d7d9c7ae
refs/heads/master
2020-04-27T00:59:13.038000
2019-06-25T20:08:27
2019-06-25T20:08:27
173,951,868
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.fatec2019.Strategy; import br.com.fatec2019.Dominio.EntidadeDominio; //interface de Strategy, cujas classes que a implementam irão sempre implementar um método com mesmo nome, //seja de validação ou outros métodos public interface IStrategy {public abstract String Processar(EntidadeDominio entidade);}
ISO-8859-1
Java
325
java
IStrategy.java
Java
[]
null
[]
package br.com.fatec2019.Strategy; import br.com.fatec2019.Dominio.EntidadeDominio; //interface de Strategy, cujas classes que a implementam irão sempre implementar um método com mesmo nome, //seja de validação ou outros métodos public interface IStrategy {public abstract String Processar(EntidadeDominio entidade);}
325
0.825
0.8
7
44.714287
30.517977
106
false
false
0
0
0
0
0
0
0.714286
false
false
13