blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
5e3e48e5fb57412823a963f0adc3bfd5d97bfba3
Java
Jiemamy/core
/jiemamy-core/src/test/java/org/jiemamy/serializer/stax2/JiemamyStaxSerializerTest.java
UTF-8
18,684
1.710938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2007-2012 Jiemamy Project and the Others. * Created on 2011/01/05 * * This file is part of Jiemamy. * * 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.jiemamy.serializer.stax2; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.UUID; import com.google.common.collect.Iterables; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.CharEncoding; import org.custommonkey.xmlunit.DetailedDiff; import org.custommonkey.xmlunit.Diff; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jiemamy.JiemamyContext; import org.jiemamy.JiemamyContextTest; import org.jiemamy.SimpleJmMetadata; import org.jiemamy.model.column.JmColumn; import org.jiemamy.model.column.JmColumnBuilder; import org.jiemamy.model.constraint.JmForeignKeyConstraint; import org.jiemamy.model.constraint.JmPrimaryKeyConstraint; import org.jiemamy.model.constraint.ReferentialAction; import org.jiemamy.model.datatype.RawTypeCategory; import org.jiemamy.model.datatype.SimpleDataType; import org.jiemamy.model.datatype.SimpleRawTypeDescriptor; import org.jiemamy.model.table.JmTable; import org.jiemamy.model.table.JmTableBuilder; import org.jiemamy.serializer.stax.JiemamyStaxSerializer; /** * {@link JiemamyStaxSerializer}のテストクラス。 * * @version $Id$ * @author daisuke */ public class JiemamyStaxSerializerTest { private static Logger logger = LoggerFactory.getLogger(JiemamyStaxSerializerTest.class); private JiemamyStaxSerializer serializer; /** * テストを初期化する。 * * @throws Exception 例外が発生した場合 */ @Before public void setUp() throws Exception { serializer = new JiemamyStaxSerializer(); } /** * 簡単なJiemamyContextのシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test01_簡単なJiemamyContextのシリアライズ結果を確認() throws Exception { JiemamyContext context = new JiemamyContext(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(context, baos); String actual = baos.toString(CharEncoding.UTF_8); String expected = getXml("core1.jiemamy"); // logger.debug(actual); // logger.debug(expected); DetailedDiff diff = new DetailedDiff(new Diff(actual, expected)); assertThat(diff.getAllDifferences().toString(), diff.similar(), is(true)); } /** * Tableを1つ含むJiemamyContextのシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test02_Tableを1つ含むJiemamyContextのシリアライズ結果を確認() throws Exception { JiemamyContext context = new JiemamyContext(); SimpleJmMetadata meta = new SimpleJmMetadata(); meta.setSchemaName("schema-name"); meta.setDescription(""); context.setMetadata(meta); UUID tid = UUID.fromString("d23695f8-76dd-4f8c-b5a2-1e02087ba44d"); JmTable t = new JmTable(tid); t.setName("foo"); context.add(t); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(context, baos); String actual = baos.toString(CharEncoding.UTF_8); // DialectClassNameはnullなので出力されない // schemaNameが設定通りに出力される // descriptionは空文字なので空要素として出力される String expected = getXml("core2.jiemamy"); DetailedDiff diff = new DetailedDiff(new Diff(actual, expected)); assertThat(diff.getAllDifferences().toString(), diff.similar(), is(true)); } /** * Columnを1つ含むTableを1つ含むJiemamyContextのシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test03_Columnを1つ含むTableを1つ含むJiemamyContextのシリアライズ結果を確認() throws Exception { JiemamyContext context = new JiemamyContext(); SimpleJmMetadata meta = new SimpleJmMetadata(); meta.setDialectClassName(null); // null → 要素欠損 meta.setSchemaName("schema-name"); meta.setDescription(""); // 空文字列 → 空要素 context.setMetadata(meta); UUID tid = UUID.fromString("d23695f8-76dd-4f8c-b5a2-1e02087ba44d"); JmTable t = new JmTable(tid); t.setName("foo"); UUID cid = UUID.fromString("58a57dcc-7745-4718-b03d-0143eaaa8af3"); JmColumn c = new JmColumn(cid); c.setName("bar"); c.setLogicalName("baz"); c.setDescription(""); c.setDataType(SimpleDataType.of(RawTypeCategory.INTEGER)); t.add(c); context.add(t); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(context, baos); String actual = baos.toString(CharEncoding.UTF_8); // DialectClassNameはnullなので出力されない // schemaNameが設定通りに出力される // descriptionは空文字なので空要素として出力される String expected = getXml("core3.jiemamy"); // logger.info("actual ={}", actual.replaceAll("[\n\r]", "")); // logger.info("expected={}", expected.replaceAll("[\n\r]", "")); DetailedDiff diff = new DetailedDiff(new Diff(actual, expected)); assertThat(diff.getAllDifferences().toString(), diff.similar(), is(true)); } /** * Tableを2つ含むJiemamyContextのシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test04_Tableを2つ含むJiemamyContextのシリアライズ結果を確認() throws Exception { JiemamyContext ctx = new JiemamyContext(); UUID id1 = UUID.fromString("cbe160fd-e229-4ede-ae01-3a0ea44ae5d6"); JmTable t1 = new JmTable(id1); t1.setName("FOO"); ctx.add(t1); UUID id2 = UUID.fromString("76d03b4d-c959-48e9-bd0e-d6c2f61ec54d"); JmTable t2 = new JmTable(id2); t2.setName("BAR"); ctx.add(t2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(ctx, baos); String actual = baos.toString(CharEncoding.UTF_8); String expected = getXml("core4.jiemamy"); // logger.info("actual ={}", actual.replaceAll("[\n\r]", "")); // logger.info("expected={}", expected.replaceAll("[\n\r]", "")); DetailedDiff diff = new DetailedDiff(new Diff(actual, expected)); assertThat(diff.getAllDifferences().toString(), diff.similar(), is(true)); } /** * Columnを2つ含むTableを1つ含むJiemamyContextのシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test05_Columnを2つ含むTableを1つ含むJiemamyContextのシリアライズ結果を確認() throws Exception { JiemamyContext ctx = new JiemamyContext(); UUID tid = UUID.fromString("0d7bf352-59c4-4683-ae59-2808f30e686e"); JmTable t = new JmTable(tid); t.setName("TTTT"); UUID cid1 = UUID.fromString("a4333846-1292-4b82-b68c-454762bf92a1"); JmColumn c1 = new JmColumn(cid1); c1.setName("CCCC1"); c1.setDataType(SimpleDataType.of(RawTypeCategory.INTEGER)); t.add(c1); UUID cid2 = UUID.fromString("7774052e-40ee-4796-b990-2411be64fb35"); JmColumn c2 = new JmColumn(cid2); c2.setName("CCCC2"); c2.setDataType(SimpleDataType.of(RawTypeCategory.INTEGER)); t.add(c2); ctx.add(t); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(ctx, baos); String actual = baos.toString(CharEncoding.UTF_8); String expected = getXml("core5.jiemamy"); logger.info("actual ={}", actual.replaceAll("[\n\r]", "")); logger.info("expected={}", expected.replaceAll("[\n\r]", "")); DetailedDiff diff = new DetailedDiff(new Diff(actual, expected)); assertThat(diff.getAllDifferences().toString(), diff.similar(), is(true)); } /** * 簡単なJiemamyContextのデシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test11_簡単なJiemamyContextのデシリアライズ結果を確認() throws Exception { String xml = getXml("core1.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); assertThat(deserialized.getMetadata(), is(notNullValue())); } /** * Tableを1つ含むJiemamyContextのデシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test12_Tableを1つ含むJiemamyContextのデシリアライズ結果を確認() throws Exception { String xml = getXml("core2.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); assertThat(deserialized.getMetadata(), is(notNullValue())); assertThat(deserialized.getMetadata().getDialectClassName(), is(nullValue())); // 要素欠損 → null assertThat(deserialized.getMetadata().getSchemaName(), is("schema-name")); assertThat(deserialized.getMetadata().getDescription(), is("")); // 空要素 → 空文字列 assertThat(deserialized.getTables().size(), is(1)); JmTable table = Iterables.get(deserialized.getTables(), 0); assertThat(table.getId(), is(UUID.fromString("d23695f8-76dd-4f8c-b5a2-1e02087ba44d"))); assertThat(table.getColumns().size(), is(0)); } /** * Columnを1つ含むTableを1つ含むJiemamyContextのデシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test13_Columnを1つ含むTableを1つ含むJiemamyContextのデシリアライズ結果を確認() throws Exception { String xml = getXml("core3.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); assertThat(deserialized.getTables().size(), is(1)); JmTable table = Iterables.get(deserialized.getTables(), 0); assertThat(table.getId(), is(UUID.fromString("d23695f8-76dd-4f8c-b5a2-1e02087ba44d"))); assertThat(table.getName(), is("foo")); assertThat(table.getLogicalName(), is(nullValue())); assertThat(table.getDescription(), is(nullValue())); assertThat(table.getColumns().size(), is(1)); JmColumn column = table.getColumns().get(0); assertThat(column.getId(), is(UUID.fromString("58a57dcc-7745-4718-b03d-0143eaaa8af3"))); assertThat(column.getName(), is("bar")); assertThat(column.getLogicalName(), is("baz")); assertThat(column.getDescription(), is("")); } /** * Tableを2つ含むJiemamyContextのデシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test14_Tableを2つ含むJiemamyContextのデシリアライズ結果を確認() throws Exception { String xml = getXml("core4.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); assertThat(deserialized.getTables().size(), is(2)); for (JmTable table : deserialized.getTables()) { if (UUID.fromString("cbe160fd-e229-4ede-ae01-3a0ea44ae5d6").equals(table.getId())) { assertThat(table.getName(), is("FOO")); } else if (UUID.fromString("76d03b4d-c959-48e9-bd0e-d6c2f61ec54d").equals(table.getId())) { assertThat(table.getName(), is("BAR")); } else { fail("unexpeceted id: " + table.getId()); } } } /** * Columnを1つ含むTableを1つ含むJiemamyContextのデシリアライズ結果を確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test15_Columnを2つ含むTableを1つ含むJiemamyContextのデシリアライズ結果を確認() throws Exception { String xml = getXml("core5.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); assertThat(deserialized.getTables().size(), is(1)); JmTable table = Iterables.get(deserialized.getTables(), 0); assertThat(table.getId(), is(UUID.fromString("0d7bf352-59c4-4683-ae59-2808f30e686e"))); assertThat(table.getName(), is("TTTT")); assertThat(table.getColumns().size(), is(2)); JmColumn c1 = table.getColumns().get(0); assertThat(c1.getId(), is(UUID.fromString("a4333846-1292-4b82-b68c-454762bf92a1"))); assertThat(c1.getName(), is("CCCC1")); JmColumn c2 = table.getColumns().get(1); assertThat(c2.getId(), is(UUID.fromString("7774052e-40ee-4796-b990-2411be64fb35"))); assertThat(c2.getName(), is("CCCC2")); } /** * シンボリックIDが利用できることを確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test16_シンボリックIDが利用できることを確認() throws Exception { String xml = getXml("symbolicid.jiemamy"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); JmTable t2 = deserialized.getTable("TABLE_2"); JmForeignKeyConstraint fk = Iterables.getOnlyElement(t2.getForeignKeyConstraints()); JmTable t1 = fk.findReferenceTable(deserialized.getTables()); assertThat(t1.getName(), is("TABLE_1")); } /** * CORE-207の再現テスト。 * * @throws Exception 例外が発生した場合 */ @Test public void test17_CORE207() throws Exception { JiemamyContext ctx = new JiemamyContext(); // FORMAT-OFF JmColumn foocolpk = new JmColumnBuilder("FOO1") .type(new SimpleDataType(new SimpleRawTypeDescriptor(RawTypeCategory.INTEGER))) .build(); JmColumn barcolpk = new JmColumnBuilder("BAR1") .type(new SimpleDataType(new SimpleRawTypeDescriptor(RawTypeCategory.INTEGER))) .build(); JmColumn barcolfk = new JmColumnBuilder("BAR2") .type(new SimpleDataType(new SimpleRawTypeDescriptor(RawTypeCategory.INTEGER))) .build(); JmForeignKeyConstraint fk = JmForeignKeyConstraint.of(barcolfk, foocolpk); fk.setOnDelete(ReferentialAction.RESTRICT); fk.setOnUpdate(ReferentialAction.CASCADE); JmTable foo = new JmTableBuilder("FOO") .with(foocolpk) .with(JmPrimaryKeyConstraint.of(foocolpk)) .build(); JmTable bar = new JmTableBuilder("BAR") .with(barcolpk) .with(barcolfk) .with(JmPrimaryKeyConstraint.of(barcolpk)) .with(fk) .build(); // FORMAT-ON ctx.add(foo); ctx.add(bar); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(ctx, baos); String xml = new String(baos.toByteArray()); logger.info(xml); assertThat(xml, containsString("<onDelete>RESTRICT</onDelete>")); assertThat(xml, containsString("<onUpdate>CASCADE</onUpdate>")); JiemamyContext ctx2 = serializer.deserialize(new ByteArrayInputStream(baos.toByteArray())); JmTable bar2 = ctx2.getTable("BAR"); JmForeignKeyConstraint fk2 = Iterables.getOnlyElement(bar2.getConstraints(JmForeignKeyConstraint.class)); assertThat(fk2.getOnDelete(), is(ReferentialAction.RESTRICT)); assertThat(fk2.getOnUpdate(), is(ReferentialAction.CASCADE)); } /** * 適当なモデルを一杯作ってみて、それぞれのシリアライズやデシリアライズが異常終了しないことを確認。 * * @throws Exception 例外が発生した場合 */ @Test public void test99_適当なモデルを一杯作ってみて_それぞれのシリアライズやデシリアライズが異常終了しないことを確認() throws Exception { File dir = new File("target/test99"); FileUtils.deleteDirectory(dir); for (int i = 0; i < 10; i++) { logger.info("test99 - " + i); File file1 = new File(dir, String.format("file%03d-1.txt", i)); if (file1.exists()) { file1.delete(); } File file2 = new File(dir, String.format("file%03d-2.txt", i)); if (file2.exists()) { file2.delete(); } // 適当なモデルを生成 JiemamyContext original = JiemamyContextTest.random(); // XMLにシリアライズしてみる(1) ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(original, baos); String first = baos.toString(CharEncoding.UTF_8); // logger.info("1 = {}", first); FileUtils.write(file1, first); // そのXMLをデシリアライズしてみる ByteArrayInputStream bais = new ByteArrayInputStream(first.getBytes(CharEncoding.UTF_8)); JiemamyContext deserialized = serializer.deserialize(bais); assertThat(deserialized, is(notNullValue())); // デシリアライズされた新しいcontextを再びシリアライズしてみる(2) ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); serializer.serialize(deserialized, baos2); String second = baos2.toString(CharEncoding.UTF_8); // logger.info("2 = {}", second); FileUtils.write(file2, second); // 何度やってもXMLは全く同じモノになるハズだ DetailedDiff diff = new DetailedDiff(new Diff(first, second)); // FORMAT-OFF String failLog = MessageFormat.format("\n1 = {0}\n2 = {1}\ndiff = {2}", first.replaceAll("[\r\n]", ""), second.replaceAll("[\r\n]", ""), diff.getAllDifferences().toString()); // FORMAT-ON assertThat(failLog, diff.similar(), is(true)); } } private String getXml(String name) { InputStream in = null; String result = null; try { in = getClass().getResourceAsStream("/org/jiemamy/serializer/" + name); result = IOUtils.toString(in); } catch (IOException e) { } finally { IOUtils.closeQuietly(in); } return result; } }
true
2fc311b0ac1c4133c0f084762141a53e057a1838
Java
dushitaoyuan/littleca
/littleca-core/src/main/java/com/taoyuanx/ca/core/bc/X509CertExtensions.java
UTF-8
3,613
2.140625
2
[ "Apache-2.0" ]
permissive
package com.taoyuanx.ca.core.bc; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.x509.*; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; /** * * @author 都市桃源 2018年7月1日下午4:41:23 x509 证书扩展信息生成工具 */ public class X509CertExtensions { /** * 证书CRL分布点 * * @return */ public static CRLDistPoint buildCRLDIstPoint() { return null; } /** * 证书策略 * * @return */ public static ASN1EncodableVector buildPolicyInfo() { return null; } /** * 增强密钥用法 见KeyPurposeId */ public static ExtendedKeyUsage builldExtendKeyUsage() { List<KeyPurposeId> list = new ArrayList<>(); list.add(KeyPurposeId.id_kp_OCSPSigning); list.add(KeyPurposeId.id_kp_capwapAC); list.add(KeyPurposeId.id_kp_timeStamping); KeyPurposeId[] usages = new KeyPurposeId[list.size()]; ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(list.toArray(usages)); return extendedKeyUsage; } /** * 密钥用法 见 KeyUsage * * @return */ public static KeyUsage builldKeyUsage() { int keyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.encipherOnly | KeyUsage.decipherOnly; return new KeyUsage(keyUsage); } /** * 主题备用名称扩展 参见:GeneralName * * @return * @throws Exception */ public static ASN1Encodable buildSubjectAlternativeName(GeneralName... generalNames) throws Exception { if (null != generalNames) { return new GeneralNames(generalNames); } return null; } /** * 颁发者备用别名扩展 * * @return */ public static ASN1EncodableVector buildIssuerAlternativeName(X509v3CertificateBuilder certBuilder) throws Exception { // Extension.issuerAlternativeName return null; } public static void buildAllExtensions(X509v3CertificateBuilder certBuilder, PublicKey userPublicKey, PublicKey caPublicKey) throws Exception { JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); // 添加CRL分布点 /// certBuilder.addExtension(Extension.cRLDistributionPoints, true, // X509CertExtensions.buildCRLDIstPoint()); // 添加证书策略 // certBuilder.addExtension(Extension.certificatePolicies, true, // X509CertExtensions.buildPolicyInfo()); // 颁发者密钥标识 certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(caPublicKey)); // 使用者密钥标识 certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(userPublicKey)); // 密钥用法 certBuilder.addExtension(Extension.keyUsage, true, X509CertExtensions.builldKeyUsage()); // 增强密钥用法 certBuilder.addExtension(Extension.extendedKeyUsage, true, X509CertExtensions.builldExtendKeyUsage()); // 主题备用名称扩展 /*certBuilder.addExtension(Extension.issuerAlternativeName, true, X509CertExtensions .buildSubjectAlternativeName(new GeneralName(GeneralName.rfc822Name, "email@163.com")));*/ // 基本约束 if (userPublicKey == caPublicKey) { certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3)); } else { certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(0)); } } }
true
4303cfa9fef909ddef1b861a1a35f93e0bd43572
Java
zyhnesmr/wechar-web
/后端/wechat-app/src/main/java/com/wechat/app/config/MyAuthenticationFailureHandler.java
UTF-8
1,738
2.375
2
[ "Apache-2.0" ]
permissive
package com.wechat.app.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.wechat.app.entity.RespBean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.*; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @Configuration public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException { resp.setContentType("application/json;charset=utf-8"); PrintWriter out=resp.getWriter(); RespBean error = RespBean.error("登录失败!"); if (exception instanceof LockedException){ error.setMsg("账户已锁定,请联系管理员!"); }else if (exception instanceof CredentialsExpiredException){ error.setMsg("密码已过期,请联系管理员!"); }else if (exception instanceof AccountExpiredException){ error.setMsg("账户已过期,请联系管理员!"); }else if (exception instanceof DisabledException){ error.setMsg("账户被禁用,请联系管理员!"); }else if (exception instanceof BadCredentialsException){ error.setMsg("用户名或密码错误,请重新输入!"); } String s = new ObjectMapper().writeValueAsString(error); out.write(s); out.flush(); out.close(); } }
true
ef94595d7751ea9a9dc2515e8cffded53911663f
Java
LeonardoBonacci/oogway
/sannyas/src/test/java/guru/bonacci/oogway/sannyas/service/general/PageTestCaches.java
UTF-8
708
2.015625
2
[]
no_license
package guru.bonacci.oogway.sannyas.service.general; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import guru.bonacci.oogway.sannyas.service.general.PageCache; @Component @Profile("cache-test") public class PageTestCaches { @Component public class PageTestCache1 implements PageCache { int i = 0; @Cacheable("pages") public Integer getNrOfPages(String searchURL) { return ++i; } } @Component public class PageTestCache2 implements PageCache { int i = 0; @Cacheable("pages") public Integer getNrOfPages(String searchURL) { return ++i; } } }
true
c974e8f7ee4ebbc0d1d3e510146bd5c382a02aa4
Java
rockydang/springdemo
/service/src/main/java/com/rockydang/service/springdemo/service/lifecycle/MyInstantiationAwareBeanPostProcessor.java
UTF-8
2,100
2.75
3
[]
no_license
package com.rockydang.service.springdemo.service.lifecycle; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.core.Ordered; import java.beans.PropertyDescriptor; import java.util.Date; /** * 文件描述。 * * @author yanxiao * @since 2016年10月04日 11:10 */ public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements Ordered { public MyInstantiationAwareBeanPostProcessor(){ System.out.println("instantiation MyInstantiationAwareBeanPostProcessor"); } //1.接口方法:在实例化Bean前调用 public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { //仅对car处理 if ("car".equals(beanName)) { System.out.println("invoke InstantiationAwareBeanPostProcessorAdapter.postProcessBeforeInstantiation.."); } return null; } //2.接口方法:在实例化Bean后调用 public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { if ("car".equals(beanName)) { System.out.println("invoke InstantiationAwareBeanPostProcessorAdapter.postProcessAfterInstantiation"); } return true; } //3.接口方法:在设置属性时调用 public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { //仅对容器中的carBean进行处理,还可以通过pds入参进行过滤 //仅对car的某个特定属性时进行处理 if ("car".equals(beanName)) { System.out.println("invoke InstantiationAwareBeanPostProcessorAdapter.postProcessPropertyValues"); // Car car = (Car)bean; // car.setDateValue(new Date()); } return pvs; } @Override public int getOrder() { return 2; } }
true
d517962e245d39d816907a931720c7aff159a415
Java
kingmore96/common_utils
/Interview/test/Stack/HanoiResolverTest.java
UTF-8
340
2.234375
2
[]
no_license
package Stack; import java.util.ArrayList; import java.util.List; import org.junit.Test; import Stack.HanoiResolver.Tower; public class HanoiResolverTest { @Test public void test_3_4() { List list = HanoiResolver.createHanoiTowers(5); HanoiResolver.moveHanoiTower((ArrayList<Tower<Integer>>) list); System.out.println(); } }
true
597db96dae0deceb48686b6686d659f7fc0e50e7
Java
buddhini81/ps-project-audition
/projects-java-spring-recruiterDB/src/test/java/com/recruiter/projectsjavaspringrecruiterDB/Module3_Tests.java
UTF-8
7,318
2.28125
2
[]
no_license
package com.recruiter.projectsjavaspringrecruiterDB; import com.recruiter.projectsjavaspringrecruiterDB.controller.ApplicantController; import com.recruiter.projectsjavaspringrecruiterDB.data.Applicant; import com.recruiter.projectsjavaspringrecruiterDB.data.ApplicantRepository; import com.recruiter.projectsjavaspringrecruiterDB.service.ApplicantService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.ui.ModelMap; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import static org.springframework.test.util.AssertionErrors.assertTrue; @SpringBootTest @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class Module3_Tests { private Class entityClass; private Class iRepo; private Class cService; private Class cController; private String basePackage; @Mock private Applicant applicant; @Mock ApplicantRepository applicantRepository; @Mock ApplicantService service; @Autowired @InjectMocks ApplicantService applicantService; @Autowired @InjectMocks private ApplicantController applicantController; @BeforeAll public void init() { MockitoAnnotations.initMocks(this); basePackage = getClass().getPackage().getName(); try { entityClass = Class.forName(basePackage + ".data.Applicant"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { cService = Class.forName(basePackage + ".service.ApplicantService"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { cController = Class.forName(basePackage + ".controller.ApplicantController"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Test public void test_1() { Method findById = null; if (cService != null) { Method[] methods = cService.getDeclaredMethods(); for (Method m : methods) { if (m.getName().equals("findApplicantById") && m.getReturnType().equals(Applicant.class)) { findById = m; break; } } try { findById.invoke(applicantService, 1L); } catch (Exception e) { //e.printStackTrace(); } boolean findByIdCalled = false; try { Mockito.verify(applicantRepository).findById(1L); findByIdCalled = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 13: Did not call findById method of applicantRepository inside findApplicantById method of ApplicantService.", findByIdCalled); } } @Test public void test_2() { Method getById = null; ModelMap modelMap = Mockito.mock(ModelMap.class); Method[] methods = cController.getDeclaredMethods(); for(Method m : methods) { if(m.getName().equals("getById")) { getById = m; break; } } try { getById.invoke(applicantController, 1L,modelMap); } catch (Exception e) { //e.printStackTrace(); } boolean findApplicantByIdCalled = false; try { Mockito.verify(service).findApplicantById(1L); findApplicantByIdCalled = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 14: Did not call findApplicantById method of applicantService inside getById method of ApplicantController", findApplicantByIdCalled); Mockito.when(modelMap.put("applicant", null)).thenReturn(null); boolean calledPut = false; try { Mockito.verify(modelMap).put("applicant", null); calledPut = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 14: Did not call ModelMap's put() method with applicant in getById method inside ApplicantController", calledPut); } @Test public void test_3() { Method editApplicant = null; ModelMap modelMap = Mockito.mock(ModelMap.class); Method[] methods = cController.getDeclaredMethods(); for(Method m : methods) { if(m.getName().equals("editApplicant")) { editApplicant = m; break; } } try { editApplicant.invoke(applicantController,modelMap); } catch (Exception e) { //e.printStackTrace(); } boolean findAllApplicantsCalled = false; try { Mockito.verify(service).findAllApplicants(); findAllApplicantsCalled = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 15: Did not call findAllApplicants method of applicantService inside editApplicant method of ApplicantController", findAllApplicantsCalled); List<Applicant> a = new ArrayList<Applicant>(); Mockito.when(modelMap.put("all", a)).thenReturn(null); boolean calledPut = false; try { Mockito.verify(modelMap).put("all", a); calledPut = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 15: Did not call ModelMap's put() method with all in editApplicant method inside ApplicantController", calledPut); } @Test public void test_4() { Method update = null; ModelMap modelMap = Mockito.mock(ModelMap.class); Applicant a = new Applicant(); a.setId(1L); Method[] methods = cController.getDeclaredMethods(); for(Method m : methods) { if(m.getName().equals("update")) { update = m; break; } } try { update.invoke(applicantController, a,modelMap); } catch (Exception e) { //e.printStackTrace(); } boolean saveCalled = false; try { Mockito.verify(service).save(a); saveCalled = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 16: Did not call save method of applicantService inside update method of ApplicantController", saveCalled); Mockito.when(modelMap.put("message", "Applicant with ID " + a.getId() + " updated!")).thenReturn(null); boolean calledPut = false; try { Mockito.verify(modelMap).put("message", "Applicant with ID " + a.getId() + " updated!"); calledPut = true; } catch (Error e) { //e.printStackTrace(); } assertTrue("Step 16: Did not call ModelMap's put() method with message in update method inside ApplicantController", calledPut); } }
true
502e6f5653b0cd206d75381157d2641c59cbadff
Java
appsfinwin/digicob_doorstep_old
/app/src/main/java/com/finwingway/digicob/ConnectivityChangeReceiver.java
UTF-8
1,681
2.578125
3
[]
no_license
package com.finwingway.digicob; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import android.widget.Toast; /** * Created by AnVin on 4/28/2017. */ public class ConnectivityChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("app", "Network connectivity change"); if (intent.getExtras() != null) { NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO); if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { if(isInternetAvailable()){ Toast.makeText(context, "You Are Connected to Internet", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "There is NO INTERNET Connection!", Toast.LENGTH_LONG).show(); } Log.i("app", "Network " + ni.getTypeName() + " connected"); } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { Log.d("app", "There's no network connectivity"); Toast.makeText(context, "You Are NOT CONNECTED to Internet", Toast.LENGTH_LONG).show(); } } } private boolean isInternetAvailable() { try { return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0); }catch (Exception ex) { ex.printStackTrace(); } return false; } }
true
e8da64dfa7655682532daf3319905e2b9901404f
Java
Lonivia/MDZ_android
/src/com/nordicsemi/nrfUARTv2/SetupActivity.java
GB18030
11,130
2.140625
2
[]
no_license
package com.nordicsemi.nrfUARTv2; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.nio.CharBuffer; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; public class SetupActivity extends Activity { private Button btnsetupsubmit; private EditText tbfu; private EditText tbzhong; private EditText tbchen; private EditText tbchi; private EditText tbhuan; private EditText tbping; private EditText tbshu; private EditText tbhuan2; private EditText tbping2; final static String FOLDER = "/MDZfile/"; //final static String FILENAME = "config"; final static String SUFFIX = ".mdz"; private void writeFile(String sb ,String FILENAME) { String foldername = Environment.getExternalStorageDirectory().getPath() + FOLDER; File folder = new File(foldername); if (folder != null && !folder.exists()) { if (!folder.mkdir() && !folder.isDirectory()) { Log.d("SelectLog", "Error: make dir failed!"); return; } } String stringToWrite = sb.toString(); String targetPath = foldername + FILENAME + SUFFIX; File targetFile = new File(targetPath); if (targetFile != null) { if (targetFile.exists()) { targetFile.delete(); } OutputStreamWriter osw; try{ osw = new OutputStreamWriter( new FileOutputStream(targetFile),"utf-8"); try { osw.write(stringToWrite); osw.flush(); osw.close(); } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } } } //TODO read file!!! private String readFile(String filename) { String foldername = Environment.getExternalStorageDirectory().getPath() + FOLDER; String targetPath = foldername + filename + SUFFIX; String filecontent = null; File f = new File(targetPath); if (f != null && f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Log.d("SelectLog", "Error: Input File not find!"); return null; } CharBuffer cb; try { cb = CharBuffer.allocate(fis.available()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Log.d("SelectLog", "Error: CharBuffer initial failed!"); return null; } InputStreamReader isr; try { isr = new InputStreamReader(fis, "utf-8"); try { if (cb != null) { isr.read(cb); } filecontent = new String(cb.array()); isr.close(); } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Log.d("SelectLog", "readFile filecontent = " + filecontent); return filecontent; } public static boolean isNumeric(String str){ for (int i = 0; i < str.length(); i++){ System.out.println(str.charAt(i)); if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); setContentView(R.layout.setup); android.view.WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes(); layoutParams.gravity=Gravity.TOP; layoutParams.y = 200; btnsetupsubmit=(Button) findViewById(R.id.buttonsetupsubmit); tbfu=(EditText) findViewById(R.id.editTextfu); tbzhong=(EditText) findViewById(R.id.editTextzhong); tbchen=(EditText) findViewById(R.id.editTextchen); tbchi=(EditText) findViewById(R.id.editTextchi); tbhuan=(EditText) findViewById(R.id.editTexthuan); tbping=(EditText) findViewById(R.id.editTextping); tbshu=(EditText) findViewById(R.id.editTextshu); tbhuan2=(EditText) findViewById(R.id.editTexthuan2); tbping2=(EditText) findViewById(R.id.editTextping2); tbhuan.setEnabled(false); tbping.setEnabled(false); tbshu.setEnabled(false); if(readFile("MDZFUSET")!=null){ tbfu.setText(readFile("MDZFUSET")); }else{ tbfu.setText("200"); } if(readFile("MDZZHONGSET")!=null){ tbzhong.setText(readFile("MDZZHONGSET")); }else{ tbzhong.setText("500"); } if(readFile("MDZCHENSET")!=null){ tbchen.setText(readFile("MDZCHENSET")); }else{ tbchen.setText("800"); } if(readFile("MDZCHISET")!=null){ tbchi.setText(readFile("MDZCHISET")); }else{ tbchi.setText("50"); } if(readFile("MDZHUANSET")!=null){ tbhuan2.setText(readFile("MDZHUANSET")); tbhuan.setText(readFile("MDZCHISET")); }else{ tbhuan2.setText("60"); tbhuan.setText("50"); } if(readFile("MDZPINGSET")!=null){ tbping2.setText(readFile("MDZPINGSET")); tbping.setText(readFile("MDZHUANSET")); tbshu.setText(readFile("MDZPINGSET")); }else{ tbping2.setText("80"); tbping.setText("60"); tbshu.setText("80"); } tbchi.addTextChangedListener(new TextWatcher(){ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub tbhuan.setText(tbchi.getText().toString()); } @Override public void afterTextChanged(Editable s) { if(isNumeric(tbchi.getText().toString())){ } } }); tbhuan2.addTextChangedListener(new TextWatcher(){ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub tbping.setText(tbhuan2.getText().toString()); } @Override public void afterTextChanged(Editable s) { } }); tbping2.addTextChangedListener(new TextWatcher(){ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub tbshu.setText(tbping2.getText().toString()); } @Override public void afterTextChanged(Editable s) { } }); btnsetupsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isNumeric(tbfu.getText().toString()) && isNumeric(tbzhong.getText().toString()) && isNumeric(tbchen.getText().toString()) && isNumeric(tbchi.getText().toString()) && isNumeric(tbhuan2.getText().toString()) && isNumeric(tbping2.getText().toString())){ if(Integer.parseInt(tbhuan2.getText().toString())>Integer.parseInt(tbchi.getText().toString()) && Integer.parseInt(tbping2.getText().toString())>Integer.parseInt(tbhuan2.getText().toString())){ writeFile(tbfu.getText().toString() ,"MDZFUSET"); writeFile(tbzhong.getText().toString() ,"MDZZHONGSET"); writeFile(tbchen.getText().toString() ,"MDZCHENSET"); MainActivity.ZM[2]=Integer.parseInt(tbchen.getText().toString()); MainActivity.ZM[1]=Integer.parseInt(tbzhong.getText().toString()); MainActivity.ZM[0]=Integer.parseInt(tbfu.getText().toString()); writeFile(tbchi.getText().toString() ,"MDZCHISET"); writeFile(tbhuan2.getText().toString() ,"MDZHUANSET"); writeFile(tbping2.getText().toString() ,"MDZPINGSET"); finish(); }else{ AlertDialog.Builder builder = new Builder(SetupActivity.this); builder.setMessage("ȷIJ"); builder.setTitle("ʾ"); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton("ȷ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }else{ AlertDialog.Builder builder = new Builder(SetupActivity.this); builder.setMessage("ȷIJΪ"); builder.setTitle("ʾ"); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton("ȷ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } } }); } }
true
458dcd9a46edd9f04ee13021b1c3a8de237ea40a
Java
abdlquadri/elexis-3-base
/ch.elexis.agenda/src/ch/elexis/agenda/series/ui/SerienTerminDialog.java
UTF-8
20,748
1.8125
2
[]
no_license
package ch.elexis.agenda.series.ui; import static ch.elexis.agenda.series.SerienTermin.decimalFormat; import java.util.Calendar; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DateTime; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.ResourceManager; import ch.elexis.actions.Activator; import ch.elexis.agenda.data.Termin; import ch.elexis.agenda.series.EndingType; import ch.elexis.agenda.series.SerienTermin; import ch.elexis.agenda.series.SeriesType; import ch.elexis.agenda.series.ui.composite.MonthlySeriesComposite; import ch.elexis.agenda.series.ui.composite.WeeklySeriesComposite; import ch.elexis.agenda.series.ui.composite.YearlySeriesComposite; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.ui.dialogs.KontaktSelektor; import ch.elexis.data.Kontakt; import ch.rgw.tools.TimeTool; public class SerienTerminDialog extends TitleAreaDialog { private static final int DAYS_OF_WEEK = 7; private static final int APPLY = 0; private static final int CANCEL = 2; private DataBindingContext m_bindingContext; private Text txtEndsAfterNOccurences; private Group groupData; private Text txtReason; private Text txtContact; private SerienTermin serienTermin; private DateTime dateTimeBegin; private DateTime dateTimeEnd; private DateTime dateTimeBeginOfSeries; private Button btnEndsAfter; private Button btnEndsOn; private CTabFolder tabFolderSeriesPattern; private WeeklySeriesComposite wsc; private MonthlySeriesComposite msc; private YearlySeriesComposite ysc; private DateTime dateEndsOn; private Combo comboArea; private Spinner durationSpinner; private int result; /** * Create the dialog. * * @param parentShell */ public SerienTerminDialog(Shell parentShell, SerienTermin serienTermin){ super(parentShell); this.serienTermin = serienTermin; if (this.serienTermin == null) this.serienTermin = new SerienTermin(); } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent){ Composite area = (Composite) super.createDialogArea(parent); setTitleImage(ResourceManager.getPluginImage("ch.elexis.agenda", "icons/recurringDate.png")); setMessage(Messages.getString("SerienTerminDialog.this.message")); //$NON-NLS-1$ Group grpTermin = new Group(area, SWT.NONE); grpTermin.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); grpTermin.setLayout(new GridLayout(6, false)); grpTermin.setText(Messages.getString("SerienTerminDialog.grpTermin.text")); //$NON-NLS-1$ Label lblBeginn = new Label(grpTermin, SWT.NONE); lblBeginn.setText(Messages.getString("SerienTerminDialog.lblBeginn.text")); //$NON-NLS-1$ dateTimeBegin = new DateTime(grpTermin, SWT.BORDER | SWT.TIME | SWT.SHORT); dateTimeBegin.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ updateSpinner(); } }); Label lblEnde = new Label(grpTermin, SWT.NONE); lblEnde.setText(Messages.getString("SerienTerminDialog.lblEnde.text")); //$NON-NLS-1$ dateTimeEnd = new DateTime(grpTermin, SWT.BORDER | SWT.TIME | SWT.SHORT); dateTimeEnd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ updateSpinner(); } }); Label lblDauer = new Label(grpTermin, SWT.NONE); lblDauer.setText(Messages.getString("SerienTerminDialog.lblDauer.text")); //$NON-NLS-1$ durationSpinner = new Spinner(grpTermin, SWT.NONE); durationSpinner.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); durationSpinner.setMinimum(5); durationSpinner.setMaximum(1440); durationSpinner.setIncrement(5); durationSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ int value = durationSpinner.getSelection(); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.HOUR_OF_DAY, dateTimeBegin.getHours()); cal.set(Calendar.MINUTE, dateTimeBegin.getMinutes()); cal.add(Calendar.MINUTE, value); dateTimeEnd.setHours(cal.get(Calendar.HOUR_OF_DAY)); dateTimeEnd.setMinutes(cal.get(Calendar.MINUTE)); } }); { Group grpSerienmuster = new Group(area, SWT.NONE); grpSerienmuster.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); grpSerienmuster.setLayout(new GridLayout(1, false)); grpSerienmuster.setText(Messages.getString("SerienTerminDialog.grpSerienmuster.text")); //$NON-NLS-1$ tabFolderSeriesPattern = new CTabFolder(grpSerienmuster, SWT.BORDER); tabFolderSeriesPattern .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); tabFolderSeriesPattern.setSelectionBackground(Display.getCurrent().getSystemColor( SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT)); tabFolderSeriesPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ serienTermin.setSeriesType((SeriesType) e.item.getData()); } }); CTabItem tbtmDaily = new CTabItem(tabFolderSeriesPattern, SWT.NONE); tbtmDaily.setText(Messages.getString("SerienTerminDialog.tbtmDaily.text")); //$NON-NLS-1$ tbtmDaily.setData(SeriesType.DAILY); Label lblNoConfigurationNecessary = new Label(tabFolderSeriesPattern, SWT.NONE); tbtmDaily.setControl(lblNoConfigurationNecessary); lblNoConfigurationNecessary.setText(Messages .getString("SerienTerminDialog.lblNoConfigurationNecessary.text")); //$NON-NLS-1$ CTabItem tbtmWeekly = new CTabItem(tabFolderSeriesPattern, SWT.NONE); tbtmWeekly.setText(Messages.getString("SerienTerminDialog.tbtmWeekly.text")); //$NON-NLS-1$ wsc = new WeeklySeriesComposite(tabFolderSeriesPattern, SWT.NONE); tbtmWeekly.setControl(wsc); tbtmWeekly.setData(SeriesType.WEEKLY); CTabItem tbtmMonthly = new CTabItem(tabFolderSeriesPattern, SWT.NONE); tbtmMonthly.setText(Messages.getString("SerienTerminDialog.tbtmMonthly.text")); //$NON-NLS-1$ msc = new MonthlySeriesComposite(tabFolderSeriesPattern, SWT.NONE); tbtmMonthly.setControl(msc); new Label(msc, SWT.NONE); tbtmMonthly.setData(SeriesType.MONTHLY); CTabItem tbtmYearly = new CTabItem(tabFolderSeriesPattern, SWT.NONE); tbtmYearly.setText(Messages.getString("SerienTerminDialog.tbtmYearly.text")); //$NON-NLS-1$ ysc = new YearlySeriesComposite(tabFolderSeriesPattern, SWT.NONE); tbtmYearly.setControl(ysc); tbtmYearly.setData(SeriesType.YEARLY); } Group grpSeriendauer = new Group(area, SWT.NONE); grpSeriendauer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); grpSeriendauer.setLayout(new GridLayout(3, false)); grpSeriendauer.setText(Messages.getString("SerienTerminDialog.grpSeriendauer.text")); //$NON-NLS-1$ Label beginOfSeries = new Label(grpSeriendauer, SWT.NONE); beginOfSeries.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); beginOfSeries.setText(Messages.getString("SerienTerminDialog.beginOfSeries.text")); //$NON-NLS-1$ dateTimeBeginOfSeries = new DateTime(grpSeriendauer, SWT.BORDER | SWT.DROP_DOWN | SWT.LONG); dateTimeBeginOfSeries.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); dateTimeBeginOfSeries.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ TimeTool tt = new TimeTool(serienTermin.getSeriesStartDate()); wsc.setWeekNumberLabel(tt.get(Calendar.WEEK_OF_YEAR), tt.get(Calendar.YEAR)); super.widgetSelected(e); } }); Composite composite = new Composite(grpSeriendauer, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); GridLayout composite_layout = new GridLayout(2, false); composite_layout.marginHeight = 0; composite_layout.marginWidth = 0; composite.setLayout(composite_layout); btnEndsAfter = new Button(composite, SWT.RADIO); btnEndsAfter.setText(Messages.getString("SerienTerminDialog.btnEndsAfter.text")); //$NON-NLS-1$ btnEndsAfter.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ serienTermin.setEndingType(EndingType.AFTER_N_OCCURENCES); } }); Composite composite_1 = new Composite(composite, SWT.NONE); composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); GridLayout composite_1_layout = new GridLayout(2, false); composite_1_layout.marginHeight = 0; composite_1_layout.marginWidth = 0; composite_1.setLayout(composite_1_layout); txtEndsAfterNOccurences = new Text(composite_1, SWT.BORDER); txtEndsAfterNOccurences .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); Label lblNewLabel = new Label(composite_1, SWT.NONE); lblNewLabel.setText(Messages.getString("SerienTerminDialog.lblNewLabel.text")); //$NON-NLS-1$ btnEndsOn = new Button(composite, SWT.RADIO); btnEndsOn.setText(Messages.getString("SerienTerminDialog.btnEndsOn.text")); //$NON-NLS-1$ btnEndsOn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ serienTermin.setEndingType(EndingType.ON_SPECIFIC_DATE); } }); dateEndsOn = new DateTime(composite, SWT.BORDER); groupData = new Group(area, SWT.NONE); groupData.setText(Messages.getString("SerienTerminDialog.groupData.text")); //$NON-NLS-1$ groupData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); groupData.setLayout(new GridLayout(4, false)); txtReason = new Text(groupData, SWT.BORDER); txtReason.setMessage(Messages.getString("SerienTerminDialog.txtReason.message")); //$NON-NLS-1$ txtReason.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Link linkCustomText = new Link(groupData, SWT.NONE); linkCustomText.setText(Messages.getString("SerienTerminDialog.linkCustomText.text")); //$NON-NLS-1$ linkCustomText.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ InputDialog inp = new InputDialog(getShell(), "Enter Text", "Enter Text/Name for the appointment", "", null); //$NON-NLS-1$ if (inp.open() == Dialog.OK) { txtContact.setText(inp.getValue()); serienTermin.setContact(null); } } }); Link linkSelectContact = new Link(groupData, SWT.NONE); linkSelectContact.setText(Messages.getString("SerienTerminDialog.linkSelectContact.text")); //$NON-NLS-1$ linkSelectContact.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ KontaktSelektor ksl = new KontaktSelektor(getShell(), Kontakt.class, "Datum zuordnen", "Please select the contact the date is assigned to", Kontakt.DEFAULT_SORT); if (ksl.open() == Dialog.OK) { serienTermin.setContact((Kontakt) ksl.getSelection()); if (serienTermin.getContact() != null) { txtContact.setText(serienTermin.getContact().getLabel()); } } } }); Label lblArea = new Label(groupData, SWT.NONE); lblArea.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1)); lblArea.setText(Messages.getString("SerienTerminDialog.lblArea.text")); //$NON-NLS-1$ comboArea = new Combo(groupData, SWT.NONE); comboArea.setItems(Activator.getDefault().getResources()); comboArea.setText(Activator.getDefault().getActResource()); comboArea.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ Activator.getDefault().setActResource(comboArea.getText()); } }); txtContact = new Text(groupData, SWT.BORDER); txtContact.setMessage(Messages.getString("SerienTerminDialog.txtContact.message")); //$NON-NLS-1$ txtContact.setEditable(false); txtContact.setTextLimit(80); txtContact.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); m_bindingContext = initDataBindings(); initDialog(); return area; } private void initDialog(){ if (serienTermin.getContact() != null) { setTitle(serienTermin.getContact().getLabel()); txtContact.setText(serienTermin.getContact().getLabel()); } else { setTitle("Kein Kontakt ausgewählt."); txtContact.setText(serienTermin.getFreeText()); } // switch (serienTermin.getSeriesType()) { case DAILY: tabFolderSeriesPattern.setSelection(0); break; case WEEKLY: tabFolderSeriesPattern.setSelection(1); String[] pattern = serienTermin.getSeriesPatternString().split(","); wsc.getTxtWeekDistance().setText(pattern[0]); if (pattern.length > 1) { for (int i = 0; i < pattern[1].length(); i++) { char c = pattern[1].charAt(i); wsc.getWeekdays()[Character.getNumericValue(c)].setSelection(true); } } Calendar cal = Calendar.getInstance(); cal.setTime(serienTermin.getSeriesStartDate()); wsc.setWeekNumberLabel(cal.get(Calendar.WEEK_OF_YEAR), cal.get(Calendar.YEAR)); break; case MONTHLY: tabFolderSeriesPattern.setSelection(2); msc.setDay(Integer.parseInt(serienTermin.getSeriesPatternString())); break; case YEARLY: tabFolderSeriesPattern.setSelection(3); ysc.setDay(Integer.parseInt(serienTermin.getSeriesPatternString().substring(0, 2))); ysc.setMonth(Integer.parseInt(serienTermin.getSeriesPatternString().substring(2, 4))); break; default: break; } // switch (serienTermin.getEndingType()) { case AFTER_N_OCCURENCES: btnEndsAfter.setSelection(true); txtEndsAfterNOccurences.setText(serienTermin.getEndingPatternString()); break; case ON_SPECIFIC_DATE: btnEndsOn.setSelection(true); Calendar calendar = Calendar.getInstance(); calendar.setTime(serienTermin.getEndsOnDate()); dateEndsOn.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)); break; default: break; } // updateSpinner(); } /** * Create contents of the button bar. * * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent){ createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); Button button = createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); button.setText(Messages.getString("SerienTerminDialog.other.text")); //$NON-NLS-1$ Button button_1 = createButton(parent, IDialogConstants.STOP_ID, "remove series", false); button_1.setText(Messages.getString("SerienTerminDialog.other.text_1")); //$NON-NLS-1$ } @Override protected void buttonPressed(int buttonId){ super.buttonPressed(buttonId); switch (buttonId) { case Dialog.OK: if (result == APPLY) { serienTermin.persist(); close(); } else if (result == CANCEL) { cancelEntry(); } break; case IDialogConstants.STOP_ID: cancelEntry(); break; default: break; } ElexisEventDispatcher.reload(Termin.class); } private void cancelEntry(){ serienTermin.delete(false); setReturnCode(IDialogConstants.STOP_ID); close(); } @Override protected void okPressed(){ switch (serienTermin.getSeriesType()) { case DAILY: switch (serienTermin.getEndingType()) { case AFTER_N_OCCURENCES: serienTermin.setSeriesPatternString(txtEndsAfterNOccurences.getText()); break; case ON_SPECIFIC_DATE: serienTermin.setSeriesPatternString(SerienTermin.dateFormat.format(serienTermin .getEndsOnDate())); break; } break; case WEEKLY: StringBuilder sb = new StringBuilder(); sb.append(wsc.getTxtWeekDistance().getText() + ","); for (int i = 1; i < 8; i++) { if (wsc.getWeekdays()[i].getSelection()) { sb.append(i); } } serienTermin.setSeriesPatternString(sb.toString()); break; case MONTHLY: serienTermin.setSeriesPatternString(msc.getDay() + ""); break; case YEARLY: serienTermin.setSeriesPatternString(decimalFormat.format(ysc.getDay()) + decimalFormat.format(ysc.getMonth())); break; default: break; } if (serienTermin.getContact() == null) { serienTermin.setFreeText(txtContact.getText()); } // ask user about next step (keep, change, cancel) in case of a lock time collision if (serienTermin.collidesWithLockTimes()) { MessageDialog collisionDialog = new MessageDialog(getShell(), Messages.getString("SerienTerminDialog.dlgLockTimesConflict"), getTitleImageLabel().getImage(), Messages.getString("SerienTerminDialog.dlgLockTimesSeriesConflict"), MessageDialog.WARNING, new String[] { Messages.getString("SerienTerminDialog.dlgBtnApplyAnyway"), Messages.getString("SerienTerminDialog.dlgBtnChange"), Messages.getString("SerienTerminDialog.dlgBtnCancel") }, 0); result = collisionDialog.open(); } else { result = APPLY; super.okPressed(); } } protected DataBindingContext initDataBindings(){ DataBindingContext bindingContext = new DataBindingContext(); // IObservableValue observeSelectionDateTimeBeginObserveWidget = WidgetProperties.selection().observe(dateTimeBegin); IObservableValue beginTimeSerienTerminObserveValue = PojoProperties.value("beginTime").observe(serienTermin); bindingContext.bindValue(observeSelectionDateTimeBeginObserveWidget, beginTimeSerienTerminObserveValue, null, null); // IObservableValue observeSelectionDateTimeEndObserveWidget = WidgetProperties.selection().observe(dateTimeEnd); IObservableValue endTimeSerienTerminObserveValue = PojoProperties.value("endTime").observe(serienTermin); bindingContext.bindValue(observeSelectionDateTimeEndObserveWidget, endTimeSerienTerminObserveValue, null, null); // IObservableValue observeSelectionDateTimeBeginOfSeriesObserveWidget = WidgetProperties.selection().observe(dateTimeBeginOfSeries); IObservableValue seriesStartDateSerienTerminObserveValue = PojoProperties.value("seriesStartDate").observe(serienTermin); bindingContext.bindValue(observeSelectionDateTimeBeginOfSeriesObserveWidget, seriesStartDateSerienTerminObserveValue, null, null); // IObservableValue observeTextTxtReasonObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtReason); IObservableValue reasonSerienTerminObserveValue = PojoProperties.value("reason").observe(serienTermin); bindingContext.bindValue(observeTextTxtReasonObserveWidget, reasonSerienTerminObserveValue, null, null); // IObservableValue observeSelectionDateEndsOnObserveWidget = WidgetProperties.selection().observe(dateEndsOn); IObservableValue endsOnDateSerienTerminObserveValue = PojoProperties.value("endsOnDate").observe(serienTermin); bindingContext.bindValue(observeSelectionDateEndsOnObserveWidget, endsOnDateSerienTerminObserveValue, null, null); // IObservableValue observeTextTxtEndsAfterNOccurencesObserveWidget = WidgetProperties.text(SWT.Modify).observe(txtEndsAfterNOccurences); IObservableValue endsAfterNDatesSerienTerminObserveValue = PojoProperties.value("endsAfterNDates").observe(serienTermin); bindingContext.bindValue(observeTextTxtEndsAfterNOccurencesObserveWidget, endsAfterNDatesSerienTerminObserveValue, null, null); // return bindingContext; } private void updateSpinner(){ int endTime = (dateTimeEnd.getHours() * 60) + dateTimeEnd.getMinutes(); int startTime = (dateTimeBegin.getHours() * 60) + dateTimeBegin.getMinutes(); int result = endTime - startTime; if (result < 0) result = 0; durationSpinner.setSelection(result); } public SerienTermin getSerienTermin(){ return serienTermin; } }
true
0d362b8a0ae3e402503b3204881cba841e6ef8fa
Java
JiniSekh2017/orderCalculator
/ordercalculator/src/main/java/com/order/promotion/Promotion.java
UTF-8
201
1.742188
2
[]
no_license
/** * */ package com.order.promotion; import com.order.model.Item; import java.util.List; /** * @author JINI * */ public interface Promotion { void applyPromotion(List<Item> itemList); }
true
115bd59e8dcfd34c6a3c527232e8e36e46b415aa
Java
AmanBisht01/Animal-Info-
/app/src/main/java/com/aman/animalsinfo/AnimalInfo.java
UTF-8
707
2.234375
2
[]
no_license
package com.aman.animalsinfo; import android.content.Intent; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class AnimalInfo extends AppCompatActivity { ImageView img; TextView txt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.animalinfo); img=findViewById(R.id.imgcircle); txt=findViewById(R.id.animal); Intent intent=getIntent(); img.setImageResource(intent.getIntExtra("image", R.drawable.dolphi)); txt.setText(intent.getStringExtra("name")); } }
true
97a36461060fe067929b6dcb4e5c80a214a7281e
Java
tcolar/javaontracks
/src/net/jot/persistance/JOTModelAddons.java
UTF-8
5,522
2.75
3
[ "Artistic-2.0" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.jot.persistance; import net.jot.persistance.query.JOTQueryInterface; import net.jot.persistance.query.JOTQueryManager; /** * * @author tcolar */ abstract class JOTModelAddons { /** * Simply use a manually built query (JOTQueryBuilder) * In my be simpler to directly call JOTQueryBuilder, which is what this does anyhow. * JOTQueryBuilder.findAll(User.class).where("name>'a'").exeute(); * @param transaction * @param queryBuilder * @return * @throws java.lang.Exception */ /* public static Vector findByQuery(JOTTransaction transaction, JOTQueryBuilder queryBuilder) throws Exception { return JOTQueryManager.findByQuery(transaction, queryBuilder); } public static Vector findByQuery(JOTQueryBuilder queryBuilder) throws Exception { return JOTQueryManager.findByQuery(queryBuilder); }*/ /** * Returns the record whith the given ID <br> * @param dataId * @return a JOTModel object or null if none found */ /*public static JOTModel findByID(JOTTransaction transaction, Class modelClass, long id) throws Exception { return JOTQueryManager.findByID(transaction, modelClass, id); } public static JOTModel findByID(Class modelClass, long id) throws Exception { return JOTQueryManager.findByID(modelClass, id); }*/ /** * This is here, if you want to make manual custom SQL calls not covered by the other methods<br> * * NOTE: your request MUST return records matching your model.<br> * * @param sql ie: "select * from 'users' where first=?, last=? order by name" ... etc ... * @param params ie: ['John','Doe'] * @return a Vector of JOTModel objects */ /*public static Vector findUsingSQL(JOTTransaction transaction, Class modelClass, String sql, String[] params, JOTStatementFlags flags) throws Exception { return JOTQueryManager.findUsingSQL(transaction, modelClass, sql, params, flags); } public static Vector findUsingSQL(JOTTransaction transaction, Class modelClass, String sql, String[] params) throws Exception { return JOTQueryManager.findUsingSQL(transaction, modelClass, sql, params); } public static Vector findUsingSQL(Class modelClass, String sql, String[] params) throws Exception { return JOTQueryManager.findUsingSQL(modelClass, sql, params); }*/ /** * Returns all the records matching the parameters<br> * @return a Vector of JOTModel objects */ /*public static Vector find(JOTTransaction transaction, Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.find(transaction, modelClass, params); } public static Vector find(Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.find(modelClass, params); }*/ /** * Returns the first records matching the parameters<br> * @return a JOTModel object or null if none found */ /*public static JOTModel findOne(JOTTransaction transaction, Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.findOne(transaction, modelClass, params); } public static JOTModel findOne(Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.findOne(modelClass, params); }*/ /** * Returns a record if it is found in the database * If it is not found then create a blank new one and return it. * @param modelClass * @param params * @return * @throws java.lang.Exception */ /*public static JOTModel findOrCreateOne(JOTTransaction transaction, Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.findOrCreateOne(transaction, modelClass, params); } public static JOTModel findOrCreateOne(Class modelClass, JOTSQLQueryParams params) throws Exception { return JOTQueryManager.findOrCreateOne(modelClass, params); } public static void dumpAllToCSV(OutputStream out, Class modelClass) throws Exception { JOTQueryManager.dumpToCSV(out, modelClass); }*/ /** * Dump a whole table (model) data into a stream(ie file) in CSV format * @param out * @param modelClass * @param params * @throws java.lang.Exception */ /*public static void dumpAllToCSV(OutputStream out, Class modelClass, JOTSQLQueryParams params) throws Exception { JOTQueryManager.dumpToCSV(out, modelClass, params); } */ public static void deleteWholeTable(JOTTransaction transaction, Class modelClass) throws Exception { JOTModelMapping mapping = JOTQueryManager.getMapping(transaction, modelClass); JOTQueryInterface impl = JOTQueryManager.getImplementation(mapping.getQueryClassName()); impl.deleteTable(transaction, mapping); } /** * Creates the table in the DB, if it doesn't exists yet */ protected static void createTableIfNecessary(JOTTransaction transaction, Class modelClass) throws Exception { JOTModelMapping mapping = JOTQueryManager.getMapping(transaction, modelClass); JOTQueryInterface impl = JOTQueryManager.getImplementation(mapping.getQueryClassName()); impl.createTable(transaction, mapping); } }
true
b070435306605e94eb49c4fb08e367f5b083bf98
Java
risha9177719594/springmvc
/src/main/java/com/biller/model/yahoo/Team.java
UTF-8
2,131
1.976563
2
[]
no_license
package com.biller.model.yahoo; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="Team") public class Team { String team; String teamid; String teamId; String teamName; String teamType; String teamCategory; List<Ranking> ranking; List<String> rank; List<Captain> captain; String id; String matchwon; @XmlAttribute(name="Team") public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } @XmlAttribute(name="teamid") public String getTeamid() { return teamid; } public void setTeamid(String teamid) { this.teamid = teamid; } @XmlAttribute(name="id") public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlAttribute(name="matchwon") public String getMatchwon() { return matchwon; } public void setMatchwon(String matchwon) { this.matchwon = matchwon; } @XmlElement(name="TeamId") public String getTeamId() { return teamId; } public void setTeamId(String teamId) { this.teamId = teamId; } @XmlElement(name="TeamName") public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } @XmlElement(name="TeamType") public String getTeamType() { return teamType; } public void setTeamType(String teamType) { this.teamType = teamType; } @XmlElement(name="TeamCategory") public String getTeamCategory() { return teamCategory; } public void setTeamCategory(String teamCategory) { this.teamCategory = teamCategory; } @XmlElement(name="Ranking") public List<Ranking> getRanking() { return ranking; } public void setRanking(List<Ranking> ranking) { this.ranking = ranking; } @XmlElement(name="Captain") public List<Captain> getCaptain() { return captain; } public void setCaptain(List<Captain> captain) { this.captain = captain; } @XmlElement(name="Ranking") public List<String> getRank() { return rank; } public void setRank(List<String> rank) { this.rank = rank; } }
true
da420d84108f7702d846453836a3958ba8cdf9a4
Java
harsh8687/TradeValidationWebApp
/src/main/java/com/cs/trade/Trade.java
UTF-8
4,073
2.234375
2
[]
no_license
package com.cs.trade; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Trade { private String customer; private String ccyPair; private String type; private String direction; private String tradeDate; private String amount1; private String amount2; private String rate; private String valueDate; private String legalEntity; private String trader; private String style; private String excerciseStartDate; private String expiryDate; private String premiumDate; private String deliveryDate; public String getDeliveryDate() { return deliveryDate; } public void setDeliveryDate(String deliveryDate) { this.deliveryDate = deliveryDate; } public String getExcerciseStartDate() { return excerciseStartDate; } public void setExcerciseStartDate(String excerciseStartDate) { this.excerciseStartDate = excerciseStartDate; } public String getExpiryDate() { return expiryDate; } public void setExpiryDate(String expiryDate) { this.expiryDate = expiryDate; } public String getPremiumDate() { return premiumDate; } public void setPremiumDate(String premiumDate) { this.premiumDate = premiumDate; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public String getCcyPair() { return ccyPair; } public void setCcyPair(String ccyPair) { this.ccyPair = ccyPair; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } public String getTradeDate() { return tradeDate; } public void setTradeDate(String tradeDate) { this.tradeDate = tradeDate; } public String getAmount1() { return amount1; } public void setAmount1(String amount1) { this.amount1 = amount1; } public String getAmount2() { return amount2; } public void setAmount2(String amount2) { this.amount2 = amount2; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getValueDate() { return valueDate; } public void setValueDate(String valueDate) { this.valueDate = valueDate; } public String getLegalEntity() { return legalEntity; } public void setLegalEntity(String legalEntity) { this.legalEntity = legalEntity; } public String getTrader() { return trader; } public void setTrader(String trader) { this.trader = trader; } @Override public String toString() { return "Trade{" + "customer='" + customer + '\'' + ", ccyPair='" + ccyPair + '\'' + ", type='" + type + '\'' + ", direction='" + direction + '\'' + ", tradeDate='" + tradeDate + '\'' + ", amount1='" + amount1 + '\'' + ", amount2='" + amount2 + '\'' + ", rate='" + rate + '\'' + ", valueDate='" + valueDate + '\'' + ", legalEntity='" + legalEntity + '\'' + ", trader='" + trader + '\'' + ", style='" + style + '\'' + ", excerciseStartDate='" + excerciseStartDate + '\'' + ", expiryDate='" + expiryDate + '\'' + ", premiumDate='" + premiumDate + '\'' + ", deliveryDate='" + deliveryDate + '\'' + '}'; } }
true
73d84cbfd07678f754ea412c24b8d7e417edb1dd
Java
project-kotinos/play2-maven-test-projects
/play24/external-modules/deadbolt/java/app/security/MyHandlerCache.java
UTF-8
994
2.328125
2
[ "Apache-2.0" ]
permissive
package security; import be.objectify.deadbolt.java.DeadboltHandler; import be.objectify.deadbolt.java.cache.HandlerCache; import javax.inject.Singleton; import java.util.HashMap; import java.util.Map; /** * @author Steve Chaloner (steve@objectify.be) */ @Singleton public class MyHandlerCache implements HandlerCache { private final DeadboltHandler defaultHandler = new MyDeadboltHandler(); private final Map<String, DeadboltHandler> handlers = new HashMap<>(); public MyHandlerCache() { handlers.put(HandlerKeys.DEFAULT.key, defaultHandler); handlers.put(HandlerKeys.ALT.key, new MyAlternativeDeadboltHandler()); handlers.put(HandlerKeys.BUGGY.key, new BuggyDeadboltHandler()); handlers.put(HandlerKeys.NO_USER.key, new NoUserDeadboltHandler()); } @Override public DeadboltHandler apply(final String key) { return handlers.get(key); } @Override public DeadboltHandler get() { return defaultHandler; } }
true
27b556c9b1300288721b44558ccb9b524082016f
Java
shengligo/xyx_boot_v1
/src/main/java/com/shell/xyxv1/service/EssayService.java
UTF-8
622
1.679688
2
[]
no_license
package com.shell.xyxv1.service; import com.baomidou.mybatisplus.extension.service.IService; import com.shell.xyxv1.core.entity.vo.Result; import com.shell.xyxv1.entity.Essay; import com.shell.xyxv1.entity.request.EssayRequest; import com.shell.xyxv1.entity.vo.EssayVo; import com.shell.xyxv1.util.PageWrapper; /** * <p> * 文章分享 服务类 * </p> * * @author shell * @since 2021-08-31 */ public interface EssayService extends IService<Essay> { Result updateOrInsertEssay(EssayRequest request); PageWrapper<EssayVo> getEssay(EssayRequest request); Result getEssayDetail(EssayRequest request); }
true
c1e4f71d879bbf9dc853acaacc34c80ae9494a89
Java
anthonysaka/Java-Programming
/20161565 - P2/src/backEnd/Vivienda.java
UTF-8
991
2.625
3
[]
no_license
package backEnd; public class Vivienda extends Cuenta { private int mesesAhorro; private float montoMensual; /* Constructor */ public Vivienda(String codigo, float saldo, int mesesApertura, int diaCorteMes, String estado, float interes, float comision, int mesesAhorro, float montoMensual) { super(codigo, saldo, mesesApertura, diaCorteMes, estado); this.mesesAhorro = mesesAhorro; this.montoMensual = montoMensual; } /* Gets and Sets */ public int getMesesAhorro() { return mesesAhorro; } public float getMontoMensual() { return montoMensual; } public void setMesesAhorro(int mesesAhorro) { this.mesesAhorro = mesesAhorro; } public void setMontoMensual(float montoMensual) { this.montoMensual = montoMensual; } @Override float interes() { float cantInteres = 0.0f; cantInteres = (float) (0.03 * montoMensual * mesesApertura); this.setInteres(cantInteres); return cantInteres; } }
true
6be8f47088ed5cc7723dc58c8bb547ba1b372db2
Java
Karthikb777/SDE-sheet-practice
/src/DSAprep/D11medianOf2SortedArrays.java
UTF-8
3,496
4.21875
4
[]
no_license
package DSAprep; /* * find the median of 2 sorted arrays: * brute force method: * merge both the arrays and find the median * * optimized method: using binary search * cutting the 2 arrays such that a condition is met * take the search space as 0 to length of longest array * * cut both the arrays as follows * cut1 will be our mid * cut2 will be (n1 + n2 + 1) / 2 - cut1 * * place l1, r1, l2, r2 according to the cuts made * l1 will be one index before the cut, l2 will be the index of the cut * r1 will be one index before the cut, r2 will be the index of the cut * * if l1 <= r2 and l2 <= r1, * then we made the cuts perfectly, so return max of left + min of right / 2 * else if l1 > r2, then, shrink the search space by moving leftwards i.e high = cut1 - 1 * else shrink the search space rightwards by doing low = cut2 + 1 * * TC - O(log min(n1, n2)) * SC - O(1) * */ import java.util.ArrayList; import java.util.Collections; import java.util.List; public class D11medianOf2SortedArrays { // brute force method public static int brute(int[] arr1, int[] arr2) { List<Integer> res = new ArrayList<>(); for (int i : arr1) { res.add(i); } for (int i : arr2) { res.add(i); } Collections.sort(res); return res.get(res.size() / 2); } // optimized method public static int optimized(int[] arr1, int[] arr2) { int n1 = arr1.length; int n2 = arr2.length; // we always take the longest array as n1 so we make sure n1 is the longest array if (n1 < n2) optimized(arr2, arr1); // defining the search space - [0 ..... n1] int high, low; low = 0; high = n1; // defining the pointers - left1, right1, left2, right2 int l1, r1, l2, r2; // while low doesn't cross high while(low <= high) { // calculating our cuts // cut1 will be our mid int cut1 = (low + high) / 2; // we calculate cut2 as shown below int cut2 = (n1 + n2 + 1) / 2 - cut1; // place all the pointers according to the cuts while handling the edge cases l1 = cut1 == 0 ? Integer.MIN_VALUE : arr1[cut1 - 1]; l2 = cut2 == 0 ? Integer.MIN_VALUE : arr2[cut2 - 1]; r1 = cut1 == n1 ? Integer.MAX_VALUE : arr1[cut1]; r2 = cut2 == n2 ? Integer.MAX_VALUE : arr2[cut2]; // if the below condition is satisfied, then we have placed our cuts perfectly // we return the max of left of cuts + min of right of cuts / 2 if (l1 <= r2 && l2 <= r1) { // if even length if ((n1 + n2) % 2 == 0) return (Math.max(l1, r1) + Math.min(l2, r2)) / 2; // if odd length else return Math.max(l1, l2); } // if l1 > r2, shrink the search space by moving leftwards else if (l1 > r2) high = cut1 - 1; // move rightwards else low = cut1 + 1; } return 0; } public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5, 7}; int[] b = {3, 6, 9}; System.out.println(optimized(a, b)); } }
true
bbade390dbca36400b7997805dc6b5a53bc2a7fe
Java
CrisDC/SISCAE
/siscae/src/main/java/pe/edu/unmsm/fisi/siscae/mapper/base/IReporteMapper.java
UTF-8
148
1.6875
2
[]
no_license
package pe.edu.unmsm.fisi.siscae.mapper.base; import java.util.List; public interface IReporteMapper<T> { public List<T> reporte(); }
true
e7b8a97dd8f15e1eabbf347ab64e6cde007fdd34
Java
Tyeboe/NeuBeginnings
/src/enums/Character/ModifiableFields.java
UTF-8
79
1.546875
2
[]
no_license
package enums.Character; public enum ModifiableFields { HITPOINTS, ENERGY }
true
232a2f20bd43badb13be793cd048639f5387458e
Java
GeneralCycles15/OOP_Calendar
/src/MonthlyCalendarPackage/NewEvent.java
UTF-8
4,606
2.859375
3
[]
no_license
package MonthlyCalendarPackage; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.JComboBox; import javax.swing.JRadioButton; import javax.swing.JButton; import javax.swing.JTextField; public class NewEvent extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void createNewEventForm(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { NewEvent frame = new NewEvent(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public NewEvent() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 460, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblMonth = new JLabel("Month:"); lblMonth.setBounds(40, 40, 46, 14); contentPane.add(lblMonth); JLabel lblDay = new JLabel("Day:"); lblDay.setBounds(121, 40, 46, 14); contentPane.add(lblDay); JLabel lblTime = new JLabel("Time:"); lblTime.setBounds(204, 40, 46, 14); contentPane.add(lblTime); JLabel lblStart = new JLabel("Start:"); lblStart.setBounds(204, 75, 46, 14); contentPane.add(lblStart); JLabel lblEnd = new JLabel("End:"); lblEnd.setBounds(204, 113, 46, 14); contentPane.add(lblEnd); JLabel lblNewEvent = new JLabel("New Event"); lblNewEvent.setHorizontalAlignment(SwingConstants.CENTER); lblNewEvent.setBounds(183, 11, 81, 14); contentPane.add(lblNewEvent); String[] monthNames = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }; JComboBox<Object> comboBox = new JComboBox<Object>(monthNames); comboBox.setBounds(40, 72, 46, 20); contentPane.add(comboBox); String[] dayNumbers = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}; JComboBox<Object> comboBox_1 = new JComboBox<Object>(dayNumbers); comboBox_1.setBounds(121, 72, 46, 20); contentPane.add(comboBox_1); String[] times = {"12:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00" }; JComboBox<Object> comboBox_2 = new JComboBox<Object>(times); comboBox_2.setBounds(260, 72, 59, 20); contentPane.add(comboBox_2); JComboBox<Object> comboBox_3 = new JComboBox<Object>(times); comboBox_3.setBounds(260, 110, 59, 20); contentPane.add(comboBox_3); JRadioButton rdbtnAm = new JRadioButton("AM"); rdbtnAm.setBounds(319, 71, 51, 23); contentPane.add(rdbtnAm); JRadioButton rdbtnPm = new JRadioButton("PM"); rdbtnPm.setBounds(367, 71, 46, 23); contentPane.add(rdbtnPm); JRadioButton rdbtnNewRadioButton = new JRadioButton("AM"); rdbtnNewRadioButton.setBounds(319, 109, 51, 23); contentPane.add(rdbtnNewRadioButton); JRadioButton rdbtnPm_1 = new JRadioButton("PM"); rdbtnPm_1.setBounds(367, 109, 46, 23); contentPane.add(rdbtnPm_1); JButton btnAddEvent = new JButton("Add Event"); btnAddEvent.setBounds(78, 227, 100, 23); contentPane.add(btnAddEvent); btnAddEvent.addActionListener(new ActionListener() { //if add event button press @Override public void actionPerformed(ActionEvent e) { setVisible(false); } } ); JButton btnCancel = new JButton("Cancel"); btnCancel.setBounds(276, 227, 89, 23); contentPane.add(btnCancel); btnCancel.addActionListener(new ActionListener() { //if cancel button press @Override public void actionPerformed(ActionEvent e) { setVisible(false); } } ); JLabel lblEventName = new JLabel("Event Name:"); lblEventName.setBounds(40, 113, 89, 14); contentPane.add(lblEventName); textField = new JTextField(); textField.setBounds(40, 138, 127, 20); contentPane.add(textField); textField.setColumns(10); JLabel lblDescription = new JLabel("Description:"); lblDescription.setBounds(40, 169, 74, 14); contentPane.add(lblDescription); textField_1 = new JTextField(); textField_1.setBounds(40, 194, 325, 20); contentPane.add(textField_1); textField_1.setColumns(10); } }
true
6cd454203e3c97af18592b69c7a76449a73fca5e
Java
souviksh3/Random-Receipe
/app/src/main/java/com/example/random_recipe/api/ApiInterface.java
UTF-8
244
1.921875
2
[]
no_license
package com.example.random_recipe.api; import com.example.random_recipe.model.Recipes; import retrofit2.Call; import retrofit2.http.GET; public interface ApiInterface { @GET("random.php") Call<Recipes> getRecipes(); }
true
684d19c8c8f6b44f608c12788de5fd1a33406f14
Java
uk-gov-mirror/UKHomeOffice.hocs-audit
/src/main/java/uk/gov/digital/ho/hocs/audit/auditdetails/exception/AuditExportException.java
UTF-8
234
1.835938
2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package uk.gov.digital.ho.hocs.audit.auditdetails.exception; public class AuditExportException extends RuntimeException { public AuditExportException(String msg, Object... args) { super(String.format(msg, args)); } }
true
6c6e09ff409506e2dad7f8551ac5d0b9e064b390
Java
jlin53882/simplefarming
/src/main/java/enemeez/simplefarming/SideProxy.java
UTF-8
2,825
1.96875
2
[ "MIT" ]
permissive
package enemeez.simplefarming; import enemeez.simplefarming.client.ClientRenderer; import enemeez.simplefarming.config.Config; import enemeez.simplefarming.events.EventSetup; import enemeez.simplefarming.init.ModBlocks; import enemeez.simplefarming.init.ModItems; import enemeez.simplefarming.init.ModWorldGen; import enemeez.simplefarming.integration.CompostItems; import enemeez.simplefarming.integration.FlammableBlocks; import enemeez.simplefarming.world.gen.SimpleGeneration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent; import net.minecraftforge.fml.event.server.FMLServerStartingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLPaths; public class SideProxy { SideProxy() { ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.CONFIG, "simplefarming.toml"); Config.loadConfig(Config.CONFIG, FMLPaths.CONFIGDIR.get().resolve("simplefarming.toml").toString()); IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus(); eventBus.addListener(SideProxy::commonSetup); eventBus.addListener(SideProxy::enqueueIMC); eventBus.addListener(SideProxy::processIMC); eventBus.addListener(ModBlocks::registerAll); eventBus.addListener(ModItems::registerAll); eventBus.addListener(ModWorldGen::registerAll); MinecraftForge.EVENT_BUS.addListener(SideProxy::serverStarting); } private static void commonSetup(FMLCommonSetupEvent event) { SimpleFarming.LOGGER.debug("common setup"); EventSetup.setupEvents(); SimpleGeneration.registerWorldGen(); FlammableBlocks.registerFlammable(); CompostItems.register(); } private static void enqueueIMC(final InterModEnqueueEvent event) { } private static void processIMC(final InterModProcessEvent event) { } private static void serverStarting(FMLServerStartingEvent event) { } static class Client extends SideProxy { Client() { FMLJavaModLoadingContext.get().getModEventBus().addListener(Client::clientSetup); } private static void clientSetup(FMLClientSetupEvent event) { ClientRenderer.registerBlocks(); } } static class Server extends SideProxy { Server() { FMLJavaModLoadingContext.get().getModEventBus().addListener(Server::serverSetup); } private static void serverSetup(FMLDedicatedServerSetupEvent event) { } } }
true
33536c1eccfa04a8c814fadc4cb25eeca1cf69b6
Java
medic/TextForms
/src/main/java/net/frontlinesms/plugins/textforms/search/AnswerQueryGenerator.java
UTF-8
2,836
2.40625
2
[]
no_license
package net.frontlinesms.plugins.textforms.search; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import net.frontlinesms.plugins.textforms.TextFormsLogger; import net.frontlinesms.plugins.textforms.search.QueryGenerator; import net.frontlinesms.plugins.textforms.ui.components.PagedAdvancedTableController; import org.springframework.context.ApplicationContext; import com.ibm.icu.util.Calendar; /** * AnswerQueryGenerator * @author dalezak * */ public class AnswerQueryGenerator extends QueryGenerator { private static final TextFormsLogger LOG = TextFormsLogger.getLogger(AnswerQueryGenerator.class); public AnswerQueryGenerator(ApplicationContext appCon, PagedAdvancedTableController resultsTable) { super(appCon, resultsTable); } @Override public void startSearch(String text) { super.runQuery(getSearchQuery(text, null, false, null, null)); } @Override public void startSearch(String text, String sortColumn, boolean sortAscending) { super.runQuery(getSearchQuery(text, sortColumn, sortAscending, null, null)); } public void startSearch(String text, String sortColumn, boolean sortAscending, String date, String phoneNumber) { super.runQuery(getSearchQuery(text, sortColumn, sortAscending, date, phoneNumber)); } private String getSearchQuery(String text, String sortColumn, boolean sortAscending, String dateString, String phoneNumber) { LOG.debug("text=%s date=%S contact=%s", text, dateString, phoneNumber); String query = "SELECT fr FROM Answer fr"; query += " WHERE (lower(fr.organizationId) LIKE lower('%"+text+"%')"; query += " OR lower(fr.question.name) LIKE lower('%"+text+"%')"; query += " OR lower(fr.question.keyword) LIKE lower('%"+text+"%'))"; if (phoneNumber != null && phoneNumber.length() > 0) { query += " AND lower(fr.contact.phoneNumber) LIKE lower('%"+phoneNumber+"%')"; } if (dateString != null && dateString.length() > 0) { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); try { Date date = dateFormat.parse(dateString); Calendar startDate = Calendar.getInstance(); startDate.setTime(date); startDate.set(Calendar.HOUR_OF_DAY, 0); query += String.format(" AND fr.dateSubmitted >= %d ", startDate.getTimeInMillis()); Calendar endDate = Calendar.getInstance(); endDate.setTime(date); endDate.set(Calendar.HOUR_OF_DAY, 23); endDate.set(Calendar.MINUTE, 59); query += String.format(" AND fr.dateSubmitted <= %d ", endDate.getTimeInMillis()); } catch (Exception e) { //do nothing } } if (sortColumn != null && sortColumn.length() > 0) { if (sortAscending) { query += String.format(" ORDER BY fr.%s ASC", sortColumn); } else { query += String.format(" ORDER BY fr.%s DESC", sortColumn); } } return query; } }
true
26a296f1174b17666d5afa1eb504c6378ac6581d
Java
01gurpreet/eBooks
/app/src/main/java/com/kinfoitsolutions/e_booksnew/adapters/LibraryBookAdapter.java
UTF-8
2,606
2.3125
2
[]
no_license
package com.kinfoitsolutions.e_booksnew.adapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.kinfoitsolutions.e_booksnew.R; import com.kinfoitsolutions.e_booksnew.response.LibraryResponse.Book; import com.squareup.picasso.Picasso; import java.util.List; public class LibraryBookAdapter extends RecyclerView.Adapter<LibraryBookAdapter.MyViewHolder> { Context context; private List<Book> books; private mLibraryBookClickListener mLibraryBookClickListener; public interface mLibraryBookClickListener { void mClickRecommeded(View v, int pos, String listsName, String name, String file, String bookFile); } public LibraryBookAdapter(Context context, List<Book> books) { this.context = context; this.books = books; } @NonNull @Override public LibraryBookAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_library, parent, false); return new LibraryBookAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull LibraryBookAdapter.MyViewHolder holder, int position) { final Book lists = books.get(position); try { Picasso.get().load(lists.getBookImage()).fit() .placeholder(R.drawable.loading) .error(R.drawable.no_image) .into(holder.book_image); } catch (Exception e) { e.printStackTrace(); holder.book_image.setImageResource(R.drawable.no_image); } holder.download_book.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(lists.getBookFile()))); } }); } @Override public int getItemCount() { return books.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView book_image,download_book; public MyViewHolder(@NonNull View itemView) { super(itemView); book_image = (ImageView)itemView.findViewById(R.id.book_image); download_book = (ImageView)itemView.findViewById(R.id.download_book); } } }
true
36e50075f958058790c87051043768b1df3448dc
Java
hymanath/PA
/partyanalyst-service/trunk/src/main/java/com/itgrids/partyanalyst/model/SelfAppraisalRuleProgram.java
UTF-8
2,856
2.21875
2
[]
no_license
package com.itgrids.partyanalyst.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.LazyToOne; import org.hibernate.annotations.LazyToOneOption; import org.hibernate.annotations.NotFoundAction; @Entity @Table(name = "self_appraisal_rule_program") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class SelfAppraisalRuleProgram { private Long selfAppraisalRuleProgramId; private Long selfAppraisalRuleId; private Long selfAppraisalProgramId; private SelfAppraisalRule selfAppraisalRule; private SelfAppraisalProgram selfAppraisalProgram; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="self_appraisal_rule_program_id", unique=true, nullable=false) public Long getSelfAppraisalRuleProgramId() { return selfAppraisalRuleProgramId; } public void setSelfAppraisalRuleProgramId(Long selfAppraisalRuleProgramId) { this.selfAppraisalRuleProgramId = selfAppraisalRuleProgramId; } @Column(name = "self_appraisal_rule_id") public Long getSelfAppraisalRuleId() { return selfAppraisalRuleId; } public void setSelfAppraisalRuleId(Long selfAppraisalRuleId) { this.selfAppraisalRuleId = selfAppraisalRuleId; } @Column(name = "self_appraisal_program_id") public Long getSelfAppraisalProgramId() { return selfAppraisalProgramId; } public void setSelfAppraisalProgramId(Long selfAppraisalProgramId) { this.selfAppraisalProgramId = selfAppraisalProgramId; } @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name="self_appraisal_rule_id",insertable=false,updatable=false) @LazyToOne(LazyToOneOption.NO_PROXY) @org.hibernate.annotations.NotFound(action=NotFoundAction.IGNORE) public SelfAppraisalRule getSelfAppraisalRule() { return selfAppraisalRule; } public void setSelfAppraisalRule(SelfAppraisalRule selfAppraisalRule) { this.selfAppraisalRule = selfAppraisalRule; } @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinColumn(name="self_appraisal_program_id",insertable=false,updatable=false) @LazyToOne(LazyToOneOption.NO_PROXY) @org.hibernate.annotations.NotFound(action=NotFoundAction.IGNORE) public SelfAppraisalProgram getSelfAppraisalProgram() { return selfAppraisalProgram; } public void setSelfAppraisalProgram(SelfAppraisalProgram selfAppraisalProgram) { this.selfAppraisalProgram = selfAppraisalProgram; } }
true
9bdd6d9ca06f5f6bc22294e43d02ce24044a6383
Java
injin/java-design-patterns
/src/main/java/abstractFactory/samsung/SamSungElevatorFactory.java
UTF-8
491
2.484375
2
[]
no_license
package abstractFactory.samsung; import abstractFactory.factory.Door; import abstractFactory.factory.ElevatorFactory; public class SamSungElevatorFactory extends ElevatorFactory { private static ElevatorFactory factory; private SamSungElevatorFactory() { } public static ElevatorFactory getInstance() { if(factory == null) factory = new SamSungElevatorFactory(); return factory; } public Door createDoor() { return new SamSungDoor(); } }
true
2284f969ebaa6dd3de621360ef91d3111e3c2343
Java
rootkwak528/PiT
/backend/src/main/java/com/ssafy/pit/common/response/BaseResponseBody.java
UTF-8
630
2.390625
2
[]
no_license
package com.ssafy.pit.common.response; import lombok.Getter; import lombok.Setter; @Getter @Setter public class BaseResponseBody { String message = null; Integer statusCode = null; public BaseResponseBody() {} public BaseResponseBody(Integer statusCode) { this.statusCode = statusCode; } public BaseResponseBody(Integer statusCode, String message) { this.statusCode = statusCode; this.message = message; } public static BaseResponseBody of(Integer statusCode, String message) { BaseResponseBody body = new BaseResponseBody(); body.message = message; body.statusCode = statusCode; return body; } }
true
cbda31d47b5a553ee8729475d8a1defef3cb15bc
Java
SistrScarlet/TheScarletHillMod
/src/main/java/com/sistr/scarlethill/entity/DefaultGroupController.java
UTF-8
2,107
2.59375
3
[ "MIT" ]
permissive
package com.sistr.scarlethill.entity; import com.google.common.collect.Sets; import net.minecraft.entity.Entity; import net.minecraft.world.server.ServerWorld; import javax.annotation.Nullable; import java.util.Optional; import java.util.Set; import java.util.UUID; public abstract class DefaultGroupController<E extends Entity> implements IGroupController<E> { private final Set<UUID> members = Sets.newHashSet(); private final int memberLimit; @Nullable private UUID leader; public DefaultGroupController(int memberLimit) { this.memberLimit = memberLimit; } @Override public boolean isLeader(E target) { if (this.leader == null) return false; return this.leader.equals(target.getUniqueID()); } @Override public void setLeaderId(UUID newLeader) { this.leader = newLeader; addMember(newLeader); } @Override public Optional<UUID> getLeaderId() { return Optional.ofNullable(this.leader); } @Override public Optional<E> getLeader() { Optional<ServerWorld> optionalServerWorld = getServerWorld(); if (optionalServerWorld.isPresent()) { Optional<UUID> LeaderId = getLeaderId(); if (LeaderId.isPresent()) { Entity leaderEntity = optionalServerWorld.get().getEntityByUuid(LeaderId.get()); return Optional.ofNullable((E) leaderEntity); } } return Optional.empty(); } abstract protected Optional<ServerWorld> getServerWorld(); @Override public boolean isMember(UUID target) { return this.members.contains(target); } @Override public Set<UUID> getMembers() { return Sets.newHashSet(this.members); } @Override public boolean addMember(UUID newMember) { if (this.memberLimit <= this.members.size() || this.members.contains(newMember)) { return false; } return this.members.add(newMember); } @Override public void removeMember(UUID member) { this.members.remove(member); } }
true
2cc78eaff677b2814baec29602c1906857e2067e
Java
gitSina9468/springboot-mongodb
/src/main/java/com/zzm/demo/dao/IUserDao.java
UTF-8
537
2.109375
2
[]
no_license
package com.zzm.demo.dao; import com.zzm.demo.pojo.User; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; /** * @Description:数据操作层,不需要写实现类,但method命名一定要对应实体类属性 * @author 钟志苗 * @date 2017/9/19 15:17 * @version V1.0 */ public interface IUserDao extends MongoRepository<User, Integer> { User findByUuidAndNameOrAge(String uid,String name,int age); List<User> findByName(String name); long removeUserById(String id); }
true
b8deffd73c01af5d28992f65ee092bc5ab916ec5
Java
NickPakhomov/JavaRushTasks
/2.JavaCore/src/com/javarush/task/task18/task1821/Solution.java
UTF-8
1,105
3.421875
3
[]
no_license
package com.javarush.task.task18.task1821; /* Встречаемость символов */ import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import java.util.TreeMap; public class Solution { public static void main(String[] args) throws IOException { if (args == null || args.length < 1) throw new IllegalArgumentException("Пожалуйста, введите верные аргументы"); FileInputStream inputStream = new FileInputStream(args[0]); Map<Integer, Integer> map = new TreeMap<>(); while (inputStream.available() > 0) { int readByte = inputStream.read(); if (map.containsKey(readByte)) { map.put(readByte, map.get(readByte) + 1); } else { map.put(readByte, 1); } } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.printf("%s %d\n", (char)(int) entry.getKey(), entry.getValue()); } inputStream.close(); } }
true
ac6cad021dabdf3391800a5c318ed00f73caaa9e
Java
thrfox/DesignPatterns
/FacadeMode/Client.java
UTF-8
169
2.078125
2
[]
no_license
package FacadeMode; public class Client { public static void main(String[] args) { Fund fund = new Fund(); fund.buy(); fund.sell(); } }
true
a2e137a1a23f174e076ec88ff1bb7adb20048ec5
Java
kotovi/portal
/src/main/java/ru/geekbase/portal/controller/ResetPasswordController.java
UTF-8
5,249
2.171875
2
[]
no_license
package ru.geekbase.portal.controller; import com.fasterxml.jackson.annotation.JsonView; //import org.apache.commons.lang3.RandomStringUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import ru.geekbase.portal.domain.LectionView; import ru.geekbase.portal.domain.Notification; import ru.geekbase.portal.domain.User; import ru.geekbase.portal.repos.NotificationRepo; import ru.geekbase.portal.repos.UserRepo; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Controller @JsonView(LectionView.ForLectionList.class) @RequestMapping("/resetpassword") @Api(description = "контроллер для генерации нового пароля") public class ResetPasswordController { private final UserRepo userRepo; private final NotificationRepo notificationRepo; private final PasswordEncoder passwordEncoder; @Autowired ResetPasswordController(UserRepo userRepo, NotificationRepo notificationRepo, PasswordEncoder passwordEncoder){ this.userRepo = userRepo; this.notificationRepo = notificationRepo; this.passwordEncoder = passwordEncoder; } String redirectUrl; @GetMapping("{uuid}") @ApiOperation("мапинг генерит новый пароль и отправляет его по почте в случае совпадения uuid, в противном случае посылает") public String Resetpassword(@PathVariable("uuid") String uuid, Notification notification){ Optional<User> user = userRepo.findByPasswordResetUUID(uuid); if(user.isPresent()){ String paswd = generateCommonLangPassword(); user.get().setPassword(passwordEncoder.encode(paswd)); notification.setNotificationRecipient(user.get().getUserEmail()); notification.setNotificationSubject("Новый пароль для авторизации на сайте"); notification.setNotificationBody( "Здравствуйте," +user.get().getLastname()+" "+user.get().getFirstname()+" "+user.get().getSecname()+"! \n" + "Вами был сделан запрос на сброс пароля для доступа к системе! \n" + "Для входа в систему Вам необходимо авторизоваться со следующими учетными данными:" + "\n Логин: "+ user.get().getUsername()+" " + "\n Пароль: " +paswd+" "+ "\n \n Это письмо было отправлено Вам, так как адрес "+ user.get().getUserEmail()+" был указан при регистрации на https://portal.ismu.baikal.ru"+" "+ "\n \n Для отказа от получения уведомлений перейдите по ССЫЛКЕ: https://portal.ismu.baikal.ru/unsubscribe/"+user.get().getNotificationUUID()); notification.setCreateNotificationDateTime(LocalDateTime.now()); notification.setNotificationStatus(0); notification.setNotificationType(3); notification.setSourceId(user.get().getId()); notification.setUnsubscribeUUID(user.get().getNotificationUUID()); notification.setSourceId(user.get().getId()); notificationRepo.save(notification); redirectUrl = "redirect:/success_reset_password"; return redirectUrl; } else { redirectUrl = "redirect:/unsuccess_reset_password"; return redirectUrl; } } public String generateCommonLangPassword() { String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true); String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true); String numbers = RandomStringUtils.randomNumeric(2); String specialChar = RandomStringUtils.random(2, 33, 47, false, false); String totalChars = RandomStringUtils.randomAlphanumeric(2); String combinedChars = upperCaseLetters.concat(lowerCaseLetters) .concat(numbers) .concat(specialChar) .concat(totalChars); List<Character> pwdChars = combinedChars.chars() .mapToObj(c -> (char) c) .collect(Collectors.toList()); Collections.shuffle(pwdChars); String password = pwdChars.stream() .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString(); return password; } }
true
5825c8a46ceccb466bb867797bed01ef6c6d7cb0
Java
pedrohr1/unitri
/Analisador Full/src/Lexico/Listas/Operadores.java
UTF-8
613
2.4375
2
[]
no_license
package Lexico.Listas; import java.util.ArrayList; import java.util.List; public class Operadores { public static final List<String> Operadores = new ArrayList<String>(); static { Operadores.add("="); Operadores.add("+"); Operadores.add("-"); Operadores.add("*"); Operadores.add("/"); Operadores.add("&&"); Operadores.add("||"); Operadores.add("."); Operadores.add("=="); Operadores.add("<"); Operadores.add(">"); Operadores.add(">="); Operadores.add("<="); Operadores.add("!="); } }
true
0e6794867c802bf7e81596d8da890efe3d15eee9
Java
ofekbytes/spring-examples
/spring-example/src/com/ofekbytes/springExamples/pk001/ex004/Ex004.java
UTF-8
340
2.328125
2
[ "MIT" ]
permissive
package com.ofekbytes.springExamples.pk001.ex004; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Ex004 { // main // public static void main(String[] args) { //create object Coach myCoach = new TrackCoach(); //use the object System.out.println( myCoach.getDailyWorkout() ); } }
true
cdb87a0ddc360e84f303b7b1a94f4ca7d9c45114
Java
ferdiaa/teacher-apps
/src/main/java/id/ac/tazkia/dosen/entity/User.java
UTF-8
1,397
2.109375
2
[ "Apache-2.0" ]
permissive
package id.ac.tazkia.dosen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import lombok.Data; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; /** * * @author Ivans */ @Entity @Table(name = "c_security_user") public class User { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid2") @Getter @Setter private String id; @Column(nullable = false, unique = true) @Getter @Setter private String username; @Column(nullable = false) @Getter @Setter private Boolean active = Boolean.TRUE; @Transient @Getter @Setter private String password; @JsonIgnore @OneToOne(mappedBy = "user", optional = true) @Cascade(CascadeType.ALL) @Getter @Setter private UserPassword userPassword; @ManyToOne @JoinColumn(name = "id_role", nullable = false) @Getter @Setter private Role role; }
true
1c30beb5c5f4baed2204cf3b221a12f57164dd95
Java
Tha1n/CompilerWhileCpp
/whileComp/src-gen/org/xtext/example/whileCpp/impl/ExprAndImpl.java
UTF-8
8,812
1.585938
2
[]
no_license
/** */ package org.xtext.example.whileCpp.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.xtext.example.whileCpp.ExprAnd; import org.xtext.example.whileCpp.ExprOr; import org.xtext.example.whileCpp.WhileCppPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Expr And</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.xtext.example.whileCpp.impl.ExprAndImpl#getExprOr <em>Expr Or</em>}</li> * <li>{@link org.xtext.example.whileCpp.impl.ExprAndImpl#getExprAnd <em>Expr And</em>}</li> * <li>{@link org.xtext.example.whileCpp.impl.ExprAndImpl#getExprAndAtt <em>Expr And Att</em>}</li> * </ul> * * @generated */ public class ExprAndImpl extends MinimalEObjectImpl.Container implements ExprAnd { /** * The cached value of the '{@link #getExprOr() <em>Expr Or</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExprOr() * @generated * @ordered */ protected ExprOr exprOr; /** * The default value of the '{@link #getExprAnd() <em>Expr And</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExprAnd() * @generated * @ordered */ protected static final String EXPR_AND_EDEFAULT = null; /** * The cached value of the '{@link #getExprAnd() <em>Expr And</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExprAnd() * @generated * @ordered */ protected String exprAnd = EXPR_AND_EDEFAULT; /** * The cached value of the '{@link #getExprAndAtt() <em>Expr And Att</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExprAndAtt() * @generated * @ordered */ protected ExprAnd exprAndAtt; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ExprAndImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return WhileCppPackage.Literals.EXPR_AND; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExprOr getExprOr() { return exprOr; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetExprOr(ExprOr newExprOr, NotificationChain msgs) { ExprOr oldExprOr = exprOr; exprOr = newExprOr; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, WhileCppPackage.EXPR_AND__EXPR_OR, oldExprOr, newExprOr); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExprOr(ExprOr newExprOr) { if (newExprOr != exprOr) { NotificationChain msgs = null; if (exprOr != null) msgs = ((InternalEObject)exprOr).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - WhileCppPackage.EXPR_AND__EXPR_OR, null, msgs); if (newExprOr != null) msgs = ((InternalEObject)newExprOr).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - WhileCppPackage.EXPR_AND__EXPR_OR, null, msgs); msgs = basicSetExprOr(newExprOr, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WhileCppPackage.EXPR_AND__EXPR_OR, newExprOr, newExprOr)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getExprAnd() { return exprAnd; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExprAnd(String newExprAnd) { String oldExprAnd = exprAnd; exprAnd = newExprAnd; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WhileCppPackage.EXPR_AND__EXPR_AND, oldExprAnd, exprAnd)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExprAnd getExprAndAtt() { return exprAndAtt; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetExprAndAtt(ExprAnd newExprAndAtt, NotificationChain msgs) { ExprAnd oldExprAndAtt = exprAndAtt; exprAndAtt = newExprAndAtt; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, WhileCppPackage.EXPR_AND__EXPR_AND_ATT, oldExprAndAtt, newExprAndAtt); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExprAndAtt(ExprAnd newExprAndAtt) { if (newExprAndAtt != exprAndAtt) { NotificationChain msgs = null; if (exprAndAtt != null) msgs = ((InternalEObject)exprAndAtt).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - WhileCppPackage.EXPR_AND__EXPR_AND_ATT, null, msgs); if (newExprAndAtt != null) msgs = ((InternalEObject)newExprAndAtt).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - WhileCppPackage.EXPR_AND__EXPR_AND_ATT, null, msgs); msgs = basicSetExprAndAtt(newExprAndAtt, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WhileCppPackage.EXPR_AND__EXPR_AND_ATT, newExprAndAtt, newExprAndAtt)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case WhileCppPackage.EXPR_AND__EXPR_OR: return basicSetExprOr(null, msgs); case WhileCppPackage.EXPR_AND__EXPR_AND_ATT: return basicSetExprAndAtt(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case WhileCppPackage.EXPR_AND__EXPR_OR: return getExprOr(); case WhileCppPackage.EXPR_AND__EXPR_AND: return getExprAnd(); case WhileCppPackage.EXPR_AND__EXPR_AND_ATT: return getExprAndAtt(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case WhileCppPackage.EXPR_AND__EXPR_OR: setExprOr((ExprOr)newValue); return; case WhileCppPackage.EXPR_AND__EXPR_AND: setExprAnd((String)newValue); return; case WhileCppPackage.EXPR_AND__EXPR_AND_ATT: setExprAndAtt((ExprAnd)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case WhileCppPackage.EXPR_AND__EXPR_OR: setExprOr((ExprOr)null); return; case WhileCppPackage.EXPR_AND__EXPR_AND: setExprAnd(EXPR_AND_EDEFAULT); return; case WhileCppPackage.EXPR_AND__EXPR_AND_ATT: setExprAndAtt((ExprAnd)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case WhileCppPackage.EXPR_AND__EXPR_OR: return exprOr != null; case WhileCppPackage.EXPR_AND__EXPR_AND: return EXPR_AND_EDEFAULT == null ? exprAnd != null : !EXPR_AND_EDEFAULT.equals(exprAnd); case WhileCppPackage.EXPR_AND__EXPR_AND_ATT: return exprAndAtt != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (exprAnd: "); result.append(exprAnd); result.append(')'); return result.toString(); } } //ExprAndImpl
true
6c01e42e5dd37f71692a5a4128ba71a68c01bfc9
Java
kjungyoun/Java_Study_2021
/Algo/src/com/beak/Main_S5_1467_날짜계산.java
UTF-8
719
2.953125
3
[]
no_license
package com.beak; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main_S5_1467_날짜계산 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); // E,S,M 입력 int E = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int k = 0; int year = 0; while(true) { year = 15 * k + E; if(year%28 == S%28 && year%19 == M%19 ) { System.out.println(year); return; } k++; } } }
true
d2b82c75e8d4391db5f45e435e891f93f1f73ea7
Java
KuznecovAl/solderingIron
/databaseConnector/src/test/java/internet_shop/ConnectionManagerTest.java
UTF-8
358
2.03125
2
[]
no_license
package internet_shop; import org.junit.Assert; import java.sql.Connection; public class ConnectionManagerTest { @org.junit.Test public void returnConnection() { if (ConnectionManager.getConnection() == null) { Assert.assertEquals(1, 0); } else { Assert.assertEquals(1, 1); } } }
true
aba60ee7b43e1e50fda99b00f7752bb445727947
Java
martinjuhasz/Softwaretechnik
/Server/relaxo/src/main/java/de/teamrocket/relaxo/rest/filter/CheckAdmin.java
UTF-8
311
1.914063
2
[]
no_license
package de.teamrocket.relaxo.rest.filter; import javax.ws.rs.NameBinding; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Filter, welches prüft, ob der User ein Administrator ist. */ @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface CheckAdmin { }
true
a786284e01ed863359be2aede12f162a531d6b71
Java
SdaJavaTorun/Zaliczenie_AR
/src/main/java/com/sda/erp/controller/ReadWriteObjectToFile.java
UTF-8
6,159
3.078125
3
[]
no_license
package com.sda.erp.controller; import com.sda.erp.model.PersonModel; import java.io.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ReadWriteObjectToFile implements Serializable{ static List<ListController> listToFile = new ArrayList<>(); static OutputStream fileOutputStream = null; static ObjectOutput objectOutputStream = null; static OutputStream bufferOut = null; // setter glównej listy public void setListToFile (List<ListController> listToFile) { ReadWriteObjectToFile.listToFile = listToFile; } public static void writeToTXTFile (String file) throws FileNotFoundException { PrintWriter out = new PrintWriter(file); out.printf("%-4s %-20s %-20s %-4s", "Id", "Imię", "Nazwisko", "Wiek\n"); for (ListController lf: listToFile) out.printf("%-4d %-20s %-20s %-4d\n", lf.getPersonId(), lf.getPersonFirstName(), lf.getPersonLastName(), lf.getPersonAge()); out.close(); } public void sortBySalaryInFile(boolean dir) throws Exception { if (dir == true) { // sortowanie rosnąco listToFile.sort(Comparator.comparing(ListController::getSalary)); ReadWriteObjectToFile.writeToTXTFile("SortOrder.txt"); } else { // sortowanie malejąco listToFile.sort(Comparator.comparing(ListController::getSalary).reversed()); ReadWriteObjectToFile.writeToTXTFile("SortRevOrd"); } } public void writeToHTMLFile() throws FileNotFoundException { String fileHTML = "pracownicy.html"; PrintWriter html = new PrintWriter(fileHTML); StringBuilder sb = new StringBuilder(); sb.append("<!DOCTYPE html>") .append("<html>") .append("<meta charset=UTF-8>") .append("<head>") .append("</head>") .append("<body>") .append("<table>") .append("<tr>") .append("<td width=20%> Nazwisko </td>") .append("<td width=10%> Imię </td>") .append("<td width=5%> Płeć </td>") .append("<td width=5%> Nr działu </td>") .append("<td width=20%> Płaca </td>") .append("<td width=10%> Wiek </td>") .append("</tr>"); for (ListController hp: listToFile) { sb.append("<tr>") .append("<td width=20%>").append(hp.getPersonLastName()).append("</td>") .append("<td width=10%>").append(hp.getPersonFirstName()).append("</td>") .append("<td width=5%>").append(hp.getPersonGender()).append("</td>") .append("<td width=5%>").append(hp.getDepartmentNr()).append("</td>") .append("<td width=20%>").append(hp.getSalary()).append("</td>") .append("<td width=10%>").append(hp.getPersonAge()).append("</td>") .append("</tr>"); } sb.append("</table></body></html>"); html.print(sb); html.close(); } public void showDataLongestLastName() { System.out.println("Dane osoby o najdłuższym nazwisku"); ListController longestLastName = new ListController(); for (ListController pll: listToFile) { if (pll.getPersonLastName().length() >= longestLastName.getPersonLastName().length()) { longestLastName = pll; } } longestLastName.toString(); } public void dataCoding(String fileName) throws Exception { PrintWriter out = new PrintWriter(fileName); out.printf("%-4s %-20s %-20s %-4s", "Id", "Imię", "Nazwisko", "Wiek\n"); double aveSal = listToFile.stream() .mapToDouble(s -> s.getSalary()) .average() .getAsDouble(); for (ListController as: listToFile) { if (as.getSalary() < aveSal) out.printf("%-4d %-20s %-20s %-4d\n", as.getPersonId(), as.getPersonFirstName(), codeLastName(as.getPersonLastName()), as.getPersonAge()); } out.close(); } public String codeLastName (String lastNameToCrypt) { StringBuilder sb = new StringBuilder(lastNameToCrypt.length()); for (int i = 1; i<lastNameToCrypt.length(); i++) sb.append('*'); return sb.toString(); } public static void writeToFile(String fileName, List<PersonController> modelList) throws Exception { try { fileOutputStream = new FileOutputStream(fileName, true); bufferOut = new BufferedOutputStream(fileOutputStream); objectOutputStream = new ObjectOutputStream(bufferOut); objectOutputStream.close(); } finally { if (objectOutputStream != null) objectOutputStream.close(); fileOutputStream.close(); bufferOut.close(); objectOutputStream.close(); } } public void readFromFile() throws Exception { String fileName = ""; try { FileInputStream fileInputStream = new FileInputStream(fileName); InputStream bufferIn = new BufferedInputStream(fileInputStream); ObjectInputStream objectInputStream = new ObjectInputStream(bufferIn); PersonModel readCase = null; List<PersonModel> recordList = new ArrayList<>(); while (true) { try { readCase = (PersonModel) objectInputStream.readObject(); recordList.add(readCase); } catch (EOFException exc) { break; } } recordList.forEach(s -> System.out.println(s.getFirstName())); fileOutputStream.close(); objectOutputStream.close(); } catch (FileNotFoundException err) { err.printStackTrace(); } } }
true
3f1135efcf39d7fbc4a464d02a9b6d6cbcedfe34
Java
OSS-MaMaMoo/OpenSource_MOOMOO_Project
/MooMooCalc/src/com/moomoo/moomoocalc/MathdroidTests.java
UTF-8
7,922
2.25
2
[]
no_license
package com.moomoo.moomoocalc; import android.app.*; import android.os.*; import android.text.*; import android.text.style.*; import android.view.*; import android.widget.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import com.moomoo.calc.test.CalculatorTest; import com.moomoo.calc.test.UnitsConverterTest; import junit.framework.*; public class MathdroidTests extends Activity { private static final int BLACK = 0xff000000; private static final int GREEN = 0xff00ff00; private static final int RED = 0xffff0000; private static final int WHITE = 0xffffffff; private TestState mTestState; public static class TestState implements TestListener { public Activity mUi; private TestSuite mSuite; private long mCurrentTestStartMs; private int mTestSuiteSize; private ArrayList<Test> mFinishedTests = new ArrayList<Test>(); private ArrayList<Long> mTestDurationsMs = new ArrayList<Long>(); private ArrayList<Test> mFailedTests = new ArrayList<Test>(); private ArrayList<Throwable> mFailures = new ArrayList<Throwable>(); public TestState(Activity ui, Class<?>... classes) { mUi = ui; mSuite = new TestSuite(classes); mTestSuiteSize = mSuite.countTestCases(); } public void runTests() { textView().setText(""); final TestResult result = new TestResult(); result.addListener(this); long t0 = System.currentTimeMillis(); // Run the tests in parallel. int threadCount = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(threadCount); submitTests(executor, mSuite, result); executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException ex) { throw new RuntimeException(ex); } long t1 = System.currentTimeMillis(); updateAtEnd(t1 - t0); } private static void submitTests(ExecutorService executor, TestSuite suite, final TestResult result) { for (int i = 0; i < suite.testCount(); ++i) { final Test test = suite.testAt(i); if (test instanceof TestSuite) { submitTests(executor, (TestSuite) test, result); } else { executor.execute(new Runnable() { @Override public void run() { test.run(result); } }); } } } public synchronized void addError(Test test, Throwable failure) { mFailedTests.add(test); mFailures.add(failure); } public void addFailure(Test test, AssertionFailedError failure) { addError(test, failure); } public synchronized void startTest(Test test) { mCurrentTestStartMs = System.currentTimeMillis(); } private synchronized boolean isFailure(Test t) { return mFailedTests.contains(t); } public synchronized void endTest(Test test) { mFinishedTests.add(test); long endMs = System.currentTimeMillis(); long durationMs = (endMs - mCurrentTestStartMs); mTestDurationsMs.add(durationMs); appendTestInfo(test, durationMs); updateProgressBar(); updateSummary(); } private void appendTestInfo(Test test, long durationMs) { String testName = test.toString().replaceAll("test(.*)\\((.*)\\)", "$2.$1"); boolean failed = isFailure(test); String text = (failed ? "[<font color='#ff0000'>FAIL</font>]" : "[<font color='#00ff00'>PASS</font>]") + " " + testName; if (durationMs > 1000) { text += " (<font color='#ffff00'>" + prettyDurationMs(durationMs) + "</font>)"; } text += "<br>\n"; if (failed) { // TODO: this is probably more useful in logcat than in the UI. Throwable failure = mFailures.get(mFailedTests.size() - 1); text += stackTrace(failure); } appendHtml(text); } private TextView summary() { return (TextView) mUi.findViewById(R.id.test_summary); } private ProgressBar progressBar() { return (ProgressBar) mUi.findViewById(R.id.test_progress); } private TextView textView() { return (TextView) mUi.findViewById(R.id.test_results); } public synchronized void updateProgressBar() { progressBar().post(new Runnable() { public void run() { // For some reason, calling setMax from onCreate didn't always work. (On JB.) progressBar().setMax(mTestSuiteSize); progressBar().setProgress(mFinishedTests.size()); } }); } public synchronized void updateSummary() { int failureCount = mFailures.size(); int passCount = mFinishedTests.size() - failureCount; String summary = String.format(Locale.US, "Passed: %d/%d Failed: %d", passCount, mTestSuiteSize, failureCount); setSummary(mFailedTests.isEmpty() ? GREEN : RED, summary); } public synchronized void updateOnRotation(Activity ui) { mUi = ui; // Refill the main text view. for (int i = 0; i < mFinishedTests.size(); ++i) { appendTestInfo(mFinishedTests.get(i), mTestDurationsMs.get(i)); } updateProgressBar(); updateSummary(); } public synchronized void updateAtEnd(long durationMs) { progressBar().post(new Runnable() { public void run() { progressBar().setVisibility(View.GONE); } }); if (mFailedTests.isEmpty()) { setSummary(GREEN, "All " + mFinishedTests.size() + " tests passed in " + prettyDurationMs(durationMs) + "."); } } private void setSummary(final int backgroundColor, final String text) { final TextView summary = summary(); summary.post(new Runnable() { public void run() { summary.setText(text); summary.setBackgroundColor(backgroundColor); summary.setTextColor((backgroundColor == RED) ? WHITE : BLACK); } }); } private static String stackTrace(Throwable t) { StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); String[] lines = stringWriter.getBuffer().toString().split("\n"); // Find the junit framework's first call into user code. int end = lines.length - 1; for (; end >= 0; --end) { if (lines[end].indexOf("java.lang.reflect.Method.invokeNative(Native Method)") != -1) { break; } } // Take all the user frames, but filter out the junit Assert machinery. String result = ""; for (int i = 0; i < end; ++i) { if (lines[i].indexOf("junit.framework.Assert.") == -1) { result += lines[i] + "\n<br>"; } } return result; } private static String prettyDurationMs(long ms) { return String.format(Locale.US, "%.1f s", ((double) ms) / 1000.0); } private void appendHtml(final String text) { final TextView textView = textView(); textView.post(new Runnable() { public void run() { textView.append(Html.fromHtml(text)); ((ScrollView) textView.getParent()).smoothScrollTo(0, textView.getBottom()); } }); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.level_3_diagnostics); mTestState = (TestState) getLastNonConfigurationInstance(); if (mTestState == null) { // TODO: pass the classes in as an Intent extra. mTestState = new TestState(this, CalculatorTest.class, UnitsConverterTest.class); new Thread(new Runnable() { public void run() { mTestState.runTests(); } }).start(); } else { mTestState.updateOnRotation(this); } } @Override public Object onRetainNonConfigurationInstance() { return mTestState; // Remember our testing progress so far. } }
true
d71040e0af88c37e18c647760eed65b2f34ca846
Java
GorelovaRF/hibernate3
/src/main/java/es/ua/eps/cursohibernate/querying/Ejercicio4.java
UTF-8
2,057
2.90625
3
[]
no_license
package es.ua.eps.cursohibernate.querying; import java.util.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.query.Query; import es.ua.eps.cursohibernate.util.HibernateUtil; import es.ua.eps.cursohibernate.model.Conexion; public class Ejercicio4 { public static void main (String [] args) { Ejercicio4.getId(); Ejercicio4.getPremium(); Ejercicio4.getDelete(); } private static void getId() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); System.out.println("Session factory creada"); session.beginTransaction(); Query query = session.getNamedQuery("selectId").setParameter("id_usuario", 11001); List<Date> dates = query.list(); for (Date date : dates) { System.out.println("Usuario con id 11001: " + date); } session.getTransaction().commit(); HibernateUtil.getSessionFactory().close(); } private static void getPremium() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); System.out.println("Session factory creada"); session.beginTransaction(); Query query = session.getNamedQuery("selectPremium"); query.setParameter("id_perfil", 2); List<Conexion> conexiones = query.list(); for (Conexion conexion : conexiones) { System.out.println( "Conexiones de usuarios con perfil Premium: " + conexion.getMomento_entrada()); } session.getTransaction().commit(); HibernateUtil.getSessionFactory().close(); } private static void getDelete() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); System.out.println("Session factory creada"); session.beginTransaction(); org.hibernate.query.Query query = session.getNamedQuery("deleteRows").setParameter("id_perfil", 0); int deletedRows = query.executeUpdate(); System.out.println("Se borraron: "+ deletedRows + " perfiles"); session.getTransaction().rollback(); HibernateUtil.getSessionFactory().close(); } }
true
3bbbecf4ed044298afe84c0964edcc7136915161
Java
yashika06/QuotesApp
/app/src/main/java/com/iskylar/yashika/quoteswallpaper/Helper/DownloadDbHelper.java
UTF-8
2,395
2.59375
3
[]
no_license
package com.iskylar.yashika.quoteswallpaper.Helper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.design.widget.Snackbar; import android.widget.Toast; import com.iskylar.yashika.quoteswallpaper.Model.Image; import java.util.ArrayList; /** * Created by Yashika on 12-07-2017. */ public class DownloadDbHelper { private SQLiteDatabase wdatabase; private SQLiteDatabase rdatabase; public static final String DWNLD_TABLE = "downloads"; public static final String IMAGE_ID = "image"; public static final String IMAGE_DES = "description"; private Context context; private DBHelper dbHelper; public DownloadDbHelper(Context context) { this.context=context; dbHelper = new DBHelper(context); wdatabase = dbHelper.getWritableDatabase(); rdatabase = dbHelper.getReadableDatabase(); } public boolean insertData(int imageRes,String desc){ if (!checkExistence(imageRes)){ ContentValues values = new ContentValues(); values.put(IMAGE_ID,imageRes); values.put(IMAGE_DES,desc); wdatabase.insert(DWNLD_TABLE,null,values); Toast.makeText(context,"image inserted",Toast.LENGTH_SHORT).show(); wdatabase.close(); return true; } else return false; } public boolean checkExistence(int imageRes){ String query = "SELECT "+IMAGE_ID+" FROM "+DWNLD_TABLE+" WHERE "+IMAGE_ID+" = '"+imageRes+"'"; Cursor cursor = rdatabase.rawQuery(query,null); if (cursor.getCount()>0){ return true; } else return false; } public ArrayList<Image> retrieveData(){ String query = "SELECT * FROM "+DWNLD_TABLE+""; Cursor cursor = rdatabase.rawQuery(query,null); ArrayList<Image> list = new ArrayList<>(); if(cursor.getCount()>0) { while (cursor.moveToNext()) { list.add(new Image(cursor.getInt(0), cursor.getString(1))); Toast.makeText(context, "list created", Toast.LENGTH_SHORT).show(); } } Toast.makeText(context, "size of list: "+list.size(), Toast.LENGTH_SHORT).show(); return list; } }
true
a8a316e9b13590387acf5370b849521943d41265
Java
FINAL-PRO/FINAL-PRO
/FinalProject/src/main/java/com/kh/dc/search/controller/SearchController.java
UTF-8
2,384
2.03125
2
[]
no_license
package com.kh.dc.search.controller; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.SessionAttributes; import com.kh.dc.common.vo.Board; import com.kh.dc.search.model.service.SearchService; @SessionAttributes(value= {"member"}) @Controller public class SearchController { @Autowired private SearchService searchService; @RequestMapping("/search/list.do") public String memberEnroll(@RequestParam String searchWord, Model model) { List<Board> searchResultList; if(!(searchWord.equals(""))) { searchResultList = searchService.searchResultList(searchWord); for(int i = 0; i < searchResultList.size(); i++) { String resultContent = ""; String originContent = searchResultList.get(i).getContent(); /*System.out.println("#####originContent" + i + " : " + originContent); */ if(originContent.contains("<p>")) { String patterString = "(&lt;img[^>]*src=[\\\"']?([^>\\\"']+)[\\\"']?[^>]*&gt;|<img[^>]*src=[\\\"']?([^>\\\"']+)[\\\"']?[^>]*>|<p>|</p>|<br>|&lt;p&gt;|&lt;/p&gt;)"; Pattern pattern = Pattern.compile(patterString); Matcher matcher = pattern.matcher(originContent); while(matcher.find()) { resultContent = matcher.replaceAll(""); } } else if(originContent.contains("&lt;p&gt;")){ String patterString = "(&lt;img[^>]*src=[\\\"']?([^>\\\"']+)[\\\"']?[^>]*&gt;|&lt;p&gt;|&lt;/p&gt;)"; Pattern pattern = Pattern.compile(patterString); Matcher matcher = pattern.matcher(originContent); while(matcher.find()) { resultContent = matcher.replaceAll(""); } }else { resultContent = originContent; } searchResultList.get(i).setContent(resultContent); /*System.out.println("#####" + i + " : " + searchResultList.get(i).getContent());*/ } } else { searchResultList = null; } model.addAttribute("searchWord", searchWord); model.addAttribute("searchResultList", searchResultList); return "/search/list"; } }
true
1afe8694f240684ae6b4591f363e6b1b2108e218
Java
baaahs/fragbyte
/src/main/java/whitesquare/glslcross/ast/ASTVisitor.java
UTF-8
1,247
2.15625
2
[ "MIT" ]
permissive
package whitesquare.glslcross.ast; public interface ASTVisitor { public void visitAssignment(Assignment assignment); public void visitBinaryOpBegin(BinaryOp op); public void visitBinaryOpMid(BinaryOp op); public void visitBinaryOpEnd(BinaryOp op); public void visitBlockStart(Block block); public void visitBlockEnd(Block block); public void visitConstruction(Construction construction); public void visitFunctionBegin(Function func); public void visitFunctionCall(FunctionCall call); public void visitFunctionEnd(Function func); public void visitFunctionMid(Function func); public void visitLoopBegin(Loop loop); public void visitLoopEnd(Loop loop); public void visitParameter(Parameter parameter); public void visitReturnStatement(ReturnStatement rtrn); public void visitSwizzleValue(SwizzleValue swizzleValue); public void visitTernaryOpAfterFirst(TernaryOp op); public void visitTernaryOpAfterSecond(TernaryOp op); public void visitTernaryOpEnd(TernaryOp op); public void visitUnaryOp(UnaryOp op); public void visitUnitStart(Unit unit); public void visitUnitEnd(Unit unit); public void visitValue(Value value); public void visitVariableStore(VariableStore value); public void visitVariableLoad(VariableLoad value); }
true
e7f10e44fb7ca47000cf553bb7b9187740f1ee78
Java
suichen/monk
/monk-common/src/main/java/com/fngry/monk/common/log/DigestLogger.java
UTF-8
1,651
2.59375
3
[]
no_license
package com.fngry.monk.common.log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class DigestLogger { private static final String SEPARATOR = ","; private final Logger logger; private final String template; public DigestLogger(Logger logger, String template) { this.logger = logger; this.template = template; } /** * need app set logger with digest.name in logback.xml * * @param name * @param value * @return */ public static DigestLogger newLogger(String name, String... value) { Logger logger = LoggerFactory.getLogger("digest." + name); if (value == null || value.length == 0) { return new DigestLogger(logger, null); } String template = createTemplate(value); return new DigestLogger(logger, template); } private static String createTemplate(String[] value) { return null; } public void log(Map<String, Object> context, boolean succeeded, long startTime, long endTime) { logger.info(renderTemplate(context, succeeded, startTime, endTime)); } private String renderTemplate(Map<String, Object> context, boolean succeeded, long startTime, long endTime) { StringBuffer logContent = new StringBuffer(); logContent.append(succeeded ? "Y" : "N").append(SEPARATOR); logContent.append(startTime).append("ms").append(SEPARATOR); logContent.append(endTime).append("ms").append(SEPARATOR); logContent.append(context.get("args")).append(SEPARATOR); return logContent.toString(); } }
true
17c8457987036cea475dcbdb1e877e09c16d04f5
Java
ttyrueiwoqp/LeetCode
/src/accepted/Q301_Q400/Q321_Q330/Q328.java
UTF-8
1,278
3.6875
4
[]
no_license
package accepted.Q301_Q400.Q321_Q330; import org.junit.Test; import util.ListNode; /** * Created by FJ on 1/24/2016. * <p/> * Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. * <p/> * You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. * <p/> * Example: * Given 1->2->3->4->5->NULL, * return 1->3->5->2->4->NULL. * <p/> * Note: * The relative order inside both the even and odd groups should remain as it was in the input. * The first node is considered odd, the second node even and so on ... */ public class Q328 { public ListNode oddEvenList(ListNode head) { if (head == null) { return null; } ListNode odd = head; ListNode even = head.next; ListNode mid = even; while (even != null && even.next != null) { odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next; } odd.next = mid; return head; } @Test public void test() { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); System.out.println(oddEvenList(head)); } }
true
ebbeb4cd2c2911b8bd9a8c05aaac9c92bb0d2a31
Java
emily-li/real-time-stock-trading-simulator
/report-generation/src/main/java/com/liemily/report/config/ReportGenerationConfig.java
UTF-8
542
1.546875
2
[]
no_license
package com.liemily.report.config; import com.liemily.stock.config.StockConfig; import com.liemily.user.config.UserConfig; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Lazy; /** * Created by Emily Li on 01/10/2017. */ @Configuration @ComponentScan("com.liemily.report") @Import({StockConfig.class, UserConfig.class}) @Lazy public class ReportGenerationConfig { }
true
33f8928e4362c230de238f2b24a6ea7db5818554
Java
tanvir1111/MoneyTracker
/app/src/main/java/com/tars/moneytracker/datamodel/NoteDataModel.java
UTF-8
549
2.34375
2
[]
no_license
package com.tars.moneytracker.datamodel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class NoteDataModel { @SerializedName("email") @Expose private String email; @SerializedName("note") @Expose private String note; public NoteDataModel(String email, String note) { this.email = email; this.note = note; } public NoteDataModel(String email) { this.email = email; } public String getNote() { return note; } }
true
c765103d61f17daf7fffeed704808c47f7925904
Java
graingrain/webapp
/webapp/webapp-mys/src/javabeans/UserInfo.java
UTF-8
3,396
2.34375
2
[]
no_license
package javabeans; import java.io.*; public class UserInfo implements Serializable { private String message=""; private String error_message=""; private String initiales=""; private String nom=""; private String prenom=""; private String mail=""; private String telephone=""; private String debug="0"; private int profil = 0; /** * Getter for property error_message. * @return Value of property error_message. */ public java.lang.String getError_message() { return error_message; } /** * Setter for property error_message. * @param error_message New value of property error_message. */ public void setError_message(java.lang.String error_message) { this.error_message = error_message; } /** * Getter for property initiales. * @return Value of property initiales. */ public java.lang.String getInitiales() { return initiales; } /** * Setter for property initiales. * @param initiales New value of property initiales. */ public void setInitiales(java.lang.String initiales) { this.initiales = initiales; } /** * Getter for property mail. * @return Value of property mail. */ public java.lang.String getMail() { return mail; } /** * Setter for property mail. * @param mail New value of property mail. */ public void setMail(java.lang.String mail) { this.mail = mail; } /** * Getter for property message. * @return Value of property message. */ public java.lang.String getMessage() { return message; } /** * Setter for property message. * @param message New value of property message. */ public void setMessage(java.lang.String message) { this.message = message; } /** * Getter for property nom. * @return Value of property nom. */ public java.lang.String getNom() { return nom; } /** * Setter for property nom. * @param nom New value of property nom. */ public void setNom(java.lang.String nom) { this.nom = nom; } /** * Getter for property prenom. * @return Value of property prenom. */ public java.lang.String getPrenom() { return prenom; } /** * Setter for property prenom. * @param prenom New value of property prenom. */ public void setPrenom(java.lang.String prenom) { this.prenom = prenom; } /** * Getter for property telephone. * @return Value of property telephone. */ public java.lang.String getTelephone() { return telephone; } /** * Setter for property telephone. * @param telephone New value of property telephone. */ public void setTelephone(java.lang.String telephone) { this.telephone = telephone; } /** * Getter for property debug. * @return Value of property debug. */ public java.lang.String getDebug() { return debug; } /** * Setter for property debug. * @param debug New value of property debug. */ public void setDebug(java.lang.String debug) { this.debug = debug; } /** * Getter for property profil. * @return Value of property profil. */ public int getProfil() { return profil; } /** * Setter for property profil. * @param profil New value of property profil. */ public void setProfil(int profil) { this.profil = profil; } }
true
ec60000622dd991853e11f0cde57a07d60a972fa
Java
yangwn/aws-elastic-search-with-springboot
/src/main/java/com/example/elasticsearch/repository/ArticleCustomRepository.java
UTF-8
1,229
1.867188
2
[]
no_license
package com.example.elasticsearch.repository; import com.example.elasticsearch.document.Article; import com.example.elasticsearch.dto.BulkOperationDTO; import com.example.elasticsearch.dto.ReIndexRequestDTO; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.index.reindex.BulkByScrollResponse; import java.util.List; public interface ArticleCustomRepository { SearchResponse findByTitle(String title); IndexResponse indexArticles(Article article); GetResponse findById(String id); DeleteResponse deleteArticleById(String id); UpdateResponse updateArticleById(String id, Article article); BulkResponse bulkOperation(BulkOperationDTO bulkOperation); MultiGetResponse getMultipleArticles(List<String> articleIdList); BulkByScrollResponse reIndexArticles(ReIndexRequestDTO reIndexRequest); SearchResponse searchArticles(String keyword); }
true
30a7839c7b90cb875670108fe2d3fb743d76b041
Java
77kkyu/Java_base
/src/post_DB_15/PostMig.java
UTF-8
2,023
3.171875
3
[]
no_license
package post_DB_15; import java.sql.ResultSet; import java.sql.Statement; import java.util.Calendar; import java.util.Scanner; import com.MyConnect; public class PostMig { public static void main(String[] args) throws Exception { // 테이블 데이터 조건줘서 옮기기 Statement stmt = MyConnect.Connect(); //1객체 Statement stmt2 = MyConnect.Connect(); //2객체 객체1개당 execute... Calendar cal = Calendar.getInstance(); //캘린더 객체생성 long sTime = cal.getTimeInMillis(); String searchValue = "서울"; String searchCode = "a2"; String sql = "SELECT * FROM post where "+searchCode+" LIKE '"+searchValue+"%' "; //서울지역만 출력 ResultSet rs = stmt.executeQuery(sql); System.out.println("=============================="); int num = 0; while(rs.next()) { String a1 = rs.getString("a1"); String a2 = rs.getString("a2"); String a3 = rs.getString("a3"); String a4 = rs.getString("a4"); String a5 = rs.getString("a5"); String a6 = rs.getString("a6"); String a7 = rs.getString("a7"); String a8 = rs.getString("a8"); sql = "SELECT count(*) as cnt FROM post_seoul " + "WHERE a1='"+a1+"' and a2='"+a2+"' and a3='"+a3+"' and a4='"+a4+"' " + "and a8='"+a8+"' "; ResultSet rs2 = stmt2.executeQuery(sql); //2번째 객체 rs2.next(); int cnt = rs2.getInt("cnt"); //중복검사 if(cnt == 0) { // 데이터가 있으면 1 이상 없으면 0 데이터가 없으면 값을 넣어주고 있으면 안넣는다. sql= "INSERT INTO post_seoul(a1,a2,a3,a4,a5,a6,a7,a8)" + "values('"+a1+"','"+a2+"','"+a3+"','"+a4+"','"+a5+"','"+a6+"','"+a7+"','"+a8+"')"; stmt.executeUpdate(sql); num++; } } cal = Calendar.getInstance(); long eTime = cal.getTimeInMillis(); //유닉스시간 1970,1,1,0:0:0 System.out.println("소요시간: "+(eTime-sTime)/1000); System.out.println(num+"개 copy 완료"); } }
true
6ca91a94ddeb432f151d9d39b3f19702cd2665b6
Java
alqodimi737/Task4
/Quation1.java
UTF-8
728
3.234375
3
[]
no_license
/** * Created by hp on 21/02/2021. */ public class Quation1 { public static void main(String[]args){ String[]starray={"mohammed","ALI","hsan","ahmed","malik"}; Integer[]inarray={1,2,3,4,5,6}; System.out.println("old array"); for (int i=0; i<inarray.length;i++) System.out.println(inarray[i]+" "); for (int j=0; j<starray.length;j++) System.out.println(starray[j]+" "); System.out.println( ); System.out.println("new array:"); for (int i=inarray.length-1;i>=0;i--) System.out.println(inarray[i]+" "); for (int j=starray.length-1;j>=0;j--) System.out.println(starray[j]+" "); } }
true
9f8c2ef7df77f0de62762a5a92025c00ef816892
Java
fang55/szxyhl
/mpxyhl/src/main/java/com/szxyyd/mpxyhl/modle/CityData.java
UTF-8
269
1.671875
2
[]
no_license
package com.szxyyd.mpxyhl.modle; import java.util.List; /** * Created by jq on 2016/7/27. */ public class CityData { private String yes; public String getYes() { return yes; } public void setYes(String yes) { this.yes = yes; } }
true
21d44be3e78421591b6ad1a32371bb329e18eb1d
Java
reakingf/Baymin
/app/src/main/java/com/qa/fgj/baymin/model/MainModel.java
UTF-8
2,111
2.15625
2
[]
no_license
package com.qa.fgj.baymin.model; import android.content.Context; import com.qa.fgj.baymin.model.entity.BayMinResponse; import com.qa.fgj.baymin.model.entity.MessageBean; import com.qa.fgj.baymin.net.RestApiService; import com.qa.fgj.baymin.net.api.CommunicationApi; import com.qa.fgj.baymin.util.Global; import com.qa.fgj.baymin.util.LogUtil; import com.qa.fgj.baymin.util.SharPreferencesDB; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; /** * Created by FangGengjia on 2017/2/18. */ public class MainModel { final CommunicationApi communicationApi; private Context mContext; private SharPreferencesDB preferencesDB; public MainModel(Context context) { this.mContext = context; preferencesDB = new SharPreferencesDB(mContext, "loginInfo"); communicationApi = RestApiService.getInstance().createApi(CommunicationApi.class); } public Observable<Boolean> getLoginCache(){ boolean shouldLogin = preferencesDB.getBoolean("isRemember"); return Observable.just(shouldLogin); } public Observable<BayMinResponse<String>> getAnswer(String question){ return communicationApi.getRespond(question); } /** * @param startId 查询的其实ID * @param offset 偏移量 * @return Observable类型的消息列表 */ public Observable<List<MessageBean>> loadData(String startId, int offset) { List<MessageBean> list = Global.messageDB.queryByMsgIdDESC(startId, offset); if (list != null){ return Observable.just(list); } return Observable.just((List<MessageBean>) new ArrayList<MessageBean>()); } public Observable<Boolean> saveData(MessageBean messageBean){ try{ if (Global.messageDB == null){ Global.initDB(); } Global.messageDB.save(messageBean); } catch (Exception e){ e.printStackTrace(); Observable.just(false); } return Observable.just(true); } }
true
ce75b48d0bec260dc15ff747a9d3dc98cf749f42
Java
artvovc/patterns
/src/main/java/com/patterns/structural/adapter/Adaptee.java
UTF-8
289
2.765625
3
[]
no_license
package com.patterns.structural.adapter; /** * Created by Artemie on 14.01.2017. */ public class Adaptee { void iDo1(){ System.out.println("iDo1"); } void iDo2(){ System.out.println("iDo2"); } void iDo3(){ System.out.println("iDo3"); } }
true
9f97327e8db601c154c7e6a0ee85324983582491
Java
csxiaoshang/leetcode
/src/main/java/offer/LevelOrder.java
UTF-8
1,010
3.203125
3
[]
no_license
package main.java.offer; import java.util.ArrayList; import java.util.LinkedList; /** * @author ashang 970090853@qq.com * @Date 20-2-27 下午11:37 * <p> * 类说明: */ public class LevelOrder { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); LinkedList<TreeNode> quene = new LinkedList<>(); quene.add(pRoot); if(pRoot == null){ return res; } TreeNode node = null; while(!quene.isEmpty()){ int length = quene.size(); ArrayList<Integer> tem = new ArrayList<>(); for(int i=0;i<length;i++){ node = quene.remove(); tem.add(node.val); if(node.left!=null){ quene.add(node.left); } if(node.right != null){ quene.add(node.right); } } res.add(tem); } return res; } }
true
034dde1d1042e5a133e201ec91bc37ac925dd27f
Java
cengizgoren/facebook_apk_crack
/app/com/facebook/orca/app/MessagesModule$SetThreadImageMethodProvider.java
UTF-8
868
1.601563
2
[]
no_license
package com.facebook.orca.app; import com.facebook.orca.attachments.MediaAttachmentFactory; import com.facebook.orca.attachments.MediaAttachmentUtil; import com.facebook.orca.inject.AbstractProvider; import com.facebook.orca.protocol.methods.SetThreadImageMethod; class MessagesModule$SetThreadImageMethodProvider extends AbstractProvider<SetThreadImageMethod> { private MessagesModule$SetThreadImageMethodProvider(MessagesModule paramMessagesModule) { } public SetThreadImageMethod a() { return new SetThreadImageMethod((MediaAttachmentFactory)b(MediaAttachmentFactory.class), (MediaAttachmentUtil)b(MediaAttachmentUtil.class)); } } /* Location: /data1/software/jd-gui/com.facebook.katana_2.0_liqucn.com-dex2jar.jar * Qualified Name: com.facebook.orca.app.MessagesModule.SetThreadImageMethodProvider * JD-Core Version: 0.6.0 */
true
b0a67670dd4f275ddd1b1d85b5f4cb2c7953dbaa
Java
ankit-sood/ms-meetup
/ms-meetup/src/main/java/com/ms/meetup/controller/LocationController.java
UTF-8
741
1.984375
2
[]
no_license
package com.ms.meetup.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ms.meetup.model.Location; import com.ms.meetup.service.LocationService; @RestController @RequestMapping(value="/locations") public class LocationController { @Autowired private LocationService locationService; @GetMapping public ResponseEntity<List<Location>> getCategories() { return ResponseEntity.ok(locationService.getLocations()); } }
true
2e32725b4efb405e029342c7c225bc197d4a39b3
Java
b5810450792/Project-Taxi-Sharing
/app/src/main/java/com/example/user/otp5/Adapter/Adapter_chat.java
UTF-8
4,999
2
2
[]
no_license
package com.example.user.otp5.Adapter; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.user.otp5.Model.Account; import com.example.user.otp5.Model.Chat; import com.example.user.otp5.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class Adapter_chat extends RecyclerView.Adapter<Adapter_chat.ViewHolder> { public static final int MSG_TYPE_LEFT = 0; public static final int MSG_TYPE_RIGHT = 1; private Context mContext; private ArrayList<Chat> mChat; private String imageurl; ArrayList<Account> accounts; FirebaseUser fuser; private OnItemClickListener mListener; DatabaseReference reference; public interface OnItemClickListener{ void onItemClick(int position); } public void setOnItemClickListener(OnItemClickListener listener){ mListener = listener; } public Adapter_chat(Context mContext, ArrayList<Chat> mChat) { this.mContext = mContext; this.mChat = mChat; } @NonNull @Override public Adapter_chat.ViewHolder onCreateViewHolder(ViewGroup parent, int viewtype) { if(viewtype == MSG_TYPE_RIGHT) { View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false); return new Adapter_chat.ViewHolder(view,mListener); }else { View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false); return new Adapter_chat.ViewHolder(view,mListener); } } @Override public void onBindViewHolder(final Adapter_chat.ViewHolder viewHolder, int position) { Chat chat = mChat.get(position); fuser = FirebaseAuth.getInstance().getCurrentUser(); viewHolder.show_message.setText(chat.getMessage()); //viewHolder.profile_image.setImageResource(R.mipmap.ic_launcher); if (chat.getImage().equals("default")) { //default picture } else { Glide.with(mContext).load(chat.getImage()).into(viewHolder.profile_image); } Log.i("nameee",chat.getName_user()); viewHolder.name.setText(chat.getName_user()+"") ; } @Override public int getItemCount() { return mChat.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView show_message; public TextView name; public ImageView profile_image; public CircleImageView myphoto; public ViewHolder(final View itemView, final OnItemClickListener listener) { super(itemView); show_message = itemView.findViewById(R.id.show_message); profile_image = itemView.findViewById(R.id.profile_image); name = itemView.findViewById(R.id.name_id); myphoto = itemView.findViewById(R.id.profile_image); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ int position = getAdapterPosition(); if(position != RecyclerView.NO_POSITION){ listener.onItemClick(position); } } AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext); mBuilder.setCancelable(false); } }); } } @Override public int getItemViewType(int position) { fuser = FirebaseAuth.getInstance().getCurrentUser(); if(mChat.get(position).getSender().equals(fuser.getUid()) ){ // Log.i("name right",mChat.get(position).getName_user()); // Log.i("sender right",mChat.get(position).getSender()); // Log.i("message right",mChat.get(position).getMessage()); return MSG_TYPE_RIGHT; } else { // Log.i("name left",mChat.get(position).getName_user()); // Log.i("key2 left",mChat.get(position).getReceiver2()); // Log.i("key3 left",mChat.get(position).getReceiver3()); // Log.i("key4 left",mChat.get(position).getReceiver4()); // Log.i("key5 left",mChat.get(position).getReceiver5()); // Log.i("message left",mChat.get(position).getMessage()); return MSG_TYPE_LEFT; } } }
true
3f7ec586c8ee8cf4ad950fd3a1d212c181fb8118
Java
2393937618/cy
/app/src/main/java/com/example/lxc/cy/main/attention_main.java
UTF-8
7,719
2.046875
2
[]
no_license
package com.example.lxc.cy.main; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.example.lxc.cy.R; import com.example.lxc.cy.adapter.Attention_listAdapter; import com.example.lxc.cy.bean.Attention_listBean; import com.example.lxc.cy.adapter.Attention_listAdapter.MyClickListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import android.widget.AdapterView.OnItemClickListener; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class attention_main extends AppCompatActivity implements OnItemClickListener { ImageButton like,collect; TextView add; String ip2 =getResources().getString(R.string.ip)+"main/attention/3"; private int index = 0; String[] like_TF,create_name,content_text,place_name,comment_num,like_num,type,owner_id,notes_id,place_id,create_time,user_name,user_pic; private static final int COMPLETED = 0; private static final int COMPLETED1 = 1; TextView likes_num; ListView listView; View heardView,footView; String note_id=""; List<Attention_listBean> aData; Attention_listAdapter adapter; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what == COMPLETED) { listView.setAdapter(new Attention_listAdapter((LinkedList<Attention_listBean>) aData,attention_main.this));//UI更改操作 } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_attention_main); adapter = new Attention_listAdapter((LinkedList<Attention_listBean>) aData,attention_main.this); listView = (ListView)findViewById(R.id.attention_list); final LayoutInflater inflater = LayoutInflater.from(this); aData = new LinkedList<Attention_listBean>(); listView.setOnItemClickListener(this); //1.创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); //2.创建Request对象,设置一个url地址,设置请求方式。 Request request = new Request.Builder() .url(ip2) .get() .build(); //3.创建一个call对象,参数就是Request请求对象 Call call = okHttpClient.newCall(request); //4.请求加入调度,重写回调方法 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { String err = e.getMessage().toString(); System.out.println("----------------------------sbsbsbs+err"+err); } @Override public void onResponse(Call call, Response response) throws IOException { //获取数据包 String rtn = response.body().string(); System.out.println("----------------------------sbsbsbs+success"+rtn); try { //解析json数据:create_time JSONObject jsonObject = new JSONObject(rtn); //将/n替换 String a = jsonObject.getString("create_time").replaceAll("\n",""); //去除[],并生成数组 create_time = a.substring(1,a.length()-1).split(","); //去除空格,测试输出结果 for(int i=0;i<create_time.length;i++){ System.out.println("----------------------------sbsbsbs+success"+create_time[i].substring(4)); } //解析[]的json数据 JSONArray jsonArray = jsonObject.getJSONArray("comment_num"); JSONArray jsonArray1 = jsonObject.getJSONArray("content_text"); JSONArray jsonArray2 = jsonObject.getJSONArray("like_num"); JSONArray jsonArray3 = jsonObject.getJSONArray("place_name"); JSONArray jsonArray4 = jsonObject.getJSONArray("user_name"); JSONArray jsonArray5 = jsonObject.getJSONArray("user_pic"); JSONArray jsonArray6 = jsonObject.getJSONArray("notes_id"); //定义数组长度 comment_num = new String[jsonArray.length()]; content_text = new String[jsonArray.length()]; like_num = new String[jsonArray.length()]; place_name = new String[jsonArray.length()]; user_name = new String[jsonArray.length()]; user_pic = new String[jsonArray.length()]; notes_id = new String[jsonArray.length()]; like_TF = new String[jsonArray.length()]; //将json数据存到数组 for(int i=0;i<jsonArray.length();i++){ comment_num[i] = jsonArray.getString(i); content_text[i] = jsonArray1.getString(i); like_num[i] = jsonArray2.getString(i); place_name[i] = jsonArray3.getString(i); user_name[i] = jsonArray4.getString(i); user_pic[i] = "http://172.16.243.163:9000/"+jsonArray5.getString(i); notes_id[i] = jsonArray6.getString(i); like_TF[i] = "0"; //测试数组数据 System.out.println("----------------------------sbsbsbs+user_name"+user_name[i]); System.out.println("----------------------------sbsbsbs+content_text"+content_text[i]); System.out.println("----------------------------sbsbsbs+like_num"+like_num[i]); System.out.println("----------------------------sbsbsbs+place_name"+place_name[i]); System.out.println("----------------------------sbsbsbs+user_name"+user_name[i]); System.out.println("----------------------------sbsbsbs+user_pic"+user_pic[i]); System.out.println("----------------------------sbsbsbs+notes_id"+notes_id[i]); aData.add(new Attention_listBean(like_TF[i],notes_id[i],user_pic[i],user_name[i],create_time[i].substring(4),content_text[i],place_name[i],comment_num[i],like_num[i])); } //不能在子线程更新UI,用handler发送消息 Message message = new Message(); message.what = COMPLETED; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(attention_main.this, "listview的item被点击了!,点击的位置是-->" + position, Toast.LENGTH_SHORT).show(); } }
true
39995970465dd14a23069babd5a0bc47067c1456
Java
tifaniwarnita/CIC-CATalyst
/CICCATalystCore/app/src/main/java/com/tifaniwarnita/ciccatalystcore/kasir/DetailReservasiActivity.java
UTF-8
2,752
2.125
2
[]
no_license
package com.tifaniwarnita.ciccatalystcore.kasir; import android.app.Activity; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.tifaniwarnita.ciccatalystcore.PilihanAksesFragment; import com.tifaniwarnita.ciccatalystcore.R; import java.util.Date; public class DetailReservasiActivity extends AppCompatActivity implements DetailReservasiFragment.ReservationDetailFragmentListener, TambahReservasiDialogFragment.TambahReservasiDialogFragmentListener { private Date date = null; private DetailReservasiFragment detailReservasiFragment = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_reservasi); if (getIntent().hasExtra(getResources().getString(R.string.detail_reservasi))) date = DetailReservasiFragment.convertStringToDate(getIntent().getStringExtra(getResources().getString(R.string.detail_reservasi))); else date = new Date(); FragmentManager fm = getSupportFragmentManager(); detailReservasiFragment = DetailReservasiFragment.newInstance( DetailReservasiFragment.convertDateToString(date)); if (date != null) { fm.beginTransaction() .replace(R.id.fragment_container, detailReservasiFragment) .commit(); } else { fm.beginTransaction() .replace(R.id.fragment_container, new DetailReservasiFragment()) .commit(); } FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show();*/ TambahReservasiDialogFragment tambahReservasiDialog = TambahReservasiDialogFragment.newInstance( DetailReservasiFragment.convertDateToString(date) ); tambahReservasiDialog.show(getSupportFragmentManager(), null); } }); } @Override public void onDetailReservasiBack() { detailReservasiFragment = null; } @Override public void onReservasi(String pemesan, int i, int j) { if (detailReservasiFragment != null) { detailReservasiFragment.updateDummy(pemesan, i, j); } } }
true
77bc4c7ebe7672a8d037b935af67081b254d8baf
Java
ViniciusRob/aulas-generation
/Exercícios 05.05/Exercicio5.java
ISO-8859-2
640
3.5
4
[]
no_license
package br.com.generation.exercicios; import java.util.Scanner; public class Exercicio5 { public static void main(String[] args) { Scanner ler = new Scanner(System.in); double nota1, nota2, nota3, media; System.out.println("Insira a primeira nota: "); nota1 = ler.nextDouble(); System.out.println("Insira a segunda nota: "); nota2 = ler.nextDouble(); System.out.println("Insira a terceira nota: "); nota3 = ler.nextDouble(); media = (nota1 * 2 + nota2 * 3 + nota3 * 5) / 10; String result = String.format("%.2f", media); System.out.println("A mdia do aluno : " +result); } }
true
5a71f981cfc87d7ee4f8b81f32525508456b5ed9
Java
rafaeldrs/FP1516
/Java/B01.1-casa/src/main/PositivoPar.java
ISO-8859-1
556
3.796875
4
[ "MIT" ]
permissive
package main; import java.util.Scanner; public class PositivoPar { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Introduzca un nmero:"); Integer n = sc.nextInt(); System.out.print("El nmero " + n + " es "); if(n>0){ System.out.print("positivo"); } else if(n<0){ System.out.print("negativo"); } else{ System.out.print("cero"); } System.out.print(" y "); if(n%2==0){ System.out.println("par"); } else{ System.out.println("impar"); } sc.close(); } }
true
578f8ea51fd94c6acc7b45e9bdf7a7a160cf3923
Java
john-dev-br/matches-api
/src/main/java/au/com/phoenixhsl/api/matches/model/MatchWrapper.java
UTF-8
497
2.265625
2
[]
no_license
package au.com.phoenixhsl.api.matches.model; import java.util.HashMap; import java.util.List; import java.util.Map; public class MatchWrapper { private Map<String, List<Match>> matches; public MatchWrapper() { } public MatchWrapper(String key, List<Match> values) { matches = new HashMap<>(); matches.put(key, values); } public Map<String, List<Match>> getMatches() { return matches; } public void setMatches(Map<String, List<Match>> matches) { this.matches = matches; } }
true
05795b9d4a3e7d7e6af150ca434e18227cf0d036
Java
currynice/leetCode
/src/main/java/com/cxy/brush/leetcode/editor/cn/[231]2的幂.java
UTF-8
756
3.21875
3
[]
no_license
package com.cxy.brush.leetcode.editor.cn; //给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 // // 示例 1: // // 输入: 1 //输出: true //解释: 20 = 1 // // 示例 2: // // 输入: 16 //输出: true //解释: 24 = 16 // // 示例 3: // // 输入: 218 //输出: false // Related Topics 位运算 数学 // 👍 273 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution231 { /** * 2的幂次方,二进制位仅有一个1,且不是末位 0....1..0 * @param n * @return */ public boolean isPowerOfTwo(int n) { long x = n; return x!=0 && ((x&(x-1))==0); } } //leetcode submit region end(Prohibit modification and deletion)
true
be36458780701d253144b6da02af1a32702fffe8
Java
hoiama/study_microservices
/spring/module-endpoints-server/src/main/java/br/com/hoiama/Repository/AlunoRepository.java
UTF-8
380
1.765625
2
[]
no_license
package br.com.hoiama.Repository; import br.com.hoiama.entity.Aluno; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AlunoRepository extends JpaRepository<Aluno, Long> { List<Aluno> findAlunoByIdAlunoOrderByNome(Long aLong); }
true
fdfbd7aa64b05de2d29dec6d2802c70dcca37e3a
Java
Dexter0526/sw_Course
/javafx_ex1/src/application/PersonVO.java
UTF-8
1,606
2.78125
3
[]
no_license
package application; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class PersonVO { private IntegerProperty no; private StringProperty name; private StringProperty email; private StringProperty tel; public PersonVO() { no = new SimpleIntegerProperty(); name = new SimpleStringProperty(); email = new SimpleStringProperty(); tel = new SimpleStringProperty(); } public PersonVO(int no, String name, String email, String tel) { this.no = new SimpleIntegerProperty(no); this.name = new SimpleStringProperty(name); this.email = new SimpleStringProperty(email); this.tel = new SimpleStringProperty(tel); } public int getNo() { return no.get(); } public void setNo(int no) { this.no.set(no); } public String getName() { return name.get(); } public void setName(String name) { this.name.set(name); } public String getEmail() { return email.get(); } public void setEmail(String email) { this.email.set(email); } public String getTel() { return tel.get(); } public void setTel(String tel) { this.tel.set(tel); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PersonVO [no="); builder.append(no.get()); builder.append(", name="); builder.append(name.get()); builder.append(", email="); builder.append(email.get()); builder.append(", tel="); builder.append(tel.get()); builder.append("]"); return builder.toString(); } }
true
8293310940efa597dcb17c4513ec3f7fc490ca43
Java
miniwolf/Fagi
/fagiServer/src/test/java/com/fagi/handler/inputhandler/CreateUserServerTests.java
UTF-8
3,660
2.0625
2
[ "MIT" ]
permissive
package com.fagi.handler.inputhandler; import com.fagi.handler.ConversationHandler; import com.fagi.handler.InputHandler; import com.fagi.model.CreateUser; import com.fagi.model.Data; import com.fagi.model.InviteCodeContainer; import com.fagi.responses.AllIsWell; import com.fagi.responses.IllegalInviteCode; import com.fagi.responses.UserExists; import com.fagi.worker.InputAgent; import com.fagi.worker.OutputAgent; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Collections; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; class CreateUserServerTests { private OutputAgent outputAgent; private InputHandler inputHandler; private InviteCodeContainer inviteCodeContainer; private Data data; @BeforeEach void setup() { data = Mockito.mock(Data.class); var inputAgent = Mockito.mock(InputAgent.class); outputAgent = Mockito.mock(OutputAgent.class); ConversationHandler conversationHandler = new ConversationHandler(data); inputHandler = new InputHandler(inputAgent, outputAgent, conversationHandler, data); inviteCodeContainer = new InviteCodeContainer(new ArrayList<>(Collections.singletonList(42))); doReturn(inviteCodeContainer) .when(data) .loadInviteCodes(); } @Test void creatingUserWithIllegalInviteCode_ShouldResultInIllegalInviteCodeResponse() { var createUser = new CreateUser("bob", "123", 23); inputHandler.handleInput(createUser); var argumentCaptor = ArgumentCaptor.forClass(IllegalInviteCode.class); Mockito .verify(outputAgent, times(1)) .addResponse(argumentCaptor.capture()); Assertions.assertNotNull(argumentCaptor.getValue()); } @Test void creatingUserFails_ShouldResultInInviteCodeNotBeingDeleted() { var inviteCode = inviteCodeContainer .codes() .get(0); var createUser = new CreateUser("bob", "123", inviteCode); doReturn(new UserExists()) .when(data) .createUser(createUser.username(), createUser.password()); inputHandler.handleInput(createUser); Assertions.assertTrue(inviteCodeContainer.contains(inviteCode)); } @Test void createUserSucceeds_ShouldDeleteInviteCode() { var inviteCode = inviteCodeContainer .codes() .get(0); var createUser = new CreateUser("bob", "123", inviteCode); doReturn(new AllIsWell()) .when(data) .createUser(createUser.username(), createUser.password()); inputHandler.handleInput(createUser); Assertions.assertFalse(inviteCodeContainer.contains(inviteCode)); } @Test void createUserSucceeds_ShouldResultInAllIsWellResponse() { var inviteCode = inviteCodeContainer .codes() .get(0); var createUser = new CreateUser("bob", "123", inviteCode); doReturn(new AllIsWell()) .when(data) .createUser(createUser.username(), createUser.password()); inputHandler.handleInput(createUser); var argumentCaptor = ArgumentCaptor.forClass(AllIsWell.class); Mockito .verify(outputAgent, times(1)) .addResponse(argumentCaptor.capture()); Assertions.assertNotNull(argumentCaptor.getValue()); } }
true
a1292821be48e0fcab49b99c2c2908bf6f9b810e
Java
SSL191919/QuickShop
/app/src/main/java/com/gmyscl/ecom/firstorder/productdetails/ProductDetails.java
UTF-8
31,968
1.875
2
[]
no_license
package com.gmyscl.ecom.firstorder.productdetails; import android.app.Dialog; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.viewpager.widget.ViewPager; import com.gmyscl.ecom.firstorder.DialogsClass; import com.gmyscl.ecom.firstorder.MainActivity; import com.gmyscl.ecom.firstorder.R; import com.gmyscl.ecom.firstorder.buyprocess.BuyNowActivity; import com.gmyscl.ecom.firstorder.database.DBquery; import com.gmyscl.ecom.firstorder.database.StaticValues; import com.gmyscl.ecom.firstorder.mycart.MyCartCheckModel; import com.gmyscl.ecom.firstorder.mycart.MyCartFragment; import com.gmyscl.ecom.firstorder.mycart.MyCartItemModel; import com.gmyscl.ecom.firstorder.mywishlist.MyWishListModel; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.tabs.TabLayout; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.gmyscl.ecom.firstorder.database.DBquery.currentUser; import static com.gmyscl.ecom.firstorder.database.StaticValues.PRODUCT_DETAILS_ACTIVITY; import static com.gmyscl.ecom.firstorder.database.StaticValues.productDetailTempList; public class ProductDetails extends AppCompatActivity { // --- Product Details Image Layout... private ViewPager productImagesViewPager; private TabLayout productImagesIndicator; public static FloatingActionButton addToWishListBtn; private ConstraintLayout productDescriptionLayout; private TextView productName; private TextView productPrice; private TextView productCutPrice; private TextView productCODText; private TextView productCODSubText; private TextView productStock; // --- Product Details Image Layout... private TextView productDetailsText; private ViewPager productDescriptionViewPager; private TabLayout productDescriptionIndicator; private Button addToCartBtn; private Button buyNowBtn; public static String productID; public static TextView badgeCartCount; private ConstraintLayout activityProductDetailLayout; // Dialogs... private Dialog dialog; // FirebaseFireStore... private FirebaseFirestore firebaseFirestore; private DocumentSnapshot documentSnapshot; private DialogsClass dialogsClass = new DialogsClass( this ); // Product Specification ... private List<ProductDetailsSpecificationModel> productDetailsSpecificationModelList = new ArrayList <>(); private String productDescription; public static boolean ALREADY_ADDED_IN_WISHLIST = false; public static boolean ALREADY_ADDED_IN_CART = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_product_details ); activityProductDetailLayout = findViewById( R.id.activity_product_detail_constLayout ); Toolbar toolbar = findViewById( R.id.x_ToolBar ); setSupportActionBar( toolbar ); // TODO : get product ID through Intent ... productID = getIntent().getStringExtra( "PRODUCT_ID" ); dialog = dialogsClass.progressDialog( ProductDetails.this ); dialog.show(); // ---- Progress Dialog... // Set Title on Action Menu try{ // To test We assign a default PRODUCT_ID ... if (productID.isEmpty()){ // productID = "k2SGQbneH477j6X18l6a"; dialog.dismiss(); Toast.makeText( this, "Product Not found.!", Toast.LENGTH_SHORT ).show(); finish(); } getSupportActionBar().setDisplayShowTitleEnabled( false ); getSupportActionBar( ).setDisplayHomeAsUpEnabled( true ); }catch (NullPointerException e){ } // Clear the ptoductDetailTempList... productDetailTempList.clear(); addToWishListBtn = findViewById( R.id.add_to_wishList_btn ); addToCartBtn = findViewById( R.id.add_to_cart_btn ); buyNowBtn = findViewById( R.id.buy_now_btn ); // --- Product Details Image Layout... productName = findViewById( R.id.product_item_name ); productPrice = findViewById( R.id.product_item_price ); productCutPrice = findViewById( R.id.product_item_cut_price ); productCODText = findViewById( R.id.product_item_cod_text ); productCODSubText = findViewById( R.id.product_item_cod_sub_text ); productStock = findViewById( R.id.product_item_stocks ); // --- Product Details Image Layout... productDescriptionLayout = findViewById( R.id.product_details_description_ConstLayout ); productDetailsText = findViewById( R.id.product_details_text ); //----------- Product Images --- productImagesViewPager = findViewById( R.id.product_images_viewpager ); productImagesIndicator = findViewById( R.id.product_images_viewpager_indicator ); // create a list for testing... final List<String> productImageList = new ArrayList <>(); firebaseFirestore = FirebaseFirestore.getInstance(); // ---------- Product Description code---- productDescriptionViewPager = findViewById( R.id.product_detail_viewpager ); productDescriptionIndicator = findViewById( R.id.product_details_indicator ); // TODO: Retrieve details from database...---------------- firebaseFirestore.collection( "PRODUCTS" ).document( productID ) .get().addOnCompleteListener( new OnCompleteListener <DocumentSnapshot>() { @Override public void onComplete(@NonNull Task <DocumentSnapshot> task) { if (task.isSuccessful()){ documentSnapshot = task.getResult(); // --- add Product Images... for (long x = 1; x < (long)documentSnapshot.get( "product_image_num" )+1; x++){ productImageList.add( documentSnapshot.get( "product_image_"+x ).toString() ); } // set adapter with viewpager... ProductDetailsImagesAdapter productDetailsImagesAdapter = new ProductDetailsImagesAdapter( productImageList ); productImagesViewPager.setAdapter( productDetailsImagesAdapter ); // Add Product ID in productDetailTempList productDetailTempList.add( 0, productID ); //add Main Image in productDetailTempList... productDetailTempList.add( 1, productImageList.get( 0 ) ); // Set other Details of Product Details Image Layout. // Product Name... productName.setText( documentSnapshot.get( "product_full_name" ).toString() ); //add name in Temp List productDetailTempList.add( 2, documentSnapshot.get( "product_full_name" ).toString() ); // Product Price... productPrice.setText( "Rs. " + documentSnapshot.get( "product_price" ).toString() +"/-" ); // add price in Temp List productDetailTempList.add( 3, documentSnapshot.get( "product_price" ).toString() ); // Product Cut Price... productCutPrice.setText( "Rs. " + documentSnapshot.get( "product_cut_price" ).toString() +"/-" ); //add cut price in Temp List productDetailTempList.add(4, documentSnapshot.get( "product_cut_price" ).toString() ); if ((boolean)documentSnapshot.get( "product_cod" )){ productCODText.setVisibility( View.VISIBLE ); productCODSubText.setVisibility( View.VISIBLE ); //add COD in Temp List productDetailTempList.add( 5, "COD" ); }else{ productCODText.setVisibility( View.INVISIBLE ); productCODSubText.setVisibility( View.INVISIBLE ); //add COD in Temp List productDetailTempList.add( 5, "NO_COD" ); } if ((long)documentSnapshot.get( "product_stocks" ) > 0){ productStock.setText( "In Stock" ); //add COD in Temp List productDetailTempList.add( 6, "IN_STOCK" ); }else{ productStock.setText( "Out of Stock" ); //add COD in Temp List productDetailTempList.add( 6, "OUT_OF_STOCK" ); } if(documentSnapshot.get( "product_qty_type" ) != null){ productDetailTempList.add( 7, documentSnapshot.get( "product_qty_type" ).toString() ); }else{ productDetailTempList.add( 7, "" ); } StaticValues.tempProductAreaCode = documentSnapshot.get( "area_code" ).toString(); // Set other Details of Product Details Image Layout. if ((boolean)documentSnapshot.get( "use_tab_layout" )){ // use tab layout... productDescriptionLayout.setVisibility( View.VISIBLE ); // TODO : set Description data.. productDescription = documentSnapshot.get( "product_description" ).toString() ; // TODO : set Specification data... for (long x = 1; x < (long) documentSnapshot.get( "pro_sp_head_num" )+1; x++){ productDetailsSpecificationModelList.add( new ProductDetailsSpecificationModel( 0, documentSnapshot.get( "pro_sp_head_" + x ).toString() ) ); for (long i = 1; i < (long)documentSnapshot.get( "pro_sp_sub_head_"+x+"_num" )+1; i++){ productDetailsSpecificationModelList.add( new ProductDetailsSpecificationModel( 1, documentSnapshot.get( "pro_sp_sub_head_" + x + i ).toString(), documentSnapshot.get( "pro_sp_sub_head_d_" + x + i ).toString() ) ); } } ProductDetailsDescriptionAdaptor productDetailsDescriptionAdaptor = new ProductDetailsDescriptionAdaptor( getSupportFragmentManager() , productDescriptionIndicator.getTabCount() , productDescription , productDetailsSpecificationModelList ); productDescriptionViewPager.setAdapter( productDetailsDescriptionAdaptor ); productDetailsDescriptionAdaptor.notifyDataSetChanged(); } else{ // don't use tabLayout... productDescriptionLayout.setVisibility( View.GONE ); } productDetailsText.setText( documentSnapshot.get( "product_details" ).toString() ); // check offline wishList Size.. and run DB query to update wishList if size is 0 if (currentUser != null){ // for Wish list... if (DBquery.myWishList.size() == 0){ DBquery.wishListQuery(ProductDetails.this, dialog, false); } // set color of wishList button based on wishList... if (DBquery.myWishList.size() != 0){ if (DBquery.myWishList.contains( productID )){ ALREADY_ADDED_IN_WISHLIST = true; addToWishListBtn.setSupportImageTintList( getResources().getColorStateList( R.color.colorRed ) ); }else{ ALREADY_ADDED_IN_WISHLIST = false; } dialog.dismiss(); } // for cart list... if (DBquery.myCartCheckList.size() == 0){ DBquery.cartListQuery(ProductDetails.this, false, dialog, PRODUCT_DETAILS_ACTIVITY); } if (DBquery.myCartCheckList.size() != 0){ for (int i = 0; i < DBquery.myCartCheckList.size(); i++) { if( DBquery.myCartCheckList.get( i ).getProductId().equals( productID )){ ALREADY_ADDED_IN_CART = true; break; }else{ ALREADY_ADDED_IN_CART = false; } } dialog.dismiss(); } }else { dialog.dismiss(); } } else{ String error = task.getException().getMessage(); showToast(error); dialog.dismiss(); } } } ); // Retrieve details from database...---------------- // connect TabLayout with viewPager... productImagesIndicator.setupWithViewPager( productImagesViewPager, true ); //----------- Product Images --- productDescriptionViewPager.addOnPageChangeListener( new TabLayout.TabLayoutOnPageChangeListener( productDescriptionIndicator ) ); productDescriptionIndicator.addOnTabSelectedListener( new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { productDescriptionViewPager.setCurrentItem( tab.getPosition() ); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } } ); // ---------- Product Description code---- // TODO: WishList Code // WishList Button click... addToWishListBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { if (currentUser == null){ dialogsClass.signInUpDialog( PRODUCT_DETAILS_ACTIVITY ); } else{ dialog.show(); addToWishListBtn.setEnabled( false ); if (ALREADY_ADDED_IN_WISHLIST){ // if ALREADY_ADDED_IN_WISH_LIST then, Code for remove from wishList int listIndex = DBquery.myWishList.indexOf( productID ); DBquery.removeItemFromWishList( listIndex, ProductDetails.this, dialog, PRODUCT_DETAILS_ACTIVITY ); addToWishListBtn.setSupportImageTintList( ColorStateList.valueOf( Color.parseColor( "#4e4e4e" ) ) ); } else { // if not add item in wishList then, Code To Add in wishList Map<String, Object> addProductIntoWishList = new HashMap <>(); for (int temX = 0; temX < DBquery.myWishList.size(); temX++){ addProductIntoWishList.put( "product_ID_"+temX, DBquery.myWishList.get( temX ) ); } addProductIntoWishList.put( "wish_list_size", (long)DBquery.myWishList.size()+1 ); addProductIntoWishList.put( "product_ID_"+ DBquery.myWishList.size(), productID ); //Since we have use set Method so we have to add all the previous fields in Map also to update the List... firebaseFirestore.collection( "USER" ).document( currentUser.getUid() ) .collection( "USER_DATA" ).document( "MY_WISH_LIST" ) .set( addProductIntoWishList ).addOnCompleteListener( new OnCompleteListener <Void>() { @Override public void onComplete(@NonNull Task <Void> task) { if (task.isSuccessful()){ DBquery.myWishList.add( productID.trim() ); if (DBquery.wishListModelList.size() != 0){ if (documentSnapshot.get( "product_qty_type" ) != null ){ DBquery.wishListModelList.add( new MyWishListModel( documentSnapshot.get( "product_image_1" ).toString() , documentSnapshot.get( "product_full_name" ).toString() , documentSnapshot.get( "product_price" ).toString() , documentSnapshot.get( "product_cut_price" ).toString() , productID , " " , true , documentSnapshot.get( "product_qty_type" ).toString() ) ); }else{ DBquery.wishListModelList.add( new MyWishListModel( documentSnapshot.get( "product_image_1" ).toString() , documentSnapshot.get( "product_full_name" ).toString() , documentSnapshot.get( "product_price" ).toString() , documentSnapshot.get( "product_cut_price" ).toString() , productID , " " , true , "" ) ); } // Update Stock info wishList... if ((long)documentSnapshot.get( "product_stocks" ) > 0){ DBquery.wishListModelList.get( DBquery.wishListModelList.size() - 1 ).setWishStockInfo( "IN_STOCK" ); // myWishListModelList.get( myWishListModelList.size() - 1 ).setWishStockInfo( "IN_STOCK" ); }else{ DBquery.wishListModelList.get( DBquery.wishListModelList.size() - 1 ).setWishStockInfo( "OUT_OF_STOCK" ); // myWishListModelList.get( myWishListModelList.size() - 1 ).setWishStockInfo( "OUT_OF_STOCK" ); } // Update COD info in wishList... if ((boolean)documentSnapshot.get( "product_cod" )){ DBquery.wishListModelList.get( DBquery.wishListModelList.size() - 1 ).setWishCODinfo( true ); }else{ DBquery.wishListModelList.get( DBquery.wishListModelList.size() - 1 ).setWishCODinfo( false ); } } addToWishListBtn.setSupportImageTintList( getResources().getColorStateList( R.color.colorRed ) ); dialog.dismiss(); // Dismiss the Dialog First Then Show Toast Msg... if (DBquery.myWishList.contains( productID )){ showToast( "Added to WishList SuccessFully..!" ); }else{ showToast( "Added to WishList but not Add in Local List." ); } ALREADY_ADDED_IN_WISHLIST = true; addToWishListBtn.setEnabled( true ); } else{ dialog.dismiss(); addToWishListBtn.setSupportImageTintList( ColorStateList.valueOf( Color.parseColor( "#4e4e4e" ) ) ); String error = task.getException().getMessage(); showToast( error ); addToWishListBtn.setEnabled( true ); } } } ); } } } } ); // WishList Button click... // TODO: MyCart Code // Add to Cart Click... addToCartBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { addToCartBtn.setEnabled( false ); if (currentUser == null){ dialogsClass.signInUpDialog( PRODUCT_DETAILS_ACTIVITY ); addToCartBtn.setEnabled( true ); } else{ dialog.show(); if (ALREADY_ADDED_IN_CART){ dialog.dismiss(); // Code if already add in cart... showToast( "Already Added in cart..!" ); addToCartBtn.setEnabled( true ); } else{ // Code if item not add in cart... final int tempCartSize = DBquery.myCartCheckList.size(); Map<String, Object> addProductIntoCart = new HashMap <>(); for (int temX = 0; temX < tempCartSize; temX++ ){ addProductIntoCart.put( "product_ID_"+ temX, DBquery.myCartCheckList.get( temX ).getProductId() ); addProductIntoCart.put( "product_qty_"+ temX, DBquery.myCartCheckList.get( temX ).getProductQuantity() ); } addProductIntoCart.put( "product_ID_"+ tempCartSize, productID ); addProductIntoCart.put( "product_qty_"+ tempCartSize, "1" ); addProductIntoCart.put( "my_cart_size", (long)DBquery.myCartCheckList.size()+1 ); //Since we have use set Method so we have to add all the previous fields in Map also to update the List... firebaseFirestore.collection( "USER" ).document( currentUser.getUid() ) .collection( "USER_DATA" ).document( "MY_CART" ) .set( addProductIntoCart ).addOnCompleteListener( new OnCompleteListener <Void>() { @Override public void onComplete(@NonNull Task <Void> task) { if (task.isSuccessful()){ DBquery.myCartCheckList.add( new MyCartCheckModel( productID, "1" ) ); if (DBquery.myCartItemModelList.size() != 0){ if(documentSnapshot.get( "product_qty_type" ) != null){ DBquery.myCartItemModelList.add( tempCartSize, new MyCartItemModel( 0, productID , 1 , documentSnapshot.get( "product_image_1" ).toString() , documentSnapshot.get( "product_full_name" ).toString() , documentSnapshot.get( "product_price" ).toString() , documentSnapshot.get( "product_cut_price" ).toString() , documentSnapshot.get( "product_qty_type" ).toString() ) ); }else{ DBquery.myCartItemModelList.add( tempCartSize, new MyCartItemModel( 0, productID , 1 , documentSnapshot.get( "product_image_1" ).toString() , documentSnapshot.get( "product_full_name" ).toString() , documentSnapshot.get( "product_price" ).toString() , documentSnapshot.get( "product_cut_price" ).toString() , " " ) ); } if (MyCartFragment.myCartAdaptor != null){ MyCartFragment.myCartAdaptor.notifyDataSetChanged(); } } ALREADY_ADDED_IN_CART = true; dialog.dismiss(); showToast( "Added to Cart SuccessFully..!" ); // To Refresh Menu... invalidateOptionsMenu(); addToCartBtn.setEnabled( true ); // Query To update List Size on firebase and offline list... } else{ dialog.dismiss(); String error = task.getException().getMessage(); showToast( error ); addToCartBtn.setEnabled( true ); } } } ); // Code if item not add in cart... } } } } ); // Add to Cart Click... // TODO: Buy Now Code // Buy Now Click... buyNowBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Intent buyNowIntent = new Intent( ProductDetails.this, BuyNowActivity.class ); // myAddressIntent.putExtra( "MODE", SELECT_ADDRESS ); startActivity( buyNowIntent ); // Set BUY_FROM value... StaticValues.BUY_FROM_VALUE = StaticValues.BUY_FROM_HOME; // Run this query to get Size of OrderList... So if user Buy this item then New order would be added..! if (currentUser != null){ DBquery.orderListQuery( ProductDetails.this, dialog, false ); } } } ); // Buy Now Click... } // onCreate method End.. ---------------------------------- @Override protected void onResume() { super.onResume(); // To Refresh Menu... invalidateOptionsMenu(); } @Override protected void onStart() { super.onStart(); // check offline wishList Size.. and run DB query to update wishList if size is 0 if (currentUser != null){ if (DBquery.myWishList.size() == 0){ DBquery.wishListQuery(ProductDetails.this, dialog, false); } // set color of wishList button based on wishList... if (DBquery.myWishList.size() != 0){ if (DBquery.myWishList.contains( productID )){ ALREADY_ADDED_IN_WISHLIST = true; addToWishListBtn.setSupportImageTintList( getResources().getColorStateList( R.color.colorRed ) ); }else{ ALREADY_ADDED_IN_WISHLIST = false; } dialog.dismiss(); } // for cart list... if (DBquery.myCartCheckList.size() == 0){ DBquery.cartListQuery(ProductDetails.this, false, dialog, PRODUCT_DETAILS_ACTIVITY); }else { for (int i = 0; i < DBquery.myCartCheckList.size(); i++) { if( DBquery.myCartCheckList.get( i ).getProductId().equals( productID )){ ALREADY_ADDED_IN_CART = true; break; }else{ ALREADY_ADDED_IN_CART = false; } } dialog.dismiss(); } }else { // dialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate( R.menu.menu_show_in_product_details,menu); MenuItem cartItem = menu.findItem( R.id.menu_cart ); // Check First whether any item in cart or not... // if any item has in cart... cartItem.setActionView( R.layout.badge_cart_layout ); // ImageView badgeCartIcon = cartItem.getActionView().findViewById( R.id.badge_cart_icon ); badgeCartCount = cartItem.getActionView().findViewById( R.id.badge_count_text ); if (DBquery.myCartCheckList.size() > 0){ badgeCartCount.setVisibility( View.VISIBLE ); badgeCartCount.setText( String.valueOf( DBquery.myCartCheckList.size() ) ); } cartItem.getActionView().setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // GOTO : Goto Cart if (currentUser == null){ dialogsClass.signInUpDialog( PRODUCT_DETAILS_ACTIVITY ); }else{ startActivity( new Intent(ProductDetails.this, MainActivity.class) ); MainActivity.isFragmentIsMyCart = true; } } } ); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if ((item.getItemId() == android.R.id.home)){ finish(); return true; }else if (id == R.id.menu_cart){ // GOTO : Goto Cart if (currentUser == null){ dialogsClass.signInUpDialog( PRODUCT_DETAILS_ACTIVITY ); }else{ startActivity( new Intent(this, MainActivity.class) ); MainActivity.isFragmentIsMyCart = true; } return true; } return super.onOptionsItemSelected( item ); } private void showToast(String s){ Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } }
true
c0147c61c5f6f872206b64e8b9bf5d3586396b8d
Java
kenynw/Cht
/app/src/main/java/com/damenghai/chahuitong/module/personal/AreaPresenter.java
UTF-8
2,693
1.992188
2
[]
no_license
package com.damenghai.chahuitong.module.personal; import android.content.Intent; import android.os.Bundle; import android.view.ViewGroup; import android.widget.TextView; import com.damenghai.chahuitong.R; import com.damenghai.chahuitong.expansion.list.BaseListActivityPresenter; import com.damenghai.chahuitong.model.AddressModel; import com.damenghai.chahuitong.model.bean.Area; import com.jude.easyrecyclerview.adapter.BaseViewHolder; import butterknife.Bind; import butterknife.ButterKnife; /** * Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved. */ public class AreaPresenter extends BaseListActivityPresenter<AreaActivity, Area> { private int mDeep; private Area mArea; private String mAction; @Override protected void onCreate(AreaActivity view, Bundle saveState) { super.onCreate(view, saveState); mDeep = getView().getIntent().getIntExtra("deep", 0); mArea = getView().getIntent().getParcelableExtra("area"); mAction = getView().getIntent().getStringExtra("action"); } @Override protected void onCreateView(AreaActivity view) { super.onCreateView(view); onRefresh(); if (mArea != null) getView().setToolbarTitle(mArea.getArea_name()); else getView().setToolbarTitle(R.string.title_activity_province); getAdapter().setOnItemClickListener(position -> { Area area = getAdapter().getItem(position); if (mArea != null) area.setArea_name(mArea.getArea_name() + " " + area.getArea_name()); Intent intent = new Intent(); intent.putExtra("area", area); intent.putExtra("action", mAction); if (area.getArea_deep() == (mDeep > 0 ? mDeep : 3)) { intent.setAction(mAction); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } else { intent.putExtra("deep", mDeep); intent.setClass(getView(), AreaActivity.class); } getView().startActivity(intent); }); } @Override public void onRefresh() { AddressModel.getInstance().getAreaList(mArea != null ? mArea.getArea_id() : 0) .unsafeSubscribe(getRefreshSubscriber()); } public static class AreaViewHolder extends BaseViewHolder<Area> { @Bind(android.R.id.text1) TextView mTvText; public AreaViewHolder(ViewGroup parent) { super(parent, android.R.layout.simple_expandable_list_item_1); ButterKnife.bind(this, itemView); } @Override public void setData(Area data) { mTvText.setText(data.getArea_name()); } } }
true
ec9a7cd3d3cba90ab3ef8adbc74efdc58a89b9b2
Java
AshwiniVijayaKumar/Chrome-Cars
/code/com/adsdk/sdk/video/AspectRatioImageView.java
UTF-8
5,572
2.15625
2
[]
no_license
package com.adsdk.sdk.video; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View.MeasureSpec; import android.widget.ImageView; public class AspectRatioImageView extends ImageView { private boolean mFill = false; private int mMaxH = -1; private int mMinW = -1; public AspectRatioImageView(Context paramContext) { super(paramContext); } public AspectRatioImageView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); } public AspectRatioImageView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); } public static float dip2pixel(int paramInt, Context paramContext) { paramContext = paramContext.getResources(); return TypedValue.applyDimension(1, paramInt, paramContext.getDisplayMetrics()); } void ensureConstraintMetAndSet(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i; int j; float f; if (paramInt3 < paramInt4) { i = 1; if (i == 0) { break label133; } j = paramInt1; i = paramInt2; if (this.mMinW > 0) { f = dip2pixel(this.mMinW, getContext()); j = paramInt1; i = paramInt2; if (paramInt1 < f) { j = (int)f; i = paramInt4 / paramInt3 * j; } } paramInt1 = j; paramInt2 = i; if (this.mMaxH > 0) { f = dip2pixel(this.mMaxH, getContext()); paramInt1 = j; paramInt2 = i; if (i > f) { paramInt2 = (int)f; paramInt1 = paramInt2 * paramInt3 / paramInt4; } } } for (;;) { setMeasuredDimension(paramInt1, paramInt2); return; i = 0; break; label133: j = paramInt1; i = paramInt2; if (this.mMaxH > 0) { f = dip2pixel(this.mMaxH, getContext()); j = paramInt1; i = paramInt2; if (paramInt2 > f) { i = (int)f; j = i * paramInt3 / paramInt4; } } paramInt1 = j; paramInt2 = i; if (this.mMinW > 0) { f = dip2pixel(this.mMinW, getContext()); paramInt1 = j; paramInt2 = i; if (j < f) { paramInt1 = (int)f; paramInt2 = paramInt4 / paramInt3 * paramInt1; } } } } public void fillParent(boolean paramBoolean, int paramInt1, int paramInt2) { this.mFill = paramBoolean; this.mMaxH = paramInt2; this.mMinW = paramInt1; } int getConstrainedHeight(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i; float f; if (paramInt3 < paramInt4) { i = 1; if (i == 0) { break label114; } i = paramInt2; if (this.mMinW > 0) { f = dip2pixel(this.mMinW, getContext()); i = paramInt2; if (paramInt1 < f) { paramInt1 = (int)f; i = paramInt4 / paramInt3 * paramInt1; } } paramInt1 = i; if (this.mMaxH > 0) { f = dip2pixel(this.mMaxH, getContext()); paramInt1 = i; if (i > f) { paramInt1 = (int)f; paramInt2 = paramInt1 * paramInt3 / paramInt4; } } } label114: int j; do { do { return paramInt1; i = 0; break; j = paramInt1; i = paramInt2; if (this.mMaxH > 0) { f = dip2pixel(this.mMaxH, getContext()); j = paramInt1; i = paramInt2; if (paramInt2 > f) { i = (int)f; j = i * paramInt3 / paramInt4; } } paramInt1 = i; } while (this.mMinW <= 0); f = dip2pixel(this.mMinW, getContext()); paramInt1 = i; } while (j >= f); paramInt1 = (int)f; return paramInt4 / paramInt3 * paramInt1; } protected int getMeasuredHeight(int paramInt1, int paramInt2) { int i = View.MeasureSpec.getSize(paramInt1); View.MeasureSpec.getSize(paramInt2); if ((!this.mFill) || (getDrawable() == null)) { super.onMeasure(paramInt1, paramInt2); return 0; } paramInt2 = getDrawable().getIntrinsicHeight(); int j = getDrawable().getIntrinsicWidth(); if (j > paramInt2) { paramInt1 = i * paramInt2 / j; } for (;;) { return getConstrainedHeight(i, paramInt1, j, paramInt2); paramInt1 = i; i = paramInt1 * j / paramInt2; } } protected void onMeasure(int paramInt1, int paramInt2) { int i = View.MeasureSpec.getSize(paramInt1); View.MeasureSpec.getSize(paramInt2); if ((!this.mFill) || (getDrawable() == null)) { super.onMeasure(paramInt1, paramInt2); return; } paramInt2 = getDrawable().getIntrinsicHeight(); int j = getDrawable().getIntrinsicWidth(); if (j > paramInt2) { paramInt1 = i * paramInt2 / j; } for (;;) { ensureConstraintMetAndSet(i, paramInt1, j, paramInt2); return; paramInt1 = i; i = paramInt1 * j / paramInt2; } } } /* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\com\adsdk\sdk\video\AspectRatioImageView.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
e554e7912a5bca48caeea015d1dd1f8efcd8bf4f
Java
NicholasMata/KeyprApi-Android
/keyprapi/src/main/java/com/matadesigns/keyprapi/models/OAuthResponse.java
UTF-8
552
1.992188
2
[]
no_license
package com.matadesigns.keyprapi.models; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class OAuthResponse implements Serializable { @SerializedName("access_token") public String accessToken; @SerializedName("expires_in") public int expiresIn; @SerializedName("token_type") public String tokenType; @SerializedName("scope") public String scope; @SerializedName("refresh_token") public String refreshToken; @SerializedName("id_token") public String idToken; }
true
5341c53161f5cda3dbc9984dc233d3149593281f
Java
imagej/imagej-common
/src/main/java/net/imagej/convert/ROITreeToMaskPredicateConverter.java
UTF-8
4,192
2.234375
2
[ "BSD-2-Clause" ]
permissive
/*- * #%L * ImageJ2 software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2023 ImageJ2 developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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. * #L% */ package net.imagej.convert; import java.lang.reflect.Type; import java.util.function.Function; import net.imagej.roi.ROITree; import net.imglib2.roi.MaskPredicate; import org.scijava.convert.AbstractConverter; import org.scijava.convert.Converter; import org.scijava.plugin.Plugin; import org.scijava.util.TreeNode; import org.scijava.util.Types; /** * {@link Converter} from {@link ROITree} to {@link MaskPredicate}. * * @author Gabriel Selzer * @author Curtis Rueden */ @Plugin(type = Converter.class) public class ROITreeToMaskPredicateConverter extends ConciseConverter<ROITree, MaskPredicate> { public ROITreeToMaskPredicateConverter() { super(ROITree.class, MaskPredicate.class, src -> (MaskPredicate) src .children().get(0).data()); } @Override public boolean canConvert(final Object src, final Type dest) { // NB: If we don't override this method, the superclass logic invokes // canConvert(Class, Class), which does the wrong thing for this // instance-sensitive converter, because if we don't have the instance, // we can't know whether a particular destination subtype is an acceptable // conversion target. We must delegate to a method that knows the instance. // // This implementation here is probably overkill, and it's hard to be // perfect about this with all generic types, but here we check that *all* // raw types of the given destination type are acceptable conversion targets // for this object. But there are certainly many ways this could go wrong. return Types.raws(dest).stream().allMatch(c -> canConvert(src, c)); } @Override public boolean canConvert(final Object src, final Class<?> dest) { if (!(src instanceof ROITree)) return false; // NB: We don't check the dest type versus MaskPredicate here. // An instance-insensitive converter cannot guarantee conversion of a // ROITree to, say, ClosedWritableEllipsoid, because by types alone we don't // know that the ROITree contains a ClosedWritableEllipsoid specifically -- // all we know is that it contains zero or more MaskPredicates. // But this converter is *instance-sensitive*, meaning it promises // convertibility to a particular destination type iff the input ROITree's // sole child is that type. So we'll check the destination type at the end, // after we have extracted the contents of the ROITree. @SuppressWarnings("unchecked") final ROITree srcTree = (ROITree) src; // Assert exactly one ROI in the tree. if (srcTree.children().size() != 1) return false; final TreeNode<?> onlyChild = srcTree.children().get(0); if (!onlyChild.children().isEmpty()) return false; // Assert the only ROI is of the type we are looking for. return dest.isInstance(onlyChild.data()); } }
true
322ccceb612cb195e31eb3673a927bee1f2f2508
Java
cgb-study/angler
/src/test/java/com/lmax/angler/monitoring/network/monitor/util/EncodedData2ObjectHashMapFuzzTest.java
UTF-8
4,471
2.40625
2
[ "Apache-2.0" ]
permissive
package com.lmax.angler.monitoring.network.monitor.util; import org.agrona.collections.Long2ObjectHashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; @RunWith(Parameterized.class) public class EncodedData2ObjectHashMapFuzzTest { private final EncodedData2ObjectHashMap<EncodableKey, String> map; private final Long2ObjectHashMap<String> comparison; private final long seed = 29095236049802L; private final Random random = new Random(seed); private final int numberOfElements; public EncodedData2ObjectHashMapFuzzTest(final int initialCapacity, final float loadFactor, final int numberOfElements) { this.numberOfElements = numberOfElements; map = new EncodedData2ObjectHashMap<>(initialCapacity, loadFactor, 8, this::encodeKey, encoded -> Long.hashCode(encoded.getLong(0)), new EncodableKey(Long.MIN_VALUE)); comparison = new Long2ObjectHashMap<>(initialCapacity, loadFactor); } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { 2, 0.5f, 37 }, { 4, 0.6f, 2347 }, { 16, 0.1f, 16 }, { 64, 0.2222f, 883 }, { 2048, 0.3f, 16555 } }); } @Test public void shouldContainValuesAfterInsert() throws Exception { try { final List<EncodableKey> keyList = generateKeyList(numberOfElements); keyList.forEach(e -> { map.put(e, Long.toString(e.value)); }); keyList.forEach(e -> { assertThat(failureMessage("Expected map to contain key " + e), map.containsKey(e), is(true)); }); } catch(RuntimeException e) { e.printStackTrace(); fail(failureMessage(e.getMessage())); } } @Test public void shouldRemoveElements() throws Exception { try { final List<EncodableKey> keyList = generateKeyList(numberOfElements); keyList.forEach(e -> { map.put(e, Long.toString(e.value)); comparison.put(e.value, Long.toString(e.value)); }); Collections.shuffle(keyList, random); keyList.forEach(e -> { assertThat(failureMessage("Expected comparison to contain a value for " + e), comparison.remove(e.value), is(not(nullValue()))); assertThat(failureMessage("Expected comparison to not contain key " + e), comparison.containsKey(e.value), is(false)); assertThat(failureMessage("Expected map to contain a value for " + e), map.remove(e), is(not(nullValue()))); assertThat(failureMessage("Expected map to not contain key " + e), map.containsKey(e), is(false)); }); } catch(RuntimeException e) { e.printStackTrace(); fail(failureMessage(e.getMessage())); } } private List<EncodableKey> generateKeyList(final int numberOfKeys) { final Set<Long> uniqueKeys = new HashSet<>(); while(uniqueKeys.size() < numberOfKeys) { uniqueKeys.add(Math.abs(random.nextLong())); } return uniqueKeys.stream().map(EncodableKey::new).collect(Collectors.toList()); } private String failureMessage(final String input) { return "SEED: " + seed + "; " + input; } private static final class EncodableKey { private long value; private EncodableKey(final long value) { this.value = value; } @Override public String toString() { return "EncodableKey{" + "value=" + value + '}'; } } private void encodeKey(final EncodableKey key, final ByteBuffer keyBuffer) { keyBuffer.putLong(key.value); } }
true
c4755b2b19ea90752b621f0ad3cf2a894685d890
Java
kevin-schmid/DistComp
/server/src/main/java/at/fhj/game/GameManagerImpl.java
UTF-8
2,255
2.765625
3
[]
no_license
package at.fhj.game; import at.fhj.SimpQui; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; class GameManagerImpl implements GameManager { private static final Logger log = LoggerFactory.getLogger(GameManagerImpl.class); private final Set<Game> gameCache = Collections.synchronizedSet(new HashSet<Game>()); private final Map<String, Player> playerCache = new ConcurrentHashMap<>(); private final UserStatProducer statProducer = new UserStatProducer(); private Game openGame = new Game(); @Override public void addPlayer(Player player) { openGame.addPlayer(player); if(openGame.isStartable()) { log.debug("game starts"); startGame(openGame); openGame = new Game(); } } @Override public void correctAnswer(String username) { log.debug("{} has the correct answer", username); playerCache.get(username).incCorrectAnswers(); } @Override public void endGame(Game game) { log.debug("game ended"); var result = Result.of(game); for(var player : game.getPlayers()) { player.send(result); playerCache.remove(player.getUsername()); } statProducer.send(result); gameCache.remove(game); } private void startGame(Game game) { gameCache.add(game); game.getPlayers().forEach(player -> playerCache.put(player.getUsername(), player)); var roundTime = Integer.parseInt(SimpQui.INSTANCE.getProperty(SimpQui.PropertyKey.GameRoundTime)); var roundCount = Integer.parseInt(SimpQui.INSTANCE.getProperty(SimpQui.PropertyKey.GameRoundCount)); log.debug("games lasts {} rounds, each {} seconds", roundCount, roundTime); var scheduler = Executors.newSingleThreadScheduledExecutor(); IntStream.range(0, roundCount).forEach(i -> scheduler.schedule(game, roundTime*i, TimeUnit.SECONDS)); scheduler.schedule(new GameTerminator(game), (roundTime*roundCount)+1, TimeUnit.SECONDS); scheduler.shutdown(); } }
true
be652a4e4db9b8e43e33f9591eb2415a7f57d1bd
Java
Pragmatism0220/Kira
/app/src/main/java/com/moemoe/lalala/di/components/SelectComponents.java
UTF-8
555
1.75
2
[ "Apache-2.0" ]
permissive
package com.moemoe.lalala.di.components; import com.moemoe.lalala.di.modules.SelectUpterModule; import com.moemoe.lalala.di.scopes.UserScope; import com.moemoe.lalala.view.activity.SelectMovieActivity; import com.moemoe.lalala.view.activity.SelectMusicActivity; import dagger.Component; /** * Created by Hygge on 2018/7/17. */ @UserScope @Component(modules = SelectUpterModule.class,dependencies = NetComponent.class) public interface SelectComponents { void inject(SelectMusicActivity activity); void inject(SelectMovieActivity activity); }
true
89827461afe3e23378578981a43b84e240d280fc
Java
MossabTN/spring-microservices-poc
/order-service/src/main/java/io/maxilog/service/mapper/impl/OrderMapperImpl.java
UTF-8
4,531
2.140625
2
[]
no_license
package io.maxilog.service.mapper.impl; import io.maxilog.client.CustomerClient; import io.maxilog.domain.Order; import io.maxilog.domain.OrderItem; import io.maxilog.service.dto.CustomerDTO; import io.maxilog.service.dto.OrderDTO; import io.maxilog.service.dto.OrderItemDTO; import io.maxilog.service.mapper.AddressMapper; import io.maxilog.service.mapper.OrderItemMapper; import io.maxilog.service.mapper.OrderMapper; import io.maxilog.service.mapper.PaymentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Component public class OrderMapperImpl implements OrderMapper { @Autowired private PaymentMapper paymentMapper; private final OrderItemMapper orderItemMapper; private final AddressMapper addressMapper; private final CustomerClient userClient; public OrderMapperImpl(OrderItemMapper orderItemMapper, AddressMapper addressMapper, CustomerClient userClient) { this.orderItemMapper = orderItemMapper; this.addressMapper = addressMapper; this.userClient = userClient; } @Override public Order toEntity(OrderDTO dto) { if (dto == null) { return null; } Order order = new Order(); order.setId(dto.getId()); order.setTotalPrice(dto.getTotalPrice()); order.setStatus(dto.getStatus()); order.setShipped(dto.getShipped()); order.setPayment(paymentMapper.toEntity(dto.getPayment())); order.setShipmentAddress(addressMapper.toEntity(dto.getShipmentAddress())); order.setOrderItems(orderItemDTOSetToOrderItemSet(dto.getOrderItems())); //order.setCustomer( dto.getCustomer() ); order.setCustomer(dto.getCustomer() == null ? null : dto.getCustomer().getUsername()); return order; } @Override public OrderDTO toDto(Order entity) { if (entity == null) { return null; } OrderDTO orderDTO = new OrderDTO(); orderDTO.setId(entity.getId()); orderDTO.setTotalPrice(entity.getTotalPrice()); orderDTO.setStatus(entity.getStatus()); orderDTO.setShipped(entity.getShipped()); orderDTO.setPayment(paymentMapper.toDto(entity.getPayment())); orderDTO.setShipmentAddress(addressMapper.toDto(entity.getShipmentAddress())); orderDTO.setOrderItems(orderItemSetToOrderItemDTOSet(entity.getOrderItems())); //orderDTO.setCustomer( entity.getCustomer() ); try { CustomerDTO customerDTO = userClient.getUserByUsername(entity.getCustomer()).getBody(); if (customerDTO != null) { orderDTO.setCustomer(customerDTO); } else { orderDTO.setCustomer(new CustomerDTO(entity.getCustomer())); } } catch (Exception e) { orderDTO.setCustomer(new CustomerDTO(entity.getCustomer())); } return orderDTO; } @Override public List<Order> toEntity(List<OrderDTO> dtoList) { if (dtoList == null) { return null; } List<Order> list = new ArrayList<Order>(dtoList.size()); for (OrderDTO orderDTO : dtoList) { list.add(toEntity(orderDTO)); } return list; } @Override public List<OrderDTO> toDto(List<Order> entityList) { if (entityList == null) { return null; } List<OrderDTO> list = new ArrayList<OrderDTO>(entityList.size()); for (Order order : entityList) { list.add(toDto(order)); } return list; } protected Set<OrderItem> orderItemDTOSetToOrderItemSet(Set<OrderItemDTO> set) { if (set == null) { return null; } Set<OrderItem> set1 = new HashSet<OrderItem>(Math.max((int) (set.size() / .75f) + 1, 16)); for (OrderItemDTO orderItemDTO : set) { set1.add(orderItemMapper.toEntity(orderItemDTO)); } return set1; } protected Set<OrderItemDTO> orderItemSetToOrderItemDTOSet(Set<OrderItem> set) { if (set == null) { return null; } Set<OrderItemDTO> set1 = new HashSet<OrderItemDTO>(Math.max((int) (set.size() / .75f) + 1, 16)); for (OrderItem orderItem : set) { set1.add(orderItemMapper.toDto(orderItem)); } return set1; } }
true
d6452081e69b08098c0a4f12d1635b02f7e9d781
Java
Eainde/spring-data-reactive
/src/main/java/com/eainde/reactive/repository/mapper/UserMapper.java
UTF-8
830
2.28125
2
[]
no_license
package com.eainde.reactive.repository.mapper; import com.eainde.reactive.entity.User; import io.r2dbc.spi.Row; import java.util.function.BiFunction; import org.springframework.stereotype.Component; @Component public class UserMapper implements BiFunction<Row, Object, User> { @Override public User apply(Row row, Object o) { long id = row.get("user_id", Long.class); String country = row.get("country", String.class); long age = row.get("age", Long.class); String name = row.get("name", String.class); String password = row.get("password", String.class); boolean enabled = row.get("enabled", Boolean.class); String roleName = row.get("role_name", String.class); long roleId = row.get("role_id", Long.class); return new User(id, name, country, age, roleName, roleId, password); } }
true
1bdb790c261e3cd18409ee89d20ce214722b0f75
Java
MarcoLunaGonzales/almacenes
/src/java/com/cofar/bean/EstadosSalidasAlmacen.java
UTF-8
771
2.015625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.cofar.bean; /** * * @author hvaldivia */ public class EstadosSalidasAlmacen { int codEstadoSalidaAlmacen = 0; String nombreEstadoSalidaAlmacen = ""; public int getCodEstadoSalidaAlmacen() { return codEstadoSalidaAlmacen; } public void setCodEstadoSalidaAlmacen(int codEstadoSalidaAlmacen) { this.codEstadoSalidaAlmacen = codEstadoSalidaAlmacen; } public String getNombreEstadoSalidaAlmacen() { return nombreEstadoSalidaAlmacen; } public void setNombreEstadoSalidaAlmacen(String nombreEstadoSalidaAlmacen) { this.nombreEstadoSalidaAlmacen = nombreEstadoSalidaAlmacen; } }
true
732a25b7394da6c5c32702d3d4ab170cd57a225d
Java
KiaShamaei/digiBackend
/src/main/java/com/healthy/project/ProjectApplication.java
UTF-8
2,062
2.109375
2
[]
no_license
package com.healthy.project; import java.util.Arrays; import java.util.List; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import com.healthy.project.security.JWTAuthorizationFilter; @SpringBootApplication public class ProjectApplication { public static void main(String[] args) { SpringApplication.run(ProjectApplication.class, args); } @EnableWebSecurity @Configuration class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers(HttpMethod.GET, "/").permitAll() .antMatchers(HttpMethod.GET, "/loginuser").permitAll() .antMatchers(HttpMethod.POST, "/adduser").permitAll() .anyRequest().authenticated(); http.cors().configurationSource(corsConfigurationSource()); } //This can be customized as required @Bean CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); return source; } }}
true
315841ffb170983b7aae87985aa087cffe39f9d7
Java
ConnectorIO/connectorio-addons
/bundles/org.connectorio.addons.profile/src/main/java/org/connectorio/addons/profile/internal/ProfileConfigOptionProvider.java
UTF-8
2,528
1.757813
2
[ "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later" ]
permissive
/* * Copyright (C) 2019-2021 ConnectorIO Sp. z o.o. * * 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.connectorio.addons.profile.internal; import java.net.URI; import java.util.Collection; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.openhab.core.config.core.ConfigOptionProvider; import org.openhab.core.config.core.ParameterOption; import org.openhab.core.thing.profiles.ProfileFactory; import org.openhab.core.thing.profiles.ProfileType; import org.openhab.core.thing.profiles.ProfileTypeRegistry; import org.openhab.core.thing.profiles.StateProfileType; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; /** * Currently brings no real value.. */ //@Component(service = ConfigOptionProvider.class) public class ProfileConfigOptionProvider implements ConfigOptionProvider { private static final String CONFIG_URI = "profile:connectorio:profiles"; private static final String PROFILES_OPTION = "profiles"; private final ProfileTypeRegistry registry; private Set<ProfileFactory> profileFactories; @Activate public ProfileConfigOptionProvider(@Reference ProfileTypeRegistry registry) { this.registry = registry; } @Override public Collection<ParameterOption> getParameterOptions(URI uri, String param, String context, Locale locale) { if (CONFIG_URI.equals(uri.toString()) && PROFILES_OPTION.equals(param)) { Set<ParameterOption> options = new HashSet<>(); for (ProfileType type : registry.getProfileTypes(locale)) { if (ConnectorioProfiles.PROFILE.equals(type.getUID())) { // remove chain from options continue; } if (type instanceof StateProfileType) { options.add(new ParameterOption(type.getUID().getAsString(), type.getLabel())); } } return options; } return null; } }
true
0720d1d0974e4b57f66d66ad4a58fc3a9763aca0
Java
DanielRubi/HomeWork-822-104
/HomeWork24_10_2018_Part2/AlarmClock.java
UTF-8
125
1.625
2
[]
no_license
package HomeWork24_10_2018_Part2; public class AlarmClock extends Alarm { private ExtendedTime currentTime; }
true
62e6d9e7afe18ca1f678782de7ff655166db4985
Java
selenide/selenide
/modules/appium/src/main/java/com/codeborne/selenide/appium/AppiumScrollOptions.java
UTF-8
1,260
2.609375
3
[ "LicenseRef-scancode-free-unknown", "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
package com.codeborne.selenide.appium; public class AppiumScrollOptions { private final ScrollDirection scrollDirection; private final int maxSwipeCounts; private static final int DEFAULT_MAX_SWIPE_COUNTS = 30; private AppiumScrollOptions(ScrollDirection scrollDirection, int maxSwipeCounts) { this.scrollDirection = scrollDirection; this.maxSwipeCounts = maxSwipeCounts; } public static AppiumScrollOptions with(ScrollDirection scrollDirection, int maxSwipeCounts) { return new AppiumScrollOptions(scrollDirection, maxSwipeCounts); } public static AppiumScrollOptions down() { return new AppiumScrollOptions(ScrollDirection.DOWN, DEFAULT_MAX_SWIPE_COUNTS); } public static AppiumScrollOptions down(int maxSwipeCounts) { return new AppiumScrollOptions(ScrollDirection.DOWN, maxSwipeCounts); } public static AppiumScrollOptions up() { return new AppiumScrollOptions(ScrollDirection.UP, DEFAULT_MAX_SWIPE_COUNTS); } public static AppiumScrollOptions up(int maxSwipeCounts) { return new AppiumScrollOptions(ScrollDirection.UP, maxSwipeCounts); } public int getMaxSwipeCounts() { return maxSwipeCounts; } public ScrollDirection getScrollDirection() { return scrollDirection; } }
true
04a25302dcc5ac37b2f909d489eb721e911f6d01
Java
erichstark/bachelor-android-app
/src/com/erichstark/pedometer/sqlite/model/SleepReport.java
UTF-8
6,196
2.515625
3
[]
no_license
package com.erichstark.pedometer.sqlite.model; public class SleepReport { int id; int currentRecordCount; String nextPageUrl; String prevPageUrl; int pageLength; int pageNumber; int recordCount; // sleep data list int awaken; String dataid; String startTime; String endTime; int fellSleep; int hoursSlept; double latitude; double longitude; String note; int sleepEfficiency; public SleepReport() { } public SleepReport(int currentRecordCount, String nextPageUrl, String prevPageUrl, int pageLength, int pageNumber, int recordCount, int awaken, String dataid, String startTime, String endTime, int fellSleep, int hoursSlept, double latitude, double longitude, String note, int sleepEfficiency) { super(); this.currentRecordCount = currentRecordCount; this.nextPageUrl = nextPageUrl; this.prevPageUrl = prevPageUrl; this.pageLength = pageLength; this.pageNumber = pageNumber; this.recordCount = recordCount; this.awaken = awaken; this.dataid = dataid; this.startTime = startTime; this.endTime = endTime; this.fellSleep = fellSleep; this.hoursSlept = hoursSlept; this.latitude = latitude; this.longitude = longitude; this.note = note; this.sleepEfficiency = sleepEfficiency; } public SleepReport(int id, int currentRecordCount, String nextPageUrl, String prevPageUrl, int pageLength, int pageNumber, int recordCount, int awaken, String dataid, String startTime, String endTime, int fellSleep, int hoursSlept, double latitude, double longitude, String note, int sleepEfficiency) { super(); this.id = id; this.currentRecordCount = currentRecordCount; this.nextPageUrl = nextPageUrl; this.prevPageUrl = prevPageUrl; this.pageLength = pageLength; this.pageNumber = pageNumber; this.recordCount = recordCount; this.awaken = awaken; this.dataid = dataid; this.startTime = startTime; this.endTime = endTime; this.fellSleep = fellSleep; this.hoursSlept = hoursSlept; this.latitude = latitude; this.longitude = longitude; this.note = note; this.sleepEfficiency = sleepEfficiency; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the currentRecordCount */ public int getCurrentRecordCount() { return currentRecordCount; } /** * @param currentRecordCount the currentRecordCount to set */ public void setCurrentRecordCount(int currentRecordCount) { this.currentRecordCount = currentRecordCount; } /** * @return the nextPageUrl */ public String getNextPageUrl() { return nextPageUrl; } /** * @param nextPageUrl the nextPageUrl to set */ public void setNextPageUrl(String nextPageUrl) { this.nextPageUrl = nextPageUrl; } /** * @return the prevPageUrl */ public String getPrevPageUrl() { return prevPageUrl; } /** * @param prevPageUrl the prevPageUrl to set */ public void setPrevPageUrl(String prevPageUrl) { this.prevPageUrl = prevPageUrl; } /** * @return the pageLength */ public int getPageLength() { return pageLength; } /** * @param pageLength the pageLength to set */ public void setPageLength(int pageLength) { this.pageLength = pageLength; } /** * @return the pageNumber */ public int getPageNumber() { return pageNumber; } /** * @param pageNumber the pageNumber to set */ public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } /** * @return the recordCount */ public int getRecordCount() { return recordCount; } /** * @param recordCount the recordCount to set */ public void setRecordCount(int recordCount) { this.recordCount = recordCount; } /** * @return the awaken */ public int getAwaken() { return awaken; } /** * @param awaken the awaken to set */ public void setAwaken(int awaken) { this.awaken = awaken; } /** * @return the dataid */ public String getDataid() { return dataid; } /** * @param dataid the dataid to set */ public void setDataid(String dataid) { this.dataid = dataid; } /** * @return the startTime */ public String getStartTime() { return startTime; } /** * @param startTime the startTime to set */ public void setStartTime(String startTime) { this.startTime = startTime; } /** * @return the endTime */ public String getEndTime() { return endTime; } /** * @param endTime the endTime to set */ public void setEndTime(String endTime) { this.endTime = endTime; } /** * @return the fellSleep */ public int getFellSleep() { return fellSleep; } /** * @param fellSleep the fellSleep to set */ public void setFellSleep(int fellSleep) { this.fellSleep = fellSleep; } /** * @return the hoursSlept */ public int getHoursSlept() { return hoursSlept; } /** * @param hoursSlept the hoursSlept to set */ public void setHoursSlept(int hoursSlept) { this.hoursSlept = hoursSlept; } /** * @return the latitude */ public double getLatitude() { return latitude; } /** * @param latitude the latitude to set */ public void setLatitude(double latitude) { this.latitude = latitude; } /** * @return the longitude */ public double getLongitude() { return longitude; } /** * @param longitude the longitude to set */ public void setLongitude(double longitude) { this.longitude = longitude; } /** * @return the note */ public String getNote() { return note; } /** * @param note the note to set */ public void setNote(String note) { this.note = note; } /** * @return the sleepEfficiency */ public int getSleepEfficiency() { return sleepEfficiency; } /** * @param sleepEfficiency the sleepEfficiency to set */ public void setSleepEfficiency(int sleepEfficiency) { this.sleepEfficiency = sleepEfficiency; } }
true
3ed64ddc75d5f51a223bbdcca63c4ac08f30bb0a
Java
LeeeYudE/HenCoderDemo1
/app/src/main/java/com/charco/android/hencoderdemo1/view/AvatarView.java
UTF-8
2,425
2.375
2
[]
no_license
package com.charco.android.hencoderdemo1.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Shader; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import com.charco.android.hencoderdemo1.R; /** * Created 18/7/16 19:24 * Author:charcolee * Version:V1.0 * ---------------------------------------------------- * 文件描述: * ---------------------------------------------------- */ public class AvatarView extends View { private Paint mBitmapPaint , mPaint; private Bitmap mBitmap; private float mPaintWidth; public AvatarView(Context context) { this(context,null); } public AvatarView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public AvatarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { //绘制图片的paint mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //绘制圆环的paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(getResources().getColor(R.color.colorPrimary)); mPaintWidth = Util.dp2px(getContext(),5); mPaint.setStrokeWidth(mPaintWidth); mPaint.setStyle(Paint.Style.STROKE); mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avatar); Shader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP); mBitmapPaint.setShader(shader); } @Override public void draw(Canvas canvas) { //绘制带image的圆,中心点为view的中心 canvas.drawCircle(mBitmap.getWidth()/2,getWidth()/2,getHeight()/2,mBitmapPaint); //绘制黑色圆边框,中心点为view的中心 canvas.drawCircle(mBitmap.getWidth()/2,getWidth()/2,getHeight()/2 - mPaintWidth/2,mPaint); super.draw(canvas); } //设置view的宽高为图片宽高 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(mBitmap.getWidth(), mBitmap.getHeight()); } }
true
f37deb30545e979eb429e9965a38de2fd68e7b68
Java
BingAds/BingAds-Java-SDK
/proxies/com/microsoft/bingads/v13/reporting/Adapter16.java
UTF-8
601
1.804688
2
[ "MIT" ]
permissive
package com.microsoft.bingads.v13.reporting; import java.util.Collection; import jakarta.xml.bind.annotation.adapters.XmlAdapter; public class Adapter16 extends XmlAdapter<String, Collection<ChangeTypeReportFilter>> { public Collection<ChangeTypeReportFilter> unmarshal(String value) { return (com.microsoft.bingads.v13.reporting.ChangeTypeReportFilterConverter.convertToList(value)); } public String marshal(Collection<ChangeTypeReportFilter> value) { return (com.microsoft.bingads.v13.reporting.ChangeTypeReportFilterConverter.convertToString(value)); } }
true
03991acc09eaff47aa5476119b66229fc53f3c59
Java
majia2968/Mental-Health-eScreening
/escreening/src/main/java/gov/va/escreening/service/export/ExportDataServiceImpl.java
UTF-8
31,450
1.789063
2
[ "Apache-2.0" ]
permissive
package gov.va.escreening.service.export; import com.google.common.base.Preconditions; import com.google.common.collect.*; import gov.va.escreening.domain.ExportTypeEnum; import gov.va.escreening.domain.MeasureTypeEnum; import gov.va.escreening.dto.dashboard.AssessmentDataExport; import gov.va.escreening.dto.dashboard.DataExportCell; import gov.va.escreening.dto.dashboard.DataExportFilterOptions; import gov.va.escreening.entity.*; import gov.va.escreening.form.ExportDataFormBean; import gov.va.escreening.repository.*; import gov.va.escreening.service.VeteranAssessmentService; import gov.va.escreening.util.DataExportAndDictionaryUtil; import gov.va.escreening.util.SurveyResponsesHelper; import gov.va.escreening.variableresolver.AssessmentVariableDto; import gov.va.escreening.variableresolver.VariableResolverService; import org.bouncycastle.util.Strings; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import javax.annotation.Resource; import java.io.ByteArrayOutputStream; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; @Service("exportDataService") public class ExportDataServiceImpl implements ExportDataService, MessageSourceAware { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource(name = "theDataDictionary") DataDictionary dd; @Resource(type = AssessmentVariableRepository.class) private AssessmentVariableRepository avr; @Resource(type = DataDictionaryService.class) private DataDictionaryService dds; @Resource(type = ExportLogRepository.class) private ExportLogRepository exportLogRepository; @Resource(type = ExportTypeRepository.class) private ExportTypeRepository exportTypeRepository; @Resource(type = ExportLogAuditRepository.class) private ExportLogAuditRepository exportLogAuditRepository; private MessageSource msgSrc; @Resource(type = ProgramRepository.class) private ProgramRepository programRepository; @Resource(type = SurveyResponsesHelper.class) private SurveyResponsesHelper srh; @Resource(type = UserRepository.class) private UserRepository userRepository; @Resource(type = VeteranAssessmentService.class) private VeteranAssessmentService veteranAssessmentService; @Resource(type = VeteranRepository.class) private VeteranRepository veteranRepository; @Resource(type = VariableResolverService.class) private VariableResolverService vrs; @Resource(type = DataExportAndDictionaryUtil.class) private DataExportAndDictionaryUtil dedUtil; /** * method to find a response of 1 in multi-select type responses. If user has responded to any question, then all * other unanswered question must be marked 999. All this method does is that it changes those 999 to 0 * * @param multiSelectMap */ private void change999To0IfNeeded( Multimap<String, DataExportCell> multiSelectMap) { for (String key : multiSelectMap.keySet()) { Collection<DataExportCell> cells = multiSelectMap.get(key); for (DataExportCell cell : cells) { if ("1".equals(cell.getCellValue())) { setMissingCellsToZero(cells); break; } } } } @Override public List<DataExportCell> buildExportDataForOneAssessment(VeteranAssessment va, int identifiedExportType) { Map<String, Map<String, String>> preFetchedData = prepareData(Arrays.asList(va), identifiedExportType); List<DataExportCell> row = buildExportDataPerAssessment(va, identifiedExportType, preFetchedData); return row; } @Override public Date getLastSnapshotDate() { return exportLogRepository.findLastSnapshotDate(); } private List<DataExportCell> buildExportDataPerAssessment( VeteranAssessment assessment, Integer identifiedExportType, Map<String, Map<String, String>> preFetchedData) { Map<String, String> formulaeMap = preFetchedData.get(formulaKey(assessment)); // has user asked to show the ppi info or not boolean show = ExportTypeEnum.DEIDENTIFIED.getExportTypeId() != identifiedExportType; // gather mandatory columns data List<DataExportCell> exportDataRowCells = buildMandatoryColumns(assessment, show); for (String surveyName : preFetchedData.get(surveyNamesKey()).keySet()) { List<String> formulaNames = dds.findAllFormulas(surveyName); Map<String, String> usrRespMap = preFetchedData.get(usrRespKey(assessment, surveyName)); Map<String, String> surveyDictionary = preFetchedData.get(dictHdrKey(surveyName)); Map<String, String> answerTypeOther = preFetchedData.get(answerTypeOtherKey(surveyName)); Map<String, String> dataTypeMap = dd.findSheet(surveyName).column(msgSrc.getMessage("data.dict.column.ques.multi.select", null, null)); // traverse through each exportName, and try to find the veteran's response for the exportName. In case the // user has not responded, leave 999 Multimap<String, DataExportCell> multiSelectMap = HashMultimap.create(); for (Entry<String, String> surveyEntry : surveyDictionary.entrySet()) { String surveyExportName = surveyEntry.getValue(); String dataType = dataTypeMap.get(surveyEntry.getKey()); boolean multiSelect = Boolean.valueOf(dataType); if (!surveyExportName.isEmpty()) { DataExportCell aCell = createExportCell(usrRespMap, formulaeMap, answerTypeOther, surveyExportName, formulaNames, show); if (logger.isTraceEnabled()) { logger.trace(String.format("adding data for data dictionary column %s->%s=%s", surveyName, surveyExportName, aCell)); } exportDataRowCells.add(aCell); saveMultiSelectResponses(multiSelect, multiSelectMap, surveyEntry, aCell); } } change999To0IfNeeded(multiSelectMap); } return exportDataRowCells; } private String surveyNamesKey() { return "DATA_DICTIONARY_SURVEY"; } private String dictHdrKey(String surveyName) { return String.format("SURVEY_DICTIONARY_KEY_%s", surveyName); } private Map<String, Map<String, String>> buildFormulaeMapForMatchingAssessments( List<VeteranAssessment> matchingAssessments) { Map<String, Map<String, String>> formulaeMap = Maps.newHashMap(); List<AssessmentVariable> avFormulaeEntities = avr.findAllFormulae(); for (VeteranAssessment va : matchingAssessments) { Iterable<AssessmentVariableDto> avFormulaeList = vrs.resolveVariablesFor(va.getVeteranAssessmentId(), avFormulaeEntities); formulaeMap.put(formulaKey(va), createFormulaeMap(avFormulaeList)); } return formulaeMap; } public List<DataExportCell> buildMandatoryColumns( VeteranAssessment assessment, boolean show) { List<DataExportCell> mandatoryData = new ArrayList<DataExportCell>(); mandatoryData.addAll(collectPpi(assessment, show)); mandatoryData.add(new DataExportCell("assessment_id", srh.getOrMiss(srh.getStrFromInt(assessment.getVeteranAssessmentId())))); mandatoryData.add(new DataExportCell("created_by", srh.getOrMiss(assessment.getCreatedByUser() != null ? assessment.getCreatedByUser().getUserFullName() : null))); mandatoryData.add(new DataExportCell("battery_name", srh.getOrMiss(assessment.getBattery() != null ? assessment.getBattery().getName() : null))); mandatoryData.add(new DataExportCell("program_name", srh.getOrMiss(assessment.getProgram() != null ? assessment.getProgram().getName() : null))); mandatoryData.add(new DataExportCell("vista_clinic", srh.getOrMiss(assessment.getClinic() != null ? assessment.getClinic().getName() : null))); mandatoryData.add(new DataExportCell("note_title", srh.getOrMiss(assessment.getNoteTitle() != null ? assessment.getNoteTitle().getName() : null))); mandatoryData.add(new DataExportCell("clinician_name", srh.getOrMiss(assessment.getClinician() != null ? assessment.getClinician().getUserFullName() : null))); mandatoryData.add(new DataExportCell("date_created", srh.getOrMiss(srh.getDtAsStr(assessment.getDateCreated())))); mandatoryData.add(new DataExportCell("time_created", srh.getOrMiss(srh.getTmAsStr(assessment.getDateCreated())))); mandatoryData.add(new DataExportCell("date_completed", srh.getOrMiss(srh.getDtAsStr(assessment.getDateCompleted())))); mandatoryData.add(new DataExportCell("time_completed", srh.getOrMiss(srh.getTmAsStr(assessment.getDateCompleted())))); mandatoryData.add(new DataExportCell("duration", srh.getOrMiss(srh.getStrFromInt(assessment.getDuration())))); mandatoryData.add(new DataExportCell("vista_DOB", show ? srh.getOrMiss(srh.getDtAsStr(assessment.getVeteran().getBirthDate())) : srh.miss())); return mandatoryData; } private List<DataExportCell> collectPpi(VeteranAssessment assessment, boolean show) { Veteran v = assessment.getVeteran(); List<DataExportCell> mandatoryIdendifiedData = new ArrayList<DataExportCell>(); // if veteran has taken the 'Identification' survey then skip this as veteran survey response // will take precedence over the clinician entered data mandatoryIdendifiedData.addAll(Arrays.asList(new DataExportCell("vista_lastname", show ? srh.getOrMiss(v.getLastName()) : srh.miss()),// new DataExportCell("vista_firstname", show ? srh.getOrMiss(v.getVistaFirstName()) : srh.miss()),// new DataExportCell("vista_midname", show ? srh.getOrMiss(v.getVistaMiddleName()) : srh.miss()),// new DataExportCell("vista_SSN", show ? srh.getOrMiss(v.getSsnLastFour()) : srh.miss()), new DataExportCell("vista_ien", v.getVeteranIen()))); return mandatoryIdendifiedData; } private List<List<DataExportCell>> createDataExportReport( List<VeteranAssessment> matchingAssessments, Integer identifiedExportType, Map<String, Map<String, String>> preFetchedData) { List<List<DataExportCell>> dataExportReport = new ArrayList<List<DataExportCell>>(); // build an export row for each assessment for (VeteranAssessment assessment : matchingAssessments) { List<DataExportCell> xportedDataForOneAssessment = buildExportDataPerAssessment(assessment, identifiedExportType, preFetchedData); dataExportReport.add(xportedDataForOneAssessment); } return dataExportReport; } private DataExportCell createExportCell(Map<String, String> usrRespMap, Map<String, String> formulaeMap, Map<String, String> answerTypeOther, String exportName, List<String> formulaNames, boolean show) { // try to find the user response String exportVal = usrRespMap == null ? null : usrRespMap.get(exportName); // if value of export name was a formula (sum, avg, or some other formula derived value) exportVal = srh.getOrMiss(exportVal == null ? formulaeMap.get(exportName) : exportVal); // find out if this is an other datatype boolean other = "true".equals(answerTypeOther.get(exportName)); boolean formula = isFormula(exportName, formulaNames, formulaeMap); // if other=true than the export name is of type other (o), or if formula=true than the export name is formula (f), else otherwise it is a regular data type (r) char dataType = other ? 'o' : formula ? 'f' : 'r'; return new DataExportCell(exportName, exportVal, dataType); } private boolean isFormula(String exportName, List<String> formulaNames, Map<String, String> formulaeMap) { boolean f = formulaeMap.get(exportName) != null; if (!f) { f = formulaNames.contains(exportName); } return f; } private ExportLog createExportLogFromOptions(DataExportFilterOptions options) { Preconditions.checkNotNull(options, "DataExportFilterOptions value cannot be null"); ExportLog exportLog = new ExportLog(); if (options.getAssessmentEnd() != null) { exportLog.setAssessmentEndFilter(options.getAssessmentEnd()); } if (options.getAssessmentStart() != null) { exportLog.setAssessmentStartFilter(options.getAssessmentStart()); } if (options.getClinicianUserId() != null) { User clinician = userRepository.findOne(options.getClinicianUserId()); exportLog.setClinician(clinician); } if (options.getComment() != null && !options.getComment().isEmpty()) { exportLog.setComment(options.getComment()); } if (options.getCreatedByUserId() != null) { User createdByUser = userRepository.findOne(options.getCreatedByUserId()); exportLog.setCreatedByUser(createdByUser); } if (options.getExportedByUserId() != null) { User exportedByUser = userRepository.findOne(options.getExportedByUserId()); exportLog.setExportedByUser(exportedByUser); } if (options.getExportTypeId() != null) { ExportType exportType = exportTypeRepository.findOne(options.getExportTypeId()); exportLog.setExportType(exportType); } if (options.getFilePath() != null && !options.getFilePath().isEmpty()) { exportLog.setFilePath(options.getFilePath()); } if (options.getProgramId() != null) { Program program = programRepository.findOne(options.getProgramId()); exportLog.setProgram(program); } if (options.getVeteranId() != null) { Veteran veteran = veteranRepository.findOne(options.getVeteranId()); exportLog.setVeteran(veteran); } return exportLog; } private DataExportFilterOptions createFilterOptions( ExportDataFormBean exportDataFormBean) { DataExportFilterOptions filterOptions = new DataExportFilterOptions(); if (exportDataFormBean.getToAssessmentDate() != null) filterOptions.setAssessmentEnd(exportDataFormBean.getToAssessmentDate()); if (exportDataFormBean.getFromAssessmentDate() != null) filterOptions.setAssessmentStart(exportDataFormBean.getFromAssessmentDate()); if (exportDataFormBean.getClinicianId() != null) filterOptions.setClinicianUserId(exportDataFormBean.getClinicianId()); if (exportDataFormBean.getCommentText() != null) filterOptions.setComment(exportDataFormBean.getCommentText()); if (exportDataFormBean.getCreatedByUserId() != null) filterOptions.setCreatedByUserId(exportDataFormBean.getCreatedByUserId()); if (exportDataFormBean.getExportedByUserId() != null) filterOptions.setExportedByUserId(exportDataFormBean.getExportedByUserId()); if (exportDataFormBean.getExportLogId() != null) filterOptions.setExportLogId(exportDataFormBean.getExportLogId()); if (exportDataFormBean.getExportTypeId() != null) filterOptions.setExportTypeId(exportDataFormBean.getExportTypeId()); if (exportDataFormBean.getProgramId() != null) filterOptions.setProgramId(exportDataFormBean.getProgramId()); if (exportDataFormBean.getVeteranId() != null) filterOptions.setVeteranId(exportDataFormBean.getVeteranId()); String filePath = String.format("va_export_data_as_of_ts_%s.csv", System.nanoTime()); filterOptions.setFilePath(filePath); return filterOptions; } private Map<String, String> createFormulaeMap( Iterable<AssessmentVariableDto> avFormulaeList) { Map<String, String> formulaeMap = Maps.newHashMap(); for (AssessmentVariableDto dto : avFormulaeList) { formulaeMap.put(dto.getDisplayName(), dto.getDisplayText()); } return formulaeMap; } @Override @Transactional public AssessmentDataExport downloadExportData(Integer userId, int exportLogId, String comment) { // create Assessment Data Export from export log ExportLog exportLog = exportLogRepository.findOne(exportLogId); AssessmentDataExport ade = AssessmentDataExport.createFromExportLog(exportLog); ade.setExportLogId(exportLog.getExportLogId()); // create a new entry in the export log audit saving the comments plus also the clinician who is downloading this export log ExportLogAudit exportLogAudit = new ExportLogAudit(); exportLogAudit.setExportLog(exportLog); exportLogAudit.setExportedByUser(userRepository.findByUserId(userId)); exportLogAudit.setComment(comment); exportLogAudit.setDateUpdated(new Date()); exportLogAuditRepository.create(exportLogAudit); return ade; } @Override @Transactional public AssessmentDataExport getAssessmentDataExport( ExportDataFormBean exportDataFormBean, StopWatch sw) { if (exportDataFormBean.getHasParameter()) { if (sw != null) sw.start("data export"); AssessmentDataExport assessmentDataExport = generateAssessmentDataExport(exportDataFormBean); if (sw != null) sw.stop(); if (sw != null) sw.start("save data as zip"); saveDataExportAsZip(assessmentDataExport); if (sw != null) sw.stop(); return assessmentDataExport; } return null; } @Override public void takeAssessmentSnapShot(Integer exportedById) { dds.tryPrepareDataDictionary(true); Date lastSnapshotDate = exportLogRepository.findLastSnapshotDate(); ExportDataFormBean exportDataFormBean = new ExportDataFormBean(); exportDataFormBean.setHasParameter(true); exportDataFormBean.setFromAssessmentDate(LocalDate.fromDateFields(lastSnapshotDate).toDate()); exportDataFormBean.setToAssessmentDate(LocalDate.now().toDate()); exportDataFormBean.setExportTypeId(ExportTypeEnum.DEIDENTIFIED.getExportTypeId()); exportDataFormBean.setExportedByUserId(exportedById); exportDataFormBean.setCommentText("snapshot taken before changing meta information"); getAssessmentDataExport(exportDataFormBean, null); } private AssessmentDataExport generateAssessmentDataExport(ExportDataFormBean exportDataFormBean) { // ***Step#1*** Use the passed in filter criteria to pull in the matching assessments List<VeteranAssessment> matchingAssessments = veteranAssessmentService.searchVeteranAssessmentForExport(exportDataFormBean); // ***Step#2*** get data dictionary (optimized with table questions) + usr responses grouped by assessment and every // module Map<String, Map<String, String>> prefetchedData = prepareData(matchingAssessments, exportDataFormBean.getExportTypeId()); // ***Step#3*** prepare exportData from matching assessments and against the data dictionary List<List<DataExportCell>> dataExportRows = createDataExportReport(matchingAssessments, exportDataFormBean.getExportTypeId(), prefetchedData); AssessmentDataExport assessmentDataExport = new AssessmentDataExport(); assessmentDataExport.setHeaderAndRows(dataExportRows); DataExportFilterOptions filterOptions = createFilterOptions(exportDataFormBean); assessmentDataExport.setFilterOptions(filterOptions); return assessmentDataExport; } /** * method to create a zip file and pack data-dict and data-export * * @param dataExport csv data consisting of data export */ private void saveDataExportAsZip(AssessmentDataExport dataExport) { ByteArrayOutputStream zippedBaos = new ByteArrayOutputStream(); String zipFileName = dedUtil.createZipFor(dataExport, zippedBaos); //extract the byte[] so we can save them dataExport.getFilterOptions().setFilePath(zipFileName); byte[] zippedBytes = zippedBaos.toByteArray(); dataExport.setExportZip(zippedBytes); saveExportLog(dataExport); } private ExportLog saveExportLog(AssessmentDataExport dataExport) { // Add an entry to the exportLog table ExportLog exportLog = createExportLogFromOptions(dataExport.getFilterOptions()); exportLog.setExportZip(dataExport.getExportZip()); exportLogRepository.create(exportLog); return exportLog; } /** * This method * <p> * <ol> * <p> * <li> * traverses every Assessment and for every Assessment, it traverses every Survey, collects the user Response, and * then adjust the Survey Dictionary for Survey. This merges export names (export names can vary for each assessment * depending on the table questions). This is necessary to merge and collect distinct columns of each assessment's * export names to allows aligning veteran rows. It saves set of merged survey columns with a key of * "SURVEY_DICTIONARY_KEY_<surveyName></li> * <p> * <li> * since this method captures the optimized survey dictionary, while doing so, it has to collect user responses for * the survey, which is time consuming--so this method also saves those user responses under the key of * USR_RESPONSE_KEY_<veteranAssessmentId>_<surveyName></li> * <p> * <li>and just before returning, it also captures Variable formulae for every assessments under the key of * FORMULAE_KEY_<veteranAssessmentId></li> * <p> * </ol> * <p> * PS: all the data this method captures for future processing is a transaction data, except the survey dictionary, * which is mostly static data * * @param matchingAssessments * @param identifiedExportType * @return */ private Map<String, Map<String, String>> prepareData( List<VeteranAssessment> matchingAssessments, Integer identifiedExportType) { String exportNameKey = msgSrc.getMessage("data.dict.column.var.name", null, null); String answerTypeKey = msgSrc.getMessage("data.dict.column.answer.type.other", null, null); boolean show = ExportTypeEnum.DEIDENTIFIED.getExportTypeId() != identifiedExportType; Map<String, Map<String, String>> miscDataMap = Maps.newHashMap(); // we want to see surveys sorted (columns are children of surveys) in the report Map<String, String> surveyNamesMap = Maps.newTreeMap(); for (VeteranAssessment assessment : matchingAssessments) { List<SurveyMeasureResponse> smrList = assessment.getSurveyMeasureResponseList(); for (String surveyName : dd.getModuleNames()) { Map<String, String> usrRespMap = srh.prepareSurveyResponsesMap(surveyName, smrList, show); if (usrRespMap == null) { continue; } miscDataMap.put(usrRespKey(assessment, surveyName), usrRespMap); // get the table data (one sheet) for this survey DataDictionarySheet surveySheet = dd.findSheet(surveyName); // extract all rows/columnValues for column key=data.dict.column.var.name Map<String, String> ddColumnData = surveySheet.column(exportNameKey); // extract all answerType is Other or not miscDataMap.put(answerTypeOtherKey(surveyName), createExportNameOtherMap(surveySheet.column(answerTypeKey))); buildDictionaryHeaderFor(surveyName, syncTableQ(usrRespMap, ddColumnData), miscDataMap); surveyNamesMap.put(surveyName, miscDataMap.get(dictHdrKey(surveyName)).toString()); } } // collect all the formulae for these matching Assessments miscDataMap.putAll(buildFormulaeMapForMatchingAssessments(matchingAssessments)); miscDataMap.put(surveyNamesKey(), surveyNamesMap); return miscDataMap; } private Map<String, String> createExportNameOtherMap(Map<String, String> ddColumnOtherData) { Map<String, String> m = Maps.newHashMap(); for (String value : ddColumnOtherData.values()) { String v[] = value.split("[$]"); if (!v[0].isEmpty()) { m.put(v[0], v[1]); } } return m; } private String answerTypeOtherKey(String surveyName) { return String.format("%s__%s", surveyName, "ANSWER_TYPE_OTHER"); } private void buildDictionaryHeaderFor(String surveyName, Map<String, String> syncTableQ, Map<String, Map<String, String>> miscDataMap) { String surveyDictionaryKey = dictHdrKey(surveyName); Map<String, String> currentSurveyDictionary = miscDataMap.get(surveyDictionaryKey); if (currentSurveyDictionary == null) { miscDataMap.put(surveyDictionaryKey, syncTableQ); } else { currentSurveyDictionary.putAll(syncTableQ); } } private String formulaKey(VeteranAssessment va) { return String.format("FORMULAE_KEY_%s", va.getVeteranAssessmentId()); } private String usrRespKey(VeteranAssessment assessment, String surveyName) { return String.format("USR_RESPONSE_KEY_%s_%s", assessment.getVeteranAssessmentId(), surveyName); } private void saveMultiSelectResponses( boolean multiSelect, Multimap<String, DataExportCell> multiSelectMap, Entry<String, String> entry, DataExportCell oneCell) { if (!multiSelect) { return; } String key = entry.getKey(); key = key.substring(0, key.lastIndexOf("_")); multiSelectMap.put(key, oneCell); } @Override public void setMessageSource(MessageSource msgSrc) { this.msgSrc = msgSrc; } private void setMissingCellsToZero(Collection<DataExportCell> cells) { for (DataExportCell cell : cells) { if (cell.getDataType() == 'r' && srh.miss().equals(cell.getCellValue())) { cell.setCellValue("0"); } } } /** * method to traverse user responses and look for table questions * <p> * for every table question, this method will add a row in data dictionary * * @param usrRespMap * @return */ private Map<String, String> syncTableQ(Map<String, String> usrRespMap, Map<String, String> dataDictionarySurveyColumns) { // map of data dictionary row id and column name (no values) Map<String, String> ddColumnData = Maps.newTreeMap(); ddColumnData.putAll(dataDictionarySurveyColumns); // keep data for modified column data and will merge with ddColumnData after finishing the traversing Map<String, String> modColumnData = Maps.newTreeMap(); // keep track of rows to delete from ddColumn--the rows will be deleted as they are modified and preserved in // modColumnData List<String> toBeDelKeys = Lists.newArrayList(); Map<String, String> tableQuestionResponseCntr = Maps.newHashMap(); Set<String> usrRespExportNames = usrRespMap.keySet().stream().filter(p -> p != null).collect(Collectors.toSet()); for (String usrRespExportName : usrRespExportNames) { if (usrRespExportName.contains("~")) { String[] exportNamesParts = Strings.split(usrRespExportName, '~'); String usrExportName = exportNamesParts[0]; String usrTQIndex = exportNamesParts[1]; // now look for this export name in the columnData [] for (Entry<String, String> entry : ddColumnData.entrySet()) { if (entry.getValue().equals(usrExportName)) { String expotNameKeyPrefix = dds.getExportNameKeyPrefix(); modColumnData.put(entry.getKey().replaceAll(expotNameKeyPrefix, expotNameKeyPrefix + usrTQIndex + "_"), usrRespExportName); toBeDelKeys.add(entry.getKey()); } } // also update userRespMap with TableQuestion response counter. Data Dictionary has a table Question // response counter for this export name // try to create the same export name here. we may end up having some redundant names here but thats ok. // as far as we have the one that matches with data dictionary table question response counter we are // fine handleTableQuestionResponse(usrExportName, tableQuestionResponseCntr, Integer.parseInt(usrTQIndex)); } } // merge table question response counter with usrRespMap usrRespMap.putAll(tableQuestionResponseCntr); // truncate the ddColumnData (remove all keys which are to be replaced with Table Questions Tabular rows) for (String key : toBeDelKeys) { ddColumnData.remove(key); } // update the data dictionary row-id with the set of new row id and column names with the new column names ddColumnData.putAll(modColumnData); return ddColumnData; } private void handleTableQuestionResponse(String usrExportName, Map<String, String> tableQuestionResponseCntr, int usrTQIndex) { String keyName = dds.createTableResponseVarName(usrExportName); String existingIndexAsStr = tableQuestionResponseCntr.get(keyName); int nextIndex = usrTQIndex + 1; // incoming index is zero based and we want to use this as a counter if (existingIndexAsStr != null) { int existingIndex = Integer.parseInt(existingIndexAsStr); nextIndex = Math.max(existingIndex, nextIndex); } tableQuestionResponseCntr.put(keyName, String.valueOf(nextIndex)); } }
true
138d100e796109e8a8cd692ef6e916ef9b5338d6
Java
FranklinNEO/BeautyCamera2016
/app/src/main/java/cn/poco/login/site/RegisterLoginPageSite402.java
UTF-8
1,239
1.945313
2
[]
no_license
package cn.poco.login.site; import android.content.Context; import android.graphics.Bitmap; import java.util.HashMap; import cn.poco.framework.FileCacheMgr; import cn.poco.framework.MyFramework; import cn.poco.framework2.Framework2; import cn.poco.utils.Utils; /** * 社区直接进入注册的验证手机 */ public class RegisterLoginPageSite402 extends RegisterLoginPageSite { public void verify_Code(HashMap<String,Object> datas,Context context) { HashMap<String ,Object> params = new HashMap<>(); Bitmap bmp = (Bitmap) datas.get("img"); String path = FileCacheMgr.GetLinePath(); if(Utils.SaveTempImg(bmp, path)) { params.put("img",path); } params.put("info",datas.get("info")); MyFramework.SITE_Open(context, RegisterLoginInfoPageSite402.class, params, Framework2.ANIM_NONE); } //返回上一步 public void toLoginPage(Context context) { MyFramework.SITE_Open(context, LoginPageSite402.class, null, Framework2.ANIM_NONE); } //返回上一步 public void onBackToLastPage(Context context) { MyFramework.SITE_ClosePopup(context, null, Framework2.ANIM_NONE); } //返回上一步 public void onBack(Context context) { MyFramework.SITE_ClosePopup(context, null, Framework2.ANIM_NONE); } }
true
10e9d7a50f988a52ac0cd86bb1f4d557b2db605c
Java
yarencheng/candidate2016
/src/main/java/net/arenx/candidate2016/appengine/enums/Sex.java
UTF-8
81
1.65625
2
[ "Apache-2.0" ]
permissive
package net.arenx.candidate2016.appengine.enums; public enum Sex{ male,female }
true
a727d6ba60a1518811477028d02398e78e1aaf54
Java
shamilsdq/peer-chat
/src/main/java/com/shamilsdq/peerchat/App.java
UTF-8
5,391
2.78125
3
[]
no_license
package com.shamilsdq.peerchat; import java.util.HashMap; import java.io.IOException; import java.net.SocketException; import java.net.UnknownHostException; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; public class App extends Application { private static Scene scene; private static GUIController gui; private static NetworkController network; private static Task receiveMessageTask; private static Task sendMessageTask; private static HashMap<String, Chat> table; @Override public void start(Stage stage) throws IOException { table = new HashMap<String, Chat>(); initGUI(); initNetwork(); // display GUI stage.setScene(scene); stage.setTitle("PEER-CHAT"); stage.setMinWidth(800.0); stage.setMinHeight(560.0); stage.show(); // default chat with self addChatter("127.0.0.1"); showChat("127.0.0.1"); } private void initGUI() throws IOException { FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("GUI.fxml")); scene = new Scene((Parent) fxmlLoader.load()); gui = (GUIController) fxmlLoader.getController(); } private void initNetwork() { try { network = new NetworkController(); receiveMessageTask = new Task<Void>() { @Override protected Void call() { int count = 0; while (true) { if (isCancelled()) break; try { count += 1; network.receiveMessage(); } catch (SocketException ex) { System.out.println(ex); gui.showWarning("Socket Exception occurred"); } catch (IOException ex) { System.out.println(ex); gui.showWarning("IO Exception occurred"); } } return null; } }; Runtime.getRuntime().addShutdownHook(new Thread(() -> { receiveMessageTask.cancel(); })); new Thread(receiveMessageTask).start(); } catch (SocketException ex) { System.out.println(ex); gui.showError("Socket Exception encountered"); Platform.exit(); } } public static void addChatter(String chatter) { if (table.containsKey(chatter) == false) { table.put(chatter, new Chat()); gui.addChatter(chatter); } } public static void showChat(String chatter) { if (table.containsKey(chatter)) gui.showChat(chatter, table.get(chatter)); } public static void sendMessage() { String chatter = gui.getChatter(); String messageContent = gui.getMessage(); if (messageContent.trim().length() == 0) return; sendMessageTask = new Task<Void>() { @Override protected Void call() { try { network.sendMessage(chatter, messageContent); } catch (SocketException ex) { System.out.println(ex); gui.showWarning("Socket Exception occurred"); } catch (UnknownHostException ex) { System.out.println(ex); gui.showWarning("UnknowHost Exception occurred"); } catch (IOException ex) { System.out.println(ex); gui.showWarning("IO Exception occurred"); } return null; } }; new Thread(sendMessageTask).start(); Message message = new Message(messageContent, true); table.get(chatter).addMessage(message); gui.addMessage(chatter, message); } public static void recieveMessage(String chatter, String messageContent) { // wil add new chatter if does not exists App.addChatter(chatter); Message message = new Message(messageContent, false); table.get(chatter).addMessage(message); if (gui.getChatter().equals(chatter)) { System.out.flush(); gui.addMessage(chatter, message); } System.out.flush(); } @Override public void stop() { if (receiveMessageTask != null && receiveMessageTask.isRunning()) receiveMessageTask.cancel(); network.close(); } public static void main(String[] args) { launch(); } }
true
6eb538ab3a753bc6f84e43caab35b31abbc9ff84
Java
ljnelson/carts
/carts-core/src/main/java/io/helidon/examples/sockshop/carts/ItemsApiAsync.java
UTF-8
3,980
2.4375
2
[ "Apache-2.0" ]
permissive
package io.helidon.examples.sockshop.carts; import java.util.List; import java.util.concurrent.CompletionStage; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PATCH; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; /** * REST API for {@code /items} sub-resource. */ public interface ItemsApiAsync { @GET @Produces(APPLICATION_JSON) @Operation(summary = "Return the list of products in the customer's shopping cart") @APIResponse( responseCode = "200", description = "The list of products in the customer's shopping cart", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(type = SchemaType.ARRAY, implementation = Item.class) )) CompletionStage<List<Item>> getItems(); @POST @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @Operation(summary = "Add item to the shopping cart", description = "This operation will add item to the shopping cart if it " + "doesn't already exist, or increment quantity by the specified " + "number of items if it does") @APIResponse(responseCode = "201", description = "Added item", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Item.class))) CompletionStage<Response> addItem(@RequestBody(description = "Item to add to the cart") Item item); @GET @Path("{itemId}") @Produces(APPLICATION_JSON) @Operation(summary = "Return specified item from the shopping cart") @APIResponses({ @APIResponse(responseCode = "200", description = "If specified item exists in the cart", content = @Content(mediaType = APPLICATION_JSON, schema = @Schema(implementation = Item.class))), @APIResponse(responseCode = "404", description = "If specified item does not exist in the cart") }) CompletionStage<Response> getItem( @Parameter(name = "itemId", description = "Item identifier") @PathParam("itemId") String itemId); @DELETE @Path("{itemId}") @Operation(summary = "Remove specified item from the shopping cart, if it exists") @APIResponse(responseCode = "202", description = "Regardless of whether the specified item exists in the cart") CompletionStage<Response> deleteItem( @Parameter(name = "itemId", description = "Item identifier") @PathParam("itemId") String itemId); @PATCH @Consumes(APPLICATION_JSON) @Operation(summary = "Update item in a shopping cart", description = "This operation will add item to the shopping cart if it " + "doesn't already exist, or replace it with the specified item " + "if it does") @APIResponse(responseCode = "202", description = "Regardless of whether the specified item exists in the cart") CompletionStage<Response> updateItem(@RequestBody(description = "Item to update") Item item); }
true
2c16b4b9f759a88b078c365fbbc93bf84e674ac3
Java
ljx958720/design_pattern
/src/main/java/com/ghy/designmode/abstractFactory/ShreddedMeat.java
UTF-8
224
2.515625
3
[]
no_license
package com.ghy.designmode.abstractFactory; //具体产品:鱼香肉丝 public class ShreddedMeat implements HunanCuisine{ @Override public void order() { System.out.println ("点了鱼香肉丝"); } }
true
ab58b83f2ed84f2807dfef0eb1c9992a64237160
Java
taisihu/demo_design-pattern
/src/main/java/com/hts/test/designpattern/bridge/TestBridge.java
UTF-8
447
2.4375
2
[]
no_license
package com.hts.test.designpattern.bridge; public class TestBridge { public static void main(String[] args) { DriverBridge driverBridge = new MyDriverBridge(); MySqlDrive mySqlDrive = new MySqlDrive(); driverBridge.setDriverable(mySqlDrive); driverBridge.drive(); OracleDrive oracleDrive = new OracleDrive(); driverBridge.setDriverable(oracleDrive); driverBridge.drive(); } }
true
5577171c09dc2fa8aa306bf13ac58762731abd70
Java
vahv/online-store-mvc-exercise
/src/main/java/com/victorherrera/onlinestoremvcexercise/services/SaleService.java
UTF-8
318
1.960938
2
[]
no_license
package com.victorherrera.onlinestoremvcexercise.services; import com.victorherrera.onlinestoremvcexercise.model.Sale; import java.util.Set; public interface SaleService { Set<Sale> findAll(); Sale findById(Long id); Sale save(Sale object); void delete(Sale object); void deleteById(Long id); }
true
3b0dfeda02768a5133c903ef6f7036c588d51f20
Java
QuanWenLan/ownJavaDemo
/src/main/java/com/lanwq/jvm/classload/ConstantClass.java
UTF-8
510
2.59375
3
[]
no_license
package com.lanwq.jvm.classload; /** * @author Vin lan * @className ConstantClass * @description TODO * @createTime 2020-12-18 17:27 **/ /** * 被动使用类字段演示三: * 常量在编译阶段会存入调用类的常量池中,本质上并没有引用到定义常量的类,因此不会触发定义的常量的类的初始化 */ public class ConstantClass { static { System.out.println("ConstantClass init!"); } public static final String HELLO_WORLD = "hello world"; }
true
fed6499f06a33c5a4e47009152d80f5b3976b99a
Java
robertcialowicz/PrzychodniaAutomatyczna
/VisitReminderSystem/src/main/java/com/iet/przychodnia/VisitReminderSystem/model/Reminder.java
UTF-8
1,751
2.484375
2
[]
no_license
package com.iet.przychodnia.VisitReminderSystem.model; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.UUID; public class Reminder { @Id @GeneratedValue(strategy = GenerationType.AUTO) private final UUID id; private final UUID patientID; private final UUID doctorID; private final UUID visitID; private final String datetime; public Reminder() { this.id = null; this.patientID = null; this.doctorID = null; this.visitID = null; this.datetime = null; } public Reminder(@JsonProperty("id") UUID id, @JsonProperty("patientID") UUID patientID, @JsonProperty("doctorID") UUID doctorID, @JsonProperty("visitID") UUID visitID, @JsonProperty("datetime") String datetime) { this.id = id; this.patientID = patientID; this.doctorID = doctorID; this.visitID = visitID; this.datetime = datetime; } public UUID getId() { return id; } public UUID getPatientID() { return patientID; } public UUID getDoctorID() { return doctorID; } public UUID getVisitID() { return visitID; } public String getDatetime() { return datetime; } @Override public String toString() { return "Reminder{" + "id=" + id + ", patientID=" + patientID + ", doctorID=" + doctorID + ", visitID=" + visitID + ", datetime='" + datetime + '\'' + '}'; } }
true