blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dfb9df2f94b970124832af8e8cdd3b08a48d93ad | 17bfc4fb7ecd2aecdb5c9db14e319352424148ec | /ATest/src/main/java/com/shirley/aTest/Controller/AssertResultController.java | 2792b89e95db6b52b029483e340aebefd2418d54 | []
| no_license | litian093488/ATest | 698c6f462eb64daf604f09d18210ae7f92f21859 | cc91c9bd9512bdcb0125dc16c264213d7e31fb62 | refs/heads/master | 2020-07-18T08:36:54.245422 | 2019-08-30T01:10:43 | 2019-08-30T01:10:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,014 | java | package com.shirley.aTest.Controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.shirley.aTest.entity.AssertResult;
import com.shirley.aTest.jsonHelper.PageHelper;
import com.shirley.aTest.service.AssertResultService;
/**
* @Description: TODO(测试报告控制类)
* @author [email protected]
* @date 2019年7月11日 上午10:56:43
*/
@Controller
public class AssertResultController {
@Resource(name = "assertResultService")
private AssertResultService assertResultService;
@RequestMapping(value = "/assertResultList", method = RequestMethod.GET)
public String assertResultList() {
return "assertResult";
}
@RequestMapping(value = "/assertResultDetail", method = RequestMethod.GET)
public String assertResultDetail() {
return "assertResultDetail";
}
/**
* 查找断言结果集(by 任务id)
*/
@RequestMapping(value = "/queryAssertResults", method = RequestMethod.GET)
@ResponseBody
public PageHelper<AssertResult> queryAssertResults(Integer pageNumber, Integer pageSize, Integer taskId) {
if (null != pageNumber && null != pageSize && null != taskId) {
List<AssertResult> assertResults = assertResultService.QueryAsserts(pageNumber, pageSize, taskId);
PageHelper<AssertResult> pageHelper = new PageHelper<AssertResult>();
// 统计总记录数
pageHelper.setTotal(assertResultService.QueryAssertsCount(taskId));
pageHelper.setRows(assertResults);
return pageHelper;
}
return null;
}
/**
* 查找断言结果详情
*/
@RequestMapping(value = "/queryAssertResult", method = RequestMethod.POST)
@ResponseBody
public AssertResult queryAssertResult(Integer assertResultId) {
if (null != assertResultId)
return assertResultService.QueryAssert(assertResultId);
return null;
}
}
| [
"[email protected]"
]
| |
4c7d97091482f8eb5ad1f30519c83fcec4616e2d | 56173a6725f814e10781e3f58d2476213f5ee00b | /src/test/java/io/github/cernier/yml2props/Yml2PropsConvertMojoTest.java | 708af1defc0aa30b3a09cea3d189e86e877226ea | [
"Apache-2.0"
]
| permissive | cernier/yml2props-maven-plugin | 4624e969695d9b70100cf3060739aa0c35863fa1 | 4ddf4c5160e047a57d776f6e649ab45aa1dd26ac | refs/heads/master | 2023-05-31T09:45:14.052465 | 2021-05-31T23:26:01 | 2021-05-31T23:28:24 | 368,127,199 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,759 | java | package io.github.cernier.yml2props;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
import static org.codehaus.plexus.PlexusTestCase.getBasedir;
import static org.junit.Assert.assertNotEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import org.apache.commons.io.FilenameUtils;
import org.apache.maven.plugin.testing.MojoRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class Yml2PropsConvertMojoTest {
@Rule
public MojoRule mojoRule = new MojoRule();
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Before
public void setUp() throws Exception {
File testPom = new File(getBasedir(), "target/test-classes/plugin-config.xml");
mojoUnderTest = (Yml2PropsConvertMojo) mojoRule.lookupMojo("convert", testPom);
mojoUnderTest.setIncludes("**/*.yml,**/*.yaml");
mojoUnderTest.setInputDirectory(testFolder.getRoot());
mojoUnderTest.setInputCharset("UTF-8");
mojoUnderTest.setOutputCharset("UTF-8");
mojoUnderTest.setDeleteOriginalFileAfterSuccessfulConversion(true);
}
private Yml2PropsConvertMojo mojoUnderTest;
@Test
public void testConvertBasic() throws Exception {
File directory = writeToFile("foo/bar.yml",
"foo:",
" bar: 42"
);
mojoUnderTest.execute();
Properties properties = loadPropertiesFromFile(directory, "bar.properties");
assertEquals(1, properties.size());
assertEquals("42", properties.getProperty("foo.bar"));
assertFalse(new File(directory, "bar.yml").exists());
}
@Test
public void testConvertComplexStructure() throws Exception {
File directory = writeToFile("foo/bar.yml",
"root:",
" foo:",
" bar: 42",
" items:",
" - prop1: 'value0.1'",
" prop2: 'value0.2'",
" - prop1: 'value1.1'",
" prop2: 'value1.2'"
);
mojoUnderTest.execute();
Properties properties = loadPropertiesFromFile(directory, "bar.properties");
assertEquals(5, properties.size());
assertEquals("42", properties.getProperty("root.foo.bar"));
assertEquals("value0.1", properties.getProperty("root.foo.items[0].prop1"));
assertEquals("value0.2", properties.getProperty("root.foo.items[0].prop2"));
assertEquals("value1.1", properties.getProperty("root.foo.items[1].prop1"));
assertEquals("value1.2", properties.getProperty("root.foo.items[1].prop2"));
}
@Test
public void testConvertOnlyIncluded() throws Exception {
mojoUnderTest.setIncludes("included/**/*.yml");
mojoUnderTest.setInputDirectory(testFolder.getRoot());
File includedFileDirectory = writeToFile("included/foo/bar.yml",
"included:",
" foo:",
" bar: 42"
);
File anotherIncludedFileDirectory = writeToFile("included/another/bar.yml",
"included:",
" another:",
" bar: 42"
);
File excludedFileDirectory = writeToFile("excluded/foo/bar.yml",
"excluded:",
" foo:",
" bar: 42"
);
mojoUnderTest.execute();
assertEquals(1, loadPropertiesFromFile(includedFileDirectory, "bar.properties").size());
assertEquals(1, loadPropertiesFromFile(anotherIncludedFileDirectory, "bar.properties").size());
try {
loadPropertiesFromFile(excludedFileDirectory, "bar.properties");
fail("FileNotFoundException should have been thrown.");
} catch (Exception e) {
assertTrue(e instanceof FileNotFoundException);
}
}
@Test
public void testConvertWithCharsetSupport() throws Exception {
File directory = writeToFileWithCharset("foo/bar.yml", "ISO-8859-1",
"foo:",
" bar: caractères accentués"
);
// Execute with default (and wrong) charsets (UTF-8)
mojoUnderTest.setDeleteOriginalFileAfterSuccessfulConversion(false); // to be able to re-execute a 2nd time
mojoUnderTest.execute();
assertNotEquals("caractères accentués", loadPropertiesFromFile(directory, "bar.properties").getProperty("foo.bar"));
assertTrue(new File(directory, "bar.yml").exists());
// Execute with appropriate charsets
mojoUnderTest.setInputCharset("ISO-8859-1");
mojoUnderTest.setOutputCharset("ISO-8859-1");
mojoUnderTest.setDeleteOriginalFileAfterSuccessfulConversion(true); // restore default cleaning config parameter
mojoUnderTest.execute();
assertEquals("caractères accentués", loadPropertiesFromFile(directory, "bar.properties").getProperty("foo.bar"));
assertFalse(new File(directory, "bar.yml").exists());
}
private File writeToFile(String fileName, String... lines) throws IOException {
return writeToFileWithCharset(fileName, "UTF-8", lines);
}
private File writeToFileWithCharset(String fileName, String charsetName, String... lines) throws IOException {
File directory = testFolder.newFolder(FilenameUtils.getPathNoEndSeparator(fileName).split("/"));
File file = new File(directory, FilenameUtils.getName(fileName));
PrintWriter printWriter = new PrintWriter(file, charsetName);
for (String line : lines) {
printWriter.println(line);
}
printWriter.close();
return directory;
}
private Properties loadPropertiesFromFile(File directory, String fileName) throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream(new File(directory, fileName)));
return properties;
}
}
| [
"[email protected]"
]
| |
18fa03b4f6a8eb0194b95d1141587d40cb83da05 | 937c455c9ebef35feb0046ea568e7402d1d8f833 | /Source/org/xianwu/dec/admin/service/CuttoolholderService.java | 5e43e55c0f000c0d730c6b6542a79dfb20d7a5af | []
| no_license | 743234238wubo/ipv6 | 42cf9e73c7114b0b9ec2b3353069e3f2edff5c1a | 9366a6155a502ec2d0fad67d9f9a17e451f4a895 | refs/heads/master | 2020-09-18T14:08:17.373756 | 2019-12-24T03:20:36 | 2019-12-24T03:20:36 | 224,151,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 901 | java | package org.xianwu.dec.admin.service;
import java.util.List;
import org.xianwu.core.metatype.Dto;
import org.xianwu.core.model.service.BizService;
/**
* 切断切槽刀体
*
* @author XianwuFu
* @since 2013-01-01
*/
public interface CuttoolholderService extends BizService {
/**
* 保存刀体
*
* @param pDto
* @return
*/
public Dto saveCuttoolholder(Dto pDto);
/**
* 批量保存刀体
*
* @param pDto
* @return
*/
public Dto batchSaveCuttoolholder(List<Dto> list);
/**
* 保存刀体
*
* @param pDto
* @return
*/
public Dto insertCuttoolholder(Dto pDto);
/**
* 删除刀体
*
* @param pDto
* @return
*/
public Dto deleteCuttoolholder(Dto pDto);
/**
* 修改刀体
*
* @param pDto
* @return
*/
public Dto updateCuttoolholder(Dto pDto);
public Dto saveMainTable(Dto dto);
public Dto saveSubTable(Dto dto);
}
| [
"[email protected]"
]
| |
2423eca332045b8f96094087b5eeec5bab10e25b | 8e438478f28dea3f1ce38ba927c6615d99833150 | /sistema/Filme/src/gui/Action/CancelarFilmeAction.java | 1951401e591e7441c7715831d1a8721615ee56fe | []
| no_license | Dyeniffer/Projeto-Filmes | 893d20add474b251263aa46d3cc41d6739d2fc26 | 037abc6635db1b122ee8e185870d9193881214c9 | refs/heads/master | 2021-01-22T23:43:25.438333 | 2013-11-26T12:27:17 | 2013-11-26T12:27:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 446 | java | package gui.Action;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import gui.CadastrarFilmePanel;
public class CancelarFilmeAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private CadastrarFilmePanel panel;
public CancelarFilmeAction(CadastrarFilmePanel panel) {
super("Cancelar");
this.panel = panel;
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
} | [
"[email protected]"
]
| |
6d8e846c4b26d1689b97b9e0a7843fef47d1a8e0 | e9746857961ab18f139096f9368f00d56666a2c4 | /src/test/java/org/quantum/quantumtest/config/timezone/HibernateTimeZoneIT.java | 5f9468556a5a7b084f928e60845fe4a686fb998a | [
"MIT"
]
| permissive | Quantum-P3/quantum-test | a80d28e481d8d7a05ac62518fff71cf1de6d66df | 6dd84c83e71701ad087310c8fa883735fd1a5d51 | refs/heads/main | 2023-05-24T10:45:59.080175 | 2021-06-19T05:15:33 | 2021-06-19T05:15:33 | 372,646,737 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,732 | java | package org.quantum.quantumtest.config.timezone;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.quantum.quantumtest.IntegrationTest;
import org.quantum.quantumtest.repository.timezone.DateTimeWrapper;
import org.quantum.quantumtest.repository.timezone.DateTimeWrapperRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the ZoneId Hibernate configuration.
*/
@IntegrationTest
class HibernateTimeZoneIT {
@Autowired
private DateTimeWrapperRepository dateTimeWrapperRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
@Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}")
private String zoneId;
private DateTimeWrapper dateTimeWrapper;
private DateTimeFormatter dateTimeFormatter;
private DateTimeFormatter timeFormatter;
private DateTimeFormatter dateFormatter;
@BeforeEach
public void setup() {
dateTimeWrapper = new DateTimeWrapper();
dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z"));
dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0"));
dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00"));
dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00"));
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId));
timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId));
dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
}
@Test
@Transactional
void storeInstantWithZoneIdConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("instant", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant());
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetTime()
.toLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
private String generateSqlRequest(String fieldName, long id) {
return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id);
}
private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) {
while (sqlRowSet.next()) {
String dbValue = sqlRowSet.getString(1);
assertThat(dbValue).isNotNull();
assertThat(dbValue).isEqualTo(expectedValue);
}
}
}
| [
"[email protected]"
]
| |
7626dc0e77c13b5fbcc3e1c9771e4776d176b601 | 1b37678c173585a25148635ed96261554f117acb | /src/main/SerialConnection/CommandSenderConnected.java | ff347c510f5d2e2cf101876a6e21eca1f6f7fdcf | []
| no_license | Hermann-Erk/BOA_Compressor_Controller | de68740af636cd390c5ab5fa40cafec3e521e390 | 074e5f4e879113d66301cce904754600420290d5 | refs/heads/master | 2021-01-23T20:23:22.859943 | 2018-07-12T10:45:56 | 2018-07-12T10:45:56 | 102,855,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 584 | java | package main.SerialConnection;
/**
* Created by Hermann on 14.09.2017.
*/
/**
* This should be implemented by all control panels, that use the command senders to send data to the arduino.
* It forces the controllers to implement a method to update the commandSenders if the connection is lost and
* then re-established. In this case new command Senders are initialized and the controllers might still refer
* to the old ones.
*/
public interface CommandSenderConnected {
void setNewCommandSenders(CommandSenderInterface frontSender, CommandSenderInterface backSender);
}
| [
"[email protected]"
]
| |
8dce198100f2a89be5c8db772be5db71c1ea6a7f | 678a3d58c110afd1e9ce195d2f20b2531d45a2e0 | /sources/com/airbnb/android/lib/fragments/alerts/AlertsFragment_ViewBinding.java | a0698deafc5fa3115ff73fc665c395ec0a304691 | []
| no_license | jasonnth/AirCode | d1c37fb9ba3d8087efcdd9fa2103fb85d13735d5 | d37db1baa493fca56f390c4205faf5c9bbe36604 | refs/heads/master | 2020-07-03T08:35:24.902940 | 2019-08-12T03:34:56 | 2019-08-12T03:34:56 | 201,842,970 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,385 | java | package com.airbnb.android.lib.fragments.alerts;
import android.support.p002v7.widget.RecyclerView;
import android.view.View;
import butterknife.Unbinder;
import butterknife.internal.Utils;
import com.airbnb.android.core.views.AirSwipeRefreshLayout;
import com.airbnb.android.lib.C0880R;
import com.airbnb.p027n2.components.AirToolbar;
public class AlertsFragment_ViewBinding implements Unbinder {
private AlertsFragment target;
public AlertsFragment_ViewBinding(AlertsFragment target2, View source) {
this.target = target2;
target2.toolbar = (AirToolbar) Utils.findRequiredViewAsType(source, C0880R.C0882id.alerts_toolbar, "field 'toolbar'", AirToolbar.class);
target2.recyclerView = (RecyclerView) Utils.findRequiredViewAsType(source, C0880R.C0882id.recycler_view, "field 'recyclerView'", RecyclerView.class);
target2.swipeRefreshLayout = (AirSwipeRefreshLayout) Utils.findRequiredViewAsType(source, C0880R.C0882id.swipe_refresh_layout, "field 'swipeRefreshLayout'", AirSwipeRefreshLayout.class);
}
public void unbind() {
AlertsFragment target2 = this.target;
if (target2 == null) {
throw new IllegalStateException("Bindings already cleared.");
}
this.target = null;
target2.toolbar = null;
target2.recyclerView = null;
target2.swipeRefreshLayout = null;
}
}
| [
"[email protected]"
]
| |
c21149fb425031d07c58ad2d24e5f6668d7bed61 | 62c4b1cd5e15676126536e72aeddbe94c7c08a8c | /app/src/main/java/com/redside/rngquest/items/ManaPotionItem.java | 22e7b7b9c39dc86a8e49b7c6a74d57a86e5ae67a | []
| no_license | redside100/RNGQuest | cc3862051ca6503edb6e5a3a39c415a52419fbe5 | 30fe9ca6b0c8f067f422806225b14013b89d2872 | refs/heads/master | 2021-01-11T22:02:03.537203 | 2018-01-23T01:53:06 | 2018-01-23T01:53:06 | 78,902,497 | 5 | 4 | null | 2017-02-08T22:21:17 | 2017-01-14T01:46:04 | Java | UTF-8 | Java | false | false | 1,016 | java | package com.redside.rngquest.items;
import android.graphics.Color;
import com.redside.rngquest.entities.Player;
import com.redside.rngquest.gameobjects.Item;
import com.redside.rngquest.managers.AnimatedTextManager;
import com.redside.rngquest.managers.CoreManager;
import com.redside.rngquest.managers.HUDManager;
import com.redside.rngquest.utils.Assets;
public class ManaPotionItem extends Item {
public ManaPotionItem(){
super(ItemType.MANA_POTION, Player.Role.ALL, "Mana Potion: Restores 40 MP" , 80, Assets.getBitmapFromMemory("items_mana_potion"), 2);
}
/**
* {@inheritDoc}
*/
@Override
public void use(){
// Display text, and add mana
HUDManager.displayFadeMessage("Recovered 40 MP", CoreManager.width / 2, (int) (CoreManager.height * 0.31), 30, 18, Color.BLUE);
HUDManager.displayParticleEffect((int) (CoreManager.height * 0.28), (int) (CoreManager.height * 0.31), Color.BLUE);
Player.addMana(40);
}
}
| [
"[email protected]"
]
| |
2f66cf44a1626357a7117412e0fc655448396a71 | eb653419205c764d9da622ababbd3b767f72f23a | /demo-microservice-sso/src/main/java/com/microservice/sso/controller/SsoController.java | b6178b63fd37c2f86dcfc3d9fc59187fdeb2ffaa | []
| no_license | agstar/spring-cloud-demo | fa11803f44afde6baed835835e1ec9b1eda3a2a8 | 829061c876e42756bc628d23475966a3e97bcf16 | refs/heads/master | 2020-03-16T15:21:24.088241 | 2018-07-22T10:01:52 | 2018-07-22T10:01:52 | 132,740,122 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | package com.microservice.sso.controller;
import com.microservice.sso.pojo.OptResult;
import com.microservice.sso.pojo.User;
import com.microservice.sso.service.SsoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class SsoController {
@Autowired
private SsoService ssoService;
/**
* 登录接口
*
* @param username 账号
* @param password 密码
* @return OptResult
*/
@GetMapping(value = "login/{username}/{password}")
public OptResult queryItemById(@PathVariable("username") String username, @PathVariable("password") String password) {
User user = ssoService.checkUser(username, password);
if (user == null || user.getId() == null) {
return new OptResult(1, "登录失败", user);
}
return new OptResult(1, "登录成功", user);
}
}
| [
"[email protected]"
]
| |
e5fef9bfa716659537fdedf724d81ab5d65e6514 | 31bc8fa48f371ae1ae8f3bf92c1f14d7ecdd8fbd | /src/pohaci/gumunda/titis/project/cgui/EmployeeTimeSheetByCriteria.java | 12bd62ff164395eb74bf0a5e13da515275c63749 | []
| no_license | rukutuk/logicerp | 6398fa9bfd80177d4bfdd186cc404cdd02a4d36f | f34f7cbefaf78655a2d4819d9261905e3cb795b1 | refs/heads/master | 2021-01-15T13:00:03.612993 | 2013-10-28T10:25:19 | 2013-10-28T10:25:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 909 | java | package pohaci.gumunda.titis.project.cgui;
public class EmployeeTimeSheetByCriteria {
long m_qualification,m_indexPersonal;
String m_workDescription,m_areaCode,m_customer,m_ipcno;
int m_days;
public EmployeeTimeSheetByCriteria(long indexPersonal,String workDescription,String AreaCode,
int days,long qualification,String customer,String ipcno){
m_indexPersonal = indexPersonal;
m_workDescription = workDescription;
m_areaCode = AreaCode;
m_days = days;
m_qualification = qualification;
m_areaCode = AreaCode;
m_customer = customer;
m_ipcno = ipcno;
}
public String getWorkdescription(){
return m_workDescription;
}
public String getAreacode(){
return m_areaCode;
}
public int getDays(){
return m_days;
}
public long getQualification(){
return m_qualification;
}
public String getCustomer(){
return m_customer;
}
public String getIpcno(){
return m_ipcno;
}
}
| [
"[email protected]"
]
| |
925e61d84b0ca7dfad27a0b8f4398e8df3d2b3ea | f1eb255c8c2230c96ced0f9165b37ddde990a365 | /java/modular-project-exmaple/javastrap/sdocommon-modular/sdocommon-print/src/main/java/it/eng/area118/sdocommon/print/impl/PrintImpl.java | b2ff8ef0205f26e6f72674ec9c1adf57dff88110 | []
| no_license | muten84/blog-examples | 01d75a3fee9d99e126488e7d014f98e95a638b3b | 742343e15bc84c9ce29585e1bf5186730dae26c2 | refs/heads/master | 2021-01-10T06:49:21.956652 | 2016-09-24T16:33:44 | 2016-09-24T16:33:44 | 47,393,209 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,510 | java | /**
*
*/
package it.eng.area118.sdocommon.print.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import it.eng.area118.sdocommon.print.IPrint;
import it.eng.area118.sdocommon.print.ReportData;
import it.eng.area118.sdocommon.print.excpetions.PrintReportException;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/**
* @author Bifulco Luigi
*
*/
public class PrintImpl implements IPrint {
@Override
public <E> OutputStream printToStream(ReportData<E> reportData, OutputStream os) throws PrintReportException {
// if (!isJasperFile(reportData.getReportPath(), "jasper")) {
// throw new PrintReportException("Input File is not a .jasper file");
// }
ByteArrayInputStream bais = null;
// if outputStream is not null then it will be processed like a jasper
// file output stream else
// the jasper file stream will be retrieved from filesystem
// finally it will be returned the exported stream.
if (os != null) {
bais = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
} else {
try {
bais = new ByteArrayInputStream(getBytesFromFile(new File(reportData.getReportSourcePath())));
} catch (IOException e1) {
throw new PrintReportException("Exception while getting bytes from File. Message cause: " + e1.getMessage());
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
JasperCompileManager.compileReportToStream(bais, baos);
} catch (JRException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bais = new ByteArrayInputStream(baos.toByteArray());
baos = new ByteArrayOutputStream();
try {
JasperFillManager.fillReportToStream(bais, baos, reportData.getReportParameters(), new JRBeanCollectionDataSource(reportData.getDatasource()));
} catch (JRException e) {
throw new PrintReportException("Exception while filling the report from InputStream. Message cause: " + e.getMessage());
}
bais = new ByteArrayInputStream(baos.toByteArray());
baos = new ByteArrayOutputStream();
try {
JasperExportManager.exportReportToPdfStream(bais, baos);
} catch (JRException e) {
throw new PrintReportException("Exception while filling the report from ByteArrayInputStream. Message cause: " + e.getMessage());
}
//osHolder.setOs(baos);
return baos;
}
protected byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// check the size of the file
if (length > Integer.MAX_VALUE) {
throw new IOException("File too large");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
}
| [
"[email protected]"
]
| |
cc3519626cd71675648969eb0daad3c432a78474 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i5441.java | 17e3e168f65adfb362bbbd91db9f2dec7d96af47 | []
| no_license | vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711400 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 68 | java | package number_of_direct_superinterfaces;
public interface i5441 {} | [
"[email protected]"
]
| |
7a6ae47d5acadba9010686ea43084ffef107a8c7 | a04dc2c5672b063b82bc0ac0cab797321763312b | /TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutoLatchWithOverride.java | 6b6a75930fe69b665122bd8dac0569b47b1e8a4a | [
"BSD-3-Clause"
]
| permissive | kylie1234/roverruckus | 7cf02db997def30bcd84d8bb73a95fafd2250af8 | 7ad9b99622bf92d57c961a7f62380b2c72ada81a | refs/heads/master | 2020-12-27T00:13:38.525485 | 2020-02-02T01:31:39 | 2020-02-02T01:31:39 | 237,701,626 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,853 | java | package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cColorSensor;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
/**
* Created by kyliestruth 10/5/17.
*/
@Disabled
@TeleOp(name = "Auto Latch With Override", group = "TankDrive")
public class AutoLatchWithOverride extends OpMode {
public ElapsedTime autolatchtime = new ElapsedTime();
public ElapsedTime colorsensortime = new ElapsedTime();
public ElapsedTime colorSensorTimeOutOpen = new ElapsedTime();
public ElapsedTime colorSensorTimeOutClose = new ElapsedTime();
int auto_latch_open = 0;
int auto_latch_close = 0;
private HardwareBeep robot = new HardwareBeep();
private boolean manual_mode = false;
private boolean latch_open_mode = false;
private boolean latch_close_mode = false;
public void init() {
robot.init(hardwareMap);
telemetry.addData("Say", "Hello Driver");
}
public void loop() {
if (!manual_mode && !latch_open_mode) {
if (auto_latch_open == 2 && colorSensorTimeOutOpen.seconds() > 1.15) {
robot.latch.setPower(0);
auto_latch_open = 0;
}
switch (auto_latch_open) {
case 0:
if (gamepad2.dpad_right) {
autolatchtime.reset();
auto_latch_open++;
}
break;
case 1:
colorSensorTimeOutOpen.reset();
robot.latch.setPower(-1);
auto_latch_open++;
break;
case 2:
if (colorsensortime.milliseconds() > 200) {
if (robot.colorSensor.readUnsignedByte(ModernRoboticsI2cColorSensor.Register.COLOR_NUMBER) == 3) {
robot.latch.setPower(0);
auto_latch_open = 0;
}
colorsensortime.reset();
}
break;
}
}
if (!manual_mode && !latch_close_mode) {
if (auto_latch_close == 2 && colorSensorTimeOutClose.seconds() > 1.15) {
robot.latch.setPower(0);
auto_latch_close = 0;
}
switch (auto_latch_close) {
case 0:
if (gamepad2.dpad_left) {
autolatchtime.reset();
auto_latch_close++;
}
break;
case 1:
colorSensorTimeOutClose.reset();
robot.latch.setPower(1);
auto_latch_close++;
break;
case 2:
if (colorsensortime.milliseconds() > 200) {
if (robot.colorSensor.readUnsignedByte(ModernRoboticsI2cColorSensor.Register.COLOR_NUMBER) == 10) {
robot.latch.setPower(0);
auto_latch_close = 0;
}
colorsensortime.reset();
}
break;
}
}
if (autolatchtime.seconds() > 1 && (gamepad2.dpad_right || gamepad2.dpad_left)) {
manual_mode = true;
robot.latch.setPower(0);
}
if (manual_mode) {
if (gamepad2.dpad_right) {
robot.latch.setPower(-1);
} else if (gamepad2.dpad_left) {
robot.latch.setPower(1);
} else robot.latch.setPower(0);
}
}
public void stop() {
}
} | [
"[email protected]"
]
| |
47bfadb404455382d5a0fad30282831ff36c43ca | c1ee80acee6e38527e3d6304b00f7036b114d722 | /MapLambdaStream/P01_Phonebook.java | e4e54fb0a0c9728383068f27f19851a086ad80f3 | []
| no_license | VeronikaNacheva/Programming-Fundamentals-January-2018 | ff21a97dcc4082d1cfc70f4ef07d9cac65ed3f4a | 1ced8e35f2b56709035576e91f0d086d91d2d9b8 | refs/heads/master | 2021-04-06T00:39:22.514654 | 2018-03-12T22:18:13 | 2018-03-12T22:18:13 | 124,807,539 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 946 | java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
public class P01_Phonebook {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
LinkedHashMap<String, String> phonebookMap = new LinkedHashMap<>();
String command = "";
while (!"END".equals(command = reader.readLine())) {
String[] input = command.split("\\s+");
if ("A".equals(input[0])) {
phonebookMap.put(input[1], input[2]);
} else {
if (phonebookMap.containsKey(input[1])) {
System.out.printf("%s -> %s%n", input[1], phonebookMap.get(input[1]));
} else {
System.out.printf("Contact %s does not exist.%n", input[1]);
}
}
}
}
}
| [
"[email protected]"
]
| |
ee6465c85477c041c976b4d42f893fc5afc488c2 | 3e87be7f51b257ca191eda2448f35083b3c329e0 | /cloud-gateway-gateway9527/src/main/java/com/atsanstwy27/springcloud/filter/MyLogGateWayFilter.java | 30f8d1da572be46d4aca5f3819112bca542dfe10 | []
| no_license | sanstwy777/SpringCloud | 5e711fb3288affe39152f360d08f6a0c1282277f | e87a513a7f8b54b7d6f2fe824f55687a340cb6bb | refs/heads/master | 2023-01-05T09:44:22.308222 | 2020-10-12T09:33:57 | 2020-11-01T04:02:52 | 286,451,005 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,220 | java | package com.atsanstwy27.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
/**
* @author Sanstwy27
* @create 8/13/2020
*/
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("*********** come in MyLogGateWayFilter: " + new Date());
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if(uname == null)
{
log.info("******* error, username is null o(╥﹏╥)o");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
| [
"[email protected]"
]
| |
214a8ff9e3bae50c1f16e60eee109373930385d2 | c44306d1d42ce180a3ffd3d2e818140c992813f7 | /src/main/java/com/example/gccoffee/controller/ProductController.java | debed6c116513418585096f9f36578a54a8541fa | []
| no_license | heoseungyeon/React-SpringBoot-Api | 4d80856b815635ddb9fe595d89a5ea31ef44bf06 | 4ee67f6fa18281332619ce7275a5bc39e3f89712 | refs/heads/main | 2023-08-13T14:07:29.936016 | 2021-10-11T07:30:45 | 2021-10-11T07:30:45 | 414,890,306 | 0 | 0 | null | 2021-10-11T07:30:46 | 2021-10-08T07:33:51 | Java | UTF-8 | Java | false | false | 1,637 | java | package com.example.gccoffee.controller;
import com.example.gccoffee.controller.CreateProductRequest;
import com.example.gccoffee.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.UUID;
@Controller
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/products")
public String productsPage(Model model) {
var products = productService.getAllProducts();
model.addAttribute("products", products);
return "product-list";
}
@GetMapping("new-product")
public String newProductPage() {
return "new-product";
}
@PostMapping("/products")
public String newProduct(CreateProductRequest createProductRequest) {
productService.createProduct(
createProductRequest.productName(),
createProductRequest.category(),
createProductRequest.price(),
createProductRequest.description());
return "redirect:/products";
}
@DeleteMapping("/products/{productId}")
public String deleteProduct(@PathVariable UUID productId) {
productService.deleteProductById(productId);
return "redirect:/products";
}
}
| [
"[email protected]"
]
| |
c091309a5c92c1e1a8862e97e18e1458a40f11b8 | 4f9b1d20889bee954d78defac323ac9854804b04 | /src/com/py/compiladores/algoritmos/Minimizacion.java | 61f28297e8e1fc7e114e076853b2300c5f026b35 | []
| no_license | sebasrojas36/Compiladores | 655c7f6f775a09ad19cb40e42a5825787e19651c | 41be53a1d8e8a823c987751f825b2f9bbd0e3da8 | refs/heads/main | 2023-05-14T10:51:44.714187 | 2021-06-02T22:08:01 | 2021-06-02T22:08:01 | 373,317,171 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 11,947 | java | package com.py.compiladores.algoritmos;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Stack;
import java.util.Vector;
import com.py.compiladores.analisis.Alfabeto;
import com.py.compiladores.estructuras.AFD;
import com.py.compiladores.estructuras.AFDMin;
import com.py.compiladores.estructuras.Automata;
import com.py.compiladores.estructuras.Conjunto;
import com.py.compiladores.estructuras.Estado;
import com.py.compiladores.estructuras.Transicion;
/**
* @author Sebastián Rojas
*/
public class Minimizacion {
/**
* Obtiene un AFD minimo a partir de un AFD determinado.
*/
public static AFDMin getAFDminimo(AFD afdOriginal) {
/* Eliminamos los estados inalcanzables */
AFD afdPostInalcanzables = new AFD();
copiarAutomata(afdOriginal, afdPostInalcanzables);
eliminarInalcanzables(afdPostInalcanzables);
/* Proceso de minimizacion */
AFD afdPostMinimizacion = minimizar(afdPostInalcanzables);
/* Eliminamos estados identidades no finales */
AFD afdPostIdentidades = new AFD();
copiarAutomata(afdPostMinimizacion, afdPostIdentidades);
eliminarIdentidades(afdPostIdentidades);
return new AFDMin(afdOriginal, afdPostInalcanzables,
afdPostMinimizacion, afdPostIdentidades);
}
/**
* Elimina los estados inalcanzables de un AFD.
*/
private static void eliminarInalcanzables(AFD afd) {
/* Conjunto de estados alcanzados desde el estado inicial */
Conjunto<Estado> alcanzados = recuperarAlcanzados(afd);
/* Eliminamos los estados no alcanzados */
afd.getEstados().retener(alcanzados);
/*
* No se actualizan los identificadores para que pueda notarse cuales
* fueron eliminados, si los hay.
*/
}
/**
* A partir del estado inicial de un AFD recupera los estados alcanzados,
* realizando un recorrido DFS no recursivo (utiliza una pila).
*/
private static Conjunto<Estado> recuperarAlcanzados(AFD afd) {
/* Estado inicial del recorrido */
Estado actual = afd.getEstadoInicial();
/* Conjunto de estados alcanzados */
Conjunto<Estado> alcanzados = new Conjunto<Estado>();
/* Agregamos el estado actual */
alcanzados.agregar(actual);
/* Pila para almacenar los estados pendientes */
Stack<Estado> pila = new Stack<Estado>();
/* Meter el estado actual como el estado inicial */
pila.push(actual);
while (!pila.isEmpty()) {
actual = pila.pop();
for (Transicion t : actual.getTransiciones()) {
Estado e = t.getEstado();
if (!alcanzados.contiene(e)) {
alcanzados.agregar(e);
pila.push(e);
}
}
}
return alcanzados;
}
/**
* Implementacion del algoritmo de minimizacion de estados.
*/
private static AFD minimizar(AFD afd) {
/* Tablas Hash auxiliares */
Hashtable<Estado, Conjunto<Integer>> tabla1;
Hashtable<Conjunto<Integer>, Conjunto<Estado>> tabla2;
/* Conjunto de las particiones del AFD */
Conjunto<Conjunto<Estado>> particion = new Conjunto<Conjunto<Estado>>();
/*
* Paso 1: Separar el AFD en dos grupos, los estados finales y
* los estados no finales.
*/
particion.agregar(afd.getEstadosNoFinales());
particion.agregar(afd.getEstadosFinales());
/*
* Paso 2: Construccion de nuevas particiones
*/
Conjunto<Conjunto<Estado>> nuevaParticion;
while (true) {
/* Conjunto de nuevas particiones en cada pasada */
nuevaParticion = new Conjunto<Conjunto<Estado>>();
for (Conjunto<Estado> grupo : particion) {
if (grupo.cantidad() == 0) {
/*
* Los grupos vacios no deben ser tenidos en cuenta. Un
* grupo vacio puede resultar en el caso de que todos los
* estados del AFD sean de aceptacion (finales), por lo que
* en la particion inicial, uno de los grupos estara vacio.
*/
continue;
} else if (grupo.cantidad() == 1) {
/*
* Los grupos unitarios se agregan directamente, debido a
* que ya no pueden ser particionados.
*/
nuevaParticion.agregar(grupo);
} else {
/*
* Paso 2.1: Hallamos los grupos alcanzados por cada estado del grupo actual.
*/
tabla1 = new Hashtable<Estado, Conjunto<Integer>>();
for (Estado e : grupo)
tabla1.put(
e,
getGruposAlcanzados(e, particion,
afd.getAlfabeto()));
/*
* Paso 2.2: Calculamos las nuevas particiones
*/
tabla2 = new Hashtable<Conjunto<Integer>, Conjunto<Estado>>();
for (Estado e : grupo) {
Conjunto<Integer> alcanzados = tabla1.get(e);
if (tabla2.containsKey(alcanzados))
tabla2.get(alcanzados).agregar(e);
else {
Conjunto<Estado> tmp = new Conjunto<Estado>();
tmp.agregar(e);
tabla2.put(alcanzados, tmp);
}
}
/*
* Paso 2.3: Copiar las nuevas particiones al conjunto de nuevas particiones.
*/
for (Conjunto<Estado> c : tabla2.values())
nuevaParticion.agregar(c);
}
}
/* Ordenamos la nueva particion */
nuevaParticion.ordenar();
/*
* Paso 2.4: Si las particiones son iguales, significa que
* no hubo cambios y debemos terminar. En caso contrario, seguimos
* particionando.
*/
if (nuevaParticion.equals(particion))
break;
else
particion = nuevaParticion;
}
/*
* Paso 3: Debemos crear el nuevo AFD, con los nuevos estados
* producidos.
*/
AFD afdPostMinimizacion = new AFD(afd.getAlfabeto(), afd.getExprReg());
/*
* Paso 3.1: Agregamos los estados al nuevo AFD. Para los
* estados agrupados, colocamos una etiqueta distintiva, para que pueda
* notarse resultado de cuales estados es.
*/
for (int i = 0; i < particion.cantidad(); i++) {
Conjunto<Estado> grupo = particion.obtener(i);
boolean esFinal = false;
/*
* El grupo actual tiene un estado final, el estado correspondiente
* en el nuevo AFD tambien debe ser final.
*/
if (tieneEstadoFinal(grupo))
esFinal = true;
/*
* Si el estado es resultado de la union de dos o mas estados, su
* etiqueta sera del tipo e1.e2.e3, donde e1, e2 y e3 son los
* estados agrupados (aparecen separados por un punto).
*/
String etiqueta = obtenerEtiqueta(grupo);
/*
* Agregamos efectivamente el estado al nuevo AFD.
*/
Estado estado = new Estado(i, esFinal);
estado.setEtiqueta(etiqueta);
afdPostMinimizacion.agregarEstado(estado);
}
/*
* Paso 3.2: Generamos un mapeo de grupos (estados del nuevo
* AFD) a estados del AFD original, de manera a que resulte sencillo
* obtener los estados adecuados en el momento de agregar las
* transiciones al nuevo AFD.
*/
Hashtable<Estado, Estado> mapeo = new Hashtable<Estado, Estado>();
for (int i = 0; i < particion.cantidad(); i++) {
/* Grupo a procesar */
Conjunto<Estado> grupo = particion.obtener(i);
/* Estado del nuevo AFD */
Estado valor = afdPostMinimizacion.getEstado(i);
/* Guardar mapeo */
for (Estado clave : grupo)
mapeo.put(clave, valor);
}
/*
* Paso 3.3: Agregamos las transiciones al nuevo AFD
* utilizando el mapeo de estados entre dicho AFD y el AFD original,
* realizado en el paso 3.2.
*/
for (int i = 0; i < particion.cantidad(); i++) {
/* Estado representante del grupo actual */
Estado representante = particion.obtener(i).obtenerPrimero();
/* Estado del nuevo AFD */
Estado origen = afdPostMinimizacion.getEstado(i);
/* Agregamos las transciones */
for (Transicion trans : representante.getTransiciones()) {
Estado destino = mapeo.get(trans.getEstado());
origen.getTransiciones().agregar(
new Transicion(destino, trans.getSimbolo()));
}
}
return afdPostMinimizacion;
}
/**
* Para un estado dado, busca los grupos en los que caen las transiciones del mismo.
*/
private static Conjunto<Integer> getGruposAlcanzados(Estado origen,
Conjunto<Conjunto<Estado>> particion, Alfabeto alfabeto) {
/* Grupos alcanzados por el estado */
Conjunto<Integer> gruposAlcanzados = new Conjunto<Integer>();
/*
* Paso 1: Para cada simbolo del alfabeto obtenemos los estados
* alcanzados. Si para un simbolo dado el estado no posee transicion,
* colocamos null.
*/
HashMap<String, Estado> transiciones = origen
.getTransicionesSegunAlfabeto(alfabeto);
/*
* Paso 2: Para cada simbolo del alfabeto obtenemos el estado
* alcanzado por el estado origen y buscamos en que grupo de la
* particion esta.
*/
for (String s : alfabeto) {
/* Estado destino de la transicion */
Estado destino = transiciones.get(s);
if (destino == null) {
/*
* Si el estado destino es "null", no pertenecera a ningun
* grupo, por lo que colocamos el grupo ficticio con indice -1.
*/
gruposAlcanzados.agregar(-1);
} else {
for (int pos = 0; pos < particion.cantidad(); pos++) {
Conjunto<Estado> grupo = particion.obtener(pos);
if (grupo.contiene(destino)) {
gruposAlcanzados.agregar(pos);
/* El estado siempre estara en un solo grupo */
break;
}
}
}
}
return gruposAlcanzados;
}
/**
* Elimina los estados identidad, aquellos que para todos los simbolos del
* alfabeto tienen transiciones a si mismos. Este tipo de estados solo deben
* ser eliminados si no son estados de aceptacion.
*/
private static void eliminarIdentidades(AFD afd) {
/* Conjunto de estados a eliminar */
Conjunto<Estado> estadosEliminados = new Conjunto<Estado>();
/* Seleccionamos los estados identidad no finales */
for (Estado e : afd.getEstados())
if (e.getEsIdentidad() && !e.getEsFinal())
estadosEliminados.agregar(e);
if (estadosEliminados.estaVacio()) {
return;
}
/* Eliminamos los estados identidad no finales */
for (Estado e : estadosEliminados)
afd.getEstados().eliminar(e);
/* Transiciones a eliminar */
Vector<List> transEliminadas = new Vector<List>();
/* Seleccionamos las transiciones colgadas */
for (Estado e : afd.getEstados())
for (Transicion t : e.getTransiciones())
if (estadosEliminados.contiene(t.getEstado()))
transEliminadas.add(Arrays.asList(t, e.getTransiciones()));
/* Eliminamos las transiciones colgadas */
for (List a : transEliminadas) {
Transicion t = (Transicion) a.get(0);
Conjunto<Transicion> c = (Conjunto<Transicion>) a.get(1);
c.eliminar(t);
}
}
/**
* Realiza la copia de un automata origen a otro de destino.
*/
private static void copiarAutomata(Automata origen, Automata destino) {
/* Copiamos los estados y transiciones */
Automata.copiarEstados(origen, destino, 0);
/* Copiamos los estados finales y las etiquetas */
for (int i = 0; i < origen.cantidadEstados(); i++) {
Estado tmp = origen.getEstado(i);
destino.getEstado(i).setEsFinal(tmp.getEsFinal());
destino.getEstado(i).setEtiqueta(tmp.getEtiqueta());
}
/* Copiamos el alfabeto y la expresion regular */
destino.setAlfabeto(origen.getAlfabeto());
destino.setExprReg(origen.getExprReg());
}
/**
* Determina si un grupo de estados tiene un estado final.
*/
private static boolean tieneEstadoFinal(Conjunto<Estado> grupo) {
for (Estado e : grupo)
if (e.getEsFinal())
return true;
return false;
}
/**
* Calcula la nueva etiqueta para un estado del nuevo AFD, segun los estados agrupados.
*/
private static String obtenerEtiqueta(Conjunto<Estado> grupo) {
String etiqueta = "";
String pedazo;
for (Estado e : grupo) {
/* Eliminamos la "i" y/o "f" en caso de que exista */
if (e.toString().endsWith("if"))
pedazo = e.toString().substring(0, e.toString().length() - 2);
else if (e.toString().endsWith("i") || e.toString().endsWith("f"))
pedazo = e.toString().substring(0, e.toString().length() - 1);
else
pedazo = e.toString();
/* Agregamos */
etiqueta += pedazo + " ";
}
if (etiqueta.endsWith(" "))
etiqueta = etiqueta.substring(0, etiqueta.length() - 1);
return "(" + etiqueta + ")";
}
}
| [
"[email protected]"
]
| |
b2c4a9059758d7aa06d581e990e64765b3269210 | 3a0d9e3e73385fdb26b68513eecf04c454e892ed | /labb5/src/labb5/FractalExplorer.java | 44bc8fd409243ebe367a5bde7cddae5a5039e9e0 | []
| no_license | mtusi419/lab5oop | 03426de7b9c28b5a116e5aa869111deceabf24b2 | 6ed8d1484e9d0ddb280fcbbf81d81b61a6903ef4 | refs/heads/master | 2022-10-01T20:28:41.868557 | 2020-06-08T19:25:26 | 2020-06-08T19:25:26 | 270,798,075 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 6,576 | java | package labb5;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.basic.BasicButtonListener;
import javax.swing.plaf.basic.BasicOptionPaneUI;
import java.awt.*;
import java.awt.color.ICC_ProfileRGB;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.io.File;
public class FractalExplorer {
private int screenSize;
private JImageDisplay display;
private FractalGenerator CurrentFractalGenerator;
private Rectangle2D.Double range;
private JFrame frame;
FractalExplorer(int size){
screenSize = size;
display = new JImageDisplay(screenSize, screenSize);
range = new Rectangle2D.Double();
CurrentFractalGenerator = new Mandelbrot();
CurrentFractalGenerator.getInitialRange(range);
}
public void createAndShowGUI(){
//кнопка сброса
Button reset = new Button("Reset");
reset.setSize(screenSize / 3, 50);
reset.addActionListener(new JButtonClick());
reset.setVisible(true);
//кнопка сохранения фрактала
Button saveImg = new Button("Save");
saveImg.setSize(screenSize / 3, 50);
saveImg.addActionListener(new SaveButtonClick());
saveImg.setVisible(true);
//создание фракталов
BurningShip BurningShipFractal = new BurningShip();
Tricorn TricornFractal = new Tricorn();
//комбобокс выбора фракталов
JComboBox<FractalGenerator> comboBox = new JComboBox<>();
comboBox.addItem(CurrentFractalGenerator);
comboBox.addItem(BurningShipFractal);
comboBox.addItem(TricornFractal);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FractalGenerator newFractal = (FractalGenerator) comboBox.getSelectedItem();
if (newFractal != null){
CurrentFractalGenerator = newFractal;
newFractal.getInitialRange(range);
drawFractal();
}
}
});
//панель вывода компонентов интерфейса
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
//настройка размещения элементов интерфейса на форме
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(display)
.addComponent(comboBox)
.addGroup(layout.createSequentialGroup()
.addComponent(reset)
.addComponent(saveImg))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(comboBox)
.addComponent(display)
.addGroup(layout.createParallelGroup()
.addComponent(reset)
.addComponent(saveImg)
)
);
display.clearImage();
//создание и настройка окна
frame = new JFrame();
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(screenSize, screenSize));
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.addMouseListener(new JMouseAdapter());
this.drawFractal();
}
private void drawFractal(){
int i, j;
double xCoord, yCoord;
int iterations;
float hue;
int rgbColor;
for (i = 0; i < display.getWidth(); i++){
for (j = 0; j < display.getHeight(); j++){
xCoord = CurrentFractalGenerator.getCoord(range.x, range.x + range.width, screenSize, i);
yCoord = CurrentFractalGenerator.getCoord(range.y, range.y + range.height, screenSize, j);
iterations = CurrentFractalGenerator.numIterations(xCoord, yCoord);
if (iterations == -1){
rgbColor = 0;
}
else{
hue = 0.7f + (float) iterations / 200f;
rgbColor = Color.HSBtoRGB(hue, 1f, 1f);
}
display.drawPixel(i, j, rgbColor);
display.repaint();
}
}
}
private class JMouseAdapter extends java.awt.event.MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
display.drawPixel(e.getX(), e.getY(), ICC_ProfileRGB.icSigGreenColorantTag);
double xCoord = CurrentFractalGenerator.getCoord(range.x, range.x + range.width, screenSize, e.getX());;
double yCoord = CurrentFractalGenerator.getCoord(range.y, range.y + range.height, screenSize, e.getY());
FractalGenerator.recenterAndZoomRange(range, xCoord, yCoord, 0.5);
display.repaint();
drawFractal();
}
}
private class JButtonClick implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
CurrentFractalGenerator.getInitialRange(range);
drawFractal();
}
}
private class SaveButtonClick implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser saveDlg = new JFileChooser();
if (saveDlg.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION){
File file = saveDlg.getSelectedFile();
FileFilter filter = new FileNameExtensionFilter("PNG Images", "png");
saveDlg.setFileFilter(filter);
saveDlg.setAcceptAllFileFilterUsed(false);
try{
javax.imageio.ImageIO.write(display.getBufferedImage(), "png", file);
}
catch (Exception Exc){
JOptionPane.showMessageDialog(frame, "Saving image failed. " + Exc.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
| [
"[email protected]"
]
| |
4271a68311d28307e64d10ea52d1c56de4705e5d | bc4200a5b91abc670d972299789f7141254a3fab | /lang-java/src/main/java/edu/lab/algorthms/lang_java/SquareRoot.java | b5e2af0d1ac29c5e8bb3a237762fd944f52e960a | []
| no_license | santoshganti/Giza | a402043a0df8d4cecaf0cee372434f5651fcff18 | 37e30c6a172efb0c3cb90d84522262ccafa4a81c | refs/heads/master | 2021-01-13T01:50:21.336206 | 2015-04-04T12:47:20 | 2015-04-04T12:47:20 | 27,341,233 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,524 | java | package edu.lab.algorthms.lang_java;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class SquareRoot {
private static final Logger logger = LogManager.getLogger(SquareRoot.class);
class Seed {
private int multiplier;
private int exponent = 0;
private final int DIVISOR = 100;
private int calculateMultiplier(double s) {
if (s < 100) {
return (int) s;
} else {
exponent++;
return calculateMultiplier(s / DIVISOR);
}
}
Seed(double s) {
multiplier = calculateMultiplier(s);
}
// public int getExponent() {
// return exponent;
// }
//
// public int getMultiplier() {
// return multiplier;
// }
public double getSeedValue() {
if (multiplier < 10)
return (2) * Math.pow(10, exponent);
else
return (6) * Math.pow(10, exponent);
}
}
private final double EPSILON = 0.001;
double guess(double s) {
Seed number = new Seed(s);
return number.getSeedValue();
}
public double squareRoot(double s) {
return squareRoot(guess(s), s);
}
double squareRoot(double guess, double s) {
logger.info("Sqrt {} current guess {}", s, guess);
if (isGoodEnough(guess, s))
return guess;
else
return squareRoot(improve(guess, s), s);
}
double improve(double guess, double s) {
return (guess + s / guess) / 2;
}
boolean isGoodEnough(double guess, double s) {
return (modulus(s - guess * guess) < EPSILON);
}
double modulus(double s) {
if (s >= 0)
return s;
else
return -s;
}
} | [
"[email protected]"
]
| |
5602a3e23cec8576f0688ca83c27510505d8f096 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/26/26_b65efe0375a2c8b5fc90dc35fe5c570954bde914/PlayerAssembly/26_b65efe0375a2c8b5fc90dc35fe5c570954bde914_PlayerAssembly_s.java | 482b993138d709380c2e2035f68231040fe8df7e | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 7,525 | java | package org.drooms.impl.util;
import java.io.File;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.drools.builder.KnowledgeBuilder;
import org.drooms.api.CustomPathBasedStrategy;
import org.drooms.api.Edge;
import org.drooms.api.Node;
import org.drooms.api.Player;
import org.drooms.api.Strategy;
import org.drooms.impl.GameController;
import edu.uci.ics.jung.algorithms.shortestpath.ShortestPath;
import edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath;
import edu.uci.ics.jung.graph.Graph;
/**
* A helper class to load {@link Strategy} implementations for all requested
* {@link Player}s.
*/
public class PlayerAssembly {
private static class DefaultPathBasedStrategy implements CustomPathBasedStrategy {
private final Strategy strategy;
public DefaultPathBasedStrategy(final Strategy nonCustomPathBasedStrategy) {
if (nonCustomPathBasedStrategy == null) {
throw new IllegalArgumentException("The strategy may not be null!");
}
if (nonCustomPathBasedStrategy instanceof CustomPathBasedStrategy) {
throw new IllegalArgumentException("The strategy must not provide its own path-finding algorithm!");
}
this.strategy = nonCustomPathBasedStrategy;
}
@Override
public boolean enableAudit() {
return this.strategy.enableAudit();
}
@Override
public boolean equals(final Object obj) {
return this.strategy.equals(obj);
}
@Override
public KnowledgeBuilder getKnowledgeBuilder(final ClassLoader cls) {
return this.strategy.getKnowledgeBuilder(cls);
}
@Override
public String getName() {
return this.strategy.getName();
}
@Override
public ShortestPath<Node, Edge> getShortestPathAlgorithm(final Graph<Node, Edge> graph) {
return new UnweightedShortestPath<>(graph);
}
@Override
public int hashCode() {
return this.strategy.hashCode();
}
@Override
public String toString() {
return this.strategy.toString();
}
}
private static URL uriToUrl(final URI uri) {
try {
return uri.toURL();
} catch (final MalformedURLException e) {
throw new IllegalArgumentException("Invalid URL: " + uri, e);
}
}
private final Properties config;
private final Map<URI, ClassLoader> strategyClassloaders = new HashMap<>();
private final Map<String, Strategy> strategyInstances = new HashMap<>();
/**
* Initialize the class.
*
* @param f
* Game config as described in
* {@link GameController#play(org.drooms.api.Playground, Properties, Collection, File)}
* .
*/
public PlayerAssembly(final File f) {
try (FileReader fr = new FileReader(f)) {
this.config = new Properties();
this.config.load(fr);
} catch (final Exception e) {
throw new IllegalArgumentException("Cannot read player config file.", e);
}
}
/**
* Perform all the strategy resolution and return a list of fully
* initialized players.
*
* @return The unmodifiable collection of players, in the order in which
* they come up in the data file.
*/
public List<Player> assemblePlayers() {
// parse a list of players
final Map<String, String> playerStrategies = new HashMap<>();
final Map<String, URI> strategyJars = new HashMap<>();
for (final String playerName : this.config.stringPropertyNames()) {
final String strategyDescr = this.config.getProperty(playerName);
final String[] parts = strategyDescr.split("\\Q@\\E");
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid strategy descriptor: " + strategyDescr);
}
final String strategyClass = parts[0];
if (strategyClass.startsWith("org.drooms.impl.")) {
throw new IllegalStateException("Strategy musn't belong to the game implementation package.");
}
try {
final URI strategyJar = new URI(parts[1]);
playerStrategies.put(playerName, strategyClass);
strategyJars.put(strategyClass, strategyJar);
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Invalid URL in the strategy descriptor: " + strategyDescr, e);
}
}
// load strategies for players
final List<Player> players = new ArrayList<>();
for (final Map.Entry<String, String> entry : playerStrategies.entrySet()) {
final String playerName = entry.getKey();
final String strategyClass = entry.getValue();
final URI strategyJar = strategyJars.get(strategyClass);
CustomPathBasedStrategy strategy;
try {
final Strategy s = this.loadStrategy(strategyClass, strategyJar);
if (s instanceof CustomPathBasedStrategy) {
strategy = (CustomPathBasedStrategy) s;
} else {
// if the strategy doesn't care about path, provide the
// default one
strategy = new DefaultPathBasedStrategy(s);
}
} catch (final Exception e) {
throw new IllegalArgumentException("Failed loading: " + strategyClass, e);
}
players.add(new Player(playerName, strategy, this.loadJar(strategyJar)));
}
return Collections.unmodifiableList(players);
}
/**
* Load a strategy JAR file in its own class-loader, effectively isolating
* the strategies from each other.
*
* @param strategyJar
* The JAR coming from the player config.
* @return The class-loader used to load the strategy jar.
*/
private ClassLoader loadJar(final URI strategyJar) {
if (!this.strategyClassloaders.containsKey(strategyJar)) {
final ClassLoader loader = URLClassLoader.newInstance(new URL[] { PlayerAssembly.uriToUrl(strategyJar) },
this.getClass().getClassLoader());
this.strategyClassloaders.put(strategyJar, loader);
}
return this.strategyClassloaders.get(strategyJar);
}
private Strategy loadStrategy(final String strategyClass, final URI strategyJar) throws Exception {
if (!this.strategyInstances.containsKey(strategyClass)) {
final Class<?> clz = Class.forName(strategyClass, true, this.loadJar(strategyJar));
final Strategy strategy = (Strategy) clz.newInstance();
this.strategyInstances.put(strategyClass, strategy);
}
return this.strategyInstances.get(strategyClass);
}
}
| [
"[email protected]"
]
| |
e6844b07ade523333bc1746176ac5300ece7e889 | 14ad650ed2f961f040d23bfd371f2146b8348734 | /Module_2/src/CaseStudy/services/ManageEmployee.java | e8aa13a99dcc0d0529f06823e6514a9eb06ae917 | []
| no_license | theanh2010/Chien | 0811e08864d35a9247703e758557843f5661ddfb | 4c8b1b72ef58537c34f6f5fc3d4852f85c4623ff | refs/heads/master | 2023-01-24T15:23:06.258428 | 2020-11-23T03:28:01 | 2020-11-23T03:28:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,768 | java | package CaseStudy.services;
import CaseStudy.common.ReadWriteFile;
import CaseStudy.controller.MainController;
import CaseStudy.documents.EmployeesFile;
import CaseStudy.models.Employee;
import CaseStudy.view.Main;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class ManageEmployee extends Employee {
public static void showInformationOfEmployee() {
Map<Integer, Employee> employeeMaps = ReadWriteFile.readFileEmployee();
for (Map.Entry<Integer, Employee> employees : employeeMaps.entrySet()) {
System.out.println(employees.toString());
}
boolean check = false;
Set<Integer> keys = employeeMaps.keySet();
boolean check1 = true;
Integer number = null;
do {
System.out.println("Chọn hành động" +
"\n1. Tìm kiếm nhân viên bằng ID" +
"\n2. Tìm kiếm nhân viên bằng tên");
String choose = Main.inputScanner().nextLine();
switch (choose) {
case "1": {
System.out.println("Nhập ID: ");
number = Main.inputScanner().nextInt();
for (Integer i : keys) {
if (i == number) {
check1 = false;
}
}
break;
}
case "2": {
EmployeesFile.employeeFile();
MainController.showMenu();
break;
}
}
}
while (check1) ;
Employee employee = employeeMaps.get(number);
System.out.println(employee.toString());
}
} | [
"[email protected]"
]
| |
6b5f1df15d177f22833593dac3bb0a46f1be5499 | b07f617193c99407e9651afcabe451e870b9ed7f | /kr.ac.kopo.day12/src/kr/ac/kopo/day12/LGTV.java | 6124855aa85ff1afac076a732d8498f22e876ed3 | []
| no_license | Jooheehan-kopo/lecture_java | af1bb343d6880739c46050409afd840dc5fe07b0 | 1b92800ea0d760dd3537684e8e91558769d2231a | refs/heads/master | 2023-05-25T12:29:52.984644 | 2021-06-03T09:08:18 | 2021-06-03T09:08:18 | 345,900,701 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 549 | java | package kr.ac.kopo.day12;
public class LGTV {
public LGTV() {
System.out.println("엘지 티비 구매하였습니다");
}
public void turnOn() {
System.out.println("전원 ON");
}
public void turnOff() {
System.out.println("전원 Off");
}
public void channelDown() {
System.out.println("channelDown..");
}
public void channelUp() {
System.out.println("channelUp..");
}
public void soundUp() {
System.out.println("soundUp..");
}
public void soundDown() {
System.out.println("soundDown..");
}
}
| [
"[email protected]"
]
| |
5496d094e09b7f30c2139436489a631a2d8f9ca3 | 52dc9d80b9ac0fd076608bab443cc465c16f5bd4 | /compiler/src/main/java/de/tub/dima/babelfish/ir/lqp/streaming/Window.java | c8489ea4885fa51477ded7bc0bc253d402d3742a | [
"Apache-2.0"
]
| permissive | TU-Berlin-DIMA/babelfish | 9316ac56b6b85166babdf1ca26aba92a8a7dadcf | 4926384d994ab4ab324a056d69be64d9b52ed7a0 | refs/heads/master | 2023-08-15T09:59:04.259520 | 2021-10-20T08:17:51 | 2021-10-20T08:17:51 | 415,998,147 | 11 | 0 | null | null | null | null | UTF-8 | Java | false | false | 479 | java | package de.tub.dima.babelfish.ir.lqp.streaming;
import de.tub.dima.babelfish.ir.lqp.LogicalOperator;
public class Window extends LogicalOperator {
private final WindowAssigner assigner;
private final WindowTrigger trigger;
private final WindowFunction function;
public Window(WindowAssigner assigner, WindowTrigger trigger, WindowFunction function) {
this.assigner = assigner;
this.trigger = trigger;
this.function = function;
}
}
| [
"[email protected]"
]
| |
1ac4b4991f0223dadd3c94eb0a54e4364bec8ae9 | f036dd566ea1039fb0e55b977762b812e324fc9b | /src/maquina/MaquinaElectrica.java | 54b85adf4f0921c118c6125818d138c45f51775e | []
| no_license | tulkas72/maquina | fe0934b344288b4b11fe7144c2aecaa2f26ad951 | 5ad2b4a32a579e36dbda009ed3beeccaf41b8027 | refs/heads/master | 2023-03-13T17:33:35.694826 | 2021-03-03T19:44:16 | 2021-03-03T19:44:16 | 338,417,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,798 | java | package maquina;
abstract public class MaquinaElectrica extends Maquina
{
private int voltaje;
private double potencia;
private static int MIN_VOLTAJE=10;
private static int MAX_VOLTAJE=400;
private static int DEFAULT_VOLTAJE=MIN_VOLTAJE;
private static double MIN_POTENCIA_ELECTRICA=700.0;
private static double MAX_POTENCIA_ELECTRICA=200_000.0;
private static double DEFAULT_POTENCIA_ELECTRICA=MIN_POTENCIA_ELECTRICA;
public MaquinaElectrica(String marca, String modelo, int voltaje, double potencia) throws IllegalArgumentException
{
super(marca, modelo);
if(voltaje < MIN_VOLTAJE || voltaje>MAX_VOLTAJE)
{
throw new IllegalArgumentException(" Error de voltaje:" + voltaje + ". Mínimo " +
MIN_VOLTAJE + "v y máximo" + MAX_VOLTAJE + " v.");
}
if(potencia < MIN_POTENCIA_ELECTRICA || potencia > MAX_POTENCIA_ELECTRICA)
{
throw new IllegalArgumentException(" Error de potencia:" + potencia + ". Mínimo " +
MIN_POTENCIA_ELECTRICA + "w y máximo" + MAX_POTENCIA_ELECTRICA + " kw.");
}
this.voltaje = voltaje;
this.potencia = potencia;
}
public MaquinaElectrica(String marca, String modelo)
{
this(marca, modelo,MIN_VOLTAJE,MIN_POTENCIA_ELECTRICA);
}
public int getVoltaje()
{
return voltaje;
}
public double getPotencia()
{
return potencia;
}
@Override
public String toString()
{
String toStringSuper = super.toString();
return String.format("%s; Voltaje: %-10d ; Potencia: %-10f}",
toStringSuper.substring(0, toStringSuper.length() - 2),
this.getVoltaje(),this.getPotencia());
}
}
| [
"[email protected]"
]
| |
5112f404b8820ef176742d09908e2dd003832302 | b83d127b9a397ac42c214def65ea2d578ea9146d | /src/main/java/com/notification/dao/repo/GroupCustomerRepo.java | 1cdd06ea5a31e2e8b89961203810b100af4935cf | []
| no_license | amremaish/NotificationService | e26afc33cc1b8b0fd498cae2a56673deb10d7dba | e16db804eb373c4b8d63e505a4cc8bd072e01f3c | refs/heads/master | 2023-07-14T15:46:51.620209 | 2021-08-12T05:05:38 | 2021-08-12T05:05:38 | 392,693,111 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 332 | java | package com.notification.dao.repo;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.notification.dao.entites.GroupCustomer;
@Repository
public interface GroupCustomerRepo extends PagingAndSortingRepository<GroupCustomer, Long> {
}
| [
"[email protected]"
]
| |
b045a27c4321262a2e34bbe824be74cbc5ab0de2 | 7c0fa99406bf37438d1582a93c803927b608eac1 | /gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareSkuEntity.java | 8f278ba827a4196f69a48efee9c8fbf8abd00698 | [
"Apache-2.0"
]
| permissive | jibingwu/gmall0826 | 05574a042041440c08d8334d0381afebe76a9da9 | d83af565ef7907df9b5db1d990f9cb86e4d0123e | refs/heads/master | 2022-12-25T09:03:54.190141 | 2020-04-08T04:40:58 | 2020-04-08T04:40:58 | 241,264,621 | 0 | 0 | Apache-2.0 | 2022-12-16T15:25:44 | 2020-02-18T03:36:09 | JavaScript | UTF-8 | Java | false | false | 1,150 | java | package com.atguigu.gmall.wms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 商品库存
*
* @author jsonwu
* @email [email protected]
* @date 2020-02-22 00:16:07
*/
@ApiModel
@Data
@TableName("wms_ware_sku")
public class WareSkuEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
@ApiModelProperty(name = "id",value = "id")
private Long id;
/**
* sku_id
*/
@ApiModelProperty(name = "skuId",value = "sku_id")
private Long skuId;
/**
* 仓库id
*/
@ApiModelProperty(name = "wareId",value = "仓库id")
private Long wareId;
/**
* 库存数
*/
@ApiModelProperty(name = "stock",value = "库存数")
private Integer stock;
/**
* sku_name
*/
@ApiModelProperty(name = "skuName",value = "sku_name")
private String skuName;
/**
* 锁定库存
*/
@ApiModelProperty(name = "stockLocked",value = "锁定库存")
private Integer stockLocked;
}
| [
"[email protected]"
]
| |
914a73c78a36f0e3ec4451cb6cddebf30838a203 | faaf4ca0fc3218ae831b0b457f1cf453034cbc8a | /src/test/java/cn/com/ttblog/ssmbootstrap_table/MockTest.java | 08d70edaff9fb56204b367cc57c99e40f51e877e | []
| no_license | 352328690/ssmbootstrap_table | 0a510a09dea81cef7565f7da91418157403dff8e | 1284c3d5eeedef790532923cfc530d16044fe28c | refs/heads/master | 2020-04-17T17:30:08.303422 | 2018-12-18T06:51:00 | 2018-12-18T06:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,084 | java | package cn.com.ttblog.ssmbootstrap_table;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.ttblog.ssmbootstrap_table.service.IUserService;
public class MockTest {
@Mock
private IUserService userService;
@Mock
private PersonDao personDAO;
private PersonService personService;
private static final Logger LOG = LoggerFactory.getLogger(MockTest.class);
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
personService = new PersonService(personDAO);
}
@Test
public void simpleTest() {
LOG.debug("userService.getUserById(1L):{}", userService.getUserById(1L));
}
@Test
public void shouldUpdatePersonName() {
Person person = new Person(1, "Phillip");
when(personDAO.fetchPerson(1)).thenReturn(person);
boolean updated = personService.update(1, "David");
assertTrue(updated);
verify(personDAO).fetchPerson(1);
ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass(Person.class);
verify(personDAO).update(personCaptor.capture());
Person updatedPerson = personCaptor.getValue();
assertEquals("David", updatedPerson.getPersonName());
// asserts that during the test, there are no other calls to the mock
// object.
verifyNoMoreInteractions(personDAO);
}
@Test
public void shouldNotUpdateIfPersonNotFound() {
when(personDAO.fetchPerson(1)).thenReturn(null);
boolean updated = personService.update(1, "David");
assertFalse(updated);
verify(personDAO).fetchPerson(1);
verifyZeroInteractions(personDAO);
verifyNoMoreInteractions(personDAO);
}
} | [
"[email protected]"
]
| |
5a95bdeaf94ed8299a00f4cfecc887fe75184511 | b92054a462e3f862b47bf692318e8ec026427108 | /store_v5/src/com/zy/store/dao/OrderDao.java | 4647a7318ce01fef4d16125a3c7060e3c8a1aae1 | []
| no_license | zhuneng1369306648/Learning | b345a18a807a0013f5539ea877ba47a99cfa3f23 | 7f3d7bec813194861727e285863f1fa1c237e3b7 | refs/heads/master | 2022-12-22T03:46:43.354110 | 2019-06-24T16:18:39 | 2019-06-24T16:18:39 | 193,538,092 | 0 | 0 | null | 2022-12-16T02:50:23 | 2019-06-24T16:08:29 | JavaScript | UTF-8 | Java | false | false | 691 | java | package com.zy.store.dao;
import java.sql.Connection;
import java.util.List;
import com.zy.store.domain.Order;
import com.zy.store.domain.OrderItem;
import com.zy.store.domain.User;
public interface OrderDao {
void saveOrder(Connection conn, Order order)throws Exception;
void saveOrderItem(Connection conn, OrderItem item)throws Exception;
int getTotalRecords(User user)throws Exception;
List findMyOrdersWithPage(User user, int startIndex, int pageSize)throws Exception;
Order findOrderByOid(String oid)throws Exception;
void updateOrder(Order order)throws Exception;
List<Order> findAllOrders()throws Exception;
List<Order> findAllOrders(String st)throws Exception;
}
| [
"[email protected]"
]
| |
e8e42369ec66999c582a682ee6f166a77686dbfe | acd22c7f71b6660fae2dbdb6dcaeb145fe41abe7 | /BetMasters/src/main/java/com/example/group/controllers/ChatController.java | 462737d1a100115a0c937ba65e63b120787ad72a | []
| no_license | aufheben68/BetMastersProject | 08dc015487f2cb1ddc83f1037d6585d86131f00a | bfeeecc5c579ee742df3aedd09811d1710d09e66 | refs/heads/main | 2023-03-31T21:15:59.982701 | 2021-03-31T17:04:14 | 2021-03-31T17:04:14 | 353,422,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 933 | java | package com.example.group.controllers;
import com.example.group.model.ChatMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;
/**
*
* @author Ody
*/
@Controller
public class ChatController {
@MessageMapping("/chat.register")
@SendTo("/topic/public")
public ChatMessage register(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
return chatMessage;
}
@MessageMapping("/chat.send")
@SendTo("/topic/public")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
return chatMessage;
}
}
| [
"[email protected]"
]
| |
1270887d100e49e621c9a2307f4d7a26fd6f32b5 | 51543c97251067370bba2ff2bb77a5548aedabd9 | /src/main/java/FileProvider.java | 5687fb0e9caefbbc4a14f3c5e669ff9612d4e909 | []
| no_license | mezd10/CarInfo | 4a1fac256492823e499ad1e84ac8edfecb896f15 | 6801d4eb9660c19f5974a616b18251eb702643dd | refs/heads/master | 2020-08-21T18:33:53.407150 | 2019-10-19T23:57:53 | 2019-10-19T23:57:53 | 216,219,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,983 | java | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileProvider {
private String host;
private String port;
private String database;
private String login;
private String password;
public FileProvider(String configFileName) throws IOException {
readConfigFile(configFileName);
}
private void readConfigFile(String fileName) throws IOException {
File file = new File(fileName);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
parseLine(line);
}
bufferedReader.close();
fileReader.close();
}
private void parseLine(String line) throws IllegalArgumentException{
String[] lineParts = line.split(":");
if (lineParts.length != 2) {
throw new IllegalArgumentException("Wrong line: " + "\"" + line + "\"");
}
lineParts[0] = lineParts[0].trim().toLowerCase();
lineParts[1] = lineParts[1].trim().toLowerCase();
storeParameter(lineParts);
}
private void storeParameter(String[] lineParts) throws NumberFormatException {
host = lineParts[0].equals("host") ? lineParts[1] : host;
port = lineParts[0].equals("port") ? lineParts[1] : port;
database = lineParts[0].equals("database") ? lineParts[1] : database;
login = lineParts[0].equals("login") ? lineParts[1] : login;
password = lineParts[0].equals("password") ? lineParts[1] : password;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public String getDatabase() {
return database;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}
| [
"[email protected]"
]
| |
fa892fee69ae1d9aa4e85bdb3b91ea91569291ed | a837aeb4602a82201910a724ec6c22f6f6356e1f | /swm/swm-services/src/main/java/org/egov/swm/domain/service/VehicleScheduleService.java | 6eaea7c4da2dd7111f7327dba155d910b393dac0 | []
| no_license | ramanareddy4/egov-services | 163fd8a0e30ea37367e31b4abd8b2900ef58e2a7 | 3dc72dc3a0244f53d092c5b2ac26924cf995572d | refs/heads/master | 2021-08-30T15:04:59.397828 | 2017-12-18T11:01:57 | 2017-12-18T11:01:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,284 | java | package org.egov.swm.domain.service;
import java.util.Date;
import org.egov.common.contract.request.RequestInfo;
import org.egov.swm.domain.model.AuditDetails;
import org.egov.swm.domain.model.Pagination;
import org.egov.swm.domain.model.Route;
import org.egov.swm.domain.model.RouteSearch;
import org.egov.swm.domain.model.Vehicle;
import org.egov.swm.domain.model.VehicleSchedule;
import org.egov.swm.domain.model.VehicleScheduleSearch;
import org.egov.swm.domain.model.VehicleSearch;
import org.egov.swm.domain.repository.VehicleScheduleRepository;
import org.egov.swm.web.repository.IdgenRepository;
import org.egov.swm.web.requests.VehicleScheduleRequest;
import org.egov.tracer.model.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(readOnly = true)
public class VehicleScheduleService {
@Autowired
private VehicleScheduleRepository vehicleScheduleRepository;
@Autowired
private IdgenRepository idgenRepository;
@Value("${egov.swm.vehicleschedule.transaction.num.idgen.name}")
private String idGenNameForVehicleScheduleTNRNumPath;
@Autowired
private VehicleService vehicleService;
@Autowired
private RouteService routeService;
@Transactional
public VehicleScheduleRequest create(final VehicleScheduleRequest vehicleScheduleRequest) {
validate(vehicleScheduleRequest);
Long userId = null;
if (vehicleScheduleRequest.getRequestInfo() != null
&& vehicleScheduleRequest.getRequestInfo().getUserInfo() != null
&& null != vehicleScheduleRequest.getRequestInfo().getUserInfo().getId())
userId = vehicleScheduleRequest.getRequestInfo().getUserInfo().getId();
for (final VehicleSchedule v : vehicleScheduleRequest.getVehicleSchedules()) {
setAuditDetails(v, userId);
v.setTransactionNo(generateTransactionNumber(v.getTenantId(), vehicleScheduleRequest.getRequestInfo()));
}
return vehicleScheduleRepository.save(vehicleScheduleRequest);
}
@Transactional
public VehicleScheduleRequest update(final VehicleScheduleRequest vehicleScheduleRequest) {
final Long userId = null;
for (final VehicleSchedule v : vehicleScheduleRequest.getVehicleSchedules())
setAuditDetails(v, userId);
validate(vehicleScheduleRequest);
return vehicleScheduleRepository.update(vehicleScheduleRequest);
}
private void validate(final VehicleScheduleRequest vehicleScheduleRequest) {
RouteSearch routeSearch;
Pagination<Route> routes;
VehicleSearch vehicleSearch;
Pagination<Vehicle> vehicleList;
for (final VehicleSchedule vehicleSchedule : vehicleScheduleRequest.getVehicleSchedules()) {
if (vehicleSchedule.getVehicle() != null && (vehicleSchedule.getVehicle().getRegNumber() == null
|| vehicleSchedule.getVehicle().getRegNumber().isEmpty()))
throw new CustomException("Vehicle",
"The field Vehicle registration number is Mandatory . It cannot be not be null or empty.Please provide correct value ");
// Validate Vehicle
if (vehicleSchedule.getVehicle() != null && vehicleSchedule.getVehicle().getRegNumber() != null
&& !vehicleSchedule.getVehicle().getRegNumber().isEmpty()) {
vehicleSearch = new VehicleSearch();
vehicleSearch.setTenantId(vehicleSchedule.getTenantId());
vehicleSearch.setRegNumber(vehicleSchedule.getVehicle().getRegNumber());
vehicleList = vehicleService.search(vehicleSearch);
if (vehicleList == null || vehicleList.getPagedData() == null || vehicleList.getPagedData().isEmpty())
throw new CustomException("Vehicle",
"Given Vehicle is invalid: " + vehicleSchedule.getVehicle().getRegNumber());
else
vehicleSchedule.setVehicle(vehicleList.getPagedData().get(0));
} else {
throw new CustomException("Vehicle",
"The field Vehicle is Mandatory . It cannot be not be null or empty.Please provide correct value ");
}
if (vehicleSchedule.getRoute() != null && (vehicleSchedule.getRoute().getCode() == null
|| vehicleSchedule.getRoute().getCode().isEmpty()))
throw new CustomException("Route",
"Given Route is invalid: " + vehicleSchedule.getRoute().getCode());
// Validate Route
if (vehicleSchedule.getRoute() != null && vehicleSchedule.getRoute().getCode() != null
&& !vehicleSchedule.getRoute().getCode().isEmpty()) {
routeSearch = new RouteSearch();
routeSearch.setTenantId(vehicleSchedule.getTenantId());
routeSearch.setCode(vehicleSchedule.getRoute().getCode());
routes = routeService.search(routeSearch);
if (routes == null || routes.getPagedData() == null || routes.getPagedData().isEmpty())
throw new CustomException("Route",
"Given Route is invalid: " + vehicleSchedule.getRoute().getCode());
else
vehicleSchedule.setRoute(routes.getPagedData().get(0));
} else {
throw new CustomException("Route",
"The field Route is Mandatory . It cannot be not be null or empty.Please provide correct value ");
}
if (vehicleSchedule.getScheduledFrom() != null && vehicleSchedule.getScheduledTo() != null)
if (new Date(vehicleSchedule.getScheduledTo()).before(new Date(vehicleSchedule.getScheduledFrom())))
throw new CustomException("ScheduledToDate ",
"Given Scheduled To Date is invalid: " + new Date(vehicleSchedule.getScheduledTo()));
}
}
private String generateTransactionNumber(final String tenantId, final RequestInfo requestInfo) {
return idgenRepository.getIdGeneration(tenantId, requestInfo, idGenNameForVehicleScheduleTNRNumPath);
}
public Pagination<VehicleSchedule> search(final VehicleScheduleSearch vehicleScheduleSearch) {
return vehicleScheduleRepository.search(vehicleScheduleSearch);
}
private void setAuditDetails(final VehicleSchedule contract, final Long userId) {
if (contract.getAuditDetails() == null)
contract.setAuditDetails(new AuditDetails());
if (null == contract.getTransactionNo() || contract.getTransactionNo().isEmpty()) {
contract.getAuditDetails().setCreatedBy(null != userId ? userId.toString() : null);
contract.getAuditDetails().setCreatedTime(new Date().getTime());
}
contract.getAuditDetails().setLastModifiedBy(null != userId ? userId.toString() : null);
contract.getAuditDetails().setLastModifiedTime(new Date().getTime());
}
} | [
"[email protected]"
]
| |
44be6cc8e1269f6d337c2e4e94ff7a70f3f80c23 | ee7ffcc7a7e670082ce4dedab68cfa1df14f4d2d | /src/seleniumManual/TableSort.java | 74cbb1c555f9e1315aa6cc4c188f12dc3cfa4915 | []
| no_license | Sabrimi/GitDemo | 83524b201d5a7efe652b6188e8322bfb39c8e181 | ad080f5c11ed23f764e3e1127d13d8fd13024198 | refs/heads/master | 2022-11-23T13:34:36.723717 | 2020-07-23T20:50:37 | 2020-07-23T20:50:37 | 282,043,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,526 | java | package seleniumManual;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class TableSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "//Users//Sabrusutra//Downloads//chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/offers");
driver.findElement(By.xpath("//b[contains(text(),'Veg')]")).click();
// driver.findElement(By.xpath("//b[contains(text(),'Veg')]")).click();
List<WebElement> fristColList = driver.findElements(By.xpath("//tr/td[2]"));
ArrayList<String> originalList = new ArrayList<String>();
for (int i = 0; i < fristColList.size(); i++) {
originalList.add(fristColList.get(i).getText());
}
ArrayList<String> copitedList = new ArrayList<String>();
for (int i = 0; i < originalList.size(); i++) {
copitedList.add(originalList.get(i));
}
System.out.println("***********************");
Collections.sort(copitedList);
Collections.reverse(copitedList);
for (String s : copitedList) {
System.out.println(s);
}
System.out.println("********Original List***************+");
for (String s : originalList) {
System.out.println(s);
}
Assert.assertTrue(originalList.equals(copitedList));
}
}
| [
"[email protected]"
]
| |
3bbe9843cff97c265b7182e60fd301139ea1deb4 | bbf4de973c9d08cbce36ac5f7d6035a656532d81 | /src/team/artyukh/project/HomeActivity.java | dd3d443a09d9d6060c34c99fc3f3b23c2b20c044 | []
| no_license | jaskirankaur/meet-up | 37a4240d52fe3bf4f76a3ceaa83680e8a9006875 | dcad61bceb21713a95b04faf55909e5037831a99 | refs/heads/master | 2021-01-18T08:57:44.404469 | 2015-03-05T01:57:31 | 2015-03-05T01:57:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,971 | java | package team.artyukh.project;
import java.util.ArrayList;
import team.artyukh.project.fragments.ChatFragment;
import team.artyukh.project.fragments.GroupFragment;
import team.artyukh.project.fragments.MapViewFragment;
import team.artyukh.project.fragments.SearchFragment;
import team.artyukh.project.lists.DrawerItemClickListener;
import team.artyukh.project.messages.server.ChatUpdate;
import team.artyukh.project.messages.server.GroupUpdate;
import team.artyukh.project.messages.server.ImageDownloadUpdate;
import team.artyukh.project.messages.server.MapUpdate;
import team.artyukh.project.messages.server.SearchUpdate;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HomeActivity extends BindingActivity {
MapViewFragment fragMap = new MapViewFragment();
GroupFragment fragGroup = new GroupFragment();
ChatFragment fragChat = new ChatFragment();
SearchFragment fragSearch = new SearchFragment();
private ViewPager myPager;
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawer,
R.drawable.icon_drawer,
R.string.accept,
R.string.accept
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("Activity");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Navigation");
}
};
mDrawer.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ArrayList<String> listItems = new ArrayList<String>();
listItems.add("My Profile");
listItems.add("My Places");
listItems.add("Friends");
listItems.add("Settings");
//ADD DRAWER LIST ADAPTER
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener(this));
myPager = (ViewPager) findViewById(R.id.pager);
MyPagerAdapter myAdapter = new MyPagerAdapter(getSupportFragmentManager());
myAdapter.addFragment(fragMap, "Map");
myAdapter.addFragment(fragChat, "Chat");
myAdapter.addFragment(fragGroup, "Meeting");
myAdapter.addFragment(fragSearch, "Search");
myPager.setAdapter(myAdapter);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
protected void applyUpdate(MapUpdate message){
fragMap.updateMap(message);
}
protected void applyUpdate(SearchUpdate message){
fragSearch.setResult(HomeActivity.this, message.getResult());
myPager.setCurrentItem(3);
}
protected void applyUpdate(GroupUpdate message){
fragGroup.setMemberAdapter(message.getMembers(), this);
fragGroup.configureViews();
fragChat.restoreChat();
}
protected void applyUpdate(ChatUpdate message){
fragChat.restoreChat();
}
protected void applyUpdate(ImageDownloadUpdate message){
super.applyUpdate(message);
fragChat.refreshViews();
fragGroup.refreshViews();
fragSearch.refreshViews();
}
public void startSearch(View v){
fragSearch.startSearch();
}
public void backToSearch(View v){
fragSearch.backToSearch();
}
public void sendMessage(View v){
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} | [
"[email protected]"
]
| |
c0b1550b9472c39af3608980d8b2e7ead0771d6d | efdda326cba1b95cd22970c5787007e3af1a5d59 | /src/main/java/com/newvery/web/filter/OnlineUserListener.java | dbf1a4cf53e7a39e3e9dfc0fb5f2e9a51da8b087 | []
| no_license | xiaoxi1313/benr | 43e2056496ad344c4cb32b4599fc1ee7c4e06edd | 28557161d7906e6ff9cd43208341b73e8eb5ba05 | refs/heads/master | 2020-12-24T06:48:51.553548 | 2016-11-10T15:47:22 | 2016-11-10T15:47:22 | 73,397,241 | 0 | 0 | null | 2016-11-10T15:54:35 | 2016-11-10T15:54:35 | null | UTF-8 | Java | false | false | 1,035 | java | package com.newvery.web.filter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineUserListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
// 取得登录的用户名
String userName = (String) session.getAttribute("userName");
// 从在线列表中删除用户名
List onlineUserList = (List) application.getAttribute("onlineUserList");
onlineUserList.remove(session);
System.out.println("ID为: " + session.getId() + " 用户名为:" + userName + "已经退出!");
System.out.println("time: " +session.getLastAccessedTime());
}
}
| [
"[email protected]"
]
| |
86be1a1cd980938726d9da46dca718b8d2c36742 | c992a95469ccefdbb21f37f35c106f4f0b9c23ff | /besu/src/main/java/org/hyperledger/besu/cli/options/stable/P2PTLSConfigOptions.java | 3ae6583b3cabe1217674752a51ea65b9da8ff404 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
]
| permissive | matkt/besu | 2db4f474ad726d8492fbd21de1ce59815edd74aa | cba7b86eca755619c1cfad37a32f376d1c1d2290 | refs/heads/develop | 2023-08-31T23:13:26.891388 | 2022-04-14T15:20:25 | 2022-04-14T15:20:25 | 219,831,062 | 1 | 0 | Apache-2.0 | 2022-03-15T09:36:21 | 2019-11-05T19:12:52 | Java | UTF-8 | Java | false | false | 5,217 | java | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.cli.options.stable;
import static java.util.Arrays.asList;
import static org.hyperledger.besu.cli.DefaultCommandValues.DEFAULT_KEYSTORE_TYPE;
import static org.hyperledger.besu.cli.DefaultCommandValues.MANDATORY_FILE_FORMAT_HELP;
import org.hyperledger.besu.cli.util.CommandLineUtils;
import org.hyperledger.besu.ethereum.api.tls.FileBasedPasswordProvider;
import org.hyperledger.besu.ethereum.p2p.rlpx.connections.netty.TLSConfiguration;
import java.nio.file.Path;
import java.util.Optional;
import org.slf4j.Logger;
import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException;
public class P2PTLSConfigOptions {
@Option(
names = {"--Xp2p-tls-enabled"},
hidden = true,
description = "Enable P2P TLS functionality (default: ${DEFAULT-VALUE})")
private final Boolean p2pTLSEnabled = false;
@SuppressWarnings({
"FieldCanBeFinal",
"FieldMayBeFinal"
}) // p2pTLSKeyStoreType requires non-final Strings.
@Option(
names = {"--Xp2p-tls-keystore-type"},
hidden = true,
paramLabel = "<NAME>",
description = "P2P service keystore type. Required if P2P TLS is enabled.")
private String p2pTLSKeyStoreType = DEFAULT_KEYSTORE_TYPE;
@Option(
names = {"--Xp2p-tls-keystore-file"},
hidden = true,
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description = "Keystore containing key/certificate for the P2P service.")
private final Path p2pTLSKeyStoreFile = null;
@Option(
names = {"--Xp2p-tls-keystore-password-file"},
hidden = true,
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description =
"File containing password to unlock keystore for the P2P service. Required if P2P TLS is enabled.")
private final Path p2pTLSKeyStorePasswordFile = null;
@SuppressWarnings({
"FieldCanBeFinal",
"FieldMayBeFinal"
}) // p2pTLSTrustStoreType requires non-final Strings.
@Option(
names = {"--Xp2p-tls-truststore-type"},
hidden = true,
paramLabel = "<NAME>",
description = "P2P service truststore type.")
private String p2pTLSTrustStoreType = DEFAULT_KEYSTORE_TYPE;
@Option(
names = {"--Xp2p-tls-truststore-file"},
hidden = true,
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description = "Truststore containing trusted certificates for the P2P service.")
private final Path p2pTLSTrustStoreFile = null;
@Option(
names = {"--Xp2p-tls-truststore-password-file"},
hidden = true,
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description = "File containing password to unlock truststore for the P2P service.")
private final Path p2pTLSTrustStorePasswordFile = null;
@Option(
names = {"--Xp2p-tls-crl-file"},
hidden = true,
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description = "Certificate revocation list for the P2P service.")
private final Path p2pCrlFile = null;
public Optional<TLSConfiguration> p2pTLSConfiguration(final CommandLine commandLine) {
if (!p2pTLSEnabled) {
return Optional.empty();
}
if (p2pTLSKeyStoreType == null) {
throw new ParameterException(
commandLine, "Keystore type is required when p2p TLS is enabled");
}
if (p2pTLSKeyStorePasswordFile == null) {
throw new ParameterException(
commandLine,
"File containing password to unlock keystore is required when p2p TLS is enabled");
}
return Optional.of(
TLSConfiguration.Builder.tlsConfiguration()
.withKeyStoreType(p2pTLSKeyStoreType)
.withKeyStorePath(p2pTLSKeyStoreFile)
.withKeyStorePasswordSupplier(new FileBasedPasswordProvider(p2pTLSKeyStorePasswordFile))
.withKeyStorePasswordPath(p2pTLSKeyStorePasswordFile)
.withTrustStoreType(p2pTLSTrustStoreType)
.withTrustStorePath(p2pTLSTrustStoreFile)
.withTrustStorePasswordSupplier(
null == p2pTLSTrustStorePasswordFile
? null
: new FileBasedPasswordProvider(p2pTLSTrustStorePasswordFile))
.withTrustStorePasswordPath(p2pTLSTrustStorePasswordFile)
.withCrlPath(p2pCrlFile)
.build());
}
public void checkP2PTLSOptionsDependencies(final Logger logger, final CommandLine commandLine) {
CommandLineUtils.checkOptionDependencies(
logger,
commandLine,
"--Xp2p-tls-enabled",
!p2pTLSEnabled,
asList("--Xp2p-tls-keystore-type", "--Xp2p-tls-keystore-password-file"));
}
}
| [
"[email protected]"
]
| |
6b2970c8675ff764c74db8834f6783707a9c181a | 29ab453ad5e8115b06104eca3048b84f75a645f0 | /append-and-delete/src/main/java/Solution.java | 7f36f9eac490b6cdf7fbded56368da93992fd9cb | []
| no_license | MarceloLeite2604/hackerrank | 02675950fab8428689b7533ff82add03e9b2890c | 50eccccc0beb5bd072283d70a088864365ef52ab | refs/heads/master | 2023-03-09T11:35:00.916450 | 2023-02-21T16:18:43 | 2023-02-21T16:18:43 | 207,789,378 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,670 | java | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Solution {
// Complete the appendAndDelete function below.
static String appendAndDelete(String s, String t, int k) {
Context context = new Context(s, t, k);
if (canFullyRewrite(context)) {
return "Yes";
}
if (areSameSequences(context)) {
return hasOddRemainingMoves(context.getMoves()) ? "Yes" : "No";
}
// Append only.
if (shouldAppendOnly(context)) {
if (hasEnoughMovesToAppend(context)) {
int remainingMoves = context.getRemainingTargetCharacters() - context.getMoves();
return hasOddRemainingMoves(remainingMoves) ? "Yes" : "No";
} else {
return "No";
}
}
// Delete only.
if (shouldDeleteOnly(context)) {
if (hasEnoughMovesToDelete(context)) {
int remainingMoves = context.getRemainingSourceCharacters() - context.getMoves();
return hasOddRemainingMoves(remainingMoves) ? "Yes" : "No";
} else {
return "No";
}
}
// Append and delete.
if (hasEnoughMoves(k, context.getTotalRemainingCharacters())) {
if (context.isNoMatchingPrefix()) {
return "Yes";
} else {
int remainingMoves = context.getTotalRemainingCharacters() - context.getMoves();
return hasOddRemainingMoves(remainingMoves) ? "Yes" : "No";
}
}
return "No";
}
private static boolean canFullyRewrite(Context context) {
return context.getMoves() >= context.getSource().length() + context.getTarget().length();
}
private static boolean hasEnoughMoves(int totalMoves, int requiredMoves) {
return totalMoves >= requiredMoves;
}
private static boolean shouldDeleteOnly(Context context) {
return context.getSource()
.length() > context.getTarget()
.length()
&& context.getMatchingPrefix()
.equals(context.getTarget());
}
private static boolean hasEnoughMovesToAppend(Context context) {
return hasEnoughMoves(context.getMoves(), context.getRemainingTargetCharacters());
}
private static boolean hasEnoughMovesToDelete(Context context) {
return hasEnoughMoves(context.getMoves(), context.getRemainingSourceCharacters());
}
private static boolean shouldAppendOnly(Context context) {
return context.getSource()
.length() < context.getTarget()
.length()
&& context.getMatchingPrefix()
.equals(context.getSource());
}
private static boolean hasOddRemainingMoves(int moves) {
return moves % 2 == 0;
}
private static boolean areSameSequences(Context context) {
return context.getSource()
.equals(context.getTarget());
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(
new FileWriter(System.getenv("OUTPUT_PATH")));
String s = scanner.nextLine();
String t = scanner.nextLine();
int k = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String result = appendAndDelete(s, t, k);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
private static class Context {
private String matchingPrefix;
private int remainingTargetCharacters;
private int remainingSourceCharacters;
private int totalRemainingCharacters;
private boolean noMatchingPrefix;
private String source;
private String target;
private int moves;
public Context(String s, String t, int k) {
source = s;
target = t;
moves = k;
matchingPrefix = retrieveMatchingPrefix(s, t);
remainingTargetCharacters = t.replaceFirst(matchingPrefix, "")
.length();
remainingSourceCharacters = s.replaceFirst(matchingPrefix, "")
.length();
totalRemainingCharacters = remainingSourceCharacters + remainingTargetCharacters;
noMatchingPrefix = matchingPrefix.length() == 0;
}
public String getMatchingPrefix() {
return matchingPrefix;
}
public int getRemainingTargetCharacters() {
return remainingTargetCharacters;
}
public int getRemainingSourceCharacters() {
return remainingSourceCharacters;
}
public int getTotalRemainingCharacters() {
return totalRemainingCharacters;
}
public boolean isNoMatchingPrefix() {
return noMatchingPrefix;
}
public String getSource() {
return source;
}
public String getTarget() {
return target;
}
public int getMoves() {
return moves;
}
private String retrieveMatchingPrefix(String s, String t) {
int index = 0;
while (index < s.length() && index < t.length() && s.charAt(index) == t.charAt(index)) {
index++;
}
return s.substring(0, index);
}
}
}
| [
"[email protected]"
]
| |
17e3bb853d57f8a363e90797f2e91ce43db463d1 | 91297ffb10fb4a601cf1d261e32886e7c746c201 | /java.source/test/unit/src/org/netbeans/api/java/source/gen/MoveTreeTest.java | f18af51b5656ccf7c45420ddb4d82df2882b41e2 | []
| no_license | JavaQualitasCorpus/netbeans-7.3 | 0b0a49d8191393ef848241a4d0aa0ecc2a71ceba | 60018fd982f9b0c9fa81702c49980db5a47f241e | refs/heads/master | 2023-08-12T09:29:23.549956 | 2019-03-16T17:06:32 | 2019-03-16T17:06:32 | 167,005,013 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 27,477 | java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2009 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.api.java.source.gen;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeKind;
import org.netbeans.api.java.source.Task;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.JavaSource.Phase;
import org.netbeans.api.java.source.TestUtilities;
import org.netbeans.api.java.source.TreeMaker;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.junit.NbTestSuite;
import org.netbeans.modules.java.ui.FmtOptions;
/**
* Tests method type parameters changes.
*
* @author Pavel Flaska
*/
public class MoveTreeTest extends GeneratorTestBase {
static {
System.setProperty("org.netbeans.api.java.source.WorkingCopy.keep-old-trees", "true");
}
/** Creates a new instance of MethodParametersTest */
public MoveTreeTest(String testName) {
super(testName);
}
public static NbTestSuite suite() {
NbTestSuite suite = new NbTestSuite();
suite.addTestSuite(MoveTreeTest.class);
return suite;
}
public void testMoveExpression1() throws Exception {
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 = 1+ 2 *3;\n" +
" int i2 = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 = 1+ 2 *3;\n" +
" int i2 = 1+ 2 *3;\n" +
" }\n" +
"}\n");
}
public void testMoveExpression2() throws Exception {
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 = 1+ \n" +
" 2 *3;\n" +
" int foo = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 = 1+ \n" +
" 2 *3;\n" +
" int foo = 1+ \n" +
" 2 *3;\n" +
" }\n" +
"}\n");
}
public void testMoveExpression3() throws Exception {
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 =\n" +
" 1+ \n" +
" 2 *3;\n" +
" int foo = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 =\n" +
" 1+ \n" +
" 2 *3;\n" +
" int foo = 1+ \n" +
" 2 *3;\n" +
" }\n" +
"}\n");
}
public void testMoveExpression4() throws Exception {
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 =\n" +
" 1+ \n" +
" 2 *3;\n" +
" int foo = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" int i1 =\n" +
" 1+ \n" +
" 2 *3;\n" +
" int foo = 1+ \n" +
" 2 *3;\n" +
" }\n" +
"}\n");
}
private static final Map<String, String> TAB_SIZE_PREFERENCES =
Utils.MapBuilder.<String, String>create().add(FmtOptions.indentSize, "4")
.add(FmtOptions.tabSize, "8")
.build();
public void testMoveExpression2Tab() throws Exception {
Map<String, String> origValues = Utils.setCodePreferences(TAB_SIZE_PREFERENCES);
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
"\tint i1 = 1+ \n" +
"\t 2 *3;\n" +
" int foo = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
"\tint i1 = 1+ \n" +
"\t 2 *3;\n" +
" int foo = 1+ \n" +
" 2 *3;\n" +
" }\n" +
"}\n");
Utils.setCodePreferences(origValues);
}
public void testMoveExpression3Tab() throws Exception {
Map<String, String> origValues = Utils.setCodePreferences(TAB_SIZE_PREFERENCES);
performMoveExpressionTest(
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
"\tint i1 =\n" +
"\t 1+ \n" +
"\t 2 *3;\n" +
" int foo = 0;\n" +
" }\n" +
"}\n",
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
"\tint i1 =\n" +
"\t 1+ \n" +
"\t 2 *3;\n" +
" int foo = 1+ \n" +
" 2 *3;\n" +
" }\n" +
"}\n");
Utils.setCodePreferences(origValues);
}
private void performMoveExpressionTest(String code, String golden) throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile, code);
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
VariableTree var1 = (VariableTree) method.getBody().getStatements().get(0);
VariableTree var2 = (VariableTree) method.getBody().getStatements().get(1);
workingCopy.rewrite(var2.getInitializer(), var1.getInitializer());
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
public void testMoveExpressionToStatement() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui(String s1, String s2) {\n" +
" int i1 = taragui(\"foo\",\n" +
" \"bar\");\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui(String s1, String s2) {\n" +
" taragui(\"foo\",\n" +
" \"bar\");\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
VariableTree var = (VariableTree) method.getBody().getStatements().get(0);
workingCopy.rewrite(var, workingCopy.getTreeMaker().ExpressionStatement(var.getInitializer()));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
public void testMoveExpressionToStatementTab() throws Exception {
Map<String, String> origValues = Utils.setCodePreferences(TAB_SIZE_PREFERENCES);
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui(String s1, String s2) {\n" +
"\tint i1 = taragui(\"foo\",\n" +
"\t\t\t \"bar\");\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui(String s1, String s2) {\n" +
" taragui(\"foo\",\n" +
" \"bar\");\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
VariableTree var = (VariableTree) method.getBody().getStatements().get(0);
workingCopy.rewrite(var, workingCopy.getTreeMaker().ExpressionStatement(var.getInitializer()));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
Utils.setCodePreferences(origValues);
}
public void testMoveMethod() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" private static class A {\n" +
" public void taragui() {\n" +
" int i1 = 1+ 2 *3;\n" +
" int i2 = 1+ 2 *3;\n" +
" }\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" private static class A {\n" +
" }\n" +
"\n" +
" public void taragui() {\n" +
" int i1 = 1+ 2 *3;\n" +
" int i2 = 1+ 2 *3;\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
ClassTree clazzInner = (ClassTree) clazz.getMembers().get(1);
MethodTree method = (MethodTree) clazzInner.getMembers().get(1);
workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
workingCopy.rewrite(clazzInner, make.removeClassMember(clazzInner, method));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
public void testMoveStatements() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" System.err.println(5);\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" {\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" }\n" +
" System.err.println(5);\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree inner = make.Block(body.getStatements().subList(1, 5), false);
BlockTree nue = make.Block(Arrays.asList(body.getStatements().get(0), inner, body.getStatements().get(5)), false);
workingCopy.rewrite(body, nue);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
public void testMoveStatements2() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" {\n" +
" while (true) {\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" }\n" +
" }\n" +
" if (true) {\n" +
" System.err.println(5);\n" +
" }\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" System.err.println(1);\n" +
" if (true) {\n" +
" System.err.println(2);\n" +
"\n" +
"\n" +
" System.err.println(3);System.err.println(3.5);\n" +
" System. err.\n" +
" println(4);\n" +
" }\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree block = (BlockTree)body.getStatements().get(1);
WhileLoopTree loop = (WhileLoopTree)block.getStatements().get(0);
IfTree inner = make.If(make.Parenthesized(make.Literal(Boolean.TRUE)), loop.getStatement(), null);
BlockTree nue = make.Block(Arrays.asList(body.getStatements().get(0), inner), false);
workingCopy.rewrite(body, nue);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
public void test187616() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
" //blabla\n" +
"\twhile(path.getLeaf().getKind() != Kind.CLASS) {\n" +
" }\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
" //blabla\n" +
"\twhile(!TreeUtilities.SET.contains(path.getLeaf().getKind())) {\n" +
" }\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.PARSED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
BlockTree body = method.getBody();
WhileLoopTree loop = (WhileLoopTree)body.getStatements().get(0);
BinaryTree origCond = (BinaryTree) ((ParenthesizedTree) loop.getCondition()).getExpression();
ExpressionTree nueCondition = make.Unary(Tree.Kind.LOGICAL_COMPLEMENT, make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.MemberSelect(make.Identifier("TreeUtilities"), "SET"), "contains"), Collections.singletonList(origCond.getLeftOperand())));
workingCopy.rewrite(origCond, nueCondition);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
private static final Map<String, String> NO_TAB_EXPAND_PREFERENCES =
Utils.MapBuilder.<String, String>create().add(FmtOptions.indentSize, "4")
.add(FmtOptions.tabSize, "8")
.add(FmtOptions.expandTabToSpaces, "false")
.build();
public void test192753() throws Exception {
Map<String, String> origValues = Utils.setCodePreferences(NO_TAB_EXPAND_PREFERENCES);
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
"\tint a = 0;\n" +
"\tSystem.err.println(1);\n" +
"\tSystem.err.println(2);\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public void taragui(String str) {\n" +
"\tint a = 0;\n" +
" }\n\n" +
" void nue() {\n" +
"\tSystem.err.println(1);\n" +
"\tSystem.err.println(2);\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
BlockTree body = method.getBody();
BlockTree nueBlock = make.Block(body.getStatements().subList(1, body.getStatements().size()), false);
MethodTree nueMethod = make.Method(make.Modifiers(EnumSet.noneOf(Modifier.class)), "nue", make.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), nueBlock, null);
workingCopy.rewrite(clazz, make.addClassMember(clazz, nueMethod));
workingCopy.rewrite(body, make.Block(body.getStatements().subList(0, 1), false));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
Utils.setCodePreferences(origValues);
}
public void testCLikeArray() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui() {\n" +
" int ii[] = null;" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public int taragui(int[] a) {\n" +
" int ii[] = null;" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
VariableTree var = (VariableTree) method.getBody().getStatements().get(0);
TreeMaker make = workingCopy.getTreeMaker();
VariableTree param = workingCopy.getTreeMaker().Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "a", var.getType(), null);
workingCopy.rewrite(method, make.addMethodParameter(method, param));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
String getGoldenPckg() {
return "";
}
String getSourcePckg() {
return "";
}
}
| [
"[email protected]"
]
| |
e06db947453d4ad719eda6190b819e8e89efe386 | b727c877917754502424c6d6fd6d37103c612f87 | /src/com/landray/kmss/zsrd/knc/form/service/IZsrdKncFormMainService.java | 2bc9a8babceb1dfec5a1d86c03c8ef3dbda1f71f | []
| no_license | Anience/ekp | 5d60ed53f3256bf232d64eddaf838bfd9d334324 | 487281bf80302a8a1bbedbae4e725c631f449ec4 | refs/heads/master | 2020-03-28T12:55:23.378445 | 2018-09-11T16:52:53 | 2018-09-11T16:52:53 | 144,544,741 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package com.landray.kmss.zsrd.knc.form.service;
import com.landray.kmss.common.service.IBaseService;
import com.landray.kmss.zsrd.knc.form.model.ZsrdKncFormCategory;
import com.landray.kmss.zsrd.knc.form.model.ZsrdKncFormMain;
/**
* 标准库业务对象接口
*
* @author
* @version 1.0 2017-03-06
*/
public interface IZsrdKncFormMainService extends IBaseService {
ZsrdKncFormCategory getZsrdKncFormCategory(String docCategoryId) throws Exception;
void startProcess(ZsrdKncFormMain doc) throws Exception;
}
| [
"323546"
]
| 323546 |
486513ef1fbe1be4b496661477bba2e785bbbe5f | 86d61d5c78a0d64f12a3c6f3892e799df3ccd190 | /Codificador-ejb/src/java/catalogo/entidad/TipoNomina.java | b6b7d4f740b58e6b0d810c407dcf4ff411ad42ad | []
| no_license | fcoggtzn/Codificador | 2b62fa4e3252d4ba8ada7cd43310d2db509de298 | b7a2fecba9862a42b63fbefa464e550269a5a25d | refs/heads/master | 2021-04-15T09:50:47.236821 | 2020-04-04T04:45:14 | 2020-04-04T04:45:14 | 94,573,991 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,913 | java | /*
* 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 catalogo.entidad;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author ovante
*/
@Entity
@Table(name = "tipo_nomina", catalog = "catalogoSat", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TipoNomina.findAll", query = "SELECT t FROM TipoNomina t")
, @NamedQuery(name = "TipoNomina.findById", query = "SELECT t FROM TipoNomina t WHERE t.id = :id")
, @NamedQuery(name = "TipoNomina.findByTipoNomina", query = "SELECT t FROM TipoNomina t WHERE t.tipoNomina = :tipoNomina")
, @NamedQuery(name = "TipoNomina.findByDescripcion", query = "SELECT t FROM TipoNomina t WHERE t.descripcion = :descripcion")})
public class TipoNomina implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 255)
@Column(name = "tipo_nomina")
private String tipoNomina;
@Size(max = 255)
@Column(name = "descripcion")
private String descripcion;
public TipoNomina() {
}
public TipoNomina(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTipoNomina() {
return tipoNomina;
}
public void setTipoNomina(String tipoNomina) {
this.tipoNomina = tipoNomina;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TipoNomina)) {
return false;
}
TipoNomina other = (TipoNomina) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "catalogo.entidad.TipoNomina[ id=" + id + " ]";
}
}
| [
"ovante@minideovante2"
]
| ovante@minideovante2 |
0e188d2439a4934e8abb92e1a3312cdd1e6ffe1c | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /java/java-tests/testData/psi/optimizeImports/ExcludeNonStaticElementsFromStaticConflictingMembers.java | 051b6d9195f914ad9f250220f579ebf4ab662164 | [
"Apache-2.0"
]
| permissive | JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560889 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | null | UTF-8 | Java | false | false | 260 | java | import static java.lang.String.format;
import static java.lang.String.valueOf;
import static java.lang.String.copyValueOf;
class OptimizeImport {
public static void main(String[] args) {
format("foo");
valueOf(1);
copyValueOf(new char[0]);
}
} | [
"[email protected]"
]
| |
0b067e2f79cb7791e06c574f65d7d4bbfe6bc64c | d69ec1b9029ab4fcc1a93c3ab3a1c4fc81177946 | /src/com/browserhorde/server/XMachineIdFilter.java | 951e81033ceb3e272911984a134db94fba7b403e | []
| no_license | easyas314159/Browser-Horde | ce1349a264024399c810948766844aab29ca4151 | c745d8bb4533967dbec508607cbe399ee39cfe1f | refs/heads/master | 2021-01-18T18:16:19.600923 | 2012-07-05T22:25:43 | 2012-07-05T22:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,501 | java | package com.browserhorde.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import net.spy.memcached.MemcachedClient;
import org.apache.commons.codec.digest.DigestUtils;
import com.browserhorde.server.api.ApiHeaders;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class XMachineIdFilter extends HttpFilter implements Filter {
private static final Pattern uuidPattern = Pattern.compile(
"\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}"
);
private static final String NS_MACHINE_ID = DigestUtils.md5Hex("machine_id");
@Inject @Nullable private MemcachedClient memcached;
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse rsp, FilterChain chain) throws IOException, ServletException {
// TODO: Maybe tie this into auth so we can track the number of machines each user has
final String checkHeaders[] = new String[]{
ApiHeaders.X_HORDE_MACHINE_ID,
HttpHeaders.IF_MODIFIED_SINCE
};
// FIXME: This needs some fixing
String machineId = null;
boolean userIsNice = true;
Set<String> machineIds = new HashSet<String>();
for(String headerName : checkHeaders) {
Enumeration<String> headerValues = req.getHeaders(headerName);
while(headerValues.hasMoreElements()) {
String headerValue = headerValues.nextElement();
Matcher matcher = uuidPattern.matcher(headerValue);
if(matcher.matches()) {
machineIds.add(headerValue.toLowerCase());
}
}
if(machineIds.size() == 1) {
machineId = machineIds.iterator().next();
break;
}
machineIds.clear();
}
if(machineId == null) {
machineId = UUID.randomUUID().toString();
}
req = new ModifyHeaderWrapper(req)
.withHeader(ApiHeaders.X_HORDE_MACHINE_ID, machineId);
rsp.setHeader(ApiHeaders.X_HORDE_MACHINE_ID, machineId);
rsp.setHeader(HttpHeaders.LAST_MODIFIED, machineId);
chain.doFilter(req, rsp);
}
}
| [
"[email protected]"
]
| |
71b1da3a497492ad7041ae29364e369f346301e8 | f450e28c7cb7da9c385e3fb72c7ba4d03e122841 | /redis-client-core/src/test/java/net/lbtech/redis/User.java | ca4199e087a35bb12fe13aa6978be430b52be251 | []
| no_license | jiaengithub/redis-client-core | c01d827128f788bc53720f895d7aaafaaecc0c5d | 8aea6c092f44d63fcc60dfd6a37da7b4c2421cf6 | refs/heads/master | 2021-01-12T08:35:34.528038 | 2016-08-13T12:31:15 | 2016-08-13T12:31:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 456 | java | package net.lbtech.redis;
import java.io.Serializable;
public class User implements Serializable{
private String id;
private Integer age;
public User(String id, Integer age) {
super();
this.id = id;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
| [
"DF@HDF"
]
| DF@HDF |
c3386fb5356800fd34e71195a49caac1ec2257d6 | d5072fbeaa5bf7e4f09830b8f0fc837226468248 | /src/더블릿/twothirtynine.java | 31fc0e046365bb4d924bc5724ce585bf32649a3d | []
| no_license | anseohyun/javadouble | 058ef779e7ab7207d8ae008358c42834727cf331 | 7a3d4115990dfb42cd6652a3a07883d9d10d31c3 | refs/heads/master | 2021-01-02T02:13:50.649456 | 2020-03-22T02:33:46 | 2020-03-22T02:33:46 | 239,449,472 | 1 | 0 | null | null | null | null | UHC | Java | false | false | 1,398 | java | // 프로그램 명: profit
// 제한시간: 1 초
//
// 물건의 원가가 a 이고 , 원가에 b % 이윤을 붙여서 정가를 정했으나 물건이 잘 팔리지 않아 정가의 c% 를 할인해서 팔았다. 이 물건을 팔았을때의 이윤을 구하여라.
//
// 입력
// a,b,c 가 입력으로 주어진다. (모두 자연수이고 a < 100000 , b,c < 100)
// 출력
// 이윤을 소수 첫째 자리에서 반올림하여 출력한다. 손해를 볼 경우에는 loss 를 출력한다.
//
// 입출력 예
// 입력
// 100 10 10
// 출력
// loss
// 입력
// 100 10 8
// 출력
// 1
package 더블릿;
import java.util.Scanner;
public class twothirtynine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextInt();
double b = sc.nextInt();
double c = sc.nextInt();
double oriprice;
double disprice;
double profit;
oriprice = (a/100)*(b+100);
disprice = (oriprice/100)*(100-c);
if(disprice < a)
{
// System.out.println(oriprice);
// System.out.println(a);
// System.out.println(disprice);
System.out.println("loss");
}
else
{
// System.out.println(oriprice);
// System.out.println(a);
// System.out.println(disprice);
profit = disprice - a;
System.out.println(String.format("%.0f", profit));
}
}
}
| [
"[email protected]"
]
| |
95fa9b77a6c5b8fae45d4dd3cd6e1b6117dfcae9 | 4fb5a3972d311ea836c523f25654bc182f066f64 | /Batch13_CLASS/src/Day4_arithmeticOperators/task17_averageNumbers.java | a2a143ad39ddf055d109324534e5c078b208bed3 | []
| no_license | BalcilarMustafa/JAVA-Course-2019 | 8c434a7920075faf9a576d480b0487afa9fd2b31 | 51afddf74a40ec616f3fa536e73185d709f36b46 | refs/heads/master | 2023-07-22T15:55:11.457521 | 2021-08-29T18:15:34 | 2021-08-29T18:15:34 | 401,105,119 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 396 | java | package Day4_arithmeticOperators;
public class task17_averageNumbers {
public static void main(String[] args) {
double average;
int num1,num2,num3;
num1=10;
num2=35;
num3=50;
average=(num1+num2+num3)/3;
System.out.println("Average is " + average);
int pies=10,people=4;
double piecesPerson;
piecesPerson=pies/people;
System.out.println(piecesPerson);
}
}
| [
"[email protected]"
]
| |
e1e7924ac7bf5d9f81491fdeadec7187e0834fd5 | 8fa9d15d64ac0cef2ad41d8a1890ea1cf89f31e1 | /src/main/java/com/codecool/java/LoginForm.java | a046cfb1f597476eaa72b7d11032806bb95953f1 | []
| no_license | idzia/LoginForm | 596e77b0c978671ed2b9b9bb459a5eec93825e0d | 714bb0c80d2b29e19751652e5bd82d67154f249e | refs/heads/master | 2020-03-23T13:34:17.817330 | 2018-07-21T21:32:04 | 2018-07-21T21:32:04 | 141,625,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,534 | java | package com.codecool.java;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LoginForm implements HttpHandler {
private DBloginForm loginformDB;
public LoginForm() {
loginformDB = new DBloginForm();
}
public void handle(HttpExchange httpExchange) throws IOException {
String method = httpExchange.getRequestMethod();
//Map<String, String> dbpairs = loginformDB.getPairs();
String response = "";
if (method.equals("GET")) {
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/loginForm.twig");
JtwigModel model = JtwigModel.newModel();
model.with("pairs", loginformDB.getPairs() );
response = template.render(model);
}
if (method.equals("POST")) {
InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String formData = br.readLine();
System.out.println(formData);
Map inputs = parseFormData(formData);
String login = inputs.get("login").toString();
String password = inputs.get("pass").toString();
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/gbook.twig");
JtwigModel model = JtwigModel.newModel();
model.with("messageList", loginformDB.getPairs());
response = template.render(model);
}
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private static Map<String, String> parseFormData(String formData) throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<String, String>();
String[] pairs = formData.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
String value = URLDecoder.decode(keyValue[1], "UTF-8");
map.put(keyValue[0], value);
}
return map;
}
private boolean isValid(String login, String pass) {
if (loginformDB.getPairs().get(login).equals(pass)){
return true;
} else return false;
}
}
| [
"[email protected]"
]
| |
cb2188416f30ec0faa4fd527fa6b4a0a36d45404 | 4e808a6196817ca7368f142b924c482ece3a75e7 | /Day05/datastoragetest/src/main/java/com/example/datastoragetest/DBActivity.java | 5dd848503e1e8962314b42adeafd58eecc3774f6 | []
| no_license | l793854601/ATGuiguAndroid | 53caab6fcb86f578ceacccf84ffc2c71636f46f6 | 4567c3dd23b58ca117aec72c4579a70780c946ef | refs/heads/main | 2023-06-25T19:29:00.510827 | 2021-07-26T11:20:03 | 2021-07-26T11:20:03 | 389,599,236 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,367 | java | package com.example.datastoragetest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
/*
测试SQLite数据库村塾
*/
public class DBActivity extends AppCompatActivity {
private static final String TAG = "DBActivity";
private DBHelper mDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbactivity);
}
/*
创建数据库
*/
public void onClickCreateDB(View v) {
mDBHelper = new DBHelper(this, 1);
// 获取数据库连接,此时才会真正的创建数据库文件
mDBHelper.getReadableDatabase();
Toast.makeText(this, "创建数据库", Toast.LENGTH_SHORT).show();
}
/*
更新数据库
*/
public void onClickUpdateDB(View v) {
// mDBHelper = new DBHelper(this, 2);
// mDatabase = mDBHelper.getReadableDatabase();
// Toast.makeText(this, "创建数据库", Toast.LENGTH_SHORT).show();
}
/*
插入数据
*/
public void onClickInsert(View v) {
if (mDBHelper == null) {
Toast.makeText(this, "请先创建数据库", Toast.LENGTH_SHORT).show();
return;
}
// 1.得到(打开)数据库连接
SQLiteDatabase database = mDBHelper.getReadableDatabase();
// 2.执行insert into person(name, age) value('Jerry', 14)
ContentValues values = new ContentValues();
values.put("name", "Jerry");
values.put("age", 14);
// 返回值为插入数据的rowId,-1表示失败
long id = database.insert("person", null, values);
// 3.关闭数据库连接
database.close();
// 4.提示
if (id != -1) {
Toast.makeText(this, "插入数据库成功,id:" + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "插入数据库失败", Toast.LENGTH_SHORT).show();
}
}
/*
更新数据
*/
public void onClickUpdate(View v) {
if (mDBHelper == null) {
Toast.makeText(this, "请先创建数据库", Toast.LENGTH_SHORT).show();
return;
}
// 1.得到(打开)数据库连接
SQLiteDatabase database = mDBHelper.getReadableDatabase();
// 2.执行update person set name='Jack', age = 13 where _id=4
ContentValues values = new ContentValues();
values.put("name", "Jack");
values.put("age", 13);
int count = database.update("person", values, "_id=?", new String[]{"4"});
// 3.关闭数据库连接
database.close();
// 4.提示
Toast.makeText(this, "更新了" + count + "条数据", Toast.LENGTH_SHORT).show();
}
/*
删除数据
*/
public void onClickDelete(View v) {
if (mDBHelper == null) {
Toast.makeText(this, "请先创建数据库", Toast.LENGTH_SHORT).show();
return;
}
// 1.得到(打开)数据库连接
SQLiteDatabase database = mDBHelper.getReadableDatabase();
// 2.执行delete from person where _id=2
int count = database.delete("person", "_id=?", new String[]{"2"});
// 3.关闭数据库连接
database.close();
// 4.提示
Toast.makeText(this, "删除了" + count + "条数据", Toast.LENGTH_SHORT).show();
}
/*
查询数据
*/
public void onClickQuery(View v) {
if (mDBHelper == null) {
Toast.makeText(this, "请先创建数据库", Toast.LENGTH_SHORT).show();
return;
}
// 1.得到(打开)数据库连接
SQLiteDatabase database = mDBHelper.getReadableDatabase();
// 2.执行select * from person
Cursor cursor = database.query("person", null, null, null, null, null, null);
// 得到查询结的数量
int count = cursor.getCount();
// 通过Cursor查询数据
while (cursor.moveToNext()) {
// _id
int idIndex = cursor.getColumnIndex("_id");
int idValue = cursor.getInt(idIndex);
// name
int nameIndex = cursor.getColumnIndex("name");
String nameValue = cursor.getString(nameIndex);
// age
int ageIndex = cursor.getColumnIndex("age");
int ageValue = cursor.getInt(ageIndex);
// 打印数据
Log.d(TAG, "onClickQuery: " + "_id = " + idValue + ", name = " + nameValue + ", age = " + ageValue);
}
// 3.关闭游标、数据库连接
cursor.close(); // Cursor也需要关闭
database.close();
// 4.提示
Toast.makeText(this, "查询到" + count + "条数据", Toast.LENGTH_SHORT).show();
}
/*
事务
执行条sql:
1.将_id为1的数据,age改为15 update person set age=15 where _id=1
2.将_id为3的数据,age改为17 update person set age=17 where _id=3
要保证两条sql都执行成功(要么1、2执行都生效,要么1、2执行都不生效)
事务处理的步骤:
try-catch-finally
1.开启事务(在获取数据库连接后)
2.标记事务成功(在全部正常执行完后)
3.结束事务(finally中)
*/
public void onClickTransaction(View v) {
if (mDBHelper == null) {
Toast.makeText(this, "请先创建数据库", Toast.LENGTH_SHORT).show();
return;
}
SQLiteDatabase database = null;
try {
// 得到数据库连接
database = mDBHelper.getReadableDatabase();
// 开启事务(在获取数据库连接后)
database.beginTransaction();
// update person set age=15 where _id=1
ContentValues values1 = new ContentValues();
values1.put("age", 15);
int count1 = database.update("person", values1, "_id=?", new String[]{"1"});
Log.d(TAG, "updateCount1 = " + count1);
// 模拟出现了异常
Boolean flag = true;
if (flag) {
throw new RuntimeException("出异常了!!!");
}
// update person set age=17 where _id=3
ContentValues values2 = new ContentValues();
values2.put("age", 17);
int count2 = database.update("person", values2, "_id=?", new String[]{"3"});
Log.d(TAG, "updateCount2 = " + count2);
// 标记事务成功(在全部正常执行完后)
database.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "异常!!!", Toast.LENGTH_SHORT).show();
} finally {
if (database != null && database.isOpen()) {
// 结束事务(finally中)
database.endTransaction();
// 关闭数据库连接
database.close();
}
}
}
} | [
"[email protected]"
]
| |
1d14cd739abf3d035d633fdd5963ee2c0012f751 | c95a1bd4008cb397e213c4bb897f038cf65c1c7b | /src/main/java/io/github/homepy/whale/calcite/cs/po/pbc/CspPbcTaxArrear.java | 5b9ac46d01b89c604ad4cb9642cc195c45b5fb02 | []
| no_license | homepy/whale-calcite | b578f20bcb6f980209a0d53ab1e57b1de0bce321 | 25aada0970d4431471794768a0cb93c91209da80 | refs/heads/master | 2022-09-24T20:46:29.208697 | 2020-03-15T17:32:10 | 2020-03-15T17:32:10 | 236,676,007 | 0 | 1 | null | 2022-09-16T23:57:46 | 2020-01-28T06:54:58 | Java | UTF-8 | Java | false | false | 372 | java | package io.github.homepy.whale.calcite.cs.po.pbc;
/** 欠税记录信息(CSP_PBC_TAXARREAR) */
public class CspPbcTaxArrear {
/** 报告编号 */
public String reportid;
/** 主管税务机关 */
public String organname;
/** 欠税总额 */
public String taxarreaamount;
/** 欠税统计日期 */
public String revenuedate;
/** 标识 */
public String seq;
}
| [
"[email protected]"
]
| |
dee3e385185944ef3f8156d6b13ecc1e94061849 | a37c58dea80ff93dab8a6c345cae0f356c4115eb | /javaVerano/src/javaverano/NewClass.java | 79a88ff1a08bb3442b4aef3825fe26e65cf2c7c5 | []
| no_license | alb-martinez/javaVerano | bb5bddb8b8f4875fab832b547ea5fa9224c34613 | e444ad74ce94f7a08b3c0d2f52fc05cf4dfb24f8 | refs/heads/master | 2021-09-28T22:31:11.235212 | 2021-09-14T18:56:46 | 2021-09-14T18:56:46 | 194,132,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 281 | java | /*
* 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 javaverano;
/**
*
* @author Alberto
*/
public class NewClass {
}
| [
"[email protected]"
]
| |
0fc2448ddb9d0c0ba0c7ffa7011fe66da40cfc20 | bb2463935b216001cb0f29034b2da04e065b9c28 | /eureka-consume-Feign/src/main/java/eureka/consume/EurekaConsumeApplication.java | a12efb496eaf6b04530b7f711131a5b0f79442f6 | []
| no_license | lilong0719/springcloud | 79a6914129f2414e9e74855b63a221c656061a66 | 57af9dc90857f491afd79e2c183dee9d549444be | refs/heads/master | 2021-01-20T03:09:38.237087 | 2018-03-23T07:13:07 | 2018-03-23T07:13:07 | 101,352,364 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 721 | java | package eureka.consume;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableCircuitBreaker
public class EurekaConsumeApplication {
/*@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}*/
public static void main(String[] args) {
SpringApplication.run(EurekaConsumeApplication.class, args);
}
}
| [
"[email protected]"
]
| |
081281ab8b7c9029fbf255285b1fa7399188e980 | e19756b907066915284343ebfd504649abff22b2 | /SteamPunkDND/src/steampunkdnd/SteamPunkDND.java | aa83ebbd158547d31407bd1ef89c109cd1c97692 | []
| no_license | pickledcabbage/JAVA | 46009cf31398b317f2cb4f557572093a3d5e6fa6 | ed9d95041edfad64aa663585e0f33b80c7d2f072 | refs/heads/master | 2021-01-10T06:15:13.438577 | 2016-01-28T18:34:15 | 2016-01-28T18:34:15 | 50,539,509 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,647 | java | /*
* 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 steampunkdnd;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Dima
*/
public class SteamPunkDND extends JFrame {
int GAMEWIDTH = 1028;
int GAMEHEIGHT = 796;
int REFRESH_SPEED = 15;
int x = 0;
int y = 0;
private Image dbImage;
private Graphics dbg;
private JPanel charCreation;
public SteamPunkDND ()
{
addKeyListener(new AL());
addMouseListener(new Mouse());
setTitle("SteamPunkDND or something we'll figure out later");
setSize(GAMEWIDTH,GAMEHEIGHT);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
charCreation = new JPanel();
}
public Image importImage(String path)
{
try
{
return ImageIO.read(new File(path));
}
catch(IOException e)
{
e.printStackTrace();
System.exit(0);
}
return null;
}
public static void main(String [] args)
{
SteamPunkDND run = new SteamPunkDND();
run.loop();
}
public void loop()
{
try
{
while(true)
{
repaint();
Thread.sleep(REFRESH_SPEED);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public void paint (Graphics g)
{
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paintComponent(Graphics g)
{
for(int i = 0; i < 32; i++)
{
for (int a = 1; a < 25; a++)
{
g.drawImage(importImage("grass1.png"),i*32,a*32-8,null);
g.drawRect(i*32,a*32-8,32,32);
}
}
}
public class AL extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
}
public class Mouse extends MouseAdapter
{
}
}
| [
"[email protected]"
]
| |
37de80b26145bc88a7a9134597cd8895e3992452 | 13c2d3db2d49c40c74c2e6420a9cd89377f1c934 | /program_data/JavaProgramData/67/2104.java | fcb5f78ae6995c297b597e9a56f0a7c854664b80 | [
"MIT"
]
| permissive | qiuchili/ggnn_graph_classification | c2090fefe11f8bf650e734442eb96996a54dc112 | 291ff02404555511b94a4f477c6974ebd62dcf44 | refs/heads/master | 2021-10-18T14:54:26.154367 | 2018-10-21T23:34:14 | 2018-10-21T23:34:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 922 | java | package <missing>;
public class GlobalMembers
{
public static int Main()
{
int n;
n = Integer.parseInt(ConsoleInput.readToWhiteSpace(true));
double a;
double b;
a = Double.parseDouble(ConsoleInput.readToWhiteSpace(true));
b = Double.parseDouble(ConsoleInput.readToWhiteSpace(true));
double c;
c = b / a;
int i = 1;
while (i < n)
{
i++;
double m;
double n;
m = Double.parseDouble(ConsoleInput.readToWhiteSpace(true));
n = Double.parseDouble(ConsoleInput.readToWhiteSpace(true));
double d = n / m;
if ((c - d) > 0.05)
{
System.out.print("worse");
System.out.print("\n");
}
else if ((d - c) > 0.05)
{
System.out.print("better");
System.out.print("\n");
}
else
{
System.out.print("same");
System.out.print("\n");
}
}
System.in.read();
System.in.read();
System.in.read();
return 0;
}
}
| [
"[email protected]"
]
| |
905a82fea50815b5ea0c0e015a652304e55c2f79 | 4c304a7a7aa8671d7d1b9353acf488fdd5008380 | /src/main/java/com/alipay/api/response/AlipayEbppProdmodeUnionbankQueryResponse.java | df1c35c642e1adeff5a0d61da8aa882cd783c2f0 | [
"Apache-2.0"
]
| permissive | zhaorongxi/alipay-sdk-java-all | c658983d390e432c3787c76a50f4a8d00591cd5c | 6deda10cda38a25dcba3b61498fb9ea839903871 | refs/heads/master | 2021-02-15T19:39:11.858966 | 2020-02-16T10:44:38 | 2020-02-16T10:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,505 | java | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.ebpp.prodmode.unionbank.query response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class AlipayEbppProdmodeUnionbankQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 4557635665317876472L;
/**
* 银联编号
*/
@ApiField("bank_code")
private String bankCode;
/**
* 联行名称
*/
@ApiField("bank_name")
private String bankName;
/**
* 支行名称
*/
@ApiField("branch_name")
private String branchName;
/**
* 市区信息
*/
@ApiField("city")
private String city;
/**
* 省名称
*/
@ApiField("prov")
private String prov;
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getBankCode( ) {
return this.bankCode;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBankName( ) {
return this.bankName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getBranchName( ) {
return this.branchName;
}
public void setCity(String city) {
this.city = city;
}
public String getCity( ) {
return this.city;
}
public void setProv(String prov) {
this.prov = prov;
}
public String getProv( ) {
return this.prov;
}
}
| [
"[email protected]"
]
| |
c896e53071874d7d2d657f5e10002f736aac08f6 | 5f64d496f1ed6788e0e38d9dbda71a8dd2337a01 | /Silencer/src/main/java/cz/sajwy/silencer/model/Udalost.java | 4f818ba35b72c52267f9ac04a65ca00cb18ce5c6 | []
| no_license | Sajwy/SMAP | f634d52993ca48d1062c189c02d7506cb73ffed8 | c01cb791c0abe8acaccd546c0727cff1b1b615bf | refs/heads/master | 2019-08-05T02:15:28.577562 | 2018-02-02T17:06:29 | 2018-02-02T17:06:29 | 73,010,956 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 702 | java | package cz.sajwy.silencer.model;
public class Udalost {
private String nazev;
private long zacatek;
private long konec;
public Udalost(String nazev, long zacatek, long konec) {
this.nazev = nazev;
this.zacatek = zacatek;
this.konec = konec;
}
public String getNazev() {
return nazev;
}
public void setNazev(String nazev) {
this.nazev = nazev;
}
public long getZacatek() {
return zacatek;
}
public void setZacatek(long zacatek) {
this.zacatek = zacatek;
}
public long getKonec() {
return konec;
}
public void setKonec(long konec) {
this.konec = konec;
}
} | [
"[email protected]"
]
| |
f7a2d514dc55f53cb93fe1122aeb80e9b52d0d1f | a2b14a460699b0582c7a6f4a15215c72c8666979 | /JAVA_PROJECT/src/com/asthvinayak/variable/LocalVariableDemo.java | 05a5ba0818610fa50f130143d43a8bb18337aea6 | []
| no_license | manish2802/Babrak | 0dde7bcace561a8d7cca41dfc2951389d2d78a70 | cf95ad0fe0c3c6ebc1e71d495fd471499dff2008 | refs/heads/master | 2020-05-21T11:44:02.181000 | 2019-06-04T04:52:56 | 2019-06-04T04:52:56 | 186,037,043 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 338 | java | package com.asthvinayak.variable;
public class LocalVariableDemo {
void deposit(int ammount) {
}
public static void main(String[] args) {
final int i = 10;
int[] a=new int[5];
String s="manish";
System.out.println(i);
System.out.println(a);
System.out.println(s);
}
}
| [
"[email protected]"
]
| |
1302c9cb262a759743a858f2d0c54c0ae0314894 | 4130d38d1d87f0a0f32dd92597d07b62d8c97dd2 | /scanner3.java | 9417acd719c82e43b29e668b9973b8722babef6f | []
| no_license | RohitChambiyal/Javacodes | e80a73c86f6930b86a84e0fe9d18d332594c7e46 | e99307a7b0fc39e0de1f9a8cb07b02f95a2bda8b | refs/heads/master | 2020-03-26T11:39:35.113824 | 2019-09-05T21:00:40 | 2019-09-05T21:00:40 | 144,853,159 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 373 | java | import java.util.Scanner;
import java.util.regex.Pattern;
public class scanner3{
public static void main(String[] args){
Scanner s = new Scanner("hello 12hles 432fsd 23jkl jlkj23 32lkjkl23 jkl23klj");
while(s.hasNext("hel.......")){
System.out.println(s.next());
}
System.out.println("end");
}
} | [
"[email protected]"
]
| |
482aa74dfdcb08f3783e8c2374d6d94a2560afb7 | 56345887f87495c458a80373002159dbbbd7717f | /client-adapter/hbase/src/main/java/com/alibaba/otter/canal/client/adapter/hbase/HbaseAdapter.java | e97035ed143be764124ed94ff93fcd5f4087e425 | [
"Apache-2.0"
]
| permissive | cainiao22/canal-bigdata | 724199c61632e98b43797d4fd276abcba7e426fb | a88362535faeda5f846a8f147d341f8d22ffd2e4 | refs/heads/master | 2022-12-26T16:59:50.256698 | 2018-12-05T07:27:17 | 2018-12-05T07:27:17 | 214,317,447 | 1 | 0 | Apache-2.0 | 2022-12-14T20:35:10 | 2019-10-11T01:30:07 | Java | UTF-8 | Java | false | false | 7,192 | java | package com.alibaba.otter.canal.client.adapter.hbase;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfigLoader;
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseEtlService;
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseSyncService;
import com.alibaba.otter.canal.client.adapter.hbase.support.HbaseTemplate;
import com.alibaba.otter.canal.client.adapter.support.*;
/**
* HBase外部适配器
*
* @author machengyuan 2018-8-21 下午8:45:38
* @version 1.0.0
*/
@SPI("hbase")
public class HbaseAdapter implements OuterAdapter {
private static Logger logger = LoggerFactory.getLogger(HbaseAdapter.class);
private static volatile Map<String, MappingConfig> hbaseMapping = null; // 文件名对应配置
private static volatile Map<String, MappingConfig> mappingConfigCache = null; // 库名-表名对应配置
private Connection conn;
private HbaseSyncService hbaseSyncService;
private HbaseTemplate hbaseTemplate;
@Override
public void init(OuterAdapterConfig configuration) {
try {
if (mappingConfigCache == null) {
synchronized (MappingConfig.class) {
if (mappingConfigCache == null) {
hbaseMapping = MappingConfigLoader.load();
mappingConfigCache = new HashMap<>();
for (MappingConfig mappingConfig : hbaseMapping.values()) {
mappingConfigCache.put(StringUtils.trimToEmpty(mappingConfig.getHbaseMapping().getDestination())
+ "." + mappingConfig.getHbaseMapping().getDatabase() + "."
+ mappingConfig.getHbaseMapping().getTable(),
mappingConfig);
}
}
}
}
Map<String, String> propertites = configuration.getProperties();
Configuration hbaseConfig = HBaseConfiguration.create();
propertites.forEach(hbaseConfig::set);
conn = ConnectionFactory.createConnection(hbaseConfig);
hbaseTemplate = new HbaseTemplate(conn);
hbaseSyncService = new HbaseSyncService(hbaseTemplate);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void sync(Dml dml) {
if (dml == null) {
return;
}
String destination = StringUtils.trimToEmpty(dml.getDestination());
String database = dml.getDatabase();
String table = dml.getTable();
MappingConfig config = mappingConfigCache.get(destination + "." + database + "." + table);
hbaseSyncService.sync(config, dml);
}
@Override
public EtlResult etl(String task, List<String> params) {
EtlResult etlResult = new EtlResult();
MappingConfig config = hbaseMapping.get(task);
if (config != null) {
DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
if (dataSource != null) {
return HbaseEtlService.importData(dataSource, hbaseTemplate, config, params);
} else {
etlResult.setSucceeded(false);
etlResult.setErrorMessage("DataSource not found");
return etlResult;
}
} else {
DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(task);
if (dataSource != null) {
StringBuilder resultMsg = new StringBuilder();
boolean resSucc = true;
// ds不为空说明传入的是datasourceKey
for (MappingConfig configTmp : hbaseMapping.values()) {
// 取所有的datasourceKey为task的配置
if (configTmp.getDataSourceKey().equals(task)) {
EtlResult etlRes = HbaseEtlService.importData(dataSource, hbaseTemplate, configTmp, params);
if (!etlRes.getSucceeded()) {
resSucc = false;
resultMsg.append(etlRes.getErrorMessage()).append("\n");
} else {
resultMsg.append(etlRes.getResultMessage()).append("\n");
}
}
}
if (resultMsg.length() > 0) {
etlResult.setSucceeded(resSucc);
if (resSucc) {
etlResult.setResultMessage(resultMsg.toString());
} else {
etlResult.setErrorMessage(resultMsg.toString());
}
return etlResult;
}
}
}
etlResult.setSucceeded(false);
etlResult.setErrorMessage("Task not found");
return etlResult;
}
@Override
public Map<String, Object> count(String task) {
MappingConfig config = hbaseMapping.get(task);
String hbaseTable = config.getHbaseMapping().getHbaseTable();
long rowCount = 0L;
try {
HTable table = (HTable) conn.getTable(TableName.valueOf(hbaseTable));
Scan scan = new Scan();
scan.setFilter(new FirstKeyOnlyFilter());
ResultScanner resultScanner = table.getScanner(scan);
for (Result result : resultScanner) {
rowCount += result.size();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
Map<String, Object> res = new LinkedHashMap<>();
res.put("hbaseTable", hbaseTable);
res.put("count", rowCount);
return res;
}
@Override
public void destroy() {
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public String getDestination(String task) {
MappingConfig config = hbaseMapping.get(task);
if (config != null && config.getHbaseMapping() != null) {
return config.getHbaseMapping().getDestination();
}
return null;
}
}
| [
"[email protected]"
]
| |
f7e790168a0018d74640de0bc31e974d86bf2792 | f273c0e324697e8af9ea25a21c785595f3700a27 | /first/src/com/koreait/first/control/Switch.java | fbbe09ad1ecd7a58e495ddeac637c0ba911851fe | []
| no_license | JaeJin2044/2020_classA_JavaDev_Java | 8775e780d67ad3cde01cf5a5c389ec7e600606a7 | 25d3a3d9cfc49dcda6357a83ea7f1d52742846b8 | refs/heads/main | 2023-02-04T09:32:08.419355 | 2020-12-12T13:15:56 | 2020-12-12T13:15:56 | 315,940,220 | 1 | 0 | null | 2020-11-25T12:58:38 | 2020-11-25T12:58:38 | null | UTF-8 | Java | false | false | 1,205 | java | package com.koreait.first.control;
public class Switch {
public static void main(String[] args) {
//
int num = 4;
//switch 문은 break만나기 전까지 모든 것을 실행한다.
switch(num) {
case 1:
System.out.println("1입니다");
break;
case 2:
System.out.println("2입니다");
break;
case 3:
System.out.println("3입니다");
break;
case 4:
System.out.println("4입니다");
break;
case 5:
System.out.println("5입니다");
break;
default:
System.out.println("1~5아닙니다.");
}
System.out.println("-------------------------------");
// switch문은 문자열과 궁합이 좋다 .
String season = "겨울";
switch(season) {
case "봄":
System.out.println("꽃이 피었습니다");
break;
case "여름":
System.out.println("물놀이 가요 ");
break;
case "가을":
System.out.println("단풍구경 가요 ");
break;
case "겨울":
System.out.println("눈싸움 해요 ~~~");
break;
default:
System.out.println("존재하지 않는 계절이요!!");
}
}
}
| [
"[email protected]"
]
| |
01e48c16c4a4a44d4d0ee9794cb6fd23172f637c | 22d05ee28e67c7437e74a28022ab31c296cad9a4 | /SM.DGR.Biblioteca_1/src/sm/dgr/graficos/MiRectanguloRedondeado2D.java | 37a2f26cec99bfe5fecaab087840d741d51f8105 | []
| no_license | danigrz/MultimediaAPPJava | d7169a67478352e47adba82dcc5a43b567f3d2e7 | 0972506b3fb82ac5d6d33f8e3f66d8b833c7fcd1 | refs/heads/master | 2021-01-10T12:51:50.136971 | 2016-02-19T00:44:08 | 2016-02-19T00:44:08 | 52,397,077 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,540 | java | /*
* 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 sm.dgr.graficos;
import com.sun.javafx.geom.PathIterator;
import com.sun.javafx.geom.RectangularShape;
import com.sun.javafx.geom.transform.BaseTransform;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import static java.awt.Color.red;
import java.awt.Composite;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
/**
* @author Daniel Guerra Ruiz
* @version 16/6/1015
* Clase MiRectanguloRedondeado2D que extiende de DGRShape, lo cual tiene los atributos de la clase DGRShape
* @see DGRShape
*/
public class MiRectanguloRedondeado2D extends DGRShape{
boolean relleno;
boolean composite_bool;
boolean renderinghints;
boolean gradiente;
boolean angulo;
float gradual = 1;
int trazo;
int tipotrazo;
Color colorUno;
Color colorDos;
RenderingHints render = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints norender = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F);
AlphaComposite nocomposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1F);
GradientPaint verticalGradient;
GradientPaint gradient;
RoundRectangle2D.Double RectanguloRedondeado = new RoundRectangle2D.Double();
final static float dash1[] = {10.0f};
final static BasicStroke dashed = new BasicStroke(1.0f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,10.0f,dash1, 0.0f);
BufferedImage bf;
/**
*Constructor MiRectangulo2D
*@param x Double
*@param y Double
*@param ancho Double
*@param alto Double
*@param color Color
*@param relleno Boolean
*@param c Boolean, contiene el valor booleano de composite/transparencia para el objeto
*@param st Stroke
*@param r Boolean del alisado de la imagen (RenderingHints)
*@param grad Boolean del gradiente del objeto
*@param bff BufferedImage que se usara como alisado para este objeto
*/
public MiRectanguloRedondeado2D(double x, double y, double ancho, double alto, Color color,boolean relleno, boolean c, int st,int tipotrazo ,boolean r,boolean grad,boolean ang,Color c1, Color c2,float gradual, BufferedImage bff){
this.setColor(color);
this.setCompositeBoolean(c);
this.setGradiente(grad);
this.setAngulo(ang);
this.setColorUno(c1);
this.setColorDos(c2);
this.setRelleno(relleno);
this.gradual = gradual;
this.tipotrazo = tipotrazo;
this.setRenderinghints(r);
this.trazo = st;
//this.setStroke(st);
this.setBufferedImage(bff);
RectanguloRedondeado = new RoundRectangle2D.Double(x, y, ancho, alto, 10, 10);
RectanguloRedondeado.setFrame(x, y, ancho, alto);
}
/**
*Constructor sin parámetros
*/
public MiRectanguloRedondeado2D(){
}
/**
*Metodo setAtributos
*Asigna las propiedades para modificar el objeto
*@param color Color
*@param relleno Boolean
*@param c Boolean, contiene el valor booleano de composite/transparencia para el objeto
*@param st Stroke
*@param r Boolean del alisado de la imagen (RenderingHints)
*@param grad Boolean del gradiente del objeto
*@param img BufferedImage que se usara como alisado para este objeto
*/
public void setAtributos(Color color,boolean relleno, boolean c, int st,int tipotrazo, boolean r,boolean grad,boolean ang,Color c1, Color c2,float gradual,BufferedImage img){
this.setColor(color);
this.setCompositeBoolean(c);
this.setRelleno(relleno);
this.setAngulo(ang);
this.setRenderinghints(r);
//this.setStroke(st);
this.setGradiente(grad);
this.gradual = gradual;
this.trazo = st;
this.tipotrazo = tipotrazo;
this.setColorUno(c1);
this.setColorDos(c2);
this.setBufferedImage(img);
}
/**
*Metodo getRectanguloRedondeado
*Devuelve el objeto RoundRectangle2D.Double
*@return RectanguloRedondeado
*/
public RoundRectangle2D.Double getRectanguloRedondeado() {
return RectanguloRedondeado;
}
/**
*Metodo setRectanguloRedondeado
*Asigna valores al rectangulo redondeado con un objeto RoundRectangle2D.Double
*@param RectanguloRedondeado RoundRectangle2D.Double
*/
public void setRectanguloRedondeado(RoundRectangle2D.Double RectanguloRedondeado) {
this.RectanguloRedondeado = RectanguloRedondeado;
}
/**
*Metodo getBufferedImage
*Devuelve el objeto BufferedImage
*@return BufferedImage
*/
public BufferedImage getBufferedImage() {
return bf;
}
/**
*Metodo setBufferedImage
*Asigna un BufferedImage que se usará como textura del objeto
*@param buf BufferedImage
*/
public void setBufferedImage(BufferedImage buf) {
this.bf = buf;
if(bf!=null){
this.setBuffImg(bf);
}
}
/**
*Metodo isGradiente
*Devuelve valor del booleano gradiente
*@return boolean
*/
public boolean isGradiente() {
return gradiente;
}
/**
*Metodo setGradiente
*Asigna el gradiente al objeto y se pintará el gradiente
*@param gradiente Boolean
*/
public void setGradiente(boolean gradiente) {
this.gradiente = gradiente;
if(gradiente){
this.setGradient(gradient);
}
}
/**
*Metodo isRenderinghints
*Devuelve booleano de si tiene alisado ( renderinghints)
*@return boolean
*/
public boolean isRenderinghints() {
return renderinghints;
}
/**
*Metodo setRenderingHints
*Asigna valor al booleano renderinghints, y se pintará con alisado
*@param renderinghints Boolean
*/
public void setRenderinghints(boolean renderinghints) {
this.renderinghints = renderinghints;
if(renderinghints){
this.setRender(render);
}
}
/**
*Metodo isCompositeBoolean
*Devuelve el valor del booleano composite_bool
*@return boolean
*/
public boolean isCompositeBoolean(){
return composite_bool;
}
/**
*Metodo isRelleno
*Devuelve valor booleano de relleno
*@return boolean
*/
public boolean isRelleno() {
return relleno;
}
/**
*Metodo setRelleno
*Asigna valor booleano a relleno, si es asi se rellena la figura
*@param relleno Boolean
*/
public void setRelleno(boolean relleno) {
this.relleno = relleno;
}
/**
*Metodo getTransparencia
*Devuelve AlphaComposite/transparencia del objeto
*@return AlphaComposite
*/
public AlphaComposite getTransparencia(){
return composite;
}
/**
*Metodo setCompositeBoolean
*Asigna la transparencia al objeto, y se añade mediante el objeto composite
*@param c boolean
*/
public void setCompositeBoolean(boolean c) {
this.composite_bool = c;
if(composite_bool){
this.setComposite(composite);
}
}
/**
*Metodo draw
*Se encarga de pintar el objeto con todas sus propiedades: color, relleno,
*alisado, transparencia, grosor, gradiente y textura
*@param g2d Graphics2D
*/
public void draw(Graphics2D g2d){
//Establece el trazo
//g2d.setStroke(this.getMiStroke());
switch(tipotrazo){
case 1:
BasicStroke basico = new BasicStroke(trazo);
g2d.setStroke(basico);
break;
case 2:
float dash1[] = {2.0f};
BasicStroke dashed = new BasicStroke(trazo,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2d.setStroke(dashed);
break;
case 3:
float dash2[] = {10.0f};
BasicStroke dashed2 = new BasicStroke(trazo,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash2, 0.0f);
g2d.setStroke(dashed2);
break;
default:
BasicStroke defecto = new BasicStroke(trazo);
g2d.setStroke(defecto);
break;
}
// g2d.setStroke(new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,5.0f, 1, 0.0f));
//Establece renderinghints / alisado
if(renderinghints){
g2d.setRenderingHints(this.getRender());
}else{
g2d.setRenderingHints(norender);
}
//Establece gradiente/textura/color
if(gradiente){
if(angulo){
if(colorUno!=null && colorDos!=null)
gradient = new GradientPaint(0,0,colorUno,400, 0,colorDos);
else
gradient = new GradientPaint(0,0,Color.RED,400, 0,Color.CYAN);
this.setGradient(gradient);
}else{
if(colorUno!=null && colorDos!=null)
gradient = new GradientPaint(0,0,colorUno,0, 400,colorDos);
else
gradient = new GradientPaint(0,0,Color.RED,0,400,Color.CYAN);
this.setGradient(gradient);
}
g2d.setPaint(this.getGradient());
}else if(bf!=null){
Rectangle r = new Rectangle(0, 0, 20, 20);
g2d.setPaint(new TexturePaint(this.getBuffImg(), r));
}else{
g2d.setColor(this.getColor());
}
if(relleno){
g2d.fill(RectanguloRedondeado);
}
//Establece transparencia
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,gradual));
//Pinta la figura
g2d.draw(RectanguloRedondeado);
}
/**
*Metodo contains
*Devuelve si el Point2D p contiene al objeto
*@return Boolean
*/
public boolean contains(Point2D p) {
return RectanguloRedondeado.contains(p);
}
/* /** Devuelve el color 1 del gradiente
* @return colorUno
*/
public Color getColorUno() {
return colorUno;
}
/**
* Asigna el color 1 al gradiente
* @param colorUno
*/
public void setColorUno(Color colorUno) {
this.colorUno = colorUno;
}
/**
* Devuelve el color 2 del gradiente
* @return
*/
public Color getColorDos() {
return colorDos;
}
/**
* Asigna el color 2 al gradiente
* @param colorDos
*/
public void setColorDos(Color colorDos) {
this.colorDos = colorDos;
}
/**
* Devuelve el angulo del gradiente
* @return
*/
public boolean isAngulo() {
return angulo;
}
/**
* Asigna angulo al gradiente
* @param angulo Boolean
*/
public void setAngulo(boolean angulo) {
this.angulo = angulo;
}
/*
*@deprecated
*/
@Override
public com.sun.javafx.geom.Shape impl_configShape() {
return null; //To change body of generated methods, choose Tools | Templates.
}
}
| [
"[email protected]"
]
| |
418ea0429a1287952dec64fdb689c10bf6e6ffab | d1ebd8b5506d4ef5f2456701e2a77b0f1a704d2f | /src/test/java/com/k2data/demo/rest/unit/web/service/server/UnitWebServiceTest.java | 358cd241a2ede43a1e5cf499cbc9a47d959a37d1 | []
| no_license | guanxine/rest-unit-test | 2a1c5d93f8041c9ea69a195d048ea6d19458be3f | bc180d2c612f7cacec4da8d5d3a7f8fb86a5e35f | refs/heads/master | 2020-04-07T11:40:50.421997 | 2018-11-23T07:11:26 | 2018-11-23T07:11:26 | 158,336,278 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,819 | java | package com.k2data.demo.rest.unit.web.service.server;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.SocketUtils;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Created by guanxine on 18-11-19.
* 通过 Spring 启动一个 cxf 内嵌的服务
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:cxf-test.xml"})
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"})
public class UnitWebServiceTest {
private String baseUrl;
private RequestSpecification spec;
@Autowired
MockHttpSession session;
@Autowired
MockHttpServletRequest request;
@BeforeClass
public static void configure() {
// fix address already in use in multiple test cases
System.setProperty("servicePort", String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@Before
public void setUp() {
this.baseUrl = "http://localhost:" + System.getProperty("servicePort") + "/rest-unit-test";
spec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setBaseUri(baseUrl)
.addFilter(new ResponseLoggingFilter())//log request and response for better debugging. You can also only log if a requests fails.
.addFilter(new RequestLoggingFilter())
.build();
}
@Test
public void create() {
given().spec(spec)
.contentType(ContentType.JSON)
.body("{\n" +
" \"id\": 1,\n" +
" \"unit\": \"a rest unit test\"\n" +
"}")
.when().post("unit").then()//res
.statusCode(200)
.body("code", equalTo(0))
.body("body.id", equalTo(1));
}
} | [
"[email protected]"
]
| |
423ddab21601477ceb2ed7423f0a5ec1232d089b | ab7081b3fae970e5b0ca460abdf4d8b550791336 | /src/main/java/com/yem/entity/YemPermission.java | 1e4801dd21b67f4887925ddbc2013f84a261cac1 | []
| no_license | guchuang/yem-model | 280c8eab6a03afee60d642ac2149ee53e68156be | ddee79e0289012c264a643c5de38d30ab7e65e5e | refs/heads/master | 2022-06-22T16:09:31.007451 | 2019-08-30T09:40:22 | 2019-08-30T09:40:22 | 197,723,543 | 0 | 0 | null | 2022-06-17T02:17:23 | 2019-07-19T07:24:24 | Java | UTF-8 | Java | false | false | 690 | java | package com.yem.entity;
import java.util.Date;
import com.yem.common.IModel;
import lombok.Data;
@Data
public class YemPermission implements IModel {
/**
* serialVersionUID:TODO(用一句话描述这个变量表示什么).
* @since JDK 1.8
*/
private static final long serialVersionUID = 5713267162702034342L;
private String permissionId;
private Long permissionCode;
private String permissionName;
private String method;
private String zuulPrefix;
private String serverPrefix;
private String uri;
private String valid;
private Date createTime;
private Long createBy;
private Date updateTime;
private Long updateBy;
} | [
"[email protected]"
]
| |
16620fffe959714c01f01120e060d61fc92da9ba | f95156e92ba6e16f2e1477a9bee6185aad1f5a6f | /stackImplentation/src/OverFlowException.java | 9a532788a111648d7beee8b390919e3ee55f8af1 | []
| no_license | shoaib30/Java-Lab | 1098a63ceeca4421e3fc66801b7f8ffacd86e082 | 073fce38a256f73eea80a9899a954040145b1e80 | refs/heads/master | 2021-01-21T13:17:33.024092 | 2018-07-31T17:25:49 | 2018-07-31T17:25:49 | 50,035,339 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 157 | java |
public class OverFlowException extends Exception{
String desc;
OverFlowException(String s){
desc = s;
}
public String toString(){
return desc;
}
}
| [
"[email protected]"
]
| |
52974d9e763ce6faf7017fffa7d3685ef76bec2a | 47c3ac0da2f812082e3ad37a167809b7543e462e | /basico/src/main/java/poo_ex2/Aplicacao.java | 3e21928a111c34ca24781a658c58841fbc18228b | []
| no_license | mariacmaruch/java-dio | e86412fda123fbe5832b0547452a9d101a068042 | b1357a4d30d222f09533db695f253c160cf9ff54 | refs/heads/main | 2023-06-15T17:06:14.520078 | 2021-07-15T00:45:57 | 2021-07-15T00:45:57 | 375,528,080 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 179 | java | package poo_ex2;
public class Aplicacao {
public static void main (String[] args){
Carro c1 = new Carro("Ford","Ecosport", 2019 );
c1.imprimir();
}
}
| [
"[email protected]"
]
| |
6649bb294e31e9270aa3bf49dac9a37cf3c2b7ad | 1520cf984747a1dabfda31c1bdcb79f641882314 | /src/main/java/com/premium/studfarm/domain/Authority.java | 2d22fa800e0f707f4cf96b12533c5c9d44066e4d | []
| no_license | Koen78/premiumStableManagement | 368b0321d564d5cf9b0d75789b9a49c5cbcedf52 | caa9b0ac994feb2b0eb7e70dcf14c19ee80a3404 | refs/heads/master | 2020-03-14T14:00:56.153707 | 2018-05-07T19:46:06 | 2018-05-07T19:46:06 | 131,644,642 | 0 | 0 | null | 2018-05-07T19:48:27 | 2018-04-30T20:43:33 | Java | UTF-8 | Java | false | false | 1,458 | java | package com.premium.studfarm.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* An authority (a security role) used by Spring Security.
*/
@Entity
@Table(name = "jhi_authority")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Authority authority = (Authority) o;
return !(name != null ? !name.equals(authority.name) : authority.name != null);
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
}
| [
"[email protected]"
]
| |
7686b7556f73f7de3f935157046beaa7afa3c2b2 | 7d739ef024228c320fff6f6783e7def38cf75556 | /src/co/edu/unicundi/carrerarelevoshilos/Principal.java | 6d7bb4a46a98f9453b1d3e9c872645f363225a10 | []
| no_license | 1Alejandra3/CarreraRelevosHilos | de8205d7c336a2e3be00c6ba11f315573d5e26e5 | 4d7d4f4cfa1d05c042e87465bd419ce54f19148a | refs/heads/master | 2023-04-09T08:00:48.049223 | 2021-04-16T04:54:15 | 2021-04-16T04:54:15 | 358,472,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,347 | java |
package co.edu.unicundi.carrerarelevoshilos;
/**
* class main Se crean los hilos en cada uno de los grupos.
* @author Alejandra Guzman
* @author James Alzate
*
*/
public class Principal {
/**
* Metodo que crea el objeto de las clases e inicia los hilos
*/
public void inicio(){
Equipo equipo1 = new Equipo("Equipo 1",0,100);
Corredor c1e1= new Corredor(0,33,equipo1);
Corredor c2e1= new Corredor(33,66,equipo1);
Corredor c3e1 = new Corredor(66,99,equipo1);
Equipo equipo2 = new Equipo("Equipo 2",0,100);
Corredor c1e2 = new Corredor(0,33,equipo2);
Corredor c2e2 = new Corredor(33,66,equipo2);
Corredor c3e2 = new Corredor(66,99,equipo2);
Equipo equipo3 = new Equipo("Equipo 3",0,100);
Corredor c1e3 = new Corredor(0,33,equipo3);
Corredor c2e3 = new Corredor(33,66,equipo3);
Corredor c3e3 = new Corredor(66,99,equipo3);
//Se le da inicio al hilo a cada uno de los hilos.
c1e1.start();
c2e1.start();
c3e1.start();
c1e2.start();
c2e2.start();
c3e2.start();
c1e3.start();
c2e3.start();
c3e3.start();
}
public static void main(String[] args) {
Principal p = new Principal();
p.inicio();
}
}
| [
"[email protected]"
]
| |
324f1cd53132c6e7748292437dbc16b90263cbc5 | 98ad2473de8fd9f55abee8e1fb48dc1c9672301f | /src/main/java/ru/homer/leaderboard/service/impl/JiraUserService.java | f0ca0d8e008cd7eb77609f825ed940a40cd8cc24 | []
| no_license | rnemykin/homer-leader-board | f8b8a16cc7bbab95d8dac50854d34c108798f7dc | bf611c31b47c7c8510ba367caefec4329e462a87 | refs/heads/master | 2020-12-02T08:07:22.443740 | 2017-08-31T08:59:52 | 2017-08-31T08:59:52 | 96,771,082 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,045 | java | package ru.homer.leaderboard.service.impl;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.homer.leaderboard.config.JiraClientConfiguration;
import ru.homer.leaderboard.entity.IssueDto;
import ru.homer.leaderboard.entity.IssueStatistic;
import ru.homer.leaderboard.entity.UserDto;
import ru.homer.leaderboard.enums.Issue;
import ru.homer.leaderboard.enums.IssueType;
import ru.homer.leaderboard.mapper.Mapper;
import ru.homer.leaderboard.service.IssueService;
import ru.homer.leaderboard.service.UserService;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vadmurzakov on 23.07.17.
*/
@Service
public class JiraUserService implements UserService {
private final IssueService jiraIssueService;
private final Mapper mapper;
private JiraRestClient jiraRestClient;
@Autowired
public JiraUserService(JiraClientConfiguration jiraClientConfiguration, IssueService jiraIssueService, Mapper mapper) {
this.jiraIssueService = jiraIssueService;
this.mapper = mapper;
this.jiraRestClient = jiraClientConfiguration.jiraRestClient();
}
@Override
public UserDto getUserByUsername(String username) {
return mapper.mapUserDto(jiraRestClient.getUserClient().getUser(username).claim());
}
@Override
public UserDto getStatisticByUsername(String username, int countMonth) {
UserDto userDto = getUserByUsername(username);
List<IssueDto> issues = jiraIssueService.getAllIssuesForLastMonthByUser(username, countMonth);
List<IssueStatistic> issueStatistics = new ArrayList<>();
issueStatistics.add(getStatisticByIssueType(Issue.SIMPLE_BUG, issues));
issueStatistics.add(getStatisticByIssueType(Issue.PRODUCT_BUG, issues));
issueStatistics.add(new IssueStatistic(
Issue.BUGS,
issueStatistics.get(0).getCount() + issueStatistics.get(1).getCount(),
issueStatistics.get(0).getTime() + issueStatistics.get(1).getTime()
));
issueStatistics.add(getStatisticByIssueType(Issue.ANALYTICS, issues));
issueStatistics.add(getStatisticByIssueType(Issue.PATCH, issues));
issueStatistics.add(getStatisticForDev(issueStatistics, issues));
userDto.setIssueStatistics(issueStatistics);
userDto.setIssueDtos(issues);
return userDto;
}
/**
* Получить статистику в зависимости от типа задачи
*
* @param issue тип бага
* @param issueDtos список задач
* @return IssueStatistic
*/
private IssueStatistic getStatisticByIssueType(Issue issue, List<IssueDto> issueDtos) {
long count = 0;
double time = 0;
List<Long> idsIssueType = IssueType.getIdsByType(issue);
for (IssueDto issueDto : issueDtos) {
if (idsIssueType.contains(issueDto.getIssueType().getId()) && issueDto.getWorkTime() > 10) {
count++;
time += issueDto.getWorkTime();
}
}
return new IssueStatistic(issue, count, time);
}
private IssueStatistic getStatisticForDev(List<IssueStatistic> issueStatistic, List<IssueDto> issueDtos) {
long count = 0;
double time = 0;
for (IssueDto issueDto : issueDtos) {
if (issueDto.getWorkTime() > 10) {
count ++;
time += issueDto.getWorkTime();
}
}
long countOtherIssue = 0;
double timeOtherIssue = 0;
for (IssueStatistic issue : issueStatistic) {
if (issue.getIssue() != Issue.BUGS) {
countOtherIssue += issue.getCount();
timeOtherIssue += issue.getTime();
}
}
return new IssueStatistic(
Issue.DEV,
count - countOtherIssue,
time - timeOtherIssue);
}
}
| [
"[email protected]"
]
| |
0228d87956a2c2b9f8b2c6b7cfc541f6ff7b0ada | 168c045fa492e9ea44ca3fed7ae4ae4407b9ae1e | /最新作业/UIBestPractice/app/src/main/java/com/example/feng/uibestpractice/MsgAdapter.java | 5f100eb7e1c472489446d9cbaedddbb58cc8731f | []
| no_license | FZUTonyHao/AndroidAPP | a0d38765579e4b04d072ebc7ce471064e8000d3c | 1ff6557e4704ed0bff44a9fb54d2ee258d2e7828 | refs/heads/master | 2020-04-14T12:20:19.634199 | 2019-01-03T16:05:49 | 2019-01-03T16:05:49 | 163,837,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,000 | java | package com.example.feng.uibestpractice;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
private List<Msg> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
public ViewHolder(View view) {
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rightMsg = (TextView) view.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List<Msg> msgList) {
mMsgList = msgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.msg_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVED) {
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
} else if (msg.getType() == Msg.TYPE_SENT) {
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rightMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
| [
"[email protected]"
]
| |
a3e337342ccc53caa019dd046086fe6acc6df099 | 359fc29554ebb6a7fe73a21a1188b9227bac5809 | /src/br/com/caelum/erp/dao/JPAUtil.java | 6868a3f92a2fc55e57d6b2c0b73cd348567c994e | []
| no_license | osaias/erp | cdbe933431dc8688c888a38be398cae7e47bd9b6 | 1f04ce488e3345c8e7d2133a04fb80f4a8ad0008 | refs/heads/master | 2020-03-31T13:38:49.119492 | 2018-10-09T14:17:31 | 2018-10-09T14:17:31 | 152,263,485 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 175 | java | package br.com.caelum.erp.dao;
import javax.persistence.EntityManager;
public class JPAUtil {
EntityManager em;
EntityManager getEntityManager(){
return em;
}
}
| [
"[email protected]"
]
| |
9ec195996f15e96054e0fb76b5ccfc48d06ae554 | 0bf7578e1cc8503c61cc76d370b903cfec8ef30a | /commons/src/main/java/com/joycity/joyclub/commons/modal/base/BooleanResult.java | 19b37e1428360e943f2c372e34f86412442454db | []
| no_license | FreeTimeWork/JoyClubBackPriLab | b7358106e96358ff8ed8455ccf0affb53aae36d4 | edf4a6773a18725271bf80e0cc7fc0fd1320ded7 | refs/heads/master | 2021-09-10T16:25:51.609130 | 2018-03-15T08:35:07 | 2018-03-15T08:35:07 | 333,125,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 497 | java | package com.joycity.joyclub.commons.modal.base;
/**
* Created by fangchen.chai on 2017/7/24
* 验证等返回Boolean类型结果
*/
public class BooleanResult {
private Boolean resultFlag;
public Boolean getResultFlag() {
return resultFlag;
}
public void setResultFlag(Boolean resultFlag) {
this.resultFlag = resultFlag;
}
public BooleanResult() {
}
public BooleanResult(Boolean resultFlag) {
this.resultFlag = resultFlag;
}
}
| [
"[email protected]"
]
| |
8a6cd5b0855de931917af3e0c83f20c8d23f4da9 | ddc15ff37cf1d88b1580aec11ea07a7244817218 | /bubbleSort/src/bubbleSort/BubbleSort2.java | eb8cfd4e112da1f7f0184b8bfe871130f74d2b0a | []
| no_license | LemonDeng/arithmetic | 158532347a3711e1d73521ac969bdfb456ed9068 | 8424ed7f1ac775d649113c3bdce22e7ca1cf2e7d | refs/heads/master | 2023-07-15T10:01:57.939168 | 2021-08-26T03:11:25 | 2021-08-26T03:11:25 | 385,900,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 964 | java | package bubbleSort;
import java.util.Arrays;
/**
* @ClassName:bubbleSort2
* @Description: TUDO
* @Author: Deng Zhi Li
* @Date: 2021/7/14 16:05
*/
public class BubbleSort2 {
public static void bubbleSort2(int[] arr)
{
boolean swapped = true;
for (int i = 0;i < arr.length - 1;i++)
{
if (!swapped) break;
swapped = false;
for (int j = 0;j < arr.length - 1 - i;j++ )
{
if (arr[j] > arr[j+1])
{
swap(arr,j,j+1);
swapped = true;
}
}
}
}
// 交换元素
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int [] arr = new int[]{1,2,3,4,5};
bubbleSort2(arr);
System.out.println(Arrays.toString(arr));
}
}
| [
"[email protected]"
]
| |
e660c688d586ae4bd79eda8dd3a45ea075e82c69 | ea282cc70de0f867f671a71fc515cc7641d3d3fe | /src/xfuzzy/lang/AggregateMemFunc.java | 7c4749e209c56fc6bb966d9ee5e24f89b175d287 | [
"MIT"
]
| permissive | dayse/gesplan | aff1cc1e38ec22231099063592648674d77b575d | 419ee1dcad2fa96550c99032928e9ea30e7da7cd | refs/heads/master | 2021-01-23T07:03:23.606901 | 2014-08-12T14:38:26 | 2014-08-12T14:38:26 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 6,544 | java | //--------------------------------------------------------------------------------//
// COPYRIGHT NOTICE //
//--------------------------------------------------------------------------------//
// Copyright (c) 2012, Instituto de Microelectronica de Sevilla (IMSE-CNM) //
// //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions are met: //
// //
// * Redistributions of source code must retain the above copyright notice, //
// this list of conditions and the following disclaimer. //
// //
// * Redistributions in binary form must reproduce the above copyright //
// notice, this list of conditions and the following disclaimer in the //
// documentation and/or other materials provided with the distribution. //
// //
// * Neither the name of the IMSE-CNM nor the names of its contributors may //
// be used to endorse or promote products derived from this software //
// without specific prior written permission. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE //
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
//--------------------------------------------------------------------------------//
package xfuzzy.lang;
/**
* Función de pertenencia formada por la agregación de un conjunto
* de conclusiones
*
* @author Francisco José Moreno Velo
*
*/
public class AggregateMemFunc implements MemFunc {
//----------------------------------------------------------------------------//
// MIEMBROS PÚBLICOS //
//----------------------------------------------------------------------------//
/**
* Lista de conclusiones a agregar
*/
public ImpliedMemFunc conc[];
/**
* Valor de las entradas, para las funciones de tipo paramétrico
* (Takagi-Sugeno)
*/
public double input[];
//----------------------------------------------------------------------------//
// MIEMBROS PRIVADOS //
//----------------------------------------------------------------------------//
/**
* Universo de discurso de la función de pertenencia
*/
private Universe u;
/**
* Base de reglas de la que procede la función de pertenencia agregada
*/
private Rulebase mod;
//----------------------------------------------------------------------------//
// CONSTRUCTOR //
//----------------------------------------------------------------------------//
/**
* Constructor
* @param universe Universo de discurso de la función de pertenencia
* @param mod Base de reglas de la que procede la función de pertenencia
*/
public AggregateMemFunc(Universe universe, Rulebase mod) {
this.u = universe;
this.mod = mod;
this.conc = new ImpliedMemFunc[0];
}
//----------------------------------------------------------------------------//
// MÉTODOS PÚBLICOS //
//----------------------------------------------------------------------------//
/**
* Añade una nueva función a la agregación
*/
public void add(ImpliedMemFunc imf) {
ImpliedMemFunc amf[] = new ImpliedMemFunc[this.conc.length+1];
System.arraycopy(this.conc,0,amf,0,this.conc.length);
amf[this.conc.length] = imf;
this.conc = amf;
}
/**
* Calcula el grado de pertenencia de la agregación
*/
public double compute(double x) {
double degree = this.conc[0].compute(x);
for(int i=1; i<this.conc.length; i++)
degree = this.mod.operation.also.compute(degree, this.conc[i].compute(x));
return degree;
}
/**
* Aplica el método de concreción a la agregación
*/
public double defuzzify() {
return this.mod.operation.defuz.compute(this);
}
/**
* Obtiene el mínimo del universo de discurso de la función
*/
public double min() {
return this.u.min();
}
/**
* Obtiene el máximo del universo de discurso de la función
*/
public double max() {
return this.u.max();
}
/**
* Obtiene la división del universo de discurso de la función
*/
public double step() {
return this.u.step();
}
/**
* Analiza si se trata de una agregacion de singularidades
*/
public boolean isDiscrete() {
for(int i=0; i<conc.length; i++)
if( !(conc[i].getMF() instanceof pkg.xfl.mfunc.singleton) ) return false;
return true;
}
/**
* Obtiene los valores de una agregación de singularidades
*/
public double[][] getDiscreteValues() {
double[][] value = new double[conc.length][2];
for(int i=0; i<conc.length; i++) {
value[i][0] = conc[i].getParam()[0];
value[i][1] = conc[i].getDegree();
}
return value;
}
/**
* Obtiene el grado de activación de una singularidad
*/
public double getActivationDegree(double label) {
double degree = 0;
for(int i=0; i<conc.length; i++)
if(conc[i].center() == label)
if(degree<conc[i].getDegree()) degree = conc[i].getDegree();
return degree;
}
}
| [
"[email protected]"
]
| |
cdcdad81a7b1d5b0422a15167bdc79a5a32d986e | 3ecb9c533ec00f02176a5e1f51cd691b4db25adc | /taotao-common/src/main/java/com/taotao/common/pojo/SearchItem.java | 800a889c830df91f4e6c56efe8225ebfeef57831 | []
| no_license | king970745495/king-Taotao | 7842c3413d4bba7fc3dfc777cb37187b4bb57ba1 | 23f4fc95c37ad0f261d92172f12583f1cc316feb | refs/heads/master | 2022-12-22T17:50:03.143541 | 2019-11-14T07:52:09 | 2019-11-14T07:52:09 | 214,077,462 | 1 | 0 | null | 2022-12-16T07:18:39 | 2019-10-10T03:24:03 | CSS | UTF-8 | Java | false | false | 1,546 | java | package com.taotao.common.pojo;
import java.io.Serializable;
/**
* 搜索的商品数据POJO
* @title SearchItem.java
* <p>description</p>
* <p>company: www.itheima.com</p>
* @author ljh
* @version 1.0
*/
public class SearchItem implements Serializable {
private Long id;//商品的id
private String title;//商品标题
private String sell_point;//商品卖点
private Long price;//价格
private String image;//商品图片的路径
private String category_name;//商品分类名称
private String item_desc;//商品的描述
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSell_point() {
return sell_point;
}
public void setSell_point(String sell_point) {
this.sell_point = sell_point;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory_name() {
return category_name;
}
public void setCategory_name(String category_name) {
this.category_name = category_name;
}
public String getItem_desc() {
return item_desc;
}
public void setItem_desc(String item_desc) {
this.item_desc = item_desc;
}
public String[] getImages1() {
if(this.getImage()!=null) {
String[] split=this.getImage().split(",");
return split;
}
return null;
}
}
| [
"[email protected]"
]
| |
f0b473ae63c087eaae00ed30f7ffd4b939b1c6f0 | ead5a617b23c541865a6b57cf8cffcc1137352f2 | /decompiled/sources/org/joda/time/YearMonthDay.java | 14e84957c860eb9a6b0e07d0339f4a92a7654a39 | []
| no_license | erred/uva-ssn | 73a6392a096b38c092482113e322fdbf9c3c4c0e | 4fb8ea447766a735289b96e2510f5a8d93345a8c | refs/heads/master | 2022-02-26T20:52:50.515540 | 2019-10-14T12:30:33 | 2019-10-14T12:30:33 | 210,376,140 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,980 | java | package org.joda.time;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.joda.time.base.BasePartial;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.field.AbstractPartialFieldProperty;
import org.joda.time.field.FieldUtils;
import org.joda.time.format.ISODateTimeFormat;
@Deprecated
public final class YearMonthDay extends BasePartial implements Serializable, ReadablePartial {
public static final int DAY_OF_MONTH = 2;
private static final DateTimeFieldType[] FIELD_TYPES = {DateTimeFieldType.year(), DateTimeFieldType.monthOfYear(), DateTimeFieldType.dayOfMonth()};
public static final int MONTH_OF_YEAR = 1;
public static final int YEAR = 0;
private static final long serialVersionUID = 797544782896179L;
@Deprecated
public static class Property extends AbstractPartialFieldProperty implements Serializable {
private static final long serialVersionUID = 5727734012190224363L;
private final int iFieldIndex;
private final YearMonthDay iYearMonthDay;
Property(YearMonthDay yearMonthDay, int i) {
this.iYearMonthDay = yearMonthDay;
this.iFieldIndex = i;
}
public DateTimeField getField() {
return this.iYearMonthDay.getField(this.iFieldIndex);
}
/* access modifiers changed from: protected */
public ReadablePartial getReadablePartial() {
return this.iYearMonthDay;
}
public YearMonthDay getYearMonthDay() {
return this.iYearMonthDay;
}
public int get() {
return this.iYearMonthDay.getValue(this.iFieldIndex);
}
public YearMonthDay addToCopy(int i) {
return new YearMonthDay(this.iYearMonthDay, getField().add(this.iYearMonthDay, this.iFieldIndex, this.iYearMonthDay.getValues(), i));
}
public YearMonthDay addWrapFieldToCopy(int i) {
return new YearMonthDay(this.iYearMonthDay, getField().addWrapField(this.iYearMonthDay, this.iFieldIndex, this.iYearMonthDay.getValues(), i));
}
public YearMonthDay setCopy(int i) {
return new YearMonthDay(this.iYearMonthDay, getField().set(this.iYearMonthDay, this.iFieldIndex, this.iYearMonthDay.getValues(), i));
}
public YearMonthDay setCopy(String str, Locale locale) {
return new YearMonthDay(this.iYearMonthDay, getField().set(this.iYearMonthDay, this.iFieldIndex, this.iYearMonthDay.getValues(), str, locale));
}
public YearMonthDay setCopy(String str) {
return setCopy(str, null);
}
public YearMonthDay withMaximumValue() {
return setCopy(getMaximumValue());
}
public YearMonthDay withMinimumValue() {
return setCopy(getMinimumValue());
}
}
public int size() {
return 3;
}
public static YearMonthDay fromCalendarFields(Calendar calendar) {
if (calendar != null) {
return new YearMonthDay(calendar.get(1), calendar.get(2) + 1, calendar.get(5));
}
throw new IllegalArgumentException("The calendar must not be null");
}
public static YearMonthDay fromDateFields(Date date) {
if (date != null) {
return new YearMonthDay(date.getYear() + 1900, date.getMonth() + 1, date.getDate());
}
throw new IllegalArgumentException("The date must not be null");
}
public YearMonthDay() {
}
public YearMonthDay(DateTimeZone dateTimeZone) {
super((Chronology) ISOChronology.getInstance(dateTimeZone));
}
public YearMonthDay(Chronology chronology) {
super(chronology);
}
public YearMonthDay(long j) {
super(j);
}
public YearMonthDay(long j, Chronology chronology) {
super(j, chronology);
}
public YearMonthDay(Object obj) {
super(obj, null, ISODateTimeFormat.dateOptionalTimeParser());
}
public YearMonthDay(Object obj, Chronology chronology) {
super(obj, DateTimeUtils.getChronology(chronology), ISODateTimeFormat.dateOptionalTimeParser());
}
public YearMonthDay(int i, int i2, int i3) {
this(i, i2, i3, null);
}
public YearMonthDay(int i, int i2, int i3, Chronology chronology) {
super(new int[]{i, i2, i3}, chronology);
}
YearMonthDay(YearMonthDay yearMonthDay, int[] iArr) {
super((BasePartial) yearMonthDay, iArr);
}
YearMonthDay(YearMonthDay yearMonthDay, Chronology chronology) {
super((BasePartial) yearMonthDay, chronology);
}
/* access modifiers changed from: protected */
public DateTimeField getField(int i, Chronology chronology) {
switch (i) {
case 0:
return chronology.year();
case 1:
return chronology.monthOfYear();
case 2:
return chronology.dayOfMonth();
default:
StringBuilder sb = new StringBuilder();
sb.append("Invalid index: ");
sb.append(i);
throw new IndexOutOfBoundsException(sb.toString());
}
}
public DateTimeFieldType getFieldType(int i) {
return FIELD_TYPES[i];
}
public DateTimeFieldType[] getFieldTypes() {
return (DateTimeFieldType[]) FIELD_TYPES.clone();
}
public YearMonthDay withChronologyRetainFields(Chronology chronology) {
Chronology withUTC = DateTimeUtils.getChronology(chronology).withUTC();
if (withUTC == getChronology()) {
return this;
}
YearMonthDay yearMonthDay = new YearMonthDay(this, withUTC);
withUTC.validate(yearMonthDay, getValues());
return yearMonthDay;
}
public YearMonthDay withField(DateTimeFieldType dateTimeFieldType, int i) {
int indexOfSupported = indexOfSupported(dateTimeFieldType);
if (i == getValue(indexOfSupported)) {
return this;
}
return new YearMonthDay(this, getField(indexOfSupported).set(this, indexOfSupported, getValues(), i));
}
public YearMonthDay withFieldAdded(DurationFieldType durationFieldType, int i) {
int indexOfSupported = indexOfSupported(durationFieldType);
if (i == 0) {
return this;
}
return new YearMonthDay(this, getField(indexOfSupported).add(this, indexOfSupported, getValues(), i));
}
public YearMonthDay withPeriodAdded(ReadablePeriod readablePeriod, int i) {
if (readablePeriod == null || i == 0) {
return this;
}
int[] values = getValues();
for (int i2 = 0; i2 < readablePeriod.size(); i2++) {
int indexOf = indexOf(readablePeriod.getFieldType(i2));
if (indexOf >= 0) {
values = getField(indexOf).add(this, indexOf, values, FieldUtils.safeMultiply(readablePeriod.getValue(i2), i));
}
}
return new YearMonthDay(this, values);
}
public YearMonthDay plus(ReadablePeriod readablePeriod) {
return withPeriodAdded(readablePeriod, 1);
}
public YearMonthDay plusYears(int i) {
return withFieldAdded(DurationFieldType.years(), i);
}
public YearMonthDay plusMonths(int i) {
return withFieldAdded(DurationFieldType.months(), i);
}
public YearMonthDay plusDays(int i) {
return withFieldAdded(DurationFieldType.days(), i);
}
public YearMonthDay minus(ReadablePeriod readablePeriod) {
return withPeriodAdded(readablePeriod, -1);
}
public YearMonthDay minusYears(int i) {
return withFieldAdded(DurationFieldType.years(), FieldUtils.safeNegate(i));
}
public YearMonthDay minusMonths(int i) {
return withFieldAdded(DurationFieldType.months(), FieldUtils.safeNegate(i));
}
public YearMonthDay minusDays(int i) {
return withFieldAdded(DurationFieldType.days(), FieldUtils.safeNegate(i));
}
public Property property(DateTimeFieldType dateTimeFieldType) {
return new Property(this, indexOfSupported(dateTimeFieldType));
}
public LocalDate toLocalDate() {
return new LocalDate(getYear(), getMonthOfYear(), getDayOfMonth(), getChronology());
}
public DateTime toDateTimeAtMidnight() {
return toDateTimeAtMidnight(null);
}
public DateTime toDateTimeAtMidnight(DateTimeZone dateTimeZone) {
DateTime dateTime = new DateTime(getYear(), getMonthOfYear(), getDayOfMonth(), 0, 0, 0, 0, getChronology().withZone(dateTimeZone));
return dateTime;
}
public DateTime toDateTimeAtCurrentTime() {
return toDateTimeAtCurrentTime(null);
}
public DateTime toDateTimeAtCurrentTime(DateTimeZone dateTimeZone) {
Chronology withZone = getChronology().withZone(dateTimeZone);
return new DateTime(withZone.set(this, DateTimeUtils.currentTimeMillis()), withZone);
}
public DateMidnight toDateMidnight() {
return toDateMidnight(null);
}
public DateMidnight toDateMidnight(DateTimeZone dateTimeZone) {
return new DateMidnight(getYear(), getMonthOfYear(), getDayOfMonth(), getChronology().withZone(dateTimeZone));
}
public DateTime toDateTime(TimeOfDay timeOfDay) {
return toDateTime(timeOfDay, null);
}
public DateTime toDateTime(TimeOfDay timeOfDay, DateTimeZone dateTimeZone) {
Chronology withZone = getChronology().withZone(dateTimeZone);
long j = withZone.set(this, DateTimeUtils.currentTimeMillis());
if (timeOfDay != null) {
j = withZone.set(timeOfDay, j);
}
return new DateTime(j, withZone);
}
public Interval toInterval() {
return toInterval(null);
}
public Interval toInterval(DateTimeZone dateTimeZone) {
return toDateMidnight(DateTimeUtils.getZone(dateTimeZone)).toInterval();
}
public int getYear() {
return getValue(0);
}
public int getMonthOfYear() {
return getValue(1);
}
public int getDayOfMonth() {
return getValue(2);
}
public YearMonthDay withYear(int i) {
return new YearMonthDay(this, getChronology().year().set(this, 0, getValues(), i));
}
public YearMonthDay withMonthOfYear(int i) {
return new YearMonthDay(this, getChronology().monthOfYear().set(this, 1, getValues(), i));
}
public YearMonthDay withDayOfMonth(int i) {
return new YearMonthDay(this, getChronology().dayOfMonth().set(this, 2, getValues(), i));
}
public Property year() {
return new Property(this, 0);
}
public Property monthOfYear() {
return new Property(this, 1);
}
public Property dayOfMonth() {
return new Property(this, 2);
}
public String toString() {
return ISODateTimeFormat.yearMonthDay().print((ReadablePartial) this);
}
}
| [
"[email protected]"
]
| |
955b81cff61bfa7b15503d26e39e660f25cd44f6 | 5027c34d8f768a5e79b17b003ab142c12817b92f | /chapter_001/src/main/java/ru/job4j/array/ArrayChar.java | 0dcdf9a8d03bf0272fe9ae6ba805c8fdacb2ac45 | [
"Apache-2.0"
]
| permissive | PopovMS/job4j | 9e1182e3efcafd1f32ab4d2ced52bb0fc64c0cb8 | e07597cc33b25c2a5361d9e9c2aa7caf5e9395b0 | refs/heads/master | 2021-11-21T14:53:17.797508 | 2021-09-01T12:39:22 | 2021-09-01T12:39:22 | 145,887,797 | 0 | 0 | Apache-2.0 | 2020-10-12T23:20:15 | 2018-08-23T17:42:27 | Java | UTF-8 | Java | false | false | 847 | java | package ru.job4j.array;
/*
@author Popov Mikhail ([email protected])
* @version $Id$
* @since 0.1
*/
/**
* Обертка над строкой.
*/
public class ArrayChar {
private char[] data;
public ArrayChar(String line) {
this.data = line.toCharArray();
}
/**
* Проверяет. что слово начинается с префикса.
* @param prefix префикс.
* @return если слово начинается с префикса
*/
public boolean startWith(String prefix) {
boolean result = true;
char[] value = prefix.toCharArray();
for (int index = 0; index < value.length; index++) {
if (value[index] != data[index]) {
result = false;
break;
}
}
return result;
}
} | [
"[email protected]"
]
| |
18d5e3624dc48766172ef4b74c3d634a5d68d466 | 57e7c2fd0823efa7d5cb3cd34c85772bf70f0c6c | /Amanda/app/src/main/java/com/example/aws/amanda/DataContext/Entities/CategoriasCuentas.java | a86c494267411e234198af7b80ce753125aec6b2 | []
| no_license | Isamel/android_room_db | d5b66d8d1e9ac7ac4ce1e45147da38a0652784a8 | 560298de8d0859bf114c7372d40c097f0a5afa79 | refs/heads/master | 2020-04-04T23:31:44.065086 | 2018-11-07T03:57:19 | 2018-11-07T03:57:19 | 156,362,736 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 923 | java | package com.example.aws.amanda.DataContext.Entities;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
@Entity(tableName = "CategoriasCuentas")
public class CategoriasCuentas {
@PrimaryKey(autoGenerate = true)
@NonNull
@ColumnInfo(name = "IdCategoriasCuentas")
private Integer _idCategoriasCuentas;
@NonNull
@ColumnInfo(name = "Name")
private String _name;
public CategoriasCuentas(@NonNull String name) {
_name = name;
}
public void setIdCategoriasCuentas(@NonNull Integer _idCategoriasCuentas) {
this._idCategoriasCuentas = _idCategoriasCuentas;
}
@NonNull
public Integer getIdCategoria() {
return _idCategoriasCuentas;
}
@NonNull
public String getName() {
return _name;
}
}
| [
"[email protected]"
]
| |
202ec64b4e83a2e1d3986493d66deac69482368d | e46e10051fa38e95e77b4c5f4281a26fe1b899f2 | /processor/src/test/resources/expected/com/example/observable_ref/Arez_RawObservableModel.java | 8073080c738568efe87eeae4618d754c01d503f9 | [
"Apache-2.0"
]
| permissive | jcosmo/arez | 820f82ab53e1d3b57813c8438f545cd09bf68dcd | 67bf4972d3bda4d850374a0483788c630384e87b | refs/heads/master | 2020-03-17T12:23:05.521806 | 2018-05-14T05:38:35 | 2018-05-14T05:38:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,467 | java | package com.example.observable_ref;
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.Observable;
import arez.component.ComponentObservable;
import arez.component.ComponentState;
import arez.component.Identifiable;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.braincheck.Guards;
@Generated("arez.processor.ArezProcessor")
public final class Arez_RawObservableModel extends RawObservableModel implements Disposable, Identifiable<Long>, ComponentObservable {
private static volatile long $$arezi$$_nextId;
private final long $$arezi$$_id;
private byte $$arezi$$_state;
@Nullable
private final ArezContext $$arezi$$_context;
private final Component $$arezi$$_component;
private final Observable<Boolean> $$arezi$$_disposedObservable;
@Nonnull
private final Observable<Long> $$arez$$_time;
public Arez_RawObservableModel() {
super();
this.$$arezi$$_context = Arez.areZonesEnabled() ? Arez.context() : null;
this.$$arezi$$_id = ( Arez.areNativeComponentsEnabled() || Arez.areNativeComponentsEnabled() ) ? $$arezi$$_nextId++ : 0L;
this.$$arezi$$_state = ComponentState.COMPONENT_INITIALIZED;
this.$$arezi$$_component = Arez.areNativeComponentsEnabled() ? $$arezi$$_context().createComponent( "RawObservableModel", $$arezi$$_id(), Arez.areNamesEnabled() ? $$arezi$$_name() : null ) : null;
this.$$arezi$$_disposedObservable = $$arezi$$_context().createObservable( Arez.areNativeComponentsEnabled() ? this.$$arezi$$_component : null, Arez.areNamesEnabled() ? $$arezi$$_name() + ".isDisposed" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> this.$$arezi$$_state >= 0 : null );
this.$$arez$$_time = $$arezi$$_context().createObservable( Arez.areNativeComponentsEnabled() ? this.$$arezi$$_component : null, Arez.areNamesEnabled() ? $$arezi$$_name() + ".time" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> super.getTime() : null, Arez.arePropertyIntrospectorsEnabled() ? v -> super.setTime( v ) : null );
this.$$arezi$$_state = ComponentState.COMPONENT_CONSTRUCTED;
if ( Arez.areNativeComponentsEnabled() ) {
this.$$arezi$$_component.complete();
}
this.$$arezi$$_state = ComponentState.COMPONENT_READY;
}
final ArezContext $$arezi$$_context() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> ComponentState.hasBeenInitialized( this.$$arezi$$_state ), () -> "Method named '$$arezi$$_context' invoked on uninitialized component of type 'RawObservableModel'" );
}
return Arez.areZonesEnabled() ? this.$$arezi$$_context : Arez.context();
}
final long $$arezi$$_id() {
if ( Arez.shouldCheckInvariants() && !Arez.areNamesEnabled() && !Arez.areNativeComponentsEnabled() ) {
Guards.fail( () -> "Method invoked to access id when id not expected." );
}
return this.$$arezi$$_id;
}
@Override
@Nonnull
public final Long getArezId() {
return $$arezi$$_id();
}
String $$arezi$$_name() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> ComponentState.hasBeenInitialized( this.$$arezi$$_state ), () -> "Method named '$$arezi$$_name' invoked on uninitialized component of type 'RawObservableModel'" );
}
return "RawObservableModel." + $$arezi$$_id();
}
private boolean $$arezi$$_observe() {
final boolean isDisposed = isDisposed();
if ( !isDisposed ) {
this.$$arezi$$_disposedObservable.reportObserved();
}
return !isDisposed;
}
@Override
public boolean observe() {
return $$arezi$$_observe();
}
@Override
public boolean isDisposed() {
return ComponentState.isDisposingOrDisposed( this.$$arezi$$_state );
}
@Override
public void dispose() {
if ( !ComponentState.isDisposingOrDisposed( this.$$arezi$$_state ) ) {
this.$$arezi$$_state = ComponentState.COMPONENT_DISPOSING;
if ( Arez.areNativeComponentsEnabled() ) {
this.$$arezi$$_component.dispose();
} else {
$$arezi$$_context().dispose( Arez.areNamesEnabled() ? $$arezi$$_name() : null, () -> { {
this.$$arezi$$_disposedObservable.dispose();
this.$$arez$$_time.dispose();
} } );
}
this.$$arezi$$_state = ComponentState.COMPONENT_DISPOSED;
}
}
@Override
public long getTime() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> ComponentState.isActive( this.$$arezi$$_state ), () -> "Method named 'getTime' invoked on " + ComponentState.describe( this.$$arezi$$_state ) + " component named '" + $$arezi$$_name() + "'" );
}
this.$$arez$$_time.reportObserved();
return super.getTime();
}
@Override
public void setTime(final long time) {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> ComponentState.isActive( this.$$arezi$$_state ), () -> "Method named 'setTime' invoked on " + ComponentState.describe( this.$$arezi$$_state ) + " component named '" + $$arezi$$_name() + "'" );
}
if ( time != super.getTime() ) {
this.$$arez$$_time.preReportChanged();
super.setTime(time);
this.$$arez$$_time.reportChanged();
}
}
@Nonnull
@Override
public Observable getTimeObservable() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> ComponentState.isActive( this.$$arezi$$_state ), () -> "Method named 'getTimeObservable' invoked on " + ComponentState.describe( this.$$arezi$$_state ) + " component named '" + $$arezi$$_name() + "'" );
}
return $$arez$$_time;
}
@Override
public final int hashCode() {
if ( Arez.areNativeComponentsEnabled() ) {
return Long.hashCode( $$arezi$$_id() );
} else {
return super.hashCode();
}
}
@Override
public final boolean equals(final Object o) {
if ( Arez.areNativeComponentsEnabled() ) {
if ( this == o ) {
return true;
} else if ( null == o || !(o instanceof Arez_RawObservableModel) ) {
return false;
} else {
final Arez_RawObservableModel that = (Arez_RawObservableModel) o;;
return $$arezi$$_id() == that.$$arezi$$_id();
}
} else {
return super.equals( o );
}
}
@Override
public final String toString() {
if ( Arez.areNamesEnabled() ) {
return "ArezComponent[" + $$arezi$$_name() + "]";
} else {
return super.toString();
}
}
}
| [
"[email protected]"
]
| |
1b8635307e62597f82d02b39c2acb8dd7d2dc0a2 | 8a28b2ff44dab2e949ababc341452e89a2b7d0e0 | /spring-boot-cc/src/main/java/com/cc/entity/key/MasterCardsKey.java | 7b9d7a23e5d96484357d180c871aaf60484f0952 | [
"Apache-2.0"
]
| permissive | eatnoodles/LineBotCC | 6b49a596f9d741e318c2a2c4c9595b136988a821 | 5e4099138ce8f21fbed2657d14b6a5d187b7efab | refs/heads/master | 2021-01-22T19:14:10.191936 | 2017-09-26T03:38:21 | 2017-09-26T03:38:21 | 85,176,442 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 775 | java | package com.cc.entity.key;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.cc.entity.irol.Irol;
/**
* @author Caleb Cheng
*
*/
@SuppressWarnings("serial")
@Embeddable
public class MasterCardsKey implements Serializable {
private String lineId;
@ManyToOne
@JoinColumn(name = "IROL_ID")
private Irol irol;
public MasterCardsKey() {
}
public MasterCardsKey(String lineId, Irol irol) {
this.lineId = lineId;
this.irol = irol;
}
public String getLineId() {
return lineId;
}
public void setLineId(String lineId) {
this.lineId = lineId;
}
public Irol getIrol() {
return irol;
}
public void setIrol(Irol irol) {
this.irol = irol;
}
}
| [
"[email protected]"
]
| |
83b5bbccc792f11c785f0819a6d778f17015bf0d | 597ba8c31b9be3869719eff6c0026526f7f3b3e9 | /src/main/java/dev/iakunin/codexiabot/codexia/entity/CodexiaReview.java | 0aada6b7962ae4988bbc702a03ba9658b7a64d31 | [
"MIT"
]
| permissive | yegor256/codexia-bot | 871d8178714ef40f89d31089d86dd1816c44a55e | eaa3da3d711fbbc6a7b5d8b1aef719858a16b455 | refs/heads/master | 2023-08-28T23:13:53.681201 | 2020-04-28T19:05:30 | 2020-04-28T19:05:30 | 259,689,026 | 1 | 1 | MIT | 2020-04-28T16:15:26 | 2020-04-28T16:15:25 | null | UTF-8 | Java | false | false | 512 | java | package dev.iakunin.codexiabot.codexia.entity;
import dev.iakunin.codexiabot.common.entity.AbstractEntity;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Entity
@Data
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public final class CodexiaReview extends AbstractEntity {
@ManyToOne
private CodexiaProject codexiaProject;
private String author;
private String reason;
private String text;
}
| [
"[email protected]"
]
| |
d7cf23beefefe7423f89e19e49168f3fc33ea6cb | 72148ad83802ffba87d40e2ad3067d9bab2053bd | /spring-activemq-listener/src/main/java/hei/activemq/alerts/PersonJmsMain.java | df68f6012edaf795e7e0fd25e58a766242ec0c11 | []
| no_license | heizq/activemq-test | 9bf7e347d8d8b04465753097d6151c9c05defb79 | a3772cb2b9b6b26114496d1394e3ae663f14d41b | refs/heads/master | 2021-01-10T11:35:30.222885 | 2015-12-31T09:20:42 | 2015-12-31T09:20:42 | 48,843,480 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 742 | java | package hei.activemq.alerts;
import hei.activemq.alerts.domain.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by heizhiqiang on 2015/12/31 0031.
*/
public class PersonJmsMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("messaging-context.xml");
AlertService alertService = context.getBean(AlertService.class);
Person person = new Person("123456","tom","159678678","jelei");
int star = 0;
for(int i=0; i< 10; i++) {
star += 1;
person.setStar(star);
alertService.sendMessageAlert(person);
}
context.close();
}
}
| [
"[email protected]"
]
| |
7531fb6af0bd0f2d3b96a59699663d0fa7c351fc | a8fcb15cf271d35a75b45dc38dd4485538aef7e1 | /others/DivideNewton.java | bf6885f71059bdff09143c15b893c8b43f109cf9 | []
| no_license | rogerdai16/luoleet | e45265770e4f43bbd67d29944b2e9ee8902fbb2f | 64ae0061cee39a1b68c8d9b8253a583b6c7fb36a | refs/heads/master | 2016-09-08T02:06:08.438767 | 2015-10-17T00:29:29 | 2015-10-17T00:29:29 | 21,675,971 | 0 | 3 | null | 2015-10-07T01:04:00 | 2014-07-10T02:12:28 | Java | UTF-8 | Java | false | false | 377 | java | /**
* Created by Qinghao on 6/27/2015.
* ????????????????????????????
*/
public class DivideNewton {
private static double eps = 1E-6;
public static double divideNewton(double n){
double x0 = 1;
do{
x0 = x0 * (2 - n * x0);
}while(n * x0 - 1 >= eps);
return x0;
}
public static void main(String[] args){
}
}
| [
"[email protected]"
]
| |
ecda0f8d99ce205f4b1cfab4ab4b616a3bf6a126 | b1af4d9e16d5baaf44eae90593550a8c27da8d4e | /src/main/java/com/sixtyfour/basicshell/Runner.java | 53abfb3ba4bd69e66902c8c08fa7db702176dea2 | [
"Unlicense"
]
| permissive | amramsey/basicv2 | e9315b27e74b32ef8e3c4123f00e8f464ce77cef | 150fb4b1170fbc7841eadc9e26dd723202d9d312 | refs/heads/master | 2023-04-03T02:19:17.048751 | 2023-03-26T13:20:01 | 2023-03-26T13:20:01 | 243,966,500 | 0 | 0 | Unlicense | 2023-03-26T13:20:02 | 2020-02-29T12:40:01 | Java | UTF-8 | Java | false | false | 2,632 | java | package com.sixtyfour.basicshell;
import java.util.concurrent.Future;
import com.sixtyfour.Basic;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.extensions.graphics.GraphicsBasic;
import com.sixtyfour.extensions.textmode.ConsoleSupport;
/**
* Runs the program that's inside the editor.
*
* @author nietoperz809
*/
public class Runner implements Runnable {
private final Basic olsenBasic;
private boolean running;
private Basic runningBasic = null;
private CompilerConfig config = new CompilerConfig();
public Runner(String[] program, BasicShell shellFrame) {
Basic.registerExtension(new GraphicsBasic());
Basic.registerExtension(new ConsoleSupport());
this.olsenBasic = new Basic(program);
olsenBasic.setOutputChannel(new ShellOutputChannel(shellFrame));
olsenBasic.setInputProvider(new ShellInputProvider(shellFrame));
}
public void dispose() {
if (olsenBasic != null) {
olsenBasic.resetMemory();
}
}
public void registerKey(Character key) {
if (olsenBasic.getInputProvider() instanceof ShellInputProvider) {
((ShellInputProvider) olsenBasic.getInputProvider()).setCurrentKey(key);
}
}
/**
* Start BASIC task and blocks starter until task ends
*/
public void synchronousStart() {
Future<?> f = BasicShell.executor.submit(this);
try {
f.get();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Executes a command in "direct mode" by shoehorning it into a one line
* program.
*
* @param command the command the execute
*/
public void executeDirectCommand(final String command) {
Future<?> f = BasicShell.executor.submit(new Runnable() {
@Override
public void run() {
running = true;
Basic imm = new Basic("0" + command, olsenBasic.getMachine());
// imm.setLoopMode(LoopMode.REMOVE);
runningBasic = imm;
imm.compile(config, false);
imm.start(config);
running = false;
runningBasic = null;
}
});
try {
f.get();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isRunning() {
return running;
}
public Basic getOlsenBasic() {
return olsenBasic;
}
public Basic getRunningBasic() {
return runningBasic;
}
/**
* Start BASIC task
*
* @param synchronous if true the caller is blocked
*/
public void start(boolean synchronous) {
Future<?> f = BasicShell.executor.submit(this);
if (!synchronous)
return;
try {
f.get();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
running = true;
runningBasic = olsenBasic;
olsenBasic.run(config);
running = false;
runningBasic = null;
}
}
| [
"[email protected]"
]
| |
9c2d2b5df262c2b1a7f237b431a9d1aa8351840b | 8e12048800aefa2677cbcf022ec3880c6f6dffdf | /matrices/TwoDTaskOne.java | 2caeb3b2bf4fa55e58ac21d18b794b175309baf2 | []
| no_license | Ravi0715/Important-Tasks | 81c23b3a71a97fedd1d2336db337e26914feb4da | 2f746e5a1b93cafe599b4e7cb65b69dca28a24bd | refs/heads/master | 2020-04-19T12:53:40.209248 | 2016-09-26T20:59:53 | 2016-09-26T20:59:53 | 67,369,178 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 975 | java | package practice.matrices;
import java.util.Scanner;
public class TwoDTaskOne {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value:");
int n=in.nextInt();
char a[][] = new char[n][n];
if(n>10)
{
System.out.println("Out of range.....");
System.exit(0);
}
System.out.println("Enter 1st character:");
char ch = in.next().charAt(0);
System.out.println("Enter 2nd character:");
char ch1 = in.next().charAt(0);
System.out.println("Enter 3rd character:");
char ch2=in.next().charAt(0);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||i==n-1)
{
if(j!=0&&j!=n-1)
System.out.print(ch+" ");
else
System.out.print(ch2+" ");
}
else
{
if(j==0||j==n-1)
System.out.print(ch1+" ");
else
System.out.print(ch2+" ");
}
}
System.out.println();
}
}
}
| [
"[email protected]"
]
| |
acd4a0f47e037cc2479e8cd856690561da52aaa3 | cfdac8d167974057d25fd374bdb90923fc1195d8 | /test/test/StringTest.java | fed4f3e6e805d751e4bb1938238b0febf324f6a1 | []
| no_license | troyhen/neo | 2ce76dd6523cb9fad93c0c325d8ebcc096a44d14 | 9ea0ef3a7831fd66ce39a2aac9d40d196da86a4c | refs/heads/master | 2021-03-12T19:34:45.202238 | 2011-11-16T03:08:50 | 2011-11-16T03:08:50 | 2,231,743 | 14 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,151 | java | package test;
import org.neo.util.Log;
import org.junit.After;
import org.neo.core.Strings;
import org.neo.NeoLang;
import org.neo.parse.Node;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author theninger
*/
public class StringTest {
private NeoLang lang;
@Before
public void setUp() {
lang = new NeoLang();
}
@After
public void tearDown() {
Log.testStop();
}
@Test
public void testTokenizer() {
String simple = "\"this is a string\" "
+ "'this is another' "
+ "`word "
+ "\"\"\"This\nis\na\nvery\nlong\nstring\"\"\" ";
lang.load(simple);
Node tokens = lang.tokenize();
assertEquals("terminator_bof", tokens.get(0).getName());
assertEquals(Strings.STRING_DOUBLE, tokens.get(1).getName());
assertEquals(Strings.STRING_SINGLE, tokens.get(2).getName());
assertEquals(Strings.STRING_WORD, tokens.get(3).getName());
assertEquals(Strings.STRING_MULTILINE, tokens.get(4).getName());
}
}
| [
"[email protected]"
]
| |
8e4d37c2750a09c9d8e98198f73b04c4ddbf6909 | d37bd88a7858e56832e7db06138ec16f41760fa2 | /.svn/pristine/8e/8e4d37c2750a09c9d8e98198f73b04c4ddbf6909.svn-base | 961af0cc489c52493a880c3cf8b6723211356d32 | []
| no_license | couozu/floreantpos | fe84f19be438407596af0f7c6ba3e9830793002d | 31936b2115e5ad14052679b9100d55c90c7ea8f8 | refs/heads/master | 2021-01-10T13:14:17.876691 | 2016-11-07T21:05:19 | 2016-11-07T21:05:19 | 47,064,272 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,361 | /*
* PayoutDialog.java
*
* Created on August 25, 2006, 8:44 PM
*/
package com.floreantpos.ui.dialog;
import java.util.Date;
import com.floreantpos.Messages;
import com.floreantpos.main.Application;
import com.floreantpos.model.ActionHistory;
import com.floreantpos.model.PayOutTransaction;
import com.floreantpos.model.PaymentType;
import com.floreantpos.model.PayoutReason;
import com.floreantpos.model.PayoutRecepient;
import com.floreantpos.model.Terminal;
import com.floreantpos.model.TransactionType;
import com.floreantpos.model.dao.ActionHistoryDAO;
import com.floreantpos.model.dao.PayOutTransactionDAO;
import com.floreantpos.util.NumberUtil;
/**
*
* @author MShahriar
*/
public class PayoutDialog extends POSDialog {
/** Creates new form PayoutDialog */
public PayoutDialog() {
initComponents();
setTitle(Application.getTitle() + ": PAY OUT"); //$NON-NLS-1$
payOutView.initialize();
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
transparentPanel1 = new com.floreantpos.swing.TransparentPanel();
payOutView = new com.floreantpos.ui.views.PayOutView();
transparentPanel2 = new com.floreantpos.swing.TransparentPanel();
btnFinish = new com.floreantpos.swing.PosButton();
btnCancel = new com.floreantpos.swing.PosButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
transparentPanel1.setLayout(new java.awt.BorderLayout());
transparentPanel1.setOpaque(true);
transparentPanel1.add(payOutView, java.awt.BorderLayout.CENTER);
transparentPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 10, 5));
btnFinish.setText(com.floreantpos.POSConstants.FINISH);
btnFinish.setPreferredSize(new java.awt.Dimension(140, 50));
btnFinish.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doFinishPayout(evt);
}
});
transparentPanel2.add(btnFinish);
btnCancel.setText(com.floreantpos.POSConstants.CANCEL);
btnCancel.setPreferredSize(new java.awt.Dimension(140, 50));
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
transparentPanel2.add(btnCancel);
transparentPanel1.add(transparentPanel2, java.awt.BorderLayout.SOUTH);
getContentPane().add(transparentPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void doFinishPayout(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doFinishPayout
Application application = Application.getInstance();
Terminal terminal = application.refreshAndGetTerminal();
double payoutAmount = payOutView.getPayoutAmount();
PayoutReason reason = payOutView.getReason();
PayoutRecepient recepient = payOutView.getRecepient();
String note = payOutView.getNote();
terminal.setCurrentBalance(terminal.getCurrentBalance() - payoutAmount);
PayOutTransaction payOutTransaction = new PayOutTransaction();
payOutTransaction.setPaymentType(PaymentType.CASH.name());
payOutTransaction.setTransactionType(TransactionType.DEBIT.name());
payOutTransaction.setReason(reason);
payOutTransaction.setRecepient(recepient);
payOutTransaction.setNote(note);
payOutTransaction.setAmount(Double.valueOf(payoutAmount));
payOutTransaction.setUser(Application.getCurrentUser());
payOutTransaction.setTransactionTime(new Date());
payOutTransaction.setTerminal(terminal);
try {
PayOutTransactionDAO dao = new PayOutTransactionDAO();
dao.saveTransaction(payOutTransaction, terminal);
setCanceled(false);
// PAYOUT ACTION
String actionMessage = ""; //$NON-NLS-1$
actionMessage += Messages.getString("PayoutDialog.2") + ":" + NumberUtil.formatNumber(payoutAmount); //$NON-NLS-1$ //$NON-NLS-2$
ActionHistoryDAO.getInstance().saveHistory(Application.getCurrentUser(), ActionHistory.PAY_OUT, actionMessage);
dispose();
} catch (Exception e) {
POSMessageDialog.showError(Application.getPosWindow(), e.getMessage(), e);
}
}//GEN-LAST:event_doFinishPayout
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
canceled = true;
dispose();
}//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private com.floreantpos.swing.PosButton btnCancel;
private com.floreantpos.swing.PosButton btnFinish;
private com.floreantpos.ui.views.PayOutView payOutView;
private com.floreantpos.swing.TransparentPanel transparentPanel1;
private com.floreantpos.swing.TransparentPanel transparentPanel2;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
]
| ||
8928db9b2be3f68b4d3b8a6f7b5a701f04d6429d | ddb79816c9efad32b634d1dbbcb69d7ab7f17997 | /src/main/java/com/hpit/demo1/conteroller/HouseConrtoller.java | 24358dee1f7eccbfe1a6ab96f3b2a11b8fbec609 | []
| no_license | lwhlwh123456/SSM88 | 00491e978e703029d6c3232910855f0a666f81d0 | 296db0a43098f02a1a2c40694427ec6bb561b0db | refs/heads/master | 2022-12-21T13:35:25.263473 | 2019-07-02T11:57:11 | 2019-07-02T11:57:11 | 194,627,598 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,338 | java | package com.hpit.demo1.conteroller;
import com.github.pagehelper.PageInfo;
import com.hpit.demo1.entity.*;
import com.hpit.demo1.service.DistrictService;
import com.hpit.demo1.service.HouseService;
import com.hpit.demo1.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/lll/")
public class HouseConrtoller {
@Autowired
private TypeService typeService;
@Autowired
private DistrictService districtService;
@Autowired
private HouseService houseService;
@RequestMapping("getHao")
public String getHao(Model model){
List<Type> hao = typeService.getHao();
List<District> hao1 = districtService.getAllType();
System.out.println("hao = " + hao);
model.addAttribute("hao",hao);
model.addAttribute("hao1",hao1);
return "fabu";
}
@RequestMapping("addHouse")
public String add(House house,@RequestParam(value = "pfile",required = false) CommonsMultipartFile pfile, HttpSession session) throws IOException {
//将文件保存在服务器中 D:\\images
String fname=pfile.getOriginalFilename();
String expName=fname.substring(fname.lastIndexOf("."));
String saveName=System.currentTimeMillis()+expName; //保存文件名
File file=new File("D:\\images\\"+saveName);
pfile.transferTo(file); //保存
//设置编号
house.setId(System.currentTimeMillis()+"");
//设置用户编号
Users usersname = (Users) session.getAttribute("usersname");
house.setUserId(usersname.getId());
//设置审核状态 0 如果表中有默认值 可不设
house.setIspass(0);
//设置是否删除 0
house.setIsdel(0);
//设置图片路径
house.setPath(saveName);
if(houseService.addHouse(house)>0){ //保存数据
/*调用业务
houseService.addHouse(house); //添加信息到数据库*/
return "redirect:/page/guanli.jsp"; //跳转页面
}
else{
//成功上传的图片删除
file.delete();
return "redirect:goFaBu"; //跳转页面
}
}
@RequestMapping("getHaoHouse")
public String getSelectHouse(Integer page,HttpSession session,Model model){
Users usersname =(Users) session.getAttribute("usersname");
PageInfo<House> pageInfo=houseService.getSelectHouse(page==null?1:page,10,usersname.getId());
model.addAttribute("pageInfo",pageInfo);
return "guanli";
}
@RequestMapping("getUpdate")
public String getUpdate(String id, Model model){
List<Type> hao = typeService.getHao();
List<District> hao1 = districtService.getAllType();
House house = houseService.getHouse(id);
System.out.println("house = " + house);
model.addAttribute("hao",hao);
model.addAttribute("hao1",hao1);
model.addAttribute("house",house);
return "update";
}
@RequestMapping("upHouse")
public String update(String tuPan,House house,@RequestParam(value = "pfile",required = false) CommonsMultipartFile pfile, HttpSession session) throws IOException {
File file = null;
//1.修改时判断用户有没有修改图片
if (pfile.getOriginalFilename().equals("")) {
} else {
//上传新的图片,删除旧的图片,设置path为上传新的图片名称
file = new File("D\\images\\"+tuPan);
pfile.transferTo(file);
//设置图片名称
house.setPath(tuPan);
}
if (houseService.Update(house) <= 0) {
//成功上传的图片删除
if (file != null) file.delete();
}
return "redirect:/lll/getHaoHouse";
}
@RequestMapping("delete")
@ResponseBody
public String delete(String id){
int delete = houseService.delete(id);
return "{\"result\":"+delete+"}";
}
}
| [
"[email protected]"
]
| |
296d79c355de725adf62e6ff39fc61883c5c8bd1 | 509f39b747a2a73273caed46a777eb468f424015 | /src/nepic/util/Builder.java | 1290d9d4e6d5a5455692054add26e7cd7f78ba5c | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
]
| permissive | ajkwak/NEPIC | ce4c9f4d0df9fdf61dfd03f58df840a485479d33 | 5eabb2f75f5853fca010cc6b478539b1dfd515c6 | refs/heads/master | 2020-06-04T19:06:41.136782 | 2014-04-24T04:14:51 | 2014-04-24T04:14:51 | 12,758,706 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 387 | java | package nepic.util;
/**
* An interface for classes that are designed to build objects of other classes.
*
* @author AJ Parmidge
*
* @param <T> The type of object this {@link Builder} builds
*/
public interface Builder<T> {
/**
* Build the desired object from the data given to the {@link Builder}.
*
* @return the built object
*/
public T build();
}
| [
"[email protected]"
]
| |
200363e9f7753f4d39d55c3a27a0d94de841ee81 | c885ef92397be9d54b87741f01557f61d3f794f3 | /results/Mockito-4/org.mockito.exceptions.Reporter/BBC-F0-opt-20/tests/28/org/mockito/exceptions/Reporter_ESTest_scaffolding.java | 9643fb838b1aae5bd21d4e66a2593f39b6b464a8 | [
"CC-BY-4.0",
"MIT"
]
| permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 14,288 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Sat Oct 23 23:04:02 GMT 2021
*/
package org.mockito.exceptions;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
import static org.evosuite.shaded.org.mockito.Mockito.*;
@EvoSuiteClassExclude
public class Reporter_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "org.mockito.exceptions.Reporter";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {}
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
/*No java.lang.System property to set*/
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Reporter_ESTest_scaffolding.class.getClassLoader() ,
"org.mockito.internal.configuration.plugins.PluginRegistry",
"org.mockito.internal.matchers.ContainsExtraTypeInformation",
"org.mockito.configuration.AnnotationEngine",
"org.mockito.cglib.proxy.Callback",
"org.mockito.exceptions.misusing.UnfinishedVerificationException",
"org.mockito.invocation.Invocation",
"org.mockito.listeners.MethodInvocationReport",
"org.mockito.invocation.Location",
"org.mockito.mock.SerializableMode",
"org.mockito.internal.invocation.InvocationMatcher",
"org.mockito.exceptions.Reporter",
"org.mockito.exceptions.verification.VerificationInOrderFailure",
"org.mockito.internal.exceptions.VerificationAwareInvocation",
"org.mockito.configuration.DefaultMockitoConfiguration",
"org.mockito.exceptions.misusing.NullInsteadOfMockException",
"org.mockito.internal.configuration.plugins.PluginLoader",
"org.mockito.internal.debugging.VerboseMockInvocationLogger",
"org.mockito.internal.util.StringJoiner",
"org.mockito.internal.exceptions.stacktrace.StackTraceFilter",
"org.mockito.exceptions.misusing.NotAMockException",
"org.mockito.exceptions.misusing.FriendlyReminderException",
"org.mockito.exceptions.misusing.MissingMethodInvocationException",
"org.mockito.exceptions.verification.SmartNullPointerException",
"org.mockito.exceptions.verification.TooLittleActualInvocations",
"org.mockito.invocation.StubInfo",
"org.mockito.internal.matchers.MatcherDecorator",
"org.mockito.internal.configuration.GlobalConfiguration",
"org.mockito.internal.configuration.plugins.Plugins",
"org.mockito.cglib.proxy.MethodInterceptor",
"org.mockito.exceptions.verification.TooManyActualInvocations",
"org.mockito.plugins.MockMaker",
"org.mockito.exceptions.verification.ArgumentsAreDifferent",
"org.mockito.internal.invocation.InvocationImpl",
"org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider",
"org.mockito.plugins.StackTraceCleanerProvider",
"org.mockito.internal.junit.JUnitDetecter",
"org.mockito.exceptions.misusing.MockitoConfigurationException",
"org.hamcrest.SelfDescribing",
"org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter",
"org.mockito.exceptions.misusing.InvalidUseOfMatchersException",
"org.mockito.exceptions.misusing.UnfinishedStubbingException",
"org.mockito.exceptions.verification.junit.ArgumentsAreDifferent",
"org.mockito.exceptions.verification.NoInteractionsWanted",
"org.mockito.internal.invocation.CapturesArgumensFromInvocation",
"org.mockito.exceptions.PrintableInvocation",
"org.mockito.listeners.InvocationListener",
"org.mockito.mock.MockName",
"org.mockito.invocation.DescribedInvocation",
"org.mockito.internal.configuration.ClassPathLoader",
"org.mockito.exceptions.base.MockitoException",
"org.mockito.plugins.PluginSwitch",
"org.mockito.internal.matchers.CapturesArguments",
"org.mockito.internal.junit.FriendlyExceptionMaker",
"org.hamcrest.BaseMatcher",
"org.mockito.stubbing.Answer",
"org.mockito.invocation.InvocationOnMock",
"org.mockito.internal.util.collections.Iterables",
"org.hamcrest.core.AnyOf",
"org.mockito.internal.configuration.plugins.DefaultPluginSwitch",
"org.mockito.exceptions.verification.WantedButNotInvoked",
"org.hamcrest.core.ShortcutCombination",
"org.mockito.invocation.MockHandler",
"org.mockito.internal.creation.cglib.CglibMockMaker",
"org.mockito.internal.exceptions.util.ScenarioPrinter",
"org.hamcrest.Description",
"org.mockito.configuration.IMockitoConfiguration",
"org.mockito.internal.junit.JUnitTool",
"org.mockito.exceptions.misusing.WrongTypeOfReturnValue",
"org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner",
"org.mockito.cglib.proxy.Factory",
"org.mockito.internal.reporting.Pluralizer",
"org.mockito.exceptions.stacktrace.StackTraceCleaner",
"org.mockito.exceptions.base.MockitoAssertionError",
"org.mockito.internal.reporting.Discrepancy",
"org.mockito.internal.debugging.LocationImpl",
"org.mockito.internal.configuration.plugins.PluginFinder",
"org.mockito.internal.util.MockUtil",
"org.mockito.internal.matchers.LocalizedMatcher",
"org.mockito.exceptions.verification.NeverWantedButInvoked",
"org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue",
"org.mockito.exceptions.misusing.CannotVerifyStubOnlyMock",
"org.hamcrest.Matcher"
);
}
private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException {
mock(Class.forName("org.mockito.invocation.Invocation", false, Reporter_ESTest_scaffolding.class.getClassLoader()));
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(Reporter_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"org.mockito.exceptions.Reporter",
"org.mockito.internal.junit.JUnitDetecter",
"org.mockito.internal.junit.JUnitTool",
"org.mockito.exceptions.base.MockitoException",
"org.mockito.internal.util.StringJoiner",
"org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter",
"org.mockito.internal.configuration.GlobalConfiguration",
"org.mockito.configuration.DefaultMockitoConfiguration",
"org.mockito.internal.configuration.ClassPathLoader",
"org.mockito.internal.configuration.plugins.PluginRegistry",
"org.mockito.internal.configuration.plugins.PluginLoader",
"org.mockito.internal.configuration.plugins.DefaultPluginSwitch",
"org.mockito.internal.configuration.plugins.PluginFinder",
"org.mockito.internal.util.collections.Iterables",
"org.mockito.internal.creation.cglib.CglibMockMaker",
"org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider",
"org.mockito.internal.configuration.plugins.Plugins",
"org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner",
"org.mockito.internal.exceptions.stacktrace.StackTraceFilter",
"org.mockito.exceptions.misusing.MissingMethodInvocationException",
"org.mockito.exceptions.misusing.InvalidUseOfMatchersException",
"org.mockito.internal.debugging.LocationImpl",
"org.mockito.exceptions.base.MockitoAssertionError",
"org.mockito.internal.reporting.Pluralizer",
"org.hamcrest.BaseMatcher",
"org.hamcrest.collection.IsIn",
"org.hamcrest.internal.ReflectiveTypeFinder",
"org.hamcrest.TypeSafeDiagnosingMatcher",
"org.hamcrest.core.CombinableMatcher",
"org.hamcrest.core.IsAnything",
"org.hamcrest.core.ShortcutCombination",
"org.hamcrest.core.AnyOf",
"org.mockito.internal.matchers.LocalizedMatcher",
"org.mockito.internal.invocation.InvocationMatcher",
"org.mockito.internal.stubbing.StubbedInvocationMatcher",
"org.mockito.exceptions.misusing.UnfinishedVerificationException",
"org.mockito.internal.invocation.realmethod.DefaultRealMethod",
"org.mockito.internal.invocation.InvocationImpl",
"org.mockito.internal.invocation.ArgumentsProcessor",
"org.mockito.internal.invocation.SerializableMethod",
"org.mockito.exceptions.misusing.NotAMockException",
"org.mockito.exceptions.misusing.NullInsteadOfMockException",
"org.mockito.internal.invocation.realmethod.CleanTraceRealMethod",
"org.mockito.exceptions.verification.SmartNullPointerException",
"org.mockito.exceptions.misusing.CannotVerifyStubOnlyMock",
"org.mockito.internal.debugging.VerboseMockInvocationLogger",
"org.hamcrest.core.IsNull",
"org.hamcrest.text.IsEmptyString",
"org.hamcrest.BaseDescription",
"org.hamcrest.StringDescription",
"org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue",
"org.mockito.internal.reporting.Discrepancy",
"org.mockito.exceptions.misusing.FriendlyReminderException",
"org.mockito.internal.junit.FriendlyExceptionMaker",
"org.mockito.exceptions.verification.junit.ArgumentsAreDifferent",
"org.mockito.ArgumentMatcher",
"org.mockito.internal.matchers.Equals",
"org.mockito.exceptions.misusing.WrongTypeOfReturnValue",
"org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer",
"org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls",
"org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues",
"org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues",
"org.mockito.internal.util.ObjectMethodsGuru",
"org.mockito.internal.util.MockUtil",
"org.mockito.internal.stubbing.defaultanswers.ReturnsMocks",
"org.mockito.internal.MockitoCore",
"org.mockito.internal.progress.ThreadSafeMockingProgress",
"org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs",
"org.mockito.internal.stubbing.answers.CallsRealMethods",
"org.mockito.Answers",
"org.hamcrest.core.IsSame",
"org.hamcrest.FeatureMatcher",
"org.hamcrest.object.HasToString",
"org.hamcrest.core.IsEqual",
"org.hamcrest.DiagnosingMatcher",
"org.hamcrest.core.AllOf",
"org.hamcrest.core.Is",
"org.hamcrest.core.IsInstanceOf",
"org.mockito.exceptions.misusing.UnfinishedStubbingException",
"org.mockito.internal.listeners.NotifiedMethodInvocationReport",
"org.mockito.internal.invocation.StubInfoImpl",
"org.mockito.exceptions.verification.VerificationInOrderFailure",
"org.hamcrest.TypeSafeMatcher",
"org.hamcrest.beans.HasProperty",
"org.mockito.internal.exceptions.util.ScenarioPrinter",
"org.mockito.exceptions.verification.NoInteractionsWanted",
"org.hamcrest.text.IsEqualIgnoringWhiteSpace",
"org.mockito.exceptions.verification.WantedButNotInvoked",
"org.hamcrest.internal.SelfDescribingValueIterator",
"org.hamcrest.number.OrderingComparison",
"org.hamcrest.Description$NullDescription",
"org.hamcrest.core.IsNot",
"org.hamcrest.beans.SamePropertyValuesAs",
"org.hamcrest.beans.PropertyUtil",
"org.hamcrest.beans.SamePropertyValuesAs$PropertyMatcher",
"org.hamcrest.core.SubstringMatcher",
"org.hamcrest.core.StringStartsWith",
"org.mockito.exceptions.verification.NeverWantedButInvoked",
"org.hamcrest.beans.HasPropertyWithValue$2",
"org.hamcrest.beans.HasPropertyWithValue",
"org.hamcrest.core.StringContains",
"org.hamcrest.core.DescribedAs",
"org.hamcrest.core.StringEndsWith",
"org.hamcrest.text.IsEqualIgnoringCase",
"org.hamcrest.text.StringContainsInOrder",
"org.hamcrest.Condition$NotMatched",
"org.hamcrest.Condition",
"org.hamcrest.beans.HasPropertyWithValue$1",
"org.hamcrest.Description",
"org.hamcrest.internal.SelfDescribingValue",
"org.hamcrest.core.CombinableMatcher$CombinableBothMatcher",
"org.hamcrest.core.CombinableMatcher$CombinableEitherMatcher"
);
}
}
| [
"[email protected]"
]
| |
45e3fedc42fd7cb8ead84ede340f911001b9cb72 | 033e43ea4e596045c088e8b359b22d7c97574ce7 | /src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryTests.java | 61ffed0c8ea02ed0647d3b4bce761851fb38c5df | []
| no_license | zhangwei5095/spring-data-commons | db1d134cb5fa443cad4ffcf371aa49dcdbf1f8e8 | 20950fa9762ec604c8b89f22d18de4ac89f6a355 | refs/heads/master | 2021-01-09T09:01:37.543016 | 2016-09-21T02:59:06 | 2016-09-21T02:59:06 | 27,736,216 | 0 | 0 | null | 2016-09-21T02:59:06 | 2014-12-08T21:30:52 | Java | UTF-8 | Java | false | false | 13,172 | java | /*
* Copyright 2016 the original author or authors.
*
* 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.springframework.data.mapping.model;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.*;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.annotation.AccessType.Type;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.context.SampleMappingContext;
import org.springframework.data.mapping.context.SamplePersistentProperty;
import org.springframework.data.mapping.model.subpackage.TypeInOtherPackage;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit tests for {@link ClassGeneratingPropertyAccessorFactory}
*
* @author Mark Paluch
* @see DATACMNS-809
*/
@RunWith(Parameterized.class)
public class ClassGeneratingPropertyAccessorFactoryTests {
private final ClassGeneratingPropertyAccessorFactory factory = new ClassGeneratingPropertyAccessorFactory();
private final SampleMappingContext mappingContext = new SampleMappingContext();
private final Object bean;
private final String propertyName;
private final Class<?> expectedConstructorType;
public ClassGeneratingPropertyAccessorFactoryTests(Object bean, String propertyName, Class<?> expectedConstructorType,
String displayName) {
this.bean = bean;
this.propertyName = propertyName;
this.expectedConstructorType = expectedConstructorType;
}
@Parameters(name = "{3}")
public static List<Object[]> parameters() {
List<Object[]> parameters = new ArrayList<Object[]>();
List<String> propertyNames = Arrays.asList("privateField", "packageDefaultField", "protectedField", "publicField",
"privateProperty", "packageDefaultProperty", "protectedProperty", "publicProperty", "syntheticProperty");
parameters.addAll(parameters(new InnerPrivateType(), propertyNames, Object.class));
parameters.addAll(parameters(new InnerTypeWithPrivateAncesor(), propertyNames, InnerTypeWithPrivateAncesor.class));
parameters.addAll(parameters(new InnerPackageDefaultType(), propertyNames, InnerPackageDefaultType.class));
parameters.addAll(parameters(new InnerProtectedType(), propertyNames, InnerProtectedType.class));
parameters.addAll(parameters(new InnerPublicType(), propertyNames, InnerPublicType.class));
parameters.addAll(parameters(new ClassGeneratingPropertyAccessorPackageDefaultType(), propertyNames,
ClassGeneratingPropertyAccessorPackageDefaultType.class));
parameters.addAll(parameters(new ClassGeneratingPropertyAccessorPublicType(), propertyNames,
ClassGeneratingPropertyAccessorPublicType.class));
parameters.addAll(parameters(new SubtypeOfTypeInOtherPackage(), propertyNames, SubtypeOfTypeInOtherPackage.class));
return parameters;
}
private static List<Object[]> parameters(Object bean, List<String> propertyNames, Class<?> expectedConstructorType) {
List<Object[]> parameters = new ArrayList<Object[]>();
for (String propertyName : propertyNames) {
parameters.add(new Object[] { bean, propertyName, expectedConstructorType,
bean.getClass().getSimpleName() + "/" + propertyName });
}
return parameters;
}
/**
* @see DATACMNS-809
* @throws Exception
*/
@Test
public void shouldSetAndGetProperty() throws Exception {
PersistentProperty<?> property = getProperty(bean, propertyName);
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
persistentPropertyAccessor.setProperty(property, "value");
assertThat(persistentPropertyAccessor.getProperty(property), is(equalTo((Object) "value")));
}
/**
* @see DATACMNS-809
* @throws Exception
*/
@Test
@SuppressWarnings("rawtypes")
public void accessorShouldDeclareConstructor() throws Exception {
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
Constructor<?>[] declaredConstructors = persistentPropertyAccessor.getClass().getDeclaredConstructors();
assertThat(declaredConstructors.length, is(1));
assertThat(declaredConstructors[0].getParameterTypes().length, is(1));
assertThat(declaredConstructors[0].getParameterTypes()[0], is(equalTo((Class) expectedConstructorType)));
}
/**
* @see DATACMNS-809
*/
@Test(expected = IllegalArgumentException.class)
public void shouldFailOnNullBean() {
factory.getPropertyAccessor(mappingContext.getPersistentEntity(bean.getClass()), null);
}
/**
* @see DATACMNS-809
*/
@Test(expected = UnsupportedOperationException.class)
public void getPropertyShouldFailOnUnhandledProperty() {
PersistentProperty<?> property = getProperty(new Dummy(), "dummy");
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
persistentPropertyAccessor.getProperty(property);
}
/**
* @see DATACMNS-809
*/
@Test(expected = UnsupportedOperationException.class)
public void setPropertyShouldFailOnUnhandledProperty() {
PersistentProperty<?> property = getProperty(new Dummy(), "dummy");
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
persistentPropertyAccessor.setProperty(property, null);
}
/**
* @see DATACMNS-809
*/
@Test
public void shouldUseClassPropertyAccessorFactory() throws Exception {
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
.getPersistentEntity(bean.getClass());
assertThat(ReflectionTestUtils.getField(persistentEntity, "propertyAccessorFactory"),
is(instanceOf(ClassGeneratingPropertyAccessorFactory.class)));
}
private PersistentPropertyAccessor getPersistentPropertyAccessor(Object bean) {
return factory.getPropertyAccessor(mappingContext.getPersistentEntity(bean.getClass()), bean);
}
private PersistentProperty<?> getProperty(Object bean, String name) {
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
.getPersistentEntity(bean.getClass());
return persistentEntity.getPersistentProperty(name);
}
/**
* @see DATACMNS-809
*/
@SuppressWarnings("unused")
private static class InnerPrivateType {
private String privateField;
String packageDefaultField;
protected String protectedField;
public String publicField;
private String backing;
@AccessType(Type.PROPERTY) private String privateProperty;
@AccessType(Type.PROPERTY) private String packageDefaultProperty;
@AccessType(Type.PROPERTY) private String protectedProperty;
@AccessType(Type.PROPERTY) private String publicProperty;
private String getPrivateProperty() {
return privateProperty;
}
private void setPrivateProperty(String privateProperty) {
this.privateProperty = privateProperty;
}
String getPackageDefaultProperty() {
return packageDefaultProperty;
}
void setPackageDefaultProperty(String packageDefaultProperty) {
this.packageDefaultProperty = packageDefaultProperty;
}
protected String getProtectedProperty() {
return protectedProperty;
}
protected void setProtectedProperty(String protectedProperty) {
this.protectedProperty = protectedProperty;
}
public String getPublicProperty() {
return publicProperty;
}
public void setPublicProperty(String publicProperty) {
this.publicProperty = publicProperty;
}
@AccessType(Type.PROPERTY)
public String getSyntheticProperty() {
return backing;
}
public void setSyntheticProperty(String syntheticProperty) {
backing = syntheticProperty;
}
}
/**
* @see DATACMNS-809
*/
public static class InnerTypeWithPrivateAncesor extends InnerPrivateType {
}
/**
* @see DATACMNS-809
*/
@SuppressWarnings("unused")
static class InnerPackageDefaultType {
private String privateField;
String packageDefaultField;
protected String protectedField;
public String publicField;
private String backing;
@AccessType(Type.PROPERTY) private String privateProperty;
@AccessType(Type.PROPERTY) private String packageDefaultProperty;
@AccessType(Type.PROPERTY) private String protectedProperty;
@AccessType(Type.PROPERTY) private String publicProperty;
private String getPrivateProperty() {
return privateProperty;
}
private void setPrivateProperty(String privateProperty) {
this.privateProperty = privateProperty;
}
String getPackageDefaultProperty() {
return packageDefaultProperty;
}
void setPackageDefaultProperty(String packageDefaultProperty) {
this.packageDefaultProperty = packageDefaultProperty;
}
protected String getProtectedProperty() {
return protectedProperty;
}
protected void setProtectedProperty(String protectedProperty) {
this.protectedProperty = protectedProperty;
}
public String getPublicProperty() {
return publicProperty;
}
public void setPublicProperty(String publicProperty) {
this.publicProperty = publicProperty;
}
@AccessType(Type.PROPERTY)
public String getSyntheticProperty() {
return backing;
}
public void setSyntheticProperty(String syntheticProperty) {
backing = syntheticProperty;
}
}
/**
* @see DATACMNS-809
*/
@SuppressWarnings("unused")
protected static class InnerProtectedType {
private String privateField;
String packageDefaultField;
protected String protectedField;
public String publicField;
private String backing;
@AccessType(Type.PROPERTY) private String privateProperty;
@AccessType(Type.PROPERTY) private String packageDefaultProperty;
@AccessType(Type.PROPERTY) private String protectedProperty;
@AccessType(Type.PROPERTY) private String publicProperty;
private String getPrivateProperty() {
return privateProperty;
}
private void setPrivateProperty(String privateProperty) {
this.privateProperty = privateProperty;
}
String getPackageDefaultProperty() {
return packageDefaultProperty;
}
void setPackageDefaultProperty(String packageDefaultProperty) {
this.packageDefaultProperty = packageDefaultProperty;
}
protected String getProtectedProperty() {
return protectedProperty;
}
protected void setProtectedProperty(String protectedProperty) {
this.protectedProperty = protectedProperty;
}
public String getPublicProperty() {
return publicProperty;
}
public void setPublicProperty(String publicProperty) {
this.publicProperty = publicProperty;
}
@AccessType(Type.PROPERTY)
public String getSyntheticProperty() {
return backing;
}
public void setSyntheticProperty(String syntheticProperty) {
backing = syntheticProperty;
}
}
/**
* @see DATACMNS-809
*/
@SuppressWarnings("unused")
public static class InnerPublicType {
private String privateField;
String packageDefaultField;
protected String protectedField;
public String publicField;
private String backing;
@AccessType(Type.PROPERTY) private String privateProperty;
@AccessType(Type.PROPERTY) private String packageDefaultProperty;
@AccessType(Type.PROPERTY) private String protectedProperty;
@AccessType(Type.PROPERTY) private String publicProperty;
private String getPrivateProperty() {
return privateProperty;
}
private void setPrivateProperty(String privateProperty) {
this.privateProperty = privateProperty;
}
String getPackageDefaultProperty() {
return packageDefaultProperty;
}
void setPackageDefaultProperty(String packageDefaultProperty) {
this.packageDefaultProperty = packageDefaultProperty;
}
protected String getProtectedProperty() {
return protectedProperty;
}
protected void setProtectedProperty(String protectedProperty) {
this.protectedProperty = protectedProperty;
}
public String getPublicProperty() {
return publicProperty;
}
public void setPublicProperty(String publicProperty) {
this.publicProperty = publicProperty;
}
@AccessType(Type.PROPERTY)
public String getSyntheticProperty() {
return backing;
}
public void setSyntheticProperty(String syntheticProperty) {
backing = syntheticProperty;
}
}
public static class SubtypeOfTypeInOtherPackage extends TypeInOtherPackage {}
/**
* @see DATACMNS-809
*/
@SuppressWarnings("unused")
private static class Dummy {
private String dummy;
public String publicField;
}
}
| [
"[email protected]"
]
| |
c788e1691b0f78c5eaf035861a6fb25ad8e3b6dd | a63d261c59ac4e66e20313a8837f22fac3cd0855 | /src/cn/edu/xmu/servlet/Sec_AddGraduateAndDoctoralServlet.java | 4a9f29da85e87457305ae5cef77feb56682742fc | []
| no_license | Guosmilesmile/iqa | 9a7d54a3192b0e4634b9a0f268c106b9cbf1f07d | db7935120911396818146eeadb1ac4da095e0ffb | refs/heads/master | 2021-01-20T17:46:31.076475 | 2016-08-21T08:46:25 | 2016-08-21T08:46:25 | 65,795,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,341 | java | package cn.edu.xmu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
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.JSONException;
import org.json.JSONObject;
import cn.edu.xmu.dao.GraduateAndDoctoralDao;
import cn.edu.xmu.daoimpl.GraduateAndDoctoralDaoImpl;
import cn.edu.xmu.entity.GraduateAndDoctoral;
import cn.edu.xmu.table.GraduateAndDoctoralTable;
/**
* 表4-1-3 博士点、硕士点 (时点)
* @author yue
*
*/
@WebServlet("/Sec_AddGraduateAndDoctoralServlet")
public class Sec_AddGraduateAndDoctoralServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Sec_AddGraduateAndDoctoralServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;Charset=UTF-8");
PrintWriter out = response.getWriter();
String data = request.getParameter("rowdata");
int serialnumber = Integer.parseInt(request.getParameter("serialnumber"));
String college = request.getParameter("gd_college");
//解码
college = URLDecoder.decode(college,"UTF-8");
data = URLDecoder.decode(data,"UTF-8");
data = data.substring(1, data.length()-1);
try {
JSONObject json = new JSONObject(data);
String gd_name = json.getString(GraduateAndDoctoralTable.GD_NAME);
String gd_code = json.getString(GraduateAndDoctoralTable.GD_CODE);
String gd_departmentname = json.getString(GraduateAndDoctoralTable.GD_DEPARTMENTNAME);
String gd_departmentnumber = json.getString( GraduateAndDoctoralTable.GD_DEPARTMENTNUMBER);
String gd_type = json.getString(GraduateAndDoctoralTable.GD_TYPE);
//添加修改点击保存的时候需要判断,0表示完整,1表示缺失
int isnull = 0;
if(gd_name.equals("")||gd_code.equals("")||gd_departmentname.equals("")||gd_departmentnumber.equals("")||
gd_type.equals(""))
isnull = 1;
if(gd_name.equals("")&&gd_code.equals("")&&gd_departmentname.equals("")&&gd_departmentnumber.equals("")&&
gd_type.equals(""))
{
out.println(false);
return;
}
int gd_serialnumber = serialnumber;
String gd_college = college;
String gd_comments = "";
GraduateAndDoctoral gd = new GraduateAndDoctoral( gd_name, gd_code, gd_departmentname,
gd_departmentnumber, gd_type, gd_serialnumber, gd_college, gd_comments,isnull);
GraduateAndDoctoralDao gdDao = new GraduateAndDoctoralDaoImpl();
gdDao.addGraduateAndDoctoralRecord(gd);
out.print(true);
} catch (JSONException e) {
e.printStackTrace();
}finally{
out.close();
}
}
}
| [
"[email protected]"
]
| |
386f8e2eb66228e6e1cf41552bffae3166c5d011 | 23e765af8963076380fd0ce75a770182907da064 | /MMCJPA/src/main/java/com/mountainmusicco/music/entities/Employee.java | b47b5d465b235a00123be86f568c978f2367dfc6 | []
| no_license | braidenm/mmc | ab0e97cfe968d8936a59058048d7023246b5c0f2 | 597840462130698f07334df4c7a8602533b1c649 | refs/heads/master | 2023-01-19T17:15:04.037792 | 2020-01-17T03:57:10 | 2020-01-17T03:57:10 | 180,888,101 | 0 | 0 | null | 2023-01-07T07:42:40 | 2019-04-11T22:33:37 | JavaScript | UTF-8 | Java | false | false | 3,152 | java | package com.mountainmusicco.music.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class Employee {
// F E I L D S
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
@Column(name="pay_rate")
private double payRate;
private String email;
@ManyToOne
private Address address;
@OneToOne
@JoinColumn(name="user_id")
private User user;
@OneToMany(mappedBy = "employee")
private List<EmployeeNote> employeeNotes;
@ManyToMany(mappedBy = "employees")
private List<Event> events;
// C O N S T R U C T O R S
public Employee(int id, String title, double payRate, String email, Address address, User user) {
super();
this.id = id;
this.title = title;
this.payRate = payRate;
this.email = email;
this.address = address;
this.user = user;
}
public Employee() {
super();
}
// G E T T E R S / S E T T E R S
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPayRate() {
return payRate;
}
public void setPayRate(double payRate) {
this.payRate = payRate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<EmployeeNote> getNotes() {
return employeeNotes;
}
public void setNotes(List<EmployeeNote> notes) {
this.employeeNotes = notes;
}
// H A S H C O D E / E Q U A L S
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
return true;
}
// T O S T R I N G
@Override
public String toString() {
return user + "-" + title;
}
// M E T H O D S
public Event addEvent(Event event) {
if (events == null) {
events = new ArrayList<Event>();
}
if (!events.contains(event)) {
events.add(event);
event.addEmployee(this);
}
return event;
}
public Event removeEvent(Event event) {
if (events != null && events.contains(event)) {
events.remove(event);
event.removeEmployee(this);
}
return event;
}
}
| [
"[email protected]"
]
| |
4ade1fe6a7ad3a4a52ebaf6fbffc8b2482a520f4 | 478f182325fba6a3e45cdaa473c5512988f73dea | /carparking/src/test/java/com/spring/project/carparking/CarparkingApplicationTests.java | dc86690921e1e680782ff250525ee1d14ac80d43 | []
| no_license | sreeharsha111/carparking | 45f3026951492cf98be14b7b360e2fabf1676b6c | 6758ca9259c69210252a5f754e37aa6b15bf11ff | refs/heads/master | 2021-02-10T00:51:12.965164 | 2020-03-02T10:18:13 | 2020-03-02T10:18:13 | 244,339,760 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 225 | java | package com.spring.project.carparking;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CarparkingApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
]
| |
30c135936553719a2aba5493a9336aba3d92046f | e87c9128fee85472de0142e4b350c9a605be98ac | /blitz-service/src/main/java/org/dancres/blitz/txn/TimeBarrierPersonality.java | 6410224012469f505f52422721914e88322ec0dc | []
| no_license | sorcersoft/blitz-javaspaces-modularised | d82b7f2ab45d421cf0782df87afa4b496aa3b162 | 65d09f78d48335346379873a25ddc126e955c955 | refs/heads/master | 2021-01-15T22:56:46.851052 | 2014-03-14T10:39:49 | 2014-03-14T10:39:49 | 11,525,405 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,366 | java | package org.dancres.blitz.txn;
import java.util.logging.Level;
import org.prevayler.implementation.SnapshotPrevayler;
import org.prevayler.implementation.BufferingPrevaylerImpl;
import org.prevayler.PrevalentSystem;
import org.dancres.blitz.config.TimeBarrierPersistent;
import org.dancres.blitz.disk.Disk;
/**
Understands how to translate TimeBarrierPersistent into core component
configuration.
@see org.dancres.blitz.config.TimeBarrierPersistent
*/
class TimeBarrierPersonality implements StoragePersonality {
private TimeBarrierPersistent theModel;
private String theLogDir;
TimeBarrierPersonality(TimeBarrierPersistent aModel, String aLogDir) {
theModel = aModel;
theLogDir = aLogDir;
TxnManager.theLogger.log(Level.INFO, "TimeBarrierPersonality");
TxnManager.theLogger.log(Level.INFO, "Max logs before sync: " +
theModel.getMaxLogsBeforeSync());
TxnManager.theLogger.log(Level.INFO, "Reset log stream: " +
theModel.shouldResetLogStream());
if (theModel.shouldCleanLogs()) {
TxnManager.theLogger.log(Level.WARNING,
"*** Automatically cleaning logs *** [EXPERIMENTAL]");
}
Disk.init();
}
public CheckpointTrigger getCheckpointTrigger(Checkpointer aCheckpointer) {
/*
return
new OpCountingCheckpointTrigger(aCheckpointer,
theModel.getMaxLogsBeforeSync());
*/
return
new TimeoutCheckpointTrigger(aCheckpointer,
theModel.getMaxLogsBeforeSync(), theModel.getFlushTime());
}
public SnapshotPrevayler getPrevayler(PrevalentSystem aSystem)
throws Exception {
PersistentReboot myReboot = new PersistentReboot(theModel);
myReboot.execute();
SnapshotPrevayler myPrevayler =
new BufferingPrevaylerImpl(aSystem, theLogDir,
theModel.shouldResetLogStream(),
theModel.shouldCleanLogs(),
theModel.getLogBufferSize());
return myPrevayler;
}
public void destroy() {
Disk.destroy();
Disk.clean(theLogDir);
}
}
| [
"[email protected]"
]
| |
8aaff40480fbcab36f12e81a7eb27d7a141d8595 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_709abf417947d89ef419d1412dfee997cd98a8ed/ProductListActivity/2_709abf417947d89ef419d1412dfee997cd98a8ed_ProductListActivity_t.java | 33274e0548e3c2b447b9d27ced8fd685411ab450 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 2,449 | java | package com.grupo3.productConsult.activities;
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.grupo3.productConsult.Category;
import com.grupo3.productConsult.CategoryManager;
import com.grupo3.productConsult.Product;
import com.grupo3.productConsult.R;
import com.grupo3.productConsult.services.CategoriesSearchService;
public class ProductListActivity extends ListActivity {
private List<Product> currList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] products = getProductNames();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
products));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent newIntent = new Intent(ProductListActivity.this
.getApplicationContext(), ProductDisplayActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("product", currList.get(position));
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
});
}
private String[] getProductNames() {
Bundle recdData = getIntent().getExtras();
int catPos = Integer.parseInt(recdData.getString("categoryPos"));
int subCatPos = Integer.parseInt(recdData.getString("subCategoryPos"));
CategoryManager catManager;
try {
catManager = CategoryManager.getInstance();
Category slectedCat = catManager.getCategoryList().get(catPos);
int catId = slectedCat.getId();
int subCatId = slectedCat.getSubCategories().get(subCatPos).getId();
currList = CategoriesSearchService.fetchProductsBySubcategory(
catId, subCatId);
String[] names = new String[currList.size()];
int i = 0;
for (Product c : currList) {
names[i++] = c.getName() + " " + Product.CURRENCY + " "
+ c.getPrice();
}
return names;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
}
| [
"[email protected]"
]
| |
df92b70863c045fce22b668260ae3ec2c425ddcb | abaf0add8f99452d8ef2f042acb36fd9408741b1 | /app/src/main/java/com/yoryky/safeeye/utils/SharePreferencesUtils.java | 3e0b6dfd2b87320dffec23ddb5b8892564e74e97 | []
| no_license | Yoryky/SafeEye | cb3666b05304f0f7055a350ad1c0d945387ca329 | 2f34f7788065ddd471f816a618efdaa752a21a4c | refs/heads/master | 2020-03-31T05:32:48.067073 | 2018-10-07T15:17:18 | 2018-10-07T15:17:18 | 151,949,830 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,101 | java | package com.yoryky.safeeye.utils;
import android.content.Context;
import android.content.SharedPreferences;
public class SharePreferencesUtils {
//定义一个SharePreference对象
SharedPreferences sharedPreferences;
//定义一个上下文对象
//创建SharePreference对象时要上下文和存储的模式
//通过构造方法传入一个上下文
public SharePreferencesUtils(Context context, String fileName) {
//实例化SharePreference对象,使用的是get方法,而不是new创建
//第一个参数是文件的名字
//第二个参数是存储的模式,一般都是使用私有方式:Context.MODE_PRIVATE
sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
}
/**
* 存储数据
* 这里要对存储的数据进行判断在存储
* 只能存储简单的几种数据
* 这里使用的是自定义的ContentValue类,来进行对多个数据的处理
*/
//创建一个内部类使用,里面有key和value这两个值
public static class ContentValue {
String key;
Object value;
//通过构造方法来传入key和value
public ContentValue(String key, Object value) {
this.key = key;
this.value = value;
}
}
//一次可以传入多个ContentValue对象的值
public void putValues(ContentValue... contentValues) {
//获取SharePreference对象的编辑对象,才能进行数据的存储
SharedPreferences.Editor editor = sharedPreferences.edit();
//数据分类和存储
for (ContentValue contentValue : contentValues) {
//如果是字符型类型
if (contentValue.value instanceof String) {
editor.putString(contentValue.key, contentValue.value.toString()).commit();
}
//如果是int类型
if (contentValue.value instanceof Integer) {
editor.putInt(contentValue.key, Integer.parseInt(contentValue.value.toString())).commit();
}
//如果是Long类型
if (contentValue.value instanceof Long) {
editor.putLong(contentValue.key, Long.parseLong(contentValue.value.toString())).commit();
}
//如果是布尔类型
if (contentValue.value instanceof Boolean) {
editor.putBoolean(contentValue.key, Boolean.parseBoolean(contentValue.value.toString())).commit();
}
}
}
//获取数据的方法
public String getString(String key) {
return sharedPreferences.getString(key, null);
}
public boolean getBoolean(String key) {
return sharedPreferences.getBoolean(key, false);
}
public int getInt(String key) {
return sharedPreferences.getInt(key, -1);
}
public long getLong(String key) {
return sharedPreferences.getLong(key, -1);
}
//清除当前文件的所有的数据
public void clear() {
sharedPreferences.edit().clear().commit();
}
}
| [
"[email protected]"
]
| |
a0038552ba31d28e3de763bc798f3ba3a542de0e | 0cd0cb67b8ada15ae2b71d2c13375141a5ebc130 | /src/main/java/com/cloudwarriors/containercrush/vo/DataModelVo.java | 31e9f3af03384961404ae178d8aabaa213441b80 | [
"Apache-2.0"
]
| permissive | kishorece/ContainerCrush | 5baf38ff4c9672a159179aa945cdaa85e3c2ea16 | a5fa9e22bc67cdf7d0cefc9a03e1e1446d4f08b0 | refs/heads/master | 2020-09-24T06:05:37.077683 | 2019-12-22T07:21:53 | 2019-12-22T07:21:53 | 225,683,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 575 | java | package com.cloudwarriors.containercrush.vo;
import com.cloudwarriors.containercrush.datamodels.ProductCatalog;
import com.cloudwarriors.containercrush.datamodels.ProductPricing;
import com.cloudwarriors.containercrush.datamodels.ProductSku;
import com.cloudwarriors.containercrush.datamodels.ProductStyle;
import lombok.Data;
@Data
public class DataModelVo {
ProductCatalog productCatalog = new ProductCatalog();
ProductPricing productPricing = new ProductPricing();
ProductSku productSku = new ProductSku();
ProductStyle productStyle = new ProductStyle();
}
| [
"[email protected]"
]
| |
042d5eb30451eb6669a3943ca25aa46d01b1a9ae | f00df5ef0d5a848bf442a8b281235483d25daf68 | /src/behavioral/chainofresponsibility/CheckAgeImpl.java | 929bcb7fc97a4cc98fac60eb42d9b49577654116 | []
| no_license | adolphofjun/designPattern | 13e5e8eea9bd2e03b6866a937c09e1400ab6484c | b2d46e8566d4beab4af55bbc04eef3445ccf102d | refs/heads/master | 2021-01-08T22:48:10.728917 | 2020-03-10T14:57:28 | 2020-03-10T14:57:28 | 242,165,788 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 273 | java | package behavioral.chainofresponsibility;
public class CheckAgeImpl extends AbsInfoCheck {
public CheckAgeImpl(){
this.type = AbsInfoCheck.checkAge;
}
@Override
void printResult() {
System.out.println("=========" + this.type);
}
}
| [
"[email protected]"
]
| |
682cf09abeda0378694cc456d94349f3218671b2 | 7455e550c5be42aadc9ff993ec969033b30f7839 | /Assignments/Module 19/19.1 BST/Solution.java | 3c0265d9508f2964b877daeb084fe778f9e82204 | []
| no_license | Gayatri-Prathyusha/ADS-1 | 319c50b9d03f049f24da42aa5bfacff54e66d7e6 | 2a83932cafd0f966f7e84dcd3a2dabd74321202b | refs/heads/master | 2020-03-29T17:21:25.350756 | 2018-10-27T08:23:51 | 2018-10-27T08:23:51 | 150,157,383 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,143 | java | import java.util.Scanner;
/**
* client program.
*/
public final class Solution {
/**
* Constructs the object.
*/
private Solution() {
//unused constructor.
}
/**
* main method.
*
* @param args The arguments
*/
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
BinarySearchTree binaryobject = new BinarySearchTree();
while (sc.hasNext()) {
String[] tokens = sc.nextLine().split(",");
switch (tokens[0]) {
case "put":
BookDetails detailsobject = new BookDetails(tokens[1],
tokens[2], Float.parseFloat(tokens[2 + 1]));
binaryobject.put(detailsobject, Integer.parseInt(tokens[2 + 2]));
break;
case "get":
detailsobject = new BookDetails(tokens[1], tokens[2],
Float.parseFloat(tokens[2 + 1]));
if (binaryobject.get(detailsobject) == -1) {
System.out.println("null");
} else {
System.out.println(binaryobject.get(detailsobject));
}
break;
case "max":
System.out.println(binaryobject.max());
break;
case "min":
System.out.println(binaryobject.min());
break;
case "select":
System.out.println(binaryobject.select(Integer.parseInt(tokens[1])));
break;
case "floor":
detailsobject = new BookDetails(tokens[1],
tokens[2], Float.parseFloat(tokens[2 + 1]));
System.out.println(binaryobject.floor(detailsobject));
break;
case "ceiling":
detailsobject = new BookDetails(tokens[1],
tokens[2], Float.parseFloat(tokens[2 + 1]));
System.out.println(binaryobject.ceiling(detailsobject));
break;
default:
break;
}
}
}
}
| [
"[email protected]"
]
| |
c1488ac9ea928bb711573c21791e59aedb11f0f8 | e50a38b272dde071966969cadab9d50818d1d962 | /wechat-offiaccount/src/main/java/xyz/xcyd/wechat/offiaccount/handler/LogHandler.java | d75eb94bb711aedd68fdf6b2c1bbb2ecd831aff8 | []
| no_license | yzengchn/wechat | 21c21ec6e7085f143e43a42ca1e699a5b4b6248d | 5b9d46874d1eb03946655c36591dfb4a372ec51e | refs/heads/main | 2023-07-06T00:33:25.460403 | 2021-08-10T09:56:52 | 2021-08-10T09:56:52 | 157,679,959 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 859 | java | package xyz.xcyd.wechat.offiaccount.handler;
import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author Binary Wang(https://github.com/binarywang)
*/
@Component
public class LogHandler extends AbstractHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map<String, Object> context, WxMpService wxMpService,
WxSessionManager sessionManager) {
this.logger.info("\n接收到请求消息,内容:{}", JSONUtil.toJsonStr(wxMessage));
return null;
}
}
| [
"[email protected]"
]
| |
cb00dbb81ac36338772d025bc947c042bcabea10 | 00760ce37752d368b37add08bf2d128ce0b08b9e | /android/app/src/main/java/com/time_keeper_26759/MainActivity.java | 96af3cb08caa249f2b7053e38b5966806b32e63a | []
| no_license | crowdbotics-apps/time-keeper-26759 | b21c97fa1aa7350a8db7d977bb3a796ea2c9f5e7 | fb6854f69e7b9412d06258f72f6952e0effdbaf2 | refs/heads/master | 2023-04-25T08:56:34.123963 | 2021-05-16T21:34:30 | 2021-05-16T21:34:30 | 367,989,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 361 | java | package com.time_keeper_26759;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "time_keeper_26759";
}
}
| [
"[email protected]"
]
| |
e289c2dc5022018fa6db34d889157f7a9ca78b9e | f9e6650ddd490e02ec77ecddd3897460856d6541 | /src/main/java/me/libelula/libelulalogger/Commands.java | d71c3143ca6a7da04efe72fc114d8fa37948e9ea | []
| no_license | Noraaron1/Test | 18dac5d85dd831a41d0a6d8a7b14fcb52ee463e4 | cfd43fc8c15c8d9485a1c7b33349c87174a92d47 | refs/heads/master | 2020-05-30T10:44:15.246734 | 2013-11-29T20:45:43 | 2013-11-29T20:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,246 | java | /*
* This file is part of Libelula Logger plugin.
*
* Libelula Logger is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Libelula Logger is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Libelula Logger. If not, see <http://www.gnu.org/licenses/>.
*
*/
package me.libelula.libelulalogger;
import com.sk89q.worldedit.bukkit.selections.Selection;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Class Commands of the plugin.
*
* @author Diego Lucio D'Onofrio <[email protected]>
* @version 1.0
*/
public class Commands implements CommandExecutor {
private final LibelulaLogger plugin;
public Commands(LibelulaLogger plugin) {
this.plugin = plugin;
}
public void registerCommands() {
plugin.getCommand("libelulalogger").setExecutor(this);
plugin.getCommand("whomadethis").setExecutor(this);
plugin.getCommand("/whoeditedthisarea").setExecutor(this);
plugin.getCommand("whoeditedthisarea").setExecutor(this);
plugin.getCommand("blockrestore").setExecutor(this);
plugin.getCommand("undoedited").setExecutor(this);
plugin.getCommand("/undoedited").setExecutor(this);
plugin.getCommand("redoedited").setExecutor(this);
plugin.getCommand("/redoedited").setExecutor(this);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String string, String[] args) {
if (!(sender instanceof Player)) {
if (!command.getName().equals("libelulalogger")) {
sender.sendMessage("This command must be used by a player in game.");
return true;
}
}
switch (command.getName()) {
case "libelulalogger":
if (args.length == 0) {
sender.sendMessage(plugin.getPluginFullDescription());
sender.sendMessage("Posible commands are:");
sender.sendMessage(ChatColor.GREEN + "/ll config" + ChatColor.RESET + " - List configuration keys.");
sender.sendMessage(ChatColor.GREEN + "/whomadethis" + ChatColor.RESET + " - Activates the block by block Discovery Tool.");
sender.sendMessage(ChatColor.GREEN + "/blockrestore " + ChatColor.RESET + " - Activates the block by block restore tool.");
sender.sendMessage(ChatColor.GREEN + "/whoeditedthisarea [radius]" + ChatColor.RESET + " - Shows who edited current area.");
sender.sendMessage(ChatColor.GREEN + "//whoeditedthisarea " + ChatColor.RESET + " - The same but with a WE selection.");
sender.sendMessage(ChatColor.GREEN + "/undoedited [playername] [radius]" + ChatColor.RESET + " - Undo given player editions from current area.");
sender.sendMessage(ChatColor.GREEN + "//undoedited [playername]" + ChatColor.RESET + " - The same but with a WE selection.");
sender.sendMessage(ChatColor.GREEN + "/redoedited [playername] [radius]" + ChatColor.RESET + " - Redo given player editions from current area.");
sender.sendMessage(ChatColor.GREEN + "//redoedited [playername]" + ChatColor.RESET + " - The same but with a WE selection.");
return true;
} else if (args.length == 1 && args[0].equalsIgnoreCase("version")) {
sender.sendMessage(plugin.getPluginFullDescription());
return true;
}
switch (args[0].toLowerCase()) {
case "config":
processLibelulaConfigCommand(sender, args);
return true;
case "reload":
if (args.length == 1) {
plugin.config.reload();
sender.sendMessage(ChatColor.GREEN + "Configuration reloaded.");
return true;
}
break;
default:
break;
}
break;
case "whomadethis":
if (args.length == 0) {
plugin.toolbox.giveDiscoveryTool((Player) sender);
return true;
}
break;
case "/whoeditedthisarea":
return processWhoEditedThisAreaCmd(args, sender);
case "whoeditedthisarea":
return processWhoEditedThisAreaByRadCmd(args, sender);
case "blockrestore":
if (args.length == 0) {
if (sender instanceof Player) {
plugin.toolbox.giveRestoreTool((Player) sender);
} else {
sender.sendMessage("This command must be used by a player in game.");
}
return true;
}
break;
case "undoedited":
return processEditedByRadiusCmd(args, sender, true);
case "/undoedited":
return processEditedCmd(args, sender, true);
case "redoedited":
return processEditedByRadiusCmd(args, sender, false);
case "/redoedited":
return processEditedCmd(args, sender, false);
default:
throw new NotImplementedException();
}
return false;
}
void processLibelulaConfigCommand(CommandSender sender, String[] args) {
if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("list"))) {
for (String configLine : plugin.config.toString().split("\\|")) {
sender.sendMessage(ChatColor.GREEN + configLine);
}
return;
}
switch (args[1].toLowerCase()) {
case "reload":
if (args.length == 2) {
plugin.config.reload();
return;
}
case "set":
if (args.length > 3) {
String value = args[3];
for (int i = 4; i < args.length; i++) {
value = value.concat(",").concat(args[i]);
}
plugin.config.setValue(args[2], value, sender);
return;
}
case "del":
if (args.length == 3) {
plugin.config.delValue(args[2], sender);
return;
}
}
sender.sendMessage(ChatColor.RED + "Incorrect usage of the config command.");
}
private boolean validateArea(int area, CommandSender sender) {
if (area <= 4000000) {
sender.sendMessage(ChatColor.AQUA + "Quering for " + area + " selected blocks...");
} else {
sender.sendMessage(ChatColor.RED + "You tried to query for " + area + " selected blocks...");
sender.sendMessage(ChatColor.RED + "Current maximum max amount is configured to 4 millons, please perform multiple queries.");
return false;
}
if (area > 500000) {
sender.sendMessage(ChatColor.AQUA + "This may take some time, please be patience...");
}
return true;
}
private Selection getWESelection(CommandSender sender) {
if (plugin.we == null) {
sender.sendMessage(ChatColor.RED + "This command must be used with WordlEdit and it is not installed.");
sender.sendMessage(ChatColor.RED + "Instead you can use the radius version of this command by typing it with a single slash.");
return null;
}
Selection selection = plugin.we.getSelection((Player) sender);
if (selection == null) {
sender.sendMessage(ChatColor.RED + "Make a region selection first.");
}
return selection;
}
boolean processWhoEditedThisAreaByRadCmd(String[] args, CommandSender sender) {
int radius;
int area;
if (args.length != 1) {
return false;
}
try {
radius = Integer.parseInt(args[0]);
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "The radius must be a positive integer number.");
return true;
}
if (radius < 1) {
sender.sendMessage(ChatColor.RED + "The value of the radius must be 1 at least.");
}
area = (int) Math.pow(radius, 3);
if (!validateArea(area, sender)) {
return true;
}
Player player = (Player) sender;
plugin.meode.asyncQuerySellection(player.getLocation(), radius, player, null);
return true;
}
boolean processWhoEditedThisAreaCmd(String[] args, CommandSender sender) {
if (args.length == 0) {
Selection selection = getWESelection(sender);
if (selection == null) {
return true;
} else {
if (!validateArea(selection.getArea(), sender)) {
return true;
}
plugin.meode.asyncQuerySellection(selection.getMinimumPoint(),
selection.getMaximumPoint(), (Player) sender, null);
return true;
}
}
return false;
}
boolean processEditedCmd(String[] args, CommandSender sender, boolean undo) {
if (args.length != 1) {
return false;
}
String playerName = args[0];
if (!plugin.getServer().getOfflinePlayer(playerName).hasPlayedBefore()) {
if (plugin.getServer().getPlayer(playerName) == null) {
sender.sendMessage(ChatColor.RED + "The player \"".concat(playerName).concat("\" never played on this server."));
return true;
}
}
Selection selection = getWESelection(sender);
if (selection == null) {
return true;
}
if (!validateArea(selection.getArea(), sender)) {
return true;
}
plugin.meode.asyncEditSellection(selection.getMinimumPoint(),
selection.getMaximumPoint(), (Player) sender, playerName, undo);
return true;
}
private boolean processEditedByRadiusCmd(String[] args, CommandSender sender, boolean undo) {
if (args.length < 2 || args.length > 3) {
return false;
}
String playerName = args[0];
if (!plugin.getServer().getOfflinePlayer(playerName).hasPlayedBefore()) {
if (plugin.getServer().getPlayer(playerName) == null) {
sender.sendMessage(ChatColor.RED + "The player \"".concat(playerName).concat("\" never played on this server."));
return true;
}
}
int radius;
try {
radius = Integer.parseInt(args[1]);
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Use a integer positive number for radius.");
return true;
}
if (radius < 1) {
sender.sendMessage(ChatColor.RED + "You have to specify a radius or use the double slashed command with worldedit selections.");
return true;
}
int area = (int) Math.pow(radius, 3);
if (!validateArea(area, sender)) {
return true;
}
Player player = (Player) sender;
plugin.meode.asyncEditSellection(player.getLocation(), radius, (Player) sender, playerName, undo);
return true;
}
}
| [
"[email protected]"
]
| |
6a650ff1dfd799dc19b9308cd9514df8bbf38f9e | c7359be3c38c940eb393ee8b734802e7c45ec499 | /Launcher3/src/cn/netin/launcher/Workspace.java | 91414f9c406226cff77558206c62829c7d573590 | []
| no_license | jichuangsi/school-desk | 43b087b5331bba402b24b19044637327ce4fcf39 | fd5bd7c5e27e2e9bfa5d1a15952eab5ee99226de | refs/heads/master | 2020-04-16T12:27:33.699575 | 2019-01-29T09:37:10 | 2019-01-29T09:37:10 | 165,580,330 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 23,582 | java | package cn.netin.launcher;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;
/**
* 允许不指定加入的item在哪一屏
*/
public class Workspace extends ViewGroup {
private static final String TAG = "EL Workspace" ;
private Scroller mScroller;
private Paint mPaint;
private Bitmap mWallpaperBitmap = null;
private WorkspaceIndicator mIndicator;
/**生成程序view的inflater*/
private LayoutInflater mInflater;
private WallpaperManager mWallpaperManager;
private final static int SNAP_VELOCITY = 500;
private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
private final static int TOUCH_STATE_AUTOSCROLL = 2 ;
private final static int GAP = 40 ;
private final static int INVALID_SCREEN = -1;
private int mScrollerX = 0;
private int mCurrentScreen = 0;
private int mNextScreen = INVALID_SCREEN;
private int mCurrentDuration ;
private float mDownX ;
private float mLastX ;
private float mMoveDistance ;
private long mLastTime ;
private int mSpeed = 0 ;
private int mTouchState = TOUCH_STATE_REST;
private int mScreenCount = 0 ;
private int mCapacityPerScreen = 0 ;
private int mItemTotal = 0 ;
private boolean mScrollLeft = false ;
private boolean mWallpaperLoaded = false ;
private boolean childrenCacheEnabled = false ;
private boolean mIsScrolling = false ;
public Workspace(Context context) {
super(context);
mWallpaperManager = WallpaperManager.getInstance(context);
mScroller = new Scroller(context);
this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
mPaint = new Paint();
mPaint.setDither(false);
mInflater = LayoutInflater.from(context);//实例化inflater
}
public Workspace(Context context, AttributeSet attrs) {
super(context, attrs);
mWallpaperManager = WallpaperManager.getInstance(context);
mScroller = new Scroller(context);
this.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
//Brent
//TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Workspace);
//mCurrentScreen = a.getInteger(R.styleable.Workspace_defaultScreen, 0);
mPaint = new Paint();
//No dithering is generally faster, but higher precision colors are just truncated down (e.g. 8888 -> 565).
mPaint.setDither(false);
mInflater = LayoutInflater.from(context);//实例化inflater
}
/**
* Set the background's wallpaper.
*/
void loadWallpaper(Bitmap bitmap) {
mWallpaperBitmap = bitmap;
mWallpaperLoaded = true;
//Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree.
requestLayout();
//Invalidate the whole view. If the view is visible, onDraw(Canvas) will be called at some point in the future.
//This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
invalidate();
}
/**
* 判断用户是否在拖动,如果是就让这里的OnTouch处理,否则,让子View处理
onInterceptTouchEvent默认返回值是false,
Layout里 onTouchEvent默认返回值是false,所以只消费了ACTION_DOWN事件,
View里onTouch默认返回值是true, 消费了:ACTION_DOW,ACTION_UP。
1.当onInterceptTouchEvent返回false时,表示没有消费完此事件,会继续传递个子组件的onTouch继续处理。
注意这种情况不会就不会传递给这个ViewGroup自身的onTouch事件处理了。这和onTouch如果返回false,后续的move、up等事件都不会继续处理了可以做同样理解。
2.当onInterceptTouchEvent返回true时,表示消费完此事件,或者说将在此组件上消费该事件。这种情况该事件会传递给ViewGroup自身的onTouch事件去处理,
而不会传递给子组件的onTouch方法了。
onInterceptTouchEvent()说的是是否允许Touch事件继续向下(子控件)传递,一但返回True,则向下传递之路被截断(所有子控件将没有机会参与Touch事件);
onTouchEvent()说的是当前控件在处理完Touch事件后,是否还允许Touch事件继续向上(父控件)传递,一但返回True,则父控件不用操心,由自己来处理Touch事件。
Parameters
* (non-Javadoc)
* @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getChildCount() == 0) {
return true;
}
final int action = ev.getAction();
//如果是ACTION_MOVE,且mTouchState是滚动中
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
//交到自己的onTouch处理
return true;
}
final float currentX = ev.getX();
switch (action) {
case MotionEvent.ACTION_MOVE:
final int xDiff = (int) Math.abs(currentX - mDownX);
//如果拖动足够长的距离,就进入滚动状态
boolean xMoved = xDiff > GAP;
if (xMoved) {
//System.out.println("xxxxxxxxxxxxxxxxx moved " + xDiff + " mTouchSlop=" + mTouchSlop );
mTouchState = TOUCH_STATE_SCROLLING;
}else{
//System.out.println("xxxxxxxxxxxxxxxxx NOT moved " + xDiff + " mTouchSlop=" + mTouchSlop );
}
break;
case MotionEvent.ACTION_DOWN:
handleActionDown(currentX) ;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// 如果抬起或取消,状态为REST
mTouchState = TOUCH_STATE_REST;
break;
}
//如果SCROLLING, 就return true, 在这里处理OnTouch
//如果REST , 就return false, 让子view获得事件
return mTouchState != TOUCH_STATE_REST;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (getChildCount() == 0) {
return true;
}
final float currentX = event.getX();
mScrollerX = this.getScrollX();
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
handleActionDown(currentX) ;
break;
case MotionEvent.ACTION_MOVE:
//移动得慢,TP上报会迟钝,可能移动5px,才上报1px
//deltaX 为本次移动的相对值
float deltaX = currentX - mLastX ;
//累计移动距离
mMoveDistance = deltaX ;
//要够一定的距离,才处理
if (deltaX < - GAP) { //如果向左滑动
mScrollLeft = true ;
//scrollBy((int) -deltaX, 0);
handleMove(currentX) ;
} else if (deltaX > GAP) { ////如果向右滑动
mScrollLeft = false ;
//scrollBy((int) deltaX, 0);
handleMove(currentX) ;
} // end if (deltaX < - GAP) {
break;
case MotionEvent.ACTION_UP:
float movedX = currentX - mDownX;
//判断滑动距离
if (movedX < - GAP) { //如果向左滑动
mScrollLeft = true ;
} else if (movedX > GAP) { ////如果向右滑动
mScrollLeft = false ;
} // end if (deltaX < - GAP) {
//如果速度够大
boolean fastEnougth = mSpeed > SNAP_VELOCITY ;
//如果移动的总距离超过GAP
boolean farEnougth = Math.abs(movedX) > GAP ;
//System.out.println("up speed=" + mSpeed + " mCurrentScreen=" + mCurrentScreen + " mScrollLeft=" + mScrollLeft + " movedX=" + movedX + " event.getX()=" + event.getX());
if (fastEnougth || farEnougth) {
if (mScrollLeft && mCurrentScreen < mScreenCount -1) {
mNextScreen = mCurrentScreen + 1 ;
//System.out.println("page - 1 =" + mNextScreen );
snapToScreen() ;
}
else if (!mScrollLeft && mCurrentScreen > 0 ) {
mNextScreen = mCurrentScreen - 1 ;
//System.out.println("page - 1 =" + mNextScreen);
snapToScreen() ;
}else{
//System.out.println("up speed3=" + mSpeed + " mCurrentScreen=" + mCurrentScreen + " mScrollLeft=" + mScrollLeft);
mNextScreen = mCurrentScreen ;
snapToScreen() ;
}
}else{
//System.out.println("up slow or near Speed=" + mSpeed + " mCurrentScreen=" + mCurrentScreen + " mScrollLeft=" + mScrollLeft);
mNextScreen = mCurrentScreen ;
snapToScreen() ;
}
//将状态设为静止
mTouchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_CANCEL:
//将状态设为静止
mTouchState = TOUCH_STATE_REST;
break;
}
return true;
}
private void handleActionDown(float currentX) {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
mNextScreen = INVALID_SCREEN ;
}
// 记下刚按下的位置
mDownX = currentX ;
mLastX = currentX ;
mLastTime = System.currentTimeMillis() ;
//System.out.println("@@@@@ ACTION_DOWN mDownX=" + mDownX) ;
mMoveDistance = 0 ;
mTouchState = TOUCH_STATE_REST ;
}
/**
* mScrollLeft=true时,手势从右到左, mMoveDistance为负数,且值越来越小,mScrollX为正数,且值越来越大
* mScrollLeft=true时,手势从左到右, mMoveDistance为正数,且值越来越大,mScrollX为负数,且值越来越小
* */
private void handleMove(float currentX) {
long currentTime = System.currentTimeMillis() ;
long timePassed = currentTime - mLastTime ;
if (timePassed < 100) {
timePassed = 100 ;
}
mSpeed = (int ) ( Math.abs(mMoveDistance) * 1000 / timePassed );
//System.out.println("handleMove mMoveDistance=" + mMoveDistance + "mSpeed=" + mSpeed+ " timePassed=" + timePassed) ;
float distance = 0 ;
//如果是按下去之后的第一个Move事件
if (mTouchState != TOUCH_STATE_AUTOSCROLL ) {
mTouchState = TOUCH_STATE_AUTOSCROLL;
int plus = 0 ;
if (mSpeed > 1000) {
plus = 400 ;
mCurrentDuration = 900 ;
}
else if (mSpeed > 500 && mSpeed < 1001) {
plus = 400 ;
mCurrentDuration = 1200 ;
}
else if (mSpeed > 200 && mSpeed < 501) {
plus = 300 ;
mCurrentDuration = 2500 ;
}
else if (mSpeed < 201) {
plus = 200 ;
mCurrentDuration = 3000 ;
}
if (mScrollLeft) {
distance = mMoveDistance - plus ;
}else{
distance = mMoveDistance + plus ;
}
int scrollX = this.getScrollX() ;
//System.out.println("######### FIRST mMoveDistance=" + mMoveDistance + " distance=" + distance + " duration=" + mCurrentDuration
// + " scrollX=" + scrollX + " timePassed=" + timePassed);
enableChildrenCache();
mScroller.startScroll( (int)scrollX, 0, - (int)distance, 0, mCurrentDuration);
mIndicator.show(mCurrentScreen);
mLastTime = currentTime ;
mLastX = currentX ;
mMoveDistance = 0 ;
}else{ //是后继的Move事件
if (timePassed < 800) {
return ;
}
if (Math.abs(mMoveDistance) < 150) {
return ;
}
//是否可以继续滑动
boolean moreToGo ;
if (mScrollLeft) {
moreToGo = mScrollerX < getWidth() * ( mScreenCount - 1) ;
}else{
moreToGo = mScrollerX > 0 ;
}
if (!moreToGo) {
//System.out.println("!!!!!!!!!!!!!!!! no more to go") ;
return ;
}
int plus = 0 ;
if (mSpeed > 500) {
plus = 200 ;
mCurrentDuration = 1800 ;
}
else if (mSpeed > 200 && mSpeed < 501) {
plus = 150 ;
mCurrentDuration = 3700 ;
}
else if (mSpeed < 201) {
plus = 100 ;
mCurrentDuration = 4500 ;
}
if (mScrollLeft) {
distance = mMoveDistance - plus ;
}else{
distance = mMoveDistance + plus ;
}
int scrollX = this.getScrollX() ;
//System.out.println("######### NEXT distance=" + distance + " duration=" + mCurrentDuration
// + " scrollX=" + scrollX + " FinalX()=" + mScroller.getFinalX());
//mScroller.forceFinished(true) ;
enableChildrenCache();
mScroller.startScroll( scrollX, 0, - (int)distance, 0, mCurrentDuration);
final int whichScreen = (mScrollerX + (getWidth() / 2)) / getWidth();
if (whichScreen != mCurrentScreen) {
//mCurrentScreen = whichScreen ;
mIndicator.show(whichScreen);
}
mLastTime = currentTime ;
mLastX = currentX ;
mMoveDistance = 0 ;
}
}
/**
* 让Scroller产生滚动数据,并根据这些数据重绘,产生动画效果
* */
private void snapToScreen() {
//System.out.println("snapToScreen " + mNextScreen);
final int newX = mNextScreen * getWidth();
final int delta = newX - mScrollerX;
enableChildrenCache();
mScroller.startScroll(mScrollerX, 0, delta, 0, 1000);
mCurrentScreen = mNextScreen ;
mIndicator.show(mNextScreen);
mNextScreen = INVALID_SCREEN ;
}
/**
* 让Scroller产生滚动数据,并根据这些数据重绘,产生动画效果
* */
public void snapToScreen(int screen) {
mNextScreen = screen ;
snapToScreen() ;
}
/**
* 直接跳到某一屏
*/
public void setToScreen(int whichScreen) {
mCurrentScreen = whichScreen;
final int newX = whichScreen * getWidth();
//mScroller.startScroll(newX, 0, 0, 0, 0);
//Log.d(TAG, "newX=" + newX) ;
scrollTo(newX, 0);
enableChildrenCache();
mIndicator.show(whichScreen);
invalidate();
}
/**
* 指示这个ViewGroup的每个子View的大小和位置
* */
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childX = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
final int childWidth = child.getMeasuredWidth();
child.layout(childX, 0, childX + childWidth, child.getMeasuredHeight());
childX += childWidth;
}
}
}
/**
* 指示这个ViewGroup的大小
* widthMeasure和heightMeasureSpec虽然是整型,实际上它是根据SpecView.MeasureSpec编码的,包含了int mode和int size数据。
* 用getMode()来获得mode (三种模式: AT_MOST, EXACTLY, UNSPECIFIED), 用getSize()来获得size
* */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//final int width = MeasureSpec.getSize(widthMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("error mode.");
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("error mode.");
}
//给每个子View和本ViewGroup一样大小
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
Log.d(TAG, "onMeasure getSize=" + MeasureSpec.getSize(widthMeasureSpec) ) ;
}
/** 无论在任何情况下, 这个会一直调用 */
@Override
public void computeScroll() {
mIsScrolling = mScroller.computeScrollOffset() ;
if (mIsScrolling) {
mScrollerX = mScroller.getCurrX();
//todo: Set the scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.
//System.out.println( "mScroller scrollTo " + mScrollerX) ;
scrollTo(mScrollerX, 0);
// 如果没有墙纸,就通知系统墙纸滚动
if (!mWallpaperLoaded) {
updateWallpaperOffset();
}
} else { //如果滚动已经停止
//System.out.println( "mScroller not mIsScrolling") ;
//滚动停止,就清除缓存
clearChildrenCache();
}
//非常重要,否则界面会不更新
invalidate() ;
}
/**
* 添加view 到桌面
*/
public void addInCurrentScreen(View child, int cellX, int cellY, int spanX, int spanY) {
addInScreen(child, mCurrentScreen, cellX, cellY, spanX, spanY, false);
}
/**
* 添加view 到桌面
*/
public void addInCurrentScreen(View child, int cellX, int cellY, int spanX, int spanY, boolean insert) {
addInScreen(child, mCurrentScreen, cellX, cellY, spanX, spanY, insert);
}
/**
* 添加view 到桌面,指定哪一屏,哪个位置自动计算
*/
public void addInScreen(View child, int screen) {
addInScreen(child, screen, -1, -1, 1, 1, false);
}
/**
* 添加view 到桌面,哪一屏,哪个位置自动计算
*/
public void addInScreen(View child) {
addInScreen(child, -1, -1, -1, 1, 1, false);
}
/**
* 添加view 到桌面
*/
public void addInScreen(View child, int screen, int cellX, int cellY, int spanX, int spanY) {
addInScreen(child, screen, cellX, cellY, spanX, spanY, false);
}
/**
* 添加view 到桌面
* @param child 要添加的View
* @param screen 哪一屏, 如果 -1 , 就让CellLayout自己计算
* @param cellX 放在格子的第几列,如果 -1 , 就让CellLayout自己计算摆放的位置
* @param cellY 放在格子的第几行
* @param spanX 横向占多少个格,正常1
* @param spanY 竖向占多少个格,正常1
* @param insert 插入否
*/
public void addInScreen(View child, int screen, int cellX, int cellY, int spanX, int spanY, boolean insert) {
if (child == null) {
Log.e(TAG, "addInScreen child == null !!!");
return ;
}
//不指定哪一屏,就要计算放在哪一屏
if (screen == -1) {
//mCapacityPerScreen还没获得时,数值为0,为防止出错,先给一个99的值
if (mCapacityPerScreen == 0) {
mCapacityPerScreen = 99;
}
screen = mItemTotal / mCapacityPerScreen ;
//System.out.println("addInScreen screen=" + screen ) ;
}
mItemTotal++ ;
//每个Screen 都是一个cell layout
CellLayout workspaceScreen ;
//Log.d(TAG, "screen=" + screen + " mScreenCount=" + mScreenCount + " ") ;
//如果要放入的屏现在还没有,就增加一个屏
if ( screen > mScreenCount - 1) {
workspaceScreen = (CellLayout) mInflater.inflate(R.layout.workspace_screen, null, false);
this.addView(workspaceScreen) ;
mScreenCount = screen + 1 ;
mIndicator.setScreenCount(mScreenCount);
}else{
workspaceScreen = (CellLayout) getChildAt(screen);
}
if (workspaceScreen == null) {
Log.e(TAG, "workspaceScreen == null") ;
return ;
}
//计算每屏的格子个数
if (mCapacityPerScreen == 99) {
mCapacityPerScreen = workspaceScreen.getCountX() * workspaceScreen.getCountY() ;
Log.d(TAG, "mCapacityPerScreen=" + mCapacityPerScreen
+ " count x=" + workspaceScreen.getCountX() + " count y=" + workspaceScreen.getCountY()
+ " spanX=" + spanX + " spanY=" + spanY) ;
}
/**把子View的layoutParams强制转成CellLayout.LayoutParams,无论如何,只为带上x,y, spanX, spanY这几个值
* 为什么不直接创建CellLayoutParams,而是先取child的LayoutParams呢?为的是取child的宽度和高度。如果没有指定,
* 就创建CellLayoutParams,宽度和高度默认都是wrap_content
*/
CellLayout.CellLayoutParams cellLayoutParams = (CellLayout.CellLayoutParams) child.getLayoutParams();
if (cellLayoutParams == null) {
cellLayoutParams = new CellLayout.CellLayoutParams(cellX, cellY, spanX, spanY);
} else {
cellLayoutParams.cellX = cellX;
cellLayoutParams.cellY = cellY;
cellLayoutParams.cellHSpan = spanX;
cellLayoutParams.cellVSpan = spanY;
}
workspaceScreen.addView(child, insert ? 0 : -1, cellLayoutParams);
}
/**
* 设置页码指示器
* @param indicator
*/
public void setIndicator(WorkspaceIndicator indicator) {
mIndicator = indicator;
}
/**
* 获取当前第几屏
* @return
*/
public int getCurrentScreen() {
return mCurrentScreen;
}
/**
* 绘制VIew本身的内容,通过调用View.onDraw(canvas)函数实现,绘制自己的孩子通过dispatchDraw(canvas)实现
* Called by draw to draw the child views. This may be overridden by derived classes to gain control
* just before its children are drawn (but after its own view has been drawn).
* **/
@Override
protected void dispatchDraw(Canvas canvas) {
boolean restore = false;
View child ;
if (mWallpaperLoaded) {
canvas.drawBitmap(mWallpaperBitmap, mScrollerX, 0, mPaint);
}
//取得视图树开始重绘的时间,给drawChild用,大概是用于重绘状态改变、同步之类
final long drawingTime = getDrawingTime();
/*
for (int i = 0 ; i < this.getChildCount(); i++) {
child = getChildAt(i) ;
if (child != null) {
drawChild(canvas, child, getDrawingTime());
}
}
*/
//如果不是在自动滚动中,就只画当前屏
//boolean fastDraw = mTouchState != TOUCH_STATE_AUTOSCROLL && mNextScreen == INVALID_SCREEN;
boolean fastDraw = !mIsScrolling ;
if (fastDraw) {
child = getChildAt(mCurrentScreen) ;
if (child != null) {
//Log.d(TAG, "mCurrentScreen is not null: " + mCurrentScreen) ;
drawChild(canvas, child, drawingTime);
}
} else {//滚动中
//Log.d(TAG, "not is fastDraw") ;
//画左屏
if (mCurrentScreen > 0) {
child = getChildAt(mCurrentScreen - 1) ;
if (child != null) {
drawChild(canvas, child, drawingTime);
}
}
//画当前屏
child = getChildAt(mCurrentScreen) ;
if (child != null) {
drawChild(canvas, child, drawingTime);
}
//画右屏
if (mCurrentScreen < mScreenCount -1) {
child = getChildAt(mCurrentScreen + 1) ;
if (child != null) {
drawChild(canvas, child, drawingTime);
}
}
}
/*
if (restore) {
canvas.restore();
}
*/
}
/**
* 页面重绘时使用图像缓存。可能是基于性能的考虑,会多用内存。画完后,用clearChildrenCache释放内存。
* 实际使用中,不如不用,或者只开一次,不释放。
* */
void enableChildrenCache() {
/*
if (childrenCacheEnabled) {
//System.out.println("childrenCacheEnabled before");
return ;
}
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(true);
layout.setChildrenDrawingCacheEnabled(true);
}
childrenCacheEnabled = true ;
*/
}
void clearChildrenCache() {
/*
if (!childrenCacheEnabled) {
//System.out.println("clearChildrenCache before");
return ;
}
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(false);
layout.setChildrenDrawingCacheEnabled(false);
}
childrenCacheEnabled = false ;
*/
}
/**
* 更新壁纸位置
*/
private void updateWallpaperOffset() {
View child = getChildAt(getChildCount() - 1) ;
if (child == null) {
return ;
}
int scrollRange = child.getRight() - (getRight() - getLeft()) ;
mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1),0);
//System.out.println("mScrollX=" + mScrollX + " scrollRange=" + scrollRange);
int scrollX = mScrollerX ;
if (scrollX > scrollRange) {
scrollX = scrollRange ;
}
mWallpaperManager.setWallpaperOffsets(getWindowToken(), scrollX / (float) scrollRange, 0);
}
/**
* 将每一屏的child清除,然后将每一屏(CellLayout)清除
*/
public void clearWorksapce() {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final ViewGroup child = (ViewGroup) getChildAt(i);
child.removeAllViews() ;
}
this.removeAllViews() ;
//mWallpaperLoaded = false;
mScreenCount = 0 ;
mCapacityPerScreen = 0 ;
mItemTotal = 0 ;
mIndicator.setScreenCount(0);
}
public void release() {
mScroller = null ;
mPaint = null ;
mWallpaperBitmap = null;
mIndicator = null ;
mInflater = null ;
mWallpaperManager = null ;
}
}
| [
"school@jichuangsi"
]
| school@jichuangsi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.