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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
049a5dc48e32842dde5d2a9e646cea6203f60b54 | 35,442,070,161,485 | f777322b82473aa6beb6bde22a8df38cfbea4077 | /SSM/src/ssm/util/CmdException.java | b6f70e459c2049edd148d88d72d20b982062e079 | [] | no_license | scalpovich/ssm-1 | https://github.com/scalpovich/ssm-1 | 1ececfb0b6cfdde2aa7992228b55c3f7546c8b30 | eb0a2c03c2102a375616f4481ed85fb9f4fecb25 | refs/heads/master | 2022-12-04T16:11:03.449000 | 2020-08-31T07:46:49 | 2020-08-31T07:46:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ssm.util;
public class CmdException extends Exception {
public CmdException(String string) {
super(string);
}
private static final long serialVersionUID = 1L;
}
| UTF-8 | Java | 189 | java | CmdException.java | Java | [] | null | [] | package ssm.util;
public class CmdException extends Exception {
public CmdException(String string) {
super(string);
}
private static final long serialVersionUID = 1L;
}
| 189 | 0.708995 | 0.703704 | 11 | 15.181818 | 18.609959 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 2 |
08314405d3f7ac3d5b94bdee8494b710ef7b7480 | 15,848,429,342,132 | efd638c93ad741380ada689bd3c4dfb397cce8dd | /app/src/main/java/com/knwedu/ourschool/model/StudentData.java | 21d8c6cb7cee63f1d5bfe86684fa2ff78c2a8b4b | [] | no_license | raisahab-ritwik/MY_CPS | https://github.com/raisahab-ritwik/MY_CPS | fa6d69bf99aa1f6976318f767aa5e8a0aff3b6cf | eeb74e5604498d4d309846e03304fb9f30700800 | refs/heads/master | 2020-03-12T06:56:59.658000 | 2018-04-21T17:33:32 | 2018-04-21T17:33:32 | 130,496,725 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.knwedu.ourschool.model;
import org.json.JSONObject;
/**
* Created by ddasgupta on 25/03/17.
*/
public class StudentData {
public String name;
public String id;
public String roll_no;
public String user_code;
public String registration_no;
public JSONObject object;
public StudentData(JSONObject c){
this.object = c;
try {
this.name = c.getString("name").trim();
this.id = c.getString("id").trim();
this.roll_no = c.getString("roll_no").trim();
this.user_code = c.getString("user_code").trim();
this.registration_no = c.getString("registration_no").trim();
}catch (Exception e){
}
}
}
| UTF-8 | Java | 732 | java | StudentData.java | Java | [
{
"context": "l;\n\nimport org.json.JSONObject;\n\n/**\n * Created by ddasgupta on 25/03/17.\n */\n\npublic class StudentData {\n ",
"end": 93,
"score": 0.9994113445281982,
"start": 84,
"tag": "USERNAME",
"value": "ddasgupta"
}
] | null | [] | package com.knwedu.ourschool.model;
import org.json.JSONObject;
/**
* Created by ddasgupta on 25/03/17.
*/
public class StudentData {
public String name;
public String id;
public String roll_no;
public String user_code;
public String registration_no;
public JSONObject object;
public StudentData(JSONObject c){
this.object = c;
try {
this.name = c.getString("name").trim();
this.id = c.getString("id").trim();
this.roll_no = c.getString("roll_no").trim();
this.user_code = c.getString("user_code").trim();
this.registration_no = c.getString("registration_no").trim();
}catch (Exception e){
}
}
}
| 732 | 0.590164 | 0.581967 | 34 | 20.529411 | 20.445387 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 2 |
a53d008305a60cc188a4cf28970c095b7576b77e | 1,649,267,477,539 | 46c307e23f572e7a2062a804b738c868bcfcf8bb | /src/Utility.java | 8fa12af7a85bde6d31ff99af9caf6c4c53c3cdfb | [] | no_license | Om1938/Om1938-Makkajai-Dev-challenge-task-omprakash-das | https://github.com/Om1938/Om1938-Makkajai-Dev-challenge-task-omprakash-das | 15872f68a7377933233697449cf2d75b00a4f569 | cdfd9fb6fe8cd90235d4a735c3c42e66e3744a3e | refs/heads/master | 2023-05-30T09:34:00.625000 | 2021-06-16T16:09:49 | 2021-06-16T16:09:49 | 376,474,053 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Utility {
private Utility() {
throw new IllegalStateException("Utility class");
}
/**
* Utility function to format currency values
*
* @param value
* @return Formatted string with decimal precision of 2
*/
public static String format(float value) {
return String.format("%.2f", value);
}
}
| UTF-8 | Java | 367 | java | Utility.java | Java | [] | null | [] | public class Utility {
private Utility() {
throw new IllegalStateException("Utility class");
}
/**
* Utility function to format currency values
*
* @param value
* @return Formatted string with decimal precision of 2
*/
public static String format(float value) {
return String.format("%.2f", value);
}
}
| 367 | 0.607629 | 0.60218 | 16 | 21.9375 | 20.998419 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 2 |
b2942295b7d3909e8dffa6edc162a237609209df | 13,365,938,288,532 | 2fadba5ac661a9d0ef89679b2b91e0c4db43a302 | /vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/MetadataApiExpectTest.java | 36e50e37fc328f9812772f55ed4b2dba461e6bf7 | [
"Apache-2.0"
] | permissive | cloudsigma/jclouds-labs | https://github.com/cloudsigma/jclouds-labs | 9fadb356c5a6ac32eb393921889f7844767f5867 | df08c741e74c2856b2f43c0de62edb781ed42b11 | refs/heads/master | 2020-12-25T10:24:08.068000 | 2013-11-20T10:50:24 | 2013-11-21T22:17:45 | 11,307,065 | 1 | 0 | null | true | 2013-08-04T19:27:39 | 2013-07-10T08:53:53 | 2013-08-04T19:27:38 | 2013-08-04T19:27:38 | 19,687 | null | 1 | 0 | Java | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.jclouds.vcloud.director.v1_5.features;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.ANY;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.ERROR;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.METADATA;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.METADATA_ENTRY;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.TASK;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import java.net.URI;
import java.util.TimeZone;
import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorException;
import org.jclouds.vcloud.director.v1_5.domain.Link;
import org.jclouds.vcloud.director.v1_5.domain.Metadata;
import org.jclouds.vcloud.director.v1_5.domain.MetadataEntry;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.internal.VCloudDirectorAdminApiExpectTest;
import org.testng.annotations.Test;
/**
* Tests the request/response behavior of {@link org.jclouds.vcloud.director.v1_5.features.MetadataApi}
*
* @author Adam Lowe
*/
@Test(groups = { "unit", "user" }, testName = "MetadataApiExpectTest")
public class MetadataApiExpectTest extends VCloudDirectorAdminApiExpectTest {
public MetadataApiExpectTest() {
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
}
public void testVappTemplateMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata").acceptMedia(ANY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/metadata.xml", METADATA).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("POST", templateId + "/metadata").xmlFilePayload("/vapptemplate/metadata.xml", METADATA).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build()
).getMetadataApi(uri);
assertNotNull(api);
Metadata metadata = api.get();
assertEquals(metadata, exampleMetadata());
Task task = api.putAll(exampleMetadata());
assertNotNull(task);
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorGetMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata").acceptMedia(ANY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.get();
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorEditMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("POST", templateId + "/metadata").xmlFilePayload("/vapptemplate/metadata.xml", METADATA).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.putAll(exampleMetadata());
}
public void testVappTemplateMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata/12345").acceptMedia(METADATA_ENTRY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("PUT", templateId + "/metadata/12345").xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("DELETE", templateId + "/metadata/12345").acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build()
).getMetadataApi(uri);
assertNotNull(api);
String metadata = api.get("12345");
assertEquals(metadata, "some value");
Task task = api.put("12345", "some value");
assertNotNull(task);
task = api.remove("12345");
assertNotNull(task);
}
public void testErrorGetMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata/12345").acceptMedia(METADATA_ENTRY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error403.xml", ERROR).httpResponseBuilder().statusCode(403).build()).getMetadataApi(uri);
assertNull(api.get("12345"));
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorEditMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("PUT", templateId + "/metadata/12345").xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.put("12345", "some value");
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testRemoveMissingMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("DELETE", templateId + "/metadata/12345").acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error403.xml", ERROR).httpResponseBuilder().statusCode(403).build()).getMetadataApi(uri);
api.remove("12345");
}
private Metadata exampleMetadata() {
return Metadata.builder()
.href(URI.create("https://vcloudbeta.bluelock.com/api/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9/metadata"))
.type("application/vnd.vmware.vcloud.metadata+xml")
.link(Link.builder().href(URI.create("https://vcloudbeta.bluelock.com/api/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9"))
.type("application/vnd.vmware.vcloud.vAppTemplate+xml").rel("up").build())
.entry(MetadataEntry.builder().key("key").value("value").build()).build();
}
}
| UTF-8 | Java | 8,899 | java | MetadataApiExpectTest.java | Java | [
{
"context": ".director.v1_5.features.MetadataApi}\n *\n * @author Adam Lowe\n */\n@Test(groups = { \"unit\", \"user\" }, testName =",
"end": 2032,
"score": 0.9998212456703186,
"start": 2023,
"tag": "NAME",
"value": "Adam Lowe"
}
] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.jclouds.vcloud.director.v1_5.features;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.ANY;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.ERROR;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.METADATA;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.METADATA_ENTRY;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.TASK;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import java.net.URI;
import java.util.TimeZone;
import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorException;
import org.jclouds.vcloud.director.v1_5.domain.Link;
import org.jclouds.vcloud.director.v1_5.domain.Metadata;
import org.jclouds.vcloud.director.v1_5.domain.MetadataEntry;
import org.jclouds.vcloud.director.v1_5.domain.Task;
import org.jclouds.vcloud.director.v1_5.internal.VCloudDirectorAdminApiExpectTest;
import org.testng.annotations.Test;
/**
* Tests the request/response behavior of {@link org.jclouds.vcloud.director.v1_5.features.MetadataApi}
*
* @author <NAME>
*/
@Test(groups = { "unit", "user" }, testName = "MetadataApiExpectTest")
public class MetadataApiExpectTest extends VCloudDirectorAdminApiExpectTest {
public MetadataApiExpectTest() {
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
}
public void testVappTemplateMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata").acceptMedia(ANY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/metadata.xml", METADATA).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("POST", templateId + "/metadata").xmlFilePayload("/vapptemplate/metadata.xml", METADATA).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build()
).getMetadataApi(uri);
assertNotNull(api);
Metadata metadata = api.get();
assertEquals(metadata, exampleMetadata());
Task task = api.putAll(exampleMetadata());
assertNotNull(task);
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorGetMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata").acceptMedia(ANY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.get();
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorEditMetadata() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("POST", templateId + "/metadata").xmlFilePayload("/vapptemplate/metadata.xml", METADATA).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.putAll(exampleMetadata());
}
public void testVappTemplateMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata/12345").acceptMedia(METADATA_ENTRY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("PUT", templateId + "/metadata/12345").xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build(),
new VcloudHttpRequestPrimer().apiCommand("DELETE", templateId + "/metadata/12345").acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/task/task.xml", TASK).httpResponseBuilder().build()
).getMetadataApi(uri);
assertNotNull(api);
String metadata = api.get("12345");
assertEquals(metadata, "some value");
Task task = api.put("12345", "some value");
assertNotNull(task);
task = api.remove("12345");
assertNotNull(task);
}
public void testErrorGetMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("GET", templateId + "/metadata/12345").acceptMedia(METADATA_ENTRY).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error403.xml", ERROR).httpResponseBuilder().statusCode(403).build()).getMetadataApi(uri);
assertNull(api.get("12345"));
}
@Test(expectedExceptions = VCloudDirectorException.class)
public void testErrorEditMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("PUT", templateId + "/metadata/12345").xmlFilePayload("/vapptemplate/metadataValue.xml", METADATA_ENTRY).acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error400.xml", ERROR).httpResponseBuilder().statusCode(400).build()).getMetadataApi(uri);
api.put("12345", "some value");
}
@Test(expectedExceptions = ResourceNotFoundException.class)
public void testRemoveMissingMetadataValue() {
final String templateId = "/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9";
URI uri = URI.create(endpoint + templateId);
MetadataApi api = orderedRequestsSendResponses(loginRequest, sessionResponse,
new VcloudHttpRequestPrimer().apiCommand("DELETE", templateId + "/metadata/12345").acceptMedia(TASK).httpRequestBuilder().build(),
new VcloudHttpResponsePrimer().xmlFilePayload("/vapptemplate/error403.xml", ERROR).httpResponseBuilder().statusCode(403).build()).getMetadataApi(uri);
api.remove("12345");
}
private Metadata exampleMetadata() {
return Metadata.builder()
.href(URI.create("https://vcloudbeta.bluelock.com/api/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9/metadata"))
.type("application/vnd.vmware.vcloud.metadata+xml")
.link(Link.builder().href(URI.create("https://vcloudbeta.bluelock.com/api/vAppTemplate/vappTemplate-ef4415e6-d413-4cbb-9262-f9bbec5f2ea9"))
.type("application/vnd.vmware.vcloud.vAppTemplate+xml").rel("up").build())
.entry(MetadataEntry.builder().key("key").value("value").build()).build();
}
}
| 8,896 | 0.741656 | 0.710979 | 164 | 53.262196 | 50.019493 | 205 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737805 | false | false | 2 |
78a2af1a3ee26efa5d64023421b10fa6b0669be9 | 13,365,938,287,454 | 9c22ae98d1855c2dd547bad146f2348dc4c1c3dc | /java/harry-potter/src/test/java/HarryPotterTest.java | 2d588da02f4f1740bcd9831cc116bdba9654f779 | [
"MIT"
] | permissive | enolive/learning | https://github.com/enolive/learning | 7cb361a31ac716b3fb44dbeab17a6da765f62d75 | da15e2949e6566ffe94b231f3b224e384506baca | refs/heads/master | 2023-01-12T22:33:09.516000 | 2022-09-21T22:17:35 | 2022-09-21T22:17:35 | 65,559,078 | 9 | 4 | MIT | false | 2023-01-09T07:46:52 | 2016-08-12T14:24:20 | 2022-06-01T17:55:59 | 2023-01-09T07:46:52 | 7,962 | 9 | 3 | 113 | Java | false | false | import io.vavr.collection.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.math.BigDecimal;
import java.util.Comparator;
import static org.assertj.core.api.Assertions.assertThat;
class HarryPotterTest {
private static final Comparator<Bundle> BUNDLES_COMPARATOR = Comparator.comparing(Bundle::getNumberOfDistinctBooks)
.thenComparing(Bundle::getCount);
@ParameterizedTest
@CsvSource(value = {
"1, 8.0",
"2, 15.2",
"3, 21.6",
"4, 25.6",
"5, 30.0"
})
void priceGroup(int numberOfBooks, BigDecimal expected) {
assertThat(HarryPotter.getGroupPrice(numberOfBooks)).isEqualByComparingTo(expected);
}
@Test
void getBookSets() {
final var books = List.of(
new Book(1),
new Book(1),
new Book(1),
new Book(2),
new Book(2),
new Book(3));
final var bookSetComparator = Comparator.comparing(BookSet::getVolume)
.thenComparing(BookSet::getCount);
assertThat(HarryPotter.getBookSets(books))
.as("books should be grouped by their volume and sorted by their count ascending")
.usingElementComparator(bookSetComparator)
.containsExactly(
new BookSet(3, 1),
new BookSet(2, 2),
new BookSet(1, 3)
);
}
@Test
void getBundles() {
final var bookSets = List.of(
new BookSet(1, 1),
new BookSet(2, 1),
new BookSet(3, 2),
new BookSet(4, 2)
);
assertThat(HarryPotter.getBundles(bookSets))
.as("book sets should be placed into bundles of distinct books")
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(
new Bundle(2, 1),
new Bundle(4, 1)
);
}
@Test
void adjust() {
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(3, 1));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 1), new Bundle(5, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(4, 2));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 2), new Bundle(5, 2))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(4, 4));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 3), new Bundle(5, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(3, 2), new Bundle(4, 2));
}
@Test
void singleDiscount() {
assertThat(HarryPotter.getPrice(books(1))).isEqualByComparingTo("8.00");
assertThat(HarryPotter.getPrice(books(1, 2))).isEqualByComparingTo("15.20");
assertThat(HarryPotter.getPrice(books(1, 2, 3))).isEqualByComparingTo("21.60");
assertThat(HarryPotter.getPrice(books(1, 2, 3, 4))).isEqualByComparingTo("25.60");
assertThat(HarryPotter.getPrice(books(1, 2, 3, 4, 5))).isEqualByComparingTo("30.00");
}
private List<Book> books(int... volumes) {
return List.ofAll(volumes).map(Book::new);
}
@Test
void multipleDiscount() {
assertThat(HarryPotter.getPrice(books(1, 1, 2, 2))).isEqualByComparingTo("30.40");
assertThat(HarryPotter.getPrice(books(1, 1, 2, 3))).isEqualByComparingTo("29.60");
}
@Test
void edgeCases() {
assertThat(HarryPotter.getPrice(books(1, 1, 2, 2, 3, 3, 4, 5))).isEqualByComparingTo("51.20");
assertThat(HarryPotter.getPrice(books(
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4,
5, 5, 5))).isEqualByComparingTo("111.20");
}
}
| UTF-8 | Java | 4,262 | java | HarryPotterTest.java | Java | [] | null | [] | import io.vavr.collection.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.math.BigDecimal;
import java.util.Comparator;
import static org.assertj.core.api.Assertions.assertThat;
class HarryPotterTest {
private static final Comparator<Bundle> BUNDLES_COMPARATOR = Comparator.comparing(Bundle::getNumberOfDistinctBooks)
.thenComparing(Bundle::getCount);
@ParameterizedTest
@CsvSource(value = {
"1, 8.0",
"2, 15.2",
"3, 21.6",
"4, 25.6",
"5, 30.0"
})
void priceGroup(int numberOfBooks, BigDecimal expected) {
assertThat(HarryPotter.getGroupPrice(numberOfBooks)).isEqualByComparingTo(expected);
}
@Test
void getBookSets() {
final var books = List.of(
new Book(1),
new Book(1),
new Book(1),
new Book(2),
new Book(2),
new Book(3));
final var bookSetComparator = Comparator.comparing(BookSet::getVolume)
.thenComparing(BookSet::getCount);
assertThat(HarryPotter.getBookSets(books))
.as("books should be grouped by their volume and sorted by their count ascending")
.usingElementComparator(bookSetComparator)
.containsExactly(
new BookSet(3, 1),
new BookSet(2, 2),
new BookSet(1, 3)
);
}
@Test
void getBundles() {
final var bookSets = List.of(
new BookSet(1, 1),
new BookSet(2, 1),
new BookSet(3, 2),
new BookSet(4, 2)
);
assertThat(HarryPotter.getBundles(bookSets))
.as("book sets should be placed into bundles of distinct books")
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(
new Bundle(2, 1),
new Bundle(4, 1)
);
}
@Test
void adjust() {
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(3, 1));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 1), new Bundle(5, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(4, 2));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 2), new Bundle(5, 2))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(4, 4));
assertThat(HarryPotter.adjustBundles(List.of(new Bundle(3, 3), new Bundle(5, 1))))
.usingElementComparator(BUNDLES_COMPARATOR)
.containsExactly(new Bundle(3, 2), new Bundle(4, 2));
}
@Test
void singleDiscount() {
assertThat(HarryPotter.getPrice(books(1))).isEqualByComparingTo("8.00");
assertThat(HarryPotter.getPrice(books(1, 2))).isEqualByComparingTo("15.20");
assertThat(HarryPotter.getPrice(books(1, 2, 3))).isEqualByComparingTo("21.60");
assertThat(HarryPotter.getPrice(books(1, 2, 3, 4))).isEqualByComparingTo("25.60");
assertThat(HarryPotter.getPrice(books(1, 2, 3, 4, 5))).isEqualByComparingTo("30.00");
}
private List<Book> books(int... volumes) {
return List.ofAll(volumes).map(Book::new);
}
@Test
void multipleDiscount() {
assertThat(HarryPotter.getPrice(books(1, 1, 2, 2))).isEqualByComparingTo("30.40");
assertThat(HarryPotter.getPrice(books(1, 1, 2, 3))).isEqualByComparingTo("29.60");
}
@Test
void edgeCases() {
assertThat(HarryPotter.getPrice(books(1, 1, 2, 2, 3, 3, 4, 5))).isEqualByComparingTo("51.20");
assertThat(HarryPotter.getPrice(books(
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4,
5, 5, 5))).isEqualByComparingTo("111.20");
}
}
| 4,262 | 0.562177 | 0.526513 | 110 | 37.745453 | 29.972847 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.036364 | false | false | 2 |
44904ba73578bebacbddeb479d5ee8bcbbc1a15e | 20,976,620,297,821 | 816f69d2e46c0e80be3f7ecb96a57ee363f8ead6 | /Zing Mp3/com/facebook/ads/internal/p000i/C0396r.java | 24d15286a21fa6ecef50fc516185a0b334af351f | [] | no_license | vqthanh1412489/ProjectAndroidTemplete | https://github.com/vqthanh1412489/ProjectAndroidTemplete | fcee774758ae527b5068a03333093c24be46efdb | 242795002459451fac3b4c83fa0cf4352645761d | refs/heads/master | 2021-01-21T06:18:50.650000 | 2017-02-26T12:31:15 | 2017-02-26T12:31:15 | 83,206,789 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.ads.internal.p000i;
/* renamed from: com.facebook.ads.internal.i.r */
public interface C0396r {
void m139a(int i);
}
| UTF-8 | Java | 143 | java | C0396r.java | Java | [] | null | [] | package com.facebook.ads.internal.p000i;
/* renamed from: com.facebook.ads.internal.i.r */
public interface C0396r {
void m139a(int i);
}
| 143 | 0.72028 | 0.65035 | 6 | 22.833334 | 18.178894 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
4ece9c173c329d8a9f08515d9e68b1b58c269c34 | 20,976,620,298,025 | 013d7babc7a9067f281934f87f9f119d80aec47b | /app/src/main/java/com/ftx/mvvm_template/views/listeners/NetworkRetryCallback.java | dc47f18606b83eda73ece68b9a6c4896056ae10a | [] | no_license | chiragpatelFTX/MVVM_Architecture | https://github.com/chiragpatelFTX/MVVM_Architecture | b47ac0c9208f14c3ac64f4d79beb274efc4c02ed | 01a560583da6f425c080cd2ffc3f1db61bbbeca6 | refs/heads/master | 2023-01-07T07:07:08.507000 | 2020-11-12T14:12:51 | 2020-11-12T14:12:51 | 224,837,931 | 0 | 3 | null | false | 2020-11-12T14:27:36 | 2019-11-29T11:06:52 | 2020-11-12T14:13:07 | 2020-11-12T14:17:18 | 592 | 0 | 0 | 0 | Java | false | false | package com.ftx.mvvm_template.views.listeners;
/**
* Name : NetworkRetryCallback
*<br> Purpose :Interface to handle the Network Retry Mechanism.
*/
public interface NetworkRetryCallback {
void onNetworkRetry();
}
| UTF-8 | Java | 225 | java | NetworkRetryCallback.java | Java | [] | null | [] | package com.ftx.mvvm_template.views.listeners;
/**
* Name : NetworkRetryCallback
*<br> Purpose :Interface to handle the Network Retry Mechanism.
*/
public interface NetworkRetryCallback {
void onNetworkRetry();
}
| 225 | 0.737778 | 0.737778 | 13 | 16.307692 | 21.250826 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 2 |
3c26e621be1d657b80d4e0fc5a15b695205d3cfa | 24,292,335,043,856 | 0e4ab6a748986a04557924d7e10cdd1529fa92c3 | /database_player/src/main/java/player/Player.java | 6fe18814bd12c34d5e40955e8ca98a742e010e49 | [] | no_license | Gelo2424/ChessGame | https://github.com/Gelo2424/ChessGame | 545c5d543d126488b59aeebcbc7f982dbc83425f | 96d4f2bf8e271a67ce456bfa5e53ee7babe16b50 | refs/heads/master | 2023-08-01T01:19:18.177000 | 2021-09-22T18:52:58 | 2021-09-22T18:52:58 | 409,313,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package player;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import player.enums.ChessboardStyle;
import player.enums.PieceColor;
import player.enums.FiguresStyle;
public abstract class Player {
private PieceColor pieceColor;
private FiguresStyle figuresStyle;
private ChessboardStyle chessboardStyle;
private int score;
public Player(PieceColor pieceColor, FiguresStyle figuresStyle, ChessboardStyle chessboardStyle, int score) {
this.pieceColor = pieceColor;
this.figuresStyle = figuresStyle;
this.chessboardStyle = chessboardStyle;
this.score = score;
}
public PieceColor getPieceColor() {
return pieceColor;
}
public void setPieceColor(PieceColor pieceColor) {
this.pieceColor = pieceColor;
}
public FiguresStyle getPieceDesign() {
return figuresStyle;
}
public void setPieceDesign(FiguresStyle figuresStyle) {
this.figuresStyle = figuresStyle;
}
public ChessboardStyle getBoardDesign() {
return chessboardStyle;
}
public void setBoardDesign(ChessboardStyle chessboardStyle) {
this.chessboardStyle = chessboardStyle;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
return new EqualsBuilder()
.append(score, player.score)
.append(pieceColor, player.pieceColor)
.append(figuresStyle, player.figuresStyle)
.append(chessboardStyle, player.chessboardStyle)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(pieceColor)
.append(figuresStyle)
.append(chessboardStyle)
.append(score)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("pieceColor", pieceColor)
.append("pieceDesign", figuresStyle)
.append("boardDesign", chessboardStyle)
.append("score", score)
.toString();
}
}
| UTF-8 | Java | 2,520 | java | Player.java | Java | [] | null | [] | package player;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import player.enums.ChessboardStyle;
import player.enums.PieceColor;
import player.enums.FiguresStyle;
public abstract class Player {
private PieceColor pieceColor;
private FiguresStyle figuresStyle;
private ChessboardStyle chessboardStyle;
private int score;
public Player(PieceColor pieceColor, FiguresStyle figuresStyle, ChessboardStyle chessboardStyle, int score) {
this.pieceColor = pieceColor;
this.figuresStyle = figuresStyle;
this.chessboardStyle = chessboardStyle;
this.score = score;
}
public PieceColor getPieceColor() {
return pieceColor;
}
public void setPieceColor(PieceColor pieceColor) {
this.pieceColor = pieceColor;
}
public FiguresStyle getPieceDesign() {
return figuresStyle;
}
public void setPieceDesign(FiguresStyle figuresStyle) {
this.figuresStyle = figuresStyle;
}
public ChessboardStyle getBoardDesign() {
return chessboardStyle;
}
public void setBoardDesign(ChessboardStyle chessboardStyle) {
this.chessboardStyle = chessboardStyle;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Player player = (Player) o;
return new EqualsBuilder()
.append(score, player.score)
.append(pieceColor, player.pieceColor)
.append(figuresStyle, player.figuresStyle)
.append(chessboardStyle, player.chessboardStyle)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(pieceColor)
.append(figuresStyle)
.append(chessboardStyle)
.append(score)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("pieceColor", pieceColor)
.append("pieceDesign", figuresStyle)
.append("boardDesign", chessboardStyle)
.append("score", score)
.toString();
}
}
| 2,520 | 0.630159 | 0.627381 | 91 | 26.692308 | 22.02331 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472527 | false | false | 2 |
fb73992bb244d0f5e0f810fe576e9b0c7c7e25c0 | 20,435,454,445,938 | 2944f73577d645c5007834e9717e09572d741535 | /Music_shop/Instrument.java | ac0e1f20b2f7b9fff3c8531630a31cd1b4889bbe | [] | no_license | PolinaEfimova888/JavaLabs | https://github.com/PolinaEfimova888/JavaLabs | 58a71884b662df81b101472496f4e498baf5508d | b2a5825481a7cfb7d8ff803531c51e52c3c37334 | refs/heads/master | 2023-02-01T16:47:32.664000 | 2020-12-03T08:18:02 | 2020-12-03T08:18:02 | 299,289,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zxc;
import java.util.Objects;
abstract class Instrument implements Comparable<Instrument>{
String model;
public Instrument(String model) {
this.model = model;
}
abstract int getPrice();
@Override
public int compareTo(Instrument instrument)
{
if (instrument == null)
return 1;
if (this.getPrice() > instrument.getPrice())
return 1;
else if (this.getPrice() < instrument.getPrice())
return -1;
else return 0;
}
public boolean equals(Instrument instrument) {
return (this.model == instrument.model && this.getPrice()==instrument.getPrice());
}
public void compare(Instrument instrument) {
int k = compareTo(instrument);
if (k == 0){
System.out.println("Инструменты стоят одинаково");
}
else if (k == 1){
System.out.println("Первый инстурмент дороже");
}
else if (k == -1){
System.out.println("Второй инстурмент дороже");
}
}
public void equal(Instrument instrument) {
if (equals(instrument)) {
System.out.println("Одинаковые инструменты");
} else System.out.println("Разные инструменты");
}
}
| UTF-8 | Java | 1,373 | java | Instrument.java | Java | [] | null | [] | package zxc;
import java.util.Objects;
abstract class Instrument implements Comparable<Instrument>{
String model;
public Instrument(String model) {
this.model = model;
}
abstract int getPrice();
@Override
public int compareTo(Instrument instrument)
{
if (instrument == null)
return 1;
if (this.getPrice() > instrument.getPrice())
return 1;
else if (this.getPrice() < instrument.getPrice())
return -1;
else return 0;
}
public boolean equals(Instrument instrument) {
return (this.model == instrument.model && this.getPrice()==instrument.getPrice());
}
public void compare(Instrument instrument) {
int k = compareTo(instrument);
if (k == 0){
System.out.println("Инструменты стоят одинаково");
}
else if (k == 1){
System.out.println("Первый инстурмент дороже");
}
else if (k == -1){
System.out.println("Второй инстурмент дороже");
}
}
public void equal(Instrument instrument) {
if (equals(instrument)) {
System.out.println("Одинаковые инструменты");
} else System.out.println("Разные инструменты");
}
}
| 1,373 | 0.584518 | 0.578989 | 46 | 26.5 | 22.466158 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 2 |
e1f24d1728acda2eea19ad0608171bbcaf889147 | 32,272,384,281,773 | 8e331273dab054b9bad35e60073954c07cd27746 | /src/main/java/com/celfocus/integratedtestsuserservice/dto/InputBody.java | 5972ea27f23f2133b98a2843c3f741f7aba4950b | [] | no_license | leonormadureira/integrated-tests-user-service | https://github.com/leonormadureira/integrated-tests-user-service | 7ab8deedb83488b83dc8dc81cba6980f35b0ea8c | 8be57bc48c1046d6bd7679b8f0dcf4617dc0eb23 | refs/heads/master | 2020-05-04T01:41:49.215000 | 2019-04-10T09:32:41 | 2019-04-10T09:32:41 | 178,911,235 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.celfocus.integratedtestsuserservice.dto;
import lombok.Data;
@Data
public class InputBody {
public Long user_id;
public String first_name;
public String last_name;
public Long nif;
public Long car_id;
}
| UTF-8 | Java | 237 | java | InputBody.java | Java | [] | null | [] | package com.celfocus.integratedtestsuserservice.dto;
import lombok.Data;
@Data
public class InputBody {
public Long user_id;
public String first_name;
public String last_name;
public Long nif;
public Long car_id;
}
| 237 | 0.725738 | 0.725738 | 12 | 18.75 | 14.657905 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 2 |
cd9ffd4e76d0b3504d08fc696d2b74b72c7c1557 | 32,272,384,281,376 | 853ddb19051fec4e053c58679b05d4e4a568319f | /Case.java | 79ec6a0950426c17e61c13caade033fd61ca1873 | [] | no_license | KaenatSYED/Jeu-echecs-java | https://github.com/KaenatSYED/Jeu-echecs-java | 744738bac474b46fb7dcbb1e15a931314132e5e4 | eb1c5a55848838f1ff683be90e9efd074658a0c4 | refs/heads/main | 2023-05-28T21:50:07.432000 | 2021-06-07T10:18:49 | 2021-06-07T10:18:49 | 368,924,007 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Case {
// Declaration des instances
private int ligne;
private int colonne;
private Piece p;
// Getters et Setters
public int getColonne() {
return colonne;
}
public void setColonne(int colonne) {
this.colonne = colonne;
}
public Piece getP() {
return p;
}
public void setP(Piece p) {
this.p = p;
}
public int getLigne() {
return ligne;
}
public void setLigne(int ligne) {
this.ligne = ligne;
}
// Constructeurs champs à champs
public Case(Piece p)
{
this.p = p;
}
public Case(int ligne, int colonne)
{
this.ligne = ligne;
this.colonne = colonne;
}
public Case(int ligne, int colonne, Piece p)
{
this.ligne = ligne;
this.colonne = colonne;
this.p = p;
}
public boolean CaseVide() {
if(this.p!=null)
return false;
return true;
}
public String toString() {
String s;
if(this.CaseVide() == true)
s = "La case est vide";
else
s = "Il y a une pièce sur la case.";
return ("La case est à la ligne "+getLigne()+", et à la colonne "+ getColonne()+". "+s);
}
/** memeColonne, memeLigne, mangerpiece, caseDevant */
public boolean memeColonne(Case a)
{
if(this.getColonne() == a.getColonne())
return true;
return false;
}
public boolean memeLigne(Case a)
{
if(this.getLigne()== a.getLigne())
return true;
return false;
}
public boolean mangerpiece(Case a) {
if(this.getP().getCouleur() != a.getP().getCouleur())
{
if(this.getP().getCouleur()==0)//Blanc
if(a.getLigne()==this.getLigne()+1)
{
if(a.getColonne()==this.getColonne()-1)
return true;
else if (a.getColonne()==this.getColonne()+1)
return true;
}
else
if(a.getLigne()==this.getLigne()-1)
{
if(a.getColonne()==this.getColonne()-1)
return true;
else if (a.getColonne()==this.getColonne()+1)
return true;
}
}
return false;
}
public boolean caseDevant(Case a) {
if(this.getP().getCouleur() == 0)//blanc
if(this.memeColonne(a) && this.getLigne()+1 == a.getLigne())
return true;
else if (this.getP().getCouleur() == 1)
if(this.memeColonne(a) && this.getLigne()-1 == a.getLigne())
return true;
return false;
}
}
| UTF-8 | Java | 2,611 | java | Case.java | Java | [] | null | [] |
public class Case {
// Declaration des instances
private int ligne;
private int colonne;
private Piece p;
// Getters et Setters
public int getColonne() {
return colonne;
}
public void setColonne(int colonne) {
this.colonne = colonne;
}
public Piece getP() {
return p;
}
public void setP(Piece p) {
this.p = p;
}
public int getLigne() {
return ligne;
}
public void setLigne(int ligne) {
this.ligne = ligne;
}
// Constructeurs champs à champs
public Case(Piece p)
{
this.p = p;
}
public Case(int ligne, int colonne)
{
this.ligne = ligne;
this.colonne = colonne;
}
public Case(int ligne, int colonne, Piece p)
{
this.ligne = ligne;
this.colonne = colonne;
this.p = p;
}
public boolean CaseVide() {
if(this.p!=null)
return false;
return true;
}
public String toString() {
String s;
if(this.CaseVide() == true)
s = "La case est vide";
else
s = "Il y a une pièce sur la case.";
return ("La case est à la ligne "+getLigne()+", et à la colonne "+ getColonne()+". "+s);
}
/** memeColonne, memeLigne, mangerpiece, caseDevant */
public boolean memeColonne(Case a)
{
if(this.getColonne() == a.getColonne())
return true;
return false;
}
public boolean memeLigne(Case a)
{
if(this.getLigne()== a.getLigne())
return true;
return false;
}
public boolean mangerpiece(Case a) {
if(this.getP().getCouleur() != a.getP().getCouleur())
{
if(this.getP().getCouleur()==0)//Blanc
if(a.getLigne()==this.getLigne()+1)
{
if(a.getColonne()==this.getColonne()-1)
return true;
else if (a.getColonne()==this.getColonne()+1)
return true;
}
else
if(a.getLigne()==this.getLigne()-1)
{
if(a.getColonne()==this.getColonne()-1)
return true;
else if (a.getColonne()==this.getColonne()+1)
return true;
}
}
return false;
}
public boolean caseDevant(Case a) {
if(this.getP().getCouleur() == 0)//blanc
if(this.memeColonne(a) && this.getLigne()+1 == a.getLigne())
return true;
else if (this.getP().getCouleur() == 1)
if(this.memeColonne(a) && this.getLigne()-1 == a.getLigne())
return true;
return false;
}
}
| 2,611 | 0.521289 | 0.517069 | 128 | 19.359375 | 18.020706 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.648438 | false | false | 2 |
ef54069e80d49785fa3cb89a9ffe37acab7c7dc6 | 34,024,730,962,553 | 92403f744572477322236922313405879262e83b | /lry_admin/src/main/java/com/lanrenyou/admin/controller/msg/AdminMsgController.java | 58670b1a6aeea101007fb2a4936741cb220f28fb | [] | no_license | voovo/lanrenyou | https://github.com/voovo/lanrenyou | 2572badb0232a4da1caa5365dc023aa9b95af047 | 1b6676b7d0085222695913349b7b19cdc2fa2fc3 | refs/heads/master | 2021-06-16T00:26:19.299000 | 2017-04-13T16:04:54 | 2017-04-13T16:04:54 | 20,763,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lanrenyou.admin.controller.msg;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mybatis.framework.core.support.PageIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.lanrenyou.admin.controller.base.BaseController;
import com.lanrenyou.letter.model.PrivateLetter;
import com.lanrenyou.letter.service.IPrivateLetterService;
import com.lanrenyou.user.model.UserInfo;
import com.lanrenyou.user.service.IUserInfoService;
@Controller
@RequestMapping("/msg")
public class AdminMsgController extends BaseController {
@Autowired
private IPrivateLetterService privateLetterService;
@Autowired
private IUserInfoService userInfoService;
@RequestMapping(value="/list")
public ModelAndView travelList(
@RequestParam(value="queryUid",required=false, defaultValue="-1") Integer queryUid,
@RequestParam(value="pageNo",required=false, defaultValue="1") int pageNo,
@RequestParam(value="pageSize",required=false, defaultValue="10") int pageSize
){
ModelAndView mav = new ModelAndView();
mav.setViewName("/admin/msg/letter_list");
mav.addObject("queryUid", queryUid);
mav.addObject("pageNo", pageNo);
if(null == queryUid){
queryUid = -1;
}
PageIterator<Map<String, Object>> pageIter = privateLetterService.pageQueryByUid(queryUid, pageNo, pageSize);
mav.addObject("pageIter", pageIter);
if(null != pageIter && pageIter.getData() != null){
Set<Integer> uidSet = new HashSet<Integer>();
for(Map<String, Object> map : pageIter.getData()){
Integer senderUid = (Integer) map.get("sender_uid");
if(null != senderUid){
uidSet.add(senderUid);
}
Integer receiverUid = (Integer) map.get("receiver_uid");
if(null != receiverUid){
uidSet.add(receiverUid);
}
}
Map<Integer, UserInfo> userInfoMap = userInfoService.getUserInfoMapByUidList(new ArrayList<Integer>(uidSet));
mav.addObject("userInfoMap", userInfoMap);
}
return mav;
}
@RequestMapping(value="/showMsg")
public ModelAndView showMsgBetweenUidAAndUidB(
@RequestParam(value="senderUid",required=true) Integer senderUid,
@RequestParam(value="receiverUid",required=true) Integer receiverUid){
ModelAndView mav = new ModelAndView();
mav.setViewName("/admin/msg/show_msg");
UserInfo receiver = userInfoService.getUserInfoByUid(receiverUid);
if(null == receiver){
return toError("被回复人不存在");
}
mav.addObject("receiver", receiver);
UserInfo sender = userInfoService.getUserInfoByUid(senderUid);
if(null == sender){
return toError("主回复人不存在");
}
mav.addObject("sender", sender);
List<PrivateLetter> letterList = privateLetterService.getPrivateLetterOfTwoManForUidA(senderUid, receiverUid);
mav.addObject("letterList", letterList);
Map<Integer, UserInfo> userMap = new HashMap<Integer, UserInfo>();
userMap.put(receiverUid, receiver);
userMap.put(senderUid, sender);
mav.addObject("userMap", userMap);
return mav;
}
}
| UTF-8 | Java | 3,315 | java | AdminMsgController.java | Java | [] | null | [] | package com.lanrenyou.admin.controller.msg;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mybatis.framework.core.support.PageIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.lanrenyou.admin.controller.base.BaseController;
import com.lanrenyou.letter.model.PrivateLetter;
import com.lanrenyou.letter.service.IPrivateLetterService;
import com.lanrenyou.user.model.UserInfo;
import com.lanrenyou.user.service.IUserInfoService;
@Controller
@RequestMapping("/msg")
public class AdminMsgController extends BaseController {
@Autowired
private IPrivateLetterService privateLetterService;
@Autowired
private IUserInfoService userInfoService;
@RequestMapping(value="/list")
public ModelAndView travelList(
@RequestParam(value="queryUid",required=false, defaultValue="-1") Integer queryUid,
@RequestParam(value="pageNo",required=false, defaultValue="1") int pageNo,
@RequestParam(value="pageSize",required=false, defaultValue="10") int pageSize
){
ModelAndView mav = new ModelAndView();
mav.setViewName("/admin/msg/letter_list");
mav.addObject("queryUid", queryUid);
mav.addObject("pageNo", pageNo);
if(null == queryUid){
queryUid = -1;
}
PageIterator<Map<String, Object>> pageIter = privateLetterService.pageQueryByUid(queryUid, pageNo, pageSize);
mav.addObject("pageIter", pageIter);
if(null != pageIter && pageIter.getData() != null){
Set<Integer> uidSet = new HashSet<Integer>();
for(Map<String, Object> map : pageIter.getData()){
Integer senderUid = (Integer) map.get("sender_uid");
if(null != senderUid){
uidSet.add(senderUid);
}
Integer receiverUid = (Integer) map.get("receiver_uid");
if(null != receiverUid){
uidSet.add(receiverUid);
}
}
Map<Integer, UserInfo> userInfoMap = userInfoService.getUserInfoMapByUidList(new ArrayList<Integer>(uidSet));
mav.addObject("userInfoMap", userInfoMap);
}
return mav;
}
@RequestMapping(value="/showMsg")
public ModelAndView showMsgBetweenUidAAndUidB(
@RequestParam(value="senderUid",required=true) Integer senderUid,
@RequestParam(value="receiverUid",required=true) Integer receiverUid){
ModelAndView mav = new ModelAndView();
mav.setViewName("/admin/msg/show_msg");
UserInfo receiver = userInfoService.getUserInfoByUid(receiverUid);
if(null == receiver){
return toError("被回复人不存在");
}
mav.addObject("receiver", receiver);
UserInfo sender = userInfoService.getUserInfoByUid(senderUid);
if(null == sender){
return toError("主回复人不存在");
}
mav.addObject("sender", sender);
List<PrivateLetter> letterList = privateLetterService.getPrivateLetterOfTwoManForUidA(senderUid, receiverUid);
mav.addObject("letterList", letterList);
Map<Integer, UserInfo> userMap = new HashMap<Integer, UserInfo>();
userMap.put(receiverUid, receiver);
userMap.put(senderUid, sender);
mav.addObject("userMap", userMap);
return mav;
}
}
| 3,315 | 0.753879 | 0.752358 | 100 | 31.860001 | 27.03591 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.37 | false | false | 2 |
e81328032cfd96e2f109988cee74c1e3e4d3bf0a | 33,251,636,875,494 | 882bb514805179716738da42d75ea3fee99b1f57 | /Ex3/src/dataStructure/DGraph.java | 7a96ff59087bab92b5454882626acc477ed9dccf | [] | no_license | TalAbed/OOP_EX3 | https://github.com/TalAbed/OOP_EX3 | 9c8df9e2398371bf8abe38be420f1f1189a2d3d2 | 10acb740c7d20c5ad4f02197220dd1f42c0acdb0 | refs/heads/master | 2020-12-15T16:35:20.489000 | 2020-01-20T19:26:20 | 2020-01-20T19:26:20 | 233,793,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dataStructure;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import utils.Point3D;
public class DGraph implements graph{
private HashMap <Integer, HashMap<Integer, edge_data>> edgeMap = new HashMap <Integer, HashMap<Integer, edge_data>>();
private HashMap <Integer, node_data> nodeMap = new HashMap <Integer, node_data>();
private int McCounter = 0;
private int edgeCounter = 0;
@Override
public node_data getNode(int key) {
return nodeMap.get(key);
}
@Override
public edge_data getEdge(int src, int dest) {
if (src==dest || nodeMap.get(src)==null || nodeMap.get(dest)==null)
return null;
if (edgeMap.get(nodeMap.get(src))!=null)
return edgeMap.get(nodeMap.get(src)).get(dest);
return null;
}
@Override
public void addNode(node_data n) {
nodeMap.put(n.getKey(), n);
}
@Override
public void connect(int src, int dest, double w) {
boolean b = true;
if (src==dest) {
System.out.println("src and dest are equals");
b = false;
}
if (b || ((nodeMap.get(src)!=null) || (nodeMap.get(dest)!=null))) {
if (!nodeMap.containsKey(src)||nodeMap.containsKey(dest)) {
if (edgeMap.containsKey(src)&&edgeMap.get(src).get(dest) != null)
throw new RuntimeException ("this edge is already exist");
else {
edge_data ed = new Edge (src, dest, w);
if(edgeMap.containsKey(src)) {
this.edgeMap.get(src).put(dest, ed);
}
else {
HashMap<Integer, edge_data> value=new HashMap<Integer, edge_data>();
value.put(dest, ed);
this.edgeMap.put(src, value);
}
McCounter++;
edgeCounter++;
}
}
else if (b)
throw new RuntimeException ("src or dest is not exist");
}
}
public Collection<node_data> getV() {
Collection<node_data> list = new ArrayList<node_data>(nodeMap.values());
return list;
}
@Override
public Collection<edge_data> getE(int node_id) {
if (edgeMap.get(node_id) != null) {
return edgeMap.get(node_id).values();
}
return null;
}
@Override
public node_data removeNode(int key) {
node_data n1 = this.getNode(key);
if (n1!=null) {
for (Iterator<node_data> it = this.getV().iterator();it.hasNext();) {
node_data n2 = (node_data) it.next();
this.removeEdge(n2.getKey(), key);
}
if (edgeMap.get(key)!=null) {
edgeCounter -= edgeMap.get(key).size();
McCounter += edgeMap.get(key).size();
}
nodeMap.remove(key);
edgeMap.remove(key);
McCounter++;
}
return n1;
}
@Override
public edge_data removeEdge(int src, int dest) {
McCounter++;
if (edgeMap.get(src).get(dest)!=null) {
Edge e = new Edge ();
e = (Edge) edgeMap.get(src).get(dest);
edgeMap.get(src).remove(dest);
return e;
}
return null;
}
@Override
public int nodeSize() {
return nodeMap.size();
}
@Override
public int edgeSize() {
return this.edgeCounter;
}
@Override
public int getMC() {
return this.McCounter;
}
public void init (String file) {
DGraph dg = new DGraph();
try {
JSONObject o = new JSONObject (file);
JSONArray edges = o.getJSONArray("Edges");
JSONArray nodes = o.getJSONArray("Nodes");
for (int i=0;i<nodes.length();i++) {
String pos = nodes.getJSONObject(i).getString("pos");
String sa[] = pos.split(",");
int id=nodes.getJSONObject(i).getInt("id");
Point3D p=new Point3D(Double.parseDouble(sa[0]),Double.parseDouble(sa[1]),Double.parseDouble(sa[2]));
node_data n =new Node(id,p);
dg.addNode(n);
}
for(int i = 0; i < edges.length(); i++)
{
int src = edges.getJSONObject(i).getInt("src");
int dst = edges.getJSONObject(i).getInt("dest");
double w = edges.getJSONObject(i).getDouble("w");
dg.connect(src, dst, w);
}
}
catch (Exception e) {
System.out.println(e.toString());
}
this.nodeMap = dg.nodeMap;
this.edgeMap = dg.edgeMap;
}
}
| UTF-8 | Java | 4,118 | java | DGraph.java | Java | [] | null | [] | package dataStructure;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import utils.Point3D;
public class DGraph implements graph{
private HashMap <Integer, HashMap<Integer, edge_data>> edgeMap = new HashMap <Integer, HashMap<Integer, edge_data>>();
private HashMap <Integer, node_data> nodeMap = new HashMap <Integer, node_data>();
private int McCounter = 0;
private int edgeCounter = 0;
@Override
public node_data getNode(int key) {
return nodeMap.get(key);
}
@Override
public edge_data getEdge(int src, int dest) {
if (src==dest || nodeMap.get(src)==null || nodeMap.get(dest)==null)
return null;
if (edgeMap.get(nodeMap.get(src))!=null)
return edgeMap.get(nodeMap.get(src)).get(dest);
return null;
}
@Override
public void addNode(node_data n) {
nodeMap.put(n.getKey(), n);
}
@Override
public void connect(int src, int dest, double w) {
boolean b = true;
if (src==dest) {
System.out.println("src and dest are equals");
b = false;
}
if (b || ((nodeMap.get(src)!=null) || (nodeMap.get(dest)!=null))) {
if (!nodeMap.containsKey(src)||nodeMap.containsKey(dest)) {
if (edgeMap.containsKey(src)&&edgeMap.get(src).get(dest) != null)
throw new RuntimeException ("this edge is already exist");
else {
edge_data ed = new Edge (src, dest, w);
if(edgeMap.containsKey(src)) {
this.edgeMap.get(src).put(dest, ed);
}
else {
HashMap<Integer, edge_data> value=new HashMap<Integer, edge_data>();
value.put(dest, ed);
this.edgeMap.put(src, value);
}
McCounter++;
edgeCounter++;
}
}
else if (b)
throw new RuntimeException ("src or dest is not exist");
}
}
public Collection<node_data> getV() {
Collection<node_data> list = new ArrayList<node_data>(nodeMap.values());
return list;
}
@Override
public Collection<edge_data> getE(int node_id) {
if (edgeMap.get(node_id) != null) {
return edgeMap.get(node_id).values();
}
return null;
}
@Override
public node_data removeNode(int key) {
node_data n1 = this.getNode(key);
if (n1!=null) {
for (Iterator<node_data> it = this.getV().iterator();it.hasNext();) {
node_data n2 = (node_data) it.next();
this.removeEdge(n2.getKey(), key);
}
if (edgeMap.get(key)!=null) {
edgeCounter -= edgeMap.get(key).size();
McCounter += edgeMap.get(key).size();
}
nodeMap.remove(key);
edgeMap.remove(key);
McCounter++;
}
return n1;
}
@Override
public edge_data removeEdge(int src, int dest) {
McCounter++;
if (edgeMap.get(src).get(dest)!=null) {
Edge e = new Edge ();
e = (Edge) edgeMap.get(src).get(dest);
edgeMap.get(src).remove(dest);
return e;
}
return null;
}
@Override
public int nodeSize() {
return nodeMap.size();
}
@Override
public int edgeSize() {
return this.edgeCounter;
}
@Override
public int getMC() {
return this.McCounter;
}
public void init (String file) {
DGraph dg = new DGraph();
try {
JSONObject o = new JSONObject (file);
JSONArray edges = o.getJSONArray("Edges");
JSONArray nodes = o.getJSONArray("Nodes");
for (int i=0;i<nodes.length();i++) {
String pos = nodes.getJSONObject(i).getString("pos");
String sa[] = pos.split(",");
int id=nodes.getJSONObject(i).getInt("id");
Point3D p=new Point3D(Double.parseDouble(sa[0]),Double.parseDouble(sa[1]),Double.parseDouble(sa[2]));
node_data n =new Node(id,p);
dg.addNode(n);
}
for(int i = 0; i < edges.length(); i++)
{
int src = edges.getJSONObject(i).getInt("src");
int dst = edges.getJSONObject(i).getInt("dest");
double w = edges.getJSONObject(i).getDouble("w");
dg.connect(src, dst, w);
}
}
catch (Exception e) {
System.out.println(e.toString());
}
this.nodeMap = dg.nodeMap;
this.edgeMap = dg.edgeMap;
}
}
| 4,118 | 0.61729 | 0.613647 | 160 | 23.725 | 22.32486 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.76875 | false | false | 2 |
2c50a17602fe02656c32390a6cbe8c01bd58f925 | 22,222,160,843,272 | 319790f4a4ebb5c3e66e0df7bf287d6f4325a450 | /class/server/AjaxTest/src/com/test/ajax/Ex04Ok.java | bab43b818ca46d5a3c6984e36318d2b2420d17a4 | [] | no_license | ithansiyeon/material | https://github.com/ithansiyeon/material | eb933910b9215bf7e2e6eae6c753a296c59194f8 | 3e6deaa283f3b462ae820f81b3ea49f7cf2712a9 | refs/heads/master | 2023-05-06T09:57:56.069000 | 2021-05-16T10:55:54 | 2021-05-16T10:55:54 | 298,319,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//ajax 객체의 요청 받아서 응답하는 서블릿
// - 브라우저를 상대하는 서블릿이 아니다.
//브라우저 -> HTML 문서를 반환
// ajax -> 데이터를 반환(HTML (X))
@WebServlet("/ex04ok.do")
public class Ex04Ok extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String type = req.getParameter("type");
if(type.equals("1")) {
m1(req,resp);
} else if(type.equals("2")) {
m2(req,resp);
} else if(type.equals("3")) {
m3(req,resp);
} else if(type.equals("4")) {
m4(req,resp);
} else if(type.equals("5")) {
m5(req,resp);
} else if(type.equals("6")) {
m6(req,resp);
}
}
private void m6(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//m3() === m6()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
//바깥이 배열 안이 객체
String temp = "";
temp+="[";
for(BoardDTO dto : list) {
temp+="{";
temp+=String.format("\"seq\":\"%s\"",dto.getSeq());
temp+=",";
temp+=String.format("\"subject\":\"%s\"",dto.getSubject());
temp+=",";
temp+=String.format(" \"regdate\":\"%s\"",dto.getRegdate());
temp+="}";
temp+=",";
}
temp = temp.substring(0,temp.length()-1);
temp+="]";
writer.print(temp);
writer.close();
}
private void m5(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// m2() == m5()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/xml");
PrintWriter writer = resp.getWriter();
writer.print("<?xml version = '1.0' encoding = 'UTF-8' ?>");
writer.print("<list>");
for(BoardDTO dto : list) {
writer.print("<item>");
writer.print("<seq>");
writer.print(dto.getSeq());
writer.print("</seq>");
writer.print("<subject>");
writer.print(dto.getSubject());
writer.print("</subject>");
writer.print("<regdate>");
writer.print(dto.getRegdate());
writer.print("</regdate>");
writer.print("</item>");
}
writer.print("</list>");
writer.close();
}
private void m4(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//m1()==m4()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
//ajax에게 게시물 반환
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
//CSV
for(BoardDTO dto : list) {
writer.printf("%s,%s,%s\n",
dto.getSeq()
,dto.getSubject()
,dto.getRegdate());
}
writer.close();
}
private void m3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//JSON 요청
//JSON(JavaScript Object Notation) -> 자바 표기법을 사용한 객체 표현 방식
/*
var obj = {
name : "홍길동",
age : 20,
address :"서울시"
}
//JSON 표기법 => 자바스크립트 기반
//데이터의 구조를 가지고 있어, xml과 유사 => 마크업 기반
{
"name":"홍길동",
"age":"20",
"address":"서울시"
}
*/
int count = 111;
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("{");
writer.printf("\"result\":\"%d\"",count);
writer.print("}");
writer.close();
}
private void m2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//XML 요청
// -> ajax에게 돌려주는 데이터를 XML 형식으로 만들어서 반환
// -> writer로 작성하는 데이터가 XML 문법의 출력물이면 된다.
int count = 250;
resp.setContentType("text/xml"); // MINME 타입(브라우저에게 현재 전달되는 데이터가 XML 형식의 데이터라고.. 알려주는 역할)
resp.setCharacterEncoding("UTF-8"); //돌려주는 resp, 수신하는거는 req
PrintWriter writer = resp.getWriter();
writer.print("<?xml version = '1.0' encoding = 'UTF-8' ?>");
writer.print("<item>");
writer.print(count);
writer.print("</item>");
}
private void m1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Text 요청
//select count(*) ->
int count = 175;
//ajax에게 응답
PrintWriter writer = resp.getWriter();
writer.print(count);
writer.close();
}
}
| UTF-8 | Java | 5,214 | java | Ex04Ok.java | Java | [
{
"context": "표현 방식\n\t\t\t\n\t\t\t/*\n\t\t\t \n\t\t\t var obj = {\n\t\t\t \tname : \"홍길동\",\n\t\t\t \tage : 20,\n\t\t\t \taddress :\"서울시\"\n\t\t\t }\n\t\t\t \n\t",
"end": 3409,
"score": 0.9998117685317993,
"start": 3406,
"tag": "NAME",
"value": "홍길동"
},
{
"context": "구조를 가지고 있어, xml... | null | [] | package com.test.ajax;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//ajax 객체의 요청 받아서 응답하는 서블릿
// - 브라우저를 상대하는 서블릿이 아니다.
//브라우저 -> HTML 문서를 반환
// ajax -> 데이터를 반환(HTML (X))
@WebServlet("/ex04ok.do")
public class Ex04Ok extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String type = req.getParameter("type");
if(type.equals("1")) {
m1(req,resp);
} else if(type.equals("2")) {
m2(req,resp);
} else if(type.equals("3")) {
m3(req,resp);
} else if(type.equals("4")) {
m4(req,resp);
} else if(type.equals("5")) {
m5(req,resp);
} else if(type.equals("6")) {
m6(req,resp);
}
}
private void m6(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//m3() === m6()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
//바깥이 배열 안이 객체
String temp = "";
temp+="[";
for(BoardDTO dto : list) {
temp+="{";
temp+=String.format("\"seq\":\"%s\"",dto.getSeq());
temp+=",";
temp+=String.format("\"subject\":\"%s\"",dto.getSubject());
temp+=",";
temp+=String.format(" \"regdate\":\"%s\"",dto.getRegdate());
temp+="}";
temp+=",";
}
temp = temp.substring(0,temp.length()-1);
temp+="]";
writer.print(temp);
writer.close();
}
private void m5(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// m2() == m5()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/xml");
PrintWriter writer = resp.getWriter();
writer.print("<?xml version = '1.0' encoding = 'UTF-8' ?>");
writer.print("<list>");
for(BoardDTO dto : list) {
writer.print("<item>");
writer.print("<seq>");
writer.print(dto.getSeq());
writer.print("</seq>");
writer.print("<subject>");
writer.print(dto.getSubject());
writer.print("</subject>");
writer.print("<regdate>");
writer.print(dto.getRegdate());
writer.print("</regdate>");
writer.print("</item>");
}
writer.print("</list>");
writer.close();
}
private void m4(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//m1()==m4()
AjaxDAO dao = new AjaxDAO();
ArrayList<BoardDTO> list = dao.list();
//ajax에게 게시물 반환
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
//CSV
for(BoardDTO dto : list) {
writer.printf("%s,%s,%s\n",
dto.getSeq()
,dto.getSubject()
,dto.getRegdate());
}
writer.close();
}
private void m3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//JSON 요청
//JSON(JavaScript Object Notation) -> 자바 표기법을 사용한 객체 표현 방식
/*
var obj = {
name : "홍길동",
age : 20,
address :"서울시"
}
//JSON 표기법 => 자바스크립트 기반
//데이터의 구조를 가지고 있어, xml과 유사 => 마크업 기반
{
"name":"홍길동",
"age":"20",
"address":"서울시"
}
*/
int count = 111;
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("{");
writer.printf("\"result\":\"%d\"",count);
writer.print("}");
writer.close();
}
private void m2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//XML 요청
// -> ajax에게 돌려주는 데이터를 XML 형식으로 만들어서 반환
// -> writer로 작성하는 데이터가 XML 문법의 출력물이면 된다.
int count = 250;
resp.setContentType("text/xml"); // MINME 타입(브라우저에게 현재 전달되는 데이터가 XML 형식의 데이터라고.. 알려주는 역할)
resp.setCharacterEncoding("UTF-8"); //돌려주는 resp, 수신하는거는 req
PrintWriter writer = resp.getWriter();
writer.print("<?xml version = '1.0' encoding = 'UTF-8' ?>");
writer.print("<item>");
writer.print(count);
writer.print("</item>");
}
private void m1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Text 요청
//select count(*) ->
int count = 175;
//ajax에게 응답
PrintWriter writer = resp.getWriter();
writer.print(count);
writer.close();
}
}
| 5,214 | 0.603297 | 0.592028 | 208 | 22.038462 | 22.936964 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.336539 | false | false | 2 |
904124a5deb6326e5b21010cb6f968d1e5ba57de | 33,801,392,663,660 | a2dc31fb7372a6ab9986095ede1c979d9c914cea | /javacourse/reflection/src/main/java/com/sirma/itt/evgeni/task1/ClassAnalyserRunner.java | 04450ee1b459801aff7fca54bda999e9af274801 | [] | no_license | gecatar/course | https://github.com/gecatar/course | 50dc771312899a988d5cfa37c8384cf1715ec269 | 56174562a43708a49319e9e9cea355e7b103253a | refs/heads/master | 2021-01-14T13:57:54.569000 | 2015-01-29T17:27:20 | 2015-01-29T17:27:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sirma.itt.evgeni.task1;
import com.sirma.itt.evgeni.reflection.TestClass;
/**
* Allow set primitive value on selected class. List all declared functions and
* variables.
*
* @author Evgeni Stefanov
*
*/
public class ClassAnalyserRunner {
/**
* Set primitive values and list all methods and variables.
*
* @param args
*/
public static void main(String[] args) {
ClassAnalyzer analyzer = new ClassAnalyzer();
TestClass temp = new TestClass();
System.out.println(analyzer.listDeclaredFields(temp));
System.out.println("-----------------------------------");
System.out.println(analyzer.listDeclaredMethods(temp));
}
} | UTF-8 | Java | 688 | java | ClassAnalyserRunner.java | Java | [
{
"context": "ared functions and\r\n * variables.\r\n * \r\n * @author Evgeni Stefanov\r\n * \r\n */\r\npublic class ClassAnalyserRunner {\r\n\r\n",
"end": 224,
"score": 0.9998744130134583,
"start": 209,
"tag": "NAME",
"value": "Evgeni Stefanov"
}
] | null | [] | package com.sirma.itt.evgeni.task1;
import com.sirma.itt.evgeni.reflection.TestClass;
/**
* Allow set primitive value on selected class. List all declared functions and
* variables.
*
* @author <NAME>
*
*/
public class ClassAnalyserRunner {
/**
* Set primitive values and list all methods and variables.
*
* @param args
*/
public static void main(String[] args) {
ClassAnalyzer analyzer = new ClassAnalyzer();
TestClass temp = new TestClass();
System.out.println(analyzer.listDeclaredFields(temp));
System.out.println("-----------------------------------");
System.out.println(analyzer.listDeclaredMethods(temp));
}
} | 679 | 0.655523 | 0.65407 | 28 | 22.642857 | 24.294641 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 2 |
5770c132414a0dbfdb6384f3ca5cba20070ec004 | 12,678,743,492,516 | 38169f140eeb8eda58da4b7528ce10a5d5dce715 | /src/SocketIO/Message.java | 5455919c897e7ba5f270067fd18df95f937b0244 | [
"MIT"
] | permissive | Alexander-Hjelm/SocketIO | https://github.com/Alexander-Hjelm/SocketIO | 3161ae03833f55a4aa8dc5b2e1c2e6aa12f964bb | b6eef5944ac7e83881be581e742f11174149e0e3 | refs/heads/master | 2020-04-11T03:53:17.107000 | 2018-12-12T13:36:40 | 2018-12-12T13:36:40 | 161,493,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package SocketIO;
import org.json.JSONException;
import org.json.JSONObject;
public class Message {
// Add more message properties here, as needed...
public Type type;
public String id;
public String data;
public enum Type {
// Add more message types here, as needed...
TYPE_A,
TYPE_B,
TYPE_C
}
public Message(Type type, String id, String data) {
this.type = type;
this.id = id;
this.data = data;
}
public Message() {}
public JSONObject ToJson() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("type", type.name());
obj.put("id", id);
obj.put("data", data);
return obj;
}
public static Message FromJson(JSONObject obj) throws JSONException {
return new Message(Type.valueOf((String)obj.get("type")), (String)obj.get("id"),(String) obj.get("data"));
}
}
| UTF-8 | Java | 848 | java | Message.java | Java | [] | null | [] | package SocketIO;
import org.json.JSONException;
import org.json.JSONObject;
public class Message {
// Add more message properties here, as needed...
public Type type;
public String id;
public String data;
public enum Type {
// Add more message types here, as needed...
TYPE_A,
TYPE_B,
TYPE_C
}
public Message(Type type, String id, String data) {
this.type = type;
this.id = id;
this.data = data;
}
public Message() {}
public JSONObject ToJson() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("type", type.name());
obj.put("id", id);
obj.put("data", data);
return obj;
}
public static Message FromJson(JSONObject obj) throws JSONException {
return new Message(Type.valueOf((String)obj.get("type")), (String)obj.get("id"),(String) obj.get("data"));
}
}
| 848 | 0.65566 | 0.65566 | 39 | 20.743589 | 22.42448 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 2 |
ab07455995f3f559e5b828191c0d16d2f992350c | 21,157,008,964,913 | 35c4992ec7d56ce77dbfe9bc06d77b22db9d71b8 | /Workspace/bank/src/test/PrepareGuiForTrigger.java | 0395e23399687eb96b31454abc470bf1cb6f8977 | [] | no_license | flohtux/fhdw-aufgaben | https://github.com/flohtux/fhdw-aufgaben | eef6e5bb6a236b69046d30639b0350d25f28a053 | 77a2edcc3551f538337f89962afe5214cf5b9b9d | refs/heads/master | 2020-05-20T07:27:13.106000 | 2013-09-26T15:20:39 | 2013-09-26T15:20:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import static org.junit.Assert.*;
import model.Administrator;
import model.Amount;
import model.BankCreator;
import model.DoubleRuleDefinitionException;
import model.Euro;
import model.Money;
import model.NoRuleDefinitionException;
import model.SubjectRule;
import org.junit.Before;
import org.junit.Test;
import common.Fraction;
import persistence.PersistenceException;
import persistence.PersistentAccount;
import persistence.PersistentAdministrator;
import persistence.PersistentBank;
import persistence.PersistentTransfer;
import persistence.PersistentTrigger;
public class PrepareGuiForTrigger {
private final String BankName1 = "Bank1";
private final String BankName2 = "Bank2";
private final long FirstAccountNumber = serverConstants.ServerConstants.FirstAccountNumber + 1;
private final long SecondAccountNumber = FirstAccountNumber + 1;
@Before
public void setUpDatabase() {
try {
TestSupport.prepareDatabase(); // TODO PREREQUISITES: Test:
// substitute by following statement
// for database-less test:
// ConnectionHandler.getTheConnectionHandler().connect("localhost:1521:xe",
// "bank", "bank", "pg".toCharArray(), false);
TestSupport.prepareSingletons();
persistence.Cache.getTheCache().reset$For$Test();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Erzeugt einen Standardfall für die Oberfläche:
* also 2 accounts 1@1 und 2@1 mit jeweils einem zyklischen trigger.
* resettet natürlich vorher
*/
@Test
public void test() throws PersistenceException, DoubleRuleDefinitionException, NoRuleDefinitionException {
PersistentAdministrator admin = Administrator.createAdministrator();
PersistentBank b = BankCreator.getTheBankCreator().createBank(BankName1, admin);
b.createAccount("Euro");
b.createAccount("Euro");
PersistentAccount acc1 = b.getAccounts().get(FirstAccountNumber);
PersistentAccount acc2 = b.getAccounts().get(SecondAccountNumber);
PersistentTransfer action = acc2.createTransfer();
action.setSubject("Folge 2->1");
action.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("12")), Euro.getTheEuro()));
action.setReceiverAccountNumber(acc1.getAccountNumber());
action.setReceiverBankNumber(acc1.getBank().getBankNumber());
PersistentTrigger tr = acc2.createTrigger("T2",action);
tr.addRule(SubjectRule.createSubjectRule());
tr.enable();
PersistentTransfer action2 = acc1.createTransfer();
action2.setSubject("Folge 1->2");
action2.setReceiverAccountNumber(acc2.getAccountNumber());
action2.setReceiverBankNumber(acc2.getBank().getBankNumber());
action2.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("13")), Euro.getTheEuro()));
PersistentTrigger tr2 = acc1.createTrigger("T1",action2);
tr2.addRule(SubjectRule.createSubjectRule());
tr2.enable();
}
@Test
public void test2() throws PersistenceException, DoubleRuleDefinitionException, NoRuleDefinitionException {
PersistentAdministrator admin = Administrator.createAdministrator();
PersistentBank b = BankCreator.getTheBankCreator().createBank(BankName1, admin);
b.createAccount("Euro");
b.createAccount("Euro");
PersistentAccount acc1 = b.getAccounts().get(FirstAccountNumber);
PersistentAccount acc2 = b.getAccounts().get(SecondAccountNumber);
PersistentTransfer action = acc2.createTransfer();
action.setSubject("Folge 2->1");
action.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("12")), Euro.getTheEuro()));
action.setReceiverAccountNumber(acc1.getAccountNumber());
action.setReceiverBankNumber(acc1.getBank().getBankNumber());
PersistentTrigger tr = acc2.createTrigger("T2",action);
tr.addRule(SubjectRule.createSubjectRule());
tr.enable();
PersistentTransfer action2 = acc1.createTransfer();
action2.setSubject("Folge 1->2");
action2.setReceiverAccountNumber(acc2.getAccountNumber());
action2.setReceiverBankNumber(acc2.getBank().getBankNumber());
action2.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("13")), Euro.getTheEuro()));
PersistentTrigger tr2 = acc1.createTrigger("T1",action2);
tr2.addRule(SubjectRule.createSubjectRule());
tr2.enable();
}
}
| ISO-8859-1 | Java | 4,349 | java | PrepareGuiForTrigger.java | Java | [] | null | [] | package test;
import static org.junit.Assert.*;
import model.Administrator;
import model.Amount;
import model.BankCreator;
import model.DoubleRuleDefinitionException;
import model.Euro;
import model.Money;
import model.NoRuleDefinitionException;
import model.SubjectRule;
import org.junit.Before;
import org.junit.Test;
import common.Fraction;
import persistence.PersistenceException;
import persistence.PersistentAccount;
import persistence.PersistentAdministrator;
import persistence.PersistentBank;
import persistence.PersistentTransfer;
import persistence.PersistentTrigger;
public class PrepareGuiForTrigger {
private final String BankName1 = "Bank1";
private final String BankName2 = "Bank2";
private final long FirstAccountNumber = serverConstants.ServerConstants.FirstAccountNumber + 1;
private final long SecondAccountNumber = FirstAccountNumber + 1;
@Before
public void setUpDatabase() {
try {
TestSupport.prepareDatabase(); // TODO PREREQUISITES: Test:
// substitute by following statement
// for database-less test:
// ConnectionHandler.getTheConnectionHandler().connect("localhost:1521:xe",
// "bank", "bank", "pg".toCharArray(), false);
TestSupport.prepareSingletons();
persistence.Cache.getTheCache().reset$For$Test();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Erzeugt einen Standardfall für die Oberfläche:
* also 2 accounts 1@1 und 2@1 mit jeweils einem zyklischen trigger.
* resettet natürlich vorher
*/
@Test
public void test() throws PersistenceException, DoubleRuleDefinitionException, NoRuleDefinitionException {
PersistentAdministrator admin = Administrator.createAdministrator();
PersistentBank b = BankCreator.getTheBankCreator().createBank(BankName1, admin);
b.createAccount("Euro");
b.createAccount("Euro");
PersistentAccount acc1 = b.getAccounts().get(FirstAccountNumber);
PersistentAccount acc2 = b.getAccounts().get(SecondAccountNumber);
PersistentTransfer action = acc2.createTransfer();
action.setSubject("Folge 2->1");
action.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("12")), Euro.getTheEuro()));
action.setReceiverAccountNumber(acc1.getAccountNumber());
action.setReceiverBankNumber(acc1.getBank().getBankNumber());
PersistentTrigger tr = acc2.createTrigger("T2",action);
tr.addRule(SubjectRule.createSubjectRule());
tr.enable();
PersistentTransfer action2 = acc1.createTransfer();
action2.setSubject("Folge 1->2");
action2.setReceiverAccountNumber(acc2.getAccountNumber());
action2.setReceiverBankNumber(acc2.getBank().getBankNumber());
action2.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("13")), Euro.getTheEuro()));
PersistentTrigger tr2 = acc1.createTrigger("T1",action2);
tr2.addRule(SubjectRule.createSubjectRule());
tr2.enable();
}
@Test
public void test2() throws PersistenceException, DoubleRuleDefinitionException, NoRuleDefinitionException {
PersistentAdministrator admin = Administrator.createAdministrator();
PersistentBank b = BankCreator.getTheBankCreator().createBank(BankName1, admin);
b.createAccount("Euro");
b.createAccount("Euro");
PersistentAccount acc1 = b.getAccounts().get(FirstAccountNumber);
PersistentAccount acc2 = b.getAccounts().get(SecondAccountNumber);
PersistentTransfer action = acc2.createTransfer();
action.setSubject("Folge 2->1");
action.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("12")), Euro.getTheEuro()));
action.setReceiverAccountNumber(acc1.getAccountNumber());
action.setReceiverBankNumber(acc1.getBank().getBankNumber());
PersistentTrigger tr = acc2.createTrigger("T2",action);
tr.addRule(SubjectRule.createSubjectRule());
tr.enable();
PersistentTransfer action2 = acc1.createTransfer();
action2.setSubject("Folge 1->2");
action2.setReceiverAccountNumber(acc2.getAccountNumber());
action2.setReceiverBankNumber(acc2.getBank().getBankNumber());
action2.setMoney(Money.createMoney(Amount.createAmount(Fraction.parseDec("13")), Euro.getTheEuro()));
PersistentTrigger tr2 = acc1.createTrigger("T1",action2);
tr2.addRule(SubjectRule.createSubjectRule());
tr2.enable();
}
}
| 4,349 | 0.749655 | 0.732167 | 118 | 34.81356 | 29.209631 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.20339 | false | false | 2 |
79c35c4005a08d515f9cc52eecdbcd5932f9e0dc | 17,325,898,133,134 | c582ff9a987008133425d9ba5d590608ddc82b32 | /app/src/main/java/com/example/lutali/beconcerts/activities/MyConcerts.java | 248d602b840184a236fee37bf6e09cea6a2884a4 | [] | no_license | ShadaLA/BeConcert | https://github.com/ShadaLA/BeConcert | 72822584999a35033e8fc40e5a99ce80b1ffc078 | c0282b76ceabe5434b514dcbb5ef7b65dac40ffc | refs/heads/master | 2016-09-19T15:08:35.740000 | 2016-08-31T23:44:07 | 2016-08-31T23:44:27 | 67,080,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.lutali.beconcerts.activities;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.lutali.beconcerts.R;
import com.example.lutali.beconcerts.activities.HomePage;
import com.example.lutali.beconcerts.model.DAO.ReserverDAO;
import com.example.lutali.beconcerts.model.DAO.UserDAO;
public class MyConcerts extends AppCompatActivity {
private ReserverDAO rdao;
private UserDAO udao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_concerts);
}
public String getCurrentUser(){
SharedPreferences prefs = this.getSharedPreferences("userPrefs", Context.MODE_PRIVATE);
String setUserFirstName = prefs.getString(HomePage.USER_NAME, "");
return setUserFirstName;
}
}
| UTF-8 | Java | 976 | java | MyConcerts.java | Java | [] | null | [] | package com.example.lutali.beconcerts.activities;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.lutali.beconcerts.R;
import com.example.lutali.beconcerts.activities.HomePage;
import com.example.lutali.beconcerts.model.DAO.ReserverDAO;
import com.example.lutali.beconcerts.model.DAO.UserDAO;
public class MyConcerts extends AppCompatActivity {
private ReserverDAO rdao;
private UserDAO udao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_concerts);
}
public String getCurrentUser(){
SharedPreferences prefs = this.getSharedPreferences("userPrefs", Context.MODE_PRIVATE);
String setUserFirstName = prefs.getString(HomePage.USER_NAME, "");
return setUserFirstName;
}
}
| 976 | 0.770492 | 0.769467 | 30 | 31.533333 | 25.120686 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false | 2 |
c114c7b7b05cba3bec6bf55d79b600f392133a90 | 7,584,912,311,359 | 91b4d4799bb4cd9dda2d74001143f7821b22eb73 | /hbase-server/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationEditsDroppedWithDroppedTable.java | 3b73262980ae2fc6ac2bf7629610e25d80a9cf98 | [
"CC-BY-3.0",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-protobuf",
"MIT"
] | permissive | apache/hbase | https://github.com/apache/hbase | dce46e0c368a0aacee2ca414edfdbd6159059800 | 121c8e17ecea66267fe77bab078f79d14a74a832 | refs/heads/master | 2023-09-04T10:46:40.146000 | 2023-08-31T13:33:45 | 2023-08-31T13:33:45 | 20,089,857 | 5,493 | 3,991 | Apache-2.0 | false | 2023-09-14T14:55:43 | 2014-05-23T07:00:07 | 2023-09-14T07:16:55 | 2023-09-14T08:07:28 | 479,849 | 4,963 | 3,247 | 189 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.apache.hadoop.hbase.replication;
import static org.junit.Assert.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter.Predicate;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.replication.regionserver.HBaseInterClusterReplicationEndpoint;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category({ LargeTests.class })
public class TestReplicationEditsDroppedWithDroppedTable {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestReplicationEditsDroppedWithDroppedTable.class);
private static final Logger LOG =
LoggerFactory.getLogger(TestReplicationEditsDroppedWithDroppedTable.class);
private static Configuration conf1 = HBaseConfiguration.create();
private static Configuration conf2 = HBaseConfiguration.create();
protected static HBaseTestingUtil utility1;
protected static HBaseTestingUtil utility2;
private static Admin admin1;
private static Admin admin2;
private static final String namespace = "NS";
private static final TableName NORMAL_TABLE = TableName.valueOf("normal-table");
private static final TableName DROPPED_TABLE = TableName.valueOf("dropped-table");
private static final TableName DROPPED_NS_TABLE = TableName.valueOf("NS:dropped-table");
private static final byte[] ROW = Bytes.toBytes("row");
private static final byte[] FAMILY = Bytes.toBytes("f");
private static final byte[] QUALIFIER = Bytes.toBytes("q");
private static final byte[] VALUE = Bytes.toBytes("value");
private static final String PEER_ID = "1";
private static final long SLEEP_TIME = 1000;
private static final int NB_RETRIES = 10;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// Set true to filter replication edits for dropped table
conf1.setBoolean(HBaseInterClusterReplicationEndpoint.REPLICATION_DROP_ON_DELETED_TABLE_KEY,
true);
conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
conf1.setInt("replication.source.nb.capacity", 1);
utility1 = new HBaseTestingUtil(conf1);
utility1.startMiniZKCluster();
MiniZooKeeperCluster miniZK = utility1.getZkCluster();
conf1 = utility1.getConfiguration();
conf2 = HBaseConfiguration.create(conf1);
conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
utility2 = new HBaseTestingUtil(conf2);
utility2.setZkCluster(miniZK);
utility1.startMiniCluster(1);
utility2.startMiniCluster(1);
admin1 = utility1.getAdmin();
admin2 = utility2.getAdmin();
NamespaceDescriptor nsDesc = NamespaceDescriptor.create(namespace).build();
admin1.createNamespace(nsDesc);
admin2.createNamespace(nsDesc);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
utility2.shutdownMiniCluster();
utility1.shutdownMiniCluster();
}
@Before
public void setup() throws Exception {
// Roll log
for (JVMClusterUtil.RegionServerThread r : utility1.getHBaseCluster()
.getRegionServerThreads()) {
utility1.getAdmin().rollWALWriter(r.getRegionServer().getServerName());
}
// add peer
ReplicationPeerConfig rpc = ReplicationPeerConfig.newBuilder()
.setClusterKey(utility2.getClusterKey()).setReplicateAllUserTables(true).build();
admin1.addReplicationPeer(PEER_ID, rpc);
// create table
createTable(NORMAL_TABLE);
}
@After
public void tearDown() throws Exception {
// Remove peer
admin1.removeReplicationPeer(PEER_ID);
// Drop table
admin1.disableTable(NORMAL_TABLE);
admin1.deleteTable(NORMAL_TABLE);
admin2.disableTable(NORMAL_TABLE);
admin2.deleteTable(NORMAL_TABLE);
}
private void createTable(TableName tableName) throws Exception {
TableDescriptor desc =
TableDescriptorBuilder.newBuilder(tableName).setColumnFamily(ColumnFamilyDescriptorBuilder
.newBuilder(FAMILY).setScope(HConstants.REPLICATION_SCOPE_GLOBAL).build()).build();
admin1.createTable(desc);
admin2.createTable(desc);
utility1.waitUntilAllRegionsAssigned(tableName);
utility2.waitUntilAllRegionsAssigned(tableName);
}
@Test
public void testEditsDroppedWithDroppedTable() throws Exception {
testWithDroppedTable(DROPPED_TABLE);
}
@Test
public void testEditsDroppedWithDroppedTableNS() throws Exception {
testWithDroppedTable(DROPPED_NS_TABLE);
}
private void testWithDroppedTable(TableName droppedTableName) throws Exception {
createTable(droppedTableName);
admin1.disableReplicationPeer(PEER_ID);
try (Table droppedTable = utility1.getConnection().getTable(droppedTableName)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
droppedTable.put(put);
}
admin1.disableTable(droppedTableName);
admin1.deleteTable(droppedTableName);
admin2.disableTable(droppedTableName);
admin2.deleteTable(droppedTableName);
admin1.enableReplicationPeer(PEER_ID);
verifyReplicationProceeded();
}
@Test
public void testEditsBehindDroppedTableTiming() throws Exception {
createTable(DROPPED_TABLE);
admin1.disableReplicationPeer(PEER_ID);
try (Table droppedTable = utility1.getConnection().getTable(DROPPED_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
droppedTable.put(put);
}
// Only delete table from peer cluster
admin2.disableTable(DROPPED_TABLE);
admin2.deleteTable(DROPPED_TABLE);
admin1.enableReplicationPeer(PEER_ID);
// the source table still exists, replication should be stalled
verifyReplicationStuck();
admin1.disableTable(DROPPED_TABLE);
// still stuck, source table still exists
verifyReplicationStuck();
admin1.deleteTable(DROPPED_TABLE);
// now the source table is gone, replication should proceed, the
// offending edits be dropped
verifyReplicationProceeded();
}
private void verifyReplicationProceeded() throws Exception {
try (Table normalTable = utility1.getConnection().getTable(NORMAL_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
normalTable.put(put);
}
utility2.waitFor(NB_RETRIES * SLEEP_TIME, (Predicate<Exception>) () -> {
try (Table normalTable = utility2.getConnection().getTable(NORMAL_TABLE)) {
Result result = normalTable.get(new Get(ROW).addColumn(FAMILY, QUALIFIER));
return result != null && !result.isEmpty()
&& Bytes.equals(VALUE, result.getValue(FAMILY, QUALIFIER));
}
});
}
private void verifyReplicationStuck() throws Exception {
try (Table normalTable = utility1.getConnection().getTable(NORMAL_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
normalTable.put(put);
}
try (Table normalTable = utility2.getConnection().getTable(NORMAL_TABLE)) {
for (int i = 0; i < NB_RETRIES; i++) {
Result result = normalTable.get(new Get(ROW).addColumn(FAMILY, QUALIFIER));
if (result != null && !result.isEmpty()) {
fail("Edit should have been stuck behind dropped tables, but value is "
+ Bytes.toString(result.getValue(FAMILY, QUALIFIER)));
} else {
LOG.info("Row not replicated, let's wait a bit more...");
Thread.sleep(SLEEP_TIME);
}
}
}
}
}
| UTF-8 | Java | 9,270 | java | TestReplicationEditsDroppedWithDroppedTable.java | Java | [] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.apache.hadoop.hbase.replication;
import static org.junit.Assert.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter.Predicate;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.replication.regionserver.HBaseInterClusterReplicationEndpoint;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category({ LargeTests.class })
public class TestReplicationEditsDroppedWithDroppedTable {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestReplicationEditsDroppedWithDroppedTable.class);
private static final Logger LOG =
LoggerFactory.getLogger(TestReplicationEditsDroppedWithDroppedTable.class);
private static Configuration conf1 = HBaseConfiguration.create();
private static Configuration conf2 = HBaseConfiguration.create();
protected static HBaseTestingUtil utility1;
protected static HBaseTestingUtil utility2;
private static Admin admin1;
private static Admin admin2;
private static final String namespace = "NS";
private static final TableName NORMAL_TABLE = TableName.valueOf("normal-table");
private static final TableName DROPPED_TABLE = TableName.valueOf("dropped-table");
private static final TableName DROPPED_NS_TABLE = TableName.valueOf("NS:dropped-table");
private static final byte[] ROW = Bytes.toBytes("row");
private static final byte[] FAMILY = Bytes.toBytes("f");
private static final byte[] QUALIFIER = Bytes.toBytes("q");
private static final byte[] VALUE = Bytes.toBytes("value");
private static final String PEER_ID = "1";
private static final long SLEEP_TIME = 1000;
private static final int NB_RETRIES = 10;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// Set true to filter replication edits for dropped table
conf1.setBoolean(HBaseInterClusterReplicationEndpoint.REPLICATION_DROP_ON_DELETED_TABLE_KEY,
true);
conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
conf1.setInt("replication.source.nb.capacity", 1);
utility1 = new HBaseTestingUtil(conf1);
utility1.startMiniZKCluster();
MiniZooKeeperCluster miniZK = utility1.getZkCluster();
conf1 = utility1.getConfiguration();
conf2 = HBaseConfiguration.create(conf1);
conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
utility2 = new HBaseTestingUtil(conf2);
utility2.setZkCluster(miniZK);
utility1.startMiniCluster(1);
utility2.startMiniCluster(1);
admin1 = utility1.getAdmin();
admin2 = utility2.getAdmin();
NamespaceDescriptor nsDesc = NamespaceDescriptor.create(namespace).build();
admin1.createNamespace(nsDesc);
admin2.createNamespace(nsDesc);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
utility2.shutdownMiniCluster();
utility1.shutdownMiniCluster();
}
@Before
public void setup() throws Exception {
// Roll log
for (JVMClusterUtil.RegionServerThread r : utility1.getHBaseCluster()
.getRegionServerThreads()) {
utility1.getAdmin().rollWALWriter(r.getRegionServer().getServerName());
}
// add peer
ReplicationPeerConfig rpc = ReplicationPeerConfig.newBuilder()
.setClusterKey(utility2.getClusterKey()).setReplicateAllUserTables(true).build();
admin1.addReplicationPeer(PEER_ID, rpc);
// create table
createTable(NORMAL_TABLE);
}
@After
public void tearDown() throws Exception {
// Remove peer
admin1.removeReplicationPeer(PEER_ID);
// Drop table
admin1.disableTable(NORMAL_TABLE);
admin1.deleteTable(NORMAL_TABLE);
admin2.disableTable(NORMAL_TABLE);
admin2.deleteTable(NORMAL_TABLE);
}
private void createTable(TableName tableName) throws Exception {
TableDescriptor desc =
TableDescriptorBuilder.newBuilder(tableName).setColumnFamily(ColumnFamilyDescriptorBuilder
.newBuilder(FAMILY).setScope(HConstants.REPLICATION_SCOPE_GLOBAL).build()).build();
admin1.createTable(desc);
admin2.createTable(desc);
utility1.waitUntilAllRegionsAssigned(tableName);
utility2.waitUntilAllRegionsAssigned(tableName);
}
@Test
public void testEditsDroppedWithDroppedTable() throws Exception {
testWithDroppedTable(DROPPED_TABLE);
}
@Test
public void testEditsDroppedWithDroppedTableNS() throws Exception {
testWithDroppedTable(DROPPED_NS_TABLE);
}
private void testWithDroppedTable(TableName droppedTableName) throws Exception {
createTable(droppedTableName);
admin1.disableReplicationPeer(PEER_ID);
try (Table droppedTable = utility1.getConnection().getTable(droppedTableName)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
droppedTable.put(put);
}
admin1.disableTable(droppedTableName);
admin1.deleteTable(droppedTableName);
admin2.disableTable(droppedTableName);
admin2.deleteTable(droppedTableName);
admin1.enableReplicationPeer(PEER_ID);
verifyReplicationProceeded();
}
@Test
public void testEditsBehindDroppedTableTiming() throws Exception {
createTable(DROPPED_TABLE);
admin1.disableReplicationPeer(PEER_ID);
try (Table droppedTable = utility1.getConnection().getTable(DROPPED_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
droppedTable.put(put);
}
// Only delete table from peer cluster
admin2.disableTable(DROPPED_TABLE);
admin2.deleteTable(DROPPED_TABLE);
admin1.enableReplicationPeer(PEER_ID);
// the source table still exists, replication should be stalled
verifyReplicationStuck();
admin1.disableTable(DROPPED_TABLE);
// still stuck, source table still exists
verifyReplicationStuck();
admin1.deleteTable(DROPPED_TABLE);
// now the source table is gone, replication should proceed, the
// offending edits be dropped
verifyReplicationProceeded();
}
private void verifyReplicationProceeded() throws Exception {
try (Table normalTable = utility1.getConnection().getTable(NORMAL_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
normalTable.put(put);
}
utility2.waitFor(NB_RETRIES * SLEEP_TIME, (Predicate<Exception>) () -> {
try (Table normalTable = utility2.getConnection().getTable(NORMAL_TABLE)) {
Result result = normalTable.get(new Get(ROW).addColumn(FAMILY, QUALIFIER));
return result != null && !result.isEmpty()
&& Bytes.equals(VALUE, result.getValue(FAMILY, QUALIFIER));
}
});
}
private void verifyReplicationStuck() throws Exception {
try (Table normalTable = utility1.getConnection().getTable(NORMAL_TABLE)) {
Put put = new Put(ROW);
put.addColumn(FAMILY, QUALIFIER, VALUE);
normalTable.put(put);
}
try (Table normalTable = utility2.getConnection().getTable(NORMAL_TABLE)) {
for (int i = 0; i < NB_RETRIES; i++) {
Result result = normalTable.get(new Get(ROW).addColumn(FAMILY, QUALIFIER));
if (result != null && !result.isEmpty()) {
fail("Edit should have been stuck behind dropped tables, but value is "
+ Bytes.toString(result.getValue(FAMILY, QUALIFIER)));
} else {
LOG.info("Row not replicated, let's wait a bit more...");
Thread.sleep(SLEEP_TIME);
}
}
}
}
}
| 9,270 | 0.742503 | 0.733657 | 247 | 36.530365 | 26.240366 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 2 |
829459a25f9ccff1e9d354d99acaa14daefc6215 | 17,154,099,420,512 | 8e19e829c7a172fbcf207fc7a3def36d0108cbdd | /src/metier/CreditMetierTest.java | 63038e60723227e443418cf2381fde85fd8e817c | [] | no_license | ounon/Java | https://github.com/ounon/Java | 87ff535350a786e166c046a8d539e6e0cae3edc2 | 46962273c684ff4e622d05b4e2c6874aca267909 | refs/heads/master | 2020-06-01T05:19:47.908000 | 2019-06-06T21:57:15 | 2019-06-06T21:57:15 | 190,654,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package metier;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CreditMetierTest {
private ICreditMetier metier;
@Before
public void setUp() throws Exception {
metier = new CreditMetier();
}
@Test
public void testCalculerMensualiteCredit() {
double capital = 200000;
int duree = 240;
double taux = 4.5;
double resultatAttendu = 1265.2987;
double resultatCalculer = metier.calculerMensualiteCredit(capital, taux, duree);
assertEquals(resultatAttendu, resultatCalculer, 0.0001);
}
}
| UTF-8 | Java | 596 | java | CreditMetierTest.java | Java | [] | null | [] | package metier;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CreditMetierTest {
private ICreditMetier metier;
@Before
public void setUp() throws Exception {
metier = new CreditMetier();
}
@Test
public void testCalculerMensualiteCredit() {
double capital = 200000;
int duree = 240;
double taux = 4.5;
double resultatAttendu = 1265.2987;
double resultatCalculer = metier.calculerMensualiteCredit(capital, taux, duree);
assertEquals(resultatAttendu, resultatCalculer, 0.0001);
}
}
| 596 | 0.697987 | 0.657718 | 30 | 17.866667 | 20.069435 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.466667 | false | false | 2 |
9a5b66ee26c569fc31068d9459e4ba4075ed2907 | 34,995,393,573,386 | 865a23fe2dbaf578db59f7bf521533f37aa97635 | /ejerciciosPOO3/gestisimalOrientadoAObjetos/TestAlmacen.java | 49e852503547ec6bbe50daea70d69da0157ff52d | [] | no_license | alvaroolt/POO3 | https://github.com/alvaroolt/POO3 | a1a77f6cb0e2a195bb83e500626c556781a83584 | 2aad5791ba64d4c3e0397da4b81c20640552505b | refs/heads/master | 2020-04-26T13:12:41.078000 | 2019-04-03T18:53:01 | 2019-04-03T18:53:01 | 173,573,000 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ejerciciosPOO3.gestisimalOrientadoAObjetos;
import java.io.IOException;
import java.util.Scanner;
import utiles.Teclado;
/**
* Crea el programa GESTISIMAL (GESTIón SIMplificada de Almacén) para llevar el
* control de los artículos de un almacén. De cada artículo se debe saber el
* código, la descripción, el precio de compra, el precio de venta y el stock
* (número de unidades). La entrada y salida de mercancía supone respectivamente
* el incremento y decremento de stock de un determinado artículo. Hay que
* controlar que no se pueda sacar más mercancía de la que hay en el almacén.
*
* @author Álvaro Leiva
* @author Rafael Infante
* @version 1.0
*/
public class TestAlmacen {
// scanner
static Scanner sc = new Scanner(System.in);
// objeto almacen
static Almacen almacen = new Almacen();
public static void main(String[] args)
throws ParametroNoNumericoException, ValorNoPositivoException, NumberFormatException, IOException {
almacen.darAlta("Coca-Cola", -30, 45, 68);
almacen.darAlta("Nestea", 22, 35, 40);
almacen.darAlta("Fanta", 33, 42, 53);
ejecutaMenu();
}
/**
* metodo vacio que muestra el menu del almacen
*/
private static void mostrarMenu() {
System.out.println("ALMACEN" + "\n=========" + "\n1. Listado" + "\n2. Alta" + "\n3. Baja" + "\n4. Modificación"
+ "\n5. Entrada de mercancía" + "\n6. Salida de mercancía" + "\n7. Salir" + "\n");
}
/**
* método que devuelve un entero, el cual define la opción del menú
*
* @return int
* @throws ParametroNoNumericoException
*/
private static int elegirOpcion() throws ParametroNoNumericoException {
try {
System.out.print("\nElige una opción: ");
int opcion = sc.nextInt();
return opcion;
} catch (Exception e) { // si opcion no es numérico, salta el catch
System.err.println("Error al introducir el parámetro. Has de introducir valores numéricos.");
sc.nextLine();
return 0;
}
}
/**
* método vacio que finaliza el programa
*/
private static void finalizarPrograma() {
System.out.println("Fin de programa.");
System.exit(0);
}
/**
* método vacio que ejecuta el menú junto a mostrarMenu() y elegirOpcion()
*
* @throws ParametroNoNumericoException
* @throws ValorNoPositivoException
* @throws IOException
* @throws NumberFormatException
*/
private static void ejecutaMenu()
throws ParametroNoNumericoException, ValorNoPositivoException, NumberFormatException, IOException {
int opcion;
do {
mostrarMenu();
opcion = elegirOpcion();
switch (opcion) {
case 1:
almacen.muestraListado();
break;
case 2:
darAlta();
break;
case 3:
darBaja();
break;
case 4:
modificarArticulo();
break;
case 5:
incrementarStock();
break;
case 6:
decrementarStock();
break;
case 7:
finalizarPrograma();
break;
// si el switch no entra en ningún case, entra en default
default:
System.out.println("No introdujiste una opción correcta. Inténtalo de nuevo.\n");
break;
}
} while (opcion != 7);
}
/**
* método vacio que añade un nuevo artículo al almacén
*
* @throws IOException
* @throws NumberFormatException
*/
private static void darAlta() throws ValorNoPositivoException, NumberFormatException, IOException {
try {
String descripcion = Teclado.leerCadena("Introduce una breve descripción del artículo:");
double precioCompra = Teclado.leerDecimal("Precio de compra del artículo: ");
double precioVenta = Teclado.leerDecimal("Precio de venta del artículo: ");
int stock = Teclado.leerEntero("Cantidad del artículo en stock: ");
almacen.darAlta(descripcion, precioCompra, precioVenta, stock);
System.out.println("Artículo dado de alta correctamente.\n");
} catch (ValorNoPositivoException e) {
System.err.println("Hubo algún problema al añadir el artículo.\n" + e.getMessage());
sc.nextLine();
}
}
/**
* método vacio que elimina un artículo del almacén
*/
private static void darBaja() {
try {
int codigo = Teclado.leerEntero("Introduce el código identificador del artículo a eliminar: ");
almacen.darBaja(codigo);
} catch (Exception e) { // si no existe el codigo, salta el catch
System.err.println("El artículo no se encuentra en el almacén.\n");
sc.nextLine();
}
}
/**
* método vacio que permite modificar los valores de un artículo
*/
private static void modificarArticulo() {
try {
System.out.print("Introduce el código identificador del artículo a modificar: ");
int codigo = sc.nextInt();
sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.println("Introduce una breve descripción del artículo:");
String descripcion = sc.nextLine();
System.out.print("Precio de compra del artículo: ");
double precioCompra = sc.nextDouble();
System.out.print("Precio de venta del artículo: ");
double precioVenta = sc.nextDouble();
System.out.print("Cantidad del artículo en stock: ");
int stock = sc.nextInt();
// if (precioCompra < 0 || precioVenta < 0 || stock < 0) {
// throw new ValorNoPositivoException("Introdujiste algún valor negativo.");
// }
almacen.modificarArticulo(articulo, descripcion, precioCompra, precioVenta, stock);
} catch (Exception e) {
System.err.println("Hubo algún problema al modificar el artículo.\n" + e.getMessage());
sc.nextLine();
}
}
/**
* método vacio que incrementa el stock según el parámetro codigo que le envie
* el usuario
*/
private static void incrementarStock() {
try {
System.out.print("Introduce el código identificador del artículo a aumentar el stock: ");
int codigo = sc.nextInt();
// sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.print("Introduce cuánto stock nuevo hay en el almacén (" + articulo.getStock() + " actuales): ");
int cantidad = sc.nextInt();
// throw new ValorNoPositivoException("No se pueden añadir números negativos.");
// sc.nextLine();
almacen.incrementarStock(codigo, cantidad);
System.out.println("Stock añadido correctamente.");
// if (cantidad < 0) {
//
//
//
// }
} catch (Exception e) {
System.err.println("Hubo algún problema al incrementar el stock.\n" + e.getMessage());
// sc.nextLine();
}
}
/**
* método vacio que decrementa el stock según el parámetro codigo que le envie
* el usuario
*/
private static void decrementarStock() {
try {
System.out.print("Introduce el código identificador del artículo a disminuir el sotck: ");
int codigo = sc.nextInt();
sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.println("Introduce cuánto stock se ha eliminado del almacén (" + articulo.getStock() + " actuales): ");
int cantidad = sc.nextInt();
// sc.nextLine();
// if (cantidad < 0) {
// cantidad *= -1;
// }
// if (articulo.getStock() - cantidad < 0) {
// throw new ValorNoPositivoException("El stock no puede ser negativo.");
// }
almacen.decrementarStock(codigo, cantidad);
System.out.println("Stock eliminado correctamente.");
} catch (Exception e) {
System.err.println("Hubo algún problema al decrementar el stock.\n" + e.getMessage());
sc.nextLine();
}
}
} | UTF-8 | Java | 7,685 | java | TestAlmacen.java | Java | [
{
"context": "ncía de la que hay en el almacén.\r\n * \r\n * @author Álvaro Leiva\r\n * @author Rafael Infante\r\n * @version 1.0\r\n */\r",
"end": 647,
"score": 0.9998795390129089,
"start": 635,
"tag": "NAME",
"value": "Álvaro Leiva"
},
{
"context": "almacén.\r\n * \r\n * @author Ál... | null | [] | package ejerciciosPOO3.gestisimalOrientadoAObjetos;
import java.io.IOException;
import java.util.Scanner;
import utiles.Teclado;
/**
* Crea el programa GESTISIMAL (GESTIón SIMplificada de Almacén) para llevar el
* control de los artículos de un almacén. De cada artículo se debe saber el
* código, la descripción, el precio de compra, el precio de venta y el stock
* (número de unidades). La entrada y salida de mercancía supone respectivamente
* el incremento y decremento de stock de un determinado artículo. Hay que
* controlar que no se pueda sacar más mercancía de la que hay en el almacén.
*
* @author <NAME>
* @author <NAME>
* @version 1.0
*/
public class TestAlmacen {
// scanner
static Scanner sc = new Scanner(System.in);
// objeto almacen
static Almacen almacen = new Almacen();
public static void main(String[] args)
throws ParametroNoNumericoException, ValorNoPositivoException, NumberFormatException, IOException {
almacen.darAlta("Coca-Cola", -30, 45, 68);
almacen.darAlta("Nestea", 22, 35, 40);
almacen.darAlta("Fanta", 33, 42, 53);
ejecutaMenu();
}
/**
* metodo vacio que muestra el menu del almacen
*/
private static void mostrarMenu() {
System.out.println("ALMACEN" + "\n=========" + "\n1. Listado" + "\n2. Alta" + "\n3. Baja" + "\n4. Modificación"
+ "\n5. Entrada de mercancía" + "\n6. Salida de mercancía" + "\n7. Salir" + "\n");
}
/**
* método que devuelve un entero, el cual define la opción del menú
*
* @return int
* @throws ParametroNoNumericoException
*/
private static int elegirOpcion() throws ParametroNoNumericoException {
try {
System.out.print("\nElige una opción: ");
int opcion = sc.nextInt();
return opcion;
} catch (Exception e) { // si opcion no es numérico, salta el catch
System.err.println("Error al introducir el parámetro. Has de introducir valores numéricos.");
sc.nextLine();
return 0;
}
}
/**
* método vacio que finaliza el programa
*/
private static void finalizarPrograma() {
System.out.println("Fin de programa.");
System.exit(0);
}
/**
* método vacio que ejecuta el menú junto a mostrarMenu() y elegirOpcion()
*
* @throws ParametroNoNumericoException
* @throws ValorNoPositivoException
* @throws IOException
* @throws NumberFormatException
*/
private static void ejecutaMenu()
throws ParametroNoNumericoException, ValorNoPositivoException, NumberFormatException, IOException {
int opcion;
do {
mostrarMenu();
opcion = elegirOpcion();
switch (opcion) {
case 1:
almacen.muestraListado();
break;
case 2:
darAlta();
break;
case 3:
darBaja();
break;
case 4:
modificarArticulo();
break;
case 5:
incrementarStock();
break;
case 6:
decrementarStock();
break;
case 7:
finalizarPrograma();
break;
// si el switch no entra en ningún case, entra en default
default:
System.out.println("No introdujiste una opción correcta. Inténtalo de nuevo.\n");
break;
}
} while (opcion != 7);
}
/**
* método vacio que añade un nuevo artículo al almacén
*
* @throws IOException
* @throws NumberFormatException
*/
private static void darAlta() throws ValorNoPositivoException, NumberFormatException, IOException {
try {
String descripcion = Teclado.leerCadena("Introduce una breve descripción del artículo:");
double precioCompra = Teclado.leerDecimal("Precio de compra del artículo: ");
double precioVenta = Teclado.leerDecimal("Precio de venta del artículo: ");
int stock = Teclado.leerEntero("Cantidad del artículo en stock: ");
almacen.darAlta(descripcion, precioCompra, precioVenta, stock);
System.out.println("Artículo dado de alta correctamente.\n");
} catch (ValorNoPositivoException e) {
System.err.println("Hubo algún problema al añadir el artículo.\n" + e.getMessage());
sc.nextLine();
}
}
/**
* método vacio que elimina un artículo del almacén
*/
private static void darBaja() {
try {
int codigo = Teclado.leerEntero("Introduce el código identificador del artículo a eliminar: ");
almacen.darBaja(codigo);
} catch (Exception e) { // si no existe el codigo, salta el catch
System.err.println("El artículo no se encuentra en el almacén.\n");
sc.nextLine();
}
}
/**
* método vacio que permite modificar los valores de un artículo
*/
private static void modificarArticulo() {
try {
System.out.print("Introduce el código identificador del artículo a modificar: ");
int codigo = sc.nextInt();
sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.println("Introduce una breve descripción del artículo:");
String descripcion = sc.nextLine();
System.out.print("Precio de compra del artículo: ");
double precioCompra = sc.nextDouble();
System.out.print("Precio de venta del artículo: ");
double precioVenta = sc.nextDouble();
System.out.print("Cantidad del artículo en stock: ");
int stock = sc.nextInt();
// if (precioCompra < 0 || precioVenta < 0 || stock < 0) {
// throw new ValorNoPositivoException("Introdujiste algún valor negativo.");
// }
almacen.modificarArticulo(articulo, descripcion, precioCompra, precioVenta, stock);
} catch (Exception e) {
System.err.println("Hubo algún problema al modificar el artículo.\n" + e.getMessage());
sc.nextLine();
}
}
/**
* método vacio que incrementa el stock según el parámetro codigo que le envie
* el usuario
*/
private static void incrementarStock() {
try {
System.out.print("Introduce el código identificador del artículo a aumentar el stock: ");
int codigo = sc.nextInt();
// sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.print("Introduce cuánto stock nuevo hay en el almacén (" + articulo.getStock() + " actuales): ");
int cantidad = sc.nextInt();
// throw new ValorNoPositivoException("No se pueden añadir números negativos.");
// sc.nextLine();
almacen.incrementarStock(codigo, cantidad);
System.out.println("Stock añadido correctamente.");
// if (cantidad < 0) {
//
//
//
// }
} catch (Exception e) {
System.err.println("Hubo algún problema al incrementar el stock.\n" + e.getMessage());
// sc.nextLine();
}
}
/**
* método vacio que decrementa el stock según el parámetro codigo que le envie
* el usuario
*/
private static void decrementarStock() {
try {
System.out.print("Introduce el código identificador del artículo a disminuir el sotck: ");
int codigo = sc.nextInt();
sc.nextLine();
Articulo articulo = almacen.getCodigo(codigo);
System.out.println("Introduce cuánto stock se ha eliminado del almacén (" + articulo.getStock() + " actuales): ");
int cantidad = sc.nextInt();
// sc.nextLine();
// if (cantidad < 0) {
// cantidad *= -1;
// }
// if (articulo.getStock() - cantidad < 0) {
// throw new ValorNoPositivoException("El stock no puede ser negativo.");
// }
almacen.decrementarStock(codigo, cantidad);
System.out.println("Stock eliminado correctamente.");
} catch (Exception e) {
System.err.println("Hubo algún problema al decrementar el stock.\n" + e.getMessage());
sc.nextLine();
}
}
} | 7,670 | 0.654918 | 0.649001 | 295 | 23.783051 | 29.361343 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.938983 | false | false | 2 |
4f4d581309a5be9e624fb0fe60585050a0565bd9 | 3,985,729,704,221 | 9c971f816e314d31b6d0c52dd1979f3bfec62212 | /lib_image_loader/src/main/java/com/tomtaw/image_loader/glide/CustomGlideModule.java | ff89ddba585eb2be2d4a33fa315cea0d86494961 | [] | no_license | zyl0501/common-controller | https://github.com/zyl0501/common-controller | 5ca7074579d2417146eebb20d91add08ec4962c2 | 9eebcbff9b7570624e3635717efa5388175dbf61 | refs/heads/master | 2020-03-23T01:33:39.829000 | 2018-07-14T07:02:57 | 2018-07-14T07:02:57 | 140,924,348 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tomtaw.image_loader.glide;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.GlideModule;
import com.tomtaw.image_loader.ConfigOptions;
/**
* glide 3.5 版本之后,在manifest中配置meta-data
*/
public class CustomGlideModule implements GlideModule{
@Override public void applyOptions(Context context, GlideBuilder builder) {
builder.setDiskCache(
new InternalCacheDiskCacheFactory(context, ConfigOptions.MAX_DISK_CACHE_SIZE));
}
@Override public void registerComponents(Context context, Glide glide) {
// register ModelLoaders here.
}
}
| UTF-8 | Java | 772 | java | CustomGlideModule.java | Java | [] | null | [] | package com.tomtaw.image_loader.glide;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.GlideModule;
import com.tomtaw.image_loader.ConfigOptions;
/**
* glide 3.5 版本之后,在manifest中配置meta-data
*/
public class CustomGlideModule implements GlideModule{
@Override public void applyOptions(Context context, GlideBuilder builder) {
builder.setDiskCache(
new InternalCacheDiskCacheFactory(context, ConfigOptions.MAX_DISK_CACHE_SIZE));
}
@Override public void registerComponents(Context context, Glide glide) {
// register ModelLoaders here.
}
}
| 772 | 0.766578 | 0.763926 | 23 | 31.782608 | 28.799089 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 2 |
665fcc8796be35e5d2d717a8ae9260e66da730c7 | 21,028,159,896,496 | 64f2747d4de7a2606d71b9306b4b14e0dd49d436 | /component/ArmyProductionManager.java | e493c759651f0068c1cfe9d6d60a5af9cbe7c4c0 | [] | no_license | cgy4ever/SAI | https://github.com/cgy4ever/SAI | fc002870253a8784c0f06f990f5e040f3f66d705 | 4068dded68d729cd8e9fa590df55de02e5accb49 | refs/heads/master | 2016-09-11T03:42:50.473000 | 2015-04-21T18:48:52 | 2015-04-21T18:48:52 | 30,404,165 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import task.Task;
import task.TrainUnit;
import bwapi.Unit;
import bwapi.UnitType;
import main.Bot;
public class ArmyProductionManager extends Component {
public ArmyProductionManager(Bot r) {
super(r);
}
@Override
public int getResourcePriority() {
return 100;
}
@Override
public String getName() {
return "ArmyProductionManager";
}
@Override
public void onFrame() {
//root.goal.setGoal(UnitType.Protoss_Gateway, 2);
//root.goal.setGoal(UnitType.Protoss_Robotics_Facility, 2);
//root.goal.setGoal(UnitType.Protoss_Stargate, 2);
List <Unit> freeGateway = new ArrayList<Unit>();
List <Unit> freeRoboticsFacility = new ArrayList<Unit>();
List <Unit> freeStargate = new ArrayList<Unit>();
HashMap<UnitType, List<Unit>> freeBuilding = new HashMap<UnitType, List<Unit>>();
freeBuilding.put(UnitType.Protoss_Gateway, freeGateway);
freeBuilding.put(UnitType.Protoss_Robotics_Facility, freeRoboticsFacility);
freeBuilding.put(UnitType.Protoss_Stargate, freeStargate);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Gateway))
if(root.info.canStartNewTask(u))
freeGateway.add(u);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Robotics_Facility))
if(root.info.canStartNewTask(u))
freeRoboticsFacility.add(u);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Stargate))
if(root.info.canStartNewTask(u))
freeStargate.add(u);
// deal with 'require'
//for(UnitType ut : root.goal.armyUnit)
// root.goal.setGoal(ut);
for(UnitType ut : root.goal.armyUnit)
{
if(root.goal.getBuilding(ut) == null)
continue;
if(root.goal.finishAllPrerequests(ut) == false)
continue;
int need = root.goal.getGoal(ut) - root.util.countUnit(ut, true, true, true);
if(need <= 0)
continue;
List<Unit> buildings = freeBuilding.get(root.goal.getBuilding(ut));
//System.out.println(ut + " needs " + need + " .. haveFreeBuildiing = " + freeGateway.size());
for(int i = 0; i < need; i++)
{
if(buildings.size() == 0)
break;
Unit b = buildings.get(buildings.size()-1);
TrainUnit task = new TrainUnit(root, b, ut);
//System.out.println("buingds = " + buildings.size());
if(makeProposal(task))
buildings.remove(buildings.size()-1);
}
}
}
}
| UTF-8 | Java | 2,406 | java | ArmyProductionManager.java | Java | [] | null | [] | package component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import task.Task;
import task.TrainUnit;
import bwapi.Unit;
import bwapi.UnitType;
import main.Bot;
public class ArmyProductionManager extends Component {
public ArmyProductionManager(Bot r) {
super(r);
}
@Override
public int getResourcePriority() {
return 100;
}
@Override
public String getName() {
return "ArmyProductionManager";
}
@Override
public void onFrame() {
//root.goal.setGoal(UnitType.Protoss_Gateway, 2);
//root.goal.setGoal(UnitType.Protoss_Robotics_Facility, 2);
//root.goal.setGoal(UnitType.Protoss_Stargate, 2);
List <Unit> freeGateway = new ArrayList<Unit>();
List <Unit> freeRoboticsFacility = new ArrayList<Unit>();
List <Unit> freeStargate = new ArrayList<Unit>();
HashMap<UnitType, List<Unit>> freeBuilding = new HashMap<UnitType, List<Unit>>();
freeBuilding.put(UnitType.Protoss_Gateway, freeGateway);
freeBuilding.put(UnitType.Protoss_Robotics_Facility, freeRoboticsFacility);
freeBuilding.put(UnitType.Protoss_Stargate, freeStargate);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Gateway))
if(root.info.canStartNewTask(u))
freeGateway.add(u);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Robotics_Facility))
if(root.info.canStartNewTask(u))
freeRoboticsFacility.add(u);
for(Unit u : root.info.getMyUnitsByType(UnitType.Protoss_Stargate))
if(root.info.canStartNewTask(u))
freeStargate.add(u);
// deal with 'require'
//for(UnitType ut : root.goal.armyUnit)
// root.goal.setGoal(ut);
for(UnitType ut : root.goal.armyUnit)
{
if(root.goal.getBuilding(ut) == null)
continue;
if(root.goal.finishAllPrerequests(ut) == false)
continue;
int need = root.goal.getGoal(ut) - root.util.countUnit(ut, true, true, true);
if(need <= 0)
continue;
List<Unit> buildings = freeBuilding.get(root.goal.getBuilding(ut));
//System.out.println(ut + " needs " + need + " .. haveFreeBuildiing = " + freeGateway.size());
for(int i = 0; i < need; i++)
{
if(buildings.size() == 0)
break;
Unit b = buildings.get(buildings.size()-1);
TrainUnit task = new TrainUnit(root, b, ut);
//System.out.println("buingds = " + buildings.size());
if(makeProposal(task))
buildings.remove(buildings.size()-1);
}
}
}
}
| 2,406 | 0.693682 | 0.689111 | 88 | 26.34091 | 24.454451 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.556818 | false | false | 2 |
e4f5b108c58dba9604964954a973f49b4a1da04e | 17,910,013,681,079 | fd6f5015bfc9f666b194a2984c498251cd3612db | /src/java_210701_210711/kyw/Solution_0705.java | c46345db8deabc2c7be61857c97d2ab8f606a7c0 | [] | no_license | BigdataCodingStudy/Coding_Fundamental | https://github.com/BigdataCodingStudy/Coding_Fundamental | 66eb0695f08f98543b9408984126967d27ceda3d | 5303095584407b65592a693355928a1677bd092c | refs/heads/master | 2023-06-26T10:06:04.499000 | 2021-07-29T12:31:11 | 2021-07-29T12:31:11 | 378,971,388 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package java_210701_210711.kyw;
//정수 제곱근 판별
public class Solution_0705 {
public long solution(long n) {
long answer = 0;
if((int)Math.sqrt(n)==Math.sqrt(n)) {
answer = (long)(Math.pow(Math.sqrt(n)+1, 2));
}else {
answer = (-1);
}
return answer;
}
public static void main(String[] args) {
Solution_0705 s = new Solution_0705();
System.out.println(s.solution(120));
}
}
| UTF-8 | Java | 511 | java | Solution_0705.java | Java | [] | null | [] | package java_210701_210711.kyw;
//정수 제곱근 판별
public class Solution_0705 {
public long solution(long n) {
long answer = 0;
if((int)Math.sqrt(n)==Math.sqrt(n)) {
answer = (long)(Math.pow(Math.sqrt(n)+1, 2));
}else {
answer = (-1);
}
return answer;
}
public static void main(String[] args) {
Solution_0705 s = new Solution_0705();
System.out.println(s.solution(120));
}
}
| 511 | 0.503018 | 0.440644 | 32 | 13.53125 | 16.02339 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5625 | false | false | 2 |
9134dff2b8403c1e062e123e39a8e09cde4c7633 | 26,534,307,991,443 | 50dc01b858ccbe00aa371e295fd683cc616d427e | /src/com/sebli/Main.java | e75e99b67a8ffa6f246343dcce653e9611e0a9d2 | [] | no_license | seblechernet/RoboResume | https://github.com/seblechernet/RoboResume | f1e47e9d145d016188b9458391231052d12e0b52 | 93798835b33423dedd0f127dfb88fd1909d1638b | refs/heads/master | 2020-04-02T00:26:07.825000 | 2018-10-21T14:23:22 | 2018-10-21T14:23:22 | 153,804,751 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sebli;
public class Main {
public static void main(String[] args) {
ResumeMaker resumeMaker=new ResumeMaker();
resumeMaker.resumeBuilder();
}
}
| UTF-8 | Java | 169 | java | Main.java | Java | [] | null | [] | package com.sebli;
public class Main {
public static void main(String[] args) {
ResumeMaker resumeMaker=new ResumeMaker();
resumeMaker.resumeBuilder();
}
}
| 169 | 0.710059 | 0.710059 | 10 | 15.9 | 16.759773 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
bd4ac9f2644bea8c3b27db58a0373de5e8c210f2 | 18,038,862,698,274 | bc8f88c9a8d309564f10360d6189e9a5a4b1f30f | /src/main/java/co/com/myappname/restcontroller/GreetingController.java | 99a1128de7135aac83c4ccec953adaed020def86 | [] | no_license | stedennis90/Minimal-SpringBoot-App-with-Gradle | https://github.com/stedennis90/Minimal-SpringBoot-App-with-Gradle | 87cec90643316ec2537b6a772fc709afb7e462e6 | 403880922c73a31466c5722ae850b82d1adbf2e1 | refs/heads/master | 2020-05-24T17:07:24.521000 | 2017-03-13T18:50:15 | 2017-03-13T18:50:15 | 84,860,845 | 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 co.com.myappname.restcontroller;
import co.com.myappname.dto.Greeting;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author Dmartinezb
*/
@RestController
public class GreetingController implements ErrorController{
private static final String ERROR_PATH = "/error";
private static final String TEMPLATE = "Hello, %s!";
private final AtomicLong COUNTER = new AtomicLong();
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(COUNTER.incrementAndGet(),
String.format(TEMPLATE, name));
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String error() {
return "Sorry, an error has ocurred!";
}
}
| UTF-8 | Java | 1,425 | java | GreetingController.java | Java | [
{
"context": "bind.annotation.RestController;\n\n/**\n *\n * @author Dmartinezb\n */\n@RestController\npublic class GreetingControll",
"end": 595,
"score": 0.9996377229690552,
"start": 585,
"tag": "USERNAME",
"value": "Dmartinezb"
}
] | 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 co.com.myappname.restcontroller;
import co.com.myappname.dto.Greeting;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author Dmartinezb
*/
@RestController
public class GreetingController implements ErrorController{
private static final String ERROR_PATH = "/error";
private static final String TEMPLATE = "Hello, %s!";
private final AtomicLong COUNTER = new AtomicLong();
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(COUNTER.incrementAndGet(),
String.format(TEMPLATE, name));
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String error() {
return "Sorry, an error has ocurred!";
}
}
| 1,425 | 0.703158 | 0.703158 | 47 | 29.319149 | 25.532713 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468085 | false | false | 2 |
894b287423aec0eab5e61c5cc38eb992f791c06f | 12,111,807,833,486 | eb1343219a925101de1b4ca4aadae71b51dfffd2 | /mnisqm/mnisqm-services/src/main/java/com/lachesis/mnisqm/module/user/dao/ComUserEducationMapper.java | 47f327d1a72cf9d955af2a91f46c97197bae7eb6 | [
"Apache-2.0"
] | permissive | gavin2lee/incubator | https://github.com/gavin2lee/incubator | b961c23c63fc88c059e74e427b665125115717db | c95623af811195c3e89513ec30e52862d6562add | refs/heads/master | 2020-12-13T20:52:26.951000 | 2017-01-25T00:31:59 | 2017-01-25T00:31:59 | 58,938,038 | 4 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lachesis.mnisqm.module.user.dao;
import com.lachesis.mnisqm.module.user.domain.ComUserEducation;
public interface ComUserEducationMapper {
/**
* 逻辑删除
* @param edu
* @return
*/
public int deleteByPrimaryKey(ComUserEducation edu);
int insert(ComUserEducation record);
int updateByPrimaryKey(ComUserEducation record);
} | UTF-8 | Java | 361 | java | ComUserEducationMapper.java | Java | [] | null | [] | package com.lachesis.mnisqm.module.user.dao;
import com.lachesis.mnisqm.module.user.domain.ComUserEducation;
public interface ComUserEducationMapper {
/**
* 逻辑删除
* @param edu
* @return
*/
public int deleteByPrimaryKey(ComUserEducation edu);
int insert(ComUserEducation record);
int updateByPrimaryKey(ComUserEducation record);
} | 361 | 0.756374 | 0.756374 | 16 | 21.125 | 22.775742 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 2 |
35c38d82ba0ab2367259ef93640b85deadbdbad8 | 549,755,863,631 | c474b03758be154e43758220e47b3403eb7fc1fc | /apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/google/android/gms/ads/internal/overlay/C4276h.java | 40d98c46f7c2d276df4e803f83ec2472083c4b0e | [] | no_license | EstebanDalelR/tinderAnalysis | https://github.com/EstebanDalelR/tinderAnalysis | f80fe1f43b3b9dba283b5db1781189a0dd592c24 | 941e2c634c40e5dbf5585c6876ef33f2a578b65c | refs/heads/master | 2020-04-04T09:03:32.659000 | 2018-11-23T20:41:28 | 2018-11-23T20:41:28 | 155,805,042 | 0 | 0 | null | false | 2018-11-18T16:02:45 | 2018-11-02T02:44:34 | 2018-11-18T15:58:25 | 2018-11-18T16:02:44 | 353,670 | 0 | 0 | 0 | null | false | null | package com.google.android.gms.ads.internal.overlay;
import android.graphics.Bitmap;
import com.google.android.gms.ads.internal.ar;
import com.google.android.gms.internal.dy;
import com.google.android.gms.internal.fk;
import com.google.android.gms.internal.zzzv;
@zzzv
/* renamed from: com.google.android.gms.ads.internal.overlay.h */
final class C4276h extends dy {
/* renamed from: a */
final /* synthetic */ C4275c f13921a;
private C4276h(C4275c c4275c) {
this.f13921a = c4275c;
}
/* renamed from: a */
public final void m17153a() {
Bitmap a = ar.m8666w().a(Integer.valueOf(this.f13921a.f13901a.zzcjg.zzaqt));
if (a != null) {
fk.f16060a.post(new C2399i(this, ar.m8650g().a(this.f13921a.f13902c, a, this.f13921a.f13901a.zzcjg.zzaqr, this.f13921a.f13901a.zzcjg.zzaqs)));
}
}
/* renamed from: b */
public final void m17154b() {
}
}
| UTF-8 | Java | 922 | java | C4276h.java | Java | [] | null | [] | package com.google.android.gms.ads.internal.overlay;
import android.graphics.Bitmap;
import com.google.android.gms.ads.internal.ar;
import com.google.android.gms.internal.dy;
import com.google.android.gms.internal.fk;
import com.google.android.gms.internal.zzzv;
@zzzv
/* renamed from: com.google.android.gms.ads.internal.overlay.h */
final class C4276h extends dy {
/* renamed from: a */
final /* synthetic */ C4275c f13921a;
private C4276h(C4275c c4275c) {
this.f13921a = c4275c;
}
/* renamed from: a */
public final void m17153a() {
Bitmap a = ar.m8666w().a(Integer.valueOf(this.f13921a.f13901a.zzcjg.zzaqt));
if (a != null) {
fk.f16060a.post(new C2399i(this, ar.m8650g().a(this.f13921a.f13902c, a, this.f13921a.f13901a.zzcjg.zzaqr, this.f13921a.f13901a.zzcjg.zzaqs)));
}
}
/* renamed from: b */
public final void m17154b() {
}
}
| 922 | 0.670282 | 0.560738 | 30 | 29.733334 | 31.250528 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 2 |
1f5b5cfca765cf78f23852d651693a85a565b5b5 | 14,809,047,237,684 | 51394231ea039236457c73dbcdb5997d9cf2d6a1 | /commons-vfs2/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClientFactory.java | cf703eebfcd295ebbce986e8c369e7b18cdec6a6 | [
"Apache-2.0"
] | permissive | wso2/wso2-commons-vfs | https://github.com/wso2/wso2-commons-vfs | 9c43b32ecdd572c459df32e6a5a7fbfeb1f8459c | 94238737553d356f6612331e9c1508af04c1f965 | refs/heads/2.2.x | 2023-08-21T16:37:18.991000 | 2023-08-17T06:37:01 | 2023-08-17T06:37:01 | 17,473,456 | 40 | 72 | Apache-2.0 | false | 2023-08-17T06:35:14 | 2014-03-06T10:01:42 | 2023-08-17T06:03:25 | 2023-08-17T06:35:13 | 1,228 | 38 | 65 | 2 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.apache.commons.vfs2.provider.ftp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPHTTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.Proxy;
import java.net.SocketTimeoutException;
/**
* Create a FtpClient instance.
*/
public final class FtpClientFactory {
private FtpClientFactory() {
}
/**
* Creates a new connection to the server.
*
* @param hostname The host name of the server.
* @param port The port to connect to.
* @param username The name of the user for authentication.
* @param password The user's password.
* @param workingDirectory The base directory.
* @param fileSystemOptions The FileSystemOptions.
* @return An FTPClient.
* @throws FileSystemException if an error occurs while connecting.
*/
public static FTPClient createConnection(final String hostname, final int port, final char[] username,
final char[] password, final String workingDirectory, final FileSystemOptions fileSystemOptions)
throws FileSystemException {
final FtpConnectionFactory factory = new FtpConnectionFactory(FtpFileSystemConfigBuilder.getInstance());
return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions);
}
/**
* Creates a new connection to the server.
*
* @param hostname The host name of the server.
* @param port The port to connect to.
* @param username The name of the user for authentication.
* @param password The user's password.
* @param workingDirectory The base directory.
* @param fileSystemOptions The FileSystemOptions.
* @param proxyServer Proxy server address
* @param proxyPort Proxy server port
* @param proxyUser Proxy server username
* @param proxyPassword Proxy server password
* @return An FTPClient.
* @throws FileSystemException if an error occurs while connecting.
*/
public static FTPClient createConnection(String hostname, int port, char[] username, char[] password, String
workingDirectory, FileSystemOptions fileSystemOptions, String proxyServer, String proxyPort, String
proxyUser, String proxyPassword, String timeout, String retryCount) throws FileSystemException {
final FtpConnectionFactory factory = new FtpConnectionFactory(FtpFileSystemConfigBuilder.getInstance());
return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions,
proxyServer, proxyPort, proxyUser, proxyPassword, timeout, retryCount);
}
/** Connection Factory, used to configure the FTPClient. */
public static final class FtpConnectionFactory extends ConnectionFactory<FTPClient, FtpFileSystemConfigBuilder> {
private FtpConnectionFactory(final FtpFileSystemConfigBuilder builder) {
super(builder);
}
@Override
protected FTPClient createClient(final FileSystemOptions fileSystemOptions) {
return new FTPClient();
}
@Override
protected void setupOpenConnection(final FTPClient client, final FileSystemOptions fileSystemOptions) {
// nothing to do for FTP
}
}
/** Abstract Factory, used to configure different FTPClients. */
public abstract static class ConnectionFactory<C extends FTPClient, B extends FtpFileSystemConfigBuilder> {
private static final char[] ANON_CHAR_ARRAY = "anonymous".toCharArray();
private static final int BUFSZ = 40;
private final Log log = LogFactory.getLog(getClass());
protected B builder;
protected ConnectionFactory(final B builder) {
this.builder = builder;
}
public C createConnection(final String hostname, final int port, char[] username, char[] password, final
String workingDirectory, final FileSystemOptions fileSystemOptions) throws FileSystemException {
return createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions, null,
null, null, null, null, null);
}
public C createConnection(String hostname, int port, char[] username, char[] password, String
workingDirectory, FileSystemOptions fileSystemOptions, String proxyServer, String proxyPort, String
proxyUser, String proxyPassword, String timeout, String retryCount) throws FileSystemException {
// Determine the username and password to use
if (username == null) {
username = ANON_CHAR_ARRAY;
}
if (password == null) {
password = ANON_CHAR_ARRAY;
}
Integer connectionTimeout;
if (timeout == null) {
connectionTimeout = builder.getConnectTimeout(fileSystemOptions);
} else {
try {
connectionTimeout = Integer.parseInt(timeout);
} catch (NumberFormatException nfe) {
log.warn("Invalid connection timeout " + timeout + ". Set the connectionTimeout as 5000. (default)");
connectionTimeout = 5000;
}
}
Integer connectionRetryCount;
if (retryCount == null) {
connectionRetryCount = builder.getRetryCount(fileSystemOptions);
} else {
try {
connectionRetryCount = Integer.parseInt(retryCount);
} catch (NumberFormatException nfe) {
log.warn("Invalid connection retry count " + retryCount + ". Set the connectionRetryCount as 5. "
+ "(default)");
connectionRetryCount = 5;
}
}
boolean proxyMode = false;
try {
final C client;
//Implement the logic to support FTP over HTTP Proxy
if (proxyServer != null && proxyPort != null) {
int parsedProxyPort;
try {
parsedProxyPort = Integer.parseInt(proxyPort);
} catch (NumberFormatException e) {
log.warn("Invalid proxy port " + proxyPort + ". Set the port as 8080. (default)");
parsedProxyPort = 8080;
}
if (proxyUser != null && proxyPassword != null) {
client = (C) new FTPHTTPClient(proxyServer, parsedProxyPort, proxyUser, proxyPassword);
proxyMode = true;
} else {
client = (C) new FTPHTTPClient(proxyServer, parsedProxyPort);
proxyMode = true;
}
} else {
client = createClient(fileSystemOptions);
}
if (log.isDebugEnabled()) {
final Writer writer = new StringWriter(1024) {
@Override
public void flush() {
final StringBuffer buffer = getBuffer();
String message = buffer.toString();
if (message.toUpperCase().startsWith("PASS ") && message.length() > 5) {
message = "PASS ***";
}
log.debug(message);
buffer.setLength(0);
}
};
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(writer)));
}
configureClient(fileSystemOptions, client);
final FTPFileEntryParserFactory myFactory = builder.getEntryParserFactory(fileSystemOptions);
if (myFactory != null) {
client.setParserFactory(myFactory);
}
final Boolean remoteVerification = builder.getRemoteVerification(fileSystemOptions);
if (remoteVerification != null) {
client.setRemoteVerificationEnabled(remoteVerification.booleanValue());
}
try {
preConfigureClient(fileSystemOptions);
// Set connect timeout
final Integer connectTimeout = builder.getConnectTimeout(fileSystemOptions);
if (connectTimeout != null) {
client.setDefaultTimeout(connectTimeout.intValue());
}
final String controlEncoding = builder.getControlEncoding(fileSystemOptions);
if (controlEncoding != null) {
client.setControlEncoding(controlEncoding);
}
final Proxy proxy = builder.getProxy(fileSystemOptions);
if (proxy != null) {
client.setProxy(proxy);
}
//Need to enforce this since some times if we don't do this thread will hang forever
if (proxyMode) {
client.setConnectTimeout(connectionTimeout);
boolean connect = false;
while (!connect && (connectionRetryCount > 0)) {
try {
client.connect(hostname, port);
connect = true;
} catch (SocketTimeoutException e) {
connectionRetryCount--;
} catch (IOException e) {
connectionRetryCount--;
}
}
} else {
client.connect(hostname, port);
}
final int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
}
// Login
if (!client.login(UserAuthenticatorUtils.toString(username), UserAuthenticatorUtils.toString
(password))) {
throw new FileSystemException("vfs.provider.ftp/login.error", hostname,
UserAuthenticatorUtils.toString(username));
}
FtpFileType fileType = builder.getFileType(fileSystemOptions);
if (fileType == null) {
fileType = FtpFileType.BINARY;
}
// Set binary mode
if (!client.setFileType(fileType.getValue())) {
throw new FileSystemException("vfs.provider.ftp/set-file-type.error", fileType);
}
// Set dataTimeout value
final Integer dataTimeout = builder.getDataTimeout(fileSystemOptions);
if (dataTimeout != null) {
client.setDataTimeout(dataTimeout.intValue());
}
final Integer socketTimeout = builder.getSoTimeout(fileSystemOptions);
if (socketTimeout != null) {
client.setSoTimeout(socketTimeout.intValue());
}
final Boolean userDirIsRoot = builder.getUserDirIsRoot(fileSystemOptions);
if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue())) {
if (!client.changeWorkingDirectory(workingDirectory)) {
throw new FileSystemException("vfs.provider.ftp/change-work-directory.error",
workingDirectory);
}
}
final Boolean passiveMode = builder.getPassiveMode(fileSystemOptions);
if (proxyMode || (passiveMode != null && passiveMode.booleanValue())) {
client.enterLocalPassiveMode();
}
setupOpenConnection(client, fileSystemOptions);
} catch (final IOException e) {
if (client.isConnected()) {
client.disconnect();
}
throw e;
}
return client;
} catch (final Exception exc) {
throw new FileSystemException("vfs.provider.ftp/connect.error", exc, hostname);
}
}
protected void preConfigureClient(FileSystemOptions fileSystemOptions) throws
Exception {
// nothing to do for FTP
}
protected abstract C createClient(FileSystemOptions fileSystemOptions) throws FileSystemException;
protected abstract void setupOpenConnection(C client, FileSystemOptions fileSystemOptions) throws IOException;
protected void configureClient(final FileSystemOptions fileSystemOptions, final C client) throws Exception {
final String key = builder.getEntryParser(fileSystemOptions);
if (key != null) {
final FTPClientConfig config = new FTPClientConfig(key);
final String serverLanguageCode = builder.getServerLanguageCode(fileSystemOptions);
if (serverLanguageCode != null) {
config.setServerLanguageCode(serverLanguageCode);
}
final String defaultDateFormat = builder.getDefaultDateFormat(fileSystemOptions);
if (defaultDateFormat != null) {
config.setDefaultDateFormatStr(defaultDateFormat);
}
final String recentDateFormat = builder.getRecentDateFormat(fileSystemOptions);
if (recentDateFormat != null) {
config.setRecentDateFormatStr(recentDateFormat);
}
final String serverTimeZoneId = builder.getServerTimeZoneId(fileSystemOptions);
if (serverTimeZoneId != null) {
config.setServerTimeZoneId(serverTimeZoneId);
}
final String[] shortMonthNames = builder.getShortMonthNames(fileSystemOptions);
if (shortMonthNames != null) {
final StringBuilder shortMonthNamesStr = new StringBuilder(BUFSZ);
for (final String shortMonthName : shortMonthNames) {
if (shortMonthNamesStr.length() > 0) {
shortMonthNamesStr.append("|");
}
shortMonthNamesStr.append(shortMonthName);
}
config.setShortMonthNames(shortMonthNamesStr.toString());
}
client.configure(config);
}
}
}
}
| UTF-8 | Java | 16,525 | java | FtpClientFactory.java | Java | [
{
"context": "ser for authentication.\n * @param password The user's password.\n * @param workingDirectory The base director",
"end": 1960,
"score": 0.9578225016593933,
"start": 1945,
"tag": "PASSWORD",
"value": "user's password"
},
{
"context": "or authentication.\n * @p... | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.apache.commons.vfs2.provider.ftp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPHTTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.Proxy;
import java.net.SocketTimeoutException;
/**
* Create a FtpClient instance.
*/
public final class FtpClientFactory {
private FtpClientFactory() {
}
/**
* Creates a new connection to the server.
*
* @param hostname The host name of the server.
* @param port The port to connect to.
* @param username The name of the user for authentication.
* @param password The <PASSWORD>.
* @param workingDirectory The base directory.
* @param fileSystemOptions The FileSystemOptions.
* @return An FTPClient.
* @throws FileSystemException if an error occurs while connecting.
*/
public static FTPClient createConnection(final String hostname, final int port, final char[] username,
final char[] password, final String workingDirectory, final FileSystemOptions fileSystemOptions)
throws FileSystemException {
final FtpConnectionFactory factory = new FtpConnectionFactory(FtpFileSystemConfigBuilder.getInstance());
return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions);
}
/**
* Creates a new connection to the server.
*
* @param hostname The host name of the server.
* @param port The port to connect to.
* @param username The name of the user for authentication.
* @param password <PASSWORD>.
* @param workingDirectory The base directory.
* @param fileSystemOptions The FileSystemOptions.
* @param proxyServer Proxy server address
* @param proxyPort Proxy server port
* @param proxyUser Proxy server username
* @param proxyPassword Proxy server password
* @return An FTPClient.
* @throws FileSystemException if an error occurs while connecting.
*/
public static FTPClient createConnection(String hostname, int port, char[] username, char[] password, String
workingDirectory, FileSystemOptions fileSystemOptions, String proxyServer, String proxyPort, String
proxyUser, String proxyPassword, String timeout, String retryCount) throws FileSystemException {
final FtpConnectionFactory factory = new FtpConnectionFactory(FtpFileSystemConfigBuilder.getInstance());
return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions,
proxyServer, proxyPort, proxyUser, proxyPassword, timeout, retryCount);
}
/** Connection Factory, used to configure the FTPClient. */
public static final class FtpConnectionFactory extends ConnectionFactory<FTPClient, FtpFileSystemConfigBuilder> {
private FtpConnectionFactory(final FtpFileSystemConfigBuilder builder) {
super(builder);
}
@Override
protected FTPClient createClient(final FileSystemOptions fileSystemOptions) {
return new FTPClient();
}
@Override
protected void setupOpenConnection(final FTPClient client, final FileSystemOptions fileSystemOptions) {
// nothing to do for FTP
}
}
/** Abstract Factory, used to configure different FTPClients. */
public abstract static class ConnectionFactory<C extends FTPClient, B extends FtpFileSystemConfigBuilder> {
private static final char[] ANON_CHAR_ARRAY = "anonymous".toCharArray();
private static final int BUFSZ = 40;
private final Log log = LogFactory.getLog(getClass());
protected B builder;
protected ConnectionFactory(final B builder) {
this.builder = builder;
}
public C createConnection(final String hostname, final int port, char[] username, char[] password, final
String workingDirectory, final FileSystemOptions fileSystemOptions) throws FileSystemException {
return createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions, null,
null, null, null, null, null);
}
public C createConnection(String hostname, int port, char[] username, char[] password, String
workingDirectory, FileSystemOptions fileSystemOptions, String proxyServer, String proxyPort, String
proxyUser, String proxyPassword, String timeout, String retryCount) throws FileSystemException {
// Determine the username and password to use
if (username == null) {
username = ANON_CHAR_ARRAY;
}
if (password == null) {
password = <PASSWORD>;
}
Integer connectionTimeout;
if (timeout == null) {
connectionTimeout = builder.getConnectTimeout(fileSystemOptions);
} else {
try {
connectionTimeout = Integer.parseInt(timeout);
} catch (NumberFormatException nfe) {
log.warn("Invalid connection timeout " + timeout + ". Set the connectionTimeout as 5000. (default)");
connectionTimeout = 5000;
}
}
Integer connectionRetryCount;
if (retryCount == null) {
connectionRetryCount = builder.getRetryCount(fileSystemOptions);
} else {
try {
connectionRetryCount = Integer.parseInt(retryCount);
} catch (NumberFormatException nfe) {
log.warn("Invalid connection retry count " + retryCount + ". Set the connectionRetryCount as 5. "
+ "(default)");
connectionRetryCount = 5;
}
}
boolean proxyMode = false;
try {
final C client;
//Implement the logic to support FTP over HTTP Proxy
if (proxyServer != null && proxyPort != null) {
int parsedProxyPort;
try {
parsedProxyPort = Integer.parseInt(proxyPort);
} catch (NumberFormatException e) {
log.warn("Invalid proxy port " + proxyPort + ". Set the port as 8080. (default)");
parsedProxyPort = 8080;
}
if (proxyUser != null && proxyPassword != null) {
client = (C) new FTPHTTPClient(proxyServer, parsedProxyPort, proxyUser, proxyPassword);
proxyMode = true;
} else {
client = (C) new FTPHTTPClient(proxyServer, parsedProxyPort);
proxyMode = true;
}
} else {
client = createClient(fileSystemOptions);
}
if (log.isDebugEnabled()) {
final Writer writer = new StringWriter(1024) {
@Override
public void flush() {
final StringBuffer buffer = getBuffer();
String message = buffer.toString();
if (message.toUpperCase().startsWith("PASS ") && message.length() > 5) {
message = "PASS ***";
}
log.debug(message);
buffer.setLength(0);
}
};
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(writer)));
}
configureClient(fileSystemOptions, client);
final FTPFileEntryParserFactory myFactory = builder.getEntryParserFactory(fileSystemOptions);
if (myFactory != null) {
client.setParserFactory(myFactory);
}
final Boolean remoteVerification = builder.getRemoteVerification(fileSystemOptions);
if (remoteVerification != null) {
client.setRemoteVerificationEnabled(remoteVerification.booleanValue());
}
try {
preConfigureClient(fileSystemOptions);
// Set connect timeout
final Integer connectTimeout = builder.getConnectTimeout(fileSystemOptions);
if (connectTimeout != null) {
client.setDefaultTimeout(connectTimeout.intValue());
}
final String controlEncoding = builder.getControlEncoding(fileSystemOptions);
if (controlEncoding != null) {
client.setControlEncoding(controlEncoding);
}
final Proxy proxy = builder.getProxy(fileSystemOptions);
if (proxy != null) {
client.setProxy(proxy);
}
//Need to enforce this since some times if we don't do this thread will hang forever
if (proxyMode) {
client.setConnectTimeout(connectionTimeout);
boolean connect = false;
while (!connect && (connectionRetryCount > 0)) {
try {
client.connect(hostname, port);
connect = true;
} catch (SocketTimeoutException e) {
connectionRetryCount--;
} catch (IOException e) {
connectionRetryCount--;
}
}
} else {
client.connect(hostname, port);
}
final int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
}
// Login
if (!client.login(UserAuthenticatorUtils.toString(username), UserAuthenticatorUtils.toString
(password))) {
throw new FileSystemException("vfs.provider.ftp/login.error", hostname,
UserAuthenticatorUtils.toString(username));
}
FtpFileType fileType = builder.getFileType(fileSystemOptions);
if (fileType == null) {
fileType = FtpFileType.BINARY;
}
// Set binary mode
if (!client.setFileType(fileType.getValue())) {
throw new FileSystemException("vfs.provider.ftp/set-file-type.error", fileType);
}
// Set dataTimeout value
final Integer dataTimeout = builder.getDataTimeout(fileSystemOptions);
if (dataTimeout != null) {
client.setDataTimeout(dataTimeout.intValue());
}
final Integer socketTimeout = builder.getSoTimeout(fileSystemOptions);
if (socketTimeout != null) {
client.setSoTimeout(socketTimeout.intValue());
}
final Boolean userDirIsRoot = builder.getUserDirIsRoot(fileSystemOptions);
if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue())) {
if (!client.changeWorkingDirectory(workingDirectory)) {
throw new FileSystemException("vfs.provider.ftp/change-work-directory.error",
workingDirectory);
}
}
final Boolean passiveMode = builder.getPassiveMode(fileSystemOptions);
if (proxyMode || (passiveMode != null && passiveMode.booleanValue())) {
client.enterLocalPassiveMode();
}
setupOpenConnection(client, fileSystemOptions);
} catch (final IOException e) {
if (client.isConnected()) {
client.disconnect();
}
throw e;
}
return client;
} catch (final Exception exc) {
throw new FileSystemException("vfs.provider.ftp/connect.error", exc, hostname);
}
}
protected void preConfigureClient(FileSystemOptions fileSystemOptions) throws
Exception {
// nothing to do for FTP
}
protected abstract C createClient(FileSystemOptions fileSystemOptions) throws FileSystemException;
protected abstract void setupOpenConnection(C client, FileSystemOptions fileSystemOptions) throws IOException;
protected void configureClient(final FileSystemOptions fileSystemOptions, final C client) throws Exception {
final String key = builder.getEntryParser(fileSystemOptions);
if (key != null) {
final FTPClientConfig config = new FTPClientConfig(key);
final String serverLanguageCode = builder.getServerLanguageCode(fileSystemOptions);
if (serverLanguageCode != null) {
config.setServerLanguageCode(serverLanguageCode);
}
final String defaultDateFormat = builder.getDefaultDateFormat(fileSystemOptions);
if (defaultDateFormat != null) {
config.setDefaultDateFormatStr(defaultDateFormat);
}
final String recentDateFormat = builder.getRecentDateFormat(fileSystemOptions);
if (recentDateFormat != null) {
config.setRecentDateFormatStr(recentDateFormat);
}
final String serverTimeZoneId = builder.getServerTimeZoneId(fileSystemOptions);
if (serverTimeZoneId != null) {
config.setServerTimeZoneId(serverTimeZoneId);
}
final String[] shortMonthNames = builder.getShortMonthNames(fileSystemOptions);
if (shortMonthNames != null) {
final StringBuilder shortMonthNamesStr = new StringBuilder(BUFSZ);
for (final String shortMonthName : shortMonthNames) {
if (shortMonthNamesStr.length() > 0) {
shortMonthNamesStr.append("|");
}
shortMonthNamesStr.append(shortMonthName);
}
config.setShortMonthNames(shortMonthNamesStr.toString());
}
client.configure(config);
}
}
}
}
| 16,506 | 0.577247 | 0.575068 | 357 | 45.288517 | 33.651337 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582633 | false | false | 2 |
626e7b4b5f31f227fbbdf63344ddd0125b149df0 | 10,007,273,868,557 | c4d82b0cfa0e1572041969bb25414229c766e293 | /app/src/main/java/com/luckyliuqs/mymusic/adapter/FindFragmentPagerAdapter.java | bbf75d53ab41094fff515ef93f9cd2beaf5493c1 | [
"Apache-2.0"
] | permissive | yunshangdaoren/mymusic | https://github.com/yunshangdaoren/mymusic | 8b33ac055fc39bac7e192c72d5111ac9c2a1fd71 | 809db78d76bdeeb5d59be7786580959581637db3 | refs/heads/master | 2020-05-01T18:20:20.218000 | 2019-10-17T17:24:27 | 2019-10-17T17:24:27 | 177,613,744 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.luckyliuqs.mymusic.adapter;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import com.luckyliuqs.mymusic.fragment.FMFragment;
import com.luckyliuqs.mymusic.fragment.FeedFragment;
import com.luckyliuqs.mymusic.fragment.RecommendFragment;
/**
* 发现界面Adapter类
*/
public class FindFragmentPagerAdapter extends BaseFragmentPagerAdapter<Integer> {
private static String[] titleNames = {"推荐", "朋友", "电台"};
public FindFragmentPagerAdapter(Context context, FragmentManager fm) {
super(context, fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0){
//推荐页面
return RecommendFragment.newInstance();
}else if(position == 1){
//朋友动态页面
return FeedFragment.newInstance();
}else{
//FM电台页面
return FMFragment.newInstance();
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titleNames[position];
}
}
| UTF-8 | Java | 1,178 | java | FindFragmentPagerAdapter.java | Java | [] | null | [] | package com.luckyliuqs.mymusic.adapter;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import com.luckyliuqs.mymusic.fragment.FMFragment;
import com.luckyliuqs.mymusic.fragment.FeedFragment;
import com.luckyliuqs.mymusic.fragment.RecommendFragment;
/**
* 发现界面Adapter类
*/
public class FindFragmentPagerAdapter extends BaseFragmentPagerAdapter<Integer> {
private static String[] titleNames = {"推荐", "朋友", "电台"};
public FindFragmentPagerAdapter(Context context, FragmentManager fm) {
super(context, fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0){
//推荐页面
return RecommendFragment.newInstance();
}else if(position == 1){
//朋友动态页面
return FeedFragment.newInstance();
}else{
//FM电台页面
return FMFragment.newInstance();
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titleNames[position];
}
}
| 1,178 | 0.678191 | 0.674645 | 41 | 26.512196 | 22.333527 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.439024 | false | false | 2 |
57766cb0f199119c05e2e8da47bab6e32e6ebdb7 | 4,724,464,069,859 | 5b7df93bc3e97d081d82ce63d3600e7b0beebac6 | /src/com/herman/ebookstore/sdk/package-info.java | e1a96e34939149300d6d2f2c7eeaaf06d3a60155 | [] | no_license | huangjinbao/E-bookstore | https://github.com/huangjinbao/E-bookstore | 5f502783e96f41804ea3bb9954fd972799fa2d76 | ca52254755e1e5d86ec1138e6ace380fbf403762 | refs/heads/master | 2020-04-12T17:57:11.599000 | 2019-05-17T02:06:10 | 2019-05-17T02:06:10 | 162,663,534 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @Title: package-info.java
* @Package com.herman.ebookstore.sdk
* @Description: TODO()
* @author 黄金宝
* @date 2018年12月13日
* @version V1.0
**/
/**
* @ClassName: package-info
* @Description: TODO()
* @author 黄金宝
* @date 2018年12月13日
*
*/
package com.herman.ebookstore.sdk; | UTF-8 | Java | 325 | java | package-info.java | Java | [
{
"context": "ookstore.sdk\r\n * @Description: TODO()\r\n * @author 黄金宝\r\n * @date 2018年12月13日\r\n * @version V1.0\r\n **/\r\n/*",
"end": 113,
"score": 0.9996536374092102,
"start": 110,
"tag": "NAME",
"value": "黄金宝"
},
{
"context": "package-info\r\n * @Description: TODO()\r\n * @aut... | null | [] | /**
* @Title: package-info.java
* @Package com.herman.ebookstore.sdk
* @Description: TODO()
* @author 黄金宝
* @date 2018年12月13日
* @version V1.0
**/
/**
* @ClassName: package-info
* @Description: TODO()
* @author 黄金宝
* @date 2018年12月13日
*
*/
package com.herman.ebookstore.sdk; | 325 | 0.61794 | 0.55814 | 16 | 16.9375 | 11.18296 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.0625 | false | false | 2 |
ed05bfef4e4a30a6afb8f8a54bdb94c24a607304 | 16,381,005,306,376 | 621f956e62830ab902f8e44bd6424bae9ba067e1 | /src/player/Croupier.java | ecb0aa3db547c2e624e2473cebdb81d7d2006968 | [] | no_license | BioinformaticMarcin/Console-Card-Game | https://github.com/BioinformaticMarcin/Console-Card-Game | c15b279372b775f6b98a2c695f409ee7e9a8392b | 124081be63b2ec6dd15290f83ae8e3496f7bfc8c | refs/heads/master | 2023-04-18T01:26:06.605000 | 2021-04-29T22:28:19 | 2021-04-29T22:28:19 | 356,663,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package player;
import main.Karta;
public class Croupier extends Player {
public Croupier() {
super();
}
public void showFirst() {
Karta karta = actualCards.iterator().next();
System.out.println(karta.toString());
System.out.println("X");
if (karta.getWartosc() == 14) {
System.out.println("Wartość: 1/11");
} else {
System.out.println("Wartość: " + karta.getValue());
}
System.out.println("------------------------------------");
}
public Boolean endGame() {
if (points <= 16) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}
| WINDOWS-1250 | Java | 591 | java | Croupier.java | Java | [] | null | [] | package player;
import main.Karta;
public class Croupier extends Player {
public Croupier() {
super();
}
public void showFirst() {
Karta karta = actualCards.iterator().next();
System.out.println(karta.toString());
System.out.println("X");
if (karta.getWartosc() == 14) {
System.out.println("Wartość: 1/11");
} else {
System.out.println("Wartość: " + karta.getValue());
}
System.out.println("------------------------------------");
}
public Boolean endGame() {
if (points <= 16) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
}
}
| 591 | 0.591141 | 0.579216 | 31 | 17.935484 | 17.288698 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.741935 | false | false | 2 |
7636fa96b904b33f9f48d6113ae78f939a7e1a84 | 35,038,343,200,800 | e5baa5ba65c5cb80b38203b28c064a475aa63693 | /src/cn/edustar/jitar/service/impl/ChatRoomServiceImpl.java | 67bdf99ea8d0bf89dbe0f74be38471f0721a6e22 | [] | no_license | yxxcrtd/jitar2012 | https://github.com/yxxcrtd/jitar2012 | bbe00b1eb2e505400dcfec396201752c3888199c | ccae07ff44a3cb9dc3d0b75673cbca699fa66b80 | refs/heads/master | 2020-05-31T15:26:40.107000 | 2019-06-05T08:05:22 | 2019-06-05T08:05:22 | 190,352,419 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edustar.jitar.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.edustar.jitar.dao.ChatRoomDao;
import cn.edustar.jitar.pojos.ChatRoom;
import cn.edustar.jitar.service.ChatRoomService;
public class ChatRoomServiceImpl implements ChatRoomService{
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(ChatRoomServiceImpl.class);
/** 数据访问对象 */
private ChatRoomDao chatRoomDao;
/** 数据访问对象. */
public void setChatRoomDao(ChatRoomDao chatRoomDao) {
this.chatRoomDao = chatRoomDao;
}
public ChatRoomServiceImpl()
{
}
public int getPrepareCourseRoomId(int prepareCourseId)
{
return chatRoomDao.getPrepareCourseRoomId(prepareCourseId);
}
public int getRoomId(int groupId)
{
return chatRoomDao.getRoomId(groupId);
}
public void saveChatRoom(ChatRoom chatRoom) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 981 | java | ChatRoomServiceImpl.java | Java | [] | null | [] | package cn.edustar.jitar.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.edustar.jitar.dao.ChatRoomDao;
import cn.edustar.jitar.pojos.ChatRoom;
import cn.edustar.jitar.service.ChatRoomService;
public class ChatRoomServiceImpl implements ChatRoomService{
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(ChatRoomServiceImpl.class);
/** 数据访问对象 */
private ChatRoomDao chatRoomDao;
/** 数据访问对象. */
public void setChatRoomDao(ChatRoomDao chatRoomDao) {
this.chatRoomDao = chatRoomDao;
}
public ChatRoomServiceImpl()
{
}
public int getPrepareCourseRoomId(int prepareCourseId)
{
return chatRoomDao.getPrepareCourseRoomId(prepareCourseId);
}
public int getRoomId(int groupId)
{
return chatRoomDao.getRoomId(groupId);
}
public void saveChatRoom(ChatRoom chatRoom) {
// TODO Auto-generated method stub
}
}
| 981 | 0.752351 | 0.752351 | 35 | 25.342857 | 22.428226 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.228571 | false | false | 2 |
e078baf92f1f060d84a4e168dc32c2b9b0d3cd8d | 1,941,325,226,651 | e8f50a80ae48780ddb093a7ecdf61a83cbbbaba8 | /Week2/Triangle.java | 81e8e147912cb31e7d7ed64df097c20605c27853 | [] | no_license | mhsu0020/CSULA-CS202-Winter2016 | https://github.com/mhsu0020/CSULA-CS202-Winter2016 | 244494978ea02802bc09d595dd7a59fbad49f917 | bcab77715f62af90e646342e87fb395c1964de55 | refs/heads/master | 2021-01-10T06:33:09.244000 | 2016-02-25T04:45:05 | 2016-02-25T04:45:05 | 49,025,821 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Triangle {
/*
* numeric primitives:
*
* default value is 0
*
* */
public double base;
public double height;
/*
* defaults to ascii code 0
* */
public char exampleChar;
/*
*
* boolean: default value is false
*
* */
public boolean isWhole;
/*
*
* reference types: null
*
* */
public String[] tags;
public String name;
public Triangle innerTriangle;
public Triangle(double base, double height){
name = "Example Triangle";
this.base = base;
this.height = height;
this.tags = new String[10];
}
// public Triangle(){
// }
public void addTag(String tag){
tags[0] = tag;
}
public double calculateArea() {
return base * height /2;
}
public static void doSomething(){
}
}
| UTF-8 | Java | 746 | java | Triangle.java | Java | [] | null | [] |
public class Triangle {
/*
* numeric primitives:
*
* default value is 0
*
* */
public double base;
public double height;
/*
* defaults to ascii code 0
* */
public char exampleChar;
/*
*
* boolean: default value is false
*
* */
public boolean isWhole;
/*
*
* reference types: null
*
* */
public String[] tags;
public String name;
public Triangle innerTriangle;
public Triangle(double base, double height){
name = "Example Triangle";
this.base = base;
this.height = height;
this.tags = new String[10];
}
// public Triangle(){
// }
public void addTag(String tag){
tags[0] = tag;
}
public double calculateArea() {
return base * height /2;
}
public static void doSomething(){
}
}
| 746 | 0.626005 | 0.617962 | 53 | 13.056603 | 12.630324 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.169811 | false | false | 2 |
c6361e3ea3f372cae77b75148ee4cba888b123b0 | 4,853,313,052,711 | f2644b11c16796b1b984091883a5a45ebd28b330 | /src/main/java/net/soomsam/zirmegghuette/zars/persistence/dao/jpa/JpaSettingDao.java | 4872e420714008d5dfd2b320fa1810efe0662e51 | [
"BSD-3-Clause"
] | permissive | qpanda/zars | https://github.com/qpanda/zars | 9ac1f1c92c93e20f1b2b0ada02b874364735bb14 | 23bbc918515e8a0fa455a1486d4d800b22839ee3 | refs/heads/master | 2020-03-17T13:49:41.438000 | 2018-05-16T10:04:57 | 2018-05-16T10:04:57 | 133,210,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.soomsam.zirmegghuette.zars.persistence.dao.jpa;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import net.soomsam.zirmegghuette.zars.enums.SettingType;
import net.soomsam.zirmegghuette.zars.persistence.dao.EntityNotFoundException;
import net.soomsam.zirmegghuette.zars.persistence.dao.SettingDao;
import net.soomsam.zirmegghuette.zars.persistence.entity.Setting;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Repository;
@Repository("settingDao")
public class JpaSettingDao extends JpaEntityDao<Setting> implements SettingDao {
private final BeanWrapper beanWrapper = new BeanWrapperImpl();
@Override
protected Class<Setting> determineEntityClass() {
return Setting.class;
}
@Override
public Setting findBySettingType(final SettingType settingType) {
if (null == settingType) {
throw new IllegalArgumentException("'settingType' must not be null");
}
final TypedQuery<Setting> findSettingTypedQuery = createNamedTypedQuery(Setting.FINDSETTING_QUERYNAME);
findSettingTypedQuery.setParameter("name", settingType.getSettingName());
try {
return findSettingTypedQuery.getSingleResult();
} catch (final NoResultException noResultException) {
return null;
}
}
@Override
public Setting create(final SettingType settingType, final Object value) {
if (null == value) {
return new Setting(settingType.getSettingName(), Object.class.getCanonicalName());
}
final String settingValue = beanWrapper.convertIfNecessary(value, String.class);
final String settingValueType = value.getClass().getCanonicalName();
return new Setting(settingType.getSettingName(), settingValue, settingValueType);
}
@Override
public Setting update(final SettingType settingType, final Object value) {
final Setting setting = findBySettingType(settingType);
if (null == setting) {
throw new EntityNotFoundException("setting [" + settingType.getSettingName() + "] does not exist");
}
if (null == value) {
setting.setValue(null);
setting.setType(Object.class.getCanonicalName());
} else {
final String settingValue = beanWrapper.convertIfNecessary(value, String.class);
final String settingValueType = value.getClass().getCanonicalName();
setting.setValue(settingValue);
setting.setType(settingValueType);
}
return setting;
}
} | UTF-8 | Java | 2,492 | java | JpaSettingDao.java | Java | [] | null | [] | package net.soomsam.zirmegghuette.zars.persistence.dao.jpa;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import net.soomsam.zirmegghuette.zars.enums.SettingType;
import net.soomsam.zirmegghuette.zars.persistence.dao.EntityNotFoundException;
import net.soomsam.zirmegghuette.zars.persistence.dao.SettingDao;
import net.soomsam.zirmegghuette.zars.persistence.entity.Setting;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Repository;
@Repository("settingDao")
public class JpaSettingDao extends JpaEntityDao<Setting> implements SettingDao {
private final BeanWrapper beanWrapper = new BeanWrapperImpl();
@Override
protected Class<Setting> determineEntityClass() {
return Setting.class;
}
@Override
public Setting findBySettingType(final SettingType settingType) {
if (null == settingType) {
throw new IllegalArgumentException("'settingType' must not be null");
}
final TypedQuery<Setting> findSettingTypedQuery = createNamedTypedQuery(Setting.FINDSETTING_QUERYNAME);
findSettingTypedQuery.setParameter("name", settingType.getSettingName());
try {
return findSettingTypedQuery.getSingleResult();
} catch (final NoResultException noResultException) {
return null;
}
}
@Override
public Setting create(final SettingType settingType, final Object value) {
if (null == value) {
return new Setting(settingType.getSettingName(), Object.class.getCanonicalName());
}
final String settingValue = beanWrapper.convertIfNecessary(value, String.class);
final String settingValueType = value.getClass().getCanonicalName();
return new Setting(settingType.getSettingName(), settingValue, settingValueType);
}
@Override
public Setting update(final SettingType settingType, final Object value) {
final Setting setting = findBySettingType(settingType);
if (null == setting) {
throw new EntityNotFoundException("setting [" + settingType.getSettingName() + "] does not exist");
}
if (null == value) {
setting.setValue(null);
setting.setType(Object.class.getCanonicalName());
} else {
final String settingValue = beanWrapper.convertIfNecessary(value, String.class);
final String settingValueType = value.getClass().getCanonicalName();
setting.setValue(settingValue);
setting.setType(settingValueType);
}
return setting;
}
} | 2,492 | 0.761637 | 0.761637 | 72 | 32.638889 | 31.642229 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.722222 | false | false | 2 |
0b623f7da9bb2d2f27792b6d566fb1901c41ec22 | 6,837,587,940,132 | 54bbaab2739774ea3bdb84f1a64ac98ea2b82ed7 | /Calculator/src/tw/edu/npu/mis/CalculatorView.java | 64755b5264fddb539bae3283af68a93d7a83bc1b | [
"BSD-2-Clause"
] | permissive | npu10133/npu-java-course-spring-2015 | https://github.com/npu10133/npu-java-course-spring-2015 | d593e21548df21c67c32a38c7cdd3efad42333f8 | 4aeea59ee85375348497fb49784fafe57ff49555 | refs/heads/master | 2020-05-01T03:08:32.498000 | 2015-06-12T06:01:18 | 2015-06-12T06:01:18 | 36,152,736 | 0 | 0 | null | true | 2015-05-24T02:46:20 | 2015-05-24T02:46:20 | 2015-05-17T04:00:07 | 2015-05-23T18:05:42 | 148 | 0 | 0 | 0 | null | null | null | package tw.edu.npu.mis;
/*
* 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 user
*/
import tw.edu.npu.mis.CalculatorModel;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
/**
*
* @author ahza
*/
public class CalculatorView extends javax.swing.JFrame {
/** Creates new form CalculatorView */
public CalculatorView() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
CalculatorModel model = new CalculatorModel();
String operand="";
public void getOperand(javax.swing.JButton button){
operand+=button.getText();
model.setOperand(operand);
resultLabel.setText(operand);
}
private void getOperator(int opt){
model.setOperator(opt);
operand="";
}
private void process(){
DecimalFormat df = new DecimalFormat("#,###.########");
model.process();
operand = "";
resultLabel.setText(df.format(model.getResult())+"");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
resultLabel = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
button7 = new javax.swing.JButton();
button4 = new javax.swing.JButton();
button1 = new javax.swing.JButton();
buttonKoma = new javax.swing.JButton();
button11 = new javax.swing.JButton();
button12 = new javax.swing.JButton();
button2 = new javax.swing.JButton();
button3 = new javax.swing.JButton();
button5 = new javax.swing.JButton();
button6 = new javax.swing.JButton();
button8 = new javax.swing.JButton();
button9 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
buttonOver = new javax.swing.JButton();
buttonTimes = new javax.swing.JButton();
buttonMinus = new javax.swing.JButton();
buttonPlus = new javax.swing.JButton();
buttonClear = new javax.swing.JButton();
buttonPercent = new javax.swing.JButton();
buttonReciprocal = new javax.swing.JButton();
buttonEqual = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuExit = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenu = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Calculator");
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
resultLabel.setBackground(new java.awt.Color(255, 255, 255));
resultLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 36)); // NOI18N
resultLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
resultLabel.setText("0");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(resultLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(resultLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
button7.setText("7");
button7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button7ActionPerformed(evt);
}
});
button4.setText("4");
button4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button4ActionPerformed(evt);
}
});
button1.setText("1");
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
buttonKoma.setText(".");
buttonKoma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonKomaActionPerformed(evt);
}
});
button11.setText("0");
button11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button11ActionPerformed(evt);
}
});
button12.setText("C");
button12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button12ActionPerformed(evt);
}
});
button2.setText("2");
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button2ActionPerformed(evt);
}
});
button3.setText("3");
button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button3ActionPerformed(evt);
}
});
button5.setText("5");
button5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button5ActionPerformed(evt);
}
});
button6.setText("6");
button6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button6ActionPerformed(evt);
}
});
button8.setText("8");
button8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button8ActionPerformed(evt);
}
});
button9.setText("9");
button9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button9ActionPerformed(evt);
}
});
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)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button7, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button8, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button9, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(buttonKoma, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button11, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button12, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button7, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button8, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button9, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button6, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonKoma, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button11, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button12, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
buttonOver.setText("/");
buttonOver.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonOverActionPerformed(evt);
}
});
buttonTimes.setText("*");
buttonTimes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTimesActionPerformed(evt);
}
});
buttonMinus.setText("-");
buttonMinus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonMinusActionPerformed(evt);
}
});
buttonPlus.setText("+");
buttonPlus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPlusActionPerformed(evt);
}
});
buttonClear.setText("AC");
buttonClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonClearActionPerformed(evt);
}
});
buttonPercent.setText("%");
buttonPercent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPercentActionPerformed(evt);
}
});
buttonReciprocal.setText("1/x");
buttonReciprocal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonReciprocalActionPerformed(evt);
}
});
buttonEqual.setText("=");
buttonEqual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonEqualActionPerformed(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()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(buttonMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonReciprocal))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(buttonPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonEqual, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(buttonTimes, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonPercent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(buttonOver, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonClear))))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonOver, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonClear, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTimes, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonPercent, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonReciprocal, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(14, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
getOperand(button1);
}//GEN-LAST:event_button1ActionPerformed
private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed
getOperand(button2);
}//GEN-LAST:event_button2ActionPerformed
private void button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button3ActionPerformed
getOperand(button3);
}//GEN-LAST:event_button3ActionPerformed
private void button4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button4ActionPerformed
getOperand(button4);
}//GEN-LAST:event_button4ActionPerformed
private void button5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button5ActionPerformed
getOperand(button5);
}//GEN-LAST:event_button5ActionPerformed
private void button6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button6ActionPerformed
getOperand(button6);
}//GEN-LAST:event_button6ActionPerformed
private void button7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button7ActionPerformed
getOperand(button7);
}//GEN-LAST:event_button7ActionPerformed
private void button8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button8ActionPerformed
getOperand(button8);
}//GEN-LAST:event_button8ActionPerformed
private void button9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button9ActionPerformed
getOperand(button9);
}//GEN-LAST:event_button9ActionPerformed
private void buttonPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPlusActionPerformed
getOperator(1);
}//GEN-LAST:event_buttonPlusActionPerformed
private void buttonMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMinusActionPerformed
getOperator(2);
}//GEN-LAST:event_buttonMinusActionPerformed
private void buttonTimesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTimesActionPerformed
getOperator(3);
}//GEN-LAST:event_buttonTimesActionPerformed
private void buttonOverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOverActionPerformed
getOperator(4);
}//GEN-LAST:event_buttonOverActionPerformed
private void buttonPercentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPercentActionPerformed
getOperator(5);
}//GEN-LAST:event_buttonPercentActionPerformed
private void buttonReciprocalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReciprocalActionPerformed
getOperator(6);
}//GEN-LAST:event_buttonReciprocalActionPerformed
private void buttonEqualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEqualActionPerformed
process();
}//GEN-LAST:event_buttonEqualActionPerformed
private void button11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button11ActionPerformed
getOperand(button11);
}//GEN-LAST:event_button11ActionPerformed
private void buttonKomaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonKomaActionPerformed
getOperand(buttonKoma);
}//GEN-LAST:event_buttonKomaActionPerformed
private void button12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button12ActionPerformed
if(operand.length()>1){
operand = operand.substring(0, operand.length()-1);
model.setOperand(operand);
resultLabel.setText(operand);
}else{
operand = "";
model.setOperand(operand);
resultLabel.setText("0");
}
}//GEN-LAST:event_button12ActionPerformed
private void buttonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonClearActionPerformed
operand = "";
model.setOperator(0);
model.setResult(0);
resultLabel.setText("0");
}//GEN-LAST:event_buttonClearActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenu;
private javax.swing.JButton button1;
private javax.swing.JButton button11;
private javax.swing.JButton button12;
private javax.swing.JButton button2;
private javax.swing.JButton button3;
private javax.swing.JButton button4;
private javax.swing.JButton button5;
private javax.swing.JButton button6;
private javax.swing.JButton button7;
private javax.swing.JButton button8;
private javax.swing.JButton button9;
private javax.swing.JButton buttonClear;
private javax.swing.JButton buttonOver;
private javax.swing.JButton buttonTimes;
private javax.swing.JButton buttonKoma;
private javax.swing.JButton buttonMinus;
private javax.swing.JButton buttonPercent;
private javax.swing.JButton buttonEqual;
private javax.swing.JButton buttonReciprocal;
private javax.swing.JButton buttonPlus;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JMenuItem menuExit;
private javax.swing.JMenu menuFile;
private javax.swing.JLabel resultLabel;
// End of variables declaration//GEN-END:variables
} | UTF-8 | Java | 26,940 | java | CalculatorView.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author user\n */\nimport tw.edu.npu.mis.CalculatorModel;\nimport",
"end": 233,
"score": 0.9979099631309509,
"start": 229,
"tag": "USERNAME",
"value": "user"
},
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * ... | null | [] | package tw.edu.npu.mis;
/*
* 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 user
*/
import tw.edu.npu.mis.CalculatorModel;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
/**
*
* @author ahza
*/
public class CalculatorView extends javax.swing.JFrame {
/** Creates new form CalculatorView */
public CalculatorView() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
CalculatorModel model = new CalculatorModel();
String operand="";
public void getOperand(javax.swing.JButton button){
operand+=button.getText();
model.setOperand(operand);
resultLabel.setText(operand);
}
private void getOperator(int opt){
model.setOperator(opt);
operand="";
}
private void process(){
DecimalFormat df = new DecimalFormat("#,###.########");
model.process();
operand = "";
resultLabel.setText(df.format(model.getResult())+"");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
resultLabel = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
button7 = new javax.swing.JButton();
button4 = new javax.swing.JButton();
button1 = new javax.swing.JButton();
buttonKoma = new javax.swing.JButton();
button11 = new javax.swing.JButton();
button12 = new javax.swing.JButton();
button2 = new javax.swing.JButton();
button3 = new javax.swing.JButton();
button5 = new javax.swing.JButton();
button6 = new javax.swing.JButton();
button8 = new javax.swing.JButton();
button9 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
buttonOver = new javax.swing.JButton();
buttonTimes = new javax.swing.JButton();
buttonMinus = new javax.swing.JButton();
buttonPlus = new javax.swing.JButton();
buttonClear = new javax.swing.JButton();
buttonPercent = new javax.swing.JButton();
buttonReciprocal = new javax.swing.JButton();
buttonEqual = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuExit = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenu = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Calculator");
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
resultLabel.setBackground(new java.awt.Color(255, 255, 255));
resultLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 36)); // NOI18N
resultLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
resultLabel.setText("0");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(resultLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(resultLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
button7.setText("7");
button7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button7ActionPerformed(evt);
}
});
button4.setText("4");
button4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button4ActionPerformed(evt);
}
});
button1.setText("1");
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
buttonKoma.setText(".");
buttonKoma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonKomaActionPerformed(evt);
}
});
button11.setText("0");
button11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button11ActionPerformed(evt);
}
});
button12.setText("C");
button12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button12ActionPerformed(evt);
}
});
button2.setText("2");
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button2ActionPerformed(evt);
}
});
button3.setText("3");
button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button3ActionPerformed(evt);
}
});
button5.setText("5");
button5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button5ActionPerformed(evt);
}
});
button6.setText("6");
button6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button6ActionPerformed(evt);
}
});
button8.setText("8");
button8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button8ActionPerformed(evt);
}
});
button9.setText("9");
button9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button9ActionPerformed(evt);
}
});
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)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button7, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button8, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button9, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(buttonKoma, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button11, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button12, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button7, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button8, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button9, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button6, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonKoma, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button11, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(button12, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
buttonOver.setText("/");
buttonOver.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonOverActionPerformed(evt);
}
});
buttonTimes.setText("*");
buttonTimes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonTimesActionPerformed(evt);
}
});
buttonMinus.setText("-");
buttonMinus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonMinusActionPerformed(evt);
}
});
buttonPlus.setText("+");
buttonPlus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPlusActionPerformed(evt);
}
});
buttonClear.setText("AC");
buttonClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonClearActionPerformed(evt);
}
});
buttonPercent.setText("%");
buttonPercent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPercentActionPerformed(evt);
}
});
buttonReciprocal.setText("1/x");
buttonReciprocal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonReciprocalActionPerformed(evt);
}
});
buttonEqual.setText("=");
buttonEqual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonEqualActionPerformed(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()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(buttonMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonReciprocal))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(buttonPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonEqual, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(buttonTimes, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonPercent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(buttonOver, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonClear))))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonOver, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonClear, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonTimes, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonPercent, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonReciprocal, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(14, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
getOperand(button1);
}//GEN-LAST:event_button1ActionPerformed
private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed
getOperand(button2);
}//GEN-LAST:event_button2ActionPerformed
private void button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button3ActionPerformed
getOperand(button3);
}//GEN-LAST:event_button3ActionPerformed
private void button4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button4ActionPerformed
getOperand(button4);
}//GEN-LAST:event_button4ActionPerformed
private void button5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button5ActionPerformed
getOperand(button5);
}//GEN-LAST:event_button5ActionPerformed
private void button6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button6ActionPerformed
getOperand(button6);
}//GEN-LAST:event_button6ActionPerformed
private void button7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button7ActionPerformed
getOperand(button7);
}//GEN-LAST:event_button7ActionPerformed
private void button8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button8ActionPerformed
getOperand(button8);
}//GEN-LAST:event_button8ActionPerformed
private void button9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button9ActionPerformed
getOperand(button9);
}//GEN-LAST:event_button9ActionPerformed
private void buttonPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPlusActionPerformed
getOperator(1);
}//GEN-LAST:event_buttonPlusActionPerformed
private void buttonMinusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMinusActionPerformed
getOperator(2);
}//GEN-LAST:event_buttonMinusActionPerformed
private void buttonTimesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTimesActionPerformed
getOperator(3);
}//GEN-LAST:event_buttonTimesActionPerformed
private void buttonOverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOverActionPerformed
getOperator(4);
}//GEN-LAST:event_buttonOverActionPerformed
private void buttonPercentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPercentActionPerformed
getOperator(5);
}//GEN-LAST:event_buttonPercentActionPerformed
private void buttonReciprocalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReciprocalActionPerformed
getOperator(6);
}//GEN-LAST:event_buttonReciprocalActionPerformed
private void buttonEqualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEqualActionPerformed
process();
}//GEN-LAST:event_buttonEqualActionPerformed
private void button11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button11ActionPerformed
getOperand(button11);
}//GEN-LAST:event_button11ActionPerformed
private void buttonKomaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonKomaActionPerformed
getOperand(buttonKoma);
}//GEN-LAST:event_buttonKomaActionPerformed
private void button12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button12ActionPerformed
if(operand.length()>1){
operand = operand.substring(0, operand.length()-1);
model.setOperand(operand);
resultLabel.setText(operand);
}else{
operand = "";
model.setOperand(operand);
resultLabel.setText("0");
}
}//GEN-LAST:event_button12ActionPerformed
private void buttonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonClearActionPerformed
operand = "";
model.setOperator(0);
model.setResult(0);
resultLabel.setText("0");
}//GEN-LAST:event_buttonClearActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenu;
private javax.swing.JButton button1;
private javax.swing.JButton button11;
private javax.swing.JButton button12;
private javax.swing.JButton button2;
private javax.swing.JButton button3;
private javax.swing.JButton button4;
private javax.swing.JButton button5;
private javax.swing.JButton button6;
private javax.swing.JButton button7;
private javax.swing.JButton button8;
private javax.swing.JButton button9;
private javax.swing.JButton buttonClear;
private javax.swing.JButton buttonOver;
private javax.swing.JButton buttonTimes;
private javax.swing.JButton buttonKoma;
private javax.swing.JButton buttonMinus;
private javax.swing.JButton buttonPercent;
private javax.swing.JButton buttonEqual;
private javax.swing.JButton buttonReciprocal;
private javax.swing.JButton buttonPlus;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JMenuItem menuExit;
private javax.swing.JMenu menuFile;
private javax.swing.JLabel resultLabel;
// End of variables declaration//GEN-END:variables
} | 26,940 | 0.672086 | 0.658055 | 519 | 50.909443 | 40.103882 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689788 | false | false | 2 |
75362334c9b44e5f992c2c36fac310848208eabc | 18,640,158,071,625 | 855be9d3955343e2bf6f88620ad5962e2643fd35 | /src/util/DataUtil.java | b7ea1f012f61c5f2f35d814bad3f548151e5c727 | [] | no_license | tinyplan/Java | https://github.com/tinyplan/Java | 80e0450326938ae899ce3f56444ed78083fea350 | 0e330148e23ecaa8f7b1dd7692653f52120ec5c0 | refs/heads/master | 2022-01-21T04:13:21.270000 | 2019-07-22T11:09:54 | 2019-07-22T11:09:54 | 198,205,258 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
public class DataUtil {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement prestmt = null;
public DataUtil() {
String[] str = readConfigFile();
try {
Class.forName(str[0]);
conn = DriverManager.getConnection(str[1], str[2], str[3]);//连接数据库
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//似乎仅作为实验
DataUtil dbc = new DataUtil();
String[] str = dbc.readConfigFile();
for(String info:str){
System.out.println(info);
}
//System.out.println(Fn.time());
}
/**
* 读取配置文件SystemConfig.properties
* @return
*/
private String[] readConfigFile() {
String[] str = new String[4];
try {
Properties props = new Properties();
InputStream infile = this.getClass().getResourceAsStream("/ConfigFile/SystemConfig.properties");
props.load(infile);
str[0] = props.getProperty("driver");
str[1] = props.getProperty("url");
str[2] = props.getProperty("username");
str[3] = props.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 函数功能:删除数据
*
* @param tableName
* 表名
* @param condition
* 条件 例:delete from 表 where condition
*/
public boolean deleteData(String tableName, String condition) {
String sql = "";
boolean flag = false;
//sql语句组装
if (condition == null || condition == "") {
sql = "delete from " + tableName;
} else {
sql = "delete from " + tableName + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();//被影响的记录条数
if (rscount > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:从表中取出符合条件的数据
*
* @param tableName
* 表名
* @param field
* 列名
* @param condition
* 查询条件
* @return 一个向量集合,每个向量含String[] field
*/
public Vector<String[]> getData(String tableName, String[] field, String condition) {
Vector<String[]> vec = new Vector<String[]>();
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName;
} else {
sql = "select " + strField + " from " + tableName + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();//获取结果集
while (rs.next()) {
String[] temp = new String[field.length];//缓存数组的长度与属性名长度个数相同
for (int i = 0; i < field.length; i++) {
temp[i] = rs.getString(field[i]);//获取对应的属性值
// Debug(temp[i]);
}
vec.add(temp);
}
} catch (SQLException e) {
e.printStackTrace();
}
return vec;
}
/**实现两表连接
*
* @param tableName1 母表
* @param tableName2 子表
* @param field 列名
* @param joinConditioin 链接条件
* @param condition 筛选条件
* @return
*/
public Vector<String[]> getData(String tableName1,String tableName2,String[] field, String joinConditioin,String condition) {
Vector<String[]> vec=new Vector<String[]>();
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName1+ " join "+tableName2+ " on " +joinConditioin;
} else {
sql = "select " + strField + " from " + tableName1+ " join "+tableName2+ " on " +joinConditioin + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while (rs.next()) {
String[] temp = new String[field.length];
for (int i = 0; i < field.length; i++) {
temp[i] = rs.getString(field[i]);
// Debug(temp[i]);
}
vec.add(temp);
}
} catch (SQLException e) {
e.printStackTrace();
}
return vec;
}
/**
* 函数功能:用户登录检查
*
* @param table
* @param condition
* @return
*/
public boolean CheckLogin(String table, String condition) {
boolean flag = false;
try {
String sql = "select * from " + table + " where " + condition;
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
if (rs.next()) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能说明:插入数据
*
* @param tableName
* @param field
* @param value
* @throws SQLException
* 第二个参数和第三个参数个数要相等,若为空或"",则表示该表全部字段
*/
public boolean addData(String tableName, String[] field, String[] value) {
boolean flag = false;
if (field == null || value == null || field.length == 0 || value.length == 0 || field.length != value.length)
return flag;
String strField = "", strValue = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
strValue += "'" + value[i] + "',";
}
strField = strField.substring(0, strField.lastIndexOf(","));
strValue = strValue.substring(0, strValue.lastIndexOf(","));
try {
String sql = "insert into " + tableName;
sql += " (" + strField + ") values(";
sql += strValue + ")";
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();
if (rscount > 0)
flag = true;
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:修改数据
*
* @param tableName
* 表名
* @param field
* 字段列表
* @param value
* 值列表
* @param condition
* 条件 例:update 表 set 字段1=值1 where 条件
*/
public boolean updateData(String tableName, String[] field, String[] value, String condition) {
boolean flag = false;
if (field == null || value == null || field.length == 0 || value.length == 0 || field.length != value.length)
return flag;
String str = "";
for (int i = 0; i < field.length; i++) {
str += field[i] + "='" + value[i] + "',";
}
str = str.substring(0, str.lastIndexOf(","));
// Debug(str);
String sql = "";
if (condition == null || condition == "") {
sql = "update " + tableName + " set " + str;
} else {
sql = "update " + tableName + " set " + str + " where " + condition;
}
// Debug(sql);
try {
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();
if (rscount > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:执行单条语句返回一个哈希表
*
* @param table
* @param field
* @param condition
* @return
*/
public Hashtable<String, String> execSQL(String table, String field, String condition) {
Hashtable<String, String> ht = new Hashtable<String, String>();
try {
String sql = "select " + field + " from " + table + " where " + condition;
System.out.println(sql);
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while (rs.next()) {
ht.put(field, rs.getString(field));
}
} catch (Exception e) {
e.printStackTrace();
}
return ht;
}
/**
* 分页
* @param tableName
* @param field
* @param condition
* @param pageNo 当前页码
* @param pageSize 每页数量
* @return
*/
public PageUtil getPage(String tableName,String[] field,String condition,int pageNo,int pageSize){
Vector<String[]> data = new Vector<String[]>();
PageUtil pu = null;
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName + " limit " + (pageNo-1)*pageSize + "," + pageSize;
} else {
sql = "select " + strField + " from " + tableName + " limit " + (pageNo-1)*pageSize + "," + pageSize +" where " + condition;
}
try{
//获取总数据条数
int totalCount=0;
String queryCount = "select count(bno) from book";
prestmt = conn.prepareStatement(queryCount);
rs = prestmt.executeQuery();
while(rs.next()){
totalCount = rs.getInt(1);
}
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while(rs.next()){
String[] tmp = new String[field.length];
for(int i=0;i<field.length;i++){
tmp[i] = rs.getString(field[i]);
}
data.add(tmp);
}
pu = new PageUtil(pageSize, totalCount);
pu.setData(data);
}catch(SQLException e){
e.printStackTrace();
}
return pu;
}
} | GB18030 | Java | 9,381 | java | DataUtil.java | Java | [] | null | [] | package util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
public class DataUtil {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement prestmt = null;
public DataUtil() {
String[] str = readConfigFile();
try {
Class.forName(str[0]);
conn = DriverManager.getConnection(str[1], str[2], str[3]);//连接数据库
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//似乎仅作为实验
DataUtil dbc = new DataUtil();
String[] str = dbc.readConfigFile();
for(String info:str){
System.out.println(info);
}
//System.out.println(Fn.time());
}
/**
* 读取配置文件SystemConfig.properties
* @return
*/
private String[] readConfigFile() {
String[] str = new String[4];
try {
Properties props = new Properties();
InputStream infile = this.getClass().getResourceAsStream("/ConfigFile/SystemConfig.properties");
props.load(infile);
str[0] = props.getProperty("driver");
str[1] = props.getProperty("url");
str[2] = props.getProperty("username");
str[3] = props.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 函数功能:删除数据
*
* @param tableName
* 表名
* @param condition
* 条件 例:delete from 表 where condition
*/
public boolean deleteData(String tableName, String condition) {
String sql = "";
boolean flag = false;
//sql语句组装
if (condition == null || condition == "") {
sql = "delete from " + tableName;
} else {
sql = "delete from " + tableName + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();//被影响的记录条数
if (rscount > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:从表中取出符合条件的数据
*
* @param tableName
* 表名
* @param field
* 列名
* @param condition
* 查询条件
* @return 一个向量集合,每个向量含String[] field
*/
public Vector<String[]> getData(String tableName, String[] field, String condition) {
Vector<String[]> vec = new Vector<String[]>();
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName;
} else {
sql = "select " + strField + " from " + tableName + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();//获取结果集
while (rs.next()) {
String[] temp = new String[field.length];//缓存数组的长度与属性名长度个数相同
for (int i = 0; i < field.length; i++) {
temp[i] = rs.getString(field[i]);//获取对应的属性值
// Debug(temp[i]);
}
vec.add(temp);
}
} catch (SQLException e) {
e.printStackTrace();
}
return vec;
}
/**实现两表连接
*
* @param tableName1 母表
* @param tableName2 子表
* @param field 列名
* @param joinConditioin 链接条件
* @param condition 筛选条件
* @return
*/
public Vector<String[]> getData(String tableName1,String tableName2,String[] field, String joinConditioin,String condition) {
Vector<String[]> vec=new Vector<String[]>();
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName1+ " join "+tableName2+ " on " +joinConditioin;
} else {
sql = "select " + strField + " from " + tableName1+ " join "+tableName2+ " on " +joinConditioin + " where " + condition;
}
try {
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while (rs.next()) {
String[] temp = new String[field.length];
for (int i = 0; i < field.length; i++) {
temp[i] = rs.getString(field[i]);
// Debug(temp[i]);
}
vec.add(temp);
}
} catch (SQLException e) {
e.printStackTrace();
}
return vec;
}
/**
* 函数功能:用户登录检查
*
* @param table
* @param condition
* @return
*/
public boolean CheckLogin(String table, String condition) {
boolean flag = false;
try {
String sql = "select * from " + table + " where " + condition;
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
if (rs.next()) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能说明:插入数据
*
* @param tableName
* @param field
* @param value
* @throws SQLException
* 第二个参数和第三个参数个数要相等,若为空或"",则表示该表全部字段
*/
public boolean addData(String tableName, String[] field, String[] value) {
boolean flag = false;
if (field == null || value == null || field.length == 0 || value.length == 0 || field.length != value.length)
return flag;
String strField = "", strValue = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
strValue += "'" + value[i] + "',";
}
strField = strField.substring(0, strField.lastIndexOf(","));
strValue = strValue.substring(0, strValue.lastIndexOf(","));
try {
String sql = "insert into " + tableName;
sql += " (" + strField + ") values(";
sql += strValue + ")";
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();
if (rscount > 0)
flag = true;
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:修改数据
*
* @param tableName
* 表名
* @param field
* 字段列表
* @param value
* 值列表
* @param condition
* 条件 例:update 表 set 字段1=值1 where 条件
*/
public boolean updateData(String tableName, String[] field, String[] value, String condition) {
boolean flag = false;
if (field == null || value == null || field.length == 0 || value.length == 0 || field.length != value.length)
return flag;
String str = "";
for (int i = 0; i < field.length; i++) {
str += field[i] + "='" + value[i] + "',";
}
str = str.substring(0, str.lastIndexOf(","));
// Debug(str);
String sql = "";
if (condition == null || condition == "") {
sql = "update " + tableName + " set " + str;
} else {
sql = "update " + tableName + " set " + str + " where " + condition;
}
// Debug(sql);
try {
prestmt = conn.prepareStatement(sql);
int rscount = prestmt.executeUpdate();
if (rscount > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
/**
* 函数功能:执行单条语句返回一个哈希表
*
* @param table
* @param field
* @param condition
* @return
*/
public Hashtable<String, String> execSQL(String table, String field, String condition) {
Hashtable<String, String> ht = new Hashtable<String, String>();
try {
String sql = "select " + field + " from " + table + " where " + condition;
System.out.println(sql);
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while (rs.next()) {
ht.put(field, rs.getString(field));
}
} catch (Exception e) {
e.printStackTrace();
}
return ht;
}
/**
* 分页
* @param tableName
* @param field
* @param condition
* @param pageNo 当前页码
* @param pageSize 每页数量
* @return
*/
public PageUtil getPage(String tableName,String[] field,String condition,int pageNo,int pageSize){
Vector<String[]> data = new Vector<String[]>();
PageUtil pu = null;
String strField = "", sql = "";
for (int i = 0; i < field.length; i++) {
strField += field[i] + ",";
}
strField = strField.substring(0, strField.lastIndexOf(","));//去除strField中最后的逗号
if (condition == null || condition == "") {
sql = "select " + strField + " from " + tableName + " limit " + (pageNo-1)*pageSize + "," + pageSize;
} else {
sql = "select " + strField + " from " + tableName + " limit " + (pageNo-1)*pageSize + "," + pageSize +" where " + condition;
}
try{
//获取总数据条数
int totalCount=0;
String queryCount = "select count(bno) from book";
prestmt = conn.prepareStatement(queryCount);
rs = prestmt.executeQuery();
while(rs.next()){
totalCount = rs.getInt(1);
}
prestmt = conn.prepareStatement(sql);
rs = prestmt.executeQuery();
while(rs.next()){
String[] tmp = new String[field.length];
for(int i=0;i<field.length;i++){
tmp[i] = rs.getString(field[i]);
}
data.add(tmp);
}
pu = new PageUtil(pageSize, totalCount);
pu.setData(data);
}catch(SQLException e){
e.printStackTrace();
}
return pu;
}
} | 9,381 | 0.6 | 0.59502 | 348 | 24.390804 | 23.495588 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.571839 | false | false | 2 |
e2f8ad0b7d6d3dc4d966fdac77c76feae677d0d2 | 12,283,606,479,928 | 27bdbcb0a391dcde4ed6d01bc5fbeb2bee7a46a2 | /src/main/java/com/bookshop/service/impl/BookServiceImpl.java | 30315f4438321dbf338a11645c1bbdb62d0ac3f0 | [] | no_license | LamVanHai/web_ban_sach | https://github.com/LamVanHai/web_ban_sach | 913614c93281c37dc492107fcc3644feb7af6bd6 | af0160183c18670cb8a46bb47a8d98ea63a2495f | refs/heads/main | 2023-06-05T17:54:00.232000 | 2021-06-28T09:03:51 | 2021-06-28T09:03:51 | 380,969,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bookshop.service.impl;
import com.bookshop.dto.request.BookRequest;
import com.bookshop.dto.response.BookResponse;
import com.bookshop.dto.response.ThongKeResponse;
import com.bookshop.entity.*;
import com.bookshop.mapper.BookMapper;
import com.bookshop.repository.*;
import com.bookshop.service.BookService;
import com.bookshop.util.RandomUtil;
import com.bookshop.util.ReflectionUtil;
import com.bookshop.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private PublisherRepository publisherRepository;
@Autowired
private CommentRepository commentRepository;
@Autowired
private Order_detailRepository order_detailRepository;
@Autowired
private RandomUtil randomUtil;
@Autowired
private WriterRepository writerRepository;
@Autowired
private BookMapper bookMapper;
@Override
public List<BookResponse> findAll(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByKeyWord(String keyWord, Pageable pageable) {
List<Book> books = bookRepository.findByName(keyWord, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int getTotalItem() {
return (int) bookRepository.count();
}
@Override
@Transactional
public BookRequest save(BookRequest bookRequest) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Category category = categoryRepository.findOne(bookRequest.getCategory_id());
Publisher publisher = publisherRepository.findOne(bookRequest.getPublisher_id());
Writer writer = writerRepository.findOne(bookRequest.getWriter_id());
Book book = new Book();
Set<Writer> writers = new HashSet<>();
writers.add(writer);
if (bookRequest.getId() != null) {
Book oldBook = bookRepository.findOne(bookRequest.getId());
oldBook.setCategory(category);
oldBook.setPublisher_book(publisher);
ReflectionUtil.mapper(bookRequest, oldBook);
book = oldBook;
if (UploadFileUtil.fileURL != null) {
book.setImage(UploadFileUtil.fileURL);//gán file ảnh
}
List<Order_detail> order_details = order_detailRepository.findAllByBook_id(book.getId());
int amount = 0;
if (order_details != null) {
for (Order_detail detail : order_details
) {
if (detail.getOrder3().getStatus() != 3) {
amount += detail.getAmount();
}
}
book.setAmount(book.getInput_amount() - amount);
}
} else {
ReflectionUtil.mapper(bookRequest, book);
book.setCategory(category);
book.setAmount(book.getInput_amount());
book.setPublisher_book(publisher);
book.setWriters(writers);
book.setImage(UploadFileUtil.fileURL);
}
bookRepository.save(book);
ReflectionUtil.mapper(book, bookRequest);
return bookRequest;
}
@Override
public BookRequest findOneById(Long id) {
Book book = bookRepository.findOne(id);
BookRequest bookRequest = new BookRequest();
try {
ReflectionUtil.mapper(book, bookRequest);
bookRequest.setCategory_id(book.getCategory().getId());
bookRequest.setPublisher_id(book.getPublisher_book().getId());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return bookRequest;
}
@Override
@Transactional
public void delete(long[] ids) {
for (long i : ids) {
List<Comment> comment = commentRepository.findByBook_Id(i);
List<Order_detail> order_details = order_detailRepository.findAllByBook_id(i);
for (Comment comment1 : comment) {
commentRepository.delete(comment1.getId());
}
for (Order_detail order_detail : order_details) {
order_detailRepository.delete(order_detail.getId());
}
bookRepository.delete(i);
}
}
@Override
public List<BookResponse> findAllKy_Nang_Song() {
List<Book> books = bookRepository.findAllByCategory1("ky-nang-song");
List<Book> books1;
books1 = randomUtil.random(books);
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
@Override
public List<BookResponse> findAllTop8Next() {
List<Book> books = bookRepository.findAll();
List<Book> books1;
books1 = randomUtil.random(books);
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
public static int countName;
@Override
public List<BookResponse> findByCategory(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByCategory(name, pageable);
countName = books.size();
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByPublisher(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByPublisher(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
int a = books.size();
return bookResponses;
}
@Override
public List<BookResponse> findNewBook() {
List<Book> books = bookRepository.findAll();
List<Book> books1 = new ArrayList<>();
Map<Integer, Book> map = new HashMap<>();
int k = 1;
for (int i = 0; i < books.size(); i++) {
map.put(k++, books.get(i));
}
for (int i = map.size(); i > 0; i--) {
books1.add(map.get(i));
if (books1.size() == 8) {
break;
}
}
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
@Override
public List<BookResponse> findByWriter(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByWriters(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countPublisher(String name) {
List<Book> books = bookRepository.countByPublisher(name);
return books.size();
}
@Override
public int countByLikeNameBook(String name) {
List<Book> books = bookRepository.countByKeyWord(name);
return books.size();
}
@Override
public int countCaterory(String name) {
List<Book> books = bookRepository.findAllByCategory1(name);
return books.size();
}
@Override
public BookResponse findById(Long id) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Book book = bookRepository.findOneById(id);
BookResponse bookResponse = new BookResponse();
ReflectionUtil.mapper(book, bookResponse);
// if(book.getPrice()!=null){
// bookResponse.setPrice1(CheckUtil.convertVND(book.getPrice()));
// }
// if(book.getSale_price()!=null) {
// bookResponse.setSale_price1(CheckUtil.convertVND(book.getSale_price()));
// }
return bookResponse;
}
@Override
public List<BookResponse> findByName(String name, Pageable pageable) {
List<Book> books = bookRepository.findByName(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countByAmount(Long id) {
int quanty = bookRepository.countByAmount(id);
return quanty;
}
@Override
public List<BookResponse> findByDiscount(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<Book> bookDiscount = new ArrayList<>();
for (Book book : books
) {
if (book.getSale_price() != null) {
if (book.getSale_price() > 0) {
bookDiscount.add(book);
}
}
}
List<BookResponse> bookResponses = bookDiscount.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByTopDiscount() {
List<Book> books = bookRepository.findAll();
List<Book> bookDiscount = new ArrayList<>();
List<Book> bookDiscount1 = new ArrayList<>();
for (Book book : books
) {
if (book.getSale_price() != null) {
if (book.getSale_price() > 0) {
bookDiscount.add(book);
}
}
}
Collections.sort(bookDiscount, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o2.getSale_price().compareTo(o1.getSale_price());
}
});
int i = 0;
for (Book book : bookDiscount
) {
if (i > 8) {
break;
}
bookDiscount1.add(book);
i++;
}
List<BookResponse> bookResponses = bookDiscount1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countByDiscount() {
List<Book> books = bookRepository.findAll();
int count = 0;
for (Book bookk : books) {
if (bookk.getSale_price() != null) {
if (bookk.getSale_price() > 0) {
count++;
}
}
}
return count;
}
@Override
public List<ThongKeResponse> list(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<ThongKeResponse> thongKeResponses = books.stream().map(bookMapper::mapToThongKeResponse).collect(Collectors.toList());
return thongKeResponses;
}
@Override
public List<ThongKeResponse> list() {
List<Book> books = bookRepository.findAll();
List<ThongKeResponse> thongKeResponses = books.stream().map(bookMapper::mapToThongKeResponse).collect(Collectors.toList());
return thongKeResponses;
}
}
| UTF-8 | Java | 11,667 | java | BookServiceImpl.java | Java | [] | null | [] | package com.bookshop.service.impl;
import com.bookshop.dto.request.BookRequest;
import com.bookshop.dto.response.BookResponse;
import com.bookshop.dto.response.ThongKeResponse;
import com.bookshop.entity.*;
import com.bookshop.mapper.BookMapper;
import com.bookshop.repository.*;
import com.bookshop.service.BookService;
import com.bookshop.util.RandomUtil;
import com.bookshop.util.ReflectionUtil;
import com.bookshop.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private PublisherRepository publisherRepository;
@Autowired
private CommentRepository commentRepository;
@Autowired
private Order_detailRepository order_detailRepository;
@Autowired
private RandomUtil randomUtil;
@Autowired
private WriterRepository writerRepository;
@Autowired
private BookMapper bookMapper;
@Override
public List<BookResponse> findAll(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByKeyWord(String keyWord, Pageable pageable) {
List<Book> books = bookRepository.findByName(keyWord, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int getTotalItem() {
return (int) bookRepository.count();
}
@Override
@Transactional
public BookRequest save(BookRequest bookRequest) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Category category = categoryRepository.findOne(bookRequest.getCategory_id());
Publisher publisher = publisherRepository.findOne(bookRequest.getPublisher_id());
Writer writer = writerRepository.findOne(bookRequest.getWriter_id());
Book book = new Book();
Set<Writer> writers = new HashSet<>();
writers.add(writer);
if (bookRequest.getId() != null) {
Book oldBook = bookRepository.findOne(bookRequest.getId());
oldBook.setCategory(category);
oldBook.setPublisher_book(publisher);
ReflectionUtil.mapper(bookRequest, oldBook);
book = oldBook;
if (UploadFileUtil.fileURL != null) {
book.setImage(UploadFileUtil.fileURL);//gán file ảnh
}
List<Order_detail> order_details = order_detailRepository.findAllByBook_id(book.getId());
int amount = 0;
if (order_details != null) {
for (Order_detail detail : order_details
) {
if (detail.getOrder3().getStatus() != 3) {
amount += detail.getAmount();
}
}
book.setAmount(book.getInput_amount() - amount);
}
} else {
ReflectionUtil.mapper(bookRequest, book);
book.setCategory(category);
book.setAmount(book.getInput_amount());
book.setPublisher_book(publisher);
book.setWriters(writers);
book.setImage(UploadFileUtil.fileURL);
}
bookRepository.save(book);
ReflectionUtil.mapper(book, bookRequest);
return bookRequest;
}
@Override
public BookRequest findOneById(Long id) {
Book book = bookRepository.findOne(id);
BookRequest bookRequest = new BookRequest();
try {
ReflectionUtil.mapper(book, bookRequest);
bookRequest.setCategory_id(book.getCategory().getId());
bookRequest.setPublisher_id(book.getPublisher_book().getId());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return bookRequest;
}
@Override
@Transactional
public void delete(long[] ids) {
for (long i : ids) {
List<Comment> comment = commentRepository.findByBook_Id(i);
List<Order_detail> order_details = order_detailRepository.findAllByBook_id(i);
for (Comment comment1 : comment) {
commentRepository.delete(comment1.getId());
}
for (Order_detail order_detail : order_details) {
order_detailRepository.delete(order_detail.getId());
}
bookRepository.delete(i);
}
}
@Override
public List<BookResponse> findAllKy_Nang_Song() {
List<Book> books = bookRepository.findAllByCategory1("ky-nang-song");
List<Book> books1;
books1 = randomUtil.random(books);
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
@Override
public List<BookResponse> findAllTop8Next() {
List<Book> books = bookRepository.findAll();
List<Book> books1;
books1 = randomUtil.random(books);
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
public static int countName;
@Override
public List<BookResponse> findByCategory(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByCategory(name, pageable);
countName = books.size();
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByPublisher(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByPublisher(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
int a = books.size();
return bookResponses;
}
@Override
public List<BookResponse> findNewBook() {
List<Book> books = bookRepository.findAll();
List<Book> books1 = new ArrayList<>();
Map<Integer, Book> map = new HashMap<>();
int k = 1;
for (int i = 0; i < books.size(); i++) {
map.put(k++, books.get(i));
}
for (int i = map.size(); i > 0; i--) {
books1.add(map.get(i));
if (books1.size() == 8) {
break;
}
}
List<BookResponse> userResponses = books1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return userResponses;
}
@Override
public List<BookResponse> findByWriter(String name, Pageable pageable) {
List<Book> books = bookRepository.findAllByWriters(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countPublisher(String name) {
List<Book> books = bookRepository.countByPublisher(name);
return books.size();
}
@Override
public int countByLikeNameBook(String name) {
List<Book> books = bookRepository.countByKeyWord(name);
return books.size();
}
@Override
public int countCaterory(String name) {
List<Book> books = bookRepository.findAllByCategory1(name);
return books.size();
}
@Override
public BookResponse findById(Long id) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Book book = bookRepository.findOneById(id);
BookResponse bookResponse = new BookResponse();
ReflectionUtil.mapper(book, bookResponse);
// if(book.getPrice()!=null){
// bookResponse.setPrice1(CheckUtil.convertVND(book.getPrice()));
// }
// if(book.getSale_price()!=null) {
// bookResponse.setSale_price1(CheckUtil.convertVND(book.getSale_price()));
// }
return bookResponse;
}
@Override
public List<BookResponse> findByName(String name, Pageable pageable) {
List<Book> books = bookRepository.findByName(name, pageable);
List<BookResponse> bookResponses = books.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countByAmount(Long id) {
int quanty = bookRepository.countByAmount(id);
return quanty;
}
@Override
public List<BookResponse> findByDiscount(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<Book> bookDiscount = new ArrayList<>();
for (Book book : books
) {
if (book.getSale_price() != null) {
if (book.getSale_price() > 0) {
bookDiscount.add(book);
}
}
}
List<BookResponse> bookResponses = bookDiscount.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public List<BookResponse> findByTopDiscount() {
List<Book> books = bookRepository.findAll();
List<Book> bookDiscount = new ArrayList<>();
List<Book> bookDiscount1 = new ArrayList<>();
for (Book book : books
) {
if (book.getSale_price() != null) {
if (book.getSale_price() > 0) {
bookDiscount.add(book);
}
}
}
Collections.sort(bookDiscount, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o2.getSale_price().compareTo(o1.getSale_price());
}
});
int i = 0;
for (Book book : bookDiscount
) {
if (i > 8) {
break;
}
bookDiscount1.add(book);
i++;
}
List<BookResponse> bookResponses = bookDiscount1.stream().map(BookMapper::mapToResponse).collect(Collectors.toList());
return bookResponses;
}
@Override
public int countByDiscount() {
List<Book> books = bookRepository.findAll();
int count = 0;
for (Book bookk : books) {
if (bookk.getSale_price() != null) {
if (bookk.getSale_price() > 0) {
count++;
}
}
}
return count;
}
@Override
public List<ThongKeResponse> list(Pageable pageable) {
List<Book> books = bookRepository.findAll(pageable).getContent();
List<ThongKeResponse> thongKeResponses = books.stream().map(bookMapper::mapToThongKeResponse).collect(Collectors.toList());
return thongKeResponses;
}
@Override
public List<ThongKeResponse> list() {
List<Book> books = bookRepository.findAll();
List<ThongKeResponse> thongKeResponses = books.stream().map(bookMapper::mapToThongKeResponse).collect(Collectors.toList());
return thongKeResponses;
}
}
| 11,667 | 0.632373 | 0.629201 | 336 | 33.714287 | 30.39064 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517857 | false | false | 2 |
6de6884c245ca9afcb3d4f7a04c05e5ee38009e5 | 31,370,441,141,423 | 107b6d40f8d75596a3229b62560e399980bb3416 | /JavaFundamentals/JavaAdvanced/JavaAdvancedExercises/ManualStringProcessingExercises/src/ConvertFromBaseNToBase10.java | 4c9049c0a444dfb9a4d4bd9a03474b0ba29d8d1b | [] | no_license | TheXaXo/SoftwareUniversity | https://github.com/TheXaXo/SoftwareUniversity | 73b574474c7384b476f22330627784c2826f0a10 | 9e83cb609b0c41ec043ed473741e4d5961d923f2 | refs/heads/master | 2021-05-03T20:08:28.002000 | 2019-02-19T15:13:58 | 2019-02-19T15:13:58 | 68,926,607 | 0 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class ConvertFromBaseNToBase10 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] input = reader.readLine().split(" ");
int base = Integer.parseInt(input[0]);
StringBuilder numberStr = new StringBuilder(input[1]).reverse();
int n = 0;
BigInteger result = new BigInteger("0");
for (char digit : numberStr.toString().toCharArray()) {
BigInteger digitBigInt = new BigInteger(Character.toString(digit));
BigInteger multiplier = new BigInteger(Integer.toString(base));
multiplier = multiplier.pow(n);
digitBigInt = digitBigInt.multiply(multiplier);
result = result.add(digitBigInt);
n++;
}
System.out.println(result);
}
} | UTF-8 | Java | 1,004 | java | ConvertFromBaseNToBase10.java | Java | [] | null | [] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class ConvertFromBaseNToBase10 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] input = reader.readLine().split(" ");
int base = Integer.parseInt(input[0]);
StringBuilder numberStr = new StringBuilder(input[1]).reverse();
int n = 0;
BigInteger result = new BigInteger("0");
for (char digit : numberStr.toString().toCharArray()) {
BigInteger digitBigInt = new BigInteger(Character.toString(digit));
BigInteger multiplier = new BigInteger(Integer.toString(base));
multiplier = multiplier.pow(n);
digitBigInt = digitBigInt.multiply(multiplier);
result = result.add(digitBigInt);
n++;
}
System.out.println(result);
}
} | 1,004 | 0.651394 | 0.645418 | 32 | 30.40625 | 27.530504 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 2 |
4db0ed72d08909315dcebcb1f180393b2a9367c2 | 9,294,309,239,437 | c42d1c618ebdf8c0696af96444d3d32fbde6adb9 | /Flourish android app/Flourish/src/com/flourish/adapters/MoneyMileageBaseAdapter.java | 1f53e258995ddbdfe7633ad92966fddaacdca081 | [] | no_license | vladimirsolovey/Flourish-android-app | https://github.com/vladimirsolovey/Flourish-android-app | 66dca9693d19c4e2279df29c8c9c0d9b7075dcc4 | d6d1998bab8f37bed76f81973a5f16ba62cb03be | refs/heads/master | 2020-05-20T05:43:46.251000 | 2013-11-05T11:08:37 | 2013-11-05T11:08:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flourish.adapters;
import java.util.List;
import com.flourish.R;
import com.flourish.adapters.MoneyExpenseBaseAdapter.ViewHolder;
import com.flourish.utils.MoneyMileageData;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MoneyMileageBaseAdapter extends BaseAdapter{
Context mContext=null;
List<MoneyMileageData> mAllMoneyMileageList=null;
public MoneyMileageBaseAdapter(Context context,List<MoneyMileageData> mAllMoneyMilageList) {
// TODO Auto-generated constructor stub
mContext=context;
this.mAllMoneyMileageList=mAllMoneyMilageList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mAllMoneyMileageList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder{
TextView mTripDescription;
TextView mTripMiles;
TextView mMileageDate;
TextView mVehicleDescription;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View mView=convertView;
ViewHolder holder;
if (convertView==null) {
holder=new ViewHolder();
mView=((Activity)mContext).getLayoutInflater().inflate(R.layout.money_mileage_row, null);
holder.mTripDescription = (TextView)mView.findViewById(R.id.money_mileage_trip_description);
holder.mTripMiles = (TextView)mView.findViewById(R.id.money_mileage_trip_miles);
holder.mMileageDate = (TextView)mView.findViewById(R.id.money_mileage_mileage_date);
holder.mVehicleDescription = (TextView)mView.findViewById(R.id.money_mileage_vehicle_descptn);
/************ Set holder with LayoutInflater ************/
mView.setTag( holder );
}
else{
holder=(ViewHolder)mView.getTag();
}
if (mAllMoneyMileageList.get(position).TripDescription != null)
{
holder.mTripDescription.setText(mAllMoneyMileageList.get(position).TripDescription);
}
if(mAllMoneyMileageList.get(position).TripMiles != null)
{
holder.mTripMiles.setText(mAllMoneyMileageList.get(position).TripMiles+" miles");
}
if(mAllMoneyMileageList.get(position).MileageDate != null)
{
String mMileageDateStr =mAllMoneyMileageList.get(position).MileageDate;
String[] mPersonBirthDateArray = mMileageDateStr.split("-");
mMileageDateStr = mPersonBirthDateArray[1]+"/"+mPersonBirthDateArray[2].substring(0, 2)+"/"+mPersonBirthDateArray[0];
holder.mMileageDate.setText(mMileageDateStr);
}
if(mAllMoneyMileageList.get(position).VehicleDescription != null)
{
holder.mVehicleDescription.setText(mAllMoneyMileageList.get(position).VehicleDescription);
}
return mView;
}
}
| UTF-8 | Java | 2,927 | java | MoneyMileageBaseAdapter.java | Java | [] | null | [] | package com.flourish.adapters;
import java.util.List;
import com.flourish.R;
import com.flourish.adapters.MoneyExpenseBaseAdapter.ViewHolder;
import com.flourish.utils.MoneyMileageData;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MoneyMileageBaseAdapter extends BaseAdapter{
Context mContext=null;
List<MoneyMileageData> mAllMoneyMileageList=null;
public MoneyMileageBaseAdapter(Context context,List<MoneyMileageData> mAllMoneyMilageList) {
// TODO Auto-generated constructor stub
mContext=context;
this.mAllMoneyMileageList=mAllMoneyMilageList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mAllMoneyMileageList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder{
TextView mTripDescription;
TextView mTripMiles;
TextView mMileageDate;
TextView mVehicleDescription;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View mView=convertView;
ViewHolder holder;
if (convertView==null) {
holder=new ViewHolder();
mView=((Activity)mContext).getLayoutInflater().inflate(R.layout.money_mileage_row, null);
holder.mTripDescription = (TextView)mView.findViewById(R.id.money_mileage_trip_description);
holder.mTripMiles = (TextView)mView.findViewById(R.id.money_mileage_trip_miles);
holder.mMileageDate = (TextView)mView.findViewById(R.id.money_mileage_mileage_date);
holder.mVehicleDescription = (TextView)mView.findViewById(R.id.money_mileage_vehicle_descptn);
/************ Set holder with LayoutInflater ************/
mView.setTag( holder );
}
else{
holder=(ViewHolder)mView.getTag();
}
if (mAllMoneyMileageList.get(position).TripDescription != null)
{
holder.mTripDescription.setText(mAllMoneyMileageList.get(position).TripDescription);
}
if(mAllMoneyMileageList.get(position).TripMiles != null)
{
holder.mTripMiles.setText(mAllMoneyMileageList.get(position).TripMiles+" miles");
}
if(mAllMoneyMileageList.get(position).MileageDate != null)
{
String mMileageDateStr =mAllMoneyMileageList.get(position).MileageDate;
String[] mPersonBirthDateArray = mMileageDateStr.split("-");
mMileageDateStr = mPersonBirthDateArray[1]+"/"+mPersonBirthDateArray[2].substring(0, 2)+"/"+mPersonBirthDateArray[0];
holder.mMileageDate.setText(mMileageDateStr);
}
if(mAllMoneyMileageList.get(position).VehicleDescription != null)
{
holder.mVehicleDescription.setText(mAllMoneyMileageList.get(position).VehicleDescription);
}
return mView;
}
}
| 2,927 | 0.759822 | 0.757772 | 124 | 22.604839 | 28.403719 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.241935 | false | false | 2 |
bd352c4430154a744dd188da58de160a00275dd2 | 2,138,893,731,139 | 36c5346d30d0fe56b749840261ce4ff12bc1d512 | /Lab 5 - JSSE/SSLClient.java | 20728141003aa9c68c1b6e078674780c09923685 | [] | no_license | matosjoaops/MIEIC_SDIS | https://github.com/matosjoaops/MIEIC_SDIS | f2ec2192b8788c64230e5c53b891798a242d1bb8 | 931cc661322a44102fb30b268204763c8cfd687f | refs/heads/main | 2023-04-09T21:46:47.901000 | 2021-04-23T16:14:45 | 2021-04-23T16:14:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLClient
{
public static void main(String[] args) throws IOException
{
// System.setProperty("javax.net.ssl.keyStore", "server.keys");
// System.setProperty("javax.net.ssl.keyStorePassword", "123456");
System.setProperty("javax.net.ssl.keyStore", "client.keys");
System.setProperty("javax.net.ssl.keyStorePassword", "123456");
System.setProperty("javax.net.ssl.trustStore", "server.keys");
System.setProperty("javax.net.ssl.trustStorePassword", "123456");
// System.setProperty("javax.net.ssl.trustStore", "truststore");
// System.setProperty("javax.net.ssl.trustStorePassword", "123456");
String response = new String();
String message = new String();
try
{
//process command line args
String host = args[0];
int port = Integer.parseInt(args[1]);
String operation = args[2];
List<String> operands = new ArrayList<>();
InetAddress address = InetAddress.getByName(host);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(address, port);
if (operation.equals("REGISTER"))
{
operands.add(args[3]);
operands.add(args[4]);
if (args.length > 5)
{
String[] cipherSuites = new String[args.length - 5];
for (int i = 5; i < args.length; i++) {
cipherSuites[i - 5] = args[i];
}
socket.setEnabledCipherSuites(cipherSuites);
}
}
else
{
operands.add(args[3]);
if (args.length > 4)
{
String[] cipherSuites = new String[args.length - 4];
for (int i = 4; i < args.length; i++) {
cipherSuites[i - 4] = args[i];
}
socket.setEnabledCipherSuites(cipherSuites);
}
}
//build message
message = operation;
for (String operand : operands)
{
message += " " + operand;
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//send message
out.println(message);
//process response
response = in.readLine();
//close socket
socket.shutdownOutput();
socket.close();
}
catch (SocketException e)
{
e.printStackTrace();
System.out.println("Couldn't setup socket!");
response = "ERROR";
}
catch (UnknownHostException e)
{
// e.printStackTrace();
System.out.println("Couldn't get host!");
response = "ERROR";
}
catch (IOException e)
{
System.out.println(e.toString());
System.out.println("Couldn't read/write to/from socket!");
response = "ERROR";
}
finally
{
//print log
System.out.println("SSLClient: " + message + " : " + response);
}
}
} | UTF-8 | Java | 3,862 | java | SSLClient.java | Java | [
{
"context": "em.setProperty(\"javax.net.ssl.keyStorePassword\", \"123456\");\n System.setProperty(\"javax.net.ssl.keyS",
"end": 669,
"score": 0.999302089214325,
"start": 663,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "em.setProperty(\"javax.net.ssl.keyStorePassword... | null | [] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLClient
{
public static void main(String[] args) throws IOException
{
// System.setProperty("javax.net.ssl.keyStore", "server.keys");
// System.setProperty("javax.net.ssl.keyStorePassword", "<PASSWORD>");
System.setProperty("javax.net.ssl.keyStore", "client.keys");
System.setProperty("javax.net.ssl.keyStorePassword", "<PASSWORD>");
System.setProperty("javax.net.ssl.trustStore", "server.keys");
System.setProperty("javax.net.ssl.trustStorePassword", "<PASSWORD>");
// System.setProperty("javax.net.ssl.trustStore", "truststore");
// System.setProperty("javax.net.ssl.trustStorePassword", "<PASSWORD>");
String response = new String();
String message = new String();
try
{
//process command line args
String host = args[0];
int port = Integer.parseInt(args[1]);
String operation = args[2];
List<String> operands = new ArrayList<>();
InetAddress address = InetAddress.getByName(host);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(address, port);
if (operation.equals("REGISTER"))
{
operands.add(args[3]);
operands.add(args[4]);
if (args.length > 5)
{
String[] cipherSuites = new String[args.length - 5];
for (int i = 5; i < args.length; i++) {
cipherSuites[i - 5] = args[i];
}
socket.setEnabledCipherSuites(cipherSuites);
}
}
else
{
operands.add(args[3]);
if (args.length > 4)
{
String[] cipherSuites = new String[args.length - 4];
for (int i = 4; i < args.length; i++) {
cipherSuites[i - 4] = args[i];
}
socket.setEnabledCipherSuites(cipherSuites);
}
}
//build message
message = operation;
for (String operand : operands)
{
message += " " + operand;
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//send message
out.println(message);
//process response
response = in.readLine();
//close socket
socket.shutdownOutput();
socket.close();
}
catch (SocketException e)
{
e.printStackTrace();
System.out.println("Couldn't setup socket!");
response = "ERROR";
}
catch (UnknownHostException e)
{
// e.printStackTrace();
System.out.println("Couldn't get host!");
response = "ERROR";
}
catch (IOException e)
{
System.out.println(e.toString());
System.out.println("Couldn't read/write to/from socket!");
response = "ERROR";
}
finally
{
//print log
System.out.println("SSLClient: " + message + " : " + response);
}
}
} | 3,878 | 0.530813 | 0.520974 | 116 | 32.301723 | 23.603119 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612069 | false | false | 2 |
02aaa9bf0ef7e9af8e08f40bc5a440cd58f16ee8 | 35,296,041,241,136 | 0ee502b5574fd94e3755bb5f7c689a792f104838 | /interface-infosnake-cleverreach/src/main/java/com/jmg/iic/Application.java | 5c450eba6d03b6ee3cf8953ec99a5412be9d0bba | [] | no_license | javi-more-garc/infosnake | https://github.com/javi-more-garc/infosnake | 3ff1c91171756814221a308147c9a22237d09f2a | edd7f2bd4bb3ca17e55df3d5b5e7176eae29c420 | refs/heads/master | 2021-05-02T08:34:24.737000 | 2015-05-19T20:32:04 | 2015-05-19T20:32:04 | 35,867,101 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jmg.iic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
*
* Class that servers as the application's launcher
*
* @author Javier Moreno Garcia
*
*/
@SpringBootApplication
@EnableScheduling
@PropertySources({ @PropertySource("classpath:/conf.properties"),
@PropertySource(value = "file:conf.properties", ignoreResourceNotFound = true) })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| UTF-8 | Java | 756 | java | Application.java | Java | [
{
"context": "rvers as the application's launcher\n * \n * @author Javier Moreno Garcia\n *\n */\n\n@SpringBootApplication\n@EnableScheduling\n",
"end": 430,
"score": 0.999875009059906,
"start": 410,
"tag": "NAME",
"value": "Javier Moreno Garcia"
}
] | null | [] | package com.jmg.iic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
*
* Class that servers as the application's launcher
*
* @author <NAME>
*
*/
@SpringBootApplication
@EnableScheduling
@PropertySources({ @PropertySource("classpath:/conf.properties"),
@PropertySource(value = "file:conf.properties", ignoreResourceNotFound = true) })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 742 | 0.797619 | 0.797619 | 27 | 27 | 27.226076 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 2 |
3574f4013410fb0b826d8810a95181703ea5f6b4 | 33,621,004,040,068 | 3d822dd9b29253ff32e50bf394527667a96085b5 | /BackEnd/service/src/main/java/com/basis/sge/service/recurso/UsuarioAutenticacaoRecurso.java | fe74a8ee06089fe607476920f46c5663066d2a22 | [] | no_license | kayc-drummond/Basis-SGE | https://github.com/kayc-drummond/Basis-SGE | 8a69cf195a74aa4a52bd6a1c9b49c5729e65eca6 | 79d7105696ee45eb8f35434deee0b90898d4e98f | refs/heads/main | 2023-03-01T13:03:24.623000 | 2021-02-10T11:42:44 | 2021-02-10T11:42:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.basis.sge.service.recurso;
import com.basis.sge.service.servico.UsuarioAutenticacaoServico;
import com.basis.sge.service.servico.dto.UsuarioAutenticacaoDTO;
import com.basis.sge.service.servico.dto.UsuarioDTO;
import com.basis.sge.service.servico.exception.RegraNegocioException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.net.URISyntaxException;
@RestController
@RequestMapping("/api/login")
@RequiredArgsConstructor
public class UsuarioAutenticacaoRecurso {
private final UsuarioAutenticacaoServico usuarioAutenticacaoServico;
@PostMapping
public ResponseEntity<UsuarioDTO> autenticacaoCpfEChave(@Valid @RequestBody UsuarioAutenticacaoDTO usuarioAutenticacaoDTO) throws URISyntaxException, RegraNegocioException {
return ResponseEntity.ok(usuarioAutenticacaoServico.autenticacaoCpfEChave(usuarioAutenticacaoDTO));
}
}
| UTF-8 | Java | 1,194 | java | UsuarioAutenticacaoRecurso.java | Java | [] | null | [] | package com.basis.sge.service.recurso;
import com.basis.sge.service.servico.UsuarioAutenticacaoServico;
import com.basis.sge.service.servico.dto.UsuarioAutenticacaoDTO;
import com.basis.sge.service.servico.dto.UsuarioDTO;
import com.basis.sge.service.servico.exception.RegraNegocioException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.net.URISyntaxException;
@RestController
@RequestMapping("/api/login")
@RequiredArgsConstructor
public class UsuarioAutenticacaoRecurso {
private final UsuarioAutenticacaoServico usuarioAutenticacaoServico;
@PostMapping
public ResponseEntity<UsuarioDTO> autenticacaoCpfEChave(@Valid @RequestBody UsuarioAutenticacaoDTO usuarioAutenticacaoDTO) throws URISyntaxException, RegraNegocioException {
return ResponseEntity.ok(usuarioAutenticacaoServico.autenticacaoCpfEChave(usuarioAutenticacaoDTO));
}
}
| 1,194 | 0.850921 | 0.850921 | 28 | 41.642857 | 38.050919 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
18ecabf6558debb8c002107c7fc9ef90b0a77eee | 2,551,210,606,378 | 13bb6aeaa5c6f1ebb5c6a8cced5f1e8c1df1eda0 | /Surf/src/main/java/controller/MainProductsServlet.java | 08697b7f9f308a9e5cb5ec356570cce6984f6fa3 | [] | no_license | SurfEEIT86/surf | https://github.com/SurfEEIT86/surf | 1d1bad0f4ced68e06e25cd657759f5783a9396d2 | 1a4046d8cee006ee36d890b3486e785df9395fa6 | refs/heads/master | 2021-01-17T17:55:50.534000 | 2016-08-08T01:27:20 | 2016-08-08T01:27:20 | 64,100,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONValue;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.surf.producttype.model.ProducttypesDAO;
import com.surf.producttype.model.ProducttypesVO;
/**
* Servlet implementation class MainProductsServlet
*/
@WebServlet("/MainProductsServlet.do")
public class MainProductsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ProducttypesDAO dao;
public MainProductsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
List<ProducttypesVO> prodTypes = dao.selectAll();
Iterator<ProducttypesVO> beans = prodTypes.iterator();
List<Map<String, String>> types = new LinkedList<Map<String, String>>();
while(beans.hasNext()){
Map<String, String> m1 = new HashMap<String, String>();
ProducttypesVO bean = beans.next();
if(bean.getStatus()){
m1.put("type", bean.getType());
m1.put("typeno", bean.getTypeno().toString());
types.add(m1);
}
}
String jsonString = JSONValue.toJSONString(types);
out.println(jsonString);
}
@Override
public void init() throws ServletException {
ServletContext application = this.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
dao = (ProducttypesDAO) context.getBean("producttypesDAO");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
| UTF-8 | Java | 2,438 | java | MainProductsServlet.java | Java | [] | null | [] | package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONValue;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.surf.producttype.model.ProducttypesDAO;
import com.surf.producttype.model.ProducttypesVO;
/**
* Servlet implementation class MainProductsServlet
*/
@WebServlet("/MainProductsServlet.do")
public class MainProductsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ProducttypesDAO dao;
public MainProductsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
List<ProducttypesVO> prodTypes = dao.selectAll();
Iterator<ProducttypesVO> beans = prodTypes.iterator();
List<Map<String, String>> types = new LinkedList<Map<String, String>>();
while(beans.hasNext()){
Map<String, String> m1 = new HashMap<String, String>();
ProducttypesVO bean = beans.next();
if(bean.getStatus()){
m1.put("type", bean.getType());
m1.put("typeno", bean.getTypeno().toString());
types.add(m1);
}
}
String jsonString = JSONValue.toJSONString(types);
out.println(jsonString);
}
@Override
public void init() throws ServletException {
ServletContext application = this.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
dao = (ProducttypesDAO) context.getBean("producttypesDAO");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
| 2,438 | 0.736259 | 0.733388 | 72 | 31.861111 | 27.461744 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.805556 | false | false | 2 |
7d0a7a0664fa4511bc53dd0561f879f78f701b80 | 30,253,749,692,671 | f71474166e00974c24df3bdc06d32c531a8acb62 | /app/src/main/java/com/fxb/receiver/myapplication/SelectReceiverActivity.java | 05d9ff449596f2f214e4a26278d9755fdb213661 | [] | no_license | ZFKnife/MagUHF_LYM_Receiver | https://github.com/ZFKnife/MagUHF_LYM_Receiver | b9da5b9a4b26f7df087d5fe14f15db207e339add | b1b564d568d0aa1bcae5bfd5affb73462393e2ae | refs/heads/master | 2021-06-22T07:49:35.386000 | 2017-08-18T09:36:08 | 2017-08-18T09:36:08 | 99,873,318 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fxb.receiver.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.fxb.receiver.myapplication.application.App;
import com.fxb.receiver.myapplication.config.RequestConfig;
import com.fxb.receiver.myapplication.util.Sp;
import com.fxb.receiver.myapplication.util.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/7/18 0018.
*/
public class SelectReceiverActivity extends Activity {
private String TAG = SelectReceiverActivity.class.getSimpleName();
private Spinner selectActivityReceiver;
private Button selectActivityBtn;
private List<String> list;
private int size = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_receiver);
init();
getReceiver();
}
private void init() {
selectActivityReceiver = (Spinner) findViewById(R.id.select_activity_receiver);
selectActivityBtn = (Button) findViewById(R.id.select_activity_btn);
selectActivityReceiver.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
size = i;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
selectActivityBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (list == null) {
return;
}
if (size == -1) {
return;
}
Sp.putString(SelectReceiverActivity.this, "name", list.get(size));
Toast.makeText(SelectReceiverActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
finish();
}
});
}
public void getReceiver() {
StringRequest getContactRequest = new StringRequest(RequestConfig.getReceiverList, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
if (TextUtils.isEmpty(s)) {
ToastUtil.getShortToastByString(SelectReceiverActivity.this, "服务器数据异常");
return;
}
try {
JSONObject o = new JSONObject(s);
JSONArray ja = new JSONArray(o.getString("namelist"));
int w = ja.length();
list = new ArrayList<>();
for (int i = 0; i < w; i++) {
list.add(ja.getString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SelectReceiverActivity.this,
android.R.layout.simple_expandable_list_item_1, list);
selectActivityReceiver.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
ToastUtil.getShortToastByString(SelectReceiverActivity.this, "网络异常,请稍后再试");
}
});
getContactRequest.setTag(this);
App.getRequestQueue().add(getContactRequest);
}
@Override
protected void onDestroy() {
super.onDestroy();
App.getRequestQueue().cancelAll(this);
}
}
| UTF-8 | Java | 4,114 | java | SelectReceiverActivity.java | Java | [] | null | [] | package com.fxb.receiver.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.fxb.receiver.myapplication.application.App;
import com.fxb.receiver.myapplication.config.RequestConfig;
import com.fxb.receiver.myapplication.util.Sp;
import com.fxb.receiver.myapplication.util.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/7/18 0018.
*/
public class SelectReceiverActivity extends Activity {
private String TAG = SelectReceiverActivity.class.getSimpleName();
private Spinner selectActivityReceiver;
private Button selectActivityBtn;
private List<String> list;
private int size = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_receiver);
init();
getReceiver();
}
private void init() {
selectActivityReceiver = (Spinner) findViewById(R.id.select_activity_receiver);
selectActivityBtn = (Button) findViewById(R.id.select_activity_btn);
selectActivityReceiver.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
size = i;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
selectActivityBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (list == null) {
return;
}
if (size == -1) {
return;
}
Sp.putString(SelectReceiverActivity.this, "name", list.get(size));
Toast.makeText(SelectReceiverActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
finish();
}
});
}
public void getReceiver() {
StringRequest getContactRequest = new StringRequest(RequestConfig.getReceiverList, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
if (TextUtils.isEmpty(s)) {
ToastUtil.getShortToastByString(SelectReceiverActivity.this, "服务器数据异常");
return;
}
try {
JSONObject o = new JSONObject(s);
JSONArray ja = new JSONArray(o.getString("namelist"));
int w = ja.length();
list = new ArrayList<>();
for (int i = 0; i < w; i++) {
list.add(ja.getString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SelectReceiverActivity.this,
android.R.layout.simple_expandable_list_item_1, list);
selectActivityReceiver.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
ToastUtil.getShortToastByString(SelectReceiverActivity.this, "网络异常,请稍后再试");
}
});
getContactRequest.setTag(this);
App.getRequestQueue().add(getContactRequest);
}
@Override
protected void onDestroy() {
super.onDestroy();
App.getRequestQueue().cancelAll(this);
}
}
| 4,114 | 0.609283 | 0.605599 | 120 | 32.933334 | 27.099426 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
de4176f8183ad80255232a1ffe8351d97d4d6afe | 30,253,749,694,519 | 39b36276e06a42304b30a25f7222b0a0a0f9a66c | /webapp/v6_webapp/trunk/src/main/java/com/xxdai/external/borrowFee/ws/ObjectFactory.java | 4755552721a29138cd842b743477109fbf78335a | [] | no_license | moutainhigh/x-project | https://github.com/moutainhigh/x-project | 9673c791e258cd36fa9ca93046f2a356d48d038a | 2ce3b10e6f2990a2fa78bfaddb45a7bea4f7c80b | refs/heads/master | 2021-09-16T15:27:02.523000 | 2018-06-21T21:42:21 | 2018-06-21T21:42:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xxdai.external.borrowFee.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.xxdai.external.borrowFee.ws package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _SelectBorrowFeesMapByBorrowIdResponse_QNAME = new QName("http://webservice.borrow.xxdai.com/", "selectBorrowFeesMapByBorrowIdResponse");
private final static QName _DaoException_QNAME = new QName("http://webservice.borrow.xxdai.com/", "DaoException");
private final static QName _SelectBorrowFeesMapByBorrowId_QNAME = new QName("http://webservice.borrow.xxdai.com/", "selectBorrowFeesMapByBorrowId");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.xxdai.external.borrowFee.ws
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link SelectBorrowFeesMapByBorrowId }
*
*/
public SelectBorrowFeesMapByBorrowId createSelectBorrowFeesMapByBorrowId() {
return new SelectBorrowFeesMapByBorrowId();
}
/**
* Create an instance of {@link DaoException }
*
*/
public DaoException createDaoException() {
return new DaoException();
}
/**
* Create an instance of {@link SelectBorrowFeesMapByBorrowIdResponse }
*
*/
public SelectBorrowFeesMapByBorrowIdResponse createSelectBorrowFeesMapByBorrowIdResponse() {
return new SelectBorrowFeesMapByBorrowIdResponse();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SelectBorrowFeesMapByBorrowIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "selectBorrowFeesMapByBorrowIdResponse")
public JAXBElement<SelectBorrowFeesMapByBorrowIdResponse> createSelectBorrowFeesMapByBorrowIdResponse(SelectBorrowFeesMapByBorrowIdResponse value) {
return new JAXBElement<SelectBorrowFeesMapByBorrowIdResponse>(_SelectBorrowFeesMapByBorrowIdResponse_QNAME, SelectBorrowFeesMapByBorrowIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DaoException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "DaoException")
public JAXBElement<DaoException> createDaoException(DaoException value) {
return new JAXBElement<DaoException>(_DaoException_QNAME, DaoException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SelectBorrowFeesMapByBorrowId }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "selectBorrowFeesMapByBorrowId")
public JAXBElement<SelectBorrowFeesMapByBorrowId> createSelectBorrowFeesMapByBorrowId(SelectBorrowFeesMapByBorrowId value) {
return new JAXBElement<SelectBorrowFeesMapByBorrowId>(_SelectBorrowFeesMapByBorrowId_QNAME, SelectBorrowFeesMapByBorrowId.class, null, value);
}
}
| UTF-8 | Java | 3,651 | java | ObjectFactory.java | Java | [] | null | [] |
package com.xxdai.external.borrowFee.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.xxdai.external.borrowFee.ws package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _SelectBorrowFeesMapByBorrowIdResponse_QNAME = new QName("http://webservice.borrow.xxdai.com/", "selectBorrowFeesMapByBorrowIdResponse");
private final static QName _DaoException_QNAME = new QName("http://webservice.borrow.xxdai.com/", "DaoException");
private final static QName _SelectBorrowFeesMapByBorrowId_QNAME = new QName("http://webservice.borrow.xxdai.com/", "selectBorrowFeesMapByBorrowId");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.xxdai.external.borrowFee.ws
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link SelectBorrowFeesMapByBorrowId }
*
*/
public SelectBorrowFeesMapByBorrowId createSelectBorrowFeesMapByBorrowId() {
return new SelectBorrowFeesMapByBorrowId();
}
/**
* Create an instance of {@link DaoException }
*
*/
public DaoException createDaoException() {
return new DaoException();
}
/**
* Create an instance of {@link SelectBorrowFeesMapByBorrowIdResponse }
*
*/
public SelectBorrowFeesMapByBorrowIdResponse createSelectBorrowFeesMapByBorrowIdResponse() {
return new SelectBorrowFeesMapByBorrowIdResponse();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SelectBorrowFeesMapByBorrowIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "selectBorrowFeesMapByBorrowIdResponse")
public JAXBElement<SelectBorrowFeesMapByBorrowIdResponse> createSelectBorrowFeesMapByBorrowIdResponse(SelectBorrowFeesMapByBorrowIdResponse value) {
return new JAXBElement<SelectBorrowFeesMapByBorrowIdResponse>(_SelectBorrowFeesMapByBorrowIdResponse_QNAME, SelectBorrowFeesMapByBorrowIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DaoException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "DaoException")
public JAXBElement<DaoException> createDaoException(DaoException value) {
return new JAXBElement<DaoException>(_DaoException_QNAME, DaoException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SelectBorrowFeesMapByBorrowId }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://webservice.borrow.xxdai.com/", name = "selectBorrowFeesMapByBorrowId")
public JAXBElement<SelectBorrowFeesMapByBorrowId> createSelectBorrowFeesMapByBorrowId(SelectBorrowFeesMapByBorrowId value) {
return new JAXBElement<SelectBorrowFeesMapByBorrowId>(_SelectBorrowFeesMapByBorrowId_QNAME, SelectBorrowFeesMapByBorrowId.class, null, value);
}
}
| 3,651 | 0.736784 | 0.736784 | 88 | 40.477272 | 46.947742 | 174 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340909 | false | false | 2 |
6eb17aae21e0e062e2275702ebc6d5a6c0b72b19 | 17,540,646,489,379 | 4d70c126c9bbd67edbd3d254a95f036c60010d59 | /src/com/smorg/data/GoalDAO.java | cf5c57a581066d5bac925d8ce4504b8bc0e36d32 | [] | no_license | Tar3k/smorg-frontendapi15 | https://github.com/Tar3k/smorg-frontendapi15 | 0efa89a577157eb87b2d25ad4b7b44e3d8501854 | 824cd8ab04c238460aa8ab25d7db2f883f8ee56b | refs/heads/master | 2016-09-10T10:49:10.577000 | 2012-07-09T15:22:25 | 2012-07-09T15:22:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smorg.data;
import java.io.Serializable;
import java.util.ArrayList;
public interface GoalDAO extends Serializable{
/**
* Persists Goal information to a persistent data store
*/
public void addGoal(Goal goal);
/**
* Gets all of the Goal instances in the data store
*/
public ArrayList<Goal> getAllGoals(String userId);
/**
* Removed a Goal instance in data store that
* matches Goal
*/
public void removeGoal(Long goalId);
public void addEventToGoal(Long goalId,String eventId);
public ArrayList<String> getGoalEvents (Long goalId);
} | UTF-8 | Java | 628 | java | GoalDAO.java | Java | [] | null | [] | package com.smorg.data;
import java.io.Serializable;
import java.util.ArrayList;
public interface GoalDAO extends Serializable{
/**
* Persists Goal information to a persistent data store
*/
public void addGoal(Goal goal);
/**
* Gets all of the Goal instances in the data store
*/
public ArrayList<Goal> getAllGoals(String userId);
/**
* Removed a Goal instance in data store that
* matches Goal
*/
public void removeGoal(Long goalId);
public void addEventToGoal(Long goalId,String eventId);
public ArrayList<String> getGoalEvents (Long goalId);
} | 628 | 0.676752 | 0.676752 | 27 | 22.296297 | 21.774628 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
10a376d0feed66aafedd7d39846484ad8de3aafd | 34,119,220,217,820 | 600c9f7b166ae86e94f947fa143f1cb32ece18a9 | /src/pt/iscte/poo/instalacao/Tomada.java | 8c16df88e3aeeb61184a4d31adecdcd5d92b2696 | [] | no_license | afonso218/project-iot | https://github.com/afonso218/project-iot | fc5bd83a92c1d82e96dbe42019c30d2d3e25fa4f | cfa15295cd309aea2b6584536ca7460305aa896b | refs/heads/master | 2022-12-03T18:06:44.571000 | 2020-08-11T09:41:01 | 2020-08-11T09:41:01 | 286,704,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pt.iscte.poo.instalacao;
import pt.iscte.poo.instalacao.aparelhos.Tripla;
public class Tomada {
private Ligavel ligavel;
public boolean isFree() {
if(ligavel == null){
return true;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).isFree();
}else
return false;
}
}
public Tomada getFree(){
if(ligavel == null){
return this;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).getFree();
}else
return null;
}
}
public boolean haveAparelho(String nome) {
if(ligavel == null){
return false;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).haveAparelho(nome);
}else
return ligavel.getId().equals(nome);
}
}
// TEM
public Ligavel getAparelho(String nome) {
if(ligavel == null)
return null;
else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).getAparelho(nome);
}else{
if(ligavel.getId().equals(nome)){
return ligavel;
}else{
return null;
}
}
}
}
// TEM
public boolean estaLigado() {
if(ligavel != null)
return ligavel.estaLigado();
else
return false;
}
// TEM
public void liga(Ligavel ligavel) {
this.ligavel = ligavel;
}
public Ligavel getLigavel(){
return ligavel;
}
public String getId() {
if(ligavel == null)
return "";
else
return ligavel.getId();
}
}
| UTF-8 | Java | 1,353 | java | Tomada.java | Java | [] | null | [] | package pt.iscte.poo.instalacao;
import pt.iscte.poo.instalacao.aparelhos.Tripla;
public class Tomada {
private Ligavel ligavel;
public boolean isFree() {
if(ligavel == null){
return true;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).isFree();
}else
return false;
}
}
public Tomada getFree(){
if(ligavel == null){
return this;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).getFree();
}else
return null;
}
}
public boolean haveAparelho(String nome) {
if(ligavel == null){
return false;
}else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).haveAparelho(nome);
}else
return ligavel.getId().equals(nome);
}
}
// TEM
public Ligavel getAparelho(String nome) {
if(ligavel == null)
return null;
else{
if(ligavel.isTripla()){
return ((Tripla)ligavel).getAparelho(nome);
}else{
if(ligavel.getId().equals(nome)){
return ligavel;
}else{
return null;
}
}
}
}
// TEM
public boolean estaLigado() {
if(ligavel != null)
return ligavel.estaLigado();
else
return false;
}
// TEM
public void liga(Ligavel ligavel) {
this.ligavel = ligavel;
}
public Ligavel getLigavel(){
return ligavel;
}
public String getId() {
if(ligavel == null)
return "";
else
return ligavel.getId();
}
}
| 1,353 | 0.627494 | 0.627494 | 83 | 15.301205 | 13.666188 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.192771 | false | false | 2 |
b09499e823fb26e2865f2f712b16c45844dd4225 | 36,945,308,689,745 | 2675cf7c30af9e0d0ece733ef34b81c1ff7da5d5 | /day1/wednesday/Question02.java | c742df66b4bd15b8220d8d406cbc3113f9c15530 | [] | no_license | PeterFLopis/TY_JAVA_ABRIDGE_PETERLOPIS_FEB24 | https://github.com/PeterFLopis/TY_JAVA_ABRIDGE_PETERLOPIS_FEB24 | d3c09b8e7aaa870af43473722c359e28106821d2 | 1750eb792d18c2d33d00d453aefee99598845736 | refs/heads/master | 2021-03-06T17:25:56.979000 | 2020-03-10T05:12:44 | 2020-03-10T05:12:44 | 246,212,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.capgemini.quiz.day1.wednesday;
public class Question02 {
/* which of the following is a platform independent .
* a) JDK b) c++ c) java d) .net
*
*
*
* ANSWER: c)Java
*/
}
| UTF-8 | Java | 204 | java | Question02.java | Java | [] | null | [] | package com.capgemini.quiz.day1.wednesday;
public class Question02 {
/* which of the following is a platform independent .
* a) JDK b) c++ c) java d) .net
*
*
*
* ANSWER: c)Java
*/
}
| 204 | 0.607843 | 0.593137 | 12 | 16 | 17.860571 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.083333 | false | false | 2 |
ecbe87028a3fb0fca86b46cede8eb25fc9fc3d60 | 35,897,336,682,251 | 17c52db74cc8bfb89cfda1ae1fb1bf7f756a38e5 | /src/server/Server.java | b5b38d26f51ad7b4a7e23f2072ba24ab5be6edec | [] | no_license | mcvoogd/Pac-manHunter | https://github.com/mcvoogd/Pac-manHunter | 4476e7babb5b97e8aa9c05bd9697e4e689253766 | 15bbb8998520046ba7df4372635ebd2c18c49cf2 | refs/heads/master | 2020-12-30T12:56:12.777000 | 2016-06-13T21:33:02 | 2016-06-13T21:33:02 | 91,377,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server;
import util.Images;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame {
// Text area for displaying contents
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new Server();
}
public Server() {
new Images();
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("MultiThreadServer");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("MultiThreadServer started at " + new Date() + '\n');
// Number a client
int clientNo = 1;
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
Socket socket2 = serverSocket.accept();
// Display the client number
jta.append("Starting thread for client " + clientNo + " and " + (clientNo + 1) +
" at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress inetAddress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "
+ inetAddress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is "
+ inetAddress.getHostAddress() + "\n");
clientNo++;
InetAddress inetAddress2 = socket2.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "
+ inetAddress2.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is "
+ inetAddress2.getHostAddress() + "\n");
// Create a new thread for the connection
HandleAClient task = new HandleAClient(socket, socket2, new Game());
// Start the new thread
new Thread(task).start();
// Increment clientNo
clientNo++;
}
} catch (IOException ex) {
System.err.println(ex);
}
}
class HandleAClient implements Runnable {
private Socket socket1, socket2;
private Game game;
private boolean stop;
/** Construct a thread */
public HandleAClient(Socket socket1, Socket socket2, Game game) {
this.socket1 = socket1;
this.socket2 = socket2;
this.game = game;
}
/** Run a thread */
public void run() {
try {
// Create data input and output streams
DataInputStream inputFromClient1 = new DataInputStream(
socket1.getInputStream());
DataOutputStream outputToClient1 = new DataOutputStream(
socket1.getOutputStream());
DataInputStream inputFromClient2 = new DataInputStream(
socket2.getInputStream());
DataOutputStream outputToClient2 = new DataOutputStream(
socket2.getOutputStream());
int oldx1 = 0;
int oldy1 = 0;
int oldx2 = 0;
int oldy2 = 0;
int oldDirectionX1 = 0;
int oldDirectionY1 = 0;
int oldDirectionX2 = 0;
int oldDirectionY2 = 0;
outputToClient1.writeBoolean(true);
outputToClient2.writeBoolean(true);
outputToClient1.writeInt(1);
outputToClient2.writeInt(2);
// Continuously serve the client
while (true) {
if(!stop){
game.update();
if (inputFromClient1.available() > 0) {
int readInt = inputFromClient1.readInt();
int readInt2 = inputFromClient1.readInt();
int x1 = oldx1;
int y1 = oldy1;
int directionX = oldDirectionX1;
int directionY = oldDirectionY1;
if (readInt - 8000 >= 0) {
directionY = readInt;
} else if (readInt - 7000 >= 0) {
directionX = readInt;
} else if ((readInt - 2000) > 0) {
y1 = readInt;
} else {
x1 = readInt;
}
if ((readInt2 - 2000) > 0) {
y1 = readInt2;
} else {
x1 = readInt2;
}
if ((x1 != oldx1) || (y1 != oldy1)) {
outputToClient2.writeInt(x1);
outputToClient2.writeInt(y1);
game.setPlayer1Location(x1 - 1000, y1 - 2000);
}
if (directionX != oldDirectionX1 || directionY != oldDirectionY1) {
outputToClient2.writeInt(directionX);
outputToClient2.writeInt(directionY);
}
oldx1 = x1;
oldy1 = y1;
oldDirectionX1 = directionX;
oldDirectionY1 = directionY;
}
if (inputFromClient2.available() > 0) {
int readInt = inputFromClient2.readInt();
int readInt2 = inputFromClient2.readInt();
int x2 = oldx2;
int y2 = oldy2;
int directionX = oldDirectionX2;
int directionY = oldDirectionY2;
if (readInt - 8000 >= 0) {
directionY = readInt;
} else if (readInt - 7000 >= 0) {
directionX = readInt;
} else if ((readInt - 2000) > 0) {
y2 = readInt;
} else {
x2 = readInt;
}
if ((readInt2 - 2000) > 0) {
y2 = readInt2;
} else {
x2 = readInt2;
}
if ((x2 != oldx2) || (y2 != oldy2)) {
outputToClient1.writeInt(x2);
outputToClient1.writeInt(y2);
game.setPlayer2Location(x2 - 1000, y2 - 2000);
}
if (directionX != oldDirectionX2 || directionY != oldDirectionY2) {
outputToClient1.writeInt(directionX);
outputToClient1.writeInt(directionY);
}
oldx2 = x2;
oldy2 = y2;
oldDirectionX2 = directionX;
oldDirectionY2 = directionY;
}
int x = game.getPacman().getXCoord() + 3000;
int y = game.getPacman().getYCoord() + 4000;
outputToClient1.writeInt(x);
outputToClient1.writeInt(y);
outputToClient2.writeInt(x);
outputToClient2.writeInt(y);
int score1 = game.getScorePlayer1() + 5000;
int score2 = game.getScorePlayer2() + 6000;
outputToClient1.writeInt(score1);
outputToClient1.writeInt(score2);
outputToClient2.writeInt(score1 + 1000);
outputToClient2.writeInt(score2 - 1000);
int pacmanDirectionX = game.getPacman().getxDirection() + 10050;
int pacmanDirectionY = game.getPacman().getyDirection() + 11050;
outputToClient1.writeInt(pacmanDirectionX);
outputToClient1.writeInt(pacmanDirectionY);
outputToClient2.writeInt(pacmanDirectionX);
outputToClient2.writeInt(pacmanDirectionY);
}
if(game.isFinished() && !stop){
int winner = game.getWinner() + 13000;
outputToClient1.writeInt(winner);
outputToClient2.writeInt(winner);
stop = true;
}
}
}
catch(IOException e) {
System.err.println(e);
}
}
}
}
| UTF-8 | Java | 9,503 | java | Server.java | Java | [] | null | [] | package server;
import util.Images;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Server extends JFrame {
// Text area for displaying contents
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new Server();
}
public Server() {
new Images();
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("MultiThreadServer");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("MultiThreadServer started at " + new Date() + '\n');
// Number a client
int clientNo = 1;
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
Socket socket2 = serverSocket.accept();
// Display the client number
jta.append("Starting thread for client " + clientNo + " and " + (clientNo + 1) +
" at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress inetAddress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "
+ inetAddress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is "
+ inetAddress.getHostAddress() + "\n");
clientNo++;
InetAddress inetAddress2 = socket2.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "
+ inetAddress2.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is "
+ inetAddress2.getHostAddress() + "\n");
// Create a new thread for the connection
HandleAClient task = new HandleAClient(socket, socket2, new Game());
// Start the new thread
new Thread(task).start();
// Increment clientNo
clientNo++;
}
} catch (IOException ex) {
System.err.println(ex);
}
}
class HandleAClient implements Runnable {
private Socket socket1, socket2;
private Game game;
private boolean stop;
/** Construct a thread */
public HandleAClient(Socket socket1, Socket socket2, Game game) {
this.socket1 = socket1;
this.socket2 = socket2;
this.game = game;
}
/** Run a thread */
public void run() {
try {
// Create data input and output streams
DataInputStream inputFromClient1 = new DataInputStream(
socket1.getInputStream());
DataOutputStream outputToClient1 = new DataOutputStream(
socket1.getOutputStream());
DataInputStream inputFromClient2 = new DataInputStream(
socket2.getInputStream());
DataOutputStream outputToClient2 = new DataOutputStream(
socket2.getOutputStream());
int oldx1 = 0;
int oldy1 = 0;
int oldx2 = 0;
int oldy2 = 0;
int oldDirectionX1 = 0;
int oldDirectionY1 = 0;
int oldDirectionX2 = 0;
int oldDirectionY2 = 0;
outputToClient1.writeBoolean(true);
outputToClient2.writeBoolean(true);
outputToClient1.writeInt(1);
outputToClient2.writeInt(2);
// Continuously serve the client
while (true) {
if(!stop){
game.update();
if (inputFromClient1.available() > 0) {
int readInt = inputFromClient1.readInt();
int readInt2 = inputFromClient1.readInt();
int x1 = oldx1;
int y1 = oldy1;
int directionX = oldDirectionX1;
int directionY = oldDirectionY1;
if (readInt - 8000 >= 0) {
directionY = readInt;
} else if (readInt - 7000 >= 0) {
directionX = readInt;
} else if ((readInt - 2000) > 0) {
y1 = readInt;
} else {
x1 = readInt;
}
if ((readInt2 - 2000) > 0) {
y1 = readInt2;
} else {
x1 = readInt2;
}
if ((x1 != oldx1) || (y1 != oldy1)) {
outputToClient2.writeInt(x1);
outputToClient2.writeInt(y1);
game.setPlayer1Location(x1 - 1000, y1 - 2000);
}
if (directionX != oldDirectionX1 || directionY != oldDirectionY1) {
outputToClient2.writeInt(directionX);
outputToClient2.writeInt(directionY);
}
oldx1 = x1;
oldy1 = y1;
oldDirectionX1 = directionX;
oldDirectionY1 = directionY;
}
if (inputFromClient2.available() > 0) {
int readInt = inputFromClient2.readInt();
int readInt2 = inputFromClient2.readInt();
int x2 = oldx2;
int y2 = oldy2;
int directionX = oldDirectionX2;
int directionY = oldDirectionY2;
if (readInt - 8000 >= 0) {
directionY = readInt;
} else if (readInt - 7000 >= 0) {
directionX = readInt;
} else if ((readInt - 2000) > 0) {
y2 = readInt;
} else {
x2 = readInt;
}
if ((readInt2 - 2000) > 0) {
y2 = readInt2;
} else {
x2 = readInt2;
}
if ((x2 != oldx2) || (y2 != oldy2)) {
outputToClient1.writeInt(x2);
outputToClient1.writeInt(y2);
game.setPlayer2Location(x2 - 1000, y2 - 2000);
}
if (directionX != oldDirectionX2 || directionY != oldDirectionY2) {
outputToClient1.writeInt(directionX);
outputToClient1.writeInt(directionY);
}
oldx2 = x2;
oldy2 = y2;
oldDirectionX2 = directionX;
oldDirectionY2 = directionY;
}
int x = game.getPacman().getXCoord() + 3000;
int y = game.getPacman().getYCoord() + 4000;
outputToClient1.writeInt(x);
outputToClient1.writeInt(y);
outputToClient2.writeInt(x);
outputToClient2.writeInt(y);
int score1 = game.getScorePlayer1() + 5000;
int score2 = game.getScorePlayer2() + 6000;
outputToClient1.writeInt(score1);
outputToClient1.writeInt(score2);
outputToClient2.writeInt(score1 + 1000);
outputToClient2.writeInt(score2 - 1000);
int pacmanDirectionX = game.getPacman().getxDirection() + 10050;
int pacmanDirectionY = game.getPacman().getyDirection() + 11050;
outputToClient1.writeInt(pacmanDirectionX);
outputToClient1.writeInt(pacmanDirectionY);
outputToClient2.writeInt(pacmanDirectionX);
outputToClient2.writeInt(pacmanDirectionY);
}
if(game.isFinished() && !stop){
int winner = game.getWinner() + 13000;
outputToClient1.writeInt(winner);
outputToClient2.writeInt(winner);
stop = true;
}
}
}
catch(IOException e) {
System.err.println(e);
}
}
}
}
| 9,503 | 0.428707 | 0.402294 | 231 | 40.138527 | 24.191477 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.601732 | false | false | 2 |
98b93519cda7a029d5cf990703a232b0b1a3139e | 1,898,375,594,591 | 12cd22299ae8fea21e2c975829e3d66ef53d5c66 | /src/IO/MyCompressorOutputStream.java | 35577095594b7a485b9e7689d01e11b51c805bc3 | [] | no_license | ayemoy/ATP-Project-PartB | https://github.com/ayemoy/ATP-Project-PartB | 948aba87c2689c365ce8e5eba1e536e94f66b7c5 | d5c5ef9d75804c4057b5dd432f065a3cc3a7317c | refs/heads/master | 2023-04-23T08:53:38.303000 | 2021-05-10T10:23:29 | 2021-05-10T10:23:29 | 361,366,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package IO;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
public class MyCompressorOutputStream extends OutputStream { //this class exstend the outputstream class (not ours)
private OutputStream out;
public MyCompressorOutputStream(OutputStream outputStream) { //constructor
this.out = outputStream;
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] bytesArray) throws IOException { //this func get byte array and compress it
if(bytesArray == null)
{
throw new IOException("The Bytes Array Is Empty");
}
//super.write(bytesArray); //TODO check if we need the super?
byte[] finalCompressedArray = Arrays.copyOfRange(bytesArray, 0, 24); //copy the 24 first byte to the new compressed array
int sizeOfBytesArray = bytesArray.length - 24; //save the size of the bytesArray without the 24 first bytes
int indexInBytesArray = 24; //save the start index to take 32 bytes for convert
while (sizeOfBytesArray > 0) //while the original bytesArray not empty
{
if (sizeOfBytesArray >= 32)
{
byte[] arrayToConvert = Arrays.copyOfRange(bytesArray, indexInBytesArray, indexInBytesArray + 32); //copy only 32 bytes from original array
finalCompressedArray =convertByteArrayToInt(arrayToConvert ,arrayToConvert.length ,finalCompressedArray); //send to this function for int conversion
sizeOfBytesArray -= 32;
indexInBytesArray += 32;
}
else
{
int newSizeOfBytesArray = sizeOfBytesArray%32; //minimize the original size array
byte[] arrayToConvert = Arrays.copyOfRange(bytesArray, indexInBytesArray,(indexInBytesArray+newSizeOfBytesArray)); //copy the rest of bytes from original array
finalCompressedArray =convertByteArrayToInt(arrayToConvert ,newSizeOfBytesArray ,finalCompressedArray); //send to this function for int conversion
sizeOfBytesArray-=newSizeOfBytesArray;
}
}
if (out instanceof ObjectOutputStream)
((ObjectOutputStream) out).writeObject(finalCompressedArray);
else
out.write(finalCompressedArray);
out.flush();
out.close();
}
private byte[] convertByteArrayToInt(byte[] arrayToConvert ,int arrayToConvertSize ,byte[] finalCompressedArray) throws IOException {
if (arrayToConvert == null || arrayToConvertSize == 0 || finalCompressedArray == null)
{
throw new IOException("Incorrect Arguments") ;
}
String arrConvertedAsString = Arrays.toString(arrayToConvert); //make the 32 bits array to string
String cleanArrConvertedAsString = arrConvertedAsString.replaceAll("[^0-9.]", ""); //replace all the not number to empty string
if(arrayToConvertSize<32) //if the array that we want to convert small then 32, we put 0 to do it size 32
{
int additionSize = 32-arrayToConvertSize;
cleanArrConvertedAsString = String.join("", Collections.nCopies(additionSize,"0")) + cleanArrConvertedAsString;
}
//converts the binary string toint
int stringAsInt = (int)Long.parseLong(cleanArrConvertedAsString,2); //convert cleanArrConvertedAsString to int
//converts the int to 4 bytes
ByteBuffer bytes4 = ByteBuffer.allocate(4);
bytes4.putInt(stringAsInt);
//concatenates the 4 bytes to the compressed byte array
byte[] finalArray = new byte[finalCompressedArray.length + 4];
//System.arraycopy(finalCompressedArray, 0, finalArray, 0, finalCompressedArray.length);
System.arraycopy(finalCompressedArray, 0, finalArray, 0, finalCompressedArray.length);
System.arraycopy(bytes4.array(), 0, finalArray, finalCompressedArray.length, 4);
return finalArray;
}
}
| UTF-8 | Java | 4,143 | java | MyCompressorOutputStream.java | Java | [] | null | [] | package IO;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
public class MyCompressorOutputStream extends OutputStream { //this class exstend the outputstream class (not ours)
private OutputStream out;
public MyCompressorOutputStream(OutputStream outputStream) { //constructor
this.out = outputStream;
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] bytesArray) throws IOException { //this func get byte array and compress it
if(bytesArray == null)
{
throw new IOException("The Bytes Array Is Empty");
}
//super.write(bytesArray); //TODO check if we need the super?
byte[] finalCompressedArray = Arrays.copyOfRange(bytesArray, 0, 24); //copy the 24 first byte to the new compressed array
int sizeOfBytesArray = bytesArray.length - 24; //save the size of the bytesArray without the 24 first bytes
int indexInBytesArray = 24; //save the start index to take 32 bytes for convert
while (sizeOfBytesArray > 0) //while the original bytesArray not empty
{
if (sizeOfBytesArray >= 32)
{
byte[] arrayToConvert = Arrays.copyOfRange(bytesArray, indexInBytesArray, indexInBytesArray + 32); //copy only 32 bytes from original array
finalCompressedArray =convertByteArrayToInt(arrayToConvert ,arrayToConvert.length ,finalCompressedArray); //send to this function for int conversion
sizeOfBytesArray -= 32;
indexInBytesArray += 32;
}
else
{
int newSizeOfBytesArray = sizeOfBytesArray%32; //minimize the original size array
byte[] arrayToConvert = Arrays.copyOfRange(bytesArray, indexInBytesArray,(indexInBytesArray+newSizeOfBytesArray)); //copy the rest of bytes from original array
finalCompressedArray =convertByteArrayToInt(arrayToConvert ,newSizeOfBytesArray ,finalCompressedArray); //send to this function for int conversion
sizeOfBytesArray-=newSizeOfBytesArray;
}
}
if (out instanceof ObjectOutputStream)
((ObjectOutputStream) out).writeObject(finalCompressedArray);
else
out.write(finalCompressedArray);
out.flush();
out.close();
}
private byte[] convertByteArrayToInt(byte[] arrayToConvert ,int arrayToConvertSize ,byte[] finalCompressedArray) throws IOException {
if (arrayToConvert == null || arrayToConvertSize == 0 || finalCompressedArray == null)
{
throw new IOException("Incorrect Arguments") ;
}
String arrConvertedAsString = Arrays.toString(arrayToConvert); //make the 32 bits array to string
String cleanArrConvertedAsString = arrConvertedAsString.replaceAll("[^0-9.]", ""); //replace all the not number to empty string
if(arrayToConvertSize<32) //if the array that we want to convert small then 32, we put 0 to do it size 32
{
int additionSize = 32-arrayToConvertSize;
cleanArrConvertedAsString = String.join("", Collections.nCopies(additionSize,"0")) + cleanArrConvertedAsString;
}
//converts the binary string toint
int stringAsInt = (int)Long.parseLong(cleanArrConvertedAsString,2); //convert cleanArrConvertedAsString to int
//converts the int to 4 bytes
ByteBuffer bytes4 = ByteBuffer.allocate(4);
bytes4.putInt(stringAsInt);
//concatenates the 4 bytes to the compressed byte array
byte[] finalArray = new byte[finalCompressedArray.length + 4];
//System.arraycopy(finalCompressedArray, 0, finalArray, 0, finalCompressedArray.length);
System.arraycopy(finalCompressedArray, 0, finalArray, 0, finalCompressedArray.length);
System.arraycopy(bytes4.array(), 0, finalArray, finalCompressedArray.length, 4);
return finalArray;
}
}
| 4,143 | 0.678494 | 0.665218 | 95 | 42.578949 | 46.464153 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.768421 | false | false | 2 |
c181d3e4f6b09cf15719d5f682e5fc9b86f8115b | 36,258,113,955,295 | b8288839e30a1134ab5f1c87d37d833d17361838 | /src/vue/Index.java | 5f97e9954f6107c4a0dd898124f183e64d9f1326 | [] | no_license | tojonirina/Java-Netywork | https://github.com/tojonirina/Java-Netywork | c7aff15e8f69d2c8bf2aa28c0a96911f29dd98f6 | f7d1012bb81c72e37cbec185b95f2fd85a13d58d | refs/heads/master | 2020-04-26T18:32:25.188000 | 2019-03-04T14:08:29 | 2019-03-04T14:08:29 | 173,747,551 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vue;
import javax.swing.*;
import controleur.IndexController;
import java.awt.Font;
import java.awt.Color;
public class Index extends JFrame{
public JTextField nbr_machine;
public JTextField netmask;
public JTextField adresse_reseau;
public JTextField premier_adresse;
public JTextField broadcast;
public JButton btnValider;
public Index(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Netywork");
setBounds(250,200,502,402);
getContentPane().setLayout(null);
JLabel lblNetywork = new JLabel("Netywork");
lblNetywork.setFont(new Font("Leelawadee", Font.BOLD, 17));
lblNetywork.setBounds(196, 11, 89, 40);
getContentPane().add(lblNetywork);
JLabel lblNombreDeMachine = new JLabel("Nombre de machine:");
lblNombreDeMachine.setBounds(27, 60, 150, 27);
getContentPane().add(lblNombreDeMachine);
nbr_machine = new JTextField();
nbr_machine.setBounds(187, 62, 268, 27);
getContentPane().add(nbr_machine);
nbr_machine.setColumns(10);
JLabel lblNetmask = new JLabel("Netmask:");
lblNetmask.setBounds(80, 103, 54, 27);
getContentPane().add(lblNetmask);
netmask = new JTextField();
netmask.setBounds(187, 105, 268, 27);
getContentPane().add(netmask);
netmask.setColumns(10);
JLabel lblAdresseRseau = new JLabel("Adresse r\u00E9seau:");
lblAdresseRseau.setBounds(45, 141, 132, 27);
getContentPane().add(lblAdresseRseau);
adresse_reseau = new JTextField();
adresse_reseau.setBounds(187, 143, 268, 27);
getContentPane().add(adresse_reseau);
adresse_reseau.setColumns(10);
JLabel lblreAdresseRseau = new JLabel("1\u00E8re adresse r\u00E9seau:");
lblreAdresseRseau.setBounds(21, 179, 156, 27);
getContentPane().add(lblreAdresseRseau);
premier_adresse = new JTextField();
premier_adresse.setBounds(185, 184, 270, 27);
getContentPane().add(premier_adresse);
premier_adresse.setColumns(10);
JLabel lblBroadcast = new JLabel("Broadcast:");
lblBroadcast.setBounds(72, 212, 105, 40);
getContentPane().add(lblBroadcast);
broadcast = new JTextField();
broadcast.setBounds(187, 224, 268, 27);
getContentPane().add(broadcast);
broadcast.setColumns(10);
btnValider = new JButton("Valider");
btnValider.setFont(new Font("Arial", Font.PLAIN, 12));
btnValider.setForeground(new Color(255, 255, 255));
btnValider.setBackground(new Color(34, 139, 34));
btnValider.setBounds(196, 294, 113, 23);
getContentPane().add(btnValider);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\Projet Java Native\\Netywork\\src\\vue\\img\\netywork.png"));
label.setBounds(0, 0, 496, 374);
getContentPane().add(label);
this.init();
}
public void init(){
IndexController ic = new IndexController(this);
btnValider.addActionListener(ic);
}
}
| UTF-8 | Java | 2,835 | java | Index.java | Java | [] | null | [] | package vue;
import javax.swing.*;
import controleur.IndexController;
import java.awt.Font;
import java.awt.Color;
public class Index extends JFrame{
public JTextField nbr_machine;
public JTextField netmask;
public JTextField adresse_reseau;
public JTextField premier_adresse;
public JTextField broadcast;
public JButton btnValider;
public Index(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Netywork");
setBounds(250,200,502,402);
getContentPane().setLayout(null);
JLabel lblNetywork = new JLabel("Netywork");
lblNetywork.setFont(new Font("Leelawadee", Font.BOLD, 17));
lblNetywork.setBounds(196, 11, 89, 40);
getContentPane().add(lblNetywork);
JLabel lblNombreDeMachine = new JLabel("Nombre de machine:");
lblNombreDeMachine.setBounds(27, 60, 150, 27);
getContentPane().add(lblNombreDeMachine);
nbr_machine = new JTextField();
nbr_machine.setBounds(187, 62, 268, 27);
getContentPane().add(nbr_machine);
nbr_machine.setColumns(10);
JLabel lblNetmask = new JLabel("Netmask:");
lblNetmask.setBounds(80, 103, 54, 27);
getContentPane().add(lblNetmask);
netmask = new JTextField();
netmask.setBounds(187, 105, 268, 27);
getContentPane().add(netmask);
netmask.setColumns(10);
JLabel lblAdresseRseau = new JLabel("Adresse r\u00E9seau:");
lblAdresseRseau.setBounds(45, 141, 132, 27);
getContentPane().add(lblAdresseRseau);
adresse_reseau = new JTextField();
adresse_reseau.setBounds(187, 143, 268, 27);
getContentPane().add(adresse_reseau);
adresse_reseau.setColumns(10);
JLabel lblreAdresseRseau = new JLabel("1\u00E8re adresse r\u00E9seau:");
lblreAdresseRseau.setBounds(21, 179, 156, 27);
getContentPane().add(lblreAdresseRseau);
premier_adresse = new JTextField();
premier_adresse.setBounds(185, 184, 270, 27);
getContentPane().add(premier_adresse);
premier_adresse.setColumns(10);
JLabel lblBroadcast = new JLabel("Broadcast:");
lblBroadcast.setBounds(72, 212, 105, 40);
getContentPane().add(lblBroadcast);
broadcast = new JTextField();
broadcast.setBounds(187, 224, 268, 27);
getContentPane().add(broadcast);
broadcast.setColumns(10);
btnValider = new JButton("Valider");
btnValider.setFont(new Font("Arial", Font.PLAIN, 12));
btnValider.setForeground(new Color(255, 255, 255));
btnValider.setBackground(new Color(34, 139, 34));
btnValider.setBounds(196, 294, 113, 23);
getContentPane().add(btnValider);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\Projet Java Native\\Netywork\\src\\vue\\img\\netywork.png"));
label.setBounds(0, 0, 496, 374);
getContentPane().add(label);
this.init();
}
public void init(){
IndexController ic = new IndexController(this);
btnValider.addActionListener(ic);
}
}
| 2,835 | 0.71746 | 0.653263 | 98 | 27.928572 | 19.885513 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.867347 | false | false | 4 |
946e04c8f6bf1ea22e169dedf8fed93b5efd8882 | 36,258,113,954,452 | ff75f1946dd691f4b1a0eae7f565eb95596f485d | /src/main/java/com/example/demo/controller/IndexController.java | fd76054a01fd9e0b3153bd2cb5560f50cc45dca1 | [] | no_license | metertop/springboot-demo | https://github.com/metertop/springboot-demo | 67aaaad9f4a2c6b577a62a5694e3b2950a06c2bd | a83921a70c0a2d27157df59ed24219e32507c87e | refs/heads/master | 2020-03-22T07:06:30.725000 | 2019-05-01T01:40:35 | 2019-05-01T01:40:35 | 139,678,584 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by haoyuexun on 2018/7/5.
*/
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
}
| UTF-8 | Java | 319 | java | IndexController.java | Java | [
{
"context": "bind.annotation.RequestMapping;\n\n/**\n * Created by haoyuexun on 2018/7/5.\n */\n\npublic class IndexController {\n",
"end": 188,
"score": 0.9995400309562683,
"start": 179,
"tag": "USERNAME",
"value": "haoyuexun"
}
] | null | [] | package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by haoyuexun on 2018/7/5.
*/
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
}
| 319 | 0.711599 | 0.69279 | 16 | 18.9375 | 20.326918 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
acc5b05546421d191162b42f8744f80dcaab7797 | 38,809,324,533,279 | ec579efd6f4428fba46ce242ab35574f40204f3b | /src/main/java/com/ai/amc/core/service/impl/Trends_uintSvImpl.java | f865f4595d4dc1602634bddab1143e5972703531 | [] | no_license | yyzz1987431/platform-amc-service | https://github.com/yyzz1987431/platform-amc-service | 8a6613a253e4a3dae99d7be07f795602ac32377a | df96c8906372611b7fba3b0fb5925d433a39e59d | refs/heads/master | 2021-01-16T21:01:38.250000 | 2016-03-08T08:50:22 | 2016-03-08T08:50:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ai.amc.core.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ai.amc.core.dao.mapper.Trends_uintMapper;
import com.ai.amc.core.po.Trends_uint;
import com.ai.amc.core.po.Trends_uintKey;
import com.ai.amc.core.service.ITrends_uintSv;
@Repository
@Transactional
public class Trends_uintSvImpl implements ITrends_uintSv {
@Autowired
private Trends_uintMapper trends_uintMapper;
@Override
public List<Trends_uint> getTrendsByKey(Trends_uintKey key) {
return trends_uintMapper.selectByPrimaryKey(key);
}
}
| UTF-8 | Java | 704 | java | Trends_uintSvImpl.java | Java | [] | null | [] | package com.ai.amc.core.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ai.amc.core.dao.mapper.Trends_uintMapper;
import com.ai.amc.core.po.Trends_uint;
import com.ai.amc.core.po.Trends_uintKey;
import com.ai.amc.core.service.ITrends_uintSv;
@Repository
@Transactional
public class Trends_uintSvImpl implements ITrends_uintSv {
@Autowired
private Trends_uintMapper trends_uintMapper;
@Override
public List<Trends_uint> getTrendsByKey(Trends_uintKey key) {
return trends_uintMapper.selectByPrimaryKey(key);
}
}
| 704 | 0.81108 | 0.81108 | 25 | 27.16 | 23.734667 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 4 |
09fe93c7c866c0918e6f29744001fa9bd1c2257a | 19,756,849,561,775 | ca656f1e99fb5c1e8cc47263ff8a2de66b8c5895 | /src/main/java/model/Bar.java | 8b36cca9460b517fc72fc4639ede820e1460af16 | [] | no_license | kevcen/visuAlgorithm | https://github.com/kevcen/visuAlgorithm | df581543e52cdca535b93ca9d8f8652411dd9d0d | 5fcdab048c1d202c61df8a76e567d600390d7d7f | refs/heads/master | 2022-11-14T19:03:06.364000 | 2020-07-04T15:30:15 | 2020-07-04T15:30:15 | 266,532,534 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Bar extends Rectangle implements Comparable<Bar> {
public static final int PADDING = 50;
private int heightScale = 1;
private int value;
private boolean visited = false;
public Bar(int value) {
super();
setValue(value);
// setWidth(BarsModel.getWidthOfBar());
resetStyle();
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
updateHeight();
}
public void setHeightScale(int heightScale) {
this.heightScale = heightScale;
updateHeight();
}
private void updateHeight() {
setHeight(value * heightScale);
setY(700 - getHeight() - PADDING);
}
public boolean isVisited() {
return visited;
}
public void setVisited() {
visited = true;
setFill(Color.valueOf("#7bd1ce"));
}
public void setEnd() {
setFill(Color.valueOf("#ff9012"));
}
public void resetStyle() {
setFill(Color.WHITE);
}
public void setCurrent() {
setFill(Color.RED);
}
public void setResult() {
setFill(Color.NAVAJOWHITE);
}
@Override
public int compareTo(Bar other) {
return Integer.compare(value, other.getValue());
}
}
| UTF-8 | Java | 1,402 | java | Bar.java | Java | [] | null | [] | package model;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Bar extends Rectangle implements Comparable<Bar> {
public static final int PADDING = 50;
private int heightScale = 1;
private int value;
private boolean visited = false;
public Bar(int value) {
super();
setValue(value);
// setWidth(BarsModel.getWidthOfBar());
resetStyle();
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
updateHeight();
}
public void setHeightScale(int heightScale) {
this.heightScale = heightScale;
updateHeight();
}
private void updateHeight() {
setHeight(value * heightScale);
setY(700 - getHeight() - PADDING);
}
public boolean isVisited() {
return visited;
}
public void setVisited() {
visited = true;
setFill(Color.valueOf("#7bd1ce"));
}
public void setEnd() {
setFill(Color.valueOf("#ff9012"));
}
public void resetStyle() {
setFill(Color.WHITE);
}
public void setCurrent() {
setFill(Color.RED);
}
public void setResult() {
setFill(Color.NAVAJOWHITE);
}
@Override
public int compareTo(Bar other) {
return Integer.compare(value, other.getValue());
}
}
| 1,402 | 0.595578 | 0.587019 | 67 | 19.925373 | 16.709381 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.402985 | false | false | 4 |
bf169d393e62f5d34c089b139e5c41c583b5cdfb | 34,591,666,656,985 | 2ad13cb71ef49715640863045821acfe289e08c8 | /tower-ejb/src/main/java/org/lorislab/tower/service/system/ejb/ScmClientService.java | 8438ceba5d2b22e5e76f9e19f45ac762d1a8f193 | [
"Apache-2.0"
] | permissive | lorislab/tower | https://github.com/lorislab/tower | aa1eb577eeb6c7bf19c5064d473bad9b86f4c0a0 | bf3ed99f7dea8e29a5613e0aac2bac54ea7da097 | refs/heads/master | 2021-06-11T05:13:04.719000 | 2015-02-15T12:44:52 | 2015-02-15T12:44:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2014 lorislab.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lorislab.tower.service.system.ejb;
import java.util.Map;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import org.lorislab.tower.scm.model.ScmCriteria;
import org.lorislab.tower.scm.model.ScmResult;
import org.lorislab.tower.scm.service.ScmService;
/**
*
* @author Andrej_Petras
*/
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class ScmClientService {
/**
* Gets the set of client service types.
*
* @return the set of client service types.
*/
public Map<String, String> getTypes() {
return ScmService.getTypes();
}
/**
* Gets the list of issues.
*
* @param criteria the criteria.
* @return the list of logs.
* @throws Exception if the method fails.
*/
public ScmResult getLog(ScmCriteria criteria) throws Exception {
return ScmService.getLog(criteria);
}
/**
* Tests the connection to the server.
*
* @param criteria the criteria.
* @throws Exception if the method fails.
*/
public void testConnection(ScmCriteria criteria) throws Exception {
ScmService.testConnection(criteria);
}
/**
* Tests the connection to the server.
*
* @param criteria the criteria.
* @throws Exception if the method fails.
*/
public void testRepository(ScmCriteria criteria) throws Exception {
ScmService.testRepository(criteria);
}
}
| UTF-8 | Java | 2,110 | java | ScmClientService.java | Java | [
{
"context": "b.tower.scm.service.ScmService;\n\n/**\n *\n * @author Andrej_Petras\n */\n@Stateless\n@TransactionAttribute(TransactionA",
"end": 956,
"score": 0.9997840523719788,
"start": 943,
"tag": "NAME",
"value": "Andrej_Petras"
}
] | null | [] | /*
* Copyright 2014 lorislab.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lorislab.tower.service.system.ejb;
import java.util.Map;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import org.lorislab.tower.scm.model.ScmCriteria;
import org.lorislab.tower.scm.model.ScmResult;
import org.lorislab.tower.scm.service.ScmService;
/**
*
* @author Andrej_Petras
*/
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class ScmClientService {
/**
* Gets the set of client service types.
*
* @return the set of client service types.
*/
public Map<String, String> getTypes() {
return ScmService.getTypes();
}
/**
* Gets the list of issues.
*
* @param criteria the criteria.
* @return the list of logs.
* @throws Exception if the method fails.
*/
public ScmResult getLog(ScmCriteria criteria) throws Exception {
return ScmService.getLog(criteria);
}
/**
* Tests the connection to the server.
*
* @param criteria the criteria.
* @throws Exception if the method fails.
*/
public void testConnection(ScmCriteria criteria) throws Exception {
ScmService.testConnection(criteria);
}
/**
* Tests the connection to the server.
*
* @param criteria the criteria.
* @throws Exception if the method fails.
*/
public void testRepository(ScmCriteria criteria) throws Exception {
ScmService.testRepository(criteria);
}
}
| 2,110 | 0.693839 | 0.690047 | 73 | 27.90411 | 23.69623 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.246575 | false | false | 4 |
f59dc014e86c59fa47590b0059342e01870c646d | 9,139,690,415,084 | 403bf9529b85990a7d96865c20cfc9c6500c2599 | /src/main/java/web_page_handler/Main.java | f4a8354cd5b55c3d85c602c4452d224d308be83f | [] | no_license | mypro11/Web-Page-Handle | https://github.com/mypro11/Web-Page-Handle | 1a2ef0249a1132a7a3adca7c7da81f09ed6916fd | 6b2a3c46c234e1983733185ab49a0e2debb96592 | refs/heads/master | 2021-01-23T01:02:14.677000 | 2017-03-22T19:50:01 | 2017-03-22T19:50:01 | 85,868,350 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package web_page_handler;
import web_page_handler.html_handler.HtmlHandler;
import web_page_handler.html_handler.HtmlHandlerByUrl;
import web_page_handler.html_parser.HtmlParser;
import java.io.IOException;
/**
* Created by brina on 3/22/17.
*/
public class Main {
public static void main(String[] args) {
HtmlHandler handler = new HtmlHandlerByUrl();
try {
StringBuilder str = handler.handleWebPage("https://eda.ru/recepty/osnovnye-blyuda/kurica-pikasso-25902");
HtmlParser parser = new HtmlParser();
System.out.println(parser.getClearText(str));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 695 | java | Main.java | Java | [
{
"context": "r;\n\nimport java.io.IOException;\n\n/**\n * Created by brina on 3/22/17.\n */\npublic class Main {\n public st",
"end": 233,
"score": 0.996187150478363,
"start": 228,
"tag": "USERNAME",
"value": "brina"
}
] | null | [] | package web_page_handler;
import web_page_handler.html_handler.HtmlHandler;
import web_page_handler.html_handler.HtmlHandlerByUrl;
import web_page_handler.html_parser.HtmlParser;
import java.io.IOException;
/**
* Created by brina on 3/22/17.
*/
public class Main {
public static void main(String[] args) {
HtmlHandler handler = new HtmlHandlerByUrl();
try {
StringBuilder str = handler.handleWebPage("https://eda.ru/recepty/osnovnye-blyuda/kurica-pikasso-25902");
HtmlParser parser = new HtmlParser();
System.out.println(parser.getClearText(str));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 695 | 0.666187 | 0.651799 | 24 | 27.958334 | 27.335079 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 4 |
d04c30c3fa30e9cc4526320e1652009ea581dbbc | 17,712,445,137,222 | f4707270b2f5cb7bc830387365ac7896804be280 | /src-core/com/youcan/core/InitListener.java | 5efb5afa3bb6af7de9b8e2b136231d4d3389b9ac | [
"Apache-2.0"
] | permissive | jiaozhujun/c3f | https://github.com/jiaozhujun/c3f | 744304da338905037d1bfb6bbf05796b0bc4b7d1 | afc9b9c8fe0d936f6982e7b7dbac73bcac90fd51 | refs/heads/master | 2021-01-10T09:08:29.857000 | 2015-10-09T08:29:13 | 2015-10-09T08:29:13 | 43,939,314 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.youcan.core;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class InitListener extends Context implements ServletContextListener {
// 释放连接池的资源
@Override
public void contextDestroyed(ServletContextEvent event) {
super.descroyed();
}
// 初始化连接池
@Override
public void contextInitialized(ServletContextEvent event) {
if (event != null) {
ServletContext cxt = event.getServletContext();
init(cxt.getRealPath("/"), cxt.getRealPath("/WEB-INF/classes/"));
} else {
init("", "conf");
}
}
}
| UTF-8 | Java | 658 | java | InitListener.java | Java | [] | null | [] | package com.youcan.core;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class InitListener extends Context implements ServletContextListener {
// 释放连接池的资源
@Override
public void contextDestroyed(ServletContextEvent event) {
super.descroyed();
}
// 初始化连接池
@Override
public void contextInitialized(ServletContextEvent event) {
if (event != null) {
ServletContext cxt = event.getServletContext();
init(cxt.getRealPath("/"), cxt.getRealPath("/WEB-INF/classes/"));
} else {
init("", "conf");
}
}
}
| 658 | 0.715873 | 0.715873 | 25 | 23.200001 | 23.57626 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 4 |
0b38093a8d161cdbc8d75b120926ed3699b1684b | 24,438,363,919,064 | ed9ce08c3cb45931ad3b9dd7d2458d764f125201 | /qingtao/src/main/java/com/zhoumai/qingtao/utils/UiUtils.java | 9e913d20a947dd433f6d6375153ad677022182c7 | [] | no_license | yangweiqiao/qingtao | https://github.com/yangweiqiao/qingtao | a44f3e9e6de6a65398db3f0d082d35821dd1399a | ce71a11966a5c73f164a3629c997bd6e2a322f2c | refs/heads/master | 2020-06-11T02:27:40.365000 | 2017-12-30T07:33:17 | 2017-12-30T07:33:17 | 76,023,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhoumai.qingtao.utils;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.zhoumai.qingtao.view.base.application.MyApp;
import java.util.Random;
/***
* 封装Ui相关的工具类
* @author dzl
*
*/
public class UiUtils {
/**
* 在屏幕的中央显示一个Toast
* @param text
*/
public static void showToast (CharSequence text) {
Toast toast = Toast.makeText(MyApp.getContext(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);// 设置Toast的显示位置在屏幕的中央
toast.show();
}
/**
* 把一个dp单位的值转换为px(像素)
* @param dp
* @return
*/
public static int dp2px(int dp) {
float density = MyApp.getContext().getResources().getDisplayMetrics().density; // 获取屏幕密度
int px = (int) (dp * density + 0.5); // 加0.5是为了四舍五入
return px;
}
/** 创建一个颜色颜色 */
public static int createRandomColor() {
Random random = new Random();
int red = 50 + random.nextInt(151);// 50 ~ 200
int green = 50 + random.nextInt(151);// 50 ~ 200
int blue = 50 + random.nextInt(151);// 50 ~ 200
int color = Color.rgb(red, green, blue);
return color;
}
/** 创建一个带有随机颜色选择器的TextView */
@SuppressWarnings("deprecation")
public static TextView createRandomColorSelectorTextView(Context context) {
final TextView textView = new TextView(context);
textView.setTextColor(Color.WHITE);
int padding = dp2px(6);
textView.setPadding(padding, padding, padding, padding);
textView.setGravity(Gravity.CENTER);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showToast(textView.getText());
}
});
textView.setBackgroundDrawable(createRandomColorSelector());
return textView;
}
/** 创建一个随机颜色选择器 */
private static Drawable createRandomColorSelector() {
// 创建一个选择器对象
StateListDrawable stateListDrawable = new StateListDrawable();
// 创建一个按下状态和按下状态要显示的Drawable
int[] pressedState = {android.R.attr.state_pressed, android.R.attr.state_enabled};
Drawable pressedDrawable = createRandomColorDrawable();
// 创建一个正常状态和正常状态要显示的Drawable
int[] normalState = {};
Drawable normalDrawable = createRandomColorDrawable();
stateListDrawable.addState(pressedState, pressedDrawable);
stateListDrawable.addState(normalState, normalDrawable);
return stateListDrawable;
}
/** 创建一个随机颜色的圆角矩形 */
private static Drawable createRandomColorDrawable() {
// 创建一个图形对象
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);// 设置图形为矩形
gradientDrawable.setCornerRadius(dp2px(5)); // 设置矩形的圆角角度
gradientDrawable.setColor(createRandomColor()); // 设置矩形的颜色
return gradientDrawable;
}
}
| UTF-8 | Java | 3,300 | java | UiUtils.java | Java | [
{
"context": "t java.util.Random;\n\n/***\n * 封装Ui相关的工具类\n * @author dzl\n *\n */\npublic class UiUtils {\n\n\t/**\n\t * 在屏幕的中央显示一",
"end": 520,
"score": 0.9996638894081116,
"start": 517,
"tag": "USERNAME",
"value": "dzl"
}
] | null | [] | package com.zhoumai.qingtao.utils;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.zhoumai.qingtao.view.base.application.MyApp;
import java.util.Random;
/***
* 封装Ui相关的工具类
* @author dzl
*
*/
public class UiUtils {
/**
* 在屏幕的中央显示一个Toast
* @param text
*/
public static void showToast (CharSequence text) {
Toast toast = Toast.makeText(MyApp.getContext(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);// 设置Toast的显示位置在屏幕的中央
toast.show();
}
/**
* 把一个dp单位的值转换为px(像素)
* @param dp
* @return
*/
public static int dp2px(int dp) {
float density = MyApp.getContext().getResources().getDisplayMetrics().density; // 获取屏幕密度
int px = (int) (dp * density + 0.5); // 加0.5是为了四舍五入
return px;
}
/** 创建一个颜色颜色 */
public static int createRandomColor() {
Random random = new Random();
int red = 50 + random.nextInt(151);// 50 ~ 200
int green = 50 + random.nextInt(151);// 50 ~ 200
int blue = 50 + random.nextInt(151);// 50 ~ 200
int color = Color.rgb(red, green, blue);
return color;
}
/** 创建一个带有随机颜色选择器的TextView */
@SuppressWarnings("deprecation")
public static TextView createRandomColorSelectorTextView(Context context) {
final TextView textView = new TextView(context);
textView.setTextColor(Color.WHITE);
int padding = dp2px(6);
textView.setPadding(padding, padding, padding, padding);
textView.setGravity(Gravity.CENTER);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showToast(textView.getText());
}
});
textView.setBackgroundDrawable(createRandomColorSelector());
return textView;
}
/** 创建一个随机颜色选择器 */
private static Drawable createRandomColorSelector() {
// 创建一个选择器对象
StateListDrawable stateListDrawable = new StateListDrawable();
// 创建一个按下状态和按下状态要显示的Drawable
int[] pressedState = {android.R.attr.state_pressed, android.R.attr.state_enabled};
Drawable pressedDrawable = createRandomColorDrawable();
// 创建一个正常状态和正常状态要显示的Drawable
int[] normalState = {};
Drawable normalDrawable = createRandomColorDrawable();
stateListDrawable.addState(pressedState, pressedDrawable);
stateListDrawable.addState(normalState, normalDrawable);
return stateListDrawable;
}
/** 创建一个随机颜色的圆角矩形 */
private static Drawable createRandomColorDrawable() {
// 创建一个图形对象
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);// 设置图形为矩形
gradientDrawable.setCornerRadius(dp2px(5)); // 设置矩形的圆角角度
gradientDrawable.setColor(createRandomColor()); // 设置矩形的颜色
return gradientDrawable;
}
}
| 3,300 | 0.739973 | 0.726037 | 103 | 27.563107 | 23.394327 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.854369 | false | false | 4 |
06f565f27125d24808060e374f58732282911430 | 27,934,467,297,977 | 2df308c315f3b1d6303868a97910e79523d4af2f | /src/com/gammarush/engine/math/noise/Noise2D.java | 1ecc6626c28736f7498977bb2a98e54d7158cabc | [] | no_license | dcturner5/ECB-Game-Engine | https://github.com/dcturner5/ECB-Game-Engine | b82fdce51474569ed10f40fe71a47d2ee853e5bc | 60dd95ccd25a3d3c12a7e81eea7d24ad364ada82 | refs/heads/master | 2022-11-24T10:45:37.938000 | 2020-07-30T04:29:58 | 2020-07-30T04:29:58 | 111,650,976 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gammarush.engine.math.noise;
import java.util.Random;
//PERLIN NOISE 2D, USED FOR GENERATING CAVES IN WORLD
public class Noise2D {
private int seed;
private int octaves;
private float persistance;
private float frequency;
public Noise2D(int seed, int octaves, float persistance, float frequency) {
this.seed = seed;
this.octaves = octaves;
this.persistance = persistance;
this.frequency = frequency;
}
public float generate(float x, float y) {
float total = 0.0f;
float frequency = this.frequency;
float amplitude = persistance;
for(int i = 0; i < octaves; i++) {
total += interpolateNoise(x * frequency, y * frequency) * amplitude;
frequency *= 2;
amplitude *= persistance;
}
return total;
}
private long hash(int x, int y) {
int a = x >= 0 ? 2 * x : -2 * x - 1;
int b = y >= 0 ? 2 * y : -2 * y - 1;
return a >= b ? a * a + a + b : a + b * b;
}
private float getNoise(int x, int y) {
Random rng = new Random(hash((int) hash(x, y), seed));
int r = rng.nextInt();
return (float)(r & 0x7fff)/(float)0x7fff - .5f;
}
private float interpolateNoise(float x, float y) {
int intX, intY;
float fractX, fractY, v1, v2, v3, v4, i1, i2;
intX = (int) x;
fractX = x - intX;
intY = (int) y;
fractY = y - intY;
v1 = smoothNoise(intX, intY);
v2 = smoothNoise(intX + 1, intY);
v3 = smoothNoise(intX, intY + 1);
v4 = smoothNoise(intX + 1, intY + 1);
i1 = interpolate(v1, v2, fractX);
i2 = interpolate(v3, v4, fractX);
return interpolate(i1, i2, fractY);
}
private float interpolate(float a, float b, float x) {
float ft = x * 3.1415927f;
float f = (float) ((1 - Math.cos(ft)) * .5);
return a * (1 - f) + b * f;
}
private float smoothNoise(int x, int y) {
float corners = (getNoise(x-1, y-1) + getNoise(x+1, y-1) + getNoise(x-1, y+1) + getNoise(x+1, y+1) ) / 16;
float sides = (getNoise(x-1, y) + getNoise(x+1, y) + getNoise(x, y-1) + getNoise(x, y+1) ) / 8;
float center = getNoise(x, y) / 4;
return corners + sides + center;
}
}
| UTF-8 | Java | 2,045 | java | Noise2D.java | Java | [] | null | [] | package com.gammarush.engine.math.noise;
import java.util.Random;
//PERLIN NOISE 2D, USED FOR GENERATING CAVES IN WORLD
public class Noise2D {
private int seed;
private int octaves;
private float persistance;
private float frequency;
public Noise2D(int seed, int octaves, float persistance, float frequency) {
this.seed = seed;
this.octaves = octaves;
this.persistance = persistance;
this.frequency = frequency;
}
public float generate(float x, float y) {
float total = 0.0f;
float frequency = this.frequency;
float amplitude = persistance;
for(int i = 0; i < octaves; i++) {
total += interpolateNoise(x * frequency, y * frequency) * amplitude;
frequency *= 2;
amplitude *= persistance;
}
return total;
}
private long hash(int x, int y) {
int a = x >= 0 ? 2 * x : -2 * x - 1;
int b = y >= 0 ? 2 * y : -2 * y - 1;
return a >= b ? a * a + a + b : a + b * b;
}
private float getNoise(int x, int y) {
Random rng = new Random(hash((int) hash(x, y), seed));
int r = rng.nextInt();
return (float)(r & 0x7fff)/(float)0x7fff - .5f;
}
private float interpolateNoise(float x, float y) {
int intX, intY;
float fractX, fractY, v1, v2, v3, v4, i1, i2;
intX = (int) x;
fractX = x - intX;
intY = (int) y;
fractY = y - intY;
v1 = smoothNoise(intX, intY);
v2 = smoothNoise(intX + 1, intY);
v3 = smoothNoise(intX, intY + 1);
v4 = smoothNoise(intX + 1, intY + 1);
i1 = interpolate(v1, v2, fractX);
i2 = interpolate(v3, v4, fractX);
return interpolate(i1, i2, fractY);
}
private float interpolate(float a, float b, float x) {
float ft = x * 3.1415927f;
float f = (float) ((1 - Math.cos(ft)) * .5);
return a * (1 - f) + b * f;
}
private float smoothNoise(int x, int y) {
float corners = (getNoise(x-1, y-1) + getNoise(x+1, y-1) + getNoise(x-1, y+1) + getNoise(x+1, y+1) ) / 16;
float sides = (getNoise(x-1, y) + getNoise(x+1, y) + getNoise(x, y-1) + getNoise(x, y+1) ) / 8;
float center = getNoise(x, y) / 4;
return corners + sides + center;
}
}
| 2,045 | 0.617604 | 0.583863 | 74 | 26.635136 | 22.450891 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.594594 | false | false | 4 |
16afb92beb6cb1a9eaae77f2f5ad3a91794bd7df | 25,340,307,056,164 | 2a118397cf29293c940f77cd6cf6cb03054832d0 | /app/src/main/java/teknologi/inspira/bentang/sistemcutipegawai/util/Constant.java | 7792c6cffd9807e25c28b8669d49928a8d6f5e6f | [] | no_license | halimbimantara/SistemCutiPegawai | https://github.com/halimbimantara/SistemCutiPegawai | bef811edda479769483d7ec8b3376e8a223eca6c | ec041fb3c26fcf37b2303c4ada7579e8972bc3b3 | refs/heads/master | 2021-01-11T06:19:51.725000 | 2016-10-06T06:09:06 | 2016-10-06T06:09:06 | 69,450,916 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teknologi.inspira.bentang.sistemcutipegawai.util;
/**
* Created by halim on 9/27/2016.
*/
public class Constant {
public static final String BASE_API = "http://layananpeg.bit.co.id/sistemcuti/v1/";
}
| UTF-8 | Java | 215 | java | Constant.java | Java | [
{
"context": "bentang.sistemcutipegawai.util;\n\n/**\n * Created by halim on 9/27/2016.\n */\npublic class Constant {\n pub",
"end": 82,
"score": 0.9949835538864136,
"start": 77,
"tag": "USERNAME",
"value": "halim"
}
] | null | [] | package teknologi.inspira.bentang.sistemcutipegawai.util;
/**
* Created by halim on 9/27/2016.
*/
public class Constant {
public static final String BASE_API = "http://layananpeg.bit.co.id/sistemcuti/v1/";
}
| 215 | 0.725581 | 0.688372 | 8 | 25.875 | 29.788578 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
ba89b0a236549ae9cc0e38384325dfa2ed414f8f | 26,233,660,256,983 | 7e7c887feac90bc09a022022244b72516ada5af6 | /MissingNumber.java | 8d2c80b3eacc45a30e7eff3cd9b03afe61f1b5c2 | [] | no_license | dariaev/leetcode_solutions | https://github.com/dariaev/leetcode_solutions | e58e1ef1b82715d18a6f34e1668b0a3c0a13dcf6 | bf405f75125dc89dc36421db8f342e85d9efbbb3 | refs/heads/master | 2016-09-09T23:12:07.419000 | 2015-09-04T23:31:42 | 2015-09-04T23:31:42 | 41,696,185 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Array doesn't have to be sorted.
For example,
Given nums = [0, 1, 3] return 2.
*/
public class MissingNumber {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int index = 0;
while (index < nums.length) {
if (nums[index] != index) return nums[index]-1;
index++;
}
// if no missing number found return the next consecutive that would be added
return index;
}
} | UTF-8 | Java | 574 | java | MissingNumber.java | Java | [] | null | [] | /*
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Array doesn't have to be sorted.
For example,
Given nums = [0, 1, 3] return 2.
*/
public class MissingNumber {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int index = 0;
while (index < nums.length) {
if (nums[index] != index) return nums[index]-1;
index++;
}
// if no missing number found return the next consecutive that would be added
return index;
}
} | 574 | 0.602787 | 0.587108 | 19 | 29.263159 | 35.870884 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 4 |
fd2b80016ebeb977a0debe83b7d6ed33ea6b104c | 28,518,582,859,611 | 629b35d766f0de44ee724cc4f1cb784289e0d7bf | /modao/.svn/pristine/26/2657a2ab6acb4bb68d7ae976d7c588f18904a357.svn-base | d96f40fc8aba9d089a711d0548181e9c5bf85e11 | [] | no_license | angus720/NuanliuBao | https://github.com/angus720/NuanliuBao | 23cb9acb196d99fb3007e518f135732bed73586a | 8df516eb402e14443b25a6d3e5cce37c5cc067d5 | refs/heads/master | 2020-03-30T00:43:22.294000 | 2018-09-27T06:28:10 | 2018-09-27T06:28:10 | 150,540,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nuanliu.com.modao.bean;
public class CommonResponse {
public String status_name;
public String status_detail;
public int status;
public String getStatus_name() {
return status_name;
}
public void setStatus_name(String status_name) {
this.status_name = status_name;
}
public String getStatus_detail() {
return status_detail;
}
public void setStatus_detail(String status_detail) {
this.status_detail = status_detail;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
| UTF-8 | Java | 647 | 2657a2ab6acb4bb68d7ae976d7c588f18904a357.svn-base | Java | [] | null | [] | package nuanliu.com.modao.bean;
public class CommonResponse {
public String status_name;
public String status_detail;
public int status;
public String getStatus_name() {
return status_name;
}
public void setStatus_name(String status_name) {
this.status_name = status_name;
}
public String getStatus_detail() {
return status_detail;
}
public void setStatus_detail(String status_detail) {
this.status_detail = status_detail;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
| 647 | 0.627512 | 0.627512 | 34 | 18.029411 | 17.539007 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 4 | |
d982a0e6822dbec6e50c482e36933a7970445d10 | 28,518,582,858,972 | 7479c59d117b8c765a2024f2fa6ba1d345ff723b | /src/main/java/com/isi/sn/demo/entities/Abonnement.java | 981eea969bfa20d2a2008b333b1a574ad13847b1 | [] | no_license | mamitasow/BackendForage | https://github.com/mamitasow/BackendForage | 8a94d08cbe4431802a160a3a14c4e41cd4c7a6bd | 6f1ae461d22c2fd0eb28781d1e61ee065af45c8c | refs/heads/master | 2020-06-16T13:07:08.433000 | 2019-07-16T14:16:22 | 2019-07-16T14:16:22 | 195,585,842 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.isi.sn.demo.entities;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Entity
public class Abonnement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.DATE)
private Date dateAbonnement;
private String numero;
private String description;
@ManyToOne
@JoinColumn(name="code_client")
private Client client;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "compteur_id")
private Compteur compteur;
@OneToMany(mappedBy="abonnement",fetch= FetchType.LAZY)
private List<Facture> factures;
@ManyToOne
@JoinColumn(name="user")
private User user;
public Abonnement() {
}
public Abonnement(Date dateAbonnement, String numero, String description, Client client, Compteur compteur, List<Facture> factures, User user) {
this.dateAbonnement = dateAbonnement;
this.numero = numero;
this.description = description;
this.client = client;
this.compteur = compteur;
this.factures = factures;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDateAbonnement() {
return dateAbonnement;
}
public void setDateAbonnement(Date dateAbonnement) {
this.dateAbonnement = dateAbonnement;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Compteur getCompteur() {
return compteur;
}
public void setCompteur(Compteur compteur) {
this.compteur = compteur;
}
public List<Facture> getFactures() {
return factures;
}
public void setFactures(List<Facture> factures) {
this.factures = factures;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| UTF-8 | Java | 2,343 | java | Abonnement.java | Java | [] | null | [] | package com.isi.sn.demo.entities;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Entity
public class Abonnement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.DATE)
private Date dateAbonnement;
private String numero;
private String description;
@ManyToOne
@JoinColumn(name="code_client")
private Client client;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "compteur_id")
private Compteur compteur;
@OneToMany(mappedBy="abonnement",fetch= FetchType.LAZY)
private List<Facture> factures;
@ManyToOne
@JoinColumn(name="user")
private User user;
public Abonnement() {
}
public Abonnement(Date dateAbonnement, String numero, String description, Client client, Compteur compteur, List<Facture> factures, User user) {
this.dateAbonnement = dateAbonnement;
this.numero = numero;
this.description = description;
this.client = client;
this.compteur = compteur;
this.factures = factures;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDateAbonnement() {
return dateAbonnement;
}
public void setDateAbonnement(Date dateAbonnement) {
this.dateAbonnement = dateAbonnement;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Compteur getCompteur() {
return compteur;
}
public void setCompteur(Compteur compteur) {
this.compteur = compteur;
}
public List<Facture> getFactures() {
return factures;
}
public void setFactures(List<Facture> factures) {
this.factures = factures;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| 2,343 | 0.633803 | 0.633803 | 103 | 21.747572 | 20.548176 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407767 | false | false | 4 |
8e8d425c3c0edae602851122edb824f4cdcb7b86 | 16,724,602,662,807 | 83c37f02d96086c767622b941066d8194a22c7cc | /src/main/java/impl/ActiveMQConfig.java | e85ede7caaffca713a040f44035c0701993ef6f6 | [] | no_license | IldarZainulinDev/fuse-bundle | https://github.com/IldarZainulinDev/fuse-bundle | 5bfc0b63fd4641bbb04d33cbc3737485cd11a828 | b3d807e4aae18dd93c246ea545ca8ee964795f11 | refs/heads/master | 2022-11-11T15:10:10.727000 | 2020-07-03T17:59:46 | 2020-07-03T17:59:46 | 276,746,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package impl;
public class ActiveMQConfig {
String brokerURL;
String username;
String password;
String queue;
public void setBrokerURL(String brokerURL) {
this.brokerURL = brokerURL;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setQueue(String queue) {
this.queue = queue;
}
}
| UTF-8 | Java | 473 | java | ActiveMQConfig.java | Java | [
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public void setPassword(String passwo",
"end": 299,
"score": 0.9965718984603882,
"start": 291,
"tag": "USERNAME",
"value": "username"
},
{
"context": "assword(String password) {\n this.pa... | null | [] | package impl;
public class ActiveMQConfig {
String brokerURL;
String username;
String password;
String queue;
public void setBrokerURL(String brokerURL) {
this.brokerURL = brokerURL;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public void setQueue(String queue) {
this.queue = queue;
}
}
| 475 | 0.638478 | 0.638478 | 24 | 18.708334 | 16.468351 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 4 |
9464a3ca43789fbb831b955bcc1ae16daf8aaced | 15,513,421,929,204 | bb232fe8a68e31393f40b152bd4831e5de2036f0 | /app/src/main/java/com/ices507/troy/ivalue_clock/geofence/RoundGeofence.java | 63049f337a42ff15e8895d17f653681feb6492b8 | [] | no_license | MoonlightStill/iValue | https://github.com/MoonlightStill/iValue | 5c9d5dee5652445532b9f7c2c66cdc4999eda373 | f906c1a01b7414e12ab323c1a31771a81849e07e | refs/heads/master | 2021-09-01T09:14:08.698000 | 2017-12-26T06:20:40 | 2017-12-26T06:20:40 | 115,391,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ices507.troy.ivalue_clock.geofence;
import android.util.Log;
/**
* Created by troy on 17-12-10.
*
* @Description:
* @Modified By:
*/
public class RoundGeofence extends BaseGeofence {
private Point center;
private double radius;
@Override
public int setGeofence(Point[] points,double radius) {
try {
center = points[0];
this.radius = radius;
return GEOFENCE_ADD_SUCCESS;
} catch (NullPointerException e){
Log.e("NullPointError","Points is null");
return GEOFENCE_ADD_FAILED;
}
}
@Override
public double juggePointStatus(Point point) {
Log.e("distance",String.valueOf(Point.computeDistance(point, center) - radius));
return Point.computeDistance(point, center) - radius;
}
@Override
public int deleteGeofence() {
return 0;
}
}
| UTF-8 | Java | 901 | java | RoundGeofence.java | Java | [
{
"context": "ence;\n\nimport android.util.Log;\n\n/**\n * Created by troy on 17-12-10.\n *\n * @Description:\n * @Modified By:",
"end": 97,
"score": 0.9992042779922485,
"start": 93,
"tag": "USERNAME",
"value": "troy"
}
] | null | [] | package com.ices507.troy.ivalue_clock.geofence;
import android.util.Log;
/**
* Created by troy on 17-12-10.
*
* @Description:
* @Modified By:
*/
public class RoundGeofence extends BaseGeofence {
private Point center;
private double radius;
@Override
public int setGeofence(Point[] points,double radius) {
try {
center = points[0];
this.radius = radius;
return GEOFENCE_ADD_SUCCESS;
} catch (NullPointerException e){
Log.e("NullPointError","Points is null");
return GEOFENCE_ADD_FAILED;
}
}
@Override
public double juggePointStatus(Point point) {
Log.e("distance",String.valueOf(Point.computeDistance(point, center) - radius));
return Point.computeDistance(point, center) - radius;
}
@Override
public int deleteGeofence() {
return 0;
}
}
| 901 | 0.618202 | 0.605993 | 39 | 22.102564 | 21.502289 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435897 | false | false | 4 |
f556ebb6d4c671a4a411a648e2079f17041ab48a | 28,965,259,479,918 | 1b7879f6d370c57c1f34ab53fa25161b7aa590e1 | /containerWithMostWater/src/Main.java | e69e11442f0b978c9d8e84a3380050d4ce0edaa2 | [] | no_license | jeffreytigerwang/Java-Practice | https://github.com/jeffreytigerwang/Java-Practice | 4c37024c5d89b7c0f6085080525bbd9df31e6983 | eb1dab0095f4bb7e22910e03c713b21dcd2ab5c8 | refs/heads/master | 2023-04-23T18:25:55.556000 | 2021-05-10T22:12:17 | 2021-05-10T22:12:17 | 363,272,680 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Main {
public static void main(String[] args){
int[] height = new int[]{1,8,6,2,5,4,8,3,7};
int answer = new Solution().maxArea(height);
System.out.print(answer);
}
}
| UTF-8 | Java | 214 | java | Main.java | Java | [] | null | [] | public class Main {
public static void main(String[] args){
int[] height = new int[]{1,8,6,2,5,4,8,3,7};
int answer = new Solution().maxArea(height);
System.out.print(answer);
}
}
| 214 | 0.570093 | 0.528037 | 9 | 22.777779 | 21.248674 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 4 |
7e07a5b3b670548b8fdd87f54ef0af6eb6b9d79d | 31,945,966,782,841 | f7443b222efd6252156b8b5b593546e4f5e8bfd3 | /src/main/java/cn/hn/java/summer/db/multiple/MultipleDataSource.java | d14681cee6a9cb1218d33364a8f525657c423197 | [] | no_license | google2013/summer | https://github.com/google2013/summer | 914536c47a69e316a286350b5c8ca46226c089b4 | 5feefe8d53289f52928c605d2a880625a5008b3a | refs/heads/master | 2021-01-20T02:33:40.376000 | 2017-04-22T07:22:14 | 2017-04-22T07:22:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.hn.java.summer.db.multiple;
import cn.hn.java.summer.db.DbOperator;
import java.util.ArrayList;
import java.util.List;
/**
* 多个数据源类
* @author sjg
* @version 1.0.1 2013-10-26
*
*/
public class MultipleDataSource {
/**
* 存放多个JdbcTemplate
*/
private List<DbOperator> dbOperators=new ArrayList<>();
public List<DbOperator> getDbOperators() {
return dbOperators;
}
/**
* 添加数据库操作实例
* @param dbOperator 数据库操作类实例
*/
public void addDbOperator(DbOperator dbOperator){
dbOperators.add(dbOperator);
}
/**
* 添加数据库操作实例集合
* @param dbOperators 数据库操作实例集合
*/
public void addAllDbOperator(List<DbOperator> dbOperators){
dbOperators.addAll(dbOperators);
}
/**
* 取对应序号数据源的dbOperators
* @param mc
* @return
*/
public DbOperator get(Object mc){
if(mc instanceof DataSource2){
return dbOperators.get(1);
}else if(mc instanceof DataSource3){
return dbOperators.get(2);
}
return dbOperators.get(0);
}
}
| UTF-8 | Java | 1,072 | java | MultipleDataSource.java | Java | [
{
"context": ";\nimport java.util.List;\n\n/**\n * 多个数据源类\n * @author sjg\n * @version 1.0.1 2013-10-26\n *\n */\npublic class ",
"end": 161,
"score": 0.9996212720870972,
"start": 158,
"tag": "USERNAME",
"value": "sjg"
}
] | null | [] | package cn.hn.java.summer.db.multiple;
import cn.hn.java.summer.db.DbOperator;
import java.util.ArrayList;
import java.util.List;
/**
* 多个数据源类
* @author sjg
* @version 1.0.1 2013-10-26
*
*/
public class MultipleDataSource {
/**
* 存放多个JdbcTemplate
*/
private List<DbOperator> dbOperators=new ArrayList<>();
public List<DbOperator> getDbOperators() {
return dbOperators;
}
/**
* 添加数据库操作实例
* @param dbOperator 数据库操作类实例
*/
public void addDbOperator(DbOperator dbOperator){
dbOperators.add(dbOperator);
}
/**
* 添加数据库操作实例集合
* @param dbOperators 数据库操作实例集合
*/
public void addAllDbOperator(List<DbOperator> dbOperators){
dbOperators.addAll(dbOperators);
}
/**
* 取对应序号数据源的dbOperators
* @param mc
* @return
*/
public DbOperator get(Object mc){
if(mc instanceof DataSource2){
return dbOperators.get(1);
}else if(mc instanceof DataSource3){
return dbOperators.get(2);
}
return dbOperators.get(0);
}
}
| 1,072 | 0.695833 | 0.679167 | 55 | 16.454546 | 16.442537 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.036364 | false | false | 4 |
c22e9e7eb8e00af57803a9eaf68fe0e4ec77e055 | 31,585,189,535,376 | 2d8b3f6d53b89b9556105b214d06c08952155d05 | /app/src/main/java/araikovichinc/barbershop/datasource/GenderCardsDataSource.java | 743e7312f72fef47019812852160351c0c15deef | [] | no_license | araikovich/BarberShop | https://github.com/araikovich/BarberShop | 4d25362ed015770e423cc42417ababd0a6e5edaf | 8738c149f9230c8d56477a1ce1fd6110806533d4 | refs/heads/master | 2021-04-29T17:54:35.978000 | 2018-03-29T09:15:51 | 2018-03-29T09:15:51 | 121,681,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package araikovichinc.barbershop.datasource;
import java.util.ArrayList;
import araikovichinc.barbershop.callbacks.LoadCallBack;
import araikovichinc.barbershop.pojo.GenderCard;
/**
* Created by Tigran on 23.02.2018.
*/
public interface GenderCardsDataSource {
void getCards(LoadCallBack callBack);
void saveCardsToDb(ArrayList<GenderCard> cards);
}
| UTF-8 | Java | 364 | java | GenderCardsDataSource.java | Java | [
{
"context": "inc.barbershop.pojo.GenderCard;\n\n/**\n * Created by Tigran on 23.02.2018.\n */\n\npublic interface GenderCardsD",
"end": 205,
"score": 0.9993341565132141,
"start": 199,
"tag": "NAME",
"value": "Tigran"
}
] | null | [] | package araikovichinc.barbershop.datasource;
import java.util.ArrayList;
import araikovichinc.barbershop.callbacks.LoadCallBack;
import araikovichinc.barbershop.pojo.GenderCard;
/**
* Created by Tigran on 23.02.2018.
*/
public interface GenderCardsDataSource {
void getCards(LoadCallBack callBack);
void saveCardsToDb(ArrayList<GenderCard> cards);
}
| 364 | 0.796703 | 0.774725 | 15 | 23.266666 | 21.760719 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
da44a5856569e464ba858fa856e71c4e3baec08a | 16,226,386,460,802 | bc1ee9ab0de251d7a0d98417b4e35630871c9f1d | /src/main/java/com/code/rpc_simple/provider/service/Calculator.java | 9aca017498b59daa609703647500ed03794d697a | [] | no_license | Djx980831/rpc_simple | https://github.com/Djx980831/rpc_simple | 5840a1441b17c182b68b8f514dfaeb7904d4c96c | 8b575fb3f4b1b88ff60cb4157dda0923bc085510 | refs/heads/master | 2021-07-09T15:59:40.927000 | 2019-07-11T09:45:07 | 2019-07-11T09:45:07 | 196,366,217 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.code.rpc_simple.provider.service;
/*
* @Author dongjingxiong
* @Date 17:38 2019/7/11
**/
public interface Calculator {
int add(int a, int b);
}
| UTF-8 | Java | 164 | java | Calculator.java | Java | [
{
"context": "m.code.rpc_simple.provider.service;\n\n/*\n * @Author dongjingxiong\n * @Date 17:38 2019/7/11\n **/\npublic interface Ca",
"end": 74,
"score": 0.9983771443367004,
"start": 61,
"tag": "USERNAME",
"value": "dongjingxiong"
}
] | null | [] | package com.code.rpc_simple.provider.service;
/*
* @Author dongjingxiong
* @Date 17:38 2019/7/11
**/
public interface Calculator {
int add(int a, int b);
}
| 164 | 0.676829 | 0.609756 | 9 | 17.222221 | 15.075939 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
5786a4450bdc305d0f23a5dd27b7c5a8d1519982 | 31,920,196,960,913 | 655bd4398dafd11c46047e9af49b053d3aabd4af | /src/com/nfa/drs/DataReductionPanel.java | acddacf6a8ff5315397a2dbf3129d0908b9eadd9 | [] | no_license | ntemplon/DataReducer | https://github.com/ntemplon/DataReducer | d3cc36e24f4645d989dbc85bd9d8a662b1d16a35 | 2fe2c0cabb770e77fd5b52b11b85cbed9f6973d2 | refs/heads/master | 2021-01-01T16:13:59.694000 | 2015-04-06T19:15:09 | 2015-04-06T19:15:09 | 31,343,702 | 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 com.nfa.drs;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jupiter.ganymede.property.Property;
import com.jupiter.ganymede.property.Property.PropertyChangedArgs;
import com.nfa.drs.constants.ModelConstants;
import com.nfa.drs.data.DataContainerViewer;
import com.nfa.drs.data.DataFormat;
import com.nfa.drs.data.DataSet.DataValues;
import com.nfa.drs.data.Datapoint;
import com.nfa.drs.data.Run;
import com.nfa.drs.data.StudentWindTunnelFormatCsv;
import com.nfa.drs.data.StudentWindTunnelFormatXls;
import com.nfa.drs.data.Test;
import com.nfa.drs.reduction.ReductionProcessor;
import com.nfa.drs.reduction.ReductionProcessor.ReductionResults;
import com.nfa.drs.reduction.thermal.ThermalBiasSettings;
import com.nfa.drs.reduction.thermal.ThermalBiasSettings.ThermalBiasLinearity;
import com.nfa.drs.reduction.thermal.ThermalBiasTimeTable;
import com.nfa.drs.reduction.tare.TareSettings;
import com.nfa.drs.reduction.tare.TareSettings.TareSettingsEntry;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.filechooser.FileFilter;
/**
*
* @author Nathan Templon
*/
public class DataReductionPanel extends javax.swing.JPanel {
// Constants
public static final String NO_TARE_KEY = "NONE";
// Static Fields
private static final Map<String, DataFormat> formats = new HashMap<>();
static {
DataFormat wsu3by4 = new StudentWindTunnelFormatCsv();
formats.put(wsu3by4.getName(), wsu3by4);
DataFormat wsu3by4xls = new StudentWindTunnelFormatXls();
formats.put(wsu3by4xls.getName(), wsu3by4xls);
}
private static final FileFilter JSON_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.toString().endsWith(".json");
}
@Override
public String getDescription() {
return "Json Files (*.json)";
}
};
private static final FileFilter DAT_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.toString().endsWith(".dat");
}
@Override
public String getDescription() {
return "DAT Files (*.dat)";
}
};
// Fields
private final Property<Test> test = new Property<>();
private final Map<String, ThermalBiasSettings> thermalBiasSettings = new HashMap<>();
private final DataContainerViewer thermalDataView = new DataContainerViewer();
private final ThermalBiasTimeTable thermalTimeTable = new ThermalBiasTimeTable();
private Defaults defaults = new Defaults();
private TareSettings tareSettings = new TareSettings();
private ReductionResults lastResults;
// Properties
public final Defaults getDefaults() {
return this.defaults;
}
public final void setDefaults(Defaults defaults) {
this.defaults = defaults;
if (this.defaults != null) {
String importFormat = this.defaults.getImportFormat();
if (importFormat != null) {
ComboBoxModel model = this.formatCombo.getModel();
if (model instanceof DefaultComboBoxModel) {
int index = ((DefaultComboBoxModel)model).getIndexOf(importFormat);
if (index >= 0) {
this.formatCombo.setSelectedIndex(index);
}
}
}
}
}
private ThermalBiasSettings getCurrentThermalBiasSettings() {
if (this.thermalBiasRunCombo.getSelectedItem() != null) {
String currentRun = this.thermalBiasRunCombo.getSelectedItem().toString();
return this.thermalBiasSettings.get(currentRun);
}
return null;
}
/**
* Creates new form DataReductionPanel
*/
public DataReductionPanel() {
this.thermalDataView.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
this.initComponents();
this.thermalViewPane.setLayout(new BorderLayout());
this.thermalViewPane.add(this.thermalDataView.getTableHeader(), BorderLayout.PAGE_START);
this.thermalViewPane.add(this.thermalDataView, BorderLayout.CENTER);
this.thermalTimingPanel.setLayout(new BorderLayout());
this.thermalTimingPanel.add(this.thermalTimeTable.getTableHeader(), BorderLayout.PAGE_START);
this.thermalTimingPanel.add(this.thermalTimeTable, BorderLayout.CENTER);
// Add Items to ComboBoxes
this.formatCombo.removeAllItems();
formats.keySet().stream()
.forEach((String name) -> this.formatCombo.addItem(name));
this.thermalBiasRunCombo.removeAllItems();
this.biasLinearityCombo.removeAllItems();
for (ThermalBiasLinearity lin : ThermalBiasLinearity.values()) {
this.biasLinearityCombo.addItem(lin);
}
this.tareRunComboBox.removeAllItems();
this.staticTareList.setListData(new Object[0]);
this.dynamicTareList.setListData(new Object[0]);
// Add Listeners
this.importButton.addActionListener(this::importButtonActionPerformed);
this.thermalBiasRunCombo.addItemListener(this::thermalBiasItemEvent);
this.computeThermalBiasCheckBox.addItemListener(this::computeThermalBiasItemEvent);
this.biasLinearityCombo.addItemListener(this::biasLinearityItemEvent);
this.importThermalButton.addActionListener(this::importBiasButtonAction);
this.exportThermalButton.addActionListener(this::exportBiasButtonAction);
this.tareRunComboBox.addItemListener(this::tareRunComboBoxChange);
this.staticTareList.addListSelectionListener(this::staticTareListEvent);
this.dynamicTareList.addListSelectionListener(this::dynamicTareListEvent);
this.tareImportButton.addActionListener(this::importTareSettingsAction);
this.tareExportButton.addActionListener(this::exportTareSettingsAction);
this.refreshReductionButton.addActionListener(this::refreshReductionButtonAction);
this.viewDetailReductionButton.addActionListener(this::showResultsDetailButtonAction);
this.exportReducedButton.addActionListener(this::exportResultsButtonAction);
this.formatCombo.addItemListener(this::importFormatItemEvent);
this.thermalDataView.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
DataReductionPanel.this.resizeThermalBiasView();
}
});
this.thermalDataView.getModel().addTableModelListener((TableModelEvent e) -> this.resizeThermalBiasView());
this.thermalTimeTable.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
DataReductionPanel.this.resizeThermalTimingPanel();
}
});
this.thermalTimeTable.getModel().addTableModelListener((TableModelEvent e) -> {
this.resizeThermalTimingPanel();
this.getCurrentThermalBiasSettings().setTimes(this.thermalTimeTable.getTimes());
});
this.test.addPropertyChangedListener(this::resetThermalBias);
this.test.addPropertyChangedListener((PropertyChangedArgs<Test> e) -> this.thermalBiasItemEvent(null));
}
// Private Methods
private void importButtonActionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path dir = chooser.getSelectedFile().toPath();
if (!Files.isDirectory(dir)) {
dir = dir.getParent();
}
if (Files.isDirectory(dir)) {
this.importDataFrom(dir);
}
}
}
private void importDataFrom(Path dir) {
this.getDefaults().setImportDirectory(dir.toString());
DataFormat format = formats.get(this.formatCombo.getSelectedItem().toString());
this.test.set(format.fromDirectory(dir));
// Attempt to Import Model Constants
this.modelConstantsPanel.setDefaultDirectory(dir);
Path mcFile = dir.resolve(ModelConstants.DEFAULT_FILE_NAME);
if (Files.exists(mcFile)) {
this.modelConstantsPanel.importModelConstantsFile(mcFile);
}
// Attempt to Import Thermal Bias
Path tbFile = dir.resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(tbFile)) {
this.importThermalBias(tbFile);
}
// Attempt to Import Tare Settings
Path tareFile = dir.resolve(TareSettings.DEFAULT_TARE_SETTINGS_FILE);
if (Files.exists(tareFile)) {
this.importTareSettings(tareFile);
}
else {
this.tareSettings.setAllSettings(new HashMap<>());
this.test.get().getRuns().stream()
.forEach((Run run) -> this.tareSettings.setSettings(run.getName(), new TareSettingsEntry()));
if (this.tareRunComboBox.getItemCount() > 0) {
this.tareRunComboBox.setSelectedIndex(0);
}
}
// Fill in blanks with thermal bias and tare settings
this.test.get().getRuns().stream()
.filter((Run run) ->
!this.thermalBiasSettings.containsKey(run.getName())
)
.forEach((Run run) ->
this.thermalBiasSettings.put(run.getName(), new ThermalBiasSettings(run.getPointCount()))
);
this.test.get().getRuns().stream()
.filter((Run run) ->
!this.tareSettings.getAllSettings().containsKey(run.getName())
)
.forEach((Run run) ->
this.tareSettings.setSettings(run.getName(), new TareSettingsEntry())
);
// Calculate Initial Coefficients
this.test.get().getRuns().stream()
.forEach((Run run) ->
run.getDatapoints().stream()
.forEach((Datapoint point) ->
point.getData().coefficientsFromLoads(this.modelConstantsPanel.getModelConstants())
)
);
// Adding the Runs to Various Things
this.tareRunComboBox.removeAllItems();
this.dataViewer.clear();
this.test.get().getRuns().stream()
.forEach((Run run) -> {
run.getDatapoints().stream()
.forEach((Datapoint point) -> {
this.dataViewer.addData(run.getName(), point);
});
this.tareRunComboBox.addItem(run.getName());
});
this.resizeThermalBiasView();
this.refreshTareSettings();
}
private void resetThermalBias(PropertyChangedArgs<Test> e) {
this.thermalBiasSettings.clear();
this.thermalBiasRunCombo.removeAllItems();
this.test.get().getRuns().stream()
.forEach((Run run) -> {
this.thermalBiasRunCombo.addItem(run.getName());
this.thermalBiasSettings.put(run.getName(), new ThermalBiasSettings(run.getPointCount()));
});
}
private void thermalBiasItemEvent(ItemEvent e) {
if (e == null || e.getStateChange() == ItemEvent.SELECTED) {
if (this.test.get() != null) {
// Load Data
Object selected = this.thermalBiasRunCombo.getSelectedItem();
if (selected != null) {
final String runName = selected.toString();
Run run = this.test.get().getRun(runName);
if (run != null) {
this.thermalDataView.clear();
run.getDatapoints().stream()
.forEach((Datapoint point) ->
this.thermalDataView.addData(runName, point)
);
}
}
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
// Set Values
if (tbs != null) {
this.biasLinearityCombo.setSelectedItem(tbs.getLinearity());
this.thermalTimeTable.setTimes(tbs.getTimes());
}
// Update Check Box
if (tbs != null) {
this.computeThermalBiasCheckBox.setSelected(tbs.getComputeThermalBias());
}
// Fire Faux Related Events
this.biasLinearityItemEvent(null);
this.revalidate();
}
}
}
private void computeThermalBiasItemEvent(ItemEvent e) {
if (this.computeThermalBiasCheckBox.isSelected()) {
this.biasLinearityCombo.setEnabled(true);
this.thermalTimeTable.setEnabled(this.biasLinearityCombo.getSelectedItem().equals(ThermalBiasLinearity.TIME));
}
else {
this.biasLinearityCombo.setEnabled(false);
this.thermalTimeTable.clearSelection();
this.thermalTimeTable.setEnabled(false);
}
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
if (tbs != null) {
tbs.setComputeThermalBias(this.computeThermalBiasCheckBox.isSelected());
}
}
private void resizeThermalBiasView() {
this.thermalViewPane.setPreferredSize(new Dimension(
this.thermalDataView.getPreferredSize().width,
this.thermalDataView.getPreferredSize().height + DataReductionPanel.this.thermalDataView.getTableHeader().getHeight()
+ this.thermalViewPane.getInsets().top
));
}
private void resizeThermalTimingPanel() {
this.thermalTimingPanel.setPreferredSize(new Dimension(
this.thermalTimeTable.getPreferredSize().width,
this.thermalTimeTable.getPreferredSize().height + DataReductionPanel.this.thermalTimeTable.getTableHeader().getHeight()
+ this.thermalTimingPanel.getInsets().top
));
}
private void biasLinearityItemEvent(ItemEvent e) {
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
if (tbs != null) {
Object o = this.biasLinearityCombo.getSelectedItem();
if (o instanceof ThermalBiasLinearity) {
ThermalBiasLinearity lin = (ThermalBiasLinearity) o;
tbs.setLinearity(lin);
}
}
boolean inTime = this.biasLinearityCombo.getSelectedItem().equals(ThermalBiasLinearity.TIME);
if (!inTime) {
this.thermalTimeTable.clearSelection();
}
this.thermalTimeTable.setEnabled(inTime);
}
private void importBiasButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null && Files.exists(Paths.get(this.getDefaults().getImportDirectory()))) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
Path defaultMcFile = chooser.getCurrentDirectory().toPath().resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(defaultMcFile)) {
chooser.setSelectedFile(defaultMcFile.toFile());
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path mcFile = chooser.getSelectedFile().toPath();
if (Files.exists(mcFile)) {
this.importThermalBias(mcFile);
}
}
}
private void exportBiasButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), ThermalBiasSettings.DEFAULT_FILE_NAME));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(JSON_FILTER) && !file.toString().endsWith(".json")) {
file = Paths.get(file.toString() + ".json");
}
this.exportThermalBias(file);
}
}
private void importThermalBias(Path mcFile) {
try {
String json = Files.readAllLines(mcFile).stream()
.reduce("", (String first, String second) -> first + System.lineSeparator() + second);
JsonObject map = new JsonParser().parse(json).getAsJsonObject();
this.thermalBiasSettings.clear();
map.entrySet().stream()
.forEach((Entry<String, JsonElement> entry) -> {
String name = entry.getKey();
JsonElement element = entry.getValue();
try {
ThermalBiasSettings tbs = DataReducer.GSON.fromJson(element, ThermalBiasSettings.class);
this.thermalBiasSettings.put(name, tbs);
}
catch (Exception ex) {
}
});
this.thermalBiasItemEvent(null);
this.resizeThermalBiasView();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(this, "There was an error while importing the thermal bias.", "Import Error", JOptionPane.ERROR_MESSAGE);
}
this.resizeThermalBiasView();
}
private void exportThermalBias(Path mcFile) {
String json = DataReducer.GSON.toJson(this.thermalBiasSettings);
try {
Files.write(mcFile, Arrays.asList(new String[]{json}));
}
catch (IOException ex) {
}
}
private void tareRunComboBoxChange(ItemEvent e) {
this.refreshTareSettings();
}
private void refreshTareSettings() {
if (this.test.get() != null && this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
List<String> tareRuns = new ArrayList<>();
tareRuns.add(NO_TARE_KEY);
tareRuns.addAll(this.test.get().getRuns().stream()
.filter((Run run) -> !run.getName().equals(runName))
.map((Run run) -> run.getName())
.collect(Collectors.toList()));
Object[] listDataArray = tareRuns.toArray();
this.staticTareList.setListData(listDataArray);
this.dynamicTareList.setListData(listDataArray);
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
String staticTare = tse.getStaticTare();
if (!staticTare.isEmpty()) {
this.staticTareList.setSelectedValue(staticTare, true);
}
else {
this.staticTareList.setSelectedValue(NO_TARE_KEY, true);
}
String dynamicTare = tse.getDynamicTare();
if (!dynamicTare.isEmpty()) {
this.dynamicTareList.setSelectedValue(dynamicTare, true);
}
else {
this.dynamicTareList.setSelectedValue(NO_TARE_KEY, true);
}
}
}
}
private void staticTareListEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
Object item = this.staticTareList.getSelectedValue();
if (item != null) {
if (item.equals(NO_TARE_KEY)) {
tse.setStaticTare("");
}
else {
tse.setStaticTare(item.toString());
}
}
}
}
}
private void dynamicTareListEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
Object item = this.dynamicTareList.getSelectedValue();
if (item != null) {
if (item.equals(NO_TARE_KEY)) {
tse.setDynamicTare("");
}
else {
tse.setDynamicTare(item.toString());
}
}
}
}
}
private void importTareSettingsAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null && Files.exists(Paths.get(this.getDefaults().getImportDirectory()))) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
Path defaultMcFile = chooser.getCurrentDirectory().toPath().resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(defaultMcFile)) {
chooser.setSelectedFile(defaultMcFile.toFile());
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (Files.exists(file)) {
this.importTareSettings(file);
}
}
}
private void exportTareSettingsAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), TareSettings.DEFAULT_TARE_SETTINGS_FILE));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(JSON_FILTER) && !file.toString().endsWith(".json")) {
file = Paths.get(file.toString() + ".json");
}
this.exportTareSettings(file);
}
}
private void importTareSettings(Path file) {
try {
String json = Files.readAllLines(file).stream()
.reduce("", (String first, String second) -> first + System.lineSeparator() + second);
this.tareSettings = DataReducer.GSON.fromJson(json, TareSettings.class);
this.refreshTareSettings();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(this, "There was an error while importing the tare settings.", "Import Error", JOptionPane.ERROR_MESSAGE);
}
this.refreshTareSettings();
}
private void exportTareSettings(Path file) {
String json = DataReducer.GSON.toJson(this.tareSettings);
try {
Files.write(file, Arrays.asList(new String[]{json}));
}
catch (IOException ex) {
}
}
private void refreshReductionButtonAction(ActionEvent e) {
this.calculateReducedData();
}
private void calculateReducedData() {
ReductionProcessor proc = new ReductionProcessor(this.test.get(), this.modelConstantsPanel.getModelConstants(), this.tareSettings,
this.thermalBiasSettings);
this.lastResults = proc.reduce();
this.reducedDataViewer.clear();
this.lastResults.getReducedData().getRuns().stream()
.forEach((Run run) ->
run.getDatapoints().stream()
.forEach((Datapoint point) ->
this.reducedDataViewer.addData(run.getName(), point)
)
);
}
private void showResultsDetailButtonAction(ActionEvent e) {
if (this.lastResults == null) {
return;
}
ReductionDetailFrame frame = new ReductionDetailFrame();
frame.setDetailedResults(this.lastResults.getReductionSteps());
frame.setVisible(true);
}
private void exportResultsButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(DAT_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "output.dat"));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(DAT_FILTER) && !file.toString().endsWith(".dat")) {
file = Paths.get(file.toString() + ".dat");
}
this.exportResults(file);
}
}
private void exportResults(Path file) {
final List<String> lines = new ArrayList<>();
final List<DataValues> values = Collections.unmodifiableList(Arrays.asList(DataValues.values()));
StringBuilder decBuilder = new StringBuilder();
decBuilder.append("Run,Test Point,");
values.stream()
.forEach((DataValues value) -> {
decBuilder.append(value.getDisplayName()).append(",");
});
String decLine = decBuilder.toString();
if (this.lastResults != null) {
this.lastResults.getReducedData().getRuns().stream()
.forEach((Run run) -> {
lines.add(run.getName());
lines.add(decLine);
run.getDatapoints().stream()
.forEach((Datapoint point) -> {
StringBuilder dataLine = new StringBuilder();
dataLine.append(run.getName()).append(",");
dataLine.append(point.getPointNumber()).append(",");
values.stream()
.forEach((DataValues value) -> {
dataLine.append(point.getData().get(value)).append(",");
});
lines.add(dataLine.toString());
});
lines.add("");
});
}
try {
Files.write(file, lines);
}
catch (IOException ex) {
}
}
private void importFormatItemEvent(ItemEvent e) {
if (this.defaults != null) {
this.defaults.setImportFormat(e.getItem().toString());
}
}
// Designer
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
tabbedPane = new javax.swing.JTabbedPane();
dataPanel = new javax.swing.JPanel();
inputFormatLabel = new javax.swing.JLabel();
formatCombo = new javax.swing.JComboBox();
dataScrollPane = new javax.swing.JScrollPane();
dataViewer = new com.nfa.drs.data.DataContainerViewer();
importButton = new javax.swing.JButton();
mcConfigPanel = new javax.swing.JPanel();
botGlue = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
modelConstantsLabel = new javax.swing.JLabel();
modelConstantsPanel = new com.nfa.drs.constants.ModelConstantsPanel();
tarePanel = new javax.swing.JPanel();
tareRunLabel = new javax.swing.JLabel();
tareVerticalFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
tareRunComboBox = new javax.swing.JComboBox();
staticTareLabel = new javax.swing.JLabel();
staticTareScrollPane = new javax.swing.JScrollPane();
staticTareList = new javax.swing.JList();
dynamicTareLabel = new javax.swing.JLabel();
dynamicTareScrollPane = new javax.swing.JScrollPane();
dynamicTareList = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
tareExportButton = new javax.swing.JButton();
tareImportButton = new javax.swing.JButton();
filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
tareHorizontalFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
thermalPanel = new javax.swing.JPanel();
thermalRunLabel = new javax.swing.JLabel();
thermalBiasRunCombo = new javax.swing.JComboBox();
thermalBiasGlue = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
computeThermalBiasCheckBox = new javax.swing.JCheckBox();
thermalViewPane = new javax.swing.JPanel();
startEndStrut = new javax.swing.Box.Filler(new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 32767));
biasLinearityLabel = new javax.swing.JLabel();
biasLinearityCombo = new javax.swing.JComboBox();
thermalTimingPanel = new javax.swing.JPanel();
buttonPanel = new javax.swing.JPanel();
importThermalButton = new javax.swing.JButton();
exportThermalButton = new javax.swing.JButton();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
dataTab = new javax.swing.JPanel();
reducedDataLabel = new javax.swing.JLabel();
reducedDataViewerScrollPane = new javax.swing.JScrollPane();
reducedDataViewer = new com.nfa.drs.data.DataContainerViewer();
viewDetailReductionButton = new javax.swing.JButton();
exportReducedButton = new javax.swing.JButton();
refreshReductionButton = new javax.swing.JButton();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new java.awt.Dimension(950, 600));
setLayout(new java.awt.BorderLayout());
dataPanel.setLayout(new java.awt.GridBagLayout());
inputFormatLabel.setText("Data Format");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
dataPanel.add(inputFormatLabel, gridBagConstraints);
formatCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
formatCombo.setPreferredSize(new java.awt.Dimension(275, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
dataPanel.add(formatCombo, gridBagConstraints);
dataViewer.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
dataScrollPane.setViewportView(dataViewer);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
dataPanel.add(dataScrollPane, gridBagConstraints);
importButton.setText("Import Data");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
dataPanel.add(importButton, gridBagConstraints);
tabbedPane.addTab("Raw Data", dataPanel);
mcConfigPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
mcConfigPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 50;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
mcConfigPanel.add(botGlue, gridBagConstraints);
modelConstantsLabel.setText("Model Constants");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
mcConfigPanel.add(modelConstantsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
mcConfigPanel.add(modelConstantsPanel, gridBagConstraints);
tabbedPane.addTab("Model Constants", mcConfigPanel);
tarePanel.setLayout(new java.awt.GridBagLayout());
tareRunLabel.setText("Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(tareRunLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 100;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
tarePanel.add(tareVerticalFiller, gridBagConstraints);
tareRunComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
tareRunComboBox.setPreferredSize(new java.awt.Dimension(200, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(tareRunComboBox, gridBagConstraints);
staticTareLabel.setText("Static Tare");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(20, 5, 0, 5);
tarePanel.add(staticTareLabel, gridBagConstraints);
staticTareScrollPane.setPreferredSize(new java.awt.Dimension(200, 300));
staticTareList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
staticTareScrollPane.setViewportView(staticTareList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(staticTareScrollPane, gridBagConstraints);
dynamicTareLabel.setText("Dynamic Tare");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(20, 5, 0, 5);
tarePanel.add(dynamicTareLabel, gridBagConstraints);
dynamicTareScrollPane.setPreferredSize(new java.awt.Dimension(200, 300));
dynamicTareList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
dynamicTareScrollPane.setViewportView(dynamicTareList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(dynamicTareScrollPane, gridBagConstraints);
jPanel2.setPreferredSize(new java.awt.Dimension(20, 25));
jPanel2.setLayout(new java.awt.GridBagLayout());
tareExportButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
jPanel2.add(tareExportButton, gridBagConstraints);
tareImportButton.setText("Import");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
jPanel2.add(tareImportButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel2.add(filler2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 20;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
tarePanel.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 100;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
tarePanel.add(tareHorizontalFiller, gridBagConstraints);
tabbedPane.addTab("Tares", tarePanel);
thermalPanel.setLayout(new java.awt.GridBagLayout());
thermalRunLabel.setText("Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(thermalRunLabel, gridBagConstraints);
thermalBiasRunCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
thermalBiasRunCombo.setPreferredSize(new java.awt.Dimension(200, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(thermalBiasRunCombo, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 100;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
thermalPanel.add(thermalBiasGlue, gridBagConstraints);
computeThermalBiasCheckBox.setSelected(true);
computeThermalBiasCheckBox.setText("Compute Thermal Bias for This Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(computeThermalBiasCheckBox, gridBagConstraints);
thermalViewPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
thermalViewPane.setPreferredSize(new java.awt.Dimension(100, 150));
javax.swing.GroupLayout thermalViewPaneLayout = new javax.swing.GroupLayout(thermalViewPane);
thermalViewPane.setLayout(thermalViewPaneLayout);
thermalViewPaneLayout.setHorizontalGroup(
thermalViewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 923, Short.MAX_VALUE)
);
thermalViewPaneLayout.setVerticalGroup(
thermalViewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(thermalViewPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 11;
thermalPanel.add(startEndStrut, gridBagConstraints);
biasLinearityLabel.setText("Bias Linear In:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(biasLinearityLabel, gridBagConstraints);
biasLinearityCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
biasLinearityCombo.setPreferredSize(new java.awt.Dimension(175, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(biasLinearityCombo, gridBagConstraints);
thermalTimingPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
thermalTimingPanel.setPreferredSize(new java.awt.Dimension(925, 150));
javax.swing.GroupLayout thermalTimingPanelLayout = new javax.swing.GroupLayout(thermalTimingPanel);
thermalTimingPanel.setLayout(thermalTimingPanelLayout);
thermalTimingPanelLayout.setHorizontalGroup(
thermalTimingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 923, Short.MAX_VALUE)
);
thermalTimingPanelLayout.setVerticalGroup(
thermalTimingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 14;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(thermalTimingPanel, gridBagConstraints);
buttonPanel.setPreferredSize(new java.awt.Dimension(100, 25));
buttonPanel.setLayout(new java.awt.GridBagLayout());
importThermalButton.setText("Import");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
buttonPanel.add(importThermalButton, gridBagConstraints);
exportThermalButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
buttonPanel.add(exportThermalButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(filler1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 20;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(buttonPanel, gridBagConstraints);
tabbedPane.addTab("Thermal Bias", thermalPanel);
dataTab.setLayout(new java.awt.GridBagLayout());
reducedDataLabel.setText("Reduced Data");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
dataTab.add(reducedDataLabel, gridBagConstraints);
reducedDataViewer.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
reducedDataViewerScrollPane.setViewportView(reducedDataViewer);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
dataTab.add(reducedDataViewerScrollPane, gridBagConstraints);
viewDetailReductionButton.setText("View Reduction Details");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 10;
gridBagConstraints.gridy = 10;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
dataTab.add(viewDetailReductionButton, gridBagConstraints);
exportReducedButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 20;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
dataTab.add(exportReducedButton, gridBagConstraints);
refreshReductionButton.setText("Recalculate");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
dataTab.add(refreshReductionButton, gridBagConstraints);
tabbedPane.addTab("Reduced Data", dataTab);
add(tabbedPane, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox biasLinearityCombo;
private javax.swing.JLabel biasLinearityLabel;
private javax.swing.Box.Filler botGlue;
private javax.swing.JPanel buttonPanel;
private javax.swing.JCheckBox computeThermalBiasCheckBox;
private javax.swing.JPanel dataPanel;
private javax.swing.JScrollPane dataScrollPane;
private javax.swing.JPanel dataTab;
private com.nfa.drs.data.DataContainerViewer dataViewer;
private javax.swing.JLabel dynamicTareLabel;
private javax.swing.JList dynamicTareList;
private javax.swing.JScrollPane dynamicTareScrollPane;
private javax.swing.JButton exportReducedButton;
private javax.swing.JButton exportThermalButton;
private javax.swing.Box.Filler filler1;
private javax.swing.Box.Filler filler2;
private javax.swing.JComboBox formatCombo;
private javax.swing.JButton importButton;
private javax.swing.JButton importThermalButton;
private javax.swing.JLabel inputFormatLabel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel mcConfigPanel;
private javax.swing.JLabel modelConstantsLabel;
private com.nfa.drs.constants.ModelConstantsPanel modelConstantsPanel;
private javax.swing.JLabel reducedDataLabel;
private com.nfa.drs.data.DataContainerViewer reducedDataViewer;
private javax.swing.JScrollPane reducedDataViewerScrollPane;
private javax.swing.JButton refreshReductionButton;
private javax.swing.Box.Filler startEndStrut;
private javax.swing.JLabel staticTareLabel;
private javax.swing.JList staticTareList;
private javax.swing.JScrollPane staticTareScrollPane;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JButton tareExportButton;
private javax.swing.Box.Filler tareHorizontalFiller;
private javax.swing.JButton tareImportButton;
private javax.swing.JPanel tarePanel;
private javax.swing.JComboBox tareRunComboBox;
private javax.swing.JLabel tareRunLabel;
private javax.swing.Box.Filler tareVerticalFiller;
private javax.swing.Box.Filler thermalBiasGlue;
private javax.swing.JComboBox thermalBiasRunCombo;
private javax.swing.JPanel thermalPanel;
private javax.swing.JLabel thermalRunLabel;
private javax.swing.JPanel thermalTimingPanel;
private javax.swing.JPanel thermalViewPane;
private javax.swing.JButton viewDetailReductionButton;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 55,727 | java | DataReductionPanel.java | Java | [
{
"context": "x.swing.filechooser.FileFilter;\n\n/**\n *\n * @author Nathan Templon\n */\npublic class DataReductionPanel extends javax",
"end": 2103,
"score": 0.9998772144317627,
"start": 2089,
"tag": "NAME",
"value": "Nathan Templon"
}
] | 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 com.nfa.drs;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jupiter.ganymede.property.Property;
import com.jupiter.ganymede.property.Property.PropertyChangedArgs;
import com.nfa.drs.constants.ModelConstants;
import com.nfa.drs.data.DataContainerViewer;
import com.nfa.drs.data.DataFormat;
import com.nfa.drs.data.DataSet.DataValues;
import com.nfa.drs.data.Datapoint;
import com.nfa.drs.data.Run;
import com.nfa.drs.data.StudentWindTunnelFormatCsv;
import com.nfa.drs.data.StudentWindTunnelFormatXls;
import com.nfa.drs.data.Test;
import com.nfa.drs.reduction.ReductionProcessor;
import com.nfa.drs.reduction.ReductionProcessor.ReductionResults;
import com.nfa.drs.reduction.thermal.ThermalBiasSettings;
import com.nfa.drs.reduction.thermal.ThermalBiasSettings.ThermalBiasLinearity;
import com.nfa.drs.reduction.thermal.ThermalBiasTimeTable;
import com.nfa.drs.reduction.tare.TareSettings;
import com.nfa.drs.reduction.tare.TareSettings.TareSettingsEntry;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.filechooser.FileFilter;
/**
*
* @author <NAME>
*/
public class DataReductionPanel extends javax.swing.JPanel {
// Constants
public static final String NO_TARE_KEY = "NONE";
// Static Fields
private static final Map<String, DataFormat> formats = new HashMap<>();
static {
DataFormat wsu3by4 = new StudentWindTunnelFormatCsv();
formats.put(wsu3by4.getName(), wsu3by4);
DataFormat wsu3by4xls = new StudentWindTunnelFormatXls();
formats.put(wsu3by4xls.getName(), wsu3by4xls);
}
private static final FileFilter JSON_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.toString().endsWith(".json");
}
@Override
public String getDescription() {
return "Json Files (*.json)";
}
};
private static final FileFilter DAT_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.toString().endsWith(".dat");
}
@Override
public String getDescription() {
return "DAT Files (*.dat)";
}
};
// Fields
private final Property<Test> test = new Property<>();
private final Map<String, ThermalBiasSettings> thermalBiasSettings = new HashMap<>();
private final DataContainerViewer thermalDataView = new DataContainerViewer();
private final ThermalBiasTimeTable thermalTimeTable = new ThermalBiasTimeTable();
private Defaults defaults = new Defaults();
private TareSettings tareSettings = new TareSettings();
private ReductionResults lastResults;
// Properties
public final Defaults getDefaults() {
return this.defaults;
}
public final void setDefaults(Defaults defaults) {
this.defaults = defaults;
if (this.defaults != null) {
String importFormat = this.defaults.getImportFormat();
if (importFormat != null) {
ComboBoxModel model = this.formatCombo.getModel();
if (model instanceof DefaultComboBoxModel) {
int index = ((DefaultComboBoxModel)model).getIndexOf(importFormat);
if (index >= 0) {
this.formatCombo.setSelectedIndex(index);
}
}
}
}
}
private ThermalBiasSettings getCurrentThermalBiasSettings() {
if (this.thermalBiasRunCombo.getSelectedItem() != null) {
String currentRun = this.thermalBiasRunCombo.getSelectedItem().toString();
return this.thermalBiasSettings.get(currentRun);
}
return null;
}
/**
* Creates new form DataReductionPanel
*/
public DataReductionPanel() {
this.thermalDataView.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
this.initComponents();
this.thermalViewPane.setLayout(new BorderLayout());
this.thermalViewPane.add(this.thermalDataView.getTableHeader(), BorderLayout.PAGE_START);
this.thermalViewPane.add(this.thermalDataView, BorderLayout.CENTER);
this.thermalTimingPanel.setLayout(new BorderLayout());
this.thermalTimingPanel.add(this.thermalTimeTable.getTableHeader(), BorderLayout.PAGE_START);
this.thermalTimingPanel.add(this.thermalTimeTable, BorderLayout.CENTER);
// Add Items to ComboBoxes
this.formatCombo.removeAllItems();
formats.keySet().stream()
.forEach((String name) -> this.formatCombo.addItem(name));
this.thermalBiasRunCombo.removeAllItems();
this.biasLinearityCombo.removeAllItems();
for (ThermalBiasLinearity lin : ThermalBiasLinearity.values()) {
this.biasLinearityCombo.addItem(lin);
}
this.tareRunComboBox.removeAllItems();
this.staticTareList.setListData(new Object[0]);
this.dynamicTareList.setListData(new Object[0]);
// Add Listeners
this.importButton.addActionListener(this::importButtonActionPerformed);
this.thermalBiasRunCombo.addItemListener(this::thermalBiasItemEvent);
this.computeThermalBiasCheckBox.addItemListener(this::computeThermalBiasItemEvent);
this.biasLinearityCombo.addItemListener(this::biasLinearityItemEvent);
this.importThermalButton.addActionListener(this::importBiasButtonAction);
this.exportThermalButton.addActionListener(this::exportBiasButtonAction);
this.tareRunComboBox.addItemListener(this::tareRunComboBoxChange);
this.staticTareList.addListSelectionListener(this::staticTareListEvent);
this.dynamicTareList.addListSelectionListener(this::dynamicTareListEvent);
this.tareImportButton.addActionListener(this::importTareSettingsAction);
this.tareExportButton.addActionListener(this::exportTareSettingsAction);
this.refreshReductionButton.addActionListener(this::refreshReductionButtonAction);
this.viewDetailReductionButton.addActionListener(this::showResultsDetailButtonAction);
this.exportReducedButton.addActionListener(this::exportResultsButtonAction);
this.formatCombo.addItemListener(this::importFormatItemEvent);
this.thermalDataView.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
DataReductionPanel.this.resizeThermalBiasView();
}
});
this.thermalDataView.getModel().addTableModelListener((TableModelEvent e) -> this.resizeThermalBiasView());
this.thermalTimeTable.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
DataReductionPanel.this.resizeThermalTimingPanel();
}
});
this.thermalTimeTable.getModel().addTableModelListener((TableModelEvent e) -> {
this.resizeThermalTimingPanel();
this.getCurrentThermalBiasSettings().setTimes(this.thermalTimeTable.getTimes());
});
this.test.addPropertyChangedListener(this::resetThermalBias);
this.test.addPropertyChangedListener((PropertyChangedArgs<Test> e) -> this.thermalBiasItemEvent(null));
}
// Private Methods
private void importButtonActionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path dir = chooser.getSelectedFile().toPath();
if (!Files.isDirectory(dir)) {
dir = dir.getParent();
}
if (Files.isDirectory(dir)) {
this.importDataFrom(dir);
}
}
}
private void importDataFrom(Path dir) {
this.getDefaults().setImportDirectory(dir.toString());
DataFormat format = formats.get(this.formatCombo.getSelectedItem().toString());
this.test.set(format.fromDirectory(dir));
// Attempt to Import Model Constants
this.modelConstantsPanel.setDefaultDirectory(dir);
Path mcFile = dir.resolve(ModelConstants.DEFAULT_FILE_NAME);
if (Files.exists(mcFile)) {
this.modelConstantsPanel.importModelConstantsFile(mcFile);
}
// Attempt to Import Thermal Bias
Path tbFile = dir.resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(tbFile)) {
this.importThermalBias(tbFile);
}
// Attempt to Import Tare Settings
Path tareFile = dir.resolve(TareSettings.DEFAULT_TARE_SETTINGS_FILE);
if (Files.exists(tareFile)) {
this.importTareSettings(tareFile);
}
else {
this.tareSettings.setAllSettings(new HashMap<>());
this.test.get().getRuns().stream()
.forEach((Run run) -> this.tareSettings.setSettings(run.getName(), new TareSettingsEntry()));
if (this.tareRunComboBox.getItemCount() > 0) {
this.tareRunComboBox.setSelectedIndex(0);
}
}
// Fill in blanks with thermal bias and tare settings
this.test.get().getRuns().stream()
.filter((Run run) ->
!this.thermalBiasSettings.containsKey(run.getName())
)
.forEach((Run run) ->
this.thermalBiasSettings.put(run.getName(), new ThermalBiasSettings(run.getPointCount()))
);
this.test.get().getRuns().stream()
.filter((Run run) ->
!this.tareSettings.getAllSettings().containsKey(run.getName())
)
.forEach((Run run) ->
this.tareSettings.setSettings(run.getName(), new TareSettingsEntry())
);
// Calculate Initial Coefficients
this.test.get().getRuns().stream()
.forEach((Run run) ->
run.getDatapoints().stream()
.forEach((Datapoint point) ->
point.getData().coefficientsFromLoads(this.modelConstantsPanel.getModelConstants())
)
);
// Adding the Runs to Various Things
this.tareRunComboBox.removeAllItems();
this.dataViewer.clear();
this.test.get().getRuns().stream()
.forEach((Run run) -> {
run.getDatapoints().stream()
.forEach((Datapoint point) -> {
this.dataViewer.addData(run.getName(), point);
});
this.tareRunComboBox.addItem(run.getName());
});
this.resizeThermalBiasView();
this.refreshTareSettings();
}
private void resetThermalBias(PropertyChangedArgs<Test> e) {
this.thermalBiasSettings.clear();
this.thermalBiasRunCombo.removeAllItems();
this.test.get().getRuns().stream()
.forEach((Run run) -> {
this.thermalBiasRunCombo.addItem(run.getName());
this.thermalBiasSettings.put(run.getName(), new ThermalBiasSettings(run.getPointCount()));
});
}
private void thermalBiasItemEvent(ItemEvent e) {
if (e == null || e.getStateChange() == ItemEvent.SELECTED) {
if (this.test.get() != null) {
// Load Data
Object selected = this.thermalBiasRunCombo.getSelectedItem();
if (selected != null) {
final String runName = selected.toString();
Run run = this.test.get().getRun(runName);
if (run != null) {
this.thermalDataView.clear();
run.getDatapoints().stream()
.forEach((Datapoint point) ->
this.thermalDataView.addData(runName, point)
);
}
}
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
// Set Values
if (tbs != null) {
this.biasLinearityCombo.setSelectedItem(tbs.getLinearity());
this.thermalTimeTable.setTimes(tbs.getTimes());
}
// Update Check Box
if (tbs != null) {
this.computeThermalBiasCheckBox.setSelected(tbs.getComputeThermalBias());
}
// Fire Faux Related Events
this.biasLinearityItemEvent(null);
this.revalidate();
}
}
}
private void computeThermalBiasItemEvent(ItemEvent e) {
if (this.computeThermalBiasCheckBox.isSelected()) {
this.biasLinearityCombo.setEnabled(true);
this.thermalTimeTable.setEnabled(this.biasLinearityCombo.getSelectedItem().equals(ThermalBiasLinearity.TIME));
}
else {
this.biasLinearityCombo.setEnabled(false);
this.thermalTimeTable.clearSelection();
this.thermalTimeTable.setEnabled(false);
}
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
if (tbs != null) {
tbs.setComputeThermalBias(this.computeThermalBiasCheckBox.isSelected());
}
}
private void resizeThermalBiasView() {
this.thermalViewPane.setPreferredSize(new Dimension(
this.thermalDataView.getPreferredSize().width,
this.thermalDataView.getPreferredSize().height + DataReductionPanel.this.thermalDataView.getTableHeader().getHeight()
+ this.thermalViewPane.getInsets().top
));
}
private void resizeThermalTimingPanel() {
this.thermalTimingPanel.setPreferredSize(new Dimension(
this.thermalTimeTable.getPreferredSize().width,
this.thermalTimeTable.getPreferredSize().height + DataReductionPanel.this.thermalTimeTable.getTableHeader().getHeight()
+ this.thermalTimingPanel.getInsets().top
));
}
private void biasLinearityItemEvent(ItemEvent e) {
ThermalBiasSettings tbs = this.getCurrentThermalBiasSettings();
if (tbs != null) {
Object o = this.biasLinearityCombo.getSelectedItem();
if (o instanceof ThermalBiasLinearity) {
ThermalBiasLinearity lin = (ThermalBiasLinearity) o;
tbs.setLinearity(lin);
}
}
boolean inTime = this.biasLinearityCombo.getSelectedItem().equals(ThermalBiasLinearity.TIME);
if (!inTime) {
this.thermalTimeTable.clearSelection();
}
this.thermalTimeTable.setEnabled(inTime);
}
private void importBiasButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null && Files.exists(Paths.get(this.getDefaults().getImportDirectory()))) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
Path defaultMcFile = chooser.getCurrentDirectory().toPath().resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(defaultMcFile)) {
chooser.setSelectedFile(defaultMcFile.toFile());
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path mcFile = chooser.getSelectedFile().toPath();
if (Files.exists(mcFile)) {
this.importThermalBias(mcFile);
}
}
}
private void exportBiasButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), ThermalBiasSettings.DEFAULT_FILE_NAME));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(JSON_FILTER) && !file.toString().endsWith(".json")) {
file = Paths.get(file.toString() + ".json");
}
this.exportThermalBias(file);
}
}
private void importThermalBias(Path mcFile) {
try {
String json = Files.readAllLines(mcFile).stream()
.reduce("", (String first, String second) -> first + System.lineSeparator() + second);
JsonObject map = new JsonParser().parse(json).getAsJsonObject();
this.thermalBiasSettings.clear();
map.entrySet().stream()
.forEach((Entry<String, JsonElement> entry) -> {
String name = entry.getKey();
JsonElement element = entry.getValue();
try {
ThermalBiasSettings tbs = DataReducer.GSON.fromJson(element, ThermalBiasSettings.class);
this.thermalBiasSettings.put(name, tbs);
}
catch (Exception ex) {
}
});
this.thermalBiasItemEvent(null);
this.resizeThermalBiasView();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(this, "There was an error while importing the thermal bias.", "Import Error", JOptionPane.ERROR_MESSAGE);
}
this.resizeThermalBiasView();
}
private void exportThermalBias(Path mcFile) {
String json = DataReducer.GSON.toJson(this.thermalBiasSettings);
try {
Files.write(mcFile, Arrays.asList(new String[]{json}));
}
catch (IOException ex) {
}
}
private void tareRunComboBoxChange(ItemEvent e) {
this.refreshTareSettings();
}
private void refreshTareSettings() {
if (this.test.get() != null && this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
List<String> tareRuns = new ArrayList<>();
tareRuns.add(NO_TARE_KEY);
tareRuns.addAll(this.test.get().getRuns().stream()
.filter((Run run) -> !run.getName().equals(runName))
.map((Run run) -> run.getName())
.collect(Collectors.toList()));
Object[] listDataArray = tareRuns.toArray();
this.staticTareList.setListData(listDataArray);
this.dynamicTareList.setListData(listDataArray);
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
String staticTare = tse.getStaticTare();
if (!staticTare.isEmpty()) {
this.staticTareList.setSelectedValue(staticTare, true);
}
else {
this.staticTareList.setSelectedValue(NO_TARE_KEY, true);
}
String dynamicTare = tse.getDynamicTare();
if (!dynamicTare.isEmpty()) {
this.dynamicTareList.setSelectedValue(dynamicTare, true);
}
else {
this.dynamicTareList.setSelectedValue(NO_TARE_KEY, true);
}
}
}
}
private void staticTareListEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
Object item = this.staticTareList.getSelectedValue();
if (item != null) {
if (item.equals(NO_TARE_KEY)) {
tse.setStaticTare("");
}
else {
tse.setStaticTare(item.toString());
}
}
}
}
}
private void dynamicTareListEvent(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (this.tareRunComboBox.getSelectedItem() != null) {
String runName = this.tareRunComboBox.getSelectedItem().toString();
TareSettingsEntry tse = this.tareSettings.getSettings(runName);
if (tse != null) {
Object item = this.dynamicTareList.getSelectedValue();
if (item != null) {
if (item.equals(NO_TARE_KEY)) {
tse.setDynamicTare("");
}
else {
tse.setDynamicTare(item.toString());
}
}
}
}
}
private void importTareSettingsAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
if (this.getDefaults() != null && this.getDefaults().getImportDirectory() != null && Files.exists(Paths.get(this.getDefaults().getImportDirectory()))) {
chooser.setCurrentDirectory(new File(this.getDefaults().getImportDirectory()));
}
Path defaultMcFile = chooser.getCurrentDirectory().toPath().resolve(ThermalBiasSettings.DEFAULT_FILE_NAME);
if (Files.exists(defaultMcFile)) {
chooser.setSelectedFile(defaultMcFile.toFile());
}
if (chooser.showDialog(this, "Import") == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (Files.exists(file)) {
this.importTareSettings(file);
}
}
}
private void exportTareSettingsAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(JSON_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), TareSettings.DEFAULT_TARE_SETTINGS_FILE));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(JSON_FILTER) && !file.toString().endsWith(".json")) {
file = Paths.get(file.toString() + ".json");
}
this.exportTareSettings(file);
}
}
private void importTareSettings(Path file) {
try {
String json = Files.readAllLines(file).stream()
.reduce("", (String first, String second) -> first + System.lineSeparator() + second);
this.tareSettings = DataReducer.GSON.fromJson(json, TareSettings.class);
this.refreshTareSettings();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(this, "There was an error while importing the tare settings.", "Import Error", JOptionPane.ERROR_MESSAGE);
}
this.refreshTareSettings();
}
private void exportTareSettings(Path file) {
String json = DataReducer.GSON.toJson(this.tareSettings);
try {
Files.write(file, Arrays.asList(new String[]{json}));
}
catch (IOException ex) {
}
}
private void refreshReductionButtonAction(ActionEvent e) {
this.calculateReducedData();
}
private void calculateReducedData() {
ReductionProcessor proc = new ReductionProcessor(this.test.get(), this.modelConstantsPanel.getModelConstants(), this.tareSettings,
this.thermalBiasSettings);
this.lastResults = proc.reduce();
this.reducedDataViewer.clear();
this.lastResults.getReducedData().getRuns().stream()
.forEach((Run run) ->
run.getDatapoints().stream()
.forEach((Datapoint point) ->
this.reducedDataViewer.addData(run.getName(), point)
)
);
}
private void showResultsDetailButtonAction(ActionEvent e) {
if (this.lastResults == null) {
return;
}
ReductionDetailFrame frame = new ReductionDetailFrame();
frame.setDetailedResults(this.lastResults.getReductionSteps());
frame.setVisible(true);
}
private void exportResultsButtonAction(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(DAT_FILTER);
Path defaultDir = Paths.get(this.getDefaults().getImportDirectory());
if (defaultDir != null && Files.exists(defaultDir)) {
chooser.setCurrentDirectory(defaultDir.toFile());
}
chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "output.dat"));
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path file = chooser.getSelectedFile().toPath();
if (chooser.getFileFilter().equals(DAT_FILTER) && !file.toString().endsWith(".dat")) {
file = Paths.get(file.toString() + ".dat");
}
this.exportResults(file);
}
}
private void exportResults(Path file) {
final List<String> lines = new ArrayList<>();
final List<DataValues> values = Collections.unmodifiableList(Arrays.asList(DataValues.values()));
StringBuilder decBuilder = new StringBuilder();
decBuilder.append("Run,Test Point,");
values.stream()
.forEach((DataValues value) -> {
decBuilder.append(value.getDisplayName()).append(",");
});
String decLine = decBuilder.toString();
if (this.lastResults != null) {
this.lastResults.getReducedData().getRuns().stream()
.forEach((Run run) -> {
lines.add(run.getName());
lines.add(decLine);
run.getDatapoints().stream()
.forEach((Datapoint point) -> {
StringBuilder dataLine = new StringBuilder();
dataLine.append(run.getName()).append(",");
dataLine.append(point.getPointNumber()).append(",");
values.stream()
.forEach((DataValues value) -> {
dataLine.append(point.getData().get(value)).append(",");
});
lines.add(dataLine.toString());
});
lines.add("");
});
}
try {
Files.write(file, lines);
}
catch (IOException ex) {
}
}
private void importFormatItemEvent(ItemEvent e) {
if (this.defaults != null) {
this.defaults.setImportFormat(e.getItem().toString());
}
}
// Designer
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
tabbedPane = new javax.swing.JTabbedPane();
dataPanel = new javax.swing.JPanel();
inputFormatLabel = new javax.swing.JLabel();
formatCombo = new javax.swing.JComboBox();
dataScrollPane = new javax.swing.JScrollPane();
dataViewer = new com.nfa.drs.data.DataContainerViewer();
importButton = new javax.swing.JButton();
mcConfigPanel = new javax.swing.JPanel();
botGlue = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
modelConstantsLabel = new javax.swing.JLabel();
modelConstantsPanel = new com.nfa.drs.constants.ModelConstantsPanel();
tarePanel = new javax.swing.JPanel();
tareRunLabel = new javax.swing.JLabel();
tareVerticalFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
tareRunComboBox = new javax.swing.JComboBox();
staticTareLabel = new javax.swing.JLabel();
staticTareScrollPane = new javax.swing.JScrollPane();
staticTareList = new javax.swing.JList();
dynamicTareLabel = new javax.swing.JLabel();
dynamicTareScrollPane = new javax.swing.JScrollPane();
dynamicTareList = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
tareExportButton = new javax.swing.JButton();
tareImportButton = new javax.swing.JButton();
filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
tareHorizontalFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
thermalPanel = new javax.swing.JPanel();
thermalRunLabel = new javax.swing.JLabel();
thermalBiasRunCombo = new javax.swing.JComboBox();
thermalBiasGlue = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
computeThermalBiasCheckBox = new javax.swing.JCheckBox();
thermalViewPane = new javax.swing.JPanel();
startEndStrut = new javax.swing.Box.Filler(new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 0), new java.awt.Dimension(40, 32767));
biasLinearityLabel = new javax.swing.JLabel();
biasLinearityCombo = new javax.swing.JComboBox();
thermalTimingPanel = new javax.swing.JPanel();
buttonPanel = new javax.swing.JPanel();
importThermalButton = new javax.swing.JButton();
exportThermalButton = new javax.swing.JButton();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
dataTab = new javax.swing.JPanel();
reducedDataLabel = new javax.swing.JLabel();
reducedDataViewerScrollPane = new javax.swing.JScrollPane();
reducedDataViewer = new com.nfa.drs.data.DataContainerViewer();
viewDetailReductionButton = new javax.swing.JButton();
exportReducedButton = new javax.swing.JButton();
refreshReductionButton = new javax.swing.JButton();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new java.awt.Dimension(950, 600));
setLayout(new java.awt.BorderLayout());
dataPanel.setLayout(new java.awt.GridBagLayout());
inputFormatLabel.setText("Data Format");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
dataPanel.add(inputFormatLabel, gridBagConstraints);
formatCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
formatCombo.setPreferredSize(new java.awt.Dimension(275, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
dataPanel.add(formatCombo, gridBagConstraints);
dataViewer.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
dataScrollPane.setViewportView(dataViewer);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
dataPanel.add(dataScrollPane, gridBagConstraints);
importButton.setText("Import Data");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
dataPanel.add(importButton, gridBagConstraints);
tabbedPane.addTab("Raw Data", dataPanel);
mcConfigPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
mcConfigPanel.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 50;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
mcConfigPanel.add(botGlue, gridBagConstraints);
modelConstantsLabel.setText("Model Constants");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
mcConfigPanel.add(modelConstantsLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
mcConfigPanel.add(modelConstantsPanel, gridBagConstraints);
tabbedPane.addTab("Model Constants", mcConfigPanel);
tarePanel.setLayout(new java.awt.GridBagLayout());
tareRunLabel.setText("Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(tareRunLabel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 100;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
tarePanel.add(tareVerticalFiller, gridBagConstraints);
tareRunComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
tareRunComboBox.setPreferredSize(new java.awt.Dimension(200, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(tareRunComboBox, gridBagConstraints);
staticTareLabel.setText("Static Tare");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(20, 5, 0, 5);
tarePanel.add(staticTareLabel, gridBagConstraints);
staticTareScrollPane.setPreferredSize(new java.awt.Dimension(200, 300));
staticTareList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
staticTareScrollPane.setViewportView(staticTareList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(staticTareScrollPane, gridBagConstraints);
dynamicTareLabel.setText("Dynamic Tare");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(20, 5, 0, 5);
tarePanel.add(dynamicTareLabel, gridBagConstraints);
dynamicTareScrollPane.setPreferredSize(new java.awt.Dimension(200, 300));
dynamicTareList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
dynamicTareScrollPane.setViewportView(dynamicTareList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 11;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
tarePanel.add(dynamicTareScrollPane, gridBagConstraints);
jPanel2.setPreferredSize(new java.awt.Dimension(20, 25));
jPanel2.setLayout(new java.awt.GridBagLayout());
tareExportButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
jPanel2.add(tareExportButton, gridBagConstraints);
tareImportButton.setText("Import");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
jPanel2.add(tareImportButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel2.add(filler2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 20;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
tarePanel.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 100;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
tarePanel.add(tareHorizontalFiller, gridBagConstraints);
tabbedPane.addTab("Tares", tarePanel);
thermalPanel.setLayout(new java.awt.GridBagLayout());
thermalRunLabel.setText("Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(thermalRunLabel, gridBagConstraints);
thermalBiasRunCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
thermalBiasRunCombo.setPreferredSize(new java.awt.Dimension(200, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(thermalBiasRunCombo, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 100;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
thermalPanel.add(thermalBiasGlue, gridBagConstraints);
computeThermalBiasCheckBox.setSelected(true);
computeThermalBiasCheckBox.setText("Compute Thermal Bias for This Run");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(computeThermalBiasCheckBox, gridBagConstraints);
thermalViewPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
thermalViewPane.setPreferredSize(new java.awt.Dimension(100, 150));
javax.swing.GroupLayout thermalViewPaneLayout = new javax.swing.GroupLayout(thermalViewPane);
thermalViewPane.setLayout(thermalViewPaneLayout);
thermalViewPaneLayout.setHorizontalGroup(
thermalViewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 923, Short.MAX_VALUE)
);
thermalViewPaneLayout.setVerticalGroup(
thermalViewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(thermalViewPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 11;
thermalPanel.add(startEndStrut, gridBagConstraints);
biasLinearityLabel.setText("Bias Linear In:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(biasLinearityLabel, gridBagConstraints);
biasLinearityCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
biasLinearityCombo.setPreferredSize(new java.awt.Dimension(175, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
thermalPanel.add(biasLinearityCombo, gridBagConstraints);
thermalTimingPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
thermalTimingPanel.setPreferredSize(new java.awt.Dimension(925, 150));
javax.swing.GroupLayout thermalTimingPanelLayout = new javax.swing.GroupLayout(thermalTimingPanel);
thermalTimingPanel.setLayout(thermalTimingPanelLayout);
thermalTimingPanelLayout.setHorizontalGroup(
thermalTimingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 923, Short.MAX_VALUE)
);
thermalTimingPanelLayout.setVerticalGroup(
thermalTimingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 14;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(thermalTimingPanel, gridBagConstraints);
buttonPanel.setPreferredSize(new java.awt.Dimension(100, 25));
buttonPanel.setLayout(new java.awt.GridBagLayout());
importThermalButton.setText("Import");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
buttonPanel.add(importThermalButton, gridBagConstraints);
exportThermalButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
buttonPanel.add(exportThermalButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
buttonPanel.add(filler1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 20;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
thermalPanel.add(buttonPanel, gridBagConstraints);
tabbedPane.addTab("Thermal Bias", thermalPanel);
dataTab.setLayout(new java.awt.GridBagLayout());
reducedDataLabel.setText("Reduced Data");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
dataTab.add(reducedDataLabel, gridBagConstraints);
reducedDataViewer.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
reducedDataViewerScrollPane.setViewportView(reducedDataViewer);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
dataTab.add(reducedDataViewerScrollPane, gridBagConstraints);
viewDetailReductionButton.setText("View Reduction Details");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 10;
gridBagConstraints.gridy = 10;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
dataTab.add(viewDetailReductionButton, gridBagConstraints);
exportReducedButton.setText("Export");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 20;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
dataTab.add(exportReducedButton, gridBagConstraints);
refreshReductionButton.setText("Recalculate");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
dataTab.add(refreshReductionButton, gridBagConstraints);
tabbedPane.addTab("Reduced Data", dataTab);
add(tabbedPane, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox biasLinearityCombo;
private javax.swing.JLabel biasLinearityLabel;
private javax.swing.Box.Filler botGlue;
private javax.swing.JPanel buttonPanel;
private javax.swing.JCheckBox computeThermalBiasCheckBox;
private javax.swing.JPanel dataPanel;
private javax.swing.JScrollPane dataScrollPane;
private javax.swing.JPanel dataTab;
private com.nfa.drs.data.DataContainerViewer dataViewer;
private javax.swing.JLabel dynamicTareLabel;
private javax.swing.JList dynamicTareList;
private javax.swing.JScrollPane dynamicTareScrollPane;
private javax.swing.JButton exportReducedButton;
private javax.swing.JButton exportThermalButton;
private javax.swing.Box.Filler filler1;
private javax.swing.Box.Filler filler2;
private javax.swing.JComboBox formatCombo;
private javax.swing.JButton importButton;
private javax.swing.JButton importThermalButton;
private javax.swing.JLabel inputFormatLabel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel mcConfigPanel;
private javax.swing.JLabel modelConstantsLabel;
private com.nfa.drs.constants.ModelConstantsPanel modelConstantsPanel;
private javax.swing.JLabel reducedDataLabel;
private com.nfa.drs.data.DataContainerViewer reducedDataViewer;
private javax.swing.JScrollPane reducedDataViewerScrollPane;
private javax.swing.JButton refreshReductionButton;
private javax.swing.Box.Filler startEndStrut;
private javax.swing.JLabel staticTareLabel;
private javax.swing.JList staticTareList;
private javax.swing.JScrollPane staticTareScrollPane;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JButton tareExportButton;
private javax.swing.Box.Filler tareHorizontalFiller;
private javax.swing.JButton tareImportButton;
private javax.swing.JPanel tarePanel;
private javax.swing.JComboBox tareRunComboBox;
private javax.swing.JLabel tareRunLabel;
private javax.swing.Box.Filler tareVerticalFiller;
private javax.swing.Box.Filler thermalBiasGlue;
private javax.swing.JComboBox thermalBiasRunCombo;
private javax.swing.JPanel thermalPanel;
private javax.swing.JLabel thermalRunLabel;
private javax.swing.JPanel thermalTimingPanel;
private javax.swing.JPanel thermalViewPane;
private javax.swing.JButton viewDetailReductionButton;
// End of variables declaration//GEN-END:variables
}
| 55,719 | 0.654082 | 0.645486 | 1,261 | 43.192703 | 30.30752 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785091 | false | false | 4 |
dea8d9e1d152d6ed463e91fe4ff7df4943f0c5cf | 33,483,565,050,235 | 3de455fabf3929b3b3a0bbdb36aedabc6e97f143 | /ДИСК/Dao/BookRepository.java | efe4a92a59d10f259e06b8ef0d607752d070c8c3 | [] | no_license | TheAntoshkaBy/diploma | https://github.com/TheAntoshkaBy/diploma | 3bb48bc9fc771ab6cccabaaecd29b8301fc4edac | ef9aac9e979b06d78baa61bdd3dcba69327e934b | refs/heads/master | 2023-04-25T21:16:47.464000 | 2021-06-01T07:21:02 | 2021-06-01T07:21:02 | 370,243,101 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.epam.esm.repository;
import com.epam.esm.entity.Book;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
@Override
List<Book> findAll();
List<Book> findByIdBetween(Long offset, Long lastBook);
@Override
List<Book> findAll(Sort sort);
@Override
List<Book> findAllById(Iterable<Long> iterable);
int getBookById(long id);
@Modifying(clearAutomatically = true)
@Query("update book b set b.name = :name, b.description = :description, b.author = :author where b.id = :id")
void update(@Param("id") long id, @Param("name") String name, @Param("description") String description,
@Param("author") String author);
@Modifying
@Query("select b.count from book b where b.id = :id")
int getBookCount();
}
| UTF-8 | Java | 1,186 | java | BookRepository.java | Java | [] | null | [] | package com.epam.esm.repository;
import com.epam.esm.entity.Book;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
@Override
List<Book> findAll();
List<Book> findByIdBetween(Long offset, Long lastBook);
@Override
List<Book> findAll(Sort sort);
@Override
List<Book> findAllById(Iterable<Long> iterable);
int getBookById(long id);
@Modifying(clearAutomatically = true)
@Query("update book b set b.name = :name, b.description = :description, b.author = :author where b.id = :id")
void update(@Param("id") long id, @Param("name") String name, @Param("description") String description,
@Param("author") String author);
@Modifying
@Query("select b.count from book b where b.id = :id")
int getBookCount();
}
| 1,186 | 0.714165 | 0.714165 | 36 | 31.944445 | 29.843987 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 4 |
4cf7ad8f9bc291f29131f405b167c96a081d84ab | 33,483,565,047,590 | 4a627a99cdf202019fa4088ca23316e9cc427e7b | /nyd-cash-user/nyd-cash-user-dao/src/main/java/com/nyd/user/dao/mapper/UserJxMapper.java | 3b2e57b073e324baa82e9e8f15950e58b0b52305 | [] | no_license | P79N6A/zlqb | https://github.com/P79N6A/zlqb | 4bdcc62db76f8b4fdd4176c06812c9bd8ac2148b | 66a8781e74216ead7ea4969d89972c16e9d45b54 | refs/heads/master | 2020-07-13T14:18:36.941000 | 2019-08-26T12:22:20 | 2019-08-26T12:22:20 | 205,096,175 | 0 | 1 | null | true | 2019-08-29T06:30:30 | 2019-08-29T06:30:30 | 2019-08-29T06:26:27 | 2019-08-29T06:25:43 | 0 | 0 | 0 | 0 | null | false | false | package com.nyd.user.dao.mapper;
import com.nyd.user.entity.UserJx;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author liuqiu
*/
@Mapper
public interface UserJxMapper {
/**
* 查询已经推单外审确认的所有用户
* @param userId
* @return
*/
List<UserJx> getUserJxByUserId(String userId);
}
| UTF-8 | Java | 382 | java | UserJxMapper.java | Java | [
{
"context": "pper;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * @author liuqiu\r\n */\r\n@Mapper\r\npublic interface UserJxMapper {\r\n ",
"end": 168,
"score": 0.9988625049591064,
"start": 162,
"tag": "USERNAME",
"value": "liuqiu"
}
] | null | [] | package com.nyd.user.dao.mapper;
import com.nyd.user.entity.UserJx;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author liuqiu
*/
@Mapper
public interface UserJxMapper {
/**
* 查询已经推单外审确认的所有用户
* @param userId
* @return
*/
List<UserJx> getUserJxByUserId(String userId);
}
| 382 | 0.642045 | 0.642045 | 19 | 16.526316 | 15.229363 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 4 |
23c0f737afb75513d55637305e5567563088d6e3 | 5,600,637,413,356 | b200fe882e5c4c652814d5877b12507467076eb5 | /MasterMind/MainFrame.java | 8b6a02d5b4859f6ab633609b392cfd864af16385 | [] | no_license | FarmerTedd/Repozytorium-1 | https://github.com/FarmerTedd/Repozytorium-1 | 00ce21c601881baf95008714c5b0e1c0f2781b28 | ed79f1badd16696155844205a6164d8e6d8fde8e | refs/heads/master | 2020-05-27T20:21:54.055000 | 2017-05-08T16:34:42 | 2017-05-08T16:34:42 | 82,571,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* Created by Farmer on 2017-04-19.
*/
public class MainFrame extends JFrame {
public MainFrame(){
JMenu optionMenu = new JMenu("Opcje");
Action rekordAction = new RecordAction("Rekord");
optionMenu.add(rekordAction);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(optionMenu);
MainPanel panel = new MainPanel();
add(panel, BorderLayout.CENTER);
pack();
}
class RecordAction extends AbstractAction{
public RecordAction(String name){
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
Rekord rekord = new Rekord();
rekord.setVisible(true);
}catch (Exception ex){};
}
}
}
| UTF-8 | Java | 899 | java | MainFrame.java | Java | [
{
"context": "ort java.awt.event.ActionEvent;\n\n/**\n * Created by Farmer on 2017-04-19.\n */\npublic class MainFrame extends",
"end": 101,
"score": 0.9996062517166138,
"start": 95,
"tag": "NAME",
"value": "Farmer"
}
] | null | [] | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* Created by Farmer on 2017-04-19.
*/
public class MainFrame extends JFrame {
public MainFrame(){
JMenu optionMenu = new JMenu("Opcje");
Action rekordAction = new RecordAction("Rekord");
optionMenu.add(rekordAction);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(optionMenu);
MainPanel panel = new MainPanel();
add(panel, BorderLayout.CENTER);
pack();
}
class RecordAction extends AbstractAction{
public RecordAction(String name){
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
Rekord rekord = new Rekord();
rekord.setVisible(true);
}catch (Exception ex){};
}
}
}
| 899 | 0.581757 | 0.572859 | 36 | 23.972221 | 17.691 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472222 | false | false | 4 |
785f2fd5bc6a87cc57143401159201357d7bf812 | 7,825,430,439,681 | aa6723f1435bc776810a7538e33409a303d95390 | /gatk_tools/main/java/org/systemsbiology/gatk/GeneUtilities.java | dc8de22a8bb8adca78107b0c8ddbdcf489c509e1 | [] | no_license | lordjoe/hydra-proteomics | https://github.com/lordjoe/hydra-proteomics | c35eb77370ed5bc3f56b3aec7ba7e941b9ca708a | a350d5652c8aed10e06cda7bee589dae0eec680c | refs/heads/master | 2021-01-18T22:35:57.911000 | 2016-04-14T14:06:07 | 2016-04-14T14:06:07 | 42,201,110 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.systemsbiology.gatk;
import com.sun.jndi.toolkit.url.*;
import net.sf.picard.reference.*;
import net.sf.samtools.*;
import org.broadinstitute.sting.gatk.contexts.*;
import org.broadinstitute.sting.gatk.datasources.reference.*;
import org.broadinstitute.sting.utils.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
/**
* PACKAGE_NAME.org.systemsbiology.gatk.GeneUtilities
* some useful static methods
* User: Steve
* Date: 6/14/12
*/
public class GeneUtilities {
public static final GeneUtilities[] EMPTY_ARRAY = {};
private static File gReferenceFile;
private static SAMSequenceDictionary gReferenceDictionary;
public static File getReferenceFile() {
return gReferenceFile;
}
public static void setReferenceFile(File refFile) {
ReferenceDataSource rds = new ReferenceDataSource(refFile);
IndexedFastaSequenceFile reference = rds.getReference();
SAMSequenceDictionary sd = reference.getSequenceDictionary();
setReferenceDictionary(sd);
gReferenceFile = refFile;
}
public static SAMSequenceDictionary getReferenceDictionary() {
return gReferenceDictionary;
}
private static void setReferenceDictionary(SAMSequenceDictionary referenceDictionary) {
gReferenceDictionary = referenceDictionary;
}
public static void guaranteeHeader(SAMFileWriter writer, ReferenceContext ref) {
SAMFileHeader fileHeader = writer.getFileHeader();
SAMSequenceDictionary sd = fileHeader.getSequenceDictionary();
if (sd.getSequences().isEmpty()) {
GenomeLocParser gp = ref.getGenomeLocParser();
}
}
/**
* { method
*
* @param FileName the file name
* @return - array or strings - null if file empty or does not exist
* }
* @name readInLines
* @function reads all the data in a file into an array of strings - one per line
*/
public static String[] readInLines(String TheFile) {
return readInLines(new File(TheFile));
}
public static String[] readInLines(File TheFile) {
try {
if(TheFile.getName().endsWith(".gz"))
return readInLines(new InputStreamReader(new GZIPInputStream(new FileInputStream(TheFile))));
else
return readInLines(new FileReader(TheFile));
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String extractQuotedText(String xml, String beforeQuote) {
int loc = xml.indexOf(beforeQuote);
if (loc == -1)
return null;
loc++;
int end = xml.indexOf("\"", loc + 1);
return xml.substring(loc, end);
}
public static String[] extractQuotedTextItems(String xml, String beforeQuote) {
List<String> holder = new ArrayList<String>();
int end = 0;
int loc = xml.indexOf(beforeQuote, end);
while (loc != -1) {
loc++;
end = xml.indexOf("\"", loc + 1);
if (end > -1)
holder.add(xml.substring(loc, end));
}
String[] ret = new String[holder.size()];
holder.toArray(ret);
return ret;
}
public static String[] readInLines(URL url) {
InputStream inp = null;
try {
inp = url.openStream();
return readInLines(inp);
}
catch (IOException e) {
throw new RuntimeException(e);
}
finally {
if (inp != null) {
try {
inp.close();
}
catch (IOException e) {
}
}
}
}
public static String[] readInLines(Reader in) {
try {
LineNumberReader r = new LineNumberReader(in);
List<String> holder = new ArrayList<String>();
String s = r.readLine();
while (s != null) {
holder.add(s);
s = r.readLine();
}
String[] ret = holder.toArray(new String[0]);
r.close();
return (ret);
}
catch (IOException ex) {
throw new IllegalStateException(ex.getMessage());
}
}
public static String[] readInLines(InputStream inp) {
return readInLines(new InputStreamReader(inp));
}
public static GeneVariant[] variantsFromLines(String[] lines) {
List<GeneVariant> holder = new ArrayList<GeneVariant>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
GeneVariant e = variantFromLine(line);
if (e != null)
holder.add(e);
}
GeneVariant[] ret = new GeneVariant[holder.size()];
holder.toArray(ret);
return ret;
}
public static GeneVariant variantFromLine(String line) {
if (line.startsWith("#"))
return null;
String[] items = line.split("\t");
String chromosome = items[0];
long start = Long.parseLong(items[1]);
GeneLocation loc = new GeneLocation(chromosome, start);
String original = items[3];
String changedTo = items[4];
double score = Double.parseDouble(items[5]);
String annotation = items[7];
if (original.length() == 1) {
if (changedTo.length() == 1) {
return new SNPVariation(loc, score, DNABase.valueOf(original), DNABase.valueOf(changedTo), annotation);
}
else {
if (original.contains(",")) //deal with A,AT
original = changedTo.substring(0, 1);
return new InsertionVariation(loc, score, DNABase.valueOf(original), DNABase.fromString(changedTo), annotation);
}
}
else {
if (changedTo.contains(",")) //deal with ATT A,AT
changedTo = changedTo.substring(0, 1);
return new DeletionVariation(loc, score, DNABase.fromString(original), DNABase.valueOf(changedTo), annotation);
}
}
public static MapToGeneRegion readGeneMap(final String geneFile) {
return readGeneMap(new File(geneFile));
}
/**
* fins all varaints common in the list
*
* @param samples
* @param numberCases
* @return
*/
public static GeneVariant[] commonVariants(GeneVariant[] samples, int numberCases) {
Arrays.sort(samples);
if (numberCases == 1)
return samples;
// System.out.println("Looking for common in " + samples.length);
int commonCount = 0;
if (samples.length == 0)
return GeneVariant.EMPTY_ARRAY;
GeneVariant lastSample = null;
List<GeneVariant> holder = new ArrayList<GeneVariant>();
for (int i = 0; i < samples.length; i++) {
GeneVariant sample = samples[i];
if (lastSample != null && lastSample.equivalent(sample)) {
commonCount++;
if (commonCount >= numberCases) {
holder.add(lastSample);
lastSample = null;
}
}
else {
commonCount = 1;
lastSample = sample.asSample();
}
}
GeneVariant[] ret = new GeneVariant[holder.size()];
holder.toArray(ret);
return ret;
}
public static MapToGeneRegion readGeneMap(final File geneFile) {
String[] lines = GeneUtilities.readInLines(geneFile);
GeneRegion[] regions = regionsFromLines(lines);
return new MapToGeneRegion(regions);
}
public static GeneRegion[] regionsFromLines(String[] lines) {
List<GeneRegion> holder = new ArrayList<GeneRegion>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
holder.add(regionFromLine(line));
}
GeneRegion[] ret = new GeneRegion[holder.size()];
holder.toArray(ret);
return ret;
}
/**
* linf like THBS1 chr15:39873279-39889668
*
* @param line
* @return
*/
public static GeneRegion regionFromLine(String line) {
String[] items = line.split("\t");
String gene = items[0];
return new GeneRegion(items[1], items[0]);
}
public static String genomeToAminoAcid(String genome)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < genome.length() - 2; i += 3) {
String cdn = genome.substring(i,i + 3);
Codon codon = Codon.valueOf(cdn);
String aa = codon.getAminoAcid();
if(aa == null)
aa = codon.getAminoAcid(); // break here
sb.append(aa);
}
return sb.toString();
}
public static KnownGene[] knownGeneFromLines(String[] lines) {
List<KnownGene> holder = new ArrayList<KnownGene>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i].trim();
if (line.startsWith("#"))
continue;
if (line.length() == 0)
continue;
KnownGene gene = new KnownGene(line);
holder.add(gene);
}
KnownGene[] ret = new KnownGene[holder.size()];
holder.toArray(ret);
return ret;
}
public static String locationToGenome(GeneInterval loc) {
String fullGenome = chromosomeToGenome( loc.getChromosome());
String me = fullGenome.substring(loc.getStart(),loc.getEnd());
StringBuilder sb = new StringBuilder(me); // force creat new string so large buffer not held
return sb.toString();
}
private static final Map<String, String> gLastGenome = new HashMap<String, String>();
public static String chromosomeToGenome(String chromosome) {
String ret = gLastGenome.get(chromosome);
if (ret != null)
return ret;
ret = readChromosome(chromosome);
gLastGenome.clear();
gLastGenome.put(chromosome, ret);
return ret;
}
public static final String RESOURCE_LOC = "e:/resources/";
private static String readChromosome(String chromosome) {
File f = new File (RESOURCE_LOC + chromosome + ".fa.gz");
String[] strings = GeneUtilities.readInLines(f);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if(string.startsWith(">"))
continue;
sb.append(string);
}
return sb.toString();
}
}
| UTF-8 | Java | 11,127 | java | GeneUtilities.java | Java | [
{
"context": "Utilities\r\n * some useful static methods\r\n * User: Steve\r\n * Date: 6/14/12\r\n */\r\npublic class GeneUtilitie",
"end": 483,
"score": 0.9716289639472961,
"start": 478,
"tag": "NAME",
"value": "Steve"
}
] | null | [] | package org.systemsbiology.gatk;
import com.sun.jndi.toolkit.url.*;
import net.sf.picard.reference.*;
import net.sf.samtools.*;
import org.broadinstitute.sting.gatk.contexts.*;
import org.broadinstitute.sting.gatk.datasources.reference.*;
import org.broadinstitute.sting.utils.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
/**
* PACKAGE_NAME.org.systemsbiology.gatk.GeneUtilities
* some useful static methods
* User: Steve
* Date: 6/14/12
*/
public class GeneUtilities {
public static final GeneUtilities[] EMPTY_ARRAY = {};
private static File gReferenceFile;
private static SAMSequenceDictionary gReferenceDictionary;
public static File getReferenceFile() {
return gReferenceFile;
}
public static void setReferenceFile(File refFile) {
ReferenceDataSource rds = new ReferenceDataSource(refFile);
IndexedFastaSequenceFile reference = rds.getReference();
SAMSequenceDictionary sd = reference.getSequenceDictionary();
setReferenceDictionary(sd);
gReferenceFile = refFile;
}
public static SAMSequenceDictionary getReferenceDictionary() {
return gReferenceDictionary;
}
private static void setReferenceDictionary(SAMSequenceDictionary referenceDictionary) {
gReferenceDictionary = referenceDictionary;
}
public static void guaranteeHeader(SAMFileWriter writer, ReferenceContext ref) {
SAMFileHeader fileHeader = writer.getFileHeader();
SAMSequenceDictionary sd = fileHeader.getSequenceDictionary();
if (sd.getSequences().isEmpty()) {
GenomeLocParser gp = ref.getGenomeLocParser();
}
}
/**
* { method
*
* @param FileName the file name
* @return - array or strings - null if file empty or does not exist
* }
* @name readInLines
* @function reads all the data in a file into an array of strings - one per line
*/
public static String[] readInLines(String TheFile) {
return readInLines(new File(TheFile));
}
public static String[] readInLines(File TheFile) {
try {
if(TheFile.getName().endsWith(".gz"))
return readInLines(new InputStreamReader(new GZIPInputStream(new FileInputStream(TheFile))));
else
return readInLines(new FileReader(TheFile));
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String extractQuotedText(String xml, String beforeQuote) {
int loc = xml.indexOf(beforeQuote);
if (loc == -1)
return null;
loc++;
int end = xml.indexOf("\"", loc + 1);
return xml.substring(loc, end);
}
public static String[] extractQuotedTextItems(String xml, String beforeQuote) {
List<String> holder = new ArrayList<String>();
int end = 0;
int loc = xml.indexOf(beforeQuote, end);
while (loc != -1) {
loc++;
end = xml.indexOf("\"", loc + 1);
if (end > -1)
holder.add(xml.substring(loc, end));
}
String[] ret = new String[holder.size()];
holder.toArray(ret);
return ret;
}
public static String[] readInLines(URL url) {
InputStream inp = null;
try {
inp = url.openStream();
return readInLines(inp);
}
catch (IOException e) {
throw new RuntimeException(e);
}
finally {
if (inp != null) {
try {
inp.close();
}
catch (IOException e) {
}
}
}
}
public static String[] readInLines(Reader in) {
try {
LineNumberReader r = new LineNumberReader(in);
List<String> holder = new ArrayList<String>();
String s = r.readLine();
while (s != null) {
holder.add(s);
s = r.readLine();
}
String[] ret = holder.toArray(new String[0]);
r.close();
return (ret);
}
catch (IOException ex) {
throw new IllegalStateException(ex.getMessage());
}
}
public static String[] readInLines(InputStream inp) {
return readInLines(new InputStreamReader(inp));
}
public static GeneVariant[] variantsFromLines(String[] lines) {
List<GeneVariant> holder = new ArrayList<GeneVariant>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
GeneVariant e = variantFromLine(line);
if (e != null)
holder.add(e);
}
GeneVariant[] ret = new GeneVariant[holder.size()];
holder.toArray(ret);
return ret;
}
public static GeneVariant variantFromLine(String line) {
if (line.startsWith("#"))
return null;
String[] items = line.split("\t");
String chromosome = items[0];
long start = Long.parseLong(items[1]);
GeneLocation loc = new GeneLocation(chromosome, start);
String original = items[3];
String changedTo = items[4];
double score = Double.parseDouble(items[5]);
String annotation = items[7];
if (original.length() == 1) {
if (changedTo.length() == 1) {
return new SNPVariation(loc, score, DNABase.valueOf(original), DNABase.valueOf(changedTo), annotation);
}
else {
if (original.contains(",")) //deal with A,AT
original = changedTo.substring(0, 1);
return new InsertionVariation(loc, score, DNABase.valueOf(original), DNABase.fromString(changedTo), annotation);
}
}
else {
if (changedTo.contains(",")) //deal with ATT A,AT
changedTo = changedTo.substring(0, 1);
return new DeletionVariation(loc, score, DNABase.fromString(original), DNABase.valueOf(changedTo), annotation);
}
}
public static MapToGeneRegion readGeneMap(final String geneFile) {
return readGeneMap(new File(geneFile));
}
/**
* fins all varaints common in the list
*
* @param samples
* @param numberCases
* @return
*/
public static GeneVariant[] commonVariants(GeneVariant[] samples, int numberCases) {
Arrays.sort(samples);
if (numberCases == 1)
return samples;
// System.out.println("Looking for common in " + samples.length);
int commonCount = 0;
if (samples.length == 0)
return GeneVariant.EMPTY_ARRAY;
GeneVariant lastSample = null;
List<GeneVariant> holder = new ArrayList<GeneVariant>();
for (int i = 0; i < samples.length; i++) {
GeneVariant sample = samples[i];
if (lastSample != null && lastSample.equivalent(sample)) {
commonCount++;
if (commonCount >= numberCases) {
holder.add(lastSample);
lastSample = null;
}
}
else {
commonCount = 1;
lastSample = sample.asSample();
}
}
GeneVariant[] ret = new GeneVariant[holder.size()];
holder.toArray(ret);
return ret;
}
public static MapToGeneRegion readGeneMap(final File geneFile) {
String[] lines = GeneUtilities.readInLines(geneFile);
GeneRegion[] regions = regionsFromLines(lines);
return new MapToGeneRegion(regions);
}
public static GeneRegion[] regionsFromLines(String[] lines) {
List<GeneRegion> holder = new ArrayList<GeneRegion>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
holder.add(regionFromLine(line));
}
GeneRegion[] ret = new GeneRegion[holder.size()];
holder.toArray(ret);
return ret;
}
/**
* linf like THBS1 chr15:39873279-39889668
*
* @param line
* @return
*/
public static GeneRegion regionFromLine(String line) {
String[] items = line.split("\t");
String gene = items[0];
return new GeneRegion(items[1], items[0]);
}
public static String genomeToAminoAcid(String genome)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < genome.length() - 2; i += 3) {
String cdn = genome.substring(i,i + 3);
Codon codon = Codon.valueOf(cdn);
String aa = codon.getAminoAcid();
if(aa == null)
aa = codon.getAminoAcid(); // break here
sb.append(aa);
}
return sb.toString();
}
public static KnownGene[] knownGeneFromLines(String[] lines) {
List<KnownGene> holder = new ArrayList<KnownGene>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i].trim();
if (line.startsWith("#"))
continue;
if (line.length() == 0)
continue;
KnownGene gene = new KnownGene(line);
holder.add(gene);
}
KnownGene[] ret = new KnownGene[holder.size()];
holder.toArray(ret);
return ret;
}
public static String locationToGenome(GeneInterval loc) {
String fullGenome = chromosomeToGenome( loc.getChromosome());
String me = fullGenome.substring(loc.getStart(),loc.getEnd());
StringBuilder sb = new StringBuilder(me); // force creat new string so large buffer not held
return sb.toString();
}
private static final Map<String, String> gLastGenome = new HashMap<String, String>();
public static String chromosomeToGenome(String chromosome) {
String ret = gLastGenome.get(chromosome);
if (ret != null)
return ret;
ret = readChromosome(chromosome);
gLastGenome.clear();
gLastGenome.put(chromosome, ret);
return ret;
}
public static final String RESOURCE_LOC = "e:/resources/";
private static String readChromosome(String chromosome) {
File f = new File (RESOURCE_LOC + chromosome + ".fa.gz");
String[] strings = GeneUtilities.readInLines(f);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if(string.startsWith(">"))
continue;
sb.append(string);
}
return sb.toString();
}
}
| 11,127 | 0.555136 | 0.549744 | 340 | 30.726471 | 25.079378 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567647 | false | false | 4 |
3e3978d89078a749b675c404336b5adfe4c209a7 | 12,524,124,642,723 | db6267ac3c7b02fd31f191db8082d201d5695dfa | /src/main/java/promansew/mcmodupdater/Main.java | d6a0c554ebf37f4cae57f9392fd981ce765dc4a2 | [] | no_license | PromanSEW/MinecraftModUpdater | https://github.com/PromanSEW/MinecraftModUpdater | 157f4015733704a7dc6ae427cf211ebbef349146 | fd1421496012b49fc7eeb6c280916c7e6ccc505f | refs/heads/master | 2021-07-11T05:45:13.763000 | 2020-10-14T06:57:16 | 2020-10-14T06:57:16 | 208,254,012 | 0 | 0 | null | false | 2020-10-14T06:57:17 | 2019-09-13T11:47:31 | 2019-09-15T16:39:26 | 2020-10-14T06:57:17 | 22 | 0 | 0 | 0 | Java | false | false | package promansew.mcmodupdater;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import java.util.ResourceBundle;
import static promansew.mcmodupdater.Utils.getResourceBundle;
public class Main extends Application {
public static final ResourceBundle STRINGS = getResourceBundle("Main");
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
if (!MCData.PATH.exists()) {
minecraftNotFound();
return;
}
Parent root = FXMLLoader.load(getClass().getResource("main.fxml"), STRINGS);
stage.setTitle("Minecraft Mod Updater");
stage.setScene(new Scene(root, 854, 480));
stage.show();
}
/** Minecraft не найден */
private void minecraftNotFound() {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(STRINGS.getString("error"));
alert.setHeaderText(null);
alert.setContentText(STRINGS.getString("error.mcnotfound"));
if (!alert.showAndWait().isPresent()) System.exit(0);
}
}
| UTF-8 | Java | 1,135 | java | Main.java | Java | [] | null | [] | package promansew.mcmodupdater;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import java.util.ResourceBundle;
import static promansew.mcmodupdater.Utils.getResourceBundle;
public class Main extends Application {
public static final ResourceBundle STRINGS = getResourceBundle("Main");
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
if (!MCData.PATH.exists()) {
minecraftNotFound();
return;
}
Parent root = FXMLLoader.load(getClass().getResource("main.fxml"), STRINGS);
stage.setTitle("Minecraft Mod Updater");
stage.setScene(new Scene(root, 854, 480));
stage.show();
}
/** Minecraft не найден */
private void minecraftNotFound() {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(STRINGS.getString("error"));
alert.setHeaderText(null);
alert.setContentText(STRINGS.getString("error.mcnotfound"));
if (!alert.showAndWait().isPresent()) System.exit(0);
}
}
| 1,135 | 0.748891 | 0.74268 | 42 | 25.833334 | 21.855495 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.52381 | false | false | 4 |
6587503e832ad51fb48c15c16390ac414b927eda | 30,425,548,336,689 | 3943e17a8b747b085af3830f8954a53790ea4ee5 | /LeetCode/0217_ContainsDuplicate.java | ff9bcef08626ae53d57075dcc18d5d806125a489 | [
"MIT"
] | permissive | HaileyGu/Algorithm | https://github.com/HaileyGu/Algorithm | 63e533778c3d862486fd14cf11184def6f250145 | 229002f27cc3cb4b5ab8785997d0790a892f7741 | refs/heads/master | 2021-11-28T15:26:08.732000 | 2021-11-06T22:43:45 | 2021-11-06T22:43:45 | 173,558,291 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Approach #2 (Sorting) [Accepted]
// Time complexity : O(nlogn)
// Space complexity : O(1), auxiliary space if heapsort is used.
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i = 1; i < nums.length; i++){
if(nums[i] == nums[i-1]){
return true;
}
}
return false;
}
}
// Approach #3 (Hash Table) [Accepted]
// Time complexity : O(n). We do search() and insert() for n times and each operation takes constant time.
// Space complexity : O(n). The space used by a hash table is linear with the number of elements in it.
// class Solution {
// public boolean containsDuplicate(int[] nums) {
// HashSet<Integer> set = new HashSet<>();
// for (int i = 0; i < nums.length; i++) {
// if (!set.add(nums[i])) return true;
// }
// return false;
// }
// }
// class Solution {
// public boolean containsDuplicate(int[] nums) {
// HashSet<Integer> elements = new HashSet<Integer>();
// for(int i = 0; i < nums.length; i++) {
// if(elements.contains(nums[i]))
// return true;
// elements.add((Integer)nums[i]);
// }
// return false;
// }
// }
| UTF-8 | Java | 1,291 | java | 0217_ContainsDuplicate.java | Java | [] | null | [] | // Approach #2 (Sorting) [Accepted]
// Time complexity : O(nlogn)
// Space complexity : O(1), auxiliary space if heapsort is used.
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i = 1; i < nums.length; i++){
if(nums[i] == nums[i-1]){
return true;
}
}
return false;
}
}
// Approach #3 (Hash Table) [Accepted]
// Time complexity : O(n). We do search() and insert() for n times and each operation takes constant time.
// Space complexity : O(n). The space used by a hash table is linear with the number of elements in it.
// class Solution {
// public boolean containsDuplicate(int[] nums) {
// HashSet<Integer> set = new HashSet<>();
// for (int i = 0; i < nums.length; i++) {
// if (!set.add(nums[i])) return true;
// }
// return false;
// }
// }
// class Solution {
// public boolean containsDuplicate(int[] nums) {
// HashSet<Integer> elements = new HashSet<Integer>();
// for(int i = 0; i < nums.length; i++) {
// if(elements.contains(nums[i]))
// return true;
// elements.add((Integer)nums[i]);
// }
// return false;
// }
// }
| 1,291 | 0.538342 | 0.53292 | 42 | 29.738094 | 25.552057 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404762 | false | false | 4 |
14f93b9d022b0c15b9078cc7d293fcb08326fc63 | 13,632,226,207,589 | 0f68e790aa8895fe39bc27f9331cc33929ec98be | /raw_dataset/62164039@dfs@OK.java | 18608fe9bfe027105657d5d6601454785434f34c | [
"MIT"
] | permissive | ruanyuan115/code2vec_treelstm | https://github.com/ruanyuan115/code2vec_treelstm | c50b784cbe2a576905c372675270e95e64908575 | 0c5f98d280b506317738ba603b719cac6036896f | refs/heads/master | 2023-04-09T14:11:02.992000 | 2020-04-16T08:29:59 | 2020-04-16T08:29:59 | 256,151,081 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | void dfs(int[][] g, int[] sub, int u, int p, int anc) {
int max = anc, max1 = 0, max2 = 0;
for (int v : g[u]) {
if (v != p) {
max = Math.max(max, sub[v]);
if (sub[v] > max1) {
max2 = max1;
max1 = sub[v];
} else if (sub[v] > max2) {
max2 = sub[v];
}
}
}
ans = Math.max(ans, max + g[u].length + Math.max(max2 - 1, 0));
for (int v : g[u]) {
if (v != p) {
max = anc;
if (sub[v] == max1) {
max = Math.max(max2, max);
} else {
max = Math.max(max1, max);
}
int rv = max + Math.max(g[u].length - 1, 0);
dfs(g, sub, v, u, rv);
}
}
} | UTF-8 | Java | 779 | java | 62164039@dfs@OK.java | Java | [] | null | [] | void dfs(int[][] g, int[] sub, int u, int p, int anc) {
int max = anc, max1 = 0, max2 = 0;
for (int v : g[u]) {
if (v != p) {
max = Math.max(max, sub[v]);
if (sub[v] > max1) {
max2 = max1;
max1 = sub[v];
} else if (sub[v] > max2) {
max2 = sub[v];
}
}
}
ans = Math.max(ans, max + g[u].length + Math.max(max2 - 1, 0));
for (int v : g[u]) {
if (v != p) {
max = anc;
if (sub[v] == max1) {
max = Math.max(max2, max);
} else {
max = Math.max(max1, max);
}
int rv = max + Math.max(g[u].length - 1, 0);
dfs(g, sub, v, u, rv);
}
}
} | 779 | 0.344031 | 0.320924 | 27 | 27.888889 | 16.175732 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
d11ac633c4aa33966d42db1110e4ce0117d52dea | 30,030,411,365,677 | b845ea95e3e7a4873ca69784a40af894ccc6def3 | /Simple RSS Reader/src/br/com/samirrolemberg/simplerssreader/dialog/DetalhesAnexosPostDialog.java | a337dd3fbae9f694239324676406c3d19951250e | [] | no_license | srolemberg/rss-reader | https://github.com/srolemberg/rss-reader | 3c8ee3baf5887f6b83c6a3a3b1addce59c7f3898 | f276f53e7b093dcc70dd670c9963291b728e3a5d | refs/heads/master | 2021-01-10T03:43:37.926000 | 2016-02-04T16:48:34 | 2016-02-04T16:48:34 | 51,089,976 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.samirrolemberg.simplerssreader.dialog;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import br.com.samirrolemberg.simplerssreader.R;
import br.com.samirrolemberg.simplerssreader.adapter.ListaAnexosPostAdapter;
import br.com.samirrolemberg.simplerssreader.conn.DatabaseManager;
import br.com.samirrolemberg.simplerssreader.dao.DAOAnexo;
import br.com.samirrolemberg.simplerssreader.model.Anexo;
import br.com.samirrolemberg.simplerssreader.model.Post;
public class DetalhesAnexosPostDialog {
private Context context;
private View view;
private Post post;
private ListaAnexosPostAdapter adapter;
public DetalhesAnexosPostDialog(Context context, View view, Post post) {
super();
this.context = context;
this.view = view;
this.post = post;
}
public View create(){
DAOAnexo daoAnexo = new DAOAnexo(context);
List<Anexo> anexos = daoAnexo.listarTudo(post);
adapter = new ListaAnexosPostAdapter(anexos, (Activity)context);
DatabaseManager.getInstance().closeDatabase();
ListView list = (ListView) view.findViewById(R.id.lista_dialogo_anexos_post);
list.setAdapter(adapter);
TextView titulo = (TextView) view.findViewById(R.id.texto_titulo_dialogo_customizado);
titulo.setText("Anexos");
return view;
}
}
| UTF-8 | Java | 1,430 | java | DetalhesAnexosPostDialog.java | Java | [
{
"context": "package br.com.samirrolemberg.simplerssreader.dialog;\r\n\r\nimport java.uti",
"end": 22,
"score": 0.5222899913787842,
"start": 18,
"tag": "USERNAME",
"value": "irro"
},
{
"context": ";\r\nimport android.widget.TextView;\r\nimport br.com.samirrolemberg.simplerssreader.R... | null | [] | package br.com.samirrolemberg.simplerssreader.dialog;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import br.com.samirrolemberg.simplerssreader.R;
import br.com.samirrolemberg.simplerssreader.adapter.ListaAnexosPostAdapter;
import br.com.samirrolemberg.simplerssreader.conn.DatabaseManager;
import br.com.samirrolemberg.simplerssreader.dao.DAOAnexo;
import br.com.samirrolemberg.simplerssreader.model.Anexo;
import br.com.samirrolemberg.simplerssreader.model.Post;
public class DetalhesAnexosPostDialog {
private Context context;
private View view;
private Post post;
private ListaAnexosPostAdapter adapter;
public DetalhesAnexosPostDialog(Context context, View view, Post post) {
super();
this.context = context;
this.view = view;
this.post = post;
}
public View create(){
DAOAnexo daoAnexo = new DAOAnexo(context);
List<Anexo> anexos = daoAnexo.listarTudo(post);
adapter = new ListaAnexosPostAdapter(anexos, (Activity)context);
DatabaseManager.getInstance().closeDatabase();
ListView list = (ListView) view.findViewById(R.id.lista_dialogo_anexos_post);
list.setAdapter(adapter);
TextView titulo = (TextView) view.findViewById(R.id.texto_titulo_dialogo_customizado);
titulo.setText("Anexos");
return view;
}
}
| 1,430 | 0.768531 | 0.768531 | 44 | 30.5 | 24.828045 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.613636 | false | false | 4 |
657d7fb8534addaf2a570f8c3365d94a0a6fbce3 | 24,859,270,749,760 | 225adb7f2df81ebdd870d0b0d9681242b486565b | /src/main/java/com/meetingplanner/model/MeetingRoomInformationList.java | 1c2fd21e80a1908d2d27ee929fa419a910558c29 | [] | no_license | snevula123456/Meeting-Planner | https://github.com/snevula123456/Meeting-Planner | 33d2e3509ebfa9cb605129fab202cd6fe140d23b | 6487a472f268d092c4121c8762e4a1ceb71cba34 | refs/heads/master | 2020-07-04T14:45:28.270000 | 2019-08-14T09:15:52 | 2019-08-14T09:15:52 | 202,315,850 | 0 | 0 | null | false | 2021-01-21T00:13:22 | 2019-08-14T09:12:05 | 2019-08-14T09:16:15 | 2021-01-21T00:13:20 | 41 | 0 | 0 | 8 | JavaScript | false | false | package com.meetingplanner.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="MeetingRoomList",schema="COUNTRYDATA")
public class MeetingRoomInformationList{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
int id;
@Column(name = "MeetingRoomID")
int meetingRoomID;
@Column(name = "MeetingRoomName")
String meetingRoomName;
@Column(name = "Location")
String location;
@Column(name = "MeetingStartTime")
String meetingStartTime;
@Column(name = "MeetingEndTime")
String meetingEndTime;
@Column(name = "BookedBy")
String bookedBy;
@Column(name = "OrganiserEmail")
String organiserEmail;
@Column(name = "Purpose")
String purpose;
public MeetingRoomInformationList(){
super();
}
public MeetingRoomInformationList(int id,int meetingroomID,String meetingRoomName,String location,String meetingStartTime,String meetingEndTime,String bookedBy,
String organiserEmail,String purpose){
super();
this.id=id;
this.meetingRoomID=meetingroomID;
this.meetingRoomName=meetingRoomName;
this.location=location;
this.meetingStartTime=meetingStartTime;
this.meetingEndTime=meetingEndTime;
this.bookedBy=bookedBy;
this.organiserEmail=organiserEmail;
this.purpose=purpose;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMeetingRoomID() {
return meetingRoomID;
}
public void setMeetingRoomID(Integer meetingRoomID) {
this.meetingRoomID = meetingRoomID;
}
public String getMeetingRoomName() {
return meetingRoomName;
}
public void setMeetingRoomName(String meetingRoomName) {
this.meetingRoomName = meetingRoomName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getMeetingStartTime() {
return meetingStartTime;
}
public void setMeetingStartTime(String meetingStartTime) {
this.meetingStartTime = meetingStartTime;
}
public String getMeetingEndTime() {
return meetingEndTime;
}
public void setMeetingEndTime(String meetingEndTime) {
this.meetingEndTime = meetingEndTime;
}
public String getBookedBy() {
return bookedBy;
}
public void setBookedBy(String bookedBy) {
this.bookedBy = bookedBy;
}
public String getOrganiserEmail() {
return organiserEmail;
}
public void setOrganiserEmail(String organiserEmail) {
this.organiserEmail = organiserEmail;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
}
| UTF-8 | Java | 2,884 | java | MeetingRoomInformationList.java | Java | [] | null | [] | package com.meetingplanner.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="MeetingRoomList",schema="COUNTRYDATA")
public class MeetingRoomInformationList{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
int id;
@Column(name = "MeetingRoomID")
int meetingRoomID;
@Column(name = "MeetingRoomName")
String meetingRoomName;
@Column(name = "Location")
String location;
@Column(name = "MeetingStartTime")
String meetingStartTime;
@Column(name = "MeetingEndTime")
String meetingEndTime;
@Column(name = "BookedBy")
String bookedBy;
@Column(name = "OrganiserEmail")
String organiserEmail;
@Column(name = "Purpose")
String purpose;
public MeetingRoomInformationList(){
super();
}
public MeetingRoomInformationList(int id,int meetingroomID,String meetingRoomName,String location,String meetingStartTime,String meetingEndTime,String bookedBy,
String organiserEmail,String purpose){
super();
this.id=id;
this.meetingRoomID=meetingroomID;
this.meetingRoomName=meetingRoomName;
this.location=location;
this.meetingStartTime=meetingStartTime;
this.meetingEndTime=meetingEndTime;
this.bookedBy=bookedBy;
this.organiserEmail=organiserEmail;
this.purpose=purpose;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMeetingRoomID() {
return meetingRoomID;
}
public void setMeetingRoomID(Integer meetingRoomID) {
this.meetingRoomID = meetingRoomID;
}
public String getMeetingRoomName() {
return meetingRoomName;
}
public void setMeetingRoomName(String meetingRoomName) {
this.meetingRoomName = meetingRoomName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getMeetingStartTime() {
return meetingStartTime;
}
public void setMeetingStartTime(String meetingStartTime) {
this.meetingStartTime = meetingStartTime;
}
public String getMeetingEndTime() {
return meetingEndTime;
}
public void setMeetingEndTime(String meetingEndTime) {
this.meetingEndTime = meetingEndTime;
}
public String getBookedBy() {
return bookedBy;
}
public void setBookedBy(String bookedBy) {
this.bookedBy = bookedBy;
}
public String getOrganiserEmail() {
return organiserEmail;
}
public void setOrganiserEmail(String organiserEmail) {
this.organiserEmail = organiserEmail;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
}
| 2,884 | 0.750694 | 0.750694 | 149 | 18.355705 | 21.221134 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.288591 | false | false | 4 |
c7064b4a318de0937853f98f33f39f7e19c992b5 | 24,859,270,751,678 | fa93c9be2923e697fb8a2066f8fb65c7718cdec7 | /sources/com/google/common/util/concurrent/Monitor.java | 08bf5213538b0ad63bf34653554da91d909a5abc | [] | no_license | Auch-Auch/avito_source | https://github.com/Auch-Auch/avito_source | b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b | 76fdcc5b7e036c57ecc193e790b0582481768cdc | refs/heads/master | 2023-05-06T01:32:43.014000 | 2021-05-25T10:19:22 | 2021-05-25T10:19:22 | 370,650,685 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.Weak;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
@Beta
@GwtIncompatible
public final class Monitor {
public final boolean a;
public final ReentrantLock b;
@GuardedBy("lock")
public Guard c;
@Beta
public static abstract class Guard {
@Weak
public final Monitor a;
public final Condition b;
@GuardedBy("monitor.lock")
public int c = 0;
@NullableDecl
@GuardedBy("monitor.lock")
public Guard d;
public Guard(Monitor monitor) {
this.a = (Monitor) Preconditions.checkNotNull(monitor, "monitor");
this.b = monitor.b.newCondition();
}
public abstract boolean isSatisfied();
}
public Monitor() {
this(false);
}
public static long f(long j) {
if (j <= 0) {
return 0;
}
long nanoTime = System.nanoTime();
if (nanoTime == 0) {
return 1;
}
return nanoTime;
}
public static long g(long j, long j2) {
if (j2 <= 0) {
return 0;
}
return j2 - (System.nanoTime() - j);
}
public static long i(long j, TimeUnit timeUnit) {
long nanos = timeUnit.toNanos(j);
if (nanos <= 0) {
return 0;
}
if (nanos > 6917529027641081853L) {
return 6917529027641081853L;
}
return nanos;
}
@GuardedBy("lock")
public final void a(Guard guard, boolean z) throws InterruptedException {
if (z) {
h();
}
d(guard);
do {
try {
guard.b.await();
} finally {
e(guard);
}
} while (!guard.isSatisfied());
}
@GuardedBy("lock")
public final boolean b(Guard guard, long j, boolean z) throws InterruptedException {
boolean z2 = true;
while (j > 0) {
if (z2) {
if (z) {
try {
h();
} catch (Throwable th) {
if (!z2) {
e(guard);
}
throw th;
}
}
d(guard);
z2 = false;
}
j = guard.b.awaitNanos(j);
if (guard.isSatisfied()) {
if (!z2) {
e(guard);
}
return true;
}
}
if (!z2) {
e(guard);
}
return false;
}
@GuardedBy("lock")
public final void c(Guard guard, boolean z) {
if (z) {
h();
}
d(guard);
do {
try {
guard.b.awaitUninterruptibly();
} finally {
e(guard);
}
} while (!guard.isSatisfied());
}
@GuardedBy("lock")
public final void d(Guard guard) {
int i = guard.c;
guard.c = i + 1;
if (i == 0) {
guard.d = this.c;
this.c = guard;
}
}
@GuardedBy("lock")
public final void e(Guard guard) {
int i = guard.c - 1;
guard.c = i;
if (i == 0) {
Guard guard2 = this.c;
Guard guard3 = null;
while (guard2 != guard) {
guard3 = guard2;
guard2 = guard2.d;
}
if (guard3 == null) {
this.c = guard2.d;
} else {
guard3.d = guard2.d;
}
guard2.d = null;
}
}
public void enter() {
this.b.lock();
}
public boolean enterIf(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
reentrantLock.lock();
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
reentrantLock.lockInterruptibly();
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public void enterInterruptibly() throws InterruptedException {
this.b.lockInterruptibly();
}
public void enterWhen(Guard guard) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
boolean isHeldByCurrentThread = reentrantLock.isHeldByCurrentThread();
reentrantLock.lockInterruptibly();
try {
if (!guard.isSatisfied()) {
a(guard, isHeldByCurrentThread);
}
} catch (Throwable th) {
leave();
throw th;
}
} else {
throw new IllegalMonitorStateException();
}
}
public void enterWhenUninterruptibly(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
boolean isHeldByCurrentThread = reentrantLock.isHeldByCurrentThread();
reentrantLock.lock();
try {
if (!guard.isSatisfied()) {
c(guard, isHeldByCurrentThread);
}
} catch (Throwable th) {
leave();
throw th;
}
} else {
throw new IllegalMonitorStateException();
}
}
public int getOccupiedDepth() {
return this.b.getHoldCount();
}
public int getQueueLength() {
return this.b.getQueueLength();
}
public int getWaitQueueLength(Guard guard) {
if (guard.a == this) {
this.b.lock();
try {
return guard.c;
} finally {
this.b.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
@GuardedBy("lock")
public final void h() {
for (Guard guard = this.c; guard != null; guard = guard.d) {
try {
if (guard.isSatisfied()) {
guard.b.signal();
return;
}
} catch (Throwable th) {
for (Guard guard2 = this.c; guard2 != null; guard2 = guard2.d) {
guard2.b.signalAll();
}
throw th;
}
}
}
public boolean hasQueuedThread(Thread thread) {
return this.b.hasQueuedThread(thread);
}
public boolean hasQueuedThreads() {
return this.b.hasQueuedThreads();
}
public boolean hasWaiters(Guard guard) {
return getWaitQueueLength(guard) > 0;
}
public boolean isFair() {
return this.a;
}
public boolean isOccupied() {
return this.b.isLocked();
}
public boolean isOccupiedByCurrentThread() {
return this.b.isHeldByCurrentThread();
}
public void leave() {
ReentrantLock reentrantLock = this.b;
try {
if (reentrantLock.getHoldCount() == 1) {
h();
}
} finally {
reentrantLock.unlock();
}
}
public boolean tryEnter() {
return this.b.tryLock();
}
public boolean tryEnterIf(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
if (!reentrantLock.tryLock()) {
return false;
}
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public void waitFor(Guard guard) throws InterruptedException {
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (!guard.isSatisfied()) {
a(guard, true);
}
}
public void waitForUninterruptibly(Guard guard) {
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (!guard.isSatisfied()) {
c(guard, true);
}
}
public Monitor(boolean z) {
this.c = null;
this.a = z;
this.b = new ReentrantLock(z);
}
/* JADX WARNING: Removed duplicated region for block: B:22:0x0037 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enter(long r8, java.util.concurrent.TimeUnit r10) {
/*
r7 = this;
long r8 = i(r8, r10)
java.util.concurrent.locks.ReentrantLock r10 = r7.b
boolean r0 = r7.a
r1 = 1
if (r0 != 0) goto L_0x0012
boolean r0 = r10.tryLock()
if (r0 == 0) goto L_0x0012
return r1
L_0x0012:
boolean r0 = java.lang.Thread.interrupted()
long r2 = java.lang.System.nanoTime() // Catch:{ all -> 0x0033 }
r4 = r8
L_0x001b:
java.util.concurrent.TimeUnit r6 = java.util.concurrent.TimeUnit.NANOSECONDS // Catch:{ InterruptedException -> 0x002b }
boolean r8 = r10.tryLock(r4, r6) // Catch:{ InterruptedException -> 0x002b }
if (r0 == 0) goto L_0x002a
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x002a:
return r8
L_0x002b:
long r4 = g(r2, r8) // Catch:{ all -> 0x0031 }
r0 = 1
goto L_0x001b
L_0x0031:
r8 = move-exception
goto L_0x0035
L_0x0033:
r8 = move-exception
r1 = r0
L_0x0035:
if (r1 == 0) goto L_0x003e
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x003e:
throw r8
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enter(long, java.util.concurrent.TimeUnit):boolean");
}
public boolean enterInterruptibly(long j, TimeUnit timeUnit) throws InterruptedException {
return this.b.tryLock(j, timeUnit);
}
public boolean waitFor(Guard guard, long j, TimeUnit timeUnit) throws InterruptedException {
long i = i(j, timeUnit);
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (guard.isSatisfied()) {
return true;
} else {
if (!Thread.interrupted()) {
return b(guard, i, true);
}
throw new InterruptedException();
}
}
/* JADX WARNING: Removed duplicated region for block: B:26:0x0050 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean waitForUninterruptibly(com.google.common.util.concurrent.Monitor.Guard r8, long r9, java.util.concurrent.TimeUnit r11) {
/*
r7 = this;
long r9 = i(r9, r11)
com.google.common.util.concurrent.Monitor r11 = r8.a
r0 = 0
r1 = 1
if (r11 != r7) goto L_0x000c
r11 = 1
goto L_0x000d
L_0x000c:
r11 = 0
L_0x000d:
java.util.concurrent.locks.ReentrantLock r2 = r7.b
boolean r2 = r2.isHeldByCurrentThread()
r11 = r11 & r2
if (r11 == 0) goto L_0x0058
boolean r11 = r8.isSatisfied()
if (r11 == 0) goto L_0x001d
return r1
L_0x001d:
long r2 = f(r9)
boolean r11 = java.lang.Thread.interrupted()
r4 = r9
r6 = 1
L_0x0027:
boolean r8 = r7.b(r8, r4, r6) // Catch:{ InterruptedException -> 0x0038, all -> 0x0035 }
if (r11 == 0) goto L_0x0034
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x0034:
return r8
L_0x0035:
r8 = move-exception
r1 = r11
goto L_0x004e
L_0x0038:
boolean r11 = r8.isSatisfied() // Catch:{ all -> 0x004d }
if (r11 == 0) goto L_0x0046
java.lang.Thread r8 = java.lang.Thread.currentThread()
r8.interrupt()
return r1
L_0x0046:
long r4 = g(r2, r9)
r11 = 1
r6 = 0
goto L_0x0027
L_0x004d:
r8 = move-exception
L_0x004e:
if (r1 == 0) goto L_0x0057
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x0057:
throw r8
L_0x0058:
java.lang.IllegalMonitorStateException r8 = new java.lang.IllegalMonitorStateException
r8.<init>()
throw r8
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.waitForUninterruptibly(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
public boolean enterIf(Guard guard, long j, TimeUnit timeUnit) {
if (guard.a != this) {
throw new IllegalMonitorStateException();
} else if (!enter(j, timeUnit)) {
return false;
} else {
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
this.b.unlock();
}
}
}
public boolean enterIfInterruptibly(Guard guard, long j, TimeUnit timeUnit) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
if (!reentrantLock.tryLock(j, timeUnit)) {
return false;
}
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
/* JADX WARNING: Code restructure failed: missing block: B:22:0x0047, code lost:
if (b(r11, r0, r3) != false) goto L_0x0049;
*/
/* JADX WARNING: Removed duplicated region for block: B:17:0x003a A[Catch:{ all -> 0x0050, all -> 0x0057 }] */
/* JADX WARNING: Removed duplicated region for block: B:25:0x004c A[DONT_GENERATE] */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enterWhen(com.google.common.util.concurrent.Monitor.Guard r11, long r12, java.util.concurrent.TimeUnit r14) throws java.lang.InterruptedException {
/*
r10 = this;
long r0 = i(r12, r14)
com.google.common.util.concurrent.Monitor r2 = r11.a
if (r2 != r10) goto L_0x0060
java.util.concurrent.locks.ReentrantLock r2 = r10.b
boolean r3 = r2.isHeldByCurrentThread()
boolean r4 = r10.a
r5 = 0
r6 = 0
if (r4 != 0) goto L_0x0029
boolean r4 = java.lang.Thread.interrupted()
if (r4 != 0) goto L_0x0023
boolean r4 = r2.tryLock()
if (r4 == 0) goto L_0x0029
r8 = r6
goto L_0x0034
L_0x0023:
java.lang.InterruptedException r11 = new java.lang.InterruptedException
r11.<init>()
throw r11
L_0x0029:
long r8 = f(r0)
boolean r12 = r2.tryLock(r12, r14)
if (r12 != 0) goto L_0x0034
return r5
L_0x0034:
boolean r12 = r11.isSatisfied() // Catch:{ all -> 0x0050 }
if (r12 != 0) goto L_0x0049
int r12 = (r8 > r6 ? 1 : (r8 == r6 ? 0 : -1))
if (r12 != 0) goto L_0x003f
goto L_0x0043
L_0x003f:
long r0 = g(r8, r0) // Catch:{ all -> 0x0050 }
L_0x0043:
boolean r11 = r10.b(r11, r0, r3) // Catch:{ all -> 0x0050 }
if (r11 == 0) goto L_0x004a
L_0x0049:
r5 = 1
L_0x004a:
if (r5 != 0) goto L_0x004f
r2.unlock()
L_0x004f:
return r5
L_0x0050:
r11 = move-exception
if (r3 != 0) goto L_0x005c
r10.h() // Catch:{ all -> 0x0057 }
goto L_0x005c
L_0x0057:
r11 = move-exception
r2.unlock()
throw r11
L_0x005c:
r2.unlock()
throw r11
L_0x0060:
java.lang.IllegalMonitorStateException r11 = new java.lang.IllegalMonitorStateException
r11.<init>()
throw r11
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enterWhen(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
/* JADX WARNING: Removed duplicated region for block: B:18:0x0036 A[Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }] */
/* JADX WARNING: Removed duplicated region for block: B:19:0x0037 A[Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }] */
/* JADX WARNING: Removed duplicated region for block: B:25:0x004b */
/* JADX WARNING: Removed duplicated region for block: B:27:0x0050 */
/* JADX WARNING: Removed duplicated region for block: B:45:0x0076 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enterWhenUninterruptibly(com.google.common.util.concurrent.Monitor.Guard r12, long r13, java.util.concurrent.TimeUnit r15) {
/*
r11 = this;
long r13 = i(r13, r15)
com.google.common.util.concurrent.Monitor r15 = r12.a
if (r15 != r11) goto L_0x007e
java.util.concurrent.locks.ReentrantLock r15 = r11.b
boolean r0 = r15.isHeldByCurrentThread()
boolean r1 = java.lang.Thread.interrupted()
r2 = 1
boolean r3 = r11.a // Catch:{ all -> 0x0073 }
r4 = 0
r5 = 0
if (r3 != 0) goto L_0x0023
boolean r3 = r15.tryLock() // Catch:{ all -> 0x0073 }
if (r3 != 0) goto L_0x0021
goto L_0x0023
L_0x0021:
r7 = r5
goto L_0x0030
L_0x0023:
long r7 = f(r13) // Catch:{ all -> 0x0073 }
r9 = r13
L_0x0028:
java.util.concurrent.TimeUnit r3 = java.util.concurrent.TimeUnit.NANOSECONDS // Catch:{ InterruptedException -> 0x006a }
boolean r3 = r15.tryLock(r9, r3) // Catch:{ InterruptedException -> 0x006a }
if (r3 == 0) goto L_0x0060
L_0x0030:
boolean r3 = r12.isSatisfied() // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
if (r3 == 0) goto L_0x0037
goto L_0x0049
L_0x0037:
int r3 = (r7 > r5 ? 1 : (r7 == r5 ? 0 : -1))
if (r3 != 0) goto L_0x0041
long r7 = f(r13) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
r9 = r13
goto L_0x0045
L_0x0041:
long r9 = g(r7, r13) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
L_0x0045:
boolean r2 = r11.b(r12, r9, r0) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
L_0x0049:
if (r2 != 0) goto L_0x004e
r15.unlock()
L_0x004e:
if (r1 == 0) goto L_0x0057
java.lang.Thread r12 = java.lang.Thread.currentThread()
r12.interrupt()
L_0x0057:
return r2
L_0x0058:
r12 = move-exception
r15.unlock()
throw r12
L_0x005d:
r0 = 0
r1 = 1
goto L_0x0030
L_0x0060:
if (r1 == 0) goto L_0x0069
java.lang.Thread r12 = java.lang.Thread.currentThread()
r12.interrupt()
L_0x0069:
return r4
L_0x006a:
long r9 = g(r7, r13) // Catch:{ all -> 0x0070 }
r1 = 1
goto L_0x0028
L_0x0070:
r12 = move-exception
r1 = 1
goto L_0x0074
L_0x0073:
r12 = move-exception
L_0x0074:
if (r1 == 0) goto L_0x007d
java.lang.Thread r13 = java.lang.Thread.currentThread()
r13.interrupt()
L_0x007d:
throw r12
L_0x007e:
java.lang.IllegalMonitorStateException r12 = new java.lang.IllegalMonitorStateException
r12.<init>()
throw r12
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enterWhenUninterruptibly(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
}
| UTF-8 | Java | 22,371 | java | Monitor.java | Java | [] | null | [] | package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.Weak;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
@Beta
@GwtIncompatible
public final class Monitor {
public final boolean a;
public final ReentrantLock b;
@GuardedBy("lock")
public Guard c;
@Beta
public static abstract class Guard {
@Weak
public final Monitor a;
public final Condition b;
@GuardedBy("monitor.lock")
public int c = 0;
@NullableDecl
@GuardedBy("monitor.lock")
public Guard d;
public Guard(Monitor monitor) {
this.a = (Monitor) Preconditions.checkNotNull(monitor, "monitor");
this.b = monitor.b.newCondition();
}
public abstract boolean isSatisfied();
}
public Monitor() {
this(false);
}
public static long f(long j) {
if (j <= 0) {
return 0;
}
long nanoTime = System.nanoTime();
if (nanoTime == 0) {
return 1;
}
return nanoTime;
}
public static long g(long j, long j2) {
if (j2 <= 0) {
return 0;
}
return j2 - (System.nanoTime() - j);
}
public static long i(long j, TimeUnit timeUnit) {
long nanos = timeUnit.toNanos(j);
if (nanos <= 0) {
return 0;
}
if (nanos > 6917529027641081853L) {
return 6917529027641081853L;
}
return nanos;
}
@GuardedBy("lock")
public final void a(Guard guard, boolean z) throws InterruptedException {
if (z) {
h();
}
d(guard);
do {
try {
guard.b.await();
} finally {
e(guard);
}
} while (!guard.isSatisfied());
}
@GuardedBy("lock")
public final boolean b(Guard guard, long j, boolean z) throws InterruptedException {
boolean z2 = true;
while (j > 0) {
if (z2) {
if (z) {
try {
h();
} catch (Throwable th) {
if (!z2) {
e(guard);
}
throw th;
}
}
d(guard);
z2 = false;
}
j = guard.b.awaitNanos(j);
if (guard.isSatisfied()) {
if (!z2) {
e(guard);
}
return true;
}
}
if (!z2) {
e(guard);
}
return false;
}
@GuardedBy("lock")
public final void c(Guard guard, boolean z) {
if (z) {
h();
}
d(guard);
do {
try {
guard.b.awaitUninterruptibly();
} finally {
e(guard);
}
} while (!guard.isSatisfied());
}
@GuardedBy("lock")
public final void d(Guard guard) {
int i = guard.c;
guard.c = i + 1;
if (i == 0) {
guard.d = this.c;
this.c = guard;
}
}
@GuardedBy("lock")
public final void e(Guard guard) {
int i = guard.c - 1;
guard.c = i;
if (i == 0) {
Guard guard2 = this.c;
Guard guard3 = null;
while (guard2 != guard) {
guard3 = guard2;
guard2 = guard2.d;
}
if (guard3 == null) {
this.c = guard2.d;
} else {
guard3.d = guard2.d;
}
guard2.d = null;
}
}
public void enter() {
this.b.lock();
}
public boolean enterIf(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
reentrantLock.lock();
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
reentrantLock.lockInterruptibly();
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public void enterInterruptibly() throws InterruptedException {
this.b.lockInterruptibly();
}
public void enterWhen(Guard guard) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
boolean isHeldByCurrentThread = reentrantLock.isHeldByCurrentThread();
reentrantLock.lockInterruptibly();
try {
if (!guard.isSatisfied()) {
a(guard, isHeldByCurrentThread);
}
} catch (Throwable th) {
leave();
throw th;
}
} else {
throw new IllegalMonitorStateException();
}
}
public void enterWhenUninterruptibly(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
boolean isHeldByCurrentThread = reentrantLock.isHeldByCurrentThread();
reentrantLock.lock();
try {
if (!guard.isSatisfied()) {
c(guard, isHeldByCurrentThread);
}
} catch (Throwable th) {
leave();
throw th;
}
} else {
throw new IllegalMonitorStateException();
}
}
public int getOccupiedDepth() {
return this.b.getHoldCount();
}
public int getQueueLength() {
return this.b.getQueueLength();
}
public int getWaitQueueLength(Guard guard) {
if (guard.a == this) {
this.b.lock();
try {
return guard.c;
} finally {
this.b.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
@GuardedBy("lock")
public final void h() {
for (Guard guard = this.c; guard != null; guard = guard.d) {
try {
if (guard.isSatisfied()) {
guard.b.signal();
return;
}
} catch (Throwable th) {
for (Guard guard2 = this.c; guard2 != null; guard2 = guard2.d) {
guard2.b.signalAll();
}
throw th;
}
}
}
public boolean hasQueuedThread(Thread thread) {
return this.b.hasQueuedThread(thread);
}
public boolean hasQueuedThreads() {
return this.b.hasQueuedThreads();
}
public boolean hasWaiters(Guard guard) {
return getWaitQueueLength(guard) > 0;
}
public boolean isFair() {
return this.a;
}
public boolean isOccupied() {
return this.b.isLocked();
}
public boolean isOccupiedByCurrentThread() {
return this.b.isHeldByCurrentThread();
}
public void leave() {
ReentrantLock reentrantLock = this.b;
try {
if (reentrantLock.getHoldCount() == 1) {
h();
}
} finally {
reentrantLock.unlock();
}
}
public boolean tryEnter() {
return this.b.tryLock();
}
public boolean tryEnterIf(Guard guard) {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
if (!reentrantLock.tryLock()) {
return false;
}
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
public void waitFor(Guard guard) throws InterruptedException {
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (!guard.isSatisfied()) {
a(guard, true);
}
}
public void waitForUninterruptibly(Guard guard) {
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (!guard.isSatisfied()) {
c(guard, true);
}
}
public Monitor(boolean z) {
this.c = null;
this.a = z;
this.b = new ReentrantLock(z);
}
/* JADX WARNING: Removed duplicated region for block: B:22:0x0037 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enter(long r8, java.util.concurrent.TimeUnit r10) {
/*
r7 = this;
long r8 = i(r8, r10)
java.util.concurrent.locks.ReentrantLock r10 = r7.b
boolean r0 = r7.a
r1 = 1
if (r0 != 0) goto L_0x0012
boolean r0 = r10.tryLock()
if (r0 == 0) goto L_0x0012
return r1
L_0x0012:
boolean r0 = java.lang.Thread.interrupted()
long r2 = java.lang.System.nanoTime() // Catch:{ all -> 0x0033 }
r4 = r8
L_0x001b:
java.util.concurrent.TimeUnit r6 = java.util.concurrent.TimeUnit.NANOSECONDS // Catch:{ InterruptedException -> 0x002b }
boolean r8 = r10.tryLock(r4, r6) // Catch:{ InterruptedException -> 0x002b }
if (r0 == 0) goto L_0x002a
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x002a:
return r8
L_0x002b:
long r4 = g(r2, r8) // Catch:{ all -> 0x0031 }
r0 = 1
goto L_0x001b
L_0x0031:
r8 = move-exception
goto L_0x0035
L_0x0033:
r8 = move-exception
r1 = r0
L_0x0035:
if (r1 == 0) goto L_0x003e
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x003e:
throw r8
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enter(long, java.util.concurrent.TimeUnit):boolean");
}
public boolean enterInterruptibly(long j, TimeUnit timeUnit) throws InterruptedException {
return this.b.tryLock(j, timeUnit);
}
public boolean waitFor(Guard guard, long j, TimeUnit timeUnit) throws InterruptedException {
long i = i(j, timeUnit);
if (!(guard.a == this) || !this.b.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
} else if (guard.isSatisfied()) {
return true;
} else {
if (!Thread.interrupted()) {
return b(guard, i, true);
}
throw new InterruptedException();
}
}
/* JADX WARNING: Removed duplicated region for block: B:26:0x0050 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean waitForUninterruptibly(com.google.common.util.concurrent.Monitor.Guard r8, long r9, java.util.concurrent.TimeUnit r11) {
/*
r7 = this;
long r9 = i(r9, r11)
com.google.common.util.concurrent.Monitor r11 = r8.a
r0 = 0
r1 = 1
if (r11 != r7) goto L_0x000c
r11 = 1
goto L_0x000d
L_0x000c:
r11 = 0
L_0x000d:
java.util.concurrent.locks.ReentrantLock r2 = r7.b
boolean r2 = r2.isHeldByCurrentThread()
r11 = r11 & r2
if (r11 == 0) goto L_0x0058
boolean r11 = r8.isSatisfied()
if (r11 == 0) goto L_0x001d
return r1
L_0x001d:
long r2 = f(r9)
boolean r11 = java.lang.Thread.interrupted()
r4 = r9
r6 = 1
L_0x0027:
boolean r8 = r7.b(r8, r4, r6) // Catch:{ InterruptedException -> 0x0038, all -> 0x0035 }
if (r11 == 0) goto L_0x0034
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x0034:
return r8
L_0x0035:
r8 = move-exception
r1 = r11
goto L_0x004e
L_0x0038:
boolean r11 = r8.isSatisfied() // Catch:{ all -> 0x004d }
if (r11 == 0) goto L_0x0046
java.lang.Thread r8 = java.lang.Thread.currentThread()
r8.interrupt()
return r1
L_0x0046:
long r4 = g(r2, r9)
r11 = 1
r6 = 0
goto L_0x0027
L_0x004d:
r8 = move-exception
L_0x004e:
if (r1 == 0) goto L_0x0057
java.lang.Thread r9 = java.lang.Thread.currentThread()
r9.interrupt()
L_0x0057:
throw r8
L_0x0058:
java.lang.IllegalMonitorStateException r8 = new java.lang.IllegalMonitorStateException
r8.<init>()
throw r8
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.waitForUninterruptibly(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
public boolean enterIf(Guard guard, long j, TimeUnit timeUnit) {
if (guard.a != this) {
throw new IllegalMonitorStateException();
} else if (!enter(j, timeUnit)) {
return false;
} else {
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
this.b.unlock();
}
}
}
public boolean enterIfInterruptibly(Guard guard, long j, TimeUnit timeUnit) throws InterruptedException {
if (guard.a == this) {
ReentrantLock reentrantLock = this.b;
if (!reentrantLock.tryLock(j, timeUnit)) {
return false;
}
try {
boolean isSatisfied = guard.isSatisfied();
if (!isSatisfied) {
}
return isSatisfied;
} finally {
reentrantLock.unlock();
}
} else {
throw new IllegalMonitorStateException();
}
}
/* JADX WARNING: Code restructure failed: missing block: B:22:0x0047, code lost:
if (b(r11, r0, r3) != false) goto L_0x0049;
*/
/* JADX WARNING: Removed duplicated region for block: B:17:0x003a A[Catch:{ all -> 0x0050, all -> 0x0057 }] */
/* JADX WARNING: Removed duplicated region for block: B:25:0x004c A[DONT_GENERATE] */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enterWhen(com.google.common.util.concurrent.Monitor.Guard r11, long r12, java.util.concurrent.TimeUnit r14) throws java.lang.InterruptedException {
/*
r10 = this;
long r0 = i(r12, r14)
com.google.common.util.concurrent.Monitor r2 = r11.a
if (r2 != r10) goto L_0x0060
java.util.concurrent.locks.ReentrantLock r2 = r10.b
boolean r3 = r2.isHeldByCurrentThread()
boolean r4 = r10.a
r5 = 0
r6 = 0
if (r4 != 0) goto L_0x0029
boolean r4 = java.lang.Thread.interrupted()
if (r4 != 0) goto L_0x0023
boolean r4 = r2.tryLock()
if (r4 == 0) goto L_0x0029
r8 = r6
goto L_0x0034
L_0x0023:
java.lang.InterruptedException r11 = new java.lang.InterruptedException
r11.<init>()
throw r11
L_0x0029:
long r8 = f(r0)
boolean r12 = r2.tryLock(r12, r14)
if (r12 != 0) goto L_0x0034
return r5
L_0x0034:
boolean r12 = r11.isSatisfied() // Catch:{ all -> 0x0050 }
if (r12 != 0) goto L_0x0049
int r12 = (r8 > r6 ? 1 : (r8 == r6 ? 0 : -1))
if (r12 != 0) goto L_0x003f
goto L_0x0043
L_0x003f:
long r0 = g(r8, r0) // Catch:{ all -> 0x0050 }
L_0x0043:
boolean r11 = r10.b(r11, r0, r3) // Catch:{ all -> 0x0050 }
if (r11 == 0) goto L_0x004a
L_0x0049:
r5 = 1
L_0x004a:
if (r5 != 0) goto L_0x004f
r2.unlock()
L_0x004f:
return r5
L_0x0050:
r11 = move-exception
if (r3 != 0) goto L_0x005c
r10.h() // Catch:{ all -> 0x0057 }
goto L_0x005c
L_0x0057:
r11 = move-exception
r2.unlock()
throw r11
L_0x005c:
r2.unlock()
throw r11
L_0x0060:
java.lang.IllegalMonitorStateException r11 = new java.lang.IllegalMonitorStateException
r11.<init>()
throw r11
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enterWhen(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
/* JADX WARNING: Removed duplicated region for block: B:18:0x0036 A[Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }] */
/* JADX WARNING: Removed duplicated region for block: B:19:0x0037 A[Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }] */
/* JADX WARNING: Removed duplicated region for block: B:25:0x004b */
/* JADX WARNING: Removed duplicated region for block: B:27:0x0050 */
/* JADX WARNING: Removed duplicated region for block: B:45:0x0076 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean enterWhenUninterruptibly(com.google.common.util.concurrent.Monitor.Guard r12, long r13, java.util.concurrent.TimeUnit r15) {
/*
r11 = this;
long r13 = i(r13, r15)
com.google.common.util.concurrent.Monitor r15 = r12.a
if (r15 != r11) goto L_0x007e
java.util.concurrent.locks.ReentrantLock r15 = r11.b
boolean r0 = r15.isHeldByCurrentThread()
boolean r1 = java.lang.Thread.interrupted()
r2 = 1
boolean r3 = r11.a // Catch:{ all -> 0x0073 }
r4 = 0
r5 = 0
if (r3 != 0) goto L_0x0023
boolean r3 = r15.tryLock() // Catch:{ all -> 0x0073 }
if (r3 != 0) goto L_0x0021
goto L_0x0023
L_0x0021:
r7 = r5
goto L_0x0030
L_0x0023:
long r7 = f(r13) // Catch:{ all -> 0x0073 }
r9 = r13
L_0x0028:
java.util.concurrent.TimeUnit r3 = java.util.concurrent.TimeUnit.NANOSECONDS // Catch:{ InterruptedException -> 0x006a }
boolean r3 = r15.tryLock(r9, r3) // Catch:{ InterruptedException -> 0x006a }
if (r3 == 0) goto L_0x0060
L_0x0030:
boolean r3 = r12.isSatisfied() // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
if (r3 == 0) goto L_0x0037
goto L_0x0049
L_0x0037:
int r3 = (r7 > r5 ? 1 : (r7 == r5 ? 0 : -1))
if (r3 != 0) goto L_0x0041
long r7 = f(r13) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
r9 = r13
goto L_0x0045
L_0x0041:
long r9 = g(r7, r13) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
L_0x0045:
boolean r2 = r11.b(r12, r9, r0) // Catch:{ InterruptedException -> 0x005d, all -> 0x0058 }
L_0x0049:
if (r2 != 0) goto L_0x004e
r15.unlock()
L_0x004e:
if (r1 == 0) goto L_0x0057
java.lang.Thread r12 = java.lang.Thread.currentThread()
r12.interrupt()
L_0x0057:
return r2
L_0x0058:
r12 = move-exception
r15.unlock()
throw r12
L_0x005d:
r0 = 0
r1 = 1
goto L_0x0030
L_0x0060:
if (r1 == 0) goto L_0x0069
java.lang.Thread r12 = java.lang.Thread.currentThread()
r12.interrupt()
L_0x0069:
return r4
L_0x006a:
long r9 = g(r7, r13) // Catch:{ all -> 0x0070 }
r1 = 1
goto L_0x0028
L_0x0070:
r12 = move-exception
r1 = 1
goto L_0x0074
L_0x0073:
r12 = move-exception
L_0x0074:
if (r1 == 0) goto L_0x007d
java.lang.Thread r13 = java.lang.Thread.currentThread()
r13.interrupt()
L_0x007d:
throw r12
L_0x007e:
java.lang.IllegalMonitorStateException r12 = new java.lang.IllegalMonitorStateException
r12.<init>()
throw r12
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.common.util.concurrent.Monitor.enterWhenUninterruptibly(com.google.common.util.concurrent.Monitor$Guard, long, java.util.concurrent.TimeUnit):boolean");
}
}
| 22,371 | 0.508873 | 0.456752 | 688 | 31.515989 | 27.820433 | 235 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338663 | false | false | 4 |
faec6d3282ad462aa08e14e26309311eadbfaf77 | 28,982,439,328,290 | 8fadb696ff2ed92bd4cab6db091d54e49f7c7e52 | /app/src/main/java/com/wemgmemgfang/bt/ui/fragment/DownRankingFragment.java | 466223214aa262042e97234289995c64cdb7190c | [] | no_license | sayid0927/tt | https://github.com/sayid0927/tt | d7c32813dcc78e29f8df65d84dcf0bcd7525c00a | 27f7e2b0d0e3f8b14185bc0da9fb44f8bc8db43f | refs/heads/master | 2021-04-18T19:33:37.412000 | 2018-05-13T16:36:32 | 2018-05-13T16:36:32 | 126,700,082 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wemgmemgfang.bt.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wemgmemgfang.bt.R;
import com.wemgmemgfang.bt.base.BaseFragment;
import com.wemgmemgfang.bt.base.Constant;
import com.wemgmemgfang.bt.bean.DownRaningBean;
import com.wemgmemgfang.bt.component.AppComponent;
import com.wemgmemgfang.bt.component.DaggerMainComponent;
import com.wemgmemgfang.bt.presenter.contract.DownRankingContract;
import com.wemgmemgfang.bt.presenter.impl.DownRankingPresenter;
import com.wemgmemgfang.bt.ui.activity.DownListActivity;
import com.wemgmemgfang.bt.ui.activity.MainActivity;
import com.wemgmemgfang.bt.ui.activity.ViewBoxActivity;
import com.wemgmemgfang.bt.ui.adapter.DownRanking_Adapter;
import com.wemgmemgfang.bt.utils.UmengUtil;
import com.wemgmemgfang.bt.view.MyLoadMoreView;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
/**
* sayid ....
* Created by wengmf on 2018/3/12.
*/
public class DownRankingFragment extends BaseFragment implements DownRankingContract.View,BaseQuickAdapter.RequestLoadMoreListener,
SwipeRefreshLayout.OnRefreshListener {
@Inject
DownRankingPresenter mPresenter;
@BindView(R.id.title_list)
RecyclerView rvList;
@BindView(R.id.srl_android)
SwipeRefreshLayout srlAndroid;
private DownRanking_Adapter mAdapter;
private List<DownRaningBean> dataBean;
private static String DownRankingUrl = "http://www.zei8.me/movie/lunli/";
// private static String DownRankingUrl = "http://www.bttwo.com/movie/20741.html";
private boolean isRefresh = false;
private int index = 1;
@Override
public void loadData() {
mPresenter.Fetch_DownRankingInfo(DownRankingUrl);
}
@Override
public int getLayoutResId() {
return R.layout.fragment_downranking;
}
@Override
protected void initView(Bundle bundle) {
UmengUtil.onEvent("DownRankingFragment");
mAdapter = new DownRanking_Adapter(dataBean, getSupportActivity());
mAdapter.setOnLoadMoreListener(DownRankingFragment.this, rvList);
mAdapter.setLoadMoreView(new MyLoadMoreView());
srlAndroid.setOnRefreshListener(this);
rvList.setLayoutManager(new GridLayoutManager(getSupportActivity(), 1));
rvList.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new DownRanking_Adapter.OnItemClickListener() {
@Override
public void onItemClickListener(DownRaningBean item) {
Intent intent = new Intent(getActivity(), ViewBoxActivity.class);
intent.putExtra("HrefUrl",item.getHref());
intent.putExtra("ImgUrl",item.getImgUrl());
MainActivity.mainActivity.startActivityIn(intent,getActivity());
}
});
}
@Override
public void attachView() {
mPresenter.attachView(this);
}
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerMainComponent.builder().appComponent(appComponent).build().inject(this);
}
@Override
public void onRefresh() {
isRefresh = true;
mAdapter.setEnableLoadMore(false);
mPresenter.Fetch_DownRankingInfo(DownRankingUrl);
}
@Override
public void showError(String message) {
UmengUtil.onEvent("showError_DownRankingFragment");
}
@Override
public void Fetch_DownRankingInfo_Success(List<DownRaningBean> dataBean) {
if (isRefresh) {
srlAndroid.setRefreshing(false);
mAdapter.setEnableLoadMore(true);
isRefresh = false;
mAdapter.setNewData(dataBean);
} else {
setState(Constant.STATE_SUCCESS);
srlAndroid.setEnabled(true);
mAdapter.addData(dataBean);
mAdapter.loadMoreComplete();
}
}
@Override
public void onLoadMoreRequested() {
if (index < 46) {
index++;
mPresenter.Fetch_DownRankingInfo(DownRankingUrl + "index_" +index+ ".html");
srlAndroid.setEnabled(false);
}
}
}
| UTF-8 | Java | 4,335 | java | DownRankingFragment.java | Java | [
{
"context": "erknife.BindView;\n\n/**\n * sayid ....\n * Created by wengmf on 2018/3/12.\n */\n\npublic class DownRankingFragme",
"end": 1152,
"score": 0.9996649622917175,
"start": 1146,
"tag": "USERNAME",
"value": "wengmf"
}
] | null | [] | package com.wemgmemgfang.bt.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wemgmemgfang.bt.R;
import com.wemgmemgfang.bt.base.BaseFragment;
import com.wemgmemgfang.bt.base.Constant;
import com.wemgmemgfang.bt.bean.DownRaningBean;
import com.wemgmemgfang.bt.component.AppComponent;
import com.wemgmemgfang.bt.component.DaggerMainComponent;
import com.wemgmemgfang.bt.presenter.contract.DownRankingContract;
import com.wemgmemgfang.bt.presenter.impl.DownRankingPresenter;
import com.wemgmemgfang.bt.ui.activity.DownListActivity;
import com.wemgmemgfang.bt.ui.activity.MainActivity;
import com.wemgmemgfang.bt.ui.activity.ViewBoxActivity;
import com.wemgmemgfang.bt.ui.adapter.DownRanking_Adapter;
import com.wemgmemgfang.bt.utils.UmengUtil;
import com.wemgmemgfang.bt.view.MyLoadMoreView;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
/**
* sayid ....
* Created by wengmf on 2018/3/12.
*/
public class DownRankingFragment extends BaseFragment implements DownRankingContract.View,BaseQuickAdapter.RequestLoadMoreListener,
SwipeRefreshLayout.OnRefreshListener {
@Inject
DownRankingPresenter mPresenter;
@BindView(R.id.title_list)
RecyclerView rvList;
@BindView(R.id.srl_android)
SwipeRefreshLayout srlAndroid;
private DownRanking_Adapter mAdapter;
private List<DownRaningBean> dataBean;
private static String DownRankingUrl = "http://www.zei8.me/movie/lunli/";
// private static String DownRankingUrl = "http://www.bttwo.com/movie/20741.html";
private boolean isRefresh = false;
private int index = 1;
@Override
public void loadData() {
mPresenter.Fetch_DownRankingInfo(DownRankingUrl);
}
@Override
public int getLayoutResId() {
return R.layout.fragment_downranking;
}
@Override
protected void initView(Bundle bundle) {
UmengUtil.onEvent("DownRankingFragment");
mAdapter = new DownRanking_Adapter(dataBean, getSupportActivity());
mAdapter.setOnLoadMoreListener(DownRankingFragment.this, rvList);
mAdapter.setLoadMoreView(new MyLoadMoreView());
srlAndroid.setOnRefreshListener(this);
rvList.setLayoutManager(new GridLayoutManager(getSupportActivity(), 1));
rvList.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new DownRanking_Adapter.OnItemClickListener() {
@Override
public void onItemClickListener(DownRaningBean item) {
Intent intent = new Intent(getActivity(), ViewBoxActivity.class);
intent.putExtra("HrefUrl",item.getHref());
intent.putExtra("ImgUrl",item.getImgUrl());
MainActivity.mainActivity.startActivityIn(intent,getActivity());
}
});
}
@Override
public void attachView() {
mPresenter.attachView(this);
}
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerMainComponent.builder().appComponent(appComponent).build().inject(this);
}
@Override
public void onRefresh() {
isRefresh = true;
mAdapter.setEnableLoadMore(false);
mPresenter.Fetch_DownRankingInfo(DownRankingUrl);
}
@Override
public void showError(String message) {
UmengUtil.onEvent("showError_DownRankingFragment");
}
@Override
public void Fetch_DownRankingInfo_Success(List<DownRaningBean> dataBean) {
if (isRefresh) {
srlAndroid.setRefreshing(false);
mAdapter.setEnableLoadMore(true);
isRefresh = false;
mAdapter.setNewData(dataBean);
} else {
setState(Constant.STATE_SUCCESS);
srlAndroid.setEnabled(true);
mAdapter.addData(dataBean);
mAdapter.loadMoreComplete();
}
}
@Override
public void onLoadMoreRequested() {
if (index < 46) {
index++;
mPresenter.Fetch_DownRankingInfo(DownRankingUrl + "index_" +index+ ".html");
srlAndroid.setEnabled(false);
}
}
}
| 4,335 | 0.70519 | 0.700577 | 137 | 30.642336 | 26.50733 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532847 | false | false | 4 |
84841dc211139eea10101a6dc595b855dfe6a8a9 | 15,367,393,053,489 | ee318deacac4a9f6896d8053ed04a8f820211696 | /src/main/java/com/example/sapBusinessApp/domain/User.java | 4c9232fc6b065a28fa56a3ec56a20d450a322a73 | [] | no_license | bopan8/BusinessApp | https://github.com/bopan8/BusinessApp | 1987229afacbd19718fa27db444aecce0d0ee2c1 | 95979f82c7a9c1d52ad0ba54df79c4a808b229ff | refs/heads/master | 2023-03-06T13:49:56.584000 | 2021-02-13T19:35:38 | 2021-02-13T19:35:38 | 338,648,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sapBusinessApp.domain;
public interface User {
public void setId(int id);
public int getId();
public String getName();
public void setName(String name);
public String getPassword();
public void setPassword(String password);
public String getRole();
}
| UTF-8 | Java | 307 | java | User.java | Java | [] | null | [] | package com.example.sapBusinessApp.domain;
public interface User {
public void setId(int id);
public int getId();
public String getName();
public void setName(String name);
public String getPassword();
public void setPassword(String password);
public String getRole();
}
| 307 | 0.693811 | 0.693811 | 18 | 16.055555 | 16.781181 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 4 |
d9bb128e86c25ae4e7f9ad25483b2ee1d2bfae28 | 15,367,393,055,079 | df00aab0a65d291e5e774a36e33f9f0a06d47757 | /algEstrutI/src/tads/GeneralTreeOfInteger.java | b1e8654a6457dc1fb4f74290e67b02948a15379a | [] | no_license | grupodobaralho/AlgEstrutI | https://github.com/grupodobaralho/AlgEstrutI | a4c9746bd0b951d8e725869da60000092c6b1030 | 4cb9eac443e99b28dc33972def9cf9bac4a38935 | refs/heads/master | 2021-01-12T08:01:03.254000 | 2016-11-23T08:44:58 | 2016-11-23T08:44:58 | 77,099,746 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tads;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GeneralTreeOfInteger {
private static final class Node{
public Node father;
public Integer element;
public ArrayList<Node> subtrees;
public Node(Integer element){
this.father = null;
this.element = element;
subtrees = new ArrayList<>();
}
public void addSubtree(Node n){
n.father = this;
subtrees.add(n);
}
public boolean removeSubtree(Node n){
n.father = null;
return subtrees.remove(n);
}
public Node getSubtree(int i){
if(i >= 0 && i < subtrees.size()) {
return subtrees.get(i);
}
return null;
}
public int getSubtreeSize(){
return subtrees.size();
}
@Override
public String toString() {
return "Node [father=" + father + ", element=" + element + ", subtrees=" + subtrees + "]";
}
}
private Node root;
private int count;
//Construtor
public GeneralTreeOfInteger(){
root = null;
count = 0;
}
//Retorna a referência pro Node que possui element
private Node searchNodeRef(Integer e){
return searchNodeRef(e, root);
}
//método auxiliar recursivo
private Node searchNodeRef(Integer element, Node target){
Node n = null;
if(target != null){
if(element.equals(target.element)){
n = target;
} else {
int i = 0;
Node aux = null;
while(aux == null && i<target.getSubtreeSize()) {
aux = searchNodeRef(element, target.getSubtree(i));
i++;
n = aux;
}
}
return n;
}
return null;
}
//insere o elemento e como filho de f
public boolean add(Integer e, Integer f){
try{
searchNodeRef(f).addSubtree(new Node(e));
count++;
return true;
} catch (Exception exc) {
return false;
}
}
//retorna o elemento armazenado na raiz
public Integer getRoot(){
if(root != null) {
return root.element;
}
return null;
}
//cria a raíz, se já existir altera o elemento armazenado na raiz
public void setRoot(Integer e){
if(root == null) {
root = new Node(e);
count++;
} else {
root.element = e;
}
}
//retorna o pai do elemento e
public Integer getParent(Integer e){
try{
return searchNodeRef(e).father.element;
} catch (Exception exc) {
return null;
}
}
//remove o elemento e e seus filhos
public boolean removeBranch(Integer e){
try{
Node n = searchNodeRef(e);
ArrayList<Integer> lista = new ArrayList<>();
positionsPosAux(n, lista);
count = count - lista.size();
return n.father.removeSubtree(n);
} catch (Exception exc) {
return false;
}
}
//retorna true se a árvore contém o elemento
public boolean contains(Integer e){
try{
return searchNodeRef(e) != null;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento está armazenado em um nodo interno
public boolean isInternal(Integer e){
try{
return searchNodeRef(e).getSubtreeSize() > 0;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento está armazenado em um nodo externo
public boolean isExternal(Integer e){
try{
return searchNodeRef(e).getSubtreeSize() == 0;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento e está armazenado na raiz
public boolean isRoot(Integer e){
try{
return root.element.equals(e);
} catch (Exception exc) {
return false;
}
}
//retorna true se a árvore está vazia
public boolean isEmpty(){
return count == 0;
}
//retorna o número de elementos armazenados na árvore
public int size(){
return count;
}
//remove todos os elementos da árvore
public void clear(){
root = null;
count = 0;
}
//retorna uma lista com todos os elementos da árvore na ordem pré-fixada
public ArrayList<Integer> positionsPre(){
ArrayList<Integer> lista = new ArrayList<>();
positionsPreAux(root, lista);
return lista;
}
//método auxiliar pré-fixada
public void positionsPreAux(Node n, ArrayList<Integer> lista){
if(n != null){
lista.add(n.element);
for(int i=0; i<n.getSubtreeSize(); i++) {
positionsPreAux(n.getSubtree(i), lista);
}
}
}
//retorna uma lista com todos os elementos da árvore na ordem pós-fixada
public ArrayList<Integer> positionsPos(){
ArrayList<Integer> lista = new ArrayList<>();
positionsPosAux(root, lista);
return lista;
}
//método auxiliar pós-fixada
public void positionsPosAux(Node n, ArrayList<Integer> lista){
if(n != null){
for(int i=0; i<n.getSubtreeSize(); i++) {
positionsPosAux(n.getSubtree(i), lista);
}
lista.add(n.element);
}
}
//retorna uma lista com todos os elementos da árvore com um caminhamento em largura
public ArrayList<Integer> positionsWidth(){
ArrayList<Integer> lista = new ArrayList<>();
if(root != null){
Queue<Node> fila = new LinkedList<>();
Node aux = root;
fila.offer(aux);
while(!fila.isEmpty()) {
aux = fila.poll();
lista.add(aux.element);
for(int i=0; i<aux.getSubtreeSize(); i++){
fila.offer(aux.getSubtree(i));
}
}
}
return lista;
}
public ArrayList<Integer> ancestors(Integer e){
ArrayList<Integer> lista = new ArrayList<>();
try{
Node n = searchNodeRef(e);
while(n != null){
lista.add(n.element);
n = n.father;
}
} catch (Exception exc) {
//System.out.println("Mensagem: " + exc);
}
return lista;
}
}
| ISO-8859-1 | Java | 5,414 | java | GeneralTreeOfInteger.java | Java | [] | null | [] | package tads;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GeneralTreeOfInteger {
private static final class Node{
public Node father;
public Integer element;
public ArrayList<Node> subtrees;
public Node(Integer element){
this.father = null;
this.element = element;
subtrees = new ArrayList<>();
}
public void addSubtree(Node n){
n.father = this;
subtrees.add(n);
}
public boolean removeSubtree(Node n){
n.father = null;
return subtrees.remove(n);
}
public Node getSubtree(int i){
if(i >= 0 && i < subtrees.size()) {
return subtrees.get(i);
}
return null;
}
public int getSubtreeSize(){
return subtrees.size();
}
@Override
public String toString() {
return "Node [father=" + father + ", element=" + element + ", subtrees=" + subtrees + "]";
}
}
private Node root;
private int count;
//Construtor
public GeneralTreeOfInteger(){
root = null;
count = 0;
}
//Retorna a referência pro Node que possui element
private Node searchNodeRef(Integer e){
return searchNodeRef(e, root);
}
//método auxiliar recursivo
private Node searchNodeRef(Integer element, Node target){
Node n = null;
if(target != null){
if(element.equals(target.element)){
n = target;
} else {
int i = 0;
Node aux = null;
while(aux == null && i<target.getSubtreeSize()) {
aux = searchNodeRef(element, target.getSubtree(i));
i++;
n = aux;
}
}
return n;
}
return null;
}
//insere o elemento e como filho de f
public boolean add(Integer e, Integer f){
try{
searchNodeRef(f).addSubtree(new Node(e));
count++;
return true;
} catch (Exception exc) {
return false;
}
}
//retorna o elemento armazenado na raiz
public Integer getRoot(){
if(root != null) {
return root.element;
}
return null;
}
//cria a raíz, se já existir altera o elemento armazenado na raiz
public void setRoot(Integer e){
if(root == null) {
root = new Node(e);
count++;
} else {
root.element = e;
}
}
//retorna o pai do elemento e
public Integer getParent(Integer e){
try{
return searchNodeRef(e).father.element;
} catch (Exception exc) {
return null;
}
}
//remove o elemento e e seus filhos
public boolean removeBranch(Integer e){
try{
Node n = searchNodeRef(e);
ArrayList<Integer> lista = new ArrayList<>();
positionsPosAux(n, lista);
count = count - lista.size();
return n.father.removeSubtree(n);
} catch (Exception exc) {
return false;
}
}
//retorna true se a árvore contém o elemento
public boolean contains(Integer e){
try{
return searchNodeRef(e) != null;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento está armazenado em um nodo interno
public boolean isInternal(Integer e){
try{
return searchNodeRef(e).getSubtreeSize() > 0;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento está armazenado em um nodo externo
public boolean isExternal(Integer e){
try{
return searchNodeRef(e).getSubtreeSize() == 0;
} catch (Exception exc) {
return false;
}
}
//retorna true se o elemento e está armazenado na raiz
public boolean isRoot(Integer e){
try{
return root.element.equals(e);
} catch (Exception exc) {
return false;
}
}
//retorna true se a árvore está vazia
public boolean isEmpty(){
return count == 0;
}
//retorna o número de elementos armazenados na árvore
public int size(){
return count;
}
//remove todos os elementos da árvore
public void clear(){
root = null;
count = 0;
}
//retorna uma lista com todos os elementos da árvore na ordem pré-fixada
public ArrayList<Integer> positionsPre(){
ArrayList<Integer> lista = new ArrayList<>();
positionsPreAux(root, lista);
return lista;
}
//método auxiliar pré-fixada
public void positionsPreAux(Node n, ArrayList<Integer> lista){
if(n != null){
lista.add(n.element);
for(int i=0; i<n.getSubtreeSize(); i++) {
positionsPreAux(n.getSubtree(i), lista);
}
}
}
//retorna uma lista com todos os elementos da árvore na ordem pós-fixada
public ArrayList<Integer> positionsPos(){
ArrayList<Integer> lista = new ArrayList<>();
positionsPosAux(root, lista);
return lista;
}
//método auxiliar pós-fixada
public void positionsPosAux(Node n, ArrayList<Integer> lista){
if(n != null){
for(int i=0; i<n.getSubtreeSize(); i++) {
positionsPosAux(n.getSubtree(i), lista);
}
lista.add(n.element);
}
}
//retorna uma lista com todos os elementos da árvore com um caminhamento em largura
public ArrayList<Integer> positionsWidth(){
ArrayList<Integer> lista = new ArrayList<>();
if(root != null){
Queue<Node> fila = new LinkedList<>();
Node aux = root;
fila.offer(aux);
while(!fila.isEmpty()) {
aux = fila.poll();
lista.add(aux.element);
for(int i=0; i<aux.getSubtreeSize(); i++){
fila.offer(aux.getSubtree(i));
}
}
}
return lista;
}
public ArrayList<Integer> ancestors(Integer e){
ArrayList<Integer> lista = new ArrayList<>();
try{
Node n = searchNodeRef(e);
while(n != null){
lista.add(n.element);
n = n.father;
}
} catch (Exception exc) {
//System.out.println("Mensagem: " + exc);
}
return lista;
}
}
| 5,414 | 0.650343 | 0.648488 | 251 | 20.470119 | 18.392849 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.434263 | false | false | 4 |
3877ca9f82b1cc47645afa6a7059c011a5a514be | 8,461,085,578,571 | 6b5d7d02e536f8aef7f389b193992d4a3a8924b9 | /src/com/midgarb/day5/f4/Double.java | 195abf5e9ed1bb0b79df31a31ea4b55a78502e57 | [] | no_license | Simon060893/firstCourse | https://github.com/Simon060893/firstCourse | 437eefed7db83b45cf496f892356098babb36906 | 698d2d9e17c2ed4635f6226b88d3d149f5792e3c | refs/heads/master | 2020-05-18T17:07:45.282000 | 2014-11-15T12:30:52 | 2014-11-15T12:30:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.midgarb.day5.f4;
public class Double extends Integer {
public Double(){
System.out.print("Double");
}
public static void f(){
Integer.f();
}
}
| UTF-8 | Java | 168 | java | Double.java | Java | [] | null | [] | package com.midgarb.day5.f4;
public class Double extends Integer {
public Double(){
System.out.print("Double");
}
public static void f(){
Integer.f();
}
}
| 168 | 0.660714 | 0.64881 | 12 | 13 | 13.2665 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
0b87bbfe805843285c35636a0904d241b764cf10 | 13,262,859,027,442 | f2a10d99aab6d841cc5cc0dc1e841ec00e13a08d | /src/Armor.java | 8cbb74a25d19cd58ef4652b3de076b6897fdfdbe | [] | no_license | jschwarzwalder/JavaMocking | https://github.com/jschwarzwalder/JavaMocking | 55c2f28bb86242f6e5586961bfa079e1828e93f2 | 4ee0b50201313b4a04f8da0b1601808519ca145e | refs/heads/master | 2020-09-26T15:44:01.038000 | 2019-12-06T08:49:16 | 2019-12-06T08:49:16 | 226,285,094 | 0 | 0 | null | false | 2019-12-11T01:42:56 | 2019-12-06T08:49:32 | 2019-12-06T08:49:40 | 2019-12-11T01:42:40 | 4 | 0 | 0 | 1 | Java | false | false | public enum Armor {
CLOTH,
LEATHER,
PLATE
}
| UTF-8 | Java | 56 | java | Armor.java | Java | [] | null | [] | public enum Armor {
CLOTH,
LEATHER,
PLATE
}
| 56 | 0.571429 | 0.571429 | 5 | 10.2 | 5.775812 | 19 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
9ea5c5e4db7f8969b6999e51079fe80cf14f0519 | 22,428,319,228,133 | 956044fc673dd5512a04de06d18ab885469e0ec6 | /app/src/main/java/teamtreehouse/com/movienight/model/Genres.java | a7e3da30162f51cdb696c33694310f6eb90a3a4c | [] | no_license | jwagnerpl/MovieNight | https://github.com/jwagnerpl/MovieNight | 12e408f89122f6460782a70acc9327bec28616e8 | a88cfb20000fbcb2295cb992409975be6c70d830 | refs/heads/master | 2021-08-10T16:07:56.110000 | 2017-11-12T19:32:19 | 2017-11-12T19:32:19 | 110,386,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teamtreehouse.com.movienight.model;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import teamtreehouse.com.movienight.MainActivity;
public class Genres {
public List<Genre> getGenreList() {
return genreList;
}
public void setGenreList(List<Genre> genreList) {
this.genreList = genreList;
}
private List<Genre> genreList = new ArrayList<Genre>();
public class Genre {
public String getGenreName() {
return genreName;
}
public int getGenreId() {
return genreId;
}
String genreName;
int genreId;
public Genre(String genreName, int genreId) {
this.genreId = genreId;
this.genreName = genreName;
}
}
public Genres() {
genreList.add(new Genre("Choose a Genre", 28));
genreList.add(new Genre("Action", 28));
genreList.add(new Genre("Adventure", 12));
genreList.add(new Genre("Animation", 16));
genreList.add(new Genre("Comedy", 35));
genreList.add(new Genre("Crime", 80));
genreList.add(new Genre("Documentary", 99));
genreList.add(new Genre("Drama", 18));
genreList.add(new Genre("Family", 10751));
genreList.add(new Genre("Fantasy", 14));
genreList.add(new Genre("History", 36));
genreList.add(new Genre("Horror", 27));
genreList.add(new Genre("Music", 10402));
genreList.add(new Genre("Mystery", 9648));
genreList.add(new Genre("Romance", 10749));
genreList.add(new Genre("Science Fiction", 878));
genreList.add(new Genre("TV Movie", 10770));
genreList.add(new Genre("Thriller", 53));
genreList.add(new Genre("War", 10752));
genreList.add(new Genre("Western", 37));
}
public int getGenreNumber(String genreNamein){
int genreNumber = 0;
for(Genre genre:genreList){
if(genreNamein == genre.genreName){
genreNumber = genre.genreId;
}
}
return genreNumber;
}
public String[] getGenreTitleArray() {
return genreTitleArray;
}
String[] genreTitleArray = {"Choose a Genre", "Action", "Adventure", "Animation", "Comedy", "Crime", "Documentary", "Drama", "Family", "Fantasy", "History", "Horror"
, "Music", "Mystery", "Romance", "Science Fiction", "TV Movie", "Thriller", "War", "Western"};
}
| UTF-8 | Java | 2,812 | java | Genres.java | Java | [] | null | [] | package teamtreehouse.com.movienight.model;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import teamtreehouse.com.movienight.MainActivity;
public class Genres {
public List<Genre> getGenreList() {
return genreList;
}
public void setGenreList(List<Genre> genreList) {
this.genreList = genreList;
}
private List<Genre> genreList = new ArrayList<Genre>();
public class Genre {
public String getGenreName() {
return genreName;
}
public int getGenreId() {
return genreId;
}
String genreName;
int genreId;
public Genre(String genreName, int genreId) {
this.genreId = genreId;
this.genreName = genreName;
}
}
public Genres() {
genreList.add(new Genre("Choose a Genre", 28));
genreList.add(new Genre("Action", 28));
genreList.add(new Genre("Adventure", 12));
genreList.add(new Genre("Animation", 16));
genreList.add(new Genre("Comedy", 35));
genreList.add(new Genre("Crime", 80));
genreList.add(new Genre("Documentary", 99));
genreList.add(new Genre("Drama", 18));
genreList.add(new Genre("Family", 10751));
genreList.add(new Genre("Fantasy", 14));
genreList.add(new Genre("History", 36));
genreList.add(new Genre("Horror", 27));
genreList.add(new Genre("Music", 10402));
genreList.add(new Genre("Mystery", 9648));
genreList.add(new Genre("Romance", 10749));
genreList.add(new Genre("Science Fiction", 878));
genreList.add(new Genre("TV Movie", 10770));
genreList.add(new Genre("Thriller", 53));
genreList.add(new Genre("War", 10752));
genreList.add(new Genre("Western", 37));
}
public int getGenreNumber(String genreNamein){
int genreNumber = 0;
for(Genre genre:genreList){
if(genreNamein == genre.genreName){
genreNumber = genre.genreId;
}
}
return genreNumber;
}
public String[] getGenreTitleArray() {
return genreTitleArray;
}
String[] genreTitleArray = {"Choose a Genre", "Action", "Adventure", "Animation", "Comedy", "Crime", "Documentary", "Drama", "Family", "Fantasy", "History", "Horror"
, "Music", "Mystery", "Romance", "Science Fiction", "TV Movie", "Thriller", "War", "Western"};
}
| 2,812 | 0.625178 | 0.602063 | 96 | 28.291666 | 25.411167 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.947917 | false | false | 4 |
57f9aca7aa1e057f3ae92e8f0e0a19c9ae0ed5dc | 17,308,718,214,109 | 0433dd8b388a942bc342964e588bdd731a3cfd4a | /src/sgp/models/Registro.java | d9f2d0764f471f1e0f3cedc5e8186df0bca37a1f | [
"MIT"
] | permissive | victorsouzaleal/sgp-sistema-gerenciador-pesagem | https://github.com/victorsouzaleal/sgp-sistema-gerenciador-pesagem | e9d8047223bc867922766e0909c468306abcb0f7 | fbe4f98e97c32bf2e6877f63ea99e92d1f7a6784 | refs/heads/master | 2022-03-28T17:52:00.985000 | 2020-01-30T13:22:48 | 2020-01-30T13:22:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* CLASSE : Registro
* FUNÇÃO : Gerencia os registros de entrada/saida de motoristas
*/
package sgp.models;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import sgp.persistence.AcoesSQL;
/**
*
* @author Desenvolvimento
*/
public class Registro {
private int id;
private String placa;
private String nome;
private String produto;
private String fornecedor;
private String ps_entrada;
private String ps_saida;
private String ps_liquido;
private String dt_entrada;
private String h_entrada;
private String dt_saida;
private String h_saida;
private String tipo;
private static int num_registros;
public Registro(){
}
public Registro(int id,String placa, String nome, String produto, String fornecedor, String dt_entrada, String h_entrada, String ps_entrada, String dt_saida, String h_saida, String ps_saida, String ps_liquido){
setId(id);
setPlaca(placa);
setNome(nome);
setProduto(produto);
setFornecedor(fornecedor);
setDt_entrada(dt_entrada);
setH_entrada(h_entrada);
setPs_entrada(ps_entrada);
setDt_saida(dt_saida);
setH_saida(h_saida);
setPs_saida(ps_saida);
setPs_liquido(ps_liquido);
}
//REGISTRA ENTRADA DOS MOTORISTAS
public boolean registrarEntrada(String placa, String ps_entrada){
AcoesSQL acao = new AcoesSQL();
Motorista mot = acao.procurarPlaca(placa);
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
this.setPlaca(placa);
this.setNome(mot.getNome());
this.setProduto(mot.getProduto());
this.setFornecedor(mot.getFornecedor());
this.setDt_entrada(fmtDate.format(data));
this.setH_entrada(fmtTime.format(data));
this.setPs_entrada(ps_entrada);
return acao.entradaRegistro(this);
}
//REGISTRA SAIDA DO MOTORISTA
public boolean registrarSaida(String placa, String ps_entrada, String ps_saida){
AcoesSQL acao = new AcoesSQL();
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
Registro reg = new Registro();
reg.setPlaca(placa);
reg.setDt_saida(fmtDate.format(data));
reg.setH_saida(fmtTime.format(data));
reg.setPs_saida(ps_saida);
String peso_liq = "";
if(ps_saida.contains(".") || ps_entrada.contains(".")){
BigDecimal b = new BigDecimal(ps_saida).subtract(new BigDecimal(ps_entrada));
peso_liq = b.toString();
}else {
peso_liq = String.valueOf(Integer.parseInt(ps_saida) - Integer.parseInt(ps_entrada));
}
reg.setPs_liquido(peso_liq);
return acao.saidaRegistro(reg);
}
//REGISTRA ENTRADA DOS MOTORISTAS
public boolean registrarEntradaManual(String placa, String ps_entrada){
AcoesSQL acao = new AcoesSQL();
Motorista mot = acao.procurarPlaca(placa);
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
this.setPlaca(placa);
this.setNome(mot.getNome());
this.setProduto(mot.getProduto());
this.setFornecedor(mot.getFornecedor());
this.setDt_entrada(fmtDate.format(data));
this.setH_entrada(fmtTime.format(data));
this.setPs_entrada(ps_entrada);
return acao.entradaRegistroManual(this);
}
//REGISTRA SAIDA DO MOTORISTA
public boolean registrarSaidaManual(String placa, String ps_entrada, String ps_saida){
AcoesSQL acao = new AcoesSQL();
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
Registro reg = new Registro();
reg.setPlaca(placa);
reg.setDt_saida(fmtDate.format(data));
reg.setH_saida(fmtTime.format(data));
reg.setPs_saida(ps_saida);
String peso_liq = "";
if(ps_saida.contains(".") || ps_entrada.contains(".")){
BigDecimal b = new BigDecimal(ps_saida).subtract(new BigDecimal(ps_entrada));
peso_liq = b.toString();
}else {
peso_liq = String.valueOf(Integer.parseInt(ps_saida) - Integer.parseInt(ps_entrada));
}
reg.setPs_liquido(peso_liq);
return acao.saidaRegistroManual(reg);
}
//RETORNA O ULTIMO REGISTRO DE UMA DETERMINADA PLACA
public Registro ultimoRegistro(String placa){
AcoesSQL acao = new AcoesSQL();
return acao.getUltimoRegistro(placa);
}
public Registro ultimoRegistroManual(String placa){
AcoesSQL acao = new AcoesSQL();
return acao.getUltimoRegistroManual(placa);
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS
public ObservableList<Registro> listaDeRegistros() {
AcoesSQL acao = new AcoesSQL();
return FXCollections.observableList(acao.listarRegistros());
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS DE UMA DETERMINADA PLACA
public ObservableList<Registro> listaDeRegistros(String placa) {
AcoesSQL acao = new AcoesSQL();
List<Registro> registros = acao.listarRegistros(placa);
Motorista.setNum_registros(registros.size() + 1);
return FXCollections.observableList(registros);
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS NUM PERIODO ESPECIFICO
public List<Registro> listaDeRegistros(String data_ini, String data_fim) {
AcoesSQL acao = new AcoesSQL();
return acao.listarRegistros(data_ini, data_fim);
}
//GETTERS E SETTERS
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public String getFornecedor() {
return fornecedor;
}
public void setFornecedor(String fornecedor) {
this.fornecedor = fornecedor;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getPs_entrada() {
return ps_entrada;
}
public void setPs_entrada(String ps_entrada) {
this.ps_entrada = ps_entrada;
}
public String getPs_saida() {
return ps_saida;
}
public void setPs_saida(String ps_saida) {
this.ps_saida = ps_saida;
}
public String getPs_liquido() {
return ps_liquido;
}
public void setPs_liquido(String ps_liquido) {
this.ps_liquido = ps_liquido;
}
public String getDt_entrada() {
return dt_entrada;
}
public void setDt_entrada(String dt_entrada) {
this.dt_entrada = dt_entrada;
}
public String getH_entrada() {
return h_entrada;
}
public void setH_entrada(String h_entrada) {
this.h_entrada = h_entrada;
}
public String getDt_saida() {
return dt_saida;
}
public void setDt_saida(String dt_saida) {
this.dt_saida = dt_saida;
}
public String getH_saida() {
return h_saida;
}
public void setH_saida(String h_saida) {
this.h_saida = h_saida;
}
public static int getNum_registros() {
return num_registros;
}
public static void setNum_registros(int num_registros) {
Registro.num_registros = num_registros;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
| UTF-8 | Java | 8,550 | java | Registro.java | Java | [
{
"context": "t sgp.persistence.AcoesSQL;\r\n\r\n/**\r\n *\r\n * @author Desenvolvimento\r\n */\r\npublic class Registro {\r\n private int id;\r",
"end": 394,
"score": 0.8765486478805542,
"start": 379,
"tag": "NAME",
"value": "Desenvolvimento"
}
] | null | [] | /*
* CLASSE : Registro
* FUNÇÃO : Gerencia os registros de entrada/saida de motoristas
*/
package sgp.models;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import sgp.persistence.AcoesSQL;
/**
*
* @author Desenvolvimento
*/
public class Registro {
private int id;
private String placa;
private String nome;
private String produto;
private String fornecedor;
private String ps_entrada;
private String ps_saida;
private String ps_liquido;
private String dt_entrada;
private String h_entrada;
private String dt_saida;
private String h_saida;
private String tipo;
private static int num_registros;
public Registro(){
}
public Registro(int id,String placa, String nome, String produto, String fornecedor, String dt_entrada, String h_entrada, String ps_entrada, String dt_saida, String h_saida, String ps_saida, String ps_liquido){
setId(id);
setPlaca(placa);
setNome(nome);
setProduto(produto);
setFornecedor(fornecedor);
setDt_entrada(dt_entrada);
setH_entrada(h_entrada);
setPs_entrada(ps_entrada);
setDt_saida(dt_saida);
setH_saida(h_saida);
setPs_saida(ps_saida);
setPs_liquido(ps_liquido);
}
//REGISTRA ENTRADA DOS MOTORISTAS
public boolean registrarEntrada(String placa, String ps_entrada){
AcoesSQL acao = new AcoesSQL();
Motorista mot = acao.procurarPlaca(placa);
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
this.setPlaca(placa);
this.setNome(mot.getNome());
this.setProduto(mot.getProduto());
this.setFornecedor(mot.getFornecedor());
this.setDt_entrada(fmtDate.format(data));
this.setH_entrada(fmtTime.format(data));
this.setPs_entrada(ps_entrada);
return acao.entradaRegistro(this);
}
//REGISTRA SAIDA DO MOTORISTA
public boolean registrarSaida(String placa, String ps_entrada, String ps_saida){
AcoesSQL acao = new AcoesSQL();
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
Registro reg = new Registro();
reg.setPlaca(placa);
reg.setDt_saida(fmtDate.format(data));
reg.setH_saida(fmtTime.format(data));
reg.setPs_saida(ps_saida);
String peso_liq = "";
if(ps_saida.contains(".") || ps_entrada.contains(".")){
BigDecimal b = new BigDecimal(ps_saida).subtract(new BigDecimal(ps_entrada));
peso_liq = b.toString();
}else {
peso_liq = String.valueOf(Integer.parseInt(ps_saida) - Integer.parseInt(ps_entrada));
}
reg.setPs_liquido(peso_liq);
return acao.saidaRegistro(reg);
}
//REGISTRA ENTRADA DOS MOTORISTAS
public boolean registrarEntradaManual(String placa, String ps_entrada){
AcoesSQL acao = new AcoesSQL();
Motorista mot = acao.procurarPlaca(placa);
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
this.setPlaca(placa);
this.setNome(mot.getNome());
this.setProduto(mot.getProduto());
this.setFornecedor(mot.getFornecedor());
this.setDt_entrada(fmtDate.format(data));
this.setH_entrada(fmtTime.format(data));
this.setPs_entrada(ps_entrada);
return acao.entradaRegistroManual(this);
}
//REGISTRA SAIDA DO MOTORISTA
public boolean registrarSaidaManual(String placa, String ps_entrada, String ps_saida){
AcoesSQL acao = new AcoesSQL();
SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
Date data = new Date();
Registro reg = new Registro();
reg.setPlaca(placa);
reg.setDt_saida(fmtDate.format(data));
reg.setH_saida(fmtTime.format(data));
reg.setPs_saida(ps_saida);
String peso_liq = "";
if(ps_saida.contains(".") || ps_entrada.contains(".")){
BigDecimal b = new BigDecimal(ps_saida).subtract(new BigDecimal(ps_entrada));
peso_liq = b.toString();
}else {
peso_liq = String.valueOf(Integer.parseInt(ps_saida) - Integer.parseInt(ps_entrada));
}
reg.setPs_liquido(peso_liq);
return acao.saidaRegistroManual(reg);
}
//RETORNA O ULTIMO REGISTRO DE UMA DETERMINADA PLACA
public Registro ultimoRegistro(String placa){
AcoesSQL acao = new AcoesSQL();
return acao.getUltimoRegistro(placa);
}
public Registro ultimoRegistroManual(String placa){
AcoesSQL acao = new AcoesSQL();
return acao.getUltimoRegistroManual(placa);
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS
public ObservableList<Registro> listaDeRegistros() {
AcoesSQL acao = new AcoesSQL();
return FXCollections.observableList(acao.listarRegistros());
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS DE UMA DETERMINADA PLACA
public ObservableList<Registro> listaDeRegistros(String placa) {
AcoesSQL acao = new AcoesSQL();
List<Registro> registros = acao.listarRegistros(placa);
Motorista.setNum_registros(registros.size() + 1);
return FXCollections.observableList(registros);
}
//RETORNA UMA OBSERVABLE LIST DE REGISTROS NUM PERIODO ESPECIFICO
public List<Registro> listaDeRegistros(String data_ini, String data_fim) {
AcoesSQL acao = new AcoesSQL();
return acao.listarRegistros(data_ini, data_fim);
}
//GETTERS E SETTERS
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public String getFornecedor() {
return fornecedor;
}
public void setFornecedor(String fornecedor) {
this.fornecedor = fornecedor;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getPs_entrada() {
return ps_entrada;
}
public void setPs_entrada(String ps_entrada) {
this.ps_entrada = ps_entrada;
}
public String getPs_saida() {
return ps_saida;
}
public void setPs_saida(String ps_saida) {
this.ps_saida = ps_saida;
}
public String getPs_liquido() {
return ps_liquido;
}
public void setPs_liquido(String ps_liquido) {
this.ps_liquido = ps_liquido;
}
public String getDt_entrada() {
return dt_entrada;
}
public void setDt_entrada(String dt_entrada) {
this.dt_entrada = dt_entrada;
}
public String getH_entrada() {
return h_entrada;
}
public void setH_entrada(String h_entrada) {
this.h_entrada = h_entrada;
}
public String getDt_saida() {
return dt_saida;
}
public void setDt_saida(String dt_saida) {
this.dt_saida = dt_saida;
}
public String getH_saida() {
return h_saida;
}
public void setH_saida(String h_saida) {
this.h_saida = h_saida;
}
public static int getNum_registros() {
return num_registros;
}
public static void setNum_registros(int num_registros) {
Registro.num_registros = num_registros;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
| 8,550 | 0.604937 | 0.60482 | 288 | 27.680555 | 24.756355 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 4 |
399cb226e22dd77953f893393de54b1ad38fa91f | 15,504,831,949,331 | 380366cde7f499290a61f8372034744cae137a4e | /adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/PluginAction.java | 634b2ad60dbea33d25995dacd8743c7d8a9f16ec | [
"Apache-2.0"
] | permissive | onap/so | https://github.com/onap/so | 82a219ed0e5559a94d630cc9956180dbab0d33b8 | 43224c4dc5ff3bf67979f480d8628f300497da07 | refs/heads/master | 2023-08-21T00:09:36.560000 | 2023-07-03T16:30:22 | 2023-07-03T16:30:55 | 115,077,083 | 18 | 25 | Apache-2.0 | false | 2022-03-21T09:59:49 | 2017-12-22T04:39:28 | 2022-01-18T13:12:09 | 2022-03-21T09:59:49 | 143,795 | 15 | 19 | 2 | Java | false | false | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.adapters.vdu;
/**
* Java beam representing a detailed action performed within a plugin during VDU orchestration. This allows the plugin
* to convey more detailed information about recent activities it has performed. It is primarily intended for logging
* and troubleshooting, so plugins are free to populate this as desired.
*/
public class PluginAction {
private String action;
private String status;
private String rawMessage;
public PluginAction() {}
public PluginAction(String action, String status, String rawMessage) {
this.action = action;
this.status = status;
this.rawMessage = rawMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getRawMessage() {
return rawMessage;
}
public void setRawMessage(String rawMessage) {
this.rawMessage = rawMessage;
}
}
| UTF-8 | Java | 2,117 | java | PluginAction.java | Java | [] | null | [] | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.adapters.vdu;
/**
* Java beam representing a detailed action performed within a plugin during VDU orchestration. This allows the plugin
* to convey more detailed information about recent activities it has performed. It is primarily intended for logging
* and troubleshooting, so plugins are free to populate this as desired.
*/
public class PluginAction {
private String action;
private String status;
private String rawMessage;
public PluginAction() {}
public PluginAction(String action, String status, String rawMessage) {
this.action = action;
this.status = status;
this.rawMessage = rawMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getRawMessage() {
return rawMessage;
}
public void setRawMessage(String rawMessage) {
this.rawMessage = rawMessage;
}
}
| 2,117 | 0.593765 | 0.589986 | 66 | 31.075758 | 30.990864 | 118 | false | false | 0 | 0 | 0 | 0 | 81 | 0.076523 | 0.318182 | false | false | 4 |
c3ec4b60b404c77e9aa6a89eab4b5318e4c8b117 | 31,507,880,104,680 | 9048ac7f7f85225c09d6bed94190d38b1e6f1a1b | /src/office_hour/Practice_12_16.java | dc2cc1c9c8e2bfdd2dd993490fa4a5e46725eecb | [] | no_license | isilg/JavaProgrammingB15Online | https://github.com/isilg/JavaProgrammingB15Online | 5f2e99775ef1725fee26392c368e98a0ecae15f8 | 1c7f5ab43b6bd138f2d6bc9b6fa245b993fcf5f6 | refs/heads/master | 2020-12-13T04:07:05.073000 | 2020-04-15T01:35:31 | 2020-04-15T01:35:31 | 234,308,239 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package office_hour;
public class Practice_12_16 {
public static void main(String[] args) {
String [] names = {"John", "Kevin", "Scott"};
for (String name: names){
System.out.println( name );
}
//lets say we need to store some table
//where we have rows and columns
String[][] students = { {"1", "John", "35", "USA" }, {"2", "Kevin","40" ,"Brazil"}, { "3" , "Scott", "20","Canada"}};
//loop through inner arrays
for ( String[] arr : students){
//loop through values in every inner array
for (String value: arr){
System.out.print(value+ " ");
}
System.out.println();
}
System.out.println();
//FIND OLDEST STUDENT AND PRINT HIS NAME
// //first just print age
// String oldestPersonName = students[0][1];
//
// for (String[] row : students ){
// //go through every row and get value only from 3rd column | number -1 = index
// //because 3rd columns hold the ages. In tables columns are organize
// //so age column is specific, name column is specific ext
// System.out.println(row[2]); //3rd row represents age
// //I need to convert into integer to be able to compare
// int age = Integer.parseInt(row[2]);//convert string --> into int
//
// }
// }
}
}
| UTF-8 | Java | 1,441 | java | Practice_12_16.java | Java | [
{
"context": "ain(String[] args) {\n\n String [] names = {\"John\", \"Kevin\", \"Scott\"};\n for (String name: na",
"end": 130,
"score": 0.9998730421066284,
"start": 126,
"tag": "NAME",
"value": "John"
},
{
"context": "ng[] args) {\n\n String [] names = {\"John\"... | null | [] | package office_hour;
public class Practice_12_16 {
public static void main(String[] args) {
String [] names = {"John", "Kevin", "Scott"};
for (String name: names){
System.out.println( name );
}
//lets say we need to store some table
//where we have rows and columns
String[][] students = { {"1", "John", "35", "USA" }, {"2", "Kevin","40" ,"Brazil"}, { "3" , "Scott", "20","Canada"}};
//loop through inner arrays
for ( String[] arr : students){
//loop through values in every inner array
for (String value: arr){
System.out.print(value+ " ");
}
System.out.println();
}
System.out.println();
//FIND OLDEST STUDENT AND PRINT HIS NAME
// //first just print age
// String oldestPersonName = students[0][1];
//
// for (String[] row : students ){
// //go through every row and get value only from 3rd column | number -1 = index
// //because 3rd columns hold the ages. In tables columns are organize
// //so age column is specific, name column is specific ext
// System.out.println(row[2]); //3rd row represents age
// //I need to convert into integer to be able to compare
// int age = Integer.parseInt(row[2]);//convert string --> into int
//
// }
// }
}
}
| 1,441 | 0.530881 | 0.516308 | 44 | 31.75 | 29.451906 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568182 | false | false | 4 |
ba398e20509b4a0d46f1e957d7ad646cf6d7fe3b | 9,818,295,261,453 | 221c8895a68b53578997620e2156c5241407f6a7 | /src/main/java/xyz/nkomarn/Harbor/gui/GUIType.java | 6dca8270d3161c41f5f464bdf3ae445308da889d | [
"MIT"
] | permissive | RohugMC/Harbor | https://github.com/RohugMC/Harbor | ac2a8eff2c5522ca4fa3069a48ccbaf466422337 | 2b8e5c3f806b0a7a7737e4f20aae9bd833648af3 | refs/heads/master | 2020-06-25T06:22:38.734000 | 2019-07-28T01:37:58 | 2019-07-28T01:37:58 | 199,229,979 | 0 | 0 | null | true | 2019-07-28T01:37:06 | 2019-07-28T01:37:06 | 2019-07-27T14:07:24 | 2019-07-27T14:33:37 | 114 | 0 | 0 | 0 | null | false | false | package xyz.nkomarn.Harbor.gui;
public enum GUIType {
SLEEPING
}
| UTF-8 | Java | 70 | java | GUIType.java | Java | [
{
"context": "package xyz.nkomarn.Harbor.gui;\n\npublic enum GUIType {\n SLEEPING\n}",
"end": 19,
"score": 0.5675163865089417,
"start": 16,
"tag": "USERNAME",
"value": "arn"
}
] | null | [] | package xyz.nkomarn.Harbor.gui;
public enum GUIType {
SLEEPING
}
| 70 | 0.728571 | 0.728571 | 5 | 13 | 11.849051 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
560b92c71f4f51d1ae83453d918355e93efeea6b | 1,494,648,625,201 | 093d9903de5b36d33865350ff981abffc6572e2d | /MaterialFileExplorer/src/main/java/com/devnull/fileexplorer/di/FileTypeCacheRepoComponent.java | 86a173e0dcc9a5bf390f79c038a1e0b9134f2733 | [] | no_license | ogkuzmin/FileExplorer | https://github.com/ogkuzmin/FileExplorer | 30b58b7045b0ad6c016f81ce38e839b9e5b42c1e | ec90c4823cec64be73b0329c20e554c8fbece028 | refs/heads/master | 2021-01-10T05:52:33.835000 | 2017-08-20T19:21:41 | 2017-08-20T19:21:41 | 55,580,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.devnull.fileexplorer.di;
import com.devnull.fileexplorer.interfaces.IFileAnalyzerController;
import com.devnull.fileexplorer.interfaces.IFileTypeCacheRepo;
import com.devnull.fileexplorer.ui.PresentationModelTransformer;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {FileTypeCacheRepoModule.class})
public interface FileTypeCacheRepoComponent {
IFileTypeCacheRepo provideFileTypeCacheRepo();
void inject(IFileAnalyzerController controller);
void inject(PresentationModelTransformer transformer);
}
| UTF-8 | Java | 572 | java | FileTypeCacheRepoComponent.java | Java | [] | null | [] | package com.devnull.fileexplorer.di;
import com.devnull.fileexplorer.interfaces.IFileAnalyzerController;
import com.devnull.fileexplorer.interfaces.IFileTypeCacheRepo;
import com.devnull.fileexplorer.ui.PresentationModelTransformer;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {FileTypeCacheRepoModule.class})
public interface FileTypeCacheRepoComponent {
IFileTypeCacheRepo provideFileTypeCacheRepo();
void inject(IFileAnalyzerController controller);
void inject(PresentationModelTransformer transformer);
}
| 572 | 0.840909 | 0.840909 | 20 | 27.6 | 25.950722 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 4 |
68f84984f0a742acbf84c0e1fdb3739915e5fe8d | 32,418,413,204,803 | d2278af650b4bff752de4db8371465f271696576 | /src/main/com/chatroomclient/java/controller/RegisterController.java | 91a6f331d0d58b21d08d35a2f558d7bca3b927d8 | [] | no_license | UltraChatRoom/ChatRoomClient | https://github.com/UltraChatRoom/ChatRoomClient | bb5550c33bb15b931a12cad4563b26b9e44b4204 | a7f0699ed3e719490a97df5e6090045478b053c3 | refs/heads/main | 2023-01-13T16:44:50.539000 | 2020-11-22T08:10:24 | 2020-11-22T08:10:24 | 312,781,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.com.chatroomclient.java.controller;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;
import main.com.chatroomclient.java.Main;
import main.com.chatroomclient.java.common.constant.UserConstants;
import java.net.URL;
import java.util.ResourceBundle;
/**
* @className: RegisterController
* @program: ChatRoomClient
* @description: //TODO 注册窗口控制层
* @author: GirtSeanking
* @create: 2020-11-16 21:35
**/
public class RegisterController implements Initializable {
@FXML
private Button closeBtn;
@FXML
private Button backBtn;
@FXML
private Label welcomeLabel = new Label();
@FXML
private TextField userName;
@FXML
private PasswordField registerPassword;
@FXML
private PasswordField registerPasswordAgain;
@FXML
private TextField securityQuestion;
@FXML
private TextField questionAnswer;
@FXML
private Button registerBtn;
/**
* @Author GirtSeanking
* @Description //TODO 初始化界面
* @Date 18:33
* @Param [url, resourceBundle]
* @return void
**/
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
typingEffect("注册");
}
/**
* @Author GirtSeanking
* @Description //TODO 注册窗口关闭
* @Date 18:53
* @Param [mouseEvent]
* @return void
**/
public void closeMouseClick(MouseEvent mouseEvent) {
System.out.println("(♥◠‿◠)ノ゙ MagicChat关闭成功 ლ(´ڡ`ლ)゙ \n" + "o(*^@^*)o 感谢您的使用!!! O(∩_∩)O\n");
System.exit(0);
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口关闭按钮样式变化设置
* @Date 18:53
**/
public void closeMouseEnter(MouseEvent mouseEvent) {
closeBtn.setStyle("-fx-background-color: #99999999");
}
public void closeMouseExit(MouseEvent mouseEvent) {
closeBtn.setStyle("-fx-background-color: #00000000");
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口返回按钮点击事件响应
* @Date 16:39
* @Param [mouseEvent]
* @return void
**/
public void backMouseClick(MouseEvent mouseEvent) {
Main.getRegisterStage().close();
Main.getLoginStage().show();
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口返回按钮样式变化设置
* @Date 10:50
* @Param [mouseEvent]
* @return void
**/
public void backMouseEnter(MouseEvent mouseEvent) {
backBtn.setStyle("-fx-background-color: #99999999");
}
public void backMouseExit(MouseEvent mouseEvent) {
backBtn.setStyle("-fx-background-color: #00000000");
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置昵称时的事件响应
* @Date 18:55
* @Param [keyEvent]
* @return void
**/
public void userNameKeyReleas(KeyEvent keyEvent) {
judgeUserName();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户鼠标点击设置昵称时的事件响应
* @Date 21:42
* @Param [mouseEvent]
* @return void
**/
public void userNameMouseClick(MouseEvent mouseEvent) {
judgeUserName();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户昵称校验
* @Date 17:07
* @Param []
* @return void
**/
public boolean judgeUserName() {
if (userName.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!userName.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("昵称中不能有空格");
userName.setText("");
return false;
} else {
if (userName.getText().length() > UserConstants.USERNAME_MAX_LENGTH) {
typingEffect("您输入的昵称过长");
return false;
} else {
typingEffect("欢迎 " + userName.getText() + " 来到MC");
return true;
}
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密码时的事件响应
* @Date 18:49
* @Param [keyEvent]
* @return void
**/
public void passwordKeyRelease(KeyEvent keyEvent) {
judgePassword();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户密码校验
* @Date 21:28
* @Param []
* @return boolean
**/
public boolean judgePassword() {
if (registerPassword.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!registerPassword.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("密码中不能存在空格");
registerPassword.setText("");
return false;
} else if (registerPassword.getText().length() < UserConstants.PASSWORD_MIN_LENGTH) {
typingEffect("密码长度过短");
return false;
} else if (registerPassword.getText().length() > UserConstants.PASSWORD_MAX_LENGTH) {
typingEffect("密码长度过长");
return false;
} else if (!passwordStrengthJudgement()) {
typingEffect("密码至少包含数字、大小写字母、特殊字符中的两种");
return false;
} else if (registerPassword.getText().length() != registerPassword.getText().getBytes().length) {
typingEffect("密码中不能存在汉字");
return false;
} else {
typingEffect("密码格式正确");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 密码强度校验
* @Date 17:06
* @Param []
* @return java.lang.String
**/
public boolean passwordStrengthJudgement() {
int flag = 0;
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_NUMBER)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_LOWERCASE)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_UPPERCASE)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_SYMBOL)) {
flag++;
}
return flag >= 2;
}
/**
* @Author GirtSeanking
* @Description //TODO 用户再次确认密码时的事件响应
* @Date 18:50
* @Param [keyEvent]
* @return void
**/
public void passwordAaginKeyRelease(KeyEvent keyEvent) {
judgePasswordAaging();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户确认密码校验
* @Date 21:27
* @Param []
* @return boolean
**/
public boolean judgePasswordAaging() {
if (registerPasswordAgain.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!registerPasswordAgain.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("不能输入空格");
registerPasswordAgain.setText("");
return false;
} else if (registerPassword.getText().isEmpty()) {
typingEffect("您还未设置登录密码");
registerPasswordAgain.setText("");
return false;
} else if (registerPassword.getText().equals(registerPasswordAgain.getText())) {
typingEffect("两次密码一致");
return true;
} else {
typingEffect("两次密码不一致");
return false;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题时的事件响应
* @Date 21:08
* @Param [keyEvent]
* @return void
**/
public void securityQuestionKeyRelease(KeyEvent keyEvent) {
judgeScurityQuestion();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题校验
* @Date 21:30
* @Param []
* @return boolean
**/
public boolean judgeScurityQuestion() {
if (securityQuestion.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!securityQuestion.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("设置的密保问题中不能存在空格");
return false;
} else if (securityQuestion.getText().length() > UserConstants.SCURITY_QUESTION_MAX_LENGTH) {
typingEffect("设置的密保问题内容过长");
return false;
} else {
typingEffect("请尽量设置简短又好记的问题");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题的答案时的事件响应
* @Date 21:14
* @Param [keyEvent]
* @return void
**/
public void questionAnswerKeyRelease(KeyEvent keyEvent) {
judgeQuestionAnswer();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题答案校验
* @Date 21:31
* @Param []
* @return boolean
**/
public boolean judgeQuestionAnswer() {
if (questionAnswer.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (questionAnswer.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("设置答案中不能存在空格");
return false;
} else if (questionAnswer.getText().length() > UserConstants.QUESTION_ANSWER_MAX_LENGTH) {
typingEffect("设置的答案内容过长");
return false;
} else {
typingEffect("请尽量设置简短又好记的答案");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 注册按钮样式变化设置
* @Date 21:33
* @Param [mouseEvent]
* @return void
**/
public void registerBtnMouseEnter(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%)");
}
public void registerBtnMouseExit(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to right, #4facfe 0%, #00f2fe 100%)");
}
public void registerBtnMousePress(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #30cfd0 0%, #330867 100%)");
}
/**
* @Author GirtSeanking
* @Description //TODO 注册按钮点击后的事件响应
* @Date 21:34
* @Param [mouseEvent]
* @return void
**/
public void registerBtnMouseRelease(MouseEvent mouseEvent) {
/* 按钮点击后样式 */
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%)");
if (judgeRegisterForm()) {
userReister();
} else {
typingEffect("请仔细填写注册信息");
}
}
/**
* @Author GirtSeanking
* @Description //TODO 判断注册表单
* @Date 21:37
* @Param []
* @return boolean
**/
public boolean judgeRegisterForm() {
if (judgeUserName()) {
if (judgePassword()) {
if (judgePasswordAaging()) {
if (judgeScurityQuestion()) {
if (judgeQuestionAnswer()) {
return true;
}
}
}
}
}
return false;
}
/**
* @Author GirtSeanking
* @Description //TODO 进行用户注册功能
* @Date 9:39
* @Param []
* @return void
**/
public void userReister() {
}
public void typingEffect(String msg) {
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(700));
}
@Override
protected void interpolate(double frac) {
final int length = msg.length();
final int n = Math.round(length * (float) frac);
welcomeLabel.setText(msg.substring(0, n));
}
};
animation.play();
}
}
| UTF-8 | Java | 12,696 | java | RegisterController.java | Java | [
{
"context": "Client\n * @description: //TODO 注册窗口控制层\n * @author: GirtSeanking\n * @create: 2020-11-16 21:35\n **/\n\npublic class R",
"end": 723,
"score": 0.9993346929550171,
"start": 711,
"tag": "USERNAME",
"value": "GirtSeanking"
},
{
"context": "rivate Button registerBtn;\n\n ... | null | [] | package main.com.chatroomclient.java.controller;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;
import main.com.chatroomclient.java.Main;
import main.com.chatroomclient.java.common.constant.UserConstants;
import java.net.URL;
import java.util.ResourceBundle;
/**
* @className: RegisterController
* @program: ChatRoomClient
* @description: //TODO 注册窗口控制层
* @author: GirtSeanking
* @create: 2020-11-16 21:35
**/
public class RegisterController implements Initializable {
@FXML
private Button closeBtn;
@FXML
private Button backBtn;
@FXML
private Label welcomeLabel = new Label();
@FXML
private TextField userName;
@FXML
private PasswordField registerPassword;
@FXML
private PasswordField registerPasswordAgain;
@FXML
private TextField securityQuestion;
@FXML
private TextField questionAnswer;
@FXML
private Button registerBtn;
/**
* @Author GirtSeanking
* @Description //TODO 初始化界面
* @Date 18:33
* @Param [url, resourceBundle]
* @return void
**/
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
typingEffect("注册");
}
/**
* @Author GirtSeanking
* @Description //TODO 注册窗口关闭
* @Date 18:53
* @Param [mouseEvent]
* @return void
**/
public void closeMouseClick(MouseEvent mouseEvent) {
System.out.println("(♥◠‿◠)ノ゙ MagicChat关闭成功 ლ(´ڡ`ლ)゙ \n" + "o(*^@^*)o 感谢您的使用!!! O(∩_∩)O\n");
System.exit(0);
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口关闭按钮样式变化设置
* @Date 18:53
**/
public void closeMouseEnter(MouseEvent mouseEvent) {
closeBtn.setStyle("-fx-background-color: #99999999");
}
public void closeMouseExit(MouseEvent mouseEvent) {
closeBtn.setStyle("-fx-background-color: #00000000");
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口返回按钮点击事件响应
* @Date 16:39
* @Param [mouseEvent]
* @return void
**/
public void backMouseClick(MouseEvent mouseEvent) {
Main.getRegisterStage().close();
Main.getLoginStage().show();
}
/**
* @Author GirtSeanking
* @Description //TODO 窗口返回按钮样式变化设置
* @Date 10:50
* @Param [mouseEvent]
* @return void
**/
public void backMouseEnter(MouseEvent mouseEvent) {
backBtn.setStyle("-fx-background-color: #99999999");
}
public void backMouseExit(MouseEvent mouseEvent) {
backBtn.setStyle("-fx-background-color: #00000000");
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置昵称时的事件响应
* @Date 18:55
* @Param [keyEvent]
* @return void
**/
public void userNameKeyReleas(KeyEvent keyEvent) {
judgeUserName();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户鼠标点击设置昵称时的事件响应
* @Date 21:42
* @Param [mouseEvent]
* @return void
**/
public void userNameMouseClick(MouseEvent mouseEvent) {
judgeUserName();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户昵称校验
* @Date 17:07
* @Param []
* @return void
**/
public boolean judgeUserName() {
if (userName.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!userName.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("昵称中不能有空格");
userName.setText("");
return false;
} else {
if (userName.getText().length() > UserConstants.USERNAME_MAX_LENGTH) {
typingEffect("您输入的昵称过长");
return false;
} else {
typingEffect("欢迎 " + userName.getText() + " 来到MC");
return true;
}
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密码时的事件响应
* @Date 18:49
* @Param [keyEvent]
* @return void
**/
public void passwordKeyRelease(KeyEvent keyEvent) {
judgePassword();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户密码校验
* @Date 21:28
* @Param []
* @return boolean
**/
public boolean judgePassword() {
if (registerPassword.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!registerPassword.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("密码中不能存在空格");
registerPassword.setText("");
return false;
} else if (registerPassword.getText().length() < UserConstants.PASSWORD_MIN_LENGTH) {
typingEffect("密码长度过短");
return false;
} else if (registerPassword.getText().length() > UserConstants.PASSWORD_MAX_LENGTH) {
typingEffect("密码长度过长");
return false;
} else if (!passwordStrengthJudgement()) {
typingEffect("密码至少包含数字、大小写字母、特殊字符中的两种");
return false;
} else if (registerPassword.getText().length() != registerPassword.getText().getBytes().length) {
typingEffect("密码中不能存在汉字");
return false;
} else {
typingEffect("密码格式正确");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 密码强度校验
* @Date 17:06
* @Param []
* @return java.lang.String
**/
public boolean passwordStrengthJudgement() {
int flag = 0;
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_NUMBER)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_LOWERCASE)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_UPPERCASE)) {
flag++;
}
if (registerPassword.getText().matches(UserConstants.PASSWORD_REG_SYMBOL)) {
flag++;
}
return flag >= 2;
}
/**
* @Author GirtSeanking
* @Description //TODO 用户再次确认密码时的事件响应
* @Date 18:50
* @Param [keyEvent]
* @return void
**/
public void passwordAaginKeyRelease(KeyEvent keyEvent) {
judgePasswordAaging();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户确认密码校验
* @Date 21:27
* @Param []
* @return boolean
**/
public boolean judgePasswordAaging() {
if (registerPasswordAgain.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!registerPasswordAgain.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("不能输入空格");
registerPasswordAgain.setText("");
return false;
} else if (registerPassword.getText().isEmpty()) {
typingEffect("您还未设置登录密码");
registerPasswordAgain.setText("");
return false;
} else if (registerPassword.getText().equals(registerPasswordAgain.getText())) {
typingEffect("两次密码一致");
return true;
} else {
typingEffect("两次密码不一致");
return false;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题时的事件响应
* @Date 21:08
* @Param [keyEvent]
* @return void
**/
public void securityQuestionKeyRelease(KeyEvent keyEvent) {
judgeScurityQuestion();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题校验
* @Date 21:30
* @Param []
* @return boolean
**/
public boolean judgeScurityQuestion() {
if (securityQuestion.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (!securityQuestion.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("设置的密保问题中不能存在空格");
return false;
} else if (securityQuestion.getText().length() > UserConstants.SCURITY_QUESTION_MAX_LENGTH) {
typingEffect("设置的密保问题内容过长");
return false;
} else {
typingEffect("请尽量设置简短又好记的问题");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题的答案时的事件响应
* @Date 21:14
* @Param [keyEvent]
* @return void
**/
public void questionAnswerKeyRelease(KeyEvent keyEvent) {
judgeQuestionAnswer();
}
/**
* @Author GirtSeanking
* @Description //TODO 用户设置密保问题答案校验
* @Date 21:31
* @Param []
* @return boolean
**/
public boolean judgeQuestionAnswer() {
if (questionAnswer.getText().isEmpty()) {
typingEffect("注册");
return false;
} else if (questionAnswer.getText().matches(UserConstants.SPACE_REG)) {
typingEffect("设置答案中不能存在空格");
return false;
} else if (questionAnswer.getText().length() > UserConstants.QUESTION_ANSWER_MAX_LENGTH) {
typingEffect("设置的答案内容过长");
return false;
} else {
typingEffect("请尽量设置简短又好记的答案");
return true;
}
}
/**
* @Author GirtSeanking
* @Description //TODO 注册按钮样式变化设置
* @Date 21:33
* @Param [mouseEvent]
* @return void
**/
public void registerBtnMouseEnter(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%)");
}
public void registerBtnMouseExit(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to right, #4facfe 0%, #00f2fe 100%)");
}
public void registerBtnMousePress(MouseEvent mouseEvent) {
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #30cfd0 0%, #330867 100%)");
}
/**
* @Author GirtSeanking
* @Description //TODO 注册按钮点击后的事件响应
* @Date 21:34
* @Param [mouseEvent]
* @return void
**/
public void registerBtnMouseRelease(MouseEvent mouseEvent) {
/* 按钮点击后样式 */
registerBtn.setStyle("-fx-background-color: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%)");
if (judgeRegisterForm()) {
userReister();
} else {
typingEffect("请仔细填写注册信息");
}
}
/**
* @Author GirtSeanking
* @Description //TODO 判断注册表单
* @Date 21:37
* @Param []
* @return boolean
**/
public boolean judgeRegisterForm() {
if (judgeUserName()) {
if (judgePassword()) {
if (judgePasswordAaging()) {
if (judgeScurityQuestion()) {
if (judgeQuestionAnswer()) {
return true;
}
}
}
}
}
return false;
}
/**
* @Author GirtSeanking
* @Description //TODO 进行用户注册功能
* @Date 9:39
* @Param []
* @return void
**/
public void userReister() {
}
public void typingEffect(String msg) {
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(700));
}
@Override
protected void interpolate(double frac) {
final int length = msg.length();
final int n = Math.round(length * (float) frac);
welcomeLabel.setText(msg.substring(0, n));
}
};
animation.play();
}
}
| 12,696 | 0.571356 | 0.556338 | 427 | 26.601873 | 22.199032 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.288056 | false | false | 4 |
0954e438b5c2229eb24fe6efe9b39bc110ca6de9 | 11,519,102,319,806 | a613b0a7287696b42f3d977447746c2bde573394 | /application-server/group-project-application/src/main/java/com/app/groupprojectapplication/service/IVisaStatusService.java | 32581aa577457cf466e82ea64aeffd925fb5b44c | [
"MIT"
] | permissive | YaochengTong/GroupProjectOne | https://github.com/YaochengTong/GroupProjectOne | 16311cd513b65bb761ff0f5c0ded48269ef97f4a | 2dae47d89032cb225bd8ca981c2ae5c07406ca6c | refs/heads/main | 2023-06-10T06:25:12.507000 | 2021-06-21T21:02:43 | 2021-06-21T21:02:43 | 376,469,922 | 0 | 0 | MIT | true | 2021-06-13T07:28:16 | 2021-06-13T07:28:15 | 2021-06-12T02:11:16 | 2021-06-13T03:33:04 | 63 | 0 | 0 | 0 | null | false | false | package com.app.groupprojectapplication.service;
import com.app.groupprojectapplication.domain.visaStatusManagement.VisaStatusInfo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
public interface IVisaStatusService {
List<VisaStatusInfo> getVisaInfoList();
VisaStatusInfo getVisaInfo(Integer userId);
String findEmailByUserId(Integer userId);
boolean updateInfo(Map<String, Object> result);
Map<String, Object> uploadAndUpdate(List<MultipartFile> files, Map<String, Object> paramMap, Integer userId);
}
| UTF-8 | Java | 580 | java | IVisaStatusService.java | Java | [] | null | [] | package com.app.groupprojectapplication.service;
import com.app.groupprojectapplication.domain.visaStatusManagement.VisaStatusInfo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
public interface IVisaStatusService {
List<VisaStatusInfo> getVisaInfoList();
VisaStatusInfo getVisaInfo(Integer userId);
String findEmailByUserId(Integer userId);
boolean updateInfo(Map<String, Object> result);
Map<String, Object> uploadAndUpdate(List<MultipartFile> files, Map<String, Object> paramMap, Integer userId);
}
| 580 | 0.806897 | 0.806897 | 15 | 37.666668 | 31.111984 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
ef62e7521f67f593ea305933e0104ba6e16c9587 | 9,766,755,652,305 | 28ee846c31050c999c9f22d4ed49d86c421eacb5 | /BudgetMasterServer/src/main/java/de/deadlocker8/budgetmaster/reports/columns/ReportColumn.java | 69959c753bd11e713eb1a068f3a0829808ee713b | [
"MIT"
] | permissive | deadlocker8/BudgetMaster | https://github.com/deadlocker8/BudgetMaster | 1fd72877bf1296852ce7d6d18e42b1724209c3b6 | 5b5c0f58f7c6d69e00214db9d653cb1469934c7d | refs/heads/master | 2023-07-27T08:54:46.408000 | 2023-07-18T19:59:57 | 2023-07-18T19:59:57 | 76,727,757 | 39 | 22 | MIT | false | 2023-06-02T07:17:00 | 2016-12-17T14:11:35 | 2023-05-28T00:19:23 | 2023-05-27T09:33:44 | 101,585 | 35 | 12 | 16 | Java | false | false | package de.deadlocker8.budgetmaster.reports.columns;
import de.deadlocker8.budgetmaster.reports.settings.ReportSettings;
import jakarta.persistence.*;
@Entity
public class ReportColumn
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer ID;
private String localizationKey;
private boolean activated;
private int columnPosition;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private ReportSettings referringSettings;
public ReportColumn(String localizationKey, int columnPosition)
{
this.localizationKey = localizationKey;
this.activated = true;
this.columnPosition = columnPosition;
}
public ReportColumn()
{
}
public Integer getID()
{
return ID;
}
public void setID(Integer ID)
{
this.ID = ID;
}
public String getLocalizationKey()
{
return localizationKey;
}
public void setLocalizationKey(String key)
{
this.localizationKey = key;
}
public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getColumnPosition()
{
return columnPosition;
}
public void setColumnPosition(int position)
{
this.columnPosition = position;
}
public ReportSettings getReferringSettings()
{
return referringSettings;
}
public void setReferringSettings(ReportSettings referringSettings)
{
this.referringSettings = referringSettings;
}
@Override
public String toString()
{
return "ReportColumn{" +
"ID=" + ID +
", localizationKey='" + localizationKey + '\'' +
", activated=" + activated +
", columnPosition=" + columnPosition +
'}';
}
}
| UTF-8 | Java | 1,643 | java | ReportColumn.java | Java | [] | null | [] | package de.deadlocker8.budgetmaster.reports.columns;
import de.deadlocker8.budgetmaster.reports.settings.ReportSettings;
import jakarta.persistence.*;
@Entity
public class ReportColumn
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer ID;
private String localizationKey;
private boolean activated;
private int columnPosition;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private ReportSettings referringSettings;
public ReportColumn(String localizationKey, int columnPosition)
{
this.localizationKey = localizationKey;
this.activated = true;
this.columnPosition = columnPosition;
}
public ReportColumn()
{
}
public Integer getID()
{
return ID;
}
public void setID(Integer ID)
{
this.ID = ID;
}
public String getLocalizationKey()
{
return localizationKey;
}
public void setLocalizationKey(String key)
{
this.localizationKey = key;
}
public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getColumnPosition()
{
return columnPosition;
}
public void setColumnPosition(int position)
{
this.columnPosition = position;
}
public ReportSettings getReferringSettings()
{
return referringSettings;
}
public void setReferringSettings(ReportSettings referringSettings)
{
this.referringSettings = referringSettings;
}
@Override
public String toString()
{
return "ReportColumn{" +
"ID=" + ID +
", localizationKey='" + localizationKey + '\'' +
", activated=" + activated +
", columnPosition=" + columnPosition +
'}';
}
}
| 1,643 | 0.732806 | 0.731589 | 92 | 16.858696 | 19.124638 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.336957 | false | false | 4 |
e079c579d479c1c6a2512ed1a1adf965795b5f01 | 11,682,311,098,105 | 7b7e9816a5edd7bcd1c9da6ed7abc78272e4a791 | /test/files/neg/t4581/static_2.java | 2fd5bf1d822ec767f7724e891306d02a1f72a4d9 | [
"LicenseRef-scancode-generic-cla"
] | no_license | rkuhn/scala | https://github.com/rkuhn/scala | aceb73407e4f639bcc76a018e703340c73259042 | 4f9851d1fdbad7c5584931935e138b16d20ac478 | refs/heads/master | 2020-05-19T09:52:51.576000 | 2012-09-05T07:48:41 | 2012-09-05T07:48:41 | 2,052,679 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class static_2 {
public static void main(String[] args) {
Constants.Const = 17;
Constants.FinalConst = 99;
Constants.MutableField = 199;
}
}
| UTF-8 | Java | 164 | java | static_2.java | Java | [] | null | [] |
public class static_2 {
public static void main(String[] args) {
Constants.Const = 17;
Constants.FinalConst = 99;
Constants.MutableField = 199;
}
}
| 164 | 0.664634 | 0.615854 | 7 | 21.285715 | 13.718749 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.571429 | false | false | 4 |
40dbefe10ab39466a48260c741d9c3e8bd88b074 | 4,020,089,430,158 | c3d412e89aea72c7e3cefc2d6749d110d5071e85 | /src/AllSolutions/Jzoffer471.java | 80753385b4571a018d21a939aa471ab258756b7d | [] | no_license | Super262/JianzhiSolutionsInJava | https://github.com/Super262/JianzhiSolutionsInJava | c851ef45263ea9a246681537f283722446e9d3f1 | 3be83a7f32754360dace269613c0514ad15d587b | refs/heads/master | 2023-02-25T12:30:12.086000 | 2021-02-01T12:51:44 | 2021-02-01T12:51:44 | 330,841,703 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package AllSolutions;
public class Jzoffer471 {
public int maxValue(int[][] grid) {
final int height = grid.length + 1;
final int width = grid[0].length + 1;
int[][] pathValue = new int[height][width];
pathValue[0][0] = grid[0][0];
for (int i = 1; i < height; ++i) {
for (int j = 1; j < width; ++j) {
pathValue[i][j] = Math.max(pathValue[i][j],Math.max(pathValue[i - 1][j],pathValue[i][j - 1]) + grid[i - 1][j - 1]);
}
}
return pathValue[height - 1][width - 1];
}
}
| UTF-8 | Java | 571 | java | Jzoffer471.java | Java | [] | null | [] | package AllSolutions;
public class Jzoffer471 {
public int maxValue(int[][] grid) {
final int height = grid.length + 1;
final int width = grid[0].length + 1;
int[][] pathValue = new int[height][width];
pathValue[0][0] = grid[0][0];
for (int i = 1; i < height; ++i) {
for (int j = 1; j < width; ++j) {
pathValue[i][j] = Math.max(pathValue[i][j],Math.max(pathValue[i - 1][j],pathValue[i][j - 1]) + grid[i - 1][j - 1]);
}
}
return pathValue[height - 1][width - 1];
}
}
| 571 | 0.502627 | 0.471103 | 16 | 34.6875 | 30.320618 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 4 |
3db892c5cd139948934424cd03683fbff82cf847 | 26,121,991,156,821 | cf6db2647b285ef065a3d6e16d28874e9d1b3293 | /SpringHelloWorldAnnotation/src/com/deepsingh44/model/Book.java | 60b448d3ef45265ddfdfce5c61dd6c83d1abf510 | [] | no_license | deepsingh44/Spring-Hibernate-Project-Tutorial | https://github.com/deepsingh44/Spring-Hibernate-Project-Tutorial | d7accc49514e028ae96f1e7d5ab21da6f3ec8f97 | dd038b59e95117604e9cd0508b4216a7b0e0b98b | refs/heads/master | 2023-03-30T02:35:21.944000 | 2021-04-07T06:26:34 | 2021-04-07T06:26:34 | 353,610,071 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.deepsingh44.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String author;
private float price;
private String category;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
| UTF-8 | Java | 1,114 | java | Book.java | Java | [] | null | [] | package com.deepsingh44.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String author;
private float price;
private String category;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
| 1,114 | 0.711849 | 0.710054 | 69 | 15.144928 | 13.927634 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15942 | false | false | 4 |
c76d871d6017fdba9721affaa843058df4df0a1b | 13,640,816,192,631 | 5a9c15643215b4eefde85d8f869f305d7fa52767 | /PKI_Mobile/app/src/main/java/com/example/milan/mojmajstor/utils/CommentsListViewAdapter.java | fb3077dfa3e11eb34734ad21fddba4f0afebefbc | [] | no_license | dusandjoric995/PKI_Mobile | https://github.com/dusandjoric995/PKI_Mobile | 05373387466076e7fc006b1021a278bb86a6763c | 19d3d0de3e37a18e6653c3bcafbddd6f027a555b | refs/heads/master | 2020-04-15T22:20:22.668000 | 2019-02-05T10:26:42 | 2019-02-05T10:26:42 | 165,068,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.milan.mojmajstor.utils;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.milan.mojmajstor.R;
import java.util.ArrayList;
public class CommentsListViewAdapter extends ArrayAdapter<Pair<User, String>> {
private ArrayList<Pair<User, String>> dataSet;
Activity thisActivity;
public CommentsListViewAdapter(Activity thisActivity, ArrayList<Pair<User, String>> dataSet) {
super(thisActivity, R.layout.list_view_item_comment, dataSet);
this.dataSet = dataSet;
this.thisActivity = thisActivity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Pair<User, String> comment = getItem(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_view_item_comment, null);
}
TextView tvFirstAndLastName = convertView.findViewById(R.id.tvCFirstAndLastName);
TextView tvComment = convertView.findViewById(R.id.tvCComment);
tvFirstAndLastName.setText(comment.first.getFirstAndLastName());
tvComment.setText(comment.second);
return convertView;
}
}
| UTF-8 | Java | 1,529 | java | CommentsListViewAdapter.java | Java | [] | null | [] | package com.example.milan.mojmajstor.utils;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.milan.mojmajstor.R;
import java.util.ArrayList;
public class CommentsListViewAdapter extends ArrayAdapter<Pair<User, String>> {
private ArrayList<Pair<User, String>> dataSet;
Activity thisActivity;
public CommentsListViewAdapter(Activity thisActivity, ArrayList<Pair<User, String>> dataSet) {
super(thisActivity, R.layout.list_view_item_comment, dataSet);
this.dataSet = dataSet;
this.thisActivity = thisActivity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Pair<User, String> comment = getItem(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_view_item_comment, null);
}
TextView tvFirstAndLastName = convertView.findViewById(R.id.tvCFirstAndLastName);
TextView tvComment = convertView.findViewById(R.id.tvCComment);
tvFirstAndLastName.setText(comment.first.getFirstAndLastName());
tvComment.setText(comment.second);
return convertView;
}
}
| 1,529 | 0.740353 | 0.739699 | 44 | 33.75 | 30.581579 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795455 | false | false | 4 |
c5f24a006a9dd9010a4c9259aa984f308b63d7d2 | 19,155,554,142,859 | 8de24eab5dc3dc615418269925872e7183cc5b31 | /PIKA-JDK-Study2019/src/pika/java/study/pract/week13_task1.java | 18bc918d579c5fe641e37cbd1bbe5224537f9760 | [] | no_license | PIKACHUIM/Pika-JDK-App-Study19 | https://github.com/PIKACHUIM/Pika-JDK-App-Study19 | 76e19fbc91e67723bc2e17fdfa77f2a08e659229 | 354b8913420544c3d52218b2b1200be926139a73 | refs/heads/master | 2022-06-09T03:04:43.719000 | 2020-05-05T04:02:35 | 2020-05-05T04:02:35 | 218,663,333 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pika.java.study.pract;
public class week13_task1 {
public static void main(String[] args){
complex t1=new complex( 1,5);
complex t2=new complex( 4,6);
show("源复数:");t1.com_pnt();
show("源复数:");t2.com_pnt();
t1.com_add(t2);show("做加法:");t1.com_pnt();
t1.com_mul(t2);show("做乘法:");t1.com_pnt();
t1.com_sub(t2);show("做减法:");t1.com_pnt();
t1.com_div(t2);show("做除法:");t1.com_pnt();
}
static void show(String in){System.out.print(in);}
}
class complex{
public double a; //存储实部
public double b; //存储虚部
public complex( ){a= 0;b= 0;} //无参构造
public complex(double ia ){a=ia;b= 0;} //实部构造
public complex(double ia,double ib){a=ia;b=ib;} //完整构造
public double getreal(){return a;} //获取实部
public double getimag(){return b;} //获取虚部
public void com_add(complex is){a+=is.a;b+=is.b;}//复数加法
public void com_sub(complex is){a-=is.a;b-=is.b;}//复数减法
public void com_mul(complex is){ //复数乘法
a=a*is.a-b*is.b; b=a*is.b+b*is.a;}
public void com_div(complex is){ //复数除法
a=a*is.a+b*is.b/(is.a*is.a-is.b*is.b);
b=a*is.b+b*is.a/(is.a*is.a-is.b*is.b); }
public String com_str( ){ //转换字符
String t=String.format(" %.4f",a);
if(b-0.000001!=0)
if(b>0)
t=t+String.format("+%.4f",b);
else
t=t+String.format("%.4f",b);
return t; }
public void com_pnt( ){ //显示复数
System.out.println(this.com_str()); }
}
| UTF-8 | Java | 1,926 | java | week13_task1.java | Java | [] | null | [] | package pika.java.study.pract;
public class week13_task1 {
public static void main(String[] args){
complex t1=new complex( 1,5);
complex t2=new complex( 4,6);
show("源复数:");t1.com_pnt();
show("源复数:");t2.com_pnt();
t1.com_add(t2);show("做加法:");t1.com_pnt();
t1.com_mul(t2);show("做乘法:");t1.com_pnt();
t1.com_sub(t2);show("做减法:");t1.com_pnt();
t1.com_div(t2);show("做除法:");t1.com_pnt();
}
static void show(String in){System.out.print(in);}
}
class complex{
public double a; //存储实部
public double b; //存储虚部
public complex( ){a= 0;b= 0;} //无参构造
public complex(double ia ){a=ia;b= 0;} //实部构造
public complex(double ia,double ib){a=ia;b=ib;} //完整构造
public double getreal(){return a;} //获取实部
public double getimag(){return b;} //获取虚部
public void com_add(complex is){a+=is.a;b+=is.b;}//复数加法
public void com_sub(complex is){a-=is.a;b-=is.b;}//复数减法
public void com_mul(complex is){ //复数乘法
a=a*is.a-b*is.b; b=a*is.b+b*is.a;}
public void com_div(complex is){ //复数除法
a=a*is.a+b*is.b/(is.a*is.a-is.b*is.b);
b=a*is.b+b*is.a/(is.a*is.a-is.b*is.b); }
public String com_str( ){ //转换字符
String t=String.format(" %.4f",a);
if(b-0.000001!=0)
if(b>0)
t=t+String.format("+%.4f",b);
else
t=t+String.format("%.4f",b);
return t; }
public void com_pnt( ){ //显示复数
System.out.println(this.com_str()); }
}
| 1,926 | 0.465051 | 0.44363 | 41 | 42.268291 | 19.101812 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.195122 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.