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
15d8883f18aa1b39a65519daf2f0f36cdcca93ac
35,450,660,088,577
7d5b8772d8425772dd12c63302e6fe4ccac1856f
/W-H/src/com/ros/workandhome/activities/sectionsettings/SectionSettingsIncomingCallsAdapter.java
6eda97678127e522e8041b0d0a3c3d448cb1e67f
[]
no_license
Rostyk/W-H
https://github.com/Rostyk/W-H
ec8bf7717f0b67074fd5b070dac73f63536f6017
a8c3a5c2eb1ca59a4407eba23e688a8726a790ff
refs/heads/master
2021-01-22T11:41:23.750000
2014-06-14T10:15:07
2014-06-14T10:15:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ros.workandhome.activities.sectionsettings; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.TextView; import com.ros.workandhome.R; import com.ros.workandhome.core.entities.GPSLocation.WHGPSLocation; import com.ros.workandhome.core.entities.WHContact.WHContact; public class SectionSettingsIncomingCallsAdapter extends ArrayAdapter<WHContact>{ private TextView contactNameTextView; private TextView contactCellPhoneTextView; private CheckBox rejectCallCheckBox; private CheckBox replyCallWithSMSCheckBox; private List<WHContact> contacts = new ArrayList<WHContact>(); public SectionSettingsIncomingCallsAdapter(Context context, int textViewResourceId, List<WHContact> objects) { super(context, textViewResourceId, objects); this.contacts = objects; } public int getCount() { if(this.contacts == null) return 0; return this.contacts.size(); } public WHContact getItem(int index) { return this.contacts.get(index); } /* * * * * * section_settings_incomming_call_item_remove */ public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { // ROW INFLATION LayoutInflater inflater = (LayoutInflater) this.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.section_settings_incoming_call_list_item, parent, false); } // Get item WHContact contact = getItem(position); //Name contactNameTextView = (TextView) row.findViewById(R.id.section_settings_incomming_call_item_name); String name = contact.getName(); contactNameTextView.setText(name); contactCellPhoneTextView = (TextView) row.findViewById(R.id.section_settings_incomming_call_item_cell_phone); String cellPhone = contact.getCellPhone(); contactCellPhoneTextView.setText(cellPhone); rejectCallCheckBox = (CheckBox) row.findViewById(R.id.section_settings_incomming_call_item_reject_call); rejectCallCheckBox.setChecked(contact.getRejectCall()); replyCallWithSMSCheckBox = (CheckBox) row.findViewById(R.id.section_settings_incomming_call_item_reply_wth_sms); replyCallWithSMSCheckBox.setChecked(contact.getReplyWithSMS()); return row; } }
UTF-8
Java
2,727
java
SectionSettingsIncomingCallsAdapter.java
Java
[]
null
[]
package com.ros.workandhome.activities.sectionsettings; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.TextView; import com.ros.workandhome.R; import com.ros.workandhome.core.entities.GPSLocation.WHGPSLocation; import com.ros.workandhome.core.entities.WHContact.WHContact; public class SectionSettingsIncomingCallsAdapter extends ArrayAdapter<WHContact>{ private TextView contactNameTextView; private TextView contactCellPhoneTextView; private CheckBox rejectCallCheckBox; private CheckBox replyCallWithSMSCheckBox; private List<WHContact> contacts = new ArrayList<WHContact>(); public SectionSettingsIncomingCallsAdapter(Context context, int textViewResourceId, List<WHContact> objects) { super(context, textViewResourceId, objects); this.contacts = objects; } public int getCount() { if(this.contacts == null) return 0; return this.contacts.size(); } public WHContact getItem(int index) { return this.contacts.get(index); } /* * * * * * section_settings_incomming_call_item_remove */ public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { // ROW INFLATION LayoutInflater inflater = (LayoutInflater) this.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.section_settings_incoming_call_list_item, parent, false); } // Get item WHContact contact = getItem(position); //Name contactNameTextView = (TextView) row.findViewById(R.id.section_settings_incomming_call_item_name); String name = contact.getName(); contactNameTextView.setText(name); contactCellPhoneTextView = (TextView) row.findViewById(R.id.section_settings_incomming_call_item_cell_phone); String cellPhone = contact.getCellPhone(); contactCellPhoneTextView.setText(cellPhone); rejectCallCheckBox = (CheckBox) row.findViewById(R.id.section_settings_incomming_call_item_reject_call); rejectCallCheckBox.setChecked(contact.getRejectCall()); replyCallWithSMSCheckBox = (CheckBox) row.findViewById(R.id.section_settings_incomming_call_item_reply_wth_sms); replyCallWithSMSCheckBox.setChecked(contact.getReplyWithSMS()); return row; } }
2,727
0.693069
0.692703
78
33.96154
30.378992
120
false
false
0
0
0
0
0
0
0.641026
false
false
9
97ad9c8280d59a1adade488a469b643e4cc5380b
30,511,447,739,288
946415580cbcd892e9d2ff82cc3ff8c08e12bc80
/src/com/postagain/realim/RealIMApplication.java
2578907768cf7654ee5871a28d4d87830f0aed88
[]
no_license
shahbaz07/RealIM
https://github.com/shahbaz07/RealIM
8abf7d8297c10f6919a16145b161b59e5f5a61c1
6bb15d91f2b65b1e3c8f8b5da5a80149db985a4a
refs/heads/master
2020-05-24T12:45:20.807000
2015-09-12T02:23:16
2015-09-12T02:23:16
42,340,731
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.postagain.realim; import android.app.Application; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.parse.Parse; import com.parse.ParseObject; import com.postagain.realim.model.ChatMessage; public class RealIMApplication extends Application { private static final String APPLICATION_ID = "jjFBUf5TeeK5fDiF6HX9A3TaQ2GcNYREaSlAaQPl"; private static final String CLIENT_KEY = "aC1QvAXp32FlnQosYUl0OPLofzC0OB28F8mAtxXF"; @Override public void onCreate() { super.onCreate(); Parse.enableLocalDatastore(this); ParseObject.registerSubclass(ChatMessage.class); Parse.initialize(this, APPLICATION_ID, CLIENT_KEY); DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() .cacheOnDisk(true) .cacheInMemory(true) .imageScaleType(ImageScaleType.EXACTLY) .displayer(new FadeInBitmapDisplayer(300)).build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( getApplicationContext()) .defaultDisplayImageOptions(defaultOptions) .memoryCache(new WeakMemoryCache()) .diskCacheSize(100 * 1024 * 1024).build(); ImageLoader.getInstance().init(config); } }
UTF-8
Java
1,575
java
RealIMApplication.java
Java
[ { "context": "aQPl\";\n\tprivate static final String CLIENT_KEY = \"aC1QvAXp32FlnQosYUl0OPLofzC0OB28F8mAtxXF\";\n \n @Override\n public void onCreate() {", "end": 813, "score": 0.9997639656066895, "start": 773, "tag": "KEY", "value": "aC1QvAXp32FlnQosYUl0OPLofzC0OB28F8mAtxXF" } ]
null
[]
package com.postagain.realim; import android.app.Application; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.parse.Parse; import com.parse.ParseObject; import com.postagain.realim.model.ChatMessage; public class RealIMApplication extends Application { private static final String APPLICATION_ID = "jjFBUf5TeeK5fDiF6HX9A3TaQ2GcNYREaSlAaQPl"; private static final String CLIENT_KEY = "<KEY>"; @Override public void onCreate() { super.onCreate(); Parse.enableLocalDatastore(this); ParseObject.registerSubclass(ChatMessage.class); Parse.initialize(this, APPLICATION_ID, CLIENT_KEY); DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() .cacheOnDisk(true) .cacheInMemory(true) .imageScaleType(ImageScaleType.EXACTLY) .displayer(new FadeInBitmapDisplayer(300)).build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( getApplicationContext()) .defaultDisplayImageOptions(defaultOptions) .memoryCache(new WeakMemoryCache()) .diskCacheSize(100 * 1024 * 1024).build(); ImageLoader.getInstance().init(config); } }
1,540
0.789206
0.76381
41
37.414635
27.000429
89
false
false
0
0
0
0
0
0
1.268293
false
false
9
5e5f63205e21b10a9f03575f87c07b0ca81aacb9
25,898,652,811,843
6b3fb9a4371e3a1767704ebfed1440704d546824
/src/com/aa/Main.java
6b6b8b7565b7b4f2b95c49f0c077919d52cc198b
[]
no_license
ping3136/rep01
https://github.com/ping3136/rep01
5c54b4c5e84d4ec307b64f6d56e40a033faca7e2
13d9c6226ae27a07de2fc5bf5030fa5ca925432f
refs/heads/master
2020-03-07T12:53:58.565000
2018-03-31T02:39:44
2018-03-31T02:39:44
127,487,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aa; public class Main { public static void main(String[] args) { System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("44444454aaa"); System.out.println("44444454aaa_master_modify"); System.out.println("44444454aaa_release02_modify"); System.out.println("44444454aaa_release modify01"); System.out.println("44444454aaa_release modify02"); System.out.println("44444454aaa_release01 modify03"); System.out.println("44444454aaaa_release01 modify02"); System.out.println("fffffwerwerwr"); System.out.println("ffffffss"); } }
UTF-8
Java
721
java
Main.java
Java
[]
null
[]
package com.aa; public class Main { public static void main(String[] args) { System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("444444aaa"); System.out.println("44444454aaa"); System.out.println("44444454aaa_master_modify"); System.out.println("44444454aaa_release02_modify"); System.out.println("44444454aaa_release modify01"); System.out.println("44444454aaa_release modify02"); System.out.println("44444454aaa_release01 modify03"); System.out.println("44444454aaaa_release01 modify02"); System.out.println("fffffwerwerwr"); System.out.println("ffffffss"); } }
721
0.680999
0.550624
31
21.258064
21.127825
56
false
false
0
0
0
0
0
0
1.935484
false
false
14
81507f54972a8b646ab7472be8e47cf61953801a
26,809,185,867,189
6ec9ed9505421ec472b1326474397fc491fd6fa0
/src/main/java/pl/coderslab/repository/GroupsRepository.java
2563e343817dc90b3598afd37dde086a161a082c
[]
no_license
Szumika/Project_Company
https://github.com/Szumika/Project_Company
fd3b114eb952110085084a425962cdc7d9cce027
6d5783bb14a4d78d3fafb91cfb939ddcca3241cd
refs/heads/master
2022-12-28T11:48:23.030000
2020-01-18T17:47:34
2020-01-18T17:47:34
144,566,199
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.coderslab.repository; import org.springframework.data.jpa.repository.JpaRepository; import pl.coderslab.entity.groups; public interface GroupsRepository extends JpaRepository<groups, Long> { }
UTF-8
Java
208
java
GroupsRepository.java
Java
[]
null
[]
package pl.coderslab.repository; import org.springframework.data.jpa.repository.JpaRepository; import pl.coderslab.entity.groups; public interface GroupsRepository extends JpaRepository<groups, Long> { }
208
0.826923
0.826923
10
19.9
26.425177
71
false
false
0
0
0
0
0
0
0.4
false
false
14
6ec2bbfc83e15b2b09cf08cc6c99f29033406643
24,988,119,737,062
b255f4ea56fc650f6c82c036ed3f8643758a122e
/WomenShopping/src/main/java/pages/OrderDetailsPage.java
637abab9ea386e486a1f177e6a795e189037d4f0
[]
no_license
gangamuthu/Eshopping
https://github.com/gangamuthu/Eshopping
e42f3726245ecc8a911067e23e53453b07eaf1f6
8dce91349952fe8f3c1ee50800528bf8824e20a9
refs/heads/master
2023-02-28T22:33:45.300000
2021-02-08T19:35:05
2021-02-08T19:35:05
337,178,232
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import generic.WebActionUtil; public class OrderDetailsPage extends Basepage { String xpath="//tbody//td//a[contains(@href,'pid')]/../..//i[@class='icon-trash']"; @FindBy(xpath="//td[@class='cart_product']/a@)") private List<WebElement>productsList; public OrderDetailsPage(WebDriver driver, WebActionUtil webActionUtil) { super(driver, webActionUtil); // TODO Auto-generated constructor stub } @FindBy(xpath="//tbody//td[@class='cart_product']/a") private List<WebElement>ProductsList; public boolean isProductDisplayed(String productId) { for(WebElement product:ProductsList) { if(product.getAttribute("href").contains(productId)) { return true; } } return false; } public void deleteProductFromODP(String productId) { xpath=xpath.replace("pid", productId); WebElement productTrashIcon=driver.findElement(By.xpath(xpath)); webActionUtil.clickOnElement(productTrashIcon); } }
UTF-8
Java
1,205
java
OrderDetailsPage.java
Java
[]
null
[]
package pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import generic.WebActionUtil; public class OrderDetailsPage extends Basepage { String xpath="//tbody//td//a[contains(@href,'pid')]/../..//i[@class='icon-trash']"; @FindBy(xpath="//td[@class='cart_product']/a@)") private List<WebElement>productsList; public OrderDetailsPage(WebDriver driver, WebActionUtil webActionUtil) { super(driver, webActionUtil); // TODO Auto-generated constructor stub } @FindBy(xpath="//tbody//td[@class='cart_product']/a") private List<WebElement>ProductsList; public boolean isProductDisplayed(String productId) { for(WebElement product:ProductsList) { if(product.getAttribute("href").contains(productId)) { return true; } } return false; } public void deleteProductFromODP(String productId) { xpath=xpath.replace("pid", productId); WebElement productTrashIcon=driver.findElement(By.xpath(xpath)); webActionUtil.clickOnElement(productTrashIcon); } }
1,205
0.693776
0.693776
52
21.192308
23.285055
84
false
false
0
0
0
0
0
0
1.557692
false
false
14
28c6854175b66360748be3603468880134663678
15,040,975,528,884
46c8c343bd3ec63ff2d795327cef987c2e2633e9
/app/src/main/java/com/codepath/apps/mytinytwitter/activities/TimelineActivity.java
9ab17e0d4c3bc8c10ce95b54d74c7f644bd34b3c
[ "Apache-2.0" ]
permissive
erioness1125/MyTinyTwitter
https://github.com/erioness1125/MyTinyTwitter
f92a5e0f2c8922321ad157aefae7186180e43391
6743b7d0b0b530405fbbccc9e1084d97b1cd4544
refs/heads/master
2021-01-09T21:46:14.155000
2016-02-22T05:56:47
2016-02-22T05:56:47
52,184,428
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codepath.apps.mytinytwitter.activities; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.codepath.apps.mytinytwitter.R; import com.codepath.apps.mytinytwitter.TwitterApplication; import com.codepath.apps.mytinytwitter.TwitterClient; import com.codepath.apps.mytinytwitter.adapters.TimelineAdapter; import com.codepath.apps.mytinytwitter.fragments.ComposeDialogFragment; import com.codepath.apps.mytinytwitter.listeners.EndlessRecyclerViewScrollListener; import com.codepath.apps.mytinytwitter.models.Tweet; import com.codepath.apps.mytinytwitter.models.User; import com.codepath.apps.mytinytwitter.utils.DividerItemDecoration; import com.codepath.apps.mytinytwitter.utils.MyGson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.JsonHttpResponseHandler; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONObject; import org.parceler.Parcels; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class TimelineActivity extends AppCompatActivity implements ComposeDialogFragment.ComposeDialogListener { @Bind(R.id.rvTweets) RecyclerView rvTweets; @Bind(R.id.swipeContainer) SwipeRefreshLayout swipeContainer; private List<Tweet> tweetList; private TimelineAdapter adapter; private TwitterClient twitterClient; private int tweetsCount = 20; private String nextMaxId; private final User[] me = new User[1]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showComposeDialog(); } }); ButterKnife.bind(this); twitterClient = TwitterApplication.getRestClient(); // singleton client // get my user info getMyUserInfo(); /********************** SwipeRefreshLayout **********************/ // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. fetchTimelineAsync(); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); /********************** end of SwipeRefreshLayout **********************/ /********************** RecyclerView **********************/ tweetList = new ArrayList<>(); adapter = new TimelineAdapter(tweetList); // Attach the adapter to the RecyclerView to populate items rvTweets.setAdapter(adapter); // Set layout manager to position the items final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvTweets.setLayoutManager(linearLayoutManager); // Add the scroll listener rvTweets.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount) { Tweet lastTweet = tweetList.get(tweetList.size() - 1); nextMaxId = lastTweet.getIdStr(); populateTimeline(tweetsCount, nextMaxId); } }); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST); rvTweets.addItemDecoration(itemDecoration); /********************** end of RecyclerView **********************/ adapter.setOnItemClickListener(new TimelineAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { // create an intent to display the article Intent i = new Intent(getApplicationContext(), TweetActivity.class); // get the article to display Tweet tweet = tweetList.get(position); // pass objects to the target activity i.putExtra("tweet", Parcels.wrap(tweet)); i.putExtra("me", Parcels.wrap(me[0])); // launch the activity startActivity(i); } }); // first request // from dev.twitter.com: // To use max_id correctly, an application’s first request to a timeline endpoint should only specify a count. populateTimeline(tweetsCount, null); } private void fetchTimelineAsync() { new android.os.Handler().postDelayed(new Runnable() { @Override public void run() { populateTimeline(tweetsCount, null); swipeContainer.setRefreshing(false); } }, 1000); } // 1. send an API request to get the timeline json // 2. fill the RecyclerView by creating the tweet objects from the json private void populateTimeline(int count, String maxId) { if (maxId == null || maxId.trim().isEmpty()) { adapter.clear(); } twitterClient.getHomeTimeline(count, maxId, new JsonHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { // super.onFailure(statusCode, headers, throwable, errorResponse); Toast.makeText(getApplicationContext(), "Cannot retrieve more tweets... Try again", Toast.LENGTH_LONG).show(); } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { String responseString = response.toString(); Type collectionType = new TypeToken<List<Tweet>>() { }.getType(); Gson gson = MyGson.getMyGson(); List<Tweet> loadedTweetList = gson.fromJson(responseString, collectionType); tweetList.addAll(loadedTweetList); adapter.setTweetList(tweetList); adapter.notifyDataSetChanged(); } }); } private void showComposeDialog() { FragmentManager fm = getSupportFragmentManager(); ComposeDialogFragment editNameDialog = ComposeDialogFragment.newInstance(me[0].getProfileImageUrl()); editNameDialog.show(fm, "fragment_compose"); } private void getMyUserInfo() { twitterClient.getUserAccount(new JsonHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { // super.onFailure(statusCode, headers, throwable, errorResponse); Toast.makeText(getApplicationContext(), "Failed to load my info", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { String responseString = response.toString(); Gson gson = MyGson.getMyGson(); me[0] = gson.fromJson(responseString, User.class); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_timeline, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // perform query here // workaround to avoid issues with some emulators and keyboard devices firing twice if a keyboard enter is used // see https://code.google.com/p/android/issues/detail?id=24599 searchView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; } @Override public void onFinishComposeDialog(Tweet tweet) { tweetList.add(0, tweet); adapter.setTweetList(tweetList); adapter.notifyDataSetChanged(); rvTweets.getLayoutManager().scrollToPosition(0); } }
UTF-8
Java
9,739
java
TimelineActivity.java
Java
[]
null
[]
package com.codepath.apps.mytinytwitter.activities; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.codepath.apps.mytinytwitter.R; import com.codepath.apps.mytinytwitter.TwitterApplication; import com.codepath.apps.mytinytwitter.TwitterClient; import com.codepath.apps.mytinytwitter.adapters.TimelineAdapter; import com.codepath.apps.mytinytwitter.fragments.ComposeDialogFragment; import com.codepath.apps.mytinytwitter.listeners.EndlessRecyclerViewScrollListener; import com.codepath.apps.mytinytwitter.models.Tweet; import com.codepath.apps.mytinytwitter.models.User; import com.codepath.apps.mytinytwitter.utils.DividerItemDecoration; import com.codepath.apps.mytinytwitter.utils.MyGson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.JsonHttpResponseHandler; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONObject; import org.parceler.Parcels; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class TimelineActivity extends AppCompatActivity implements ComposeDialogFragment.ComposeDialogListener { @Bind(R.id.rvTweets) RecyclerView rvTweets; @Bind(R.id.swipeContainer) SwipeRefreshLayout swipeContainer; private List<Tweet> tweetList; private TimelineAdapter adapter; private TwitterClient twitterClient; private int tweetsCount = 20; private String nextMaxId; private final User[] me = new User[1]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showComposeDialog(); } }); ButterKnife.bind(this); twitterClient = TwitterApplication.getRestClient(); // singleton client // get my user info getMyUserInfo(); /********************** SwipeRefreshLayout **********************/ // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. fetchTimelineAsync(); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); /********************** end of SwipeRefreshLayout **********************/ /********************** RecyclerView **********************/ tweetList = new ArrayList<>(); adapter = new TimelineAdapter(tweetList); // Attach the adapter to the RecyclerView to populate items rvTweets.setAdapter(adapter); // Set layout manager to position the items final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvTweets.setLayoutManager(linearLayoutManager); // Add the scroll listener rvTweets.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount) { Tweet lastTweet = tweetList.get(tweetList.size() - 1); nextMaxId = lastTweet.getIdStr(); populateTimeline(tweetsCount, nextMaxId); } }); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST); rvTweets.addItemDecoration(itemDecoration); /********************** end of RecyclerView **********************/ adapter.setOnItemClickListener(new TimelineAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { // create an intent to display the article Intent i = new Intent(getApplicationContext(), TweetActivity.class); // get the article to display Tweet tweet = tweetList.get(position); // pass objects to the target activity i.putExtra("tweet", Parcels.wrap(tweet)); i.putExtra("me", Parcels.wrap(me[0])); // launch the activity startActivity(i); } }); // first request // from dev.twitter.com: // To use max_id correctly, an application’s first request to a timeline endpoint should only specify a count. populateTimeline(tweetsCount, null); } private void fetchTimelineAsync() { new android.os.Handler().postDelayed(new Runnable() { @Override public void run() { populateTimeline(tweetsCount, null); swipeContainer.setRefreshing(false); } }, 1000); } // 1. send an API request to get the timeline json // 2. fill the RecyclerView by creating the tweet objects from the json private void populateTimeline(int count, String maxId) { if (maxId == null || maxId.trim().isEmpty()) { adapter.clear(); } twitterClient.getHomeTimeline(count, maxId, new JsonHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { // super.onFailure(statusCode, headers, throwable, errorResponse); Toast.makeText(getApplicationContext(), "Cannot retrieve more tweets... Try again", Toast.LENGTH_LONG).show(); } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { String responseString = response.toString(); Type collectionType = new TypeToken<List<Tweet>>() { }.getType(); Gson gson = MyGson.getMyGson(); List<Tweet> loadedTweetList = gson.fromJson(responseString, collectionType); tweetList.addAll(loadedTweetList); adapter.setTweetList(tweetList); adapter.notifyDataSetChanged(); } }); } private void showComposeDialog() { FragmentManager fm = getSupportFragmentManager(); ComposeDialogFragment editNameDialog = ComposeDialogFragment.newInstance(me[0].getProfileImageUrl()); editNameDialog.show(fm, "fragment_compose"); } private void getMyUserInfo() { twitterClient.getUserAccount(new JsonHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { // super.onFailure(statusCode, headers, throwable, errorResponse); Toast.makeText(getApplicationContext(), "Failed to load my info", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { String responseString = response.toString(); Gson gson = MyGson.getMyGson(); me[0] = gson.fromJson(responseString, User.class); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_timeline, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // perform query here // workaround to avoid issues with some emulators and keyboard devices firing twice if a keyboard enter is used // see https://code.google.com/p/android/issues/detail?id=24599 searchView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; } @Override public void onFinishComposeDialog(Tweet tweet) { tweetList.add(0, tweet); adapter.setTweetList(tweetList); adapter.notifyDataSetChanged(); rvTweets.getLayoutManager().scrollToPosition(0); } }
9,739
0.649584
0.646708
242
39.23967
29.345201
127
false
false
0
0
0
0
0
0
0.652893
false
false
14
d00a43caa03c97ff33aa930643f4fda4fe3eb0c0
23,055,384,487,868
5b50726f067c3e782ad585bf34c5fc62e80d6496
/CodeForces/src/CF279B_Books_alt2.java
b378b38f2f0e855f6560db0c04f95e1b8d99e983
[]
no_license
Zedronar/algorithms-java
https://github.com/Zedronar/algorithms-java
f11c4843906352f9c44b0fb203c4efa5f4771a45
0d15c5e059a9b040da2d7dde0e22bacc1e068c8e
refs/heads/master
2021-07-11T17:19:20.791000
2019-01-21T22:31:02
2019-01-21T22:31:02
104,587,515
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.util.StringTokenizer; public class CF279B_Books_alt2 { private void solve() { int n = readInt(), t = readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = readInt(); int sum = 0, max = 0; for (int i = 0, j = 0; i < n; i++) { sum += a[i]; while (j < n && sum > t) sum -= a[j++]; max = Math.max(max, i - j + 1); } out.println(max); } public static void main(String[] args) { new CF279B_Books_alt2().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); private void init() throws IOException { String filename = ""; if (filename.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(new FileWriter(filename + ".out")); } } private String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } private double readDouble() { return Double.parseDouble(readString()); } }
UTF-8
Java
1,845
java
CF279B_Books_alt2.java
Java
[]
null
[]
import java.io.*; import java.util.StringTokenizer; public class CF279B_Books_alt2 { private void solve() { int n = readInt(), t = readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = readInt(); int sum = 0, max = 0; for (int i = 0, j = 0; i < n; i++) { sum += a[i]; while (j < n && sum > t) sum -= a[j++]; max = Math.max(max, i - j + 1); } out.println(max); } public static void main(String[] args) { new CF279B_Books_alt2().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); private void init() throws IOException { String filename = ""; if (filename.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(filename + ".in")); out = new PrintWriter(new FileWriter(filename + ".out")); } } private String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } private double readDouble() { return Double.parseDouble(readString()); } }
1,845
0.485637
0.477507
75
23.613333
18.269753
70
false
false
0
0
0
0
0
0
0.506667
false
false
14
f44e8b507d8e6208364328c02b6b85f1898e8c85
5,403,068,887,563
e359b782c28b089b6035c053626d159f32f0c4ee
/src/main/java/com/roy360erick/app/repositories/IProducto.java
e2097791b3f93c32a586186a5fa1fa5fafc3ebd6
[]
no_license
Roy360erick/ProyectoAplicacionesWeb
https://github.com/Roy360erick/ProyectoAplicacionesWeb
54d06fea44334e137622a30585e5ad06ed0f9b40
b761aa7ad4ee6329d2f42409f188c9897d0b678c
refs/heads/master
2020-04-09T03:46:53.411000
2018-12-03T14:13:11
2018-12-03T14:13:11
159,996,312
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.roy360erick.app.repositories; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.roy360erick.app.models.Producto; import com.roy360erick.app.models.Venta; @Repository public interface IProducto extends JpaRepository<Producto, Serializable>{ public abstract Producto findById(Long id); public abstract Producto findByNombre(String producto); }
UTF-8
Java
479
java
IProducto.java
Java
[]
null
[]
package com.roy360erick.app.repositories; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.roy360erick.app.models.Producto; import com.roy360erick.app.models.Venta; @Repository public interface IProducto extends JpaRepository<Producto, Serializable>{ public abstract Producto findById(Long id); public abstract Producto findByNombre(String producto); }
479
0.807933
0.789144
16
27.9375
25.088514
73
false
false
0
0
0
0
0
0
0.6875
false
false
14
3ed887eba345256bdb0c144aaff050b68f8c13c2
21,105,469,331,452
86ce3726de5b7fd1610c6289848e88f37a8e3ebf
/app/src/main/java/com/fourstars/gosilent/gosilent/activities/StartActivity.java
407419276350946106385d9f6dc99ebf8f52ace4
[]
no_license
jayantrane/GoSilent
https://github.com/jayantrane/GoSilent
199c6e1f80ac6b856b867304d7e58860b1d8f5f4
d2469f1c2bfa25fdfe63069e8133431992716554
refs/heads/master
2021-05-23T06:10:24.382000
2017-07-22T20:13:06
2017-07-22T20:13:06
94,851,083
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fourstars.gosilent.gosilent.activities; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.fourstars.gosilent.gosilent.services.LocationService; import com.fourstars.gosilent.gosilent.databaseanddao.MyApplication; import com.fourstars.gosilent.gosilent.permissions.PermissionUtils; import com.fourstars.gosilent.gosilent.R; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import java.io.File; /** * Created by Jayant on 18-07-2017. */ public class StartActivity extends AppCompatActivity { LocationRequest mLocationRequest; final static int REQUEST_LOCATION = 1; private static final int LOCATION_PERMISSION_REQUEST_CODE = 1; protected static final int REQUEST_CHECK_SETTINGS = 0x1; volatile boolean setLocation=false; private FusedLocationProviderClient mFusedLocationClient; private boolean mPermissionDenied = false; private boolean mLocationEnabled = false; private boolean mRequestingLocationUpdates=false; private LatLng myhome; private LocationCallback mLocationCallback; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); final Thread welcomeThread = new Thread() { @Override public void run() { try { super.run(); while(setLocation==false) { Log.e("Start","Location Start Accessing"); sleep(5000); Log.e("Start","Location accessing"); // Toast.makeText(StartActivity.this,"Location Accesed",Toast.LENGTH_SHORT).show(); }//Delay of 10 seconds } catch (Exception e) { Log.e("Start","Location catch accessing"); } finally { Log.e("Start","Location finally accessing"); Intent i = new Intent(StartActivity.this, MainActivity.class); startActivity(i); finish(); } } }; mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Log.e("Start"," new thread Location accessing"); Location location =locationResult.getLastLocation(); myhome = new LatLng(location.getLatitude(), location.getLongitude()); setLocation=true; Log.e("msg","Location has been set"); ((MyApplication) StartActivity.this.getApplication()).setMyLocation(myhome); welcomeThread.start(); } }; enableMyLocation(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(3000); mLocationRequest.setFastestInterval(2000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } public void tasker(){ createLocationRequest(); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); Log.e("msg","GPS and Location permissions will be requested."); SettingsClient client = LocationServices.getSettingsClient(this); Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build()); task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { mLocationEnabled=true; Log.e("msg","GPS task success"); // enableMyLocation(); // All location settings are satisfied. The client can initialize // location requests here. // ... } }); task.addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case CommonStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied, but this can be fixed // by showing the user a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). ResolvableApiException resolvable = (ResolvableApiException) e; resolvable.startResolutionForResult(StartActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sendEx) { Log.e("msg","Task failed in catch task"); // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way // to fix the settings so we won't show the dialog. break; } } }); } private void enableMyLocation() { Log.e("msg","EnableMyLocation requested."); if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Permission to access the location is missing. PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, android.Manifest.permission.ACCESS_FINE_LOCATION, true); } else { // Access to the location has been granted to the app. tasker(); mRequestingLocationUpdates=true; startLocationUpdates(); Log.e("msg","Permission is granted."); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); if(!mPermissionDenied && mLocationEnabled) { mFusedLocationClient.getLastLocation() .addOnSuccessListener(StartActivity.this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { // mtextView.setText("Lat : " + location.getLatitude() + " Lng : " + location.getLongitude()); Log.e("msg","FusedLocationClient location is not null."); } else{ Log.e("msg","FusedLocationClient location is null."); } } }); } // mMap.setMyLocationEnabled(true); } } private void startLocationUpdates() { mFusedLocationClient.requestLocationUpdates(mLocationRequest,mLocationCallback, null); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { return; } if (PermissionUtils.isPermissionGranted(permissions, grantResults, android.Manifest.permission.ACCESS_FINE_LOCATION)) { // Enable the my location layer if the permission has been granted. mPermissionDenied = false; enableMyLocation(); } else { // Display the missing permission error dialog when the fragments resume. Log.e("msg","Location Permission is Denied."); mPermissionDenied = true; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("onActivityResult()", Integer.toString(resultCode)); //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case REQUEST_LOCATION: switch (resultCode) { case Activity.RESULT_OK: { // All required changes were successfully made Log.e("msg","GPS enabled."); mLocationEnabled=true; // enableMyLocation(); // Toast.makeText(StartActivity.this, "Location enabled by user!", Toast.LENGTH_SHORT).show(); // Toast.makeText(StartActivity.this, "Please wait for process to complete", Toast.LENGTH_LONG).show(); break; } case Activity.RESULT_CANCELED: { // The user was asked to change settings, but chose not to Log.e("msg","GPS not enabled."); // Toast.makeText(StartActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show(); break; } default: { break; } } break; } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } @Override protected void onResume() { super.onResume(); if (mRequestingLocationUpdates) { startLocationUpdates(); } } private void stopLocationUpdates() { mFusedLocationClient.removeLocationUpdates(mLocationCallback); } }
UTF-8
Java
11,470
java
StartActivity.java
Java
[ { "context": "sks.Task;\n\nimport java.io.File;\n\n/**\n * Created by Jayant on 18-07-2017.\n */\n\npublic class StartActivity ex", "end": 1726, "score": 0.8261846899986267, "start": 1720, "tag": "NAME", "value": "Jayant" } ]
null
[]
package com.fourstars.gosilent.gosilent.activities; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.fourstars.gosilent.gosilent.services.LocationService; import com.fourstars.gosilent.gosilent.databaseanddao.MyApplication; import com.fourstars.gosilent.gosilent.permissions.PermissionUtils; import com.fourstars.gosilent.gosilent.R; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import java.io.File; /** * Created by Jayant on 18-07-2017. */ public class StartActivity extends AppCompatActivity { LocationRequest mLocationRequest; final static int REQUEST_LOCATION = 1; private static final int LOCATION_PERMISSION_REQUEST_CODE = 1; protected static final int REQUEST_CHECK_SETTINGS = 0x1; volatile boolean setLocation=false; private FusedLocationProviderClient mFusedLocationClient; private boolean mPermissionDenied = false; private boolean mLocationEnabled = false; private boolean mRequestingLocationUpdates=false; private LatLng myhome; private LocationCallback mLocationCallback; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); final Thread welcomeThread = new Thread() { @Override public void run() { try { super.run(); while(setLocation==false) { Log.e("Start","Location Start Accessing"); sleep(5000); Log.e("Start","Location accessing"); // Toast.makeText(StartActivity.this,"Location Accesed",Toast.LENGTH_SHORT).show(); }//Delay of 10 seconds } catch (Exception e) { Log.e("Start","Location catch accessing"); } finally { Log.e("Start","Location finally accessing"); Intent i = new Intent(StartActivity.this, MainActivity.class); startActivity(i); finish(); } } }; mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Log.e("Start"," new thread Location accessing"); Location location =locationResult.getLastLocation(); myhome = new LatLng(location.getLatitude(), location.getLongitude()); setLocation=true; Log.e("msg","Location has been set"); ((MyApplication) StartActivity.this.getApplication()).setMyLocation(myhome); welcomeThread.start(); } }; enableMyLocation(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(3000); mLocationRequest.setFastestInterval(2000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } public void tasker(){ createLocationRequest(); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); Log.e("msg","GPS and Location permissions will be requested."); SettingsClient client = LocationServices.getSettingsClient(this); Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build()); task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { mLocationEnabled=true; Log.e("msg","GPS task success"); // enableMyLocation(); // All location settings are satisfied. The client can initialize // location requests here. // ... } }); task.addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case CommonStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied, but this can be fixed // by showing the user a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). ResolvableApiException resolvable = (ResolvableApiException) e; resolvable.startResolutionForResult(StartActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sendEx) { Log.e("msg","Task failed in catch task"); // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way // to fix the settings so we won't show the dialog. break; } } }); } private void enableMyLocation() { Log.e("msg","EnableMyLocation requested."); if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Permission to access the location is missing. PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, android.Manifest.permission.ACCESS_FINE_LOCATION, true); } else { // Access to the location has been granted to the app. tasker(); mRequestingLocationUpdates=true; startLocationUpdates(); Log.e("msg","Permission is granted."); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); if(!mPermissionDenied && mLocationEnabled) { mFusedLocationClient.getLastLocation() .addOnSuccessListener(StartActivity.this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { // mtextView.setText("Lat : " + location.getLatitude() + " Lng : " + location.getLongitude()); Log.e("msg","FusedLocationClient location is not null."); } else{ Log.e("msg","FusedLocationClient location is null."); } } }); } // mMap.setMyLocationEnabled(true); } } private void startLocationUpdates() { mFusedLocationClient.requestLocationUpdates(mLocationRequest,mLocationCallback, null); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { return; } if (PermissionUtils.isPermissionGranted(permissions, grantResults, android.Manifest.permission.ACCESS_FINE_LOCATION)) { // Enable the my location layer if the permission has been granted. mPermissionDenied = false; enableMyLocation(); } else { // Display the missing permission error dialog when the fragments resume. Log.e("msg","Location Permission is Denied."); mPermissionDenied = true; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("onActivityResult()", Integer.toString(resultCode)); //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case REQUEST_LOCATION: switch (resultCode) { case Activity.RESULT_OK: { // All required changes were successfully made Log.e("msg","GPS enabled."); mLocationEnabled=true; // enableMyLocation(); // Toast.makeText(StartActivity.this, "Location enabled by user!", Toast.LENGTH_SHORT).show(); // Toast.makeText(StartActivity.this, "Please wait for process to complete", Toast.LENGTH_LONG).show(); break; } case Activity.RESULT_CANCELED: { // The user was asked to change settings, but chose not to Log.e("msg","GPS not enabled."); // Toast.makeText(StartActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show(); break; } default: { break; } } break; } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } @Override protected void onResume() { super.onResume(); if (mRequestingLocationUpdates) { startLocationUpdates(); } } private void stopLocationUpdates() { mFusedLocationClient.removeLocationUpdates(mLocationCallback); } }
11,470
0.591456
0.589015
282
39.673759
29.754551
132
false
false
0
0
0
0
0
0
0.609929
false
false
14
36a83f577ced69c895096052fd96c3d599523a28
20,633,022,947,864
5308297e063c59a065a025711ae62b0b7b015886
/SDK/src/com/skyworth/mobileui/apk/AsyncImageLoader.java
8a6b934ece4c126ad83b010afd80e8adb871d06b
[]
no_license
bibiRe/AppStore
https://github.com/bibiRe/AppStore
77ddde3261cabe9294ffb74714c00febd0ec7268
06f5e05050ad01753fd9e6a9f6ec251474e3c6f1
refs/heads/master
2020-12-29T01:54:54.175000
2014-02-12T07:30:44
2014-02-12T07:30:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.skyworth.mobileui.apk; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import com.skyworth.webservice.threading.ITask; import com.skyworth.webservice.threading.ThreadPool; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ImageView; /** * Asynchronous Load Image . Can with a mask. * * @author YanLin * */ public class AsyncImageLoader { public interface ILoadFinishedListener { public void onLoadFinished(String url, Drawable d); } class LoadTask implements ITask { ImageView imgView = null; String url = ""; Drawable defaultDrawable = null; Drawable maskDrawable = null; ImageView markImgView = null; ImageView bgImgView = null; private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; } private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView ) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; } private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView, ImageView bgImgView ) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; this.bgImgView = bgImgView; } public void execute(){ // Maybe already in the ache. Drawable loadDrawable = getImgFromCache(url); // not in the cache. if (loadDrawable == null) { loadDrawable = downloadImg(url); if (loadDrawable != null) { synchronized (drawableCache) { drawableCache.put(url, new SoftReference<Drawable>( loadDrawable)); } } } handler.sendMessage(handler.obtainMessage(0, new LoadResult(url, this.imgView, loadDrawable, this.defaultDrawable, this.maskDrawable,this.markImgView))); } } class LoadResult { ImageView imgView = null; Drawable loadDrawable = null; Drawable defaultDrawable = null; Drawable maskDrawable = null; ImageView markImgView = null; ImageView bgImgView = null; String url = ""; LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; } LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; } LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView, ImageView bgImgView) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; this.bgImgView = bgImgView; } float getScaleFactor(Rect pic, int viewWidth, int viewHeight){ if (pic.width() >= pic.height()){ return pic.width() / (float)viewWidth; }else{ return pic.height() / (float)viewHeight; } } void setImage() { Drawable target = this.defaultDrawable; if (this.loadDrawable != null) { target = this.loadDrawable; } // image with mask. if (target != null && this.maskDrawable != null) { Drawable[] array = new Drawable[2]; array[0] = target; array[1] = this.maskDrawable; // margin // Rect bgRect = target.getBounds(); // Rect maskRec = this.maskDrawable.getBounds(); // float scaleFactor = this.getScaleFactor(bgRect, this.imgView.getWidth(), this.imgView.getHeight()); // int margin_h = (bgRect.width() - (int)(maskRec.width() * scaleFactor)) / 2; // int margin_v = (bgRect.height() - (int)(maskRec.height() * scaleFactor)) / 2; LayerDrawable layerDrawable = new LayerDrawable(array); layerDrawable.setLayerInset(0, 0, 0, 0, 0); // l t r b // layerDrawable.setLayerInset(1, margin_h, margin_v, margin_h, // margin_v); layerDrawable.setLayerInset(1, 60, 60, 60,60); if(this.markImgView == null) { this.imgView.setImageDrawable(layerDrawable); } else { if(this.bgImgView != null) { this.bgImgView.setVisibility(View.VISIBLE); } this.imgView.setImageDrawable(target); this.markImgView.setImageDrawable(this.maskDrawable); } } else { // no mask. if (target != null){ this.imgView.setImageDrawable(target); } } } } private static HashMap<String, SoftReference<Drawable>> drawableCache = null; private static AsyncImageLoader globalInstance = null; private ILoadFinishedListener listener = null; private ThreadPool threadPool = null; private Handler handler = null; //image view width and height private int imgWidth = 0; private int imgHeight = 0; private AsyncImageLoader() { // Initialization :handler cache... this.drawableCache = new HashMap<String, SoftReference<Drawable>>(); handler = new Handler() { public void handleMessage(Message msg) { System.out.println("Handler--The ThreadId is: "+Thread.currentThread().getId()); LoadResult r = (LoadResult) msg.obj; r.setImage(); // if the user want to the load finish event. if (listener != null) { listener.onLoadFinished(r.url, r.loadDrawable); } } }; threadPool = new ThreadPool(6); threadPool.startUp(); } public static void setLoadFinishedListener(ILoadFinishedListener listener) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } AsyncImageLoader.globalInstance.listener = listener; } public static void setImageViewRect(int width, int height){ if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } AsyncImageLoader.globalInstance.imgWidth = width; AsyncImageLoader.globalInstance .imgHeight = height; } /** * User interface. No mask * * @param imgView * @param url * @param defaultDrawable */ public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable) { AsyncImageLoader.LoadImage(imgView, url, defaultDrawable, null); } /** * User interface . With mask. * * @param imgView * @param url * @param defaultDrawable * @param maskDrawable */ public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); // } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { System.out.println("Load in cache"); AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable).setImage(); } else { // not in the cache. System.out.println("new task"); AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable); } } public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable,markImgView).setImage(); } else { // not in the cache. AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView); } } public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView, ImageView bgImgView) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable,markImgView,bgImgView).setImage(); } else { // not in the cache. AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView, bgImgView); } } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable)); } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView)); } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView, ImageView bgImgView) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView,bgImgView)); } private Drawable getImgFromCache(String url) { Drawable d = null; SoftReference<Drawable> rd = null; //SoftReference是啥? synchronized (this.drawableCache) { rd = drawableCache.get(url); } if (rd != null) { d = rd.get(); } return d; } private Drawable downloadImg(String url) { URL m; InputStream i = null; Drawable d = null; if (url != null && !url.equals("")) { // check if exist already try { m = new URL(url); i = (InputStream) m.getContent(); // d = Drawable.createFromStream(i, "src"); BitmapFactory.Options options = new BitmapFactory.Options(); // if (SystemInfo.getSystemInfo("MID").startsWith("RTK")) // { // options.inSampleSize = 2; // } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(i, null, options); d = new BitmapDrawable(bmp); } catch (OutOfMemoryError ome) { } } catch (MalformedURLException e1) { d = null; System.out.println(e1.getMessage() + "for url:" + url); e1.printStackTrace(); } catch (IOException e) { d = null; System.out.println(e.getMessage() + "for url:" + url); e.printStackTrace(); } catch (NullPointerException e2) { d = null; System.out.println(e2.getMessage() + "for url:" + url); e2.printStackTrace(); } catch (IllegalStateException e3) { d = null; System.out.println(e3.getMessage() + "for url:" + url); e3.printStackTrace(); } } return d; } public static void clearCacheImage(){ drawableCache.clear(); } }
UTF-8
Java
11,637
java
AsyncImageLoader.java
Java
[ { "context": "onous Load Image . Can with a mask.\n * \n * @author YanLin\n * \n */\npublic class AsyncImageLoader {\n\n\tpublic ", "end": 745, "score": 0.9824764132499695, "start": 739, "tag": "NAME", "value": "YanLin" } ]
null
[]
package com.skyworth.mobileui.apk; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import com.skyworth.webservice.threading.ITask; import com.skyworth.webservice.threading.ThreadPool; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ImageView; /** * Asynchronous Load Image . Can with a mask. * * @author YanLin * */ public class AsyncImageLoader { public interface ILoadFinishedListener { public void onLoadFinished(String url, Drawable d); } class LoadTask implements ITask { ImageView imgView = null; String url = ""; Drawable defaultDrawable = null; Drawable maskDrawable = null; ImageView markImgView = null; ImageView bgImgView = null; private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; } private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView ) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; } private LoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView, ImageView bgImgView ) { this.imgView = imgView; this.url = url; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; this.bgImgView = bgImgView; } public void execute(){ // Maybe already in the ache. Drawable loadDrawable = getImgFromCache(url); // not in the cache. if (loadDrawable == null) { loadDrawable = downloadImg(url); if (loadDrawable != null) { synchronized (drawableCache) { drawableCache.put(url, new SoftReference<Drawable>( loadDrawable)); } } } handler.sendMessage(handler.obtainMessage(0, new LoadResult(url, this.imgView, loadDrawable, this.defaultDrawable, this.maskDrawable,this.markImgView))); } } class LoadResult { ImageView imgView = null; Drawable loadDrawable = null; Drawable defaultDrawable = null; Drawable maskDrawable = null; ImageView markImgView = null; ImageView bgImgView = null; String url = ""; LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; } LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; } LoadResult(String url, ImageView imgView, Drawable loadDrawable, Drawable defaultDrawable, Drawable maskDrawable, ImageView markImgView, ImageView bgImgView) { this.url = url; this.imgView = imgView; this.loadDrawable = loadDrawable; this.defaultDrawable = defaultDrawable; this.maskDrawable = maskDrawable; this.markImgView = markImgView; this.bgImgView = bgImgView; } float getScaleFactor(Rect pic, int viewWidth, int viewHeight){ if (pic.width() >= pic.height()){ return pic.width() / (float)viewWidth; }else{ return pic.height() / (float)viewHeight; } } void setImage() { Drawable target = this.defaultDrawable; if (this.loadDrawable != null) { target = this.loadDrawable; } // image with mask. if (target != null && this.maskDrawable != null) { Drawable[] array = new Drawable[2]; array[0] = target; array[1] = this.maskDrawable; // margin // Rect bgRect = target.getBounds(); // Rect maskRec = this.maskDrawable.getBounds(); // float scaleFactor = this.getScaleFactor(bgRect, this.imgView.getWidth(), this.imgView.getHeight()); // int margin_h = (bgRect.width() - (int)(maskRec.width() * scaleFactor)) / 2; // int margin_v = (bgRect.height() - (int)(maskRec.height() * scaleFactor)) / 2; LayerDrawable layerDrawable = new LayerDrawable(array); layerDrawable.setLayerInset(0, 0, 0, 0, 0); // l t r b // layerDrawable.setLayerInset(1, margin_h, margin_v, margin_h, // margin_v); layerDrawable.setLayerInset(1, 60, 60, 60,60); if(this.markImgView == null) { this.imgView.setImageDrawable(layerDrawable); } else { if(this.bgImgView != null) { this.bgImgView.setVisibility(View.VISIBLE); } this.imgView.setImageDrawable(target); this.markImgView.setImageDrawable(this.maskDrawable); } } else { // no mask. if (target != null){ this.imgView.setImageDrawable(target); } } } } private static HashMap<String, SoftReference<Drawable>> drawableCache = null; private static AsyncImageLoader globalInstance = null; private ILoadFinishedListener listener = null; private ThreadPool threadPool = null; private Handler handler = null; //image view width and height private int imgWidth = 0; private int imgHeight = 0; private AsyncImageLoader() { // Initialization :handler cache... this.drawableCache = new HashMap<String, SoftReference<Drawable>>(); handler = new Handler() { public void handleMessage(Message msg) { System.out.println("Handler--The ThreadId is: "+Thread.currentThread().getId()); LoadResult r = (LoadResult) msg.obj; r.setImage(); // if the user want to the load finish event. if (listener != null) { listener.onLoadFinished(r.url, r.loadDrawable); } } }; threadPool = new ThreadPool(6); threadPool.startUp(); } public static void setLoadFinishedListener(ILoadFinishedListener listener) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } AsyncImageLoader.globalInstance.listener = listener; } public static void setImageViewRect(int width, int height){ if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } AsyncImageLoader.globalInstance.imgWidth = width; AsyncImageLoader.globalInstance .imgHeight = height; } /** * User interface. No mask * * @param imgView * @param url * @param defaultDrawable */ public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable) { AsyncImageLoader.LoadImage(imgView, url, defaultDrawable, null); } /** * User interface . With mask. * * @param imgView * @param url * @param defaultDrawable * @param maskDrawable */ public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); // } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { System.out.println("Load in cache"); AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable).setImage(); } else { // not in the cache. System.out.println("new task"); AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable); } } public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable,markImgView).setImage(); } else { // not in the cache. AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView); } } public static void LoadImage(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView, ImageView bgImgView) { if (AsyncImageLoader.globalInstance == null) { AsyncImageLoader.globalInstance = new AsyncImageLoader(); } // in cache. Drawable loadDrawable = AsyncImageLoader.globalInstance .getImgFromCache(url); if (loadDrawable != null) { AsyncImageLoader.globalInstance.new LoadResult(url, imgView, loadDrawable, defaultDrawable, maskDrawable,markImgView,bgImgView).setImage(); } else { // not in the cache. AsyncImageLoader.globalInstance.addLoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView, bgImgView); } } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable)); } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView)); } private void addLoadTask(ImageView imgView, String url, Drawable defaultDrawable, Drawable maskDrawable,ImageView markImgView, ImageView bgImgView) { threadPool.addTasks(new LoadTask(imgView, url, defaultDrawable, maskDrawable, markImgView,bgImgView)); } private Drawable getImgFromCache(String url) { Drawable d = null; SoftReference<Drawable> rd = null; //SoftReference是啥? synchronized (this.drawableCache) { rd = drawableCache.get(url); } if (rd != null) { d = rd.get(); } return d; } private Drawable downloadImg(String url) { URL m; InputStream i = null; Drawable d = null; if (url != null && !url.equals("")) { // check if exist already try { m = new URL(url); i = (InputStream) m.getContent(); // d = Drawable.createFromStream(i, "src"); BitmapFactory.Options options = new BitmapFactory.Options(); // if (SystemInfo.getSystemInfo("MID").startsWith("RTK")) // { // options.inSampleSize = 2; // } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(i, null, options); d = new BitmapDrawable(bmp); } catch (OutOfMemoryError ome) { } } catch (MalformedURLException e1) { d = null; System.out.println(e1.getMessage() + "for url:" + url); e1.printStackTrace(); } catch (IOException e) { d = null; System.out.println(e.getMessage() + "for url:" + url); e.printStackTrace(); } catch (NullPointerException e2) { d = null; System.out.println(e2.getMessage() + "for url:" + url); e2.printStackTrace(); } catch (IllegalStateException e3) { d = null; System.out.println(e3.getMessage() + "for url:" + url); e3.printStackTrace(); } } return d; } public static void clearCacheImage(){ drawableCache.clear(); } }
11,637
0.706044
0.703121
399
28.150375
23.955627
105
false
false
0
0
0
0
0
0
2.992481
false
false
14
bf984ed7538f41608eac0507a6988c4d54a7c0e1
25,847,113,220,798
ac7662aebad9356e107f8ef7a7ca3e72835d5b3d
/src/pp/p2/c13/search/object/IntSetList.java
2e3daba7299544238c187ac91c8638a45c4bb03c
[]
no_license
ch3n0l1/programming_pearls
https://github.com/ch3n0l1/programming_pearls
1ef36803f0c668d5c8aeef40c8eab32a1a658f5a
a78075f21f77d727c8ff0ec5618bd47a3ccb9750
refs/heads/master
2017-10-02T00:28:25.517000
2017-04-01T12:36:02
2017-04-01T12:36:02
84,441,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pp.p2.c13.search.object; public class IntSetList extends IntSetImp{ private class Node{ public int val; public Node next; public Node(int v, Node node) { val = v; next = node; } } private int n; private Node head; private Node sentinel; private Node rinsert(Node p, int t) { if(p.val < t) { p.next = rinsert(p.next, t); } else if(p.val > t) { p = new Node(t, p); n++; } return p; } public IntSetList(int maxelms, int maxval) { super(maxelms, maxval); sentinel = head = new Node(maxval, null); n = 0; } @Override protected int size() { return n; } @Override protected void insert(int t) { head = rinsert(head, t); } @Override protected void report(int[] v) { int j = 0; for(Node p = head; p != sentinel; p = p.next) { v[j] = p.val; j++; } } }
UTF-8
Java
1,060
java
IntSetList.java
Java
[]
null
[]
package pp.p2.c13.search.object; public class IntSetList extends IntSetImp{ private class Node{ public int val; public Node next; public Node(int v, Node node) { val = v; next = node; } } private int n; private Node head; private Node sentinel; private Node rinsert(Node p, int t) { if(p.val < t) { p.next = rinsert(p.next, t); } else if(p.val > t) { p = new Node(t, p); n++; } return p; } public IntSetList(int maxelms, int maxval) { super(maxelms, maxval); sentinel = head = new Node(maxval, null); n = 0; } @Override protected int size() { return n; } @Override protected void insert(int t) { head = rinsert(head, t); } @Override protected void report(int[] v) { int j = 0; for(Node p = head; p != sentinel; p = p.next) { v[j] = p.val; j++; } } }
1,060
0.468868
0.464151
54
18.629629
14.545327
55
false
false
0
0
0
0
0
0
0.555556
false
false
14
dc672bf4a43e9ab5e153449e4635a138b40bb3c5
919,123,052,647
78b4c7874e02de46146069255f54926163adbabf
/KeyPress.java
14c507df0bae129c269b8e15ac0bd7d405ea2142
[]
no_license
R4y1237/FlappyBird
https://github.com/R4y1237/FlappyBird
0b3e1b03bada7ad9fdc5e6328305e642d25812ba
fa66e97afdfaf9e6b091207fdcdba50994e007f5
refs/heads/main
2023-03-31T17:22:41.898000
2021-04-01T14:13:32
2021-04-01T14:13:32
353,722,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Ray Wang and Jimmy Liu 11/11/2020 Teacher: Mr.Gugliemli This program will create the game Flappy Bird */ import java.awt.*; import hsa.Console; import javax.swing.*; // The "KeyPress" class. public class KeyPress extends Thread { Console c; boolean running, pressed, quit; ImageDisplayer bird; char key; int up; // The number of pixels the bird needs to move up int birdY; public KeyPress (Console con) { c = con; birdY = 250; } //This method will wait for a keypress while the program is running //No parameters //No return methods public void waitForKey () { key = c.getChar (); if (key == 'q') { quit = true; } else if (key == ' ' && up < 8) { up = 10; pressed = true; } try { sleep (100); } catch (Exception e) { } } //This method will just run the code //No parameters //No return methods public void control () { while (running) // controlled by main thread { waitForKey (); } } public void pauseGame () { JFrame f = new JFrame (); JOptionPane.showMessageDialog (f, "The game is currently paused. Press \"ok\" to continue."); } public void run () { running = true; key = 0; quit = false; control (); } } // KeyPress class
UTF-8
Java
1,386
java
KeyPress.java
Java
[ { "context": "/*\r\nRay Wang and Jimmy Liu\r\n11/11/2020\r\nTeacher: Mr.Gugliemli\r", "end": 12, "score": 0.9998096227645874, "start": 4, "tag": "NAME", "value": "Ray Wang" }, { "context": "/*\r\nRay Wang and Jimmy Liu\r\n11/11/2020\r\nTeacher: Mr.Gugliemli\r\nThis program ", "end": 26, "score": 0.9998235106468201, "start": 17, "tag": "NAME", "value": "Jimmy Liu" } ]
null
[]
/* <NAME> and <NAME> 11/11/2020 Teacher: Mr.Gugliemli This program will create the game Flappy Bird */ import java.awt.*; import hsa.Console; import javax.swing.*; // The "KeyPress" class. public class KeyPress extends Thread { Console c; boolean running, pressed, quit; ImageDisplayer bird; char key; int up; // The number of pixels the bird needs to move up int birdY; public KeyPress (Console con) { c = con; birdY = 250; } //This method will wait for a keypress while the program is running //No parameters //No return methods public void waitForKey () { key = c.getChar (); if (key == 'q') { quit = true; } else if (key == ' ' && up < 8) { up = 10; pressed = true; } try { sleep (100); } catch (Exception e) { } } //This method will just run the code //No parameters //No return methods public void control () { while (running) // controlled by main thread { waitForKey (); } } public void pauseGame () { JFrame f = new JFrame (); JOptionPane.showMessageDialog (f, "The game is currently paused. Press \"ok\" to continue."); } public void run () { running = true; key = 0; quit = false; control (); } } // KeyPress class
1,381
0.559885
0.546898
95
12.589474
16.092165
94
false
false
0
0
0
0
0
0
0.578947
false
false
14
d20efc066815c401b8dde023e07a9733981fc9ca
11,467,562,702,897
4b5c2bfa44959c5e1c4aaea508e65f977e235327
/app/src/main/java/com/zhy/dagger2/ThirdActivity.java
ab66e91119d6fe84bb69db2dd7e4740df2e30e51
[]
no_license
zhy060307/dagger2
https://github.com/zhy060307/dagger2
6e740a549db8589b863868865ba915d6ba41d8cf
8d3e55ba8726dbd37028a40658782bf8a4e3711f
refs/heads/master
2020-04-21T09:29:00.981000
2019-02-10T07:21:06
2019-02-10T07:21:06
169,450,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhy.dagger2; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.zhy.dagger2.bindinstance.DaggerThirdComponent; import com.zhy.dagger2.bindinstance.Login; import com.zhy.dagger2.bindinstance.ThirdComponent; public class ThirdActivity extends AppCompatActivity { private ThirdComponent component; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); component = DaggerThirdComponent.builder() .login(new Login("zhangsan", "lisi")) .build(); component .inject(this); } public void login(View view) { TextView tvMsg = findViewById(R.id.tv_msg); Login login = component.login(); tvMsg.setText(String.format("%s %s login success.", login.getUsername(), login.getPassword())); } }
UTF-8
Java
1,056
java
ThirdActivity.java
Java
[ { "context": "onent.builder()\n .login(new Login(\"zhangsan\", \"lisi\"))\n .build();\n comp", "end": 720, "score": 0.9993774890899658, "start": 712, "tag": "USERNAME", "value": "zhangsan" }, { "context": "r()\n .login(new Login(\"zhangsan\", \"lisi\"))\n .build();\n component\n ", "end": 728, "score": 0.7343050241470337, "start": 724, "tag": "USERNAME", "value": "lisi" } ]
null
[]
package com.zhy.dagger2; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.zhy.dagger2.bindinstance.DaggerThirdComponent; import com.zhy.dagger2.bindinstance.Login; import com.zhy.dagger2.bindinstance.ThirdComponent; public class ThirdActivity extends AppCompatActivity { private ThirdComponent component; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); component = DaggerThirdComponent.builder() .login(new Login("zhangsan", "lisi")) .build(); component .inject(this); } public void login(View view) { TextView tvMsg = findViewById(R.id.tv_msg); Login login = component.login(); tvMsg.setText(String.format("%s %s login success.", login.getUsername(), login.getPassword())); } }
1,056
0.700758
0.696023
35
29.171429
24.4207
103
false
false
0
0
0
0
0
0
0.571429
false
false
14
4d879c107622b597703dced0dc7fdcab0b4ec1d2
28,355,374,104,565
b796403692acd9cd1dcae90ee41c37ef4bc56f44
/CobolPorterParser/src/main/java/tr/com/vbt/java/general/JavaOneDimensionArrayElement.java
53fcbdc247b8b532ea17e457830b555c79c4e92f
[]
no_license
latift/PorterEngine
https://github.com/latift/PorterEngine
7626bae05f41ef4e7828e13f2a55bf77349e1bb3
c78a12f1cb2e72c90b1b22d6f50f71456d0c4345
refs/heads/master
2023-09-02T05:16:24.793000
2021-09-29T12:02:52
2021-09-29T12:02:52
95,788,676
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tr.com.vbt.java.general; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import tr.com.vbt.java.AbstractJavaElement; import tr.com.vbt.java.utils.ConvertUtilities; import tr.com.vbt.java.utils.JavaWriteUtilities; import tr.com.vbt.token.AbstractToken; //*S**01 #SECIM-YURT-ICI-AKARYAKIT(A1/4) --> String[4] SECIM_YURT_ICI_AKARYAKIT=new String[4]; //*S**01 #ROL1(N1/15) --> int[15] ROL1=new int[15]; /** * * (A15) * (N8) --> int * (N10) --> double * (D) -->Date * (P7) --> * (C) --> * * A 253 length Alpha (letters, numbers, certain symbols) N 29 length Numeric I Integer P 29 (length /2) Packed B Binary D 4 Date (internal day number) T 7 Time (internal day number and time) L 1 Logical (TRUE or FALSE) C 1 Control (whether modified) * * * 0414 2 D_SECIM (A1/1:100) * @author 47159500 * */ public class JavaOneDimensionArrayElement extends AbstractJavaElement { final static Logger logger = Logger.getLogger(JavaOneDimensionArrayElement.class); private String type; private String dataType; private int length; private int lengthAfterDot; private String dataName; private String visibility; private int arrayLength; private int levelNumber; private List<AbstractToken> initialValue; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { this.visibility = visibility; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getDataName() { return dataName; } public void setDataName(String dataName) { this.dataName = dataName; } //*S**1 #SECIM (N2) @Override public boolean writeJavaToStream() throws Exception{ super.writeJavaToStream(); try { writeFieldAnnotation(); dataType = (String) this.parameters.get("dataType"); if(this.parameters.get("length")!=null){ length=(int)((long) this.parameters.get("length")); } dataName = (String) this.parameters.get("dataName"); levelNumber = (int)((long) this.parameters.get("levelNumber")); if(this.parameters.get("arrayLength")!=null){ arrayLength=(int) ((long)this.parameters.get("arrayLength")); } if(parameters.get("lengthAfterDot")!=null){ lengthAfterDot=(int)((long) parameters.get("lengthAfterDot")); } if(parameters.get("initialValue")!=null){ initialValue= (List<AbstractToken>) parameters.get("initialValue"); } type=ConvertUtilities.getJavaVariableType(dataType, length, lengthAfterDot); //String[4] SECIM_YURT_ICI_AKARYAKIT=new String[4]; //int[15] ROL1=new int[15]; JavaClassElement.javaCodeBuffer.append("public "+type + "[] "); if (dataName != null) { JavaClassElement.javaCodeBuffer.append(dataName.replace('-', '_')); } else { JavaClassElement.javaCodeBuffer .append("Untransmitted_Constant_Name"); } if(type.equalsIgnoreCase("bigdecimal") && (initialValue==null || initialValue.size()==0)){ JavaClassElement.javaCodeBuffer.append("=FCU.BigDecimalArray("+arrayLength+","+lengthAfterDot+")"); }else if(type.equalsIgnoreCase("string") && (initialValue==null || initialValue.size()==0)){ JavaClassElement.javaCodeBuffer.append("=FCU.resetStringArray("+arrayLength+")"); }else if(initialValue!=null && initialValue.size()>0){ //public String[] YETPROG=new String[]{IDGP0011,IDGP0013,IDGP0012,}; JavaClassElement.javaCodeBuffer.append("=new "); JavaClassElement.javaCodeBuffer.append(type + "[]{"); for(int i=0; i<initialValue.size()-1; i++){ JavaClassElement.javaCodeBuffer.append(JavaWriteUtilities.toCustomString(initialValue.get(i))); JavaClassElement.javaCodeBuffer.append(","); } JavaClassElement.javaCodeBuffer.append(JavaWriteUtilities.toCustomString(initialValue.get(initialValue.size()-1))); JavaClassElement.javaCodeBuffer.append("}"); }else{ JavaClassElement.javaCodeBuffer.append("=new "); JavaClassElement.javaCodeBuffer.append(type + "["+arrayLength+"]"); } JavaClassElement.javaCodeBuffer.append(JavaConstants.DOT_WITH_COMMA); JavaClassElement.javaCodeBuffer.append(JavaConstants.NEW_LINE); } catch (Exception e) { logger.debug("//Conversion Error"+this.getClass()+this.getSourceCode().getSatirNumarasi()+this.getSourceCode().getCommandName()); JavaClassElement.javaCodeBuffer.append("/*Conversion Error"+this.getClass()+this.getSourceCode().getSatirNumarasi() +this.getSourceCode().getCommandName()+"*/"+JavaConstants.NEW_LINE); logger.error("//Conversion Error:"+e.getMessage(), e); ConvertUtilities.writeconversionErrors(e, this); } return true; } public int getLengthAfterDot() { return lengthAfterDot; } public void setLengthAfterDot(int lengthAfterDot) { this.lengthAfterDot = lengthAfterDot; } }
UTF-8
Java
5,131
java
JavaOneDimensionArrayElement.java
Java
[ { "context": " * \n * 0414 2 D_SECIM (A1/1:100)\n * @author 47159500\n * \n */\npublic class JavaOneDimensionArrayElement", "end": 882, "score": 0.9544873237609863, "start": 874, "tag": "USERNAME", "value": "47159500" } ]
null
[]
package tr.com.vbt.java.general; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import tr.com.vbt.java.AbstractJavaElement; import tr.com.vbt.java.utils.ConvertUtilities; import tr.com.vbt.java.utils.JavaWriteUtilities; import tr.com.vbt.token.AbstractToken; //*S**01 #SECIM-YURT-ICI-AKARYAKIT(A1/4) --> String[4] SECIM_YURT_ICI_AKARYAKIT=new String[4]; //*S**01 #ROL1(N1/15) --> int[15] ROL1=new int[15]; /** * * (A15) * (N8) --> int * (N10) --> double * (D) -->Date * (P7) --> * (C) --> * * A 253 length Alpha (letters, numbers, certain symbols) N 29 length Numeric I Integer P 29 (length /2) Packed B Binary D 4 Date (internal day number) T 7 Time (internal day number and time) L 1 Logical (TRUE or FALSE) C 1 Control (whether modified) * * * 0414 2 D_SECIM (A1/1:100) * @author 47159500 * */ public class JavaOneDimensionArrayElement extends AbstractJavaElement { final static Logger logger = Logger.getLogger(JavaOneDimensionArrayElement.class); private String type; private String dataType; private int length; private int lengthAfterDot; private String dataName; private String visibility; private int arrayLength; private int levelNumber; private List<AbstractToken> initialValue; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { this.visibility = visibility; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getDataName() { return dataName; } public void setDataName(String dataName) { this.dataName = dataName; } //*S**1 #SECIM (N2) @Override public boolean writeJavaToStream() throws Exception{ super.writeJavaToStream(); try { writeFieldAnnotation(); dataType = (String) this.parameters.get("dataType"); if(this.parameters.get("length")!=null){ length=(int)((long) this.parameters.get("length")); } dataName = (String) this.parameters.get("dataName"); levelNumber = (int)((long) this.parameters.get("levelNumber")); if(this.parameters.get("arrayLength")!=null){ arrayLength=(int) ((long)this.parameters.get("arrayLength")); } if(parameters.get("lengthAfterDot")!=null){ lengthAfterDot=(int)((long) parameters.get("lengthAfterDot")); } if(parameters.get("initialValue")!=null){ initialValue= (List<AbstractToken>) parameters.get("initialValue"); } type=ConvertUtilities.getJavaVariableType(dataType, length, lengthAfterDot); //String[4] SECIM_YURT_ICI_AKARYAKIT=new String[4]; //int[15] ROL1=new int[15]; JavaClassElement.javaCodeBuffer.append("public "+type + "[] "); if (dataName != null) { JavaClassElement.javaCodeBuffer.append(dataName.replace('-', '_')); } else { JavaClassElement.javaCodeBuffer .append("Untransmitted_Constant_Name"); } if(type.equalsIgnoreCase("bigdecimal") && (initialValue==null || initialValue.size()==0)){ JavaClassElement.javaCodeBuffer.append("=FCU.BigDecimalArray("+arrayLength+","+lengthAfterDot+")"); }else if(type.equalsIgnoreCase("string") && (initialValue==null || initialValue.size()==0)){ JavaClassElement.javaCodeBuffer.append("=FCU.resetStringArray("+arrayLength+")"); }else if(initialValue!=null && initialValue.size()>0){ //public String[] YETPROG=new String[]{IDGP0011,IDGP0013,IDGP0012,}; JavaClassElement.javaCodeBuffer.append("=new "); JavaClassElement.javaCodeBuffer.append(type + "[]{"); for(int i=0; i<initialValue.size()-1; i++){ JavaClassElement.javaCodeBuffer.append(JavaWriteUtilities.toCustomString(initialValue.get(i))); JavaClassElement.javaCodeBuffer.append(","); } JavaClassElement.javaCodeBuffer.append(JavaWriteUtilities.toCustomString(initialValue.get(initialValue.size()-1))); JavaClassElement.javaCodeBuffer.append("}"); }else{ JavaClassElement.javaCodeBuffer.append("=new "); JavaClassElement.javaCodeBuffer.append(type + "["+arrayLength+"]"); } JavaClassElement.javaCodeBuffer.append(JavaConstants.DOT_WITH_COMMA); JavaClassElement.javaCodeBuffer.append(JavaConstants.NEW_LINE); } catch (Exception e) { logger.debug("//Conversion Error"+this.getClass()+this.getSourceCode().getSatirNumarasi()+this.getSourceCode().getCommandName()); JavaClassElement.javaCodeBuffer.append("/*Conversion Error"+this.getClass()+this.getSourceCode().getSatirNumarasi() +this.getSourceCode().getCommandName()+"*/"+JavaConstants.NEW_LINE); logger.error("//Conversion Error:"+e.getMessage(), e); ConvertUtilities.writeconversionErrors(e, this); } return true; } public int getLengthAfterDot() { return lengthAfterDot; } public void setLengthAfterDot(int lengthAfterDot) { this.lengthAfterDot = lengthAfterDot; } }
5,131
0.701423
0.685636
182
27.192308
28.581892
132
false
false
0
0
0
0
0
0
2.082417
false
false
14
0fa978448a51b2078446c4e3c3a9647e0fd2f91e
11,733,850,700,053
b831fd3bfe867e8cea03e9f74d1856ced6e94741
/src/main/java/com/project/xghk416/pojo/dto/UploaderInfoDto.java
e9fc8e0e9582c1939dbc7d19c0526dbfc1f7132b
[]
no_license
frankiegu/BiliSpy_Api
https://github.com/frankiegu/BiliSpy_Api
62312d57fc1139f4870f11026fc8d143f1c16828
d5ec1f66e729c10fef5e92f32ea604bdeb194c30
refs/heads/master
2022-12-14T20:32:57.676000
2020-09-03T07:20:11
2020-09-03T07:20:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.xghk416.pojo.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.project.xghk416.pojo.bili.BiliUploaderPo; import lombok.Data; import java.time.LocalDateTime; @Data public class UploaderInfoDto { String profile; String nick_name; int mid; String vip; String belong_section; String idiograph; @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone="GMT+8") LocalDateTime last_publish; int detect_time; public UploaderInfoDto(){}; public UploaderInfoDto(BiliUploaderPo uploader,String belongSection,LocalDateTime dateTime,int detectTime){ nick_name = uploader.getNickName(); profile = uploader.getProfile(); mid = uploader.getUserId(); vip = uploader.getVip(); idiograph = uploader.getSign(); belong_section = belongSection; last_publish = dateTime; detect_time = detectTime; } }
UTF-8
Java
930
java
UploaderInfoDto.java
Java
[]
null
[]
package com.project.xghk416.pojo.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.project.xghk416.pojo.bili.BiliUploaderPo; import lombok.Data; import java.time.LocalDateTime; @Data public class UploaderInfoDto { String profile; String nick_name; int mid; String vip; String belong_section; String idiograph; @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone="GMT+8") LocalDateTime last_publish; int detect_time; public UploaderInfoDto(){}; public UploaderInfoDto(BiliUploaderPo uploader,String belongSection,LocalDateTime dateTime,int detectTime){ nick_name = uploader.getNickName(); profile = uploader.getProfile(); mid = uploader.getUserId(); vip = uploader.getVip(); idiograph = uploader.getSign(); belong_section = belongSection; last_publish = dateTime; detect_time = detectTime; } }
930
0.691398
0.683871
37
24.135136
22.674145
111
false
false
0
0
0
0
0
0
0.702703
false
false
14
ddf4f347b8a8ce1ee33f3f59a1a2decae82b0397
128,849,070,016
08c31846afa129fcc50350a05635a931b0326add
/Java Source files_2/Problem2_sodaClass.java
8d00f58de9d2c298a5c599615bf6b4574af16639
[]
no_license
SarikaRKshatriya/JUnit-Examples
https://github.com/SarikaRKshatriya/JUnit-Examples
3fc04b3837cdd6fc55d593656ca810a51e4841ec
b295c2c46de73c10b8a51d9c3aefa43a2afdc6cc
refs/heads/master
2020-04-17T21:37:05.973000
2018-08-01T03:57:36
2018-08-01T03:57:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Homework5; public class Problem2_sodaClass { private String m; private boolean c,d; private Problem2_sodaEnum State; public Problem2_sodaClass(String m, boolean c, boolean d, Problem2_sodaEnum state) { this.m = m; this.c = c; this.d = d; this.State = state; } public void processState (boolean q,boolean s,boolean r) { switch (State) { case S0:if (s || r) {m = "Welcome";State=Problem2_sodaEnum.S0;} else {m = "25 cents credit";State=Problem2_sodaEnum.S1;} c=d=false; break; case S1:if (s) {m = "25 cents credit";c=d=false;State=Problem2_sodaEnum.S1;} else if (r) {m = "Welcome";d=false; c=true;State=Problem2_sodaEnum.S0;} else {m = "50 cents credit";c=d=false;State=Problem2_sodaEnum.S2;} break; case S2:if (s) {m = "50 cents credit";c=d=false;State=Problem2_sodaEnum.S2;} else if (r) {m = "25 cents credit";d=false; c=true;State=Problem2_sodaEnum.S1;} else {m = "75 cents credit";c=d=false;State=Problem2_sodaEnum.S3;} break; case S3:if (s) {m = "Welcome";d=true; c=false;State=Problem2_sodaEnum.S0;} else if (r) {m = "50 cents credit";d=false; c=true;State=Problem2_sodaEnum.S2;} else {m = "75 cents credit";c=d=false;State=Problem2_sodaEnum.S3;} break; case Start: default: //this is for the Start constructor - we ignore this } } public String getM() { return m; } public boolean isC() { return c; } public boolean isD() { return d; } public Problem2_sodaEnum getState() { return State; } public void setState(Problem2_sodaEnum state) { State = state; } }
UTF-8
Java
1,718
java
Problem2_sodaClass.java
Java
[]
null
[]
package Homework5; public class Problem2_sodaClass { private String m; private boolean c,d; private Problem2_sodaEnum State; public Problem2_sodaClass(String m, boolean c, boolean d, Problem2_sodaEnum state) { this.m = m; this.c = c; this.d = d; this.State = state; } public void processState (boolean q,boolean s,boolean r) { switch (State) { case S0:if (s || r) {m = "Welcome";State=Problem2_sodaEnum.S0;} else {m = "25 cents credit";State=Problem2_sodaEnum.S1;} c=d=false; break; case S1:if (s) {m = "25 cents credit";c=d=false;State=Problem2_sodaEnum.S1;} else if (r) {m = "Welcome";d=false; c=true;State=Problem2_sodaEnum.S0;} else {m = "50 cents credit";c=d=false;State=Problem2_sodaEnum.S2;} break; case S2:if (s) {m = "50 cents credit";c=d=false;State=Problem2_sodaEnum.S2;} else if (r) {m = "25 cents credit";d=false; c=true;State=Problem2_sodaEnum.S1;} else {m = "75 cents credit";c=d=false;State=Problem2_sodaEnum.S3;} break; case S3:if (s) {m = "Welcome";d=true; c=false;State=Problem2_sodaEnum.S0;} else if (r) {m = "50 cents credit";d=false; c=true;State=Problem2_sodaEnum.S2;} else {m = "75 cents credit";c=d=false;State=Problem2_sodaEnum.S3;} break; case Start: default: //this is for the Start constructor - we ignore this } } public String getM() { return m; } public boolean isC() { return c; } public boolean isD() { return d; } public Problem2_sodaEnum getState() { return State; } public void setState(Problem2_sodaEnum state) { State = state; } }
1,718
0.606519
0.577998
71
22.225351
26.158884
85
false
false
0
0
0
0
0
0
3.140845
false
false
14
26d0249cabe6f0634d7bfb07f5e2ddabc4b4ebcb
14,525,579,447,527
d3e59f295f4e0f2513a6be207a597b66fe81f213
/src/com/iboxpay/interfaceStudy/interfaceStudy1/Instrument.java
a2c548b2e0850ba0d0aaacffe4c818d12a05b625
[]
no_license
ZJsnowman/Observer
https://github.com/ZJsnowman/Observer
7ad3c168c5136f2d78b3be42262d65bb6009e0ad
9eaadfc9b4bb8ecce2392ef4efdd82d86aa21a4b
refs/heads/master
2016-09-05T19:44:20.330000
2016-08-05T07:36:59
2016-08-05T07:36:59
47,613,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iboxpay.interfaceStudy.interfaceStudy1; /** * Created by zhangjun on 2016/1/15. */ public abstract class Instrument { private int i; public abstract void play(Note note); public String what() { return "Instrument"; } public abstract void adjust(); }
UTF-8
Java
296
java
Instrument.java
Java
[ { "context": "interfaceStudy.interfaceStudy1;\n\n/**\n * Created by zhangjun on 2016/1/15.\n */\npublic abstract class Instrumen", "end": 79, "score": 0.9949519038200378, "start": 71, "tag": "USERNAME", "value": "zhangjun" } ]
null
[]
package com.iboxpay.interfaceStudy.interfaceStudy1; /** * Created by zhangjun on 2016/1/15. */ public abstract class Instrument { private int i; public abstract void play(Note note); public String what() { return "Instrument"; } public abstract void adjust(); }
296
0.668919
0.641892
16
17.5
17.352953
51
false
false
0
0
0
0
0
0
0.3125
false
false
14
44287cf38866c843b110d157f3f3a39e5f86c8a0
2,869,038,197,553
31158e72f2be244cf10cf1876bc8b92a333b0381
/src/Controllers/BackEnd/Socket/MockSocket.java
5444c3cda3155ee7243bd84776d341ecfc068210
[]
no_license
DeclanBarrett/CAB302Assignment1AssetTradingPlatform
https://github.com/DeclanBarrett/CAB302Assignment1AssetTradingPlatform
4e3ac8e2c6439b7b0f861031a5e9128d9c11f21a
3a3dbf0f69ec02a9208a894933de0078dc671acc
refs/heads/main
2023-05-06T19:15:01.842000
2021-06-04T02:09:02
2021-06-04T02:09:02
353,874,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Controllers.BackEnd.Socket; import Controllers.BackEnd.*; import Controllers.BackEnd.NetworkObjects.*; import Controllers.Exceptions.AuthenticationException; import Controllers.Exceptions.ServerException; import java.time.Duration; import java.util.*; /** * Mock database for testing. */ public class MockSocket implements IDataSource { private boolean databaseConnected; private ArrayList<User> userTable = new ArrayList<>(); private ArrayList<OrganisationalUnit> organisationalUnitTable = new ArrayList<>(); private HashMap<java.lang.String, Integer> organisationAssets = new HashMap<>(); private ArrayList<Order> orderTable = new ArrayList<>(); private ArrayList<java.lang.String> assetTypesTable = new ArrayList<>(); private ArrayList<Trade> tradesTable = new ArrayList<>(); /* * Populating the mock database with values */ protected MockSocket() { databaseConnected = false; userTable.add(new User("User 1", "b717415eb5e699e4989ef3e2c4e9cbf7", AccountType.User, "Sales", "12345")); //qwerty userTable.add(new User("User 2", "b717415eb5e699e4989ef3e2c4e9cbf7", AccountType.User, "Sales", "12345")); userTable.add(new User("User 3", "8d421e892a47dff539f46142eb09e56b", AccountType.User, "Finance", "123456")); //1234 userTable.add(new User("User 4", "b26b843656e6834822b83179b4297620", AccountType.User, "Finance", "123457")); userTable.add(new User("User 5", "c3a4b61825259a74c26d49daa3e89312", AccountType.User, "Finance", "123458")); //password userTable.add(new User("User 6", "2ec7484fa99bbaa7bdebe544f1f52f61", AccountType.User, "Research", "123459")); userTable.add(new User("User 7", "ccab59bc481b2105a4dbdf3d30a66248", AccountType.User, "Research", "123450")); userTable.add(new User("User 8", "aa3cae505478da19d13efa65bc8c71b3", AccountType.User, "Research", "123451")); userTable.add(new User("User 9", "43bf88d863f230f328c15ccf61d9d89d", AccountType.User, "Research", "123452")); userTable.add(new User("Declan Testing", "802b492fc1d1fe592090399c1ca3b56a", AccountType.SystemAdmin, "Admin", "12346")); //qwerty userTable.add(new User("Aiden Testing", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("Brad Testing", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("Ethan Testing", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("User 10", "579d9ec9d0c3d687aaa91289ac2854e4", AccountType.UnitLeader, "Sales", "123456")); //123 userTable.add(new User("User 11", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Finance", "123456")); //qwerty userTable.add(new User("User 12", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Research", "123456")); userTable.add(new User("User 13", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Research", "123456")); organisationAssets.put("Paper", 50); organisationAssets.put("CPU hours", 600); organisationAssets.put("Pickles", 50); organisationAssets.put("Casino Chips", 50); organisationalUnitTable.add(new OrganisationalUnit("Sales", 3000.50, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Finance", 100, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Research", 90, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Admin", 0, organisationAssets)); assetTypesTable.add("Paper"); assetTypesTable.add("CPU hours"); assetTypesTable.add("Pickles"); assetTypesTable.add("Casino Chips"); orderTable.add(new Order(123456, OrderType.BUY, "Paper", 3, 3, "Research", new Date())); orderTable.add(new Order(123457, OrderType.SELL, "CPU hours", 3, 3000, "Research", new Date())); orderTable.add(new Order(123458, OrderType.BUY, "Pickles", 3, 3000, "Sales", new Date())); orderTable.add(new Order(123459, OrderType.SELL, "Casino Chips", 3, 3, "Sales", new Date())); Date date = new Date(); tradesTable.add(new Trade(123456, "Paper", 5, 3.0, "Research", "Sales", new Date(date.getTime() + 1))); tradesTable.add(new Trade(123457, "Paper", 4, 3.2, "Research", "Sales", new Date(date.getTime() + 2))); tradesTable.add(new Trade(123458, "Paper", 6, 4.3, "Research", "Sales", new Date(date.getTime() + 3))); tradesTable.add(new Trade(123459, "Paper", 2, 4.5, "Research", "Sales", new Date(date.getTime() + 4))); tradesTable.add(new Trade(123410, "Paper", 4, 3.1, "Research", "Sales", new Date(date.getTime() + 5))); tradesTable.add(new Trade(123412, "Paper", 5, 5.0, "Research", "Sales", new Date(date.getTime() + 6))); tradesTable.add(new Trade(123413, "Paper", 1, 1.0, "Research", "Sales", new Date(date.getTime() + 7))); System.out.println("HELL"); } private static class MockSocketHolder { private final static MockSocket INSTANCE = new MockSocket(); } public static MockSocket getInstance() { return MockSocketHolder.INSTANCE; } @Override public java.lang.String GetSalt(java.lang.String username) throws ServerException{ for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { return currentUser.getSalt(); } } return null; } @Override public String AttemptLogin(java.lang.String username, java.lang.String password) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username) && currentUser.getPassword().equals(password)) { Date actualDate = new Date(); actualDate.toInstant().plus(Duration.ofHours(2)); String login = currentUser.getUsername() + new Date(); return login; } } return null; } @Override public java.lang.String AttemptResetPassword(String token, java.lang.String username, java.lang.String newPassword) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), newPassword, currentUser.getAccountType(), currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public UserInfo GetUser(String token, java.lang.String username) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { System.out.println(currentUser.getOrganisationalUnit()); return new UserInfo(currentUser.getUsername(), currentUser.getAccountType(), currentUser.getOrganisationalUnit()); } } return null; } @Override public OrganisationalUnit GetOrganisation(String token, java.lang.String orgName) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(orgName)) { return organisationalUnit; } } return null; } @Override public List<Order> GetOrganisationOrders(String token, java.lang.String orgName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(orgName)) orders.add(order); } return orders; } @Override public List<Order> GetAllOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> orders = orderTable; return orders; } @Override public List<Order> GetBuyOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> buyOrders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrderType().equals(OrderType.BUY)) { buyOrders.add(order); } } return buyOrders; } @Override public List<Order> GetSellOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> sellOrders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrderType().equals(OrderType.SELL)) { sellOrders.add(order); } } return sellOrders; } @Override public List<Order> GetOrganisationBuyOrders(String token, java.lang.String organisationName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(organisationName)) orders.add(order); } ArrayList<Order> buyOrders = new ArrayList<>(); for (Order order: orders) { if (order.getOrderType().equals(OrderType.BUY)) { buyOrders.add(order); } } return buyOrders; } @Override public List<Order> GetOrganisationSellOrders(String token, java.lang.String organisationName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(organisationName)) orders.add(order); } ArrayList<Order> sellOrders = new ArrayList<>(); for (Order order: orders) { if (order.getOrderType().equals(OrderType.SELL)) { sellOrders.add(order); } } return sellOrders; } @Override public java.lang.String AddOrder(String token, Order newOrder) throws AuthenticationException, ServerException { Random rand = new Random(); orderTable.add(new Order(rand.nextInt(), newOrder.getOrderType(), newOrder.getAssetType(), newOrder.getAssetQuantity(), newOrder.getRequestPrice(), newOrder.getOrganisationalUnit(), new Date())); return "Success"; } @Override public java.lang.String RemoveOrder(String token, int OrderID) throws AuthenticationException, ServerException { orderTable.removeIf(order -> order.getOrderID() == OrderID); return "Success"; } @Override public List<java.lang.String> GetAssetTypes(String token) throws AuthenticationException, ServerException { return assetTypesTable; } @Override public List<Trade> GetTradeHistory(String token, java.lang.String AssetType) throws AuthenticationException, ServerException { List<Trade> trades = new ArrayList<>(); for (Trade trade: tradesTable) { if (trade.getAssetName().equals(AssetType)) { trades.add(trade); } } return trades; } @Override public List<Trade> GetAllTradeHistory(String token) throws AuthenticationException, ServerException { return null; } @Override public java.lang.String AddUser(String token, User user) throws AuthenticationException, ServerException { userTable.add(user); return "Success"; } @Override public List<UserInfo> GetAllUsers(String token) throws AuthenticationException, ServerException { List<UserInfo> infoTable = new ArrayList<>(); for (User user : userTable) { infoTable.add(new UserInfo(user.getUsername(), user.getAccountType(), user.getOrganisationalUnit())); } return infoTable; } @Override public java.lang.String UpdateUserPassword(String token, java.lang.String username, java.lang.String hashedPassword) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), hashedPassword, currentUser.getAccountType(), currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "mp"; } @Override public java.lang.String UpdateUserAccountType(String token, java.lang.String username, AccountType accountType) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), currentUser.getPassword(), accountType, currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String UpdateUserOrganisation(String token, java.lang.String username, java.lang.String organisationName) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), currentUser.getPassword(), currentUser.getAccountType(), organisationName, currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String AddAsset(String token, java.lang.String assetName) throws AuthenticationException, ServerException { assetTypesTable.add(assetName); return "Success"; } @Override public java.lang.String AddOrganisation(String token, OrganisationalUnit organisation) throws AuthenticationException, ServerException { organisationalUnitTable.add(organisation); return "Success"; } @Override public List<OrganisationalUnit> GetAllOrganisations(String token) throws AuthenticationException, ServerException { return organisationalUnitTable; } @Override public java.lang.String UpdateOrganisationAsset(String token, java.lang.String organisationName, java.lang.String AssetType, int AssetQuantity) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(organisationName)) { HashMap<java.lang.String, Integer> assets = organisationalUnit.GetAllAssets(); if (assetTypesTable.contains(AssetType)) { assets.put(AssetType, AssetQuantity); } else { return "BAD"; } OrganisationalUnit updatedOrg = new OrganisationalUnit(organisationalUnit.getUnitName(), organisationalUnit.getCredits(), assets); organisationalUnitTable.remove(organisationalUnit); organisationalUnitTable.add(updatedOrg); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String UpdateOrganisationCredit(String token, java.lang.String organisationName, int creditAmount) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(organisationName)) { OrganisationalUnit updatedOrg = new OrganisationalUnit(organisationalUnit.getUnitName(), creditAmount, organisationalUnit.GetAllAssets()); organisationalUnitTable.remove(organisationalUnit); organisationalUnitTable.add(updatedOrg); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } }
UTF-8
Java
16,900
java
MockSocket.java
Java
[ { "context": "false;\n\n userTable.add(new User(\"User 1\", \"b717415eb5e699e4989ef3e2c4e9cbf7\", AccountType.User, \"Sales\", \"12345\")); //qwerty\n", "end": 1026, "score": 0.8946223258972168, "start": 994, "tag": "KEY", "value": "b717415eb5e699e4989ef3e2c4e9cbf7" }, { "context": "/qwerty\n userTable.add(new User(\"User 2\", \"b717415eb5e699e4989ef3e2c4e9cbf7\", AccountType.User, \"Sales\", \"12345\"));\n u", "end": 1150, "score": 0.9338735938072205, "start": 1118, "tag": "KEY", "value": "b717415eb5e699e4989ef3e2c4e9cbf7" }, { "context": "49daa3e89312\", AccountType.User, \"Finance\", \"123458\")); //password\n userTable.add(new User(\"Us", "end": 1547, "score": 0.9456629753112793, "start": 1546, "tag": "PASSWORD", "value": "8" }, { "context": "assword\n userTable.add(new User(\"User 6\", \"2ec7484fa99bbaa7bdebe544f1f52f61\", AccountType.User, \"Research\", \"123459\"));\n ", "end": 1637, "score": 0.5215404629707336, "start": 1605, "tag": "PASSWORD", "value": "2ec7484fa99bbaa7bdebe544f1f52f61" }, { "context": "451\"));\n userTable.add(new User(\"User 9\", \"43bf88d863f230f328c15ccf61d9d89d\", AccountType.User, \"Research\", \"123452\"));\n\n ", "end": 1994, "score": 0.9939968585968018, "start": 1962, "tag": "PASSWORD", "value": "43bf88d863f230f328c15ccf61d9d89d" }, { "context": "ch\", \"123452\"));\n\n userTable.add(new User(\"Declan Testing\", \"802b492fc1d1fe592090399c1ca3b56a\", AccountType", "end": 2086, "score": 0.9960238337516785, "start": 2072, "tag": "NAME", "value": "Declan Testing" }, { "context": " userTable.add(new User(\"Declan Testing\", \"802b492fc1d1fe592090399c1ca3b56a\", AccountType.SystemAdmin, \"Admin\", \"123", "end": 2113, "score": 0.7248824238777161, "start": 2090, "tag": "PASSWORD", "value": "802b492fc1d1fe592090399" }, { "context": "w User(\"Declan Testing\", \"802b492fc1d1fe592090399c1ca3b56a\", AccountType.SystemAdmin, \"Admin\", \"12346\")); //", "end": 2122, "score": 0.6682578921318054, "start": 2114, "tag": "PASSWORD", "value": "1ca3b56a" }, { "context": "2346\")); //qwerty\n userTable.add(new User(\"Aiden Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType", "end": 2224, "score": 0.9877931475639343, "start": 2211, "tag": "NAME", "value": "Aiden Testing" }, { "context": " userTable.add(new User(\"Aiden Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.SystemAdmin, \"Admin\", \"123456\"));\n ", "end": 2260, "score": 0.8698093891143799, "start": 2229, "tag": "KEY", "value": "86e1b7e1c12ba37cd473670b3a15214" }, { "context": "min\", \"123456\"));\n userTable.add(new User(\"Brad Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType", "end": 2353, "score": 0.9885331988334656, "start": 2341, "tag": "NAME", "value": "Brad Testing" }, { "context": "\n userTable.add(new User(\"Brad Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.SystemAdmin, \"Admin\", \"123456\"));\n ", "end": 2389, "score": 0.8303970694541931, "start": 2358, "tag": "KEY", "value": "86e1b7e1c12ba37cd473670b3a15214" }, { "context": "min\", \"123456\"));\n userTable.add(new User(\"Ethan Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType", "end": 2483, "score": 0.9872806668281555, "start": 2470, "tag": "NAME", "value": "Ethan Testing" }, { "context": "\n userTable.add(new User(\"Ethan Testing\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.SystemAdmin, \"Admin\", \"123456\"));\n\n", "end": 2519, "score": 0.8574711084365845, "start": 2487, "tag": "KEY", "value": "086e1b7e1c12ba37cd473670b3a15214" }, { "context": "userTable.add(new User(\"User 10\", \"579d9ec9d0c3d687aaa91289ac2854e4\", AccountType.UnitLeader, \"Sales\", \"123456\")); //", "end": 2644, "score": 0.9751988649368286, "start": 2627, "tag": "KEY", "value": "7aaa91289ac2854e4" }, { "context": " //123\n userTable.add(new User(\"User 11\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.UnitLeader, \"Finance\", \"123456\")); ", "end": 2773, "score": 0.9937471151351929, "start": 2741, "tag": "KEY", "value": "086e1b7e1c12ba37cd473670b3a15214" }, { "context": "qwerty\n userTable.add(new User(\"User 12\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.UnitLeader, \"Research\", \"123456\"));", "end": 2907, "score": 0.990339994430542, "start": 2875, "tag": "KEY", "value": "086e1b7e1c12ba37cd473670b3a15214" }, { "context": "56\"));\n userTable.add(new User(\"User 13\", \"086e1b7e1c12ba37cd473670b3a15214\", AccountType.UnitLeader, \"Research\", \"123456\"));", "end": 3033, "score": 0.9872944355010986, "start": 3001, "tag": "KEY", "value": "086e1b7e1c12ba37cd473670b3a15214" } ]
null
[]
package Controllers.BackEnd.Socket; import Controllers.BackEnd.*; import Controllers.BackEnd.NetworkObjects.*; import Controllers.Exceptions.AuthenticationException; import Controllers.Exceptions.ServerException; import java.time.Duration; import java.util.*; /** * Mock database for testing. */ public class MockSocket implements IDataSource { private boolean databaseConnected; private ArrayList<User> userTable = new ArrayList<>(); private ArrayList<OrganisationalUnit> organisationalUnitTable = new ArrayList<>(); private HashMap<java.lang.String, Integer> organisationAssets = new HashMap<>(); private ArrayList<Order> orderTable = new ArrayList<>(); private ArrayList<java.lang.String> assetTypesTable = new ArrayList<>(); private ArrayList<Trade> tradesTable = new ArrayList<>(); /* * Populating the mock database with values */ protected MockSocket() { databaseConnected = false; userTable.add(new User("User 1", "b717415eb5e699e4989ef3e2c4e9cbf7", AccountType.User, "Sales", "12345")); //qwerty userTable.add(new User("User 2", "b717415eb5e699e4989ef3e2c4e9cbf7", AccountType.User, "Sales", "12345")); userTable.add(new User("User 3", "8d421e892a47dff539f46142eb09e56b", AccountType.User, "Finance", "123456")); //1234 userTable.add(new User("User 4", "b26b843656e6834822b83179b4297620", AccountType.User, "Finance", "123457")); userTable.add(new User("User 5", "c3a4b61825259a74c26d49daa3e89312", AccountType.User, "Finance", "123458")); //password userTable.add(new User("User 6", "<PASSWORD>", AccountType.User, "Research", "123459")); userTable.add(new User("User 7", "ccab59bc481b2105a4dbdf3d30a66248", AccountType.User, "Research", "123450")); userTable.add(new User("User 8", "aa3cae505478da19d13efa65bc8c71b3", AccountType.User, "Research", "123451")); userTable.add(new User("User 9", "<PASSWORD>", AccountType.User, "Research", "123452")); userTable.add(new User("<NAME>", "<PASSWORD>c<PASSWORD>", AccountType.SystemAdmin, "Admin", "12346")); //qwerty userTable.add(new User("<NAME>", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("<NAME>", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("<NAME>", "086e1b7e1c12ba37cd473670b3a15214", AccountType.SystemAdmin, "Admin", "123456")); userTable.add(new User("User 10", "579d9ec9d0c3d68<KEY>", AccountType.UnitLeader, "Sales", "123456")); //123 userTable.add(new User("User 11", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Finance", "123456")); //qwerty userTable.add(new User("User 12", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Research", "123456")); userTable.add(new User("User 13", "086e1b7e1c12ba37cd473670b3a15214", AccountType.UnitLeader, "Research", "123456")); organisationAssets.put("Paper", 50); organisationAssets.put("CPU hours", 600); organisationAssets.put("Pickles", 50); organisationAssets.put("Casino Chips", 50); organisationalUnitTable.add(new OrganisationalUnit("Sales", 3000.50, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Finance", 100, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Research", 90, organisationAssets)); organisationalUnitTable.add(new OrganisationalUnit("Admin", 0, organisationAssets)); assetTypesTable.add("Paper"); assetTypesTable.add("CPU hours"); assetTypesTable.add("Pickles"); assetTypesTable.add("Casino Chips"); orderTable.add(new Order(123456, OrderType.BUY, "Paper", 3, 3, "Research", new Date())); orderTable.add(new Order(123457, OrderType.SELL, "CPU hours", 3, 3000, "Research", new Date())); orderTable.add(new Order(123458, OrderType.BUY, "Pickles", 3, 3000, "Sales", new Date())); orderTable.add(new Order(123459, OrderType.SELL, "Casino Chips", 3, 3, "Sales", new Date())); Date date = new Date(); tradesTable.add(new Trade(123456, "Paper", 5, 3.0, "Research", "Sales", new Date(date.getTime() + 1))); tradesTable.add(new Trade(123457, "Paper", 4, 3.2, "Research", "Sales", new Date(date.getTime() + 2))); tradesTable.add(new Trade(123458, "Paper", 6, 4.3, "Research", "Sales", new Date(date.getTime() + 3))); tradesTable.add(new Trade(123459, "Paper", 2, 4.5, "Research", "Sales", new Date(date.getTime() + 4))); tradesTable.add(new Trade(123410, "Paper", 4, 3.1, "Research", "Sales", new Date(date.getTime() + 5))); tradesTable.add(new Trade(123412, "Paper", 5, 5.0, "Research", "Sales", new Date(date.getTime() + 6))); tradesTable.add(new Trade(123413, "Paper", 1, 1.0, "Research", "Sales", new Date(date.getTime() + 7))); System.out.println("HELL"); } private static class MockSocketHolder { private final static MockSocket INSTANCE = new MockSocket(); } public static MockSocket getInstance() { return MockSocketHolder.INSTANCE; } @Override public java.lang.String GetSalt(java.lang.String username) throws ServerException{ for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { return currentUser.getSalt(); } } return null; } @Override public String AttemptLogin(java.lang.String username, java.lang.String password) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username) && currentUser.getPassword().equals(password)) { Date actualDate = new Date(); actualDate.toInstant().plus(Duration.ofHours(2)); String login = currentUser.getUsername() + new Date(); return login; } } return null; } @Override public java.lang.String AttemptResetPassword(String token, java.lang.String username, java.lang.String newPassword) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), newPassword, currentUser.getAccountType(), currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public UserInfo GetUser(String token, java.lang.String username) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { System.out.println(currentUser.getOrganisationalUnit()); return new UserInfo(currentUser.getUsername(), currentUser.getAccountType(), currentUser.getOrganisationalUnit()); } } return null; } @Override public OrganisationalUnit GetOrganisation(String token, java.lang.String orgName) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(orgName)) { return organisationalUnit; } } return null; } @Override public List<Order> GetOrganisationOrders(String token, java.lang.String orgName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(orgName)) orders.add(order); } return orders; } @Override public List<Order> GetAllOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> orders = orderTable; return orders; } @Override public List<Order> GetBuyOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> buyOrders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrderType().equals(OrderType.BUY)) { buyOrders.add(order); } } return buyOrders; } @Override public List<Order> GetSellOrders(String token) throws AuthenticationException, ServerException { ArrayList<Order> sellOrders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrderType().equals(OrderType.SELL)) { sellOrders.add(order); } } return sellOrders; } @Override public List<Order> GetOrganisationBuyOrders(String token, java.lang.String organisationName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(organisationName)) orders.add(order); } ArrayList<Order> buyOrders = new ArrayList<>(); for (Order order: orders) { if (order.getOrderType().equals(OrderType.BUY)) { buyOrders.add(order); } } return buyOrders; } @Override public List<Order> GetOrganisationSellOrders(String token, java.lang.String organisationName) throws AuthenticationException, ServerException { ArrayList<Order> orders = new ArrayList<>(); for (Order order: orderTable) { if (order.getOrganisationalUnit().equals(organisationName)) orders.add(order); } ArrayList<Order> sellOrders = new ArrayList<>(); for (Order order: orders) { if (order.getOrderType().equals(OrderType.SELL)) { sellOrders.add(order); } } return sellOrders; } @Override public java.lang.String AddOrder(String token, Order newOrder) throws AuthenticationException, ServerException { Random rand = new Random(); orderTable.add(new Order(rand.nextInt(), newOrder.getOrderType(), newOrder.getAssetType(), newOrder.getAssetQuantity(), newOrder.getRequestPrice(), newOrder.getOrganisationalUnit(), new Date())); return "Success"; } @Override public java.lang.String RemoveOrder(String token, int OrderID) throws AuthenticationException, ServerException { orderTable.removeIf(order -> order.getOrderID() == OrderID); return "Success"; } @Override public List<java.lang.String> GetAssetTypes(String token) throws AuthenticationException, ServerException { return assetTypesTable; } @Override public List<Trade> GetTradeHistory(String token, java.lang.String AssetType) throws AuthenticationException, ServerException { List<Trade> trades = new ArrayList<>(); for (Trade trade: tradesTable) { if (trade.getAssetName().equals(AssetType)) { trades.add(trade); } } return trades; } @Override public List<Trade> GetAllTradeHistory(String token) throws AuthenticationException, ServerException { return null; } @Override public java.lang.String AddUser(String token, User user) throws AuthenticationException, ServerException { userTable.add(user); return "Success"; } @Override public List<UserInfo> GetAllUsers(String token) throws AuthenticationException, ServerException { List<UserInfo> infoTable = new ArrayList<>(); for (User user : userTable) { infoTable.add(new UserInfo(user.getUsername(), user.getAccountType(), user.getOrganisationalUnit())); } return infoTable; } @Override public java.lang.String UpdateUserPassword(String token, java.lang.String username, java.lang.String hashedPassword) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), hashedPassword, currentUser.getAccountType(), currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "mp"; } @Override public java.lang.String UpdateUserAccountType(String token, java.lang.String username, AccountType accountType) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), currentUser.getPassword(), accountType, currentUser.getOrganisationalUnit(), currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String UpdateUserOrganisation(String token, java.lang.String username, java.lang.String organisationName) throws AuthenticationException, ServerException { for (User currentUser: userTable) { if (currentUser.getUsername().equals(username)) { User updatedUser = new User(currentUser.getUsername(), currentUser.getPassword(), currentUser.getAccountType(), organisationName, currentUser.getSalt()); userTable.remove(currentUser); userTable.add(updatedUser); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String AddAsset(String token, java.lang.String assetName) throws AuthenticationException, ServerException { assetTypesTable.add(assetName); return "Success"; } @Override public java.lang.String AddOrganisation(String token, OrganisationalUnit organisation) throws AuthenticationException, ServerException { organisationalUnitTable.add(organisation); return "Success"; } @Override public List<OrganisationalUnit> GetAllOrganisations(String token) throws AuthenticationException, ServerException { return organisationalUnitTable; } @Override public java.lang.String UpdateOrganisationAsset(String token, java.lang.String organisationName, java.lang.String AssetType, int AssetQuantity) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(organisationName)) { HashMap<java.lang.String, Integer> assets = organisationalUnit.GetAllAssets(); if (assetTypesTable.contains(AssetType)) { assets.put(AssetType, AssetQuantity); } else { return "BAD"; } OrganisationalUnit updatedOrg = new OrganisationalUnit(organisationalUnit.getUnitName(), organisationalUnit.getCredits(), assets); organisationalUnitTable.remove(organisationalUnit); organisationalUnitTable.add(updatedOrg); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } @Override public java.lang.String UpdateOrganisationCredit(String token, java.lang.String organisationName, int creditAmount) throws AuthenticationException, ServerException { for (OrganisationalUnit organisationalUnit: organisationalUnitTable) { if (organisationalUnit.getUnitName().equals(organisationName)) { OrganisationalUnit updatedOrg = new OrganisationalUnit(organisationalUnit.getUnitName(), creditAmount, organisationalUnit.GetAllAssets()); organisationalUnitTable.remove(organisationalUnit); organisationalUnitTable.add(updatedOrg); return "Success"; } } return "BAD";//throw new AuthenticationException("USERNAME OR PASSWORD IS INCORRECT"); } }
16,805
0.662544
0.626746
379
43.59103
45.215332
197
false
false
0
0
0
0
0
0
0.997361
false
false
14
8a363946d58ab26df9fa889b9ba09238ab6cd491
26,036,091,793,343
f923e2b65dcb1ab8f03a2bfa8565f29711f17cb4
/restful-web-services/src/main/java/com/microservices/rest/webservices/restfulwebservices/SecurityConfig.java
ef4e9cfad4a13ee4364392d6108c1c672af47ca6
[]
no_license
luizfelipew/microservices-springboot
https://github.com/luizfelipew/microservices-springboot
05000efc015f746e9dd484e8ba06806e1bd4c3ad
289cd1b838b5edb75da8ae6250d9c460f47c32cb
refs/heads/master
2021-06-26T15:45:13.969000
2019-02-12T15:12:55
2019-02-12T15:12:55
133,882,755
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.microservices.rest.webservices.restfulwebservices; /*@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }*/
UTF-8
Java
271
java
SecurityConfig.java
Java
[]
null
[]
package com.microservices.rest.webservices.restfulwebservices; /*@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }*/
271
0.756458
0.756458
10
26.1
26.651266
66
false
false
0
0
0
0
0
0
0.2
false
false
14
14a2046036c8ff078171028967d7dc88223dbbd8
31,404,800,911,065
fe3c3f50ef1ba12abcf62e8ba1baee0e6877bc65
/vteba-core/src/main/java/com/vteba/tx/jdbc/spring/GenericRowMapper.java
27a06c36423fdac291e32e1a34249a45c1f1a95f
[]
no_license
yapingzhang/vteba-core
https://github.com/yapingzhang/vteba-core
45f51f29bd2cc9811e37ffb657069fc8117b8e89
ef138f2f36fc7de3a3de20a3b91d7d1a6cec3069
refs/heads/master
2021-01-17T17:12:41.697000
2014-11-11T07:53:50
2014-11-11T07:53:50
26,588,922
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vteba.tx.jdbc.spring; import java.sql.Blob; import java.sql.Clob; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.vteba.lang.bytecode.ConstructorAccess; import com.vteba.lang.bytecode.MethodAccess; import com.vteba.utils.common.CaseUtils; import com.vteba.utils.reflection.AsmUtils; /** * Spring JdbcTemplate 通用RowMapper,基于getter,setter实现。 * @author yinlei * date 2013-6-25 下午10:20:06 * @param <T> RowMapper要转换的对象 */ public class GenericRowMapper<T> implements RowMapper<T> { private Class<T> resultClass; private ConstructorAccess<T> constructorAccess; private MethodAccess methodAccess; private int columnCount = 0; private String[] columnLabels; private String[] methodNames; private String sql; public GenericRowMapper(Class<T> resultClass, String sql) { this.resultClass = resultClass; this.sql = sql; constructorAccess = AsmUtils.get().createConstructorAccess(this.resultClass); methodAccess = AsmUtils.get().createMethodAccess(this.resultClass); RowMapInfo rowMapInfo = RowMapInfoCache.getInstance().get(this.sql); if (rowMapInfo != null) { columnCount = rowMapInfo.getColumnCount(); columnLabels = rowMapInfo.getColumnLabels(); methodNames = rowMapInfo.getMethodNames(); } } @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { T entity = constructorAccess.newInstance(); if (columnCount == 0) { ResultSetMetaData metaData = rs.getMetaData(); columnCount = metaData.getColumnCount(); columnLabels = new String[columnCount]; methodNames = new String[columnCount]; for (int c = 0; c < columnCount; c++) { String columnLabel = metaData.getColumnLabel(c + 1).toLowerCase(); columnLabels[c] = columnLabel; String methodName = "set" + CaseUtils.toCapCamelCase(columnLabel); methodNames[c] = methodName; methodAccess.invoke(entity, methodName, getResultSetValue(rs, c + 1)); } RowMapInfo rowMapInfo = new RowMapInfo(); rowMapInfo.setColumnCount(columnCount); rowMapInfo.setColumnLabels(columnLabels); rowMapInfo.setMethodNames(methodNames); RowMapInfoCache.getInstance().put(this.sql, rowMapInfo); } else { for (int c = 0; c < columnCount; c++) { methodAccess.invoke(entity, methodNames[c], getResultSetValue(rs, c + 1)); } } return entity; } public Object getResultSetValue(ResultSet rs, int index) throws SQLException { Object obj = rs.getObject(index); String className = null; if (obj != null) { className = obj.getClass().getName(); } if (obj instanceof Blob) { obj = rs.getBytes(index); } else if (obj instanceof Clob) { obj = rs.getString(index); } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className))) { obj = rs.getTimestamp(index); } else if (className != null && className.startsWith("oracle.sql.DATE")) { String metaDataClassName = rs.getMetaData().getColumnClassName(index); if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) { obj = rs.getTimestamp(index); } else { obj = rs.getDate(index); } } else if (obj != null && obj instanceof java.sql.Date) { if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) { obj = rs.getTimestamp(index); } } return obj; } }
UTF-8
Java
3,500
java
GenericRowMapper.java
Java
[ { "context": "Template 通用RowMapper,基于getter,setter实现。\n * @author yinlei\n * date 2013-6-25 下午10:20:06\n * @param <T> RowMap", "end": 477, "score": 0.9778600931167603, "start": 471, "tag": "USERNAME", "value": "yinlei" } ]
null
[]
package com.vteba.tx.jdbc.spring; import java.sql.Blob; import java.sql.Clob; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.vteba.lang.bytecode.ConstructorAccess; import com.vteba.lang.bytecode.MethodAccess; import com.vteba.utils.common.CaseUtils; import com.vteba.utils.reflection.AsmUtils; /** * Spring JdbcTemplate 通用RowMapper,基于getter,setter实现。 * @author yinlei * date 2013-6-25 下午10:20:06 * @param <T> RowMapper要转换的对象 */ public class GenericRowMapper<T> implements RowMapper<T> { private Class<T> resultClass; private ConstructorAccess<T> constructorAccess; private MethodAccess methodAccess; private int columnCount = 0; private String[] columnLabels; private String[] methodNames; private String sql; public GenericRowMapper(Class<T> resultClass, String sql) { this.resultClass = resultClass; this.sql = sql; constructorAccess = AsmUtils.get().createConstructorAccess(this.resultClass); methodAccess = AsmUtils.get().createMethodAccess(this.resultClass); RowMapInfo rowMapInfo = RowMapInfoCache.getInstance().get(this.sql); if (rowMapInfo != null) { columnCount = rowMapInfo.getColumnCount(); columnLabels = rowMapInfo.getColumnLabels(); methodNames = rowMapInfo.getMethodNames(); } } @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { T entity = constructorAccess.newInstance(); if (columnCount == 0) { ResultSetMetaData metaData = rs.getMetaData(); columnCount = metaData.getColumnCount(); columnLabels = new String[columnCount]; methodNames = new String[columnCount]; for (int c = 0; c < columnCount; c++) { String columnLabel = metaData.getColumnLabel(c + 1).toLowerCase(); columnLabels[c] = columnLabel; String methodName = "set" + CaseUtils.toCapCamelCase(columnLabel); methodNames[c] = methodName; methodAccess.invoke(entity, methodName, getResultSetValue(rs, c + 1)); } RowMapInfo rowMapInfo = new RowMapInfo(); rowMapInfo.setColumnCount(columnCount); rowMapInfo.setColumnLabels(columnLabels); rowMapInfo.setMethodNames(methodNames); RowMapInfoCache.getInstance().put(this.sql, rowMapInfo); } else { for (int c = 0; c < columnCount; c++) { methodAccess.invoke(entity, methodNames[c], getResultSetValue(rs, c + 1)); } } return entity; } public Object getResultSetValue(ResultSet rs, int index) throws SQLException { Object obj = rs.getObject(index); String className = null; if (obj != null) { className = obj.getClass().getName(); } if (obj instanceof Blob) { obj = rs.getBytes(index); } else if (obj instanceof Clob) { obj = rs.getString(index); } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className))) { obj = rs.getTimestamp(index); } else if (className != null && className.startsWith("oracle.sql.DATE")) { String metaDataClassName = rs.getMetaData().getColumnClassName(index); if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) { obj = rs.getTimestamp(index); } else { obj = rs.getDate(index); } } else if (obj != null && obj instanceof java.sql.Date) { if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) { obj = rs.getTimestamp(index); } } return obj; } }
3,500
0.718696
0.712926
103
32.650486
23.553989
95
false
false
0
0
0
0
0
0
2.572815
false
false
14
490d8e5a514de04c125dba71a6c7d3729461559a
23,673,859,744,212
f628ac876b63604686e9c170f452fe990dad8b66
/src/main/java/com/ig/ecommsolution/auth/controller/ContentController.java
1408b51437a8ec6843bfefade490ada0d0a1c989
[]
no_license
yashpal-singh/auth-project
https://github.com/yashpal-singh/auth-project
1cd6b5fafb201cebb236de729e5707cd77a6a63d
5b291bcc0ee14834968389bfd916c5ea24fdf0c1
refs/heads/master
2021-01-20T18:52:34.521000
2019-05-16T12:21:28
2019-05-16T12:21:28
61,112,211
2
0
null
false
2019-05-17T10:34:55
2016-06-14T10:03:08
2019-05-16T12:21:31
2019-05-17T10:34:41
24
1
0
1
Java
false
false
/** * */ package com.ig.ecommsolution.auth.controller; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.Date; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.ig.ecommsolution.auth.domain.User; import com.ig.ecommsolution.auth.repository.UserRepository; /** * @author Yashpal.Singh * */ @RestController public class ContentController { private String filePath = "D:\\Content"; @Autowired private UserRepository repository; @RequestMapping(value = "/files", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String addContent(@RequestParam("file") MultipartFile file) { try{ if(file != null && !file.isEmpty()) { String imageName = file.getOriginalFilename(); String extension = getExtension(imageName, "."); String newImageName = "user_" + new Date().getTime() + "." + extension; String location = filePath + "\\user\\image\\"; File imageFile = new File(location + newImageName); imageFile.mkdirs(); file.transferTo(imageFile); } } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/files", method = RequestMethod.GET) public void getContent(@RequestParam("path") String path, HttpServletResponse response) { InputStream inputStream = null; OutputStream outputStream = null; try{ File file = new File(filePath + path); // BufferedImage img = ImageIO.read(inputStream); // outputStream = new ByteArrayOutputStream(); // ImageIO.write(img, getExtension(file.getName(), "."), outputStream); // return new ResponseEntity<>(outputStream, HttpStatus.OK); response.setContentType(Files.probeContentType(file.toPath())); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName()); inputStream = Files.newInputStream(file.toPath()); outputStream = response.getOutputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try{ if(inputStream != null) inputStream.close(); if(outputStream != null) outputStream.close(); } catch(IOException iee) { iee.printStackTrace(); } } } @RequestMapping(value = "/image", method = RequestMethod.GET) public void getImage(HttpServletResponse response) { InputStream inputStream = null; OutputStream outputStream = null; try{ response.setContentType("image/jpeg"); outputStream = response.getOutputStream(); User user = repository.findOne("5746894c40e8874a110673e6"); inputStream = new ByteArrayInputStream(user.getImage()); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try{ if(inputStream != null) inputStream.close(); if(outputStream != null) outputStream.close(); } catch(IOException iee) { iee.printStackTrace(); } } } @RequestMapping(value = "/image", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String addImage(@RequestParam("file") MultipartFile file) { try{ if(file != null && !file.isEmpty()) { byte[] imageBytes = file.getBytes(); User user = repository.findOne("5746894c40e8874a110673e6"); user.setImage(imageBytes); repository.save(user); } } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return null; } public String getExtension(String name, String extensionSeparator) { int dotIndex = name.lastIndexOf(extensionSeparator); return name.substring(dotIndex + 1); } }
UTF-8
Java
4,973
java
ContentController.java
Java
[ { "context": "on.auth.repository.UserRepository;\n\n/**\n * @author Yashpal.Singh\n *\n */\n@RestController\npublic class ContentContro", "end": 849, "score": 0.9998658299446106, "start": 836, "tag": "NAME", "value": "Yashpal.Singh" }, { "context": "utputStream();\n\t\t\tUser user = repository.findOne(\"5746894c40e8874a110673e6\");\n\t\t\tinputStream = new ByteArrayInputStream(user", "end": 3545, "score": 0.8458946347236633, "start": 3521, "tag": "PASSWORD", "value": "5746894c40e8874a110673e6" }, { "context": ".getBytes();\n\t\t\t\tUser user = repository.findOne(\"5746894c40e8874a110673e6\");\n\t\t\t\tuser.setImage(imageBytes);\n\t\t\t\trepository.", "end": 4537, "score": 0.7759636640548706, "start": 4514, "tag": "PASSWORD", "value": "746894c40e8874a110673e6" } ]
null
[]
/** * */ package com.ig.ecommsolution.auth.controller; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.Date; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.ig.ecommsolution.auth.domain.User; import com.ig.ecommsolution.auth.repository.UserRepository; /** * @author Yashpal.Singh * */ @RestController public class ContentController { private String filePath = "D:\\Content"; @Autowired private UserRepository repository; @RequestMapping(value = "/files", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String addContent(@RequestParam("file") MultipartFile file) { try{ if(file != null && !file.isEmpty()) { String imageName = file.getOriginalFilename(); String extension = getExtension(imageName, "."); String newImageName = "user_" + new Date().getTime() + "." + extension; String location = filePath + "\\user\\image\\"; File imageFile = new File(location + newImageName); imageFile.mkdirs(); file.transferTo(imageFile); } } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/files", method = RequestMethod.GET) public void getContent(@RequestParam("path") String path, HttpServletResponse response) { InputStream inputStream = null; OutputStream outputStream = null; try{ File file = new File(filePath + path); // BufferedImage img = ImageIO.read(inputStream); // outputStream = new ByteArrayOutputStream(); // ImageIO.write(img, getExtension(file.getName(), "."), outputStream); // return new ResponseEntity<>(outputStream, HttpStatus.OK); response.setContentType(Files.probeContentType(file.toPath())); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName()); inputStream = Files.newInputStream(file.toPath()); outputStream = response.getOutputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try{ if(inputStream != null) inputStream.close(); if(outputStream != null) outputStream.close(); } catch(IOException iee) { iee.printStackTrace(); } } } @RequestMapping(value = "/image", method = RequestMethod.GET) public void getImage(HttpServletResponse response) { InputStream inputStream = null; OutputStream outputStream = null; try{ response.setContentType("image/jpeg"); outputStream = response.getOutputStream(); User user = repository.findOne("<PASSWORD>"); inputStream = new ByteArrayInputStream(user.getImage()); int read = 0; final byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try{ if(inputStream != null) inputStream.close(); if(outputStream != null) outputStream.close(); } catch(IOException iee) { iee.printStackTrace(); } } } @RequestMapping(value = "/image", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String addImage(@RequestParam("file") MultipartFile file) { try{ if(file != null && !file.isEmpty()) { byte[] imageBytes = file.getBytes(); User user = repository.findOne("5<PASSWORD>"); user.setImage(imageBytes); repository.save(user); } } catch(IOException ie) { ie.printStackTrace(); } catch(IllegalStateException ile) { ile.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return null; } public String getExtension(String name, String extensionSeparator) { int dotIndex = name.lastIndexOf(extensionSeparator); return name.substring(dotIndex + 1); } }
4,946
0.706616
0.695556
166
28.95783
25.683512
156
false
false
0
0
0
0
0
0
2.680723
false
false
14
a53f1e441e52f9b994f2644e86c88f8c1c138d96
12,360,915,885,504
63f8616bb86b617c9934b244c48ee3339f8afd0b
/app/src/main/java/kr/co/softcampus/how_do_i/ProfileChangeFragment.java
648d72dce7cfcedfd88845897ab01186407736e4
[]
no_license
sexyboy1315093/How_do_i
https://github.com/sexyboy1315093/How_do_i
3c80dfc94d985630fef87276ea541c9a1cb7e620
0f93d3fb0efdd47e52a535b467417e5f176eb0bf
refs/heads/master
2023-07-25T02:28:59.414000
2021-09-10T05:29:56
2021-09-10T05:29:56
404,966,904
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.softcampus.how_do_i; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.FileProvider; import androidx.fragment.app.DialogFragment; import androidx.loader.content.CursorLoader; import android.os.Environment; import android.provider.MediaStore; 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.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.theartofdev.edmodo.cropper.CropImage; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ProfileChangeFragment extends DialogFragment{ ImageView profile_camera; EditText edit_nickname; String dir_path; String pic_path; Uri contentUri; Button gallery; FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; FirebaseFirestore firebaseFirestore; DocumentReference documentReference; ProfileChangeFragment profileChangeFragment; public ProfileChangeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); firebaseAuth = FirebaseAuth.getInstance(); firebaseUser = firebaseAuth.getCurrentUser(); firebaseFirestore = FirebaseFirestore.getInstance(); } @NonNull @NotNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { HomeActivity activity = (HomeActivity) getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); profileChangeFragment = this; LayoutInflater inflater = getLayoutInflater(); View v1 = inflater.inflate(R.layout.fragment_profile_change,null); profile_camera = v1.findViewById(R.id.profile_camera); profile_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { init(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String file_name = "/temp_"+System.currentTimeMillis()+".jpg"; pic_path = dir_path+file_name; File file = new File(pic_path); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ contentUri = FileProvider.getUriForFile(getContext(),"kr.co.softcampus.how_do_i.file_provider",file); }else { contentUri = Uri.fromFile(file); } intent.putExtra(MediaStore.EXTRA_OUTPUT,contentUri); startActivityForResult(intent,2000); } }); gallery = v1.findViewById(R.id.gallery); gallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CropImage.activity() .start(getContext(),profileChangeFragment); } }); edit_nickname = v1.findViewById(R.id.edit_title); builder.setView(v1); builder.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(edit_nickname.getText().toString().length()!=0 && contentUri!=null ){ documentReference = firebaseFirestore.collection("loginUser").document(firebaseUser.getUid()); Map<String,Object> map = new HashMap<>(); map.put("name",edit_nickname.getText().toString()); map.put("profile",contentUri.getPath()); documentReference.update(map) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Toast.makeText(activity, "프로필을 등록했습니다", Toast.LENGTH_SHORT).show(); } }); }else { Toast.makeText(activity, "프로필 혹은 닉네임을 입력해주세요", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("취소",null); AlertDialog dialog = builder.create(); return dialog; } public void init(){ File f1 = Environment.getExternalStorageDirectory(); String a1 = f1.getAbsolutePath(); String a2 = getActivity().getPackageName(); dir_path = a1+"/android/data/"+a2; File file = new File(dir_path); if(file.exists()==false){ file.mkdir(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_profile_change, container, false); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) { super.onActivityResult(requestCode,resultCode,data); if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){ CropImage.ActivityResult result = CropImage.getActivityResult(data); if(resultCode==Activity.RESULT_OK){ contentUri = result.getUri(); Log.e("asdkljasld",contentUri.getPath()); Glide.with(getContext()).load(contentUri.getPath()).into(profile_camera); }else if(resultCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){ Exception error = result.getError(); } }else if(requestCode==2000){ if(resultCode==Activity.RESULT_OK){ Glide.with(getContext()).load(contentUri.getPath()).into(profile_camera); } } } }
UTF-8
Java
7,002
java
ProfileChangeFragment.java
Java
[ { "context": ".firebase.firestore.FirebaseFirestore;\nimport com.theartofdev.edmodo.cropper.CropImage;\n\nimport org.jetbrains.a", "end": 1413, "score": 0.8317410349845886, "start": 1402, "tag": "USERNAME", "value": "theartofdev" } ]
null
[]
package kr.co.softcampus.how_do_i; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.FileProvider; import androidx.fragment.app.DialogFragment; import androidx.loader.content.CursorLoader; import android.os.Environment; import android.provider.MediaStore; 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.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.theartofdev.edmodo.cropper.CropImage; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ProfileChangeFragment extends DialogFragment{ ImageView profile_camera; EditText edit_nickname; String dir_path; String pic_path; Uri contentUri; Button gallery; FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; FirebaseFirestore firebaseFirestore; DocumentReference documentReference; ProfileChangeFragment profileChangeFragment; public ProfileChangeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); firebaseAuth = FirebaseAuth.getInstance(); firebaseUser = firebaseAuth.getCurrentUser(); firebaseFirestore = FirebaseFirestore.getInstance(); } @NonNull @NotNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { HomeActivity activity = (HomeActivity) getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); profileChangeFragment = this; LayoutInflater inflater = getLayoutInflater(); View v1 = inflater.inflate(R.layout.fragment_profile_change,null); profile_camera = v1.findViewById(R.id.profile_camera); profile_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { init(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String file_name = "/temp_"+System.currentTimeMillis()+".jpg"; pic_path = dir_path+file_name; File file = new File(pic_path); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ contentUri = FileProvider.getUriForFile(getContext(),"kr.co.softcampus.how_do_i.file_provider",file); }else { contentUri = Uri.fromFile(file); } intent.putExtra(MediaStore.EXTRA_OUTPUT,contentUri); startActivityForResult(intent,2000); } }); gallery = v1.findViewById(R.id.gallery); gallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CropImage.activity() .start(getContext(),profileChangeFragment); } }); edit_nickname = v1.findViewById(R.id.edit_title); builder.setView(v1); builder.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(edit_nickname.getText().toString().length()!=0 && contentUri!=null ){ documentReference = firebaseFirestore.collection("loginUser").document(firebaseUser.getUid()); Map<String,Object> map = new HashMap<>(); map.put("name",edit_nickname.getText().toString()); map.put("profile",contentUri.getPath()); documentReference.update(map) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Toast.makeText(activity, "프로필을 등록했습니다", Toast.LENGTH_SHORT).show(); } }); }else { Toast.makeText(activity, "프로필 혹은 닉네임을 입력해주세요", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("취소",null); AlertDialog dialog = builder.create(); return dialog; } public void init(){ File f1 = Environment.getExternalStorageDirectory(); String a1 = f1.getAbsolutePath(); String a2 = getActivity().getPackageName(); dir_path = a1+"/android/data/"+a2; File file = new File(dir_path); if(file.exists()==false){ file.mkdir(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_profile_change, container, false); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) { super.onActivityResult(requestCode,resultCode,data); if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){ CropImage.ActivityResult result = CropImage.getActivityResult(data); if(resultCode==Activity.RESULT_OK){ contentUri = result.getUri(); Log.e("asdkljasld",contentUri.getPath()); Glide.with(getContext()).load(contentUri.getPath()).into(profile_camera); }else if(resultCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){ Exception error = result.getError(); } }else if(requestCode==2000){ if(resultCode==Activity.RESULT_OK){ Glide.with(getContext()).load(contentUri.getPath()).into(profile_camera); } } } }
7,002
0.647897
0.644873
192
35.171875
26.852541
126
false
false
0
0
0
0
0
0
0.677083
false
false
14
67f5b0e5468498edfa31c77a0b501ced7bc99a61
20,298,015,461,270
118c30b847d9fe96d1b1abc067eab28fe6084f1e
/src/main/java/com/ctg/flagadmin/config/InterceptorWebConfigurer.java
02daa2b20dd7006fd505a17808b7951b86ba8434
[]
no_license
TGclub/TGproject_flagadmin
https://github.com/TGclub/TGproject_flagadmin
cd97836b8377b55b981e0127a4c9abb8b0223937
9ef43c394439fc266a63d9ef5fffdaac80f3284a
refs/heads/master
2021-04-15T05:45:00.699000
2018-06-07T10:00:47
2018-06-07T10:00:47
126,584,400
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ctg.flagadmin.config; import com.ctg.flagadmin.web.interceptor.AuthenticationInterceptor; import com.ctg.flagadmin.web.interceptor.CouncilAuthorityInterceptor; import com.ctg.flagadmin.web.interceptor.PostMessageInterceptor; import com.ctg.flagadmin.web.interceptor.SpaceApplyAuthorityInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorWebConfigurer implements WebMvcConfigurer { private AuthenticationInterceptor authenticationInterceptor; private PostMessageInterceptor postMessageInterceptor; private CouncilAuthorityInterceptor councilAuthorityInterceptor; private SpaceApplyAuthorityInterceptor spaceApplyAuthorityInterceptor; public InterceptorWebConfigurer(AuthenticationInterceptor authenticationInterceptor, PostMessageInterceptor postMessageInterceptor, CouncilAuthorityInterceptor councilAuthorityInterceptor, SpaceApplyAuthorityInterceptor spaceApplyAuthorityInterceptor) { this.authenticationInterceptor = authenticationInterceptor; this.postMessageInterceptor = postMessageInterceptor; this.councilAuthorityInterceptor = councilAuthorityInterceptor; this.spaceApplyAuthorityInterceptor = spaceApplyAuthorityInterceptor; } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .exposedHeaders("authorization") .allowCredentials(false).maxAge(3600); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**").excludePathPatterns("/admin/login"); registry.addInterceptor(postMessageInterceptor).addPathPatterns("/message/**"); registry.addInterceptor(spaceApplyAuthorityInterceptor).addPathPatterns("/spaceApply/**"); registry.addInterceptor(councilAuthorityInterceptor).addPathPatterns("/councilOrder/**", "/place/council"); } }
UTF-8
Java
2,367
java
InterceptorWebConfigurer.java
Java
[]
null
[]
package com.ctg.flagadmin.config; import com.ctg.flagadmin.web.interceptor.AuthenticationInterceptor; import com.ctg.flagadmin.web.interceptor.CouncilAuthorityInterceptor; import com.ctg.flagadmin.web.interceptor.PostMessageInterceptor; import com.ctg.flagadmin.web.interceptor.SpaceApplyAuthorityInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorWebConfigurer implements WebMvcConfigurer { private AuthenticationInterceptor authenticationInterceptor; private PostMessageInterceptor postMessageInterceptor; private CouncilAuthorityInterceptor councilAuthorityInterceptor; private SpaceApplyAuthorityInterceptor spaceApplyAuthorityInterceptor; public InterceptorWebConfigurer(AuthenticationInterceptor authenticationInterceptor, PostMessageInterceptor postMessageInterceptor, CouncilAuthorityInterceptor councilAuthorityInterceptor, SpaceApplyAuthorityInterceptor spaceApplyAuthorityInterceptor) { this.authenticationInterceptor = authenticationInterceptor; this.postMessageInterceptor = postMessageInterceptor; this.councilAuthorityInterceptor = councilAuthorityInterceptor; this.spaceApplyAuthorityInterceptor = spaceApplyAuthorityInterceptor; } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .exposedHeaders("authorization") .allowCredentials(false).maxAge(3600); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**").excludePathPatterns("/admin/login"); registry.addInterceptor(postMessageInterceptor).addPathPatterns("/message/**"); registry.addInterceptor(spaceApplyAuthorityInterceptor).addPathPatterns("/spaceApply/**"); registry.addInterceptor(councilAuthorityInterceptor).addPathPatterns("/councilOrder/**", "/place/council"); } }
2,367
0.784537
0.782847
43
54.046513
40.259018
204
false
false
0
0
0
0
0
0
0.697674
false
false
14
6db195b3a3f2d6dea61961e4fcadafe62aa3ad4b
20,298,015,461,374
43a0eec7d9fd88878cf4acc911ce7f40900ec1ab
/src/main/javafx/config/MySQLConnectionSingleton.java
2acf6c8b08ebd77f7d8cf818057f56f7ca1e8802
[]
no_license
bruno-albino/clothestore-v2
https://github.com/bruno-albino/clothestore-v2
955972fe2ae5f2e66b0a142421e77ab2bb71ec22
6174ffde9643aa65a0bbe03f48542d2599928a80
refs/heads/master
2023-03-20T23:36:48.781000
2021-03-16T01:38:13
2021-03-16T01:38:13
348,177,072
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.javafx.config; import java.sql.Connection; import java.sql.DriverManager; import main.javafx.utils.WarningMessage; public final class MySQLConnectionSingleton implements IConnectionSingleton { private static MySQLConnectionSingleton instance = null; private static Connection connection = null; final private static String host = "localhost"; final private static String user = "root"; final private static String password = "masterkey"; private MySQLConnectionSingleton() { System.out.println("Conectando..."); try { Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); String url = "jdbc:mysql://" + host + "/clothestore?useTimezone=true&serverTimezone=UTC&user=" + user + "&password=" + password; connection = (Connection) DriverManager.getConnection(url); System.out.println("Connection opened"); } catch(Exception e) { System.out.println(e.toString()); WarningMessage.show("Ocorreu um erro inesperado. Por favor, reinicie o sistema."); } } public static MySQLConnectionSingleton getInstance() { if(instance == null) { instance = new MySQLConnectionSingleton(); } return instance; } public Connection getConnection() { return connection; } }
UTF-8
Java
1,256
java
MySQLConnectionSingleton.java
Java
[ { "context": "\"root\";\n \tfinal private static String password = \"masterkey\";\n \t\n \tprivate MySQLConnectionSingleton() {\n\t\tSys", "end": 458, "score": 0.9991000890731812, "start": 449, "tag": "PASSWORD", "value": "masterkey" } ]
null
[]
package main.javafx.config; import java.sql.Connection; import java.sql.DriverManager; import main.javafx.utils.WarningMessage; public final class MySQLConnectionSingleton implements IConnectionSingleton { private static MySQLConnectionSingleton instance = null; private static Connection connection = null; final private static String host = "localhost"; final private static String user = "root"; final private static String password = "<PASSWORD>"; private MySQLConnectionSingleton() { System.out.println("Conectando..."); try { Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); String url = "jdbc:mysql://" + host + "/clothestore?useTimezone=true&serverTimezone=UTC&user=" + user + "&password=" + password; connection = (Connection) DriverManager.getConnection(url); System.out.println("Connection opened"); } catch(Exception e) { System.out.println(e.toString()); WarningMessage.show("Ocorreu um erro inesperado. Por favor, reinicie o sistema."); } } public static MySQLConnectionSingleton getInstance() { if(instance == null) { instance = new MySQLConnectionSingleton(); } return instance; } public Connection getConnection() { return connection; } }
1,257
0.721338
0.721338
46
26.304348
23.154367
85
false
false
0
0
0
0
0
0
2.021739
false
false
14
46d5e61c84e08ac5039a0efdb50441ac1d588d7b
26,551,487,832,546
f83539da108b25481df60757ecca3e90b9d0e586
/src/Internal1.java
4fbc922025cf17a15d79edc96e2bbd955ec7d965
[]
no_license
KevinManjarrez/TAP_U1_Practica4
https://github.com/KevinManjarrez/TAP_U1_Practica4
00d78a92e55148074c3d0d37b577ad16520c5bd1
e898b35e42a5759326ab12b1536757d82337a3eb
refs/heads/master
2022-12-30T12:26:28.261000
2020-10-23T04:40:21
2020-10-23T04:40:21
306,528,984
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.KeyEvent; import javax.swing.JOptionPane; import static javax.swing.JOptionPane.showMessageDialog; import javax.swing.table.DefaultTableModel; /* * 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. */ /** * * @author Kevin Manjarrez */ public class Internal1 extends javax.swing.JInternalFrame { /** * Creates new form NewJInternalFrame */ public Internal1() { initComponents(); m = (DefaultTableModel) tblPredial.getModel(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblCodigoPostal = new javax.swing.JLabel(); lblClaveCatastral = new javax.swing.JLabel(); ftClaveCatastral = new javax.swing.JFormattedTextField(); ftCodigoPostal = new javax.swing.JFormattedTextField(); txtCalle = new javax.swing.JTextField(); lblCalle = new javax.swing.JLabel(); txtNumero = new javax.swing.JTextField(); lblNumero = new javax.swing.JLabel(); lblColonia = new javax.swing.JLabel(); txtColonia = new javax.swing.JTextField(); lblTituloDatosDomicilio = new javax.swing.JLabel(); btnGuardar = new javax.swing.JButton(); btnVaciarTabla = new javax.swing.JButton(); btnVaciarCampos = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); lblFrente = new javax.swing.JLabel(); txtArea = new javax.swing.JTextField(); lblArea = new javax.swing.JLabel(); lblFondo = new javax.swing.JLabel(); txtFrente = new javax.swing.JTextField(); txtFondo = new javax.swing.JTextField(); lblLote = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); lblServicios = new javax.swing.JLabel(); cmbServicios = new javax.swing.JComboBox<>(); jPanel4 = new javax.swing.JPanel(); txtCambio = new javax.swing.JFormattedTextField(); lblIVA = new javax.swing.JLabel(); lblTotal = new javax.swing.JLabel(); lblPago = new javax.swing.JLabel(); lblCambio = new javax.swing.JLabel(); chbHabilitar = new javax.swing.JCheckBox(); lblDescuento = new javax.swing.JLabel(); lblTotal2 = new javax.swing.JLabel(); txtSubtotal = new javax.swing.JFormattedTextField(); txtIVA = new javax.swing.JFormattedTextField(); txtTotal = new javax.swing.JFormattedTextField(); txtDescuento = new javax.swing.JTextField(); txtTotal2 = new javax.swing.JFormattedTextField(); txtPago = new javax.swing.JTextField(); lblSubTotal = new javax.swing.JLabel(); lblCobro = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tblPredial = new javax.swing.JTable(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setMaximizable(true); setResizable(true); setTitle("Formulario Catastro"); setToolTipText(""); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } }); jPanel1.setBackground(new java.awt.Color(0, 153, 153)); lblCodigoPostal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCodigoPostal.setText("Código Postal"); lblClaveCatastral.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblClaveCatastral.setText("Clave Catastral"); try { ftClaveCatastral.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("M###-###"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } ftClaveCatastral.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { ftClaveCatastralKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { ftClaveCatastralKeyReleased(evt); } }); try { ftCodigoPostal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } ftCodigoPostal.setText("#####"); ftCodigoPostal.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { ftCodigoPostalKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { ftCodigoPostalKeyReleased(evt); } }); txtCalle.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtCalle.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtCalleKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtCalleKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtCalleKeyTyped(evt); } }); lblCalle.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCalle.setText("Calle: "); txtNumero.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtNumero.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtNumeroKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtNumeroKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtNumeroKeyTyped(evt); } }); lblNumero.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblNumero.setText("Número de vivienda:"); lblColonia.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblColonia.setText("Colonia:"); txtColonia.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtColonia.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtColoniaKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtColoniaKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtColoniaKeyTyped(evt); } }); lblTituloDatosDomicilio.setBackground(new java.awt.Color(255, 255, 255)); lblTituloDatosDomicilio.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblTituloDatosDomicilio.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTituloDatosDomicilio.setText("Datos del domicilio."); lblTituloDatosDomicilio.setOpaque(true); btnGuardar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnGuardar.setText("Guardar"); btnGuardar.setEnabled(false); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnVaciarTabla.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnVaciarTabla.setText("Vaciar Tabla"); btnVaciarTabla.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVaciarTablaActionPerformed(evt); } }); btnVaciarCampos.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnVaciarCampos.setText("Vaciar campos"); btnVaciarCampos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVaciarCamposActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTituloDatosDomicilio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(58, 58, 58) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblClaveCatastral) .addComponent(lblCalle)) .addGap(50, 50, 50) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCalle) .addComponent(ftClaveCatastral, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblColonia) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblNumero) .addComponent(lblCodigoPostal)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtColonia) .addComponent(txtNumero) .addComponent(ftCodigoPostal, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnVaciarCampos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(167, 167, 167) .addComponent(btnVaciarTabla))) .addGap(0, 79, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblTituloDatosDomicilio, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblClaveCatastral) .addComponent(ftClaveCatastral, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCalle) .addComponent(txtCalle, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(lblNumero)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblColonia) .addComponent(txtColonia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblCodigoPostal) .addComponent(ftCodigoPostal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addComponent(btnGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnVaciarCampos) .addComponent(btnVaciarTabla)) .addContainerGap()) ); jPanel2.setBackground(new java.awt.Color(102, 102, 102)); lblFrente.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblFrente.setText("Frente:"); txtArea.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtArea.setEnabled(false); lblArea.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblArea.setText("Área:"); lblFondo.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblFondo.setText("Fondo"); txtFrente.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtFrente.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtFrenteKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtFrenteKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtFrenteKeyTyped(evt); } }); txtFondo.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtFondo.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtFondoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtFondoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtFondoKeyTyped(evt); } }); lblLote.setBackground(new java.awt.Color(255, 255, 255)); lblLote.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblLote.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLote.setText("Datos del Lote."); lblLote.setOpaque(true); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFrente) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFondo) .addComponent(lblArea)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtFondo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtFrente, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtArea, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(lblLote, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(lblLote) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFondo, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFrente, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtFrente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblArea) .addComponent(txtArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); lblServicios.setBackground(new java.awt.Color(255, 255, 255)); lblServicios.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblServicios.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblServicios.setText("Servicios."); lblServicios.setOpaque(true); cmbServicios.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N cmbServicios.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Elige el servicio:", "Agua", "Luz", "Drenaje" })); cmbServicios.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbServiciosActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(cmbServicios, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblServicios, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(cmbServicios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lblServicios) .addGap(0, 37, Short.MAX_VALUE))) ); jPanel4.setBackground(new java.awt.Color(0, 102, 102)); txtCambio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtCambio.setEnabled(false); txtCambio.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblIVA.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblIVA.setText("IVA:"); lblTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblTotal.setText("Total"); lblPago.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblPago.setText("Pago con:"); lblCambio.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCambio.setText("Cambio"); chbHabilitar.setText("Hablilitar descuento."); chbHabilitar.setEnabled(false); lblDescuento.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblDescuento.setText("Descuento: "); lblTotal2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblTotal2.setText("Total a pagar"); txtSubtotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtSubtotal.setEnabled(false); txtSubtotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtIVA.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtIVA.setEnabled(false); txtIVA.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtTotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtTotal.setEnabled(false); txtTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtDescuento.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtDescuento.setEnabled(false); txtDescuento.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtDescuentoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtDescuentoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtDescuentoKeyTyped(evt); } }); txtTotal2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtTotal2.setEnabled(false); txtTotal2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtPago.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtPago.setEnabled(false); txtPago.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPagoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtPagoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtPagoKeyTyped(evt); } }); lblSubTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblSubTotal.setText("Subtotal:"); lblCobro.setBackground(new java.awt.Color(255, 255, 255)); lblCobro.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblCobro.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblCobro.setText("Cobro."); lblCobro.setOpaque(true); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblSubTotal) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTotal) .addComponent(lblIVA)) .addGap(72, 72, 72) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtTotal) .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(lblDescuento)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTotal2) .addComponent(lblPago) .addComponent(lblCambio)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(txtTotal2)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(txtPago, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCambio, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(chbHabilitar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addComponent(lblCobro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblCobro) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTotal2) .addComponent(txtTotal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPago) .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblCambio) .addComponent(txtCambio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblSubTotal) .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addComponent(lblIVA) .addGap(8, 8, 8) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTotal) .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDescuento) .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chbHabilitar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5.setBackground(new java.awt.Color(0, 153, 153)); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Tabla de registros."); jLabel1.setOpaque(true); tblPredial.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N tblPredial.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Clave catastral", "Calle", "Número", "Colonia", "Código postal", "Fondo ", "Frente", "Área", "Subtotal", "IVA", "Total", "Descuento", "Total a pagar", "Pago", "Cambio" } )); tblPredial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblPredialMouseClicked(evt); } }); tblPredial.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { tblPredialKeyPressed(evt); } }); jScrollPane1.setViewportView(tblPredial); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(190, 190, 190)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed if (evt.getKeyCode() == KeyEvent.VK_DOWN) { ftClaveCatastral.requestFocus(); }//if. }//GEN-LAST:event_formKeyPressed private void ftClaveCatastralKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftClaveCatastralKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarClaveCatastral(ftClaveCatastral.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtCalle.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_ftClaveCatastralKeyPressed private void ftClaveCatastralKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftClaveCatastralKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_ftClaveCatastralKeyReleased private void txtCalleKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { calleVacia(txtCalle.getText()); } catch (Excepciones e) { e.getMessage(); }//catch }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtNumero.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtCalleKeyPressed private void txtCalleKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyReleased txtCalle.setText(txtCalle.getText().toUpperCase()); if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtCalleKeyReleased private void txtCalleKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !Character.isAlphabetic(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtCalleKeyTyped private void txtNumeroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { numeroVacio(txtNumero.getText()); } catch (Excepciones e) { e.getMessage(); }//if. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtCalle.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtColonia.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtNumeroKeyPressed private void txtNumeroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtNumeroKeyReleased private void txtNumeroKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtNumeroKeyTyped private void txtColoniaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { coloniaVacia(txtColonia.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtNumero.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { ftCodigoPostal.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtColoniaKeyPressed private void txtColoniaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyReleased txtColonia.setText(txtColonia.getText().toUpperCase()); if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtColoniaKeyReleased private void txtColoniaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !Character.isAlphabetic(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtColoniaKeyTyped private void ftCodigoPostalKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftCodigoPostalKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarCodigoPostal(ftCodigoPostal.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtColonia.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_ftCodigoPostalKeyPressed private void ftCodigoPostalKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftCodigoPostalKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_ftCodigoPostalKeyReleased private void txtFondoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { fondoVacio(txtFondo.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { ftCodigoPostal.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtFrente.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_LEFT) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtFondoKeyPressed private void txtFondoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { vaciarCuenta(); }//else. if (txtFrente.getText().isEmpty() || txtFondo.getText().isEmpty()) { vaciarCuenta(); }//if. if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { operaciones(); if (Float.parseFloat(txtFrente.getText()) == 0 || Float.parseFloat(txtFondo.getText()) == 0) { vaciarCuenta(); }//if. }//if. }//GEN-LAST:event_txtFondoKeyReleased private void txtFondoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); } }//GEN-LAST:event_txtFondoKeyTyped private void txtFrenteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { frenteVacio(txtFrente.getText()); } catch (Excepciones e) { e.getMessage(); }//catch }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_LEFT) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtFrenteKeyPressed private void txtFrenteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { vaciarCuenta(); } if (txtFrente.getText().isEmpty() || txtFondo.getText().isEmpty()) { vaciarCuenta(); } if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { operaciones(); if (Float.parseFloat(txtFrente.getText()) == 0 || Float.parseFloat(txtFondo.getText()) == 0) { vaciarCuenta(); } } }//GEN-LAST:event_txtFrenteKeyReleased private void txtFrenteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); } }//GEN-LAST:event_txtFrenteKeyTyped private void cmbServiciosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbServiciosActionPerformed int opcion = cmbServicios.getSelectedIndex(); switch(opcion){ case 1 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); break; }//if }//case 1. case 2 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//case 2. case 3 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//case 3. default -> { operaciones(); }//default. }//switch. }//GEN-LAST:event_cmbServiciosActionPerformed private void txtDescuentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarDescuento(txtDescuento.getText()); } catch (Excepciones e) { e.getMessage(); }//if. }//if if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtPago.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtDescuentoKeyPressed private void txtDescuentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyReleased if (txtDescuento.getText().length() > 0) { if (Float.parseFloat(txtDescuento.getText()) > 0 && Float.parseFloat(txtDescuento.getText()) <= 50) { descuento = total2 * (Float.parseFloat(txtDescuento.getText()) / 100); txtTotal2.setText((total2 - descuento) + ""); } else { txtTotal2.setText(total2 + ""); }//if. } else { txtTotal2.setText(total2 + ""); }//if. }//GEN-LAST:event_txtDescuentoKeyReleased private void txtDescuentoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyTyped if (txtDescuento.getText().length() == 2) { evt.consume(); }//if if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); }//if. }//GEN-LAST:event_txtDescuentoKeyTyped private void txtPagoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarPago(txtPago.getText()); } catch (Excepciones e) { e.getMessage(); } } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtDescuento.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); } }//GEN-LAST:event_txtPagoKeyPressed private void txtPagoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyReleased if (txtPago.getText().length() > 0) { if (Float.parseFloat(txtPago.getText()) >= total2) { pago = Float.parseFloat(txtPago.getText()); cambio = pago - Float.parseFloat(txtTotal2.getText()); if(cambio>=0){ txtCambio.setText(cambio + ""); } } else { txtCambio.setText(""); } } else { txtCambio.setText(""); } }//GEN-LAST:event_txtPagoKeyReleased private void txtPagoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); }//if. }//GEN-LAST:event_txtPagoKeyTyped private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed if (btnGuardar.isEnabled()) { chbHabilitar.setEnabled(true); txtPago.setEnabled(true); } if (camposLlenos2() == true) { camposVaciosExcepciones2(); Object O[] =new Object[15]; O[0]=ftClaveCatastral.getText(); O[1]=txtCalle.getText(); O[2]=txtNumero.getText(); O[3]=txtColonia.getText(); O[4]=ftCodigoPostal.getText(); O[5]=txtFondo.getText(); O[6]=txtFrente.getText(); O[7]=txtArea.getText(); O[8]=txtSubtotal.getText(); O[9]=txtIVA.getText(); O[10]=txtTotal.getText(); O[11]=txtDescuento.getText(); O[12]=txtTotal2.getText(); O[13]=txtPago.getText(); O[14]=txtCambio.getText(); m.addRow(O); showMessageDialog(this, "Registro guardado.", "Predial", JOptionPane.INFORMATION_MESSAGE); llenarTabla(); vaciarCampos(); } else { showMessageDialog(this, "No se pudo guardar el registro. ", "Predial.", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_btnGuardarActionPerformed private void tblPredialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblPredialKeyPressed int r = tblPredial.getSelectedRow(); if (evt.getKeyCode() == 8) { int dialogo = JOptionPane.showConfirmDialog(null, "¿Esta seguro?", "Alerta!", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (dialogo == JOptionPane.YES_OPTION) { try { m.removeRow(r); showMessageDialog(this, "Fila borrada exitosamente.", "Aviso", JOptionPane.INFORMATION_MESSAGE); //i.vaciarCampos(); } catch (ArrayIndexOutOfBoundsException ex) { showMessageDialog(this, "No has seleccionado el registro.", "Tabla.", JOptionPane.INFORMATION_MESSAGE); }//catch }//if. }//if. }//GEN-LAST:event_tblPredialKeyPressed private void tblPredialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPredialMouseClicked int r = tblPredial.getSelectedRow(); ftClaveCatastral.setText(m.getValueAt(r, 0).toString()); txtCalle.setText(m.getValueAt(r, 1).toString()); txtNumero.setText(m.getValueAt(r, 2).toString()); txtColonia.setText(m.getValueAt(r, 3).toString()); ftCodigoPostal.setText(m.getValueAt(r, 4).toString()); txtFrente.setText(m.getValueAt(r, 5).toString()); txtFondo.setText(m.getValueAt(r, 6).toString()); txtArea.setText(m.getValueAt(r, 7).toString()); txtSubtotal.setText(m.getValueAt(r, 8).toString()); txtIVA.setText(m.getValueAt(r, 9).toString()); txtTotal.setText(m.getValueAt(r, 10).toString()); txtDescuento.setText(m.getValueAt(r, 11).toString()); txtTotal2.setText(m.getValueAt(r, 12).toString()); txtPago.setText(m.getValueAt(r, 13).toString()); txtCambio.setText(m.getValueAt(r, 14).toString()); btnGuardar.setEnabled(true); txtPago.setEnabled(true); }//GEN-LAST:event_tblPredialMouseClicked private void btnVaciarCamposActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVaciarCamposActionPerformed vaciarCampos(); }//GEN-LAST:event_btnVaciarCamposActionPerformed private void btnVaciarTablaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVaciarTablaActionPerformed if (m.getRowCount() > 0) { int a = m.getRowCount() - 1; for (int i = a; i >= 0; i--) { m.removeRow(i); }//for. showMessageDialog(this, "Registros removidos con éxito", "Tabla.", JOptionPane.INFORMATION_MESSAGE); } else { showMessageDialog(this, "No existen registros por eliminar.", "Tabla.", JOptionPane.INFORMATION_MESSAGE); }//else. }//GEN-LAST:event_btnVaciarTablaActionPerformed public void validarClaveCatastral(String c) throws Excepciones { if (!c.matches("[M]+\\d{3}+[-]+\\d{3}")) { showMessageDialog(this, "Formato: M###-###", "Clave catastral.", JOptionPane.ERROR_MESSAGE); ftClaveCatastral.requestFocus(); }//if. else { txtCalle.requestFocus(); }//else. }//claveCatastral. public void calleVacia(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado la calle.", "Calle.", JOptionPane.INFORMATION_MESSAGE); txtCalle.requestFocus(); } else if (!c.isEmpty()) { txtNumero.requestFocus(); }//else if. }//calleVacia. public void numeroVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el número de la vivienda.", "Número.", JOptionPane.INFORMATION_MESSAGE); txtNumero.requestFocus(); } else if (!c.isEmpty()) { txtColonia.requestFocus(); }//else if. }//numeroVacio. public void coloniaVacia(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado la colonia.", "Colonia.", JOptionPane.INFORMATION_MESSAGE); txtColonia.requestFocus(); } else if (!c.isEmpty()) { ftCodigoPostal.requestFocus(); }//else if. }//coloniaVacia. public void validarCodigoPostal(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el código postal.", "Código Postal.", JOptionPane.INFORMATION_MESSAGE); ftCodigoPostal.requestFocus(); } else if (c.length() < 5) { showMessageDialog(this, "Son cinco dígitos.", "Código Postal.", JOptionPane.WARNING_MESSAGE); ftCodigoPostal.requestFocus(); } else if (!c.isEmpty()) { txtFondo.requestFocus(); }//else if. }//validarCodigoPostal. public void fondoVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el fondo.", "Fondo.", JOptionPane.INFORMATION_MESSAGE); txtFondo.requestFocus(); } else if (!c.isEmpty()) { txtFrente.requestFocus(); }//else if. }//fondoVacio. public void frenteVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el frente.", "Frente.", JOptionPane.INFORMATION_MESSAGE); txtFrente.requestFocus(); }//if. }//frenteVacio. public void validarDescuento(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el descuento", "Descuento.", JOptionPane.INFORMATION_MESSAGE); txtDescuento.requestFocus(); } else if (Float.parseFloat(c) <= 0 || Float.parseFloat(c) > 50) { showMessageDialog(this, "Sólo se admite de 1-50 % de descuento.", "Descuento.", JOptionPane.WARNING_MESSAGE); txtDescuento.requestFocus(); } else if (!c.isEmpty()) { txtPago.requestFocus(); }//else if. }//validarDescuento. public void validarPago(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el pago", "Pago.", JOptionPane.INFORMATION_MESSAGE); txtDescuento.requestFocus(); } else if (Float.parseFloat(c) < Float.parseFloat(txtTotal2.getText())) { showMessageDialog(this, "Cantidad menor a la requerida.", "Pagar", JOptionPane.WARNING_MESSAGE); txtDescuento.requestFocus(); } else if (!c.isEmpty() && (Float.parseFloat(c) >= Float.parseFloat(txtTotal2.getText()))) { btnGuardar.requestFocus(); }//else if. }//valildarPago. public void vaciarCuenta() { txtArea.setText(""); txtSubtotal.setText(""); txtIVA.setText(""); txtTotal.setText(""); txtDescuento.setText(""); txtTotal2.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setEnabled(false); chbHabilitar.setSelected(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); }//vaciarCuenta. public void inhabilitar() { txtDescuento.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setSelected(false); chbHabilitar.setEnabled(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); }//inhabilitar. public void operaciones() { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { area = Float.parseFloat(txtFrente.getText()) * Float.parseFloat(txtFondo.getText()); txtArea.setText(area + ""); subtotal = area * 2; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//operaciones. public boolean camposLlenos() { return (!(ftClaveCatastral.getText().isEmpty()) && (ftClaveCatastral.getText().matches("[M]+\\d{3}+[-]+\\d{3}")) && !(txtCalle.getText().isEmpty()) && !(txtNumero.getText().isEmpty()) && !(txtColonia.getText().isEmpty()) && !(ftCodigoPostal.getText().isEmpty()) && (ftCodigoPostal.getText().length() == 5) && !(txtFondo.getText().isEmpty()) && !(txtFrente.getText().isEmpty())); }//camposLlenos. public void camposVaciosExcepciones2() { try { validarClaveCatastral(ftClaveCatastral.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { calleVacia(txtCalle.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { numeroVacio(txtNumero.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { coloniaVacia(txtColonia.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { validarCodigoPostal(ftCodigoPostal.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { fondoVacio(txtFondo.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { frenteVacio(txtFrente.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { validarPago(txtPago.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//camposVaciosExcepciones2. public boolean camposLlenos2() { return (!(ftClaveCatastral.getText().isEmpty()) && (ftClaveCatastral.getText().matches("[M]+\\d{3}+[-]+\\d{3}")) && !(txtCalle.getText().isEmpty()) && !(txtNumero.getText().isEmpty()) && !(txtColonia.getText().isEmpty()) && !(ftCodigoPostal.getText().isEmpty()) && (ftCodigoPostal.getText().length() == 5) && !(txtFondo.getText().isEmpty()) && !(txtFrente.getText().isEmpty()) && !(txtPago.getText().isEmpty()) && !(txtCambio.getText().isEmpty())); }//campsoLLenos2. private void llenarTabla() { for (int i = 0; i < a; i++) { m.setValueAt(ftClaveCatastral.getText(), i, 0); m.setValueAt(txtCalle.getText(), i, 1); m.setValueAt(txtNumero.getText(), i, 2); m.setValueAt(txtColonia.getText(), i, 3); m.setValueAt(ftCodigoPostal.getText(), i, 4); m.setValueAt(txtFondo.getText(), i, 5); m.setValueAt(txtFrente.getText(), i, 6); m.setValueAt(txtArea.getText(), i, 7); m.setValueAt(txtSubtotal.getText(), i, 8); m.setValueAt(txtIVA.getText(), i, 9); m.setValueAt(txtTotal.getText(), i, 10); m.setValueAt(txtDescuento.getText(), i, 11); m.setValueAt(txtTotal2.getText(), i, 12); m.setValueAt(txtPago.getText(), i, 13); m.setValueAt(txtCambio.getText(), i, 14); }//for. }//llenarTabla. public void vaciarCampos() { ftClaveCatastral.setText(""); txtCalle.setText(""); txtNumero.setText(""); txtColonia.setText(""); ftCodigoPostal.setText(""); txtFrente.setText(""); txtFondo.setText(""); txtArea.setText(""); txtSubtotal.setText(""); txtIVA.setText(""); txtTotal.setText(""); txtDescuento.setText(""); txtTotal2.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setEnabled(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); chbHabilitar.setSelected(false); }//vaciarCampos. protected DefaultTableModel m; protected int a; protected int b; protected int c; protected float impuesto; protected float area; protected float subtotal; protected float iva; protected float total; protected float descuento; protected float total2; protected float pago; protected float cambio; // Variables declaration - do not modify//GEN-BEGIN:variables protected javax.swing.JButton btnGuardar; protected javax.swing.JButton btnVaciarCampos; protected javax.swing.JButton btnVaciarTabla; protected javax.swing.JCheckBox chbHabilitar; protected javax.swing.JComboBox<String> cmbServicios; protected javax.swing.JFormattedTextField ftClaveCatastral; protected javax.swing.JFormattedTextField ftCodigoPostal; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; protected javax.swing.JLabel lblArea; protected javax.swing.JLabel lblCalle; protected javax.swing.JLabel lblCambio; protected javax.swing.JLabel lblClaveCatastral; protected javax.swing.JLabel lblCobro; protected javax.swing.JLabel lblCodigoPostal; protected javax.swing.JLabel lblColonia; protected javax.swing.JLabel lblDescuento; protected javax.swing.JLabel lblFondo; protected javax.swing.JLabel lblFrente; protected javax.swing.JLabel lblIVA; protected javax.swing.JLabel lblLote; protected javax.swing.JLabel lblNumero; protected javax.swing.JLabel lblPago; protected javax.swing.JLabel lblServicios; protected javax.swing.JLabel lblSubTotal; protected javax.swing.JLabel lblTituloDatosDomicilio; protected javax.swing.JLabel lblTotal; protected javax.swing.JLabel lblTotal2; private javax.swing.JTable tblPredial; protected javax.swing.JTextField txtArea; protected javax.swing.JTextField txtCalle; protected javax.swing.JFormattedTextField txtCambio; protected javax.swing.JTextField txtColonia; protected javax.swing.JTextField txtDescuento; protected javax.swing.JTextField txtFondo; protected javax.swing.JTextField txtFrente; protected javax.swing.JFormattedTextField txtIVA; protected javax.swing.JTextField txtNumero; protected javax.swing.JTextField txtPago; protected javax.swing.JFormattedTextField txtSubtotal; protected javax.swing.JFormattedTextField txtTotal; protected javax.swing.JFormattedTextField txtTotal2; // End of variables declaration//GEN-END:variables }
UTF-8
Java
70,449
java
Internal1.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author Kevin Manjarrez\n */\npublic class Internal1 extends javax.swing.JI", "end": 389, "score": 0.9998788833618164, "start": 374, "tag": "NAME", "value": "Kevin Manjarrez" } ]
null
[]
import java.awt.event.KeyEvent; import javax.swing.JOptionPane; import static javax.swing.JOptionPane.showMessageDialog; import javax.swing.table.DefaultTableModel; /* * 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. */ /** * * @author <NAME> */ public class Internal1 extends javax.swing.JInternalFrame { /** * Creates new form NewJInternalFrame */ public Internal1() { initComponents(); m = (DefaultTableModel) tblPredial.getModel(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblCodigoPostal = new javax.swing.JLabel(); lblClaveCatastral = new javax.swing.JLabel(); ftClaveCatastral = new javax.swing.JFormattedTextField(); ftCodigoPostal = new javax.swing.JFormattedTextField(); txtCalle = new javax.swing.JTextField(); lblCalle = new javax.swing.JLabel(); txtNumero = new javax.swing.JTextField(); lblNumero = new javax.swing.JLabel(); lblColonia = new javax.swing.JLabel(); txtColonia = new javax.swing.JTextField(); lblTituloDatosDomicilio = new javax.swing.JLabel(); btnGuardar = new javax.swing.JButton(); btnVaciarTabla = new javax.swing.JButton(); btnVaciarCampos = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); lblFrente = new javax.swing.JLabel(); txtArea = new javax.swing.JTextField(); lblArea = new javax.swing.JLabel(); lblFondo = new javax.swing.JLabel(); txtFrente = new javax.swing.JTextField(); txtFondo = new javax.swing.JTextField(); lblLote = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); lblServicios = new javax.swing.JLabel(); cmbServicios = new javax.swing.JComboBox<>(); jPanel4 = new javax.swing.JPanel(); txtCambio = new javax.swing.JFormattedTextField(); lblIVA = new javax.swing.JLabel(); lblTotal = new javax.swing.JLabel(); lblPago = new javax.swing.JLabel(); lblCambio = new javax.swing.JLabel(); chbHabilitar = new javax.swing.JCheckBox(); lblDescuento = new javax.swing.JLabel(); lblTotal2 = new javax.swing.JLabel(); txtSubtotal = new javax.swing.JFormattedTextField(); txtIVA = new javax.swing.JFormattedTextField(); txtTotal = new javax.swing.JFormattedTextField(); txtDescuento = new javax.swing.JTextField(); txtTotal2 = new javax.swing.JFormattedTextField(); txtPago = new javax.swing.JTextField(); lblSubTotal = new javax.swing.JLabel(); lblCobro = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tblPredial = new javax.swing.JTable(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setMaximizable(true); setResizable(true); setTitle("Formulario Catastro"); setToolTipText(""); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } }); jPanel1.setBackground(new java.awt.Color(0, 153, 153)); lblCodigoPostal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCodigoPostal.setText("Código Postal"); lblClaveCatastral.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblClaveCatastral.setText("Clave Catastral"); try { ftClaveCatastral.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("M###-###"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } ftClaveCatastral.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { ftClaveCatastralKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { ftClaveCatastralKeyReleased(evt); } }); try { ftCodigoPostal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } ftCodigoPostal.setText("#####"); ftCodigoPostal.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { ftCodigoPostalKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { ftCodigoPostalKeyReleased(evt); } }); txtCalle.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtCalle.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtCalleKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtCalleKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtCalleKeyTyped(evt); } }); lblCalle.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCalle.setText("Calle: "); txtNumero.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtNumero.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtNumeroKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtNumeroKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtNumeroKeyTyped(evt); } }); lblNumero.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblNumero.setText("Número de vivienda:"); lblColonia.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblColonia.setText("Colonia:"); txtColonia.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtColonia.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtColoniaKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtColoniaKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtColoniaKeyTyped(evt); } }); lblTituloDatosDomicilio.setBackground(new java.awt.Color(255, 255, 255)); lblTituloDatosDomicilio.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblTituloDatosDomicilio.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTituloDatosDomicilio.setText("Datos del domicilio."); lblTituloDatosDomicilio.setOpaque(true); btnGuardar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnGuardar.setText("Guardar"); btnGuardar.setEnabled(false); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnVaciarTabla.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnVaciarTabla.setText("Vaciar Tabla"); btnVaciarTabla.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVaciarTablaActionPerformed(evt); } }); btnVaciarCampos.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N btnVaciarCampos.setText("Vaciar campos"); btnVaciarCampos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVaciarCamposActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTituloDatosDomicilio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(58, 58, 58) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblClaveCatastral) .addComponent(lblCalle)) .addGap(50, 50, 50) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCalle) .addComponent(ftClaveCatastral, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblColonia) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblNumero) .addComponent(lblCodigoPostal)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtColonia) .addComponent(txtNumero) .addComponent(ftCodigoPostal, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnVaciarCampos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(167, 167, 167) .addComponent(btnVaciarTabla))) .addGap(0, 79, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblTituloDatosDomicilio, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblClaveCatastral) .addComponent(ftClaveCatastral, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCalle) .addComponent(txtCalle, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(lblNumero)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblColonia) .addComponent(txtColonia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblCodigoPostal) .addComponent(ftCodigoPostal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addComponent(btnGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnVaciarCampos) .addComponent(btnVaciarTabla)) .addContainerGap()) ); jPanel2.setBackground(new java.awt.Color(102, 102, 102)); lblFrente.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblFrente.setText("Frente:"); txtArea.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtArea.setEnabled(false); lblArea.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblArea.setText("Área:"); lblFondo.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblFondo.setText("Fondo"); txtFrente.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtFrente.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtFrenteKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtFrenteKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtFrenteKeyTyped(evt); } }); txtFondo.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtFondo.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtFondoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtFondoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtFondoKeyTyped(evt); } }); lblLote.setBackground(new java.awt.Color(255, 255, 255)); lblLote.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblLote.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLote.setText("Datos del Lote."); lblLote.setOpaque(true); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFrente) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFondo) .addComponent(lblArea)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtFondo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtFrente, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtArea, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(lblLote, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(lblLote) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFondo, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFrente, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtFrente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblArea) .addComponent(txtArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); lblServicios.setBackground(new java.awt.Color(255, 255, 255)); lblServicios.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblServicios.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblServicios.setText("Servicios."); lblServicios.setOpaque(true); cmbServicios.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N cmbServicios.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Elige el servicio:", "Agua", "Luz", "Drenaje" })); cmbServicios.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbServiciosActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(cmbServicios, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblServicios, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(cmbServicios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lblServicios) .addGap(0, 37, Short.MAX_VALUE))) ); jPanel4.setBackground(new java.awt.Color(0, 102, 102)); txtCambio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtCambio.setEnabled(false); txtCambio.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblIVA.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblIVA.setText("IVA:"); lblTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblTotal.setText("Total"); lblPago.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblPago.setText("Pago con:"); lblCambio.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblCambio.setText("Cambio"); chbHabilitar.setText("Hablilitar descuento."); chbHabilitar.setEnabled(false); lblDescuento.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblDescuento.setText("Descuento: "); lblTotal2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblTotal2.setText("Total a pagar"); txtSubtotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtSubtotal.setEnabled(false); txtSubtotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtIVA.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtIVA.setEnabled(false); txtIVA.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtTotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtTotal.setEnabled(false); txtTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtDescuento.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtDescuento.setEnabled(false); txtDescuento.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtDescuentoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtDescuentoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtDescuentoKeyTyped(evt); } }); txtTotal2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00 $")))); txtTotal2.setEnabled(false); txtTotal2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtPago.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtPago.setEnabled(false); txtPago.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPagoKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { txtPagoKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtPagoKeyTyped(evt); } }); lblSubTotal.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lblSubTotal.setText("Subtotal:"); lblCobro.setBackground(new java.awt.Color(255, 255, 255)); lblCobro.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N lblCobro.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblCobro.setText("Cobro."); lblCobro.setOpaque(true); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblSubTotal) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTotal) .addComponent(lblIVA)) .addGap(72, 72, 72) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtTotal) .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(lblDescuento)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTotal2) .addComponent(lblPago) .addComponent(lblCambio)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(txtTotal2)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(txtPago, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCambio, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(chbHabilitar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addComponent(lblCobro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblCobro) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTotal2) .addComponent(txtTotal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPago) .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblCambio) .addComponent(txtCambio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblSubTotal) .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addComponent(lblIVA) .addGap(8, 8, 8) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTotal) .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblDescuento) .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chbHabilitar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5.setBackground(new java.awt.Color(0, 153, 153)); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Tabla de registros."); jLabel1.setOpaque(true); tblPredial.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N tblPredial.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Clave catastral", "Calle", "Número", "Colonia", "Código postal", "Fondo ", "Frente", "Área", "Subtotal", "IVA", "Total", "Descuento", "Total a pagar", "Pago", "Cambio" } )); tblPredial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblPredialMouseClicked(evt); } }); tblPredial.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { tblPredialKeyPressed(evt); } }); jScrollPane1.setViewportView(tblPredial); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(190, 190, 190)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed if (evt.getKeyCode() == KeyEvent.VK_DOWN) { ftClaveCatastral.requestFocus(); }//if. }//GEN-LAST:event_formKeyPressed private void ftClaveCatastralKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftClaveCatastralKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarClaveCatastral(ftClaveCatastral.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtCalle.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_ftClaveCatastralKeyPressed private void ftClaveCatastralKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftClaveCatastralKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_ftClaveCatastralKeyReleased private void txtCalleKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { calleVacia(txtCalle.getText()); } catch (Excepciones e) { e.getMessage(); }//catch }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtNumero.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtCalleKeyPressed private void txtCalleKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyReleased txtCalle.setText(txtCalle.getText().toUpperCase()); if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtCalleKeyReleased private void txtCalleKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCalleKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !Character.isAlphabetic(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtCalleKeyTyped private void txtNumeroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { numeroVacio(txtNumero.getText()); } catch (Excepciones e) { e.getMessage(); }//if. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtCalle.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtColonia.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtNumeroKeyPressed private void txtNumeroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtNumeroKeyReleased private void txtNumeroKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtNumeroKeyTyped private void txtColoniaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { coloniaVacia(txtColonia.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtNumero.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { ftCodigoPostal.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtColoniaKeyPressed private void txtColoniaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyReleased txtColonia.setText(txtColonia.getText().toUpperCase()); if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_txtColoniaKeyReleased private void txtColoniaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtColoniaKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !Character.isAlphabetic(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_SPACE)) { evt.consume(); }//if. }//GEN-LAST:event_txtColoniaKeyTyped private void ftCodigoPostalKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftCodigoPostalKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarCodigoPostal(ftCodigoPostal.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtColonia.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_RIGHT) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_ftCodigoPostalKeyPressed private void ftCodigoPostalKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftCodigoPostalKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { inhabilitar(); }//else. }//GEN-LAST:event_ftCodigoPostalKeyReleased private void txtFondoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { fondoVacio(txtFondo.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { ftCodigoPostal.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtFrente.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_LEFT) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtFondoKeyPressed private void txtFondoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { vaciarCuenta(); }//else. if (txtFrente.getText().isEmpty() || txtFondo.getText().isEmpty()) { vaciarCuenta(); }//if. if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { operaciones(); if (Float.parseFloat(txtFrente.getText()) == 0 || Float.parseFloat(txtFondo.getText()) == 0) { vaciarCuenta(); }//if. }//if. }//GEN-LAST:event_txtFondoKeyReleased private void txtFondoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFondoKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); } }//GEN-LAST:event_txtFondoKeyTyped private void txtFrenteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { frenteVacio(txtFrente.getText()); } catch (Excepciones e) { e.getMessage(); }//catch }//if. if (evt.getKeyCode() == KeyEvent.VK_UP) { txtFondo.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_LEFT) { ftClaveCatastral.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtFrenteKeyPressed private void txtFrenteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyReleased if (camposLlenos() == true) { btnGuardar.setEnabled(true); txtPago.setEnabled(true); chbHabilitar.setEnabled(true); } else { vaciarCuenta(); } if (txtFrente.getText().isEmpty() || txtFondo.getText().isEmpty()) { vaciarCuenta(); } if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { operaciones(); if (Float.parseFloat(txtFrente.getText()) == 0 || Float.parseFloat(txtFondo.getText()) == 0) { vaciarCuenta(); } } }//GEN-LAST:event_txtFrenteKeyReleased private void txtFrenteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFrenteKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); } }//GEN-LAST:event_txtFrenteKeyTyped private void cmbServiciosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbServiciosActionPerformed int opcion = cmbServicios.getSelectedIndex(); switch(opcion){ case 1 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); break; }//if }//case 1. case 2 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//case 2. case 3 -> { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { impuesto = (float) (subtotal * .10); subtotal = subtotal + impuesto; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//case 3. default -> { operaciones(); }//default. }//switch. }//GEN-LAST:event_cmbServiciosActionPerformed private void txtDescuentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarDescuento(txtDescuento.getText()); } catch (Excepciones e) { e.getMessage(); }//if. }//if if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtPago.requestFocus(); }//if. if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); }//if. }//GEN-LAST:event_txtDescuentoKeyPressed private void txtDescuentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyReleased if (txtDescuento.getText().length() > 0) { if (Float.parseFloat(txtDescuento.getText()) > 0 && Float.parseFloat(txtDescuento.getText()) <= 50) { descuento = total2 * (Float.parseFloat(txtDescuento.getText()) / 100); txtTotal2.setText((total2 - descuento) + ""); } else { txtTotal2.setText(total2 + ""); }//if. } else { txtTotal2.setText(total2 + ""); }//if. }//GEN-LAST:event_txtDescuentoKeyReleased private void txtDescuentoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoKeyTyped if (txtDescuento.getText().length() == 2) { evt.consume(); }//if if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); }//if. }//GEN-LAST:event_txtDescuentoKeyTyped private void txtPagoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { try { validarPago(txtPago.getText()); } catch (Excepciones e) { e.getMessage(); } } if (evt.getKeyCode() == KeyEvent.VK_DOWN) { txtDescuento.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { super.requestFocus(); } }//GEN-LAST:event_txtPagoKeyPressed private void txtPagoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyReleased if (txtPago.getText().length() > 0) { if (Float.parseFloat(txtPago.getText()) >= total2) { pago = Float.parseFloat(txtPago.getText()); cambio = pago - Float.parseFloat(txtTotal2.getText()); if(cambio>=0){ txtCambio.setText(cambio + ""); } } else { txtCambio.setText(""); } } else { txtCambio.setText(""); } }//GEN-LAST:event_txtPagoKeyReleased private void txtPagoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPagoKeyTyped if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE) && !(evt.getKeyChar() == KeyEvent.VK_PERIOD)) { evt.consume(); }//if. }//GEN-LAST:event_txtPagoKeyTyped private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed if (btnGuardar.isEnabled()) { chbHabilitar.setEnabled(true); txtPago.setEnabled(true); } if (camposLlenos2() == true) { camposVaciosExcepciones2(); Object O[] =new Object[15]; O[0]=ftClaveCatastral.getText(); O[1]=txtCalle.getText(); O[2]=txtNumero.getText(); O[3]=txtColonia.getText(); O[4]=ftCodigoPostal.getText(); O[5]=txtFondo.getText(); O[6]=txtFrente.getText(); O[7]=txtArea.getText(); O[8]=txtSubtotal.getText(); O[9]=txtIVA.getText(); O[10]=txtTotal.getText(); O[11]=txtDescuento.getText(); O[12]=txtTotal2.getText(); O[13]=txtPago.getText(); O[14]=txtCambio.getText(); m.addRow(O); showMessageDialog(this, "Registro guardado.", "Predial", JOptionPane.INFORMATION_MESSAGE); llenarTabla(); vaciarCampos(); } else { showMessageDialog(this, "No se pudo guardar el registro. ", "Predial.", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_btnGuardarActionPerformed private void tblPredialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblPredialKeyPressed int r = tblPredial.getSelectedRow(); if (evt.getKeyCode() == 8) { int dialogo = JOptionPane.showConfirmDialog(null, "¿Esta seguro?", "Alerta!", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (dialogo == JOptionPane.YES_OPTION) { try { m.removeRow(r); showMessageDialog(this, "Fila borrada exitosamente.", "Aviso", JOptionPane.INFORMATION_MESSAGE); //i.vaciarCampos(); } catch (ArrayIndexOutOfBoundsException ex) { showMessageDialog(this, "No has seleccionado el registro.", "Tabla.", JOptionPane.INFORMATION_MESSAGE); }//catch }//if. }//if. }//GEN-LAST:event_tblPredialKeyPressed private void tblPredialMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPredialMouseClicked int r = tblPredial.getSelectedRow(); ftClaveCatastral.setText(m.getValueAt(r, 0).toString()); txtCalle.setText(m.getValueAt(r, 1).toString()); txtNumero.setText(m.getValueAt(r, 2).toString()); txtColonia.setText(m.getValueAt(r, 3).toString()); ftCodigoPostal.setText(m.getValueAt(r, 4).toString()); txtFrente.setText(m.getValueAt(r, 5).toString()); txtFondo.setText(m.getValueAt(r, 6).toString()); txtArea.setText(m.getValueAt(r, 7).toString()); txtSubtotal.setText(m.getValueAt(r, 8).toString()); txtIVA.setText(m.getValueAt(r, 9).toString()); txtTotal.setText(m.getValueAt(r, 10).toString()); txtDescuento.setText(m.getValueAt(r, 11).toString()); txtTotal2.setText(m.getValueAt(r, 12).toString()); txtPago.setText(m.getValueAt(r, 13).toString()); txtCambio.setText(m.getValueAt(r, 14).toString()); btnGuardar.setEnabled(true); txtPago.setEnabled(true); }//GEN-LAST:event_tblPredialMouseClicked private void btnVaciarCamposActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVaciarCamposActionPerformed vaciarCampos(); }//GEN-LAST:event_btnVaciarCamposActionPerformed private void btnVaciarTablaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVaciarTablaActionPerformed if (m.getRowCount() > 0) { int a = m.getRowCount() - 1; for (int i = a; i >= 0; i--) { m.removeRow(i); }//for. showMessageDialog(this, "Registros removidos con éxito", "Tabla.", JOptionPane.INFORMATION_MESSAGE); } else { showMessageDialog(this, "No existen registros por eliminar.", "Tabla.", JOptionPane.INFORMATION_MESSAGE); }//else. }//GEN-LAST:event_btnVaciarTablaActionPerformed public void validarClaveCatastral(String c) throws Excepciones { if (!c.matches("[M]+\\d{3}+[-]+\\d{3}")) { showMessageDialog(this, "Formato: M###-###", "Clave catastral.", JOptionPane.ERROR_MESSAGE); ftClaveCatastral.requestFocus(); }//if. else { txtCalle.requestFocus(); }//else. }//claveCatastral. public void calleVacia(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado la calle.", "Calle.", JOptionPane.INFORMATION_MESSAGE); txtCalle.requestFocus(); } else if (!c.isEmpty()) { txtNumero.requestFocus(); }//else if. }//calleVacia. public void numeroVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el número de la vivienda.", "Número.", JOptionPane.INFORMATION_MESSAGE); txtNumero.requestFocus(); } else if (!c.isEmpty()) { txtColonia.requestFocus(); }//else if. }//numeroVacio. public void coloniaVacia(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado la colonia.", "Colonia.", JOptionPane.INFORMATION_MESSAGE); txtColonia.requestFocus(); } else if (!c.isEmpty()) { ftCodigoPostal.requestFocus(); }//else if. }//coloniaVacia. public void validarCodigoPostal(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el código postal.", "Código Postal.", JOptionPane.INFORMATION_MESSAGE); ftCodigoPostal.requestFocus(); } else if (c.length() < 5) { showMessageDialog(this, "Son cinco dígitos.", "Código Postal.", JOptionPane.WARNING_MESSAGE); ftCodigoPostal.requestFocus(); } else if (!c.isEmpty()) { txtFondo.requestFocus(); }//else if. }//validarCodigoPostal. public void fondoVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el fondo.", "Fondo.", JOptionPane.INFORMATION_MESSAGE); txtFondo.requestFocus(); } else if (!c.isEmpty()) { txtFrente.requestFocus(); }//else if. }//fondoVacio. public void frenteVacio(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el frente.", "Frente.", JOptionPane.INFORMATION_MESSAGE); txtFrente.requestFocus(); }//if. }//frenteVacio. public void validarDescuento(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el descuento", "Descuento.", JOptionPane.INFORMATION_MESSAGE); txtDescuento.requestFocus(); } else if (Float.parseFloat(c) <= 0 || Float.parseFloat(c) > 50) { showMessageDialog(this, "Sólo se admite de 1-50 % de descuento.", "Descuento.", JOptionPane.WARNING_MESSAGE); txtDescuento.requestFocus(); } else if (!c.isEmpty()) { txtPago.requestFocus(); }//else if. }//validarDescuento. public void validarPago(String c) throws Excepciones { if (c.isEmpty()) { showMessageDialog(this, "No has ingresado el pago", "Pago.", JOptionPane.INFORMATION_MESSAGE); txtDescuento.requestFocus(); } else if (Float.parseFloat(c) < Float.parseFloat(txtTotal2.getText())) { showMessageDialog(this, "Cantidad menor a la requerida.", "Pagar", JOptionPane.WARNING_MESSAGE); txtDescuento.requestFocus(); } else if (!c.isEmpty() && (Float.parseFloat(c) >= Float.parseFloat(txtTotal2.getText()))) { btnGuardar.requestFocus(); }//else if. }//valildarPago. public void vaciarCuenta() { txtArea.setText(""); txtSubtotal.setText(""); txtIVA.setText(""); txtTotal.setText(""); txtDescuento.setText(""); txtTotal2.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setEnabled(false); chbHabilitar.setSelected(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); }//vaciarCuenta. public void inhabilitar() { txtDescuento.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setSelected(false); chbHabilitar.setEnabled(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); }//inhabilitar. public void operaciones() { if (txtFrente.getText().length() > 0 && txtFondo.getText().length() > 0) { area = Float.parseFloat(txtFrente.getText()) * Float.parseFloat(txtFondo.getText()); txtArea.setText(area + ""); subtotal = area * 2; txtSubtotal.setText(subtotal + ""); iva = (float) (subtotal * 0.16); txtIVA.setText(iva + ""); total = subtotal + iva; txtTotal.setText(total + ""); total2 = total; txtTotal2.setText(total2 + ""); }//if. }//operaciones. public boolean camposLlenos() { return (!(ftClaveCatastral.getText().isEmpty()) && (ftClaveCatastral.getText().matches("[M]+\\d{3}+[-]+\\d{3}")) && !(txtCalle.getText().isEmpty()) && !(txtNumero.getText().isEmpty()) && !(txtColonia.getText().isEmpty()) && !(ftCodigoPostal.getText().isEmpty()) && (ftCodigoPostal.getText().length() == 5) && !(txtFondo.getText().isEmpty()) && !(txtFrente.getText().isEmpty())); }//camposLlenos. public void camposVaciosExcepciones2() { try { validarClaveCatastral(ftClaveCatastral.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { calleVacia(txtCalle.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { numeroVacio(txtNumero.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { coloniaVacia(txtColonia.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { validarCodigoPostal(ftCodigoPostal.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { fondoVacio(txtFondo.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { frenteVacio(txtFrente.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. try { validarPago(txtPago.getText()); } catch (Excepciones e) { e.getMessage(); }//catch. }//camposVaciosExcepciones2. public boolean camposLlenos2() { return (!(ftClaveCatastral.getText().isEmpty()) && (ftClaveCatastral.getText().matches("[M]+\\d{3}+[-]+\\d{3}")) && !(txtCalle.getText().isEmpty()) && !(txtNumero.getText().isEmpty()) && !(txtColonia.getText().isEmpty()) && !(ftCodigoPostal.getText().isEmpty()) && (ftCodigoPostal.getText().length() == 5) && !(txtFondo.getText().isEmpty()) && !(txtFrente.getText().isEmpty()) && !(txtPago.getText().isEmpty()) && !(txtCambio.getText().isEmpty())); }//campsoLLenos2. private void llenarTabla() { for (int i = 0; i < a; i++) { m.setValueAt(ftClaveCatastral.getText(), i, 0); m.setValueAt(txtCalle.getText(), i, 1); m.setValueAt(txtNumero.getText(), i, 2); m.setValueAt(txtColonia.getText(), i, 3); m.setValueAt(ftCodigoPostal.getText(), i, 4); m.setValueAt(txtFondo.getText(), i, 5); m.setValueAt(txtFrente.getText(), i, 6); m.setValueAt(txtArea.getText(), i, 7); m.setValueAt(txtSubtotal.getText(), i, 8); m.setValueAt(txtIVA.getText(), i, 9); m.setValueAt(txtTotal.getText(), i, 10); m.setValueAt(txtDescuento.getText(), i, 11); m.setValueAt(txtTotal2.getText(), i, 12); m.setValueAt(txtPago.getText(), i, 13); m.setValueAt(txtCambio.getText(), i, 14); }//for. }//llenarTabla. public void vaciarCampos() { ftClaveCatastral.setText(""); txtCalle.setText(""); txtNumero.setText(""); txtColonia.setText(""); ftCodigoPostal.setText(""); txtFrente.setText(""); txtFondo.setText(""); txtArea.setText(""); txtSubtotal.setText(""); txtIVA.setText(""); txtTotal.setText(""); txtDescuento.setText(""); txtTotal2.setText(""); txtPago.setText(""); txtCambio.setText(""); btnGuardar.setEnabled(false); chbHabilitar.setEnabled(false); txtDescuento.setEnabled(false); txtPago.setEnabled(false); chbHabilitar.setSelected(false); }//vaciarCampos. protected DefaultTableModel m; protected int a; protected int b; protected int c; protected float impuesto; protected float area; protected float subtotal; protected float iva; protected float total; protected float descuento; protected float total2; protected float pago; protected float cambio; // Variables declaration - do not modify//GEN-BEGIN:variables protected javax.swing.JButton btnGuardar; protected javax.swing.JButton btnVaciarCampos; protected javax.swing.JButton btnVaciarTabla; protected javax.swing.JCheckBox chbHabilitar; protected javax.swing.JComboBox<String> cmbServicios; protected javax.swing.JFormattedTextField ftClaveCatastral; protected javax.swing.JFormattedTextField ftCodigoPostal; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; protected javax.swing.JLabel lblArea; protected javax.swing.JLabel lblCalle; protected javax.swing.JLabel lblCambio; protected javax.swing.JLabel lblClaveCatastral; protected javax.swing.JLabel lblCobro; protected javax.swing.JLabel lblCodigoPostal; protected javax.swing.JLabel lblColonia; protected javax.swing.JLabel lblDescuento; protected javax.swing.JLabel lblFondo; protected javax.swing.JLabel lblFrente; protected javax.swing.JLabel lblIVA; protected javax.swing.JLabel lblLote; protected javax.swing.JLabel lblNumero; protected javax.swing.JLabel lblPago; protected javax.swing.JLabel lblServicios; protected javax.swing.JLabel lblSubTotal; protected javax.swing.JLabel lblTituloDatosDomicilio; protected javax.swing.JLabel lblTotal; protected javax.swing.JLabel lblTotal2; private javax.swing.JTable tblPredial; protected javax.swing.JTextField txtArea; protected javax.swing.JTextField txtCalle; protected javax.swing.JFormattedTextField txtCambio; protected javax.swing.JTextField txtColonia; protected javax.swing.JTextField txtDescuento; protected javax.swing.JTextField txtFondo; protected javax.swing.JTextField txtFrente; protected javax.swing.JFormattedTextField txtIVA; protected javax.swing.JTextField txtNumero; protected javax.swing.JTextField txtPago; protected javax.swing.JFormattedTextField txtSubtotal; protected javax.swing.JFormattedTextField txtTotal; protected javax.swing.JFormattedTextField txtTotal2; // End of variables declaration//GEN-END:variables }
70,440
0.607235
0.596544
1,509
45.673958
35.178043
184
false
false
0
0
0
0
0
0
0.683897
false
false
14
034ff4c9dc03c445c3cd537be44d21b562980b0a
15,118,284,886,284
adc3b190fb80471a6b6dfd7a827dcfc22a906734
/src/test/java/org/tagaprice/server/service/templates/ReceiptServiceTestTemplate.java
8c7a7fb80a07165c33387a139e341873567ed22f
[]
no_license
forste/tagaprice
https://github.com/forste/tagaprice
651ec756324603b56cc81b98fd6511515525a2af
8a68d2e31ff796a5f725b1760f3177f1c28691a1
refs/heads/master
2021-01-18T14:55:12.258000
2011-12-15T10:17:32
2011-12-15T10:17:32
2,790,333
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.tagaprice.server.service.templates; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.tagaprice.core.api.IReceiptService; import org.tagaprice.core.api.ServerException; import org.tagaprice.core.entities.Account; import org.tagaprice.core.entities.Receipt; import org.tagaprice.core.entities.ReceiptEntry; import org.tagaprice.server.dao.helper.HibernateSaveEntityCreator; import org.tagaprice.server.dao.interfaces.IReceiptDAO; import org.tagaprice.server.service.helper.EntityCreator; public abstract class ReceiptServiceTestTemplate extends AbstractJUnit4SpringContextTests { protected IReceiptService _receiptService; protected IReceiptDAO _receiptDao; @Test public void getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList() throws ServerException { Long productId = 1L; Integer productRevision = 2; getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList_DAO_SETUP(productId, productRevision); List<ReceiptEntry> receiptEntries = _receiptService.getReceiptEntriesByProductIdAndRev(productId, productRevision); assertThat(receiptEntries.isEmpty(), is(true)); } protected abstract void getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList_DAO_SETUP( Long productId, Integer productRevision); @Test public void getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique() throws ServerException { Long productId = 1L; Integer productRevision = 1; ArrayList<ReceiptEntry> entries = new ArrayList<ReceiptEntry>(); ReceiptEntry entry1 = EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(1L, EntityCreator.createBasicShop(1L, "testShop")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 1, 10); entries.add(entry1); ReceiptEntry entry2 = EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(2L, EntityCreator.createBasicShop(2L, "otherTestShopX")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 3, 8); entries.add(entry2); getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique_DAO_SETUP(productId, productRevision, entries); List<ReceiptEntry> actualReceiptEntries = _receiptService.getReceiptEntriesByProductIdAndRev(productId, productRevision); List<ReceiptEntry> expectedEntries = new ArrayList<ReceiptEntry>(); expectedEntries.add(EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(1L, EntityCreator.createBasicShop(1L, "testShop")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 1, 10)); expectedEntries.add(EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(2L, EntityCreator.createBasicShop(2L, "otherTestShopX")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 3, 8)); assertThat(actualReceiptEntries, is(expectedEntries)); } protected abstract void getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique_DAO_SETUP( Long productId, Integer productRevision, List<ReceiptEntry> entries); // // save tests // @Test public void saveEmptyReceipt_shouldSaveReceipt() throws Exception { long receiptId = 3L; // TODO this should be set to null when id in receipt is set to generatedValue long shopId = 1L; Date createdAt = EntityCreator.getDefaultDate(); Account creator = HibernateSaveEntityCreator.createAccount(1L); Receipt receiptToSave = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator); saveEmptyReceipt_shouldSaveReceipt_DAO_SETUP(receiptToSave); Receipt actual = _receiptService.save(receiptToSave); Receipt expected = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator); assertThat(actual, is(expected)); saveEmptyReceipt_shouldSaveReceipt_DB_ASSERTS(receiptToSave); } protected abstract void saveEmptyReceipt_shouldSaveReceipt_DAO_SETUP(Receipt receiptToSave); protected abstract void saveEmptyReceipt_shouldSaveReceipt_DB_ASSERTS(Receipt receiptToSave); @Test public void saveReceiptWithReceiptEntries_shouldSaveReceipt() throws Exception { long receiptId = 3L; long shopId = 1L; Date createdAt = EntityCreator.getDefaultDate(); Account creator = HibernateSaveEntityCreator.createAccount(1L); Set<ReceiptEntry> receiptEntries = new HashSet<ReceiptEntry>(); long prod1Id = 1; int prod1RevNr = 1; receiptEntries.add(HibernateSaveEntityCreator .createReceiptEntry(receiptId, shopId, prod1Id, prod1RevNr, 1, 200)); long prod2Id = 2; int prod2RevNr = 2; receiptEntries.add(HibernateSaveEntityCreator.createReceiptEntry(receiptId, shopId, prod2Id, prod2RevNr, 5, 1000)); Receipt receiptToSave = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator, receiptEntries); saveReceiptWithReceiptEntries_shouldSaveReceipt_DAO_SETUP(receiptToSave); Receipt actual = _receiptService.save(receiptToSave); Receipt expected = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator, receiptEntries); assertThat(actual, is(expected)); saveReceiptWithReceiptEntries_shouldSaveReceipt_DB_ASSERTS(receiptToSave, receiptEntries); } protected abstract void saveReceiptWithReceiptEntries_shouldSaveReceipt_DAO_SETUP(Receipt receipt); protected abstract void saveReceiptWithReceiptEntries_shouldSaveReceipt_DB_ASSERTS(Receipt receiptToSave, Set<ReceiptEntry> receiptEntries); }
UTF-8
Java
5,840
java
ReceiptServiceTestTemplate.java
Java
[]
null
[]
package org.tagaprice.server.service.templates; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.tagaprice.core.api.IReceiptService; import org.tagaprice.core.api.ServerException; import org.tagaprice.core.entities.Account; import org.tagaprice.core.entities.Receipt; import org.tagaprice.core.entities.ReceiptEntry; import org.tagaprice.server.dao.helper.HibernateSaveEntityCreator; import org.tagaprice.server.dao.interfaces.IReceiptDAO; import org.tagaprice.server.service.helper.EntityCreator; public abstract class ReceiptServiceTestTemplate extends AbstractJUnit4SpringContextTests { protected IReceiptService _receiptService; protected IReceiptDAO _receiptDao; @Test public void getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList() throws ServerException { Long productId = 1L; Integer productRevision = 2; getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList_DAO_SETUP(productId, productRevision); List<ReceiptEntry> receiptEntries = _receiptService.getReceiptEntriesByProductIdAndRev(productId, productRevision); assertThat(receiptEntries.isEmpty(), is(true)); } protected abstract void getReceiptEntriesByProductIdAndRev_passProductRevisionIdsNotStored_shouldReturnEmptyList_DAO_SETUP( Long productId, Integer productRevision); @Test public void getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique() throws ServerException { Long productId = 1L; Integer productRevision = 1; ArrayList<ReceiptEntry> entries = new ArrayList<ReceiptEntry>(); ReceiptEntry entry1 = EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(1L, EntityCreator.createBasicShop(1L, "testShop")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 1, 10); entries.add(entry1); ReceiptEntry entry2 = EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(2L, EntityCreator.createBasicShop(2L, "otherTestShopX")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 3, 8); entries.add(entry2); getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique_DAO_SETUP(productId, productRevision, entries); List<ReceiptEntry> actualReceiptEntries = _receiptService.getReceiptEntriesByProductIdAndRev(productId, productRevision); List<ReceiptEntry> expectedEntries = new ArrayList<ReceiptEntry>(); expectedEntries.add(EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(1L, EntityCreator.createBasicShop(1L, "testShop")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 1, 10)); expectedEntries.add(EntityCreator.createReceiptEntry( EntityCreator.createBasicReceipt(2L, EntityCreator.createBasicShop(2L, "otherTestShopX")), EntityCreator.createProductRevision(productId, productRevision, "coke"), 3, 8)); assertThat(actualReceiptEntries, is(expectedEntries)); } protected abstract void getReceiptEntriesByProductIdAndRev_shouldReturnEntriesAsGivenByDaoButOnlyUnique_DAO_SETUP( Long productId, Integer productRevision, List<ReceiptEntry> entries); // // save tests // @Test public void saveEmptyReceipt_shouldSaveReceipt() throws Exception { long receiptId = 3L; // TODO this should be set to null when id in receipt is set to generatedValue long shopId = 1L; Date createdAt = EntityCreator.getDefaultDate(); Account creator = HibernateSaveEntityCreator.createAccount(1L); Receipt receiptToSave = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator); saveEmptyReceipt_shouldSaveReceipt_DAO_SETUP(receiptToSave); Receipt actual = _receiptService.save(receiptToSave); Receipt expected = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator); assertThat(actual, is(expected)); saveEmptyReceipt_shouldSaveReceipt_DB_ASSERTS(receiptToSave); } protected abstract void saveEmptyReceipt_shouldSaveReceipt_DAO_SETUP(Receipt receiptToSave); protected abstract void saveEmptyReceipt_shouldSaveReceipt_DB_ASSERTS(Receipt receiptToSave); @Test public void saveReceiptWithReceiptEntries_shouldSaveReceipt() throws Exception { long receiptId = 3L; long shopId = 1L; Date createdAt = EntityCreator.getDefaultDate(); Account creator = HibernateSaveEntityCreator.createAccount(1L); Set<ReceiptEntry> receiptEntries = new HashSet<ReceiptEntry>(); long prod1Id = 1; int prod1RevNr = 1; receiptEntries.add(HibernateSaveEntityCreator .createReceiptEntry(receiptId, shopId, prod1Id, prod1RevNr, 1, 200)); long prod2Id = 2; int prod2RevNr = 2; receiptEntries.add(HibernateSaveEntityCreator.createReceiptEntry(receiptId, shopId, prod2Id, prod2RevNr, 5, 1000)); Receipt receiptToSave = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator, receiptEntries); saveReceiptWithReceiptEntries_shouldSaveReceipt_DAO_SETUP(receiptToSave); Receipt actual = _receiptService.save(receiptToSave); Receipt expected = HibernateSaveEntityCreator.createReceipt(receiptId, shopId, createdAt, creator, receiptEntries); assertThat(actual, is(expected)); saveReceiptWithReceiptEntries_shouldSaveReceipt_DB_ASSERTS(receiptToSave, receiptEntries); } protected abstract void saveReceiptWithReceiptEntries_shouldSaveReceipt_DAO_SETUP(Receipt receipt); protected abstract void saveReceiptWithReceiptEntries_shouldSaveReceipt_DB_ASSERTS(Receipt receiptToSave, Set<ReceiptEntry> receiptEntries); }
5,840
0.815068
0.805479
154
36.922077
36.78783
124
false
false
0
0
0
0
0
0
2.11039
false
false
14
3efb9edfde64473241c16cfec629d91e204ff4b8
15,118,284,887,356
b0bb30883e2c519497bad7252b621722c7a3a882
/usian_item_service/src/main/java/com/usian/service/impl/ItemServiceImpl.java
db540e1b09bbf5b288adf2c91fd0598fb54ff51a
[]
no_license
xy-9612/malll
https://github.com/xy-9612/malll
e3dcf34b2cb07898293aae673659516af361f935
4f58906373841715717c43ccd8046926bff02cb1
refs/heads/master
2023-05-13T03:49:51.949000
2021-05-12T06:42:12
2021-05-12T06:42:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.usian.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.usian.mapper.*; import com.usian.pojo.*; import com.usian.redis.RedisClient; import com.usian.service.ItemService; import com.usian.utils.IDUtils; import com.usian.utils.PageResult; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * service接口实现类 * * @author : xy1201 * @version 1.0 * @date : 2021/4/7 21:16 */ @Service @Transactional public class ItemServiceImpl implements ItemService { /** * @Date: 2021/4/7 21:32 * 注入mapper */ @Autowired private TbItemMapper tbItemMapper; @Autowired private TbItemDescMapper tbItemDescMapper; @Autowired private TbItemParamMapper tbItemParamMapper; @Autowired private TbItemCatMapper tbItemCatMapper; @Autowired private TbItemParamItemMapper tbItemParamItemMapper; @Autowired private AmqpTemplate amqpTemplate; @Value("${ITEM_INFO}") private String ITEM_INFO; @Value("${BASE}") private String BASE; @Value("${DESC}") private String DESC; @Value("${ITEM_INFO_EXPIRE}") private Integer ITEM_INFO_EXPIRE; @Autowired private RedisClient redisClient; /** * 查询商品信息 * * @param : [itemId] * @return : com.usian.pojo.TbItem * @Author : xy * @Date : 2021/5/6 17:06 */ @Override public TbItem selectItemInfo(Long itemId) { /** * @Date: 2021/5/6 17:08 * Step 1: 查询缓存 */ TbItem tbItem = (TbItem) redisClient.get(ITEM_INFO + ":" + itemId + ":" + BASE); if (tbItem != null) { return tbItem; } /** * @Date: 2021/5/6 17:09 * Step 2: 缓存中没有时查询数据库 */ tbItem = tbItemMapper.selectItemInfo(itemId); /** * @Date: 2021/5/6 17:11 * Step 3: 把数据保存到缓存中,并设置有效期 */ redisClient.set(ITEM_INFO + ":" + itemId + ":" + BASE, tbItem); redisClient.expire(ITEM_INFO + ":" + itemId + ":" + BASE, ITEM_INFO_EXPIRE); /** * @Date: 2021/5/6 17:12 * Step 4: 返回结果 */ return tbItem; } /** * 根据商品 ID 查询商品描述 * * @param itemId * @return */ @Override public TbItemDesc selectItemDescByItemId(Long itemId) { /** * @Date: 2021/5/6 17:16 * Step 1: 查询缓存 */ TbItemDesc tbItemDesc = (TbItemDesc) redisClient.get(ITEM_INFO + ":" + itemId + ":" + DESC); if (tbItemDesc != null) { return tbItemDesc; } /** * @Date: 2021/5/6 17:16 * Step 2: 缓存中没有查询数据库,并将查到的有效信息保存到缓存中,并设置缓存的有效期 */ List<TbItemDesc> itemDescList = this.tbItemDescMapper.selectItemDescByItemId(itemId); if (itemDescList != null && itemDescList.size() > 0) { //把数据保存到缓存 redisClient.set(ITEM_INFO + ":" + itemId + ":" + DESC, itemDescList.get(0)); //设置缓存的有效期 redisClient.expire(ITEM_INFO + ":" + itemId + ":" + DESC, ITEM_INFO_EXPIRE); return itemDescList.get(0); } /** * @Date: 2021/5/6 17:19 * Step 3: 为空则返回null */ return null; } /** * 查询所有商品,并分页。 * * @param page * @param rows * @return PageResult */ @Override public PageResult selectTbItemAllByPage(Integer page, Integer rows) { /** * @Date: 2021/4/8 20:40 * Step 1: 开启分页 */ PageHelper.startPage(page, 10); /** * @Date: 2021/4/8 20:40 * Step 2: 查询数据库 */ List<TbItem> tbItemList = this.tbItemMapper.selectTbItemAllByPage(); /** * @Date: 2021/4/8 20:42 * Step 3: 将查询结果封装成pageinfo */ PageInfo<TbItem> pageInfo = new PageInfo<>(tbItemList); /** * @Date: 2021/4/8 20:43 * Step 4: 封装pageresult并返回 */ return new PageResult(pageInfo.getPageNum(), Long.valueOf(pageInfo.getTotal()), pageInfo.getList()); } /** * @return : java.lang.Integer * @Description :添加商品业务层(除添加商品表,还需补全商品描述) * @Param : [tbItem, desc, itemParams] * @Author : xy * @Date : 2021/4/12 11:56 */ @Override public Integer insertTbItem(TbItem tbItem, String desc, String itemParams) { /** * @Date: 2021/4/12 14:20 * Step 0: 定义时间的全局变量。表示当前时间 */ Date date = new Date(); /** * @Date: 2021/4/12 14:03 * Step 1: 添加商品表信息,并返回主键ID(tb_item表) */ Long itemId = IDUtils.genItemId(); tbItem.setId(itemId); Integer tbItemNum = tbItemMapper.insertTbItem(tbItem); //TODO 商品描述未添加,param未添加,只添加了item表的参数信息(后两布也写了,没测==测了好使) /** * @Date: 2021/4/12 14:04 * Step 2: 添加商品描述(tb_item_desc表) */ Integer tbItemDescNum = tbItemDescMapper.insertDesc(new TbItemDesc(itemId, date, date, desc)); /** * @Date: 2021/4/12 14:15 * Step 3: 添加商品规格信息(tb_item_param_item表) */ Integer tbItemParamItemNum = tbItemParamItemMapper.insertParam(new TbItemParamItem(null, itemId, date, date, itemParams)); /** * @Date: 2021/5/6 16:13 * Step 4: 添加商品发布到mq */ amqpTemplate.convertAndSend("item_exchage", "item.add", itemId); /** * @Date: 2021/4/13 9:05 * Step 5: 返回结果信息,当结果为3时说明全部添加成功 */ return tbItemNum + tbItemDescNum + tbItemParamItemNum; } /** * 修改回显 * * @return : java.util.Map<java.lang.String,java.lang.Object> * @Param : [itemId] * @Author : xy * @Date : 2021/4/13 9:08 */ @Override public Map<String, Object> preUpdateItem(Long itemId) { /** * @Date: 2021/4/12 15:21 * Step 0: 新建一个hashmap,用于存放查询到的数据 */ HashMap<String, Object> map = new HashMap<>(); /** * @Date: 2021/4/12 15:22 * Step 1: 根据商品ID查询商品,将结果放到map中 */ TbItem item = this.tbItemMapper.queryByItemId(itemId); map.put("item", item); /** * @Date: 2021/4/12 15:23 * Step 2: 根据商品ID查询商品描述,将结果放到map中 */ TbItemDesc desc = this.tbItemDescMapper.queryByItemId(itemId); map.put("itemDesc", desc.getItemDesc()); /** * @Date: 2021/4/12 15:24 * Step 3: 根据商品ID查询商品类目,将结果放到map中 */ TbItemCat cat = this.tbItemCatMapper.queryByItemId(item.getCid()); map.put("itemCat", cat.getName()); /** * @Date: 2021/4/12 15:27 * Step 4: 根据商品ID查询商品规格信息,判空之后,将结果放到map中 */ List<TbItemParamItem> paramItems = this.tbItemParamItemMapper.queryByItemId(itemId); if (paramItems != null && paramItems.size() > 0) { map.put("itemParamItem", paramItems.get(0).getParamData()); } /** * @Date: 2021/4/12 15:33 * Step 5: 返回结果 */ return map; } /** * @return : java.lang.Integer * @Description : 修改商品业务层 * @Param : [tbItem, desc, itemParams] * @Author : xy * @Date : 2021/4/13 8:58 */ @Override public Integer updateTbItem(TbItem tbItem, String desc, String itemParams) { /** * @Date: 2021/4/13 9:00 * Step 0: 定义时间的全局变量 */ Date date = new Date(); /** * @Date: 2021/4/13 9:00 * Step 1: 根据商品ID修改商品信息(tb_item表) */ Integer tbItemNum = tbItemMapper.updateTbItem(tbItem); /** * @Date: 2021/4/13 9:02 * Step 2: 根据商品ID修改商品描述(tb_item_desc表) */ Integer tbItemDescNum = tbItemDescMapper.updateDesc(new TbItemDesc(tbItem.getId(), date, date, desc)); /** * @Date: 2021/4/13 9:04 * Step 3: 根据商品ID修改商品规格信息 */ Integer tbItemParamItemNum = tbItemParamItemMapper.updateParam(new TbItemParamItem(null, tbItem.getId(), date, date, itemParams)); /** * @Date: 2021/4/13 9:05 * Step 4: 返回结果信息,当结果为3时说明全部修改成功 */ return tbItemNum + tbItemDescNum + tbItemParamItemNum; } /** * 根据ID删除(其实是修改,将商品对应的状态调整为3) * * @return : java.lang.Integer * @Param : [itemId] * @Author : xy * @Date : 2021/4/13 14:16 */ @Override public Integer deleteItemById(Long itemId) { /** * @Date: 2021/4/13 14:19 * Step 1: 删除(修改)商品信息(tb_item表) */ Integer tbItemNum = tbItemMapper.deleteItemById(itemId); return tbItemNum; } }
UTF-8
Java
9,938
java
ItemServiceImpl.java
Java
[ { "context": "ava.util.Map;\n\n/**\n * service接口实现类\n *\n * @author : xy1201\n * @version 1.0\n * @date : 2021/4/7 21:16\n */\n@Se", "end": 729, "score": 0.999539852142334, "start": 723, "tag": "USERNAME", "value": "xy1201" }, { "context": "* @return : com.usian.pojo.TbItem\n * @Author : xy\n * @Date : 2021/5/6 17:06\n */\n @Overri", "end": 1679, "score": 0.9964383244514465, "start": 1677, "tag": "USERNAME", "value": "xy" }, { "context": "aram : [tbItem, desc, itemParams]\n * @Author : xy\n * @Date : 2021/4/12 11:56\n */\n @Overr", "end": 4580, "score": 0.9964880347251892, "start": 4578, "tag": "USERNAME", "value": "xy" }, { "context": ".Object>\n * @Param : [itemId]\n * @Author : xy\n * @Date : 2021/4/13 9:08\n */\n @Overri", "end": 6048, "score": 0.9992809891700745, "start": 6046, "tag": "USERNAME", "value": "xy" }, { "context": "aram : [tbItem, desc, itemParams]\n * @Author : xy\n * @Date : 2021/4/13 8:58\n */\n @Overri", "end": 7531, "score": 0.9962654113769531, "start": 7529, "tag": "USERNAME", "value": "xy" }, { "context": ".Integer\n * @Param : [itemId]\n * @Author : xy\n * @Date : 2021/4/13 14:16\n */\n @Overr", "end": 8686, "score": 0.9859786629676819, "start": 8684, "tag": "USERNAME", "value": "xy" } ]
null
[]
package com.usian.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.usian.mapper.*; import com.usian.pojo.*; import com.usian.redis.RedisClient; import com.usian.service.ItemService; import com.usian.utils.IDUtils; import com.usian.utils.PageResult; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * service接口实现类 * * @author : xy1201 * @version 1.0 * @date : 2021/4/7 21:16 */ @Service @Transactional public class ItemServiceImpl implements ItemService { /** * @Date: 2021/4/7 21:32 * 注入mapper */ @Autowired private TbItemMapper tbItemMapper; @Autowired private TbItemDescMapper tbItemDescMapper; @Autowired private TbItemParamMapper tbItemParamMapper; @Autowired private TbItemCatMapper tbItemCatMapper; @Autowired private TbItemParamItemMapper tbItemParamItemMapper; @Autowired private AmqpTemplate amqpTemplate; @Value("${ITEM_INFO}") private String ITEM_INFO; @Value("${BASE}") private String BASE; @Value("${DESC}") private String DESC; @Value("${ITEM_INFO_EXPIRE}") private Integer ITEM_INFO_EXPIRE; @Autowired private RedisClient redisClient; /** * 查询商品信息 * * @param : [itemId] * @return : com.usian.pojo.TbItem * @Author : xy * @Date : 2021/5/6 17:06 */ @Override public TbItem selectItemInfo(Long itemId) { /** * @Date: 2021/5/6 17:08 * Step 1: 查询缓存 */ TbItem tbItem = (TbItem) redisClient.get(ITEM_INFO + ":" + itemId + ":" + BASE); if (tbItem != null) { return tbItem; } /** * @Date: 2021/5/6 17:09 * Step 2: 缓存中没有时查询数据库 */ tbItem = tbItemMapper.selectItemInfo(itemId); /** * @Date: 2021/5/6 17:11 * Step 3: 把数据保存到缓存中,并设置有效期 */ redisClient.set(ITEM_INFO + ":" + itemId + ":" + BASE, tbItem); redisClient.expire(ITEM_INFO + ":" + itemId + ":" + BASE, ITEM_INFO_EXPIRE); /** * @Date: 2021/5/6 17:12 * Step 4: 返回结果 */ return tbItem; } /** * 根据商品 ID 查询商品描述 * * @param itemId * @return */ @Override public TbItemDesc selectItemDescByItemId(Long itemId) { /** * @Date: 2021/5/6 17:16 * Step 1: 查询缓存 */ TbItemDesc tbItemDesc = (TbItemDesc) redisClient.get(ITEM_INFO + ":" + itemId + ":" + DESC); if (tbItemDesc != null) { return tbItemDesc; } /** * @Date: 2021/5/6 17:16 * Step 2: 缓存中没有查询数据库,并将查到的有效信息保存到缓存中,并设置缓存的有效期 */ List<TbItemDesc> itemDescList = this.tbItemDescMapper.selectItemDescByItemId(itemId); if (itemDescList != null && itemDescList.size() > 0) { //把数据保存到缓存 redisClient.set(ITEM_INFO + ":" + itemId + ":" + DESC, itemDescList.get(0)); //设置缓存的有效期 redisClient.expire(ITEM_INFO + ":" + itemId + ":" + DESC, ITEM_INFO_EXPIRE); return itemDescList.get(0); } /** * @Date: 2021/5/6 17:19 * Step 3: 为空则返回null */ return null; } /** * 查询所有商品,并分页。 * * @param page * @param rows * @return PageResult */ @Override public PageResult selectTbItemAllByPage(Integer page, Integer rows) { /** * @Date: 2021/4/8 20:40 * Step 1: 开启分页 */ PageHelper.startPage(page, 10); /** * @Date: 2021/4/8 20:40 * Step 2: 查询数据库 */ List<TbItem> tbItemList = this.tbItemMapper.selectTbItemAllByPage(); /** * @Date: 2021/4/8 20:42 * Step 3: 将查询结果封装成pageinfo */ PageInfo<TbItem> pageInfo = new PageInfo<>(tbItemList); /** * @Date: 2021/4/8 20:43 * Step 4: 封装pageresult并返回 */ return new PageResult(pageInfo.getPageNum(), Long.valueOf(pageInfo.getTotal()), pageInfo.getList()); } /** * @return : java.lang.Integer * @Description :添加商品业务层(除添加商品表,还需补全商品描述) * @Param : [tbItem, desc, itemParams] * @Author : xy * @Date : 2021/4/12 11:56 */ @Override public Integer insertTbItem(TbItem tbItem, String desc, String itemParams) { /** * @Date: 2021/4/12 14:20 * Step 0: 定义时间的全局变量。表示当前时间 */ Date date = new Date(); /** * @Date: 2021/4/12 14:03 * Step 1: 添加商品表信息,并返回主键ID(tb_item表) */ Long itemId = IDUtils.genItemId(); tbItem.setId(itemId); Integer tbItemNum = tbItemMapper.insertTbItem(tbItem); //TODO 商品描述未添加,param未添加,只添加了item表的参数信息(后两布也写了,没测==测了好使) /** * @Date: 2021/4/12 14:04 * Step 2: 添加商品描述(tb_item_desc表) */ Integer tbItemDescNum = tbItemDescMapper.insertDesc(new TbItemDesc(itemId, date, date, desc)); /** * @Date: 2021/4/12 14:15 * Step 3: 添加商品规格信息(tb_item_param_item表) */ Integer tbItemParamItemNum = tbItemParamItemMapper.insertParam(new TbItemParamItem(null, itemId, date, date, itemParams)); /** * @Date: 2021/5/6 16:13 * Step 4: 添加商品发布到mq */ amqpTemplate.convertAndSend("item_exchage", "item.add", itemId); /** * @Date: 2021/4/13 9:05 * Step 5: 返回结果信息,当结果为3时说明全部添加成功 */ return tbItemNum + tbItemDescNum + tbItemParamItemNum; } /** * 修改回显 * * @return : java.util.Map<java.lang.String,java.lang.Object> * @Param : [itemId] * @Author : xy * @Date : 2021/4/13 9:08 */ @Override public Map<String, Object> preUpdateItem(Long itemId) { /** * @Date: 2021/4/12 15:21 * Step 0: 新建一个hashmap,用于存放查询到的数据 */ HashMap<String, Object> map = new HashMap<>(); /** * @Date: 2021/4/12 15:22 * Step 1: 根据商品ID查询商品,将结果放到map中 */ TbItem item = this.tbItemMapper.queryByItemId(itemId); map.put("item", item); /** * @Date: 2021/4/12 15:23 * Step 2: 根据商品ID查询商品描述,将结果放到map中 */ TbItemDesc desc = this.tbItemDescMapper.queryByItemId(itemId); map.put("itemDesc", desc.getItemDesc()); /** * @Date: 2021/4/12 15:24 * Step 3: 根据商品ID查询商品类目,将结果放到map中 */ TbItemCat cat = this.tbItemCatMapper.queryByItemId(item.getCid()); map.put("itemCat", cat.getName()); /** * @Date: 2021/4/12 15:27 * Step 4: 根据商品ID查询商品规格信息,判空之后,将结果放到map中 */ List<TbItemParamItem> paramItems = this.tbItemParamItemMapper.queryByItemId(itemId); if (paramItems != null && paramItems.size() > 0) { map.put("itemParamItem", paramItems.get(0).getParamData()); } /** * @Date: 2021/4/12 15:33 * Step 5: 返回结果 */ return map; } /** * @return : java.lang.Integer * @Description : 修改商品业务层 * @Param : [tbItem, desc, itemParams] * @Author : xy * @Date : 2021/4/13 8:58 */ @Override public Integer updateTbItem(TbItem tbItem, String desc, String itemParams) { /** * @Date: 2021/4/13 9:00 * Step 0: 定义时间的全局变量 */ Date date = new Date(); /** * @Date: 2021/4/13 9:00 * Step 1: 根据商品ID修改商品信息(tb_item表) */ Integer tbItemNum = tbItemMapper.updateTbItem(tbItem); /** * @Date: 2021/4/13 9:02 * Step 2: 根据商品ID修改商品描述(tb_item_desc表) */ Integer tbItemDescNum = tbItemDescMapper.updateDesc(new TbItemDesc(tbItem.getId(), date, date, desc)); /** * @Date: 2021/4/13 9:04 * Step 3: 根据商品ID修改商品规格信息 */ Integer tbItemParamItemNum = tbItemParamItemMapper.updateParam(new TbItemParamItem(null, tbItem.getId(), date, date, itemParams)); /** * @Date: 2021/4/13 9:05 * Step 4: 返回结果信息,当结果为3时说明全部修改成功 */ return tbItemNum + tbItemDescNum + tbItemParamItemNum; } /** * 根据ID删除(其实是修改,将商品对应的状态调整为3) * * @return : java.lang.Integer * @Param : [itemId] * @Author : xy * @Date : 2021/4/13 14:16 */ @Override public Integer deleteItemById(Long itemId) { /** * @Date: 2021/4/13 14:19 * Step 1: 删除(修改)商品信息(tb_item表) */ Integer tbItemNum = tbItemMapper.deleteItemById(itemId); return tbItemNum; } }
9,938
0.5572
0.510683
316
27.436708
23.489948
138
false
false
0
0
0
0
0
0
0.367089
false
false
14
ba6147ac4110e287523dcc7e577668d0aec3ee0c
3,796,751,120,056
5e5f8830570d4017d747d8f6c82a08ec912e5f9f
/fx6/src/phone/controller/MainViewController.java
af73d30d9b67fe2842de3733de7457beb14b3000
[]
no_license
sukdongkim/crud2
https://github.com/sukdongkim/crud2
6911918a1f1b238aa2f82526743dfc9b445d0d12
cac3aa97c824ae663f96bcac4d59e280882a6a82
refs/heads/master
2023-03-01T20:32:45.248000
2021-02-09T11:17:16
2021-02-09T11:17:16
337,318,606
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package phone.controller; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.layout.AnchorPane; import phone.Main; public class MainViewController { Main main= new Main(); @FXML AnchorPane root; @FXML void onClickOne(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainView2.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickSep(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainView3.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickCafe(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/CafeMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickPizza(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/PizzaMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickBus(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/BusMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickClose(ActionEvent event) { System.exit(0); } @FXML void onClickHome(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainItem.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickStop(ActionEvent event) { System.exit(0); } }
UTF-8
Java
1,945
java
MainViewController.java
Java
[]
null
[]
package phone.controller; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.layout.AnchorPane; import phone.Main; public class MainViewController { Main main= new Main(); @FXML AnchorPane root; @FXML void onClickOne(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainView2.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickSep(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainView3.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickCafe(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/CafeMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickPizza(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/PizzaMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickBus(ActionEvent event) { main.showMainView(); try { AnchorPane root = FXMLLoader.load(getClass().getResource("../view/BusMain.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickClose(ActionEvent event) { System.exit(0); } @FXML void onClickHome(ActionEvent event) { try { root = FXMLLoader.load(getClass().getResource("../view/MainItem.fxml")); Main.mainLayout.setCenter(root); } catch(Exception e) { e.printStackTrace(); } } @FXML void onClickStop(ActionEvent event) { System.exit(0); } }
1,945
0.65347
0.651414
85
21.882353
20.892111
87
false
false
0
0
0
0
0
0
1.517647
false
false
14
39675be8bdd7e16129b9485822a73a15f541b21d
22,273,700,401,512
709d00d130164f63f3428fea483db6d230818540
/redgear/brewcraft/api/BrewingAPI.java
19a3f21825980a44481b30581e3bc9b14dc9b407
[]
no_license
RedGear/RedGear
https://github.com/RedGear/RedGear
0d233bd915d1785820ac9170bc2a4ab3efc26d07
6abb42194929a4a62b0a49c56a8deaa736818ab5
refs/heads/master
2015-08-08T10:48:35.934000
2013-12-25T21:18:08
2013-12-25T21:18:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package redgear.brewcraft.api; public class BrewingAPI { public static IRecipeRegistry registry; }
UTF-8
Java
102
java
BrewingAPI.java
Java
[]
null
[]
package redgear.brewcraft.api; public class BrewingAPI { public static IRecipeRegistry registry; }
102
0.803922
0.803922
6
16
16.27882
40
false
false
0
0
0
0
0
0
0.5
false
false
14
e91e48946035c3b046b7d11ee78c2a06685f1bc4
31,636,729,124,722
21133a2bc6191d1a7b6b56d411adc6cdb67888c1
/SpinnerConFragmentos/app/src/main/java/com/example/csoro/spinnerconfragmentos/Pantalla1.java
e617250b31b57f85896822bcadd594cd53d587b5
[]
no_license
carmar04/pmm
https://github.com/carmar04/pmm
554f1b2be9e55e4b4296d9e61d9b720961e18404
036218b9aef468fb1984354144ffdfd321e17f40
refs/heads/master
2020-03-29T05:54:37.371000
2019-02-07T13:03:56
2019-02-07T13:03:56
149,601,131
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.csoro.spinnerconfragmentos; import android.app.Activity; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; public class Pantalla1 extends AppCompatActivity { int indice; Persona persona; Spinner spinner_personas; Persona [] personas = new Persona[]{ new Persona("Matt Damon", 50, "Actor inglés, originariamente dedicado a la peliculas de acción", R.drawable.mattdaemon), new Persona("Michael Fassbender", 45, "Actor aleman que ha protagonizado diversas peliculas de la saga Aliens", R.drawable.michaelfassbender), new Persona("Tom Hanks", 60, "Actor estadounidense que ha participado en multitud de rodajes y repartos", R.drawable.tomhanks) }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pantalla1); spinner_personas = (Spinner) findViewById(R.id.spinnerPersonas); AdaptadorPersonas adaptadorPersonas = new AdaptadorPersonas(this); spinner_personas.setAdapter(adaptadorPersonas); spinner_personas.setSelection(0); spinner_personas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { indice = position; addFragment(); } public void onNothingSelected(AdapterView<?> parent){ } }); } void addFragment(){ FragmentPersona fragmentPersona = FragmentPersona.newInstance(personas[indice]); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment1, fragmentPersona); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } @Override public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); outState.putSerializable("Persona", personas[indice]); } public class AdaptadorPersonas extends ArrayAdapter{ Activity context; AdaptadorPersonas(Activity context){ super(context, R.layout.spinner_personas, personas); this.context = context; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public View getDropDownView(int position, View convertView, ViewGroup parent){ View vista = getView(position, convertView, parent); return vista; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = context.getLayoutInflater(); View item = inflater.inflate(R.layout.spinner_personas, null); TextView nombre_persona = (TextView) item.findViewById(R.id.nombre_persona); TextView edad_persona = (TextView) item.findViewById(R.id.edad_persona); ImageView imagen_persona = (ImageView) item.findViewById(R.id.imagen_persona); nombre_persona.setText(personas[position].getNombre()); edad_persona.setText(String.valueOf(personas[position].getEdad())); imagen_persona.setImageDrawable(getDrawable(personas[position].getImagen())); return item; } } }
UTF-8
Java
3,903
java
Pantalla1.java
Java
[ { "context": "ersonas = new Persona[]{\n new Persona(\"Matt Damon\", 50, \"Actor inglés, originariamente dedicado a l", "end": 735, "score": 0.9998927116394043, "start": 725, "tag": "NAME", "value": "Matt Damon" }, { "context": " R.drawable.mattdaemon),\n new Persona(\"Michael Fassbender\", 45, \"Actor aleman que ha protagonizado diversas", "end": 876, "score": 0.9998807907104492, "start": 858, "tag": "NAME", "value": "Michael Fassbender" }, { "context": "able.michaelfassbender),\n new Persona(\"Tom Hanks\", 60, \"Actor estadounidense que ha participado en", "end": 1022, "score": 0.9998781681060791, "start": 1013, "tag": "NAME", "value": "Tom Hanks" } ]
null
[]
package com.example.csoro.spinnerconfragmentos; import android.app.Activity; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; public class Pantalla1 extends AppCompatActivity { int indice; Persona persona; Spinner spinner_personas; Persona [] personas = new Persona[]{ new Persona("<NAME>", 50, "Actor inglés, originariamente dedicado a la peliculas de acción", R.drawable.mattdaemon), new Persona("<NAME>", 45, "Actor aleman que ha protagonizado diversas peliculas de la saga Aliens", R.drawable.michaelfassbender), new Persona("<NAME>", 60, "Actor estadounidense que ha participado en multitud de rodajes y repartos", R.drawable.tomhanks) }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pantalla1); spinner_personas = (Spinner) findViewById(R.id.spinnerPersonas); AdaptadorPersonas adaptadorPersonas = new AdaptadorPersonas(this); spinner_personas.setAdapter(adaptadorPersonas); spinner_personas.setSelection(0); spinner_personas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { indice = position; addFragment(); } public void onNothingSelected(AdapterView<?> parent){ } }); } void addFragment(){ FragmentPersona fragmentPersona = FragmentPersona.newInstance(personas[indice]); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment1, fragmentPersona); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } @Override public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); outState.putSerializable("Persona", personas[indice]); } public class AdaptadorPersonas extends ArrayAdapter{ Activity context; AdaptadorPersonas(Activity context){ super(context, R.layout.spinner_personas, personas); this.context = context; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public View getDropDownView(int position, View convertView, ViewGroup parent){ View vista = getView(position, convertView, parent); return vista; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = context.getLayoutInflater(); View item = inflater.inflate(R.layout.spinner_personas, null); TextView nombre_persona = (TextView) item.findViewById(R.id.nombre_persona); TextView edad_persona = (TextView) item.findViewById(R.id.edad_persona); ImageView imagen_persona = (ImageView) item.findViewById(R.id.imagen_persona); nombre_persona.setText(personas[position].getNombre()); edad_persona.setText(String.valueOf(personas[position].getEdad())); imagen_persona.setImageDrawable(getDrawable(personas[position].getImagen())); return item; } } }
3,884
0.700333
0.697257
96
39.635418
34.241215
154
false
false
0
0
0
0
0
0
0.791667
false
false
14
8d9266ade5b84c6c010f1f43609171d206c99d52
20,633,022,930,542
492b0e1728e93cf517110fd57bcc1f9ed94ca1fa
/pro02/src/ch06/bb/DD.java
1793bf71ee8504f6a3505b6790e34a8a99ffcac3
[]
no_license
areume/Kitri_Java_Basic
https://github.com/areume/Kitri_Java_Basic
8e4f49257616271f73a9f071ed13d7d223d3f579
2a181710cf04b72ab327ed59c629a42237de9f6f
refs/heads/master
2022-12-11T03:55:15.557000
2020-09-09T02:03:57
2020-09-09T02:03:57
293,818,909
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch06.bb; import ch06.aa.AA; public class DD { public static void main(String[] args) { AA a=new AA(); //System.out.println("num1 : "+a.num1); //System.out.println("num2 : "+a.num2); System.out.println("num3 : "+a.num3); //System.out.println("num4 : "+a.num4); } } // 다른 패키지 클래스의 private, protected, public은 사용할 수 없지만 public은 사용할 수 있다.
UTF-8
Java
417
java
DD.java
Java
[]
null
[]
package ch06.bb; import ch06.aa.AA; public class DD { public static void main(String[] args) { AA a=new AA(); //System.out.println("num1 : "+a.num1); //System.out.println("num2 : "+a.num2); System.out.println("num3 : "+a.num3); //System.out.println("num4 : "+a.num4); } } // 다른 패키지 클래스의 private, protected, public은 사용할 수 없지만 public은 사용할 수 있다.
417
0.623306
0.590786
20
17.25
20.405575
70
false
false
0
0
0
0
0
0
1.15
false
false
14
d7d7e89cec1c4be2c25ac6111fc2d09cbfbd8f05
20,633,022,931,944
b58d26ffaa57ffa6300395257394cdd4240e6208
/src/Num_13/IncorrectNumException.java
beb300786f278b87c71b708dab65e3977d232562
[]
no_license
Miki-san/Java_02
https://github.com/Miki-san/Java_02
6521ec4f39a9c1bcb678cb6200e3d0d98170f5b4
fbf5e070e666bd5d9626aa228f423c617b7095ee
refs/heads/master
2023-02-02T09:33:53.843000
2020-12-19T18:40:07
2020-12-19T18:40:07
297,145,744
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Num_13; public class IncorrectNumException extends IllegalArgumentException{ }
UTF-8
Java
88
java
IncorrectNumException.java
Java
[]
null
[]
package Num_13; public class IncorrectNumException extends IllegalArgumentException{ }
88
0.852273
0.829545
4
21
27.775888
68
false
false
0
0
0
0
0
0
0.25
false
false
14
78755e5bb274f31a6d5b54304e0215d81f62fdf7
23,811,298,704,433
8749d661fa54c0e61cb45085513e0f85ba2139b0
/src/main/java/cn/wsg/oj/leetcode/problems/p400/Solution485.java
a263e4c9a72c3ac5242ad5c6dc2b6091e643b954
[]
no_license
EastSunrise/oj-java
https://github.com/EastSunrise/oj-java
ed4adb6557116c79192d969c69ada7469b953cf3
63335b7f58bd912a6b392fbd91248f3f753cfa16
refs/heads/master
2021-12-27T00:12:14.421000
2021-12-22T06:43:35
2021-12-22T06:43:35
237,616,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.wsg.oj.leetcode.problems.p400; import cn.wsg.oj.Complexity; import cn.wsg.oj.leetcode.problems.base.Solution; import cn.wsg.oj.leetcode.problems.p1000.Solution1004; import cn.wsg.oj.leetcode.problems.p1400.Solution1446; import cn.wsg.oj.leetcode.problems.p1800.Solution1869; /** * 485. Max Consecutive Ones (Easy) * * @author Kingen * @see Solution487 * @see Solution1004 * @see Solution1446 * @see Solution1869 * @see <a href="https://leetcode-cn.com/problems/max-consecutive-ones/">Max Consecutive Ones</a> */ public class Solution485 implements Solution { /** * @see Complexity#TIME_N * @see Complexity#SPACE_CONSTANT */ public int findMaxConsecutiveOnes(int[] nums) { int count = 0, max = 0; for (int num : nums) { if (num == 1) { count++; } else { max = Math.max(count, max); count = 0; } } return Math.max(count, max); } }
UTF-8
Java
995
java
Solution485.java
Java
[ { "context": "\n * 485. Max Consecutive Ones (Easy)\n *\n * @author Kingen\n * @see Solution487\n * @see Solution1004\n * @see ", "end": 348, "score": 0.9026235342025757, "start": 342, "tag": "USERNAME", "value": "Kingen" } ]
null
[]
package cn.wsg.oj.leetcode.problems.p400; import cn.wsg.oj.Complexity; import cn.wsg.oj.leetcode.problems.base.Solution; import cn.wsg.oj.leetcode.problems.p1000.Solution1004; import cn.wsg.oj.leetcode.problems.p1400.Solution1446; import cn.wsg.oj.leetcode.problems.p1800.Solution1869; /** * 485. Max Consecutive Ones (Easy) * * @author Kingen * @see Solution487 * @see Solution1004 * @see Solution1446 * @see Solution1869 * @see <a href="https://leetcode-cn.com/problems/max-consecutive-ones/">Max Consecutive Ones</a> */ public class Solution485 implements Solution { /** * @see Complexity#TIME_N * @see Complexity#SPACE_CONSTANT */ public int findMaxConsecutiveOnes(int[] nums) { int count = 0, max = 0; for (int num : nums) { if (num == 1) { count++; } else { max = Math.max(count, max); count = 0; } } return Math.max(count, max); } }
995
0.61407
0.561809
37
25.891891
20.797329
97
false
false
0
0
0
0
0
0
0.378378
false
false
14
a79c69e5fcd6fe61022a2b04530fe1dc78e116cb
6,657,199,312,662
eed3854f6cc9f701cdfe06d62710be26764de130
/app/src/main/java/com/homefood/restaurant/network/ApiInterface.java
d74657214819049f969383baf3def9dd3c499a72
[]
no_license
muthu23/HomeFoodRestaurant
https://github.com/muthu23/HomeFoodRestaurant
a433e2d8fad7e019ff901d6a89867e645421e123
329aab6173ec3fdb830014e3be68b60271ce64e7
refs/heads/master
2022-11-27T19:28:58.712000
2020-08-09T13:37:34
2020-08-09T13:37:34
285,377,541
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.homefood.restaurant.network; import com.homefood.restaurant.model.Addon; import com.homefood.restaurant.model.AuthToken; import com.homefood.restaurant.model.CancelReasons; import com.homefood.restaurant.model.Category; import com.homefood.restaurant.model.ChangePassword; import com.homefood.restaurant.model.Cuisine; import com.homefood.restaurant.model.ForgotPasswordResponse; import com.homefood.restaurant.model.HistoryModel; import com.homefood.restaurant.model.IncomingOrders; import com.homefood.restaurant.model.Order; import com.homefood.restaurant.model.Profile; import com.homefood.restaurant.model.ResetPasswordResponse; import com.homefood.restaurant.model.RevenueResponse; import com.homefood.restaurant.model.Transporter; import com.homefood.restaurant.model.ordernew.OrderResponse; import com.homefood.restaurant.model.product.ProductResponse; import java.util.HashMap; import java.util.List; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; public interface ApiInterface { /*-------------USER--------------------*/ @GET("api/shop/profile") Call<Profile> getProfile(@QueryMap HashMap<String, String> params); @Multipart @POST("api/shop/profile/{id}") Call<Profile> updateProfileWithFile(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename1, @Part MultipartBody.Part filename2); @Multipart @POST("api/shop/profile/{id}") Call<Profile> updateProfile(@Path("id") int id, @PartMap HashMap<String, RequestBody> params); // // @Multipart // @POST("api/user/profile") // Call<User> updateProfileWithImage(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part filename); // // @FormUrlEncoded // @POST("api/user/otp") // Call<Otp> postOtp(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("oauth/token") Call<AuthToken> login(@FieldMap HashMap<String, String> params); @Multipart @POST("api/shop/register") Call<Profile> signUp(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename1, @Part MultipartBody.Part filename2); @GET("api/shop/cuisines") Call<List<Cuisine>> getCuisines(); @FormUrlEncoded @PATCH("api/shop/order/{id}") Call<Order> updateOrderStatus(@Path("id") int id, @FieldMap HashMap<String, String> params); @GET("api/shop/order/{id}") Call<OrderResponse> getParticularOrders(@Path("id") int id); @GET("api/shop/products") Call<List<ProductResponse>> getProductList(); @GET("api/shop/reasons") Call<List<CancelReasons>>getCancelReasonList(); /*-------------ADD-ONS--------------------*/ @GET("api/shop/addons") Call<List<Addon>> getAddons(); @FormUrlEncoded @POST("api/shop/addons") Call<Addon> addAddon(@Field("name") String name,@Field("shop_id") String shop_id); @FormUrlEncoded @PATCH("api/shop/addons/{id}") Call<Addon> updateAddon(@Path("id") int id, @Field("name") String name,@Field("shop_id") String shop_id); @DELETE("api/shop/addons/{id}") Call<List<Addon>> deleteAddon(@Path("id") int id); /*------------- CATEGORY --------------------*/ @GET("api/shop/categories") Call<List<Category>> getCategory(); @Multipart @POST("api/shop/categories") Call<Category> addCategory(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename); @Multipart @POST("api/shop/categories/{id}") Call<Category> updateCategory(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename); @DELETE("api/shop/categories/{id}") Call<List<Category>> deleteCategory(@Path("id") int id); /*---------------Change Password---------------*/ @FormUrlEncoded @POST("api/shop/password") Call<ChangePassword> changePassword(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/forgot/password") Call<ForgotPasswordResponse> forgotPassword(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/verifyotp") Call<ForgotPasswordResponse> verifyOTP(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/reset/password") Call<ResetPasswordResponse> resetPassword(@FieldMap HashMap<String, String> params); /*........Revenue Fragment......*/ @GET("api/shop/revenue") Call<RevenueResponse> getRevenueDetails(); // @Headers("Content-Type: application/json") @Multipart @POST("api/shop/products") Call<ProductResponse> addProduct(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filepart1, @Part MultipartBody.Part filepart2); @Multipart @POST("api/shop/products/{id}") Call<ProductResponse> updateProduct(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filepart1, @Part MultipartBody.Part filepart2); @DELETE("api/shop/products/{id}") Call<ResponseBody> deleteProduct(@Path("id") int id); /*....Account....*/ @DELETE("api/shop/remove/{id}") Call<ResponseBody> deleteAccount(@Path("id") String id); @GET("api/shop/logout") Call<ResponseBody> logOut(); /*-------------ORDER--------------------*/ @GET("api/shop/order") Call<IncomingOrders> getIncomingOrders(@Query("t") String type); @GET("api/shop/history") Call<HistoryModel> getHistory(); @GET("api/shop/history") Call<HistoryModel> getFilterHistory(@QueryMap HashMap<String, String> params); @GET("api/shop/transporterlist") Call<List<Transporter>> getTransporter(); // @GET("api/user/ongoing/order") // Call<List<Order>> getOngoingOrders(); // // @GET("api/user/order/{id}") // Call<Order> getParticularOrders(@Path("id") int id); // // @GET("api/user/order") // Call<List<Order>> getPastOders(); // // @DELETE("api/user/order/{id}") // Call<Order> cancelOrder(@Path("id") int id, @Query("reason") String reason); // // @FormUrlEncoded // @POST("api/user/rating") // Call<ChangePassword> rate(@FieldMap HashMap<String, String> params); // // @FormUrlEncoded // @POST("api/user/reorder") // Call <AddCart> reOrder(@FieldMap HashMap<String, String> params); // // /*-------------DISPUTE--------------------*/ // // @GET("api/user/disputehelp") // Call<List<DisputeMessage>> getDisputeList(); // // @FormUrlEncoded // @POST("api/user/dispute") // Call<Order> postDispute(@FieldMap HashMap<String, String> params); // // // /*-------------SEARCH--------------------*/ // @GET("api/user/search") // Call<Search> getSearch(@QueryMap HashMap<String, String> params); // // /*-----------------------WALLET-----------------------*/ // @GET("api/user/wallet") // Call<List<WalletHistory>> getWalletHistory(); // // @GET("api/user/wallet/promocode") // Call<List<Promotions>> getWalletPromoCode(); // // @FormUrlEncoded // @POST("api/user/wallet/promocode") // Call<PromotionResponse> applyWalletPromoCode(@Field("promocode_id") String id); // // // @GET("json?") // Call<ResponseBody> getResponse(@Query("latlng") String param1, @Query("key") String param2); // // /*-------------PAYMENT--------------------*/ // @GET("api/user/card") // Call<List<Card>> getCardList(); // // @FormUrlEncoded // @POST("api/user/card") // Call<ChangePassword> addCard(@Field("stripe_token") String stripeToken); // // @FormUrlEncoded // @POST("api/user/add/money") // Call<AddMoney> addMoney(@FieldMap HashMap<String, String> params); // // @DELETE("api/user/card/{id}") // Call<ChangePassword> deleteCard(@Path("id") int id); }
UTF-8
Java
8,153
java
ApiInterface.java
Java
[]
null
[]
package com.homefood.restaurant.network; import com.homefood.restaurant.model.Addon; import com.homefood.restaurant.model.AuthToken; import com.homefood.restaurant.model.CancelReasons; import com.homefood.restaurant.model.Category; import com.homefood.restaurant.model.ChangePassword; import com.homefood.restaurant.model.Cuisine; import com.homefood.restaurant.model.ForgotPasswordResponse; import com.homefood.restaurant.model.HistoryModel; import com.homefood.restaurant.model.IncomingOrders; import com.homefood.restaurant.model.Order; import com.homefood.restaurant.model.Profile; import com.homefood.restaurant.model.ResetPasswordResponse; import com.homefood.restaurant.model.RevenueResponse; import com.homefood.restaurant.model.Transporter; import com.homefood.restaurant.model.ordernew.OrderResponse; import com.homefood.restaurant.model.product.ProductResponse; import java.util.HashMap; import java.util.List; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; public interface ApiInterface { /*-------------USER--------------------*/ @GET("api/shop/profile") Call<Profile> getProfile(@QueryMap HashMap<String, String> params); @Multipart @POST("api/shop/profile/{id}") Call<Profile> updateProfileWithFile(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename1, @Part MultipartBody.Part filename2); @Multipart @POST("api/shop/profile/{id}") Call<Profile> updateProfile(@Path("id") int id, @PartMap HashMap<String, RequestBody> params); // // @Multipart // @POST("api/user/profile") // Call<User> updateProfileWithImage(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part filename); // // @FormUrlEncoded // @POST("api/user/otp") // Call<Otp> postOtp(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("oauth/token") Call<AuthToken> login(@FieldMap HashMap<String, String> params); @Multipart @POST("api/shop/register") Call<Profile> signUp(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename1, @Part MultipartBody.Part filename2); @GET("api/shop/cuisines") Call<List<Cuisine>> getCuisines(); @FormUrlEncoded @PATCH("api/shop/order/{id}") Call<Order> updateOrderStatus(@Path("id") int id, @FieldMap HashMap<String, String> params); @GET("api/shop/order/{id}") Call<OrderResponse> getParticularOrders(@Path("id") int id); @GET("api/shop/products") Call<List<ProductResponse>> getProductList(); @GET("api/shop/reasons") Call<List<CancelReasons>>getCancelReasonList(); /*-------------ADD-ONS--------------------*/ @GET("api/shop/addons") Call<List<Addon>> getAddons(); @FormUrlEncoded @POST("api/shop/addons") Call<Addon> addAddon(@Field("name") String name,@Field("shop_id") String shop_id); @FormUrlEncoded @PATCH("api/shop/addons/{id}") Call<Addon> updateAddon(@Path("id") int id, @Field("name") String name,@Field("shop_id") String shop_id); @DELETE("api/shop/addons/{id}") Call<List<Addon>> deleteAddon(@Path("id") int id); /*------------- CATEGORY --------------------*/ @GET("api/shop/categories") Call<List<Category>> getCategory(); @Multipart @POST("api/shop/categories") Call<Category> addCategory(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename); @Multipart @POST("api/shop/categories/{id}") Call<Category> updateCategory(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filename); @DELETE("api/shop/categories/{id}") Call<List<Category>> deleteCategory(@Path("id") int id); /*---------------Change Password---------------*/ @FormUrlEncoded @POST("api/shop/password") Call<ChangePassword> changePassword(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/forgot/password") Call<ForgotPasswordResponse> forgotPassword(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/verifyotp") Call<ForgotPasswordResponse> verifyOTP(@FieldMap HashMap<String, String> params); @FormUrlEncoded @POST("api/shop/reset/password") Call<ResetPasswordResponse> resetPassword(@FieldMap HashMap<String, String> params); /*........Revenue Fragment......*/ @GET("api/shop/revenue") Call<RevenueResponse> getRevenueDetails(); // @Headers("Content-Type: application/json") @Multipart @POST("api/shop/products") Call<ProductResponse> addProduct(@PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filepart1, @Part MultipartBody.Part filepart2); @Multipart @POST("api/shop/products/{id}") Call<ProductResponse> updateProduct(@Path("id") int id, @PartMap HashMap<String, RequestBody> params, @Part MultipartBody.Part filepart1, @Part MultipartBody.Part filepart2); @DELETE("api/shop/products/{id}") Call<ResponseBody> deleteProduct(@Path("id") int id); /*....Account....*/ @DELETE("api/shop/remove/{id}") Call<ResponseBody> deleteAccount(@Path("id") String id); @GET("api/shop/logout") Call<ResponseBody> logOut(); /*-------------ORDER--------------------*/ @GET("api/shop/order") Call<IncomingOrders> getIncomingOrders(@Query("t") String type); @GET("api/shop/history") Call<HistoryModel> getHistory(); @GET("api/shop/history") Call<HistoryModel> getFilterHistory(@QueryMap HashMap<String, String> params); @GET("api/shop/transporterlist") Call<List<Transporter>> getTransporter(); // @GET("api/user/ongoing/order") // Call<List<Order>> getOngoingOrders(); // // @GET("api/user/order/{id}") // Call<Order> getParticularOrders(@Path("id") int id); // // @GET("api/user/order") // Call<List<Order>> getPastOders(); // // @DELETE("api/user/order/{id}") // Call<Order> cancelOrder(@Path("id") int id, @Query("reason") String reason); // // @FormUrlEncoded // @POST("api/user/rating") // Call<ChangePassword> rate(@FieldMap HashMap<String, String> params); // // @FormUrlEncoded // @POST("api/user/reorder") // Call <AddCart> reOrder(@FieldMap HashMap<String, String> params); // // /*-------------DISPUTE--------------------*/ // // @GET("api/user/disputehelp") // Call<List<DisputeMessage>> getDisputeList(); // // @FormUrlEncoded // @POST("api/user/dispute") // Call<Order> postDispute(@FieldMap HashMap<String, String> params); // // // /*-------------SEARCH--------------------*/ // @GET("api/user/search") // Call<Search> getSearch(@QueryMap HashMap<String, String> params); // // /*-----------------------WALLET-----------------------*/ // @GET("api/user/wallet") // Call<List<WalletHistory>> getWalletHistory(); // // @GET("api/user/wallet/promocode") // Call<List<Promotions>> getWalletPromoCode(); // // @FormUrlEncoded // @POST("api/user/wallet/promocode") // Call<PromotionResponse> applyWalletPromoCode(@Field("promocode_id") String id); // // // @GET("json?") // Call<ResponseBody> getResponse(@Query("latlng") String param1, @Query("key") String param2); // // /*-------------PAYMENT--------------------*/ // @GET("api/user/card") // Call<List<Card>> getCardList(); // // @FormUrlEncoded // @POST("api/user/card") // Call<ChangePassword> addCard(@Field("stripe_token") String stripeToken); // // @FormUrlEncoded // @POST("api/user/add/money") // Call<AddMoney> addMoney(@FieldMap HashMap<String, String> params); // // @DELETE("api/user/card/{id}") // Call<ChangePassword> deleteCard(@Path("id") int id); }
8,153
0.671409
0.668098
245
32.27755
31.630077
178
false
false
0
0
0
0
0
0
0.530612
false
false
14
6009ef4be4a03d9ec8366aa8c580f5aa8772a4f6
14,439,680,117,066
ca979fb93c2f9b31e27bec79c2385344b255ad35
/ktest/src/test/java/com/example/ktest/controller/BrInfControllerTest.java
0bd0f91cd07744655450ae9b60d0261326817531
[]
no_license
ddoci3/kakaopayTest
https://github.com/ddoci3/kakaopayTest
93bfbc0944b058fadcffa3b3fda898cf352c8657
4b0de0d99de27ef66b678ac5f5625b0deadf1758
refs/heads/master
2020-11-25T01:19:30.312000
2019-12-16T16:42:17
2019-12-16T16:42:17
228,427,776
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ktest.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; /* * 지점정보 테스트 */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc class BrInfControllerTest { @Autowired MockMvc mockMvc; /* * 테스트 : 연도별 관리점별 거래금액 합계를 구하고 합계금액이 큰 순서로 출력하는 API */ @Test void testSelectBrTrdSumAmtByYearNBrList() throws Exception { // 기대결과 String expected = "[{\"year\":2018,\"dataList\":[{\"brCode\":\"B\",\"brName\":\"분당점\",\"sumAmt\":38484000},{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":20505700},{\"brCode\":\"C\",\"brName\":\"강남점\",\"sumAmt\":20232867},{\"brCode\":\"D\",\"brName\":\"잠실점\",\"sumAmt\":14000000}]},{\"year\":2019,\"dataList\":[{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":66795100},{\"brCode\":\"B\",\"brName\":\"분당점\",\"sumAmt\":45396700},{\"brCode\":\"C\",\"brName\":\"강남점\",\"sumAmt\":19500000},{\"brCode\":\"D\",\"brName\":\"잠실점\",\"sumAmt\":6000000}]}]"; mockMvc.perform(get("/selectBrTrdSumAmtByYearNBrList")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } /* * 테스트 : 지점 통폐합 처리 */ @Test void testIntgBrInf() throws Exception { // 기대결과 String expected = "분당점과 판교점 통폐합 처리 완료."; mockMvc.perform(get("/intgBrInf")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } /* * 테스트 : 지점명을 입력하면 해당지점의 거래금액 합계를 출력하는 API */ @Test void testSelectBrTrdSumAmt() throws Exception { /* * 1. 분당점으로 조회시 오류 발생 */ // 기대결과 String expected = "{\"code\":\"404\", \"메세지\":\"br code not found error\"}"; mockMvc.perform(get("/selectBrTrdSumAmt?brName=분당점")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); /* * 2. 판교점으로 조회시 정상 조회 */ // 기대결과 expected = "{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":171181500}"; mockMvc.perform(get("/selectBrTrdSumAmt?brName=판교점")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } }
UHC
Java
3,099
java
BrInfControllerTest.java
Java
[]
null
[]
package com.example.ktest.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; /* * 지점정보 테스트 */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc class BrInfControllerTest { @Autowired MockMvc mockMvc; /* * 테스트 : 연도별 관리점별 거래금액 합계를 구하고 합계금액이 큰 순서로 출력하는 API */ @Test void testSelectBrTrdSumAmtByYearNBrList() throws Exception { // 기대결과 String expected = "[{\"year\":2018,\"dataList\":[{\"brCode\":\"B\",\"brName\":\"분당점\",\"sumAmt\":38484000},{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":20505700},{\"brCode\":\"C\",\"brName\":\"강남점\",\"sumAmt\":20232867},{\"brCode\":\"D\",\"brName\":\"잠실점\",\"sumAmt\":14000000}]},{\"year\":2019,\"dataList\":[{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":66795100},{\"brCode\":\"B\",\"brName\":\"분당점\",\"sumAmt\":45396700},{\"brCode\":\"C\",\"brName\":\"강남점\",\"sumAmt\":19500000},{\"brCode\":\"D\",\"brName\":\"잠실점\",\"sumAmt\":6000000}]}]"; mockMvc.perform(get("/selectBrTrdSumAmtByYearNBrList")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } /* * 테스트 : 지점 통폐합 처리 */ @Test void testIntgBrInf() throws Exception { // 기대결과 String expected = "분당점과 판교점 통폐합 처리 완료."; mockMvc.perform(get("/intgBrInf")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } /* * 테스트 : 지점명을 입력하면 해당지점의 거래금액 합계를 출력하는 API */ @Test void testSelectBrTrdSumAmt() throws Exception { /* * 1. 분당점으로 조회시 오류 발생 */ // 기대결과 String expected = "{\"code\":\"404\", \"메세지\":\"br code not found error\"}"; mockMvc.perform(get("/selectBrTrdSumAmt?brName=분당점")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); /* * 2. 판교점으로 조회시 정상 조회 */ // 기대결과 expected = "{\"brCode\":\"A\",\"brName\":\"판교점\",\"sumAmt\":171181500}"; mockMvc.perform(get("/selectBrTrdSumAmt?brName=판교점")) .andExpect(status().isOk()) .andExpect(content().string(expected)) .andDo(print()); } }
3,099
0.679204
0.648101
87
30.781609
61.566044
549
false
false
0
0
0
0
0
0
1.701149
false
false
14
a245f4907d1d576a994766fa1f8ad4473f9d3c40
11,476,152,641,906
806d59fd9a3bf4401f29bf139d491677c34e985a
/src/main/java/com/ramalapure/dp/abstractfactory/Car.java
ec1df9a567878de9743dfbe2604ee6f506309a40
[]
no_license
RamAlapure/Design-Patterns
https://github.com/RamAlapure/Design-Patterns
35c775eece55b4a1bcf4fbad32324b8707687b63
4eeae78776ba070feabe8bd8b3d775d97748f3e1
refs/heads/master
2022-02-08T00:28:33.866000
2022-01-29T13:26:26
2022-01-29T13:26:26
91,100,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ramalapure.dp.abstractfactory; public interface Car { int getPrice(); }
UTF-8
Java
90
java
Car.java
Java
[]
null
[]
package com.ramalapure.dp.abstractfactory; public interface Car { int getPrice(); }
90
0.733333
0.733333
6
14
15.459625
42
false
false
0
0
0
0
0
0
0.333333
false
false
14
b6ee20ad71c34b73664a0396c15ebaf946f0b8a9
23,450,521,476,780
e13253a26578ac44976737f673ea67aaa8708ef2
/spring-boot-redis/src/main/java/com/suchaos/service/UserService.java
6dddd991c5567b2f6d9472cc5895ae4dfff2c97e
[]
no_license
suchaos/spring-boot-learn
https://github.com/suchaos/spring-boot-learn
bcc2bf4ac48496d7ecdfdd75a445ee7f96d25fd4
5131b3d1559034dc5279049f0d5d767ac9baaf38
refs/heads/master
2022-10-23T03:17:33.040000
2019-11-11T08:41:01
2019-11-11T08:41:01
158,498,511
0
0
null
false
2022-10-05T19:17:22
2018-11-21T06:00:58
2019-11-11T08:41:14
2022-10-05T19:17:20
197
0
0
3
Java
false
false
package com.suchaos.service; import com.suchaos.model.User; public interface UserService { User getUserById(long id); void deleteUserById(long id); }
UTF-8
Java
161
java
UserService.java
Java
[]
null
[]
package com.suchaos.service; import com.suchaos.model.User; public interface UserService { User getUserById(long id); void deleteUserById(long id); }
161
0.745342
0.745342
9
16.888889
14.932771
33
false
false
0
0
0
0
0
0
0.444444
false
false
14
b460402d19ad2ab4b5353fa598bf0605cbcbe13d
23,450,521,476,721
5707536bdaffe1c0de2abfa838111cabb287c452
/components/org.wso2.carbon.identity.oauth.extension/src/main/java/org/wso2/carbon/identity/oauth/extension/utils/EngineUtils.java
f2a74bd72760537c9b6e400918dcd7da71945c77
[ "Apache-2.0" ]
permissive
wso2-extensions/identity-inbound-auth-oauth
https://github.com/wso2-extensions/identity-inbound-auth-oauth
1ea5481d0595e56fdf972c1bc6e6bd1c61bd7d82
d153b3dd2ae065df135566cb6e8951ac8c1a8645
refs/heads/master
2023-09-01T08:58:09.127000
2023-09-01T05:37:33
2023-09-01T05:37:33
52,758,721
28
410
Apache-2.0
false
2023-09-14T12:13:20
2016-02-29T02:41:06
2023-07-05T11:10:32
2023-09-14T11:53:39
32,368
21
351
69
Java
false
false
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth.extension.utils; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.extension.engine.JSEngine; import org.wso2.carbon.identity.oauth.extension.engine.impl.JSEngineImpl; import org.wso2.carbon.identity.oauth.extension.engine.impl.OpenJdkJSEngineImpl; import static org.wso2.carbon.identity.oauth.extension.utils.Constants.JDK_SCRIPT_CLASS_NAME; import static org.wso2.carbon.identity.oauth.extension.utils.Constants.OPENJDK_SCRIPT_CLASS_NAME; /** * Utility class for JSEngine. */ public class EngineUtils { /** * Get the JSEngine based on the configuration. * * @return JSEngine instance. */ public static JSEngine getEngineFromConfig() { String scriptEngineName = IdentityUtil.getProperty(FrameworkConstants.SCRIPT_ENGINE_CONFIG); if (scriptEngineName != null) { if (StringUtils.equalsIgnoreCase(FrameworkConstants.OPENJDK_NASHORN, scriptEngineName)) { return OpenJdkJSEngineImpl.getInstance(); } } return getEngineBasedOnAvailability(); } private static JSEngine getEngineBasedOnAvailability() { try { Class.forName(OPENJDK_SCRIPT_CLASS_NAME); return OpenJdkJSEngineImpl.getInstance(); } catch (ClassNotFoundException e) { try { Class.forName(JDK_SCRIPT_CLASS_NAME); return JSEngineImpl.getInstance(); } catch (ClassNotFoundException classNotFoundException) { return null; } } } }
UTF-8
Java
2,407
java
EngineUtils.java
Java
[]
null
[]
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth.extension.utils; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.extension.engine.JSEngine; import org.wso2.carbon.identity.oauth.extension.engine.impl.JSEngineImpl; import org.wso2.carbon.identity.oauth.extension.engine.impl.OpenJdkJSEngineImpl; import static org.wso2.carbon.identity.oauth.extension.utils.Constants.JDK_SCRIPT_CLASS_NAME; import static org.wso2.carbon.identity.oauth.extension.utils.Constants.OPENJDK_SCRIPT_CLASS_NAME; /** * Utility class for JSEngine. */ public class EngineUtils { /** * Get the JSEngine based on the configuration. * * @return JSEngine instance. */ public static JSEngine getEngineFromConfig() { String scriptEngineName = IdentityUtil.getProperty(FrameworkConstants.SCRIPT_ENGINE_CONFIG); if (scriptEngineName != null) { if (StringUtils.equalsIgnoreCase(FrameworkConstants.OPENJDK_NASHORN, scriptEngineName)) { return OpenJdkJSEngineImpl.getInstance(); } } return getEngineBasedOnAvailability(); } private static JSEngine getEngineBasedOnAvailability() { try { Class.forName(OPENJDK_SCRIPT_CLASS_NAME); return OpenJdkJSEngineImpl.getInstance(); } catch (ClassNotFoundException e) { try { Class.forName(JDK_SCRIPT_CLASS_NAME); return JSEngineImpl.getInstance(); } catch (ClassNotFoundException classNotFoundException) { return null; } } } }
2,407
0.705858
0.697964
66
35.469696
30.106991
101
false
false
0
0
0
0
0
0
0.363636
false
false
14
c3a0e07c68254982b34402ad0a3dba88776155e3
2,826,088,527,307
ef502009df3d53708ce006d7a06c4b749a8a3c32
/src/main/java/backend/field/Pilier.java
2279e07827ff335955b7b24071c44d2cb9eab75f
[]
no_license
EldernXa/Water_Emblem
https://github.com/EldernXa/Water_Emblem
9b300559ef9380806a33abb84f0c489a42a0782b
1915bc7085b3f213ab8ae0155149062689fe0b23
refs/heads/master
2022-09-14T09:04:13.554000
2020-05-27T23:20:40
2020-05-27T23:20:40
255,077,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package backend.field; public class Pilier extends Corniche { public Pilier() { super("pilier"); } // pourquoi extends corniche ? }
UTF-8
Java
149
java
Pilier.java
Java
[]
null
[]
package backend.field; public class Pilier extends Corniche { public Pilier() { super("pilier"); } // pourquoi extends corniche ? }
149
0.651007
0.651007
7
20.285715
13.94596
38
false
false
0
0
0
0
0
0
0.285714
false
false
14
6e7fbe78c4c481def7c40fb4e07a6937b9bcccb1
13,511,967,157,947
1d267057a60deae16e5be7596a998157a923422d
/src/com/github/mauricioaniche/ck/metric/Metric.java
5e4c078eb9457283e2938cb92d3cf73bfdc68820
[]
no_license
emadpres/CodeTimeMachine
https://github.com/emadpres/CodeTimeMachine
dc0ee30bbe5521c29ad04314c1fe8f0790e102e2
a824eefba23d768b12c14575b502050a87bc5e59
refs/heads/master
2023-03-05T16:43:51.916000
2021-02-22T12:01:20
2021-02-22T12:01:20
74,590,377
8
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.mauricioaniche.ck.metric; import org.eclipse.jdt.core.dom.CompilationUnit; import com.github.mauricioaniche.ck.CKNumber; import com.github.mauricioaniche.ck.CKReport; public interface Metric { void execute(CompilationUnit cu, CKNumber result, CKReport report); void setResult(CKNumber result); }
UTF-8
Java
321
java
Metric.java
Java
[ { "context": "package com.github.mauricioaniche.ck.metric;\n\nimport org.eclipse.jdt.core.dom.Compi", "end": 33, "score": 0.9920231699943542, "start": 19, "tag": "USERNAME", "value": "mauricioaniche" }, { "context": ".jdt.core.dom.CompilationUnit;\n\nimport com.github.mauricioaniche.ck.CKNumber;\nimport com.github.mauricioaniche.ck.", "end": 128, "score": 0.9903866052627563, "start": 114, "tag": "USERNAME", "value": "mauricioaniche" }, { "context": "hub.mauricioaniche.ck.CKNumber;\nimport com.github.mauricioaniche.ck.CKReport;\n\npublic interface Metric {\n\n\tvoid ex", "end": 174, "score": 0.990215003490448, "start": 160, "tag": "USERNAME", "value": "mauricioaniche" } ]
null
[]
package com.github.mauricioaniche.ck.metric; import org.eclipse.jdt.core.dom.CompilationUnit; import com.github.mauricioaniche.ck.CKNumber; import com.github.mauricioaniche.ck.CKReport; public interface Metric { void execute(CompilationUnit cu, CKNumber result, CKReport report); void setResult(CKNumber result); }
321
0.813084
0.813084
12
25.75
23.580093
68
false
false
0
0
0
0
0
0
0.833333
false
false
14
ae1191a78d930158e1c73420945e7c7770ab074f
5,703,716,633,539
f6f09c47d2c14818c41733d6aba50c4770a16be2
/week6/codes/Student.java
559f2fbb9906fa7c1ae0fda5a029d24ae61a06f0
[]
no_license
minseonpub/Java
https://github.com/minseonpub/Java
b84b268032bf09faab75a2c5c002c15abb737e9f
588932a4eada1ffc478938ae2bb60ee3d182ebff
refs/heads/master
2020-06-11T17:25:04.206000
2019-06-27T07:17:36
2019-06-27T07:17:36
194,035,820
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Student.java class Student { String name; int ID; public Student(String name, int ID) { this.name = name; this.ID = ID; } @Override public String toString() { //return "Student name "+name+" and ID : "+ID; //Question 2-(b) return getClass().getName()+" @ "+Integer.toHexString(hashCode()); } /* // Question 5 @Override public boolean equals(Object obj) // S1.equal(S2) { try { String name1 = this.name; // this refers to S1 int ID1= this.ID; Student s = (Student)obj; String name2 = s.name; int ID2= s.ID; if(name1.contentEquals(name2)&&(ID1==ID2)) return true; else return false; } // end of try block catch(ClassCastException e) { return false; } catch(NullPointerException e) { return false; } }//end of equals */ //problem 6 /*@Override public boolean equals(Object obj) { try { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) { return true; } else { return false; } } catch (ClassCastException e) //Error of casting { return false; } catch (NullPointerException e) //변수 선언후 생성전에 접근시 에러 { return false; } }*/ //problem 7 @Override public boolean equals(Object obj) { if (obj instanceof Student) { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) // casting yes or no return true; else return false; } else return false; } //problem 8 /*@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Student) { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) { return true; } else { return false; } } else { return false; } }*/ public static void main(String[] arg) { Student S1 = new Student("Kim", 101); Student S2 = new Student("Homin",102); /* System.out.println(S1); System.out.println(S1.toString()); System.out.println(S2); */ Student S3 = new Student("Homin",102); Student S4 = S1; System.out.println(S1.equals(S2)); System.out.println(S1.equals(S3)); System.out.println(S1.equals(S4)); System.out.println(S1.equals("Kim")); System.out.println(S1.equals(null)); }// end of main }// end of class
UHC
Java
2,491
java
Student.java
Java
[ { "context": "in(String[] arg)\r\n\t{\r\n\t\tStudent S1 = new Student(\"Kim\", 101);\r\n\t\tStudent S2 = new Student(\"Homin\",102);", "end": 2008, "score": 0.9995784163475037, "start": 2005, "tag": "NAME", "value": "Kim" }, { "context": "Student(\"Kim\", 101);\r\n\t\tStudent S2 = new Student(\"Homin\",102);\r\n\t\t/*\r\n\t\tSystem.out.println(S1);\r\n\t\tSystem", "end": 2051, "score": 0.9997481107711792, "start": 2046, "tag": "NAME", "value": "Homin" }, { "context": ".println(S2);\r\n\t\t*/\t\r\n\t\tStudent S3 = new Student(\"Homin\",102);\r\n\t\tStudent S4 = S1;\r\n\t\tSystem.out.println(", "end": 2198, "score": 0.999727725982666, "start": 2193, "tag": "NAME", "value": "Homin" } ]
null
[]
// Student.java class Student { String name; int ID; public Student(String name, int ID) { this.name = name; this.ID = ID; } @Override public String toString() { //return "Student name "+name+" and ID : "+ID; //Question 2-(b) return getClass().getName()+" @ "+Integer.toHexString(hashCode()); } /* // Question 5 @Override public boolean equals(Object obj) // S1.equal(S2) { try { String name1 = this.name; // this refers to S1 int ID1= this.ID; Student s = (Student)obj; String name2 = s.name; int ID2= s.ID; if(name1.contentEquals(name2)&&(ID1==ID2)) return true; else return false; } // end of try block catch(ClassCastException e) { return false; } catch(NullPointerException e) { return false; } }//end of equals */ //problem 6 /*@Override public boolean equals(Object obj) { try { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) { return true; } else { return false; } } catch (ClassCastException e) //Error of casting { return false; } catch (NullPointerException e) //변수 선언후 생성전에 접근시 에러 { return false; } }*/ //problem 7 @Override public boolean equals(Object obj) { if (obj instanceof Student) { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) // casting yes or no return true; else return false; } else return false; } //problem 8 /*@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Student) { Student s = (Student)obj; if (name.equals(s.name) && (ID == s.ID)) { return true; } else { return false; } } else { return false; } }*/ public static void main(String[] arg) { Student S1 = new Student("Kim", 101); Student S2 = new Student("Homin",102); /* System.out.println(S1); System.out.println(S1.toString()); System.out.println(S2); */ Student S3 = new Student("Homin",102); Student S4 = S1; System.out.println(S1.equals(S2)); System.out.println(S1.equals(S3)); System.out.println(S1.equals(S4)); System.out.println(S1.equals("Kim")); System.out.println(S1.equals(null)); }// end of main }// end of class
2,491
0.554608
0.537962
138
15.833333
15.209448
68
false
false
0
0
0
0
0
0
2.434783
false
false
14
2885c7a8bd04dddce8dce0d55a6c96b2a973a1a8
7,009,386,680,879
23f61e33bf7bdb6f62e30f1462442969271505ca
/src/main/java/pl/psawczuk/mailreader/business/GmailAccountService.java
fcf99030c753a21904574624755a4515b314dc98
[]
no_license
piotrsawczuk/Mailreader
https://github.com/piotrsawczuk/Mailreader
a0ef15ff5f8412539bc3d0ad1cfc27a8fa7ed403
8139bc6843c53b78be7c4d22414b3343a4997dfd
refs/heads/master
2017-12-09T18:17:39.409000
2017-01-17T11:34:36
2017-01-17T11:34:36
79,221,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.psawczuk.mailreader.business; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.psawczuk.mailreader.domain.dao.GmailAccountDao; import pl.psawczuk.mailreader.domain.entity.GmailAccount; import java.util.ArrayList; import java.util.List; @Service public class GmailAccountService { @Autowired private GmailAccountDao gmailAccountDao; @Autowired private MailInfoService mailInfoService; public List<GmailAccount> findByUserId(Long userId){ List<GmailAccount> gmailAccounts = gmailAccountDao.findByUserId(userId); return (gmailAccounts == null || gmailAccounts.isEmpty()) ? new ArrayList<>() : gmailAccounts; } public GmailAccount findByUserIdAndLogin(Long userId, String login){ GmailAccount gmailAccount = gmailAccountDao.findByUserIdAndLogin(userId, login); return gmailAccount; } public boolean addAccount(Long userId, String login, String password) { GmailAccount account = gmailAccountDao.findByUserIdAndLogin(userId, login); GmailAccount accountAdded = new GmailAccount(); if (account == null) { accountAdded.setUserId(userId); accountAdded.setLogin(login); accountAdded.setPassword(password); gmailAccountDao.save(accountAdded); return true; } return false; } public boolean deleteAccount(Long userId, String login){ GmailAccount account = gmailAccountDao.findByUserIdAndLogin(userId, login); if (account != null) { mailInfoService.deleteMailMessages(account.getId()); gmailAccountDao.delete(account); return true; } return false; } }
UTF-8
Java
1,783
java
GmailAccountService.java
Java
[]
null
[]
package pl.psawczuk.mailreader.business; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.psawczuk.mailreader.domain.dao.GmailAccountDao; import pl.psawczuk.mailreader.domain.entity.GmailAccount; import java.util.ArrayList; import java.util.List; @Service public class GmailAccountService { @Autowired private GmailAccountDao gmailAccountDao; @Autowired private MailInfoService mailInfoService; public List<GmailAccount> findByUserId(Long userId){ List<GmailAccount> gmailAccounts = gmailAccountDao.findByUserId(userId); return (gmailAccounts == null || gmailAccounts.isEmpty()) ? new ArrayList<>() : gmailAccounts; } public GmailAccount findByUserIdAndLogin(Long userId, String login){ GmailAccount gmailAccount = gmailAccountDao.findByUserIdAndLogin(userId, login); return gmailAccount; } public boolean addAccount(Long userId, String login, String password) { GmailAccount account = gmailAccountDao.findByUserIdAndLogin(userId, login); GmailAccount accountAdded = new GmailAccount(); if (account == null) { accountAdded.setUserId(userId); accountAdded.setLogin(login); accountAdded.setPassword(password); gmailAccountDao.save(accountAdded); return true; } return false; } public boolean deleteAccount(Long userId, String login){ GmailAccount account = gmailAccountDao.findByUserIdAndLogin(userId, login); if (account != null) { mailInfoService.deleteMailMessages(account.getId()); gmailAccountDao.delete(account); return true; } return false; } }
1,783
0.701626
0.701626
56
30.839285
28.444668
102
false
false
0
0
0
0
0
0
0.625
false
false
14
e89d916633acaab7ba4b41eb2658946dd6356cad
19,181,323,949,189
41ea7b7bc1c666e433f95887c0eb4c369d9efa64
/json4img-rest/src/main/java/com/github/vitalz/jrest/json4img/service/file/FileStorageFactory.java
311c333ddebbfa725d28aa306a6020e9f477f77f
[ "Apache-2.0" ]
permissive
vitalz/jrest-json4img
https://github.com/vitalz/jrest-json4img
7e4191bd9996fd87ba219a42589a77926c08e697
1626a33eef9190501114f9ad51fb3c46666ea6af
refs/heads/main
2023-02-26T21:21:00.227000
2021-03-17T08:35:19
2021-03-17T08:35:19
333,541,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.vitalz.jrest.json4img.service.file; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public final class FileStorageFactory { private final Logger log = LoggerFactory.getLogger(FileStorageFactory.class); private String sharedDir; private String outputDir; public String getSharedDir() { return sharedDir; } public void setSharedDir(String sharedDir) { this.sharedDir = sharedDir; } public String getOutputDir() { return outputDir; } public void setOutputDir(String outputDir) { this.outputDir = outputDir; } public FileStorage createFileStorageService() { log.info("...Initializing file storage:\n\tsharedDir: '{}'\n\toutputDir: {}", this.sharedDir, this.outputDir); return new FileStorageService(() -> new File(this.sharedDir), () -> new File(this.outputDir)); // do not care of current state for file system at init } }
UTF-8
Java
978
java
FileStorageFactory.java
Java
[ { "context": "package com.github.vitalz.jrest.json4img.service.file;\n\nimport org.slf4j.Lo", "end": 25, "score": 0.9981823563575745, "start": 19, "tag": "USERNAME", "value": "vitalz" } ]
null
[]
package com.github.vitalz.jrest.json4img.service.file; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public final class FileStorageFactory { private final Logger log = LoggerFactory.getLogger(FileStorageFactory.class); private String sharedDir; private String outputDir; public String getSharedDir() { return sharedDir; } public void setSharedDir(String sharedDir) { this.sharedDir = sharedDir; } public String getOutputDir() { return outputDir; } public void setOutputDir(String outputDir) { this.outputDir = outputDir; } public FileStorage createFileStorageService() { log.info("...Initializing file storage:\n\tsharedDir: '{}'\n\toutputDir: {}", this.sharedDir, this.outputDir); return new FileStorageService(() -> new File(this.sharedDir), () -> new File(this.outputDir)); // do not care of current state for file system at init } }
978
0.692229
0.689162
34
27.764706
34.573925
158
false
false
0
0
0
0
0
0
0.470588
false
false
14
cfe05d779b723b1df6c27830bb15bfc2e06e8f3a
28,501,402,981,563
1e33feba7c38878df347723e3852a38c311bc0c9
/Unlock-Overall/app/src/main/java/com/example/weiweili/gridunlock/DisplaySmallTen.java
34c8b8dd23d232856fdc3b1702f85326b1320864
[]
no_license
Juik/HCI-Android-Unlocking
https://github.com/Juik/HCI-Android-Unlocking
c7b349c62b61a4c1a238cd3260ceda4ecb7daf62
cd6deb1e78a760a6d6065b2e2b0a6a2c1d048c43
refs/heads/master
2021-01-10T15:53:46.384000
2016-03-26T14:32:54
2016-03-26T14:32:54
53,423,527
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.weiweili.gridunlock; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.FileOutputStream; public class DisplaySmallTen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_small_ten); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Intent intent = getIntent(); String message = intent.getStringExtra(SmallTen.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(10); textView.setText(message); RelativeLayout layout = (RelativeLayout) findViewById(R.id.content3); layout.addView(textView); String filename = "myfile"; String string = message; string = "------Ci-dessous est le résultat de SmallTen------\n"+string+"-------Ci-dessus est la suite de SmallTen-------\n"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_APPEND); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public void next(View view){ Intent intent = new Intent(this, SmallSix.class); startActivity(intent); } }
UTF-8
Java
1,767
java
DisplaySmallTen.java
Java
[ { "context": "package com.example.weiweili.gridunlock;\n\nimport android.content.Context;\nimpo", "end": 28, "score": 0.8350912928581238, "start": 20, "tag": "USERNAME", "value": "weiweili" } ]
null
[]
package com.example.weiweili.gridunlock; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.FileOutputStream; public class DisplaySmallTen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_small_ten); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Intent intent = getIntent(); String message = intent.getStringExtra(SmallTen.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(10); textView.setText(message); RelativeLayout layout = (RelativeLayout) findViewById(R.id.content3); layout.addView(textView); String filename = "myfile"; String string = message; string = "------Ci-dessous est le résultat de SmallTen------\n"+string+"-------Ci-dessus est la suite de SmallTen-------\n"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_APPEND); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public void next(View view){ Intent intent = new Intent(this, SmallSix.class); startActivity(intent); } }
1,767
0.686863
0.684032
55
31.109091
25.878508
132
false
false
0
0
0
0
0
0
0.636364
false
false
14
a4bc4512687e90d495ac36efdaaaddc0d60b2bc4
2,121,713,883,008
28e2ebfe0218cbbd48dcf099144b8dc44ecefcf3
/app/src/main/java/org/random_access/flashcardsmanager/xmlImport/LFRelParser.java
4a5f2b67ad67bd3784bf6fbf6243acb9bb4d4228
[]
no_license
random-access/FlashCardsManager-Android
https://github.com/random-access/FlashCardsManager-Android
14930aba1270fe5e894316cdc4d5eef1a6c45e0d
f1017829ef910057a5d7178c32cdbcc3940df9d2
refs/heads/master
2021-01-19T16:50:48.392000
2017-02-19T12:48:42
2017-02-19T12:48:42
35,418,636
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.random_access.flashcardsmanager.xmlImport; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * <b>Project:</b> FlashCards Manager for Android <br> * <b>Date:</b> 12.06.15 <br> * <b>Author:</b> Monika Schrenk <br> * <b>E-Mail:</b> software@random-access.org <br> */ public class LFRelParser extends XMLParser { // project property strings // flashcard property strings private static final String ELEM_ROOT_ENTRY= "labels_flashcards"; private static final String ELEM_BASE_ENTRY = "label_flashcard"; private static final String ELEM_LABELS_FLASHCARDS_ID = "labels_flashcards_id"; private static final String ELEM_LABEL_ID = "label_id"; private static final String ELEM_CARD_ID = "card_id"; // We don't use namespaces private static final String ns = null; public ArrayList<LFRel> parse(InputStream in) throws XmlPullParserException, IOException { try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, null); parser.nextTag(); return readXML(parser); } finally { in.close(); } } private ArrayList<LFRel> readXML(XmlPullParser parser) throws XmlPullParserException, IOException { ArrayList<LFRel> entries = new ArrayList<>(); parser.require(XmlPullParser.START_TAG, ns, ELEM_ROOT_ENTRY); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if (name.equals(ELEM_BASE_ENTRY)) { entries.add(readEntry(parser)); } else { skip(parser); } } return entries; } public static class LFRel { public final long id; public final long labelId; public final long cardId; private LFRel(long id, long labelId, long cardId) { this.id = id; this.labelId = labelId; this.cardId = cardId; } } // Parses the contents of an entry private LFRel readEntry(XmlPullParser parser) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, ns, ELEM_BASE_ENTRY); long id = 0; long labelId = 0; long cardId = 0; while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); switch (name) { case ELEM_LABELS_FLASHCARDS_ID: id = Integer.parseInt(readContent(parser, ns, ELEM_LABELS_FLASHCARDS_ID)); break; case ELEM_CARD_ID: cardId = Integer.parseInt(readContent(parser, ns, ELEM_CARD_ID)); break; case ELEM_LABEL_ID: labelId = Integer.parseInt(readContent(parser, ns, ELEM_LABEL_ID)); break; default: skip(parser); } } return new LFRel(id, labelId, cardId); } }
UTF-8
Java
3,436
java
LFRelParser.java
Java
[ { "context": "r>\n * <b>Date:</b> 12.06.15 <br>\n * <b>Author:</b> Monika Schrenk <br>\n * <b>E-Mail:</b> software@random-access.org", "end": 372, "score": 0.9998588562011719, "start": 358, "tag": "NAME", "value": "Monika Schrenk" }, { "context": ">Author:</b> Monika Schrenk <br>\n * <b>E-Mail:</b> software@random-access.org <br>\n */\npublic class LFRelParser extends XMLPars", "end": 422, "score": 0.9999212026596069, "start": 396, "tag": "EMAIL", "value": "software@random-access.org" } ]
null
[]
package org.random_access.flashcardsmanager.xmlImport; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * <b>Project:</b> FlashCards Manager for Android <br> * <b>Date:</b> 12.06.15 <br> * <b>Author:</b> <NAME> <br> * <b>E-Mail:</b> <EMAIL> <br> */ public class LFRelParser extends XMLParser { // project property strings // flashcard property strings private static final String ELEM_ROOT_ENTRY= "labels_flashcards"; private static final String ELEM_BASE_ENTRY = "label_flashcard"; private static final String ELEM_LABELS_FLASHCARDS_ID = "labels_flashcards_id"; private static final String ELEM_LABEL_ID = "label_id"; private static final String ELEM_CARD_ID = "card_id"; // We don't use namespaces private static final String ns = null; public ArrayList<LFRel> parse(InputStream in) throws XmlPullParserException, IOException { try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, null); parser.nextTag(); return readXML(parser); } finally { in.close(); } } private ArrayList<LFRel> readXML(XmlPullParser parser) throws XmlPullParserException, IOException { ArrayList<LFRel> entries = new ArrayList<>(); parser.require(XmlPullParser.START_TAG, ns, ELEM_ROOT_ENTRY); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); if (name.equals(ELEM_BASE_ENTRY)) { entries.add(readEntry(parser)); } else { skip(parser); } } return entries; } public static class LFRel { public final long id; public final long labelId; public final long cardId; private LFRel(long id, long labelId, long cardId) { this.id = id; this.labelId = labelId; this.cardId = cardId; } } // Parses the contents of an entry private LFRel readEntry(XmlPullParser parser) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, ns, ELEM_BASE_ENTRY); long id = 0; long labelId = 0; long cardId = 0; while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); switch (name) { case ELEM_LABELS_FLASHCARDS_ID: id = Integer.parseInt(readContent(parser, ns, ELEM_LABELS_FLASHCARDS_ID)); break; case ELEM_CARD_ID: cardId = Integer.parseInt(readContent(parser, ns, ELEM_CARD_ID)); break; case ELEM_LABEL_ID: labelId = Integer.parseInt(readContent(parser, ns, ELEM_LABEL_ID)); break; default: skip(parser); } } return new LFRel(id, labelId, cardId); } }
3,409
0.58993
0.586729
100
33.369999
25.504374
103
false
false
0
0
0
0
0
0
0.65
false
false
14
2473527898ca2bf4df36742d284a7b363ca7fa65
27,144,193,330,683
4a072b02f1a9a18b0b9d32a6ce193de40467974f
/src/main/java/com/fpi/bims/service/UserServiceImpl.java
c857507efca89253b67567b9d3e3c88e5e7420d4
[]
no_license
TeamFirstAll/team
https://github.com/TeamFirstAll/team
6ef1eaa1e7b42344afa7777b7f239c7f68227257
9997b18705a2a1a52bb7025f0de7072be829c41b
refs/heads/master
2020-03-28T18:28:29.174000
2018-09-19T05:07:54
2018-09-19T05:07:54
148,884,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fpi.bims.service; import com.fpi.bims.dao.repository.UserRepository; import com.fpi.bims.model.BaseRegion; import com.fpi.bims.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author kangkang_sun * @date 2018/01/15 */ @Service public class UserServiceImpl implements UserService { Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserRepository userRepository; @Autowired private JdbcTemplate jdbcTemplate; @Override public void saveUser(User user) { userRepository.save(user); } @Override public void updateUser(User user) { saveUser(user); } @Override public void deleteUserById(Long id) { userRepository.delete(id); } @Override public User findUserById(Long id) { return userRepository.findOne(id); } @Override public User findUserByName(String name) { return userRepository.findByUserName(name); } @Override public Page<User> findPageByName(String name, Pageable pageable) { logger.info("findPageByName, name=" + name); return userRepository.findPageByName(name, pageable); } @Override public List<BaseRegion> findRegion(String name, Pageable pageable) { List<Map<String,Object>> list = jdbcTemplate.queryForList("SELECT * FROM BASE_REGION"); List<BaseRegion> regionList = new ArrayList<BaseRegion>(); for (int i=0;i<list.size();i++){ BaseRegion region = new BaseRegion(); region.setName(list.get(i).get("name").toString()); regionList.add(region); } return regionList; } }
UTF-8
Java
2,114
java
UserServiceImpl.java
Java
[ { "context": "l.List;\r\nimport java.util.Map;\r\n\r\n/**\r\n * @author kangkang_sun\r\n * @date 2018/01/15\r\n */\r\n@Service\r\npublic clas", "end": 585, "score": 0.9997177124023438, "start": 573, "tag": "USERNAME", "value": "kangkang_sun" } ]
null
[]
package com.fpi.bims.service; import com.fpi.bims.dao.repository.UserRepository; import com.fpi.bims.model.BaseRegion; import com.fpi.bims.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author kangkang_sun * @date 2018/01/15 */ @Service public class UserServiceImpl implements UserService { Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserRepository userRepository; @Autowired private JdbcTemplate jdbcTemplate; @Override public void saveUser(User user) { userRepository.save(user); } @Override public void updateUser(User user) { saveUser(user); } @Override public void deleteUserById(Long id) { userRepository.delete(id); } @Override public User findUserById(Long id) { return userRepository.findOne(id); } @Override public User findUserByName(String name) { return userRepository.findByUserName(name); } @Override public Page<User> findPageByName(String name, Pageable pageable) { logger.info("findPageByName, name=" + name); return userRepository.findPageByName(name, pageable); } @Override public List<BaseRegion> findRegion(String name, Pageable pageable) { List<Map<String,Object>> list = jdbcTemplate.queryForList("SELECT * FROM BASE_REGION"); List<BaseRegion> regionList = new ArrayList<BaseRegion>(); for (int i=0;i<list.size();i++){ BaseRegion region = new BaseRegion(); region.setName(list.get(i).get("name").toString()); regionList.add(region); } return regionList; } }
2,114
0.668401
0.663198
79
24.784811
22.923468
95
false
false
0
0
0
0
0
0
0.468354
false
false
14
41e2f229711e0bcbee146a0360dddbe36ca86e64
29,343,216,591,313
63d0d046b6f1c6aa84247cdf30160ce706135a05
/inClassDay21/src/BasketBallTeam.java
6cef9f8f393183d405adb8a0afae3130a5b3d0dc
[]
no_license
justin13520/Software_Development_HW
https://github.com/justin13520/Software_Development_HW
22f9fca4e02ccc263ae9792d35509f250cab622b
144c4a1b4e6de4edf544b91aa452a76c985b807a
refs/heads/main
2023-06-30T10:11:26.900000
2021-07-31T16:26:17
2021-07-31T16:26:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class BasketBallTeam { String name; double salaryInMillions; int numberOfWins; int numberOfLosses; int numberOfChampionships; boolean playoffTeam; public BasketBallTeam(String name, double salaryInMillions, int numberOfWins, int numberOfLosses, int numberOfChampionships, boolean playoffTeam) { this.name = name; this.salaryInMillions = salaryInMillions; this.numberOfWins = numberOfWins; this.numberOfLosses = numberOfLosses; this.numberOfChampionships = numberOfChampionships; this.playoffTeam = playoffTeam; } public double getSalaryInMillions() { return salaryInMillions; } public void setSalaryInMillions(double salaryInMillions) { this.salaryInMillions = salaryInMillions; } public int getNumberOfWins() { return numberOfWins; } public void setNumberOfWins(int numberOfWins) { this.numberOfWins = numberOfWins; } public int getNumberOfLosses() { return numberOfLosses; } public void setNumberOfLosses(int numberOfLosses) { this.numberOfLosses = numberOfLosses; } public int getNumberOfChampionships() { return numberOfChampionships; } public void setNumberOfChampionships(int numberOfChampionships) { this.numberOfChampionships = numberOfChampionships; } public boolean isPlayoffTeam() { return playoffTeam; } public void setPlayoffTeam(boolean playoffTeam) { this.playoffTeam = playoffTeam; } public String toString(){ return name; } }
UTF-8
Java
1,434
java
BasketBallTeam.java
Java
[]
null
[]
public class BasketBallTeam { String name; double salaryInMillions; int numberOfWins; int numberOfLosses; int numberOfChampionships; boolean playoffTeam; public BasketBallTeam(String name, double salaryInMillions, int numberOfWins, int numberOfLosses, int numberOfChampionships, boolean playoffTeam) { this.name = name; this.salaryInMillions = salaryInMillions; this.numberOfWins = numberOfWins; this.numberOfLosses = numberOfLosses; this.numberOfChampionships = numberOfChampionships; this.playoffTeam = playoffTeam; } public double getSalaryInMillions() { return salaryInMillions; } public void setSalaryInMillions(double salaryInMillions) { this.salaryInMillions = salaryInMillions; } public int getNumberOfWins() { return numberOfWins; } public void setNumberOfWins(int numberOfWins) { this.numberOfWins = numberOfWins; } public int getNumberOfLosses() { return numberOfLosses; } public void setNumberOfLosses(int numberOfLosses) { this.numberOfLosses = numberOfLosses; } public int getNumberOfChampionships() { return numberOfChampionships; } public void setNumberOfChampionships(int numberOfChampionships) { this.numberOfChampionships = numberOfChampionships; } public boolean isPlayoffTeam() { return playoffTeam; } public void setPlayoffTeam(boolean playoffTeam) { this.playoffTeam = playoffTeam; } public String toString(){ return name; } }
1,434
0.776848
0.776848
64
21.390625
22.855263
125
false
false
0
0
0
0
0
0
1.515625
false
false
14
84b5973e94bcb4ccca9043583e35e84c955f7b4d
23,794,118,838,184
23bdead2908c6809d035f2161c1e56354e659b31
/config/src/main/java/pers/lee/common/config/component/RemoteConfiguration.java
87f8382a9763da0c724c88ef6114bb91b97fadb3
[ "Apache-2.0" ]
permissive
Leejaywell/common-module
https://github.com/Leejaywell/common-module
da3882147156a4b0706dde57e813e1b890c91a37
079856c3fd161914a04edd6ca1087cfc8d2d1f11
refs/heads/master
2023-02-17T22:00:45.199000
2021-01-22T02:35:16
2021-01-22T02:35:16
331,815,560
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pers.lee.common.config.component; import pers.lee.common.config.Configuration; import java.util.Map; /** * RPCConfiguration * * @author Drizzt Yang */ public class RemoteConfiguration extends ReloadableConfiguration implements Configuration { private static final String PROP_TIMESTAMP = "@timestamp"; private RemoteSource remoteSource; public RemoteConfiguration(String name, RemoteSource remoteSource, boolean reloadActivated) { super(name, reloadActivated); this.remoteSource = remoteSource; } @Override protected long getCurrentTimestamp() { return remoteSource.getCurrentTimestamp(); } @Override protected Map<String, String> reload() { Map<String, String> props = remoteSource.getAll(); if (props.containsKey(PROP_TIMESTAMP)) { this.timestamp = Long.valueOf(props.get(PROP_TIMESTAMP)); props.remove(PROP_TIMESTAMP); } else { this.timestamp = this.getCurrentTimestamp(); } return props; } @Override public boolean available() { return remoteSource.available(); } @Override public void setProperty(String key, String value) { remoteSource.setProperty(key, value); super.setProperty(key, value); } @Override public void clearProperty(String key) { remoteSource.setProperty(key, null); super.clearProperty(key); } }
UTF-8
Java
1,391
java
RemoteConfiguration.java
Java
[ { "context": "a.util.Map;\n\n/**\n * RPCConfiguration\n *\n * @author Drizzt Yang\n */\npublic class RemoteConfiguration extends Relo", "end": 161, "score": 0.9998008012771606, "start": 150, "tag": "NAME", "value": "Drizzt Yang" } ]
null
[]
package pers.lee.common.config.component; import pers.lee.common.config.Configuration; import java.util.Map; /** * RPCConfiguration * * @author <NAME> */ public class RemoteConfiguration extends ReloadableConfiguration implements Configuration { private static final String PROP_TIMESTAMP = "@timestamp"; private RemoteSource remoteSource; public RemoteConfiguration(String name, RemoteSource remoteSource, boolean reloadActivated) { super(name, reloadActivated); this.remoteSource = remoteSource; } @Override protected long getCurrentTimestamp() { return remoteSource.getCurrentTimestamp(); } @Override protected Map<String, String> reload() { Map<String, String> props = remoteSource.getAll(); if (props.containsKey(PROP_TIMESTAMP)) { this.timestamp = Long.valueOf(props.get(PROP_TIMESTAMP)); props.remove(PROP_TIMESTAMP); } else { this.timestamp = this.getCurrentTimestamp(); } return props; } @Override public boolean available() { return remoteSource.available(); } @Override public void setProperty(String key, String value) { remoteSource.setProperty(key, value); super.setProperty(key, value); } @Override public void clearProperty(String key) { remoteSource.setProperty(key, null); super.clearProperty(key); } }
1,386
0.698059
0.698059
56
23.839285
23.694315
98
false
false
0
0
0
0
0
0
0.928571
false
false
14
bc3cfe535e040e62e2a9864b3bb84ebc64a9f22b
33,380,485,855,026
7add4151a860e6a183e2a8d79bdb9881faf4c675
/src/by/htp/lesson3/Main.java
d54d4243b56aa89fb12ffec38e1ecacece784bb8
[]
no_license
oandreeva/Lesson3
https://github.com/oandreeva/Lesson3
38b1ea82788aba4c97952f0ba5f8bf5c1cd1f98c
0bf09d6c2af02263009633d5694a1541a5457f05
refs/heads/master
2021-05-07T15:25:10.342000
2017-11-08T17:31:47
2017-11-08T17:31:47
110,008,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package by.htp.lesson3; /** * @author op * */ public class Main { /** * @param args */ public static void main(String[] args) { int rnd = random(900); System.out.println("rnd =" + rnd); int x = rnd / 100; int y = (rnd / 10) % 10; int z = rnd % 10; int sum = x + y + z; int mlt = x * y * z; System.out.println("sum = " + sum + " mlt = " + mlt); } public static int random(final int max) { return (int) (Math.random() * max) + 100; } }
UTF-8
Java
516
java
Main.java
Java
[ { "context": " \r\n */\r\npackage by.htp.lesson3;\r\n\r\n/**\r\n * @author op\r\n *\r\n */\r\npublic class Main {\r\n\r\n\t/**\r\n\t * @param", "end": 60, "score": 0.9926137924194336, "start": 58, "tag": "USERNAME", "value": "op" } ]
null
[]
/** * */ package by.htp.lesson3; /** * @author op * */ public class Main { /** * @param args */ public static void main(String[] args) { int rnd = random(900); System.out.println("rnd =" + rnd); int x = rnd / 100; int y = (rnd / 10) % 10; int z = rnd % 10; int sum = x + y + z; int mlt = x * y * z; System.out.println("sum = " + sum + " mlt = " + mlt); } public static int random(final int max) { return (int) (Math.random() * max) + 100; } }
516
0.486434
0.455426
33
13.636364
15.407236
55
false
false
0
0
0
0
0
0
1.060606
false
false
14
a67899951431fe947c1ab041f22cd56ce146e519
6,665,789,289,428
d14eedc6d84efb21a53c6da1691413ced87927c2
/NSTP-SSM/src/main/java/kiri/nstp/web/service/PermissionService.java
39b899e24158dc072a67b1ecaff32999a46ff7da
[]
no_license
kiribeam/nstp
https://github.com/kiribeam/nstp
bf1d473d74447b2372b957302902110211199131
74bfd4bcaff5c1f8f5f07b93d1daa77d2358b749
refs/heads/master
2020-06-26T07:01:18.357000
2019-07-30T03:41:53
2019-07-30T03:41:53
199,565,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kiri.nstp.web.service; import java.util.List; import java.util.Set; import kiri.nstp.pojo.Permission; public interface PermissionService { Set<Permission> getByRole(String role); Set<Permission> getByUsernameRole(String username); Set<Permission> getByUsernameGroupRole(String username); Set<Permission> getByUsername(String username); List<Permission> list(); Permission getById(Integer id); }
UTF-8
Java
412
java
PermissionService.java
Java
[]
null
[]
package kiri.nstp.web.service; import java.util.List; import java.util.Set; import kiri.nstp.pojo.Permission; public interface PermissionService { Set<Permission> getByRole(String role); Set<Permission> getByUsernameRole(String username); Set<Permission> getByUsernameGroupRole(String username); Set<Permission> getByUsername(String username); List<Permission> list(); Permission getById(Integer id); }
412
0.798544
0.798544
15
26.466667
18.636404
57
false
false
0
0
0
0
0
0
1.066667
false
false
14
fb420aa8c0259307535066eb68414d4cbe292be4
26,912,265,131,025
0da2db27e74f23a051f4230e562345e80cfc797d
/selenium/src/main/java/sur/snapps/jetta/selenium/elements/WebPage.java
db403e1083f1ae314e993efa5dc43e3ffa5d5f88
[]
no_license
soezen/sur-snapps-jetta
https://github.com/soezen/sur-snapps-jetta
346c6a26acb9201f6553939174be59c3f2fa6a06
7d68aaacb43abb3b5a3873cf677dad41c475350d
refs/heads/master
2021-01-18T20:35:24.529000
2015-05-14T11:35:39
2015-05-14T11:35:39
24,555,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sur.snapps.jetta.selenium.elements; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * User: SUR * Date: 4/05/14 * Time: 16:11 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface WebPage { }
UTF-8
Java
353
java
WebPage.java
Java
[ { "context": "\nimport java.lang.annotation.Target;\n\n/**\n * User: SUR\n * Date: 4/05/14\n * Time: 16:11\n */\n@Target(Eleme", "end": 223, "score": 0.9994606971740723, "start": 220, "tag": "USERNAME", "value": "SUR" } ]
null
[]
package sur.snapps.jetta.selenium.elements; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * User: SUR * Date: 4/05/14 * Time: 16:11 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface WebPage { }
353
0.773371
0.747875
16
21.0625
16.203659
44
false
false
0
0
0
0
0
0
0.3125
false
false
14
3559a20869cefc7eaf5ebe0162f9a9df55c92db4
10,505,490,012,778
f3840581d99502a0bcb31d1b9e4014aacd73e3ba
/com.dubture.twig.ui/src/com/dubture/twig/ui/outline/TwigContentOutlineConfiguration.java
8789b5a38b0c76f1273538aee91a53fee7d57a7d
[ "MIT" ]
permissive
FlakyTestDetection/Twig-Eclipse-Plugin
https://github.com/FlakyTestDetection/Twig-Eclipse-Plugin
90552fdb99a1a5ea9ae16480a81d2f9ad18a9b3c
32f18204753ec9a1f45a4bc6b8d0bedf15bb2a41
refs/heads/master
2021-01-20T04:54:34.331000
2017-11-10T15:00:01
2017-11-10T15:00:01
89,748,940
0
1
null
true
2017-04-28T22:22:35
2017-04-28T22:22:35
2017-04-12T20:56:29
2017-04-17T13:15:33
14,011
0
0
0
null
null
null
/******************************************************************************* * This file is part of the Twig eclipse plugin. * * (c) Robert Gruendler <r.gruendler@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.dubture.twig.ui.outline; import org.eclipse.dltk.ui.DLTKUIPlugin; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.php.internal.ui.actions.SortAction; import org.eclipse.php.internal.ui.outline.PHPContentOutlineConfiguration; import org.eclipse.wst.html.ui.views.contentoutline.HTMLContentOutlineConfiguration; import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; import org.eclipse.wst.xml.ui.internal.contentoutline.JFaceNodeContentProvider; import org.eclipse.wst.xml.ui.internal.contentoutline.XMLNodeActionManager; import com.dubture.twig.ui.TwigUICorePlugin; /** * * A modified {@link PHPContentOutlineConfiguration} for Twig. * * * * * @author Robert Gruendler <r.gruendler@gmail.com> * */ @SuppressWarnings("restriction") public class TwigContentOutlineConfiguration extends HTMLContentOutlineConfiguration { private static final String OUTLINE_FILTER_PREF = "com.dubture.twig.ui.OutlinePage"; //$NON-NLS-1$ protected TwigOutlineContentProvider fContentProvider = null; protected JFaceNodeContentProvider fContentProviderHTML = null; protected TwigOutlineLabelProvider fLabelProviderHTML = null; static Object[] NO_CHILDREN = new Object[0]; private SortAction sortAction; // private ShowGroupsAction fShowGroupsAction; private boolean fShowAttributes = false; protected IPreferenceStore fStore = DLTKUIPlugin.getDefault().getPreferenceStore(); // private CustomFiltersActionGroup fCustomFiltersActionGroup; public TwigContentOutlineConfiguration() { super(); } @Override protected IPreferenceStore getPreferenceStore() { return TwigUICorePlugin.getDefault().getPreferenceStore(); } @Override protected String getOutlineFilterTarget() { return OUTLINE_FILTER_PREF; } @Override protected IContributionItem[] createMenuContributions(final TreeViewer viewer) { IContributionItem[] items; // Custom filter group // if (fCustomFiltersActionGroup == null) { // fCustomFiltersActionGroup = new CustomFiltersActionGroup( // OUTLINE_PAGE, viewer); //$NON-NLS-1$ // } // // final IContributionItem filtersItem = new // FilterActionGroupContributionItem( // fCustomFiltersActionGroup); items = super.createMenuContributions(viewer); // items = new IContributionItem[] { // /* filtersItem */}; return items; } @Override protected IContributionItem[] createToolbarContributions(final TreeViewer viewer) { IContributionItem[] items; // fShowGroupsAction = new ShowGroupsAction("Show Groups", viewer); // final IContributionItem showGroupsItem = new // ActionContributionItem(fShowGroupsAction); //$NON-NLS-1$ // fixed bug 174653 // use only the toggleLinking menu and dispose the others IContributionItem[] menuContributions = super.createMenuContributions(viewer); final IContributionItem toggleLinking = menuContributions[0]; for (int i = 1; i < menuContributions.length; i++) { menuContributions[i].dispose(); } sortAction = new SortAction(viewer); final IContributionItem sortItem = new ActionContributionItem(sortAction); items = super.createToolbarContributions(viewer); if (items == null) items = new IContributionItem[] { sortItem /* , showGroupsItem */ }; else { final IContributionItem[] combinedItems = new IContributionItem[items.length + 2]; System.arraycopy(items, 0, combinedItems, 0, items.length); combinedItems[items.length] = sortItem; // combinedItems[items.length + 1] = showGroupsItem; combinedItems[items.length + 1] = toggleLinking; items = combinedItems; } return items; } @Override public void unconfigure(TreeViewer viewer) { // if (fShowGroupsAction != null) { // fShowGroupsAction.dispose(); // } super.unconfigure(viewer); } @Override public ILabelProvider getLabelProvider(final TreeViewer viewer) { if (fLabelProviderHTML == null) { fLabelProviderHTML = new TwigOutlineLabelProvider(); fLabelProviderHTML.fShowAttributes = fShowAttributes; } return fLabelProviderHTML; } @Override public ISelection getSelection(final TreeViewer viewer, final ISelection selection) { return super.getSelection(viewer, selection); } @Override protected XMLNodeActionManager createNodeActionManager(TreeViewer treeViewer) { return new TwigNodeActionManager((IStructuredModel) treeViewer.getInput(), treeViewer); } @Override protected void enableShowAttributes(boolean showAttributes, TreeViewer treeViewer) { super.enableShowAttributes(showAttributes, treeViewer); // fix bug #241111 - show attributes in outline if (fLabelProviderHTML != null) { // This option is only relevant for the HTML outline fLabelProviderHTML.fShowAttributes = showAttributes; } fShowAttributes = showAttributes; } /* * class FilterActionGroupContributionItem extends ContributionItem { * * // private boolean fState; private CustomFiltersActionGroup fActionGroup; * * public FilterActionGroupContributionItem( CustomFiltersActionGroup * actionGroup) { super("filters"); fActionGroup = actionGroup; // fState= * state; } * * public void fill(Menu menu, int index) { * * } * * public boolean isDynamic() { return true; } } */ }
UTF-8
Java
5,838
java
TwigContentOutlineConfiguration.java
Java
[ { "context": "file is part of the Twig eclipse plugin.\n *\n * (c) Robert Gruendler <r.gruendler@gmail.com>\n *\n * For the full copyri", "end": 156, "score": 0.9998729825019836, "start": 140, "tag": "NAME", "value": "Robert Gruendler" }, { "context": " Twig eclipse plugin.\n *\n * (c) Robert Gruendler <r.gruendler@gmail.com>\n *\n * For the full copyright and license informa", "end": 179, "score": 0.9999347925186157, "start": 158, "tag": "EMAIL", "value": "r.gruendler@gmail.com" }, { "context": "ineConfiguration} for Twig.\n *\n *\n *\n *\n * @author Robert Gruendler <r.gruendler@gmail.com>\n *\n */\n@SuppressWarnings(", "end": 1369, "score": 0.999879002571106, "start": 1353, "tag": "NAME", "value": "Robert Gruendler" }, { "context": "or Twig.\n *\n *\n *\n *\n * @author Robert Gruendler <r.gruendler@gmail.com>\n *\n */\n@SuppressWarnings(\"restriction\")\npublic c", "end": 1392, "score": 0.9999330639839172, "start": 1371, "tag": "EMAIL", "value": "r.gruendler@gmail.com" } ]
null
[]
/******************************************************************************* * This file is part of the Twig eclipse plugin. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.dubture.twig.ui.outline; import org.eclipse.dltk.ui.DLTKUIPlugin; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.php.internal.ui.actions.SortAction; import org.eclipse.php.internal.ui.outline.PHPContentOutlineConfiguration; import org.eclipse.wst.html.ui.views.contentoutline.HTMLContentOutlineConfiguration; import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; import org.eclipse.wst.xml.ui.internal.contentoutline.JFaceNodeContentProvider; import org.eclipse.wst.xml.ui.internal.contentoutline.XMLNodeActionManager; import com.dubture.twig.ui.TwigUICorePlugin; /** * * A modified {@link PHPContentOutlineConfiguration} for Twig. * * * * * @author <NAME> <<EMAIL>> * */ @SuppressWarnings("restriction") public class TwigContentOutlineConfiguration extends HTMLContentOutlineConfiguration { private static final String OUTLINE_FILTER_PREF = "com.dubture.twig.ui.OutlinePage"; //$NON-NLS-1$ protected TwigOutlineContentProvider fContentProvider = null; protected JFaceNodeContentProvider fContentProviderHTML = null; protected TwigOutlineLabelProvider fLabelProviderHTML = null; static Object[] NO_CHILDREN = new Object[0]; private SortAction sortAction; // private ShowGroupsAction fShowGroupsAction; private boolean fShowAttributes = false; protected IPreferenceStore fStore = DLTKUIPlugin.getDefault().getPreferenceStore(); // private CustomFiltersActionGroup fCustomFiltersActionGroup; public TwigContentOutlineConfiguration() { super(); } @Override protected IPreferenceStore getPreferenceStore() { return TwigUICorePlugin.getDefault().getPreferenceStore(); } @Override protected String getOutlineFilterTarget() { return OUTLINE_FILTER_PREF; } @Override protected IContributionItem[] createMenuContributions(final TreeViewer viewer) { IContributionItem[] items; // Custom filter group // if (fCustomFiltersActionGroup == null) { // fCustomFiltersActionGroup = new CustomFiltersActionGroup( // OUTLINE_PAGE, viewer); //$NON-NLS-1$ // } // // final IContributionItem filtersItem = new // FilterActionGroupContributionItem( // fCustomFiltersActionGroup); items = super.createMenuContributions(viewer); // items = new IContributionItem[] { // /* filtersItem */}; return items; } @Override protected IContributionItem[] createToolbarContributions(final TreeViewer viewer) { IContributionItem[] items; // fShowGroupsAction = new ShowGroupsAction("Show Groups", viewer); // final IContributionItem showGroupsItem = new // ActionContributionItem(fShowGroupsAction); //$NON-NLS-1$ // fixed bug 174653 // use only the toggleLinking menu and dispose the others IContributionItem[] menuContributions = super.createMenuContributions(viewer); final IContributionItem toggleLinking = menuContributions[0]; for (int i = 1; i < menuContributions.length; i++) { menuContributions[i].dispose(); } sortAction = new SortAction(viewer); final IContributionItem sortItem = new ActionContributionItem(sortAction); items = super.createToolbarContributions(viewer); if (items == null) items = new IContributionItem[] { sortItem /* , showGroupsItem */ }; else { final IContributionItem[] combinedItems = new IContributionItem[items.length + 2]; System.arraycopy(items, 0, combinedItems, 0, items.length); combinedItems[items.length] = sortItem; // combinedItems[items.length + 1] = showGroupsItem; combinedItems[items.length + 1] = toggleLinking; items = combinedItems; } return items; } @Override public void unconfigure(TreeViewer viewer) { // if (fShowGroupsAction != null) { // fShowGroupsAction.dispose(); // } super.unconfigure(viewer); } @Override public ILabelProvider getLabelProvider(final TreeViewer viewer) { if (fLabelProviderHTML == null) { fLabelProviderHTML = new TwigOutlineLabelProvider(); fLabelProviderHTML.fShowAttributes = fShowAttributes; } return fLabelProviderHTML; } @Override public ISelection getSelection(final TreeViewer viewer, final ISelection selection) { return super.getSelection(viewer, selection); } @Override protected XMLNodeActionManager createNodeActionManager(TreeViewer treeViewer) { return new TwigNodeActionManager((IStructuredModel) treeViewer.getInput(), treeViewer); } @Override protected void enableShowAttributes(boolean showAttributes, TreeViewer treeViewer) { super.enableShowAttributes(showAttributes, treeViewer); // fix bug #241111 - show attributes in outline if (fLabelProviderHTML != null) { // This option is only relevant for the HTML outline fLabelProviderHTML.fShowAttributes = showAttributes; } fShowAttributes = showAttributes; } /* * class FilterActionGroupContributionItem extends ContributionItem { * * // private boolean fState; private CustomFiltersActionGroup fActionGroup; * * public FilterActionGroupContributionItem( CustomFiltersActionGroup * actionGroup) { super("filters"); fActionGroup = actionGroup; // fState= * state; } * * public void fill(Menu menu, int index) { * * } * * public boolean isDynamic() { return true; } } */ }
5,790
0.747002
0.743063
173
32.745667
28.770048
99
false
false
0
0
0
0
0
0
1.554913
false
false
14
bbc1c57e675145f02962b7cce7068050f9a529fb
32,152,125,207,461
ee81efa621f8a18569d8ac00e5176aff1a736d86
/heartrate.java
4b78caeb61f9a2275c3b90c58260809932fddcf3
[]
no_license
renaldyresa/Kattis
https://github.com/renaldyresa/Kattis
c8b29f40a84f4161f49c6247abf10ec2ecc14810
e504f54602b054eeffaac48b43e70beb976ca94c
refs/heads/master
2021-12-01T14:57:57.614000
2021-11-29T07:44:43
2021-11-29T07:44:43
182,920,692
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Kattis { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int byk = sc.nextInt(); float [] hls1 = new float [byk]; float [] hls2= new float [byk]; for (int i = 0; i < byk; i++) { float ak1 = sc.nextInt(); float ak2 = sc.nextFloat(); hls2[i] = 60*ak1/ak2; hls1[i] = 60/ak2; } for (int i = 0; i < byk; i++) { System.out.println(String.format("%.4f", (hls2[i]-hls1[i]))+String.format(" %.4f", hls2[i])+String.format(" %.4f", (hls2[i]+hls1[i]))); } } }
UTF-8
Java
658
java
heartrate.java
Java
[]
null
[]
import java.util.Scanner; public class Kattis { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int byk = sc.nextInt(); float [] hls1 = new float [byk]; float [] hls2= new float [byk]; for (int i = 0; i < byk; i++) { float ak1 = sc.nextInt(); float ak2 = sc.nextFloat(); hls2[i] = 60*ak1/ak2; hls1[i] = 60/ak2; } for (int i = 0; i < byk; i++) { System.out.println(String.format("%.4f", (hls2[i]-hls1[i]))+String.format(" %.4f", hls2[i])+String.format(" %.4f", (hls2[i]+hls1[i]))); } } }
658
0.483283
0.448328
22
28.90909
30.449524
147
false
false
0
0
0
0
0
0
0.772727
false
false
14
b31a7f4d415a3c70b0bcc2f663266e1682f58fb2
34,024,730,923,679
52ecd4dac53af9df94e5b743c07c2ba864bfd2dc
/jpa-demo/src/main/java/com/example/demo/reposity/TestReposity.java
b5b5b2ed688b75c41e6620ba2a63875c6e79e4ac
[]
no_license
aaafenghao/win
https://github.com/aaafenghao/win
e6b31a1ace72c25dc16928f11be4ee01932649b3
46a0e1562d9badba7ac29e96072c8795a1fdabab
refs/heads/master
2022-10-11T01:39:31.684000
2020-03-31T07:46:02
2020-03-31T07:46:02
214,920,724
0
0
null
false
2022-10-04T23:55:44
2019-10-14T01:19:24
2020-03-31T07:46:17
2022-10-04T23:55:44
24,136
0
0
6
Java
false
false
package com.example.demo.reposity; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entity.Test; public interface TestReposity extends JpaRepository<Test, Integer> { }
UTF-8
Java
209
java
TestReposity.java
Java
[]
null
[]
package com.example.demo.reposity; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entity.Test; public interface TestReposity extends JpaRepository<Test, Integer> { }
209
0.818182
0.818182
9
22.222221
26.569731
68
false
false
0
0
0
0
0
0
0.444444
false
false
14
68a8238e867186d8e2728e612de2029f442bdb37
25,640,954,804,199
53b9e88fdfc3c616ec084ab65b4d2e679e6810b1
/Java/TRABALHO_JAVA/Capitulo_2/Ex02/Ex02.java
d4c5b8c24a2d6f4dc2e6cbe46622d525f1922e0a
[ "Apache-2.0" ]
permissive
1ricardo66/Programming_Exercises
https://github.com/1ricardo66/Programming_Exercises
6ae9e25cf280162a025e9bafffd04c460de5e150
5b7895bb93399713c0f6c5b22ac4708332e0b385
refs/heads/master
2020-03-27T00:14:14.613000
2019-03-25T19:58:12
2019-03-25T19:58:12
145,606,137
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Usando a classe Scanner para entrada de dados, faça uma classe que simule a abertura de uma conta bancária cujo saldo inicial seja zero. A seguir, simule um depósito num valor qualquer e mostre o saldo atual. Depois disso, simule uma retirada (débito) qualquer e apresente o saldo final. */ import java.util.Scanner; public class Ex02{ public static void main (String [] args){ float valor; Banco banco = new Banco(); Scanner input = new Scanner(System.in); System.out.print("Valor do deposito: "); valor = input.nextFloat(); banco.Deposito(valor); System.out.print("Quanto deseja retirar: "); valor = input.nextFloat(); banco.Saque(valor); } }
UTF-8
Java
740
java
Ex02.java
Java
[]
null
[]
/* Usando a classe Scanner para entrada de dados, faça uma classe que simule a abertura de uma conta bancária cujo saldo inicial seja zero. A seguir, simule um depósito num valor qualquer e mostre o saldo atual. Depois disso, simule uma retirada (débito) qualquer e apresente o saldo final. */ import java.util.Scanner; public class Ex02{ public static void main (String [] args){ float valor; Banco banco = new Banco(); Scanner input = new Scanner(System.in); System.out.print("Valor do deposito: "); valor = input.nextFloat(); banco.Deposito(valor); System.out.print("Quanto deseja retirar: "); valor = input.nextFloat(); banco.Saque(valor); } }
740
0.663043
0.660326
22
32.5
24.866461
77
false
false
0
0
0
0
0
0
0.590909
false
false
14
6fe4ae5cccee6750f16df65d001afef73a0df9cf
33,088,428,098,933
3c7dd7020227e8686d492ca38432b03f1691f561
/REST-Service/src/main/java/ie/gmit/ds/ClientAccount.java
7cdd9eafaa7f47d2fcbe266f2b3ecc2352fe80f2
[ "MIT" ]
permissive
IvanMcGann/REST-Service
https://github.com/IvanMcGann/REST-Service
0b73fa5c3a260ffb6c8ebc72ffc9a9498af25e98
5e423489aede6ea98ed0d366094413b061c4831e
refs/heads/master
2023-07-20T20:24:41.974000
2019-11-29T20:13:41
2019-11-29T20:13:41
224,496,744
0
0
MIT
false
2023-07-05T20:45:46
2019-11-27T18:50:53
2019-11-29T20:13:43
2023-07-05T20:45:45
29,280
0
0
1
Java
false
false
package ie.gmit.ds; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import com.google.protobuf.BoolValue; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; public class ClientAccount { // logger used to log message for application component private static final Logger logger = Logger.getLogger(ClientAccount.class.getName()); private final ManagedChannel channel; private final PasswordServiceGrpc.PasswordServiceStub asyncService; private final PasswordServiceGrpc.PasswordServiceBlockingStub syncService; private ByteString expectedHash; private ByteString salt; public ClientAccount(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); syncService = PasswordServiceGrpc.newBlockingStub(channel); asyncService = PasswordServiceGrpc.newStub(channel); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public static void main(String[] args) throws Exception { ClientAccount accClient = new ClientAccount("localhost", 50551); } // getters public ByteString getExpectedHash() { return expectedHash; } public ByteString getSalt() { return salt; } public void hash(int userId, String password) { StreamObserver<HashResponse> hr = new StreamObserver<HashResponse>() { @Override public void onNext(HashResponse value) { // TODO Auto-generated method stub salt = value.getSalt(); expectedHash = value.getHashPassword(); } @Override public void onError(Throwable t) { // TODO Auto-generated method stub } @Override public void onCompleted() { // TODO Auto-generated method stub } }; try { logger.info("Retrieve users"); HashRequest hrq = HashRequest.newBuilder().setUserId(userId).setPassword(password).build(); asyncService.hash(hrq, hr); TimeUnit.SECONDS.sleep(10); } catch (Exception e) { // TODO: handle exception return; } return; } public boolean validate(ByteString hash, ByteString salt, String password) { try { BoolValue value = syncService.validate( ValidateRequest.newBuilder().setHashPassword(hash).setSalt(salt).setPassword(password).build()); return value.getValue(); } catch (Exception e) { // TODO: handle exception return false; } } }
UTF-8
Java
2,438
java
ClientAccount.java
Java
[ { "context": "equest.newBuilder().setUserId(userId).setPassword(password).build();\n\t\t\tasyncService.hash(hrq, hr);\n\t\t\tTimeU", "end": 1939, "score": 0.9835744500160217, "start": 1931, "tag": "PASSWORD", "value": "password" } ]
null
[]
package ie.gmit.ds; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import com.google.protobuf.BoolValue; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; public class ClientAccount { // logger used to log message for application component private static final Logger logger = Logger.getLogger(ClientAccount.class.getName()); private final ManagedChannel channel; private final PasswordServiceGrpc.PasswordServiceStub asyncService; private final PasswordServiceGrpc.PasswordServiceBlockingStub syncService; private ByteString expectedHash; private ByteString salt; public ClientAccount(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); syncService = PasswordServiceGrpc.newBlockingStub(channel); asyncService = PasswordServiceGrpc.newStub(channel); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public static void main(String[] args) throws Exception { ClientAccount accClient = new ClientAccount("localhost", 50551); } // getters public ByteString getExpectedHash() { return expectedHash; } public ByteString getSalt() { return salt; } public void hash(int userId, String password) { StreamObserver<HashResponse> hr = new StreamObserver<HashResponse>() { @Override public void onNext(HashResponse value) { // TODO Auto-generated method stub salt = value.getSalt(); expectedHash = value.getHashPassword(); } @Override public void onError(Throwable t) { // TODO Auto-generated method stub } @Override public void onCompleted() { // TODO Auto-generated method stub } }; try { logger.info("Retrieve users"); HashRequest hrq = HashRequest.newBuilder().setUserId(userId).setPassword(<PASSWORD>).build(); asyncService.hash(hrq, hr); TimeUnit.SECONDS.sleep(10); } catch (Exception e) { // TODO: handle exception return; } return; } public boolean validate(ByteString hash, ByteString salt, String password) { try { BoolValue value = syncService.validate( ValidateRequest.newBuilder().setHashPassword(hash).setSalt(salt).setPassword(password).build()); return value.getValue(); } catch (Exception e) { // TODO: handle exception return false; } } }
2,440
0.743642
0.740361
97
24.144329
25.344223
101
false
false
0
0
0
0
0
0
1.824742
false
false
14
8d4ee00985a0c915fbd0a0b37b6536b90cc7aa37
25,451,976,215,101
eef72bef9ff64e5f64d2a39675c469dda74e6ce2
/rice-middleware/edl/impl/src/main/java/org/kuali/rice/edl/impl/service/EDocLiteService.java
7f4bf8ba46ee26a792c35095543ced8c2d46ca1c
[ "Artistic-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "EPL-1.0", "CPL-1.0", "LGPL-2.1-or-later", "BSD-3-Clause", "LGPL-3.0-only", "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-jdom", "LicenseRef-scancode-freemarker", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
kuali/rice
https://github.com/kuali/rice
9f9e9fd72cbac859fdae838e6d525563e21f8517
16a2684c6123fb5832ac8c1878afc5996cff6f01
refs/heads/master
2023-08-11T11:40:43.036000
2017-05-17T23:56:47
2017-05-17T23:56:47
25,359,676
18
66
ECL-2.0
false
2018-03-03T06:29:38
2014-10-17T13:35:55
2017-12-04T04:05:01
2018-03-03T06:29:37
289,167
19
36
0
Java
false
null
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.edl.impl.service; import java.io.InputStream; import java.util.List; import javax.xml.transform.Templates; import javax.xml.transform.TransformerConfigurationException; import org.kuali.rice.core.framework.impex.xml.XmlExporter; import org.kuali.rice.core.framework.impex.xml.XmlLoader; import org.kuali.rice.edl.impl.EDLController; import org.kuali.rice.edl.impl.bo.EDocLiteAssociation; import org.kuali.rice.edl.impl.bo.EDocLiteDefinition; import org.w3c.dom.Document; public interface EDocLiteService extends XmlLoader, XmlExporter { void saveEDocLiteDefinition(InputStream xml); void saveEDocLiteAssociation(InputStream xml); EDocLiteDefinition getEDocLiteDefinition(String defName); EDocLiteAssociation getEDocLiteAssociation(String docType); EDocLiteAssociation getEDocLiteAssociation(Long associationId); List<EDocLiteDefinition> getEDocLiteDefinitions(); List<EDocLiteAssociation> getEDocLiteAssociations(); Templates getStyleAsTranslet(String styleName) throws TransformerConfigurationException; List<EDocLiteAssociation> search(EDocLiteAssociation edocLite); EDLController getEDLControllerUsingEdlName(String edlName); EDLController getEDLControllerUsingDocumentId(String documentId); void initEDLGlobalConfig(); void saveEDocLiteDefinition(EDocLiteDefinition data) ; void saveEDocLiteAssociation(EDocLiteAssociation assoc); Document getDefinitionXml(EDocLiteAssociation edlAssociation); }
UTF-8
Java
2,106
java
EDocLiteService.java
Java
[]
null
[]
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.edl.impl.service; import java.io.InputStream; import java.util.List; import javax.xml.transform.Templates; import javax.xml.transform.TransformerConfigurationException; import org.kuali.rice.core.framework.impex.xml.XmlExporter; import org.kuali.rice.core.framework.impex.xml.XmlLoader; import org.kuali.rice.edl.impl.EDLController; import org.kuali.rice.edl.impl.bo.EDocLiteAssociation; import org.kuali.rice.edl.impl.bo.EDocLiteDefinition; import org.w3c.dom.Document; public interface EDocLiteService extends XmlLoader, XmlExporter { void saveEDocLiteDefinition(InputStream xml); void saveEDocLiteAssociation(InputStream xml); EDocLiteDefinition getEDocLiteDefinition(String defName); EDocLiteAssociation getEDocLiteAssociation(String docType); EDocLiteAssociation getEDocLiteAssociation(Long associationId); List<EDocLiteDefinition> getEDocLiteDefinitions(); List<EDocLiteAssociation> getEDocLiteAssociations(); Templates getStyleAsTranslet(String styleName) throws TransformerConfigurationException; List<EDocLiteAssociation> search(EDocLiteAssociation edocLite); EDLController getEDLControllerUsingEdlName(String edlName); EDLController getEDLControllerUsingDocumentId(String documentId); void initEDLGlobalConfig(); void saveEDocLiteDefinition(EDocLiteDefinition data) ; void saveEDocLiteAssociation(EDocLiteAssociation assoc); Document getDefinitionXml(EDocLiteAssociation edlAssociation); }
2,106
0.807692
0.801994
53
38.735847
28.165382
92
false
false
0
0
0
0
0
0
0.660377
false
false
14
c5b4ceac240bc5c9622c3d66f8fe5a87487aecb3
21,878,563,469,425
9fb90a4bcc514fcdfc0003ed2060e88be831ac26
/src/com/mic/demo/generics/BasicGeneratorDemo.java
9a50e16875db293c1fb61285240b59ddff70d8d3
[]
no_license
lpjhblpj/FimicsJava
https://github.com/lpjhblpj/FimicsJava
84cf93030b7172b0986b75c6d3e44226edce2019
0f00b6457500db81d9eac3499de31cc980a46166
refs/heads/master
2020-04-24T23:32:16.893000
2019-02-24T14:45:43
2019-02-24T14:45:43
132,058,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//: com.mic.demo.generics/BasicGeneratorDemo.java package com.mic.demo.generics; /* Added by Eclipse.py */ import com.mic.demo.mindview.util.BasicGenerator; import com.mic.demo.mindview.util.Generator; public class BasicGeneratorDemo { public static void main(String[] args) { Generator<CountedObject> gen = BasicGenerator.create(CountedObject.class); for (int i = 0; i < 5; i++) System.out.println(gen.next()); } } /* Output: CountedObject 0 CountedObject 1 CountedObject 2 CountedObject 3 CountedObject 4 *///:~
UTF-8
Java
568
java
BasicGeneratorDemo.java
Java
[]
null
[]
//: com.mic.demo.generics/BasicGeneratorDemo.java package com.mic.demo.generics; /* Added by Eclipse.py */ import com.mic.demo.mindview.util.BasicGenerator; import com.mic.demo.mindview.util.Generator; public class BasicGeneratorDemo { public static void main(String[] args) { Generator<CountedObject> gen = BasicGenerator.create(CountedObject.class); for (int i = 0; i < 5; i++) System.out.println(gen.next()); } } /* Output: CountedObject 0 CountedObject 1 CountedObject 2 CountedObject 3 CountedObject 4 *///:~
568
0.690141
0.677817
20
27.4
18.990524
59
false
false
0
0
0
0
0
0
0.35
false
false
14
30e9349d58da1d2819c96336d21e676d2455c21f
27,650,999,512,966
6bd25c971d364c90b17c193390342380f9fec07f
/Abstract Factory/src/sample/Rombo.java
3064b7c315e3bc8d70ab1f7cb2a08eecdd8434bb
[]
no_license
DaniCamacho29/Tarea-Extraclase
https://github.com/DaniCamacho29/Tarea-Extraclase
2f6e5d005f16363db433c6ca42b3da9bfd187f05
9d0768d352caecdd6d83faa5e644b346736b3110
refs/heads/master
2020-06-28T19:35:50.081000
2019-09-27T09:50:19
2019-09-27T09:50:19
200,318,644
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; public class Rombo implements creador { private String rombo; public Rombo() { this.rombo = "Rombo"; } @Override public void creado() { System.out.println("Rombo creado"); } @Override public void nocreado() { System.out.println("Rombo no creado"); } }
UTF-8
Java
354
java
Rombo.java
Java
[]
null
[]
package sample; public class Rombo implements creador { private String rombo; public Rombo() { this.rombo = "Rombo"; } @Override public void creado() { System.out.println("Rombo creado"); } @Override public void nocreado() { System.out.println("Rombo no creado"); } }
354
0.550847
0.550847
21
14.857142
14.495601
43
false
false
0
0
0
0
0
0
0.238095
false
false
14
c025feb707979e4711cbbed1fe4f60b2014e8529
12,859,132,143,973
0b1a4b58ea415aee576d78a2802c63fb6e3347a3
/Navigation/app/src/main/java/com/example/navigation/MainActivity.java
3addfc4e582ad2763bb8d96a2d03792d8d6fbbb4
[]
no_license
JoSunJoo/MobileProgramming
https://github.com/JoSunJoo/MobileProgramming
dc84a9bf8cc3b691170b49018bb592424fc53061
d0f79ce6fb7ebd143e0e2daee6668828c261e5c3
refs/heads/master
2020-09-11T13:27:10.317000
2019-12-05T16:37:17
2019-12-05T16:37:17
222,080,248
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.navigation; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends AppCompatActivity { TextFileManager mFileMgr = new TextFileManager(this);//파일에 대한 관리를 하는 객체 private ListView m_ListView;//리스트뷰 객체 private ArrayAdapter<String> m_Adapter;//어댑터 객체 private ArrayList<String> values = new ArrayList<>();//파일의 이름 데이터를 저장하는 ArrayList @Override protected void onCreate(Bundle savedInstanceState) {//액티비티 실행시 먼저 실행되는 함수 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//레이아웃 설정 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//저장된 폴더 내의 모든 파일의 이름을 가져와 value에 저장 m_Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);//어댑터 만들기 m_ListView = findViewById(R.id.list);//해당 리스트의 id를 가져옴 m_ListView.setAdapter(m_Adapter);//어댑터 연결 m_ListView.setOnItemClickListener(onClickListItem);//어댑터 클릭 시 실행됨 registerForContextMenu(m_ListView); } //해당 항목의 리스트를 클릭할 경우 이벤트 처리 private AdapterView.OnItemClickListener onClickListItem = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { String name = values.get(position);//해당 리스트의 폴더명을 가져옴 String[] point = name.split("->");//'->'을 기준으로 문자열 분할 String url = "https://www.google.com/maps/dir/" + point[0] + "/" + point[1]; //출발지와 도착지를 넣은 url 생성 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));//암시적 intent를 통해 검색 startActivity(intent);//인텐트 실행 } }; @Override protected void onResume() {//다른 액티비티가 종료된 후 해당 액티비티가 앞으로 올 경우 실행됨 super.onResume(); //value의 값을 갱신함 values.clear();//value값 초기화 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//다시 모든 파일의 이름을 가져와 value에 대입 m_Adapter.notifyDataSetChanged();//어댑터의 리스트항목을 업데이트해줌 } @Override public boolean onCreateOptionsMenu(Menu menu){ //메뉴 만들기 MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){//메뉴의 버튼을 클릭할 때 이벤트 처리 if(item.getItemId() == R.id.add){//add를 클릭할 경우 Intent intent = new Intent(getApplicationContext(), AddBookmark.class);//경로 추가 페이지로 이동 startActivityForResult(intent, 1);//인텐트 시작 return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuinfo){//컨텍스트메뉴 생성 super.onCreateContextMenu(menu, v, menuinfo); menu.setHeaderTitle("메뉴");//메뉴의 타이틀 설정 menu.add(0, 1, 0, "수정");//수정 버튼 생성 menu.add(0, 2, 0, "삭제");//삭제 버튼 생성 } @Override public boolean onContextItemSelected(MenuItem item){//컨텍스트 메뉴 선택시 이벤트 처리 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();//컨텍스트메뉴의 데이터 가져오기 int index = info.position;//해당 메뉴의 인덱스 가져오기 switch(item.getItemId()){ case 1: //수정버튼을 누른 경우 Intent intent = new Intent(this, ModifyBookMark.class);//수정페이지로 이동 intent.putExtra("name", values.get(index));//인텐트에 해당 리스트의 데이터 삽입 startActivityForResult(intent, 2);//인텐트 시작 break; case 2: //삭제버튼을 누른 경우 mFileMgr.delete(values.get(index));//해당 파일 삭제 values.clear();//데이터 초기화 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//파일의 이름을 다시 가져와서 value에 저장함 m_Adapter.notifyDataSetChanged();//리스트 뷰를 업데이트해줌 break; } return true; } }
UTF-8
Java
5,175
java
MainActivity.java
Java
[]
null
[]
package com.example.navigation; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends AppCompatActivity { TextFileManager mFileMgr = new TextFileManager(this);//파일에 대한 관리를 하는 객체 private ListView m_ListView;//리스트뷰 객체 private ArrayAdapter<String> m_Adapter;//어댑터 객체 private ArrayList<String> values = new ArrayList<>();//파일의 이름 데이터를 저장하는 ArrayList @Override protected void onCreate(Bundle savedInstanceState) {//액티비티 실행시 먼저 실행되는 함수 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//레이아웃 설정 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//저장된 폴더 내의 모든 파일의 이름을 가져와 value에 저장 m_Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);//어댑터 만들기 m_ListView = findViewById(R.id.list);//해당 리스트의 id를 가져옴 m_ListView.setAdapter(m_Adapter);//어댑터 연결 m_ListView.setOnItemClickListener(onClickListItem);//어댑터 클릭 시 실행됨 registerForContextMenu(m_ListView); } //해당 항목의 리스트를 클릭할 경우 이벤트 처리 private AdapterView.OnItemClickListener onClickListItem = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { String name = values.get(position);//해당 리스트의 폴더명을 가져옴 String[] point = name.split("->");//'->'을 기준으로 문자열 분할 String url = "https://www.google.com/maps/dir/" + point[0] + "/" + point[1]; //출발지와 도착지를 넣은 url 생성 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));//암시적 intent를 통해 검색 startActivity(intent);//인텐트 실행 } }; @Override protected void onResume() {//다른 액티비티가 종료된 후 해당 액티비티가 앞으로 올 경우 실행됨 super.onResume(); //value의 값을 갱신함 values.clear();//value값 초기화 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//다시 모든 파일의 이름을 가져와 value에 대입 m_Adapter.notifyDataSetChanged();//어댑터의 리스트항목을 업데이트해줌 } @Override public boolean onCreateOptionsMenu(Menu menu){ //메뉴 만들기 MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){//메뉴의 버튼을 클릭할 때 이벤트 처리 if(item.getItemId() == R.id.add){//add를 클릭할 경우 Intent intent = new Intent(getApplicationContext(), AddBookmark.class);//경로 추가 페이지로 이동 startActivityForResult(intent, 1);//인텐트 시작 return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuinfo){//컨텍스트메뉴 생성 super.onCreateContextMenu(menu, v, menuinfo); menu.setHeaderTitle("메뉴");//메뉴의 타이틀 설정 menu.add(0, 1, 0, "수정");//수정 버튼 생성 menu.add(0, 2, 0, "삭제");//삭제 버튼 생성 } @Override public boolean onContextItemSelected(MenuItem item){//컨텍스트 메뉴 선택시 이벤트 처리 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();//컨텍스트메뉴의 데이터 가져오기 int index = info.position;//해당 메뉴의 인덱스 가져오기 switch(item.getItemId()){ case 1: //수정버튼을 누른 경우 Intent intent = new Intent(this, ModifyBookMark.class);//수정페이지로 이동 intent.putExtra("name", values.get(index));//인텐트에 해당 리스트의 데이터 삽입 startActivityForResult(intent, 2);//인텐트 시작 break; case 2: //삭제버튼을 누른 경우 mFileMgr.delete(values.get(index));//해당 파일 삭제 values.clear();//데이터 초기화 values.addAll(Arrays.asList(mFileMgr.showAllFiles()));//파일의 이름을 다시 가져와서 value에 저장함 m_Adapter.notifyDataSetChanged();//리스트 뷰를 업데이트해줌 break; } return true; } }
5,175
0.657803
0.65477
111
37.62162
31.766903
123
false
false
0
0
0
0
0
0
0.747748
false
false
14
cab8d371f5e52b4c65d11a8b8a0736303b2fbc34
34,136,400,110,796
766c2ad47fe6c7425a9f159d6872776152fc575d
/mobileSafe/src/main/java/com/boyzhang/projectmobilesafe/utils/ApplicationUtils.java
625cc0d558b6a9ca4c8e30ad1546d51faeb25349
[ "Apache-2.0" ]
permissive
paifeng/Mobile-guards
https://github.com/paifeng/Mobile-guards
755986efd7950b1f47c399391a4066b9a8cae3dd
d7781a7738a55d973253a1d1575fd546a5269316
refs/heads/master
2021-01-10T06:04:11.430000
2016-03-12T16:22:28
2016-03-12T16:22:28
53,733,353
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boyzhang.projectmobilesafe.utils; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Debug; import com.boyzhang.projectmobilesafe.R; import com.boyzhang.projectmobilesafe.bean.AppInfos; import com.boyzhang.projectmobilesafe.bean.RunningAppInfos; import java.io.File; import java.util.ArrayList; import java.util.List; /** * =========================================================== * <p/> * 版权 : 张海锋 版权所有(c)2016 * <p/> * 作者 : 张海锋 * <p/> * 版本 : 1.0 * <p/> * 创建时间 : 2016-03-02 17:05 * <p/> * 描述 : 获取到所有应用程序的---应用名,包名,大小,图标 * <p/> * <p/> * 修订历史 : * <p/> * <p/> * =========================================================== **/ public class ApplicationUtils { /** * 获取到所有的应用信息 * * @param context * @return */ public static List<AppInfos> getApplicationInfos(Context context) { List<AppInfos> appInfos = new ArrayList<>(); //获取包管理器 PackageManager packageManager = context.getPackageManager(); //获取到所有的安装的包 //参数:Additional option flags. Use any combination of 表示可以使用任意参数,用0 List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0); for (PackageInfo installedPackage : installedPackages) { AppInfos appInfo = new AppInfos(); //拿到LOGO Drawable icon = installedPackage.applicationInfo.loadIcon(packageManager); //拿到应用名称 String appName = installedPackage.applicationInfo.loadLabel(packageManager).toString(); //获取到应用程序的包名 String packageName = installedPackage.packageName; //获取到apk资源路径 String sourceDir = installedPackage.applicationInfo.sourceDir; //获取到资源大小-即App占用空间 File file = new File(sourceDir); long appSize = file.length(); /* System.out.println("---------------------------------"); System.out.println("程序名称:" + appName); System.out.println("程序包名:" + packageName); System.out.println("程序大小:" + appSize); */ int flags = installedPackage.applicationInfo.flags; //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appInfo.setAppType(AppInfos.APP_SYSTEM); } else { appInfo.setAppType(AppInfos.APP_USER); } //判断安装路径是ROM中还是SD中 if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { //表示在SD卡中 appInfo.setAppLocation(AppInfos.LOCATION_SD); } else { appInfo.setAppLocation(AppInfos.LOCATION_ROM); } appInfo.setAppLogo(icon); appInfo.setAppName(appName); appInfo.setAppSize(appSize); appInfo.setAppPackageName(packageName); //增加到集合 appInfos.add(appInfo); } return appInfos; } /** * 根据包名获取应用信息 * * @param packageNames * @return */ public static List<AppInfos> getAppInfoByPackageName(Context context, List<String> packageNames) { List<AppInfos> appInfos = new ArrayList<>(); Drawable icon = null;//应用图标 String appName = null;//应用名称 int appType = -1; long appSize; //获取包管理器 PackageManager packageManager = context.getPackageManager(); for (String packageName : packageNames) { AppInfos appInfo = new AppInfos(); try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); icon = packageInfo.applicationInfo.loadIcon(packageManager);//拿到图标 appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();//拿到APP名称 int flags = packageInfo.applicationInfo.flags;//应用标记 //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appType = RunningAppInfos.APP_TYPE_SYS; } else { appType = RunningAppInfos.APP_TYPE_USER; } //判断安装路径是ROM中还是SD中 if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { //表示在SD卡中 appInfo.setAppLocation(AppInfos.LOCATION_SD); } else { appInfo.setAppLocation(AppInfos.LOCATION_ROM); } //获取到apk资源路径 String sourceDir = packageInfo.applicationInfo.sourceDir; //获取到资源大小-即App占用空间 File file = new File(sourceDir); appSize = file.length(); appInfo.setAppName(appName); appInfo.setAppLogo(icon); appInfo.setAppType(appType); appInfo.setAppSize(appSize); appInfo.setAppPackageName(packageName); //增加到集合 appInfos.add(appInfo); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return appInfos; } /** * 拿到所有正在运行的应用信息 * * @param context * @return */ public static List<RunningAppInfos> getRunningAppInfos(Context context) { Drawable icon = null;//应用图标 String appName = null;//应用名称 String packageName;//应用包名 int pid = -1; int memoSize = 0;//占用内存大小 int appType = -1; int positionID = 0; List<RunningAppInfos> infosArrayList = new ArrayList<>(); //拿到进程管理器 ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); //拿到运行的进程 List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses(); //拿到包管理器 PackageManager packageManager = context.getPackageManager(); for (ActivityManager.RunningAppProcessInfo runningAppProcesse : runningAppProcesses) { packageName = runningAppProcesse.processName;//拿到进程名(包名) try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);//拿到包信息 icon = packageInfo.applicationInfo.loadIcon(packageManager);//拿到图标 appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();//拿到APP名称 int flags = packageInfo.applicationInfo.flags;//应用标记 //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appType = RunningAppInfos.APP_TYPE_SYS; } else { appType = RunningAppInfos.APP_TYPE_USER; } pid = runningAppProcesse.pid;//拿到进程ID Debug.MemoryInfo[] memoryInfo = activityManager.getProcessMemoryInfo(new int[]{pid}); memoSize = memoryInfo[0].getTotalPrivateDirty() * 1024;//获取到进程占用内存大小 } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); //如果捕获到异常就帮其设置一个默认的图标和名称----------------!!!!!!这一点很重要,否则是不对的 icon = context.getResources().getDrawable(R.drawable.default_app_logo); appName = "UNKNOW APP"; appType = RunningAppInfos.APP_TYPE_SYS; } finally { //创建一个RunningAppInfos RunningAppInfos runningAppInfos = new RunningAppInfos(icon, appName, packageName, pid, memoSize, appType, false, positionID); //添加到集合 infosArrayList.add(runningAppInfos); } positionID++; } //SystemClock.sleep(5000); return infosArrayList; } /** * 返回进程的总个数 * * @param context * @return */ public static int getProcessCount(Context context) { // 得到进程管理者 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); // 获取到当前手机上面所有运行的进程 List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager .getRunningAppProcesses(); // 获取手机上面一共有多少个进程 return runningAppProcesses.size(); } /** * 判断是否系统APP * * @param flags * @return */ private static boolean isSystemApp(int flags) { /** * 方法一: * 第三方app放在data/data下,系统应用放在system/data下 * 可以判断路径是否包含关键路径来区别应用类型 */ /** * 方法二: * 采用App的flags进行与运算 */ //判断是系统应用还是第三方应用 if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) { //表示系统App return true; } else { return false; } } }
UTF-8
Java
10,043
java
ApplicationUtils.java
Java
[ { "context": "=================================\n * <p/>\n * 版权 : 张海锋 版权所有(c)2016\n * <p/>\n * 作者 : 张海锋\n * <p/>\n * 版本 : 1", "end": 622, "score": 0.9998698234558105, "start": 619, "tag": "NAME", "value": "张海锋" }, { "context": "=\n * <p/>\n * 版权 : 张海锋 版权所有(c)2016\n * <p/>\n * 作者 : 张海锋\n * <p/>\n * 版本 : 1.0\n * <p/>\n * 创建时间 : 2016-03-02 ", "end": 654, "score": 0.9998814463615417, "start": 651, "tag": "NAME", "value": "张海锋" } ]
null
[]
package com.boyzhang.projectmobilesafe.utils; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Debug; import com.boyzhang.projectmobilesafe.R; import com.boyzhang.projectmobilesafe.bean.AppInfos; import com.boyzhang.projectmobilesafe.bean.RunningAppInfos; import java.io.File; import java.util.ArrayList; import java.util.List; /** * =========================================================== * <p/> * 版权 : 张海锋 版权所有(c)2016 * <p/> * 作者 : 张海锋 * <p/> * 版本 : 1.0 * <p/> * 创建时间 : 2016-03-02 17:05 * <p/> * 描述 : 获取到所有应用程序的---应用名,包名,大小,图标 * <p/> * <p/> * 修订历史 : * <p/> * <p/> * =========================================================== **/ public class ApplicationUtils { /** * 获取到所有的应用信息 * * @param context * @return */ public static List<AppInfos> getApplicationInfos(Context context) { List<AppInfos> appInfos = new ArrayList<>(); //获取包管理器 PackageManager packageManager = context.getPackageManager(); //获取到所有的安装的包 //参数:Additional option flags. Use any combination of 表示可以使用任意参数,用0 List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0); for (PackageInfo installedPackage : installedPackages) { AppInfos appInfo = new AppInfos(); //拿到LOGO Drawable icon = installedPackage.applicationInfo.loadIcon(packageManager); //拿到应用名称 String appName = installedPackage.applicationInfo.loadLabel(packageManager).toString(); //获取到应用程序的包名 String packageName = installedPackage.packageName; //获取到apk资源路径 String sourceDir = installedPackage.applicationInfo.sourceDir; //获取到资源大小-即App占用空间 File file = new File(sourceDir); long appSize = file.length(); /* System.out.println("---------------------------------"); System.out.println("程序名称:" + appName); System.out.println("程序包名:" + packageName); System.out.println("程序大小:" + appSize); */ int flags = installedPackage.applicationInfo.flags; //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appInfo.setAppType(AppInfos.APP_SYSTEM); } else { appInfo.setAppType(AppInfos.APP_USER); } //判断安装路径是ROM中还是SD中 if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { //表示在SD卡中 appInfo.setAppLocation(AppInfos.LOCATION_SD); } else { appInfo.setAppLocation(AppInfos.LOCATION_ROM); } appInfo.setAppLogo(icon); appInfo.setAppName(appName); appInfo.setAppSize(appSize); appInfo.setAppPackageName(packageName); //增加到集合 appInfos.add(appInfo); } return appInfos; } /** * 根据包名获取应用信息 * * @param packageNames * @return */ public static List<AppInfos> getAppInfoByPackageName(Context context, List<String> packageNames) { List<AppInfos> appInfos = new ArrayList<>(); Drawable icon = null;//应用图标 String appName = null;//应用名称 int appType = -1; long appSize; //获取包管理器 PackageManager packageManager = context.getPackageManager(); for (String packageName : packageNames) { AppInfos appInfo = new AppInfos(); try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); icon = packageInfo.applicationInfo.loadIcon(packageManager);//拿到图标 appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();//拿到APP名称 int flags = packageInfo.applicationInfo.flags;//应用标记 //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appType = RunningAppInfos.APP_TYPE_SYS; } else { appType = RunningAppInfos.APP_TYPE_USER; } //判断安装路径是ROM中还是SD中 if ((flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { //表示在SD卡中 appInfo.setAppLocation(AppInfos.LOCATION_SD); } else { appInfo.setAppLocation(AppInfos.LOCATION_ROM); } //获取到apk资源路径 String sourceDir = packageInfo.applicationInfo.sourceDir; //获取到资源大小-即App占用空间 File file = new File(sourceDir); appSize = file.length(); appInfo.setAppName(appName); appInfo.setAppLogo(icon); appInfo.setAppType(appType); appInfo.setAppSize(appSize); appInfo.setAppPackageName(packageName); //增加到集合 appInfos.add(appInfo); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return appInfos; } /** * 拿到所有正在运行的应用信息 * * @param context * @return */ public static List<RunningAppInfos> getRunningAppInfos(Context context) { Drawable icon = null;//应用图标 String appName = null;//应用名称 String packageName;//应用包名 int pid = -1; int memoSize = 0;//占用内存大小 int appType = -1; int positionID = 0; List<RunningAppInfos> infosArrayList = new ArrayList<>(); //拿到进程管理器 ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); //拿到运行的进程 List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses(); //拿到包管理器 PackageManager packageManager = context.getPackageManager(); for (ActivityManager.RunningAppProcessInfo runningAppProcesse : runningAppProcesses) { packageName = runningAppProcesse.processName;//拿到进程名(包名) try { PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);//拿到包信息 icon = packageInfo.applicationInfo.loadIcon(packageManager);//拿到图标 appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();//拿到APP名称 int flags = packageInfo.applicationInfo.flags;//应用标记 //判断是系统应用还是第三方应用 if (isSystemApp(flags)) { //表示系统App appType = RunningAppInfos.APP_TYPE_SYS; } else { appType = RunningAppInfos.APP_TYPE_USER; } pid = runningAppProcesse.pid;//拿到进程ID Debug.MemoryInfo[] memoryInfo = activityManager.getProcessMemoryInfo(new int[]{pid}); memoSize = memoryInfo[0].getTotalPrivateDirty() * 1024;//获取到进程占用内存大小 } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); //如果捕获到异常就帮其设置一个默认的图标和名称----------------!!!!!!这一点很重要,否则是不对的 icon = context.getResources().getDrawable(R.drawable.default_app_logo); appName = "UNKNOW APP"; appType = RunningAppInfos.APP_TYPE_SYS; } finally { //创建一个RunningAppInfos RunningAppInfos runningAppInfos = new RunningAppInfos(icon, appName, packageName, pid, memoSize, appType, false, positionID); //添加到集合 infosArrayList.add(runningAppInfos); } positionID++; } //SystemClock.sleep(5000); return infosArrayList; } /** * 返回进程的总个数 * * @param context * @return */ public static int getProcessCount(Context context) { // 得到进程管理者 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); // 获取到当前手机上面所有运行的进程 List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager .getRunningAppProcesses(); // 获取手机上面一共有多少个进程 return runningAppProcesses.size(); } /** * 判断是否系统APP * * @param flags * @return */ private static boolean isSystemApp(int flags) { /** * 方法一: * 第三方app放在data/data下,系统应用放在system/data下 * 可以判断路径是否包含关键路径来区别应用类型 */ /** * 方法二: * 采用App的flags进行与运算 */ //判断是系统应用还是第三方应用 if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) { //表示系统App return true; } else { return false; } } }
10,043
0.562451
0.558106
299
29.016722
27.577494
141
false
false
0
0
0
0
0
0
0.38796
false
false
12
60379719b7b3796a21b7cd78a68f4919beb6c14f
6,124,623,428,490
2757bb6e51a639337349e3bb05d25e7e0d622aeb
/app/src/main/java/com/consultoraestrategia/ss_crmeducativo/login/LoginRepository.java
6d50b887456962f89cb4f6e583fbd483c6cf632e
[]
no_license
irwindiho/SS_crmeducativo_v2
https://github.com/irwindiho/SS_crmeducativo_v2
808df46e93d525d0db44dc45007abff974ea7176
8f25dec7ef51c1d6f022b1253666be159539fdad
refs/heads/master
2020-12-02T08:14:34.719000
2017-07-10T15:30:58
2017-07-10T15:30:58
96,554,707
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.consultoraestrategia.ss_crmeducativo.login; /** * Created by kelvi on 21/02/2017. */ public interface LoginRepository { void checkSession(); void signIn(String user, String password); }
UTF-8
Java
211
java
LoginRepository.java
Java
[ { "context": "trategia.ss_crmeducativo.login;\n\n/**\n * Created by kelvi on 21/02/2017.\n */\n\npublic interface LoginReposit", "end": 80, "score": 0.9992502331733704, "start": 75, "tag": "USERNAME", "value": "kelvi" } ]
null
[]
package com.consultoraestrategia.ss_crmeducativo.login; /** * Created by kelvi on 21/02/2017. */ public interface LoginRepository { void checkSession(); void signIn(String user, String password); }
211
0.725118
0.687204
11
18.181818
20.026428
55
false
false
0
0
0
0
0
0
0.363636
false
false
12
100d0877610b483ffafcba07c7404d93269b4e1c
22,058,952,093,612
0f6579ea885f7f1f3b5d29a9210cd7f6a7da0d66
/src/ExercMenin4/ThreadUm.java
e2ffdcf826a465443563a7ad9f4da68fecce7898
[]
no_license
VitorZaions/BufferThreads
https://github.com/VitorZaions/BufferThreads
3c5f69d34cf9241dc7c79d7d5dce1e5cf1091b3c
26819de48c178c7518d30ec4fe6e77e3a94f904f
refs/heads/main
2023-01-28T04:43:05.667000
2020-12-08T22:29:31
2020-12-08T22:29:31
319,774,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ExercMenin4; public class ThreadUm implements Runnable { @Override public void run() { try { Thread.sleep(1000); int random = Service.getRandomNumberInRange(1, 5); System.out.println("Thread 1: " + random); } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
367
java
ThreadUm.java
Java
[]
null
[]
package ExercMenin4; public class ThreadUm implements Runnable { @Override public void run() { try { Thread.sleep(1000); int random = Service.getRandomNumberInRange(1, 5); System.out.println("Thread 1: " + random); } catch (InterruptedException e) { e.printStackTrace(); } } }
367
0.558583
0.536785
19
18.31579
19.679144
62
false
false
0
0
0
0
0
0
0.315789
false
false
12
a8db301832a346d86726817659d6e554d66af25c
36,610,301,251,748
268d520679c99b428f7643ace48769add281b176
/app/src/main/java/com/ultron/ultron/app/AudioApplication.java
d0b8cfbb92d4519f11bec27c19e09d248ee0b0b9
[]
no_license
danieldhop/RECFREE
https://github.com/danieldhop/RECFREE
1ced470b73890b93fc84d9c41fa0beb25961c470
95395b0d6507638afa6ed1d5216168c43691f3a0
refs/heads/master
2020-05-04T10:39:23.616000
2019-04-02T15:01:46
2019-04-02T15:01:46
179,092,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ultron.ultron.app; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.PowerManager; import android.os.Process; import android.support.v7.preference.PreferenceManager; import android.util.Log; import android.view.View; import com.github.axet.androidlibrary.app.NotificationManagerCompat; import com.github.axet.androidlibrary.widgets.NotificationChannelCompat; import com.github.axet.androidlibrary.widgets.RemoteNotificationCompat; import com.github.axet.audiolibrary.app.RawSamples; import com.github.axet.audiolibrary.app.Sound; import com.github.axet.audiolibrary.encoders.Encoder; import com.github.axet.audiolibrary.encoders.EncoderInfo; import com.github.axet.audiolibrary.encoders.FormatFLAC; import com.github.axet.audiolibrary.encoders.FormatM4A; import com.github.axet.audiolibrary.encoders.FormatOGG; import com.github.axet.audiolibrary.encoders.OnFlyEncoding; import com.ultron.ultron.R; import com.ultron.ultron.activities.MainActivity; import com.ultron.ultron.services.RecordingService; import java.io.File; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; public class AudioApplication extends com.github.axet.audiolibrary.app.MainApplication { public static final String PREFERENCE_CONTROLS = "controls"; public static final String PREFERENCE_TARGET = "target"; public static final String PREFERENCE_FLY = "fly"; public static final String PREFERENCE_SOURCE = "bluetooth"; public static final String PREFERENCE_VERSION = "version"; public static final String PREFERENCE_OPTIMIZATION = "optimization"; public static final String PREFERENCE_NEXT = "next"; public NotificationChannelCompat channelStatus; public RecordingStorage recording; public static AudioApplication from(Context context) { return (AudioApplication) com.github.axet.audiolibrary.app.MainApplication.from(context); } public static class RecordingStorage { public static final int PINCH = 1; public static final int UPDATESAMPLES = 2; public static final int END = 3; public static final int ERROR = 4; public static final int MUTED = 5; public static final int UNMUTED = 6; public static final int PAUSED = 7; public Context context; public final ArrayList<Handler> handlers = new ArrayList<>(); public Sound sound; public Storage storage; public Encoder e; public AtomicBoolean interrupt = new AtomicBoolean(); // nio throws ClosedByInterruptException if thread interrupted public Thread thread; public final Object bufferSizeLock = new Object(); // lock for bufferSize public int bufferSize; // dynamic buffer size. big for backgound recording. small for realtime view updates. public int sampleRate; // variable from settings. how may samples per second. public int samplesUpdate; // pitch size in samples. how many samples count need to update view. 4410 for 100ms update. public int samplesUpdateStereo; // samplesUpdate * number of channels public Uri targetUri = null; // output target file 2016-01-01 01.01.01.wav public long samplesTime; // how many samples passed for current recording, stereo = samplesTime * 2 public ShortBuffer dbBuffer = null; // PinchView samples buffer public int pitchTime; // screen width public RecordingStorage(Context context, int pitchTime) { this.context = context; this.pitchTime = pitchTime; storage = new Storage(context); sound = new Sound(context); sampleRate = Sound.getSampleRate(context); samplesUpdate = (int) (pitchTime * sampleRate / 1000f); samplesUpdateStereo = samplesUpdate * Sound.getChannels(context); final SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(context); if (storage.recordingPending()) { String file = shared.getString(AudioApplication.PREFERENCE_TARGET, null); if (file != null) { if (file.startsWith(ContentResolver.SCHEME_CONTENT)) targetUri = Uri.parse(file); else if (file.startsWith(ContentResolver.SCHEME_FILE)) targetUri = Uri.parse(file); else targetUri = Uri.fromFile(new File(file)); } } if (targetUri == null) targetUri = storage.getNewFile(); SharedPreferences.Editor editor = shared.edit(); editor.putString(AudioApplication.PREFERENCE_TARGET, targetUri.toString()); editor.commit(); } public void startRecording() { sound.silent(); final SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(context); int user; if (shared.getString(AudioApplication.PREFERENCE_SOURCE, context.getString(R.string.source_mic)).equals(context.getString(R.string.source_raw))) { if (Sound.isUnprocessedSupported(context)) user = MediaRecorder.AudioSource.UNPROCESSED; else user = MediaRecorder.AudioSource.VOICE_RECOGNITION; } else { user = MediaRecorder.AudioSource.MIC; } int[] ss = new int[]{ user, MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.DEFAULT }; if (shared.getBoolean(AudioApplication.PREFERENCE_FLY, false)) { final OnFlyEncoding fly = new OnFlyEncoding(storage, targetUri, getInfo()); if (e == null) { // do not recreate encoder if on-fly mode enabled e = new Encoder() { @Override public void encode(short[] buf, int pos, int len) { fly.encode(buf, pos, len); } @Override public void close() { fly.close(); } }; } } else { final RawSamples rs = new RawSamples(storage.getTempRecording()); rs.open(samplesTime * Sound.getChannels(context)); e = new Encoder() { @Override public void encode(short[] buf, int pos, int len) { rs.write(buf, pos, len); } @Override public void close() { rs.close(); } }; } final AudioRecord recorder = Sound.createAudioRecorder(context, sampleRate, ss, 0); final Thread old = thread; final AtomicBoolean oldb = interrupt; interrupt = new AtomicBoolean(false); thread = new Thread("RecordingThread") { @Override public void run() { if (old != null) { oldb.set(true); old.interrupt(); try { old.join(); } catch (InterruptedException e) { return; } } PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wlcpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, RecordingService.class.getCanonicalName() + "_cpulock"); wlcpu.acquire(); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO); boolean silenceDetected = false; long silence = samplesTime; // last non silence frame long start = System.currentTimeMillis(); // recording start time long session = 0; // samples count from start of recording try { long last = System.currentTimeMillis(); recorder.startRecording(); int samplesTimeCount = 0; final int samplesTimeUpdate = 1000 * sampleRate / 1000; // how many samples we need to update 'samples'. time clock. every 1000ms. short[] buffer = null; boolean stableRefresh = false; while (!interrupt.get()) { synchronized (bufferSizeLock) { if (buffer == null || buffer.length != bufferSize) buffer = new short[bufferSize]; } int readSize = recorder.read(buffer, 0, buffer.length); if (readSize < 0) return; long now = System.currentTimeMillis(); long diff = (now - last) * sampleRate / 1000; last = now; int samples = readSize / Sound.getChannels(context); // mono samples (for booth channels) if (stableRefresh || diff >= samples) { stableRefresh = true; e.encode(buffer, 0, readSize); short[] dbBuf; int dbSize; int readSizeUpdate; if (dbBuffer != null) { ShortBuffer bb = ShortBuffer.allocate(dbBuffer.position() + readSize); dbBuffer.flip(); bb.put(dbBuffer); bb.put(buffer, 0, readSize); dbBuf = new short[bb.position()]; dbSize = dbBuf.length; bb.flip(); bb.get(dbBuf, 0, dbBuf.length); } else { dbBuf = buffer; dbSize = readSize; } readSizeUpdate = dbSize / samplesUpdateStereo * samplesUpdateStereo; for (int i = 0; i < readSizeUpdate; i += samplesUpdateStereo) { double a = RawSamples.getAmplitude(dbBuf, i, samplesUpdateStereo); if (a != 0) silence = samplesTime + (i + samplesUpdateStereo) / Sound.getChannels(context); double dB = RawSamples.getDB(a); Post(PINCH, dB); } int readSizeLen = dbSize - readSizeUpdate; if (readSizeLen > 0) { dbBuffer = ShortBuffer.allocate(readSizeLen); dbBuffer.put(dbBuf, readSizeUpdate, readSizeLen); } else { dbBuffer = null; } samplesTime += samples; samplesTimeCount += samples; if (samplesTimeCount > samplesTimeUpdate) { Post(UPDATESAMPLES, samplesTime); samplesTimeCount -= samplesTimeUpdate; } session += samples; if (samplesTime - silence > 2 * sampleRate) { // 2 second of mic muted if (!silenceDetected) { silenceDetected = true; Post(MUTED, null); } } else { if (silenceDetected) { silenceDetected = false; Post(UNMUTED, null); } } diff = (now - start) * sampleRate / 1000; // number of samples we expect by this moment if (diff - session > 2 * sampleRate) { // 2 second of silence / paused by os Post(PAUSED, null); session = diff; // reset } } } } catch (final RuntimeException e) { Post(e); } finally { wlcpu.release(); // redraw view, we may add one last pich which is not been drawen because draw tread already interrupted. // to prevent resume recording jump - draw last added pitch here. Post(END, null); if (recorder != null) recorder.release(); if (!shared.getBoolean(AudioApplication.PREFERENCE_FLY, false)) { // keep encoder open if encoding on fly enabled try { if (e != null) { e.close(); e = null; } } catch (RuntimeException e) { Post(e); } } } } }; thread.start(); } public void stopRecording() { if (thread != null) { interrupt.set(true); try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } thread = null; } sound.unsilent(); } public EncoderInfo getInfo() { final int channels = Sound.getChannels(context); final int bps = Sound.DEFAULT_AUDIOFORMAT == AudioFormat.ENCODING_PCM_16BIT ? 16 : 8; return new EncoderInfo(channels, sampleRate, bps); } // calcuale buffer length dynamically, this way we can reduce thread cycles when activity in background // or phone screen is off. public void updateBufferSize(boolean pause) { synchronized (bufferSizeLock) { int samplesUpdate; if (pause) { // we need make buffer multiply of pitch.getPitchTime() (100 ms). // to prevent missing blocks from view otherwise: // file may contain not multiply 'samplesUpdate' count of samples. it is about 100ms. // we can't show on pitchView sorter then 100ms samples. we can't add partial sample because on // resumeRecording we have to apply rest of samplesUpdate or reload all samples again // from file. better then confusing user we cut them on next resumeRecording. long l = 1000; l = l / pitchTime * pitchTime; samplesUpdate = (int) (l * sampleRate / 1000.0); } else { samplesUpdate = this.samplesUpdate; } bufferSize = samplesUpdate * Sound.getChannels(context); } } public boolean isForeground() { synchronized (bufferSizeLock) { return bufferSize == this.samplesUpdate * Sound.getChannels(context); } } public void Post(Exception e) { Post(ERROR, e); } public void Post(int what, Object p) { synchronized (handlers) { for (Handler h : handlers) h.obtainMessage(what, p).sendToTarget(); } } } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); channelStatus = new NotificationChannelCompat(this, "status", "Status", NotificationManagerCompat.IMPORTANCE_LOW); switch (getVersion(PREFERENCE_VERSION, R.xml.pref_general)) { case -1: SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); if (!FormatOGG.supported(this)) { if (Build.VERSION.SDK_INT >= 18) edit.putString(AudioApplication.PREFERENCE_ENCODING, FormatM4A.EXT); else edit.putString(AudioApplication.PREFERENCE_ENCODING, FormatFLAC.EXT); } edit.putInt(PREFERENCE_VERSION, 3); edit.commit(); break; case 0: version_0_to_1(); version_1_to_2(); break; case 1: version_1_to_2(); break; case 2: version_2_to_3(); break; } } void version_0_to_1() { SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putFloat(PREFERENCE_VOLUME, shared.getFloat(PREFERENCE_VOLUME, 0) + 1); // update volume from 0..1 to 0..1..4 edit.putInt(PREFERENCE_VERSION, 1); edit.commit(); } void show(String title, String text) { PendingIntent main = PendingIntent.getService(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); RemoteNotificationCompat.Builder builder = new RemoteNotificationCompat.Builder(this, R.layout.notifictaion); builder.setViewVisibility(R.id.notification_record, View.GONE); builder.setViewVisibility(R.id.notification_pause, View.GONE); builder.setTheme(AudioApplication.getTheme(this, R.style.RecThemeLight, R.style.RecThemeDark)) .setImageViewTint(R.id.icon_circle, builder.getThemeColor(R.attr.colorButtonNormal)) .setTitle(title) .setText(text) .setMainIntent(main) .setChannel(channelStatus) .setSmallIcon(R.drawable.ic_mic); NotificationManagerCompat nm = NotificationManagerCompat.from(this); nm.notify((int) System.currentTimeMillis(), builder.build()); } @SuppressLint("RestrictedApi") void version_1_to_2() { Locale locale = Locale.getDefault(); if (locale.toString().startsWith("ru")) { String title = "Программа переименована"; String text = "'Аудио Рекордер' -> '" + getString(R.string.app_name) + "'"; show(title, text); } SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putInt(PREFERENCE_VERSION, 2); edit.commit(); } @SuppressLint("RestrictedApi") void version_2_to_3() { Locale locale = Locale.getDefault(); if (locale.toString().startsWith("tr")) { String title = "Application renamed"; String text = "'Audio Recorder' -> '" + getString(R.string.app_name) + "'"; show(title, text); } SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putInt(PREFERENCE_VERSION, 3); edit.commit(); } }
UTF-8
Java
20,726
java
AudioApplication.java
Java
[ { "context": "t) {\n return (AudioApplication) com.github.axet.audiolibrary.app.MainApplication.from(context);\n ", "end": 2267, "score": 0.9731676578521729, "start": 2263, "tag": "USERNAME", "value": "axet" }, { "context": "рамма переименована\";\n String text = \"'Аудио Рекордер' -> '\" + getString(R.string.app_name) + \"'\";\n ", "end": 19832, "score": 0.9997942447662354, "start": 19818, "tag": "NAME", "value": "Аудио Рекордер" } ]
null
[]
package com.ultron.ultron.app; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.PowerManager; import android.os.Process; import android.support.v7.preference.PreferenceManager; import android.util.Log; import android.view.View; import com.github.axet.androidlibrary.app.NotificationManagerCompat; import com.github.axet.androidlibrary.widgets.NotificationChannelCompat; import com.github.axet.androidlibrary.widgets.RemoteNotificationCompat; import com.github.axet.audiolibrary.app.RawSamples; import com.github.axet.audiolibrary.app.Sound; import com.github.axet.audiolibrary.encoders.Encoder; import com.github.axet.audiolibrary.encoders.EncoderInfo; import com.github.axet.audiolibrary.encoders.FormatFLAC; import com.github.axet.audiolibrary.encoders.FormatM4A; import com.github.axet.audiolibrary.encoders.FormatOGG; import com.github.axet.audiolibrary.encoders.OnFlyEncoding; import com.ultron.ultron.R; import com.ultron.ultron.activities.MainActivity; import com.ultron.ultron.services.RecordingService; import java.io.File; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; public class AudioApplication extends com.github.axet.audiolibrary.app.MainApplication { public static final String PREFERENCE_CONTROLS = "controls"; public static final String PREFERENCE_TARGET = "target"; public static final String PREFERENCE_FLY = "fly"; public static final String PREFERENCE_SOURCE = "bluetooth"; public static final String PREFERENCE_VERSION = "version"; public static final String PREFERENCE_OPTIMIZATION = "optimization"; public static final String PREFERENCE_NEXT = "next"; public NotificationChannelCompat channelStatus; public RecordingStorage recording; public static AudioApplication from(Context context) { return (AudioApplication) com.github.axet.audiolibrary.app.MainApplication.from(context); } public static class RecordingStorage { public static final int PINCH = 1; public static final int UPDATESAMPLES = 2; public static final int END = 3; public static final int ERROR = 4; public static final int MUTED = 5; public static final int UNMUTED = 6; public static final int PAUSED = 7; public Context context; public final ArrayList<Handler> handlers = new ArrayList<>(); public Sound sound; public Storage storage; public Encoder e; public AtomicBoolean interrupt = new AtomicBoolean(); // nio throws ClosedByInterruptException if thread interrupted public Thread thread; public final Object bufferSizeLock = new Object(); // lock for bufferSize public int bufferSize; // dynamic buffer size. big for backgound recording. small for realtime view updates. public int sampleRate; // variable from settings. how may samples per second. public int samplesUpdate; // pitch size in samples. how many samples count need to update view. 4410 for 100ms update. public int samplesUpdateStereo; // samplesUpdate * number of channels public Uri targetUri = null; // output target file 2016-01-01 01.01.01.wav public long samplesTime; // how many samples passed for current recording, stereo = samplesTime * 2 public ShortBuffer dbBuffer = null; // PinchView samples buffer public int pitchTime; // screen width public RecordingStorage(Context context, int pitchTime) { this.context = context; this.pitchTime = pitchTime; storage = new Storage(context); sound = new Sound(context); sampleRate = Sound.getSampleRate(context); samplesUpdate = (int) (pitchTime * sampleRate / 1000f); samplesUpdateStereo = samplesUpdate * Sound.getChannels(context); final SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(context); if (storage.recordingPending()) { String file = shared.getString(AudioApplication.PREFERENCE_TARGET, null); if (file != null) { if (file.startsWith(ContentResolver.SCHEME_CONTENT)) targetUri = Uri.parse(file); else if (file.startsWith(ContentResolver.SCHEME_FILE)) targetUri = Uri.parse(file); else targetUri = Uri.fromFile(new File(file)); } } if (targetUri == null) targetUri = storage.getNewFile(); SharedPreferences.Editor editor = shared.edit(); editor.putString(AudioApplication.PREFERENCE_TARGET, targetUri.toString()); editor.commit(); } public void startRecording() { sound.silent(); final SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(context); int user; if (shared.getString(AudioApplication.PREFERENCE_SOURCE, context.getString(R.string.source_mic)).equals(context.getString(R.string.source_raw))) { if (Sound.isUnprocessedSupported(context)) user = MediaRecorder.AudioSource.UNPROCESSED; else user = MediaRecorder.AudioSource.VOICE_RECOGNITION; } else { user = MediaRecorder.AudioSource.MIC; } int[] ss = new int[]{ user, MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.DEFAULT }; if (shared.getBoolean(AudioApplication.PREFERENCE_FLY, false)) { final OnFlyEncoding fly = new OnFlyEncoding(storage, targetUri, getInfo()); if (e == null) { // do not recreate encoder if on-fly mode enabled e = new Encoder() { @Override public void encode(short[] buf, int pos, int len) { fly.encode(buf, pos, len); } @Override public void close() { fly.close(); } }; } } else { final RawSamples rs = new RawSamples(storage.getTempRecording()); rs.open(samplesTime * Sound.getChannels(context)); e = new Encoder() { @Override public void encode(short[] buf, int pos, int len) { rs.write(buf, pos, len); } @Override public void close() { rs.close(); } }; } final AudioRecord recorder = Sound.createAudioRecorder(context, sampleRate, ss, 0); final Thread old = thread; final AtomicBoolean oldb = interrupt; interrupt = new AtomicBoolean(false); thread = new Thread("RecordingThread") { @Override public void run() { if (old != null) { oldb.set(true); old.interrupt(); try { old.join(); } catch (InterruptedException e) { return; } } PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wlcpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, RecordingService.class.getCanonicalName() + "_cpulock"); wlcpu.acquire(); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO); boolean silenceDetected = false; long silence = samplesTime; // last non silence frame long start = System.currentTimeMillis(); // recording start time long session = 0; // samples count from start of recording try { long last = System.currentTimeMillis(); recorder.startRecording(); int samplesTimeCount = 0; final int samplesTimeUpdate = 1000 * sampleRate / 1000; // how many samples we need to update 'samples'. time clock. every 1000ms. short[] buffer = null; boolean stableRefresh = false; while (!interrupt.get()) { synchronized (bufferSizeLock) { if (buffer == null || buffer.length != bufferSize) buffer = new short[bufferSize]; } int readSize = recorder.read(buffer, 0, buffer.length); if (readSize < 0) return; long now = System.currentTimeMillis(); long diff = (now - last) * sampleRate / 1000; last = now; int samples = readSize / Sound.getChannels(context); // mono samples (for booth channels) if (stableRefresh || diff >= samples) { stableRefresh = true; e.encode(buffer, 0, readSize); short[] dbBuf; int dbSize; int readSizeUpdate; if (dbBuffer != null) { ShortBuffer bb = ShortBuffer.allocate(dbBuffer.position() + readSize); dbBuffer.flip(); bb.put(dbBuffer); bb.put(buffer, 0, readSize); dbBuf = new short[bb.position()]; dbSize = dbBuf.length; bb.flip(); bb.get(dbBuf, 0, dbBuf.length); } else { dbBuf = buffer; dbSize = readSize; } readSizeUpdate = dbSize / samplesUpdateStereo * samplesUpdateStereo; for (int i = 0; i < readSizeUpdate; i += samplesUpdateStereo) { double a = RawSamples.getAmplitude(dbBuf, i, samplesUpdateStereo); if (a != 0) silence = samplesTime + (i + samplesUpdateStereo) / Sound.getChannels(context); double dB = RawSamples.getDB(a); Post(PINCH, dB); } int readSizeLen = dbSize - readSizeUpdate; if (readSizeLen > 0) { dbBuffer = ShortBuffer.allocate(readSizeLen); dbBuffer.put(dbBuf, readSizeUpdate, readSizeLen); } else { dbBuffer = null; } samplesTime += samples; samplesTimeCount += samples; if (samplesTimeCount > samplesTimeUpdate) { Post(UPDATESAMPLES, samplesTime); samplesTimeCount -= samplesTimeUpdate; } session += samples; if (samplesTime - silence > 2 * sampleRate) { // 2 second of mic muted if (!silenceDetected) { silenceDetected = true; Post(MUTED, null); } } else { if (silenceDetected) { silenceDetected = false; Post(UNMUTED, null); } } diff = (now - start) * sampleRate / 1000; // number of samples we expect by this moment if (diff - session > 2 * sampleRate) { // 2 second of silence / paused by os Post(PAUSED, null); session = diff; // reset } } } } catch (final RuntimeException e) { Post(e); } finally { wlcpu.release(); // redraw view, we may add one last pich which is not been drawen because draw tread already interrupted. // to prevent resume recording jump - draw last added pitch here. Post(END, null); if (recorder != null) recorder.release(); if (!shared.getBoolean(AudioApplication.PREFERENCE_FLY, false)) { // keep encoder open if encoding on fly enabled try { if (e != null) { e.close(); e = null; } } catch (RuntimeException e) { Post(e); } } } } }; thread.start(); } public void stopRecording() { if (thread != null) { interrupt.set(true); try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } thread = null; } sound.unsilent(); } public EncoderInfo getInfo() { final int channels = Sound.getChannels(context); final int bps = Sound.DEFAULT_AUDIOFORMAT == AudioFormat.ENCODING_PCM_16BIT ? 16 : 8; return new EncoderInfo(channels, sampleRate, bps); } // calcuale buffer length dynamically, this way we can reduce thread cycles when activity in background // or phone screen is off. public void updateBufferSize(boolean pause) { synchronized (bufferSizeLock) { int samplesUpdate; if (pause) { // we need make buffer multiply of pitch.getPitchTime() (100 ms). // to prevent missing blocks from view otherwise: // file may contain not multiply 'samplesUpdate' count of samples. it is about 100ms. // we can't show on pitchView sorter then 100ms samples. we can't add partial sample because on // resumeRecording we have to apply rest of samplesUpdate or reload all samples again // from file. better then confusing user we cut them on next resumeRecording. long l = 1000; l = l / pitchTime * pitchTime; samplesUpdate = (int) (l * sampleRate / 1000.0); } else { samplesUpdate = this.samplesUpdate; } bufferSize = samplesUpdate * Sound.getChannels(context); } } public boolean isForeground() { synchronized (bufferSizeLock) { return bufferSize == this.samplesUpdate * Sound.getChannels(context); } } public void Post(Exception e) { Post(ERROR, e); } public void Post(int what, Object p) { synchronized (handlers) { for (Handler h : handlers) h.obtainMessage(what, p).sendToTarget(); } } } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); channelStatus = new NotificationChannelCompat(this, "status", "Status", NotificationManagerCompat.IMPORTANCE_LOW); switch (getVersion(PREFERENCE_VERSION, R.xml.pref_general)) { case -1: SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); if (!FormatOGG.supported(this)) { if (Build.VERSION.SDK_INT >= 18) edit.putString(AudioApplication.PREFERENCE_ENCODING, FormatM4A.EXT); else edit.putString(AudioApplication.PREFERENCE_ENCODING, FormatFLAC.EXT); } edit.putInt(PREFERENCE_VERSION, 3); edit.commit(); break; case 0: version_0_to_1(); version_1_to_2(); break; case 1: version_1_to_2(); break; case 2: version_2_to_3(); break; } } void version_0_to_1() { SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putFloat(PREFERENCE_VOLUME, shared.getFloat(PREFERENCE_VOLUME, 0) + 1); // update volume from 0..1 to 0..1..4 edit.putInt(PREFERENCE_VERSION, 1); edit.commit(); } void show(String title, String text) { PendingIntent main = PendingIntent.getService(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); RemoteNotificationCompat.Builder builder = new RemoteNotificationCompat.Builder(this, R.layout.notifictaion); builder.setViewVisibility(R.id.notification_record, View.GONE); builder.setViewVisibility(R.id.notification_pause, View.GONE); builder.setTheme(AudioApplication.getTheme(this, R.style.RecThemeLight, R.style.RecThemeDark)) .setImageViewTint(R.id.icon_circle, builder.getThemeColor(R.attr.colorButtonNormal)) .setTitle(title) .setText(text) .setMainIntent(main) .setChannel(channelStatus) .setSmallIcon(R.drawable.ic_mic); NotificationManagerCompat nm = NotificationManagerCompat.from(this); nm.notify((int) System.currentTimeMillis(), builder.build()); } @SuppressLint("RestrictedApi") void version_1_to_2() { Locale locale = Locale.getDefault(); if (locale.toString().startsWith("ru")) { String title = "Программа переименована"; String text = "'<NAME>' -> '" + getString(R.string.app_name) + "'"; show(title, text); } SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putInt(PREFERENCE_VERSION, 2); edit.commit(); } @SuppressLint("RestrictedApi") void version_2_to_3() { Locale locale = Locale.getDefault(); if (locale.toString().startsWith("tr")) { String title = "Application renamed"; String text = "'Audio Recorder' -> '" + getString(R.string.app_name) + "'"; show(title, text); } SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor edit = shared.edit(); edit.putInt(PREFERENCE_VERSION, 3); edit.commit(); } }
20,705
0.521724
0.515635
472
42.836864
31.499746
158
false
false
0
0
0
0
0
0
0.675847
false
false
12
2471c93197612cd50b518ddd62ac40aaba2dd94b
37,452,114,836,036
df37584496b2659258c626aff577adff1fa72cc5
/ProjetoII/app/src/main/java/com/example/douglas/projetoii/Calculadora.java
31e72526206ce3633271675185e58ea12a9ff4bd
[]
no_license
LeomaraMAbreu/ProjetoMobile_II
https://github.com/LeomaraMAbreu/ProjetoMobile_II
d0784d8eed1c59dfd9450b61f19ebaf667cfb9b6
96edc8b4078f9c156b6f5e12644809f8811854fb
refs/heads/master
2020-03-21T06:52:30.062000
2018-06-22T02:55:00
2018-06-22T02:55:00
138,246,512
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.douglas.projetoii; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Calculadora extends AppCompatActivity { private EditText v1; private EditText v2; private EditText vp1; private EditText prcv; private Button sm, sb, dv, mt, porcentagem; private TextView resultado, rPercent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculadora ); v1 = (EditText) findViewById(R.id.n1); v2 = (EditText) findViewById(R.id.n2); sm = (Button) findViewById(R.id.soma); sb = (Button) findViewById(R.id.sub); mt = (Button) findViewById(R.id.mult); dv = (Button) findViewById(R.id.div); porcentagem = (Button) findViewById(R.id.btPercent); resultado = (TextView) findViewById(R.id.result); vp1 = (EditText) findViewById(R.id.percent); prcv = (EditText) findViewById(R.id.prcValor); rPercent = (TextView) findViewById(R.id.pResult); } public void btnSomar (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = Double.valueOf(nV1) + Double.valueOf(nV2); resultado.setText(String.valueOf(res)); } public void btnSub (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = (Double.valueOf(nV2))-(Double.valueOf(nV1)); resultado.setText(String.valueOf(res)); } public void btnDiv (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = (Double.valueOf(nV2))/(Double.valueOf(nV1)); resultado.setText(String.valueOf(res)); } public void btnMult (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = Double.valueOf(nV1) * Double.valueOf(nV2); resultado.setText(String.valueOf(res)); } public void btnPercent(View view){ String p = prcv.getText().toString(); String v = vp1.getText().toString(); Double res = (Double.valueOf(v) * (Double.valueOf(p)/100)); rPercent.setText(String.valueOf(res)); } }
UTF-8
Java
2,471
java
Calculadora.java
Java
[]
null
[]
package com.example.douglas.projetoii; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Calculadora extends AppCompatActivity { private EditText v1; private EditText v2; private EditText vp1; private EditText prcv; private Button sm, sb, dv, mt, porcentagem; private TextView resultado, rPercent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculadora ); v1 = (EditText) findViewById(R.id.n1); v2 = (EditText) findViewById(R.id.n2); sm = (Button) findViewById(R.id.soma); sb = (Button) findViewById(R.id.sub); mt = (Button) findViewById(R.id.mult); dv = (Button) findViewById(R.id.div); porcentagem = (Button) findViewById(R.id.btPercent); resultado = (TextView) findViewById(R.id.result); vp1 = (EditText) findViewById(R.id.percent); prcv = (EditText) findViewById(R.id.prcValor); rPercent = (TextView) findViewById(R.id.pResult); } public void btnSomar (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = Double.valueOf(nV1) + Double.valueOf(nV2); resultado.setText(String.valueOf(res)); } public void btnSub (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = (Double.valueOf(nV2))-(Double.valueOf(nV1)); resultado.setText(String.valueOf(res)); } public void btnDiv (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = (Double.valueOf(nV2))/(Double.valueOf(nV1)); resultado.setText(String.valueOf(res)); } public void btnMult (View view){ String nV1 = v1.getText().toString(); String nV2 = v2.getText().toString(); Double res = Double.valueOf(nV1) * Double.valueOf(nV2); resultado.setText(String.valueOf(res)); } public void btnPercent(View view){ String p = prcv.getText().toString(); String v = vp1.getText().toString(); Double res = (Double.valueOf(v) * (Double.valueOf(p)/100)); rPercent.setText(String.valueOf(res)); } }
2,471
0.645488
0.630514
65
37
18.783791
67
false
false
0
0
0
0
0
0
0.784615
false
false
12
556d2237f9e341e09b885a3f3b86e2927632aa44
36,034,775,639,766
c990c22df76c1a4e02c1969286d994638efd77fe
/app/src/main/java/com/example/cloudmusic/view/viewInterface/PlayView.java
7a1e025d96c022f50f32b16b8e20abd9e87a5a0b
[]
no_license
RottenOnion/CloudMusic
https://github.com/RottenOnion/CloudMusic
2e6f6e0e4bea6d7f1a09847396192343c2474370
00903c23657f892aceef8e5f1700b4304dce17a0
refs/heads/master
2020-06-10T07:44:24.516000
2017-02-26T06:35:46
2017-02-26T06:35:46
75,986,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.cloudmusic.view.viewInterface; import android.content.Context; import android.content.Intent; /** * Created by py on 2017/2/26. */ public interface PlayView { void receiveUiBroadcast(Context context, Intent intent); void recevieSeekBarBroadcast(Context context,Intent intent); }
UTF-8
Java
312
java
PlayView.java
Java
[ { "context": "\nimport android.content.Intent;\n\n/**\n * Created by py on 2017/2/26.\n */\n\npublic interface PlayView {\n ", "end": 136, "score": 0.9976270198822021, "start": 134, "tag": "USERNAME", "value": "py" } ]
null
[]
package com.example.cloudmusic.view.viewInterface; import android.content.Context; import android.content.Intent; /** * Created by py on 2017/2/26. */ public interface PlayView { void receiveUiBroadcast(Context context, Intent intent); void recevieSeekBarBroadcast(Context context,Intent intent); }
312
0.772436
0.75
13
23
22.917913
64
false
false
0
0
0
0
0
0
0.538462
false
false
12
a5a087b80e43b3a7b8448d320befcd3427a36910
5,609,227,349,757
2c26a0f58aa29511e344c5ccb0ce49f5b6fa3581
/app/src/main/java/com/shwm/starwed/dao/bean/ChatMsgEntity.java
595b2189308589ad07c836ca78acc9aa2e814120
[]
no_license
wangru0926/Starwed
https://github.com/wangru0926/Starwed
0ba907c785021b2360df3c17ebb57237c73a21be
45a190c9eadc6ea092d46cdd07623c1963efd6b8
refs/heads/master
2020-02-28T18:25:06.048000
2017-08-15T05:20:52
2017-08-15T05:20:52
84,307,383
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shwm.starwed.dao.bean; import android.text.TextUtils; import com.shwm.starwed.bean.wechat.GetMsgBean; import com.shwm.starwed.bean.wechat.SendMsgBean; import com.shwm.starwed.dao.greendao.ChatMsgEntityDao; import com.shwm.starwed.dao.greendao.DaoSession; import com.shwm.starwed.other.wechataudio.MsgTypeEnum; import com.shwm.starwed.utils.TimeUtil; import com.shwm.starwed.utils.UL; import org.greenrobot.greendao.DaoException; import org.greenrobot.greendao.annotation.Convert; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Transient; import org.greenrobot.greendao.converter.PropertyConverter; import java.util.Date; /** * 聊天发送和接收消息保存 * Created by wr on 2017/7/6. */ @Entity( nameInDb = "ChatMsg",//表名 active = true//实体有更新,删除和刷新方法。 ) public class ChatMsgEntity { public static final String TAG = "ChatMsgEntity"; @Id(autoincrement = true) private Long id; private String fromUserAccount; private String toUserAccount; private Date sendTime; @Convert(converter = MsgTypeConverter.class, columnType = String.class)//Enum 枚举转成String private MsgTypeEnum msgTypeEnum; private String text;//文字/语音播放时长 private String url;//语音/图片 网址 private String path;//语音/图片 路径 private boolean isSuccess;//发送成功 @Transient //不存储在数据库中 private int tempUsageCount; /** * Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** * Used for active entity operations. */ @Generated(hash = 1483581399) private transient ChatMsgEntityDao myDao; /** * 收到的消息转成数据库类型 */ public ChatMsgEntity(GetMsgBean msg) { UL.d(TAG, msg.toString()); this.fromUserAccount = msg.getFromUserAccount(); this.sendTime = TimeUtil.toDate(msg.getSendTime()); this.toUserAccount = msg.getToUserAccount(); this.text = msg.getContent().getText(); this.url = msg.getContent().getUrl(); this.msgTypeEnum = new MsgTypeConverter().convertToEntityProperty(msg.getContent().getContentType()); } /** * 发送的消息转成数据库类型 */ public ChatMsgEntity(SendMsgBean msg) { UL.d(TAG, msg.toString()); this.fromUserAccount = msg.getFromUserAccount(); this.sendTime = TimeUtil.toDate(msg.getSendTime()); this.toUserAccount = msg.getToUserAccount(); this.text = msg.getContent(); this.path = msg.getPath(); this.msgTypeEnum = new MsgTypeConverter().convertToEntityProperty(msg.getContentType()); } @Generated(hash = 1372600830) public ChatMsgEntity(Long id, String fromUserAccount, String toUserAccount, Date sendTime, MsgTypeEnum msgTypeEnum, String text, String url, String path, boolean isSuccess) { this.id = id; this.fromUserAccount = fromUserAccount; this.toUserAccount = toUserAccount; this.sendTime = sendTime; this.msgTypeEnum = msgTypeEnum; this.text = text; this.url = url; this.path = path; this.isSuccess = isSuccess; } @Generated(hash = 215499640) public ChatMsgEntity() { } /** * 枚举转成String */ public static class MsgTypeConverter implements PropertyConverter<MsgTypeEnum, String> { @Override public MsgTypeEnum convertToEntityProperty(String databaseValue) { if (databaseValue == null) { return null; } for (MsgTypeEnum msgTypeEnum : MsgTypeEnum.values()) { if (TextUtils.equals(msgTypeEnum.getType(), databaseValue)) { return msgTypeEnum; } } return MsgTypeEnum.TEXT; // 准备一个默认值,防止数据移除时崩溃 } @Override public String convertToDatabaseValue(MsgTypeEnum entityProperty) { // 判断返回 null return entityProperty == null ? null : entityProperty.getType(); } } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** * called by internal mechanisms, do not call yourself. */ @Generated(hash = 484158930) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getChatMsgEntityDao() : null; } @Override public String toString() { return "ChatMsgEntity{" + "id=" + id + ", fromUserAccount='" + fromUserAccount + '\'' + ", sendTime=" + sendTime + ", toUserAccount='" + toUserAccount + '\'' + ", msgTypeEnum=" + msgTypeEnum + ", text='" + text + '\'' + ", url='" + url + '\'' + ", path='" + path + '\'' + ", isSuccess=" + isSuccess + '}'; } public MsgTypeEnum getMsgTypeEnum() { return msgTypeEnum; } public void setMsgTypeEnum(MsgTypeEnum msgTypeEnum) { this.msgTypeEnum = msgTypeEnum; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFromUserAccount() { return fromUserAccount; } public void setFromUserAccount(String fromUserAccount) { this.fromUserAccount = fromUserAccount; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getToUserAccount() { return toUserAccount; } public void setToUserAccount(String toUserAccount) { this.toUserAccount = toUserAccount; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean success) { isSuccess = success; } public boolean getIsSuccess() { return this.isSuccess; } public void setIsSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } }
UTF-8
Java
7,763
java
ChatMsgEntity.java
Java
[]
null
[]
package com.shwm.starwed.dao.bean; import android.text.TextUtils; import com.shwm.starwed.bean.wechat.GetMsgBean; import com.shwm.starwed.bean.wechat.SendMsgBean; import com.shwm.starwed.dao.greendao.ChatMsgEntityDao; import com.shwm.starwed.dao.greendao.DaoSession; import com.shwm.starwed.other.wechataudio.MsgTypeEnum; import com.shwm.starwed.utils.TimeUtil; import com.shwm.starwed.utils.UL; import org.greenrobot.greendao.DaoException; import org.greenrobot.greendao.annotation.Convert; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Transient; import org.greenrobot.greendao.converter.PropertyConverter; import java.util.Date; /** * 聊天发送和接收消息保存 * Created by wr on 2017/7/6. */ @Entity( nameInDb = "ChatMsg",//表名 active = true//实体有更新,删除和刷新方法。 ) public class ChatMsgEntity { public static final String TAG = "ChatMsgEntity"; @Id(autoincrement = true) private Long id; private String fromUserAccount; private String toUserAccount; private Date sendTime; @Convert(converter = MsgTypeConverter.class, columnType = String.class)//Enum 枚举转成String private MsgTypeEnum msgTypeEnum; private String text;//文字/语音播放时长 private String url;//语音/图片 网址 private String path;//语音/图片 路径 private boolean isSuccess;//发送成功 @Transient //不存储在数据库中 private int tempUsageCount; /** * Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** * Used for active entity operations. */ @Generated(hash = 1483581399) private transient ChatMsgEntityDao myDao; /** * 收到的消息转成数据库类型 */ public ChatMsgEntity(GetMsgBean msg) { UL.d(TAG, msg.toString()); this.fromUserAccount = msg.getFromUserAccount(); this.sendTime = TimeUtil.toDate(msg.getSendTime()); this.toUserAccount = msg.getToUserAccount(); this.text = msg.getContent().getText(); this.url = msg.getContent().getUrl(); this.msgTypeEnum = new MsgTypeConverter().convertToEntityProperty(msg.getContent().getContentType()); } /** * 发送的消息转成数据库类型 */ public ChatMsgEntity(SendMsgBean msg) { UL.d(TAG, msg.toString()); this.fromUserAccount = msg.getFromUserAccount(); this.sendTime = TimeUtil.toDate(msg.getSendTime()); this.toUserAccount = msg.getToUserAccount(); this.text = msg.getContent(); this.path = msg.getPath(); this.msgTypeEnum = new MsgTypeConverter().convertToEntityProperty(msg.getContentType()); } @Generated(hash = 1372600830) public ChatMsgEntity(Long id, String fromUserAccount, String toUserAccount, Date sendTime, MsgTypeEnum msgTypeEnum, String text, String url, String path, boolean isSuccess) { this.id = id; this.fromUserAccount = fromUserAccount; this.toUserAccount = toUserAccount; this.sendTime = sendTime; this.msgTypeEnum = msgTypeEnum; this.text = text; this.url = url; this.path = path; this.isSuccess = isSuccess; } @Generated(hash = 215499640) public ChatMsgEntity() { } /** * 枚举转成String */ public static class MsgTypeConverter implements PropertyConverter<MsgTypeEnum, String> { @Override public MsgTypeEnum convertToEntityProperty(String databaseValue) { if (databaseValue == null) { return null; } for (MsgTypeEnum msgTypeEnum : MsgTypeEnum.values()) { if (TextUtils.equals(msgTypeEnum.getType(), databaseValue)) { return msgTypeEnum; } } return MsgTypeEnum.TEXT; // 准备一个默认值,防止数据移除时崩溃 } @Override public String convertToDatabaseValue(MsgTypeEnum entityProperty) { // 判断返回 null return entityProperty == null ? null : entityProperty.getType(); } } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** * called by internal mechanisms, do not call yourself. */ @Generated(hash = 484158930) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getChatMsgEntityDao() : null; } @Override public String toString() { return "ChatMsgEntity{" + "id=" + id + ", fromUserAccount='" + fromUserAccount + '\'' + ", sendTime=" + sendTime + ", toUserAccount='" + toUserAccount + '\'' + ", msgTypeEnum=" + msgTypeEnum + ", text='" + text + '\'' + ", url='" + url + '\'' + ", path='" + path + '\'' + ", isSuccess=" + isSuccess + '}'; } public MsgTypeEnum getMsgTypeEnum() { return msgTypeEnum; } public void setMsgTypeEnum(MsgTypeEnum msgTypeEnum) { this.msgTypeEnum = msgTypeEnum; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFromUserAccount() { return fromUserAccount; } public void setFromUserAccount(String fromUserAccount) { this.fromUserAccount = fromUserAccount; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getToUserAccount() { return toUserAccount; } public void setToUserAccount(String toUserAccount) { this.toUserAccount = toUserAccount; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean success) { isSuccess = success; } public boolean getIsSuccess() { return this.isSuccess; } public void setIsSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } }
7,763
0.619313
0.608436
266
27.342106
23.45303
109
false
false
0
0
0
0
0
0
0.409774
false
false
12
f91eadd57d98b4b46e4f63b44b31f0c736c768fb
39,015,482,922,616
0989ac766fe06c6116919b3b1e9bd03300d42042
/_0000/src/SetPractice.java
457bc15d762aeeb2e772b381ec25e81f3b19177f
[]
no_license
wonup2/ACSL
https://github.com/wonup2/ACSL
7d18d0f89f3c7b52a05e917162ec6c3363e26903
935fa22dc9b8178e45b5f314b6c0c989952df57a
refs/heads/master
2023-09-01T05:18:47.230000
2023-08-21T22:57:13
2023-08-21T22:57:13
199,730,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class SetPractice { public static void main(String[] args) { HashSet<Integer> s1 = new HashSet<Integer>(); s1.add(1); s1.add(2); s1.add(10); s1.add(11); s1.add(23); s1.add(1); //<-- ignore 1 since s1 has 1 s1.add(2); //<-- ignore 2 System.out.println(s1); System.out.println(s1.size()); System.out.println("Print all values in s1"); for(int n : s1) { System.out.println(n); } System.out.println("3rd value in s1"); int cnt = 0; for(int n: s1) { cnt++; if(cnt==3) System.out.println(n); } //---------------------------------------- TreeSet<Character> s2 = new TreeSet<Character>(); s2.add('A'); s2.add('Z'); s2.add('D'); System.out.println(s2); for(char c: s2) { System.out.print(c+" "); } System.out.println(); //---------------------------------------- LinkedHashSet<String> s3 = new LinkedHashSet<String>(); s3.add("Stempia"); s3.add("Hello"); s3.add("World"); s3.add("Bye"); System.out.println(s3); } }
UTF-8
Java
1,069
java
SetPractice.java
Java
[ { "context": "ring> s3 = new LinkedHashSet<String>();\n\t\ts3.add(\"Stempia\");\n\t\ts3.add(\"Hello\");\n\t\ts3.add(\"World\");\n\t\ts3.add", "end": 973, "score": 0.9979169368743896, "start": 966, "tag": "NAME", "value": "Stempia" } ]
null
[]
import java.util.*; public class SetPractice { public static void main(String[] args) { HashSet<Integer> s1 = new HashSet<Integer>(); s1.add(1); s1.add(2); s1.add(10); s1.add(11); s1.add(23); s1.add(1); //<-- ignore 1 since s1 has 1 s1.add(2); //<-- ignore 2 System.out.println(s1); System.out.println(s1.size()); System.out.println("Print all values in s1"); for(int n : s1) { System.out.println(n); } System.out.println("3rd value in s1"); int cnt = 0; for(int n: s1) { cnt++; if(cnt==3) System.out.println(n); } //---------------------------------------- TreeSet<Character> s2 = new TreeSet<Character>(); s2.add('A'); s2.add('Z'); s2.add('D'); System.out.println(s2); for(char c: s2) { System.out.print(c+" "); } System.out.println(); //---------------------------------------- LinkedHashSet<String> s3 = new LinkedHashSet<String>(); s3.add("Stempia"); s3.add("Hello"); s3.add("World"); s3.add("Bye"); System.out.println(s3); } }
1,069
0.518241
0.478017
61
16.52459
15.603285
57
false
false
0
0
0
0
0
0
2.409836
false
false
12
0e3d389ff24898f14f972a556645968065d286de
36,902,359,028,180
27a22f189fbf4431eee526255fa91f52b6f91806
/src/main/java/com/writer1/service/ReportService.java
d0ca9556f0460403dcea30610e4538c25d3ef475
[]
no_license
lca1070841799/writer1
https://github.com/lca1070841799/writer1
ea1ffa0500b4453c263abc217276e9f97e39ad47
3982c73600f0ea6807d58710d0a30be2564521df
refs/heads/master
2020-04-17T18:19:13.196000
2020-04-08T12:54:41
2020-04-08T12:54:41
166,821,275
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.writer1.service; import com.writer1.entity.Report; public interface ReportService { public int save(Report r); public String query(String username); }
UTF-8
Java
174
java
ReportService.java
Java
[]
null
[]
package com.writer1.service; import com.writer1.entity.Report; public interface ReportService { public int save(Report r); public String query(String username); }
174
0.752874
0.741379
9
18.333334
16.512621
41
false
false
0
0
0
0
0
0
0.444444
false
false
12
387c904de3f6fbbab603d2d9d23e24c55bc2b298
30,451,318,129,662
b5dcd8876dd579e1c086895dac3e09c37f27f767
/src/main/java/com/tang/result/ExceptionHandle.java
c9d3f928835b894ce4a14336614b29778e19bcad
[]
no_license
TangWin/SSMDemo
https://github.com/TangWin/SSMDemo
ab917ccda35eb814f17fde6ef2d89e33ce36e529
c91bd00f9dd3e494621fdfff5ff381a44c4134ff
refs/heads/master
2020-03-28T07:40:03.231000
2018-10-07T16:39:01
2018-10-07T16:39:03
147,916,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tang.result; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @ControllerAdvice @EnableWebMvc public class ExceptionHandle { /** * 判断错误是否是已定义的已知错误,不是则由未知错误代替 * @param e * @return * */ @ExceptionHandler(value = Exception.class) @ResponseBody public ResultMap exceptionGet(Exception e){ System.out.println("出现了异常:"+e.getMessage()); if(e instanceof DescribeException){ DescribeException MyException = (DescribeException) e; return ResultUtil.error(MyException.getCode(),MyException.getMessage()); } return ResultUtil.error(ExceptionEnum.UNDEFINED); } }
UTF-8
Java
1,055
java
ExceptionHandle.java
Java
[]
null
[]
package com.tang.result; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @ControllerAdvice @EnableWebMvc public class ExceptionHandle { /** * 判断错误是否是已定义的已知错误,不是则由未知错误代替 * @param e * @return * */ @ExceptionHandler(value = Exception.class) @ResponseBody public ResultMap exceptionGet(Exception e){ System.out.println("出现了异常:"+e.getMessage()); if(e instanceof DescribeException){ DescribeException MyException = (DescribeException) e; return ResultUtil.error(MyException.getCode(),MyException.getMessage()); } return ResultUtil.error(ExceptionEnum.UNDEFINED); } }
1,055
0.734612
0.734612
36
26.527779
26.587891
84
false
false
0
0
0
0
0
0
0.333333
false
false
12
ca7aecd486079b58832e3852ef3cf0d5dd8e4132
32,435,593,057,805
84a9eff3c4c6f2442be6ac54e43a47c6feadd031
/test/de/fuberlin/wiwiss/d2rq/sql/DatatypeTestBase.java
42900dd3324b9c8d0cf177081f03c12a11e0c2c2
[ "Apache-2.0" ]
permissive
luiseufrasio/d2rq
https://github.com/luiseufrasio/d2rq
bce5001bd58e7db8c6c1d87c115da068276c6c49
644fe85091ca1124e38efe2407bedcaa8dee490a
refs/heads/master
2021-01-18T08:17:55.451000
2013-10-04T02:22:38
2013-10-04T02:22:38
3,655,325
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.fuberlin.wiwiss.d2rq.sql; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import de.fuberlin.wiwiss.d2rq.algebra.RelationName; import de.fuberlin.wiwiss.d2rq.dbschema.DatabaseSchemaInspector; import de.fuberlin.wiwiss.d2rq.jena.GraphD2RQ; import de.fuberlin.wiwiss.d2rq.map.ClassMap; import de.fuberlin.wiwiss.d2rq.map.Database; import de.fuberlin.wiwiss.d2rq.map.Mapping; import de.fuberlin.wiwiss.d2rq.map.PropertyBridge; public abstract class DatatypeTestBase extends TestCase { private final static String EX = "http://example.com/"; private final static Resource dbURI = ResourceFactory.createResource(EX + "db"); private final static Resource classMapURI = ResourceFactory.createResource(EX + "classmap"); private final static Resource propertyBridgeURI = ResourceFactory.createResource(EX + "propertybridge"); private final static Resource valueProperty = ResourceFactory.createProperty(EX + "value"); private String jdbcURL; private String driver; private String user; private String password; private String schema; private String script; private String datatype; private GraphD2RQ graph; private DatabaseSchemaInspector inspector; public void tearDown() { if (graph != null) graph.close(); } protected void initDB(String jdbcURL, String driver, String user, String password, String script, String schema) { this.jdbcURL = jdbcURL; this.driver = driver; this.user = user; this.password = password; this.script = script; this.schema = null; dropAllTables(); } private void dropAllTables() { ConnectedDB.registerJDBCDriver(driver); ConnectedDB db = new ConnectedDB(jdbcURL, user, password); try { Statement stmt = db.connection().createStatement(); try { for (String table: allTables()) { stmt.execute("DROP TABLE " + table); } } finally { stmt.close(); } } catch (SQLException ex) { throw new RuntimeException(ex); } finally { db.close(); } } protected void createMapping(String datatype) { this.datatype = datatype; Mapping mapping = generateMapping(); mapping.configuration().setServeVocabulary(false); mapping.configuration().setUseAllOptimizations(true); mapping.connect(); graph = getGraph(mapping); inspector = mapping.databases().iterator().next().connectedDB().schemaInspector(); } protected void assertMappedType(String rdfType) { assertEquals(rdfType, inspector.columnType( SQL.parseAttribute("T_" + datatype + ".VALUE")).rdfType()); } protected void assertValues(String[] expectedValues) { assertValues(expectedValues, true); } protected void assertValues(String[] expectedValues, boolean searchValues) { ExtendedIterator<Triple> it = graph.find(Node.ANY, Node.ANY, Node.ANY); List<String> listedValues = new ArrayList<String>(); while (it.hasNext()) { listedValues.add(it.next().getObject().getLiteralLexicalForm()); } assertEquals(Arrays.asList(expectedValues), listedValues); if (!searchValues) return; for (String value : expectedValues) { assertTrue("Expected literal not in graph: '" + value + "'", graph.contains(Node.ANY, Node.ANY, Node.createLiteral(value))); } } protected void assertValuesNotFindable(String[] expectedValues) { for (String value : expectedValues) { assertFalse("Unexpected literal found in graph: '" + value + "'", graph.contains(Node.ANY, Node.ANY, Node.createLiteral(value))); } } private Set<String> allTables() { ConnectedDB.registerJDBCDriver(driver); ConnectedDB db = new ConnectedDB(jdbcURL, user, password); try { Set<String> result = new HashSet<String>(); inspector = db.schemaInspector(); for (RelationName name: inspector.listTableNames(schema)) { result.add(name.toString()); } return result; } finally { db.close(); } } private GraphD2RQ getGraph(Mapping mapping) { return new GraphD2RQ(mapping); } private Mapping generateMapping() { Mapping mapping = new Mapping(); Database database = new Database(dbURI); database.setJdbcURL(jdbcURL); database.setJDBCDriver(driver); database.setUsername(user); database.setPassword(password); database.setStartupSQLScript(ResourceFactory.createResource("file:" + script)); mapping.addDatabase(database); ClassMap classMap = new ClassMap(classMapURI); classMap.setDatabase(database); classMap.setURIPattern("row/@@T_" + datatype + ".ID@@"); mapping.addClassMap(classMap); PropertyBridge propertyBridge = new PropertyBridge(propertyBridgeURI); propertyBridge.setBelongsToClassMap(classMap); propertyBridge.addProperty(valueProperty); propertyBridge.setColumn("T_" + datatype + ".VALUE"); classMap.addPropertyBridge(propertyBridge); return mapping; } }
UTF-8
Java
5,109
java
DatatypeTestBase.java
Java
[ { "context": "L = jdbcURL;\n\t\tthis.driver = driver;\n\t\tthis.user = user;\n\t\tthis.password = password;\n\t\tthis.script = scri", "end": 1818, "score": 0.8338048458099365, "start": 1814, "tag": "USERNAME", "value": "user" }, { "context": "er = driver;\n\t\tthis.user = user;\n\t\tthis.password = password;\n\t\tthis.script = script;\n\t\tthis.schema = null;\n\t\t", "end": 1846, "score": 0.9992768168449402, "start": 1838, "tag": "PASSWORD", "value": "password" }, { "context": "ase.setJDBCDriver(driver);\n\t\tdatabase.setUsername(user);\n\t\tdatabase.setPassword(password);\n\t\tdatabase.se", "end": 4490, "score": 0.9753413200378418, "start": 4486, "tag": "USERNAME", "value": "user" }, { "context": "atabase.setUsername(user);\n\t\tdatabase.setPassword(password);\n\t\tdatabase.setStartupSQLScript(ResourceFactory.", "end": 4524, "score": 0.9992923736572266, "start": 4516, "tag": "PASSWORD", "value": "password" } ]
null
[]
package de.fuberlin.wiwiss.d2rq.sql; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import de.fuberlin.wiwiss.d2rq.algebra.RelationName; import de.fuberlin.wiwiss.d2rq.dbschema.DatabaseSchemaInspector; import de.fuberlin.wiwiss.d2rq.jena.GraphD2RQ; import de.fuberlin.wiwiss.d2rq.map.ClassMap; import de.fuberlin.wiwiss.d2rq.map.Database; import de.fuberlin.wiwiss.d2rq.map.Mapping; import de.fuberlin.wiwiss.d2rq.map.PropertyBridge; public abstract class DatatypeTestBase extends TestCase { private final static String EX = "http://example.com/"; private final static Resource dbURI = ResourceFactory.createResource(EX + "db"); private final static Resource classMapURI = ResourceFactory.createResource(EX + "classmap"); private final static Resource propertyBridgeURI = ResourceFactory.createResource(EX + "propertybridge"); private final static Resource valueProperty = ResourceFactory.createProperty(EX + "value"); private String jdbcURL; private String driver; private String user; private String password; private String schema; private String script; private String datatype; private GraphD2RQ graph; private DatabaseSchemaInspector inspector; public void tearDown() { if (graph != null) graph.close(); } protected void initDB(String jdbcURL, String driver, String user, String password, String script, String schema) { this.jdbcURL = jdbcURL; this.driver = driver; this.user = user; this.password = <PASSWORD>; this.script = script; this.schema = null; dropAllTables(); } private void dropAllTables() { ConnectedDB.registerJDBCDriver(driver); ConnectedDB db = new ConnectedDB(jdbcURL, user, password); try { Statement stmt = db.connection().createStatement(); try { for (String table: allTables()) { stmt.execute("DROP TABLE " + table); } } finally { stmt.close(); } } catch (SQLException ex) { throw new RuntimeException(ex); } finally { db.close(); } } protected void createMapping(String datatype) { this.datatype = datatype; Mapping mapping = generateMapping(); mapping.configuration().setServeVocabulary(false); mapping.configuration().setUseAllOptimizations(true); mapping.connect(); graph = getGraph(mapping); inspector = mapping.databases().iterator().next().connectedDB().schemaInspector(); } protected void assertMappedType(String rdfType) { assertEquals(rdfType, inspector.columnType( SQL.parseAttribute("T_" + datatype + ".VALUE")).rdfType()); } protected void assertValues(String[] expectedValues) { assertValues(expectedValues, true); } protected void assertValues(String[] expectedValues, boolean searchValues) { ExtendedIterator<Triple> it = graph.find(Node.ANY, Node.ANY, Node.ANY); List<String> listedValues = new ArrayList<String>(); while (it.hasNext()) { listedValues.add(it.next().getObject().getLiteralLexicalForm()); } assertEquals(Arrays.asList(expectedValues), listedValues); if (!searchValues) return; for (String value : expectedValues) { assertTrue("Expected literal not in graph: '" + value + "'", graph.contains(Node.ANY, Node.ANY, Node.createLiteral(value))); } } protected void assertValuesNotFindable(String[] expectedValues) { for (String value : expectedValues) { assertFalse("Unexpected literal found in graph: '" + value + "'", graph.contains(Node.ANY, Node.ANY, Node.createLiteral(value))); } } private Set<String> allTables() { ConnectedDB.registerJDBCDriver(driver); ConnectedDB db = new ConnectedDB(jdbcURL, user, password); try { Set<String> result = new HashSet<String>(); inspector = db.schemaInspector(); for (RelationName name: inspector.listTableNames(schema)) { result.add(name.toString()); } return result; } finally { db.close(); } } private GraphD2RQ getGraph(Mapping mapping) { return new GraphD2RQ(mapping); } private Mapping generateMapping() { Mapping mapping = new Mapping(); Database database = new Database(dbURI); database.setJdbcURL(jdbcURL); database.setJDBCDriver(driver); database.setUsername(user); database.setPassword(<PASSWORD>); database.setStartupSQLScript(ResourceFactory.createResource("file:" + script)); mapping.addDatabase(database); ClassMap classMap = new ClassMap(classMapURI); classMap.setDatabase(database); classMap.setURIPattern("row/@@T_" + datatype + ".ID@@"); mapping.addClassMap(classMap); PropertyBridge propertyBridge = new PropertyBridge(propertyBridgeURI); propertyBridge.setBelongsToClassMap(classMap); propertyBridge.addProperty(valueProperty); propertyBridge.setColumn("T_" + datatype + ".VALUE"); classMap.addPropertyBridge(propertyBridge); return mapping; } }
5,113
0.742611
0.740262
158
31.335443
23.924885
105
false
false
0
0
0
0
0
0
2.259494
false
false
12
68818442537cf866e1f2006fbcac7fc8d5af4ef4
34,230,889,393,953
b41a76a5c84110abef8a49f921b71eea727cbb2b
/Welcom/src/main/java/org/squale/welcom/outils/excel/ExcelGenerateur.java
a5b171ab281e32deef4664ca43db8a032a711fb3
[]
no_license
zeeneddie/squale
https://github.com/zeeneddie/squale
d175db676504a92f7e1148fc28512bb88d2d3bd6
e6a44c744e37317b5d81cf5081dcd6ad5360c132
refs/heads/master
2020-03-27T07:55:27.557000
2018-09-04T07:01:42
2018-09-04T07:01:42
146,205,739
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (C) 2008-2010, Squale Project - http://www.squale.org * * This file is part of Squale. * * Squale is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or any later version. * * Squale is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Squale. If not, see <http://www.gnu.org/licenses/>. */ /* * Créé le 28 oct. 04 * * Pour changer le modèle de ce fichier généré, allez à : * Fenêtre&gt;Préférences&gt;Java&gt;Génération de code&gt;Code et commentaires */ package org.squale.welcom.outils.excel; import java.io.IOException; import java.io.OutputStream; /** * Interface à implémenter pour le formatage de la sortie des fichiers Excel. * * @author Rémy Bouquet */ public interface ExcelGenerateur { /** * @throws ExcelGenerateurException : Level une erreur sur la production du fichier */ public abstract void writeExcel() throws ExcelGenerateurException; /** * @throws IOException : Probleme lors de l'ouverture des streams */ public abstract void init() throws IOException; /** * assigne l'outputstream * * @param os outputStream à setter * @throws ExcelGenerateurException exception pouvant etre levee */ public void open( OutputStream os ) throws ExcelGenerateurException; }
ISO-8859-1
Java
1,807
java
ExcelGenerateur.java
Java
[ { "context": " de la sortie des fichiers Excel.\r\n * \r\n * @author Rémy Bouquet\r\n */\r\npublic interface ExcelGenerateur\r\n{\r\n\r\n ", "end": 1148, "score": 0.9998753070831299, "start": 1136, "tag": "NAME", "value": "Rémy Bouquet" } ]
null
[]
/** * Copyright (C) 2008-2010, Squale Project - http://www.squale.org * * This file is part of Squale. * * Squale is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or any later version. * * Squale is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Squale. If not, see <http://www.gnu.org/licenses/>. */ /* * Créé le 28 oct. 04 * * Pour changer le modèle de ce fichier généré, allez à : * Fenêtre&gt;Préférences&gt;Java&gt;Génération de code&gt;Code et commentaires */ package org.squale.welcom.outils.excel; import java.io.IOException; import java.io.OutputStream; /** * Interface à implémenter pour le formatage de la sortie des fichiers Excel. * * @author <NAME> */ public interface ExcelGenerateur { /** * @throws ExcelGenerateurException : Level une erreur sur la production du fichier */ public abstract void writeExcel() throws ExcelGenerateurException; /** * @throws IOException : Probleme lors de l'ouverture des streams */ public abstract void init() throws IOException; /** * assigne l'outputstream * * @param os outputStream à setter * @throws ExcelGenerateurException exception pouvant etre levee */ public void open( OutputStream os ) throws ExcelGenerateurException; }
1,800
0.682859
0.6756
59
28.38983
27.32852
87
false
false
0
0
0
0
0
0
0.288136
false
false
12
22924009fc438782c584fb6899cf570e301221fd
34,230,889,392,659
860fb125337540fb85ee91a694100e8760a4371e
/AI project - Mazes Mode 2/src/defpackage/MainClass.java
b4f2a1da1b2917041887b7d1694605d0249ad56f
[ "MIT" ]
permissive
Trykon/MDX-AI
https://github.com/Trykon/MDX-AI
afea1ea0335e0c6a5506a55dc5e7f0fecf9ffe3e
bd50b35f43e86166095f7bf648a7c13b834abd52
refs/heads/master
2019-12-27T04:26:18.838000
2017-08-22T14:25:13
2017-08-22T14:25:13
82,589,349
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package defpackage; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class MainClass { // THIS IS BFS FOR MODE 2 - FINDING ALL POSSIBLE PATHS final static int edges = 400; // the highest existing edge number static boolean[] visited = new boolean[edges]; static File text = new File("D:/maze1.txt"); static Queue<Integer> queue = new LinkedList<Integer>(); static Queue<ArrayList<Integer>> path = new LinkedList<ArrayList<Integer>>(); static Map<Integer, List<Integer>> Connections = new HashMap<Integer, List<Integer>>(); static int amount = 0; static void go(){ if (queue.peek() == null) System.out.println("no more paths found"); else { boolean foundPath = false; for(int i=0;i<Connections.get(queue.peek()).size();i++) { int temp = Connections.get(queue.peek()).get(i); //System.out.println(queue.peek() + " " + temp); if(temp==1 && !foundPath) { // TU DOPISZ KOD for(int j=0;j<path.peek().size();j++) { System.out.print(path.peek().get(j)+","); } System.out.println(1); amount++; System.out.println(amount); foundPath = true; } else { boolean noRepetitions = true; for(int j=0;j<path.peek().size();j++) { if(path.peek().get(j)==temp) { noRepetitions = false; break; } } if(noRepetitions) { queue.add(temp); ArrayList<Integer> tempList = new ArrayList<Integer>(); tempList.addAll(path.peek()); tempList.add(temp); path.add(tempList); } } } path.remove(); queue.remove(); go(); } } public static void main(String[] args) { long time1 = System.nanoTime(); for (int i = 0; i <= edges; i++) { Connections.put(i, new LinkedList<Integer>()); } try { Scanner scan = new Scanner(text); scan.useDelimiter(" "); while (scan.hasNext()) { String inputLine = scan.nextLine(); String inputs[] = inputLine.split(" "); int v1 = Integer.parseInt(inputs[0]); int v2 = Integer.parseInt(inputs[1]); Connections.get(v1).add(v2); Connections.get(v2).add(v1); } scan.close(); // queue ArrayList<Integer> tempList = new ArrayList<Integer>(); tempList.add(0); queue.add(0); path.add(tempList); go(); } catch (FileNotFoundException e) { e.printStackTrace(); } long time2 = System.nanoTime(); System.out.println("Time: " + (time2 - time1)); } }
UTF-8
Java
2,739
java
MainClass.java
Java
[]
null
[]
package defpackage; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class MainClass { // THIS IS BFS FOR MODE 2 - FINDING ALL POSSIBLE PATHS final static int edges = 400; // the highest existing edge number static boolean[] visited = new boolean[edges]; static File text = new File("D:/maze1.txt"); static Queue<Integer> queue = new LinkedList<Integer>(); static Queue<ArrayList<Integer>> path = new LinkedList<ArrayList<Integer>>(); static Map<Integer, List<Integer>> Connections = new HashMap<Integer, List<Integer>>(); static int amount = 0; static void go(){ if (queue.peek() == null) System.out.println("no more paths found"); else { boolean foundPath = false; for(int i=0;i<Connections.get(queue.peek()).size();i++) { int temp = Connections.get(queue.peek()).get(i); //System.out.println(queue.peek() + " " + temp); if(temp==1 && !foundPath) { // TU DOPISZ KOD for(int j=0;j<path.peek().size();j++) { System.out.print(path.peek().get(j)+","); } System.out.println(1); amount++; System.out.println(amount); foundPath = true; } else { boolean noRepetitions = true; for(int j=0;j<path.peek().size();j++) { if(path.peek().get(j)==temp) { noRepetitions = false; break; } } if(noRepetitions) { queue.add(temp); ArrayList<Integer> tempList = new ArrayList<Integer>(); tempList.addAll(path.peek()); tempList.add(temp); path.add(tempList); } } } path.remove(); queue.remove(); go(); } } public static void main(String[] args) { long time1 = System.nanoTime(); for (int i = 0; i <= edges; i++) { Connections.put(i, new LinkedList<Integer>()); } try { Scanner scan = new Scanner(text); scan.useDelimiter(" "); while (scan.hasNext()) { String inputLine = scan.nextLine(); String inputs[] = inputLine.split(" "); int v1 = Integer.parseInt(inputs[0]); int v2 = Integer.parseInt(inputs[1]); Connections.get(v1).add(v2); Connections.get(v2).add(v1); } scan.close(); // queue ArrayList<Integer> tempList = new ArrayList<Integer>(); tempList.add(0); queue.add(0); path.add(tempList); go(); } catch (FileNotFoundException e) { e.printStackTrace(); } long time2 = System.nanoTime(); System.out.println("Time: " + (time2 - time1)); } }
2,739
0.593282
0.58379
105
24.085714
18.932016
88
false
false
0
0
0
0
0
0
3.590476
false
false
12
523c444086839610995470efac320309e0731e38
11,235,634,466,823
a567783a85226c5b51b040f67d0edfe548d99a0b
/app/src/main/java/com/example/dangm/appbanhang/Activity/MainActivity.java
2c19e4eea68572c174dbdfb3aeeaf9f8bc2dc850
[]
no_license
dangminhchau1994/Appbanhang
https://github.com/dangminhchau1994/Appbanhang
b4b3a29b85a62457bff20084704935bd2acfa15b
e495c78b46b5cb35a72745de712ea4e77da061a6
refs/heads/master
2021-07-14T17:07:32.992000
2017-10-19T23:19:54
2017-10-19T23:19:54
107,517,751
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dangm.appbanhang.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ViewFlipper; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.dangm.appbanhang.Adapter.SanPhamAdapter; import com.example.dangm.appbanhang.Adapter.loaispadapter; import com.example.dangm.appbanhang.Model.GioHang; import com.example.dangm.appbanhang.Model.SanPham; import com.example.dangm.appbanhang.Model.loaiSP; import com.example.dangm.appbanhang.R; import com.example.dangm.appbanhang.Util.CheckConnection; import com.example.dangm.appbanhang.Util.Server; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private NavigationView navigationView; private ViewFlipper viewFlipper; private DrawerLayout drawerLayout; private RecyclerView recyclerView; private ArrayList<SanPham> arraySanPham = new ArrayList<>(); private ListView lv; private RequestQueue requestQueue; private ArrayList<loaiSP> loaiSPArrayList = new ArrayList<>(); private loaispadapter adapter; boolean isLoading = false; private SanPhamAdapter sanphamadapter; public static ArrayList<GioHang> manggiohang; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); //Check github commit // Seconde commit //qweqweqweqwe requestQueue = Volley.newRequestQueue(getApplicationContext()); if(CheckConnection.haveNetworkConnection(getApplicationContext())) { actionBar(); actionViewFliper(); getLoaiSP(); getSP(); catchListLoaiSP(); } else { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } } private void getSP() { JsonArrayRequest jsonArray = new JsonArrayRequest(Server.sanpham, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { if(response != null) { int id = 0; int idLoai = 0; String tensp = ""; Integer giasp = 0; String hinhsp = ""; String mota = ""; for(int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.optJSONObject(i); id = jsonObject.optInt("idSP"); idLoai = jsonObject.optInt("idloaiSP"); tensp = jsonObject.optString("tenSP"); giasp = jsonObject.optInt("giaSP"); hinhsp = jsonObject.optString("hinhSP"); mota = jsonObject.optString("mota"); arraySanPham.add(new SanPham(id, idLoai, tensp, giasp, mota, hinhsp)); } sanphamadapter = new SanPhamAdapter(getApplicationContext(), arraySanPham); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2)); recyclerView.setAdapter(sanphamadapter); sanphamadapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } }); requestQueue.add(jsonArray); } private void getLoaiSP() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Server.loaisp, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Respone", response.toString()); if (response != null) { int idLoai = 0; String tenloai = ""; String hinhloai = ""; for ( int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.optJSONObject(i); idLoai = jsonObject.optInt("idLoai"); Log.d("IdLoai", String.valueOf(idLoai)); tenloai = jsonObject.optString("tenLoai"); Log.d("Tenloai", tenloai); hinhloai = jsonObject.optString("hinhloai"); Log.d("hinhloai", hinhloai); loaiSPArrayList.add(new loaiSP(idLoai, tenloai, hinhloai)); } loaiSPArrayList.add(0, new loaiSP(0, "Trang chủ", "http://pngimages.net/sites/default/files/home-home-png-image-94707.png")); loaiSPArrayList.add(3, new loaiSP(0, "Thông tin", "http://pngimages.net/sites/default/files/info-png-image-30062.png")); loaiSPArrayList.add(4, new loaiSP(0, "Liên hệ", "https://cdn.iconscout.com/public/images/icon/premium/png-512/call-contact-dialer-phone-receiver-telephone-32dba9a3f015b045-512x512.png")); adapter = new loaispadapter(getApplicationContext(), loaiSPArrayList); lv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } } ); requestQueue.add(jsonArrayRequest); } private void catchListLoaiSP() { lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (CheckConnection.haveNetworkConnection(getApplicationContext())) { switch (position) { case 0: Intent trangchu = new Intent(MainActivity.this, MainActivity.class); startActivity(trangchu); break; case 1: Intent dienthoai = new Intent(MainActivity.this, DienThoaiActivity.class); dienthoai.putExtra("idLoai", loaiSPArrayList.get(position).getIdLoai()); startActivity(dienthoai); break; case 2: Intent laptop = new Intent(MainActivity.this, LaptopActivity.class); laptop.putExtra("idLoai", loaiSPArrayList.get(position).getIdLoai()); startActivity(laptop); break; case 3: Intent thongtin = new Intent(MainActivity.this, ThongTinActivity.class); startActivity(thongtin); break; case 4: Intent lienhe = new Intent(MainActivity.this, LienHeActivity.class); startActivity(lienhe); break; } } } }); } private void actionViewFliper() { ArrayList<String> mangQuangCao = new ArrayList<>(); mangQuangCao.add("https://cdn1.tgdd.vn/qcao/05_09_2017_16_30_38_galaxy-note8-800-300.png"); mangQuangCao.add("https://cdn2.tgdd.vn/qcao/05_09_2017_14_23_08_Sony-XZ1-800-300.png"); mangQuangCao.add("https://cdn4.tgdd.vn/qcao/31_08_2017_14_28_35_Big-800-300.png"); mangQuangCao.add("https://cdn4.tgdd.vn/qcao/11_09_2017_16_13_24_Iphone-8-Livestream-800-300.png"); mangQuangCao.add("https://cdn1.tgdd.vn/qcao/31_08_2017_13_47_06_Big-Samsung-800-300.png"); for( int i = 0; i < mangQuangCao.size(); i++) { ImageView img = new ImageView(getApplicationContext()); Picasso.with(getApplicationContext()).load(mangQuangCao.get(i)).into(img); img.setScaleType(ImageView.ScaleType.FIT_XY); viewFlipper.addView(img); } viewFlipper.setFlipInterval(5000); viewFlipper.setAutoStart(true); Animation slide_in = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide); Animation slide_out = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_out); viewFlipper.setInAnimation(slide_in); viewFlipper.setOutAnimation(slide_out); } private void actionBar() { setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.setTitle(getResources().getString(R.string.trangchu)); toolbar.setNavigationIcon(R.drawable.menu); toolbar.setTitleTextColor(0xFFFFFFFF); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.openDrawer(Gravity.START); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.giohang,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.giohang: Intent intent = new Intent(MainActivity.this, GioHangActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private void init() { toolbar = (Toolbar) findViewById(R.id.toolbar); navigationView = (NavigationView) findViewById(R.id.navi); viewFlipper = (ViewFlipper) findViewById(R.id.viewFlip); lv = (ListView) findViewById(R.id.listNavi); recyclerView = (RecyclerView) findViewById(R.id.recycleView); drawerLayout = (DrawerLayout) findViewById(R.id.myDrawer); if(manggiohang != null) { } else { manggiohang = new ArrayList<>(); } } }
UTF-8
Java
11,997
java
MainActivity.java
Java
[]
null
[]
package com.example.dangm.appbanhang.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ViewFlipper; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.dangm.appbanhang.Adapter.SanPhamAdapter; import com.example.dangm.appbanhang.Adapter.loaispadapter; import com.example.dangm.appbanhang.Model.GioHang; import com.example.dangm.appbanhang.Model.SanPham; import com.example.dangm.appbanhang.Model.loaiSP; import com.example.dangm.appbanhang.R; import com.example.dangm.appbanhang.Util.CheckConnection; import com.example.dangm.appbanhang.Util.Server; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private NavigationView navigationView; private ViewFlipper viewFlipper; private DrawerLayout drawerLayout; private RecyclerView recyclerView; private ArrayList<SanPham> arraySanPham = new ArrayList<>(); private ListView lv; private RequestQueue requestQueue; private ArrayList<loaiSP> loaiSPArrayList = new ArrayList<>(); private loaispadapter adapter; boolean isLoading = false; private SanPhamAdapter sanphamadapter; public static ArrayList<GioHang> manggiohang; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); //Check github commit // Seconde commit //qweqweqweqwe requestQueue = Volley.newRequestQueue(getApplicationContext()); if(CheckConnection.haveNetworkConnection(getApplicationContext())) { actionBar(); actionViewFliper(); getLoaiSP(); getSP(); catchListLoaiSP(); } else { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } } private void getSP() { JsonArrayRequest jsonArray = new JsonArrayRequest(Server.sanpham, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { if(response != null) { int id = 0; int idLoai = 0; String tensp = ""; Integer giasp = 0; String hinhsp = ""; String mota = ""; for(int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.optJSONObject(i); id = jsonObject.optInt("idSP"); idLoai = jsonObject.optInt("idloaiSP"); tensp = jsonObject.optString("tenSP"); giasp = jsonObject.optInt("giaSP"); hinhsp = jsonObject.optString("hinhSP"); mota = jsonObject.optString("mota"); arraySanPham.add(new SanPham(id, idLoai, tensp, giasp, mota, hinhsp)); } sanphamadapter = new SanPhamAdapter(getApplicationContext(), arraySanPham); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2)); recyclerView.setAdapter(sanphamadapter); sanphamadapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } }); requestQueue.add(jsonArray); } private void getLoaiSP() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Server.loaisp, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Respone", response.toString()); if (response != null) { int idLoai = 0; String tenloai = ""; String hinhloai = ""; for ( int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.optJSONObject(i); idLoai = jsonObject.optInt("idLoai"); Log.d("IdLoai", String.valueOf(idLoai)); tenloai = jsonObject.optString("tenLoai"); Log.d("Tenloai", tenloai); hinhloai = jsonObject.optString("hinhloai"); Log.d("hinhloai", hinhloai); loaiSPArrayList.add(new loaiSP(idLoai, tenloai, hinhloai)); } loaiSPArrayList.add(0, new loaiSP(0, "Trang chủ", "http://pngimages.net/sites/default/files/home-home-png-image-94707.png")); loaiSPArrayList.add(3, new loaiSP(0, "Thông tin", "http://pngimages.net/sites/default/files/info-png-image-30062.png")); loaiSPArrayList.add(4, new loaiSP(0, "Liên hệ", "https://cdn.iconscout.com/public/images/icon/premium/png-512/call-contact-dialer-phone-receiver-telephone-32dba9a3f015b045-512x512.png")); adapter = new loaispadapter(getApplicationContext(), loaiSPArrayList); lv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { CheckConnection.showToast(getApplicationContext(), "Vui lòng kiểm tra kết nối"); } } ); requestQueue.add(jsonArrayRequest); } private void catchListLoaiSP() { lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (CheckConnection.haveNetworkConnection(getApplicationContext())) { switch (position) { case 0: Intent trangchu = new Intent(MainActivity.this, MainActivity.class); startActivity(trangchu); break; case 1: Intent dienthoai = new Intent(MainActivity.this, DienThoaiActivity.class); dienthoai.putExtra("idLoai", loaiSPArrayList.get(position).getIdLoai()); startActivity(dienthoai); break; case 2: Intent laptop = new Intent(MainActivity.this, LaptopActivity.class); laptop.putExtra("idLoai", loaiSPArrayList.get(position).getIdLoai()); startActivity(laptop); break; case 3: Intent thongtin = new Intent(MainActivity.this, ThongTinActivity.class); startActivity(thongtin); break; case 4: Intent lienhe = new Intent(MainActivity.this, LienHeActivity.class); startActivity(lienhe); break; } } } }); } private void actionViewFliper() { ArrayList<String> mangQuangCao = new ArrayList<>(); mangQuangCao.add("https://cdn1.tgdd.vn/qcao/05_09_2017_16_30_38_galaxy-note8-800-300.png"); mangQuangCao.add("https://cdn2.tgdd.vn/qcao/05_09_2017_14_23_08_Sony-XZ1-800-300.png"); mangQuangCao.add("https://cdn4.tgdd.vn/qcao/31_08_2017_14_28_35_Big-800-300.png"); mangQuangCao.add("https://cdn4.tgdd.vn/qcao/11_09_2017_16_13_24_Iphone-8-Livestream-800-300.png"); mangQuangCao.add("https://cdn1.tgdd.vn/qcao/31_08_2017_13_47_06_Big-Samsung-800-300.png"); for( int i = 0; i < mangQuangCao.size(); i++) { ImageView img = new ImageView(getApplicationContext()); Picasso.with(getApplicationContext()).load(mangQuangCao.get(i)).into(img); img.setScaleType(ImageView.ScaleType.FIT_XY); viewFlipper.addView(img); } viewFlipper.setFlipInterval(5000); viewFlipper.setAutoStart(true); Animation slide_in = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide); Animation slide_out = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_out); viewFlipper.setInAnimation(slide_in); viewFlipper.setOutAnimation(slide_out); } private void actionBar() { setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.setTitle(getResources().getString(R.string.trangchu)); toolbar.setNavigationIcon(R.drawable.menu); toolbar.setTitleTextColor(0xFFFFFFFF); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.openDrawer(Gravity.START); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.giohang,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.giohang: Intent intent = new Intent(MainActivity.this, GioHangActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private void init() { toolbar = (Toolbar) findViewById(R.id.toolbar); navigationView = (NavigationView) findViewById(R.id.navi); viewFlipper = (ViewFlipper) findViewById(R.id.viewFlip); lv = (ListView) findViewById(R.id.listNavi); recyclerView = (RecyclerView) findViewById(R.id.recycleView); drawerLayout = (DrawerLayout) findViewById(R.id.myDrawer); if(manggiohang != null) { } else { manggiohang = new ArrayList<>(); } } }
11,997
0.57594
0.562072
279
41.903225
31.60375
215
false
false
0
0
0
0
0
0
0.756272
false
false
12
f2c49661a8ba64de3dd87ad968c34451d52ca12d
506,806,156,306
97b8c2e71920d8d24ad13ee89a799d991635d610
/client/src/main/java/me/dqn/client/ClientContext.java
99f01d679cb81f47ef0f63d881cdf897427ee277
[]
no_license
SomeoneDeng/net_proxy
https://github.com/SomeoneDeng/net_proxy
e15b4861f23d08c2e10cb9357e9ee4a6ad94fa25
be90ce14350977e1f0b7d5f575ceb94d8e20477c
refs/heads/master
2022-06-01T18:47:38.397000
2022-05-17T03:02:37
2022-05-17T03:02:37
175,464,098
0
0
null
false
2022-05-17T03:02:38
2019-03-13T17:01:03
2022-05-17T03:00:14
2022-05-17T03:02:37
90
0
0
0
Java
false
false
package me.dqn.client; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import me.dqn.util.ClientConfigure; import java.util.concurrent.ConcurrentHashMap; /** * @author dqn * created at 2019/3/23 16:27 */ public class ClientContext { private volatile static ClientContext INSTANCE = null; // 根据sess 找到到真实channel private ConcurrentHashMap<Long, Channel> serverMap; // 根据真实channel找到sess private ConcurrentHashMap<Channel, Long> serverSessMap; // 到服务端 private ChannelFuture clientFuture = null; private Client client; private ClientConfigure clientConfigure; private ClientContext() { serverMap = new ConcurrentHashMap<>(); serverSessMap = new ConcurrentHashMap<>(); clientConfigure = new ClientConfigure("client.yml"); } /** * 启动客户端 */ public void start() throws InterruptedException { client = new Client(clientConfigure.getServerHost(), clientConfigure.getServerPort()); client.startRegister(clientConfigure); } public static ClientContext getINSTANCE() { if (INSTANCE == null) { synchronized (ClientContext.class) { if (INSTANCE == null) { INSTANCE = new ClientContext(); } } } return INSTANCE; } public ConcurrentHashMap<Long, Channel> getServerMap() { return serverMap; } public ChannelFuture getClientFuture() { return clientFuture; } public void setClientFuture(ChannelFuture clientFuture) { this.clientFuture = clientFuture; } public ConcurrentHashMap<Channel, Long> getServerSessMap() { return serverSessMap; } public ClientConfigure getClientConfigure() { return clientConfigure; } public void setClientConfigure(ClientConfigure clientConfigure) { this.clientConfigure = clientConfigure; } }
UTF-8
Java
1,993
java
ClientContext.java
Java
[ { "context": "util.concurrent.ConcurrentHashMap;\n\n/**\n * @author dqn\n * created at 2019/3/23 16:27\n */\npublic class Cl", "end": 199, "score": 0.9995777010917664, "start": 196, "tag": "USERNAME", "value": "dqn" } ]
null
[]
package me.dqn.client; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import me.dqn.util.ClientConfigure; import java.util.concurrent.ConcurrentHashMap; /** * @author dqn * created at 2019/3/23 16:27 */ public class ClientContext { private volatile static ClientContext INSTANCE = null; // 根据sess 找到到真实channel private ConcurrentHashMap<Long, Channel> serverMap; // 根据真实channel找到sess private ConcurrentHashMap<Channel, Long> serverSessMap; // 到服务端 private ChannelFuture clientFuture = null; private Client client; private ClientConfigure clientConfigure; private ClientContext() { serverMap = new ConcurrentHashMap<>(); serverSessMap = new ConcurrentHashMap<>(); clientConfigure = new ClientConfigure("client.yml"); } /** * 启动客户端 */ public void start() throws InterruptedException { client = new Client(clientConfigure.getServerHost(), clientConfigure.getServerPort()); client.startRegister(clientConfigure); } public static ClientContext getINSTANCE() { if (INSTANCE == null) { synchronized (ClientContext.class) { if (INSTANCE == null) { INSTANCE = new ClientContext(); } } } return INSTANCE; } public ConcurrentHashMap<Long, Channel> getServerMap() { return serverMap; } public ChannelFuture getClientFuture() { return clientFuture; } public void setClientFuture(ChannelFuture clientFuture) { this.clientFuture = clientFuture; } public ConcurrentHashMap<Channel, Long> getServerSessMap() { return serverSessMap; } public ClientConfigure getClientConfigure() { return clientConfigure; } public void setClientConfigure(ClientConfigure clientConfigure) { this.clientConfigure = clientConfigure; } }
1,993
0.661878
0.656234
73
25.698629
22.666544
94
false
false
0
0
0
0
0
0
0.39726
false
false
12
b8a9b9a353e620f9b49cb9417495abd270bcb976
17,205,639,008,438
6afd19532b04ea1c0c2c958dae288695693baf27
/aspecio-examples/src/main/java/io/primeval/aspecio/examples/async/internal/SuperSlowServiceImpl.java
4c2cdf8176c74ad938f1846af8ab53e4f340d87a
[ "Apache-2.0" ]
permissive
libaode/aspecio
https://github.com/libaode/aspecio
0096bfbad1f0656ffbab4f5d7a1c6370029a8af4
b57ec8fe2229e23d34c175cf1b1d91e4a46d6925
refs/heads/master
2023-03-17T08:03:45.763000
2018-07-21T20:29:38
2018-07-21T20:29:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.primeval.aspecio.examples.async.internal; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.Uninterruptibles; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import io.primeval.aspecio.aspect.annotations.Weave; import io.primeval.aspecio.examples.aspect.counting.CountingAspect; import io.primeval.aspecio.examples.aspect.metric.MetricAspect; import io.primeval.aspecio.examples.aspect.metric.Timed; import io.primeval.aspecio.examples.async.SuperSlowService; @Component @Weave(required = MetricAspect.AnnotatedOnly.class, optional = CountingAspect.class) public final class SuperSlowServiceImpl implements SuperSlowService { private ExecutorService executor; @Activate public void activate() { this.executor = Executors.newFixedThreadPool(3); } @Deactivate public void deactivate() { executor.shutdown(); } @Override @Timed public Promise<Long> compute() { Deferred<Long> deferred = new Deferred<>(); executor.submit(() -> { Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS); deferred.resolve(42L); }); return deferred.getPromise(); } }
UTF-8
Java
1,509
java
SuperSlowServiceImpl.java
Java
[]
null
[]
package io.primeval.aspecio.examples.async.internal; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.Uninterruptibles; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import io.primeval.aspecio.aspect.annotations.Weave; import io.primeval.aspecio.examples.aspect.counting.CountingAspect; import io.primeval.aspecio.examples.aspect.metric.MetricAspect; import io.primeval.aspecio.examples.aspect.metric.Timed; import io.primeval.aspecio.examples.async.SuperSlowService; @Component @Weave(required = MetricAspect.AnnotatedOnly.class, optional = CountingAspect.class) public final class SuperSlowServiceImpl implements SuperSlowService { private ExecutorService executor; @Activate public void activate() { this.executor = Executors.newFixedThreadPool(3); } @Deactivate public void deactivate() { executor.shutdown(); } @Override @Timed public Promise<Long> compute() { Deferred<Long> deferred = new Deferred<>(); executor.submit(() -> { Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS); deferred.resolve(42L); }); return deferred.getPromise(); } }
1,509
0.747515
0.744864
48
30.4375
24.397665
84
false
false
0
0
0
0
0
0
0.520833
false
false
12
252c71e3d771e1b07f75e301bcc2c7e0f2e78b48
16,733,192,629,426
7dbd3436f970d47d6e937211e4cd5065f8c2afd7
/webTIS/src/com/italia/municipality/lakesebu/controller/PenaltyCalculation.java
fd0464edc71cf063837a3e871ce70a679619e902
[]
no_license
marxmind/webtis
https://github.com/marxmind/webtis
41f12d4ba76d9117c6c27aeda3968397f06a8e8e
bb6daeede1cf44508896bb1bb5b2217776206826
refs/heads/master
2023-06-25T17:02:20.542000
2023-06-14T15:23:38
2023-06-14T15:23:38
233,990,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.italia.municipality.lakesebu.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.italia.municipality.lakesebu.database.TaxDatabaseConnect; import com.italia.municipality.lakesebu.database.WebTISDatabaseConnect; import com.italia.municipality.lakesebu.enm.PenalyMonth; import com.italia.municipality.lakesebu.utils.DateUtils; public class PenaltyCalculation { private long id; private int year; private double january; private double february; private double march; private double april; private double may; private double june; private double july; private double august; private double september; private double october; private double november; private double december; public PenaltyCalculation(){} public PenaltyCalculation( long id, int year, double january, double february, double march, double april, double may, double june, double july, double august, double september, double october, double november, double december ){ this.id = id; this.year = year; this.january = january; this.february = february; this.march = march; this.april = april; this.may = may; this.june = june; this.july = july; this.august = august; this.september = september; this.october = october; this.november = november; this.december = december; } public static List<PenaltyCalculation> retrieve(String sql, String[] params){ List<PenaltyCalculation> calcs = Collections.synchronizedList(new ArrayList<>()); Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try{ conn = TaxDatabaseConnect.getConnection(); ps = conn.prepareStatement(sql); if(params!=null && params.length>0){ for(int i=0; i<params.length; i++){ ps.setString(i+1, params[i]); } } System.out.println("SQL " + ps.toString()); rs = ps.executeQuery(); while(rs.next()){ PenaltyCalculation cal = new PenaltyCalculation(); cal.setId(rs.getLong("calid")); cal.setYear(rs.getInt("year")); cal.setJanuary(rs.getDouble("jana")); cal.setFebruary(rs.getDouble("feba")); cal.setMarch(rs.getDouble("mara")); cal.setApril(rs.getDouble("apra")); cal.setMay(rs.getDouble("maya")); cal.setJune(rs.getDouble("juna")); cal.setJuly(rs.getDouble("jula")); cal.setAugust(rs.getDouble("auga")); cal.setSeptember(rs.getDouble("sepa")); cal.setNovember(rs.getDouble("nova")); cal.setDecember(rs.getDouble("deca")); } TaxDatabaseConnect.close(conn); rs.close(); ps.close(); }catch(SQLException e){} return calcs; } public static double monthPenalty(int year, PenalyMonth month){ String sql = "SELECT " + month.getName() + " FROM landtaxpenaltiescal WHERE year=?"; Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try{ conn = TaxDatabaseConnect.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, year); System.out.println("SQL " + ps.toString()); rs = ps.executeQuery(); while(rs.next()){ return rs.getDouble(month.getName()); } TaxDatabaseConnect.close(conn); rs.close(); ps.close(); }catch(SQLException e){} return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public double getJanuary() { return january; } public void setJanuary(double january) { this.january = january; } public double getFebruary() { return february; } public void setFebruary(double february) { this.february = february; } public double getMarch() { return march; } public void setMarch(double march) { this.march = march; } public double getApril() { return april; } public void setApril(double april) { this.april = april; } public double getMay() { return may; } public void setMay(double may) { this.may = may; } public double getJune() { return june; } public void setJune(double june) { this.june = june; } public double getJuly() { return july; } public void setJuly(double july) { this.july = july; } public double getAugust() { return august; } public void setAugust(double august) { this.august = august; } public double getSeptember() { return september; } public void setSeptember(double september) { this.september = september; } public double getOctober() { return october; } public void setOctober(double october) { this.october = october; } public double getNovember() { return november; } public void setNovember(double november) { this.november = november; } public double getDecember() { return december; } public void setDecember(double december) { this.december = december; } public static void main(String[] args) { int month = DateUtils.getCurrentMonth(); System.out.println(PenaltyCalculation.monthPenalty(2015,PenalyMonth.month(month))); } }
UTF-8
Java
5,391
java
PenaltyCalculation.java
Java
[]
null
[]
package com.italia.municipality.lakesebu.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.italia.municipality.lakesebu.database.TaxDatabaseConnect; import com.italia.municipality.lakesebu.database.WebTISDatabaseConnect; import com.italia.municipality.lakesebu.enm.PenalyMonth; import com.italia.municipality.lakesebu.utils.DateUtils; public class PenaltyCalculation { private long id; private int year; private double january; private double february; private double march; private double april; private double may; private double june; private double july; private double august; private double september; private double october; private double november; private double december; public PenaltyCalculation(){} public PenaltyCalculation( long id, int year, double january, double february, double march, double april, double may, double june, double july, double august, double september, double october, double november, double december ){ this.id = id; this.year = year; this.january = january; this.february = february; this.march = march; this.april = april; this.may = may; this.june = june; this.july = july; this.august = august; this.september = september; this.october = october; this.november = november; this.december = december; } public static List<PenaltyCalculation> retrieve(String sql, String[] params){ List<PenaltyCalculation> calcs = Collections.synchronizedList(new ArrayList<>()); Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try{ conn = TaxDatabaseConnect.getConnection(); ps = conn.prepareStatement(sql); if(params!=null && params.length>0){ for(int i=0; i<params.length; i++){ ps.setString(i+1, params[i]); } } System.out.println("SQL " + ps.toString()); rs = ps.executeQuery(); while(rs.next()){ PenaltyCalculation cal = new PenaltyCalculation(); cal.setId(rs.getLong("calid")); cal.setYear(rs.getInt("year")); cal.setJanuary(rs.getDouble("jana")); cal.setFebruary(rs.getDouble("feba")); cal.setMarch(rs.getDouble("mara")); cal.setApril(rs.getDouble("apra")); cal.setMay(rs.getDouble("maya")); cal.setJune(rs.getDouble("juna")); cal.setJuly(rs.getDouble("jula")); cal.setAugust(rs.getDouble("auga")); cal.setSeptember(rs.getDouble("sepa")); cal.setNovember(rs.getDouble("nova")); cal.setDecember(rs.getDouble("deca")); } TaxDatabaseConnect.close(conn); rs.close(); ps.close(); }catch(SQLException e){} return calcs; } public static double monthPenalty(int year, PenalyMonth month){ String sql = "SELECT " + month.getName() + " FROM landtaxpenaltiescal WHERE year=?"; Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try{ conn = TaxDatabaseConnect.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, year); System.out.println("SQL " + ps.toString()); rs = ps.executeQuery(); while(rs.next()){ return rs.getDouble(month.getName()); } TaxDatabaseConnect.close(conn); rs.close(); ps.close(); }catch(SQLException e){} return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public double getJanuary() { return january; } public void setJanuary(double january) { this.january = january; } public double getFebruary() { return february; } public void setFebruary(double february) { this.february = february; } public double getMarch() { return march; } public void setMarch(double march) { this.march = march; } public double getApril() { return april; } public void setApril(double april) { this.april = april; } public double getMay() { return may; } public void setMay(double may) { this.may = may; } public double getJune() { return june; } public void setJune(double june) { this.june = june; } public double getJuly() { return july; } public void setJuly(double july) { this.july = july; } public double getAugust() { return august; } public void setAugust(double august) { this.august = august; } public double getSeptember() { return september; } public void setSeptember(double september) { this.september = september; } public double getOctober() { return october; } public void setOctober(double october) { this.october = october; } public double getNovember() { return november; } public void setNovember(double november) { this.november = november; } public double getDecember() { return december; } public void setDecember(double december) { this.december = december; } public static void main(String[] args) { int month = DateUtils.getCurrentMonth(); System.out.println(PenaltyCalculation.monthPenalty(2015,PenalyMonth.month(month))); } }
5,391
0.664626
0.662957
236
20.84322
17.063341
86
false
false
0
0
0
0
0
0
2.186441
false
false
12
c60d99047ce0a3ae2edced2c15cbeb8c00409843
18,846,316,555,702
c01fef058c19f7d14cdf0d62edf78f1317119647
/main/java/com/duwei/dao/BaseDAO.java
c1f2ea5b8d533075a17ea115b652592a472a6e47
[]
no_license
duweiduwais/jpacrudmvc
https://github.com/duweiduwais/jpacrudmvc
2a9d1156540ecdb8da0db0dc22f7bd152a0de454
06b97a92a9dcfa07a21df2b00dc8d1d1496ef8ac
refs/heads/master
2016-08-03T15:38:34.155000
2015-09-11T22:49:32
2015-09-11T22:49:32
42,335,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.duwei.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import com.duwei.entity.Teacher; public interface BaseDAO<T> extends PagingAndSortingRepository<T, String>,JpaSpecificationExecutor<T>{ public List<T> findByIds(List<String> ids); }
UTF-8
Java
378
java
BaseDAO.java
Java
[]
null
[]
package com.duwei.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import com.duwei.entity.Teacher; public interface BaseDAO<T> extends PagingAndSortingRepository<T, String>,JpaSpecificationExecutor<T>{ public List<T> findByIds(List<String> ids); }
378
0.828042
0.828042
13
28.076923
33.013893
102
false
false
0
0
0
0
0
0
0.692308
false
false
12
d1c28196937cad997012bf32324a8258bb7e9e5d
21,199,958,624,415
c64987da20dcddca6e3571694c74b47cf2c9f1a0
/APP4/src/main/java/com/ninesky/classtao/wechat/service/VoteService.java
51349420eaf7f80963596656bf7bcf8f3e7dd856
[]
no_license
chentian610/999999
https://github.com/chentian610/999999
ce7dae53932220a11158e53829b42ac2d4787b31
cd52c5b0252cbe5a46da30e4ec91d5789da1e49e
refs/heads/master
2021-01-22T08:13:56.662000
2017-09-05T09:29:51
2017-09-05T09:29:51
102,323,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ninesky.classtao.wechat.service; import java.util.List; import com.ninesky.classtao.wechat.vo.VoteOptionVO; import com.ninesky.classtao.wechat.vo.VoteQuestionVO; import com.ninesky.classtao.wechat.vo.VoteVO; public interface VoteService { //投票主题 public void addVote(VoteVO vo); public void updateVote(VoteVO vo); public List<VoteVO> getVoteByAccount(Integer accountId); public List<VoteVO> getPublishVoteByAccount(Integer accountId); public VoteVO getVoteById(Integer voteId); public void deleteVoteById(Integer voteId); //投票问题 public void addQuestion(VoteQuestionVO vo); public void updateQuestion(VoteQuestionVO vo); public List<VoteQuestionVO> getQuestionByVote(Integer voteId); public VoteQuestionVO getQuestionById(Integer questionId); public void deleteQuestionById(Integer questionId); //投票问题选项 public void addOption(VoteOptionVO vo); public void updateOption(VoteOptionVO vo); public List<VoteOptionVO> getOptionByQuestion(Integer questionId); public VoteOptionVO getOptionById(Integer optionId); public void deleteOptionById(Integer optionId); }
UTF-8
Java
1,149
java
VoteService.java
Java
[]
null
[]
package com.ninesky.classtao.wechat.service; import java.util.List; import com.ninesky.classtao.wechat.vo.VoteOptionVO; import com.ninesky.classtao.wechat.vo.VoteQuestionVO; import com.ninesky.classtao.wechat.vo.VoteVO; public interface VoteService { //投票主题 public void addVote(VoteVO vo); public void updateVote(VoteVO vo); public List<VoteVO> getVoteByAccount(Integer accountId); public List<VoteVO> getPublishVoteByAccount(Integer accountId); public VoteVO getVoteById(Integer voteId); public void deleteVoteById(Integer voteId); //投票问题 public void addQuestion(VoteQuestionVO vo); public void updateQuestion(VoteQuestionVO vo); public List<VoteQuestionVO> getQuestionByVote(Integer voteId); public VoteQuestionVO getQuestionById(Integer questionId); public void deleteQuestionById(Integer questionId); //投票问题选项 public void addOption(VoteOptionVO vo); public void updateOption(VoteOptionVO vo); public List<VoteOptionVO> getOptionByQuestion(Integer questionId); public VoteOptionVO getOptionById(Integer optionId); public void deleteOptionById(Integer optionId); }
1,149
0.798394
0.798394
45
23.911112
24.014647
67
false
false
0
0
0
0
0
0
1.244444
false
false
12
8d2f6859a347fc35d978ac756255e7d724c26dc6
2,576,980,388,078
f5a573bd37e1641b668aca658675f99bf398f464
/src/main/java/com/tsoft/base/database/jda/dialect/Oracle9Dialect.java
1b9fd5efd613ab433519a6a102be9821a6b82e8e
[ "MIT" ]
permissive
frankan0/tsoft-webbase
https://github.com/frankan0/tsoft-webbase
044d2ae471a7448bdf97f301a9b8fd37e293eb24
68d3cd79d173829b5dff2004468860208ee094e6
refs/heads/master
2016-12-19T17:22:51.148000
2016-10-27T10:51:14
2016-10-27T10:51:14
62,784,436
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * WebBase: utilities and a spring & struts wrappered framework for MVC development, by networkbench. */ package com.tsoft.base.database.jda.dialect; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Calendar; import java.util.Date; import oracle.sql.DATE; /** * for Oracle 9i or above, has a bug for TIMESTAMP type, which cause timestamp column cannot be indexed correctly for searching. * Oracle jdbc type oracle.sql.DATE MUST be used instead of JDBC standard type java.sql.Timestamp. * @author BurningICE * */ public class Oracle9Dialect extends OracleDialect { /* (non-Javadoc) * @see com.networkbench.base.database.jda.dialect.Dialect#setParametersForPS(java.sql.PreparedStatement, int, java.lang.Object, int) */ public void setParametersForPS(PreparedStatement pstmt, int parameterIndex, Object param, int paramType) throws SQLException { if(paramType == Types.TIMESTAMP || paramType == oracle.jdbc.OracleTypes.DATE) { //use oracle type date if(param == null) { pstmt.setNull(parameterIndex, oracle.jdbc.OracleTypes.DATE); } else { if (param instanceof java.sql.Timestamp) { pstmt.setObject(parameterIndex, new DATE((Timestamp) param), oracle.jdbc.OracleTypes.DATE); } else if (param instanceof java.util.Date){ pstmt.setObject(parameterIndex, new DATE(new Timestamp(((Date) param).getTime())), oracle.jdbc.OracleTypes.DATE); } else if (param instanceof java.util.Calendar) { java.util.Calendar cal = (java.util.Calendar) param; pstmt.setTimestamp(parameterIndex, new Timestamp(cal.getTimeInMillis()), cal); } else { pstmt.setObject(parameterIndex, param, oracle.jdbc.OracleTypes.DATE); } } } else { super.setParametersForPS(pstmt, parameterIndex, param, paramType); } } /* (non-Javadoc) * @see com.networkbench.base.database.jda.dialect.Dialect#setParametersForPS(java.sql.PreparedStatement, int, java.lang.Object) */ public void setParametersForPS(PreparedStatement pstmt, int parameterIndex, Object param) throws SQLException { if(param == null) { super.setParametersForPS(pstmt, parameterIndex, param); } else if(param instanceof Date){ if(param instanceof java.sql.Date){ pstmt.setDate(parameterIndex, (java.sql.Date)param); }else if(param instanceof Time){ pstmt.setTime(parameterIndex, (Time)param); }else if(param instanceof Timestamp){ pstmt.setObject(parameterIndex, new DATE((Timestamp)param), oracle.jdbc.OracleTypes.DATE); }else{ pstmt.setObject(parameterIndex, new DATE(new Timestamp(((Date) param).getTime())), oracle.jdbc.OracleTypes.DATE); } } else if(param instanceof Calendar){ java.util.Calendar cal = (java.util.Calendar) param; pstmt.setTimestamp(parameterIndex, new Timestamp(cal.getTimeInMillis()), cal); } else { super.setParametersForPS(pstmt, parameterIndex, param); } } }
UTF-8
Java
3,027
java
Oracle9Dialect.java
Java
[ { "context": " JDBC standard type java.sql.Timestamp.\n * @author BurningICE\n *\n */\npublic class Oracle9Dialect extends Oracle", "end": 622, "score": 0.9994505643844604, "start": 612, "tag": "USERNAME", "value": "BurningICE" } ]
null
[]
/** * WebBase: utilities and a spring & struts wrappered framework for MVC development, by networkbench. */ package com.tsoft.base.database.jda.dialect; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Calendar; import java.util.Date; import oracle.sql.DATE; /** * for Oracle 9i or above, has a bug for TIMESTAMP type, which cause timestamp column cannot be indexed correctly for searching. * Oracle jdbc type oracle.sql.DATE MUST be used instead of JDBC standard type java.sql.Timestamp. * @author BurningICE * */ public class Oracle9Dialect extends OracleDialect { /* (non-Javadoc) * @see com.networkbench.base.database.jda.dialect.Dialect#setParametersForPS(java.sql.PreparedStatement, int, java.lang.Object, int) */ public void setParametersForPS(PreparedStatement pstmt, int parameterIndex, Object param, int paramType) throws SQLException { if(paramType == Types.TIMESTAMP || paramType == oracle.jdbc.OracleTypes.DATE) { //use oracle type date if(param == null) { pstmt.setNull(parameterIndex, oracle.jdbc.OracleTypes.DATE); } else { if (param instanceof java.sql.Timestamp) { pstmt.setObject(parameterIndex, new DATE((Timestamp) param), oracle.jdbc.OracleTypes.DATE); } else if (param instanceof java.util.Date){ pstmt.setObject(parameterIndex, new DATE(new Timestamp(((Date) param).getTime())), oracle.jdbc.OracleTypes.DATE); } else if (param instanceof java.util.Calendar) { java.util.Calendar cal = (java.util.Calendar) param; pstmt.setTimestamp(parameterIndex, new Timestamp(cal.getTimeInMillis()), cal); } else { pstmt.setObject(parameterIndex, param, oracle.jdbc.OracleTypes.DATE); } } } else { super.setParametersForPS(pstmt, parameterIndex, param, paramType); } } /* (non-Javadoc) * @see com.networkbench.base.database.jda.dialect.Dialect#setParametersForPS(java.sql.PreparedStatement, int, java.lang.Object) */ public void setParametersForPS(PreparedStatement pstmt, int parameterIndex, Object param) throws SQLException { if(param == null) { super.setParametersForPS(pstmt, parameterIndex, param); } else if(param instanceof Date){ if(param instanceof java.sql.Date){ pstmt.setDate(parameterIndex, (java.sql.Date)param); }else if(param instanceof Time){ pstmt.setTime(parameterIndex, (Time)param); }else if(param instanceof Timestamp){ pstmt.setObject(parameterIndex, new DATE((Timestamp)param), oracle.jdbc.OracleTypes.DATE); }else{ pstmt.setObject(parameterIndex, new DATE(new Timestamp(((Date) param).getTime())), oracle.jdbc.OracleTypes.DATE); } } else if(param instanceof Calendar){ java.util.Calendar cal = (java.util.Calendar) param; pstmt.setTimestamp(parameterIndex, new Timestamp(cal.getTimeInMillis()), cal); } else { super.setParametersForPS(pstmt, parameterIndex, param); } } }
3,027
0.72514
0.72448
74
39.905407
38.942497
134
false
false
0
0
0
0
0
0
2.567568
false
false
12
709f107c4679755d6875203309b6e3a1649e5f01
20,504,173,938,011
919a14743b8c1215595c7953ec9d51e222820ed6
/dec07/src/main/java/com/joshlessard/adventofcode2015/command/TunnelCommandParser.java
62f1c8d0bbca1ce07b1bc7beb5855856ba20080e
[]
no_license
JoshLessard/AdventOfCode2015
https://github.com/JoshLessard/AdventOfCode2015
994217d9e9825ebb79bace9b2f7c26f03ee2fd7f
b25cafda4796c29e8995a0fb18b18bf100a456aa
refs/heads/master
2021-01-10T16:37:46.477000
2015-12-14T16:09:29
2015-12-14T16:09:29
47,363,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.joshlessard.adventofcode2015.command; import java.util.List; import java.util.regex.Matcher; import org.javatuples.Pair; import com.google.common.collect.ImmutableList; import com.joshlessard.adventofcode2015.circuit.CircuitComponent; import com.joshlessard.adventofcode2015.circuit.component.ValueComponent; import com.joshlessard.adventofcode2015.circuit.component.Wire; public class TunnelCommandParser extends RegexCommandParser { private static final String PATTERN = "([a-z]+|\\d+) -> ([a-z]+)"; private int nextSuffix = 1; public TunnelCommandParser() { super( PATTERN ); } @Override protected List<Pair<CircuitComponent, CircuitComponent>> generateEdges( Matcher matcher ) { String wireName = matcher.group( 2 ); return ImmutableList.of( new Pair<>( createSourceComponent( matcher ), new Wire( wireName ) ) ); } private CircuitComponent createSourceComponent( Matcher matcher ) { String outputSignal = matcher.group( 1 ); return Character.isDigit( outputSignal.charAt( 0 ) ) ? new ValueComponent( "~~~value" + nextSuffix++, Integer.parseInt( outputSignal ) ) : new Wire( outputSignal ); } }
UTF-8
Java
1,153
java
TunnelCommandParser.java
Java
[]
null
[]
package com.joshlessard.adventofcode2015.command; import java.util.List; import java.util.regex.Matcher; import org.javatuples.Pair; import com.google.common.collect.ImmutableList; import com.joshlessard.adventofcode2015.circuit.CircuitComponent; import com.joshlessard.adventofcode2015.circuit.component.ValueComponent; import com.joshlessard.adventofcode2015.circuit.component.Wire; public class TunnelCommandParser extends RegexCommandParser { private static final String PATTERN = "([a-z]+|\\d+) -> ([a-z]+)"; private int nextSuffix = 1; public TunnelCommandParser() { super( PATTERN ); } @Override protected List<Pair<CircuitComponent, CircuitComponent>> generateEdges( Matcher matcher ) { String wireName = matcher.group( 2 ); return ImmutableList.of( new Pair<>( createSourceComponent( matcher ), new Wire( wireName ) ) ); } private CircuitComponent createSourceComponent( Matcher matcher ) { String outputSignal = matcher.group( 1 ); return Character.isDigit( outputSignal.charAt( 0 ) ) ? new ValueComponent( "~~~value" + nextSuffix++, Integer.parseInt( outputSignal ) ) : new Wire( outputSignal ); } }
1,153
0.756288
0.738942
37
30.162163
28.702118
92
false
false
0
0
0
0
0
0
1.405405
false
false
12
841ac7abc57163fa3308f458cbd69f0bc3a8d616
29,171,417,932,785
3720048dd4ed1cdb780989f4b7cf98cf7a510ba2
/lab4/src/msifeed/ppvis/lab4/dumbParser/DumbParser.java
0ce0333b4039312d3fcefd41c8b188c1dae54e2a
[]
no_license
msifd/ppvis
https://github.com/msifd/ppvis
c8aad08b1dbb1745ce60f3a3ab3d61bd1a6e29b4
0951220ab3b681f3e3ba81a75539a73d7247274e
refs/heads/master
2016-03-27T11:14:40.771000
2015-06-30T05:47:38
2015-06-30T05:47:38
23,732,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package msifeed.ppvis.lab4.dumbParser; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; public class DumbParser { int index; TokenType token; String lexeme; List<Token> tokenList; ArrayDeque<AST.Node> nodeStack; public AST parse(String input) { AST ast = new AST(); this.index = 0; this.token = null; this.lexeme = ""; this.tokenList = new ArrayList<>(); // Lexer while (index < input.length()) { char c = input.charAt(index); TokenType nextToken = defineToken(c); if (nextToken == null || nextToken.terminal) { pushToken(); token = nextToken; lexeme = String.valueOf(c); pushToken(); } else if (nextToken != token) { pushToken(); token = nextToken; lexeme = String.valueOf(c); } else { lexeme += c; } index++; } pushToken(); /* // Reverse lexer test String spacelessInput = input.replaceAll("\\s", ""); String lexerResult = ""; for (Token tk : tokenList) lexerResult += tk.lexeme; if (!spacelessInput.equals(lexerResult)) throw new AssertionError("Lexer test fail.\n" + spacelessInput + "\n" + lexerResult); */ // Syntax nodeStack = new ArrayDeque<>(); nodeStack.add(ast.rootNode); index = 0; while (index < tokenList.size()) { if (sequence(TokenType.OPERATION, TokenType.NUMBER) && lexemeIs(0, "-")) { Token minusToken = tokenList.get(index++); Token numberToken = tokenList.get(index); AST.Node node = new AST.Node(numberToken.token); node.value = -1 * Integer.parseInt(numberToken.lexeme); nodeStack.peek().subnodes.add(node); } else if (sequence(TokenType.NUMBER, TokenType.OPERATION, TokenType.NUMBER)) { Token leftToken = tokenList.get(index++); Token operToken = tokenList.get(index++); Token rightToken = tokenList.get(index); AST.Node operator = new AST.Node(operToken.token); operator.value = operToken.lexeme.charAt(0); operator.subnodes.add(parseToken(leftToken)); operator.subnodes.add(parseToken(rightToken)); nodeStack.peek().subnodes.add(operator); } index++; } System.out.println("Input: '" + input + "'"); System.out.println("Tokens: " + tokenList); System.out.println("Node stack: " + nodeStack); System.out.println("AST: " + ast); return ast; } private AST.Node parseToken(Token token) { AST.Node node = new AST.Node(token.token); switch (token.token) { case OPERATION: break; case NUMBER: node.value = Integer.parseInt(token.lexeme); break; } return node; } private boolean lexemeIs(int shift, String lexeme) { return tokenList.get(index + shift).lexeme.equals(lexeme); } private boolean sequence(TokenType... tokens) { for (int ind = 0; ind < tokens.length; ind++) { if (tokenList.get(index + ind).token != tokens[ind]) return false; } return true; } private void pushOnStack(AST.Node node) { nodeStack.peek().subnodes.add(node); nodeStack.push(node); } private TokenType defineToken(char c) { if (anyOf(c, " \t\f\n\r")) return null; if (anyOf(c, "0123456789")) return TokenType.NUMBER; if (c == '(') return TokenType.LBRACE; if (c == ')') return TokenType.RBRACE; if (c == ',') return TokenType.COMMA; if (c == '!') return TokenType.FACTORIAL; if (anyOf(c, "+-*/%")) return TokenType.OPERATION; if (partOfLexeme(c, "log")) return TokenType.LOGARITHM; if (partOfLexeme(c, "sqrt")) return TokenType.SQUAREROOT; throw new RuntimeException("Unexpected character! '" + c + "' at " + index); } private void pushToken() { if (token == null) return; tokenList.add(new Token(token, lexeme)); token = null; lexeme = ""; } private boolean partOfLexeme(char c, String full) { String a = full.substring(0, Math.min(lexeme.length() + 1, full.length())); String b = lexeme + c; return a.equals(b); } private boolean anyOf(Character c, String cs) { for (int i = 0; i < cs.length(); i++) if (cs.charAt(i) == c) return true; return false; } class Token { TokenType token; String lexeme; Token(TokenType token, String lexeme) { this.token = token; this.lexeme = lexeme; } @Override public String toString() { return String.format("%s:%s", token.name(), lexeme); } } }
UTF-8
Java
5,183
java
DumbParser.java
Java
[]
null
[]
package msifeed.ppvis.lab4.dumbParser; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; public class DumbParser { int index; TokenType token; String lexeme; List<Token> tokenList; ArrayDeque<AST.Node> nodeStack; public AST parse(String input) { AST ast = new AST(); this.index = 0; this.token = null; this.lexeme = ""; this.tokenList = new ArrayList<>(); // Lexer while (index < input.length()) { char c = input.charAt(index); TokenType nextToken = defineToken(c); if (nextToken == null || nextToken.terminal) { pushToken(); token = nextToken; lexeme = String.valueOf(c); pushToken(); } else if (nextToken != token) { pushToken(); token = nextToken; lexeme = String.valueOf(c); } else { lexeme += c; } index++; } pushToken(); /* // Reverse lexer test String spacelessInput = input.replaceAll("\\s", ""); String lexerResult = ""; for (Token tk : tokenList) lexerResult += tk.lexeme; if (!spacelessInput.equals(lexerResult)) throw new AssertionError("Lexer test fail.\n" + spacelessInput + "\n" + lexerResult); */ // Syntax nodeStack = new ArrayDeque<>(); nodeStack.add(ast.rootNode); index = 0; while (index < tokenList.size()) { if (sequence(TokenType.OPERATION, TokenType.NUMBER) && lexemeIs(0, "-")) { Token minusToken = tokenList.get(index++); Token numberToken = tokenList.get(index); AST.Node node = new AST.Node(numberToken.token); node.value = -1 * Integer.parseInt(numberToken.lexeme); nodeStack.peek().subnodes.add(node); } else if (sequence(TokenType.NUMBER, TokenType.OPERATION, TokenType.NUMBER)) { Token leftToken = tokenList.get(index++); Token operToken = tokenList.get(index++); Token rightToken = tokenList.get(index); AST.Node operator = new AST.Node(operToken.token); operator.value = operToken.lexeme.charAt(0); operator.subnodes.add(parseToken(leftToken)); operator.subnodes.add(parseToken(rightToken)); nodeStack.peek().subnodes.add(operator); } index++; } System.out.println("Input: '" + input + "'"); System.out.println("Tokens: " + tokenList); System.out.println("Node stack: " + nodeStack); System.out.println("AST: " + ast); return ast; } private AST.Node parseToken(Token token) { AST.Node node = new AST.Node(token.token); switch (token.token) { case OPERATION: break; case NUMBER: node.value = Integer.parseInt(token.lexeme); break; } return node; } private boolean lexemeIs(int shift, String lexeme) { return tokenList.get(index + shift).lexeme.equals(lexeme); } private boolean sequence(TokenType... tokens) { for (int ind = 0; ind < tokens.length; ind++) { if (tokenList.get(index + ind).token != tokens[ind]) return false; } return true; } private void pushOnStack(AST.Node node) { nodeStack.peek().subnodes.add(node); nodeStack.push(node); } private TokenType defineToken(char c) { if (anyOf(c, " \t\f\n\r")) return null; if (anyOf(c, "0123456789")) return TokenType.NUMBER; if (c == '(') return TokenType.LBRACE; if (c == ')') return TokenType.RBRACE; if (c == ',') return TokenType.COMMA; if (c == '!') return TokenType.FACTORIAL; if (anyOf(c, "+-*/%")) return TokenType.OPERATION; if (partOfLexeme(c, "log")) return TokenType.LOGARITHM; if (partOfLexeme(c, "sqrt")) return TokenType.SQUAREROOT; throw new RuntimeException("Unexpected character! '" + c + "' at " + index); } private void pushToken() { if (token == null) return; tokenList.add(new Token(token, lexeme)); token = null; lexeme = ""; } private boolean partOfLexeme(char c, String full) { String a = full.substring(0, Math.min(lexeme.length() + 1, full.length())); String b = lexeme + c; return a.equals(b); } private boolean anyOf(Character c, String cs) { for (int i = 0; i < cs.length(); i++) if (cs.charAt(i) == c) return true; return false; } class Token { TokenType token; String lexeme; Token(TokenType token, String lexeme) { this.token = token; this.lexeme = lexeme; } @Override public String toString() { return String.format("%s:%s", token.name(), lexeme); } } }
5,183
0.534632
0.530774
163
30.79141
22.568901
97
false
false
0
0
0
0
0
0
0.687117
false
false
12
b199bc6345a230cad02d96d067d76228e6283477
29,171,417,933,589
5650ba99a4f43ba4fdd4d397a754f093eca09d9a
/src/main/java/com/team/tracking_management_system_backend/vo/MessageVO.java
9e6986a0bebcbbcdff0b08e2d18c54f4e2f75b49
[]
no_license
ProjectManagementTrackingTeam/tracking_management_system_back-end
https://github.com/ProjectManagementTrackingTeam/tracking_management_system_back-end
a9cd54f9245e4b0e0aa7de3d7fbe942acedbc8f8
7cbfe558885f3e85e2679eae16dbb96609a59fd7
refs/heads/master
2022-11-17T20:03:37.517000
2020-07-17T04:12:40
2020-07-17T04:12:40
276,599,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.team.tracking_management_system_backend.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class MessageVO { MessageVO(String message, State state){ this.message = message; } public final static String STATE = "state"; private String message; public enum State{SUCCESS,FAIL}; }
UTF-8
Java
414
java
MessageVO.java
Java
[]
null
[]
package com.team.tracking_management_system_backend.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class MessageVO { MessageVO(String message, State state){ this.message = message; } public final static String STATE = "state"; private String message; public enum State{SUCCESS,FAIL}; }
414
0.748792
0.748792
18
22
17.058722
55
false
false
0
0
0
0
0
0
0.555556
false
false
12
691d1f202e0f4b0f283e71ffc9eeed2fe4a4d910
27,608,049,827,461
1fe75e41f5f48b59a26f0af8d6e6dc77f86d7c68
/app/src/main/java/com/nikmc/kc/api/Request.java
36896782a91e76975ccca5c07f31b3ba277da734
[]
no_license
NIKMC/KC
https://github.com/NIKMC/KC
f3aa48e6dfa3cc831c78d6bc8af5962ff05db8fb
87e3c9e34ca6b4c9b940bc2483bcc9c49060f0a6
refs/heads/master
2021-01-20T13:36:56.258000
2017-02-21T15:32:23
2017-02-21T15:32:23
82,694,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nikmc.kc.api; import com.nikmc.kc.EnumType; import java.util.ArrayList; /** * Created by NIKMC-I on 24.12.2015. */ public class Request { public EnumType enumType; public ArrayList arrayList; }
UTF-8
Java
219
java
Request.java
Java
[ { "context": "e;\n\nimport java.util.ArrayList;\n\n/**\n * Created by NIKMC-I on 24.12.2015.\n */\npublic class Request {\n pub", "end": 112, "score": 0.9992778897285461, "start": 105, "tag": "USERNAME", "value": "NIKMC-I" } ]
null
[]
package com.nikmc.kc.api; import com.nikmc.kc.EnumType; import java.util.ArrayList; /** * Created by NIKMC-I on 24.12.2015. */ public class Request { public EnumType enumType; public ArrayList arrayList; }
219
0.712329
0.675799
13
15.846154
13.955127
36
false
false
0
0
0
0
0
0
0.384615
false
false
12
7687ba72c4c057e2a7251754120202afbcd6e9a5
18,743,237,329,730
b7e4b3246891edac591b4dcf56b1ba13172ff811
/example-with-publish/publish-webapp-example/src/main/java/com/snapchat/example/WebappExampleServlet.java
1ab7e242e51ae2bbcae96fb688a8eca6f6b2cbcc
[]
no_license
rugby110/gradle
https://github.com/rugby110/gradle
92f11d20c965c02174f5f92b675a01f5c59149c7
5a6beb2509c39a4328f2a93e5dd26e274000e4c6
refs/heads/master
2021-01-18T03:59:34.817000
2016-07-22T22:32:52
2016-07-22T22:32:52
64,073,795
1
0
null
true
2016-07-24T16:06:08
2016-07-24T16:06:08
2016-06-03T01:10:18
2016-07-22T22:32:56
152,413
0
0
0
null
null
null
package com.snapchat.example; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebappExampleServlet extends HttpServlet { @Override public void init() { } @Override public void destroy() { } @Override public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { } @Override public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { } }
UTF-8
Java
697
java
WebappExampleServlet.java
Java
[]
null
[]
package com.snapchat.example; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebappExampleServlet extends HttpServlet { @Override public void init() { } @Override public void destroy() { } @Override public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { } @Override public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { } }
697
0.737446
0.737446
33
20.121212
21.694515
72
false
false
0
0
0
0
0
0
0.333333
false
false
12
130b2f529c58923d30d9c0dfb9f194e7f439007b
28,913,719,884,523
5363d50d5207dc519741ad546b253fa65f79e350
/src/controller/searchKH.java
9f7286d806a680ada8c85023e9e964a4946a8526
[]
no_license
phamthiminhthu/projectJava14
https://github.com/phamthiminhthu/projectJava14
830a53a2ed59dabe43e2a88df745c566afdd4787
c9a4850342eb6da8352174802bcfc42b776b6c65
refs/heads/master
2023-03-29T18:38:20.567000
2021-04-08T13:03:06
2021-04-08T13:03:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import java.util.ArrayList; import java.util.Scanner; import model.customer; import view.listKH; /** * * @author Minh Thu */ public class searchKH { public int search(ArrayList<customer> list, String strInfor) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getEmail().contains(strInfor) || list.get(i).getAddress().contains(strInfor) || list.get(i).getPhoneNumber().equals(strInfor)) { return 1; } } return 0; } public void searchEmail(ArrayList<customer> list) { listKH kh = new listKH(); String email; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap email muon tim : "); Scanner sc = new Scanner(System.in); email = sc.nextLine(); if (search(list, email) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getEmail().contains(email) == true && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } public void searchPhone(ArrayList<customer> list) { listKH kh = new listKH(); String phone; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap so dien thoai can tim : "); Scanner sc = new Scanner(System.in); phone = sc.nextLine(); if (search(list, phone) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (phone.equals(list.get(i).getPhoneNumber()) && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|------------------|"); } } public void searchAddress(ArrayList<customer> list) { listKH kh = new listKH(); String address; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap dia chi can tim : "); Scanner sc = new Scanner(System.in); address = sc.nextLine(); if (search(list, address) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getAddress().contains(address) && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } public customer showCustomer(ArrayList<customer> list, String user) { customer cus = new customer(); listKH kh = new listKH(); for (int i = 0; i < list.size(); i++) { if (user.equals(list.get(i).getUserName())) { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); kh.showInfor(list.get(i)); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); cus = list.get(i); } } return cus; } public void showCustomerExist(ArrayList<customer> list) { listKH kh = new listKH(); if (list.size() == 1) { System.out.println("=======<< DANH SACH TRONG! KHONG CO KHACH HANG NAO >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getStatus() == 1 && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } }
UTF-8
Java
7,055
java
searchKH.java
Java
[ { "context": "l.customer;\nimport view.listKH;\n\n/**\n *\n * @author Minh Thu\n */\npublic class searchKH {\n\n public int searc", "end": 330, "score": 0.9997460246086121, "start": 322, "tag": "NAME", "value": "Minh Thu" }, { "context": "neNumber()) && !list.get(i).getUserName().equals(\"ADMINCustomer\")) {\n kh.showInfor(list.get(i)", "end": 3198, "score": 0.9245975017547607, "start": 3185, "tag": "USERNAME", "value": "ADMINCustomer" }, { "context": "ns(address) && !list.get(i).getUserName().equals(\"ADMINCustomer\")) {\n kh.showInfor(list.get(i)", "end": 4579, "score": 0.9496626853942871, "start": 4566, "tag": "USERNAME", "value": "ADMINCustomer" }, { "context": "atus() == 1 && !list.get(i).getUserName().equals(\"ADMINCustomer\")) {\n kh.showInfor(list.get(i)", "end": 6788, "score": 0.7159433364868164, "start": 6775, "tag": "USERNAME", "value": "ADMINCustomer" } ]
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 controller; import java.util.ArrayList; import java.util.Scanner; import model.customer; import view.listKH; /** * * @author <NAME> */ public class searchKH { public int search(ArrayList<customer> list, String strInfor) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getEmail().contains(strInfor) || list.get(i).getAddress().contains(strInfor) || list.get(i).getPhoneNumber().equals(strInfor)) { return 1; } } return 0; } public void searchEmail(ArrayList<customer> list) { listKH kh = new listKH(); String email; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap email muon tim : "); Scanner sc = new Scanner(System.in); email = sc.nextLine(); if (search(list, email) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getEmail().contains(email) == true && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } public void searchPhone(ArrayList<customer> list) { listKH kh = new listKH(); String phone; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap so dien thoai can tim : "); Scanner sc = new Scanner(System.in); phone = sc.nextLine(); if (search(list, phone) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (phone.equals(list.get(i).getPhoneNumber()) && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|------------------|"); } } public void searchAddress(ArrayList<customer> list) { listKH kh = new listKH(); String address; //ArrayList<customer> listSearch = new ArrayList(); System.out.println("Moi ban nhap dia chi can tim : "); Scanner sc = new Scanner(System.in); address = sc.nextLine(); if (search(list, address) == 0) { System.out.println("=======<< KHONG TIM THAY KHACH HANG >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getAddress().contains(address) && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } public customer showCustomer(ArrayList<customer> list, String user) { customer cus = new customer(); listKH kh = new listKH(); for (int i = 0; i < list.size(); i++) { if (user.equals(list.get(i).getUserName())) { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); kh.showInfor(list.get(i)); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); cus = list.get(i); } } return cus; } public void showCustomerExist(ArrayList<customer> list) { listKH kh = new listKH(); if (list.size() == 1) { System.out.println("=======<< DANH SACH TRONG! KHONG CO KHACH HANG NAO >>======="); } else { System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); System.out.println("| ID | TEN KHACH HANG | SDT | EMAIL | POINTS | Que quan |"); System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); for (int i = 0; i < list.size(); i++) { if (list.get(i).getStatus() == 1 && !list.get(i).getUserName().equals("ADMINCustomer")) { kh.showInfor(list.get(i)); } } System.out.println("|----|--------------------------------|----------------------|----------------------------------|----------|-------------------|"); } } }
7,053
0.345854
0.344011
132
52.446968
54.866135
167
false
false
0
0
0
0
0
0
1.689394
false
false
12
0dddf4795ee69ffe6d9a2f61a8bcb1df9c8c80af
7,430,293,474,376
76daded2385909074ee565534d0adfd044ddfce1
/visualizeFrame.java
a86c229d23dcbfdad11dc158442b8fe2c0f8a83e
[]
no_license
roman-smith/CSE360_GroupProject
https://github.com/roman-smith/CSE360_GroupProject
4f42e79531a9d5171461f0f0b86ce9cc554fed22
86f26ec142c468bfaef1016c22f9fa5d297ae01b
refs/heads/main
2023-04-06T03:57:08.976000
2021-04-20T03:00:14
2021-04-20T03:00:14
357,026,812
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.awt.Color; import javax.swing.JOptionPane; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PiePlot3D; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; /** * * @author Kevin */ public class visualizeFrame extends javax.swing.JFrame { static ArrayList<Patient> patientList; /** * Creates new form visualizeFrame */ public visualizeFrame(ArrayList<Patient> patientList) { initComponents(); visualizeFrame.patientList = patientList; this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); aboutButton = new javax.swing.JButton(); loadButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); saveButton = new javax.swing.JButton(); graphicsButton = new javax.swing.JButton(); infoPanel = new javax.swing.JPanel(); barButton = new javax.swing.JButton(); pieButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); aboutButton.setText("About"); aboutButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutButtonActionPerformed(evt); } }); loadButton.setText("Load Data"); loadButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadButtonActionPerformed(evt); } }); addButton.setText("Add Data"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); saveButton.setText("Save Data"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); graphicsButton.setText("Visualize Data"); barButton.setText("Bar Graph"); barButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { barButtonActionPerformed(evt); } }); pieButton.setText("Pie Chart"); pieButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pieButtonActionPerformed(evt); } }); javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel); infoPanel.setLayout(infoPanelLayout); infoPanelLayout.setHorizontalGroup( infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(infoPanelLayout.createSequentialGroup() .addGap(190, 190, 190) .addComponent(barButton) .addGap(105, 105, 105) .addComponent(pieButton) .addContainerGap(222, Short.MAX_VALUE)) ); infoPanelLayout.setVerticalGroup( infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(barButton) .addComponent(pieButton)) .addGap(60, 60, 60)) ); javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(graphicsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(loadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(mainPanelLayout.createSequentialGroup() .addComponent(aboutButton) .addGap(64, 64, 64) .addComponent(loadButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(addButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(graphicsButton) .addGap(0, 281, Short.MAX_VALUE))) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed JOptionPane.showMessageDialog(this, "----Team 1----\n\nRoman Smith\n\nKevin Mendoza Ramirez\n\nLuis Zermeno\n\nNicole Gutierrez\n\n------------------"); }//GEN-LAST:event_aboutButtonActionPerformed private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed new loadFrame(patientList).setVisible(true); this.setVisible(false); }//GEN-LAST:event_loadButtonActionPerformed private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed new addFrame(patientList).setVisible(true); this.setVisible(false); }//GEN-LAST:event_addButtonActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) { new saveData(patientList); } private void barButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_barButtonActionPerformed DefaultCategoryDataset data = new DefaultCategoryDataset(); ArrayList<String> vaccineTypes = new ArrayList<String>(); for(Patient patient : patientList) { boolean hasVaccine = false; for(String vaccine : vaccineTypes) { if(patient.getType().equals(vaccine)) { hasVaccine = true; } } if(!hasVaccine) { vaccineTypes.add(patient.getType()); } } for(String vaccine : vaccineTypes) { int count = 0; for(Patient patient : patientList) { if(patient.getType().equals(vaccine)) { count++; } } data.setValue(count, vaccine, vaccine); } JFreeChart chart = ChartFactory.createBarChart("Vaccination Data", "Vaccine Name", "Vaccinations", data, PlotOrientation.VERTICAL, true, true, false); CategoryPlot plot = chart.getCategoryPlot(); plot.setRangeGridlinePaint(Color.black); ChartFrame chartFrame = new ChartFrame("Vaccination Data",chart,true); chartFrame.setVisible(true); chartFrame.setLocationRelativeTo(infoPanel); chartFrame.setSize(800,600); }//GEN-LAST:event_barButtonActionPerformed private void pieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pieButtonActionPerformed DefaultPieDataset data = new DefaultPieDataset(); ArrayList<String> countries = new ArrayList<String>(); for(Patient patient : patientList) { boolean hasCountry = false; for(String country : countries) { if(patient.getCountry().equals(country)) { hasCountry = true; } } if(!hasCountry) { countries.add(patient.getCountry()); } } for(String country : countries) { int count = 0; for(Patient patient : patientList) { if(patient.getCountry().equals(country)) { count++; } } data.setValue(country, count); } JFreeChart chart = ChartFactory.createPieChart("Vaccination Data", data, true, true, false); PiePlot piePlot = (PiePlot) chart.getPlot(); ChartFrame chartFrame = new ChartFrame("Vaccination Data",chart); chartFrame.setVisible(true); chartFrame.setLocationRelativeTo(infoPanel); chartFrame.setSize(500,400); }//GEN-LAST:event_pieButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new visualizeFrame(patientList).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton aboutButton; private javax.swing.JButton addButton; private javax.swing.JButton barButton; private javax.swing.JButton graphicsButton; private javax.swing.JPanel infoPanel; private javax.swing.JButton loadButton; private javax.swing.JPanel mainPanel; private javax.swing.JButton pieButton; private javax.swing.JButton saveButton; // End of variables declaration//GEN-END:variables }
UTF-8
Java
14,062
java
visualizeFrame.java
Java
[ { "context": "data.general.DefaultPieDataset;\n\n/**\n *\n * @author Kevin\n */\npublic class visualizeFrame extends javax.swi", "end": 668, "score": 0.9993311166763306, "start": 663, "tag": "NAME", "value": "Kevin" }, { "context": "onPane.showMessageDialog(this, \"----Team 1----\\n\\nRoman Smith\\n\\nKevin Mendoza Ramirez\\n\\nLuis Zermeno\\n\\nNicol", "end": 8248, "score": 0.9998564720153809, "start": 8237, "tag": "NAME", "value": "Roman Smith" }, { "context": "ageDialog(this, \"----Team 1----\\n\\nRoman Smith\\n\\nKevin Mendoza Ramirez\\n\\nLuis Zermeno\\n\\nNicole Gutierrez\\n\\n----------", "end": 8273, "score": 0.999817967414856, "start": 8252, "tag": "NAME", "value": "Kevin Mendoza Ramirez" }, { "context": " 1----\\n\\nRoman Smith\\n\\nKevin Mendoza Ramirez\\n\\nLuis Zermeno\\n\\nNicole Gutierrez\\n\\n------------------\");\n ", "end": 8289, "score": 0.9998710751533508, "start": 8277, "tag": "NAME", "value": "Luis Zermeno" }, { "context": "Smith\\n\\nKevin Mendoza Ramirez\\n\\nLuis Zermeno\\n\\nNicole Gutierrez\\n\\n------------------\");\n }//GEN-LAST:event_ab", "end": 8309, "score": 0.9998704195022583, "start": 8293, "tag": "NAME", "value": "Nicole Gutierrez" } ]
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. */ import java.util.ArrayList; import java.awt.Color; import javax.swing.JOptionPane; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PiePlot3D; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; /** * * @author Kevin */ public class visualizeFrame extends javax.swing.JFrame { static ArrayList<Patient> patientList; /** * Creates new form visualizeFrame */ public visualizeFrame(ArrayList<Patient> patientList) { initComponents(); visualizeFrame.patientList = patientList; this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); aboutButton = new javax.swing.JButton(); loadButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); saveButton = new javax.swing.JButton(); graphicsButton = new javax.swing.JButton(); infoPanel = new javax.swing.JPanel(); barButton = new javax.swing.JButton(); pieButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); aboutButton.setText("About"); aboutButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutButtonActionPerformed(evt); } }); loadButton.setText("Load Data"); loadButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadButtonActionPerformed(evt); } }); addButton.setText("Add Data"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); saveButton.setText("Save Data"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); graphicsButton.setText("Visualize Data"); barButton.setText("Bar Graph"); barButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { barButtonActionPerformed(evt); } }); pieButton.setText("Pie Chart"); pieButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pieButtonActionPerformed(evt); } }); javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel); infoPanel.setLayout(infoPanelLayout); infoPanelLayout.setHorizontalGroup( infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(infoPanelLayout.createSequentialGroup() .addGap(190, 190, 190) .addComponent(barButton) .addGap(105, 105, 105) .addComponent(pieButton) .addContainerGap(222, Short.MAX_VALUE)) ); infoPanelLayout.setVerticalGroup( infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(barButton) .addComponent(pieButton)) .addGap(60, 60, 60)) ); javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(graphicsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(loadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(aboutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(mainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(mainPanelLayout.createSequentialGroup() .addComponent(aboutButton) .addGap(64, 64, 64) .addComponent(loadButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(addButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(graphicsButton) .addGap(0, 281, Short.MAX_VALUE))) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed JOptionPane.showMessageDialog(this, "----Team 1----\n\n<NAME>\n\n<NAME>\n\n<NAME>\n\n<NAME>\n\n------------------"); }//GEN-LAST:event_aboutButtonActionPerformed private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed new loadFrame(patientList).setVisible(true); this.setVisible(false); }//GEN-LAST:event_loadButtonActionPerformed private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed new addFrame(patientList).setVisible(true); this.setVisible(false); }//GEN-LAST:event_addButtonActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) { new saveData(patientList); } private void barButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_barButtonActionPerformed DefaultCategoryDataset data = new DefaultCategoryDataset(); ArrayList<String> vaccineTypes = new ArrayList<String>(); for(Patient patient : patientList) { boolean hasVaccine = false; for(String vaccine : vaccineTypes) { if(patient.getType().equals(vaccine)) { hasVaccine = true; } } if(!hasVaccine) { vaccineTypes.add(patient.getType()); } } for(String vaccine : vaccineTypes) { int count = 0; for(Patient patient : patientList) { if(patient.getType().equals(vaccine)) { count++; } } data.setValue(count, vaccine, vaccine); } JFreeChart chart = ChartFactory.createBarChart("Vaccination Data", "Vaccine Name", "Vaccinations", data, PlotOrientation.VERTICAL, true, true, false); CategoryPlot plot = chart.getCategoryPlot(); plot.setRangeGridlinePaint(Color.black); ChartFrame chartFrame = new ChartFrame("Vaccination Data",chart,true); chartFrame.setVisible(true); chartFrame.setLocationRelativeTo(infoPanel); chartFrame.setSize(800,600); }//GEN-LAST:event_barButtonActionPerformed private void pieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pieButtonActionPerformed DefaultPieDataset data = new DefaultPieDataset(); ArrayList<String> countries = new ArrayList<String>(); for(Patient patient : patientList) { boolean hasCountry = false; for(String country : countries) { if(patient.getCountry().equals(country)) { hasCountry = true; } } if(!hasCountry) { countries.add(patient.getCountry()); } } for(String country : countries) { int count = 0; for(Patient patient : patientList) { if(patient.getCountry().equals(country)) { count++; } } data.setValue(country, count); } JFreeChart chart = ChartFactory.createPieChart("Vaccination Data", data, true, true, false); PiePlot piePlot = (PiePlot) chart.getPlot(); ChartFrame chartFrame = new ChartFrame("Vaccination Data",chart); chartFrame.setVisible(true); chartFrame.setLocationRelativeTo(infoPanel); chartFrame.setSize(500,400); }//GEN-LAST:event_pieButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(visualizeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new visualizeFrame(patientList).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton aboutButton; private javax.swing.JButton addButton; private javax.swing.JButton barButton; private javax.swing.JButton graphicsButton; private javax.swing.JPanel infoPanel; private javax.swing.JButton loadButton; private javax.swing.JPanel mainPanel; private javax.swing.JButton pieButton; private javax.swing.JButton saveButton; // End of variables declaration//GEN-END:variables }
14,026
0.647561
0.643721
310
44.36129
35.235775
160
false
false
0
0
0
0
0
0
0.590323
false
false
12
af6d508a8c2cf437bf3fb2c3a8f3d80d3a26f8c8
17,514,876,683,268
494eadad4c3dc69da84d44c6218141cbc5387c38
/src/main/java/com/yayhi/tags/Merger.java
62405dfb2b4b81834f1b21110da4bd6ab99b52a4
[]
no_license
markg454/mergetags
https://github.com/markg454/mergetags
c5e7dd5ba9e551a8036806876d74fbf55879ed25
1195d32e2295865ee0370285bdfe87acf8a984f1
refs/heads/master
2021-01-10T07:17:08.589000
2016-03-11T21:33:55
2016-03-11T21:33:55
53,466,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yayhi.tags; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.Ostermiller.util.ExcelCSVParser; import com.yayhi.dao.TagDAO; import com.yayhi.utils.YLogger; import com.yayhi.utils.YProperties; /** * ----------------------------------------------------------------------------- * @version 1.0 * @author Mark Gaither * @date Aug 19, 2010 * ----------------------------------------------------------------------------- */ public class Merger { private static YProperties iProps = null; private static Properties appProps = null; private static String logFilePath = null; private static Boolean logIt = null; private static String inputCSVFilePath = null; private static String outputCSVFilePath = null; private static boolean debug = false; private static boolean test = false; private static boolean verbose = false; private static YLogger logger = null; private static boolean hasErrors = false; // constructor Merger() { } // check if string is not empty public static boolean isEmpty(String s) { boolean empty = false; Pattern p = Pattern.compile("^[ ]*$"); Matcher m = p.matcher(s); if (m.find()) { empty = true; } return empty; } /** * Sole entry point to the class and application. * @param args Array of String arguments. * @exception java.lang.InterruptedException * Thrown from the Thread class. * @throws SQLException */ public static void main(String[] args) throws Exception { //********************************************************************************************* //* Get Command Line Arguments - overwrites the properties file value, if any //********************************************************************************************* String usage = "Usage:\n" + "java -jar merger.jar [-i INPUT_CSV] [-o OUTPUT_CSC] [-t] (TEST and validate the input file but don't database inserts - optional) [-v] (VERBOSE mode - optional) [-d] (DEBUG - optional)\n"; String example = "Example:\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -d\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -t\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -v -d\n"; // get command line arguments if (args.length >= 4) { for (int optind = 0; optind < args.length; optind++) { if (args[optind].equals("-i")) { inputCSVFilePath = args[++optind]; } else if (args[optind].equals("-o")) { outputCSVFilePath = args[++optind]; } else if (args[optind].equals("-d")) { debug = true; } else if (args[optind].equals("-v")) { verbose = true; } else if (args[optind].equals("-t")) { test = true; } } } else { System.err.println(usage); System.err.println(example); System.exit(1); } //********************************************************************************************* //* Get Properties File Data //********************************************************************************************* iProps = new YProperties(); appProps = iProps.loadProperties(); // set log file path logFilePath = appProps.getProperty("logFilePath"); logIt = Boolean.valueOf(appProps.getProperty("logIt")); // allow command line setting of debug to over rule the properties setting if (!debug) debug = Boolean.parseBoolean(appProps.getProperty("debug")); if (debug) { System.out.println("logFilePath: " + logFilePath); System.out.println("logIt: " + logIt); System.out.println("input CSV file: " + inputCSVFilePath); System.out.println("output CSV file: " + outputCSVFilePath); } //********************************************************************************************* //* Set up logging //********************************************************************************************* // create string of todays date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss"); String loggerFilePath = appProps.getProperty("logFilePath") + "/mergetags_" + sdf.format(cal.getTime()) + ".log"; // log data, if true if (logIt.booleanValue()) { // open log file try { logger = new YLogger(loggerFilePath); } catch (IOException e) { System.out.println("exception: " + e.getMessage()); } } // output run information to stdout if (verbose) { if (test) { System.out.println("\tRUN MODE =\t\tTest and Validate"); } else { System.out.println("\tRUN MODE =\t\tInsert"); } } // log run information try { if (test) { logger.write("\tRUN MODE =\t\tTest and Validate"); } else { logger.write("\tRUN MODE =\t\tInsert"); } logger.write("\tINPUT CSV =\t\t" + inputCSVFilePath); } catch (IOException e) { e.printStackTrace(); } //********************************************************************************************* //* Read input CSV //********************************************************************************************* // Create the csv input file //File input fileFile = new File(inputCSVFilePath); String[][] lines = null; // lines of input csv file // Read contents of the input file file BufferedReader br = null; String fileContents = ""; try { String sCurrentLine; br = new BufferedReader(new FileReader(inputCSVFilePath)); int lineCount = 0; while ((sCurrentLine = br.readLine()) != null) { if (lineCount == 0 && sCurrentLine.contains("keywords")) { // skip header line if it exists if (debug) System.out.println("Skipping header ..."); } else { if (debug) { System.out.println("current input file line " + sCurrentLine); } // build file contents string to give to the parser if (lineCount == 0) fileContents = sCurrentLine; else fileContents = fileContents + "\n" + sCurrentLine; } lineCount++; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } // Parse the CSV data try { lines = ExcelCSVParser.parse(fileContents); } catch(Exception e){ System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } //********************************************************************************************* //* Merge incoming CSV with new tag set from database //********************************************************************************************* if (debug) { System.out.println("Count of parsed lines: " + lines.length); } // create output CSV file CSVFileWriter fw = new CSVFileWriter(outputCSVFilePath); // write the header column data fw.write(new String[] { "id","tags","keywords" }); for (int i = 0; i < lines.length; i++) { hasErrors = false; // id String idStr = lines[i][0]; // keywords String keywordsStr = lines[i][1]; if (debug) { System.out.println("-----------"); System.out.println("idStr: " + idStr.trim()); System.out.println("keywordsStr: " + keywordsStr.trim()); } // parse out keywords list of strings String[] keywords = null; if (keywordsStr.contains(",")) { keywords = keywordsStr.split(","); if (debug) { System.out.println("keywords: " + Arrays.toString(keywords)); } // create database connection object TagDAO dao = new TagDAO(); //********************************************************************************************* //* Create list of tags for given keywords for the current title //********************************************************************************************* ArrayList <String>tags = new ArrayList<String>(); for (String keyword : keywords) { if (debug) { System.out.println("keyword: " + keyword.trim()); } // get terms for synonym, if any ArrayList<String> termList = dao.getTerms(keyword.trim().replace("'", "\\'")); // add found terms if (!termList.isEmpty()) { String pt = termList.get(0); // parent term String t = termList.get(1); // term // if term empty, use the parent if (t.equals("")) { t = pt; } if (debug) { System.out.println("\nkeyword: " + keyword.trim() + " parent found: " + pt + " term found: " + t); } // make sure not include a duplicate parent term if (!tags.contains(pt)) { tags.add(pt); // add found parent term } // make sure not include a duplicate term if (!tags.contains(t)) { tags.add(t); // add found term } } else { logger.write("\tKEYWORD NOT MAPPED: " + keyword.trim()); } } if (debug) { System.out.println("id: " + idStr + " keywords: " + keywordsStr + " tags: " + tags); } StringBuilder sb = new StringBuilder(); int sCount = 0; for (String s : tags) { if (sCount == 0) { sb.append(s); } else { sb.append(","); sb.append(s); } sCount++; } if (!fw.write(new String[] { idStr, sb.toString(), keywordsStr })) { // send error message } } } // close the output stream fw.close(); logger.close(); } }
UTF-8
Java
10,590
java
Merger.java
Java
[ { "context": "----------------------\n * @version 1.0\n * @author Mark Gaither\n * @date\tAug 19, 2010\n * ------------------------", "end": 617, "score": 0.9997718334197998, "start": 605, "tag": "NAME", "value": "Mark Gaither" } ]
null
[]
package com.yayhi.tags; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.Ostermiller.util.ExcelCSVParser; import com.yayhi.dao.TagDAO; import com.yayhi.utils.YLogger; import com.yayhi.utils.YProperties; /** * ----------------------------------------------------------------------------- * @version 1.0 * @author <NAME> * @date Aug 19, 2010 * ----------------------------------------------------------------------------- */ public class Merger { private static YProperties iProps = null; private static Properties appProps = null; private static String logFilePath = null; private static Boolean logIt = null; private static String inputCSVFilePath = null; private static String outputCSVFilePath = null; private static boolean debug = false; private static boolean test = false; private static boolean verbose = false; private static YLogger logger = null; private static boolean hasErrors = false; // constructor Merger() { } // check if string is not empty public static boolean isEmpty(String s) { boolean empty = false; Pattern p = Pattern.compile("^[ ]*$"); Matcher m = p.matcher(s); if (m.find()) { empty = true; } return empty; } /** * Sole entry point to the class and application. * @param args Array of String arguments. * @exception java.lang.InterruptedException * Thrown from the Thread class. * @throws SQLException */ public static void main(String[] args) throws Exception { //********************************************************************************************* //* Get Command Line Arguments - overwrites the properties file value, if any //********************************************************************************************* String usage = "Usage:\n" + "java -jar merger.jar [-i INPUT_CSV] [-o OUTPUT_CSC] [-t] (TEST and validate the input file but don't database inserts - optional) [-v] (VERBOSE mode - optional) [-d] (DEBUG - optional)\n"; String example = "Example:\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -d\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -t\n" + "java -jar merger.jar -i /tmp/tags.csv -o /tmp/out.csv -v -d\n"; // get command line arguments if (args.length >= 4) { for (int optind = 0; optind < args.length; optind++) { if (args[optind].equals("-i")) { inputCSVFilePath = args[++optind]; } else if (args[optind].equals("-o")) { outputCSVFilePath = args[++optind]; } else if (args[optind].equals("-d")) { debug = true; } else if (args[optind].equals("-v")) { verbose = true; } else if (args[optind].equals("-t")) { test = true; } } } else { System.err.println(usage); System.err.println(example); System.exit(1); } //********************************************************************************************* //* Get Properties File Data //********************************************************************************************* iProps = new YProperties(); appProps = iProps.loadProperties(); // set log file path logFilePath = appProps.getProperty("logFilePath"); logIt = Boolean.valueOf(appProps.getProperty("logIt")); // allow command line setting of debug to over rule the properties setting if (!debug) debug = Boolean.parseBoolean(appProps.getProperty("debug")); if (debug) { System.out.println("logFilePath: " + logFilePath); System.out.println("logIt: " + logIt); System.out.println("input CSV file: " + inputCSVFilePath); System.out.println("output CSV file: " + outputCSVFilePath); } //********************************************************************************************* //* Set up logging //********************************************************************************************* // create string of todays date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss"); String loggerFilePath = appProps.getProperty("logFilePath") + "/mergetags_" + sdf.format(cal.getTime()) + ".log"; // log data, if true if (logIt.booleanValue()) { // open log file try { logger = new YLogger(loggerFilePath); } catch (IOException e) { System.out.println("exception: " + e.getMessage()); } } // output run information to stdout if (verbose) { if (test) { System.out.println("\tRUN MODE =\t\tTest and Validate"); } else { System.out.println("\tRUN MODE =\t\tInsert"); } } // log run information try { if (test) { logger.write("\tRUN MODE =\t\tTest and Validate"); } else { logger.write("\tRUN MODE =\t\tInsert"); } logger.write("\tINPUT CSV =\t\t" + inputCSVFilePath); } catch (IOException e) { e.printStackTrace(); } //********************************************************************************************* //* Read input CSV //********************************************************************************************* // Create the csv input file //File input fileFile = new File(inputCSVFilePath); String[][] lines = null; // lines of input csv file // Read contents of the input file file BufferedReader br = null; String fileContents = ""; try { String sCurrentLine; br = new BufferedReader(new FileReader(inputCSVFilePath)); int lineCount = 0; while ((sCurrentLine = br.readLine()) != null) { if (lineCount == 0 && sCurrentLine.contains("keywords")) { // skip header line if it exists if (debug) System.out.println("Skipping header ..."); } else { if (debug) { System.out.println("current input file line " + sCurrentLine); } // build file contents string to give to the parser if (lineCount == 0) fileContents = sCurrentLine; else fileContents = fileContents + "\n" + sCurrentLine; } lineCount++; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } // Parse the CSV data try { lines = ExcelCSVParser.parse(fileContents); } catch(Exception e){ System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } //********************************************************************************************* //* Merge incoming CSV with new tag set from database //********************************************************************************************* if (debug) { System.out.println("Count of parsed lines: " + lines.length); } // create output CSV file CSVFileWriter fw = new CSVFileWriter(outputCSVFilePath); // write the header column data fw.write(new String[] { "id","tags","keywords" }); for (int i = 0; i < lines.length; i++) { hasErrors = false; // id String idStr = lines[i][0]; // keywords String keywordsStr = lines[i][1]; if (debug) { System.out.println("-----------"); System.out.println("idStr: " + idStr.trim()); System.out.println("keywordsStr: " + keywordsStr.trim()); } // parse out keywords list of strings String[] keywords = null; if (keywordsStr.contains(",")) { keywords = keywordsStr.split(","); if (debug) { System.out.println("keywords: " + Arrays.toString(keywords)); } // create database connection object TagDAO dao = new TagDAO(); //********************************************************************************************* //* Create list of tags for given keywords for the current title //********************************************************************************************* ArrayList <String>tags = new ArrayList<String>(); for (String keyword : keywords) { if (debug) { System.out.println("keyword: " + keyword.trim()); } // get terms for synonym, if any ArrayList<String> termList = dao.getTerms(keyword.trim().replace("'", "\\'")); // add found terms if (!termList.isEmpty()) { String pt = termList.get(0); // parent term String t = termList.get(1); // term // if term empty, use the parent if (t.equals("")) { t = pt; } if (debug) { System.out.println("\nkeyword: " + keyword.trim() + " parent found: " + pt + " term found: " + t); } // make sure not include a duplicate parent term if (!tags.contains(pt)) { tags.add(pt); // add found parent term } // make sure not include a duplicate term if (!tags.contains(t)) { tags.add(t); // add found term } } else { logger.write("\tKEYWORD NOT MAPPED: " + keyword.trim()); } } if (debug) { System.out.println("id: " + idStr + " keywords: " + keywordsStr + " tags: " + tags); } StringBuilder sb = new StringBuilder(); int sCount = 0; for (String s : tags) { if (sCount == 0) { sb.append(s); } else { sb.append(","); sb.append(s); } sCount++; } if (!fw.write(new String[] { idStr, sb.toString(), keywordsStr })) { // send error message } } } // close the output stream fw.close(); logger.close(); } }
10,584
0.490746
0.48848
363
28.170799
28.043621
222
false
false
0
0
0
0
0
0
2.76584
false
false
12
f9e853090f9bfc85b5dc4be7d41df3d94b7606b1
7,430,293,483,445
9d463ee809193c699cd78683c05da94651269262
/Data1_1.java
29282baae2f4db07eefb804011db069da316fc0d
[]
no_license
jhj0443/201611102_j
https://github.com/jhj0443/201611102_j
c61802452728de6630508fbe70703fde97bef388
1741ce68de2f0877857efb8620217fe785678d75
refs/heads/master
2020-12-31T03:56:28.629000
2016-12-12T03:35:58
2016-12-12T03:35:58
68,781,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; public class Data1_1{ public static void main(String[] args){ ArrayList<Integer> a= new ArrayList<Integer>(); for(int i=0; i<1001; i++) if(i%4==0 && i%5!=0){ a.add(i); } System.out.print(a); } }
UTF-8
Java
283
java
Data1_1.java
Java
[]
null
[]
import java.util.ArrayList; public class Data1_1{ public static void main(String[] args){ ArrayList<Integer> a= new ArrayList<Integer>(); for(int i=0; i<1001; i++) if(i%4==0 && i%5!=0){ a.add(i); } System.out.print(a); } }
283
0.522968
0.484099
17
14.764706
15.633784
51
false
false
0
0
0
0
0
0
0.352941
false
false
12
883e927dc0dea3d8ec51ad1cd2578c47d0421096
7,430,293,481,317
fe6876a19c52868df9f2ed1396024c2a9a34a1ac
/quartz/scheduledemo/src/main/java/com/cactus/scheduledemo/core/constant/Constants.java
5d312efca0daca63861a1b0bd2bdb323743f7ba6
[]
no_license
Cactus-L/Framework_Java
https://github.com/Cactus-L/Framework_Java
4ef3a6a082a3df1d3ba0c7b7df42cd6c99534276
af48a8fc728471aa491b535c6177af02fad79505
refs/heads/master
2022-06-26T09:36:28.297000
2019-12-05T09:24:44
2019-12-05T09:24:44
198,452,136
0
0
null
false
2022-06-17T02:20:10
2019-07-23T14:54:51
2019-12-05T09:24:46
2022-06-17T02:20:10
142
0
0
8
Java
false
false
package com.cactus.scheduledemo.core.constant; /** * Created by liruigao on 2019-06-11. */ public class Constants { /** * 任务调度参数key */ public static final String JOB_PARAM_KEY = "job_param_key"; }
UTF-8
Java
230
java
Constants.java
Java
[ { "context": "tus.scheduledemo.core.constant;\n\n/**\n * Created by liruigao on 2019-06-11.\n */\npublic class Constants {\n /", "end": 74, "score": 0.9995847940444946, "start": 66, "tag": "USERNAME", "value": "liruigao" } ]
null
[]
package com.cactus.scheduledemo.core.constant; /** * Created by liruigao on 2019-06-11. */ public class Constants { /** * 任务调度参数key */ public static final String JOB_PARAM_KEY = "job_param_key"; }
230
0.646789
0.610092
11
18.818182
20.243151
63
false
false
0
0
0
0
0
0
0.181818
false
false
12
80d18831a11868bcff658da9e01fb7895e885977
22,479,858,876,743
bb844f22cb2b0a56be01353abc7b1e60f889fdf0
/ssm-maven/src/main/java/com/jk/interceptor/Interceptor.java
238b8883675c867894ff65c4ee958bf66480b424
[]
no_license
hekairong/myrepository
https://github.com/hekairong/myrepository
96713a7fe7cd32b8b30a94395f910b77f01f605a
1a486da4ce29bcb4a6342bcf24c04df7e6738c1f
refs/heads/master
2020-04-06T13:04:40.950000
2018-11-14T08:28:10
2018-11-14T08:28:10
157,482,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <pre>项目名称:com.jk.2 * 文件名称:Interceptor.java * 包名:com.jk.interceptor * 创建日期:2018年7月11日下午4:35:37 * Copyright (c) 2018, yuxy123@gmail.com All Rights Reserved.</pre> */ package com.jk.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.jk.domain.user.User; /** * <pre>项目名称:com.jk.2 * 类名称:Interceptor * 类描述: * 创建人:付换龙 fhl_java@126.com * 创建时间:2018年7月11日 下午4:35:37 * 修改人:付换龙 fhl_java@126.com * 修改时间:2018年7月11日 下午4:35:37 * 修改备注: * @version </pre> */ public class Interceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { User uu=(User) request.getSession().getAttribute("userInfo"); if(uu != null ){ System.out.println("11111111111111"); return true; } response.sendRedirect(request.getContextPath()+"/"); System.out.println("222222222222"); return false; } }
UTF-8
Java
1,680
java
Interceptor.java
Java
[ { "context": " 创建日期:2018年7月11日下午4:35:37 \r\n * Copyright (c) 2018, yuxy123@gmail.com All Rights Reserved.</pre> \r\n */ \r\npackage com.j", "end": 154, "score": 0.9999257326126099, "start": 137, "tag": "EMAIL", "value": "yuxy123@gmail.com" }, { "context": " \r\n * 类名称:Interceptor \r\n * 类描述: \r\n * 创建人:付换龙 fhl_java@126.com \r\n * 创建时间:2018年7月11日 下午4:35:3", "end": 558, "score": 0.9978014826774597, "start": 555, "tag": "NAME", "value": "付换龙" }, { "context": " \r\n * 类名称:Interceptor \r\n * 类描述: \r\n * 创建人:付换龙 fhl_java@126.com \r\n * 创建时间:2018年7月11日 下午4:35:37 \r\n * 修改人:付换龙", "end": 575, "score": 0.9999200701713562, "start": 559, "tag": "EMAIL", "value": "fhl_java@126.com" }, { "context": "com \r\n * 创建时间:2018年7月11日 下午4:35:37 \r\n * 修改人:付换龙 fhl_java@126.com \r\n * 修改时间:2018年7月11日 下午4:35:37 ", "end": 625, "score": 0.9896149635314941, "start": 622, "tag": "NAME", "value": "付换龙" }, { "context": " \r\n * 创建时间:2018年7月11日 下午4:35:37 \r\n * 修改人:付换龙 fhl_java@126.com \r\n * 修改时间:2018年7月11日 下午4:35:37 \r\n * 修改备注: ", "end": 642, "score": 0.9999158978462219, "start": 626, "tag": "EMAIL", "value": "fhl_java@126.com" } ]
null
[]
/** * <pre>项目名称:com.jk.2 * 文件名称:Interceptor.java * 包名:com.jk.interceptor * 创建日期:2018年7月11日下午4:35:37 * Copyright (c) 2018, <EMAIL> All Rights Reserved.</pre> */ package com.jk.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.jk.domain.user.User; /** * <pre>项目名称:com.jk.2 * 类名称:Interceptor * 类描述: * 创建人:付换龙 <EMAIL> * 创建时间:2018年7月11日 下午4:35:37 * 修改人:付换龙 <EMAIL> * 修改时间:2018年7月11日 下午4:35:37 * 修改备注: * @version </pre> */ public class Interceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { User uu=(User) request.getSession().getAttribute("userInfo"); if(uu != null ){ System.out.println("11111111111111"); return true; } response.sendRedirect(request.getContextPath()+"/"); System.out.println("222222222222"); return false; } }
1,652
0.671651
0.615735
73
19.068493
26.006495
115
false
false
0
0
0
0
0
0
1.041096
false
false
12
0c57dd716d2b2083b16061889d7b406b674284c5
33,268,816,736,339
a58de078757c9d0890ee56f739e084c97d8f15ba
/app/src/main/java/com/example/petfinderproject/LoginFragment.java
97ade7480bc1e2137c4cc6b11126dff1915ffb78
[]
no_license
njanus90/PetFinderProject
https://github.com/njanus90/PetFinderProject
dd5416b3d82d4a920dcaa4187cd520a742dffdce
6fe1af88f215b4941d7a60cf7d123b89d95867df
refs/heads/master
2023-04-24T06:54:41.981000
2021-05-10T00:08:56
2021-05-10T00:08:56
362,249,414
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.petfinderproject; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; /* * Fragment to login to the app. User is prompted to enter their email and password * once the login button is clicked firebase authentication is used to authenticate. * you can also click the change password button to be taken to the change password fragment */ public class LoginFragment extends Fragment { //variables we need private FirebaseAuth mAuth; Button loginButton, forgotPassword; EditText loginEmail, loginPassword; Toolbar myToolbar; public LoginFragment() {// Required empty public constructor } public static LoginFragment newInstance() { LoginFragment fragment = new LoginFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_login, container, false); //fills the variables loginButton = view.findViewById(R.id.loginButton); forgotPassword = view.findViewById(R.id.forgotPassword); loginEmail = view.findViewById(R.id.loginEmail); loginPassword = view.findViewById(R.id.loginPassword); myToolbar = view.findViewById(R.id.toolbar); //when the login button is clicked loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAuth = FirebaseAuth.getInstance(); //does error checking to see if all the fields are correct if(loginEmail.getText().toString().isEmpty()){ Toast.makeText(getActivity(), "Enter Email", Toast.LENGTH_SHORT).show(); } else if(loginPassword.getText().toString().isEmpty()){ Toast.makeText(getActivity(), "Enter Password", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Made it", Toast.LENGTH_SHORT); //uses firebase authentication to log in mAuth.signInWithEmailAndPassword(loginEmail.getText().toString(), loginPassword.getText().toString()) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Toast.makeText(getContext(), "Made it", Toast.LENGTH_SHORT); if (task.isSuccessful()) { //Logged in successfully getActivity().setTitle(mAuth.getCurrentUser().getDisplayName()); //sets the items in the tool bar visable MainActivity.prof.setVisible(true); MainActivity.log.setVisible(true); //moves to the HomeFragment with the currently logged in user attached getFragmentManager().beginTransaction() .replace(R.id.fragmentLayout, HomeFragment.newInstance(new User(mAuth.getCurrentUser().getDisplayName(),mAuth.getCurrentUser().getUid(),mAuth.getCurrentUser().getEmail())), "home-screen") .addToBackStack(null) .commit(); } else { //Log in fail Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show(); } } }); } } }); //if user clicks forgot password it moves to forgot password fragment forgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction() .replace(R.id.fragmentLayout, new ChangePasswordFragment()) .addToBackStack(null) .commit(); } }); return view; } }
UTF-8
Java
5,237
java
LoginFragment.java
Java
[]
null
[]
package com.example.petfinderproject; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; /* * Fragment to login to the app. User is prompted to enter their email and password * once the login button is clicked firebase authentication is used to authenticate. * you can also click the change password button to be taken to the change password fragment */ public class LoginFragment extends Fragment { //variables we need private FirebaseAuth mAuth; Button loginButton, forgotPassword; EditText loginEmail, loginPassword; Toolbar myToolbar; public LoginFragment() {// Required empty public constructor } public static LoginFragment newInstance() { LoginFragment fragment = new LoginFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_login, container, false); //fills the variables loginButton = view.findViewById(R.id.loginButton); forgotPassword = view.findViewById(R.id.forgotPassword); loginEmail = view.findViewById(R.id.loginEmail); loginPassword = view.findViewById(R.id.loginPassword); myToolbar = view.findViewById(R.id.toolbar); //when the login button is clicked loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAuth = FirebaseAuth.getInstance(); //does error checking to see if all the fields are correct if(loginEmail.getText().toString().isEmpty()){ Toast.makeText(getActivity(), "Enter Email", Toast.LENGTH_SHORT).show(); } else if(loginPassword.getText().toString().isEmpty()){ Toast.makeText(getActivity(), "Enter Password", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Made it", Toast.LENGTH_SHORT); //uses firebase authentication to log in mAuth.signInWithEmailAndPassword(loginEmail.getText().toString(), loginPassword.getText().toString()) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Toast.makeText(getContext(), "Made it", Toast.LENGTH_SHORT); if (task.isSuccessful()) { //Logged in successfully getActivity().setTitle(mAuth.getCurrentUser().getDisplayName()); //sets the items in the tool bar visable MainActivity.prof.setVisible(true); MainActivity.log.setVisible(true); //moves to the HomeFragment with the currently logged in user attached getFragmentManager().beginTransaction() .replace(R.id.fragmentLayout, HomeFragment.newInstance(new User(mAuth.getCurrentUser().getDisplayName(),mAuth.getCurrentUser().getUid(),mAuth.getCurrentUser().getEmail())), "home-screen") .addToBackStack(null) .commit(); } else { //Log in fail Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show(); } } }); } } }); //if user clicks forgot password it moves to forgot password fragment forgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction() .replace(R.id.fragmentLayout, new ChangePasswordFragment()) .addToBackStack(null) .commit(); } }); return view; } }
5,237
0.580485
0.580485
116
44.155174
35.079617
235
false
false
0
0
0
0
0
0
0.603448
false
false
12
9157e517a31a24afa060b83686b14017f7725260
33,268,816,738,698
1b6ec0bd6cdbee55f15ff0ba86fc75899bc90d1a
/app/src/main/java/com/bryan/holiday/bryanholidayapp/adapters/MusicRecyclerAdapter.java
ec9166ccf55a22b849ea52fe64b08ed5243d2e6a
[]
no_license
bryanmorse05/bryanholiday
https://github.com/bryanmorse05/bryanholiday
a72c1360ab5651c5ad2bbad09d57f15bdf01772d
6009bd136b9bf64c60d079dacb61c2c2333bd82d
refs/heads/master
2020-04-05T13:16:03.307000
2018-12-20T20:56:27
2018-12-20T20:56:27
156,894,760
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bryan.holiday.bryanholidayapp.adapters; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bryan.holiday.bryanholidayapp.R; import com.bryan.holiday.bryanholidayapp.activities.MusicPlayer_Activity; import com.bryan.holiday.bryanholidayapp.models.MusicModel; import com.squareup.picasso.Picasso; import java.util.List; public class MusicRecyclerAdapter extends RecyclerView.Adapter<MusicRecyclerAdapter.MyViewHolder> { Context context; private List<MusicModel> musicModelList; // MediaPlayer mediaPlayer; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView songName; public TextView songArtist; public TextView songAlbum; public ImageView albumArt; public ConstraintLayout musicCellLayout; public MyViewHolder(View view) { super(view); songName = view.findViewById(R.id.songName); songArtist = view.findViewById(R.id.songArtist); songAlbum = view.findViewById(R.id.songAlbum); context = itemView.getContext(); albumArt = view.findViewById(R.id.albumArt); musicCellLayout = view.findViewById(R.id.musicCellLayout); // mediaPlayer = new MediaPlayer(); } } public MusicRecyclerAdapter(List<MusicModel> musicModelList) { this.musicModelList = musicModelList; } @NonNull @Override public MusicRecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_music, viewGroup, false); return new MusicRecyclerAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MusicRecyclerAdapter.MyViewHolder myViewHolder, int position) { final MusicModel musicModel = musicModelList.get(position); TextView songName = myViewHolder.songName; songName.setText(musicModel.getSongName()); TextView songArtist = myViewHolder.songArtist; songArtist.setText(musicModel.getSongArtist()); TextView songAlbum = myViewHolder.songAlbum; songAlbum.setText(musicModel.getSongAlbum()); Picasso.with(context).load(musicModel.getSongAlbumArt()).into(myViewHolder.albumArt); myViewHolder.musicCellLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, MusicPlayer_Activity.class); intent.putExtra("Song", musicModel.getSongTrack()); intent.putExtra("AlbumArt", musicModel.getSongAlbumArt()); context.startActivity(intent); } }); /*myViewHolder.playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); mediaPlayer.reset(); } else { try { MediaPlayer.create(context, songModel.getSongTrack()); Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + songModel.getSongTrack()); mediaPlayer.setDataSource(context, uri); mediaPlayer.prepare(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }); } catch (IOException e) { e.printStackTrace(); } Log.d("Button pressed", songModel.getSongName()); } } }); */ } @Override public int getItemCount() { return musicModelList.size(); } }
UTF-8
Java
4,479
java
MusicRecyclerAdapter.java
Java
[]
null
[]
package com.bryan.holiday.bryanholidayapp.adapters; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bryan.holiday.bryanholidayapp.R; import com.bryan.holiday.bryanholidayapp.activities.MusicPlayer_Activity; import com.bryan.holiday.bryanholidayapp.models.MusicModel; import com.squareup.picasso.Picasso; import java.util.List; public class MusicRecyclerAdapter extends RecyclerView.Adapter<MusicRecyclerAdapter.MyViewHolder> { Context context; private List<MusicModel> musicModelList; // MediaPlayer mediaPlayer; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView songName; public TextView songArtist; public TextView songAlbum; public ImageView albumArt; public ConstraintLayout musicCellLayout; public MyViewHolder(View view) { super(view); songName = view.findViewById(R.id.songName); songArtist = view.findViewById(R.id.songArtist); songAlbum = view.findViewById(R.id.songAlbum); context = itemView.getContext(); albumArt = view.findViewById(R.id.albumArt); musicCellLayout = view.findViewById(R.id.musicCellLayout); // mediaPlayer = new MediaPlayer(); } } public MusicRecyclerAdapter(List<MusicModel> musicModelList) { this.musicModelList = musicModelList; } @NonNull @Override public MusicRecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_music, viewGroup, false); return new MusicRecyclerAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MusicRecyclerAdapter.MyViewHolder myViewHolder, int position) { final MusicModel musicModel = musicModelList.get(position); TextView songName = myViewHolder.songName; songName.setText(musicModel.getSongName()); TextView songArtist = myViewHolder.songArtist; songArtist.setText(musicModel.getSongArtist()); TextView songAlbum = myViewHolder.songAlbum; songAlbum.setText(musicModel.getSongAlbum()); Picasso.with(context).load(musicModel.getSongAlbumArt()).into(myViewHolder.albumArt); myViewHolder.musicCellLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, MusicPlayer_Activity.class); intent.putExtra("Song", musicModel.getSongTrack()); intent.putExtra("AlbumArt", musicModel.getSongAlbumArt()); context.startActivity(intent); } }); /*myViewHolder.playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); mediaPlayer.reset(); } else { try { MediaPlayer.create(context, songModel.getSongTrack()); Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + songModel.getSongTrack()); mediaPlayer.setDataSource(context, uri); mediaPlayer.prepare(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }); } catch (IOException e) { e.printStackTrace(); } Log.d("Button pressed", songModel.getSongName()); } } }); */ } @Override public int getItemCount() { return musicModelList.size(); } }
4,479
0.6334
0.633177
125
34.832001
29.288834
127
false
false
0
0
0
0
0
0
0.576
false
false
12
7028181b7077954d638a99253a82601c2ae2c79c
24,412,594,151,661
685dc6d9d2c5f65e8964824263e83e45e7de2393
/src/bookexercise/list/chapter03/Ex3_30.java
62b735769525303fc221b5d44bd83b187eedd7df
[]
no_license
Nalixue/data-structure-algorithm
https://github.com/Nalixue/data-structure-algorithm
e6d93feaa6459c5930cc7d9b696783854b07d618
a7dcf5a74ad4106f22e38b01bb606b861fc53a94
refs/heads/master
2020-12-27T15:21:45.856000
2014-03-30T23:47:36
2014-03-30T23:47:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bookexercise.list.chapter03; public class Ex3_30 { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<Integer>(); int i = 0; for (i = 0; i < 10; ++i) { list.push(i); System.out.println(list); } // end for for (i = 0; i < 10; ++i) { list.search(i); System.out.println(list); } // end for } // end main() static class LinkedList<T> { private Node<T> startMarker; private Node<T> endMarker; private int size; public LinkedList() { startMarker = new Node<T>(); endMarker = new Node<T>(null, startMarker, null); startMarker.next = endMarker; size = 0; } // end LinkedList() public boolean search(T e) { Node<T> current = startMarker.next; boolean isExist = false; while (current != endMarker) { if (current.data.equals(e)) { isExist = true; break; } // end if else { current = current.next; } // end else } // end while if (isExist) { current.prev.next = current.next; current.next.prev = current.prev; current.next = startMarker.next; current.prev = startMarker; startMarker.next.prev = current; startMarker.next = current; } // end if return isExist; } // end search() @Override public String toString() { StringBuilder sb = new StringBuilder(); Node<T> current = startMarker.next; sb.append("["); if (current != endMarker) { sb.append(current.data); current = current.next; } // end if while (current != endMarker) { sb.append("," + current.data); current = current.next; } // end while sb.append("]"); return sb.toString(); } // end toString() public void push(T e) { Node<T> node = new Node<T>(e, null, null); node.next = startMarker.next; node.prev = startMarker; startMarker.next.prev = node; startMarker.next = node; ++size; } // end push() static class Node<T> { public T data; public Node<T> prev; public Node<T> next; public Node(){} public Node(T data, Node<T> prev, Node<T> next) { this.data = data; this.prev = prev; this.next = next; } // end Node() } // end class Node } // end class LinkedList }
UTF-8
Java
2,525
java
Ex3_30.java
Java
[]
null
[]
package bookexercise.list.chapter03; public class Ex3_30 { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<Integer>(); int i = 0; for (i = 0; i < 10; ++i) { list.push(i); System.out.println(list); } // end for for (i = 0; i < 10; ++i) { list.search(i); System.out.println(list); } // end for } // end main() static class LinkedList<T> { private Node<T> startMarker; private Node<T> endMarker; private int size; public LinkedList() { startMarker = new Node<T>(); endMarker = new Node<T>(null, startMarker, null); startMarker.next = endMarker; size = 0; } // end LinkedList() public boolean search(T e) { Node<T> current = startMarker.next; boolean isExist = false; while (current != endMarker) { if (current.data.equals(e)) { isExist = true; break; } // end if else { current = current.next; } // end else } // end while if (isExist) { current.prev.next = current.next; current.next.prev = current.prev; current.next = startMarker.next; current.prev = startMarker; startMarker.next.prev = current; startMarker.next = current; } // end if return isExist; } // end search() @Override public String toString() { StringBuilder sb = new StringBuilder(); Node<T> current = startMarker.next; sb.append("["); if (current != endMarker) { sb.append(current.data); current = current.next; } // end if while (current != endMarker) { sb.append("," + current.data); current = current.next; } // end while sb.append("]"); return sb.toString(); } // end toString() public void push(T e) { Node<T> node = new Node<T>(e, null, null); node.next = startMarker.next; node.prev = startMarker; startMarker.next.prev = node; startMarker.next = node; ++size; } // end push() static class Node<T> { public T data; public Node<T> prev; public Node<T> next; public Node(){} public Node(T data, Node<T> prev, Node<T> next) { this.data = data; this.prev = prev; this.next = next; } // end Node() } // end class Node } // end class LinkedList }
2,525
0.526337
0.521188
103
23.514563
13.16502
57
false
false
0
0
0
0
0
0
0.563107
false
false
12
ab661707dbfd416268fd4d3b3d92ab6af6847ada
28,887,950,074,244
30e5376b1956ea11e8176e5649694cb0a8f216aa
/app/src/main/java/com/example/wolfer/lab1beta/A3.java
2d4dc10b05d7a06e1113877b2401390a04861d61
[]
no_license
wolferu/Lab1Beta
https://github.com/wolferu/Lab1Beta
5641d2efc7f5160f1906f85d0519744062331a53
d6b0846185934f30f28c7be74978083c8b23f330
refs/heads/master
2020-02-16T23:04:55.840000
2018-03-17T10:07:52
2018-03-17T10:07:52
125,117,861
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.wolfer.lab1beta; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class A3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a3); } public void ActivateA2(View view) { EditText T4 = findViewById(R.id.T4); Intent startA2 = new Intent(this, A2.class); startA2.putExtra("T4",T4.getText().toString()); setResult(RESULT_OK,startA2); finish(); } }
UTF-8
Java
674
java
A3.java
Java
[]
null
[]
package com.example.wolfer.lab1beta; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class A3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a3); } public void ActivateA2(View view) { EditText T4 = findViewById(R.id.T4); Intent startA2 = new Intent(this, A2.class); startA2.putExtra("T4",T4.getText().toString()); setResult(RESULT_OK,startA2); finish(); } }
674
0.700297
0.681009
24
27.083334
19.396986
56
false
false
0
0
0
0
0
0
0.666667
false
false
12
1296d3342e067fbfb7965c845841947451458eea
7,842,610,330,500
0ea7359e27ae556127f17b0c8fb76b5fbbc7c7a3
/slf4j-lambda-lombok/src/main/java/lombok/javac/extern/handler/HandleSlf4jLambdaLog.java
50c8d26eb32c7fa1567e57436d4ed17fc3709385
[ "Apache-2.0" ]
permissive
kwon37xi/slf4j-lambda
https://github.com/kwon37xi/slf4j-lambda
86930fdad53c9f710d05edfa2af3e00a1bcf5be0
66a23e3bd0db4cec48c592c89d61a0cbca84058a
refs/heads/master
2021-09-08T18:26:41.179000
2021-09-02T13:46:07
2021-09-02T13:46:07
96,774,602
22
6
Apache-2.0
false
2021-09-02T11:15:10
2017-07-10T12:23:35
2021-05-31T11:16:26
2017-08-22T00:51:24
111
23
6
1
Java
false
false
package lombok.javac.extern.handler; /** * Handles the {@link lombok.extern.Slf4jLambda} annotation for javac. */ //@ProviderFor(JavacAnnotationHandler.class) public class HandleSlf4jLambdaLog { }
UTF-8
Java
201
java
HandleSlf4jLambdaLog.java
Java
[]
null
[]
package lombok.javac.extern.handler; /** * Handles the {@link lombok.extern.Slf4jLambda} annotation for javac. */ //@ProviderFor(JavacAnnotationHandler.class) public class HandleSlf4jLambdaLog { }
201
0.771144
0.761194
8
24.125
24.471603
70
true
false
0
0
0
0
0
0
0.125
false
false
12
b7b17b0e66255c462c511f63d42f303db3344966
8,014,408,996,471
16080deb1da8a5341528a6c58573210119ad0399
/src/main/java/com/porto/npf/sgpsweb/bo/PrioridadeBO.java
5905da2f5ef317b63730dd62e737d561bfc658d5
[]
no_license
mgsistemas/sgps-web
https://github.com/mgsistemas/sgps-web
8110cc999451655796f5fa582f5516269fe68337
653ac0200e1f5dd25fb3d44bdea09bb8a34cdab2
refs/heads/master
2016-08-08T04:52:36.544000
2015-09-23T22:58:45
2015-09-23T22:58:45
37,914,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.porto.npf.sgpsweb.bo; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import com.porto.npf.sgpsweb.common.SGPSConstants; import com.porto.npf.sgpsweb.dao.PrioridadeDAO; import com.porto.npf.sgpsweb.entity.Prioridade; import com.porto.npf.sgpsweb.exception.NegocioException; import com.porto.npf.sgpsweb.exception.PersistenceException; public class PrioridadeBO { private PrioridadeDAO priorDAO; private LogBO logBO; public PrioridadeBO(){ } /** * Método: salvar * Responsável por salvar o objeto no banco de dados * @param prior * @throws NegocioException */ public void salvar(Prioridade prior) throws NegocioException { priorDAO = new PrioridadeDAO(); logBO = new LogBO(); try { HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); Timestamp dataDeHoje = new Timestamp(System.currentTimeMillis()); String login = session.getAttribute("login").toString(); prior.setLogin(login); prior.setDataAtualizacao(dataDeHoje); if (prior.getId()!=null && !prior.getId().equals(Integer.valueOf(0))){ // Editar Prioridade Prioridade priTmp = new Prioridade(); priTmp = priorDAO.getPrioridadePorId(prior.getId()); String logTxt = "Dados originais : " + priTmp.toString() + " :: Dados alterados : " + prior.toString(); logBO.gravarLog(SGPSConstants.ACAO_ALTERAR, logTxt); priorDAO.update(prior); } else { // Não existe, então grava os dados priorDAO.salvar(prior); logBO.gravarLog(SGPSConstants.ACAO_INCLUIR, "Dados inseridos : " + prior.toString()); } } catch (Exception e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } }// Fim do método salvar /** * Método: getListPrioridade * Lista das prioridades cadastradas no sistema * @return */ public List<Prioridade> getListaPrioridade() throws NegocioException{ List<Prioridade> lista = new ArrayList<Prioridade>(); List<Prioridade> listaRetorno = new ArrayList<Prioridade>(); priorDAO = new PrioridadeDAO(); try { lista = priorDAO.getListaPrioridade(); for (Prioridade lst : lista) { Prioridade prior = new Prioridade(); prior.setId(lst.getId()); prior.setDescricaoPrioridade(lst.getDescricaoPrioridade()); if (lst.getSituacao().equals("A")) { prior.setSituacao("Ativo"); } else { prior.setSituacao("Inativo"); } prior.setLogin(lst.getLogin()); prior.setDataAtualizacao(lst.getDataAtualizacao()); listaRetorno.add(prior); } } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } return listaRetorno; }// Fim do método getListaPrioridade /** * Método: getPrioridadePorId * Retorna uma instancia do objeto PRIORIDADE pesquisada por ID * @param id * @return * @throws NegocioException */ public Prioridade getPrioridadePorId(Integer id) throws NegocioException { priorDAO = new PrioridadeDAO(); Prioridade prior = new Prioridade(); prior = null; try { prior = priorDAO.getPrioridadePorId(id); } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } return prior; }// Fim do método getPrioridadePorId /** * Método de negócio que retorma uma lista de objetos prioridades ativos * * @return * @throws NegocioException */ public List<Prioridade> getListaPrioridadesAtivas() throws NegocioException{ priorDAO = new PrioridadeDAO(); List<Prioridade> lista = new ArrayList<Prioridade>(); try { lista = priorDAO.getListaPrioridadesAtivas(); } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e); } return lista; } // fim do método de negócio getListaPrioridadesAtivas }
ISO-8859-1
Java
3,927
java
PrioridadeBO.java
Java
[]
null
[]
package com.porto.npf.sgpsweb.bo; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import com.porto.npf.sgpsweb.common.SGPSConstants; import com.porto.npf.sgpsweb.dao.PrioridadeDAO; import com.porto.npf.sgpsweb.entity.Prioridade; import com.porto.npf.sgpsweb.exception.NegocioException; import com.porto.npf.sgpsweb.exception.PersistenceException; public class PrioridadeBO { private PrioridadeDAO priorDAO; private LogBO logBO; public PrioridadeBO(){ } /** * Método: salvar * Responsável por salvar o objeto no banco de dados * @param prior * @throws NegocioException */ public void salvar(Prioridade prior) throws NegocioException { priorDAO = new PrioridadeDAO(); logBO = new LogBO(); try { HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); Timestamp dataDeHoje = new Timestamp(System.currentTimeMillis()); String login = session.getAttribute("login").toString(); prior.setLogin(login); prior.setDataAtualizacao(dataDeHoje); if (prior.getId()!=null && !prior.getId().equals(Integer.valueOf(0))){ // Editar Prioridade Prioridade priTmp = new Prioridade(); priTmp = priorDAO.getPrioridadePorId(prior.getId()); String logTxt = "Dados originais : " + priTmp.toString() + " :: Dados alterados : " + prior.toString(); logBO.gravarLog(SGPSConstants.ACAO_ALTERAR, logTxt); priorDAO.update(prior); } else { // Não existe, então grava os dados priorDAO.salvar(prior); logBO.gravarLog(SGPSConstants.ACAO_INCLUIR, "Dados inseridos : " + prior.toString()); } } catch (Exception e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } }// Fim do método salvar /** * Método: getListPrioridade * Lista das prioridades cadastradas no sistema * @return */ public List<Prioridade> getListaPrioridade() throws NegocioException{ List<Prioridade> lista = new ArrayList<Prioridade>(); List<Prioridade> listaRetorno = new ArrayList<Prioridade>(); priorDAO = new PrioridadeDAO(); try { lista = priorDAO.getListaPrioridade(); for (Prioridade lst : lista) { Prioridade prior = new Prioridade(); prior.setId(lst.getId()); prior.setDescricaoPrioridade(lst.getDescricaoPrioridade()); if (lst.getSituacao().equals("A")) { prior.setSituacao("Ativo"); } else { prior.setSituacao("Inativo"); } prior.setLogin(lst.getLogin()); prior.setDataAtualizacao(lst.getDataAtualizacao()); listaRetorno.add(prior); } } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } return listaRetorno; }// Fim do método getListaPrioridade /** * Método: getPrioridadePorId * Retorna uma instancia do objeto PRIORIDADE pesquisada por ID * @param id * @return * @throws NegocioException */ public Prioridade getPrioridadePorId(Integer id) throws NegocioException { priorDAO = new PrioridadeDAO(); Prioridade prior = new Prioridade(); prior = null; try { prior = priorDAO.getPrioridadePorId(id); } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e.getMessage()); } return prior; }// Fim do método getPrioridadePorId /** * Método de negócio que retorma uma lista de objetos prioridades ativos * * @return * @throws NegocioException */ public List<Prioridade> getListaPrioridadesAtivas() throws NegocioException{ priorDAO = new PrioridadeDAO(); List<Prioridade> lista = new ArrayList<Prioridade>(); try { lista = priorDAO.getListaPrioridadesAtivas(); } catch (PersistenceException e) { e.printStackTrace(); throw new NegocioException(e); } return lista; } // fim do método de negócio getListaPrioridadesAtivas }
3,927
0.714614
0.714359
134
28.208956
22.982496
111
false
false
0
0
0
0
0
0
2.343284
false
false
12
12f325271349a0b26e731b15d7a627c5988cc7db
22,402,549,416,685
5f66a7d729227aafe51742926a18d7994f32d6a1
/NgramModel/corpus/program_language_dataset10/java/lucene/1700.code.java
b5d81f795b2f5305f1ee0be2951cbc52145656d3
[]
no_license
SunshineAllWay/CCExperiment
https://github.com/SunshineAllWay/CCExperiment
c0a77868297dcf35d41ee5d6d4b67aff3dcc3563
2bb1c06679f8769e5ce18b636cd30a7aede5240b
refs/heads/master
2021-06-05T20:06:34.426000
2019-05-30T00:07:16
2019-05-30T00:07:16
139,319,619
0
2
null
false
2020-10-12T22:20:30
2018-07-01T10:25:55
2019-06-06T00:47:56
2020-10-12T22:20:29
137,624
0
2
5
Java
false
false
package org.apache.lucene.search; import java.io.IOException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; public class SingleTermEnum extends FilteredTermEnum { private Term singleTerm; private boolean endEnum = false; public SingleTermEnum(IndexReader reader, Term singleTerm) throws IOException { super(); this.singleTerm = singleTerm; setEnum(reader.terms(singleTerm)); } @Override public float difference() { return 1.0F; } @Override protected boolean endEnum() { return endEnum; } @Override protected boolean termCompare(Term term) { if (term.equals(singleTerm)) { return true; } else { endEnum = true; return false; } } }
UTF-8
Java
741
java
1700.code.java
Java
[]
null
[]
package org.apache.lucene.search; import java.io.IOException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; public class SingleTermEnum extends FilteredTermEnum { private Term singleTerm; private boolean endEnum = false; public SingleTermEnum(IndexReader reader, Term singleTerm) throws IOException { super(); this.singleTerm = singleTerm; setEnum(reader.terms(singleTerm)); } @Override public float difference() { return 1.0F; } @Override protected boolean endEnum() { return endEnum; } @Override protected boolean termCompare(Term term) { if (term.equals(singleTerm)) { return true; } else { endEnum = true; return false; } } }
741
0.703104
0.700405
30
23.700001
17.610888
81
false
false
0
0
0
0
0
0
0.5
false
false
12
d28268cb892277ffd3f43e391896bbeda60f9587
13,417,477,842,425
963a0f42aaebbcc29879638db0f15e76d7c676fc
/wffweb-3/src/test/java/com/webfirmframework/wffweb/css/BorderColorTest.java
eb0ff1db6b6732b9da5911ca5005d7231a84a000
[ "Apache-2.0" ]
permissive
webfirmframework/wff
https://github.com/webfirmframework/wff
0ff8f7c4f53d4ff414ec914f5b1d5d5042aecb82
843018dac3ae842a60d758a6eb60333489c9cc73
refs/heads/master
2023-08-05T21:28:27.153000
2023-07-29T03:55:08
2023-07-29T03:55:08
46,187,719
16
5
Apache-2.0
false
2023-07-29T03:55:09
2015-11-14T18:56:22
2023-04-23T18:53:44
2023-07-29T03:55:08
15,055
13
3
1
Java
false
false
/* * Copyright 2014-2021 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.css; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.NullValueException; /** * * @author WFF * @since 1.0.0 */ public class BorderColorTest { @Test public void testBorderColor() { BorderColor borderColor = new BorderColor(); assertEquals(BorderColor.INITIAL, borderColor.getCssValue()); } @Test public void testBorderColorString() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testBorderColorBorderColor() { BorderColor borderColor = new BorderColor("#0000ff"); BorderColor borderColor1 = new BorderColor(borderColor); assertEquals("#0000ff", borderColor1.getCssValue()); } @Test public void testSetValue() { BorderColor borderColor = new BorderColor(); borderColor.setValue("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testGetCssName() { BorderColor borderColor = new BorderColor(); assertEquals(CssNameConstants.BORDER_COLOR, borderColor.getCssName()); } @Test public void testGetCssValue() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testToString() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals(CssNameConstants.BORDER_COLOR + ": #0000ff", borderColor.toString()); } @Test public void testGetValue() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getValue()); } @Test public void testSetCssValueString() { BorderColor borderColor = new BorderColor(); borderColor.setCssValue("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testSetAsInitial() { BorderColor borderColor = new BorderColor(); borderColor.setAsInitial(); assertEquals(BorderColor.INITIAL, borderColor.getCssValue()); } @Test public void testSetAsInherit() { BorderColor borderColor = new BorderColor(); borderColor.setAsInherit(); assertEquals(BorderColor.INHERIT, borderColor.getCssValue()); } @Test public void testSetAsTransparent() { BorderColor borderColor = new BorderColor(); borderColor.setAsTransparent(); assertEquals(BorderColor.TRANSPARENT, borderColor.getCssValue()); } @Test(expected = NullValueException.class) public void testSetBorderColorForNullValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("red"); BorderRightColor borderRightColor = new BorderRightColor("green"); BorderBottomColor borderBottomColor = new BorderBottomColor("blue"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); try { borderColor.setBorderColor(null, null, null, null); } catch (NullValueException e) { try { borderColor.setBorderColor(null, borderRightColor, borderBottomColor, borderLeftColor); } catch (NullValueException e2) { try { borderColor.setBorderColor(borderTopColor, null, borderBottomColor, borderLeftColor); } catch (NullValueException e3) { try { borderColor.setBorderColor(borderTopColor, borderRightColor, null, borderLeftColor); } catch (NullValueException e4) { try { borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, null); } catch (NullValueException e5) { throw e4; } } } } } } @Test(expected = InvalidValueException.class) public void testSetBorderColorForInvalidValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("red"); BorderRightColor borderRightColor = new BorderRightColor("green"); BorderBottomColor borderBottomColor = new BorderBottomColor("blue"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); try { borderTopColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e) { try { borderRightColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e2) { try { borderBottomColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e3) { try { borderLeftColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e4) { throw e4; } } } } } @Test(expected = InvalidValueException.class) public void testSetBorderColorForRuntimeInvalidValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("orange"); BorderRightColor borderRightColor = new BorderRightColor("red"); BorderBottomColor borderBottomColor = new BorderBottomColor("green"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); try { borderTopColor.setAsInherit(); } catch (InvalidValueException e) { try { borderRightColor.setAsInherit(); } catch (InvalidValueException e2) { try { borderBottomColor.setAsInherit(); } catch (InvalidValueException e3) { try { borderLeftColor.setAsInherit(); } catch (InvalidValueException e4) { throw e4; } } } } } @Test public void testSetBorderColorForRuntimeInvalidValuesWithRollback() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("orange"); BorderRightColor borderRightColor = new BorderRightColor("red"); BorderBottomColor borderBottomColor = new BorderBottomColor("green"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); { try { borderTopColor.setAsInitial(); } catch (InvalidValueException e) { assertEquals("orange", borderTopColor.getCssValue()); } try { borderRightColor.setAsInitial(); } catch (InvalidValueException e2) { assertEquals("red", borderRightColor.getCssValue()); } try { borderBottomColor.setAsInitial(); } catch (InvalidValueException e3) { assertEquals("green", borderBottomColor.getCssValue()); } try { borderLeftColor.setAsInitial(); } catch (InvalidValueException e4) { assertEquals("yellow", borderLeftColor.getCssValue()); } } { try { borderTopColor.setCssValue("inherit"); } catch (InvalidValueException e) { assertEquals("orange", borderTopColor.getCssValue()); } try { borderRightColor.setCssValue("inherit"); } catch (InvalidValueException e2) { assertEquals("red", borderRightColor.getCssValue()); } try { borderBottomColor.setCssValue("inherit"); } catch (InvalidValueException e3) { assertEquals("green", borderBottomColor.getCssValue()); } try { borderLeftColor.setCssValue("inherit"); } catch (InvalidValueException e4) { assertEquals("yellow", borderLeftColor.getCssValue()); } } } @Test public void testGetBorderColor() { { BorderColor borderColor = new BorderColor("red green blue yellow"); assertEquals("red green blue yellow", borderColor.getCssValue()); final BorderTopColor borderTopColor = borderColor.getBorderTopColor(); final BorderRightColor borderRightColor = borderColor.getBorderRightColor(); final BorderBottomColor borderBottomColor = borderColor.getBorderBottomColor(); final BorderLeftColor borderLeftColor = borderColor.getBorderLeftColor(); assertNotNull(borderTopColor); assertNotNull(borderRightColor); assertNotNull(borderBottomColor); assertNotNull(borderLeftColor); assertTrue(borderTopColor.isAlreadyInUse()); assertTrue(borderRightColor.isAlreadyInUse()); assertTrue(borderBottomColor.isAlreadyInUse()); assertTrue(borderLeftColor.isAlreadyInUse()); assertEquals("red", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("blue", borderBottomColor.getCssValue()); assertEquals("yellow", borderLeftColor.getCssValue()); assertEquals("red green blue yellow", borderColor.getCssValue()); borderTopColor.setCssValue("yellow"); assertEquals("yellow green blue yellow", borderColor.getCssValue()); borderRightColor.setCssValue("black"); assertEquals("yellow black blue yellow", borderColor.getCssValue()); borderBottomColor.setCssValue("silver"); assertEquals("yellow black silver yellow", borderColor.getCssValue()); borderLeftColor.setCssValue("red"); assertEquals("yellow black silver red", borderColor.getCssValue()); borderColor.setCssValue("red green blue"); assertEquals("red", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("blue", borderBottomColor.getCssValue()); assertEquals("green", borderLeftColor.getCssValue()); borderColor.setCssValue("green blue"); assertEquals("green", borderTopColor.getCssValue()); assertEquals("blue", borderRightColor.getCssValue()); assertEquals("green", borderBottomColor.getCssValue()); assertEquals("blue", borderLeftColor.getCssValue()); borderColor.setCssValue("green"); assertEquals("green", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("green", borderBottomColor.getCssValue()); assertEquals("green", borderLeftColor.getCssValue()); borderTopColor.setCssValue("white"); borderBottomColor.setCssValue("white"); borderRightColor.setCssValue("blue"); borderLeftColor.setCssValue("blue"); assertEquals("white blue", borderColor.getCssValue()); borderTopColor.setCssValue("red"); borderBottomColor.setCssValue("green"); borderRightColor.setCssValue("blue"); borderLeftColor.setCssValue("blue"); assertEquals("red blue green", borderColor.getCssValue()); borderTopColor.setCssValue("white"); borderBottomColor.setCssValue("white"); borderRightColor.setCssValue("white"); borderLeftColor.setCssValue("white"); assertEquals("white", borderColor.getCssValue()); borderColor.setAsTransparent(); assertNull(borderColor.getBorderTopColor()); assertNull(borderColor.getBorderRightColor()); assertNull(borderColor.getBorderBottomColor()); assertNull(borderColor.getBorderLeftColor()); assertFalse(borderTopColor.isAlreadyInUse()); assertFalse(borderRightColor.isAlreadyInUse()); assertFalse(borderBottomColor.isAlreadyInUse()); assertFalse(borderLeftColor.isAlreadyInUse()); } } @Test public void testIsValid() { { final boolean valid = BorderColor.isValid("green"); assertTrue(valid); final boolean invalid = BorderColor.isValid("blu"); assertFalse(invalid); } { final boolean valid = BorderColor.isValid("GREEN"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("WHITE"); assertTrue(valid); final boolean invalid = BorderColor.isValid("dfd"); assertFalse(invalid); } { final boolean valid = BorderColor.isValid("TRANSPARENT"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("transparent"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue transparent"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue white"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue dfdf"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("dfdf red green blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red dfdf green blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green -dfdf blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue dfdf"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue initial"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue inherit"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue INITIAL"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue INHERIT"); assertFalse(valid); } } }
UTF-8
Java
16,716
java
BorderColorTest.java
Java
[ { "context": "ork.wffweb.NullValueException;\n\n/**\n * \n * @author WFF\n * @since 1.0.0\n */\npublic class BorderColorTest ", "end": 1031, "score": 0.9995605945587158, "start": 1028, "tag": "USERNAME", "value": "WFF" } ]
null
[]
/* * Copyright 2014-2021 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.css; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.NullValueException; /** * * @author WFF * @since 1.0.0 */ public class BorderColorTest { @Test public void testBorderColor() { BorderColor borderColor = new BorderColor(); assertEquals(BorderColor.INITIAL, borderColor.getCssValue()); } @Test public void testBorderColorString() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testBorderColorBorderColor() { BorderColor borderColor = new BorderColor("#0000ff"); BorderColor borderColor1 = new BorderColor(borderColor); assertEquals("#0000ff", borderColor1.getCssValue()); } @Test public void testSetValue() { BorderColor borderColor = new BorderColor(); borderColor.setValue("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testGetCssName() { BorderColor borderColor = new BorderColor(); assertEquals(CssNameConstants.BORDER_COLOR, borderColor.getCssName()); } @Test public void testGetCssValue() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testToString() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals(CssNameConstants.BORDER_COLOR + ": #0000ff", borderColor.toString()); } @Test public void testGetValue() { BorderColor borderColor = new BorderColor("#0000ff"); assertEquals("#0000ff", borderColor.getValue()); } @Test public void testSetCssValueString() { BorderColor borderColor = new BorderColor(); borderColor.setCssValue("#0000ff"); assertEquals("#0000ff", borderColor.getCssValue()); } @Test public void testSetAsInitial() { BorderColor borderColor = new BorderColor(); borderColor.setAsInitial(); assertEquals(BorderColor.INITIAL, borderColor.getCssValue()); } @Test public void testSetAsInherit() { BorderColor borderColor = new BorderColor(); borderColor.setAsInherit(); assertEquals(BorderColor.INHERIT, borderColor.getCssValue()); } @Test public void testSetAsTransparent() { BorderColor borderColor = new BorderColor(); borderColor.setAsTransparent(); assertEquals(BorderColor.TRANSPARENT, borderColor.getCssValue()); } @Test(expected = NullValueException.class) public void testSetBorderColorForNullValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("red"); BorderRightColor borderRightColor = new BorderRightColor("green"); BorderBottomColor borderBottomColor = new BorderBottomColor("blue"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); try { borderColor.setBorderColor(null, null, null, null); } catch (NullValueException e) { try { borderColor.setBorderColor(null, borderRightColor, borderBottomColor, borderLeftColor); } catch (NullValueException e2) { try { borderColor.setBorderColor(borderTopColor, null, borderBottomColor, borderLeftColor); } catch (NullValueException e3) { try { borderColor.setBorderColor(borderTopColor, borderRightColor, null, borderLeftColor); } catch (NullValueException e4) { try { borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, null); } catch (NullValueException e5) { throw e4; } } } } } } @Test(expected = InvalidValueException.class) public void testSetBorderColorForInvalidValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("red"); BorderRightColor borderRightColor = new BorderRightColor("green"); BorderBottomColor borderBottomColor = new BorderBottomColor("blue"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); try { borderTopColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e) { try { borderRightColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e2) { try { borderBottomColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e3) { try { borderLeftColor.setAsInitial(); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); } catch (InvalidValueException e4) { throw e4; } } } } } @Test(expected = InvalidValueException.class) public void testSetBorderColorForRuntimeInvalidValues() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("orange"); BorderRightColor borderRightColor = new BorderRightColor("red"); BorderBottomColor borderBottomColor = new BorderBottomColor("green"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); try { borderTopColor.setAsInherit(); } catch (InvalidValueException e) { try { borderRightColor.setAsInherit(); } catch (InvalidValueException e2) { try { borderBottomColor.setAsInherit(); } catch (InvalidValueException e3) { try { borderLeftColor.setAsInherit(); } catch (InvalidValueException e4) { throw e4; } } } } } @Test public void testSetBorderColorForRuntimeInvalidValuesWithRollback() { BorderColor borderColor = new BorderColor(); BorderTopColor borderTopColor = new BorderTopColor("orange"); BorderRightColor borderRightColor = new BorderRightColor("red"); BorderBottomColor borderBottomColor = new BorderBottomColor("green"); BorderLeftColor borderLeftColor = new BorderLeftColor("yellow"); borderColor.setBorderColor(borderTopColor, borderRightColor, borderBottomColor, borderLeftColor); { try { borderTopColor.setAsInitial(); } catch (InvalidValueException e) { assertEquals("orange", borderTopColor.getCssValue()); } try { borderRightColor.setAsInitial(); } catch (InvalidValueException e2) { assertEquals("red", borderRightColor.getCssValue()); } try { borderBottomColor.setAsInitial(); } catch (InvalidValueException e3) { assertEquals("green", borderBottomColor.getCssValue()); } try { borderLeftColor.setAsInitial(); } catch (InvalidValueException e4) { assertEquals("yellow", borderLeftColor.getCssValue()); } } { try { borderTopColor.setCssValue("inherit"); } catch (InvalidValueException e) { assertEquals("orange", borderTopColor.getCssValue()); } try { borderRightColor.setCssValue("inherit"); } catch (InvalidValueException e2) { assertEquals("red", borderRightColor.getCssValue()); } try { borderBottomColor.setCssValue("inherit"); } catch (InvalidValueException e3) { assertEquals("green", borderBottomColor.getCssValue()); } try { borderLeftColor.setCssValue("inherit"); } catch (InvalidValueException e4) { assertEquals("yellow", borderLeftColor.getCssValue()); } } } @Test public void testGetBorderColor() { { BorderColor borderColor = new BorderColor("red green blue yellow"); assertEquals("red green blue yellow", borderColor.getCssValue()); final BorderTopColor borderTopColor = borderColor.getBorderTopColor(); final BorderRightColor borderRightColor = borderColor.getBorderRightColor(); final BorderBottomColor borderBottomColor = borderColor.getBorderBottomColor(); final BorderLeftColor borderLeftColor = borderColor.getBorderLeftColor(); assertNotNull(borderTopColor); assertNotNull(borderRightColor); assertNotNull(borderBottomColor); assertNotNull(borderLeftColor); assertTrue(borderTopColor.isAlreadyInUse()); assertTrue(borderRightColor.isAlreadyInUse()); assertTrue(borderBottomColor.isAlreadyInUse()); assertTrue(borderLeftColor.isAlreadyInUse()); assertEquals("red", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("blue", borderBottomColor.getCssValue()); assertEquals("yellow", borderLeftColor.getCssValue()); assertEquals("red green blue yellow", borderColor.getCssValue()); borderTopColor.setCssValue("yellow"); assertEquals("yellow green blue yellow", borderColor.getCssValue()); borderRightColor.setCssValue("black"); assertEquals("yellow black blue yellow", borderColor.getCssValue()); borderBottomColor.setCssValue("silver"); assertEquals("yellow black silver yellow", borderColor.getCssValue()); borderLeftColor.setCssValue("red"); assertEquals("yellow black silver red", borderColor.getCssValue()); borderColor.setCssValue("red green blue"); assertEquals("red", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("blue", borderBottomColor.getCssValue()); assertEquals("green", borderLeftColor.getCssValue()); borderColor.setCssValue("green blue"); assertEquals("green", borderTopColor.getCssValue()); assertEquals("blue", borderRightColor.getCssValue()); assertEquals("green", borderBottomColor.getCssValue()); assertEquals("blue", borderLeftColor.getCssValue()); borderColor.setCssValue("green"); assertEquals("green", borderTopColor.getCssValue()); assertEquals("green", borderRightColor.getCssValue()); assertEquals("green", borderBottomColor.getCssValue()); assertEquals("green", borderLeftColor.getCssValue()); borderTopColor.setCssValue("white"); borderBottomColor.setCssValue("white"); borderRightColor.setCssValue("blue"); borderLeftColor.setCssValue("blue"); assertEquals("white blue", borderColor.getCssValue()); borderTopColor.setCssValue("red"); borderBottomColor.setCssValue("green"); borderRightColor.setCssValue("blue"); borderLeftColor.setCssValue("blue"); assertEquals("red blue green", borderColor.getCssValue()); borderTopColor.setCssValue("white"); borderBottomColor.setCssValue("white"); borderRightColor.setCssValue("white"); borderLeftColor.setCssValue("white"); assertEquals("white", borderColor.getCssValue()); borderColor.setAsTransparent(); assertNull(borderColor.getBorderTopColor()); assertNull(borderColor.getBorderRightColor()); assertNull(borderColor.getBorderBottomColor()); assertNull(borderColor.getBorderLeftColor()); assertFalse(borderTopColor.isAlreadyInUse()); assertFalse(borderRightColor.isAlreadyInUse()); assertFalse(borderBottomColor.isAlreadyInUse()); assertFalse(borderLeftColor.isAlreadyInUse()); } } @Test public void testIsValid() { { final boolean valid = BorderColor.isValid("green"); assertTrue(valid); final boolean invalid = BorderColor.isValid("blu"); assertFalse(invalid); } { final boolean valid = BorderColor.isValid("GREEN"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("WHITE"); assertTrue(valid); final boolean invalid = BorderColor.isValid("dfd"); assertFalse(invalid); } { final boolean valid = BorderColor.isValid("TRANSPARENT"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("transparent"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue transparent"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue white"); assertTrue(valid); } { final boolean valid = BorderColor.isValid("red green blue dfdf"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("dfdf red green blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red dfdf green blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green -dfdf blue"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue dfdf"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue initial"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue inherit"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue INITIAL"); assertFalse(valid); } { final boolean valid = BorderColor.isValid("red green blue INHERIT"); assertFalse(valid); } } }
16,716
0.595059
0.589555
436
37.339451
27.660614
121
false
false
0
0
0
0
0
0
0.646789
false
false
12
1ecc5e1fa1b0e546bb38fd6141e51ca09e4bca5a
4,784,593,573,321
0cb511988d126fdbb730902dc728e3983ff032d0
/app/src/main/java/com/lightheart/sphr/doctor/module/home/presenter/ClinicalRecruitPresenter.java
1016c188c2c9550b420da9235e781b8a866d92a7
[]
no_license
hongliang312/sphr-doctor-android
https://github.com/hongliang312/sphr-doctor-android
0b06745eff9aab063b1344d241f4447a075c77db
2eb8d816b37e65879b732bf621993d31e69520c0
refs/heads/master
2020-03-20T10:21:26.182000
2020-01-07T10:42:59
2020-01-07T10:42:59
137,367,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lightheart.sphr.doctor.module.home.presenter; import com.blankj.utilcode.util.SPUtils; import com.lightheart.sphr.doctor.app.Constant; import com.lightheart.sphr.doctor.app.LoadType; import com.lightheart.sphr.doctor.base.BasePresenter; import com.lightheart.sphr.doctor.bean.ClinicalDetailParam; import com.lightheart.sphr.doctor.bean.ClinicalRecruitModel; import com.lightheart.sphr.doctor.bean.ClinicalSearchParam; import com.lightheart.sphr.doctor.bean.DataResponse; import com.lightheart.sphr.doctor.bean.DocContractRequestParams; import com.lightheart.sphr.doctor.bean.DoctorBean; import com.lightheart.sphr.doctor.bean.HomePageInfo; import com.lightheart.sphr.doctor.bean.LoginSuccess; import com.lightheart.sphr.doctor.module.home.contract.ClinicalRecruitContract; import com.lightheart.sphr.doctor.net.ApiService; import com.lightheart.sphr.doctor.net.RetrofitManager; import com.lightheart.sphr.doctor.utils.RxSchedulers; import java.util.List; import javax.inject.Inject; import io.reactivex.functions.Consumer; /** * Created by fucp on 2018-5-17. * Description : */ public class ClinicalRecruitPresenter extends BasePresenter<ClinicalRecruitContract.View> implements ClinicalRecruitContract.Presenter { private boolean mIsRefresh; private ClinicalSearchParam param = new ClinicalSearchParam(); @Inject public ClinicalRecruitPresenter() { this.mIsRefresh = true; param.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); } @Override public void loadClinicals() { RetrofitManager.create(ApiService.class) .getAllClinicalTrial(new LoginSuccess()) .compose(RxSchedulers.<DataResponse<ClinicalRecruitModel>>applySchedulers()) .compose(mView.<DataResponse<ClinicalRecruitModel>>bindToLife()) .subscribe(new Consumer<DataResponse<ClinicalRecruitModel>>() { @Override public void accept(DataResponse<ClinicalRecruitModel> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinical(response.getContent().clinicalTrials, loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void loadClinicalRecruitDetail(int id) { ClinicalDetailParam clinicalDetailParam = new ClinicalDetailParam(); clinicalDetailParam.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); clinicalDetailParam.id = id; RetrofitManager.create(ApiService.class) .getctrDetails(clinicalDetailParam) .compose(RxSchedulers.<DataResponse<HomePageInfo.ClinicalTrialListBean>>applySchedulers()) .compose(mView.<DataResponse<HomePageInfo.ClinicalTrialListBean>>bindToLife()) .subscribe(new Consumer<DataResponse<HomePageInfo.ClinicalTrialListBean>>() { @Override public void accept(DataResponse<HomePageInfo.ClinicalTrialListBean> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinicalRecruitDetail(response.getContent(), loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void applyClinicalRecruit(int id) { ClinicalDetailParam param = new ClinicalDetailParam(); param.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); param.id = id; RetrofitManager.create(ApiService.class) .applyClinical(param) .compose(RxSchedulers.<DataResponse<Object>>applySchedulers()) .compose(mView.<DataResponse<Object>>bindToLife()) .subscribe(new Consumer<DataResponse<Object>>() { @Override public void accept(DataResponse<Object> response) throws Exception { if (response.getResultcode() == 200) { mView.successApply(); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void searchClinical(String s) { param.keyWord = s; RetrofitManager.create(ApiService.class) .searchClinicalTrial(param) .compose(RxSchedulers.<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>applySchedulers()) .compose(mView.<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>bindToLife()) .subscribe(new Consumer<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>() { @Override public void accept(DataResponse<List<HomePageInfo.ClinicalTrialListBean>> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinical(response.getContent(), loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void loadDoctorInfo() { DocContractRequestParams params = new DocContractRequestParams(); params.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); RetrofitManager.create(ApiService.class) .getDocInfo(params) .compose(RxSchedulers.<DataResponse<DoctorBean>>applySchedulers()) .compose(mView.<DataResponse<DoctorBean>>bindToLife()) .subscribe(new Consumer<DataResponse<DoctorBean>>() { @Override public void accept(DataResponse<DoctorBean> response) throws Exception { if (response.getResultcode() == 200) { mView.setDoctorInfo(response.getContent()); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } }
UTF-8
Java
8,087
java
ClinicalRecruitPresenter.java
Java
[ { "context": "o.reactivex.functions.Consumer;\n\n/**\n * Created by fucp on 2018-5-17.\n * Description :\n */\n\npublic class ", "end": 1062, "score": 0.9995924830436707, "start": 1058, "tag": "USERNAME", "value": "fucp" } ]
null
[]
package com.lightheart.sphr.doctor.module.home.presenter; import com.blankj.utilcode.util.SPUtils; import com.lightheart.sphr.doctor.app.Constant; import com.lightheart.sphr.doctor.app.LoadType; import com.lightheart.sphr.doctor.base.BasePresenter; import com.lightheart.sphr.doctor.bean.ClinicalDetailParam; import com.lightheart.sphr.doctor.bean.ClinicalRecruitModel; import com.lightheart.sphr.doctor.bean.ClinicalSearchParam; import com.lightheart.sphr.doctor.bean.DataResponse; import com.lightheart.sphr.doctor.bean.DocContractRequestParams; import com.lightheart.sphr.doctor.bean.DoctorBean; import com.lightheart.sphr.doctor.bean.HomePageInfo; import com.lightheart.sphr.doctor.bean.LoginSuccess; import com.lightheart.sphr.doctor.module.home.contract.ClinicalRecruitContract; import com.lightheart.sphr.doctor.net.ApiService; import com.lightheart.sphr.doctor.net.RetrofitManager; import com.lightheart.sphr.doctor.utils.RxSchedulers; import java.util.List; import javax.inject.Inject; import io.reactivex.functions.Consumer; /** * Created by fucp on 2018-5-17. * Description : */ public class ClinicalRecruitPresenter extends BasePresenter<ClinicalRecruitContract.View> implements ClinicalRecruitContract.Presenter { private boolean mIsRefresh; private ClinicalSearchParam param = new ClinicalSearchParam(); @Inject public ClinicalRecruitPresenter() { this.mIsRefresh = true; param.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); } @Override public void loadClinicals() { RetrofitManager.create(ApiService.class) .getAllClinicalTrial(new LoginSuccess()) .compose(RxSchedulers.<DataResponse<ClinicalRecruitModel>>applySchedulers()) .compose(mView.<DataResponse<ClinicalRecruitModel>>bindToLife()) .subscribe(new Consumer<DataResponse<ClinicalRecruitModel>>() { @Override public void accept(DataResponse<ClinicalRecruitModel> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinical(response.getContent().clinicalTrials, loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void loadClinicalRecruitDetail(int id) { ClinicalDetailParam clinicalDetailParam = new ClinicalDetailParam(); clinicalDetailParam.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); clinicalDetailParam.id = id; RetrofitManager.create(ApiService.class) .getctrDetails(clinicalDetailParam) .compose(RxSchedulers.<DataResponse<HomePageInfo.ClinicalTrialListBean>>applySchedulers()) .compose(mView.<DataResponse<HomePageInfo.ClinicalTrialListBean>>bindToLife()) .subscribe(new Consumer<DataResponse<HomePageInfo.ClinicalTrialListBean>>() { @Override public void accept(DataResponse<HomePageInfo.ClinicalTrialListBean> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinicalRecruitDetail(response.getContent(), loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void applyClinicalRecruit(int id) { ClinicalDetailParam param = new ClinicalDetailParam(); param.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); param.id = id; RetrofitManager.create(ApiService.class) .applyClinical(param) .compose(RxSchedulers.<DataResponse<Object>>applySchedulers()) .compose(mView.<DataResponse<Object>>bindToLife()) .subscribe(new Consumer<DataResponse<Object>>() { @Override public void accept(DataResponse<Object> response) throws Exception { if (response.getResultcode() == 200) { mView.successApply(); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void searchClinical(String s) { param.keyWord = s; RetrofitManager.create(ApiService.class) .searchClinicalTrial(param) .compose(RxSchedulers.<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>applySchedulers()) .compose(mView.<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>bindToLife()) .subscribe(new Consumer<DataResponse<List<HomePageInfo.ClinicalTrialListBean>>>() { @Override public void accept(DataResponse<List<HomePageInfo.ClinicalTrialListBean>> response) throws Exception { if (response.getResultcode() == 200) { int loadType = mIsRefresh ? LoadType.TYPE_REFRESH_SUCCESS : LoadType.TYPE_LOAD_MORE_SUCCESS; mView.setClinical(response.getContent(), loadType); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } @Override public void loadDoctorInfo() { DocContractRequestParams params = new DocContractRequestParams(); params.duid = SPUtils.getInstance(Constant.SHARED_NAME).getInt(Constant.USER_KEY); RetrofitManager.create(ApiService.class) .getDocInfo(params) .compose(RxSchedulers.<DataResponse<DoctorBean>>applySchedulers()) .compose(mView.<DataResponse<DoctorBean>>bindToLife()) .subscribe(new Consumer<DataResponse<DoctorBean>>() { @Override public void accept(DataResponse<DoctorBean> response) throws Exception { if (response.getResultcode() == 200) { mView.setDoctorInfo(response.getContent()); } else { mView.showFaild(String.valueOf(response.getResultmsg())); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mView.showFaild(throwable.getMessage()); } }); } }
8,087
0.592927
0.590207
169
46.85207
32.327404
136
false
false
0
0
0
0
0
0
0.378698
false
false
12