blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
a4e4fdb5952986a166f45141cbdb3c31e6616c69
5c153c3ebe75974c37fc53bbed07e3ba872c1aa2
/app/src/main/java/com/tariqaliiman/tariqaliiman/classes/Athkar_S_M.java
9b369cece9a809a0d3c63147115752a429d98c39
[]
no_license
BaherAlsaqa/TariqAliiman
d26eb960e362f9b198389a89d56a90b8d4f334c4
f4f5c1502d3f573240e491fc165af913111dda4f
refs/heads/master
2022-06-05T14:30:01.648473
2020-05-05T10:51:12
2020-05-05T10:51:12
235,259,099
0
0
null
null
null
null
UTF-8
Java
false
false
935
java
package com.tariqaliiman.tariqaliiman.classes; public class Athkar_S_M { public int id; public String content; public String reference; public int number; public Athkar_S_M(int id, String content, String reference, int number) { this.id = id; this.content = content; this.reference = reference; this.number = number; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } }
[ "baheralsaqa@gmail.com" ]
baheralsaqa@gmail.com
44e7eb91f83188614fe31a59e4e78a772afc5976
5c92beefaf050ff7ad4d8210eb169ee3d8504fe9
/HAAProject_Webwork_JSF_Plugin_20100423/plugin-src/haaproject/webwork/jsf/ProcessValidationsInterceptor.java
77797890c5c62ef7a6fe9618f97915f056e9c91b
[]
no_license
kutariyar/haaprojects
89a225b8b97c4501167971dcaa00c74c8c7fb9a8
f35de8af8a6b63a9bffc80c8b4b21a43cc6d59ac
refs/heads/master
2021-01-20T23:24:01.125777
2013-12-26T06:47:52
2013-12-26T06:47:52
34,249,551
0
2
null
null
null
null
UTF-8
Java
false
false
2,853
java
/* * $Id: ProcessValidationsInterceptor.java 651946 2008-04-27 13:41:38Z apetrelli $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package haaproject.webwork.jsf; import javax.faces.FacesException; import javax.faces.context.FacesContext; import javax.faces.event.PhaseId; /** * Processes validations on the component tree */ public class ProcessValidationsInterceptor extends FacesInterceptor { private static final long serialVersionUID = 8785236570688278147L; /** * Process Validations (JSF.2.2.3) * * @param viewId * The view id * @param facesContext * The faces context * @return true, if response is complete */ protected boolean executePhase(String viewId, FacesContext facesContext) throws FacesException { boolean skipFurtherProcessing = false; if (log.isTraceEnabled()) log.trace("entering processValidations"); informPhaseListenersBefore(facesContext, PhaseId.PROCESS_VALIDATIONS); try { if (isResponseComplete(facesContext, "processValidations", true)) { // have to return right away return true; } if (shouldRenderResponse(facesContext, "processValidations", true)) { skipFurtherProcessing = true; } facesContext.getViewRoot().processValidators(facesContext); } finally { informPhaseListenersAfter(facesContext, PhaseId.PROCESS_VALIDATIONS); } if (isResponseComplete(facesContext, "processValidations", false) || shouldRenderResponse(facesContext, "processValidations", false)) { // since this phase is completed we don't need to return right away // even if the response is completed skipFurtherProcessing = true; } if (!skipFurtherProcessing && log.isTraceEnabled()) log.trace("exiting processValidations"); return skipFurtherProcessing; } }
[ "gelnyang@d0820c7c-ebc6-11de-9b30-9f9d59cce923" ]
gelnyang@d0820c7c-ebc6-11de-9b30-9f9d59cce923
c43b458a34a9d8f02269326e2b364c35db9839b2
aa30dd6c464f959871589400fbe38c4d9ddd5037
/src/com/company/Reminder.java
1cd4d80ceae768fe64bcd40044a583b1c41209e4
[]
no_license
Mr0Bread/NotePad
eccad8437e78b69851e4d8c48964a669d6afa9c7
7fbcc532226a3cdf19b2627f5883a510fac93160
refs/heads/master
2020-08-18T19:05:21.478308
2019-10-29T18:39:54
2019-10-29T18:39:54
215,823,919
0
0
null
null
null
null
UTF-8
Java
false
false
1,169
java
package com.company; import java.time.LocalDate; import java.time.LocalDateTime; public class Reminder extends Alarm implements Expirable { private LocalDate date; private boolean dismissedBool; public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } @Override public String toString() { return "Reminder{" + "id=" + getId() + '\'' + "note=" + getNote() + '\'' + "time=" + getTime() + '\'' + "date=" + date.format(Asker.DATE_FORMATTER) + '\'' + "dismissed = " + dismissedBool + '}'; } @Override public void askInfo() { super.askInfo(); date = Asker.askDate("Enter date(yyyy:MM:dd): "); } @Override public boolean contains(String str) { return super.contains(str) || date.format(Asker.DATE_FORMATTER).contains("str"); } @Override public boolean isExpired() { LocalDateTime dateTime = LocalDateTime.of(date, getTime()); return LocalDateTime.now().isAfter(dateTime); } @Override public void dismiss() { dismissedBool = true; } }
[ "zimnikovvladislav@gmail.com" ]
zimnikovvladislav@gmail.com
660a04aee0b15e9bc0e32f5bc14afd5748a5dc7d
64487c6237d2558ea5910b4132def37627d4557e
/acmesky_source_code/server_python_jolie_e_client_java/soseng-project-geographical-distances-provider/java_client/src/main/java/geoprovider/JSON.java
dda4d993f70de1990e8bec9095da44140247521b
[]
no_license
MickPerl/Service-Oriented-Architecture-Project
35d0878b0d51f026a5ed6dec6f66afdc2509a7c3
f8cdad7766d3453d2ce13350ca1af3cea0724653
refs/heads/main
2023-08-11T09:46:52.364728
2021-10-08T22:54:28
2021-10-08T22:54:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,602
java
/* * fornitoreDistanzeAPI * รˆ l'API RESTful offerta dal *Fornitore delle distanze geografiche* che, come suggerisce il nome, vi racchiude la capability di calcolare la distanza tra due posizioni geografiche. * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package geoprovider; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.gsonfire.GsonFireBuilder; import io.gsonfire.PostProcessor; import io.gsonfire.TypeSelector; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.format.DateTimeFormatter; import io.swagger.client.model.*; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; import java.util.Map; import java.util.HashMap; public class JSON { private Gson gson; private boolean isLenientOnJson = false; private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() ; return fireBuilder.createGsonBuilder(); } private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { JsonElement element = readElement.getAsJsonObject().get(discriminatorField); if(null == element) { throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); } return element.getAsString(); } private static <T> Class<? extends T> getClassByDiscriminator(Map<String, Class<? extends T>> classByDiscriminatorValue, String discriminatorValue) { Class<? extends T> clazz = classByDiscriminatorValue.get(discriminatorValue.toUpperCase()); if(null == clazz) { throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); } return clazz; } public JSON() { gson = createGson() .registerTypeAdapter(Date.class, dateTypeAdapter) .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) .create(); } /** * Get Gson. * * @return Gson */ public Gson getGson() { return gson; } /** * Set Gson. * * @param gson Gson * @return JSON */ public JSON setGson(Gson gson) { this.gson = gson; return this; } public JSON setLenientOnJson(boolean lenientOnJson) { isLenientOnJson = lenientOnJson; return this; } /** * Serialize the given Java object into JSON string. * * @param obj Object * @return String representation of the JSON */ public String serialize(Object obj) { return gson.toJson(obj); } /** * Deserialize the given JSON string to Java object. * * @param <T> Type * @param body The JSON string * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) { try { if (isLenientOnJson) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; if (returnType.equals(String.class)) return (T) body; else throw (e); } } /** * Gson TypeAdapter for JSR310 OffsetDateTime type */ public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> { private DateTimeFormatter formatter; public OffsetDateTimeTypeAdapter() { this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, OffsetDateTime date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public OffsetDateTime read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); if (date.endsWith("+0000")) { date = date.substring(0, date.length()-5) + "Z"; } return OffsetDateTime.parse(date, formatter); } } } /** * Gson TypeAdapter for JSR310 LocalDate type */ public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> { private DateTimeFormatter formatter; public LocalDateTypeAdapter() { this(DateTimeFormatter.ISO_LOCAL_DATE); } public LocalDateTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, LocalDate date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public LocalDate read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return LocalDate.parse(date, formatter); } } } public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { offsetDateTimeTypeAdapter.setFormat(dateFormat); return this; } public JSON setLocalDateFormat(DateTimeFormatter dateFormat) { localDateTypeAdapter.setFormat(dateFormat); return this; } /** * Gson TypeAdapter for java.sql.Date type * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used * (more efficient than SimpleDateFormat). */ public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> { private DateFormat dateFormat; public SqlDateTypeAdapter() { } public SqlDateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, java.sql.Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = date.toString(); } out.value(value); } } @Override public java.sql.Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } } } /** * Gson TypeAdapter for java.util.Date type * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter<Date> { private DateFormat dateFormat; public DateTypeAdapter() { } public DateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = ISO8601Utils.format(date, true); } out.value(value); } } @Override public Date read(JsonReader in) throws IOException { try { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return dateFormat.parse(date); } return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } } } catch (IllegalArgumentException e) { throw new JsonParseException(e); } } } public JSON setDateFormat(DateFormat dateFormat) { dateTypeAdapter.setFormat(dateFormat); return this; } public JSON setSqlDateFormat(DateFormat dateFormat) { sqlDateTypeAdapter.setFormat(dateFormat); return this; } }
[ "micheleperlino@gmail.com" ]
micheleperlino@gmail.com
7bac188f05d0b4c355dc0469b49bfc8d7eb29c83
68f7a6e9fd7f496d9cb77cf67f138fbd7308c204
/cyrus-demo-web/src/main/java/com/cyrus/demo/ui/resolver/CustomerDate.java
6f75d4ecabddef58dbda58469330120d24e92c6a
[]
no_license
Vincent0802/spring-demo
00f902d433b4e0a9f5db0f010e3ddda419a04276
aa5c1ca4aa518363897cf41c191fe5519249c6f5
refs/heads/master
2021-01-11T03:01:42.522460
2016-11-02T05:05:38
2016-11-02T05:05:38
70,866,529
0
0
null
null
null
null
UTF-8
Java
false
false
387
java
package com.cyrus.demo.ui.resolver; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CustomerDate { String value(); }
[ "Vincentwu0802@163.com" ]
Vincentwu0802@163.com
2c96261e56e606e9bad748c51282609951ed971b
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_b341b44cc2fb6c0a25b25bf36f3ec40a90c41b25/UserAuthenticationData/17_b341b44cc2fb6c0a25b25bf36f3ec40a90c41b25_UserAuthenticationData_s.java
6b232ca94cd920590fd2f2d49b623053429724d5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
4,012
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2; import java.util.Map; import java.util.TreeMap; import java.util.Iterator; /** * Container for various authentication data. * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a> */ public class UserAuthenticationData { /** * Inner class to represent portions of the user authentication data. */ public static class Type implements Comparable<Type> { /** The type name */ private final String type; public Type(String type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Type type1 = (Type) o; if (type != null ? !type.equals(type1.type) : type1.type != null) { return false; } return true; } public int compareTo(Type o) { return type.compareTo(o.type); } /** @since 2.0 */ @Override public int hashCode() { return type != null ? type.hashCode() : 0; } /** @since 2.0 */ @Override public String toString() { return type; } } /** The user name. */ public static final Type USERNAME = new Type("username"); /** The password. */ public static final Type PASSWORD = new Type("password"); /** The user's domain. */ public static final Type DOMAIN = new Type("domain"); /** The authentication data. */ private final Map<Type, char[]> authenticationData = new TreeMap<Type, char[]>(); public UserAuthenticationData() { } /** * set a data to this collection. * @param type The Type to add * @param data The data associated with the Type */ public void setData(Type type, char[] data) { authenticationData.put(type, data); } /** * get a data from the collection. * @param type The Type to retrieve. * @return a character array containing the data associated with the type. */ public char[] getData(Type type) { return authenticationData.get(type); } /** * deleted all data stored within this authenticator. */ public void cleanup() { // step 1: nullify character buffers Iterator<char[]> iterAuthenticationData = authenticationData.values().iterator(); while (iterAuthenticationData.hasNext()) { char[] data = iterAuthenticationData.next(); if (data == null || data.length < 0) { continue; } for (int i = 0; i < data.length; i++) { data[i] = 0; } } // step 2: allow data itself to gc authenticationData.clear(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
726c587f8651a8af563cba2c64874cdfa0d37c96
5993cc2a2ade05a2aff5c6c6606f33b8f60f5a83
/app/src/main/java/com/dazzlerr_usa/utilities/retrofit/APIHelper.java
793dc871dc607ecb8e238fe081e836f97764de24
[]
no_license
ingeniouscoder45/Dazzlerr_US
cc2280e3c7d66a90a2d5e66123eec23b001707e4
79feee09f8cc741aea89912b7f46ced6442bcc65
refs/heads/master
2023-03-17T15:29:33.017639
2021-03-13T08:06:44
2021-03-13T08:06:44
344,480,260
1
0
null
null
null
null
UTF-8
Java
false
false
1,059
java
package com.dazzlerr_usa.utilities.retrofit; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Arvind on 25/10/19. */ public class APIHelper { public static final int DEFAULT_RETRIES = 3; public static <T> void enqueueWithRetry(Call<T> call, final int retryCount,final Callback<T> callback) { call.enqueue(new RetryableCallback<T>(call, retryCount) { @Override public void onFinalResponse(Call<T> call, Response<T> response) { callback.onResponse(call, response); } @Override public void onFinalFailure(Call<T> call, Throwable t) { callback.onFailure(call, t); } }); } public static <T> void enqueueWithRetry(Call<T> call, final Callback<T> callback) { enqueueWithRetry(call, DEFAULT_RETRIES, callback); } public static boolean isCallSuccess(Response response) { int code = response.code(); return (code >= 200 && code < 400); } }
[ "ingeniouscoder45@gmail.com" ]
ingeniouscoder45@gmail.com
440017c751ad1fa8bdba5da99c255072af326ab6
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/orbital/azure-resourcemanager-orbital/src/test/java/com/azure/resourcemanager/orbital/generated/ContactsPropertiesAntennaConfigurationTests.java
f2890ba18bc8622163891412686f93a4332e0fbc
[ "LicenseRef-scancode-generic-cla", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821969
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
2023-09-14T21:37:15
2011-12-06T23:33:56
Java
UTF-8
Java
false
false
1,501
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.orbital.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.orbital.models.ContactsPropertiesAntennaConfiguration; import java.util.Arrays; import org.junit.jupiter.api.Assertions; public final class ContactsPropertiesAntennaConfigurationTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ContactsPropertiesAntennaConfiguration model = BinaryData .fromString("{\"destinationIp\":\"jdkirsoodqx\",\"sourceIps\":[\"mnoh\",\"t\"]}") .toObject(ContactsPropertiesAntennaConfiguration.class); Assertions.assertEquals("jdkirsoodqx", model.destinationIp()); Assertions.assertEquals("mnoh", model.sourceIps().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ContactsPropertiesAntennaConfiguration model = new ContactsPropertiesAntennaConfiguration() .withDestinationIp("jdkirsoodqx") .withSourceIps(Arrays.asList("mnoh", "t")); model = BinaryData.fromObject(model).toObject(ContactsPropertiesAntennaConfiguration.class); Assertions.assertEquals("jdkirsoodqx", model.destinationIp()); Assertions.assertEquals("mnoh", model.sourceIps().get(0)); } }
[ "noreply@github.com" ]
Azure.noreply@github.com
b15d4bd402cb69f265a8bdd60f99e2651317f3d4
ccfc280097f0642f0077456aa62a644601f2a40f
/src/stringpack/Permutations.java
fb2448369d92748856681bf1a55d42e0a5f0bd14
[]
no_license
AndreMin/JString
9dc3885c6da0c99f1c80ebfb150b7f5e1822476c
cb4a0f89cdd00a8ea6c47843228d4053a65ed7b7
refs/heads/master
2022-11-15T14:16:15.942681
2020-07-13T12:13:13
2020-07-13T12:13:13
279,292,825
0
0
null
null
null
null
UTF-8
Java
false
false
780
java
package stringpack; public class Permutations { public static void main(String[] args) { String s1 = "ABC"; genPermut(s1, 0, s1.length()); } static String swap(String s, int i, int j) { char[] chArr = s.toCharArray(); char ch; ch = chArr[i]; chArr[i] = chArr[j]; chArr[j] = ch; return String.valueOf(chArr); } static void genPermut(String s, int start, int end) { if (start == end - 1) { System.out.println(s); } else { for (int i = start; i < end; i++) { s = swap(s, start, i); genPermut(s, (start + 1), end); s = swap(s, start, i); } // System.out.println(s); } } }
[ "minok.mal@gmail.com" ]
minok.mal@gmail.com
d7afca361fee8294ff00a37879b48b4c92226732
98832ba77e42519d45ca001a5f0b1a54ac9cf137
/source/javaserver/desk/src/main/source/cn/fx/desk/dao/ApDao.java
a389d7b794630dd8d5eb99627daab29f2b7fb9f4
[]
no_license
adoggie/swarm
3fc31ff24bfb6714c5da0051a57e073cae97c702
2916fac45ab13c8feee2fd2343c7a73527b86a8b
refs/heads/master
2016-09-15T08:53:57.604836
2016-04-27T02:50:16
2016-04-27T02:50:16
40,309,321
1
1
null
null
null
null
UTF-8
Java
false
false
336
java
package cn.fx.desk.dao; import java.util.List; /** * @author sunxy * @version 2015-7-28 * @des **/ public interface ApDao { public void insert(List list,String collectionName) throws Exception; public void drop(String collectionName) throws Exception; public void find(String collectionName) throws Exception; }
[ "24509826@qq.com" ]
24509826@qq.com
5113820cbf7035b5c3ebbfc740e754fb744e72f5
e3a5606eb811504ea3016f104f93105e5817edc0
/app/src/main/java/com/example/brianbystrom/hw09/FriendsTripActivity.java
5e343d62850a45614e95230bce1ffd5030c7e562
[]
no_license
brianbystrom/hw9
d06031f9f64570a7b8aed9781147728ba63fdf30
a175e3a4f013de8bf8de0c1e52f6653046a22b88
refs/heads/master
2021-01-19T23:02:43.064782
2017-05-02T01:04:34
2017-05-02T01:04:34
88,913,350
0
1
null
2017-04-30T01:25:35
2017-04-20T21:48:01
Java
UTF-8
Java
false
false
7,487
java
package com.example.brianbystrom.hw09; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.w3c.dom.Text; import java.util.ArrayList; public class FriendsTripActivity extends AppCompatActivity { private ArrayList<User> mDataset = new ArrayList<User>(); private FirebaseDatabase database; private DatabaseReference myRef, myRef2; private FirebaseUser user; private User currentUser = new User(); private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private String uID; private ArrayList<User> userList = new ArrayList<User>(); private ArrayList<String> fID = new ArrayList<String>(); private ArrayList<Trip> tripList = new ArrayList<Trip>(); private RecyclerView friendsTripsRV; private String uid; private TextView itemsTV; private ProgressBar PB; //final ValueEventListener listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends_trip); friendsTripsRV = (RecyclerView) findViewById(R.id.friendsTripsRV); itemsTV = (TextView) findViewById(R.id.itemsTV); PB = (ProgressBar) findViewById(R.id.progressBar); database = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in uid = user.getUid(); //Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); //welcomeTV.setText("Welcome back " + user.getDisplayName()); myRef = database.getReference("users").child(user.getUid()); myRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (com.google.firebase.database.DataSnapshot s: snapshot.getChildren()) { // Log.d("demo", snapshot.getValue(User.class).toString()); //Log.d(TAG, snapshot.getValue(User.class).getfName()); currentUser.setfName(snapshot.getValue(User.class).getfName().toString()); currentUser.setlName(snapshot.getValue(User.class).getlName().toString()); currentUser.setGender(snapshot.getValue(User.class).getGender().toString()); currentUser.setProfileURL(snapshot.getValue(User.class).getProfileURL().toString()); currentUser.setFriendsUID((ArrayList<String>) snapshot.getValue(User.class).getFriendsUID()); currentUser.setTripsID((ArrayList<String>) snapshot.getValue(User.class).getTripsID()); //welcomeTV.setText("Welcome back " + currentUser.getfName() + " " + currentUser.getlName()); myRef2 = database.getReference("trips"); myRef2.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //for (com.google.firebase.database.DataSnapshot s: snapshot.getChildren()) { tripList.clear(); Iterable<DataSnapshot> children = dataSnapshot.getChildren(); for(DataSnapshot child: children) { Trip trip = child.getValue(Trip.class); //Log.d("COMPARE", user.getUid() + " | " + request.getuID()); if(currentUser.getFriendsUID().contains(trip.getuID()) && !currentUser.getTripsID().contains(trip.gettID())) { tripList.add(trip); Log.d("ADDED", "ADDED" + trip.getTitle()); updateCount(tripList.size()); } } updateCount(tripList.size()); Log.d("USER IDIDID", uid + ""); LinearLayoutManager mLayoutManager = new LinearLayoutManager(FriendsTripActivity.this, LinearLayoutManager.VERTICAL, false); FriendsTripAdapter mAdapter = new FriendsTripAdapter(tripList, FriendsTripActivity.this, uid); //mAdapter.notifyDataSetChanged(); friendsTripsRV.setAdapter(mAdapter); friendsTripsRV.setLayoutManager(mLayoutManager); friendsTripsRV.setHasFixedSize(true); showItems(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } else { // User is signed out //Log.d(TAG, "onAuthStateChanged:signed_out"); } // ... } }; } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } public void end(){ finish(); } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } } public void updateCount(int count) { if(count == 0) { itemsTV.setText("There are no trips of your friends that you are not added on."); } else { itemsTV.setText("Found " + count + " trips."); } } public void showItems() { PB.setVisibility(View.GONE); itemsTV.setVisibility(View.VISIBLE); friendsTripsRV.setVisibility(View.VISIBLE); } }
[ "brianbystrom@gmail.com" ]
brianbystrom@gmail.com
0774ff6fcbdbed2ed3e1bf5b768b0458cee69040
a83a65908740d7859531bede276e9f71365720e0
/src/Fakulte.java
ab752e8ec1b29217636f34e497bf699a80e82d8c
[]
no_license
DokuzEylulCsc/odev-2-eminozkaradeniz1
1d63a39715035c4613dd203b18605d250bafe634
644582a24130ef4ac1e6bf671f9e4abb5cfb3110
refs/heads/master
2020-05-17T13:20:24.960964
2019-05-05T11:36:48
2019-05-05T11:36:48
183,733,696
0
0
null
null
null
null
UTF-8
Java
false
false
1,071
java
import java.util.ArrayList; import java.util.List; public class Fakulte { private String adi; private List<Bolum> bolumList; public Fakulte(String adi) { this.adi = adi; this.bolumList = new ArrayList<>(); } public String getAdi() { return adi; } public Bolum getIndexOf(int a){ return bolumList.get(a); } public List<Bolum> getBolumList() { return bolumList; } public boolean BolumEkle(String bolumAdi){ if(BolumAra(bolumAdi) == -1){ bolumList.add(new Bolum(bolumAdi)); return true; } return false; } private int BolumAra(String bolumAdi){ for (Bolum b: bolumList) { if(b.getAdi().equals(bolumAdi)){ return bolumList.indexOf(b); } } return -1; } public void BolumleriListele(){ System.out.println("Fakรผlteye ait bรถlรผmler: "); for (int i = 0; i < bolumList.size(); i++){ System.out.printf("%2d. %s \n", i+1, bolumList.get(i).getAdi()); } } }
[ "emin.ozkaradeniz@ogr.deu.edu.tr" ]
emin.ozkaradeniz@ogr.deu.edu.tr
246428f39ce1c09d28a740dc1056e30763dae423
e214497e00c4c22913d072db3e0aeea804b2906e
/src/main/java/com/rasturize/anticheat/checks/autoclicker/AutoClickerG.java
c6b334b4bc20ace38dfe1e73c44c3b6b10f36911
[]
no_license
Grac3T/Apex-Source-Code
10a6e74db1497c418c964f40c8fecd16c2675c88
bc9ef6dbc26f4327abf61618fce797bc8ebc5a4d
refs/heads/master
2023-08-23T02:01:59.500750
2021-10-09T00:27:38
2021-10-09T00:27:38
415,160,966
0
0
null
null
null
null
UTF-8
Java
false
false
1,610
java
package com.rasturize.anticheat.checks.autoclicker; import com.rasturize.anticheat.api.check.Check; import com.rasturize.anticheat.api.check.type.CheckType; import com.rasturize.anticheat.protocol.packet.in.WrappedInArmAnimationPacket; import java.util.Deque; import java.util.LinkedList; @CheckType(id = "autoclicker:g", name = "AutoClicker G", type = CheckType.Type.AUTOCLICKER, maxVl = 3) public class AutoClickerG extends Check { private long lastSwing; private double lastAverage; private final Deque<Long> swingSamples = new LinkedList<>(); void check(WrappedInArmAnimationPacket wrappedInArmAnimationPacket) { if (!canCheck() || playerData.state.isDigging) return; long now = System.currentTimeMillis(), delay = now - lastSwing; swingSamples.add(delay); if (swingSamples.size() == 20) { double average = swingSamples.stream() .mapToLong(l -> l) .average() .orElse(0.0); double totalSwings = swingSamples.stream().mapToLong(change -> change).asDoubleStream().sum(), mean = totalSwings / swingSamples.size(), deviation = swingSamples.stream().mapToLong(change -> change).mapToDouble(change -> Math.pow(change - mean, 2)).sum(); if (Math.sqrt(deviation) < 150.0 && average > 100.0 && Math.abs(average - this.lastAverage) <= 5.0) { fail(); } lastAverage = average; swingSamples.clear(); } lastSwing = now; } }
[ "gracetech@protonmail.com" ]
gracetech@protonmail.com
d4e52aa17197cf9bd10e8630316e2e6b2743db70
68d6f93ece5bdcab83d8f583743f9255b2fe91ac
/part1/SimpleList.java
3d33d722fbd5555236ef0dad361ca3f4769dbf55
[]
no_license
CalPolyCPE203F19/lab-1-maiqiansun
fc20c1c3e5fec00cb7c3de45d783c6df07cb23d8
35dcddc72b599a422334dd50144d3fa937053066
refs/heads/master
2020-07-31T02:35:46.515433
2019-09-28T06:36:52
2019-09-28T06:36:52
210,453,840
0
0
null
null
null
null
UTF-8
Java
false
false
641
java
import java.util.List; import java.util.LinkedList; class SimpleList { public static List<Integer> squareAll(List<Integer> values) { List<Integer> newValues = new LinkedList<Integer>(); /* TO DO: The output list, newValues, should hold as its elements the square of the corresponding element in the input list. Write a loop to add the square of each element from the input list into the output list. Use a "foreach". */ // newValues.add(element) for(int i : values) { i = i * i; newValues.add(i); } return newValues; } }
[ "noreply@github.com" ]
CalPolyCPE203F19.noreply@github.com
69f858fa697592e85bc44fde46415d7636aa81b4
ea8013860ed0b905c64f449c8bce9e0c34a23f7b
/SystemUIGoogle/sources/com/android/systemui/qs/QSFooter.java
c6cb1a4f0fc1a822e4d924a5582d57241ea3ddba
[]
no_license
TheScarastic/redfin_b5
5efe0dc0d40b09a1a102dfb98bcde09bac4956db
6d85efe92477576c4901cce62e1202e31c30cbd2
refs/heads/master
2023-08-13T22:05:30.321241
2021-09-28T12:33:20
2021-09-28T12:33:20
411,210,644
1
0
null
null
null
null
UTF-8
Java
false
false
427
java
package com.android.systemui.qs; import android.view.View; /* loaded from: classes.dex */ public interface QSFooter { default void disable(int i, int i2, boolean z) { } void setExpandClickListener(View.OnClickListener onClickListener); void setExpanded(boolean z); void setExpansion(float f); void setKeyguardShowing(boolean z); void setListening(boolean z); void setVisibility(int i); }
[ "warabhishek@gmail.com" ]
warabhishek@gmail.com
8744cb1804884243cc4489bb2da4df7c6233ea91
cb4049691a7d428fc0b76957609dfd1ef3e96f14
/app/src/main/java/com/example/carassistant/adapter/VehicleSaleAdapter.java
1088e29eeea653a3816cdf239b1c30351f6e9e88
[]
no_license
zhujiammy/CarAssistant
6646dc1e0fa37cd0eac856e58d579f3e11e28d99
c5dbe73d6c9b2264bd4f3087261fb6c79ae5bd84
refs/heads/master
2020-12-05T06:00:01.280234
2020-04-18T01:41:51
2020-04-18T01:41:51
232,028,362
1
0
null
null
null
null
UTF-8
Java
false
false
6,711
java
package com.example.carassistant.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.carassistant.R; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; public class VehicleSaleAdapter extends RecyclerView.Adapter implements View.OnClickListener { public static final int VIEW_TYPE_ITEM = 1; public static final int VIEW_TYPE_EMPTY = 0; private Context context; private JsonArray model; public VehicleSaleAdapter(Context context,JsonArray model){ this.context = context; this.model = model; } private OnitemClickListener onitemClickListener=null; @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { //ๅœจonCreateViewHolderๆ–นๆณ•ไธญ๏ผŒๆˆ‘ไปฌ่ฆๆ นๆฎไธๅŒ็š„ViewTypeๆฅ่ฟ”ๅ›žไธๅŒ็š„ViewHolder if (viewType == VIEW_TYPE_EMPTY) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.empty_view_tab, viewGroup, false); return new RecyclerView.ViewHolder(view) { }; } View baseView; baseView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.vehiclesnumber_data, viewGroup, false); BodyViewHolder bodyViewHolder = new BodyViewHolder(baseView); baseView.setOnClickListener(this); return bodyViewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { if(viewHolder instanceof BodyViewHolder){ JsonObject object =model.get(i).getAsJsonObject(); if(!object.get("plateNumberNo").isJsonNull()){ ((BodyViewHolder) viewHolder).plateNumberNo.setText(object.get("plateNumberNo").getAsString()); }else { ((BodyViewHolder) viewHolder).plateNumberNo.setText("ๆ— "); } if(!object.get("plateNumberColour").isJsonNull()){ if(object.get("plateNumberColour").getAsString().equals("่“่‰ฒ")){ ((BodyViewHolder) viewHolder).plateNumberNo.setBackgroundColor(context.getResources().getColor(R.color.blue)); ((BodyViewHolder) viewHolder).plateNumberNo.setTextColor(context.getResources().getColor(R.color.white)); } if(object.get("plateNumberColour").getAsString().equals("็™ฝ่‰ฒ")){ ((BodyViewHolder) viewHolder).plateNumberNo.setBackgroundColor(context.getResources().getColor(R.color.selector_grey)); ((BodyViewHolder) viewHolder).plateNumberNo.setTextColor(context.getResources().getColor(R.color.black)); } if(object.get("plateNumberColour").getAsString().equals("็ปฟ่‰ฒ")){ ((BodyViewHolder) viewHolder).plateNumberNo.setBackgroundColor(context.getResources().getColor(R.color.colorBlue)); ((BodyViewHolder) viewHolder).plateNumberNo.setTextColor(context.getResources().getColor(R.color.white)); } if(object.get("plateNumberColour").getAsString().equals("้ป„่‰ฒ")){ ((BodyViewHolder) viewHolder).plateNumberNo.setBackgroundColor(context.getResources().getColor(R.color.bg)); ((BodyViewHolder) viewHolder).plateNumberNo.setTextColor(context.getResources().getColor(R.color.white)); } if(object.get("plateNumberColour").getAsString().equals("้ป‘่‰ฒ")){ ((BodyViewHolder) viewHolder).plateNumberNo.setBackgroundColor(context.getResources().getColor(R.color.black)); ((BodyViewHolder) viewHolder).plateNumberNo.setTextColor(context.getResources().getColor(R.color.white)); } } if(!object.get("carType").isJsonNull()){ ((BodyViewHolder) viewHolder).carInfo.setText(object.get("carType").getAsString()); }else { ((BodyViewHolder) viewHolder).carInfo.setText("ๆ— "); } if(!object.get("enterTime").isJsonNull()){ ((BodyViewHolder) viewHolder).erterTime.setText(object.get("enterTime").getAsString()); } else { ((BodyViewHolder) viewHolder).erterTime.setText("ๆ— "); } if(!object.get("carCode").isJsonNull()){ ((BodyViewHolder) viewHolder).carCode.setText(object.get("carCode").getAsString()); } else { ((BodyViewHolder) viewHolder).carCode.setText("ๆ— "); } } viewHolder.itemView.setTag(i); } @Override public int getItemCount() { if (model.size() == 0) { return 1; } return model.size(); } /** * * ๅค็”จgetItemViewTypeๆ–นๆณ•๏ผŒๆ นๆฎไฝ็ฝฎ่ฟ”ๅ›ž็›ธๅบ”็š„ViewType * @param position * @return */ @Override public int getItemViewType(int position) { //ๅฆ‚ๆžœๆ˜ฏ0๏ผŒๅฐฑๆ˜ฏๅคด๏ผŒๅฆๅˆ™ๅˆ™ๆ˜ฏๅ…ถไป–็š„item if (model.size() == 0) { return VIEW_TYPE_EMPTY; } //ๅฆ‚ๆžœๆœ‰ๆ•ฐๆฎ๏ผŒๅˆ™ไฝฟ็”จITEM็š„ๅธƒๅฑ€ return VIEW_TYPE_ITEM; } @Override public void onClick(View view) { if(onitemClickListener!=null){ onitemClickListener.onItemClick(view,(int)view.getTag()); } } public void setOnitemClickListener(OnitemClickListener onitemClickListener) { this.onitemClickListener = onitemClickListener; } public static interface OnitemClickListener{ void onItemClick(View view, int position); } /** * ็ป™GridViewไธญ็š„ๆก็›ฎ็”จ็š„ViewHolder๏ผŒ้‡Œ้ขๅชๆœ‰ไธ€ไธชTextView */ public class BodyViewHolder extends RecyclerView.ViewHolder { private TextView plateNumberNo; private TextView carInfo; private TextView carCode; private TextView erterTime; public BodyViewHolder(View itemView) { super(itemView); plateNumberNo = (TextView) itemView.findViewById(R.id.plateNumberNo); carInfo = (TextView) itemView.findViewById(R.id.carInfo); carCode = (TextView) itemView.findViewById(R.id.carCode); erterTime = (TextView) itemView.findViewById(R.id.erterTime); } } }
[ "945529210@qq.com" ]
945529210@qq.com
a902b906189a4bc36ca60f226334c2ddc9f94203
28ca6feae0f2dbb97120c8484543e36bf8b65606
/TicketingSystem/src/main/java/database/DatabaseConnection.java
a138eef96c836f8d7e0e740c66e2a38bb38e4e58
[]
no_license
anton-gabriel/tehnologii-web
f74749770239a0a15f672e8007e0244c7cadc1f3
bef926e56330ab4598b3c85ef4187288ee0addda
refs/heads/master
2022-09-12T13:35:28.263817
2020-01-17T17:15:30
2020-01-17T17:15:30
219,352,450
0
1
null
2022-09-08T01:04:38
2019-11-03T19:16:53
HTML
UTF-8
Java
false
false
1,336
java
package database; import java.sql.*; /** * The type Database connection. */ public class DatabaseConnection { private static DatabaseConnection instance; private Connection connection; private String url = "jdbc:postgresql://localhost:5432/ticketing"; private String username = "postgres"; private String password = "123456"; private DatabaseConnection() throws SQLException { try { Class.forName("org.postgresql.Driver"); this.connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException ex) { System.out.println("Database Connection Creation Failed : " + ex.getMessage()); } } /** * Gets connection. * * @return the connection */ public Connection getConnection() { return connection; } /** * Gets instance. * * @return the instance * @throws SQLException the sql exception */ public static DatabaseConnection getInstance() throws SQLException { if (instance == null) { instance = new DatabaseConnection(); } else if (instance.getConnection().isClosed()) { instance = new DatabaseConnection(); } return instance; } }
[ "anton.gabi1998@gmail.com" ]
anton.gabi1998@gmail.com
43a7800b7aa8be5d66db1e5d2f835b0e91137f98
e5cc6ebe29916322155cb93016184e0f14eb5608
/src/main/java/session1/Exercice1.java
cb26f1a50c6c257017c4dbdd5b8bf327a248da9f
[]
no_license
Nassila/master-class-java
da66ae4574e6de4d42603e44c491f3d2c1e98585
bac20d65e41a29463dd267f0255ff248471155e2
refs/heads/master
2023-03-28T20:34:45.970424
2021-04-09T08:14:41
2021-04-09T08:14:41
356,189,273
0
0
null
null
null
null
UTF-8
Java
false
false
2,270
java
package session1; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Exercice1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // 1- saisi de la chaine System.out.println("Entre ta chaine"); String chaine = scan.nextLine(); // 2- Affichage System.out.println("La chaine : " + chaine); // 3- Affichage de la taille System.out.println("Sa taille : " + chaine.length()); //4- Afficher en minuscule System.out.println("Minuscule : " + chaine.toLowerCase()); //5- Afficher en majuscule System.out.println("Majuscule : " + chaine.toUpperCase()); //6- ordonner la chaine char temp = ' '; char[] chars = new char[chaine.length()]; for (int i = 0; i < chaine.length(); i++) { chars[i] = chaine.charAt(i); } for (int index = 0; index < chars.length - 1; index++) { if (chars[index] > chars[index + 1]) { temp = chars[index]; chars[index] = chars[index + 1]; chars[index + 1] = temp; index = -1; } } String chaineSorted = ""; for (int index = 0; index < chars.length; index++) { chaineSorted = chaineSorted + chars[index]; } System.out.println("Triรฉe : " + chaineSorted); //autre faรงon pour faire le tri /* char[] chars = chaine.toCharArray(); Arrays.sort(chars); String sortedChaine = String.valueOf(chars); System.out.println("Triรฉe : " + sortedChaine); */ //7- Inverse String chaineReversed = ""; for (int i = chaine.length() - 1 ; i >= 0; i--) { chaineReversed = chaineReversed + chaine.charAt(i); } System.out.println("Inverse : " + chaineReversed); //autre faรงon pour faire le reverse /* String chaineReversed = new StringBuilder(chaine).reverse().toString(); System.out.println("Inverse : " + chaineReversed); */ //8- palaindrome if(chaine.equals(chaineReversed)) { System.out.println(true); } } }
[ "nassila.hamouche@joza-it.fr" ]
nassila.hamouche@joza-it.fr
3053ed4afe583ce6c1b598e849e0844b18711d99
aaabffe8bf55973bfb1390cf7635fd00ca8ca945
/src/main/java/com/microsoft/graph/requests/extensions/ReferenceAttachmentRequest.java
6b94601597c73f9735387164ae0b858bd3e5049f
[ "MIT" ]
permissive
rgrebski/msgraph-sdk-java
e595e17db01c44b9c39d74d26cd925b0b0dfe863
759d5a81eb5eeda12d3ed1223deeafd108d7b818
refs/heads/master
2020-03-20T19:41:06.630857
2018-03-16T17:31:43
2018-03-16T17:31:43
137,648,798
0
0
null
2018-06-17T11:07:06
2018-06-17T11:07:05
null
UTF-8
Java
false
false
1,522
java
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.models.extensions.*; import com.microsoft.graph.models.generated.*; import com.microsoft.graph.http.*; import com.microsoft.graph.requests.extensions.*; import com.microsoft.graph.requests.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; // This file is available for extending, afterwards please submit a pull request. /** * The class for the Reference Attachment Request. */ public class ReferenceAttachmentRequest extends BaseReferenceAttachmentRequest implements IReferenceAttachmentRequest { /** * The request for the ReferenceAttachment * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public ReferenceAttachmentRequest(final String requestUrl, final IBaseClient client, final java.util.List<? extends Option> requestOptions) { super(requestUrl, client, requestOptions, ReferenceAttachment.class); } }
[ "caitbal@microsoft.com" ]
caitbal@microsoft.com
178ac5be72ecf919341f0df77f949a24b5c77d1b
45ccac7632f8f0cccd1d3db2e1e905fade21fa06
/clientUI/src/main/java/com/supermarket/clientUI/models/Microservice.java
2b419bb5a27b18ae9e4ab246e27d0537663867b5
[]
no_license
djamal-soft/supermarket
a341ceb256253cc5d015b9b830b035073773c0b6
668ae2ddd94fcf175379c8d0c4c8a7522e1d818a
refs/heads/master
2022-12-06T17:12:51.442737
2020-08-29T10:53:02
2020-08-29T10:53:02
263,386,704
0
0
null
null
null
null
UTF-8
Java
false
false
1,436
java
package com.supermarket.clientUI.models; public class Microservice { private int id; private String name; private String mkeys; private String address; private float version; private String status; public Microservice() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMkeys() { return mkeys; } public void setMkeys(String mkeys) { this.mkeys = mkeys; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public float getVersion() { return version; } public void setVersion(float version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "Microservice{" + "id=" + id + ", name='" + name + '\'' + ", mkeys='" + mkeys + '\'' + ", address='" + address + '\'' + ", version=" + version + ", status='" + status + '\'' + '}'; } }
[ "bekhiekh.djamal@univ-constantine2.dz" ]
bekhiekh.djamal@univ-constantine2.dz
6deb4607785a2080193360add792717199107ec6
704507754a9e7f300dfab163e97cd976b677661b
/src/java/util/zip/Deflater.java
c030a821b7315d4522de3554fa3498a95a0e3de4
[]
no_license
ossaw/jdk
60e7ca5e9f64541d07933af25c332e806e914d2a
b9d61d6ade341b4340afb535b499c09a8be0cfc8
refs/heads/master
2020-03-27T02:23:14.010857
2019-08-07T06:32:34
2019-08-07T06:32:34
145,785,700
0
0
null
null
null
null
UTF-8
Java
false
false
18,980
java
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.util.zip; /** * This class provides support for general purpose compression using the popular * ZLIB compression library. The ZLIB compression library was initially * developed as part of the PNG graphics standard and is not protected by * patents. It is fully described in the specifications at the * <a href="package-summary.html#package_description">java.util.zip package * description</a>. * <p> * The following code fragment demonstrates a trivial compression and * decompression of a string using <tt>Deflater</tt> and <tt>Inflater</tt>. * <blockquote> * * <pre> * try { * // Encode a String into bytes * String inputString = "blahblahblah"; * byte[] input = inputString.getBytes("UTF-8"); * * // Compress the bytes * byte[] output = new byte[100]; * Deflater compresser = new Deflater(); * compresser.setInput(input); * compresser.finish(); * int compressedDataLength = compresser.deflate(output); * compresser.end(); * * // Decompress the bytes * Inflater decompresser = new Inflater(); * decompresser.setInput(output, 0, compressedDataLength); * byte[] result = new byte[100]; * int resultLength = decompresser.inflate(result); * decompresser.end(); * * // Decode the bytes into a String * String outputString = new String(result, 0, resultLength, "UTF-8"); * } catch (java.io.UnsupportedEncodingException ex) { * // handle * } catch (java.util.zip.DataFormatException ex) { * // handle * } * </pre> * * </blockquote> * * @see Inflater * @author David Connelly */ public class Deflater { private final ZStreamRef zsRef; private byte[] buf = new byte[0]; private int off, len; private int level, strategy; private boolean setParams; private boolean finish, finished; private long bytesRead; private long bytesWritten; /** * Compression method for the deflate algorithm (the only one currently * supported). */ public static final int DEFLATED = 8; /** * Compression level for no compression. */ public static final int NO_COMPRESSION = 0; /** * Compression level for fastest compression. */ public static final int BEST_SPEED = 1; /** * Compression level for best compression. */ public static final int BEST_COMPRESSION = 9; /** * Default compression level. */ public static final int DEFAULT_COMPRESSION = -1; /** * Compression strategy best used for data consisting mostly of small values * with a somewhat random distribution. Forces more Huffman coding and less * string matching. */ public static final int FILTERED = 1; /** * Compression strategy for Huffman coding only. */ public static final int HUFFMAN_ONLY = 2; /** * Default compression strategy. */ public static final int DEFAULT_STRATEGY = 0; /** * Compression flush mode used to achieve best compression result. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int NO_FLUSH = 0; /** * Compression flush mode used to flush out all pending output; may degrade * compression for some compression algorithms. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int SYNC_FLUSH = 2; /** * Compression flush mode used to flush out all pending output and reset the * deflater. Using this mode too often can seriously degrade compression. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int FULL_FLUSH = 3; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } /** * Creates a new compressor using the specified compression level. If * 'nowrap' is true then the ZLIB header and checksum fields will not be * used in order to support the compression format used in both GZIP and * PKZIP. * * @param level * the compression level (0-9) * @param nowrap * if true then use GZIP compatible compression */ public Deflater(int level, boolean nowrap) { this.level = level; this.strategy = DEFAULT_STRATEGY; this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap)); } /** * Creates a new compressor using the specified compression level. * Compressed data will be generated in ZLIB format. * * @param level * the compression level (0-9) */ public Deflater(int level) { this(level, false); } /** * Creates a new compressor with the default compression level. Compressed * data will be generated in ZLIB format. */ public Deflater() { this(DEFAULT_COMPRESSION, false); } /** * Sets input data for compression. This should be called whenever * needsInput() returns true indicating that more input data is required. * * @param b * the input data bytes * @param off * the start offset of the data * @param len * the length of the data * @see Deflater#needsInput */ public void setInput(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { this.buf = b; this.off = off; this.len = len; } } /** * Sets input data for compression. This should be called whenever * needsInput() returns true indicating that more input data is required. * * @param b * the input data bytes * @see Deflater#needsInput */ public void setInput(byte[] b) { setInput(b, 0, b.length); } /** * Sets preset dictionary for compression. A preset dictionary is used when * the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * * @param b * the dictionary data bytes * @param off * the start offset of the data * @param len * the length of the data * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); setDictionary(zsRef.address(), b, off, len); } } /** * Sets preset dictionary for compression. A preset dictionary is used when * the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * * @param b * the dictionary data bytes * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b) { setDictionary(b, 0, b.length); } /** * Sets the compression strategy to the specified value. * <p> * If the compression strategy is changed, the next invocation of * {@code deflate} will compress the input available so far with the old * strategy (and may be flushed); the new strategy will take effect only * after that invocation. * * @param strategy * the new compression strategy * @exception IllegalArgumentException * if the compression strategy is * invalid */ public void setStrategy(int strategy) { switch (strategy) { case DEFAULT_STRATEGY: case FILTERED: case HUFFMAN_ONLY: break; default: throw new IllegalArgumentException(); } synchronized (zsRef) { if (this.strategy != strategy) { this.strategy = strategy; setParams = true; } } } /** * Sets the compression level to the specified value. * <p> * If the compression level is changed, the next invocation of * {@code deflate} will compress the input available so far with the old * level (and may be flushed); the new level will take effect only after * that invocation. * * @param level * the new compression level (0-9) * @exception IllegalArgumentException * if the compression level is invalid */ public void setLevel(int level) { if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) { throw new IllegalArgumentException("invalid compression level"); } synchronized (zsRef) { if (this.level != level) { this.level = level; setParams = true; } } } /** * Returns true if the input data buffer is empty and setInput() should be * called in order to provide more input. * * @return true if the input data buffer is empty and setInput() should be * called in order to provide more input */ public boolean needsInput() { synchronized (zsRef) { return len <= 0; } } /** * When called, indicates that compression should end with the current * contents of the input buffer. */ public void finish() { synchronized (zsRef) { finish = true; } } /** * Returns true if the end of the compressed data output stream has been * reached. * * @return true if the end of the compressed data output stream has been * reached */ public boolean finished() { synchronized (zsRef) { return finished; } } /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value * of 0 indicates that {@link #needsInput() needsInput} should be called in * order to determine if more input data is required. * <p> * This method uses {@link #NO_FLUSH} as its compression flush mode. An * invocation of this method of the form * {@code deflater.deflate(b, off, len)} yields the same result as the * invocation of {@code deflater.deflate(b, off, len, Deflater.NO_FLUSH)}. * * @param b * the buffer for the compressed data * @param off * the start offset of the data * @param len * the maximum number of bytes of compressed data * @return the actual number of bytes of compressed data written to the * output buffer */ public int deflate(byte[] b, int off, int len) { return deflate(b, off, len, NO_FLUSH); } /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value * of 0 indicates that {@link #needsInput() needsInput} should be called in * order to determine if more input data is required. * <p> * This method uses {@link #NO_FLUSH} as its compression flush mode. An * invocation of this method of the form {@code deflater.deflate(b)} yields * the same result as the invocation of * {@code deflater.deflate(b, 0, b.length, Deflater.NO_FLUSH)}. * * @param b * the buffer for the compressed data * @return the actual number of bytes of compressed data written to the * output buffer */ public int deflate(byte[] b) { return deflate(b, 0, b.length, NO_FLUSH); } /** * Compresses the input data and fills the specified buffer with compressed * data. Returns actual number of bytes of data compressed. * <p> * Compression flush mode is one of the following three modes: * <ul> * <li>{@link #NO_FLUSH}: allows the deflater to decide how much data to * accumulate, before producing output, in order to achieve the best * compression (should be used in normal use scenario). A return value of 0 * in this flush mode indicates that {@link #needsInput()} should be called * in order to determine if more input data is required. * <li>{@link #SYNC_FLUSH}: all pending output in the deflater is flushed, * to the specified output buffer, so that an inflater that works on * compressed data can get all input data available so far (In particular * the {@link #needsInput()} returns {@code true} after this invocation if * enough output space is provided). Flushing with {@link #SYNC_FLUSH} may * degrade compression for some compression algorithms and so it should be * used only when necessary. * <li>{@link #FULL_FLUSH}: all pending output is flushed out as with * {@link #SYNC_FLUSH}. The compression state is reset so that the inflater * that works on the compressed output data can restart from this point if * previous compressed data has been damaged or if random access is desired. * Using {@link #FULL_FLUSH} too often can seriously degrade compression. * </ul> * <p> * In the case of {@link #FULL_FLUSH} or {@link #SYNC_FLUSH}, if the return * value is {@code len}, the space available in output buffer {@code b}, * this method should be invoked again with the same {@code flush} parameter * and more output space. * * @param b * the buffer for the compressed data * @param off * the start offset of the data * @param len * the maximum number of bytes of compressed data * @param flush * the compression flush mode * @return the actual number of bytes of compressed data written to the * output buffer * @throws IllegalArgumentException * if the flush mode is invalid * @since 1.7 */ public int deflate(byte[] b, int off, int len, int flush) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); if (flush == NO_FLUSH || flush == SYNC_FLUSH || flush == FULL_FLUSH) { int thisLen = this.len; int n = deflateBytes(zsRef.address(), b, off, len, flush); bytesWritten += n; bytesRead += (thisLen - this.len); return n; } throw new IllegalArgumentException(); } } /** * Returns the ADLER-32 value of the uncompressed data. * * @return the ADLER-32 value of the uncompressed data */ public int getAdler() { synchronized (zsRef) { ensureOpen(); return getAdler(zsRef.address()); } } /** * Returns the total number of uncompressed bytes input so far. * <p> * Since the number of bytes may be greater than Integer.MAX_VALUE, the * {@link #getBytesRead()} method is now the preferred means of obtaining * this information. * </p> * * @return the total number of uncompressed bytes input so far */ public int getTotalIn() { return (int) getBytesRead(); } /** * Returns the total number of uncompressed bytes input so far. * * @return the total (non-negative) number of uncompressed bytes input so * far * @since 1.5 */ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); return bytesRead; } } /** * Returns the total number of compressed bytes output so far. * <p> * Since the number of bytes may be greater than Integer.MAX_VALUE, the * {@link #getBytesWritten()} method is now the preferred means of obtaining * this information. * </p> * * @return the total number of compressed bytes output so far */ public int getTotalOut() { return (int) getBytesWritten(); } /** * Returns the total number of compressed bytes output so far. * * @return the total (non-negative) number of compressed bytes output so far * @since 1.5 */ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); return bytesWritten; } } /** * Resets deflater so that a new set of input data can be processed. Keeps * current compression level and strategy settings. */ public void reset() { synchronized (zsRef) { ensureOpen(); reset(zsRef.address()); finish = false; finished = false; off = len = 0; bytesRead = bytesWritten = 0; } } /** * Closes the compressor and discards any unprocessed input. This method * should be called when the compressor is no longer being used, but will * also be called automatically by the finalize() method. Once this method * is called, the behavior of the Deflater object is undefined. */ public void end() { synchronized (zsRef) { long addr = zsRef.address(); zsRef.clear(); if (addr != 0) { end(addr); buf = null; } } } /** * Closes the compressor when garbage is collected. */ protected void finalize() { end(); } private void ensureOpen() { assert Thread.holdsLock(zsRef); if (zsRef.address() == 0) throw new NullPointerException("Deflater has been closed"); } private static native void initIDs(); private native static long init(int level, int strategy, boolean nowrap); private native static void setDictionary(long addr, byte[] b, int off, int len); private native int deflateBytes(long addr, byte[] b, int off, int len, int flush); private native static int getAdler(long addr); private native static void reset(long addr); private native static void end(long addr); }
[ "jianghao7625@gmail.com" ]
jianghao7625@gmail.com
0ae33a889d43b1a4219786d7fd1396593816f1fd
4407cc6dc14cb0f701abf7ce6db8656906376502
/testsuite/src/test/java/org/jboss/galleon/provision/config/layers/test/ExcludeConfigLayerExcludedAsTransitiveDepIgnoreNotExcludedLayersTestCase.java
78d4661bd3efc0a4f1f3c3137f20999196f90beb
[ "Apache-2.0" ]
permissive
wildfly/galleon
8511be420f21fc351d290a1e2a98606c4e2e3094
d273d81cb3a14d5fb5cda001c43366ee5513fabf
refs/heads/main
2023-08-17T16:11:44.646101
2023-07-05T13:10:39
2023-07-05T13:10:39
125,396,942
25
29
Apache-2.0
2023-08-15T17:43:44
2018-03-15T16:36:41
Java
UTF-8
Java
false
false
4,862
java
/* * Copyright 2016-2020 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.jboss.galleon.provision.config.layers.test; import org.jboss.galleon.Constants; import org.jboss.galleon.ProvisioningException; import org.jboss.galleon.ProvisioningOption; import org.jboss.galleon.config.ConfigModel; import org.jboss.galleon.config.FeatureConfig; import org.jboss.galleon.config.FeaturePackConfig; import org.jboss.galleon.config.ProvisioningConfig; import org.jboss.galleon.creator.FeaturePackCreator; import org.jboss.galleon.spec.ConfigLayerSpec; import org.jboss.galleon.spec.FeatureParameterSpec; import org.jboss.galleon.spec.FeatureSpec; import org.jboss.galleon.state.ProvisionedFeaturePack; import org.jboss.galleon.state.ProvisionedState; import org.jboss.galleon.test.util.fs.state.DirState; import org.jboss.galleon.universe.FeaturePackLocation; import org.jboss.galleon.universe.MvnUniverse; import org.jboss.galleon.universe.ProvisionFromUniverseTestBase; import org.jboss.galleon.xml.ProvisionedConfigBuilder; /** * * @author Alexey Loubyansky */ public class ExcludeConfigLayerExcludedAsTransitiveDepIgnoreNotExcludedLayersTestCase extends ProvisionFromUniverseTestBase { private FeaturePackLocation prod1; @Override protected void createProducers(MvnUniverse universe) throws ProvisioningException { universe.createProducer("prod1"); } @Override protected void createFeaturePacks(FeaturePackCreator creator) throws ProvisioningException { prod1 = newFpl("prod1", "1", "1.0.0.Final"); creator.newFeaturePack() .setFPID(prod1.getFPID()) .addFeatureSpec(FeatureSpec.builder("specA") .addParam(FeatureParameterSpec.createId("id")) .addParam(FeatureParameterSpec.create("p1", "spec")) .addParam(FeatureParameterSpec.create("p2", "spec")) .addParam(FeatureParameterSpec.create("p3", "spec")) .build()) .addConfigLayer(ConfigLayerSpec.builder() .setModel("model1").setName("base") .addFeature(new FeatureConfig("specA") .setParam("id", "base-prod1") .setParam("p2", "base")) .addPackageDep("base") .build()) .addConfigLayer(ConfigLayerSpec.builder() .setModel("model1").setName("layer1") .addLayerDep("base", true) .addFeature(new FeatureConfig("specA") .setParam("id", "base-prod2") .setParam("p2", "layer1")) .build()) .addConfig(ConfigModel.builder("model1", "name1") .includeLayer("layer1") .build()) .newPackage("base") .writeContent("base.txt", "base"); } @Override protected ProvisioningConfig provisioningConfig() throws ProvisioningException { return ProvisioningConfig.builder() .addFeaturePackDep(FeaturePackConfig.builder(prod1) .setInheritPackages(false) .setInheritConfigs(false) .includeDefaultConfig("model1", "name1") .build()) .addConfig(ConfigModel.builder("model1", "name1") .excludeLayer("layer1") .excludeLayer("base") .build()) .addOption(ProvisioningOption.IGNORE_NOT_EXCLUDED_LAYERS.getName(), Constants.TRUE) .build(); } protected ProvisionedState provisionedState() throws ProvisioningException { return ProvisionedState.builder() .addFeaturePack(ProvisionedFeaturePack.builder(prod1.getFPID()) .build()) .addConfig(ProvisionedConfigBuilder.builder() .setModel("model1") .setName("name1") .build()) .build(); } @Override protected DirState provisionedHomeDir() { return newDirBuilder() .build(); } }
[ "loubyansky@gmail.com" ]
loubyansky@gmail.com
b5d2eb9d6cd77abaf1a6731392ab4a909468ab1e
625f6598a4f92ba54c650a3024755d9e92be96b4
/InnerClassEx/src/com/naver/Test5.java
aba31818b016d85ace6b92f3966ee4a9c4fc7c97
[]
no_license
cksgur59/javastudy
53cb7e37942780872cf814f09bf5577f39425769
dc959523971b7ea9af6c50d928e942dea811b65a
refs/heads/main
2023-01-23T05:57:41.233887
2020-12-07T08:39:32
2020-12-07T08:39:32
303,949,655
0
0
null
null
null
null
UTF-8
Java
false
false
165
java
package com.naver; public class Test5 { public inter1 ano = new inter1() { @Override public void me1() { // TODO Auto-generated method stub } }; }
[ "cksgur59@gmail.com" ]
cksgur59@gmail.com
223eaeebbcd2ab47ce1553c267a7ed6e28c278d6
7bc86c242318566ed24569e1b6b8676c8e1c5144
/src/main/java/com/atguigu/cpes/service/impl/CertServiceImpl.java
a75bacc2f29ba78bc9d050ef4a6a14c4f45dfd4a
[]
no_license
ZHAOHUHU/cpes
b0e88eb5daa2678eda62be14c7bf31031f8256f0
e2bf50d082156d8400e156f0450e4e8928ae3344
refs/heads/master
2021-08-31T16:32:27.819990
2017-12-22T03:08:45
2017-12-22T03:08:45
114,985,098
0
0
null
null
null
null
UTF-8
Java
false
false
1,405
java
package com.atguigu.cpes.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.cpes.dao.CertDao; import com.atguigu.cpes.service.CertService; @Service public class CertServiceImpl implements CertService { @Autowired private CertDao certDao; public Page<Cert> queryPage(Integer pageno, Integer pagesize) { // ่Žทๅ–ๅˆ†้กตๅฏน่ฑก Page<Cert> page = new Page<Cert>(); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("start", (pageno-1)*pagesize); paramMap.put("pagesize", pagesize); List<Cert> data = certDao.queryCert4Page(paramMap); int count = certDao.queryCertCount4Page(paramMap); page.setDatas(data); page.setTotalsize(count); return page; } public void insertCert(Cert cert) { certDao.insertCert(cert); } public Cert queryCertById(Integer id) { return certDao.queryCertById(id); } public void updateCert(Cert cert) { certDao.updateCert(cert); } public void deleteCertById(Integer id) { certDao.deleteCertById(id); } public void deleteCerts(Datas ds) { certDao.deleteCerts(ds); } public List<Cert> queryAll() { return certDao.queryAll(); } public List<Cert> queryCertByAcctype(String acctype) { return certDao.queryCertByAcctype(acctype); } }
[ "3066918701@qq.com" ]
3066918701@qq.com
edc890a0aaf2a2bcf4167984887fa9409fa81b39
2c3b4baccbeaeb307f3888e5f6a7122446af9dca
/Exercises/Cylinder/src/com/roger/Cylinder.java
b97353b0dc274ebe55ec8c4dba31f12b52152fe0
[]
no_license
Rloui/Java_Practice
1c54ee70a8bfecebd7fc7281fa052cfb14cfca08
5d2aecc1c69eed0cf6817867497d7454c17dbb81
refs/heads/main
2023-03-21T03:04:25.613502
2021-03-07T16:04:56
2021-03-07T16:04:56
333,497,406
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.roger; public class Cylinder extends Circle { private double height; public Cylinder(double radius, double height) { super(radius); this.height = height < 0 ? 0 : height; } public double getHeight() { return height; } public double getVolume() { double volume = getArea() * getHeight(); return volume; } }
[ "69759725+Rloui@users.noreply.github.com" ]
69759725+Rloui@users.noreply.github.com
61779c68efcaab7bab8a2b944b285e1eb22a8600
d8ffa73b93eafd1b49b375d8a418977f0a17dbd1
/app/src/main/java/com/jroaes/colectiapptest/ui/map/MapsActivity.java
b089ae34c3296490a3843f3d0de2c73cb1a10ce7
[]
no_license
jroaes/ColectiAppTest
ac3cd8476b00672473f928dee2c391d9655725d5
548a89f73ef920628552557e15fb26b585f1682a
refs/heads/master
2022-04-19T14:07:43.112757
2020-04-17T17:51:43
2020-04-17T17:51:43
256,299,862
0
0
null
null
null
null
UTF-8
Java
false
false
2,023
java
package com.jroaes.colectiapptest.ui.map; import android.os.Bundle; import android.view.LayoutInflater; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.jroaes.colectiapptest.R; import com.jroaes.colectiapptest.adapters.InfoMarkerAdapter; import com.jroaes.colectiapptest.base.BaseFragmentActivity; import static com.jroaes.colectiapptest.Constants.INITIAL_POSITION; import static com.jroaes.colectiapptest.Constants.INITIAL_ZOOM; public class MapsActivity extends BaseFragmentActivity implements MapsInterface.View, OnMapReadyCallback { private static MapsPresenter presenter; private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); presenter = new MapsPresenter(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setInfoWindowAdapter(new InfoMarkerAdapter(LayoutInflater.from(this))); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(INITIAL_POSITION, INITIAL_ZOOM)); presenter.initMarkers(); } @Override public void addMarker(LatLng position, String title) { mMap.addMarker(new MarkerOptions().position(position).title(title)); } @Override public void showServerError(String text) { showErrorMessage(text); } @Override public void showLoading() { showLoadingDialog(this); } @Override public void hideLoading() { hideLoadingDialog(this); } }
[ "jroae@movidreams.com" ]
jroae@movidreams.com
72de37f228fd686ecd897c9fd88b2678f72430b6
fe33ab06a6811d370950f96277642cce0c1d72fe
/Lab_2/CircleArea.java
488ecb7863af2b66e6a96f0665d074ccfcd18300
[]
no_license
etnichols/EECS_168
fc83bd57457537c22f1598ba0b0a39ee08e72d5b
9c7f4eec4dfc7342db4aba2feea308bff1f97e12
refs/heads/master
2021-05-29T01:35:57.870011
2015-05-03T21:46:29
2015-05-03T21:46:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
701
java
/*-------------------------------------------------- * File Name: CircleArea.java * Author: Evan Nichols evan.t.nichols@ku.edu * Assignment: EECS-168/169 Lab 2 * Description: This program will compute the area of a circle with a hard-coded radius. * Date: 9/8/2014 * ----------------------------------------------------*/ public class CircleArea { public static void main(String[] args) { //Declare the variables and constants. final double PI = 3.141592; double radius; double area; //Assign a radius and calculate the area of the circle. radius = 20.0; area = PI*radius*radius; System.out.println("The area for the circle of radius "+radius+" is "+area); } }
[ "evan.t.nichols@gmail.com" ]
evan.t.nichols@gmail.com
4fc411c7d5b2ff4a31e897e57716e0f1eaf85477
660d75782923a536d9a3c51720a32a52d5539709
/java/life/tsuga/tsuga/SectionsPagerAdapter.java
ebce7be21885c725810984d894444ddb8e6ec79d
[]
no_license
skilcrafter/Tsuga
85428fdf6009561bac6256e717c3151864ffa189
add848cea6ecd710c1d8a9beff85cdec8c098f42
refs/heads/master
2020-05-17T14:18:34.666094
2015-06-19T01:54:45
2015-06-19T01:54:45
36,997,819
0
0
null
null
null
null
UTF-8
Java
false
false
680
java
package life.tsuga.tsuga; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class SectionsPagerAdapter extends FragmentPagerAdapter { protected Context mContext; public SectionsPagerAdapter(Context context,FragmentManager fm) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { switch (position){ case 0: return new InboxFragment(); } return null; } @Override public int getCount() { return 1; } }
[ "skilcrafter@hotmail.com" ]
skilcrafter@hotmail.com
f7fde795056d86eeb65d5aad1c4639cb4deee068
f112a49db89210fe24bea4ae436fbe378970697b
/src/main/java/tr/gov/egm/library/dao/impl/GenericDAOImpl.java
ef59d263057384ee430ed6caf2aa968b6b188826
[]
no_license
erkinpehlivan/kutuphane
936222c34b6cf5da57bff337bceb681591a63c12
e068d225b7727401b50a9adc31add0ea56cfa20a
refs/heads/master
2021-06-08T02:01:14.115947
2016-12-03T12:48:40
2016-12-04T07:54:05
74,826,308
0
0
null
null
null
null
UTF-8
Java
false
false
2,791
java
package tr.gov.egm.library.dao.impl; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import tr.gov.egm.library.dao.GenericDAO; import tr.gov.egm.library.exceptions.dao.CreateException; import tr.gov.egm.library.exceptions.dao.DeleteException; import tr.gov.egm.library.exceptions.dao.ReadException; import tr.gov.egm.library.exceptions.dao.UpdateException; @SuppressWarnings("unchecked") @Repository public abstract class GenericDAOImpl<E, K extends Serializable> implements GenericDAO<E, K> { @Autowired private SessionFactory sessionFactory; protected Class<? extends E> entityType; protected Session currentSession() { return sessionFactory.getCurrentSession(); } public GenericDAOImpl() { Type t = getClass().getGenericSuperclass(); ParameterizedType pType = (ParameterizedType) t; entityType = (Class<? extends E>) pType.getActualTypeArguments()[0]; } /* * (non-Javadoc) * * @see tr.gov.egm.library.dao.GenericDAO#add(java.lang.Object) */ @Override public void add(E e) throws CreateException { try { currentSession().save(e); } catch (Exception ex) { throw new CreateException("Kayฤฑt ekleme baลŸarฤฑsฤฑz", ex); } } /* * (non-Javadoc) * * @see tr.gov.egm.library.dao.GenericDAO#remove(java.lang.Object) */ @Override public void remove(E e) throws DeleteException { try { currentSession().delete(e); } catch (Exception ex) { throw new DeleteException("Silme iลŸlemi baลŸarฤฑsฤฑz", ex); } } /* * (non-Javadoc) * * @see tr.gov.egm.library.dao.GenericDAO#update(java.lang.Object) */ @Override public void update(E e) throws UpdateException { try { currentSession().update(e); } catch (Exception ex) { throw new UpdateException("Guncelleme iลŸlemi baลŸarฤฑsฤฑz", ex); } } /* * (non-Javadoc) * * @see tr.gov.egm.library.dao.GenericDAO#findById(java.lang.Object) */ @Override public E findById(K pk) throws ReadException { try { return currentSession().get(entityType, pk); } catch (Exception ex) { throw new ReadException("Kayฤฑt getirilirken hata oluลŸtu.", ex); } } /* * (non-Javadoc) * * @see tr.gov.egm.library.dao.GenericDAO#findAll() */ @Override public List<E> findAll() throws ReadException { try { return currentSession().createCriteria(entityType).list(); } catch (Exception ex) { throw new ReadException("Kayฤฑt listelenirken hata oluลŸtu.", ex); } } }
[ "erkin@javauzmani.com" ]
erkin@javauzmani.com
8624c325deb48c7cc5efc614dc592f8d4e232f5f
eec9bdcc0673081f6c67e21164219ce23e53d71d
/Lesson-5/src/com/marakana/yamba6/TimelineActivity.java
1c7e4e2039e6b6d2636311372a19c58db8e9dbc2
[]
no_license
fairyzoro/DevelopingSocialAndroidApp
5068599d95f5eb46e89c476349f1de90b51d1a88
8b678e168ad84d0a9a429e4c966c6cac545bc079
refs/heads/master
2021-01-16T20:40:49.651600
2013-08-15T02:28:20
2013-08-15T02:28:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,960
java
package com.marakana.yamba6; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.os.Bundle; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.SimpleCursorAdapter.ViewBinder; public class TimelineActivity extends BaseActivity { static final String SEND_TIMELINE_NOTIFICATIONS = "com.marakana.yamba.SEND_TIMELINE_NOTIFICATIONS"; Cursor cursor; ListView listTimeline; SimpleCursorAdapter adapter; static final String[] FROM = { StatusData.C_CREATED_AT, StatusData.C_USER, StatusData.C_TEXT }; static final int[] TO = { R.id.textCreatedAt, R.id.textUser, R.id.textText }; TimelineReceiver receiver; IntentFilter filter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timeline); // Find your views listTimeline = (ListView) findViewById(R.id.listTimeline); // Create the receiver receiver = new TimelineReceiver(); filter = new IntentFilter( UpdaterService.NEW_STATUS_INTENT ); } @Override protected void onResume() { super.onResume(); this.setupList(); // Register the receiver super.registerReceiver(receiver, filter, SEND_TIMELINE_NOTIFICATIONS, null); } @Override protected void onPause() { super.onPause(); // UNregister the receiver unregisterReceiver(receiver); } // View binder constant to inject business logic for timestamp to relative // time conversion static final ViewBinder VIEW_BINDER = new ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if(view.getId() != R.id.textCreatedAt) return false; // Update the created at text to relative time long timestamp = cursor.getLong(columnIndex); CharSequence relTime = DateUtils.getRelativeTimeSpanString(view.getContext(), timestamp); ((TextView)view).setText(relTime); return true; } }; // Responsible for fetching data and setting up the list and the adapter private void setupList() { // Get the data from the database YambaApplication yamba = (YambaApplication) super.getApplication(); this.cursor = yamba.getStatusData().getStatusUpdates(); startManagingCursor(this.cursor); // Setup the adapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, FROM, TO); adapter.setViewBinder(VIEW_BINDER); listTimeline.setAdapter(adapter); } // Receiver to wake up when UpdaterService gets a new status // It refreshes the timeline list by requerying the cursor class TimelineReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { setupList(); Log.d("TimelineReceiver", "onReceived"); } } }
[ "xtiqin@163.com" ]
xtiqin@163.com
b31dd658a6e8d275259aea278d52f2bf291ec766
25ce36fb7684df84de52cdbd0a0cfb5f4abfdf06
/app/src/main/java/com/example/matt/starwarsmovies/Movie.java
12d8e7aec4773420a7287117635e01711412788f
[]
no_license
matt-beeson/StarWarsMiniApp
d075afa3de63bbee929b0856d0229d42efa68a8f
1482bf0f8d88f9631050c6caef2877a142fba4ff
refs/heads/master
2021-04-28T01:43:26.335556
2018-02-21T03:04:58
2018-02-21T03:04:58
122,286,225
0
0
null
null
null
null
UTF-8
Java
false
false
3,478
java
package com.example.matt.starwarsmovies; import android.content.Context; import android.support.v4.content.ContextCompat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.lang.reflect.Array; import java.util.ArrayList; /** * Created by Matt on 2/15/2018. */ public class Movie { // instance variables public String title; public Integer episodeNumber; public ArrayList<String> mainCharacters = new ArrayList<>(); public String description; public String posterURL; public String imdbURL; public String hasSeen; // constructors // default // read the json file in and load into Movies // helper method that loads from any Json file private static String loadJsonFromAsset(String filename, Context context) { String json = null; try { InputStream is = context.getAssets().open(filename); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (java.io.IOException ex) { ex.printStackTrace(); return null; } return json; } // load out of movie.json using the helper method // this method will return an array list of movies from the json file public static ArrayList<Movie> getMoviesFromFile(String filename, Context context) { ArrayList<Movie> movieList = new ArrayList<Movie>(); // try to read from JSON file // get information by using the tags // construct a movie object for each movie in json // ad the object to arrayList // return arrayList try { String jsonString = loadJsonFromAsset("movies.json", context); JSONObject json = new JSONObject(jsonString); JSONArray movies = json.getJSONArray("movies"); // for loop to go through each recipe in the recipeArray for(int i = 0; i < movies.length(); i++){ Movie movie = new Movie(); movie.title = movies.getJSONObject(i).getString("title"); movie.episodeNumber = movies.getJSONObject(i).getInt("episode_number"); // because the characters appear in an array in the json file.. // you need to go through the array and put them into a JSON array // then from that JSON array you put the characters into an array list for each movie JSONArray jsonCharacters = (JSONArray)movies.getJSONObject(i).get("main_characters"); for(int j = 0; j < jsonCharacters.length()-1;j++){ movie.mainCharacters.add(j, jsonCharacters.getString(j)); } // test if all the characters are parsed correctly //System.out.println(movie.mainCharacters.toString()); movie.description = movies.getJSONObject(i).getString("description"); movie.posterURL = movies.getJSONObject(i).getString("poster"); movie.imdbURL = movies.getJSONObject(i).getString("url"); movie.hasSeen = "Has seen?"; // add arrayList movieList.add(movie); } } catch (JSONException e) { e.printStackTrace(); } return movieList; } }
[ "mbeeson7@gmail.com" ]
mbeeson7@gmail.com
279b7dbca8ec6ec98bef977fbb53781d5cb1eb1a
ac4bbf6d46285c2883ac108042b09e4edf88590b
/src/main/java/com/spring/jpa/demospringjpa/entites/Review.java
610f3016202f9a9bda70c8b16bb67fb073b168fe
[]
no_license
raghunathreddymustur/SpringDataJPA
6d8f03087573757a13b9d0d7a74a41d52946b897
f9a6de6248a7ca5fdff0156e4388c01df5cdf5dc
refs/heads/master
2023-03-23T19:13:03.915338
2021-03-17T11:46:47
2021-03-17T11:46:47
346,583,929
0
0
null
null
null
null
UTF-8
Java
false
false
1,199
java
package com.spring.jpa.demospringjpa.entites; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Review { @Id @GeneratedValue private Long id; @Column(nullable = false) private String rating; private String review; @ManyToOne private Course course; public Review(){} public Review(String rating, String review) { this.rating = rating; this.review = review; } public Long getId() { return id; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getReview() { return review; } public void setReview(String review) { this.review = review; } @Override public String toString() { return "Review [id=" + id + ", rating=" + rating + ", review=" + review + "]"; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } }
[ "raghunathreddymustur321@gmail.com" ]
raghunathreddymustur321@gmail.com
bda5a0fe87693f32142ea01f5a075194fe224c36
d50666875b8a6d58563ea7a0f6ce064c3f13213f
/src/main/java/com/yahoo/house/controller/UserController.java
06c70114a6f5f22a68f2f6397dcd4d6259a3275b
[]
no_license
Yyahoo/SSHM_hrs
9e79e8674e4fc8d4595075a3958e44ec64bde2aa
18bec4a2afabf3781da407aefb6c2d94851de0fb
refs/heads/master
2021-05-07T06:33:01.580356
2017-11-23T06:45:18
2017-11-23T06:45:18
111,764,073
0
0
null
null
null
null
UTF-8
Java
false
false
2,777
java
package com.yahoo.house.controller; import java.awt.image.BufferedImage; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.yahoo.house.domain.User; import com.yahoo.house.dto.CheckResult; import com.yahoo.house.dto.UserLoginDto; import com.yahoo.house.service.UserService; import com.yahoo.house.util.CommonUtil; @Controller public class UserController { private static final int CODE_LENGTH = 4; @Autowired private UserService userService; @GetMapping("/check") @ResponseBody public CheckResult checkUsername(String username) { boolean valid = userService.checkUnique(username); return new CheckResult(username, valid, valid ? "็”จๆˆทๅๅฏ็”จ" : "็”จๆˆทๅๅทฒ่ขซๅ ็”จ", valid ? "ok.png" : "no.png"); } @PostMapping("/login") public String loginmsg(@Valid UserLoginDto user, Errors errors, Model model, HttpServletRequest req) { String viewName = "login"; if (user.getCode().equalsIgnoreCase((String) req.getSession().getAttribute("code"))) { if (!errors.hasErrors()) { user.setIpAddress(req.getRemoteAddr()); if (userService.login(user)) { req.getSession().setAttribute("userRealname", user.getRealname()); req.getSession().setAttribute("userid", user.getId()); viewName = "redirect:home"; } else { model.addAttribute("hint", "็”จๆˆทๅๆˆ–ๅฏ†็ ้”™่ฏฏ"); } } else { model.addAttribute("hint", "่ฏท่พ“ๅ…ฅๆœ‰ๆ•ˆ็š„็™ปๅฝ•ไฟกๆฏ"); } } else { model.addAttribute("hint", "่ฏท่พ“ๅ…ฅๆญฃ็กฎ็š„้ชŒ่ฏ็ "); } return viewName; } @PostMapping("/reg") public String registmsg(@Valid User user, Model model, Errors error, HttpSession session, String code) { String viewName = "register"; if (code.equalsIgnoreCase((String)session.getAttribute("code"))) { if (!error.hasErrors()){ if (userService.register(user)) viewName = "redirect:toLogin"; }else { model.addAttribute("hint", "่ฏท่พ“ๅ…ฅๆœ‰ๆ•ˆ็š„ๆณจๅ†Œไฟกๆฏ"); } } else { model.addAttribute("hint", "่ฏท่พ“ๅ…ฅๆญฃ็กฎ็š„้ชŒ่ฏ็ "); } return viewName; } @GetMapping(value = "/code", produces = "image/png") @ResponseBody public BufferedImage getCode(HttpSession session) throws Exception { String code = CommonUtil.generateCode(CODE_LENGTH); session.setAttribute("code", code); return CommonUtil.generateCodeImage(code, 80, 30); } }
[ "hellokitty@qq.com" ]
hellokitty@qq.com
7fd96eab6546a0c45871acf9e1f3407799844d7b
52b948436b826df8164565ffe69e73a92eb92cda
/Source/comingd4jmore/GenProg_patch_Defects4J_Math_80_0_559/EigenDecompositionImpl/GenProg_patch_Defects4J_Math_80_0_559_EigenDecompositionImpl_t.java
b56c9789e45b5b8ff8c3120660d70c24c182646b
[ "Apache-2.0" ]
permissive
tdurieux/ODSExperiment
910365f1388bc684e9916f46f407d36226a2b70b
3881ef06d6b8d5efb751860811def973cb0220eb
refs/heads/main
2023-07-05T21:30:30.099605
2021-08-18T15:56:56
2021-08-18T15:56:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
67,065
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.linear; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.MaxIterationsExceededException; import org.apache.commons.math.util.MathUtils; /** * Calculates the eigen decomposition of a <strong>symmetric</strong> matrix. * <p>The eigen decomposition of matrix A is a set of two matrices: * V and D such that A = V D V<sup>T</sup>. A, V and D are all m &times; m * matrices.</p> * <p>As of 2.0, this class supports only <strong>symmetric</strong> matrices, * and hence computes only real realEigenvalues. This implies the D matrix returned by * {@link #getD()} is always diagonal and the imaginary values returned {@link * #getImagEigenvalue(int)} and {@link #getImagEigenvalues()} are always null.</p> * <p>When called with a {@link RealMatrix} argument, this implementation only uses * the upper part of the matrix, the part below the diagonal is not accessed at all.</p> * <p>Eigenvalues are computed as soon as the matrix is decomposed, but eigenvectors * are computed only when required, i.e. only when one of the {@link #getEigenvector(int)}, * {@link #getV()}, {@link #getVT()}, {@link #getSolver()} methods is called.</p> * <p>This implementation is based on Inderjit Singh Dhillon thesis * <a href="http://www.cs.utexas.edu/users/inderjit/public_papers/thesis.pdf">A * New O(n<sup>2</sup>) Algorithm for the Symmetric Tridiagonal Eigenvalue/Eigenvector * Problem</a>, on Beresford N. Parlett and Osni A. Marques paper <a * href="http://www.netlib.org/lapack/lawnspdf/lawn155.pdf">An Implementation of the * dqds Algorithm (Positive Case)</a> and on the corresponding LAPACK routines (DLARRE, * DLASQ2, DLAZQ3, DLAZQ4, DLASQ5 and DLASQ6).</p> * <p>The authors of the original fortran version are: * <ul> * <li>Beresford Parlett, University of California, Berkeley, USA</li> * <li>Jim Demmel, University of California, Berkeley, USA</li> * <li>Inderjit Dhillon, University of Texas, Austin, USA</li> * <li>Osni Marques, LBNL/NERSC, USA</li> * <li>Christof Voemel, University of California, Berkeley, USA</li> * </ul> * </p> * @version $Revision$ $Date$ * @since 2.0 */ public class EigenDecompositionImpl implements EigenDecomposition { /** Tolerance. */ private static final double TOLERANCE = 100 * MathUtils.EPSILON; /** Squared tolerance. */ private static final double TOLERANCE_2 = TOLERANCE * TOLERANCE; /** Split tolerance. */ private double splitTolerance; /** Main diagonal of the tridiagonal matrix. */ private double[] main; /** Secondary diagonal of the tridiagonal matrix. */ private double[] secondary; /** Squared secondary diagonal of the tridiagonal matrix. */ private double[] squaredSecondary; /** Transformer to tridiagonal (may be null if matrix is already tridiagonal). */ private TriDiagonalTransformer transformer; /** Lower bound of spectra. */ private double lowerSpectra; /** Upper bound of spectra. */ private double upperSpectra; /** Minimum pivot in the Sturm sequence. */ private double minPivot; /** Current shift. */ private double sigma; /** Low part of the current shift. */ private double sigmaLow; /** Shift increment to apply. */ private double tau; /** Work array for all decomposition algorithms. */ private double[] work; /** Shift within qd array for ping-pong implementation. */ private int pingPong; /** Max value of diagonal elements in current segment. */ private double qMax; /** Min value of off-diagonal elements in current segment. */ private double eMin; /** Type of the last dqds shift. */ private int tType; /** Minimal value on current state of the diagonal. */ private double dMin; /** Minimal value on current state of the diagonal, excluding last element. */ private double dMin1; /** Minimal value on current state of the diagonal, excluding last two elements. */ private double dMin2; /** Last value on current state of the diagonal. */ private double dN; /** Last but one value on current state of the diagonal. */ private double dN1; /** Last but two on current state of the diagonal. */ private double dN2; /** Shift ratio with respect to dMin used when tType == 6. */ private double g; /** Real part of the realEigenvalues. */ private double[] realEigenvalues; /** Imaginary part of the realEigenvalues. */ private double[] imagEigenvalues; /** Eigenvectors. */ private ArrayRealVector[] eigenvectors; /** Cached value of V. */ private RealMatrix cachedV; /** Cached value of D. */ private RealMatrix cachedD; /** Cached value of Vt. */ private RealMatrix cachedVt; /** * Calculates the eigen decomposition of the given symmetric matrix. * @param matrix The <strong>symmetric</strong> matrix to decompose. * @param splitTolerance tolerance on the off-diagonal elements relative to the * geometric mean to split the tridiagonal matrix (a suggested value is * {@link MathUtils#SAFE_MIN}) * @exception InvalidMatrixException (wrapping a {@link * org.apache.commons.math.ConvergenceException} if algorithm fails to converge */ public EigenDecompositionImpl(final RealMatrix matrix, final double splitTolerance) throws InvalidMatrixException { if (isSymmetric(matrix)) { this.splitTolerance = splitTolerance; transformToTridiagonal(matrix); decompose(); } else { // as of 2.0, non-symmetric matrices (i.e. complex eigenvalues) are NOT supported // see issue https://issues.apache.org/jira/browse/MATH-235 throw new InvalidMatrixException("eigen decomposition of assymetric matrices not supported yet"); } } /** * Calculates the eigen decomposition of the given tridiagonal symmetric matrix. * @param main the main diagonal of the matrix (will be copied) * @param secondary the secondary diagonal of the matrix (will be copied) * @param splitTolerance tolerance on the off-diagonal elements relative to the * geometric mean to split the tridiagonal matrix (a suggested value is * {@link MathUtils#SAFE_MIN}) * @exception InvalidMatrixException (wrapping a {@link * org.apache.commons.math.ConvergenceException} if algorithm fails to converge */ public EigenDecompositionImpl(final double[] main, double[] secondary, final double splitTolerance) throws InvalidMatrixException { this.main = main.clone(); this.secondary = secondary.clone(); transformer = null; // pre-compute some elements squaredSecondary = new double[secondary.length]; for (int i = 0; i < squaredSecondary.length; ++i) { final double s = secondary[i]; squaredSecondary[i] = s * s; } this.splitTolerance = splitTolerance; decompose(); } /** * Check if a matrix is symmetric. * @param matrix matrix to check * @return true if matrix is symmetric */ private boolean isSymmetric(final RealMatrix matrix) { final int rows = matrix.getRowDimension(); final int columns = matrix.getColumnDimension(); final double eps = 10 * rows * columns * MathUtils.EPSILON; for (int i = 0; i < rows; ++i) { for (int j = i + 1; j < columns; ++j) { final double mij = matrix.getEntry(i, j); final double mji = matrix.getEntry(j, i); if (Math.abs(mij - mji) > (Math.max(Math.abs(mij), Math.abs(mji)) * eps)) { return false; } } } return true; } /** * Decompose a tridiagonal symmetric matrix. * @exception InvalidMatrixException (wrapping a {@link * org.apache.commons.math.ConvergenceException} if algorithm fails to converge */ private void decompose() { cachedV = null; cachedD = null; cachedVt = null; work = new double[6 * main.length]; // compute the Gershgorin circles computeGershgorinCircles(); // find all the realEigenvalues findEigenvalues(); // we will search for eigenvectors only if required eigenvectors = null; } /** {@inheritDoc} */ public RealMatrix getV() throws InvalidMatrixException { if (cachedV == null) { if (eigenvectors == null) { findEigenVectors(); } final int m = eigenvectors.length; cachedV = MatrixUtils.createRealMatrix(m, m); for (int k = 0; k < m; ++k) { cachedV.setColumnVector(k, eigenvectors[k]); } } // return the cached matrix return cachedV; } /** {@inheritDoc} */ public RealMatrix getD() throws InvalidMatrixException { if (cachedD == null) { // cache the matrix for subsequent calls cachedD = MatrixUtils.createRealDiagonalMatrix(realEigenvalues); } return cachedD; } /** {@inheritDoc} */ public RealMatrix getVT() throws InvalidMatrixException { if (cachedVt == null) { if (eigenvectors == null) { findEigenVectors(); } final int m = eigenvectors.length; cachedVt = MatrixUtils.createRealMatrix(m, m); for (int k = 0; k < m; ++k) { cachedVt.setRowVector(k, eigenvectors[k]); } } // return the cached matrix return cachedVt; } /** {@inheritDoc} */ public double[] getRealEigenvalues() throws InvalidMatrixException { return realEigenvalues.clone(); } /** {@inheritDoc} */ public double getRealEigenvalue(final int i) throws InvalidMatrixException, ArrayIndexOutOfBoundsException { return realEigenvalues[i]; } /** {@inheritDoc} */ public double[] getImagEigenvalues() throws InvalidMatrixException { return imagEigenvalues.clone(); } /** {@inheritDoc} */ public double getImagEigenvalue(final int i) throws InvalidMatrixException, ArrayIndexOutOfBoundsException { return imagEigenvalues[i]; } /** {@inheritDoc} */ public RealVector getEigenvector(final int i) throws InvalidMatrixException, ArrayIndexOutOfBoundsException { if (eigenvectors == null) { findEigenVectors(); } return eigenvectors[i].copy(); } /** * Return the determinant of the matrix * @return determinant of the matrix */ public double getDeterminant() { double determinant = 1; for (double lambda : realEigenvalues) { determinant *= lambda; } return determinant; } /** {@inheritDoc} */ public DecompositionSolver getSolver() { if (eigenvectors == null) { findEigenVectors(); } return new Solver(realEigenvalues, imagEigenvalues, eigenvectors); } /** Specialized solver. */ private static class Solver implements DecompositionSolver { /** Real part of the realEigenvalues. */ private double[] realEigenvalues; /** Imaginary part of the realEigenvalues. */ private double[] imagEigenvalues; /** Eigenvectors. */ private final ArrayRealVector[] eigenvectors; /** * Build a solver from decomposed matrix. * @param realEigenvalues real parts of the eigenvalues * @param imagEigenvalues imaginary parts of the eigenvalues * @param eigenvectors eigenvectors */ private Solver(final double[] realEigenvalues, final double[] imagEigenvalues, final ArrayRealVector[] eigenvectors) { this.realEigenvalues = realEigenvalues; this.imagEigenvalues = imagEigenvalues; this.eigenvectors = eigenvectors; } /** Solve the linear equation A &times; X = B for symmetric matrices A. * <p>This method only find exact linear solutions, i.e. solutions for * which ||A &times; X - B|| is exactly 0.</p> * @param b right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match * @exception InvalidMatrixException if decomposed matrix is singular */ public double[] solve(final double[] b) throws IllegalArgumentException, InvalidMatrixException { if (!isNonSingular()) { throw new SingularMatrixException(); } final int m = realEigenvalues.length; if (b.length != m) { throw MathRuntimeException.createIllegalArgumentException( "vector length mismatch: got {0} but expected {1}", b.length, m); } final double[] bp = new double[m]; for (int i = 0; i < m; ++i) { final ArrayRealVector v = eigenvectors[i]; final double[] vData = v.getDataRef(); final double s = v.dotProduct(b) / realEigenvalues[i]; for (int j = 0; j < m; ++j) { bp[j] += s * vData[j]; } } return bp; } /** Solve the linear equation A &times; X = B for symmetric matrices A. * <p>This method only find exact linear solutions, i.e. solutions for * which ||A &times; X - B|| is exactly 0.</p> * @param b right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match * @exception InvalidMatrixException if decomposed matrix is singular */ public RealVector solve(final RealVector b) throws IllegalArgumentException, InvalidMatrixException { if (!isNonSingular()) { throw new SingularMatrixException(); } final int m = realEigenvalues.length; if (b.getDimension() != m) { throw MathRuntimeException.createIllegalArgumentException( "vector length mismatch: got {0} but expected {1}", b.getDimension(), m); } final double[] bp = new double[m]; for (int i = 0; i < m; ++i) { final ArrayRealVector v = eigenvectors[i]; final double[] vData = v.getDataRef(); final double s = v.dotProduct(b) / realEigenvalues[i]; for (int j = 0; j < m; ++j) { bp[j] += s * vData[j]; } } return new ArrayRealVector(bp, false); } /** Solve the linear equation A &times; X = B for symmetric matrices A. * <p>This method only find exact linear solutions, i.e. solutions for * which ||A &times; X - B|| is exactly 0.</p> * @param b right-hand side of the equation A &times; X = B * @return a matrix X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match * @exception InvalidMatrixException if decomposed matrix is singular */ public RealMatrix solve(final RealMatrix b) throws IllegalArgumentException, InvalidMatrixException { if (!isNonSingular()) { throw new SingularMatrixException(); } final int m = realEigenvalues.length; if (b.getRowDimension() != m) { throw MathRuntimeException.createIllegalArgumentException( "dimensions mismatch: got {0}x{1} but expected {2}x{3}", b.getRowDimension(), b.getColumnDimension(), m, "n"); } final int nColB = b.getColumnDimension(); final double[][] bp = new double[m][nColB]; for (int k = 0; k < nColB; ++k) { for (int i = 0; i < m; ++i) { final ArrayRealVector v = eigenvectors[i]; final double[] vData = v.getDataRef(); double s = 0; for (int j = 0; j < m; ++j) { s += v.getEntry(j) * b.getEntry(j, k); } s /= realEigenvalues[i]; for (int j = 0; j < m; ++j) { bp[j][k] += s * vData[j]; } } } return MatrixUtils.createRealMatrix(bp); } /** * Check if the decomposed matrix is non-singular. * @return true if the decomposed matrix is non-singular */ public boolean isNonSingular() { for (int i = 0; i < realEigenvalues.length; ++i) { if ((realEigenvalues[i] == 0) && (imagEigenvalues[i] == 0)) { return false; } } return true; } /** Get the inverse of the decomposed matrix. * @return inverse matrix * @throws InvalidMatrixException if decomposed matrix is singular */ public RealMatrix getInverse() throws InvalidMatrixException { if (!isNonSingular()) { throw new SingularMatrixException(); } final int m = realEigenvalues.length; final double[][] invData = new double[m][m]; for (int i = 0; i < m; ++i) { final double[] invI = invData[i]; for (int j = 0; j < m; ++j) { double invIJ = 0; for (int k = 0; k < m; ++k) { final double[] vK = eigenvectors[k].getDataRef(); invIJ += vK[i] * vK[j] / realEigenvalues[k]; } invI[j] = invIJ; } } return MatrixUtils.createRealMatrix(invData); } } /** * Transform matrix to tridiagonal. * @param matrix matrix to transform */ private void transformToTridiagonal(final RealMatrix matrix) { // transform the matrix to tridiagonal transformer = new TriDiagonalTransformer(matrix); main = transformer.getMainDiagonalRef(); secondary = transformer.getSecondaryDiagonalRef(); // pre-compute some elements squaredSecondary = new double[secondary.length]; for (int i = 0; i < squaredSecondary.length; ++i) { final double s = secondary[i]; squaredSecondary[i] = s * s; } } /** * Compute the Gershgorin circles for all rows. */ private void computeGershgorinCircles() { final int m = main.length; final int lowerStart = 4 * m; final int upperStart = 5 * m; lowerSpectra = Double.POSITIVE_INFINITY; upperSpectra = Double.NEGATIVE_INFINITY; double eMax = 0; double eCurrent = 0; for (int i = 0; i < m - 1; ++i) { final double dCurrent = main[i]; final double ePrevious = eCurrent; eCurrent = Math.abs(secondary[i]); eMax = Math.max(eMax, eCurrent); final double radius = ePrevious + eCurrent; final double lower = dCurrent - radius; work[lowerStart + i] = lower; lowerSpectra = Math.min(lowerSpectra, lower); final double upper = dCurrent + radius; work[upperStart + i] = upper; upperSpectra = Math.max(upperSpectra, upper); } final double dCurrent = main[m - 1]; final double lower = dCurrent - eCurrent; work[lowerStart + m - 1] = lower; lowerSpectra = Math.min(lowerSpectra, lower); final double upper = dCurrent + eCurrent; work[upperStart + m - 1] = upper; upperSpectra = Math.max(upperSpectra, upper); minPivot = MathUtils.SAFE_MIN * Math.max(1.0, eMax * eMax); } /** * Find the realEigenvalues. * @exception InvalidMatrixException if a block cannot be diagonalized */ private void findEigenvalues() throws InvalidMatrixException { // compute splitting points List<Integer> splitIndices = computeSplits(); // find realEigenvalues in each block realEigenvalues = new double[main.length]; imagEigenvalues = new double[main.length]; int begin = 0; for (final int end : splitIndices) { final int n = end - begin; switch (n) { case 1: // apply dedicated method for dimension 1 process1RowBlock(begin); break; case 2: // apply dedicated method for dimension 2 process2RowsBlock(begin); break; case 3: // apply dedicated method for dimension 3 process3RowsBlock(begin); break; default: // choose an initial shift for LDL<sup>T</sup> decomposition final double[] range = eigenvaluesRange(begin, n); final double oneFourth = 0.25 * (3 * range[0] + range[1]); final int oneFourthCount = countEigenValues(oneFourth, begin, n); final double threeFourth = 0.25 * (range[0] + 3 * range[1]); final int threeFourthCount = countEigenValues(threeFourth, begin, n); final boolean chooseLeft = (oneFourthCount - 1) >= (n - threeFourthCount); final double lambda = chooseLeft ? range[0] : range[1]; tau = (range[1] - range[0]) * MathUtils.EPSILON * n + 2 * minPivot; // decompose T-&lambda;I as LDL<sup>T</sup> ldlTDecomposition(lambda, begin, n); // apply general dqd/dqds method processGeneralBlock(n); // extract realEigenvalues if (chooseLeft) { for (int i = 0; i < n; ++i) { realEigenvalues[begin + i] = lambda + work[4 * i]; } } else { for (int i = 0; i < n; ++i) { realEigenvalues[begin + i] = lambda - work[4 * i]; } } } begin = end; } // sort the realEigenvalues in decreasing order Arrays.sort(realEigenvalues); int j = realEigenvalues.length - 1; for (int i = 0; i < j; ++i) { final double tmp = realEigenvalues[i]; realEigenvalues[i] = realEigenvalues[j]; realEigenvalues[j] = tmp; --j; } } /** * Compute splitting points. * @return list of indices after matrix can be split */ private List<Integer> computeSplits() { final List<Integer> list = new ArrayList<Integer>(); // splitting preserving relative accuracy double absDCurrent = Math.abs(main[0]); for (int i = 0; i < secondary.length; ++i) { final double absDPrevious = absDCurrent; absDCurrent = Math.abs(main[i + 1]); final double max = splitTolerance * Math.sqrt(absDPrevious * absDCurrent); if (Math.abs(secondary[i]) <= max) { list.add(i + 1); secondary[i] = 0; squaredSecondary[i] = 0; } } list.add(secondary.length + 1); return list; } /** * Find eigenvalue in a block with 1 row. * <p>In low dimensions, we simply solve the characteristic polynomial.</p> * @param index index of the first row of the block */ private void process1RowBlock(final int index) { realEigenvalues[index] = main[index]; } /** * Find realEigenvalues in a block with 2 rows. * <p>In low dimensions, we simply solve the characteristic polynomial.</p> * @param index index of the first row of the block * @exception InvalidMatrixException if characteristic polynomial cannot be solved */ private void process2RowsBlock(final int index) throws InvalidMatrixException { // the characteristic polynomial is // X^2 - (q0 + q1) X + q0 q1 - e1^2 final double q0 = main[index]; final double q1 = main[index + 1]; final double e12 = squaredSecondary[index]; final double s = q0 + q1; final double p = q0 * q1 - e12; final double delta = s * s - 4 * p; if (delta < 0) { throw new InvalidMatrixException("cannot solve degree {0} equation", 2); } final double largestRoot = 0.5 * (s + Math.sqrt(delta)); realEigenvalues[index] = largestRoot; realEigenvalues[index + 1] = p / largestRoot; } /** * Find realEigenvalues in a block with 3 rows. * <p>In low dimensions, we simply solve the characteristic polynomial.</p> * @param index index of the first row of the block * @exception InvalidMatrixException if diagonal elements are not positive */ private void process3RowsBlock(final int index) throws InvalidMatrixException { // the characteristic polynomial is // X^3 - (q0 + q1 + q2) X^2 + (q0 q1 + q0 q2 + q1 q2 - e1^2 - e2^2) X + q0 e2^2 + q2 e1^2 - q0 q1 q2 final double q0 = main[index]; final double q1 = main[index + 1]; final double q2 = main[index + 2]; final double e12 = squaredSecondary[index]; final double q1q2Me22 = q1 * q2 - squaredSecondary[index + 1]; // compute coefficients of the cubic equation as: x^3 + b x^2 + c x + d = 0 final double b = -(q0 + q1 + q2); final double c = q0 * q1 + q0 * q2 + q1q2Me22 - e12; final double d = q2 * e12 - q0 * q1q2Me22; // solve cubic equation final double b2 = b * b; final double q = (3 * c - b2) / 9; final double r = ((9 * c - 2 * b2) * b - 27 * d) / 54; final double delta = q * q * q + r * r; if (delta >= 0) { // in fact, there are solutions to the equation, but in the context // of symmetric realEigenvalues problem, there should be three distinct // real roots, so we throw an error if this condition is not met throw new InvalidMatrixException("cannot solve degree {0} equation", 3); } final double sqrtMq = Math.sqrt(-q); final double theta = Math.acos(r / (-q * sqrtMq)); final double alpha = 2 * sqrtMq; final double beta = b / 3; double z0 = alpha * Math.cos(theta / 3) - beta; double z1 = alpha * Math.cos((theta + 2 * Math.PI) / 3) - beta; double z2 = alpha * Math.cos((theta + 4 * Math.PI) / 3) - beta; if (z0 < z1) { final double t = z0; z0 = z1; z1 = t; } if (z1 < z2) { final double t = z1; z1 = z2; z2 = t; } if (z0 < z1) { final double t = z0; z0 = z1; z1 = t; } realEigenvalues[index] = z0; realEigenvalues[index + 1] = z1; realEigenvalues[index + 2] = z2; } /** * Find realEigenvalues using dqd/dqds algorithms. * <p>This implementation is based on Beresford N. Parlett * and Osni A. Marques paper <a * href="http://www.netlib.org/lapack/lawnspdf/lawn155.pdf">An * Implementation of the dqds Algorithm (Positive Case)</a> and on the * corresponding LAPACK routine DLASQ2.</p> * @param n number of rows of the block * @exception InvalidMatrixException if block cannot be diagonalized * after 30 * n iterations */ private void processGeneralBlock(final int n) throws InvalidMatrixException { // check decomposed matrix data range double sumOffDiag = 0; for (int i = 0; i < n - 1; ++i) { final int fourI = 4 * i; final double ei = work[fourI + 2]; sumOffDiag += ei; } if (sumOffDiag == 0) { // matrix is already diagonal return; } // initial checks for splits (see Parlett & Marques section 3.3) flipIfWarranted(n, 2); // two iterations with Li's test for initial splits initialSplits(n); // initialize parameters used by goodStep tType = 0; dMin1 = 0; dMin2 = 0; dN = 0; dN1 = 0; dN2 = 0; tau = 0; // process split segments int i0 = 0; int n0 = n; while (n0 > 0) { // retrieve shift that was temporarily stored as a negative off-diagonal element sigma = (n0 == n) ? 0 : -work[4 * n0 - 2]; sigmaLow = 0; // find start of a new split segment to process double offDiagMin = (i0 == n0) ? 0 : work[4 * n0 - 6]; double offDiagMax = 0; double diagMax = work[4 * n0 - 4]; double diagMin = diagMax; i0 = 0; for (int i = 4 * (n0 - 2); i >= 0; i -= 4) { if (work[i + 2] <= 0) { if (dMin <= 0.0) { tau = -dMin; tType = -1; return; } } if (diagMin >= 4 * offDiagMax) { diagMin = Math.min(diagMin, work[i + 4]); offDiagMax = Math.max(offDiagMax, work[i + 2]); } diagMax = Math.max(diagMax, work[i] + work[i + 2]); offDiagMin = Math.min(offDiagMin, work[i + 2]); } work[4 * n0 - 2] = offDiagMin; // lower bound of Gershgorin disk dMin = -Math.max(0, diagMin - 2 * Math.sqrt(diagMin * offDiagMax)); pingPong = 0; int maxIter = 30 * (n0 - i0); for (int k = 0; i0 < n0; ++k) { if (k >= maxIter) { throw new InvalidMatrixException(new MaxIterationsExceededException(maxIter)); } // perform one step n0 = goodStep(i0, n0); pingPong = 1 - pingPong; // check for new splits after "ping" steps // when the last elements of qd array are very small if ((pingPong == 0) && (n0 - i0 > 3) && (work[4 * n0 - 1] <= TOLERANCE_2 * diagMax) && (work[4 * n0 - 2] <= TOLERANCE_2 * sigma)) { int split = i0 - 1; diagMax = work[4 * i0]; offDiagMin = work[4 * i0 + 2]; double previousEMin = work[4 * i0 + 3]; for (int i = 4 * i0; i < 4 * n0 - 16; i += 4) { if ((work[i + 3] <= TOLERANCE_2 * work[i]) || (work[i + 2] <= TOLERANCE_2 * sigma)) { // insert a split work[i + 2] = -sigma; split = i / 4; diagMax = 0; offDiagMin = work[i + 6]; previousEMin = work[i + 7]; } else { diagMax = Math.max(diagMax, work[i + 4]); offDiagMin = Math.min(offDiagMin, work[i + 2]); previousEMin = Math.min(previousEMin, work[i + 3]); } } work[4 * n0 - 2] = offDiagMin; work[4 * n0 - 1] = previousEMin; i0 = split + 1; } } } } /** * Perform two iterations with Li's tests for initial splits. * @param n number of rows of the matrix to process */ private void initialSplits(final int n) { pingPong = 0; for (int k = 0; k < 2; ++k) { // apply Li's reverse test double d = work[4 * (n - 1) + pingPong]; for (int i = 4 * (n - 2) + pingPong; i >= 0; i -= 4) { if (work[i + 2] <= TOLERANCE_2 * d) { if (dMin <= 0.0) { tau = -dMin; tType = -1; return; } d = work[i]; } else { d *= work[i] / (d + work[i + 2]); } } // apply dqd plus Li's forward test. d = work[pingPong]; for (int i = 2 + pingPong; i < 4 * n - 2; i += 4) { final int j = i - 2 * pingPong - 1; work[j] = d + work[i]; if (work[i] <= TOLERANCE_2 * d) { if (work[i] <= TOLERANCE_2 * d) { work[i] = -0.0; work[j] = d; work[j + 2] = 0.0; d = work[i + 2]; } else if ((MathUtils.SAFE_MIN * work[i + 2] < work[j]) && (MathUtils.SAFE_MIN * work[j] < work[i + 2])) { final double tmp = work[i + 2] / work[j]; work[j + 2] = work[i] * tmp; d *= tmp; } else { work[j + 2] = work[i + 2] * (work[i] / work[j]); d *= work[i + 2] / work[j]; } work[j] = d; work[j + 2] = 0.0; tType = -2; } else if ((MathUtils.SAFE_MIN * work[i + 2] < work[j]) && (MathUtils.SAFE_MIN * work[j] < work[i + 2])) { final double tmp = work[i + 2] / work[j]; work[j + 2] = work[i] * tmp; d *= tmp; } else { work[j + 2] = work[i + 2] * (work[i] / work[j]); d *= work[i + 2] / work[j]; } } work[4 * n - 3 - pingPong] = d; // from ping to pong pingPong = 1 - pingPong; } } /** * Perform one "good" dqd/dqds step. * <p>This implementation is based on Beresford N. Parlett * and Osni A. Marques paper <a * href="http://www.netlib.org/lapack/lawnspdf/lawn155.pdf">An * Implementation of the dqds Algorithm (Positive Case)</a> and on the * corresponding LAPACK routine DLAZQ3.</p> * @param start start index * @param end end index * @return new end (maybe deflated) */ private int goodStep(final int start, final int end) { g = 0.0; // step 1: accepting realEigenvalues int deflatedEnd = end; for (boolean deflating = true; deflating;) { if (start >= deflatedEnd) { // the array has been completely deflated return deflatedEnd; } final int k = 4 * deflatedEnd + pingPong - 1; if ((start == deflatedEnd - 1) || ((start != deflatedEnd - 2) && ((work[k - 5] <= TOLERANCE_2 * (sigma + work[k - 3])) || (work[k - 2 * pingPong - 4] <= TOLERANCE_2 * work[k - 7])))) { // one eigenvalue found, deflate array work[4 * deflatedEnd - 4] = sigma + work[4 * deflatedEnd - 4 + pingPong]; deflatedEnd -= 1; } else if ((start == deflatedEnd - 2) || (work[k - 9] <= TOLERANCE_2 * sigma) || (work[k - 2 * pingPong - 8] <= TOLERANCE_2 * work[k - 11])) { // two realEigenvalues found, deflate array if (work[k - 3] > work[k - 7]) { final double tmp = work[k - 3]; work[k - 3] = work[k - 7]; work[k - 7] = tmp; } if (work[k - 5] > TOLERANCE_2 * work[k - 3]) { double t = 0.5 * ((work[k - 7] - work[k - 3]) + work[k - 5]); double s = work[k - 3] * (work[k - 5] / t); if (s <= t) { s = work[k - 3] * work[k - 5] / (t * (1 + Math.sqrt(1 + s / t))); } else { s = work[k - 3] * work[k - 5] / (t + Math.sqrt(t * (t + s))); } t = work[k - 7] + (s + work[k - 5]); work[k - 3] *= work[k - 7] / t; work[k - 7] = t; } work[4 * deflatedEnd - 8] = sigma + work[k - 7]; work[4 * deflatedEnd - 4] = sigma + work[k - 3]; deflatedEnd -= 2; } else { // no more realEigenvalues found, we need to iterate deflating = false; } } final int l = 4 * deflatedEnd + pingPong - 1; // step 2: flip array if needed if ((dMin <= 0) || (deflatedEnd < end)) { if (flipIfWarranted(deflatedEnd, 1)) { dMin2 = Math.min(dMin2, work[l - 1]); this.main = main.clone(); cachedD = null; final int p = main.length; dMin = -0.0; } } if ((dMin < 0) || (MathUtils.SAFE_MIN * qMax < Math.min(work[l - 1], Math.min(work[l - 9], dMin2 + work[l - 2 * pingPong])))) { // step 3: choose a shift computeShiftIncrement(start, deflatedEnd, end - deflatedEnd); // step 4a: dqds for (boolean loop = true; loop;) { // perform one dqds step with the chosen shift dqds(start, deflatedEnd); // check result of the dqds step if ((dMin >= 0) && (dMin1 > 0)) { // the shift was good updateSigma(tau); return deflatedEnd; } else if ((dMin < 0.0) && (dMin1 > 0.0) && (work[4 * deflatedEnd - 5 - pingPong] < TOLERANCE * (sigma + dN1)) && (Math.abs(dN) < TOLERANCE * sigma)) { dMin = 0.0; updateSigma(tau); tType = -7; return deflatedEnd; } else if (dMin < 0.0) { // tau too big. Select new tau and try again. if (tType < -22) { // failed twice. Play it safe. tau = 0.0; } else if (dMin1 > 0.0) { // late failure. Gives excellent shift. tau = (tau + dMin) * (1.0 - 2.0 * MathUtils.EPSILON); tType -= 11; } else { // early failure. Divide by 4. tau *= 0.25; tType -= 12; } } else if (Double.isNaN(dMin)) { tau = 0.0; } else { // possible underflow. Play it safe. loop = false; } } } // perform a dqd step (i.e. no shift) dqd(start, deflatedEnd); return deflatedEnd; } /** * Flip qd array if warranted. * @param n number of rows in the block * @param step within the array (1 for flipping all elements, 2 for flipping * only every other element) * @return true if qd array was flipped */ private boolean flipIfWarranted(final int n, final int step) { if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) { double s = 0.333 * dMin1; // flip array int j = 4 * n - 1; if (dMin1 == dN1) { tau = 0.5 * dMin1; } } return false; } /** * Compute an interval containing all realEigenvalues of a block. * @param index index of the first row of the block * @param n number of rows of the block * @return an interval containing the realEigenvalues */ private double[] eigenvaluesRange(final int index, final int n) { // find the bounds of the spectra of the local block final int lowerStart = 4 * main.length; final int upperStart = 5 * main.length; double lower = Double.POSITIVE_INFINITY; double upper = Double.NEGATIVE_INFINITY; for (int i = 0; i < n; ++i) { lower = Math.min(lower, work[lowerStart + index +i]); upper = Math.max(upper, work[upperStart + index +i]); } // set thresholds final double tNorm = Math.max(Math.abs(lower), Math.abs(upper)); final double relativeTolerance = Math.sqrt(MathUtils.EPSILON); final double absoluteTolerance = 4 * minPivot; final int maxIter = 2 + (int) ((Math.log(tNorm + minPivot) - Math.log(minPivot)) / Math.log(2.0)); final double margin = 2 * (tNorm * MathUtils.EPSILON * n + 2 * minPivot); // search lower eigenvalue double left = lower - margin; double right = upper + margin; for (int i = 0; i < maxIter; ++i) { final double range = right - left; if ((range < absoluteTolerance) || (range < relativeTolerance * Math.max(Math.abs(left), Math.abs(right)))) { // search has converged break; } final double middle = 0.5 * (left + right); if (countEigenValues(middle, index, n) >= 1) { right = middle; } else { left = middle; } } lower = Math.max(lower, left - 100 * MathUtils.EPSILON * Math.abs(left)); // search upper eigenvalue left = lower - margin; right = upper + margin; for (int i = 0; i < maxIter; ++i) { final double range = right - left; if ((range < absoluteTolerance) || (range < relativeTolerance * Math.max(Math.abs(left), Math.abs(right)))) { // search has converged break; } final double middle = 0.5 * (left + right); if (countEigenValues(middle, index, n) >= n) { right = middle; } else { left = middle; } } upper = Math.min(upper, right + 100 * MathUtils.EPSILON * Math.abs(right)); return new double[] { lower, upper }; } /** * Count the number of realEigenvalues below a point. * @param t value below which we must count the number of realEigenvalues * @param index index of the first row of the block * @param n number of rows of the block * @return number of realEigenvalues smaller than t */ private int countEigenValues(final double t, final int index, final int n) { double ratio = main[index] - t; int count = (ratio > 0) ? 0 : 1; for (int i = 1; i < n; ++i) { ratio = main[index + i] - squaredSecondary[index + i - 1] / ratio - t; if (ratio <= 0) { ++count; } } return count; } /** * Decompose the shifted tridiagonal matrix T-&lambda;I as LDL<sup>T</sup>. * <p>A shifted symmetric tridiagonal matrix T can be decomposed as * LDL<sup>T</sup> where L is a lower bidiagonal matrix with unit diagonal * and D is a diagonal matrix. This method is an implementation of * algorithm 4.4.7 from Dhillon's thesis.</p> * @param lambda shift to add to the matrix before decomposing it * to ensure it is positive definite * @param index index of the first row of the block * @param n number of rows of the block */ private void ldlTDecomposition(final double lambda, final int index, final int n) { double di = main[index] - lambda; work[0] = Math.abs(di); for (int i = 1; i < n; ++i) { final int fourI = 4 * i; final double eiM1 = secondary[index + i - 1]; final double ratio = eiM1 / di; work[fourI - 2] = ratio * ratio * Math.abs(di); di = (main[index + i] - lambda) - eiM1 * ratio; work[fourI] = Math.abs(di); } } /** * Perform a dqds step, using current shift increment. * <p>This implementation is a translation of the LAPACK routine DLASQ5.</p> * @param start start index * @param end end index */ private void dqds(final int start, final int end) { eMin = work[4 * start + pingPong + 4]; double d = work[4 * start + pingPong] - tau; dMin = d; dMin1 = -work[4 * start + pingPong]; if (pingPong == 0) { for (int j4 = 4 * start + 3; j4 <= 4 * (end - 3); j4 += 4) { work[j4 - 2] = d + work[j4 - 1]; final double tmp = work[j4 + 1] / work[j4 - 2]; d = d * tmp - tau; dMin = Math.min(dMin, d); work[j4] = work[j4 - 1] * tmp; eMin = Math.min(work[j4], eMin); } } else { for (int j4 = 4 * start + 3; j4 <= 4 * (end - 3); j4 += 4) { work[j4 - 3] = d + work[j4]; final double tmp = work[j4 + 2] / work[j4 - 3]; d = d * tmp - tau; dMin = Math.min(dMin, d); work[j4 - 1] = work[j4] * tmp; eMin = Math.min(work[j4 - 1], eMin); } } // unroll last two steps. dN2 = d; dMin2 = dMin; int j4 = 4 * (end - 2) - pingPong - 1; int j4p2 = j4 + 2 * pingPong - 1; work[j4 - 2] = dN2 + work[j4p2]; work[j4] = work[j4p2 + 2] * (work[j4p2] / work[j4 - 2]); dN1 = work[j4p2 + 2] * (dN2 / work[j4 - 2]) - tau; dMin = Math.min(dMin, dN1); dMin1 = dMin; j4 = j4 + 4; j4p2 = j4 + 2 * pingPong - 1; work[j4 - 2] = dN1 + work[j4p2]; work[j4] = work[j4p2 + 2] * (work[j4p2] / work[j4 - 2]); dN = work[j4p2 + 2] * (dN1 / work[j4 - 2]) - tau; dMin = Math.min(dMin, dN); work[j4 + 2] = dN; work[4 * end - pingPong - 1] = eMin; } /** * Perform a dqd step. * <p>This implementation is a translation of the LAPACK routine DLASQ6.</p> * @param start start index * @param end end index */ private void dqd(final int start, final int end) { eMin = work[4 * start + pingPong + 4]; double d = work[4 * start + pingPong]; dMin = d; if (pingPong == 0) { for (int j4 = 4 * start + 3; j4 < 4 * (end - 3); j4 += 4) { work[j4 - 2] = d + work[j4 - 1]; if (work[j4 - 2] == 0.0) { work[j4] = 0.0; d = work[j4 + 1]; dMin = d; eMin = 0.0; } else if ((MathUtils.SAFE_MIN * work[j4 + 1] < work[j4 - 2]) && (MathUtils.SAFE_MIN * work[j4 - 2] < work[j4 + 1])) { final double tmp = work[j4 + 1] / work[j4 - 2]; work[j4] = work[j4 - 1] * tmp; d *= tmp; } else { work[j4] = work[j4 + 1] * (work[j4 - 1] / work[j4 - 2]); d *= work[j4 + 1] / work[j4 - 2]; } dMin = Math.min(dMin, d); eMin = Math.min(eMin, work[j4]); } } else { for (int j4 = 4 * start + 3; j4 < 4 * (end - 3); j4 += 4) { work[j4 - 3] = d + work[j4]; if (work[j4 - 3] == 0.0) { work[j4 - 1] = 0.0; d = work[j4 + 2]; dMin = d; eMin = 0.0; } else if ((MathUtils.SAFE_MIN * work[j4 + 2] < work[j4 - 3]) && (MathUtils.SAFE_MIN * work[j4 - 3] < work[j4 + 2])) { final double tmp = work[j4 + 2] / work[j4 - 3]; work[j4 - 1] = work[j4] * tmp; d *= tmp; } else { work[j4 - 1] = work[j4 + 2] * (work[j4] / work[j4 - 3]); d *= work[j4 + 2] / work[j4 - 3]; } dMin = Math.min(dMin, d); eMin = Math.min(eMin, work[j4 - 1]); } } // Unroll last two steps dN2 = d; dMin2 = dMin; int j4 = 4 * (end - 2) - pingPong - 1; int j4p2 = j4 + 2 * pingPong - 1; work[j4 - 2] = dN2 + work[j4p2]; if (work[j4 - 2] == 0.0) { lowerSpectra = Double.POSITIVE_INFINITY; tau = 0; this.main = main.clone(); eMin = 0.0; } else if ((MathUtils.SAFE_MIN * work[j4p2 + 2] < work[j4 - 2]) && (MathUtils.SAFE_MIN * work[j4 - 2] < work[j4p2 + 2])) { final double tmp = work[j4p2 + 2] / work[j4 - 2]; work[j4] = work[j4p2] * tmp; dN1 = dN2 * tmp; } else { work[j4] = work[j4p2 + 2] * (work[j4p2] / work[j4 - 2]); dN1 = work[j4p2 + 2] * (dN2 / work[j4 - 2]); } dMin = Math.min(dMin, dN1); dMin1 = dMin; j4 = j4 + 4; j4p2 = j4 + 2 * pingPong - 1; work[j4 - 2] = dN1 + work[j4p2]; if (work[j4 - 2] == 0.0) { upperSpectra = Double.NEGATIVE_INFINITY; dMin = 0.0; double sum2 = 0; tau *= 0.25; eMin = 0.0; } else if ((MathUtils.SAFE_MIN * work[j4p2 + 2] < work[j4 - 2]) && (MathUtils.SAFE_MIN * work[j4 - 2] < work[j4p2 + 2])) { final double tmp = work[j4p2 + 2] / work[j4 - 2]; work[j4] = work[j4p2] * tmp; dN = dN1 * tmp; } else { double upper = Double.NEGATIVE_INFINITY; imagEigenvalues = new double[main.length]; imagEigenvalues = new double[main.length]; } dMin = Math.min(dMin, dN); work[j4 + 2] = dN; work[4 * end - pingPong - 1] = eMin; } /** * Compute the shift increment as an estimate of the smallest eigenvalue. * <p>This implementation is a translation of the LAPACK routine DLAZQ4.</p> * @param start start index * @param end end index * @param deflated number of realEigenvalues just deflated */ private void computeShiftIncrement(final int start, final int end, final int deflated) { final double cnst1 = 0.563; final double cnst2 = 1.010; final double cnst3 = 1.05; // a negative dMin forces the shift to take that absolute value // tType records the type of shift. if (dMin <= 0.0) { tau = -dMin; tType = -1; return; } int nn = 4 * end + pingPong - 1; switch (deflated) { case 0 : // no realEigenvalues deflated. if (dMin == dN || dMin == dN1) { double b1 = Math.sqrt(work[nn - 3]) * Math.sqrt(work[nn - 5]); double b2 = Math.sqrt(work[nn - 7]) * Math.sqrt(work[nn - 9]); double a2 = work[nn - 7] + work[nn - 5]; if (dMin == dN && dMin1 == dN1) { // cases 2 and 3. final double gap2 = dMin2 - a2 - dMin2 * 0.25; final double gap1 = a2 - dN - ((gap2 > 0.0 && gap2 > b2) ? (b2 / gap2) * b2 : (b1 + b2)); if (gap1 > 0.0 && gap1 > b1) { tau = Math.max(dN - (b1 / gap1) * b1, 0.5 * dMin); tType = -2; } else { double s = 0.0; if (dN > b1) { s = dN - b1; } if (a2 > (b1 + b2)) { s = Math.min(s, a2 - (b1 + b2)); } tau = Math.max(s, 0.333 * dMin); tType = -3; } } else { // case 4. tType = -4; double s = 0.25 * dMin; double gam; int np; if (dMin == dN) { gam = dN; a2 = 0.0; if (work[nn - 5] > work[nn - 7]) { return; } b2 = work[nn - 5] / work[nn - 7]; np = nn - 9; } else { np = nn - 2 * pingPong; b2 = work[np - 2]; gam = dN1; if (work[np - 4] > work[np - 2]) { return; } a2 = work[np - 4] / work[np - 2]; if (work[nn - 9] > work[nn - 11]) { return; } b2 = work[nn - 9] / work[nn - 11]; np = nn - 13; } // approximate contribution to norm squared from i < nn-1. a2 = a2 + b2; for (int i4 = np; i4 >= 4 * start + 2 + pingPong; i4 -= 4) { if(b2 == 0.0) { break; } b1 = b2; if (work[i4] > work[i4 - 2]) { return; } b2 = b2 * (work[i4] / work[i4 - 2]); a2 = a2 + b2; if (100 * Math.max(b2, b1) < a2 || cnst1 < a2) { break; } } a2 = cnst3 * a2; // rayleigh quotient residual bound. if (a2 < cnst1) { s = gam * (1 - Math.sqrt(a2)) / (1 + a2); } tau = s; } } else if (dMin == dN2) { // case 5. tType = -5; double s = 0.25 * dMin; // compute contribution to norm squared from i > nn-2. final int np = nn - 2 * pingPong; double b1 = work[np - 2]; double b2 = work[np - 6]; final double gam = dN2; if (work[np - 8] > b2 || work[np - 4] > b1) { return; } double a2 = (work[np - 8] / b2) * (1 + work[np - 4] / b1); // approximate contribution to norm squared from i < nn-2. if (end - start > 3) { b2 = work[nn - 13] / work[nn - 15]; a2 = a2 + b2; for (int i4 = nn - 17; i4 >= 4 * start + 2 + pingPong; i4 -= 4) { if (b2 == 0.0) { break; } b1 = b2; if (work[i4] > work[i4 - 2]) { return; } b2 = b2 * (work[i4] / work[i4 - 2]); a2 = a2 + b2; if (100 * Math.max(b2, b1) < a2 || cnst1 < a2) { break; } } a2 = cnst3 * a2; } if (a2 < cnst1) { tau = gam * (1 - Math.sqrt(a2)) / (1 + a2); } else { tau = s; } } else { // case 6, no information to guide us. if (tType == -6) { g += 0.333 * (1 - g); } else if (tType == -18) { g = 0.25 * 0.333; } else { g = 0.25; } tau = g * dMin; tType = -6; } break; case 1 : // one eigenvalue just deflated. use dMin1, dN1 for dMin and dN. if (dMin1 == dN1 && dMin2 == dN2) { // cases 7 and 8. tType = -7; double s = 0.333 * dMin1; if (work[nn - 5] > work[nn - 7]) { return; } double b1 = work[nn - 5] / work[nn - 7]; double b2 = b1; if (b2 != 0.0) { for (int i4 = 4 * end - 10 + pingPong; i4 >= 4 * start + 2 + pingPong; i4 -= 4) { final double oldB1 = b1; if (work[i4] > work[i4 - 2]) { return; } b1 = b1 * (work[i4] / work[i4 - 2]); b2 = b2 + b1; if (100 * Math.max(b1, oldB1) < b2) { break; } } } b2 = Math.sqrt(cnst3 * b2); final double a2 = dMin1 / (1 + b2 * b2); final double gap2 = 0.5 * dMin2 - a2; if (gap2 > 0.0 && gap2 > b2 * a2) { tau = Math.max(s, a2 * (1 - cnst2 * a2 * (b2 / gap2) * b2)); } else { tau = Math.max(s, a2 * (1 - cnst2 * b2)); tType = -8; } } else { // case 9. tau = 0.25 * dMin1; if (dMin1 == dN1) { tau = 0.5 * dMin1; } tType = -9; } break; case 2 : // two realEigenvalues deflated. use dMin2, dN2 for dMin and dN. // cases 10 and 11. if (dMin2 == dN2 && 2 * work[nn - 5] < work[nn - 7]) { tType = -10; final double s = 0.333 * dMin2; if (work[nn - 5] > work[nn - 7]) { return; } double b1 = work[nn - 5] / work[nn - 7]; double b2 = b1; if (b2 != 0.0){ for (int i4 = 4 * end - 9 + pingPong; i4 >= 4 * start + 2 + pingPong; i4 -= 4) { if (work[i4] > work[i4 - 2]) { return; } b1 *= work[i4] / work[i4 - 2]; b2 += b1; if (100 * b1 < b2) { break; } } } b2 = Math.sqrt(cnst3 * b2); final double a2 = dMin2 / (1 + b2 * b2); final double gap2 = work[nn - 7] + work[nn - 9] - Math.sqrt(work[nn - 11]) * Math.sqrt(work[nn - 9]) - a2; if (gap2 > 0.0 && gap2 > b2 * a2) { tau = Math.max(s, a2 * (1 - cnst2 * a2 * (b2 / gap2) * b2)); } else { tau = Math.max(s, a2 * (1 - cnst2 * b2)); } } else { tau = 0.25 * dMin2; tType = -11; } break; default : // case 12, more than two realEigenvalues deflated. no information. tau = 0.0; tType = -12; } } /** * Update sigma. * @param shift shift to apply to sigma */ private void updateSigma(final double shift) { // BEWARE: do NOT attempt to simplify the following statements // the expressions below take care to accumulate the part of sigma // that does not fit within a double variable into sigmaLow if (shift < sigma) { sigmaLow += shift; final double t = sigma + sigmaLow; sigmaLow -= t - sigma; sigma = t; } else { final double t = sigma + shift; sigmaLow += sigma - (t - shift); sigma = t; } } /** * Find eigenvectors. */ private void findEigenVectors() { final int m = main.length; eigenvectors = new ArrayRealVector[m]; // perform an initial non-shifted LDLt decomposition final double[] d = new double[m]; final double[] l = new double[m - 1]; // avoid zero divide on indefinite matrix final double mu = realEigenvalues[m-1] <= 0 && realEigenvalues[0] > 0 ? 0.5-realEigenvalues[m-1] : 0; double di = main[0]+mu; d[0] = di; for (int i = 1; i < m; ++i) { final double eiM1 = secondary[i - 1]; final double ratio = eiM1 / di; di = main[i] - eiM1 * ratio + mu; l[i - 1] = ratio; d[i] = di; } // compute eigenvectors for (int i = 0; i < m; ++i) { eigenvectors[i] = findEigenvector(realEigenvalues[i]+mu, d, l); } } /** * Find an eigenvector corresponding to an eigenvalue, using bidiagonals. * <p>This method corresponds to algorithm X from Dhillon's thesis.</p> * * @param eigenvalue eigenvalue for which eigenvector is desired * @param d diagonal elements of the initial non-shifted D matrix * @param l off-diagonal elements of the initial non-shifted L matrix * @return an eigenvector */ private ArrayRealVector findEigenvector(final double eigenvalue, final double[] d, final double[] l) { // compute the LDLt and UDUt decompositions of the // perfectly shifted tridiagonal matrix final int m = main.length; stationaryQuotientDifferenceWithShift(d, l, eigenvalue); progressiveQuotientDifferenceWithShift(d, l, eigenvalue); // select the twist index leading to // the least diagonal element in the twisted factorization int r = m - 1; double minG = Math.abs(work[6 * r] + work[6 * r + 3] + eigenvalue); int sixI = 0; for (int i = 0; i < m - 1; ++i) { final double absG = Math.abs(work[sixI] + d[i] * work[sixI + 9] / work[sixI + 10]); if (absG < minG) { r = i; minG = absG; } sixI += 6; } // solve the singular system by ignoring the equation // at twist index and propagating upwards and downwards double[] eigenvector = new double[m]; double n2 = 1; eigenvector[r] = 1; double z = 1; for (int i = r - 1; i >= 0; --i) { z *= -work[6 * i + 2]; eigenvector[i] = z; n2 += z * z; } z = 1; for (int i = r + 1; i < m; ++i) { z *= -work[6 * i - 1]; eigenvector[i] = z; n2 += z * z; } // normalize vector final double inv = 1.0 / Math.sqrt(n2); for (int i = 0; i < m; ++i) { eigenvector[i] *= inv; } return (transformer == null) ? new ArrayRealVector(eigenvector, false) : new ArrayRealVector(transformer.getQ().operate(eigenvector), false); } /** * Decompose matrix LDL<sup>T</sup> - &lambda; I as * L<sub>+</sub>D<sub>+</sub>L<sub>+</sub><sup>T</sup>. * <p>This method corresponds to algorithm 4.4.3 (dstqds) from Dhillon's thesis.</p> * @param d diagonal elements of D, * @param l off-diagonal elements of L * @param lambda shift to apply */ private void stationaryQuotientDifferenceWithShift(final double[] d, final double[] l, final double lambda) { final int nM1 = d.length - 1; double si = -lambda; int sixI = 0; for (int i = 0; i < nM1; ++i) { final double di = d[i]; final double li = l[i]; final double diP1 = di + si; final double liP1 = li * di / diP1; work[sixI] = si; work[sixI + 1] = diP1; work[sixI + 2] = liP1; si = li * liP1 * si - lambda; sixI += 6; } work[6 * nM1 + 1] = d[nM1] + si; work[6 * nM1] = si; } /** * Decompose matrix LDL<sup>T</sup> - &lambda; I as * U<sub>-</sub>D<sub>-</sub>U<sub>-</sub><sup>T</sup>. * <p>This method corresponds to algorithm 4.4.5 (dqds) from Dhillon's thesis.</p> * @param d diagonal elements of D * @param l off-diagonal elements of L * @param lambda shift to apply */ private void progressiveQuotientDifferenceWithShift(final double[] d, final double[] l, final double lambda) { final int nM1 = d.length - 1; double pi = d[nM1] - lambda; int sixI = 6 * (nM1 - 1); for (int i = nM1 - 1; i >= 0; --i) { final double di = d[i]; final double li = l[i]; final double diP1 = di * li * li + pi; final double t = di / diP1; work[sixI + 9] = pi; work[sixI + 10] = diP1; work[sixI + 5] = li * t; pi = pi * t - lambda; sixI -= 6; } work[3] = pi; work[4] = pi; } }
[ "he_ye_90s@hotmail.com" ]
he_ye_90s@hotmail.com
e506a62c51b00274b9b3bb4bdbcf24bcb58901e2
6db130e6a3a5965c7b0b2eb681399638cf0a2205
/ncnn_mobileNet/app/src/androidTest/java/com/nanamare/mac/mobilenet/ExampleInstrumentedTest.java
1a654a51dc2cad88f246d365c337ed72051773f5
[]
no_license
Lelouish/android_ncnn_mobilenet_classification
6f2ed1f6e3d394a8b4b48b1b68c6e5a95f03b672
712d2e4d3b4122bab734dad14be1e758543fd0dd
refs/heads/master
2021-10-10T06:28:50.320349
2019-01-07T15:24:12
2019-01-07T15:24:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
736
java
package com.nanamare.mac.mobilenet; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.nanamare.mac.mobilenet", appContext.getPackageName()); } }
[ "hyunsung.shin@continuumai.co.kr" ]
hyunsung.shin@continuumai.co.kr
446dc9d5538f1185bf1138c19af126e903b58b01
2653141da7c4b0bd78a6ae78c473d21a62af72e6
/src/main/java/com/seckillhigh/service/Impl/SecKillHighService.java
4673cc3940e72d6d504e7db6e1af6f5d1d47420a
[]
no_license
boya-zhou/lightning-deal
5abd76624d2bfbb8b849c8950b2e6dc2ba73da11
024e79d1721527c7f07c60fbd1252564620d950a
refs/heads/master
2020-03-29T07:51:02.611621
2018-09-24T17:58:36
2018-09-24T17:58:36
149,681,757
0
0
null
null
null
null
UTF-8
Java
false
false
3,211
java
package com.seckillhigh.service.Impl; import com.seckillhigh.dao.SecKillHighUserDao; import com.seckillhigh.entity.SecKillHighUser; import com.seckillhigh.exception.GlobalException; import com.seckillhigh.redis.RedisDao; import com.seckillhigh.redis.keyprefix.SeckillKeyPrefix; import com.seckillhigh.result.CodeMsg; import com.seckillhigh.utils.CookieUtil; import com.seckillhigh.utils.Md5; import com.seckillhigh.utils.UUIDUtil; import com.seckillhigh.vo.LoginVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Service public class SecKillHighService { public static final String COOKIE_NAME_TOKEN = "cookie_uuid"; @Autowired SecKillHighUserDao secKillHighUserDao; @Autowired RedisDao<SecKillHighUser> redisDao; public SecKillHighUser queryUser(Long phoneId) { return secKillHighUserDao.queryUser(phoneId); } public SecKillHighUser getUserByToken(HttpServletResponse response, String token){ if (StringUtils.isEmpty(token)){ return null; } SecKillHighUser secKillHighUser = redisDao.getSingleEle(SeckillKeyPrefix.token, token); if (secKillHighUser != null){ addCookie(response, secKillHighUser, token); } return secKillHighUser; } public Boolean doLogin(HttpServletResponse response, LoginVo loginVo, HttpServletRequest request, SecKillHighUser secKillHighUser) { String cookieToken; cookieToken = CookieUtil.getCookie(request, SecKillHighService.COOKIE_NAME_TOKEN); if (secKillHighUser == null){ secKillHighUser = secKillHighUserDao.queryUser(Long.valueOf(loginVo.getMobile())); cookieToken = UUIDUtil.uuid().replace("-", ""); } if (secKillHighUser == null) { throw new GlobalException(CodeMsg.NO_USER_ERROR); } String finalPassWord = Md5.formPassToDB(loginVo.getPassword(), secKillHighUser.getSalt()); if (!secKillHighUser.getPassword().equals(finalPassWord)) { // TODO add code for another user login with not match cookie throw new GlobalException(CodeMsg.PASSCODE_ERROR); } addCookie(response, secKillHighUser, cookieToken); return true; } private void addCookie(HttpServletResponse response, SecKillHighUser secKillHighUser, String token) { redisDao.saveSingleEle(SeckillKeyPrefix.token, token, secKillHighUser); Cookie tokenCookie = new Cookie(COOKIE_NAME_TOKEN, token); tokenCookie.setMaxAge(SeckillKeyPrefix.EXPIRE_TOKEN); tokenCookie.setPath("/"); response.addCookie(tokenCookie); } /** * Generate fake user for testing, do not use it in real * @Warning * @param secKillHighUser */ @Transactional public void insertUser(SecKillHighUser secKillHighUser){ secKillHighUserDao.insertUser(secKillHighUser); } }
[ "boyazhou1993@gmail.com" ]
boyazhou1993@gmail.com
53bd797a6f08800dbecf7c02f1051b39c44fa618
a5e57b27467f18bc515ed0430b181b78e20ec4f6
/Exam2021/core/src/main/java/domain/BaseEntity.java
6009d55225bd50365126231a33057aeaf3f9ebbb
[]
no_license
andreimoldovan23/SDI
15c8d9e0ada673a10cb36613b7dada4f608ff5ef
a5167ecf37b0404769c8d18e2c4fb34bb06e6285
refs/heads/master
2023-05-30T17:19:31.274486
2021-06-11T17:31:55
2021-06-11T17:31:55
362,459,873
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package domain; import lombok.*; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import java.io.Serializable; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString @MappedSuperclass public abstract class BaseEntity<ID> implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private ID id; }
[ "moldovanandrei2301@gmail.com" ]
moldovanandrei2301@gmail.com
0ca98b8b500eb1eb32d920f5d17d37a8d6eef90c
f4c51f527564a4300a3dc593ac11ffb5b3cc131d
/java/java_src/src/com/bixly/pastevid/screencap/components/IAudioObserver.java
3b0f9f6c8bb3fec5babc7b040842f370b50f5cb9
[ "MIT" ]
permissive
benoneb/screenbird
b63e876fe626a7b3ff8f96220d2341e220de6d8b
ae5129eecd8151c47ebc44765311ddf5a8fa5ec9
refs/heads/master
2021-06-10T01:56:38.006648
2017-01-22T16:37:39
2017-01-22T16:37:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package com.bixly.pastevid.screencap.components; /** * @author Bixly */ public interface IAudioObserver { public void update(IAudioSubject subject); }
[ "randol@bixly.com" ]
randol@bixly.com
920435bb91c560151da6abbfe49f810d824cd705
82674ee6761c97390bb5c322c243662ffa808729
/tree-inorder-traversal.java
0f0391cd55d18889960741408e333e64d59c286d
[]
no_license
sanket-tadigital/HackerRank_Sanket_Repo
e0fc741fbcc5203b3e3a3a87f5dafde8ef3c4480
ee6ded8eae5baa666378aa53eefdd22426a63f42
refs/heads/master
2020-05-07T08:12:52.791841
2019-06-18T10:32:24
2019-06-18T10:32:24
180,315,847
0
0
null
null
null
null
UTF-8
Java
false
false
1,297
java
import java.util.*; import java.io.*; class Node { Node left; Node right; int data; Node(int data) { this.data = data; left = null; right = null; } } class Solution { /* you only have to complete the function given below. Node is defined as class Node { int data; Node left; Node right; } */ public static void inOrder(Node root) { if(root==null) return; inOrder(root.left); System.out.print(root.data+" "); inOrder(root.right); } public static Node insert(Node root, int data) { if(root == null) { return new Node(data); } else { Node cur; if(data <= root.data) { cur = insert(root.left, data); root.left = cur; } else { cur = insert(root.right, data); root.right = cur; } return root; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); Node root = null; while(t-- > 0) { int data = scan.nextInt(); root = insert(root, data); } scan.close(); inOrder(root); } }
[ "training.project.sanket@gmail.com" ]
training.project.sanket@gmail.com
9629f4014546fcd2fa1b7b7214006badad8e6245
56aaee1248339ed8317e9cdb3727e3c3e34eb431
/src/main/java/net/mcreator/mysticalrealms/item/OpalGemItem.java
424332cb8f1a4c9723aac1434b48842cdcaf3262
[]
no_license
bdaly3411/EverythingAndMore
5b4e74b44a3b79cd776450c261c36b0b35614423
59c3bf9cc4f08eb45a1bdd1e78d6da0f3df22f5c
refs/heads/master
2023-03-18T23:49:32.134469
2021-03-14T15:06:14
2021-03-14T15:06:14
346,919,922
0
0
null
null
null
null
UTF-8
Java
false
false
1,224
java
package net.mcreator.mysticalrealms.item; import net.minecraftforge.registries.ObjectHolder; import net.minecraft.item.Rarity; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.Item; import net.minecraft.block.BlockState; import net.mcreator.mysticalrealms.MysticalrealmsModElements; @MysticalrealmsModElements.ModElement.Tag public class OpalGemItem extends MysticalrealmsModElements.ModElement { @ObjectHolder("mysticalrealms:opal_gem") public static final Item block = null; public OpalGemItem(MysticalrealmsModElements instance) { super(instance, 88); } @Override public void initElements() { elements.items.add(() -> new ItemCustom()); } public static class ItemCustom extends Item { public ItemCustom() { super(new Item.Properties().group(ItemGroup.MISC).maxStackSize(64).rarity(Rarity.COMMON)); setRegistryName("opal_gem"); } @Override public int getItemEnchantability() { return 0; } @Override public int getUseDuration(ItemStack itemstack) { return 0; } @Override public float getDestroySpeed(ItemStack par1ItemStack, BlockState par2Block) { return 1F; } } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
b494542c5f6d0f71d1d32294283c9b1c6dc86294
2995c423c8a74c549215dc49fe88d43656908d30
/04_Control/src/com/kh/chap01/condition/B_Else.java
731987c6ebf90b937208915134d2714a43b04b48
[]
no_license
YoonHwikyung/myJavaRepo
1d56cf913f83a87db7ce14adcf1e3f2f37af0da5
90d5f3bf2bf107a2bc2ba0923b346d9fb480c445
refs/heads/main
2023-02-24T21:13:23.875329
2021-01-30T10:21:16
2021-01-30T10:21:16
334,326,925
0
0
null
null
null
null
UHC
Java
false
false
6,936
java
package com.kh.chap01.condition; // ํ•™์Šต์ฃผ์ œ : ์ œ์–ด๋ฌธ - ์กฐ๊ฑด๋ฌธ - if-else๋ฌธ import java.util.Scanner; public class B_Else { /* * * if-else ๋ฌธ * * if(์กฐ๊ฑด์‹) { * ์‹คํ–‰ ์ฝ”๋“œ1; if์˜ ์กฐ๊ฑด์‹์ด true์ผ ๊ฒฝ์šฐ * }else { * ์‹คํ–‰ ์ฝ”๋“œ2; if์˜ ์กฐ๊ฑด์‹์ด false์ด ๊ฒฝ์šฐ * } * * ์กฐ๊ฑด์‹์˜ ๊ฒฐ๊ณผ๊ฐ€ true์ผ ๊ฒฝ์šฐ ์‹คํ–‰์ฝ”๋“œ1๋งŒ์„ ์ˆ˜ํ–‰ํ•˜๊ณ  if-else๋ฌธ ์ž์ฒด๋ฅผ ๋น ์ ธ๋‚˜๊ฐ * ๋‹จ, ์กฐ๊ฑด์‹์ด false์ผ ๊ฒฝ์šฐ ๋ฌด์กฐ๊ฑด ์‹คํ–‰์ฝ”๋“œ2๋ฅผ ์ˆ˜ํ–‰ํ•จ * * * * if-else if๋ฌธ * ๊ฐ™์€ ๋น„๊ต ๋Œ€์ƒ์œผ๋กœ ์—ฌ๋Ÿฌ๊ฐœ์˜ ์กฐ๊ฑด์„ ์ œ์‹œํ•  ๊ฒฝ์šฐ * * if(์กฐ๊ฑด์‹1) { * ์‹คํ–‰์ฝ”๋“œ1; * }else if(์กฐ๊ฑด์‹2) { * ์‹คํ–‰์ฝ”๋“œ2; * }else if(์กฐ๊ฑด์‹3) { * ์‹คํ–‰ ์ฝ”๋“œ3; * }[else { * ์œ„์˜ ์กฐ๊ฑด๋“ค์ด ๋‹ค false์ผ ๊ฒฝ์šฐ ๋ฐ˜๋“œ์‹œ ์‹คํ–‰ํ•  ์ฝ”๋“œ; * }] ==> [์ƒ๋žต ๊ฐ€๋Šฅ] * * ์กฐ๊ฑด์‹ 1์˜ ๊ฒฐ๊ณผ๊ฐ€ true์ผ ๊ฒฝ์šฐ => ์‹คํ–‰์ฝ”๋“œ1๋งŒ์„ ์‹คํ–‰ํ•˜๊ณ  ์ฝ”๋“œ ์„ธํŠธ ์ž์ฒด๋ฅผ ๋น ์ ธ๋‚˜๊ฐ * ๋‹จ, false์ผ ๊ฒฝ์šฐ => ์กฐ๊ฑด์‹ 2 ์‹คํ–‰ * ์กฐ๊ฑด์‹ 2์˜ ๊ฒฐ๊ณผ๊ฐ€ true์ผ ๊ฒฝ์šฐ => ์‹คํ–‰์ฝ”๋“œ2๋งŒ์„ ์‹คํ–‰ํ•˜๊ณ  ์ฝ”๋“œ ์„ธํŠธ ์ž์ฒด๋ฅผ ๋น ์ ธ๋‚˜๊ฐ * ๋‹จ, false์ผ ๊ฒฝ์šฐ => ์กฐ๊ฑด์‹ 3 ์‹คํ–‰ * ..... * ๋งˆ์ง€๋ง‰์— else๋ฌธ์ด ์ œ์‹œ๋˜์–ด์žˆ์„ ๊ฒฝ์šฐ ์œ„์˜ ์กฐ๊ฑด๋“ค์ด ๋‹ค false์ผ ๊ฒฝ์šฐ ๋ฌด์กฐ๊ฑด else๊ตฌ๋ฌธ ์‹คํ–‰ * */ //์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด ์–ด๋–ค ์ƒํ™ฉ์—์„œ if-else / if-else if๋ฅผ ํ™œ์šฉํ• ์ง€ ๊ณต๋ถ€ํ•ด๋ณด์ž! // ์˜ˆ์‹œ1) ef-else ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ public void method1() { // ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ •์ˆ˜ ๊ฐ’์ด ์ง์ˆ˜/ํ™€์ˆ˜ ์ถœ๋ ฅ Scanner sc = new Scanner(System.in); System.out.print("์ •์ˆ˜ : "); int num = sc.nextInt(); if(num %2 == 0) { System.out.println("์ง์ˆ˜์ž…๋‹ˆ๋‹ค."); // ์กฐ๊ฑด์‹1์ด true๋ผ๋ฉด "์ง์ˆ˜์ž…๋‹ˆ๋‹ค." false๋ผ๋ฉด "ํ™€์ˆ˜์ž…๋‹ˆ๋‹ค." }else { System.out.println("ํ™€์ˆ˜์ž…๋‹ˆ๋‹ค."); } } // ์˜ˆ์‹œ2) if-else if ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ public void method2() { // ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ •์ˆ˜ ๊ฐ’์ด ์–‘์ˆ˜/0/์Œ์ˆ˜์ธ์ง€ Scanner sc = new Scanner(System.in); System.out.print("์ •์ˆ˜ : "); int num = sc.nextInt(); if(num > 0) { System.out.println("์–‘์ˆ˜๋‹ค"); }else if(num == 0){ System.out.println("0์ด๋‹ค"); }else { System.out.println("์Œ์ˆ˜๋‹ค"); } } // if-else if ์ค‘์ฒฉ์‚ฌ์šฉ public void method3() { // ์–ด๋ฆฐ์ด / ์ฒญ์†Œ๋…„ /์–ด๋ฅธ Scanner sc = new Scanner(System.in); System.out.print("๋‚˜์ด(์ •์ˆ˜๋งŒ) : "); int age = sc.nextInt(); // ์–ด๋ฆฐ์ด(0์ด์ƒ 13์ดํ•˜) / ์ฒญ์†Œ๋…„(13์ดˆ๊ณผ 19์ดํ•˜) / ์„ฑ์ธ(19์ดˆ๊ณผ) /* if(age >= 0 && age <= 13) { System.out.println("์–ด๋ฆฐ์ด"); }else if(age > 13 && age <= 19) { System.out.println("์ฒญ์†Œ๋…„"); }else if(age > 19) { System.out.println("์„ฑ์ธ"); // => ๋งˆ์ง€๋ง‰์„ else๋กœ ํ–ˆ์„ ๊ฒฝ์šฐ : -10์„ ์ž…๋ ฅ์„ ํ–ˆ์–ด๋„ "์„ฑ์ธ"์œผ๋กœ ๋œธ. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— else๊ฐ€ ์•„๋‹Œ else if๋กœ ์ •ํ™•ํ•œ ์กฐ๊ฑด์„ ์ž‘์„ฑ! // => else๋กœ ๊ผญ ๋งˆ๋ฌด๋ฆฌ๋ฅผ ํ•ด์•ผํ•˜๋Š” ๊ฒƒ์€ ์•„๋‹ˆ๋‹ค! }else { System.out.println("์ž˜๋ชป์ž…๋ ฅํ•˜์…จ์Šต๋‹ˆ๋‹ค"); } */ // ์œ„์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ๋„์ถœํ•˜์ง€๋งŒ if-else if [์ค‘์ฒฉ์‚ฌ์šฉ] ํ•ด๋ณด์ž! if(age < 0) { // ๋‚˜์ด๊ฐ’์„ ์ž…๋ ฅํ•ด์•ผ ํ•˜๋Š”๋ฐ ์Œ์ˆ˜๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ=>์ž˜๋ชป ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ System.out.println("์ž˜๋ชป์ž…๋ ฅํ•˜์…จ์Šต๋‹ˆ๋‹ค."); }else { // ์ž˜ ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ => 0 ์ด์ƒ์˜ ๊ฐ’์„ ์ž˜ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ if(age <= 13) { // ์ด๋ฏธ 0 ์ด์ƒ ๊ฐ’์„ ์ž˜ ์ž…๋ ฅํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋„˜์–ด์˜จ ๋‹จ๊ณ„ : ์กฐ๊ฑด๋ฌธ์— age >=0 ์“ฐ์ง€ ์•Š์•„๋„ ๋œ๋‹ค. System.out.println("์–ด๋ฆฐ์ด"); }else if(age <= 19) { //์ด๋ฏธ ์œ„์—์„œ age๊ฐ€ 13์ดˆ๊ณผ์—ฌ์„œ ๋„˜์–ด์™”๊ธฐ ๋•Œ๋ฌธ์— age > 13 ์“ฐ์ง€ ์•Š์•„๋„ ๋œ๋‹ค. System.out.println("์ฒญ์†Œ๋…„"); }else { // ์œ„์—์„œ ์ด๋ฏธ 0์ด์ƒ ๊ฐ’์„ ์ž˜ ์ž…๋ ฅํ•ด์„œ ์˜จ ๋‹จ๊ณ„์ด๊ธฐ ๋•Œ๋ฌธ์— else๋กœ ๋งˆ๋ฌด๋ฆฌํ•ด๋„ ์˜ค๋ฅ˜๋ฅผ ๋ฒ”ํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์—†๋‹ค! System.out.println("์„ฑ์ธ"); } // == > ์ด๋ฏธ ์ œ์‹œ๋˜์–ด ์žˆ๋˜ ๊ฒƒ์€ ๋ถˆํ•„์š”ํ•œ ๊ฒƒ์€ ์“ธ ํ•„์š”๊ฐ€ ์—†๋‹ค! } } // if-else if ์ค‘์ฒฉ์‚ฌ์šฉ ์—ฐ์Šต๋ฌธ์ œ public void method4() { // ์‚ฌ์šฉ์ž์—๊ฒŒ ์ ์ˆ˜๋ฅผ ์ž…๋ ฅ ๋ฐ›์•„ // ์ ์ˆ˜๋ณ„๋กœ ๋“ฑ๊ธ‰์„ ๋‚˜๋ˆ  ์ถœ๋ ฅ // 90์  ์ด์ƒ์ผ ๊ฒฝ์šฐ "A๋“ฑ๊ธ‰" // 90์  ๋ฏธ๋งŒ, 80์  ์ด์ƒ์ผ ๊ฒฝ์šฐ "B๋“ฑ๊ธ‰" // 80์  ๋ฏธ๋งŒ, 70์  ์ด์ƒ์ผ ๊ฒฝ์šฐ "C๋“ฑ๊ธ‰" // 70์  ๋ฏธ๋งŒ, 60์  ์ด์ƒ์ผ ๊ฒฝ์šฐ "D๋“ฑ๊ธ‰" // 60์  ๋ฏธ๋งŒ์ผ ๊ฒฝ์šฐ, "F๋“ฑ๊ธ‰" Scanner sc = new Scanner(System.in); System.out.print("์ ์ˆ˜ : "); int score = sc.nextInt(); String grade = ""; // => ๊ฒฐ๊ณผ๊ฐ’์„ ๋‹ด์„ ๋ณ€์ˆ˜ if(score >= 90) { grade = "A๋“ฑ๊ธ‰"; }else if(score >= 80) { grade = "B๋“ฑ๊ธ‰"; }else if(score >= 70) { grade = "C๋“ฑ๊ธ‰"; }else if(score >= 60) { grade = "D๋“ฑ๊ธ‰"; }else { grade = "F๋“ฑ๊ธ‰"; } // ๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” xx์ ์ด๊ณ , ๋“ฑ๊ธ‰์€ xxx์ž…๋‹ˆ๋‹ค. System.out.println("๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” " + score +"์ ์ด๊ณ , ๋“ฑ๊ธ‰์€ " + grade + "์ž…๋‹ˆ๋‹ค."); /*if(score < 0 || score > 100) { System.out.println("์ž˜๋ชป์ž…๋ ฅํ•˜์…จ์Šต๋‹ˆ๋‹ค."); else { if(score >= 90) { System.out.println("A๋“ฑ๊ธ‰"); }else if(score >= 80) { System.out.println("B๋“ฑ๊ธ‰"); }else if(score >= 70) { System.out.println("C๋“ฑ๊ธ‰"); }else if(score >=60) { System.out.println("D๋“ฑ๊ธ‰"); }else { System.out.println("F๋“ฑ๊ธ‰"); } } } */ } // is else ์—ฐ์Šต (๋ฌธ์ž์—ด ๋™๋“ฑ๋น„๊ต) public void method5() { // ์‚ฌ์šฉ์ž์—๊ฒŒ ์ด๋ฆ„์„ ์ž…๋ ฅ ๋ฐ›์€ ํ›„ Scanner sc = new Scanner(System.in); System.out.print("์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š” : "); String name = sc.nextLine(); // ๊ทธ ์ด๋ฆ„์ด "์œคํœ˜๊ฒฝ"์ด๋ผ๋Š” ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•  ๊ฒฝ์šฐ => "๋ณธ์ธ์ž…๋‹ˆ๋‹ค." // ์ผ์น˜ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ => "๋ณธ์ธ์ด ์•„๋‹™๋‹ˆ๋‹ค. ๋Œ์•„๊ฐ€์ฃผ์„ธ์š”." /* if(name == "์œคํœ˜๊ฒฝ") { System.out.println("๋ณธ์ธ์ž…๋‹ˆ๋‹ค. ์–ด์„œ์˜ค์„ธ์š”."); }else { System.out.println("๋ณธ์ธ์ด ์•„๋‹™๋‹ˆ๋‹ค. ๋Œ์•„๊ฐ€์ฃผ์„ธ์š”."); // string ๋ณ€์ˆ˜์— ๋‹ด์•„์„œ ๊ฒฐ๊ณผ ์˜ค๋ฅ˜! } */ // ๊ธฐ๋ณธ์ž๋ฃŒํ˜•๋“ค ๋ผ๋ฆฌ ๋™๋“ฑ๋น„๊ต(==, !=) ์ž˜ ์ˆ˜ํ–‰์ด ๋œ๋‹ค. // ๋‹จ, String ๊ธฐ๋ณธ ์ž๋ฃŒํ˜•์ด ์•„๋‹Œ ์ฐธ์กฐ ์ž๋ฃŒํ˜•(์ข…ํŠน)์ž„!! => ๋™๋“ฑ๋น„๊ต์—ฐ์‚ฐ์ž๊ฐ€ ์ œ๋Œ€๋กœ ์ˆ˜ํ–‰๋˜์ง€ ์•Š์Œ!! // => ๋ฌธ์ž์—ด ๊ฐ„์˜ ๋™๋“ฑ๋น„๊ต๋ฅผ ํ•˜๋ ค๋ฉด, equals(๋น„๊ตํ•˜๊ณ ์žํ•˜๋Š”๋ฌธ์ž์—ด) ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด์•ผ ํ•œ๋‹ค! // [์‚ฌ์šฉ๋ฒ•] ๋ณ€์ˆ˜.equals("๋น„๊ตํ•˜๊ณ ์žํ•˜๋Š”๋ฌธ์ž์—ด") if(name.equals("์œคํœ˜๊ฒฝ")) { System.out.println("๋ณธ์ธ์ž…๋‹ˆ๋‹ค. ์–ด์„œ์˜ค์„ธ์š”."); }else { System.out.println("๋ณธ์ธ์ด ์•„๋‹™๋‹ˆ๋‹ค. ๋Œ์•„๊ฐ€์ฃผ์„ธ์š”."); } } }
[ "์œคํœ˜๊ฒฝ@DESKTOP-EQQTAMM" ]
์œคํœ˜๊ฒฝ@DESKTOP-EQQTAMM
334a32dab2ebbe50695843d03e901710a2ad8604
63da595a4e74145e86269e74e46c98ad1c1bcad3
/java/com/genscript/gsscm/customer/service/CustomerService.java
d6875a91bd38c1143ec635e4dfaead71f0a889cf
[]
no_license
qcamei/scm
4f2cec86fedc3b8dc0f1cc1649e9ef3be687f726
0199673fbc21396e3077fbc79eeec1d2f9bd65f5
refs/heads/master
2020-04-27T19:38:19.460288
2012-09-18T07:06:04
2012-09-18T07:06:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
109,027
java
package com.genscript.gsscm.customer.service; import java.io.File; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.genscript.gsscm.basedata.dto.DropDownDTO; import com.genscript.gsscm.customer.entity.*; import com.genscript.gsscm.report.dao.ReportDao; import org.apache.commons.lang.StringUtils; import org.apache.struts2.ServletActionContext; import org.dozer.DozerBeanMapper; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.genscript.core.orm.Page; import com.genscript.core.orm.PropertyFilter; import com.genscript.gsscm.common.FileService; import com.genscript.gsscm.common.MimeMailService; import com.genscript.gsscm.common.PageDTO; import com.genscript.gsscm.common.constant.Constants; import com.genscript.gsscm.common.constant.ContactMethod; import com.genscript.gsscm.common.constant.DocumentType; import com.genscript.gsscm.common.constant.FilePathConstant; import com.genscript.gsscm.common.constant.SalesRepSalesRole; import com.genscript.gsscm.common.constant.SessionConstant; import com.genscript.gsscm.common.constant.StatusType; import com.genscript.gsscm.common.constant.StrutsActionContant; import com.genscript.gsscm.common.events.NewCustomerEvent; import com.genscript.gsscm.common.exception.BussinessException; import com.genscript.gsscm.common.util.ArithUtil; import com.genscript.gsscm.common.util.DateUtils; import com.genscript.gsscm.common.util.SessionEmergeUtil; import com.genscript.gsscm.common.util.SessionUtil; import com.genscript.gsscm.common.util.StringUtil; import com.genscript.gsscm.common.util.Struts2Util; import com.genscript.gsscm.contact.dao.ContactDao; import com.genscript.gsscm.contact.dto.ContactActivity; import com.genscript.gsscm.contact.dto.ContactDTO; import com.genscript.gsscm.contact.entity.Contact; import com.genscript.gsscm.customer.dao.AddressDao; import com.genscript.gsscm.customer.dao.CouponDao; import com.genscript.gsscm.customer.dao.CreditCardDao; import com.genscript.gsscm.customer.dao.CreditRatingDao; import com.genscript.gsscm.customer.dao.CustContactHistDao; import com.genscript.gsscm.customer.dao.CustInfoStatDao; import com.genscript.gsscm.customer.dao.CustPersInfoDao; import com.genscript.gsscm.customer.dao.CustomerBeanDao; import com.genscript.gsscm.customer.dao.CustomerCaseDao; import com.genscript.gsscm.customer.dao.CustomerDao; import com.genscript.gsscm.customer.dao.CustomerGrantsDao; import com.genscript.gsscm.customer.dao.CustomerInterestDao; import com.genscript.gsscm.customer.dao.CustomerNoteDao; import com.genscript.gsscm.customer.dao.CustomerPointsDao; import com.genscript.gsscm.customer.dao.CustomerPointsHistoryDao; import com.genscript.gsscm.customer.dao.CustomerPublicationDao; import com.genscript.gsscm.customer.dao.CustomerSpecialPriceDao; import com.genscript.gsscm.customer.dao.CustomerStatusHistoryDao; import com.genscript.gsscm.customer.dao.DepartmentDao; import com.genscript.gsscm.customer.dao.DivisionDao; import com.genscript.gsscm.customer.dao.GiftCardDao; import com.genscript.gsscm.customer.dao.NoteDocumentDao; import com.genscript.gsscm.customer.dao.OrganizationDao; import com.genscript.gsscm.customer.dao.PaymentTermDao; import com.genscript.gsscm.customer.dao.RfmRatingDao; import com.genscript.gsscm.customer.dao.SalesRepDao; import com.genscript.gsscm.customer.dao.SourceDao; import com.genscript.gsscm.customer.dao.webbehavior.AccessAnalysisDao; import com.genscript.gsscm.customer.dao.webbehavior.AccessLogDao; import com.genscript.gsscm.customer.dao.webbehavior.VisitDao; import com.genscript.gsscm.customer.dto.AccessStatDTO; import com.genscript.gsscm.customer.dto.AnalysisDTO; import com.genscript.gsscm.customer.dto.AnalysisReport; import com.genscript.gsscm.customer.dto.AnalysisReportSrchDTO; import com.genscript.gsscm.customer.dto.AnalysisSrchDTO; import com.genscript.gsscm.customer.dto.CouponDTO; import com.genscript.gsscm.customer.dto.CustAddrOperDTO; import com.genscript.gsscm.customer.dto.CustContactInfoDTO; import com.genscript.gsscm.customer.dto.CustGrantsDTO; import com.genscript.gsscm.customer.dto.CustNoteDTO; import com.genscript.gsscm.customer.dto.CustPubsDTO; import com.genscript.gsscm.customer.dto.CustSpecialPriceDTO; import com.genscript.gsscm.customer.dto.CustomerDTO; import com.genscript.gsscm.customer.dto.DefaultAddressDTO; import com.genscript.gsscm.customer.dto.PageViewDTO; import com.genscript.gsscm.customer.dto.PaymentTermDTO; import com.genscript.gsscm.customer.dto.RedeemHistoryDTO; import com.genscript.gsscm.customer.dto.SalesStaticsSrchDTO; import com.genscript.gsscm.order.dao.DocumentDao; import com.genscript.gsscm.order.dao.ExchRateByDateDao; import com.genscript.gsscm.order.dao.OrderDao; import com.genscript.gsscm.order.dao.OrderItemDao; import com.genscript.gsscm.order.dto.SalesOrderedDTO; import com.genscript.gsscm.order.entity.Document; import com.genscript.gsscm.privilege.dao.UserDao; import com.genscript.gsscm.privilege.dao.UserRoleDao; import com.genscript.gsscm.privilege.entity.User; import com.genscript.gsscm.product.dao.CatalogDao; import com.genscript.gsscm.product.dao.ProductCategoryDao; import com.genscript.gsscm.product.dto.ProductViewDTO; import com.genscript.gsscm.product.entity.Catalog; import com.genscript.gsscm.product.entity.ProductCategory; import com.genscript.gsscm.quote.dao.QuoteDao; import com.genscript.gsscm.serv.dao.ServiceCategoryDao; import com.genscript.gsscm.serv.dto.ServiceViewDTO; import com.genscript.gsscm.serv.entity.ServiceCategory; import com.genscript.gsscm.systemsetting.dao.BillTerritoryDao; import com.opensymphony.xwork2.ActionContext; @Service @Transactional public class CustomerService implements ApplicationContextAware { @Autowired private CustomerBeanDao customerBeanDao; @Autowired private CustomerDao customerDao; @Autowired private DozerBeanMapper dozer; @Autowired private OrganizationDao organizationDao; @Autowired private CustContactHistDao custContactHistDao; @Autowired private DepartmentDao departmentDao; @Autowired private DivisionDao divisionDao; @Autowired private AddressDao addressDao; @Autowired private PaymentTermDao paymentTermDao; @Autowired private CustomerSpecialPriceDao customerSpecialPriceDao; @Autowired private CustomerPointsDao customerPointsDao; @Autowired private CustomerPointsHistoryDao customerPointsHistoryDao; @Autowired private CustomerGrantsDao customerGrantsDao; @Autowired private CustInfoStatDao custInfoStatDao; @Autowired private CustomerPublicationDao customerPublicationDao; @Autowired private CustPersInfoDao custPersInfoDao; @Autowired private CustomerCaseDao customerCaseDao; @Autowired private CustomerInterestDao customerInterestDao; @Autowired private VisitDao visitDao; @Autowired private AccessAnalysisDao accessAnalysisDao; @Autowired private AccessLogDao accessLogDao; @Autowired private UserDao userDao; @Autowired private ProductCategoryDao productCategoryDao; @Autowired private ServiceCategoryDao serviceCategoryDao; @Autowired private NoteDocumentDao noteDocumentDao; @Autowired private CustomerNoteDao customerNoteDao; @Autowired private CreditCardDao creditCardDao; @Autowired private CatalogDao catalogDao; @Autowired private OrderDao orderDao; @Autowired private QuoteDao quoteDao; @Autowired private SourceDao sourceDao; @Autowired private OrderItemDao orderItemDao; @Autowired private MimeMailService mimeMailService; @Autowired private FileService fileService; @Autowired private CustomerStatusHistoryDao customerStatusHistoryDao; @Autowired private SalesRepDao salesRepDao; @Autowired private DocumentDao documentDao; @Autowired private GiftCardDao giftCardDao; @Autowired private CouponDao couponDao; @Autowired private ContactDao contactDao; @Autowired private CreditRatingDao creditRatingDao; @Autowired private ExchRateByDateDao exchRateByDateDao; @Autowired private UserRoleDao userRoleDao; @Autowired private RfmRatingDao rfmRatingDao; @Autowired private BillTerritoryDao billTerritoryDao; private static final String WEB_BEHAVIOR_DT = "yyyy-MM-dd HH:mm:ss"; private ApplicationContext context; @Transactional(readOnly = true) public Customer findById(Integer custNo) { return this.customerDao.getById(custNo); } @Transactional(readOnly = true) public Page<CustomerBean> searchCustomer(Page<CustomerBean> page) { Page<CustomerBean> customerList = customerBeanDao.getCustomerList(page); return customerList; } public void saveCustGrants(String sessCustNo, Integer custNo) throws Exception { SessionEmergeUtil<CustGrantsDTO> sessionEmergeUtil = new SessionEmergeUtil<CustGrantsDTO>(); Map<String, CustGrantsDTO> custGrants = sessionEmergeUtil .convertMap(SessionUtil.getRow( SessionConstant.CustGrantList.value(), custNo, sessCustNo)); // ่Žทๅ–ๅฝ“ๅ‰session้‡Œ้ข ็š„ ๆ‰€ๆœ‰็š„grants // ๅฏน่ฑก็„ถๅŽๅฐ†ๅ…ถไฟๅญ˜่‡ณๆ•ฐๆฎๅบ“ไธญใ€‚ if (custGrants == null) { return; } for (Map.Entry<String, CustGrantsDTO> entry : custGrants.entrySet()) { // ๅพช็Žฏไฟๅญ˜ๆ‰€ๆœ‰็š„ๅฏน่ฑกใ€‚ System.out.println(entry.getKey() + " " + entry.getValue()); CustGrantsDTO custdtd = entry.getValue();// ้ฆ–ๅ…ˆ่ฟ›่กŒ็ฑปๅž‹่ฝฌๆข.. custdtd.setCustNo(custNo); custdtd.setCreatedBy(SessionUtil.getUserId()); custdtd.setCreationDate(new Date()); custdtd.setModifiedBy(SessionUtil.getUserId()); custdtd.setModifyDate(new Date()); CustomerGrants customerGrants = dozer.map(custdtd, CustomerGrants.class); this.customerGrantsDao.save(customerGrants); } SessionUtil.deleteRow(SessionConstant.CustGrantList.value(), String.valueOf(custNo)); } public void saveCustPublishs(String sessCustNo, Integer custNo) throws Exception { SessionEmergeUtil<CustPubsDTO> sessionEmergeUtil = new SessionEmergeUtil<CustPubsDTO>(); Map<String, CustPubsDTO> custPublishs = sessionEmergeUtil .convertMap(SessionUtil.getRow( SessionConstant.CustPubList.value(), custNo, sessCustNo)); // ่Žทๅ–ๅฝ“ๅ‰session้‡Œ้ข // ็š„ // ๆ‰€ๆœ‰็š„grants // ๅฏน่ฑก็„ถๅŽๅฐ†ๅ…ถไฟๅญ˜่‡ณๆ•ฐๆฎๅบ“ไธญใ€‚ if (custPublishs == null) { return; } for (Map.Entry<String, CustPubsDTO> entry : custPublishs.entrySet()) { // ๅพช็Žฏไฟๅญ˜ๆ‰€ๆœ‰็š„ๅฏน่ฑกใ€‚ CustPubsDTO custdtd = entry.getValue(); custdtd.setCustNo(custNo); custdtd.setCreatedBy(SessionUtil.getUserId()); custdtd.setCreationDate(new Date()); custdtd.setModifiedBy(SessionUtil.getUserId()); custdtd.setModifyDate(new Date()); CustomerPublications customerPw = dozer.map(custdtd, CustomerPublications.class); this.customerPublicationDao.save(customerPw); } SessionUtil.deleteRow(SessionConstant.CustPubList.value(), String.valueOf(custNo)); } public void saveOrUpdateCustGrants(CustomerGrants customerGrants) { this.customerGrantsDao.save(customerGrants); } @SuppressWarnings("unused") private void saveOrUpdateCustPubs(CustomerPublications customerPublications) { this.customerPublicationDao.save(customerPublications); } public CustomerContactHistory getContactHistory(Integer custNo, String method) { return this.custContactHistDao.getCustomerContactHistoryByCustNo( custNo, method); } @Transactional(readOnly = true) public Page<CustomerBean> searchCustomer(Page<CustomerBean> page, List<PropertyFilter> filters) throws Exception { String userName = SessionUtil.getUserName(); // ๅˆคๆ–ญๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅซๆœ‰้”€ๅ”ฎ็ป็†่ง’่‰ฒ boolean salesManager = userRoleDao .checkIsContainsManagerRole(Constants.ROLE_SALES_MANAGER); if (Constants.USERNAME_ADMIN.equals(userName) || salesManager) { page = customerBeanDao.findPage(page, filters); return page; } // ๅˆคๆ–ญๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅซๆœ‰ๅ†…้ƒจ่ฎขๅ•็ฎก็†ๅ‘˜่ง’่‰ฒ๏ผŒๆ˜ฏ๏ผŒๅˆ™ๆŸฅ่ฏข่‡ชๅทฑ้ƒจ้—จ็š„customer boolean internalOrderManager = userRoleDao .checkIsContainsManagerRole(Constants.ROLE_INTERNAL_ORDER_MANAGER); List<Criterion> criterionList = new ArrayList<Criterion>(); if (internalOrderManager) { if (filters == null || filters.isEmpty()) { filters = new ArrayList<PropertyFilter>(); } filters.add(new PropertyFilter("EQS_custType", Constants.INTERNAL_TYPE_CUSTOMER)); } else { Map<String, Object> salesRoleAndUserIdsMap = salesRepDao .getSameGroupUser(); if (salesRoleAndUserIdsMap.get("function") != null && salesRoleAndUserIdsMap.get("User_Ids") != null) { String salesRole = salesRoleAndUserIdsMap.get("function") .toString(); Integer[] userIdsArr = (Integer[]) salesRoleAndUserIdsMap .get("User_Ids"); if (SalesRepSalesRole.SALES_CONTACT.value().equals(salesRole)) { Criterion criterionSalesContact = Restrictions.in( "salesContactId", userIdsArr); criterionList.add(criterionSalesContact); } else if (SalesRepSalesRole.TECH_SUPPORT.value().equals( salesRole)) { Criterion criterionSalesContact = Restrictions.in( "techSupportId", userIdsArr); criterionList.add(criterionSalesContact); } } } page = customerBeanDao.searchCustomer(page, criterionList, filters); return page; } @Transactional(readOnly = true) public Page<CustomerBean> searchCustomerByFilter(Page<CustomerBean> page, List<PropertyFilter> filters) { Map<String, Object> filterMap = new HashMap<String, Object>(); if (filters != null && filters.size() > 0) { for (int i = 0; i < filters.size(); i++) { String filterName = filters.get(i).getPropertyName(); Object filterValue = filters.get(i).getPropertyValue(); if (("firstName").equals(filterName)) { filterMap.put("firstName", filterValue); filterMap.put("midName", filterValue); filterMap.put("lastName", filterValue); } else { filterMap.put(filterName, filterValue); } } } Page<CustomerBean> customerList = customerBeanDao .searchCustomerByFilter(page, filterMap); return customerList; } @Transactional(readOnly = true) public Page<CustomerBean> searchCustomer(Page<CustomerBean> page, final Map<String, String> filterParamMap) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); for (Map.Entry<String, String> entry : filterParamMap.entrySet()) { String filterName = entry.getKey(); String value = entry.getValue(); boolean omit = StringUtils.isBlank(value); if (!omit) { PropertyFilter filter = new PropertyFilter(filterName, value); filterList.add(filter); } } return customerBeanDao.findPage(page, filterList); } public int delCustomer(Integer userId, Integer customerNo) { return customerDao.delete(userId, customerNo); } public void saveOrUpdateCust(Customer customer) { String paymentCurrency = customer.getPaymentCurrency(); String priceCatalogId = customer.getPriceCatalogId(); if (StringUtils.isEmpty(priceCatalogId)) { Catalog baseCatalog = catalogDao.getBaseCatalog(); String catalogCurrency = baseCatalog.getCurrencyCode(); if (!catalogCurrency.equalsIgnoreCase(paymentCurrency)) { throw new BussinessException( BussinessException.CUST_SP_CATALOGID_DIS_CODE); } } else { Catalog catalog = catalogDao.findUniqueBy("catalogId", priceCatalogId); String catalogCurrency = catalog.getCurrencyCode(); if (!catalogCurrency.equalsIgnoreCase(paymentCurrency)) { throw new BussinessException( BussinessException.CUST_SP_CATALOGID_DIS_CODE); } } Integer custNo = customer.getCustNo(); Date now = new Date(); customer.setModifyDate(now); if (custNo == null || custNo.intValue() == 0) { customer.setCustNo(null); customer.setCreatedBy(customer.getModifiedBy()); customer.setCreationDate(now); } if (customer.getBstCallTimeFrom() != null && customer.getBstCallTimeFrom().trim().length() < 1) { customer.setBstCallTimeFrom(null); } if (customer.getBstCallTimeTo() != null && customer.getBstCallTimeTo().trim().length() < 1) { customer.setBstCallTimeTo(null); } // ๆ–ฐๅขžcustomerๆ—ถ๏ผŒๅฐ†ContactไธŽCustomerๅ…ทๆœ‰็›ธๅŒ็š„Bussiness // email็š„Contact็š„status็Šถๆ€่ฎพ็ฝฎไธบinactive if (customer.getCustNo() == null) { List<Contact> contactList = this.contactDao .findContactByBusEmail(customer.getBusEmail()); if (contactList != null && contactList.size() > 0) { for (Contact contact : contactList) { contact.setStatus(StatusType.INACTIVE.value()); contact.setModifyDate(customer.getCreationDate()); contact.setModifiedBy(customer.getCreatedBy()); this.contactDao.save(contact); } } } this.customerDao.save(customer); } /* * private Organization attachOrg(Customer customer, Organization org) { if * (org == null) { return null; } boolean bNew = org.getOrgId() == null || * (org.getOrgId().intValue() == 0); if (bNew && (org.getName() == null || * org.getName().trim().length() < 1)) { return org; } Integer id = * org.getOrgId(); Date now = new Date(); org.setModifyDate(now); * org.setModifiedBy(customer.getModifiedBy()); if (id == null || * id.intValue() == 0) { org.setOrgId(null); * org.setCreatedBy(customer.getModifiedBy()); org.setCreationDate(now); } * this.organizationDao.save(org); customer.setOrgId(org.getOrgId()); return * org; } */ private Divisions attachDivision(Customer customer, Divisions div) { if (div == null) { return null; } boolean bNew = div.getDivisionId() == null || div.getDivisionId().intValue() == 0; if (bNew && (div.getName() == null || div.getName().trim().length() < 1)) { return div; } Integer id = div.getDivisionId(); Date now = new Date(); div.setModifyDate(now); div.setModifiedBy(customer.getModifiedBy()); if (div.getOrgId() != null && div.getOrgId().intValue() == 0) { div.setOrgId(null); } if (id == null || id.intValue() == 0) {// new div.setDivisionId(null); div.setCreatedBy(customer.getModifiedBy()); div.setCreationDate(now); } this.divisionDao.save(div); customer.setDivisionId(div.getDivisionId()); return div; } private Departments attachDept(Customer customer, Departments dept) { if (dept == null) { return null; } boolean bNew = dept.getDeptId() == null || dept.getDeptId().intValue() == 0; if (bNew && (dept.getName() == null || dept.getName().trim().length() < 1)) { return dept; } Integer id = dept.getDeptId(); Date now = new Date(); dept.setModifyDate(now); // System.out.println(dept.getDeptFuncId() + // "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); dept.setModifiedBy(customer.getModifiedBy()); dept.setDeptFuncId(dept.getDeptFuncId()); if (dept.getOrgId() != null && dept.getOrgId().intValue() == 0) { dept.setOrgId(null); } if (dept.getDivisionId() != null && dept.getDivisionId().intValue() == 0) { dept.setDivisionId(null); } if (id == null || id.intValue() == 0) { dept.setDeptId(null); dept.setCreatedBy(customer.getModifiedBy()); dept.setCreationDate(now); } this.departmentDao.save(dept); customer.setDeptId(dept.getDeptId()); return dept; } private void attachAddress(Customer customer, List<CustAddrOperDTO> addrDTOList, List<Integer> delAddrIdList) { if (delAddrIdList != null && delAddrIdList.get(0) != null) { this.addressDao.delAddrList(delAddrIdList); } if (addrDTOList == null || addrDTOList.get(0) == null) { return; } Date now = new Date(); Integer custNo = customer.getCustNo(); for (CustAddrOperDTO dto : addrDTOList) { Address addr = dozer.map(dto, Address.class); if (addr.getAddrId() == null || addr.getAddrId().intValue() == 0) { addr.setAddrId(null); addr.setCreatedBy(customer.getModifiedBy()); addr.setCreationDate(now); } // addr.setOrgId(orgId); // addr.setOrgName(orgName); /* * Organization org = this.saveAddrOrg(addr.getOrganization(), * customer.getModifiedBy()); if (org == null || org.getOrgId() == * null || org.getOrgId().intValue() == 0) { * addr.setOrganization(null); } else { addr.setOrganization(org); } */ addr.setModifyDate(now); addr.setModifiedBy(customer.getModifiedBy()); addr.setCustNo(custNo); addressDao.save(addr); } } /** * ไฟๅญ˜Customer็š„ๅŒๆ—ถไฟๅญ˜CustomerNotes.ๅŠๅ…ถๅ…ณ่”็š„ๅคšไธชdocument. * * @param customer * @param dtoList * @return */ private List<Integer> attachNote(Customer customer, List<CustNoteDTO> dtoList) { List<Integer> sendMailIdList = new ArrayList<Integer>(); if (dtoList == null || dtoList.isEmpty()) { return sendMailIdList; } Date now = new Date(); for (CustNoteDTO dto : dtoList) { if (dto.getDelDocIdList() != null && !dto.getDelDocIdList().isEmpty()) { this.noteDocumentDao.delDocList(dto.getDelDocIdList()); } CustomerNote note = this.dozer.map(dto, CustomerNote.class); note.setCustNo(customer.getCustNo()); note.setCreatedBy(customer.getModifiedBy()); note.setModifiedBy(customer.getModifiedBy()); note.setCreationDate(now); note.setModifyDate(now); this.customerNoteDao.save(note); if (dto.getDocumentList() != null && !dto.getDocumentList().isEmpty()) { for (NoteDocument doc : dto.getDocumentList()) { doc.setCreatedBy(customer.getModifiedBy()); doc.setModifiedBy(customer.getModifiedBy()); doc.setCreationDate(now); doc.setModifyDate(now); doc.setRefId(note.getId()); doc.setRefType(DocumentType.CUSTOMER_NOTE_TYPE.value()); this.noteDocumentDao.save(doc); } } } return sendMailIdList; } @SuppressWarnings("unused") private Organization saveAddrOrg(Organization addrOrg, Integer userId) { if (addrOrg == null) { return null; } if (addrOrg.getOrgId() != null && addrOrg.getOrgId().intValue() > 0) { Organization dbOrg = new Organization(); dbOrg.setOrgId(addrOrg.getOrgId()); return dbOrg; } addrOrg.setOrgId(null); Date now = new Date(); addrOrg.setModifyDate(now); addrOrg.setModifiedBy(userId); addrOrg.setCreatedBy(userId); addrOrg.setCreationDate(now); this.organizationDao.save(addrOrg); return addrOrg; } private void attachContact(Customer customer, List<ContactDTO> contactDTOList, List<Integer> delContactsIdList) throws ParseException { if (delContactsIdList != null && !delContactsIdList.isEmpty()) { this.custContactHistDao.delContactsList(delContactsIdList); } if (contactDTOList == null || contactDTOList.isEmpty()) { return; } Date now = new Date(); Integer custNo = customer.getCustNo(); for (ContactDTO dto : contactDTOList) { if (dto.getCallTime() == null || dto.getCallTime().trim().length() < 1) { dto.setCallTime(null); } CustomerContactHistory history = dozer.map(dto, CustomerContactHistory.class); history.setCustNo(custNo); history.setModifyDate(now); history.setModifiedBy(customer.getModifiedBy()); if (dto.getContactId() == null || dto.getContactId().intValue() == 0) { history.setContactId(null); history.setCreatedBy(customer.getModifiedBy()); history.setCreationDate(now); } System.out.println("history: " + history); this.custContactHistDao.save(history); } } private void attachCustInterest(Customer customer, List<CustomerInterest> custInterestList, List<Integer> delCustIntIdList) { if (delCustIntIdList != null && !delCustIntIdList.isEmpty()) { this.customerInterestDao.deleteCustomerInterests(delCustIntIdList); } if (custInterestList == null || custInterestList.isEmpty()) { return; } Date now = new Date(); for (CustomerInterest intereset : custInterestList) { intereset.setInterestId(null); intereset.setCreatedBy(customer.getModifiedBy()); intereset.setModifiedBy(customer.getModifiedBy()); intereset.setCustNo(customer.getCustNo()); intereset.setCreationDate(now); intereset.setModifyDate(now); this.customerInterestDao.save(intereset); } } // public void attachCustomerPoints(Customer customer, // CustomerPoints customerPoints) { // Date now = new Date(); // customerPoints.setCreatedBy(customer.getModifiedBy()); // customerPoints.setCreationDate(now); // customerPoints.setModifyDate(now); // customerPoints.setModifiedBy(customer.getModifiedBy()); // customerPoints.setCustNo(customer.getCustNo()); // this.customerPointsDao.save(customerPoints); // } private void attachSpecialPrice(Customer customer, List<CustSpecialPriceDTO> custSpecialPriceList, List<Integer> delSpecialPriceIdList) throws ParseException { if (delSpecialPriceIdList != null && delSpecialPriceIdList.get(0) != null) { this.customerSpecialPriceDao .delSpecialPriceList(delSpecialPriceIdList); } if (custSpecialPriceList == null || custSpecialPriceList.get(0) == null) { return; } Date now = new Date(); for (CustSpecialPriceDTO dto : custSpecialPriceList) { Integer custNo = customer.getCustNo(); CustomerSpecialPrice price = dozer.map(dto, CustomerSpecialPrice.class); price.setCustNo(custNo); price.setModifyDate(now); price.setModifiedBy(customer.getModifiedBy()); if (price.getPriceId() == null || price.getPriceId().intValue() == 0) { price.setPriceId(null); price.setCreatedBy(customer.getModifiedBy()); price.setCreationDate(now); } CustomerSpecialPrice dbSpecialPrice = this.customerSpecialPriceDao .getSpecialPrice(custNo, price.getCatalogNo()); if (dbSpecialPrice != null) { // ๆ–ฐๅขžๆˆ–ไฟฎๆ”นๅ…ถๅฎƒ่ฎฐๅฝ•ไธญ็š„catalogNoไธบๆ•ฐๆฎๅบ“ไธญๅทฒๅญ˜ๅœจ็š„. if (price.getPriceId() == null || (!price.getPriceId().equals( dbSpecialPrice.getPriceId()))) { throw new BussinessException( BussinessException.CUST_SP_CATALOGNO_DULP_CODE); } this.customerSpecialPriceDao.getSession().evict(dbSpecialPrice); } this.customerSpecialPriceDao.save(price); } } private void attachCustPublications(Customer customer, List<CustomerPublications> custPubList, List<Integer> delPubIdList) { if (delPubIdList != null && !delPubIdList.isEmpty()) { this.customerPublicationDao.deleteCustomerPubs(delPubIdList); } if (custPubList == null || custPubList.isEmpty()) { return; } Date now = new Date(); for (CustomerPublications pub : custPubList) { pub.setModifyDate(now); pub.setModifiedBy(customer.getModifiedBy()); pub.setCustNo(customer.getCustNo()); if (pub.getId() == null || pub.getId().intValue() == 0) { pub.setId(null); pub.setCreatedBy(pub.getModifiedBy()); pub.setCreationDate(now); } this.customerPublicationDao.save(pub); } } private void attachCustGrants(Customer customer, List<CustomerGrants> custGrantsList, List<Integer> delIdList) { if (delIdList != null && !delIdList.isEmpty()) { this.customerGrantsDao.deleteCustomerGrants(delIdList); } if (custGrantsList == null || custGrantsList.isEmpty()) { return; } Date now = new Date(); for (CustomerGrants custGrants : custGrantsList) { custGrants.setModifyDate(now); custGrants.setModifiedBy(customer.getModifiedBy()); custGrants.setCustNo(customer.getCustNo()); if (custGrants.getGrantId() == null || custGrants.getGrantId().intValue() == 0) { custGrants.setGrantId(null); custGrants.setCreatedBy(customer.getModifiedBy()); custGrants.setCreationDate(now); } this.saveCustGrantss(custGrants); } } private void attachCustCases(Customer customer, List<CustomerCase> custCaseList) { if (custCaseList == null || custCaseList.get(0) == null) { return; } Date now = new Date(); for (CustomerCase custCase : custCaseList) { custCase.setModifyDate(now); custCase.setModifiedBy(customer.getModifiedBy()); if (custCase.getCaseId() == null || custCase.getCaseId().intValue() == 0) { custCase.setCaseId(null); custCase.setCreatedBy(customer.getModifiedBy()); custCase.setCreationDate(now); } custCase.setModifyDate(now); custCase.setCustNo(customer.getCustNo()); this.customerCaseDao.save(custCase); Map<String, NoteDocument> documentMap = custCase.getDocumentMap(); if (documentMap != null && documentMap.size() > 0) { Set<Entry<String, NoteDocument>> set = documentMap.entrySet(); for (Entry<String, NoteDocument> entry : set) { NoteDocument noteDocumnet = entry.getValue(); if (noteDocumnet == null) { this.noteDocumentDao.delete(noteDocumnet); continue; } else if (noteDocumnet.getRefId() == null || noteDocumnet.getRefId() == 0) { noteDocumnet.setRefId(custCase.getCaseId()); } this.noteDocumentDao.save(noteDocumnet); } } } } public void attachCustPersonal(Customer customer, CustomerPersonalInfo personal) { if (personal == null) { return; } Date now = new Date(); personal.setModifyDate(now); personal.setModifiedBy(customer.getModifiedBy()); personal.setCreatedBy(customer.getModifiedBy()); personal.setCreationDate(now); personal.setModifyDate(now); personal.setCustNo(customer.getCustNo()); this.custPersInfoDao.save(personal); } public Customer saveCustomer(CustomerDTO custOperDTO) throws ParseException { Customer customer = null; boolean isAdd = false; if (custOperDTO.getCustNo() == null || custOperDTO.getCustNo() == 0) { isAdd = true; } customer = dozer.map(custOperDTO, Customer.class); Organization org = custOperDTO.getOrganization(); Integer orgId = null; if (org != null) { orgId = org.getOrgId(); if (orgId != null) { customer.setOrgId(orgId); } else { customer.setOrgId(custOperDTO.getOrgId()); } } customer.setBillAccountCode(custOperDTO.getBillAccountCode()); Divisions div = null; if (custOperDTO.getDivision() != null && custOperDTO.getDivision().getDivisionId() != null) { div = this.divisionDao.getById(custOperDTO.getDivision() .getDivisionId()); } if (div != null) { div.setOrgId(orgId); // div = this.attachDivision(customer, div); } Departments dept = null; // Departments dept = new Departments(); // System.out.println("custOperDTO.getDepartment().getDeptId()========" // + custOperDTO.getDepartment().getDeptId()); // System.out.println("custOperDTO.getDepartment().getDeptFuncId()========" // + custOperDTO.getDepartment().getDeptFuncId()); if (custOperDTO.getDepartment() != null && custOperDTO.getDepartment().getDeptId() != null) { dept = this.departmentDao.getById(custOperDTO.getDepartment() .getDeptId()); } if (dept != null) { // System.out.println(dept.getDeptFuncId()); dept.setDeptFuncId(custOperDTO.getDepartment().getDeptFuncId()); dept.setOrgId(orgId); if (div != null) { dept.setDivisionId(div.getDivisionId()); } this.attachDept(customer, dept); } this.saveOrUpdateCust(customer); // this.organizationDao.save(org); this.attachAddress(customer, custOperDTO.getCustAddrList(), custOperDTO.getDelAddrIdList()); this.attachContact(customer, custOperDTO.getContactList(), custOperDTO.getDelContactsIdList()); attachSpecialPrice(customer, custOperDTO.getCustSpecialPriceList(), custOperDTO.getDelSpecialPriceIdList()); // more info this.attachCustInterest(customer, custOperDTO.getCustInterestList(), custOperDTO.getDelCustIntIdList()); this.attachCustPublications(customer, custOperDTO.getCustPubList(), custOperDTO.getDelCustPubIdList()); this.attachCustGrants(customer, custOperDTO.getCustGrantsList(), custOperDTO.getDelCustGrantsIdList()); this.attachCustCases(customer, custOperDTO.getCustCaseList()); this.attachCustPersonal(customer, custOperDTO.getPersonal()); this.attachNote(customer, custOperDTO.getCustNoteList()); if (isAdd) { // ่งฆๅ‘่ฐƒ็”จERP ApplicationEvent evt = new NewCustomerEvent(this, custOperDTO, customer.getCustNo().toString()); context.publishEvent(evt); } else { ApplicationEvent evt = new NewCustomerEvent(this, custOperDTO, customer.getCustNo().toString()); context.publishEvent(evt); } return customer; } @Transactional(readOnly = true) public Page<CustSpecialPriceDTO> getProductSpecialPriceList(Integer custNo, Page<CustomerSpecialPrice> page) { return this.getSpecialPriceList(custNo, page, "PRODUCT"); } @Transactional(readOnly = true) public Page<CustSpecialPriceDTO> getServiceSpecialPriceList(Integer custNo, Page<CustomerSpecialPrice> page) { return this.getSpecialPriceList(custNo, page, "SERVICE"); } @Transactional(readOnly = true) public CustSpecialPriceDTO getSpecialPrice(Integer custNo, String catalogNo) { CustSpecialPriceDTO specialPriceDTO = null; List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter custFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(custFilter); PropertyFilter typeFilter = new PropertyFilter("EQS_catalogNo", catalogNo.trim()); filterList.add(typeFilter); List<CustomerSpecialPrice> priceList = this.customerSpecialPriceDao .find(filterList); if (priceList != null && !priceList.isEmpty()) { specialPriceDTO = dozer.map(priceList.get(0), CustSpecialPriceDTO.class); Integer sourceId = specialPriceDTO.getSource(); if (sourceId != null) { Source source = sourceDao.get(sourceId); if (source != null) { specialPriceDTO.setSourceKey(source.getName()); } } } return specialPriceDTO; } @SuppressWarnings("unchecked") @Transactional(readOnly = true) private Page<CustSpecialPriceDTO> getSpecialPriceList(Integer custNo, Page<CustomerSpecialPrice> page, String type) { List<CustSpecialPriceDTO> pricedtoList = new ArrayList<CustSpecialPriceDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); PropertyFilter typeFilter = new PropertyFilter("EQS_type", type); filterList.add(typeFilter); Page<CustomerSpecialPrice> pagePriceList = this.customerSpecialPriceDao .findPage(page, filterList); List<CustomerSpecialPrice> priceList = pagePriceList.getResult(); if (priceList != null) { for (CustomerSpecialPrice price : priceList) { if (price.getPriceId() != null) { CustSpecialPriceDTO priceDto = dozer.map(price, CustSpecialPriceDTO.class); pricedtoList.add(priceDto); } } } pagePriceList.setResult(null); Page<CustSpecialPriceDTO> dtoPage = this.dozer.map(pagePriceList, Page.class); dtoPage.setResult(pricedtoList); return dtoPage; } /** * ่Žทๅพ—Customer็š„ๅŸบๆœฌไฟกๆฏ, ไธๅŒ…ๅซๅ…ถๅฎƒ่กจ็š„ๅ…ณ่”ๅ†…ๅฎน. * * @param customerNo * @return * @author wangsf * @serialData 2010-10-20 */ @Transactional(readOnly = true) public CustomerDTO getCustomerBase(Integer customerNo) { Customer customer = customerDao.getById(customerNo); if (customer != null) { CustomerDTO dto = dozer.map(customer, CustomerDTO.class); return dto; } return null; } @Transactional(readOnly = true) public CustomerDTO getCustomerDetail(Integer customerNo) throws Exception { this.customerDao.getSessionFactory().evict(Customer.class); System.out .println("===============getCustomerDetail evict============="); Customer customer = customerDao.getById(customerNo); Integer custNo = customer.getCustNo(); CustomerDTO dto = dozer.map(customer, CustomerDTO.class); // attach address List<CustAddrOperDTO> custAddrList = new ArrayList<CustAddrOperDTO>(); List<Address> addrList = this.addressDao.getListByCust(custNo); if (addrList != null) { for (Address addr : addrList) { CustAddrOperDTO addrDTO = dozer .map(addr, CustAddrOperDTO.class); // Organization dbOrg = addr.getOrganization(); // if (dbOrg != null) { /* * Organization org = new Organization(); * org.setName(dbOrg.getName()); org.setOrgId(dbOrg.getOrgId()); * addrDTO.setOrganization(org); */ // addrDTO.setOrgId(dbOrg.getOrgId()); // } custAddrList.add(addrDTO); } } dto.setCustAddrList(custAddrList); // attach contact include history and sche List<ContactDTO> contactList = new ArrayList<ContactDTO>(); List<CustomerContactHistory> tactHistList = this.custContactHistDao .getListByCust(custNo); if (tactHistList != null) { for (CustomerContactHistory hist : tactHistList) { ContactDTO contactDTO = dozer.map(hist, ContactDTO.class); contactList.add(contactDTO); } CustomerContactHistory contactHistory = this.custContactHistDao .getLastContact(custNo); if (contactHistory != null) { dto.setLastActivity(contactHistory.getModifyDate()); } } String billingAccountCode = ""; if (dto.getBillAccountCode() == null && !"".equals(dto.getBillAccountCode())) { if (customerNo != null && !"".equals(customerNo)) { Address dd = this.addressDao.getDefaultBillTOAddress(customerNo .intValue()); if (dd != null && !"".equals(dd)) { String billingAccount = dd.getCountry(); if (billingAccount != null && !"".equals(billingAccount)) { if (billingAccount.equals("US") || billingAccount.equals("CA")) { billingAccountCode = "US"; } else { billingAccountCode = "HK"; } } } } dto.setBillAccountCode(billingAccountCode); } dto.setContactList(contactList); // attach catalogId List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", customer.getCustNo()); filterList.add(orgFilter); // attach points // -----------------------Modify by zhang yong // Start----------------------------------// if (customerNo != null) { Long pointsSum = this.customerPointsHistoryDao .getCustomerPointsSumByCustNo(customerNo); if (pointsSum != null) { dto.setPointsAvailable(pointsSum.intValue()); } } // List<CustomerPoints> pointsList = this.customerPointsDao // .find(filterList); // if (pointsList != null && !pointsList.isEmpty()) { // CustomerPoints customerPoints = pointsList.get(0); // dto.setPointsAvailable(customerPoints.getPointsAvailable()); // } // -----------------------Modify by zhang yong End // ----------------------------------// // attach org Integer orgId = customer.getOrgId(); if (orgId != null) { dto.setOrganization(organizationDao.getById(orgId)); } Integer divId = customer.getDivisionId(); if (divId != null) { dto.setDivision(this.divisionDao.getById(customer.getDivisionId())); } Integer deptId = customer.getDeptId(); if (deptId != null) { dto.setDepartment(this.departmentDao.getById(customer.getDeptId())); } Integer rfmRatingId = customer.getRfmRatingId(); if (rfmRatingId != null) { RfmRating rfm = this.rfmRatingDao.getById(rfmRatingId); dto.setRfmRatingCd(rfm != null ? rfm.getRfmRatingCd() : ""); } // attach more info CustInfoStat custInfoStat = this.custInfoStatDao .getInfoByCustNo(custNo); if (custInfoStat != null) { dto.setCustInfoStat(custInfoStat); } // ่Žทๅ–Erpๆ•ฐๆฎ // BigDecimal totOpenCredit = // erpSalesOrderService.getCustomerTotOpenCredit(custNo); // if (totOpenCredit != null) { // if (custInfoStat != null) { // dto.getCustInfoStat().setCurrentBalance(totOpenCredit.doubleValue()); // } else { // custInfoStat = new CustInfoStat(); // custInfoStat.setCurrentBalance(totOpenCredit.doubleValue()); // dto.setCustInfoStat(custInfoStat); // } // } CustomerPersonalInfo personal = this.custPersInfoDao .getInfoByCustNo(custNo); if (personal != null) { dto.setPersonal(personal); } return dto; } @Transactional(readOnly = true) public List<PaymentTermDTO> getPaymentTermList() { List<PaymentTermDTO> dtoList = new ArrayList<PaymentTermDTO>(); List<PaymentTerm> termList = this.paymentTermDao.getAll(); if (termList != null) { for (PaymentTerm po : termList) { PaymentTermDTO dto = new PaymentTermDTO(); dto.setDueDays(po.getDueDays()); dto.setNetDays(po.getNetDays()); dto.setName(po.getName()); dto.setTermId(po.getTermId()); dtoList.add(dto); } } return dtoList; } public void saveCustGrantss(CustomerGrants entity) { customerGrantsDao.save(entity); } @Transactional(readOnly = true) public Page<CustomerGrants> listCustGrantsOld(Page<CustomerGrants> page, Integer custNo) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); return customerGrantsDao.findPage(page, filterList); } @SuppressWarnings("unchecked") @Transactional(readOnly = true) public Page<CustGrantsDTO> listCustGrants(Page<CustomerGrants> page, Integer custNo) { List<CustGrantsDTO> dtoList = new ArrayList<CustGrantsDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); Page<CustomerGrants> pageList = this.customerGrantsDao.findPage(page, filterList); List<CustomerGrants> resultList = pageList.getResult(); if (resultList != null) { for (CustomerGrants pub : resultList) { CustGrantsDTO custGrantsDTO = dozer.map(pub, CustGrantsDTO.class); dtoList.add(custGrantsDTO); } } pageList.setResult(null); Page<CustGrantsDTO> dtoPage = this.dozer.map(pageList, Page.class); dtoPage.setResult(dtoList); return dtoPage; } @Transactional(readOnly = true) public List<CustomerInterest> getCustIntList(Integer custNo) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); return this.customerInterestDao.find(filterList); } @SuppressWarnings("unchecked") @Transactional(readOnly = true) public Page<ContactDTO> getCustContactList(Integer custNo, Page<CustomerContactHistory> page) { List<ContactDTO> dtoList = new ArrayList<ContactDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); Page<CustomerContactHistory> pageList = this.custContactHistDao .findPage(page, filterList); List<CustomerContactHistory> resultList = pageList.getResult(); if (resultList != null) { User contactUser = null; for (CustomerContactHistory hist : resultList) { ContactDTO contactDTO = dozer.map(hist, ContactDTO.class); if (hist.getContactBy() != null) { contactUser = this.userDao.getById(hist.getContactBy()); if (contactUser != null) { contactDTO.setContactUserName(contactUser .getLoginName()); } if (hist.getSource() != null) { Source source = sourceDao.get(hist.getSource()); contactDTO.setSourceName(source.getName()); } } dtoList.add(contactDTO); } } pageList.setResult(null); Page<ContactDTO> dtoPage = this.dozer.map(pageList, Page.class); dtoPage.setResult(dtoList); return dtoPage; } public String modCustPassword(String password, int custNo) { Integer i = null; if (null != password && custNo > 0) { i = this.customerDao.modCustPassword(password, custNo); } if (i == 1) { return "true"; } else { return "false"; } } @Transactional(readOnly = true) public CustContactInfoDTO getContactInfo(Integer custNo) { CustContactInfoDTO dto = new CustContactInfoDTO(); int emailCount = 0; emailCount += this.custContactHistDao.getMethodCount("Email", custNo); dto.setEmailCount(emailCount); int faxCount = 0; faxCount += this.custContactHistDao.getMethodCount("Fax", custNo); dto.setFaxCount(faxCount); int letterCount = 0; letterCount += this.custContactHistDao.getMethodCount("Mail", custNo); dto.setLetterCount(letterCount); int phoneCount = 0; phoneCount += this.custContactHistDao.getMethodCount("Phone", custNo); dto.setPhoneCount(phoneCount); return dto; } @Transactional(readOnly = true) public CustInfoStat getCustInfoStat(Integer custNo) { return custInfoStatDao.get(custNo); } @Transactional(readOnly = true) public Page<CustomerPublications> getCustPublicationsListOld( Page<CustomerPublications> page, Integer custNo) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); return customerPublicationDao.findPage(page, filterList); } @SuppressWarnings("unchecked") @Transactional(readOnly = true) public Page<CustPubsDTO> getCustPublicationsList( Page<CustomerPublications> page, Integer custNo) { List<CustPubsDTO> dtoList = new ArrayList<CustPubsDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter orgFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(orgFilter); Page<CustomerPublications> pageList = this.customerPublicationDao .findPage(page, filterList); List<CustomerPublications> resultList = pageList.getResult(); if (resultList != null) { for (CustomerPublications pub : resultList) { CustPubsDTO custPubsDTO = dozer.map(pub, CustPubsDTO.class); dtoList.add(custPubsDTO); } } pageList.setResult(null); Page<CustPubsDTO> dtoPage = this.dozer.map(pageList, Page.class); dtoPage.setResult(dtoList); return dtoPage; } @Transactional(readOnly = true) public Page<CustomerCase> searchCustCase(Page<CustomerCase> page) { return this.customerCaseDao.findPage(page); } @Transactional(readOnly = true) public Page<CustomerCase> searchCustCase(Page<CustomerCase> page, final Map<String, String> filterParamMap) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); for (Map.Entry<String, String> entry : filterParamMap.entrySet()) { String filterName = entry.getKey(); String value = entry.getValue(); boolean omit = StringUtils.isBlank(value); if (!omit) { PropertyFilter filter = new PropertyFilter(filterName, value); filterList.add(filter); } } return this.customerCaseDao.findPage(page, filterList); } @Transactional(readOnly = true) public Page<CustomerCase> searchCustCase(Page<CustomerCase> page, List<PropertyFilter> filterList) { if (filterList == null) { return searchCustCase(page); } else { return this.customerCaseDao.findPage(page, filterList); } } @Transactional(readOnly = true) public CustomerCase getCustCase(Integer caseId) { CustomerCase customerCase = this.customerCaseDao.getById(caseId); if (customerCase.getOwner() != null) { User user = this.userDao.getById(customerCase.getOwner()); customerCase.setOwnerName(user != null ? user.getLoginName() : ""); } User modifyUser = this.userDao.getById(customerCase.getModifiedBy()); customerCase.setModifiedUser(modifyUser != null ? modifyUser .getLoginName() : ""); customerCase.setDocumentMap(SessionUtil.convertList2Map( this.noteDocumentDao.getDocumentList(customerCase.getCaseId(), DocumentType.CUST_CASE), "docId")); return customerCase; } public void saveCustomerInterest(Integer custNo, CustomerInterest entity) { if (custNo != null) { entity.setCustNo(custNo); } customerInterestDao.save(entity); } public void deleteCustomerInterest(List<Integer> ids) { customerInterestDao.deleteCustomerInterests(ids); } @Transactional(readOnly = true) public List<CustomerInterest> getCustomerInterestList() { return customerInterestDao.getAll(); } @Transactional(readOnly = true) public ContactActivity getContactActivity(Integer custNo) { ContactActivity act = new ContactActivity(); Customer customer = this.customerDao.get(custNo); if (customer != null) { CustomerContactHistory lastPhone = custContactHistDao .getLastContactByMethod(custNo, ContactMethod.Phone.value()); if (lastPhone != null) { act.setLastPhoneDate(lastPhone.getContactDate()); act.setLastPhoneContactUser(lastPhone.getContactName()); User contactUser = this.userDao.get(lastPhone.getContactBy()); if (contactUser != null) { act.setLastPhoneContactBy(contactUser.getLoginName()); } } CustomerContactHistory lastEmail = custContactHistDao .getLastContactByMethod(custNo, ContactMethod.Email.value()); if (lastEmail != null) { act.setLastEmailSubject(lastEmail.getSubject()); act.setLastEmailSent(lastEmail.getContactDate()); } CustomerContactHistory lastFax = custContactHistDao .getLastContactByMethod(custNo, ContactMethod.Fax.value()); if (lastFax != null) { act.setLastFaxSent(lastFax.getContactDate()); act.setLastFaxSubject(lastFax.getSubject()); } CustomerContactHistory lastLetter = custContactHistDao .getLastContactByMethod(custNo, ContactMethod.Mail.value()); if (lastLetter != null) { act.setLastMailSent(lastLetter.getContactDate()); act.setLastMailSubject(lastLetter.getSubject()); } CustomerContactHistory contactHistory = custContactHistDao .getLastContactByContentType(custNo, "Catalog"); if (contactHistory != null) { act.setLastCatalogSent(contactHistory.getContactDate()); act.setLastCatalogName(contactHistory.getReferName()); } act.setLastModifyDate(customer.getModifyDate()); act.setLastModifyUser(this.userDao.get(customer.getModifiedBy()) .getLoginName()); } return act; } @Transactional(readOnly = true) public AccessStatDTO getAccessStat(Integer custNo) { SimpleDateFormat dateFmt = new SimpleDateFormat(WEB_BEHAVIOR_DT); AccessStatDTO statDTO = new AccessStatDTO(); statDTO.setVisitTotal(this.visitDao.getVisitTotal(custNo)); Visit first = this.visitDao.getFirstVisit(custNo); if (first != null && first.getInTime() != null) { statDTO.setFirstVisit(dateFmt.format(first.getInTime())); } Visit last = this.visitDao.getLastVisit(custNo); if (last != null && last.getInTime() != null) { statDTO.setLastVisit(dateFmt.format(last.getInTime())); } Long visitTimeTotal = this.visitDao.getTotalVisitTime(custNo); if (visitTimeTotal != null && statDTO.getVisitTotal() != null && statDTO.getVisitTotal().longValue() > 0) { statDTO.setAvgStaySecd(visitTimeTotal / statDTO.getVisitTotal()); } statDTO.setVisitPagesTotal(this.visitDao.getVisitPagesTotal(custNo)); return statDTO; } @SuppressWarnings("unchecked") @Transactional(readOnly = true) public Page<AnalysisDTO> searchAccess(AnalysisSrchDTO srch, Page<AccessAnalysis> page) throws ParseException { List<AnalysisDTO> dtoList = new ArrayList<AnalysisDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd"); PropertyFilter custFilter = new PropertyFilter("EQI_custNo", srch.getCustNo()); filterList.add(custFilter); if (srch.getDateFrom() != null && srch.getDateFrom().trim().length() > 1) { PropertyFilter filter = new PropertyFilter("GED_visitTime", dateFmt.parse(srch.getDateFrom())); filterList.add(filter); } if (srch.getDateTo() != null && srch.getDateTo().trim().length() > 1) { PropertyFilter filter = new PropertyFilter("LED_visitTime", dateFmt.parse(srch.getDateTo())); filterList.add(filter); } page = this.accessAnalysisDao.findPage(page, filterList); if (page.getResult() != null) { for (AccessAnalysis model : page.getResult()) { AnalysisDTO dto = dozer.map(model, AnalysisDTO.class); dtoList.add(dto); } } page.setResult(null); Page<AnalysisDTO> retPage = dozer.map(page, Page.class); retPage.setResult(dtoList); return retPage; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Transactional(readOnly = true) public Page<PageViewDTO> getAccessPageView(Page<AccessAnalysis> page, Integer custNo) { SimpleDateFormat dateFmt = new SimpleDateFormat(WEB_BEHAVIOR_DT); page = this.accessAnalysisDao.getPageView(page, custNo); List<PageViewDTO> dtoList = new ArrayList<PageViewDTO>(); List list = page.getResult(); if (list != null) { for (int i = 0; i < list.size(); i++) { Object[] obj = (Object[]) list.get(i); PageViewDTO dto = new PageViewDTO(); dto.setUrl((String) obj[0]); dto.setViewTimes((Long) obj[1]); if (obj[2] != null) { dto.setFirstView(dateFmt.format((Date) obj[2])); } if (obj[3] != null) { dto.setLastView(dateFmt.format((Date) obj[3])); } dto.setAvgVisitTime((Double) obj[4]); dtoList.add(dto); } } page.setResult(null); Page<PageViewDTO> pageViewDTO = dozer.map(page, Page.class); pageViewDTO.setResult(dtoList); return pageViewDTO; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Transactional(readOnly = true) public Page<ProductViewDTO> getAccessProductView(Page<AccessAnalysis> page, Integer custNo) { SimpleDateFormat dateFmt = new SimpleDateFormat(WEB_BEHAVIOR_DT); page = this.accessAnalysisDao.getProductView(page, custNo); List<ProductViewDTO> dtoList = new ArrayList<ProductViewDTO>(); List list = page.getResult(); if (list != null) { for (int i = 0; i < list.size(); i++) { Object[] obj = (Object[]) list.get(i); ProductViewDTO dto = new ProductViewDTO(); ProductCategory temp = this.productCategoryDao .getById((Integer) obj[0]); if (temp != null) { dto.setProductName(temp.getName()); } dto.setViewTimes((Long) obj[1]); if (obj[2] != null) { dto.setFirstView(dateFmt.format((Date) obj[2])); } if (obj[3] != null) { dto.setLastView(dateFmt.format((Date) obj[3])); } dtoList.add(dto); } } page.setResult(null); Page<ProductViewDTO> pageViewDTO = dozer.map(page, Page.class); pageViewDTO.setResult(dtoList); return pageViewDTO; } /** * ๆœฌๆ–นๆณ•ไธๆ”ฏๆŒๅˆ†้กต. * * @param page * @param srchDTO * @return * @throws ParseException */ @Transactional(readOnly = true) public List<AnalysisReport> searchAnalysis(final PageDTO page, final AnalysisReportSrchDTO srchDTO) throws ParseException { List<AnalysisReport> dtoList = new ArrayList<AnalysisReport>(); SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd"); Date dEndDate = dateFmt.parse(srchDTO.getEndDate()); Date fromDate = dateFmt.parse(srchDTO.getBeginDate()); Integer custNo = srchDTO.getCustNo(); int period = srchDTO.getPeriod(); Date toDate = this.getToDate(page, srchDTO); boolean bLoop = true; for (; bLoop;) { String tempFromDate = dateFmt.format(fromDate); String tempToDate = dateFmt.format(toDate); // ๅฎž้™…ๅ‘็”Ÿๅˆฐๆ•ฐๆฎๅบ“็š„ๆ•ฐๆฎ่ฆๆฏ”ๆ˜พ็คบไธบDTO็š„ๅคงไธ€ๅคฉ๏ผŒ ๅฆๅˆ™ๅ–ไธๅˆฐ<=ๅŽ้ข็š„ๆ•ฐๆฎ. String actToDate = dateFmt.format(DateUtils.defineDayBefore2Object( toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date())); if (tempToDate.equals(srchDTO.getEndDate())) { bLoop = false; actToDate = tempToDate; } else if (!toDate.before(dEndDate)) { bLoop = false; tempToDate = srchDTO.getEndDate(); actToDate = tempToDate; } AnalysisReport report = new AnalysisReport(); report.setFromDate(tempFromDate); report.setToDate(tempToDate); report.setVisit(accessAnalysisDao.getAnalysisVisits(custNo, tempFromDate, actToDate)); report.setRefered(accessAnalysisDao.getAnalysisRefer(custNo, tempFromDate, actToDate)); report.setSearching(accessAnalysisDao.getAnalysisSearching(custNo, tempFromDate, actToDate)); report.setPageView(accessAnalysisDao.getAnalysisPageViewed(custNo, tempFromDate, actToDate)); report.setAvgViewTime(accessAnalysisDao.getAnalysisAvgPageStays( custNo, tempFromDate, actToDate)); dtoList.add(report); // ไธ‹ๆฌกๅพช็ŽฏไปŽๆœฌๆฌกๆˆชๆญขๆ—ฅๆœŸ็š„ๅŽไธ€ๅคฉๅผ€ๅง‹. fromDate = DateUtils.defineDayBefore2Object(toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); if (period == 1) { toDate = DateUtils.defineDayBefore2Object(toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } else if (period == 7) {// by week toDate = DateUtils.getWeekEndDay(fromDate); } else if (period == 30) {// by month toDate = DateUtils.getMonthEndDay(fromDate); } else if (period == 90) {// by quarter toDate = DateUtils.getQuarterEndDay(fromDate); } else if (period == 365) {// by year toDate = DateUtils.getYearEndDay(fromDate); } else { toDate = DateUtils.defineDayBefore2Object(toDate, period - 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } } return dtoList; } /** * ๆœฌๆ–นๆณ•ไธๆ”ฏๆŒๅˆ†้กต. * * @param * @param srchDTO * @return * @throws ParseException */ @Transactional(readOnly = true) public List<AnalysisReport> searchSalesStatistics( final SalesStaticsSrchDTO srchDTO) throws ParseException { List<AnalysisReport> dtoList = new ArrayList<AnalysisReport>(); SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd"); String fromDateStr = dateFmt.format(srchDTO.getBeginDate()); String toDateStr = dateFmt.format(srchDTO.getEndDate()); Date dEndDate = dateFmt.parse(toDateStr); Date fromDate = dateFmt.parse(fromDateStr); Integer custNo = srchDTO.getCustNo(); int period = srchDTO.getPeriod(); Date toDate = this.getToDate(srchDTO); boolean bLoop = true; for (; bLoop;) { String tempFromDate = dateFmt.format(fromDate); String tempToDate = dateFmt.format(toDate); // ๅฎž้™…ๅ‘็”Ÿๅˆฐๆ•ฐๆฎๅบ“็š„ๆ•ฐๆฎ่ฆๆฏ”ๆ˜พ็คบไธบDTO็š„ๅคงไธ€ๅคฉ๏ผŒ ๅฆๅˆ™ๅ–ไธๅˆฐ<=ๅŽ้ข็š„ๆ•ฐๆฎ. String actToDate = dateFmt.format(DateUtils.defineDayBefore2Object( toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date())); if (tempToDate.equals(srchDTO.getEndDate())) { bLoop = false; actToDate = tempToDate; } else if (!toDate.before(dEndDate)) { bLoop = false; tempToDate = toDateStr; actToDate = tempToDate; } AnalysisReport report = new AnalysisReport(); report.setFromDate(tempFromDate); report.setToDate(tempToDate); Map<String, Object> map = new HashMap<String, Object>(); map.put("custNo", custNo); map.put("fromDate", dateFmt.parse(tempFromDate)); map.put("toDate", dateFmt.parse(actToDate)); BigDecimal amountBD = new BigDecimal( orderDao.getSalesStatistics(map)); long amount = amountBD.divide(new BigDecimal(100)) .setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); report.setVisit(amount); dtoList.add(report); // ไธ‹ๆฌกๅพช็ŽฏไปŽๆœฌๆฌกๆˆชๆญขๆ—ฅๆœŸ็š„ๅŽไธ€ๅคฉๅผ€ๅง‹. fromDate = DateUtils.defineDayBefore2Object(toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); if (period == 1) { toDate = DateUtils.defineDayBefore2Object(toDate, 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } else if (period == 7) {// by week toDate = DateUtils.getWeekEndDay(fromDate); } else if (period == 30) {// by month toDate = DateUtils.getMonthEndDay(fromDate); } else if (period == 90) {// by quarter toDate = DateUtils.getQuarterEndDay(fromDate); } else if (period == 365) {// by year toDate = DateUtils.getYearEndDay(fromDate); } else { toDate = DateUtils.defineDayBefore2Object(toDate, period - 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } } return dtoList; } /** * ่Žทๅพ—็ฌฌไธ€ๆฌกๅพช็Žฏ็š„ๆˆชๆญขๆ—ฅๆœŸ. * * @param page * @param srchDTO * @return * @throws ParseException */ @Transactional(readOnly = true) private Date getToDate(final PageDTO page, final AnalysisReportSrchDTO srchDTO) throws ParseException { Date toDate = null; SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd"); Date dEndDate = dateFmt.parse(srchDTO.getEndDate()); Date fromDate = dateFmt.parse(srchDTO.getBeginDate()); int period = srchDTO.getPeriod(); if (period == 1) { toDate = fromDate; } else if (period == 7) {// by week toDate = DateUtils.getWeekEndDay(fromDate); } else if (period == 30) {// by month toDate = DateUtils.getMonthEndDay(fromDate); } else if (period == 90) {// by quarter toDate = DateUtils.getQuarterEndDay(fromDate); } else if (period == 365) {// by year toDate = DateUtils.getYearEndDay(fromDate); } else { toDate = DateUtils.defineDayBefore2Object(fromDate, period - 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } if (!toDate.before(dEndDate)) { toDate = dEndDate; } return toDate; } /** * ่Žทๅพ—็ฌฌไธ€ๆฌกๅพช็Žฏ็š„ๆˆชๆญขๆ—ฅๆœŸ. * * @param * @param srchDTO * @return * @throws ParseException */ private Date getToDate(final SalesStaticsSrchDTO srchDTO) throws ParseException { Date toDate = null; SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd"); String fromDateStr = dateFmt.format(srchDTO.getBeginDate()); String toDateStr = dateFmt.format(srchDTO.getEndDate()); Date dEndDate = dateFmt.parse(toDateStr); Date fromDate = dateFmt.parse(fromDateStr); int period = srchDTO.getPeriod(); if (period == 1) { toDate = fromDate; } else if (period == 7) {// by week toDate = DateUtils.getWeekEndDay(fromDate); } else if (period == 30) {// by month toDate = DateUtils.getMonthEndDay(fromDate); } else if (period == 90) {// by quarter toDate = DateUtils.getQuarterEndDay(fromDate); } else if (period == 365) {// by year toDate = DateUtils.getYearEndDay(fromDate); } else { toDate = DateUtils.defineDayBefore2Object(fromDate, period - 1, DateUtils.C_DATE_PATTON_DEFAULT, new Date()); } if (!toDate.before(dEndDate)) { toDate = dEndDate; } return toDate; } @Transactional(readOnly = true) public List<SalesOrderedDTO> getMostOrdered(Integer custNo, Integer top, String type) { return orderItemDao.getMostOrdered(custNo, top, type); } @Transactional(readOnly = true) public List<SalesOrderedDTO> getOrdersBy(Integer custNo, String ordersByType) { return orderItemDao.getOrdersBy(custNo, ordersByType); } @Transactional(readOnly = true) public String getPreferPaymentMthd(Integer custNo) { return customerDao.getPreferPaymentMthd(custNo); } /** * ไฟๅญ˜ไธ€ไธชCustomer็š„CreditCard. * * @param card * @param userId */ public Integer saveCreditCard(CreditCard card, Integer userId) { Date now = new Date(); card.setCreatedBy(userId); card.setModifiedBy(userId); card.setCreationDate(now); card.setModifyDate(now); card.setStatus("ACTIVE"); this.creditCardDao.save(card); return card.getId(); } /** * ๅˆ ้™คไธ€ไธชCreditCard. * * @param id * @param userId */ public void delCreditCard(Integer id, Integer userId) { this.creditCardDao.delCard(userId, id); } @Transactional(readOnly = true) public DefaultAddressDTO getDefaultAddress(final Integer custNo) { DefaultAddressDTO defaultAddressDTO = new DefaultAddressDTO(); Address billToAddr = addressDao.getDefaultBillTOAddress(custNo); Address shipToAddr = addressDao.getDefaultShipTOAddress(custNo); if (billToAddr != null) { defaultAddressDTO.setDefBillToAddr(dozer.map(billToAddr, CustAddrOperDTO.class)); } else { defaultAddressDTO.setDefBillToAddr(null); } if (shipToAddr != null) { defaultAddressDTO.setDefShipToAddr(dozer.map(shipToAddr, CustAddrOperDTO.class)); } else { defaultAddressDTO.setDefShipToAddr(null); } return defaultAddressDTO; } /** * ่Žทๅพ—ไธ€ไธชCustomer็š„ๆ‰€ๆœ‰note๏ผŒ ๆฏไธชNoteๅˆๅŒ…ๅซdocumentList. * * @param custNo * @return */ @Transactional(readOnly = true) public List<CustNoteDTO> getNoteList(Integer custNo) { List<CustNoteDTO> dtoList = new ArrayList<CustNoteDTO>(); List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter quoteFilter = new PropertyFilter("EQI_custNo", custNo); filterList.add(quoteFilter); List<CustomerNote> noteList = this.customerNoteDao.find(filterList); if (noteList != null) { for (CustomerNote note : noteList) { CustNoteDTO dto = dozer.map(note, CustNoteDTO.class); List<PropertyFilter> docFilterList = new ArrayList<PropertyFilter>(); PropertyFilter refIdFilter = new PropertyFilter("EQI_refId", note.getId()); PropertyFilter refTypeFilter = new PropertyFilter( "EQS_refType", DocumentType.CUSTOMER_NOTE_TYPE.value()); docFilterList.add(refIdFilter); docFilterList.add(refTypeFilter); List<NoteDocument> docList = this.noteDocumentDao .find(docFilterList); dto.setDocumentList(docList); dtoList.add(dto); } } return dtoList; } /** * ๅˆๅนถๅคšไธชcustomer. * * @param masterNo * @param slaveNoList * @param userId */ public void combineCustomer(Integer masterNo, List<Integer> slaveNoList, Integer userId) { for (Integer slaveNo : slaveNoList) { this.combineCustomer(masterNo, slaveNo, userId); } } /** * ๅˆๅนถไธคไธชCustomer. * * @param masterNo * @param slaveNo * @param userId */ private void combineCustomer(Integer masterNo, Integer slaveNo, Integer userId) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); PropertyFilter custNoFilter = new PropertyFilter("EQI_custNo", slaveNo); filterList.add(custNoFilter); Date now = new Date(); // CustomerPoints CustomerPoints slavePoint = this.customerPointsDao.getById(slaveNo); if (slavePoint != null) { CustomerPoints custPoint = this.customerPointsDao.getById(masterNo); if (custPoint == null) { custPoint = new CustomerPoints(); custPoint.setCustNo(masterNo); custPoint.setCreatedBy(userId); custPoint.setCreationDate(now); custPoint.setPointsAvailable(0); custPoint.setPointsHistory(0); custPoint.setPointsUsed(0); } custPoint.setPointsAvailable(slavePoint.getPointsAvailable() + custPoint.getPointsAvailable()); custPoint.setPointsHistory(slavePoint.getPointsHistory() + custPoint.getPointsHistory()); custPoint.setPointsUsed(slavePoint.getPointsUsed() + custPoint.getPointsUsed()); custPoint.setModifiedBy(userId); custPoint.setModifyDate(now); this.customerPointsDao.save(custPoint); } // CustomerContactHistory List<CustomerContactHistory> conactList = this.custContactHistDao .find(filterList); for (int i = 0; conactList != null && i < conactList.size(); i++) { CustomerContactHistory db = conactList.get(i); this.custContactHistDao.getSession().evict(db); db.setContactId(null); db.setCustNo(masterNo); db.setModifiedBy(userId); db.setStatus("ACTIVE"); db.setModifyDate(now); this.custContactHistDao.save(db); } // TODO ๆš‚ไธ”ๅŽปๆމMoreInfo. // More info. // this.combinCustMoreInfo(masterNo, slaveNo, userId, filterList); // Order, TemplateOrder, Quote, TemplateQuote. this.orderDao.updateCustomer(slaveNo, masterNo, userId); this.quoteDao.updateCustomer(slaveNo, masterNo, userId); // INVALID slave Customer. String reason = "Combined to new customer #" + masterNo; this.customerDao.delSlaveCustomer(userId, slaveNo, reason); this.customerDao.ActiveMasterCustomer(userId, masterNo, reason); Customer slaveCust = this.customerDao.getById(slaveNo); this.customerDao.getSession().evict(slaveCust); CustomerStatusHistory log = new CustomerStatusHistory(); log.setCustNo(slaveNo); log.setUpdateDate(new Date()); User updateUser = new User(); updateUser.setUserId(userId); log.setUpdatedBy(updateUser); log.setUpdateReason(reason); log.setCurrentStat("INACTIVE"); log.setPriorStat(slaveCust.getStatus()); this.customerStatusHistoryDao.save(log); } /** * ๅˆๅนถไธคไธชCustomerๆ—ถ๏ผŒ ๅˆๅนถๅฎƒไปฌ็š„More information. AccessAnalysis, AccessLog, Visit, * CustomerGrants, CustomerPublication, CustomerCase. * * @param masterNo * @param slaveNo * @param userId * @param filterList */ @SuppressWarnings("unused") private void combinCustMoreInfo(Integer masterNo, Integer slaveNo, Integer userId, List<PropertyFilter> filterList) { Date now = new Date(); // AccessLog List<AccessLog> agList = this.accessLogDao.find(filterList); for (int i = 0; agList != null && i < agList.size(); i++) { AccessLog db = agList.get(i); Integer srcLogId = db.getLogId(); this.accessLogDao.getSession().evict(db); db.setLogId(null); db.setCustNo(masterNo); this.accessLogDao.save(db); Integer newLogId = db.getLogId(); // AccessAnalysis AccessAnalysis analysis = accessAnalysisDao.getById(srcLogId); if (analysis != null) { this.accessAnalysisDao.getSession().evict(analysis); analysis.setLogId(newLogId); analysis.setCustNo(masterNo); this.accessAnalysisDao.save(analysis); } } // Visit List<Visit> visitList = this.visitDao.find(filterList); for (int i = 0; visitList != null && i < visitList.size(); i++) { Visit db = visitList.get(i); this.visitDao.getSession().evict(db); db.setVisitId(null); db.setCustNo(masterNo); this.visitDao.save(db); } // CustomerGrants List<CustomerGrants> grantList = this.customerGrantsDao .find(filterList); for (int i = 0; grantList != null && i < grantList.size(); i++) { CustomerGrants db = grantList.get(i); this.customerGrantsDao.getSession().evict(db); db.setGrantId(null); db.setCustNo(masterNo); db.setModifiedBy(userId); db.setModifyDate(now); this.customerGrantsDao.save(db); } // CustomerPublication List<CustomerPublications> pubsList = this.customerPublicationDao .find(filterList); for (int i = 0; pubsList != null && i < pubsList.size(); i++) { CustomerPublications db = pubsList.get(i); this.customerPublicationDao.getSession().evict(db); db.setId(null); db.setCustNo(masterNo); db.setModifiedBy(userId); db.setModifyDate(now); this.customerPublicationDao.save(db); } // CustomerCase List<CustomerCase> caseList = this.customerCaseDao.find(filterList); for (int i = 0; caseList != null && i < caseList.size(); i++) { CustomerCase db = caseList.get(i); this.customerCaseDao.getSession().evict(db); db.setCaseId(null); db.setCustNo(masterNo); db.setModifiedBy(userId); db.setModifyDate(now); this.customerCaseDao.save(db); } } public void sendCustMailJob() { List<CustomerContactHistory> custContactHistoryList = null; custContactHistoryList = custContactHistDao.queryMailSend(); if (custContactHistoryList != null && custContactHistoryList.size() > 0) { for (CustomerContactHistory his : custContactHistoryList) { String mailTo = his.getEmail(); String content = his.getContent(); String subject = his.getSubject(); if (StringUtils.isNotBlank(mailTo)) { mimeMailService.sendMail(mailTo, subject, content, "scm_admin@genscriptcorp.com"); his.setStatus("COMPLETE"); custContactHistDao.save(his); } } } } @Transactional(readOnly = true) public Page<CustomerBean> advSearchCustomer(Page<CustomerBean> page, List<PropertyFilter> filters, Set<Integer> custNoSet) throws Exception { List<Criterion> criterionList = new ArrayList<Criterion>(); String userName = SessionUtil.getUserName(); // ๅˆคๆ–ญๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅซๆœ‰้”€ๅ”ฎ็ป็†่ง’่‰ฒ boolean salesManager = userRoleDao .checkIsContainsManagerRole(Constants.ROLE_SALES_MANAGER); if (Constants.USERNAME_ADMIN.equals(userName) || salesManager) { page = customerBeanDao.advSearchCustomer(page, criterionList, filters, custNoSet); return page; } // ๅˆคๆ–ญๅฝ“ๅ‰็”จๆˆทๆ˜ฏๅฆๅซๆœ‰ๅ†…้ƒจ่ฎขๅ•็ฎก็†ๅ‘˜่ง’่‰ฒ๏ผŒๆ˜ฏ๏ผŒๅˆ™ๆŸฅ่ฏข่‡ชๅทฑ้ƒจ้—จ็š„customer boolean internalOrderManager = userRoleDao .checkIsContainsManagerRole(Constants.ROLE_INTERNAL_ORDER_MANAGER); if (internalOrderManager) { if (filters == null || filters.isEmpty()) { filters = new ArrayList<PropertyFilter>(); } filters.add(new PropertyFilter("EQS_custType", Constants.INTERNAL_TYPE_CUSTOMER)); } else { Map<String, Object> salesRoleAndUserIdsMap = salesRepDao .getSameGroupUser(); if (salesRoleAndUserIdsMap.get("function") != null && salesRoleAndUserIdsMap.get("User_Ids") != null) { String salesRole = salesRoleAndUserIdsMap.get("function") .toString(); Integer[] userIdsArr = (Integer[]) salesRoleAndUserIdsMap .get("User_Ids"); if (SalesRepSalesRole.SALES_CONTACT.value().equals(salesRole)) { Criterion criterionSalesContact = Restrictions.in( "salesContactId", userIdsArr); criterionList.add(criterionSalesContact); } else if (SalesRepSalesRole.TECH_SUPPORT.value().equals( salesRole)) { Criterion criterionSalesContact = Restrictions.in( "techSupportId", userIdsArr); criterionList.add(criterionSalesContact); } } } page = customerBeanDao.advSearchCustomer(page, criterionList, filters, custNoSet); return page; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Transactional(readOnly = true) public Page<ServiceViewDTO> getAccessServiceView(Page<AccessAnalysis> page, Integer custNo) { SimpleDateFormat dateFmt = new SimpleDateFormat(WEB_BEHAVIOR_DT); page = this.accessAnalysisDao.getServiceView(page, custNo); List<ServiceViewDTO> dtoList = new ArrayList<ServiceViewDTO>(); List list = page.getResult(); if (list != null) { for (int i = 0; i < list.size(); i++) { Object[] obj = (Object[]) list.get(i); ServiceViewDTO dto = new ServiceViewDTO(); ServiceCategory temp = this.serviceCategoryDao .getById((Integer) obj[0]); if (temp != null) { dto.setServiceName(temp.getName()); } dto.setViewTimes((Long) obj[1]); if (obj[2] != null) { dto.setFirstView(dateFmt.format((Date) obj[2])); } if (obj[3] != null) { dto.setLastView(dateFmt.format((Date) obj[3])); } dtoList.add(dto); } } page.setResult(null); Page<ServiceViewDTO> pageViewDTO = dozer.map(page, Page.class); pageViewDTO.setResult(dtoList); return pageViewDTO; } /* * public Page<SampleRequestDTO> * getSampleRequestDTOPage(Page<SampleRequestDTO>page, Integer custNo){ * page= this.orderDao. } */ public boolean sendEmailToCustomer(List<File> upload, List<String> uploadContentType, List<String> uploadFileName, Integer custNo, String customerBusEmail, String subject, String content) throws Exception { boolean sendStatus = false; try { if (custNo != null && custNo > 0 && customerBusEmail != null && !("").equals(customerBusEmail)) { Customer customer = customerDao.get(custNo); if (customer != null && customerBusEmail.equals(customer.getBusEmail())) { // ็›ฎๅ‰้กต้ขไธŠๅช่ƒฝไธ€ๆฌกไธŠไผ ไธ€ไธชๆ–‡ไปถ. List<String> fileNameList = new ArrayList<String>(); Date now = new Date(); Map<String, Object> session = ActionContext.getContext() .getSession(); Object userId = session.get(StrutsActionContant.USER_ID); String logName = session.get(StrutsActionContant.USER_NAME) .toString(); if (upload != null && upload.size() > 0) { for (int i = 0; i < upload.size(); i++) { String srcFileName = uploadFileName.get(i); uploadFileName.set(i, SessionUtil.generateTempId() + "_" + srcFileName); fileNameList.add(uploadFileName.get(i)); // ๅฐ†ไธŠไผ ็š„ๆ–‡ไปถ่ฎฐๅฝ•ไธ‹ๆฅ Document doc = new Document(); doc.setCreatedBy((Integer) userId); doc.setModifiedBy((Integer) userId); doc.setCreationDate(now); doc.setModifyDate(now); doc.setRefId(custNo); doc.setRefType(DocumentType.CUSTOMER_NOTE_TYPE .value()); doc.setDocName(srcFileName); doc.setFilePath("customerService/" + uploadFileName.get(i)); this.documentDao.save(doc); } fileService.uploadFile(upload, uploadContentType, uploadFileName, FilePathConstant.Email_Customer.value()); } String realPath = FilePathConstant.Email_Customer.value(); // ๅ‘้€้‚ฎไปถ mimeMailService.sendMail(customerBusEmail, subject, content, realPath, fileNameList); // ไฟๅญ˜ๅ‘้€้‚ฎไปถ่ฎฐๅฝ• CustomerContactHistory his = new CustomerContactHistory(); his.setEmail(customerBusEmail); his.setContent(content); his.setSubject(subject); his.setCustNo(custNo); his.setContactMethod("EMail"); his.setStatus("COMPLETED"); his.setCreationDate(now); his.setCreatedBy((Integer) userId); his.setModifyDate(now); his.setModifiedBy((Integer) userId); his.setContactBy((Integer) userId); his.setContactDate(now); his.setContactName(logName); his.setStatus("COMPLETE"); custContactHistDao.save(his); sendStatus = true; } } } catch (Exception ex) { return sendStatus; } return sendStatus; } /** * ๆŸฅ่ฏขcustomerๅฏๅ…‘ๆข็š„GiftCard * * @param * @return * @throws Exception * @author zhangyong */ @SuppressWarnings("unchecked") public void searchCustomerAvailableCard() throws Exception { String paramCustNo = ServletActionContext.getRequest().getParameter( "custNo"); Customer customer = this.customerDao.findUniqueBy("custNo", Integer.parseInt(paramCustNo.trim())); ServletActionContext.getRequest().setAttribute("custNo", paramCustNo); ServletActionContext.getRequest().setAttribute("firstName", customer.getFirstName()); ServletActionContext.getRequest().setAttribute("lastName", customer.getLastName()); ServletActionContext.getRequest().setAttribute("email", customer.getBusEmail()); // ่Žทๅพ—ๅฝ“ๅ‰็š„Customerๅฏ็”จ็งฏๅˆ† Integer custPointsHistSum = customerPointsHistoryDao .getCustomerPointsSumByCustNo(customer.getCustNo()).intValue(); // ่Žทๅพ—Customerๅฏ็”จ็งฏๅˆ†ๅฏไปฅๅ…‘ๆข็š„Amazonๅก List<GiftCard> giftCardlist = giftCardDao .findGiftCardByValue(custPointsHistSum / 200); if (giftCardlist != null && giftCardlist.size() > 0) { GiftCard giftCard = giftCardlist.get(0); ServletActionContext.getRequest().setAttribute("redeemGiftCard", giftCard); } // ่Žทๅพ—ๆ‰€ๆœ‰็š„ๆœช่ขซๅ…‘ๆข็š„coupon List<Coupon> couponlist = this.couponDao.findAvaliableCoupon(); ServletActionContext.getRequest().setAttribute("redeemCouponList", couponlist); // ๅฐ†่ฆๅ…‘ๆข็š„customer custNoๅญ˜ๅ…ฅsessionไธญ Integer userId = SessionUtil.getUserId(); Map<String, Object> sessionMap = (HashMap<String, Object>) SessionUtil .getRow(SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId)); if (sessionMap == null) { sessionMap = new HashMap<String, Object>(); } sessionMap.put("sessionCustNo", paramCustNo.trim()); SessionUtil.insertRow( SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId), sessionMap); } /** * ้€š่ฟ‡cardIdๆŸฅ่ฏข * * @param * @return * @author zhangyong */ @SuppressWarnings("unchecked") public boolean searchGiftCardByCardId() throws Exception { boolean status = false; String requestCustNo = ServletActionContext.getRequest().getParameter( "custNo"); if (requestCustNo == null || ("").equals(requestCustNo.trim())) { return status; } Customer reqCustomer = this.customerDao.findUniqueBy("custNo", Integer.parseInt(requestCustNo.trim())); // ่Žทๅพ—ๅฝ“ๅ‰็š„Customerๅฏ็”จ็งฏๅˆ† Integer reqCustPointsHistSum = customerPointsHistoryDao .getCustomerPointsSumByCustNo(reqCustomer.getCustNo()) .intValue(); // ่Žทๅพ—Customerๅฏ็”จ็งฏๅˆ†ๅฏไปฅๅ…‘ๆข็š„Amazonๅก List<GiftCard> reqGiftCardlist = giftCardDao .findGiftCardByValue(reqCustPointsHistSum / 200); if (reqGiftCardlist != null && reqGiftCardlist.size() > 0) { GiftCard giftCard = reqGiftCardlist.get(0); ServletActionContext.getRequest().setAttribute("redeemGiftCard", giftCard); } String couponIdValues = Struts2Util.getParameter("couponIdValues"); String requestFirstName = Struts2Util.getParameter("firstName"); String requestLastName = Struts2Util.getParameter("lastName"); String requestEmail = Struts2Util.getParameter("email"); String requestGiftCardId = Struts2Util.getParameter("giftCardId"); Integer userId = SessionUtil.getUserId(); ServletActionContext.getRequest().setAttribute("custNo", requestCustNo); ServletActionContext.getRequest().setAttribute("firstName", requestFirstName); ServletActionContext.getRequest().setAttribute("lastName", requestLastName); ServletActionContext.getRequest().setAttribute("email", requestEmail); // ่Žทๅพ—ๆ‰€ๆœ‰็š„ๆœช่ขซๅ…‘ๆข็š„coupon List<Coupon> couponlist = this.couponDao.findAvaliableCoupon(); ServletActionContext.getRequest().setAttribute("redeemCouponList", couponlist); Map<String, Object> sessionMap = (HashMap<String, Object>) SessionUtil .getRow(SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId)); if (sessionMap == null) { return status; } String sessionCustNo = (String) sessionMap.get("sessionCustNo"); if (!requestCustNo.equals(sessionCustNo)) { return status; } Customer customer = this.customerDao.findByCustNo(Integer .parseInt(sessionCustNo)); // ่Žทๅพ—ๅฝ“ๅ‰็š„Customerๅฏ็”จ็งฏๅˆ† Integer custPointsHistSum = customerPointsHistoryDao .getCustomerPointsSumByCustNo(customer.getCustNo()).intValue(); GiftCard searchGiftCard = null; if (requestGiftCardId != null && !("").equals(requestGiftCardId.trim())) { searchGiftCard = this.giftCardDao.findById(Integer .parseInt(requestGiftCardId.trim())); if (searchGiftCard == null) { ServletActionContext.getRequest().setAttribute("message", "Data anomalies, please re-exchange!"); return status; } // ่Žทๅพ—Customerๅฏ็”จ็งฏๅˆ†ๅฏไปฅๅ…‘ๆข็š„Amazonๅก List<GiftCard> giftCardlist = giftCardDao .findGiftCardByValue(custPointsHistSum / 200); if (giftCardlist != null && giftCardlist.size() > 0) { GiftCard giftCard = giftCardlist.get(0); if (giftCard.getId().intValue() != searchGiftCard.getId() .intValue()) { ServletActionContext.getRequest().setAttribute( "message", "You can only exchange $" + giftCard.getCardValue() + " amazon card"); // ่ฟ”ๅ›žๅˆฐๅ…‘ๆข้กต้ข return status; } ServletActionContext.getRequest().setAttribute( "redeemGiftCard", giftCard); } } int countCouponValue = 0; Map<String, Map<String, Coupon>> couponMap = new HashMap<String, Map<String, Coupon>>(); if (couponIdValues != null && !("").equals(couponIdValues.trim())) { if (couponlist == null || couponlist.size() == 0) { ServletActionContext.getRequest().setAttribute("message", "There are no available GenScript coupons!"); // ่ฟ”ๅ›žๅˆฐๅ…‘ๆข้กต้ข return status; } Map<String, String> couponIdsMap = new HashMap<String, String>(); for (Coupon inCoupon : couponlist) { couponIdsMap.put(inCoupon.getId().toString(), null); } String[] couponIdValueArr = couponIdValues.trim().split(","); for (String couponIdValue : couponIdValueArr) { if (couponIdValue != null && couponIdValue.trim().contains("-")) { String[] idNum = couponIdValue.trim().split("-"); if (idNum.length == 2) { String id = idNum[0]; String num = idNum[1]; if (Integer.parseInt(num) <= 0) { continue; } Coupon coupon = this.couponDao.findUniqueBy("id", Integer.parseInt(id)); if (coupon == null || !couponIdsMap.containsKey(coupon.getId() .toString())) { continue; } Map<String, Coupon> couponNum = new HashMap<String, Coupon>(); couponNum.put(num, coupon); couponMap.put(id, couponNum); } } } } if (searchGiftCard != null || couponMap.size() > 0) { if (searchGiftCard != null) { custPointsHistSum = custPointsHistSum - searchGiftCard.getCardValue() * 200; } if (couponMap.size() > 0) { for (String key : couponMap.keySet()) { Map<String, Coupon> couponNum = couponMap.get(key); for (String inKey : couponNum.keySet()) { countCouponValue += Integer.parseInt(inKey) * couponNum.get(inKey).getValue(); } } } custPointsHistSum = custPointsHistSum - countCouponValue * 100; // ็งฏๅˆ†ไธๅคŸ if (custPointsHistSum < 0) { if (searchGiftCard != null) { ServletActionContext.getRequest().setAttribute( "redeemGiftCard", searchGiftCard); } ServletActionContext.getRequest().setAttribute("message", "Your points is not enough to redeem!"); return status; } if (searchGiftCard != null) { sessionMap.put("sessionGiftCard", searchGiftCard); ServletActionContext.getRequest().setAttribute( "searchGiftCard", searchGiftCard); } if (couponMap.size() > 0) { List<CouponDTO> couponDTOlist = new ArrayList<CouponDTO>(); for (String key : couponMap.keySet()) { Map<String, Coupon> couponNum = couponMap.get(key); for (String inKey : couponNum.keySet()) { Coupon inCoupon = couponNum.get(inKey); CouponDTO couponDTO = new CouponDTO(); couponDTO.setId(inCoupon.getId()); couponDTO.setCode(StringUtil.getIntRandom(9)); couponDTO.setName(inCoupon.getName()); couponDTO.setValue(inCoupon.getValue()); couponDTO.setExprDate(inCoupon.getExprDate()); couponDTO.setStatus(inCoupon.getStatus()); couponDTO.setComments(inCoupon.getComments()); couponDTO.setNumber(Integer.parseInt(inKey)); couponDTOlist.add(couponDTO); } } ServletActionContext.getRequest().setAttribute("couponDTOlist", couponDTOlist); sessionMap.put("sessionCouponDTOList", couponDTOlist); } sessionMap.put("sessionFrstName", requestFirstName.trim()); sessionMap.put("sessionLastName", requestLastName); sessionMap.put("sessionEmail", requestEmail); SessionUtil.insertRow( SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId), sessionMap); status = true; } else { ServletActionContext .getRequest() .setAttribute("message", "Please select a amazon card or fill the number of GenScript coupons!"); } return status; } /** * ไฟๅญ˜็งฏๅˆ†ๅ…‘ๆขไผ˜ๆƒ ๅˆธ๏ผŒๆ›ดๆ–ฐๆ•ฐๆฎๅบ“ * * @return * @author zhangyong */ @SuppressWarnings("unchecked") public boolean saveRedeemPoint() throws Exception { boolean status = false; Integer userId = SessionUtil.getUserId(); Map<String, Object> sessionMap = (HashMap<String, Object>) SessionUtil .getRow(SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId)); if (sessionMap == null) { return status; } String sessionCustNo = (String) sessionMap.get("sessionCustNo"); if (sessionCustNo == null || ("").equals(sessionCustNo)) { return status; } String sessionFrstName = (String) sessionMap.get("sessionFrstName"); if (sessionFrstName == null || ("").equals(sessionFrstName)) { return status; } String sessionLastName = (String) sessionMap.get("sessionLastName"); if (sessionLastName == null || ("").equals(sessionLastName)) { return status; } String sessionEmail = (String) sessionMap.get("sessionEmail"); if (sessionEmail == null || ("").equals(sessionEmail)) { return status; } ServletActionContext.getRequest().setAttribute("custNo", sessionCustNo); ServletActionContext.getRequest().setAttribute("firstName", sessionFrstName); ServletActionContext.getRequest().setAttribute("lastName", sessionLastName); ServletActionContext.getRequest().setAttribute("email", sessionEmail); // ่Žทๅพ—ๆ‰€ๆœ‰็š„ๆœช่ขซๅ…‘ๆข็š„coupon List<Coupon> couponlistToRequest = this.couponDao.findAvaliableCoupon(); ServletActionContext.getRequest().setAttribute("redeemCouponList", couponlistToRequest); GiftCard sessionGiftCard = (GiftCard) sessionMap.get("sessionGiftCard"); ServletActionContext.getRequest().setAttribute("redeemGiftCard", sessionGiftCard); List<CouponDTO> sessionCouponDTOList = (List<CouponDTO>) sessionMap .get("sessionCouponDTOList"); if ((sessionGiftCard != null) || (sessionCouponDTOList != null && sessionCouponDTOList.size() > 0)) { Date nowDate = new Date(); StringBuffer successMsg = new StringBuffer(); StringBuffer emailMsg = new StringBuffer(); emailMsg.append( "Dear " + sessionFrstName + sessionLastName + ".<br/>") .append("<center>You have successfully redeemed:<br/>"); Integer custPointsHistSum = customerPointsHistoryDao .getCustomerPointsSumByCustNo( Integer.parseInt(sessionCustNo)).intValue(); if (sessionGiftCard != null) { GiftCard giftCard = giftCardDao.findGiftCardByValue( custPointsHistSum / 200).get(0); ServletActionContext.getRequest().setAttribute( "redeemGiftCard", giftCard); if (sessionGiftCard.getId().intValue() != giftCard.getId() .intValue()) { ServletActionContext.getRequest().setAttribute( "message", "You can only exchange $" + giftCard.getCardValue() + " amazon card."); // ่ฟ”ๅ›žๅˆฐๅ…‘ๆข้กต้ข return status; } successMsg.append(sessionGiftCard.getCardValue() * 200 + " points for 1 $" + sessionGiftCard.getCardValue() + " Amazon Gift Card.<br />"); emailMsg.append(sessionGiftCard.getCardValue() * 200 + " points for 1 $" + sessionGiftCard.getCardValue() + " Amazon Gift Card.<br/>"); custPointsHistSum = custPointsHistSum - sessionGiftCard.getCardValue() * 200; } int countCouponValue = 0; List<Coupon> couponlist = new ArrayList<Coupon>(); if (sessionCouponDTOList != null && sessionCouponDTOList.size() > 0) { ServletActionContext.getRequest().setAttribute( "redeemCouponDTOList", sessionCouponDTOList); for (CouponDTO couponDTO : sessionCouponDTOList) { int dtocardValue = couponDTO.getNumber() * couponDTO.getValue(); countCouponValue += dtocardValue; successMsg.append(dtocardValue * 100 + " points for " + couponDTO.getNumber() + " $" + couponDTO.getValue() + " GenScript Coupon(s).<br />"); emailMsg.append(dtocardValue * 100 + " points for " + couponDTO.getNumber() + " $" + couponDTO.getValue() + " GenScript Coupon(s).<br/>"); for (int i = 0; i < couponDTO.getNumber(); i++) { Coupon incoupon = new Coupon(); incoupon.setCustNo(Integer.parseInt(sessionCustNo)); incoupon.setCode(couponDTO.getCode()); incoupon.setName(couponDTO.getName()); incoupon.setValue(couponDTO.getValue()); incoupon.setCreationDate(nowDate); incoupon.setCreatedBy(userId); // incoupon.setExprDate(couponDTO.getExprDate()); incoupon.setStatus(StatusType.ACTIVE.value()); incoupon.setComments(couponDTO.getComments()); // incoupon.setConfirmDate(nowDate); // incoupon.setConfirmedBy(userId); couponlist.add(incoupon); } } custPointsHistSum = custPointsHistSum - countCouponValue * 100; } // ็งฏๅˆ†ไธๅคŸ if (custPointsHistSum < 0) { if (sessionGiftCard != null) { ServletActionContext.getRequest().setAttribute( "redeemGiftCard", sessionGiftCard); } ServletActionContext.getRequest().setAttribute("message", "Your points is not enough to redeem!"); return status; } // ไฟๅญ˜ๅ…‘ๆขamazon่ฎฐๅฝ• if (sessionGiftCard != null) { // CustomerPointsHistory customerPointsHistory = new CustomerPointsHistory(); customerPointsHistory .setCustNo(Integer.parseInt(sessionCustNo)); customerPointsHistory.setIssueDate(nowDate); customerPointsHistory .setPoints(-sessionGiftCard.getCardValue() * 200); this.customerPointsHistoryDao.save(customerPointsHistory); // GiftCard newGiftCard = this.giftCardDao.findUniqueBy("id", sessionGiftCard.getId()); newGiftCard.setSendDate(nowDate); newGiftCard.setSentBy(userId); newGiftCard.setCustNo(Integer.parseInt(sessionCustNo)); this.giftCardDao.save(newGiftCard); } // ไฟๅญ˜ๅ…‘ๆขGenscript Coupon่ฎฐๅฝ• if (countCouponValue > 0) { CustomerPointsHistory customerPointsHistory = new CustomerPointsHistory(); customerPointsHistory .setCustNo(Integer.parseInt(sessionCustNo)); customerPointsHistory.setIssueDate(nowDate); customerPointsHistory.setPoints(-countCouponValue * 100); this.customerPointsHistoryDao.save(customerPointsHistory); for (Coupon inlistcoupon : couponlist) { this.couponDao.save(inlistcoupon); } } String subject = "Redeem Point"; emailMsg.append("</center>"); // ๅ‘้€้‚ฎไปถ mimeMailService.sendMail(sessionEmail, subject, emailMsg.toString(), "scm_admin@genscriptcorp.com"); // ไฟๅญ˜ๅ‘้€้‚ฎไปถ่ฎฐๅฝ• CustomerContactHistory his = new CustomerContactHistory(); his.setEmail(sessionEmail); his.setContent(emailMsg.toString()); his.setSubject(subject); his.setCustNo(Integer.parseInt(sessionCustNo)); his.setContactMethod("EMail"); his.setStatus("COMPLETED"); his.setCreationDate(nowDate); his.setCreatedBy((Integer) userId); his.setModifyDate(nowDate); his.setModifiedBy((Integer) userId); his.setContactBy((Integer) userId); his.setContactDate(nowDate); his.setContactName(sessionFrstName + sessionLastName); his.setStatus("COMPLETE"); custContactHistDao.save(his); // ๆธ…้™คsession SessionUtil.deleteRow( SessionConstant.RedeemPointCustomerManagement.value(), String.valueOf(userId)); ServletActionContext.getRequest().setAttribute("successMsg", successMsg.toString()); status = true; } else { ServletActionContext .getRequest() .setAttribute("message", "Please select a amazon card or fill the number of GenScript coupons!"); } return status; } /** * ้€š่ฟ‡custNoๆŸฅ่ฏขๅ…‘ๆขไผ˜ๆƒ ๅˆธ็š„ๅކๅฒ่ฎฐๅฝ• */ public Page<RedeemHistoryDTO> searchCustomerRedeemCouponHistory( Page<RedeemHistoryDTO> redeemPage, String paramCustNo, String p_no) { Customer customer = this.customerDao.findUniqueBy("custNo", Integer.parseInt(paramCustNo.trim())); if (customer != null) { List<RedeemHistoryDTO> redeemHistoryDTOList = new ArrayList<RedeemHistoryDTO>(); List<Coupon> couponlist = this.couponDao .findCouponByCustNo(customer.getCustNo()); List<GiftCard> giftCardlist = this.giftCardDao .findGiftCardByCustNo(customer.getCustNo()); if (giftCardlist != null && giftCardlist.size() > 0) { for (GiftCard giftCard : giftCardlist) { RedeemHistoryDTO redeemHistoryDTO = new RedeemHistoryDTO(); redeemHistoryDTO.setRedeemDate(giftCard.getSendDate()); redeemHistoryDTO .setRedeemedPoints(giftCard.getCardValue() * 200); redeemHistoryDTO.setCouponCode("*"); redeemHistoryDTO.setCouponValue(giftCard.getCardValue()); redeemHistoryDTO.setExpirationDate(new Date()); redeemHistoryDTO.setComments("Amazon Gift Card"); redeemHistoryDTO.setStatus("--"); redeemHistoryDTOList.add(redeemHistoryDTO); } } if (couponlist != null && couponlist.size() > 0) { for (Coupon coupon : couponlist) { RedeemHistoryDTO redeemHistoryDTO = new RedeemHistoryDTO(); redeemHistoryDTO.setRedeemDate(coupon.getCreationDate()); redeemHistoryDTO.setRedeemedPoints(coupon.getValue() * 100); redeemHistoryDTO.setCouponCode(coupon.getCode()); redeemHistoryDTO.setCouponValue(coupon.getValue()); redeemHistoryDTO.setExpirationDate(coupon.getExprDate()); redeemHistoryDTO.setComments(coupon.getComments()); redeemHistoryDTO.setStatus(coupon.getStatus()); redeemHistoryDTOList.add(redeemHistoryDTO); } } List<RedeemHistoryDTO> pageList = new ArrayList<RedeemHistoryDTO>(); int pageNo = redeemPage.getPageNo(); if (!StringUtils.isEmpty(p_no) && StringUtils.isNumeric(p_no)) { pageNo = Integer.parseInt(p_no); redeemPage.setPageNo(pageNo); } for (int i = (pageNo - 1) * redeemPage.getPageSize(); i < redeemHistoryDTOList .size(); i++) { pageList.add(redeemHistoryDTOList.get(i)); if (pageList.size() == redeemPage.getPageSize()) { break; } } redeemPage.setResult(pageList); redeemPage.setTotalCount(Long.valueOf(redeemHistoryDTOList.size())); } else { redeemPage.setTotalCount(0l); } return redeemPage; } /** * ่Žทๅพ—customer ็š„ไฟก็”จ้ขๅบฆใ€‚ * * @param custNo * @param toCurrency * @return */ public Double getCreditLimit(Integer custNo, String toCurrency) { // ็ฒพๅบฆ int scale = 2; if ("JPY".equalsIgnoreCase(toCurrency)) { scale = 0; } Customer customer = customerDao.get(custNo); Integer crRatingId = customer.getCrRatingId(); if (crRatingId != null) { CreditRating creditRating = creditRatingDao.get(crRatingId); Double crLimit = creditRating.getCrLimit(); Double rate = exchRateByDateDao.getCurrencyRate("USD", toCurrency, new Date()); if (rate != null) { crLimit = ArithUtil.mul(crLimit, rate, scale); return crLimit; } } return null; } /** * ๆŸฅ่ฏขbusEmail * * @param custNo * @return * @author zhangyong */ public String findBusEmailByCustNo(Integer custNo) { Customer customer = this.customerDao.findByCustNo(custNo); if (customer != null) { return customer.getBusEmail(); } return null; } /** * ๆฃ€ๆŸฅcustomer็š„Business E-Mailๅ’Œๆœบๆž„ๆ˜ฏๅฆๅœจ้ป‘ๅๅ•ไธญ * * @author Zhang Yong * @param custNo * @return */ public String checkCustomer(int custNo) { String message = ""; Customer customer = this.customerDao.findByCustNo(custNo); if (customer == null) { message = "The customer:" + custNo + " is not exist."; } else if (customer.getBusEmail() == null) { message = "The customer:" + custNo + " Business E-Mail is null."; } else if (customer.getOrgId() == null) { message = "The customer:" + custNo + " organization is null."; } else { Organization organization = organizationDao.getById(customer .getOrgId()); if (organization == null) { message = "The customer:" + custNo + " organization:" + customer.getOrgId() + " is not exist."; } else { Address shipToAddr = addressDao.getDefaultShipTOAddress(custNo); if (shipToAddr == null) { message = "The customer:" + custNo + " shipTo Address is null."; } else { boolean inBlackListFlag = false; String dialog = " This account is temporary suspended due to the 120 days or " + "even older outstanding balances. Please notify customer to consult " + "with his or her accounts payable department for the payment status " + "before processing a new order."; // ๆฃ€ๆŸฅcustomer็š„Business E-Mail,organization,shipTo Address // organization List<Object[]> instBlackList = customerDao .findInstitutionBlackList(); if (instBlackList != null && !instBlackList.isEmpty()) { for (Object[] objs : instBlackList) { String inst_domain = objs[0] == null ? "" : objs[0] .toString(); String inst_name = objs[1] == null ? "" : objs[1] .toString(); if (StringUtils.isNotBlank(inst_domain) && customer .getBusEmail() .toUpperCase() .trim() .contains( inst_domain.toUpperCase() .trim())) { message = "The customer:" + custNo + " Business E-Mail:" + customer.getBusEmail() + " is in institution black list." + dialog; inBlackListFlag = true; break; } if (StringUtils.isNotBlank(inst_name) && organization .getName() .toUpperCase() .trim() .contains( inst_name.toUpperCase() .trim())) { message = "The customer:" + custNo + " organization:" + organization.getName() + " is in institution black list." + dialog; inBlackListFlag = true; break; } if (StringUtils.isNotBlank(inst_name) && shipToAddr != null && StringUtils.isNotBlank(shipToAddr .getOrgName()) && shipToAddr .getOrgName() .toUpperCase() .trim() .contains( inst_name.toUpperCase() .trim())) { message = "The customer:" + custNo + " shipTo Address organization:" + shipToAddr.getOrgName() + " is in institution black list." + dialog; inBlackListFlag = true; break; } } } if (StringUtils.isBlank(message)) { List<Object> accBlackList = customerDao .findAccountBlackList(custNo); if (accBlackList != null && !accBlackList.isEmpty()) { message = "The customer:" + custNo + " is in account black list." + dialog; inBlackListFlag = true; } else { message = "SUCCESS"; } } else { message = "SUCCESS"; } if (inBlackListFlag) { Integer salesContact = customer.getSalesContact(); if (salesContact != null) { User user = userDao.findByUserId(salesContact); if (user != null && StringUtils.isNotBlank(user.getEmail())) { String mailTo = user.getEmail(); StringBuilder sb = new StringBuilder(); sb.append("This account is temporary suspended due to the huge amount of 120 days or even older outstanding balances. Please notify customer to consult with his or her accounts payable department for the payment status before processing this new order. "); mimeMailService.sendMail(mailTo, "Note Email", sb.toString(), "scm_admin@genscriptcorp.com"); } } } } } } return message; } /** * ๆ นๆฎdepartmentIdๅˆ†้กตๆŸฅๆ‰พCustomers * * @param page * @param deptId * @return * @author wangsf * @serialData 2011-03-02 */ public Page<Customer> searchByDept(Page<Customer> page, Integer deptId) { List<PropertyFilter> filters = new ArrayList<PropertyFilter>(); PropertyFilter pf = new PropertyFilter("EQI_deptId", deptId); filters.add(pf); return this.customerDao.findPage(page, filters); } /** * ่Žทๅพ—customerๆ‰€ๆœ‰็š„case */ public List<CustomerCase> getAllCases(Integer custNo) { List<CustomerCase> custCaseList = this.customerCaseDao.findBy("custNo", custNo); for (CustomerCase customerCase : custCaseList) { customerCase.setDocumentMap(SessionUtil.convertList2Map( this.noteDocumentDao.getDocumentList( customerCase.getCaseId(), DocumentType.CUST_CASE), "docId")); } return custCaseList; } /** * ็ป™ๆ–ฐๅปบ็š„customer้šๆœบ็”Ÿๆˆไบ†ๅฏ†็  */ public String generalPass() { StringBuffer newPassword = new StringBuffer(); String rand = ""; for (int i = 1; i <= 6; i++) { if (i % 2 != 0) { rand = StringUtil.getCharRandom(1); } else { rand = StringUtil.getIntRandom(1); } newPassword.append(rand); } return newPassword.toString(); } /** * ็”จๆˆทemail้‡ๅค้ชŒ่ฏ */ public boolean isReapt(String custNo, String busEmail) { Integer custNoInt = this.customerDao.getCustNoByEmail(busEmail); if (StringUtils.isNotEmpty(custNo) && !StringUtil.isNumeric(custNo) && custNoInt != null) { return true; } if (StringUtils.isNotEmpty(custNo) && StringUtil.isNumeric(custNo) && custNoInt != null && !String.valueOf(custNoInt).equals(custNo)) { return true; } return false; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } public void sendMailtoUserByCustNo(String custNo, Integer id) { System.out.println(custNo); Customer customer = this.customerDao.getById(Integer.parseInt(custNo)); GiftCard gc = this.giftCardDao.findById(id); if (customer != null && gc != null) { // System.out.println(customer.getBusEmail()); // ็ป™ๆ–ฐๅขž็”จๆˆท็š„็”จๆˆทๅ‘้€้‚ฎไปถ 2011 11 15 zhou gang update String subject = " You've received a $ " + gc.getCardValue() + " Amazon.com Gift Card from GenScript"; StringBuffer content = new StringBuffer(); content.append("Dear ").append( customer.getFirstName() + ",<br><br>"); content.append("Congratulations! Your GenScript EzCoupon points are converted to Amazon Gift Card. The following is your Amazon Gift Card information:<br/><br/>"); content.append("Amazon Card Claim Code: <B>") .append(gc.getCardNo()).append("</B>;") .append("Value: <B>$").append(gc.getCardValue()) .append("</B><br/><br/>"); content.append("Thanks for using GenScript services.<br/><br/>GenScript USA Inc.<br/><br/>"); /* * content.append("Thanks for your redeemed Amazon gift card.") * .append("<br><br>"); content.append("You've received a $ " + * gc.getCardValue() + " Amazon.com Gift Card from GenScript" + * ",please use the claim code:<font size=\"14px\"><strong>" + * gc.getCardNo() + * "</strong></font>,on something just for you.<br><br>"); * content.append("By the way, Gift Cards must be redeemed on"); */ /* * content.append( * " <a href=\"http:\\www.amazon.com\">www.amazon.com</a> or its affiliated website <a href=\"http:\\www.endless.com\">www.endless.com</a>" * ) .append( * ", toward the purchase of eligible products. For more information on using Amazon gift card," * + * " visit <a href=\"http:\\www.amazon.com/help/gc\">www.amazon.com/help/gc</a><br><br>" * ); */ content.append("=== GenScript: One Stop for Gene, Peptide, Protein and Antibody Services === <br><br>"); content.append("Thank you. <br><br>"); content.append("CONFIDENTIAL <br><br>"); content.append("Unless expressly stated otherwise, this message is confidential and may be privileged. " + "It is intended for the addressee(s) only. Access to this e-mail by anyone else is unauthorized." + " If you are not an addressee, any disclosure or copying of the content of this e-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. " + "If you are not an addressee, please inform the sender immediately.<br> "); content.append("<br><a href='http://www.genscript.com'>http://www.genscript.com</a><br>"); mimeMailService.sendMail(customer.getBusEmail() == null ? "" : customer.getBusEmail(), subject, content.toString(), "support@genscript.com"); } } @SuppressWarnings("unchecked") public Page<CustomerPointsHistory> searchCustomerRedeemAmazonHistory( Page<CustomerPointsHistory> page, String paramCustNo, String p_no) { if (!StringUtils.isEmpty(p_no) && StringUtils.isNumeric(p_no)) { Integer pageNo = Integer.parseInt(p_no); page.setPageNo(pageNo); } BigDecimal totalCount = new BigDecimal(0); String hql = "select * from `customer`.`customer_points_history` where `cust_no`='" + paramCustNo + "'"; Query query = this.customerPointsHistoryDao.getSession() .createSQLQuery(hql); if (page.isAutoCount()) { String sql2 = "select count(*) from `customer`.`customer_points_history` where `cust_no`='" + paramCustNo + "'"; Query query2 = this.customerPointsHistoryDao.getSession() .createSQLQuery(sql2); if (query2.list() != null) { totalCount = (BigDecimal) query2.list().get(0); } page.setTotalCount(totalCount.longValue()); } query.setFirstResult(page.getFirst() - 1); query.setMaxResults(page.getPageSize()); page.setResult(query.list()); return page; } public Page<CustomerPointsHistory> searchCustomerAllHistory( Page<CustomerPointsHistory> page, Integer paramCustNo) { return this.customerPointsHistoryDao.searchpointhistoryListAll(page, paramCustNo); } public String getBusEmailByCustomerNo(Integer custNo) { return this.customerDao.getBusEmailByCustNo(custNo); } /** * ้€š่ฟ‡custNoๆŸฅ่ฏขcompany๏ผŒๆŸฅ่ฏข็ป“ๆžœๆ˜ฏๅœจ่Žทๅ–็š„AccountCodeๅ‰ๅŠ ไธŠ"GS"๏ผŒ็ป“ๆžœไพ‹ๅฆ‚๏ผšGSUS * * @author Zhang Yong add date 2011-11-04 * @param custNo * @return */ public String getCustomerCompany(Integer custNo, CustomerDTO customerDTO) { String company = "GSUS"; if (customerDTO != null && StringUtils.isNotBlank(customerDTO.getBillAccountCode())) { return "GS" + customerDTO.getBillAccountCode(); } if (custNo == null) { return company; } Customer customer = customerDao.getById(custNo); if (customer == null || StringUtils.isBlank(customer.getBillAccountCode())) { return company; } return "GS" + customer.getBillAccountCode(); } // add by zhanghuibin public List<SalesRep> getSalesManages(String funName) { return salesRepDao.getSalesRepsByFunction(funName); } }
[ "253479240@qq.com" ]
253479240@qq.com
b3ce90c3f6df9ac0524bbc2bc3f9c3b316271794
2bbf204cd1608c6beac4cebb82cb97611699adc5
/system/src/main/java/com/shuishou/sysmgr/ui/member/MemberUpgradeMgmtPanel.java
dcf1615088a5b3595ea9d614d863c632afab428a
[]
no_license
lousongtao/retailerpos
a2d991b7925b0687fa020dcad8692ec6070e19ed
d25a0131e6a958b219c32d5e6f2e04a675a2d83a
refs/heads/master
2022-12-22T13:58:34.237026
2021-01-30T07:02:56
2021-01-30T07:02:56
158,353,458
0
1
null
2022-12-16T03:30:42
2018-11-20T08:11:37
Java
UTF-8
Java
false
false
10,396
java
package com.shuishou.sysmgr.ui.member; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shuishou.sysmgr.ConstantValue; import com.shuishou.sysmgr.Messages; import com.shuishou.sysmgr.beans.HttpResult; import com.shuishou.sysmgr.beans.Member; import com.shuishou.sysmgr.beans.MemberBalance; import com.shuishou.sysmgr.beans.MemberScore; import com.shuishou.sysmgr.beans.MemberUpgrade; import com.shuishou.sysmgr.http.HttpUtil; import com.shuishou.sysmgr.ui.CommonDialog; import com.shuishou.sysmgr.ui.MainFrame; import com.shuishou.sysmgr.ui.components.NumberInputDialog; public class MemberUpgradeMgmtPanel extends JPanel implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; private final Logger logger = Logger.getLogger(MemberUpgradeMgmtPanel.class.getName()); private MainFrame mainFrame; private JTable table = new JTable(); private TableModel model = new TableModel(); private JButton btnAdd = new JButton("Add"); private JButton btnUpdate = new JButton("Update"); private JButton btnDelete = new JButton("Delete"); private JButton btnChange = new JButton("Available/Unavailable"); private ArrayList<MemberUpgrade> memberUpgrades = new ArrayList<>(); public MemberUpgradeMgmtPanel(MainFrame mainFrame){ this.mainFrame = mainFrame; initUI(); doQuery(); } private void initUI(){ table.setModel(model); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getColumnModel().getColumn(0).setPreferredWidth(150); table.getColumnModel().getColumn(1).setPreferredWidth(100); table.getColumnModel().getColumn(2).setPreferredWidth(80); table.getColumnModel().getColumn(3).setPreferredWidth(100); table.getColumnModel().getColumn(4).setPreferredWidth(100); table.getColumnModel().getColumn(5).setPreferredWidth(150); table.getColumnModel().getColumn(6).setPreferredWidth(100); table.setAutoCreateRowSorter(true); JScrollPane jspTable = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JPanel pButtons = new JPanel(); pButtons.add(btnAdd); pButtons.add(btnUpdate); pButtons.add(btnDelete); pButtons.add(btnChange); btnAdd.addActionListener(this); btnUpdate.addActionListener(this); btnDelete.addActionListener(this); btnChange.addActionListener(this); setLayout(new BorderLayout()); add(jspTable, BorderLayout.CENTER); add(pButtons, BorderLayout.SOUTH); } private void doQuery(){ memberUpgrades.clear(); ((TableModel)table.getModel()).setRowCount(0); String url = "member/querymemberupgrade"; Map<String, String> params = new HashMap<>(); String response = HttpUtil.getJSONObjectByPost(MainFrame.SERVER_URL + url, params); if (response == null){ logger.error("get null from server for query member upgrade. URL = " + url + ", param = "+ params); JOptionPane.showMessageDialog(this, "get null from server for query member upgrade. URL = " + url); return; } Gson gson = new GsonBuilder().setDateFormat(ConstantValue.DATE_PATTERN_YMD).create(); HttpResult<ArrayList<MemberUpgrade>> result = gson.fromJson(response, new TypeToken<HttpResult<ArrayList<MemberUpgrade>>>(){}.getType()); if (!result.success){ logger.error("return false while query member upgrade. URL = " + url + ", response = "+response); JOptionPane.showMessageDialog(this, result.result); return; } memberUpgrades = result.data; table.updateUI(); } private void doAdd(){ MemberUpgradePanel p = new MemberUpgradePanel(this); CommonDialog dlg = new CommonDialog(mainFrame, p, "Add Member Upgrade Rule", 300, 300); dlg.setVisible(true); } private void doUpdate(){ if (table.getSelectedRow() < 0) return; MemberUpgradePanel p = new MemberUpgradePanel(this); int modelRow = table.convertRowIndexToModel(table.getSelectedRow()); p.setObjectValue(model.getObjectAt(modelRow)); CommonDialog dlg = new CommonDialog(mainFrame, p, "Update Member Upgrade Rule", 300, 300); dlg.setVisible(true); } private void doDelete(){ if (table.getSelectedRow() < 0) return; if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(mainFrame, "Do you want to delete this member upgrade rule?", "Confirm", JOptionPane.YES_NO_OPTION)){ return; } int modelRow = table.convertRowIndexToModel(table.getSelectedRow()); MemberUpgrade mu = model.getObjectAt(modelRow); String url = "member/deletememberupgrade"; Map<String, String> params = new HashMap<>(); params.put("userId", MainFrame.getLoginUser().getId()+""); params.put("id", mu.getId()+""); String response = HttpUtil.getJSONObjectByPost(MainFrame.SERVER_URL + url, params); if (response == null){ logger.error("get null from server for delete member upgrade. URL = " + url + ", param = "+ params); JOptionPane.showMessageDialog(this, "get null from server for delete member upgrade. URL = " + url); return; } Gson gson = new GsonBuilder().setDateFormat(ConstantValue.DATE_PATTERN_YMD).create(); HttpResult<ArrayList<MemberUpgrade>> result = gson.fromJson(response, new TypeToken<HttpResult<ArrayList<MemberUpgrade>>>(){}.getType()); if (!result.success){ logger.error("return false while delete member upgrade. URL = " + url + ", response = "+response); JOptionPane.showMessageDialog(this, result.result); return; } memberUpgrades.remove(modelRow); table.updateUI(); } private void doChangeStatus(){ if (table.getSelectedRow() < 0) return; int modelRow = table.convertRowIndexToModel(table.getSelectedRow()); MemberUpgrade mu = model.getObjectAt(modelRow); if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(mainFrame, "Do you want to change this rule to " + (mu.getStatus() == ConstantValue.MEMBERUPGRADE_STATUS_AVAILABLE ? "UNAVAILABLE" : "AVAILABLE") + "?", "Confirm", JOptionPane.YES_NO_OPTION)){ return; } String url = "member/changestatusmemberupgrade"; Map<String, String> params = new HashMap<>(); params.put("userId", MainFrame.getLoginUser().getId()+""); params.put("id", mu.getId()+""); params.put("status", String.valueOf(mu.getStatus() == ConstantValue.MEMBERUPGRADE_STATUS_AVAILABLE ? ConstantValue.MEMBERUPGRADE_STATUS_UNAVAILABLE : ConstantValue.MEMBERUPGRADE_STATUS_AVAILABLE)); String response = HttpUtil.getJSONObjectByPost(MainFrame.SERVER_URL + url, params); if (response == null){ logger.error("get null from server for change member upgrade status. URL = " + url + ", param = "+ params); JOptionPane.showMessageDialog(this, "get null from server for change member upgrade status. URL = " + url); return; } Gson gson = new GsonBuilder().setDateFormat(ConstantValue.DATE_PATTERN_YMD).create(); HttpResult<MemberUpgrade> result = gson.fromJson(response, new TypeToken<HttpResult<MemberUpgrade>>(){}.getType()); if (!result.success){ logger.error("return false while change member upgrade status. URL = " + url + ", response = "+response); JOptionPane.showMessageDialog(this, result.result); return; } memberUpgrades.set(modelRow, result.data); table.updateUI(); } public void insertRow(MemberUpgrade m){ memberUpgrades.add(0, m); model.fireTableDataChanged(); } public void updateRow(MemberUpgrade m){ for (int i = 0; i < memberUpgrades.size(); i++) { if (m.getId() == memberUpgrades.get(i).getId()){ memberUpgrades.set(i, m); break; } } model.fireTableDataChanged(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnAdd){ doAdd(); } else if (e.getSource() == btnUpdate){ doUpdate(); } else if (e.getSource() == btnDelete){ doDelete(); } else if (e.getSource() == btnChange){ doChangeStatus(); } } class TableModel extends DefaultTableModel{ /** * */ private static final long serialVersionUID = 1L; private String[] header = new String[]{"Compare Field", "Start Relation", "Start Value", "End Relation", "End Value","Upgrade Field", "Upgrade Value", "Status"}; public TableModel(){ } @Override public int getRowCount() { if (memberUpgrades == null) return 0; return memberUpgrades.size(); } @Override public int getColumnCount() { return header.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { MemberUpgrade m = memberUpgrades.get(rowIndex); switch(columnIndex){ case 0: return m.getCompareField(); case 1: if (m.getSmallRelation() == ConstantValue.MEMBERUPGRADE_RELATION_EQUAL) return "="; else if (m.getSmallRelation() == ConstantValue.MEMBERUPGRADE_RELATION_GREATER) return ">"; else if (m.getSmallRelation() == ConstantValue.MEMBERUPGRADE_RELATION_GREATEREQUAL) return ">="; case 2: return m.getSmallValue(); case 3: if (m.getBigRelation() == ConstantValue.MEMBERUPGRADE_RELATION_EQUAL) return "="; else if (m.getBigRelation() == ConstantValue.MEMBERUPGRADE_RELATION_LESS) return "<"; else if (m.getBigRelation() == ConstantValue.MEMBERUPGRADE_RELATION_LESSEQUAL) return "<="; case 4: return m.getBigValue(); case 5: return m.getExecuteField(); case 6: return m.getExecuteValue(); case 7: if (m.getStatus() == ConstantValue.MEMBERUPGRADE_STATUS_AVAILABLE) return "AVAILABLE"; else return "UNAVAILABLE"; } return ""; } @Override public String getColumnName(int col){ return header[col]; } public MemberUpgrade getObjectAt(int row){ return memberUpgrades.get(row); } public boolean isCellEditable(int row, int column) { return false; } } }
[ "lousongtao@gmail.com" ]
lousongtao@gmail.com
f1cf6226e34898e18638aab0b535119d698cbe54
f4148153b8f157ee179536fe044b55e95c89ff9b
/MorningsideIP/src/test/java/MicrosoftFunctionality/Micro_QuoteEPFnTSaveTest.java
4b16236d99b30bd01baeab1b47964bf957a1c524
[]
no_license
MohammedYasserKhan/TestNgLearning
3267f5dcd489c6a9e149d1bfce851cdb397e4de5
c38ddfe3b78061cd72dc79528f9d10d6a20c583c
refs/heads/master
2022-07-13T23:22:05.141111
2019-12-04T06:36:37
2019-12-04T06:36:37
225,579,245
2
0
null
2022-06-29T17:49:12
2019-12-03T09:22:11
Java
UTF-8
Java
false
false
5,319
java
package MicrosoftFunctionality; import java.awt.AWTException; import org.testng.Reporter; import org.testng.annotations.Test; import com.aventstack.extentreports.Status; import MicrosoftPageFactory.login.Micro_QuoteEPFnTSave; import pageFactory.login.MyDriver; import utility.EReport; public class Micro_QuoteEPFnTSaveTest extends EReport { @Test public void Micro_QuoteEPFnTSaveTesting() throws InterruptedException, AWTException { test=extent.createTest("Quote EP Grant file and translate test"); Micro_QuoteEPFnTSave QPCT = new Micro_QuoteEPFnTSave(MyDriver.driver); System.out.println("================================================================"); System.out.println("Step 3 : users is now selecting the customer and requester"); if(QPCT.verifyEPselectionSuccessful()) { System.out.println("================================================================"); System.out.println("Success!! User has now selected EP product forom quote section"); Reporter.log("Success!! User has now selected EP product forom quote section"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); test.log(Status.PASS, "success"); } else { System.out.println("================================================================"); System.out.println("Fail !! User has not selected the product"); Reporter.log("Fail !! User has not selected the product"); test.log(Status.FAIL, "Fail !! User has not selected the product"); } if(QPCT.verifyEPapplicaitonnumber()) { System.out.println("================================================================"); System.out.println("Step 5 : users is proding the application number"); Reporter.log("user is now providing the application number"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); //test.log(Status.PASS, "success"); } else { System.out.println("================================================================"); System.out.println("User is not providing the application number"); Reporter.log("User is not providing the application number"); } if(QPCT.Quoteepclaim()) { System.out.println("================================================================"); System.out.println("Step 6 : users has opted/chosen claims"); Reporter.log("users has opted/chosen claims"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); //test.log(Status.PASS, "success"); } else { System.out.println("================================================================"); System.out.println("User is not choosen claims"); Reporter.log("User is not choosen claims"); } if(QPCT.QuoteEPFileandTranslate()) { System.out.println("================================================================"); System.out.println("Step 7 : users is chosing/selecting file and translate"); Reporter.log("users is chosing/selecting file and translate"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); //test.log(Status.PASS, "success"); } else { System.out.println("================================================================"); System.out.println("users is not chosing/selecting file and translate"); Reporter.log("users is not chosing/selecting file and translate"); } if(QPCT.Jurisdiction()) { System.out.println("================================================================"); System.out.println("Step 8 : User is choosing the target countries"); Reporter.log("User is choosing the target countries"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); } else { System.out.println("================================================================"); System.out.println("User is not choosing the target countries"); Reporter.log("User is not choosing the target countries"); } if(QPCT.Fileupload()) { System.out.println("================================================================"); System.out.println("File uploding"); Reporter.log("File uploding"); test.log(Status.PASS, "passed"); } else { System.out.println("================================================================"); System.out.println("User has not uploaded file"); Reporter.log("User has not uploaded file"); test.log(Status.FAIL, "Failed"); } if(QPCT.fileuplaodingquote()) { System.out.println("================================================================"); System.out.println("Step 9 : uploaded succesfully"); Reporter.log("uploaded successfully"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); } else { System.out.println("================================================================"); System.out.println("not uploaded successfully"); Reporter.log("Not uploaded successfully"); } if(QPCT.savequote()) { System.out.println("================================================================"); System.out.println("Step 9 : Saving Quote"); Reporter.log("Saving Quote"); test.log(com.aventstack.extentreports.Status.PASS,"Success"); } else { System.out.println("================================================================"); System.out.println("Not saving Quote"); Reporter.log("Not saving Quote"); } } }
[ "yasserkhanmohammed@gmail.com" ]
yasserkhanmohammed@gmail.com
86f757e169e39e45bff7d67c638def6f070dc3fc
2b6fffc2e23344d8788efe743ac7cc45701b3e18
/ems/src/main/java/com/cg/entities/DepartmentBean.java
c9c721084775c8779fcb4d76d00641b924a4245d
[]
no_license
rashmipriya09/EMS
8dded216b2aa1f8a584d78639e818816389e3827
7e229f42abcb9f6ee27030c260245a6a14bb06e4
refs/heads/master
2020-03-29T06:17:58.645378
2018-09-20T14:07:43
2018-09-20T14:07:43
149,618,580
0
0
null
null
null
null
UTF-8
Java
false
false
861
java
package com.cg.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Department") public class DepartmentBean { @Id @Column(name="dept_ID") private Integer departmentId; @Column(name="dept_Name") private String departmentName; public DepartmentBean(Integer departmentId, String departmentName) { super(); this.departmentId = departmentId; this.departmentName = departmentName; } public DepartmentBean() { } public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } }
[ "rashmi.priya0905@gmail.com" ]
rashmi.priya0905@gmail.com
5f0135aa358a672c73912ee05c146ba74a9aba32
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/18/18_85c2a36fd8ee1bd126d412004c7661ca0bb4d77b/FHTAdapter/18_85c2a36fd8ee1bd126d412004c7661ca0bb4d77b_FHTAdapter_s.java
03e8f03971ad5bfeb8217aec39337660ff49a17a
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
4,295
java
package li.klass.fhem.adapter.devices; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.SeekBar; import android.widget.Spinner; import li.klass.fhem.R; import li.klass.fhem.activities.deviceDetail.FHTDeviceDetailActivity; import li.klass.fhem.adapter.devices.core.DeviceDetailAvailableAdapter; import li.klass.fhem.domain.Device; import li.klass.fhem.domain.FHTDevice; import li.klass.fhem.service.device.FHTService; import static li.klass.fhem.domain.FHTDevice.*; public class FHTAdapter extends DeviceDetailAvailableAdapter<FHTDevice> { @Override public View getDeviceView(LayoutInflater layoutInflater, FHTDevice device) { View view = layoutInflater.inflate(R.layout.room_detail_fht, null); setTextView(view, R.id.deviceName, device.getAliasOrName()); setTextViewOrHideTableRow(view, R.id.tableRowTemperature, R.id.temperature, device.getTemperature()); setTextViewOrHideTableRow(view, R.id.tableRowActuator, R.id.actuator, device.getActuator()); return view; } @Override @SuppressWarnings("unchecked") protected void fillDeviceDetailView(final Context context, final View view, final FHTDevice device) { setTextViewOrHideTableRow(view, R.id.tableRowTemperature, R.id.temperature, device.getTemperature()); setTextViewOrHideTableRow(view, R.id.tableRowActuator, R.id.actuator, device.getActuator()); setTextViewOrHideTableRow(view, R.id.tableRowDesiredTemperature, R.id.desiredTemperature, device.getDesiredTempDesc()); setTextViewOrHideTableRow(view, R.id.tableRowWarnings, R.id.warnings, device.getWarningsDesc()); final SeekBar desiredTempSeekBar = (SeekBar) view.findViewById(R.id.desiredTemperatureSeek); desiredTempSeekBar.setProgress((int) ((device.getDesiredTemp() - 5.5) * 10)); desiredTempSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { private double value; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean byUser) { this.value = progress / 10 + 5.5; setTextViewOrHideTableRow(view, R.id.tableRowDesiredTemperature, R.id.desiredTemperature, desiredTemperatureToString(value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { FHTService.INSTANCE.setDesiredTemperature(seekBar.getContext(), device, value); } }); Spinner modeSpinner = (Spinner) view.findViewById(R.id.mode); ArrayAdapter adapter = new ArrayAdapter(context, R.layout.spinnercontent, FHTMode.values()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); modeSpinner.setAdapter(adapter); modeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { FHTMode mode = FHTMode.values()[position]; FHTService.INSTANCE.setMode(context, device, mode); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); createPlotButton(context, view, R.id.temperatureGraph, device.getTemperature(), device, R.string.yAxisTemperature, COLUMN_SPEC_TEMPERATURE); createPlotButton(context, view, R.id.actuatorGraph, device.getActuator(), device, R.string.yAxisActuator, COLUMN_SPEC_ACTUATOR); } @Override public Class<? extends Device> getSupportedDeviceClass() { return FHTDevice.class; } @Override public int getDetailViewLayout() { return R.layout.device_detail_fht; } @Override protected Class<? extends Activity> getDeviceDetailActivity() { return FHTDeviceDetailActivity.class; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
dd82fa08554c50cfbef9df2d7fba4bda1e09aab8
ba44e8867d176d74a6ca0a681a4f454ca0b53cad
/resources/testscript/Workflow/OnlineCache/OLC_Menu_ALLDatetypes_DB_Int_E2EHelper.java
91e4a6341ffd05a1c728d1fa989a5b5e1ef724ca
[]
no_license
eric2323223/FATPUS
1879e2fa105c7e7683afd269965d8b59a7e40894
989d2cf49127d88fdf787da5ca6650e2abd5a00e
refs/heads/master
2016-09-15T19:10:35.317021
2012-06-29T02:32:36
2012-06-29T02:32:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,369
java
// DO NOT EDIT: This file is automatically generated. // // Only the associated template file should be edited directly. // Helper class files are automatically regenerated from the template // files at various times, including record actions and test object // insertion actions. Any changes made directly to a helper class // file will be lost when automatically updated. package resources.testscript.Workflow.OnlineCache; import com.rational.test.ft.object.interfaces.*; import com.rational.test.ft.object.interfaces.SAP.*; import com.rational.test.ft.object.interfaces.WPF.*; import com.rational.test.ft.object.interfaces.siebel.*; import com.rational.test.ft.object.interfaces.flex.*; import com.rational.test.ft.object.interfaces.dojo.*; import com.rational.test.ft.script.*; import com.rational.test.ft.vp.IFtVerificationPoint; /** * Script Name : <b>OLC_Menu_ALLDatetypes_DB_Int_E2E</b><br> * Generated : <b>2012/04/10 3:25:53 AM</b><br> * Description : Helper class for script<br> * Original Host : Windows XP x86 5.1 build 2600 Service Pack 3 <br> * * @since April 10, 2012 * @author min zhao */ public abstract class OLC_Menu_ALLDatetypes_DB_Int_E2EHelper extends RationalTestScript { protected OLC_Menu_ALLDatetypes_DB_Int_E2EHelper() { setScriptName("testscript.Workflow.OnlineCache.OLC_Menu_ALLDatetypes_DB_Int_E2E"); } }
[ "eric2323223@gmail.com" ]
eric2323223@gmail.com
d248cf37e50a2ad778c1920602207968ae381cb8
7ea61988855c0e28196d3e045a9b17cb504e9439
/RegexTest.java
bd0ff9548422a31c454bc6d97385415c646a579f
[]
no_license
tXereas/CompSci
ce2bcad0c93707f499b83b03a922f4ada7a0d262
d4508c88b5ed277dd7e580db613446369ab424cf
refs/heads/master
2021-01-12T08:15:31.684296
2016-12-19T18:58:46
2016-12-19T18:58:46
76,522,174
0
0
null
null
null
null
UTF-8
Java
false
false
975
java
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class RegexTest { @Test public void isBinary() { assertFalse(Regex.isBinary("011010410")); assertTrue(Regex.isBinary("0111010010110101")); } @Test public void isHex() { assertTrue(Regex.isHex("1872865ABC63B")); assertFalse(Regex.isHex("1236754671LZ92")); } @Test public void logCheck() { assertEquals(Regex.log("Log 82334: I am now correct"), "I am now correct"); } @SuppressWarnings("deprecation") @Test public void combine() { String [] strings = {"I", "DO", "NOT", "WANT", "TO", "DO", "THIS"}; assertEquals(Regex.combine("I:DO:NOT:WANT:TO:DO:THIS"), strings ); } @Test public void convention() { List <String> strings = new ArrayList<String>(); strings.add("_fjsdfHF"); strings.add("234kjsdfH"); strings.add("Fhshf"); Regex.convention(strings); assertEquals( strings.size(), 1); } }
[ "noreply@github.com" ]
tXereas.noreply@github.com
ebf5b3a5d482e3481a6728f1f7335b538b5fb77d
ab5052b0daba62b84ae1d76cf63e4d1f6b52552f
/txtFile.java
28035a0d21aa233d03574ff1dbef38617f1c6ee6
[]
no_license
mariaguyde/lecteur-de-fichiers
7bb8e8e7de58e8b50f3057edf2c76fbfd271a02e
eb311b44e15ca8c18d35415bb82bea86a40347ad
refs/heads/main
2023-08-13T07:42:20.799574
2021-10-14T17:55:10
2021-10-14T17:55:10
416,657,408
0
0
null
null
null
null
UTF-8
Java
false
false
221
java
package file_reader; import javax.swing.JFileChooser; // CLASSE ABSTRAITE POUR LE FICHIER TXT abstract class txtFile extends file { public txtFile(String path, String nameFile) { super(path, nameFile); } }
[ "noreply@github.com" ]
mariaguyde.noreply@github.com
0a5ce8781cb603364d27391695430186585911ef
b59f239bd39d1f3a5630d63eabeb3c87f2d78a3c
/sdklib/src/main/java/com/android/sdklib/AddOnTarget.java
c7e7ea96937f0c9a8ad246ef159ee6cae627d4c5
[ "Apache-2.0" ]
permissive
lshain-android-source/tools-base
e1967b0469c5dac11e3c7c819739d5bf9cdad8ab
81867913e0d66d4d6834bf9b582989290838a36b
refs/heads/master
2020-06-08T04:26:56.300592
2014-07-09T08:31:34
2014-07-09T08:31:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,366
java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.sdklib; import com.android.SdkConstants; import com.android.annotations.NonNull; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Represents an add-on target in the SDK. * An add-on extends a standard {@link PlatformTarget}. */ final class AddOnTarget implements IAndroidTarget { private static final class OptionalLibrary implements IOptionalLibrary { private final String mJarName; private final String mJarPath; private final String mName; private final String mDescription; OptionalLibrary(String jarName, String jarPath, String name, String description) { mJarName = jarName; mJarPath = jarPath; mName = name; mDescription = description; } @Override public String getJarName() { return mJarName; } @Override public String getJarPath() { return mJarPath; } @Override public String getName() { return mName; } @Override public String getDescription() { return mDescription; } } private final String mLocation; private final PlatformTarget mBasePlatform; private final String mName; private final ISystemImage[] mSystemImages; private final String mVendor; private final int mRevision; private final String mDescription; private final boolean mHasRenderingLibrary; private final boolean mHasRenderingResources; private String[] mSkins; private String mDefaultSkin; private IOptionalLibrary[] mLibraries; private int mVendorId = NO_USB_ID; /** * Creates a new add-on * @param location the OS path location of the add-on * @param name the name of the add-on * @param vendor the vendor name of the add-on * @param revision the revision of the add-on * @param description the add-on description * @param systemImages list of supported system images. Can be null or empty. * @param libMap A map containing the optional libraries. The map key is the fully-qualified * library name. The value is a 2 string array with the .jar filename, and the description. * @param hasRenderingLibrary whether the addon has a custom layoutlib.jar * @param hasRenderingResources whether the add has custom framework resources. * @param basePlatform the platform the add-on is extending. */ AddOnTarget( String location, String name, String vendor, int revision, String description, ISystemImage[] systemImages, Map<String, String[]> libMap, boolean hasRenderingLibrary, boolean hasRenderingResources, PlatformTarget basePlatform) { if (location.endsWith(File.separator) == false) { location = location + File.separator; } mLocation = location; mName = name; mVendor = vendor; mRevision = revision; mDescription = description; mHasRenderingLibrary = hasRenderingLibrary; mHasRenderingResources = hasRenderingResources; mBasePlatform = basePlatform; // If the add-on does not have any system-image of its own, the list here // is empty and it's up to the callers to query the parent platform. mSystemImages = systemImages == null ? new ISystemImage[0] : systemImages; Arrays.sort(mSystemImages); // handle the optional libraries. if (libMap != null) { mLibraries = new IOptionalLibrary[libMap.size()]; int index = 0; for (Entry<String, String[]> entry : libMap.entrySet()) { String jarFile = entry.getValue()[0]; String desc = entry.getValue()[1]; mLibraries[index++] = new OptionalLibrary(jarFile, mLocation + SdkConstants.OS_ADDON_LIBS_FOLDER + jarFile, entry.getKey(), desc); } } } @Override public String getLocation() { return mLocation; } @Override public String getName() { return mName; } @Override public ISystemImage getSystemImage(String abiType) { for (ISystemImage sysImg : mSystemImages) { if (sysImg.getAbiType().equals(abiType)) { return sysImg; } } return null; } @Override public ISystemImage[] getSystemImages() { return mSystemImages; } @Override public String getVendor() { return mVendor; } @Override public String getFullName() { return String.format("%1$s (%2$s)", mName, mVendor); } @Override public String getClasspathName() { return String.format("%1$s [%2$s]", mName, mBasePlatform.getClasspathName()); } @Override public String getShortClasspathName() { return String.format("%1$s [%2$s]", mName, mBasePlatform.getVersionName()); } @Override public String getDescription() { return mDescription; } @Override public AndroidVersion getVersion() { // this is always defined by the base platform return mBasePlatform.getVersion(); } @Override public String getVersionName() { return mBasePlatform.getVersionName(); } @Override public int getRevision() { return mRevision; } @Override public boolean isPlatform() { return false; } @Override public IAndroidTarget getParent() { return mBasePlatform; } @Override public String getPath(int pathId) { switch (pathId) { case SKINS: return mLocation + SdkConstants.OS_SKINS_FOLDER; case DOCS: return mLocation + SdkConstants.FD_DOCS + File.separator + SdkConstants.FD_DOCS_REFERENCE; case LAYOUT_LIB: if (mHasRenderingLibrary) { return mLocation + SdkConstants.FD_DATA + File.separator + SdkConstants.FN_LAYOUTLIB_JAR; } return mBasePlatform.getPath(pathId); case RESOURCES: if (mHasRenderingResources) { return mLocation + SdkConstants.FD_DATA + File.separator + SdkConstants.FD_RES; } return mBasePlatform.getPath(pathId); case FONTS: if (mHasRenderingResources) { return mLocation + SdkConstants.FD_DATA + File.separator + SdkConstants.FD_FONTS; } return mBasePlatform.getPath(pathId); case SAMPLES: // only return the add-on samples folder if there is actually a sample (or more) File sampleLoc = new File(mLocation, SdkConstants.FD_SAMPLES); if (sampleLoc.isDirectory()) { File[] files = sampleLoc.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); if (files != null && files.length > 0) { return sampleLoc.getAbsolutePath(); } } //$FALL-THROUGH$ default : return mBasePlatform.getPath(pathId); } } @Override public BuildToolInfo getBuildToolInfo() { return mBasePlatform.getBuildToolInfo(); } @Override @NonNull public List<String> getBootClasspath() { return Collections.singletonList(getPath(IAndroidTarget.ANDROID_JAR)); } @Override public boolean hasRenderingLibrary() { return mHasRenderingLibrary || mHasRenderingResources; } @Override public String[] getSkins() { return mSkins; } @Override public String getDefaultSkin() { return mDefaultSkin; } @Override public IOptionalLibrary[] getOptionalLibraries() { return mLibraries; } /** * Returns the list of libraries of the underlying platform. * * {@inheritDoc} */ @Override public String[] getPlatformLibraries() { return mBasePlatform.getPlatformLibraries(); } @Override public String getProperty(String name) { return mBasePlatform.getProperty(name); } @Override public Integer getProperty(String name, Integer defaultValue) { return mBasePlatform.getProperty(name, defaultValue); } @Override public Boolean getProperty(String name, Boolean defaultValue) { return mBasePlatform.getProperty(name, defaultValue); } @Override public Map<String, String> getProperties() { return mBasePlatform.getProperties(); } @Override public int getUsbVendorId() { return mVendorId; } @Override public boolean canRunOn(IAndroidTarget target) { // basic test if (target == this) { return true; } /* * The method javadoc indicates: * Returns whether the given target is compatible with the receiver. * <p/>A target is considered compatible if applications developed for the receiver can * run on the given target. */ // The receiver is an add-on. There are 2 big use cases: The add-on has libraries // or the add-on doesn't (in which case we consider it a platform). if (mLibraries == null || mLibraries.length == 0) { return mBasePlatform.canRunOn(target); } else { // the only targets that can run the receiver are the same add-on in the same or later // versions. // first check: vendor/name if (mVendor.equals(target.getVendor()) == false || mName.equals(target.getName()) == false) { return false; } // now check the version. At this point since we checked the add-on part, // we can revert to the basic check on version/codename which are done by the // base platform already. return mBasePlatform.canRunOn(target); } } @Override public String hashString() { return String.format(AndroidTargetHash.ADD_ON_FORMAT, mVendor, mName, mBasePlatform.getVersion().getApiString()); } @Override public int hashCode() { return hashString().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof AddOnTarget) { AddOnTarget addon = (AddOnTarget)obj; return mVendor.equals(addon.mVendor) && mName.equals(addon.mName) && mBasePlatform.getVersion().equals(addon.mBasePlatform.getVersion()); } return false; } /* * Order by API level (preview/n count as between n and n+1). * At the same API level, order as: Platform first, then add-on ordered by vendor and then name * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(IAndroidTarget target) { // quick check. if (this == target) { return 0; } int versionDiff = getVersion().compareTo(target.getVersion()); // only if the version are the same do we care about platform/add-ons. if (versionDiff == 0) { // platforms go before add-ons. if (target.isPlatform()) { return +1; } else { AddOnTarget targetAddOn = (AddOnTarget)target; // both are add-ons of the same version. Compare per vendor then by name int vendorDiff = mVendor.compareTo(targetAddOn.mVendor); if (vendorDiff == 0) { return mName.compareTo(targetAddOn.mName); } else { return vendorDiff; } } } return versionDiff; } /** * Returns a string representation suitable for debugging. * The representation is not intended for display to the user. * * The representation is also purposely compact. It does not describe _all_ the properties * of the target, only a few key ones. * * @see #getDescription() */ @Override public String toString() { return String.format("AddonTarget %1$s rev %2$d (based on %3$s)", //$NON-NLS-1$ getVersion(), getRevision(), getParent().toString()); } // ---- local methods. void setSkins(String[] skins, String defaultSkin) { mDefaultSkin = defaultSkin; // we mix the add-on and base platform skins HashSet<String> skinSet = new HashSet<String>(); skinSet.addAll(Arrays.asList(skins)); skinSet.addAll(Arrays.asList(mBasePlatform.getSkins())); mSkins = skinSet.toArray(new String[skinSet.size()]); } /** * Sets the USB vendor id in the add-on. */ void setUsbVendorId(int vendorId) { if (vendorId == 0) { throw new IllegalArgumentException( "VendorId must be > 0"); } mVendorId = vendorId; } }
[ "lshain.gyh@gmail.com" ]
lshain.gyh@gmail.com
de10fcb1917d487c81e574e222fbdf1f966d9212
81c0123f1f336921d32873f7e3930c00103d8eea
/chapter_007/src/main/java/ru/chedmitriy/jdbc/package-info.java
9c026490d0c5d325d2e0e213aea268c37081df8f
[ "Apache-2.0" ]
permissive
CheRut/chedmitry
9c659f073d478ee87545c85f949214bf2418cbec
00d780fe0307aeb7e0cf2d1411128114678ae137
refs/heads/master
2021-01-12T04:48:25.916780
2019-01-06T13:50:43
2019-01-06T13:50:43
77,799,730
1
0
null
null
null
null
UTF-8
Java
false
false
1,370
java
/** * chedmitry * * @author CheDmitry * @version 1.0 * @since 16.12.17 * * * /** * ะœะตั‚ะพะด ะทะฐัะตะบะฐะตั‚ ะฒั€ะตะผั ะฒั‹ะฟะพะปะฝะตะฝะธั ะฒัะตั… ะพะฟะตั€ะฐั†ะธะน * @see ru.chedmitriy.jdbc.JDBCOptimization#createTable() - ัะพะทะดะฐะตะผ ั‚ะฐะฑะปะธั†ัƒ ะตัะปะธ ะฝะต ัะพะทะดะฐะฝะฐ ะตั‰ะต * @see ru.chedmitriy.jdbc.JDBCOptimization#clearTable() - ะพั‡ะธั‰ะฐะตะผ ั‚ะฐะฑะปะธั†ัƒ, * ะตัะปะธ ั‚ะฐะฑะปะธั†ัƒ ะฝะต ะฟั€ะธัˆะปะพััŒ ัะพะทะดะฐะฒะฐั‚ัŒ ะธ ะฒ ะฝะตะน ะผะพะณัƒั‚ ะฑั‹ั‚ัŒ ะทะฝะฐั‡ะตะฝะธั * @see ru.chedmitriy.jdbc.JDBCOptimization#fillData(int) - ะทะฐะฟะพะปะฝัะตะผ ั‚ะฐะฑะปะธั†ัƒ n ัะปะตะผะตะฝั‚ะฐะผะธ * @see ru.chedmitriy.jdbc.JDBCOptimization#xmlCreator(String) - ัะพะทะดะฐะตะผ ั„ะฐะนะป 1.xml * @see ru.chedmitriy.jdbc.XMLTransformation#transformXML(org.w3c.dom.Document, java.lang.String) - ะทะฐะฟะพะปะฝัะตะผ xml * ะดะพะบัƒะผะตะฝั‚ ะขะตะณะฐะผะธ ะธ ะฐั‚ั€ะธะฑัƒั‚ะฐะผะธ,ะฟั€ะธะฝะธะผะฐะตะผ ะทะฝะฐั‡ะตะฝะธั ะธะท ั‚ะฐะฑะปะธั†ั‹ ะฒ ะ‘ะ” * @see ru.chedmitriy.jdbc.XMLTransformation#applyTransform(String, String, String) * ะฟั€ะตะพะฑั€ะฐะทัƒะตะผ 1.XML ะฒ 2.xml ะธัะพะปัŒะทะตะผ ัˆะฐะฑะปะพะฝ ัั‚ะธะปะตะน template.xsl * @see ru.chedmitriy.jdbc.XmlPars#parser(String) - ะฟะตั€ะตะฑะธั€ะฐะตะผ ะทะฝะฐั‡ะตะฝะธั * ะฒ ั„ะฐะนะปะต 2.xml, ะฒั‹ะฒะพะดะธะผ ั€ะตะทัƒะปัŒั‚ะฐั‚ ัะพะณะปะฐัะฝะพ ัƒัะปะพะฒะธัŽ * */ package ru.chedmitriy.jdbc;
[ "diemason@list.ru" ]
diemason@list.ru
7900d12fdee219390b3fa7a032f72e758dd633a7
7cda679f03a66ef26df7bc554168753806f8f6ba
/src/com/projeto/model/Servicos.java
e6258ed4435001e697cd0a338866ddc7ff7a3d1b
[]
no_license
JonathanAJ/sistema-vendas-servicos-javaee
410d9630679bd0e7db52df3947b0f8970c56801d
f119b761d6ea1310dce3ed38cbbf40a2f33dc90a
refs/heads/master
2021-06-01T21:54:08.847129
2016-07-06T19:02:18
2016-07-06T19:02:18
47,300,576
1
0
null
null
null
null
UTF-8
Java
false
false
1,447
java
package com.projeto.model; public class Servicos { private Long servPkId; private String servNome; private String servDescricao; private String servValor; private int servFkCateg1; private int servFkCateg2; private int servFkUsuario; private String servImagem; public Servicos(){ } public Long getServPkId() { return servPkId; } public void setServPkId(Long servPkId) { this.servPkId = servPkId; } public String getServNome() { return servNome; } public void setServNome(String servNome) { this.servNome = servNome; } public String getServDescricao() { return servDescricao; } public void setServDescricao(String servDescricao) { this.servDescricao = servDescricao; } public String getServValor() { return servValor; } public void setServValor(String servValor) { this.servValor = servValor; } public int getServFkCateg1() { return servFkCateg1; } public void setServFkCateg1(int servFkCateg1) { this.servFkCateg1 = servFkCateg1; } public int getServFkCateg2() { return servFkCateg2; } public void setServFkCateg2(int servFkCateg2) { this.servFkCateg2 = servFkCateg2; } public int getServFkUsuario() { return servFkUsuario; } public void setServFkUsuario(int servFkUsuario) { this.servFkUsuario = servFkUsuario; } public String getServImagem() { return servImagem; } public void setServImagem(String servImagem) { this.servImagem = servImagem; } }
[ "hareta.alves@gmail.com" ]
hareta.alves@gmail.com
1b081c210e5b3cd7d9ef62bdd1aa1292904bf5c5
4b1cb91b0fdbe7be3c04d9e7edf5392746867166
/ganon-admin/src/main/java/com/lyx/ganon/admin/GanonAdminApplication.java
25eb786510bd295e479f4305239e589d3eb064ab
[]
no_license
liyustar/ganon
59a7ce4964c1a8efdb5a47d561cdd9c0baba4f45
bda0c8cf5be96bcb2c4d39c9c0eb898e0d1706ab
refs/heads/master
2023-01-12T08:46:10.603739
2020-04-12T07:26:05
2020-04-12T07:26:05
249,726,949
0
0
null
2023-01-05T17:00:28
2020-03-24T14:15:59
Java
UTF-8
Java
false
false
320
java
package com.lyx.ganon.admin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GanonAdminApplication { public static void main(String[] args) { SpringApplication.run(GanonAdminApplication.class, args); } }
[ "liyustar@gmail.com" ]
liyustar@gmail.com
1b255ab815ac5493ee7af25864d3fe3ee615babe
c89b16f0043f521b770ed4c830315cafecda6579
/container/src/main/java/iba/inst/anotation/ResourceConf.java
8984ada7fd9534005f0aa429757a7300d3cfbea4
[]
no_license
DenisSK78/core_inst
fdc78e2ae35acee01333124c0483aaff3fcb5a19
2bf4ec1fdf120576e8e718eaec72ea8bab83cfba
refs/heads/master
2020-12-28T10:48:16.714528
2020-02-17T08:05:51
2020-02-17T08:05:51
238,296,799
0
0
null
2020-11-23T10:19:11
2020-02-04T20:13:39
Java
UTF-8
Java
false
false
292
java
package iba.inst.anotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface ResourceConf { }
[ "k-d-s@mail.ru" ]
k-d-s@mail.ru
7658ebe4ed40242e8a9d8adf4a3e0f9beb02f403
c885ef92397be9d54b87741f01557f61d3f794f3
/tests-without-trycatch/JacksonDatabind-111/com.fasterxml.jackson.databind.deser.std.AtomicReferenceDeserializer/BBC-F0-opt-70/15/com/fasterxml/jackson/databind/deser/std/AtomicReferenceDeserializer_ESTest_scaffolding.java
eff6430f93916e5f23f4751b0579425bd04bc2e9
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
43,790
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Thu Oct 21 13:38:01 GMT 2021 */ package com.fasterxml.jackson.databind.deser.std; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; import static org.evosuite.shaded.org.mockito.Mockito.*; @EvoSuiteClassExclude public class AtomicReferenceDeserializer_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "com.fasterxml.jackson.databind.deser.std.AtomicReferenceDeserializer"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {} } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { /*No java.lang.System property to set*/ } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(AtomicReferenceDeserializer_ESTest_scaffolding.class.getClassLoader() , "com.fasterxml.jackson.databind.deser.DefaultDeserializationContext$Impl", "com.fasterxml.jackson.databind.exc.PropertyBindingException", "com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException", "com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver", "com.fasterxml.jackson.databind.JsonSerializable$Base", "com.fasterxml.jackson.databind.ObjectMapper$DefaultTypeResolverBuilder", "com.fasterxml.jackson.databind.deser.BeanDeserializerModifier", "com.fasterxml.jackson.databind.util.AccessPattern", "com.fasterxml.jackson.databind.deser.std.CollectionDeserializer", "com.fasterxml.jackson.databind.deser.impl.FieldProperty", "com.fasterxml.jackson.databind.jsontype.TypeSerializer", "com.fasterxml.jackson.databind.deser.std.StdDeserializer", "com.fasterxml.jackson.databind.deser.std.EnumDeserializer", "com.fasterxml.jackson.annotation.ObjectIdGenerators$Base", "com.fasterxml.jackson.databind.deser.ValueInstantiator$Base", "com.fasterxml.jackson.databind.introspect.AnnotatedConstructor", "com.fasterxml.jackson.databind.type.TypeFactory", "com.fasterxml.jackson.databind.deser.std.FromStringDeserializer$Std", "com.fasterxml.jackson.databind.cfg.MapperConfigBase", "com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", "com.fasterxml.jackson.databind.type.ArrayType", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializers", "com.fasterxml.jackson.databind.JsonNode", "com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig", "com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder", "com.fasterxml.jackson.databind.type.MapLikeType", "com.fasterxml.jackson.databind.deser.impl.ObjectIdReader", "com.fasterxml.jackson.databind.type.MapType", "com.fasterxml.jackson.databind.introspect.ObjectIdInfo", "com.fasterxml.jackson.databind.util.Named", "com.fasterxml.jackson.annotation.ObjectIdGenerators$PropertyGenerator", "com.fasterxml.jackson.core.util.JsonParserDelegate", "com.fasterxml.jackson.databind.deser.std.FromStringDeserializer", "com.fasterxml.jackson.databind.PropertyName", "com.fasterxml.jackson.databind.BeanProperty", "com.fasterxml.jackson.databind.type.TypeBase", "com.fasterxml.jackson.databind.type.CollectionType", "com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer", "com.fasterxml.jackson.databind.node.ValueNode", "com.fasterxml.jackson.databind.deser.BasicDeserializerFactory", "com.fasterxml.jackson.databind.node.JsonNodeFactory", "com.fasterxml.jackson.databind.deser.std.EnumMapDeserializer", "com.fasterxml.jackson.databind.introspect.TypeResolutionContext", "com.fasterxml.jackson.databind.util.ClassUtil$Ctor", "com.fasterxml.jackson.databind.cfg.MapperConfig", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringFactoryKeyDeserializer", "com.fasterxml.jackson.databind.deser.SettableBeanProperty", "com.fasterxml.jackson.databind.node.JsonNodeCreator", "com.fasterxml.jackson.annotation.Nulls", "com.fasterxml.jackson.databind.util.ObjectBuffer", "com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase", "com.fasterxml.jackson.databind.InjectableValues", "com.fasterxml.jackson.databind.exc.MismatchedInputException", "com.fasterxml.jackson.databind.deser.impl.ReadableObjectId", "com.fasterxml.jackson.databind.type.TypeParser", "com.fasterxml.jackson.core.JsonGenerator", "com.fasterxml.jackson.databind.deser.DefaultDeserializationContext", "com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer", "com.fasterxml.jackson.core.ObjectCodec", "com.fasterxml.jackson.databind.type.ClassStack", "com.fasterxml.jackson.databind.deser.Deserializers", "com.fasterxml.jackson.databind.deser.KeyDeserializers", "com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer", "com.fasterxml.jackson.databind.JavaType", "com.fasterxml.jackson.databind.KeyDeserializer", "com.fasterxml.jackson.databind.deser.BeanDeserializer", "com.fasterxml.jackson.databind.deser.impl.ErrorThrowingDeserializer", "com.fasterxml.jackson.databind.type.CollectionLikeType", "com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator", "com.fasterxml.jackson.core.TreeNode", "com.fasterxml.jackson.databind.node.NumericNode", "com.fasterxml.jackson.core.TreeCodec", "com.fasterxml.jackson.annotation.ObjectIdResolver", "com.fasterxml.jackson.databind.DeserializationContext", "com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase", "com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer", "com.fasterxml.jackson.databind.deser.impl.SetterlessProperty", "com.fasterxml.jackson.databind.deser.ValueInstantiator", "com.fasterxml.jackson.databind.deser.NullValueProvider", "com.fasterxml.jackson.annotation.JacksonAnnotationValue", "com.fasterxml.jackson.databind.type.ResolvedRecursiveType", "com.fasterxml.jackson.databind.introspect.Annotated", "com.fasterxml.jackson.annotation.JsonTypeInfo$None", "com.fasterxml.jackson.databind.util.NameTransformer", "com.fasterxml.jackson.databind.type.ReferenceType", "com.fasterxml.jackson.databind.deser.std.MapEntryDeserializer", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DelegatingKD", "com.fasterxml.jackson.databind.deser.BeanDeserializerBase", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$EnumKD", "com.fasterxml.jackson.databind.ObjectMapper$DefaultTyping", "com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition", "com.fasterxml.jackson.databind.deser.impl.PropertyValueBuffer", "com.fasterxml.jackson.databind.Module", "com.fasterxml.jackson.core.util.JsonParserSequence", "com.fasterxml.jackson.databind.type.PlaceholderForType", "com.fasterxml.jackson.databind.util.Converter", "com.fasterxml.jackson.databind.AnnotationIntrospector", "com.fasterxml.jackson.core.SerializableString", "com.fasterxml.jackson.databind.deser.ValueInstantiators", "com.fasterxml.jackson.databind.jsontype.TypeDeserializer", "com.fasterxml.jackson.core.Versioned", "com.fasterxml.jackson.databind.node.LongNode", "com.fasterxml.jackson.databind.deser.std.StringDeserializer", "com.fasterxml.jackson.databind.deser.std.StringArrayDeserializer", "com.fasterxml.jackson.databind.DeserializationFeature", "com.fasterxml.jackson.annotation.JsonFormat$Value", "com.fasterxml.jackson.databind.exc.InvalidTypeIdException", "com.fasterxml.jackson.databind.PropertyMetadata", "com.fasterxml.jackson.databind.deser.std.EnumSetDeserializer", "com.fasterxml.jackson.databind.deser.CreatorProperty", "com.fasterxml.jackson.databind.deser.std.ReferenceTypeDeserializer", "com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer", "com.fasterxml.jackson.databind.deser.ResolvableDeserializer", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringCtorKeyDeserializer", "com.fasterxml.jackson.databind.node.BaseJsonNode", "com.fasterxml.jackson.databind.introspect.AnnotatedMember", "com.fasterxml.jackson.databind.JsonSerializable", "com.fasterxml.jackson.databind.util.LRUMap", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer", "com.fasterxml.jackson.databind.BeanDescription", "com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer", "com.fasterxml.jackson.databind.JsonDeserializer", "com.fasterxml.jackson.core.type.TypeReference", "com.fasterxml.jackson.core.JsonParseException", "com.fasterxml.jackson.databind.introspect.ConcreteBeanPropertyBase", "com.fasterxml.jackson.databind.deser.std.NullifyingDeserializer", "com.fasterxml.jackson.databind.ObjectMapper$3", "com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition", "com.fasterxml.jackson.databind.deser.impl.MethodProperty", "com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer", "com.fasterxml.jackson.databind.deser.DeserializerFactory", "com.fasterxml.jackson.databind.introspect.AnnotatedWithParams", "com.fasterxml.jackson.annotation.JsonTypeInfo$Id", "com.fasterxml.jackson.core.Base64Variant", "com.fasterxml.jackson.databind.type.TypeModifier", "com.fasterxml.jackson.databind.introspect.AnnotatedClass", "com.fasterxml.jackson.annotation.JsonTypeInfo", "com.fasterxml.jackson.databind.deser.std.AtomicReferenceDeserializer", "com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder", "com.fasterxml.jackson.databind.introspect.ClassIntrospector$MixInResolver", "com.fasterxml.jackson.databind.JsonMappingException", "com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer", "com.fasterxml.jackson.databind.exc.InvalidFormatException", "com.fasterxml.jackson.databind.deser.AbstractDeserializer", "com.fasterxml.jackson.databind.deser.std.MapDeserializer", "com.fasterxml.jackson.annotation.JsonTypeInfo$As", "com.fasterxml.jackson.databind.deser.std.TokenBufferDeserializer", "com.fasterxml.jackson.databind.type.SimpleType", "com.fasterxml.jackson.databind.DatabindContext", "com.fasterxml.jackson.core.type.ResolvedType", "com.fasterxml.jackson.databind.MapperFeature", "com.fasterxml.jackson.databind.DeserializationConfig", "com.fasterxml.jackson.databind.type.TypeBindings", "com.fasterxml.jackson.databind.deser.std.JsonLocationInstantiator", "com.fasterxml.jackson.databind.util.ClassUtil", "com.fasterxml.jackson.databind.introspect.AnnotatedField", "com.fasterxml.jackson.databind.SerializerProvider", "com.fasterxml.jackson.core.JsonToken", "com.fasterxml.jackson.databind.introspect.AnnotatedMethod", "com.fasterxml.jackson.databind.deser.BeanDeserializerFactory", "com.fasterxml.jackson.databind.jsontype.TypeIdResolver", "com.fasterxml.jackson.annotation.JsonFormat$Feature", "com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase", "com.fasterxml.jackson.databind.util.ConstantValueInstantiator", "com.fasterxml.jackson.databind.deser.ContextualDeserializer", "com.fasterxml.jackson.core.JsonParser", "com.fasterxml.jackson.databind.introspect.AnnotatedParameter", "com.fasterxml.jackson.databind.deser.ValueInstantiator$Gettable", "com.fasterxml.jackson.databind.ObjectMapper", "com.fasterxml.jackson.databind.AbstractTypeResolver", "com.fasterxml.jackson.core.JsonProcessingException", "com.fasterxml.jackson.annotation.ObjectIdGenerator", "com.fasterxml.jackson.databind.deser.std.StdDelegatingDeserializer", "com.fasterxml.jackson.databind.deser.DeserializerCache", "com.fasterxml.jackson.databind.deser.std.ArrayBlockingQueueDeserializer", "com.fasterxml.jackson.databind.util.ArrayBuilders", "com.fasterxml.jackson.databind.cfg.ConfigFeature", "com.fasterxml.jackson.databind.exc.InvalidDefinitionException", "com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer" ); } private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { mock(Class.forName("com.fasterxml.jackson.databind.JsonDeserializer", false, AtomicReferenceDeserializer_ESTest_scaffolding.class.getClassLoader())); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(AtomicReferenceDeserializer_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "com.fasterxml.jackson.databind.JsonDeserializer", "com.fasterxml.jackson.databind.DeserializationFeature", "com.fasterxml.jackson.databind.deser.std.StdDeserializer", "com.fasterxml.jackson.databind.deser.std.ReferenceTypeDeserializer", "com.fasterxml.jackson.databind.deser.std.AtomicReferenceDeserializer", "com.fasterxml.jackson.databind.util.LRUMap", "com.fasterxml.jackson.databind.type.TypeParser", "com.fasterxml.jackson.databind.type.TypeBindings", "com.fasterxml.jackson.core.type.ResolvedType", "com.fasterxml.jackson.databind.JavaType", "com.fasterxml.jackson.databind.type.TypeBase", "com.fasterxml.jackson.databind.type.SimpleType", "com.fasterxml.jackson.databind.type.TypeFactory", "com.fasterxml.jackson.databind.type.ClassStack", "com.fasterxml.jackson.databind.util.ClassUtil", "com.fasterxml.jackson.databind.deser.ValueInstantiator", "com.fasterxml.jackson.databind.deser.ValueInstantiator$Base", "com.fasterxml.jackson.databind.jsontype.TypeDeserializer", "com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase", "com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer", "com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer", "com.fasterxml.jackson.databind.deser.std.FromStringDeserializer", "com.fasterxml.jackson.databind.deser.std.FromStringDeserializer$Std", "com.fasterxml.jackson.databind.util.AccessPattern", "com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector", "com.fasterxml.jackson.databind.BeanDescription", "com.fasterxml.jackson.databind.introspect.BasicBeanDescription", "com.fasterxml.jackson.databind.deser.DeserializerFactory", "com.fasterxml.jackson.databind.PropertyName", "com.fasterxml.jackson.databind.deser.BasicDeserializerFactory", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializers", "com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig", "com.fasterxml.jackson.databind.deser.BeanDeserializerFactory", "com.fasterxml.jackson.databind.DatabindContext", "com.fasterxml.jackson.databind.DeserializationContext", "com.fasterxml.jackson.databind.deser.DefaultDeserializationContext", "com.fasterxml.jackson.databind.deser.DefaultDeserializationContext$Impl", "com.fasterxml.jackson.databind.deser.DeserializerCache", "com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder", "com.fasterxml.jackson.core.io.SerializedString", "com.fasterxml.jackson.core.util.DefaultPrettyPrinter", "com.fasterxml.jackson.core.JsonFactory", "com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer", "com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer$TableInfo", "com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer", "com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer$TableInfo", "com.fasterxml.jackson.databind.JsonSerializer", "com.fasterxml.jackson.databind.ser.std.StdSerializer", "com.fasterxml.jackson.databind.ser.impl.FailingSerializer", "com.fasterxml.jackson.databind.ser.impl.UnknownSerializer", "com.fasterxml.jackson.databind.SerializerProvider", "com.fasterxml.jackson.databind.ser.DefaultSerializerProvider", "com.fasterxml.jackson.databind.ser.DefaultSerializerProvider$Impl", "com.fasterxml.jackson.databind.ser.std.NullSerializer", "com.fasterxml.jackson.databind.ser.SerializerCache", "com.fasterxml.jackson.core.TreeCodec", "com.fasterxml.jackson.core.ObjectCodec", "com.fasterxml.jackson.databind.AnnotationIntrospector", "com.fasterxml.jackson.databind.ext.Java7SupportImpl", "com.fasterxml.jackson.databind.ext.Java7Support", "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "com.fasterxml.jackson.databind.cfg.BaseSettings", "com.fasterxml.jackson.databind.util.StdDateFormat", "com.fasterxml.jackson.core.Base64Variant", "com.fasterxml.jackson.core.Base64Variants", "com.fasterxml.jackson.databind.ObjectMapper", "com.fasterxml.jackson.databind.jsontype.SubtypeResolver", "com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver", "com.fasterxml.jackson.databind.util.RootNameLookup", "com.fasterxml.jackson.databind.introspect.SimpleMixInResolver", "com.fasterxml.jackson.databind.introspect.ClassIntrospector", "com.fasterxml.jackson.databind.introspect.AnnotationCollector$NoAnnotations", "com.fasterxml.jackson.databind.introspect.AnnotationCollector", "com.fasterxml.jackson.databind.introspect.AnnotatedClassResolver", "com.fasterxml.jackson.databind.introspect.Annotated", "com.fasterxml.jackson.databind.introspect.AnnotatedClass$Creators", "com.fasterxml.jackson.databind.introspect.AnnotatedClass", "com.fasterxml.jackson.databind.introspect.BasicClassIntrospector", "com.fasterxml.jackson.databind.cfg.ConfigOverrides", "com.fasterxml.jackson.annotation.JsonInclude$Value", "com.fasterxml.jackson.annotation.Nulls", "com.fasterxml.jackson.annotation.JsonSetter$Value", "com.fasterxml.jackson.annotation.JsonAutoDetect$Visibility", "com.fasterxml.jackson.databind.introspect.VisibilityChecker$Std", "com.fasterxml.jackson.annotation.JsonFormat$Shape", "com.fasterxml.jackson.annotation.JsonFormat$Features", "com.fasterxml.jackson.annotation.JsonFormat$Value", "com.fasterxml.jackson.databind.cfg.MapperConfig", "com.fasterxml.jackson.databind.cfg.ConfigOverride", "com.fasterxml.jackson.databind.cfg.ConfigOverride$Empty", "com.fasterxml.jackson.databind.MapperFeature", "com.fasterxml.jackson.databind.cfg.MapperConfigBase", "com.fasterxml.jackson.core.util.DefaultPrettyPrinter$NopIndenter", "com.fasterxml.jackson.core.util.DefaultPrettyPrinter$FixedSpaceIndenter", "com.fasterxml.jackson.core.util.DefaultIndenter", "com.fasterxml.jackson.core.util.Separators", "com.fasterxml.jackson.core.PrettyPrinter", "com.fasterxml.jackson.databind.SerializationConfig", "com.fasterxml.jackson.databind.cfg.ContextAttributes", "com.fasterxml.jackson.databind.cfg.ContextAttributes$Impl", "com.fasterxml.jackson.databind.DeserializationConfig", "com.fasterxml.jackson.databind.node.JsonNodeFactory", "com.fasterxml.jackson.databind.ser.SerializerFactory", "com.fasterxml.jackson.databind.ser.std.StdScalarSerializer", "com.fasterxml.jackson.databind.ser.std.StringSerializer", "com.fasterxml.jackson.databind.ser.std.ToStringSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializers", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$Base", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntegerSerializer", "com.fasterxml.jackson.core.JsonParser$NumberType", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$LongSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntLikeSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$ShortSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$DoubleSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializers$FloatSerializer", "com.fasterxml.jackson.databind.ser.std.BooleanSerializer", "com.fasterxml.jackson.databind.ser.std.NumberSerializer", "com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase", "com.fasterxml.jackson.databind.ser.std.CalendarSerializer", "com.fasterxml.jackson.databind.ser.std.DateSerializer", "com.fasterxml.jackson.databind.ser.std.StdJdkSerializers", "com.fasterxml.jackson.databind.ser.std.UUIDSerializer", "com.fasterxml.jackson.databind.ser.BasicSerializerFactory", "com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig", "com.fasterxml.jackson.databind.ser.BeanSerializerFactory", "com.fasterxml.jackson.core.io.InputDecorator", "com.fasterxml.jackson.databind.type.TypeBindings$AsKey", "com.fasterxml.jackson.databind.type.MapLikeType", "com.fasterxml.jackson.databind.type.MapType", "com.fasterxml.jackson.core.io.OutputDecorator", "com.fasterxml.jackson.databind.type.ReferenceType", "com.fasterxml.jackson.databind.type.TypeBindings$TypeParamStash", "com.fasterxml.jackson.databind.ext.CoreXMLDeserializers$Std", "com.fasterxml.jackson.databind.type.ArrayType", "com.fasterxml.jackson.databind.type.PlaceholderForType", "com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase", "com.fasterxml.jackson.databind.jsontype.impl.ClassNameIdResolver", "com.fasterxml.jackson.core.JsonProcessingException", "com.fasterxml.jackson.databind.JsonMappingException", "com.fasterxml.jackson.databind.exc.MismatchedInputException", "com.fasterxml.jackson.databind.exc.InvalidTypeIdException", "com.fasterxml.jackson.databind.type.TypeModifier", "com.fasterxml.jackson.databind.module.SimpleDeserializers", "com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer", "com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer", "com.fasterxml.jackson.core.util.BufferRecycler", "com.fasterxml.jackson.databind.type.CollectionLikeType", "com.fasterxml.jackson.databind.ser.BeanSerializerBuilder", "com.fasterxml.jackson.databind.JsonSerializable$Base", "com.fasterxml.jackson.databind.JsonNode", "com.fasterxml.jackson.databind.node.BaseJsonNode", "com.fasterxml.jackson.databind.node.ValueNode", "com.fasterxml.jackson.databind.node.NumericNode", "com.fasterxml.jackson.databind.node.LongNode", "com.fasterxml.jackson.databind.type.CollectionType", "com.fasterxml.jackson.core.type.TypeReference", "com.fasterxml.jackson.databind.deser.DeserializationProblemHandler", "com.fasterxml.jackson.databind.util.LinkedNode", "com.fasterxml.jackson.databind.deser.BeanDeserializerBase", "com.fasterxml.jackson.databind.deser.BeanDeserializer", "com.fasterxml.jackson.databind.module.SimpleKeyDeserializers", "com.fasterxml.jackson.databind.util.ArrayBuilders", "com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector$1", "com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector", "com.fasterxml.jackson.databind.deser.BeanDeserializerModifier", "com.fasterxml.jackson.databind.deser.AbstractDeserializer", "com.fasterxml.jackson.databind.type.ResolvedRecursiveType", "com.fasterxml.jackson.databind.KeyDeserializer", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DelegatingKD", "com.fasterxml.jackson.databind.PropertyNamingStrategy$PropertyNamingStrategyBase", "com.fasterxml.jackson.databind.PropertyNamingStrategy$SnakeCaseStrategy", "com.fasterxml.jackson.databind.PropertyNamingStrategy$UpperCamelCaseStrategy", "com.fasterxml.jackson.databind.PropertyNamingStrategy$LowerCaseStrategy", "com.fasterxml.jackson.databind.PropertyNamingStrategy$KebabCaseStrategy", "com.fasterxml.jackson.databind.PropertyNamingStrategy", "com.fasterxml.jackson.databind.type.ClassKey", "com.fasterxml.jackson.databind.MappingJsonFactory", "com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder", "com.fasterxml.jackson.databind.ObjectMapper$DefaultTypeResolverBuilder", "com.fasterxml.jackson.databind.ObjectMapper$3", "com.fasterxml.jackson.databind.node.ContainerNode", "com.fasterxml.jackson.databind.node.ObjectNode", "com.fasterxml.jackson.core.JsonParser", "com.fasterxml.jackson.core.base.ParserMinimalBase", "com.fasterxml.jackson.databind.node.TreeTraversingParser", "com.fasterxml.jackson.databind.jsontype.impl.MinimalClassNameIdResolver", "com.fasterxml.jackson.databind.AbstractTypeResolver", "com.fasterxml.jackson.databind.module.SimpleAbstractTypeResolver", "com.fasterxml.jackson.core.io.IOContext", "com.fasterxml.jackson.databind.introspect.VisibilityChecker$1", "com.fasterxml.jackson.core.base.ParserBase", "com.fasterxml.jackson.core.io.CharTypes", "com.fasterxml.jackson.core.json.ReaderBasedJsonParser", "com.fasterxml.jackson.core.util.TextBuffer", "com.fasterxml.jackson.core.JsonStreamContext", "com.fasterxml.jackson.core.json.JsonReadContext", "com.fasterxml.jackson.core.JsonToken", "com.fasterxml.jackson.core.util.BufferRecyclers", "com.fasterxml.jackson.core.io.DataOutputAsStream", "com.fasterxml.jackson.core.JsonGenerator", "com.fasterxml.jackson.core.base.GeneratorBase", "com.fasterxml.jackson.core.json.JsonGeneratorImpl", "com.fasterxml.jackson.core.json.UTF8JsonGenerator", "com.fasterxml.jackson.core.json.JsonWriteContext", "com.fasterxml.jackson.core.io.NumberInput", "com.fasterxml.jackson.databind.jsontype.impl.AsExternalTypeDeserializer", "com.fasterxml.jackson.databind.BeanProperty$Bogus", "com.fasterxml.jackson.core.util.VersionUtil", "com.fasterxml.jackson.core.Version", "com.fasterxml.jackson.databind.cfg.PackageVersion", "com.fasterxml.jackson.databind.Module", "com.fasterxml.jackson.databind.module.SimpleModule", "com.fasterxml.jackson.core.io.NumberOutput", "com.fasterxml.jackson.databind.node.JsonNodeType", "com.fasterxml.jackson.annotation.ObjectIdGenerator", "com.fasterxml.jackson.annotation.ObjectIdGenerators$Base", "com.fasterxml.jackson.annotation.ObjectIdGenerators$IntSequenceGenerator", "com.fasterxml.jackson.databind.InjectableValues", "com.fasterxml.jackson.databind.InjectableValues$Std", "com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair", "com.fasterxml.jackson.core.json.async.NonBlockingJsonParserBase", "com.fasterxml.jackson.core.json.async.NonBlockingJsonParser", "com.fasterxml.jackson.annotation.JsonAutoDetect$Value", "com.fasterxml.jackson.databind.deser.ValueInstantiators$Base", "com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap", "com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer", "com.fasterxml.jackson.databind.type.TypeParser$MyTokenizer", "com.fasterxml.jackson.databind.deser.Deserializers$Base", "com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper", "com.fasterxml.jackson.databind.module.SimpleValueInstantiators", "com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition", "com.fasterxml.jackson.databind.AnnotationIntrospector$ReferenceProperty", "com.fasterxml.jackson.databind.AnnotationIntrospector$ReferenceProperty$Type", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder", "com.fasterxml.jackson.core.io.CharacterEscapes", "com.fasterxml.jackson.core.JsonpCharacterEscapes", "com.fasterxml.jackson.core.json.UTF8StreamJsonParser", "com.fasterxml.jackson.databind.node.ArrayNode", "com.fasterxml.jackson.databind.node.NodeCursor", "com.fasterxml.jackson.databind.node.NodeCursor$ArrayCursor", "com.fasterxml.jackson.core.JsonParseException", "com.fasterxml.jackson.core.JsonLocation", "com.fasterxml.jackson.databind.ObjectReader", "com.fasterxml.jackson.databind.jsontype.NamedType", "com.fasterxml.jackson.core.io.SegmentedStringWriter", "com.fasterxml.jackson.core.json.WriterBasedJsonGenerator", "com.fasterxml.jackson.databind.ser.impl.ReadOnlyClassToSerializerMap", "com.fasterxml.jackson.databind.util.TypeKey", "com.fasterxml.jackson.databind.introspect.AnnotationCollector$EmptyCollector", "com.fasterxml.jackson.databind.util.ArrayIterator", "com.fasterxml.jackson.databind.ser.std.ReferenceTypeSerializer", "com.fasterxml.jackson.databind.ser.std.AtomicReferenceSerializer", "com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap", "com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap$Empty", "com.fasterxml.jackson.databind.ser.FilterProvider", "com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider", "com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer", "com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer", "com.fasterxml.jackson.databind.node.BigIntegerNode", "com.fasterxml.jackson.databind.node.NodeCursor$RootCursor", "com.fasterxml.jackson.databind.PropertyMetadata", "com.fasterxml.jackson.databind.BeanProperty$Std", "com.fasterxml.jackson.core.util.JsonParserDelegate", "com.fasterxml.jackson.databind.ObjectMapper$1", "com.fasterxml.jackson.databind.node.BooleanNode", "com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter", "com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter$SerializeExceptFilter", "com.fasterxml.jackson.databind.exc.InvalidFormatException", "com.fasterxml.jackson.databind.introspect.AnnotationMap", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer", "com.fasterxml.jackson.databind.introspect.AnnotatedMember", "com.fasterxml.jackson.databind.introspect.VirtualAnnotatedMember", "com.fasterxml.jackson.core.util.JsonParserSequence", "com.fasterxml.jackson.core.io.MergedStream", "com.fasterxml.jackson.core.util.InternCache", "com.fasterxml.jackson.databind.introspect.ConcreteBeanPropertyBase", "com.fasterxml.jackson.databind.deser.impl.FailingDeserializer", "com.fasterxml.jackson.databind.deser.SettableBeanProperty", "com.fasterxml.jackson.databind.deser.CreatorProperty", "com.fasterxml.jackson.databind.introspect.TypeResolutionContext$Basic", "com.fasterxml.jackson.databind.introspect.AnnotatedParameter", "com.fasterxml.jackson.databind.introspect.AnnotatedField", "com.fasterxml.jackson.core.filter.TokenFilter", "com.fasterxml.jackson.core.filter.FilteringParserDelegate", "com.fasterxml.jackson.core.filter.TokenFilterContext", "com.fasterxml.jackson.databind.deser.std.NullifyingDeserializer", "com.fasterxml.jackson.databind.util.NameTransformer$NopTransformer", "com.fasterxml.jackson.databind.util.NameTransformer", "com.fasterxml.jackson.core.util.ByteArrayBuilder", "com.fasterxml.jackson.databind.introspect.AnnotatedWithParams", "com.fasterxml.jackson.databind.introspect.AnnotatedMethod", "com.fasterxml.jackson.databind.ser.BeanSerializerModifier", "com.fasterxml.jackson.databind.ext.OptionalHandlerFactory", "com.fasterxml.jackson.databind.deser.std.JdkDeserializers", "com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator", "com.fasterxml.jackson.databind.deser.impl.CreatorCollector", "com.fasterxml.jackson.databind.introspect.CollectorBase", "com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector", "com.fasterxml.jackson.databind.introspect.AnnotatedMethodCollector", "com.fasterxml.jackson.databind.introspect.MemberKey", "com.fasterxml.jackson.databind.introspect.AnnotatedMethodCollector$MethodBuilder", "com.fasterxml.jackson.databind.introspect.AnnotatedMethodMap", "com.fasterxml.jackson.databind.util.BeanUtil", "com.fasterxml.jackson.annotation.JsonAutoDetect$1", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$Linked", "com.fasterxml.jackson.databind.introspect.AnnotatedCreatorCollector", "com.fasterxml.jackson.databind.util.ClassUtil$Ctor", "com.fasterxml.jackson.databind.introspect.AnnotatedConstructor", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$9", "com.fasterxml.jackson.annotation.JsonProperty$Access", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$10", "com.fasterxml.jackson.annotation.JsonCreator$Mode", "com.fasterxml.jackson.databind.deser.impl.CreatorCandidate", "com.fasterxml.jackson.databind.deser.impl.CreatorCandidate$Param", "com.fasterxml.jackson.databind.deser.impl.CreatorCollector$StdTypeConstructor", "com.fasterxml.jackson.databind.deser.std.StdValueInstantiator", "com.fasterxml.jackson.annotation.JsonIgnoreProperties$Value", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$4", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$5", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$6", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$7", "com.fasterxml.jackson.databind.deser.impl.MethodProperty", "com.fasterxml.jackson.databind.deser.impl.NullsConstantProvider", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$2", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$8", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$1", "com.fasterxml.jackson.databind.deser.std.StringDeserializer", "com.fasterxml.jackson.annotation.JsonFormat$Feature", "com.fasterxml.jackson.databind.node.FloatNode", "com.fasterxml.jackson.databind.jsontype.impl.TypeNameIdResolver", "com.fasterxml.jackson.databind.ser.Serializers$Base", "com.fasterxml.jackson.databind.module.SimpleSerializers", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers", "com.fasterxml.jackson.databind.deser.std.DateDeserializers", "com.fasterxml.jackson.databind.deser.std.EnumDeserializer", "com.fasterxml.jackson.databind.util.EnumResolver", "com.fasterxml.jackson.databind.util.CompactStringObjectMap", "com.fasterxml.jackson.databind.util.NameTransformer$1", "com.fasterxml.jackson.databind.node.IntNode", "com.fasterxml.jackson.databind.node.NodeCursor$ObjectCursor", "com.fasterxml.jackson.databind.introspect.AnnotationCollector$OneAnnotation", "com.fasterxml.jackson.core.json.UTF8DataInputJsonParser", "com.fasterxml.jackson.core.json.DupDetector", "com.fasterxml.jackson.databind.ext.CoreXMLSerializers$XMLGregorianCalendarSerializer", "com.fasterxml.jackson.core.util.MinimalPrettyPrinter", "com.fasterxml.jackson.databind.ObjectWriter", "com.fasterxml.jackson.databind.ObjectWriter$GeneratorSettings", "com.fasterxml.jackson.databind.ObjectWriter$Prefetch", "com.fasterxml.jackson.databind.util.ObjectBuffer", "com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringKD", "com.fasterxml.jackson.databind.deser.DataFormatReaders", "com.fasterxml.jackson.core.format.MatchStrength", "com.fasterxml.jackson.annotation.SimpleObjectIdResolver", "com.fasterxml.jackson.databind.util.NameTransformer$Chained", "com.fasterxml.jackson.core.JsonPointer", "com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer", "com.fasterxml.jackson.databind.BeanProperty", "com.fasterxml.jackson.databind.ser.PropertyWriter", "com.fasterxml.jackson.databind.ser.BeanPropertyWriter", "com.fasterxml.jackson.core.json.PackageVersion", "com.fasterxml.jackson.databind.node.ShortNode", "com.fasterxml.jackson.databind.node.TextNode", "com.fasterxml.jackson.databind.node.BinaryNode", "com.fasterxml.jackson.databind.node.NullNode", "com.fasterxml.jackson.databind.ser.std.BeanSerializerBase", "com.fasterxml.jackson.databind.ser.BeanSerializer", "com.fasterxml.jackson.databind.deser.impl.NullsAsEmptyProvider", "com.fasterxml.jackson.databind.node.POJONode", "com.fasterxml.jackson.databind.introspect.ObjectIdInfo", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers$PrimitiveOrWrapperDeserializer", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer", "com.fasterxml.jackson.databind.exc.InvalidDefinitionException", "com.fasterxml.jackson.core.filter.JsonPointerBasedFilter", "com.fasterxml.jackson.databind.deser.impl.ObjectIdReader", "com.fasterxml.jackson.databind.node.DoubleNode", "com.fasterxml.jackson.annotation.ObjectIdGenerators$StringIdGenerator", "com.fasterxml.jackson.databind.util.NameTransformer$3", "com.fasterxml.jackson.databind.node.MissingNode", "com.fasterxml.jackson.databind.node.DecimalNode", "com.fasterxml.jackson.core.io.UTF32Reader", "com.fasterxml.jackson.databind.introspect.AnnotationCollector$TwoAnnotations", "com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase", "com.fasterxml.jackson.databind.deser.std.CollectionDeserializer", "com.fasterxml.jackson.databind.deser.std.MapDeserializer", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers$NumberDeserializer", "com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla", "com.fasterxml.jackson.annotation.ObjectIdGenerator$IdKey", "com.fasterxml.jackson.core.util.JsonGeneratorDelegate", "com.fasterxml.jackson.core.filter.FilteringGeneratorDelegate", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringFactoryKeyDeserializer", "com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector$FieldBuilder", "com.fasterxml.jackson.databind.introspect.AnnotationCollector$OneCollector", "com.fasterxml.jackson.databind.util.NameTransformer$2", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringCtorKeyDeserializer", "com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter$FilterExceptFilter", "com.fasterxml.jackson.databind.deser.impl.SetterlessProperty", "com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer", "com.fasterxml.jackson.databind.cfg.MutableConfigOverride", "com.fasterxml.jackson.databind.ser.std.EnumSerializer", "com.fasterxml.jackson.databind.util.EnumValues", "com.fasterxml.jackson.core.io.JsonStringEncoder", "com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$EnumKD", "com.fasterxml.jackson.databind.util.TokenBuffer", "com.fasterxml.jackson.databind.util.TokenBuffer$Segment", "com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder$1", "com.fasterxml.jackson.databind.jsontype.TypeSerializer", "com.fasterxml.jackson.databind.jsontype.impl.TypeSerializerBase", "com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeSerializer", "com.fasterxml.jackson.databind.ser.BasicSerializerFactory$1", "com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer", "com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap$Single", "com.fasterxml.jackson.databind.util.TokenBuffer$Parser", "com.fasterxml.jackson.databind.util.TokenBufferReadContext", "com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer", "com.fasterxml.jackson.databind.PropertyMetadata$MergeInfo", "com.fasterxml.jackson.core.type.WritableTypeId", "com.fasterxml.jackson.databind.ser.std.SerializableSerializer", "com.fasterxml.jackson.databind.exc.PropertyBindingException", "com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException", "com.fasterxml.jackson.databind.ser.PropertyBuilder", "com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$3", "com.fasterxml.jackson.databind.ser.PropertyBuilder$1", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers$ShortDeserializer", "com.fasterxml.jackson.databind.MappingIterator", "com.fasterxml.jackson.core.format.InputAccessor$Std", "com.fasterxml.jackson.databind.deser.impl.NullsFailProvider", "com.fasterxml.jackson.databind.deser.impl.FieldProperty", "com.fasterxml.jackson.databind.deser.std.NumberDeserializers$DoubleDeserializer", "com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder$Value", "com.fasterxml.jackson.databind.deser.impl.ReadableObjectId", "com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper$Base", "com.fasterxml.jackson.databind.JsonNode$1", "com.fasterxml.jackson.annotation.JsonTypeInfo$Id" ); } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
abca94d577fa076a61e649ec796c671fdd6123e7
bd54394554a75b7e79bf5351b7b149e23abfdf57
/shop/service/authentication/src/main/java/com/comsysto/shop/service/authentication/impl/AuthenticationServiceImpl.java
5bb86cb2d25a09cf3b952236cb6b939ab2f72a01
[ "Apache-2.0" ]
permissive
gnanendraaws/mongodb-onlineshop
c542f7247e7f1f72e20ee9327122ca31ef4b49a6
ccfaa35dc666afacbedf40d10cc13a9734aacdb5
refs/heads/master
2021-01-16T04:44:55.778646
2013-11-21T09:50:14
2013-11-21T09:50:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,865
java
package com.comsysto.shop.service.authentication.impl; import com.comsysto.shop.service.authentication.api.AuthenticationService; import com.comsysto.shop.service.authentication.model.LoginInfo; import com.comsysto.shop.service.user.api.UserService; import com.comsysto.shop.service.user.model.UserInfo; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Service; import java.util.*; /** * @author zutherb */ @Service("authenticationService") public class AuthenticationServiceImpl implements AuthenticationService { private Logger logger = LoggerFactory.getLogger(AuthenticationServiceImpl.class); private AuthenticationManager authenticationManager; private UserService userService; @Autowired public AuthenticationServiceImpl(@Qualifier("org.springframework.security.authenticationManager") AuthenticationManager authenticationManager, UserService userService){ this.authenticationManager = authenticationManager; this.userService = userService; } @Override public boolean authenticate(LoginInfo loginInfo){ try{ Authentication usernamePasswordAuthentication = new UsernamePasswordAuthenticationToken(loginInfo.getUsername(), loginInfo.getPassword()); Authentication authenticateResult = authenticationManager.authenticate(usernamePasswordAuthentication); SecurityContextHolder.getContext().setAuthentication(authenticateResult); logger.info(String.format("Authentication of '%s' was %ssuccessful", loginInfo.getUsername(), (authenticateResult.isAuthenticated() ? "" : "not "))); return authenticateResult.isAuthenticated(); }catch (AuthenticationException e) { String msg = String.format("User '%s' could not authenticated correct:", loginInfo.getUsername()); logger.info(msg, e); } return false; } @Override public void clearAuthentication() { SecurityContextHolder.clearContext(); } @Override public boolean isAuthorized(String... permissions) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Collection<ConfigAttribute> configAttributes = convertToConfigAttribute(permissions); if(authentication == null){ return false; } else { if(CollectionUtils.isEmpty(Arrays.asList(permissions))){ return true; } List<GrantedAuthority> expectedAuthorities = getAuthorities(permissions); for(GrantedAuthority authority : authentication.getAuthorities()){ if(expectedAuthorities.contains(authority)){ return true; } } return false; } } private List<GrantedAuthority> getAuthorities(String[] permissions) { ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for(String permission : permissions){ grantedAuthorities.add(new SimpleGrantedAuthority(permission)); } return grantedAuthorities; } private Collection<ConfigAttribute> convertToConfigAttribute(String[] permissions) { Set<ConfigAttribute> configAttributes = new HashSet<ConfigAttribute>(); for (final String permission : permissions){ configAttributes.add(new SecurityConfig(permission)); } return configAttributes ; } @Override public UserInfo getAuthenticatedUserInfo() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication != null && authentication.getPrincipal() != null){ User user = (User)authentication.getPrincipal(); return userService.findByUsername(user.getUsername()); } return null; } }
[ "christian.kroemer@comsysto.com" ]
christian.kroemer@comsysto.com
7bd5987a8d91a1e64e51681d7bb76c7a9285065a
9f48add932c3b92b42e3a0b7b34c3e0368fbde4f
/java/blackjack/src/main/java/Blackjack.java
f551474d03136af73f15e6242b518fc79c3dd7c5
[]
no_license
Tedford/Exercism
b5199efc7add38cdafa99b45f209411cf51b8fad
43c7d5f628afe3a182054cd4417e471b3b5f552a
refs/heads/master
2023-04-07T14:13:19.406917
2023-04-03T18:36:36
2023-04-03T18:36:36
77,917,914
0
0
null
2022-12-08T10:55:34
2017-01-03T13:07:14
F#
UTF-8
Java
false
false
2,567
java
public class Blackjack { private final int BLACKJACK = 21; private final String HIT = "H"; private final String SPLIT = "P"; private final String STAND = "S"; private final String WIN = "W"; public int parseCard(String card) { var value = 0; switch(card){ case "ace": value = 11; break; case "king": case "queen": case "jack": case "ten": value = 10; break; case "nine": value = 9; break; case "eight": value = 8; break; case "seven": value = 7; break; case "six": value = 6; break; case "five": value = 5; break; case "four": value =4; break; case "three": value =3; break; case "two": value = 2; break; case "one": value = 1; break; } return value; } public boolean isBlackjack(String card1, String card2) { return parseCard(card1) + parseCard(card2) == BLACKJACK; } public String largeHand(boolean isBlackjack, int dealerScore) { var strategy = STAND; if( !isBlackjack) { strategy =SPLIT; } else if( dealerScore < 10) { strategy = WIN; } return strategy; } public String smallHand(int handScore, int dealerScore) { var strategy = STAND; if( handScore <11|| (handScore < 17 && dealerScore > 6) ){ strategy = HIT; } return strategy; } // FirstTurn returns the semi-optimal decision for the first turn, given the cards of the player and the dealer. // This function is already implemented and does not need to be edited. It pulls the other functions together in a // complete decision tree for the first turn. public String firstTurn(String card1, String card2, String dealerCard) { int handScore = parseCard(card1) + parseCard(card2); int dealerScore = parseCard(dealerCard); if (20 < handScore) { return largeHand(isBlackjack(card1, card2), dealerScore); } else { return smallHand(handScore, dealerScore); } } }
[ "dev@tedfordjohnson.com" ]
dev@tedfordjohnson.com
07e437811698c8793ad9933c8b2e10894a19edb7
8f5dddee0f7c6137df5955e94833475e35ff1bbe
/src/main/java/com/linjiahao/security/service/ResourceService.java
051603e6a97bf258ff6ce471c038f9e5ec3f81d2
[]
no_license
1143910315/security
68c13ea523cf1dd727f54316d662969f61888bb4
cf6cdce7342ddb7dcdccce14fc119a6e241a4746
refs/heads/master
2022-12-25T11:59:51.602849
2019-06-01T09:41:34
2019-06-01T09:41:34
186,675,520
0
0
null
2022-12-14T20:39:18
2019-05-14T18:10:15
Java
UTF-8
Java
false
false
614
java
package com.linjiahao.security.service; import com.linjiahao.security.bean.Resource; import com.linjiahao.security.repository.ResourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ResourceService { private final ResourceRepository resourceRepository; @Autowired public ResourceService(ResourceRepository resourceRepository) { this.resourceRepository = resourceRepository; } public Resource getResourceByUrl(String url) { return resourceRepository.findFirstByUrl(url); } }
[ "1143910315@qq.com" ]
1143910315@qq.com
2a5a950fc70891d7f28287b919aa1afa609124cc
4c7160dfa145a9064d6d8d6e53a2439a1df73d50
/app/src/main/java/com/heizi/kuaguo/block/my/ActivityMyWallet.java
ada41ae994ce64e51fe52fcccd09e966ccfca835
[]
no_license
linalong/KuaGuo
013cb774a69a643fad4d61626385939f3a283fc6
91e609c84c9f533e5cd08fab37e904ef28fb8a67
refs/heads/master
2020-03-11T02:27:15.614385
2018-06-07T06:46:19
2018-06-07T06:46:27
129,719,443
0
0
null
null
null
null
UTF-8
Java
false
false
1,572
java
package com.heizi.kuaguo.block.my; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import com.heizi.kuaguo.R; import com.heizi.kuaguo.activity.BaseSwipeBackCompatActivity; import butterknife.InjectView; import butterknife.OnClick; /** * ๆˆ‘็š„้’ฑๅŒ… * Created by leo on 17/9/28. */ public class ActivityMyWallet extends BaseSwipeBackCompatActivity implements View.OnClickListener { @InjectView(R.id.ll_verify) LinearLayout ll_verify; @InjectView(R.id.ll_wallet) LinearLayout ll_wallet; @InjectView(R.id.ll_mail) LinearLayout ll_mail; @Override protected int getLayoutResource() { return R.layout.activity_mywallet; } @Override protected void initView() { super.initView(); tv_title.setText("ๆˆ‘็š„้’ฑๅŒ…"); btn_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void initData() { super.initData(); } @OnClick({R.id.ll_wallet, R.id.ll_mail}) @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll_wallet: Bundle bundle = new Bundle(); bundle.putInt("type", 0); startActivity(this, ActivityPayPwd.class, bundle); break; case R.id.ll_mail: startActivity(this, ActivityEmailVerify.class, null); break; } } }
[ "1653012690@qq.com" ]
1653012690@qq.com
7b3552ef2349126ce29101b61bd4a8a4f53d92c4
97e042bc734e2796998eef7bb98f7422eadacb2f
/src/main/java/com/aguan/syn/SynchronizeThreadMethod.java
08b3ec352dd0b3ff5a3b440f02167256911aaddb
[]
no_license
aguan48/multitread
0054d8349568e2b8aa3d6b529ff976fc5f04ffa4
05c94854881a094933d6d2a88392ec1c954e02b2
refs/heads/master
2021-05-19T04:08:04.857924
2020-03-31T14:05:56
2020-03-31T14:05:56
251,521,689
0
0
null
null
null
null
UTF-8
Java
false
false
979
java
package com.aguan.syn; /** * ๅŒๆญฅๆ–นๆณ•็š„ๆต‹่ฏ•็”จไพ‹ */ public class SynchronizeThreadMethod implements Runnable { private int books = 5; @Override public void run() { this.BorrowBooks(); } /** * ๅŒๆญฅๆ–นๆณ•synchronizedๅ…ณ้”ฎๅญ—ๅŠ ๅœจไบ†ๆ–นๆณ•ไธŠ */ public synchronized void BorrowBooks(){ for(int i=0;i<100 ;i++){ if(books>0){ /* try{ Thread.sleep(0); }catch(InterruptedException e){ e.printStackTrace(); }*/ System.out.println(Thread.currentThread().getName()+"borrow books๏ผšbooks="+books--); } } } public static void main(String[] args) throws InterruptedException { Runnable runnable = new SynchronizeThreadBlock(); new Thread(runnable).start(); new Thread(runnable).start(); Thread.sleep(1000); } }
[ "1589488065@qq.com" ]
1589488065@qq.com
5856221d8131ade376bde4cec924778a3f5cb53c
fe405c074a6ff19ca0e03c9e7970e6224f60d1af
/src/main/java/com/tcl/smart/server/bean/HotBaiduNewsRelatedNewsArea.java
f7fd2405df484a6d67e6bf7429705154b6c388e8
[]
no_license
QLzheng/smart-server
1fae05d890c3c270908d1dd664702dff5beeb161
ce6e85116508e5b86a80d80ab7a384d2d70e355c
refs/heads/master
2021-01-10T21:22:54.242766
2013-08-26T01:44:50
2013-08-26T01:44:50
null
0
0
null
null
null
null
GB18030
Java
false
false
1,070
java
package com.tcl.smart.server.bean; /** * ็›ธๅ…ณๆ–ฐ้—ปๅŒบๅŸŸ * * @author fanjie * @date 2013-8-22 */ public class HotBaiduNewsRelatedNewsArea { private String title; private String summary; private String date; private String source; private String href; private String newsImgUrl; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getNewsImgUrl() { return newsImgUrl; } public void setNewsImgUrl(String newsImgUrl) { this.newsImgUrl = newsImgUrl; } }
[ "fanjie@tcl.com" ]
fanjie@tcl.com
1110eeb1c2c9e58c28909d514a2e451eafa9f038
9b38efc742ed9692f252a4de55edd7a0a4e1d699
/src/by/it/group573601/losickov/lesson03/Lesson3Test.java
89eaf4c63aabfbf1a0aa2a450d674c20c78405ba
[]
no_license
menchytskys/RPPZL2017-09-02
24bfaf5f314743672cdf8a0b9a57b332701aaeba
a8201bd8b09a6b75eca69078e2ba00a2d02f12e5
refs/heads/master
2021-07-20T15:17:54.350210
2017-10-27T20:36:24
2017-10-27T20:36:24
108,955,210
0
1
null
2017-10-31T06:33:35
2017-10-31T06:33:35
null
UTF-8
Java
false
false
1,727
java
package by.it.group573601.losickov.lesson03; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import static org.junit.Assert.assertTrue; public class Lesson3Test { /* ะดะปั ะฟั€ะพั…ะพะถะดะตะฝะธั ั‚ะตัั‚ะพะฒ ัะพะทะดะฐะนั‚ะต JUnit-ะบะพะฝั„ะธะณัƒั€ะฐั†ะธัŽ ะฝะฐ ัะฒะพะน ะฟะฐะบะตั‚: ะŸะพะปั: Name: Test a_khmelev (ั‚ัƒั‚ ะฒะฐัˆะฐ ั„ะฐะผะธะปะธั) Test kind: All in package Package: by.it.a_khmelev (ั‚ัƒั‚ ะฒะฐัˆะฐ ั„ะฐะผะธะปะธั) Search for test: In whole project */ @Test public void A() throws Exception { String root = System.getProperty("user.dir") + "/src/"; File f = new File(root + "by/it/a_khmelev/lesson03/dataHuffman.txt"); A_Huffman instance = new A_Huffman(); String result = instance.encode(f); boolean ok=result.equals("01001100100111"); assertTrue("A failed", ok); } @Test public void B() throws Exception { String root = System.getProperty("user.dir") + "/src/"; File f = new File(root + "by/it/a_khmelev/lesson03/encodeHuffman.txt"); B_Huffman instance = new B_Huffman(); String result = instance.decode(f); boolean ok=result.equals("abacabad"); assertTrue("B failed", ok); } @Test public void C() throws Exception { String root = System.getProperty("user.dir") + "/src/"; InputStream stream = new FileInputStream(root + "by/it/a_khmelev/lesson03/heapData.txt"); C_HeapMax instance = new C_HeapMax(); Long res=instance.findMaxValue(stream); boolean ok=(res==500); assertTrue("C failed", ok); } }
[ "kirilllosickov@gmail.com" ]
kirilllosickov@gmail.com
873a80b53fdf94af5e2f1a60b38dc7e61896763a
f180b42bf23fd0120c81be9d29b1918473320170
/src/com/netcracker/libra/controller/TemplateController.java
d0902fada0b2d70b466ed8c7d424e477a46d0967
[]
no_license
AndryLat/Libra
fba980cf3063f124b54c696272efc948e65e2734
fb0fefa637aba59317e3fbfbf58a16b8e989c29a
refs/heads/master
2021-01-17T08:11:34.765568
2013-03-27T16:07:07
2013-03-27T16:07:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,715
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.netcracker.libra.controller; import org.springframework.web.servlet.ModelAndView; import com.netcracker.libra.model.Template; import com.netcracker.libra.dao.TemplateJDBC; import com.netcracker.libra.dao.TypeJDBC; import com.netcracker.libra.dao.UserPreferences; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.netcracker.libra.service.TemplateService; import org.springframework.web.bind.annotation.RequestParam; import com.netcracker.libra.model.InfoForDelete; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; /** * * @author Sashenka */ @Controller public class TemplateController { TemplateJDBC templateJDBC=new TemplateJDBC(); @Autowired UserPreferences userPreferences; /** * ะœะตั‚ะพะด ะพะฑั€ะฐะฑะฐั‚ั‹ะฒะฐะตั‚ ะทะฐะฟั€ะพั ะฟะพ ะดะพะฑะฐะฒะปะตะฝะธัŽ ะฝะพะฒะพะณะพ ัˆะฐะฑะปะพะฝะฐ. * @param name ะธะผั ะฝะพะฒะพะณะพ ัˆะฐะฑะปะพะฝะฐ */ @RequestMapping(value="SubmitTemplate", method= RequestMethod.POST) public ModelAndView addPost(@RequestParam("name") String name) { ModelAndView mv = new ModelAndView(); if(userPreferences.accessLevel==1) { mv.setViewName("messageView"); String message=TemplateService.checkTemplate(name); if(!message.equals("")) { return message("template.html", message, "ะžัˆะธะฑะบะฐ"); } Template lastTemplate=templateJDBC.getTemplate(templateJDBC.add(name)); return new ModelAndView("redirect:showTemplates.html"); } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } } /** * ะฃัั‚ะฐะฝะฐะฒะปะธะฒะฐะตั‚ ะฐะบั‚ะธะฒะฝั‹ะน ัˆะฐะฑะปะพะฝ * @param activeTemplate ะฝะพะผะตั€ ัˆะฐะฑะปะพะฝะฐ, ะบะพั‚ะพั€ั‹ะน ะผั‹ ั…ะพั‚ะธะผ ัƒัั‚ะฐะฝะพะฒะธั‚ัŒ ะฐะบั‚ะธะฒะฝั‹ะผ */ @RequestMapping(value="ActiveTemplate", method= RequestMethod.POST) public ModelAndView addActivePost(@RequestParam("activeTemplate") int activeTemplate) { if(userPreferences.accessLevel==1) { templateJDBC.setActive(activeTemplate); return new ModelAndView("redirect:showTemplates.html"); } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } } /** * ะœะตั‚ะพะด ะดะปั ะพั‚ะพะฑั€ะฐะถะตะฝะธั ะฒัะตั… ัˆะฐะฑะปะพะฝะพะฒ. ะžะฝ ะฟะตั€ะตะดะฐะตั‚ ะฒ ะฒะธะด ัะฟะธัะพะบ ัˆะฐะฑะปะพะฝะพะฒ. * ะŸั€ะธ ะฒะฒะตะดะตะฝะธะต ััั‹ะปะบะธ showTemplates.html ะฒั‹ะทั‹ะฒะฐะตั‚ัั ัั‚ะพั‚ ะผะตั‚ะพะด. */ @RequestMapping("showTemplates") public ModelAndView showTemplate() { if(userPreferences.accessLevel==1) { ModelAndView mav = new ModelAndView(); mav.setViewName("showTemplatesView"); mav.addObject("activeTemplate",templateJDBC.getActive()); mav.addObject("templates", templateJDBC.getAll()); return mav; } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } } /** * ะœะตั‚ะพะด ะบะพั‚ะพั€ั‹ะน ะพะฑั€ะฐะฑะฐั‚ั‹ะฒะฐะตั‚ ะทะฐะฟั€ะพั ะฝะฐ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธะต ัˆะฐะฑะปะพะฝะฐ. * @param name ะฝะพะฒะพะต ะธะผั ัˆะฐะฑะปะพะฝะฐ, ะบะพั‚ะพั€ะพะต ะฟะตั€ะตะดะฐะตั‚ัั POST ะทะฐะฟั€ะพัะพะผ * @param selTemplate ะฝะพะผะตั€ ัˆะฐะฑะปะพะฝะฐ, ะบะพั‚ะพั€ั‹ะน ะผั‹ ั…ะพั‚ะธะผ ะพั‚ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐั‚ัŒ, * ะบะพั‚ะพั€ั‹ะน ะฟะตั€ะตะดะฐะตั‚ัั POST ะทะฐะฟั€ะพัะพะผ */ @RequestMapping(value="showTemplates", method= RequestMethod.POST) public ModelAndView editPost(@RequestParam("name") String name, @RequestParam("selTemplate") int selTemplate) { ModelAndView mav = new ModelAndView(); if(userPreferences.accessLevel==1) { mav.setViewName("messageView"); String message=TemplateService.checkTemplate(name); if(!message.equals("")) { return message("<a href='showTemplates.html'>ะะฐะทะฐะด</a>", message, "ะžัˆะธะฑะบะฐ"); } if(templateJDBC.existTemplate(selTemplate)==0) { return message("<a href='showTemplates.html'>ะŸะพัะผะพั‚ั€ะตั‚ัŒ ะฒัะต ั‚ะธะฟั‹</a>", "ะขะฐะบะพะณะพ ัˆะฐะฑะปะพะฝะฐ ะฝะตั‚ัƒ", "ะžัˆะธะฑะบะฐ"); } templateJDBC.update(selTemplate, name); return new ModelAndView("redirect:showTemplates.html"); } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } } @RequestMapping(value="delTemplate", method= RequestMethod.POST) public String delTemplate(ModelMap model, @RequestParam(value="templates[]",required=false ) int[] delete) { if(delete==null) { return "redirect:showTemplates.html"; } if(userPreferences.accessLevel==1) { List<InfoForDelete> info=templateJDBC.getInfoForDelete(delete); int infoSize=info.size(); model.addAttribute("delete", delete); model.addAttribute("info", info); model.addAttribute("infoSize",infoSize); model.addAttribute("title","ะฃะดะฐะปะธั‚ัŒ ะฐะฝะบะตั‚ั‹"); model.addAttribute("h1","ะ’ั‹ ะดะตะนัั‚ะฒะธั‚ะตะปัŒะฝะพ ั…ะพั‚ะธั‚ะต ัƒะดะฐะปะธั‚ัŒ ัั‚ะพั‚ ัˆะฐะฑะปะพะฝ?"); model.addAttribute("submit","delSubmitTemplate"); model.addAttribute("location","showTemplates.html"); return "delInfoView"; } model.addAttribute("link", "<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>"); model.addAttribute("message", "ะฃ ะฒะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ"); model.addAttribute("title", "ะžัˆะธะฑะบะฐ"); return "messageView"; } /** * ะœะตั‚ะพะด, ะบะพั‚ะพั€ั‹ะน ะฟะตั€ะตะดะฐะตั‚ ะฒ ะฒะธะด ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ัˆะฐะฑะปะพะฝะต(ะดะปั ะฟั€ะตะดะฒะฐั€ะธั‚ะตะปัŒะฝะพะณะพ ะฟั€ะพัะผะพั‚ั€ะฐ), * ะฟะตั€ะตะด ัƒะดะฐะปะตะฝะธะผ ัƒะดะฐะปะธั‚ัŒ * @param templateId ะฝะพะผะตั€ ัˆะฐะฑะปะพะฝะฐ, ะบะพั‚ะพั€ั‹ะน ั…ะพั‚ะธะผ ัƒะดะฐะปะธั‚ัŒ. ะŸะตั€ะตะดะฐะตั‚ัั GET ะทะฐะฟั€ะพัะพะผ */ /* @RequestMapping(value="delTemplate", method= RequestMethod.POST) public ModelAndView delTemplate(@RequestParam(value="templates[]",required=false ) int[] templates) // public ModelAndView delTemplate() { if(templates==null) { return showTemplate(); } ModelAndView mav = new ModelAndView(); if(userPreferences.accessLevel==1) { for(int i=0; i<templates.length;i++) { if(templateJDBC.existTemplate(templates[i])==0) { return message("<a href='showTemplates.html'>ะะฐะทะฐะด</a>", "ะะตั‚ัƒ ั‚ะฐะบะพะณะพ ัˆะฐะฑะปะพะฝะฐ", "ะžัˆะธะฑะบะฐ"); } } List<InfoForDelete> info=templateJDBC.getInfoForDelete(templates); int infoSize=info.size(); mav.setViewName("delTemplateView"); mav.addObject("templates", templates); mav.addObject("info", info); mav.addObject("infoSize",infoSize); return mav; } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } }*/ /** * ะžะฑั€ะฐะฑะฐั‚ั‹ะฒะฐะตั‚ ะทะฐะฟั€ะพั ะฟะพ ัƒะดะฐะปะตะฝะธัŽ ัˆะฐะฑะปะพะฝะฐ * @param templateId ะฝะพะผะตั€ ัˆะฐะฑะปะพะฝะฐ, ะบะพั‚ะพั€ั‹ะน ัƒะดะฐะปัะตั‚ัั. ะฟะตั€ะตะดะฐะตั‚ัั POST ะทะฐะฟั€ะพัะพะผ */ @RequestMapping(value="delSubmitTemplate", method= RequestMethod.POST) public ModelAndView delSubmitTemplate(@RequestParam("delete[]") int[] delete) { if(userPreferences.accessLevel==1) { for(int i=0;i<delete.length;i++) { if(templateJDBC.existTemplate(delete[i])==0) { return message("<a href='showTemplates.html'>ะŸะพัะผะพั‚ั€ะตั‚ัŒ ะฒัะต ั‚ะธะฟั‹</a>", "ะขะฐะบะพะณะพ ัˆะฐะฑะปะพะฝะฐ ะฝะตั‚ัƒ", "ะžัˆะธะฑะบะฐ"); } templateJDBC.delete(delete[i]); } return new ModelAndView("redirect:showTemplates.html"); } else { return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะฃ ะ’ะฐั ะฝะตั‚ัƒ ะฟั€ะฐะฒ ะฝะฐ ัั‚ัƒ ัั‚ั€ะฐะฝะธั†ัƒ","ะžัˆะธะฑะบะฐ"); } } // ColumnsJDBC columnsJDBS=new ColumnsJDBC(); TypeJDBC typeJDBC=new TypeJDBC(); /*@RequestMapping(value="appForm", method= RequestMethod.GET) public ModelAndView showTemplateById(@RequestParam("template") int template) { ModelAndView mav=new ModelAndView(); List<AppFormTopics> list=topicJDBC.getAppFormTopics(template); Map<String, String> map = new HashMap<String, String>(); mav.addObject("topics", list); mav.addObject("columns", columnsJDBS.getAllByemplate(template)); mav.addObject("types", typeJDBC.getAll()); // mav.addObject("map", map); mav.setViewName("appFormView"); return mav; }*/ /* @RequestMapping(value="appForm", method= RequestMethod.GET) public ModelAndView showTemplateById(@RequestParam("template") int template) { ModelAndView mav = new ModelAndView(); List<AppFormTopics> list=topicJDBC.getAppFormTopics(template); ColumnFieldsModel columnFields = new ColumnFieldsModel(); mav.addObject("topics", list); mav.addObject("columns", columnsJDBS.getAllByTemplate(template)); // mav.addObject("types", typeJDBC.getAll()); List<Type> types=typeJDBC.getAll(); Map<Integer,List<String>> enums = new HashMap<Integer,List<String>>(); for(int i=0;i<types.size();i++) { Type t=types.get(i); if(t.getTypeName().equalsIgnoreCase("enum")||t.getTypeName().equalsIgnoreCase("multienum")) { enums.put(t.getTypeId(), TemplateService.getEnumTypes(t.getDescription())); } } mav.addObject("enums", enums); mav.addObject("columnFields", columnFields); mav.setViewName("appFormView"); return mav; } @RequestMapping(value="appForm", method=RequestMethod.POST) public ModelAndView addColumnFields(@ModelAttribute("columnFields") ColumnFieldsModel columnFields) { Map<Integer,String> map=columnFields.getMap(); Set s=map.entrySet(); // Move next key and value of HashMap by iterator Iterator it=s.iterator(); while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next(); // getKey is used to get key of HashMap int key=(Integer)m.getKey(); // getValue is used to get value of key in HashMap String value=(String)m.getValue(); if(!value.equalsIgnoreCase("")) { columnsJDBS.addColumnField(key, userPreferences.UserId, value, 1); } } return message("<a href='/Libra/'>ะ’ะตั€ะฝัƒั‚ัŒัั ะฝะฐะทะฐะด</a>","ะ’ั‹ ะทะฐะฟะพะปะฝะธะปะธ ะฐะฝะบะตั‚ัƒ","ะฃัะฟะตั…"); } */ public ModelAndView message(String link,String message,String title) { ModelAndView mav=new ModelAndView(); mav.setViewName("messageView"); mav.addObject("link",link); mav.addObject("message",message); mav.addObject("title",title); return mav; } }
[ "Sashenka@hp-pc" ]
Sashenka@hp-pc
c15673d6f24ce9252c38a4861411d7d2bd2e2abf
72e1e90dd8e1e43bad4a6ba46a44d1f30aa76fe6
/java/jee/Jee_7_essentials/base/src/main/java/br/com/fernando/chapter15_batchProcessing/part05_listeners/ExecuteBatchEJB.java
f0ee2f310043e91a91fee586740eccaed2debbce
[ "Apache-2.0" ]
permissive
fernando-romulo-silva/myStudies
bfdf9f02778d2f4993999f0ffc0ddd0066ec41b4
aa8867cda5edd54348f59583555b1f8fff3cd6b3
refs/heads/master
2023-08-16T17:18:50.665674
2023-08-09T19:47:15
2023-08-09T19:47:15
230,160,136
3
0
Apache-2.0
2023-02-08T19:49:02
2019-12-25T22:27:59
null
UTF-8
Java
false
false
1,700
java
package br.com.fernando.chapter15_batchProcessing.part05_listeners; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.List; import java.util.Map; import java.util.Properties; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.JobExecution; import javax.batch.runtime.Metric; import javax.batch.runtime.StepExecution; import javax.ejb.Stateless; import br.com.fernando.utils.BatchTestHelper; @Stateless public class ExecuteBatchEJB { public void doIt() throws Exception { final JobOperator jobOperator = BatchRuntime.getJobOperator(); final Long executionId = jobOperator.start("myJob", new Properties()); JobExecution jobExecution = jobOperator.getJobExecution(executionId); jobExecution = BatchTestHelper.keepTestAlive(jobExecution); final List<StepExecution> stepExecutions = jobOperator.getStepExecutions(executionId); for (final StepExecution stepExecution : stepExecutions) { if (stepExecution.getStepName().equals("myStep")) { final Map<Metric.MetricType, Long> metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics()); System.out.println("READ_COUNT: " + metricsMap.get(Metric.MetricType.READ_COUNT).longValue()); System.out.println("WRITE_COUNT: " + metricsMap.get(Metric.MetricType.WRITE_COUNT).longValue()); System.out.println("COMMIT_COUNT: " + metricsMap.get(Metric.MetricType.COMMIT_COUNT).longValue()); } } UtilRecorder.countDownLatch.await(0, SECONDS); System.out.println(jobExecution.getBatchStatus()); } }
[ "fernando.romulo.silva@gmail.com" ]
fernando.romulo.silva@gmail.com
89a9222fccfc8b4c91727d3f358f531a86ebfbd1
dd44fa1cd59d111ffcd949788ca88a69b804eaba
/src/be/ugent/intec/ibcn/geo/common/io/ClusteringIO.java
4eebc9327418a87e1e7e423f854e5938fffcaf88
[]
no_license
tq010or/placing-text
5f07ebe49f4e74a3a1f8c5529a3e385aef04a807
c73fb5e893e338e3f6e01c32a8b0ff74e884e796
refs/heads/master
2021-01-17T23:35:02.594598
2014-04-08T08:52:45
2014-04-08T08:52:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,073
java
package be.ugent.intec.ibcn.geo.common.io; import be.ugent.intec.ibcn.geo.clustering.datatypes.Cluster; import be.ugent.intec.ibcn.geo.common.Util; import be.ugent.intec.ibcn.geo.common.datatypes.Point; import be.ugent.intec.ibcn.geo.common.io.parsers.LineParserPoint; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * This class provides the necessary IO methods to read training data from file, * using the generic LineParserPoint interface. Secondly, this class provides * the IO code to write the clustering back to file. * * The number of training lines is expected to be the first line * of the training file. If this number is not found (currently detected by a * parse error), the number of lines in the file are counted (for large files, * this may introduce a significant delay!). * * The current IO for clustering, loads all the training items as Point objects * INTO AN ARRAY, so this component might be a bottleneck if you try to cluster * tens of millions training items. Be sure to set your -Xms and -Xmx memory * sizes to appropriate values. * * Also, the current IO loading divides the training data into a number of * blocks. Due to this, the last thread, reads the input file and skips N-1 * blocks of data from the start. This can be optimized by using a semaphore/ * lock, as has been implemented in other parts of this framework. This would * allow each thread to fetch for instance 25000 lines to process, until the * file is at the end. * * @author Olivier Van Laere <oliviervanlaere@gmail.com> */ public class ClusteringIO { /** * Holds the number of available threads. */ private static final int NR_THREADS = Runtime.getRuntime().availableProcessors(); /** * Variable holding the number of training items to process before reporting * progress to the console. */ private static final int REPORT_SIZE = 100000; /** * Counter for the number of processed items. */ private int processed = 0; /** * Timestamp for the beginning of loading the training data. */ private long t1; /** * Helper function that reports the current process to the console. */ private synchronized void report() { // process a new update of REPORT_SIZE items that were processed. processed += REPORT_SIZE; // If we have process one million items, print this if (processed % 1000000 == 0) System.out.print((processed / 1000000) + "M"); else // Else just print a dot System.out.print("."); // If we have processed 5 million items, if (processed % 5000000 == 0) { long time = System.currentTimeMillis() - t1; t1 = System.currentTimeMillis(); // Print the time it took, just to give an idea on completion time System.out.println(" ( "+time+" ms.)"); } } /** * Load all the data from file. * @param filename File to read the data from * @param lineparser Classname of the lineparser implementation to use * @return an array */ public Point[] loadDataFromFile(String filename, String lineparser) { return loadDataFromFile(filename, lineparser, -1); } /** * Load data from file. * @param filename File to read the data from * @param lineparser Classname of the lineparser implementation to use * @param limit -1 means all lines, a value >= 0 means a limit on the lines * to process * @return an array */ public Point[] loadDataFromFile(String filename, String lineparser, int limit) { System.out.println("=| Parser: " + lineparser); // Fetch the number of lines to process int lines = FileIO.getNumberOfLines(filename); // Determine the number of lines to process in case a limit was set if (limit > 0 && limit < lines) lines = limit; // Prepare the array with the results Point[] data = new Point[lines]; // Print out the number of lines the code is going to read, and if this // is limited by a threshold, print this as well, to enable verification System.out.println("Loading " + lines + " data items..." + (lines == limit ? " ++ LIMITED BY VARIABLE ++" : "")); // Start the timer long start = System.currentTimeMillis(); this.t1 = start; // Create the thread pool ExecutorService executor = Executors.newFixedThreadPool(NR_THREADS); // Create a list of DataLoaderHelper List<DataLoaderHelper> helpers = new ArrayList<DataLoaderHelper>(); // Determine the block length for each thread to process int length = (int) (data.length * 1.0 / NR_THREADS); for (int i = 0; i < NR_THREADS; i++) { // +1 because of the initial line containing the line count of the // file int begin = i * length + 1; // If this is the last thread if (i == NR_THREADS - 1) { // The block length can be determined otherwise length = data.length - (i * length); } // Determine end value int end = begin + length; // Init the helper thread with a reference to the data, begin, end, // filename and parser DataLoaderHelper helper = new DataLoaderHelper(data, begin, end, filename, lineparser); // submit the helper executor.submit(helper); // track the helper instance helpers.add(helper); } // This will make the executor accept no new threads // and finish all existing threads in the queue executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) {} System.out.println(); // Stop the timer long stop = System.currentTimeMillis(); int parser_errors = 0; int parser_processed = 0; // Fetch processed and error counters from the helper for (DataLoaderHelper helper : helpers) { parser_errors += helper.getErrors(); parser_processed += helper.getProcessed(); } int counter = 0; // Check some stats for sanity purposes for (Point item : data) { if (item != null) { counter++; } } System.out.println("Loading complete. Non-null items: "+counter+" (" + (stop - start) + " ms.)."); System.out.println("+ Parser processed: " + parser_processed); System.out.println("+ Parser errors : " + parser_errors); return data; } /** * Helper class that loads training lines for a part of the training file. */ private class DataLoaderHelper implements Runnable{ /** * Reference to the array that keeps the loaded data. */ private Point [] data; /** * Index to start processing the input data. */ private int begin; /** * Index to stop processing the input data. */ private int end; /** * Input file to process */ private String filename; /** * LineParserPoint class to use for parsing lines. */ private LineParserPoint parser; /** * @return the number of correctly processed lines. */ public int getProcessed() { return parser.getProcessed(); } /** * @return the number of parse errors encountered during processing. */ public int getErrors() { return parser.getErrors(); } /** * Constructor. * @param data Reference to the array that needs to contain the results * @param begin Start index * @param end End index * @param filename Filename to process * @param lineparserpoint class name of the LineParserPoint * implementation to use */ public DataLoaderHelper(Point [] data, int begin, int end, String filename, String lineparserpoint) { this.data = data; this.begin = begin; this.end = end; this.filename = filename; // Instantiate the LineParserPoint parser this.parser = (LineParserPoint)Util.getParser(lineparserpoint); // First line of file should contain the number of lines in the file if (this.begin == 0) this.begin = 1; } /** * run() implementation of this Runnable. */ @Override public void run() { try { // Set up the input BufferedReader file = new BufferedReader( new FileReader(filename)); String line = file.readLine(); int skipcounter = 0; // Skip the necessary number of lines to get to the part of the // file this Runnable is going to process while (skipcounter++ < begin) line = file.readLine(); int counter = begin; // Set the index int index = begin; // Process while we have input and while we have not reached end while (line != null && counter < end) { // Trim the line, just to be sure line = line.trim(); // If something remains if (line.length() > 0) // parse the line and store the result data[index-1] = parser.parse(line); ++counter; // If we need to report progress if ((counter - begin) % REPORT_SIZE == 0) // do so report(); // Read the next line line = file.readLine(); index++; } file.close(); } catch (IOException e){ System.out.println("Error loading data: " + e.getMessage()); System.exit(0); } } } /** * Helper method that facilitates writing a given grid-clustering to file. * @param clusters The resulting clusters from the algorithm * @param outputfile The name of the file to write the clusters to. */ public void writeClusteringToFile(Map<Long, Cluster> clusters, String outputfile) { writeClusteringToFile(clusters, outputfile, false); } /** * Helper method that facilitates writing a given grid-clustering to file. * @param clusters The resulting clusters from the algorithm * @param outputfile The name of the file to write the clusters to. * @param fullWrite If set to true, not only the ID,lat,lon will be written * to file, but all the elements in the cluster as well. This is mainly for * visualization and debugging purposes only. */ public void writeClusteringToFile(Map<Long, Cluster> clusters, String outputfile, boolean fullWrite) { try { PrintWriter file = new PrintWriter(new FileWriter(outputfile)); for (Cluster c : clusters.values()) { if (fullWrite) { file.println(c.toString()); } else { // Write the center data to file Point center = c.getCenter(); file.println(center.getId() + "," + center.getLatitude() + "," + center.getLongitude()); } } file.close(); } catch (IOException e) { System.err.println("Error writing clustering to file: " + e.getMessage()); System.exit(-1); } } /** * Helper method that facilitates writing a given clustering to file. * @param clusters The resulting clusters from the algorithm * @param outputfile The name of the file to write the clusters to. */ public void writeClusteringToFile(List<Cluster> clusters, String outputfile) { writeClusteringToFile(clusters, outputfile, false); } /** * Helper method that facilitates writing a given clustering to file. * @param clusters The resulting clusters from the algorithm * @param outputfile The name of the file to write the clusters to. * @param fullWrite If set to true, not only the ID,lat,lon will be written * to file, but all the elements in the cluster as well. This is mainly for * visualization and debugging purposes only. */ public void writeClusteringToFile(List<Cluster> clusters, String outputfile, boolean fullWrite) { try { PrintWriter file = new PrintWriter(new FileWriter(outputfile)); for (Cluster c : clusters) { if (fullWrite) { file.println(c.toString()); } else { // Write the center data to file Point center = c.getCenter(); file.println(center.getId() + "," + center.getLatitude() + "," + center.getLongitude()); } } file.close(); } catch (IOException e) { System.err.println("Error writing clustering to file: " + e.getMessage()); System.exit(-1); } } }
[ "oliviervanlaere@gmail.com" ]
oliviervanlaere@gmail.com
0eaf47995906b6960fc970dc428ab1f76b09b69a
3ac95358eb7d5cc12068f647d810ed3c4f2427df
/src/Game.java
66234e3ccc645791fb60d2215a9f3c2962268a86
[]
no_license
nazanin97/battleship-game
3f275ffa4d98e488241f0690d34d3f860836f0da
53f30840312a45a991c8e7946fcab39a4f6795e8
refs/heads/master
2020-05-14T19:29:05.399367
2019-04-17T16:39:20
2019-04-17T16:39:20
181,930,216
0
0
null
null
null
null
UTF-8
Java
false
false
5,893
java
import java.util.Random; import java.util.Scanner; public class Game { private Board firstPlayer; private Board secondPlayer; /** * * @param number is play mode (one or two) */ public Game(int number){ firstPlayer = new Board("firstPlayer"); if (number == 1) secondPlayer = new Board("computer"); else secondPlayer = new Board("secondPlayer"); } /** * * @param player * @return false if the input choice is not correct */ public boolean chooseArrow(Board player){ Scanner input = new Scanner(System.in); System.out.println(player.name + " choose your arrow:"); System.out.println("1-regular\n2-irregular"); int inputNum = input.nextInt(); if (inputNum == 2){ player.arrow = 2; } else if (inputNum != 1){ System.out.println("Enter correct number!"); return false; } return true; } /** * * @param playerNumber is number of players (one or two) */ public void start(int playerNumber) { if(!chooseArrow(firstPlayer)){ return; } System.out.println("**PLACE YOUR SHIPS**\nfirst player:"); Board.drawBoard(firstPlayer.battleShips); firstPlayer.drawShips(); if (playerNumber == 2){ if (!chooseArrow(secondPlayer)){ return; } System.out.println("**PLACE YOUR SHIPS**\nsecond player:"); Board.drawBoard(secondPlayer.battleShips); } secondPlayer.drawShips(); //start the game with first player System.out.println("**GAME STARTS**"); start(firstPlayer); } /** * * @param currentPlayer */ public void start(Board currentPlayer){ Board another; Scanner stream = new Scanner(System.in); if (currentPlayer.name.equals("firstPlayer")){ another = secondPlayer; } else another = firstPlayer; System.out.println("\n" + currentPlayer.name + " turn:"); if (!currentPlayer.name.equals("computer")){ Board.drawBoard(currentPlayer.battleShips); System.out.println("your grid\n"); Board.drawBoard(currentPlayer.checkedAll); System.out.println("opponent's grid\n"); } //for input numbers(coordinate) int num1; int num2; //if the player wasn't computer get coordinate from user if (!currentPlayer.name.equals("computer")){ System.out.print("x: "); num1 = stream.nextInt(); System.out.print("y: "); num2 = stream.nextInt(); } //if player was computer generate random coordinate else { Random random = new Random(); num1 = random.nextInt(10); num2 = random.nextInt(10); } //you can continue if the coordinate is acceptable if (num1<=9 && num1 >=0 && num2<=9 && num2 >=0) { Point newPoint = new Point(num1, num2); //if the arrow type was irregular choose a point from point's neighbors if (currentPlayer.arrow == 2){ newPoint = Point.neighbor(num1, num2); } //check if the coordinate hasn't been chosen yet, if it was, get new coordinate! boolean chosenBefore = false; for (Point point:currentPlayer.checkedAll) { if ((point.getX() == newPoint.getX()) && (point.getY() == newPoint.getY())) chosenBefore = true; } if (chosenBefore) start(currentPlayer); else { for (Point point : another.battleShips) { //if current player chose correct coordinate if ((point.getX() == newPoint.getX()) && (point.getY() == newPoint.getY())) { newPoint.setSign('&'); point.setSign('#'); currentPlayer.checkedTrue.add(newPoint); currentPlayer.checkedAll.add(newPoint); if (!currentPlayer.name.equals("computer")){ Board.drawBoard(currentPlayer.battleShips); System.out.println("your grid\n"); } Board.drawBoard(currentPlayer.checkedAll); System.out.println("opponent's grid\n\n"); if (currentPlayer.checkedTrue.size() == another.battleShips.size()) { System.out.println("\u001B[31m" + currentPlayer.name + " Won!"); return; } //get coordinate again for his prize! :) start(currentPlayer); } } //if current player chose wrong coordinate if (newPoint.getSign() != '&') { newPoint.setSign('X'); currentPlayer.checkedAll.add(newPoint); if (!currentPlayer.name.equals("computer")){ Board.drawBoard(currentPlayer.battleShips); System.out.println("your grid\n"); } Board.drawBoard(currentPlayer.checkedAll); System.out.println("opponent's grid\n\n"); //start with another player start(another); } } } //if the coordinate wasn't acceptable, current player should enter another coordinate else { System.out.println("wrong choice!"); start(currentPlayer); } } }
[ "n.akhtarian@gmail.com" ]
n.akhtarian@gmail.com
6abb5a2a614aed9bc8a6b1609b3775e0a4dfe117
a46346b5fb8fa052fef87edbed1b3e49e4af8695
/app/src/main/java/com/walkity/apps/journalapp/data/DiaryDao.java
d757e85d6eeb5ed927d280a9baabd36dfe0103b9
[]
no_license
alkaj/alcwithgoogle7daysofcode
e5322e71b90df731e2998dd8662d687f875e71cb
7863f51e085f5a8dc17a4508ec48778ec9e248f5
refs/heads/master
2020-03-22T02:23:20.984716
2018-07-13T18:10:28
2018-07-13T18:10:28
139,367,599
2
0
null
null
null
null
UTF-8
Java
false
false
1,071
java
package com.walkity.apps.journalapp.data; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.ArrayList; import java.util.List; /** * Created by alkaj on 6/30/18. * Class to access our Diary entries */ @Dao public interface DiaryDao { @Query("select * from diaries order by date desc") LiveData<List<DiaryEntry>> getEntries(); //a reactive entry @Query("select * from diaries where id = :id") LiveData<DiaryEntry> getEntry(int id); //and a non reactive one... @Query("select * from diaries where id = :id") DiaryEntry getNonReactiveEntry(int id); @Insert void addEntry(DiaryEntry entry); @Update(onConflict = OnConflictStrategy.REPLACE) void updateEntry(DiaryEntry entry); @Delete void deleteEntry(DiaryEntry entry); }
[ "alkaj09@gmail.com" ]
alkaj09@gmail.com
b54ce709f1c521d45ed9cad29698f1ed1cd3df3f
a0c27e888916448b9e379676dc5254e44645dced
/app/src/main/java/com/multi/myschoolshop/shop/ImageAdapter.java
5ea798f1720f0a58e89560d873b1d1c8250e2150
[]
no_license
mdmuneerhasan/MySchoolShop
0ade0737923e6cf559a2ba562cc85f808ed0b5b6
c46cd2affa71a8f195b6e8cf04da2f0b05599aaa
refs/heads/master
2020-06-28T13:17:22.982357
2019-08-09T20:33:26
2019-08-09T20:33:26
200,244,129
0
0
null
null
null
null
UTF-8
Java
false
false
1,321
java
package com.multi.myschoolshop.shop; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.multi.myschoolshop.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.Holder> { ArrayList<String> list; Context context; public ImageAdapter(ArrayList<String> list) { this.list = list; } @NonNull @Override public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { context=viewGroup.getContext(); return new Holder(LayoutInflater.from(context).inflate(R.layout.item_row_image,viewGroup,false)); } @Override public void onBindViewHolder(@NonNull Holder holder, int i) { Picasso.get().load(list.get(i)).into(holder.imageView); } @Override public int getItemCount() { return list.size(); } class Holder extends RecyclerView.ViewHolder{ ImageView imageView; public Holder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.imageView); } } }
[ "md.muneerhasan@gmail.com" ]
md.muneerhasan@gmail.com
31e63ecea9e2669f85ebdcfce4b162a261a63cd8
c29d2c95d3d8f7fbaa6d0d0b051d2e36174457d3
/ServletApiSpringMvc/src/main/java/mvc/service/CarService.java
c28371b397c2a33e8a1517845dae1143ee04e4e9
[]
no_license
egoparin/javaschool
929a755521d1086b2d9585fb476f40e5199b0341
ea43cc0ab6a449329c83f5185dd64ceaa50253ba
refs/heads/master
2023-02-03T05:07:19.455115
2020-12-24T14:59:34
2020-12-24T14:59:34
322,314,582
0
0
null
null
null
null
UTF-8
Java
false
false
794
java
package mvc.service; import java.util.List; import mvc.domain.Car; import mvc.repository.CarStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author egor.oparin@x5.ru */ @Service public class CarService { @Autowired CarStore carStore; public void register(Car car){ carStore.addCar(car); } public void unRegister(Car car){ carStore.deleteCar(car); } public Car get (String number){ for (Car car : carStore.getCarStore()) { if(number.equals(car.getNumber())){ return car; } } throw new RuntimeException("Car not found"); } public List<Car> getAll(){ return carStore.getCarStore(); } }
[ "egor.oparin@x5.ru" ]
egor.oparin@x5.ru
a4a2ad2762748cc807cb727f0289f4753fca8cb6
3241408996dbb2116991489405043768fd930993
/Q2/2.3.4/ElkTarotBot.java
509f870aff8bf4cce651cac42cc5dcf23d36d60a
[]
no_license
PatheticMustan/Computer-Science-AP-Files
fd82620ac074487e81917a411624a67602aa9de7
44f5874385c4371f75dd5edcdb76523dc2f3b5ab
refs/heads/master
2023-07-04T04:39:16.564049
2021-08-10T14:59:44
2021-08-10T14:59:44
295,856,162
0
1
null
null
null
null
UTF-8
Java
false
false
3,674
java
import java.lang.Math; import java.util.*; public class ElkTarotBot implements RPSLSBot { int turn; int diagnosticRounds; int[] opponentMoves; int[] tarotMoves; boolean[] wins; int strategy; public String getBotName() { return "ElkTarotBot"; } public String getCoderName() { return "Kevin W"; } public ElkTarotBot() { reset(); } public void reset() { turn = -1; diagnosticRounds = 50; tarotMoves = new int[10000]; opponentMoves = new int[10000]; wins = new boolean[diagnosticRounds]; strategy = -1; } // 50 turns of diagnostics, try to trick the opponent into revealing their method // rpsls, we beat them if ourMove == (n + 1) % 5 || ourMove == (n + 3) % 5 public void opponentsLastMove(int move) { opponentMoves[turn] = move; } public int getMove() { turn++; if (turn < diagnosticRounds) { // cycle through to see if the opponent responds if (turn <= 30) return move(turn); // constant spock to see if they use opponent's last move return 4; } // counter them! switch (strategy) { // s0 - beat opponent's last move case 0: return move(opponentMoves[turn-1]+1); case 1: System.out.println((turn%5) + " --> " + opponentMoves[turn]); return move(turn); } // otherwise, just do random return move((int)(Math.random() * 5)); } public int move(int m) { tarotMoves[turn] = m % 5; if (turn == 50) pickStrategy(); return tarotMoves[turn]; } public void pickStrategy() { boolean talk = true; int[] pm = Arrays.copyOfRange(tarotMoves, 0, diagnosticRounds); int[] om = Arrays.copyOfRange(opponentMoves, 0, diagnosticRounds); // track wins int[] win = new int[diagnosticRounds]; for (int i=0; i<diagnosticRounds; i++) { win[i] = cmp(pm[i], om[i]); } // constant // get unique moves, if there's only one unique move, it's constant Set<Integer> unique = new HashSet<Integer>(); for (int i=0; i<diagnosticRounds; i++) { unique.add(om[i]); } if (unique.size() == 1) { if (talk) System.out.println("Constant"); strategy = 0; return; } // copybot int[] trm = Arrays.copyOfRange(tarotMoves, 0, 20); int[] opm = Arrays.copyOfRange(opponentMoves, 1, 21); System.out.println(Arrays.toString(trm)); System.out.println(Arrays.toString(opm)); if (Arrays.equals(trm, opm)) { if (talk) System.out.println("Copybot"); strategy = 1; return; } // repeat until loss // counterbot // otherwise do repeat until loss bot System.out.println(); } public int cmp(int player1move, int player2move) { if (player1move < 0 || player1move > 4 || player2move < 0 || player2move > 4) throw new IllegalArgumentException("Illegal move: " + player1move + ", " + player2move); int[][] resultMatrix = { {0, 2, 1, 1, 2}, // +1, +4 {1, 0, 2, 2, 1}, // +1, +2 {2, 1, 0, 1, 2}, // +2, +3 {2, 1, 2, 0, 1}, // +2, +4 {1, 2, 1, 2, 0}}; //+2, +4 return resultMatrix[player1move][player2move]; } }
[ "patheticmustan@gmail.com" ]
patheticmustan@gmail.com
5a34fed664db36011707bf0e95818729ac890db8
74e4721a6652e1622f5d53f43e03af63acbc0ef3
/src/groupbase/thn/web/buyandsell/entry/UsersEntry.java
9cd7ce3917c1c1da4fdf8bd4bd99ca7f3f1b2818
[]
no_license
truonghieunghia/Web.BuyAndSell
69467bf7ffb4385f679fd5c940055f5b8d806424
b44c178784037f5f0bf189725b90207a7f65d3dc
refs/heads/master
2020-05-25T09:29:35.399133
2015-08-10T15:33:54
2015-08-10T15:33:54
40,426,799
0
0
null
null
null
null
UTF-8
Java
false
false
2,253
java
package groupbase.thn.web.buyandsell.entry; import java.io.Serializable; import groupbase.thn.web.libs.ColumnNameAnnotation; import groupbase.thn.web.libs.EntryAnnotation; @EntryAnnotation(TableName = "Users") public class UsersEntry implements Serializable { private static final long serialVersionUID = 1L; public static String UserID_Field = "UserID"; public static String Email_Field = "Email"; public static String UserName_Field = "UserName"; public static String FullName_Field = "FullName"; public static String Sex_Field = "Sex"; public static String Birthday_Field = "Birthday"; public static String Password_Field = "Password"; @ColumnNameAnnotation(ColumnName = "UserID", FieldType = Long.class, isPrimary = true, MaxLength = 19) private long UserID; @ColumnNameAnnotation(ColumnName = "Email", FieldType = String.class, MaxLength = 100) private String Email; @ColumnNameAnnotation(ColumnName = "UserName", FieldType = String.class, MaxLength = 45) private String UserName; @ColumnNameAnnotation(ColumnName = "FullName", FieldType = String.class, MaxLength = 45) private String FullName; @ColumnNameAnnotation(ColumnName = "Sex", FieldType = Integer.class, MaxLength = 1) private int Sex; @ColumnNameAnnotation(ColumnName = "Birthday", FieldType = String.class, MaxLength = 8) private String Birthday; @ColumnNameAnnotation(ColumnName = "Password", FieldType = String.class) private String Password; public long getUserID() { return UserID; } public void setUserID(long userID) { UserID = userID; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getFullName() { return FullName; } public void setFullName(String fullName) { FullName = fullName; } public int getSex() { return Sex; } public void setSex(int sex) { Sex = sex; } public String getBirthday() { return Birthday; } public void setBirthday(String birthday) { Birthday = birthday; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } }
[ "truonghieunghia.code@gmail.com" ]
truonghieunghia.code@gmail.com
6692d420072c914d1c7e9690edd20c0683828c95
67d958fd560d7a1fa6540325d6bf15d90a779b7f
/micro-core/src/main/java/org/nzdis/micro/messaging/network/netty/NettyNetworkConnector.java
9b68213fa9432c1d255ee6cd3a3000ce6891578b
[]
no_license
aragornAGH/micro-master
29cb4f2b7d7e87e6cf943a0cff33fc45573d09d6
9f545cf06a6bfab3a3f0817f1537aaed4ddda6c6
refs/heads/master
2021-01-22T21:18:15.908207
2017-06-28T18:44:29
2017-06-28T18:44:29
85,413,020
0
1
null
null
null
null
UTF-8
Java
false
false
8,320
java
/******************************************************************************* * - Micro-Agent Platform, core of the Otago Agent Platform (OPAL), * developed at the Information Science Department, * University of Otago, Dunedin, New Zealand. * * This file is part of the aforementioned software. * * is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Micro-Agents Framework. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.nzdis.micro.messaging.network.netty; import org.nzdis.micro.MTConnector; import org.nzdis.micro.MicroMessage; import org.nzdis.micro.constants.SerializationTypes; import org.nzdis.micro.events.LocalPlatformNetworkStartFailedEvent; import org.nzdis.micro.events.LocalPlatformNetworkStartedEvent; import org.nzdis.micro.messaging.MTRuntime; import org.nzdis.micro.messaging.message.Message; import org.nzdis.micro.messaging.network.*; import org.nzdis.micro.messaging.network.netty.object.ObjectReader; import org.nzdis.micro.messaging.network.netty.object.ObjectWriter; import org.nzdis.micro.messaging.network.netty.string.StringReader; import org.nzdis.micro.messaging.network.netty.string.StringWriter; /** * NettyNetworkConnector manages the Netty-based network transport for the micro-agent * platform. * * @author <a href="cfrantz@infoscience.otago.ac.nz">Christopher Frantz</a> * @version $Revision: 1.0 $ $Date: 2010/11/14 00:00:00 $ * */ public class NettyNetworkConnector extends AbstractNetworkReader implements NetworkConnectorInterface { private final String nettyPrefix = new StringBuilder(MTRuntime.getPlatformPrefix()).append("Network Transport: ").toString(); //private static boolean debug = false; private static String serialization = SerializationTypes.XML; private AbstractReader reader = null; private AbstractWriter writer = null; private HeartbeatAgent heartbeat; private static boolean networkStarted = false; //indicates if network is currently shutting down private static boolean networkShuttingDown = false; //if something goes wrong, a shutdown - immediatey after start - can be requested private static boolean shutdownImmediatelyAfterStart = false; public MonitoredConnection connections = new MonitoredConnection(); private int sendError = 0; //used to encapsulate the target node for a message sent within the message public static final String TARGET_NODE_KEYWORD = MTRuntime.nodeKeyword; public static final String TARGET_PORT_KEYWORD = "TARGET_PORT_KEYWORD"; //indicates message field holding local connection address (for Netty Channel) public static final String SENDER_LOCAL_ADDRESS = "SENDER_LOCAL_ADDRESS"; NettyNetworkConnector(){ } private static class InstanceHolder { public static NettyNetworkConnector instance = new NettyNetworkConnector(); } public static NettyNetworkConnector getInstance() { return InstanceHolder.instance; } public String getSerialization(){ return serialization; } @Override public void setSerialization(String serial){ serialization = serial; } @Override public String getPrefix(){ return nettyPrefix; } @Override public void sendMessage(Message message, String host, int port){ if(!networkStarted){ startNetwork(); } if(writer != null && writer.isAlive() && !networkShuttingDown){ writer.sendMessage(message, host, port); } } @Override public synchronized void startNetwork(){ if(!networkStarted && !networkShuttingDown){ if(serialization.equals(SerializationTypes.JAVA) || serialization.equals(SerializationTypes.JAVA_COMPATIBILITY)){ //enforce compatibility serialization if running on Android if(System.getProperty("java.vm.name").equals("Dalvik") || serialization.equals(SerializationTypes.JAVA_COMPATIBILITY)){ ObjectWriter.compatibilityMode = true; } if(writer == null){ writer = new ObjectWriter(); writer.start(); } if(reader == null){ reader = new ObjectReader(); } } if(serialization.equals(SerializationTypes.XML) || serialization.equals(SerializationTypes.JSON)){ //enforce XML serialization if running on Android if(System.getProperty("java.vm.name").equals("Dalvik") && serialization.equals(SerializationTypes.XML)){ serialization = SerializationTypes.XML; System.out.println(new StringBuilder(nettyPrefix).append("Enforced serialization type ") .append(serialization).append(" as JSON for this platform is not yet available on Android.")); } if(writer == null){ writer = new StringWriter(); if(writer.initialized){ writer.start(); } } if(reader == null){ reader = new StringReader(); } } if(writer == null || reader == null){ System.err.println(new StringBuilder(nettyPrefix).append("Please select a valid serialization type (Current setting: ") .append(serialization).append(").\n").append("Network start will be aborted.").toString()); } if(writer != null && reader != null && writer.initialized && reader.initialized){ networkStarted = true; //Heartbeat agent will be started once reader and writer are available heartbeat = new HeartbeatAgent(); heartbeat.setHeartbeatRate(MTRuntime.getHeartbeatFrequency()); if(MTRuntime.isHeartbeatActivated()){ //but only if explicitly activated it will be actively checking connections on the local platform heartbeat.start(); } MTConnector.send(new MicroMessage(new LocalPlatformNetworkStartedEvent(MTConnector.platformProcess))); //System.out.println(new StringBuilder(nettyPrefix).append("Network started.")); //if(debug){ System.out.println(new StringBuilder(nettyPrefix).append("Netty network started on port " + getPort() + " with " + serialization + " serialization.")); //} } else { MTConnector.send(new MicroMessage(new LocalPlatformNetworkStartFailedEvent(MTConnector.platformProcess))); System.err.println(new StringBuilder(nettyPrefix).append("Netty network support start with " + serialization + " serialization failed.")); shutdownImmediatelyAfterStart = true; shutdown(); } } else { System.out.println(new StringBuilder(nettyPrefix).append("Requested network start although already running.")); } } @Override public boolean networkStarted(){ return networkStarted && !networkShuttingDown; } public void setSendError(Message message) { sendError++; System.err.println(new StringBuilder(nettyPrefix).append("Error when sending message to node ").append(message.get(MTRuntime.nodeKeyword)) .append("! Message: ").append(message.toString())); } public int getNumberOfSendErrors(){ return sendError; } @Override public Integer getPort() { return MTRuntime.getTcpPort(); } @Override public void shutdown() { if((networkStarted || shutdownImmediatelyAfterStart) && !networkShuttingDown){ networkShuttingDown = true; //Heartbeat agent shutdown if(heartbeat != null){ heartbeat.shutdown(); heartbeat = null; } //Network writer shutdown System.out.println(new StringBuilder(nettyPrefix).append("Shutting down writer ...")); if(writer != null){ writer.shutdown(); writer = null; } //Network reader shutdown System.out.println(new StringBuilder(nettyPrefix).append("Shutting down reader ...")); if(reader != null){ reader.shutdown(); reader = null; } System.out.println(new StringBuilder(nettyPrefix).append("Network has been shut down.")); networkStarted = false; shutdownImmediatelyAfterStart = false; networkShuttingDown = false; } /*else { System.err.println(new StringBuilder(nettyPrefix).append("Network will not be shut down as not fully started.")); }*/ } }
[ "jkolodzi@student.agh.edu.pl" ]
jkolodzi@student.agh.edu.pl
2bfadf159dc7d9d2d7de0adfb3c5439a6ee5bc37
1fcab67675ded2e5d095ec23114606c415abdc75
/Peer4U/app/src/main/java/com/bignerdranch/android/peer4u/ProjectFragment.java
f61a920aa49b05e7b63895cb485d3892160dfbc9
[]
no_license
Shehabov/Peer4u-Mobile-app
879d935edd4cddea2ccdee55ada82242c4ed4fa9
c20c9195604a0c174ee4fd3012ead97e3b1a305b
refs/heads/master
2023-04-11T23:23:13.064160
2021-05-08T17:09:11
2021-05-08T17:09:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,921
java
package com.bignerdranch.android.peer4u; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class ProjectFragment extends Fragment { private static final String ARG_PROJECT_ID = "project_id"; private static final String ARG_SUBJECT_ID = "subject_id"; private static final String ARG_STUDENT_ID = "student_id"; private static final int REQUEST_JOINGROUP = 1; private static final int REQUEST_CREATEGROUP = 2; private static final String DIALOG_LEAVEGROUP = "DialogProject"; private static final int REQUEST_LEAVEGROUP = 0; private Project mProject; private TextView mStudentNameField; private TextView mStudentUniversityField; private ImageView mPhotoView; private TextView mProjectNameField; private TextView mDetailsField; private TextView mGroupMembersField; private Button mCreateButton; private Button mJoinButton; private Student mStudent; private File mPhotoFile; private Group mGroup; private Subject mSubject; private Button mInviteButton; private Button mLeaveButton; public static ProjectFragment newInstance(UUID projectId, UUID studentId){ Bundle args = new Bundle(); args.putSerializable(ARG_PROJECT_ID, projectId); args.putSerializable(ARG_STUDENT_ID, studentId); ProjectFragment fragment = new ProjectFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UUID projectId = (UUID) getArguments().getSerializable(ARG_PROJECT_ID); UUID studentId = (UUID) getArguments().getSerializable(ARG_STUDENT_ID); mStudent = StudentLab.get(getActivity()).getStudent(studentId); mProject = SubjectLab.get(getActivity()).getProject(projectId); mSubject = SubjectLab.get(getActivity()).getSubject(mProject.getSubjectUUID()); mGroup = StudentLab.get(getActivity()).getGroupByStudentProject(studentId, projectId); } @Override public void onPause(){ super.onPause(); SubjectLab.get(getActivity()).updateProject(mProject); updateUI(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v = inflater.inflate(R.layout.fragment_project, container, false); mPhotoView = (ImageView) v.findViewById(R.id.student_profilepic); mPhotoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = SetupActivity.newIntent(getActivity(), mStudent.getId()); startActivity(intent); } }); updatePhotoView(); mStudentNameField = (TextView) v.findViewById(R.id.student_name); mStudentNameField.setText(mStudent.getFirstName()); mStudentNameField.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = SetupActivity.newIntent(getActivity(), mStudent.getId()); startActivity(intent); } }); mStudentUniversityField = (TextView) v.findViewById(R.id.student_university); mStudentUniversityField.setText(mStudent.getUniveristy()); mStudentUniversityField.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = SetupActivity.newIntent(getActivity(), mStudent.getId()); startActivity(intent); } }); mProjectNameField = (TextView) v.findViewById(R.id.project_name); mProjectNameField.setText(mProject.getAssignmentName()); mDetailsField = (TextView) v.findViewById(R.id.project_details); mDetailsField.setText(mProject.getAssignmentDetails()); mCreateButton = (Button) v.findViewById(R.id.create_group_button); if(groupExist()){ mCreateButton.setVisibility(View.GONE); } else { mCreateButton.setVisibility(View.VISIBLE); } mCreateButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ //start activity to create group Intent intent = NewGroupActivity.newIntent(getActivity(), mStudent.getId(), mProject.getId(), mSubject.getId()); //startActivity(intent); startActivity(intent); } }); mJoinButton = (Button) v.findViewById(R.id.join_group_button); if(groupExist()){ mJoinButton.setVisibility(View.GONE); } else { mJoinButton.setVisibility(View.VISIBLE); } mJoinButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ //start activity to grouplistfragment Intent intent = GroupListActivity.newIntent(getActivity(), mStudent.getId(), mProject.getId()); //startActivity(intent); startActivity(intent); } }); mInviteButton = (Button) v.findViewById(R.id.invite_member_button); if (groupExist() && isLeader()){ mInviteButton.setVisibility(View.VISIBLE); } else { mInviteButton.setVisibility(View.GONE); } mInviteButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ //start activity to studentlistfragment Intent intent = StudentListActivity.newIntent(getActivity(), mStudent.getId(), mProject.getId(), mGroup.getId()); //startActivity(intent); startActivity(intent); } }); mLeaveButton = (Button) v.findViewById(R.id.leave_group_button); if (groupExist() && !isLeader()){ mLeaveButton.setVisibility(View.VISIBLE); } else { mLeaveButton.setVisibility(View.GONE); } mLeaveButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ //start activity to leavegroupfragment FragmentManager manager = getFragmentManager(); LeaveGroupFragment dialog = LeaveGroupFragment.newInstance(mProject.getId(), mStudent.getId()); dialog.setTargetFragment(ProjectFragment.this, REQUEST_LEAVEGROUP); dialog.show(manager, DIALOG_LEAVEGROUP); } }); mGroupMembersField = (TextView) v.findViewById(R.id.group_members); updateMembers(); return v; } //end of onCreateView @Override public void onResume(){ super.onResume(); updateUI(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ if (resultCode != Activity.RESULT_OK){ return; } if (requestCode == REQUEST_LEAVEGROUP){ updateUI(); } else if (requestCode == REQUEST_CREATEGROUP){ } } private void updatePhotoView(){ try{ mPhotoFile = null; mPhotoFile = new File(getActivity().getFilesDir(), mStudent.getPhotoFilename());; } finally { if (mPhotoFile == null || !mPhotoFile.exists()){ mPhotoView.setImageDrawable(null); } else { Bitmap bitmap = PictureUtils.getScaledBitmap( mPhotoFile.getPath(), getActivity()); mPhotoView.setImageBitmap(bitmap); } } } private void updateMembers(){ StudentLab studentLab = StudentLab.get(getActivity()); if (mGroup == null){ mGroupMembersField.setText(R.string.no_group); } else { if (mGroup.getMemberList() == null){ mGroupMembersField.setText(getString(R.string.no_group_members, mStudent.getFirstName())); } else { mGroupMembersField.setText(getString(R.string.group_members_names, studentLab.getStudent(mGroup.getLeaderId()).getFirstName(), mGroup.getMemberNames())); } } } private void updateUI(){ if(groupExist()){ mCreateButton.setVisibility(View.GONE); mJoinButton.setVisibility(View.GONE); if (!isLeader()){ mLeaveButton.setVisibility(View.VISIBLE); mInviteButton.setVisibility(View.GONE); } else { mLeaveButton.setVisibility(View.GONE); mInviteButton.setVisibility(View.VISIBLE); } } else { mCreateButton.setVisibility(View.VISIBLE); mJoinButton.setVisibility(View.VISIBLE); mLeaveButton.setVisibility(View.GONE); } updateMembers(); } private boolean groupExist(){ if (mGroup == null){ return false; } else { return true; } } private boolean isLeader(){ if (mGroup.getLeaderId().equals(mStudent.getId())){ return true; } else { return false; } } }
[ "44311810+limpeihsin15@users.noreply.github.com" ]
44311810+limpeihsin15@users.noreply.github.com
f5829e8045d1f8220b422a001134a6e5a1b7b065
9738f8f1909bb37815228a575edc3b4908d12fcf
/src/com/javaex/Book02/BookDao.java
99518114fddb587e1ffa93c71946c20f528a1b8b
[]
no_license
kimwoojin1235/jdbc
3e257771f1e1b847ca474972112ab824f49d600f
8670f9d08105c5d23e0eb8f6d2c1b784f6ac7b10
refs/heads/master
2023-02-07T22:40:07.733688
2020-12-30T03:55:41
2020-12-30T03:55:41
324,950,915
0
0
null
null
null
null
UTF-8
Java
false
false
6,264
java
package com.javaex.Book02; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BookDao { // 0. import java.sql.*; private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; //db์ •๋ณด private String driver = "oracle.jdbc.driver.OracleDriver"; private String url = "jdbc:oracle:thin:@localhost:1521:xe"; private String id = "webdb"; private String pw = "webdb"; private void getConnection() { try { // 1. JDBC ๋“œ๋ผ์ด๋ฒ„ (Oracle) ๋กœ๋”ฉ Class.forName(driver); // 2. Connection ์–ป์–ด์˜ค๊ธฐ conn = DriverManager.getConnection(url, id, pw); System.out.println("์ ‘์† ์„ฑ๊ณต"); } catch (ClassNotFoundException e) { System.out.println("error: ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ ์‹คํŒจ - " + e); } catch (SQLException e) { System.out.println("error:" + e); } } private void close() { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { System.out.println("error:" + e); } } // ์ฑ… ์ €์žฅ public int bookInsert(BookVo bVo) { int count = 0; getConnection(); try { // 3. SQL๋ฌธ ์ค€๋น„ / ๋ฐ”์ธ๋”ฉ / ์‹คํ–‰ // INSERT INTO book VALUES(SEQ_BOOK_ID.nextval, 'ํ•ด๋ฆฌํฌํ„ฐ์™€ ๋งˆ๋ฒ•์‚ฌ์˜ ๋Œ', '๋ฌธํ•™์ˆ˜์ฒฉ', // '14/12/18', 7); String query = "INSERT INTO book VALUES(SEQ_BOOK_ID.nextval, ?, ?, ?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, bVo.getTitle()); pstmt.setString(2, bVo.getPubs()); pstmt.setString(3, bVo.getPub_date()); pstmt.setInt(4, bVo.getAuthor_id()); System.out.println(query); count = pstmt.executeUpdate(); // insert // rs = pstmt.executeQuery(); // select // 4.๊ฒฐ๊ณผ์ฒ˜๋ฆฌ System.out.println("[DAO]: " + count + "๊ฑด์ด ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); } catch (SQLException e) { System.out.println("error:" + e); } close(); return count; } // ๋ฆฌ์ŠคํŠธ public List<BookVo> getBookList() { List<BookVo> bList = new ArrayList<BookVo>(); getConnection(); try { // 3. SQL๋ฌธ ์ค€๋น„ / ๋ฐ”์ธ๋”ฉ / ์‹คํ–‰ String query = ""; query += " select book_id, "; query += " title, "; query += " pubs, "; query += " pub_date, "; query += " author_id "; query += " from book "; pstmt = conn.prepareStatement(query); rs = pstmt.executeQuery();// select // 4.๊ฒฐ๊ณผ์ฒ˜๋ฆฌ while (rs.next()) { int book_id = rs.getInt("book_id");// int aId = rs.getInt(1); String title = rs.getString("title");// String aName = rs.getInt(2); String pubs = rs.getString("pubs");// String aDesc = rs.getInt(3); String pub_date = rs.getString("pub_date");// String aDesc = rs.getInt(3); int author_id = rs.getInt("author_id");// String aDesc = rs.getInt(3); BookVo bvo01 = new BookVo(book_id, title, pubs, pub_date, author_id); bList.add(bvo01); } } catch (SQLException e) { System.out.println("error:" + e); }close(); return bList; } // ๋ฆฌ์ŠคํŠธ ์ „์ฒด public List<BookVo> getBookListAll() { List<BookVo> bAllList = new ArrayList<BookVo>(); getConnection(); try { // 3. SQL๋ฌธ ์ค€๋น„ / ๋ฐ”์ธ๋”ฉ / ์‹คํ–‰ String query = ""; query += " select b.book_id, "; query += " b.title, "; query += " b.pubs, "; query += " TO_CHAR(b.pub_date, 'yyyy-mm-dd') pub_date, ";// TO_CHAR(b.pub_date, 'yyyy-mm-dd') as pub_date; query += " a.author_id, "; query += " a.author_name, "; query += " a.author_desc "; query += " from book b, author a "; query += " where b.author_id = a.author_id "; query += " order by b.book_id asc "; pstmt = conn.prepareStatement(query); rs = pstmt.executeQuery();// select // 4.๊ฒฐ๊ณผ์ฒ˜๋ฆฌ while (rs.next()) { int book_id = rs.getInt("book_id");// int bId = rs.getInt(book_id); String title = rs.getString("title");// String bTitle = rs.getInt(title); String pubs = rs.getString("pubs");// String bPubs = rs.getInt(pubs); String pub_date = rs.getString("pub_date");// String bPubD = rs.getInt(pub_date); int author_id = rs.getInt("author_id");// int aId = rs.getInt(a.author_id); String author_name = rs.getString("author_name");// String aName = rs.getInt(author_name); String author_desc = rs.getString("author_desc");// String aDesc = rs.getInt(author_desc); BookVo bvo02 = new BookVo(book_id, title, pubs, pub_date, author_id, author_name, author_desc); bAllList.add(bvo02); } }catch (SQLException e) { System.out.println("error:" + e); } close(); return bAllList; } // ์ฑ…์ •๋ณด ์ˆ˜์ • public int bookUpdate(BookVo bVo) { getConnection(); int count = 0; try { // 3. SQL๋ฌธ ์ค€๋น„ / ๋ฐ”์ธ๋”ฉ / ์‹คํ–‰ String query = ""; query += " update book "; query += " SET title = ? "; query += " WHERE book_id = ? "; pstmt = conn.prepareStatement(query); pstmt.setString(1, bVo.getTitle()); pstmt.setInt(2, bVo.getBook_id()); count = pstmt.executeUpdate(); // update // rs = pstmt.executeQuery(); // select // 4.๊ฒฐ๊ณผ์ฒ˜๋ฆฌ System.out.println("[DAO]: " + count + "๊ฑด์ด ์ˆ˜์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); } catch (SQLException e) { System.out.println("error:" + e); } close(); return count; } // ์ฑ…์‚ญ์ œ public int bookDelete(int book_id) { getConnection(); int count = 0; try { // 3. SQL๋ฌธ ์ค€๋น„ / ๋ฐ”์ธ๋”ฉ / ์‹คํ–‰ // DELETE FROM book WHERE book_id = 5; String query = "DELETE FROM book WHERE book_id = ?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, book_id); count = pstmt.executeUpdate(); // delete // rs = pstmt.executeQuery(); // select // 4.๊ฒฐ๊ณผ์ฒ˜๋ฆฌ System.out.println("[DAO]: " + count + "๊ฑด์ด ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); } catch (SQLException e) { System.out.println("error:" + e); } close(); return count; } }
[ "user@192.168.219.184" ]
user@192.168.219.184
097f8dee0fd93531a68c32ddf161ccd6ed7d48e6
c6b291233258cc23584469d4df15b8fd6a92a8cf
/aula38-datamappers-lazy-load/src/main/java/orm/northwind/OrderDetailsDataMapper.java
10620820315b850369ab4124ab48b73215ea7d12
[]
no_license
isel-leic-mpd/mpd-2012-i41d
c76365d661f4dcd412b49c1b6f964271d80e66d1
da2512a402f8766d10e2c19a03a0e921c2b26706
refs/heads/master
2016-09-16T03:08:30.195334
2012-06-08T13:06:25
2012-06-08T13:06:25
3,601,187
11
1
null
null
null
null
UTF-8
Java
false
false
2,230
java
package orm.northwind; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import javax.inject.Inject; import orm.DataMapperTemplate; import orm.JdbcBinder; import orm.JdbcCmd; import orm.JdbcCmdQuery; import orm.JdbcConverter; import orm.JdbcExecutor; public class OrderDetailsDataMapper extends DataMapperTemplate<Integer, OrderDetails>{ @Inject public OrderDetailsDataMapper(JdbcExecutor exec) { super(exec); } final static String sqlLoadAll = "SELECT orderId, ProductId, unitPrice, quantity, discount FROM [Order Details]"; final static String sqlLoadByProductId = sqlLoadAll + " WHERE ProductId = ?"; final JdbcConverter<Iterable<OrderDetails>> conv = new JdbcConverter<Iterable<OrderDetails>>() { @Override public Iterable<OrderDetails> loadRows(ResultSet rs) throws SQLException { List<OrderDetails> res = new LinkedList<OrderDetails>(); while(rs.next()){ int orderId = rs.getInt(1); OrderDetails o = getEntity(orderId); if(o == null){ o = new OrderDetails( orderId, rs.getInt(2), rs.getDouble(3), rs.getInt(4), rs.getDouble(5)); addEntity(o); } res.add(o); } return res; } }; @Override public JdbcCmd<Iterable<OrderDetails>> cmdLoadAll() { return new JdbcCmdQuery<Iterable<OrderDetails>>( sqlLoadAll, conv); } public Iterable<OrderDetails> loadByProductId(int productId) throws SQLException { JdbcCmdQuery<Iterable<OrderDetails>> cmd = new JdbcCmdQuery<Iterable<OrderDetails>>( sqlLoadByProductId, conv, JdbcBinder.IntBinder); return exec.executeQuery(cmd, productId); } @Override public JdbcCmd<Iterable<OrderDetails>> cmdLoadById() { // TODO Auto-generated method stub return null; } @Override public JdbcCmd<OrderDetails> cmdDelete() { // TODO Auto-generated method stub return null; } @Override public JdbcCmd<OrderDetails> cmdUpdate() { // TODO Auto-generated method stub return null; } @Override public JdbcCmd<Integer> cmdInsert() { // TODO Auto-generated method stub return null; } }
[ "mcarvalho@cc.isel.ipl.pt" ]
mcarvalho@cc.isel.ipl.pt
d21428e6d6b685779dfa7027305ad8d1f800ce58
df533e112e937ee0e8c47ca4f2c91c8088935f47
/Cรณdigo-fonte/EstadoPaciente.java
aaafbb473dacba253941aa7c65e7397279a17836
[]
no_license
EvoSystems-com-br/ResidenciaSW2018_MonitDetecSitEmergenciais
9c148a651b7ed594253bf92151ce1ddad5d871b0
3f41159ce407850ea126fb9292d6e288cb24e687
refs/heads/master
2020-03-26T16:49:02.411600
2018-10-30T20:11:36
2018-10-30T20:11:36
145,124,828
0
0
null
2018-10-30T20:11:38
2018-08-17T13:38:11
C++
UTF-8
Java
false
false
3,975
java
package com.example.gabri.tccv1; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; import java.util.List; import java.util.Locale; public class EstadoPaciente extends AppCompatActivity { String str_telefone, longitude, latitude,localizacao_atual; double d_latitude,d_longitude; private LocationManager locationManager = null; private LocationListener locationListener = null; Geocoder geocoder; List<Address> addresses; @SuppressLint("MissingPermission") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_estado_paciente); SharedPreferences sharedPref = getSharedPreferences("telefone_contato", Context.MODE_PRIVATE); str_telefone = sharedPref.getString("telefone_contato", "sem_cadastro"); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { longitude = " Longitude: " + location.getLongitude(); latitude = " Latitude: " + location.getLatitude(); d_latitude = location.getLatitude(); d_longitude = location.getLongitude(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); geocoder = new Geocoder(this, Locale.ENGLISH); try { addresses = geocoder.getFromLocation(d_latitude,d_longitude,2); if(addresses != null && addresses.size() > 0){ localizacao_atual = addresses.get(0).getAddressLine(0); Toast.makeText(this, "entrei aqui", Toast.LENGTH_LONG).show(); } } catch (IOException e) { e.printStackTrace(); } Button b_sim = (Button) findViewById(R.id.b_sim); // Botรฃo de sim b_sim.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendSMS(str_telefone,"Estou bem"); } }); Button b_nao = (Button) findViewById(R.id.b_nao); // Botรฃo de nรฃo b_nao.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(str_telefone.equals("sem_cadatro")){ Toast.makeText(v.getContext(), "Cadastre um contato de emergรชncia", Toast.LENGTH_LONG).show(); Intent i = new Intent(v.getContext(), EditarContato.class); startActivity(i);// Vai para Activity Editar Contato }else{ sendSMS(str_telefone, "SOCORROOO!!!!" + longitude + latitude + localizacao_atual); } } }); } private void sendSMS(String phoneNumber, String message) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); } }
[ "noreply@github.com" ]
EvoSystems-com-br.noreply@github.com
ec6ed440f54c03bf2d53e0ff5f83ae8b3a154445
a778a2a3ac2130c64bfa28d1823c2f56742495e9
/TestService/src/testXr/Message.java
b7948857a1ba69903eec9228d7965ecec242aaa6
[]
no_license
PhuQuy/FreeLancer
5b25e26d2ea5fc5e4b273211b911cf1cd33dbbe5
ca28d74463130c6e5602b6134c5940954788bdce
refs/heads/master
2016-08-12T14:50:02.043764
2016-03-14T08:53:41
2016-03-14T08:53:41
53,838,373
0
1
null
null
null
null
UTF-8
Java
false
false
1,093
java
package testXr; import java.io.Serializable; import java.util.Collection; import java.util.Date; import flexjson.JSONSerializer; public class Message implements Serializable{ private Integer id; private String nameSender; private String nameReciever; private String content; private Date sent_date; private Boolean isRead; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNameSender() { return nameSender; } public void setNameSender(String nameSender) { this.nameSender = nameSender; } public String getNameReciever() { return nameReciever; } public void setNameReciever(String nameReciever) { this.nameReciever = nameReciever; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getSent_date() { return sent_date; } public void setSent_date(Date sent_date) { this.sent_date = sent_date; } public Boolean getIsRead() { return isRead; } public void setIsRead(Boolean isRead) { this.isRead = isRead; } }
[ "phuquy.uit@gmail.com" ]
phuquy.uit@gmail.com
4be28a7cd1e6275ba36f1fc77b99c8f5f06a3e40
2df43fdd4b6e9fabe4d4dbd7f5440b87160916c5
/UdemyTestNG/src/NukriAutomation/EditPage.java
853afdf29dc4863a632bc5e759a2c1c4df6a7f7e
[]
no_license
pradhanssingh719/Java_Practice_Code
f50bcaeb647e843109787166856c138308f24b93
dfcbc8b8b5ea354fa8891ba8242eea45d3b8d36f
refs/heads/master
2022-11-29T09:06:30.272990
2020-08-13T03:42:59
2020-08-13T03:42:59
287,171,828
0
0
null
null
null
null
UTF-8
Java
false
false
1,873
java
package NukriAutomation; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class EditPage { public static WebElement element = null; public static WebDriver driver; public static WebElement clickOnTitle(WebDriver driver) { element = driver.findElement(By.cssSelector("div[title='Pradhan Singh Meena']")); return element; } public static WebElement ResumeHeadline(WebDriver driver) { // WebDriverWait wait = new WebDriverWait(driver, 5); // element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='lazyResumeHead']//span[@class='edit icon']"))); element = driver.findElement(By.xpath("//div[@id='lazyResumeHead']//span[@class='edit icon']")); return element; } public static WebElement editHeadline(WebDriver driver) { element = driver.findElement(By.id("resumeHeadlineTxt")); return element; } public static WebElement cancelOrSave(WebDriver driver) { element = driver.findElement(By.xpath("//div[@class='action s12']//a[@class='cancelLayer']")); return element; } //screenshot code but not worked so put it into ActionClass.. // public static void screenshot(int length) throws IOException { // String fileName = randomString(length) + ".png"; // String directory = System.getProperty("user.dir") + "/screenshots//"; // File fileSource = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // FileUtils.copyFile(fileSource, new File(directory + fileName)); // } // public static String randomString(int length) { // StringBuffer sb = new StringBuffer(); // String characters = "abcdefghijklmnopqrstuvwxyz1234567890"; // int size = characters.length(); // for(int i = 0; i < length; i++ ) { // int index = (int)(Math.random() * size); // sb.append(characters.charAt(index)); // } // return sb.toString(); // } }
[ "pradhansingh719@gmail.com" ]
pradhansingh719@gmail.com
1f8bd13eaf53bfbec041253824b46d126e24547c
00f5860a0521f9e151b4e35ddd6a546084a450ad
/FoST2.AndreasLengqvist.al223bn/src/exercise5/WordCount2Main.java
5585846b184b7f82482eae492cf298dd55ab95ec
[]
no_license
alengqvist/Foundations-of-Software-Technology
1d41b49e29b4d854a4cf4b5aa8125dcbdf50a752
c73c62c0ed8aaa87180dfb0b59b3f2d7744452a7
refs/heads/master
2021-01-19T00:47:31.754400
2016-06-27T11:00:48
2016-06-27T11:00:48
41,910,071
0
0
null
null
null
null
UTF-8
Java
false
false
977
java
package exercise5; import java.util.Iterator; /** * This class reads from a given file (not as in-parameter) and adds the content * to a HashWordSet and a TreeWordSet. * * @version 1.0 * @author Andreas Lengqvist * Created 15:25, September 25, 2015. */ public class WordCount2Main { /** * Main method which executes when the program starts. * * @param args array of strings arguments */ public static void main(String[] args) { // Read from file and get HashWordSet. WordSet hashWordSet = Reader.readToWordSet(new HashWordSet(), "word.txt"); // Gives the size of the HashWordSet. System.out.println(hashWordSet.size()); // Read from file and get TreeWordSet. WordSet treeWordSet = Reader.readToWordSet(new TreeWordSet(), "word.txt"); // Print out the content of the TreeSet. @SuppressWarnings("rawtypes") Iterator it = treeWordSet.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
[ "al223bn@student.lnu.se" ]
al223bn@student.lnu.se
669a95226b509e5aca4d30144d14dd3e572a1082
42786befcc2abf65082812618f1bb8596c7fb7e4
/src/main/java/jpuppeteer/cdp/client/constant/audits/BlockedByResponseReason.java
946eb91e3a96bc6c6423338ecec8629cf0dc569b
[ "Apache-2.0" ]
permissive
sunshinex/jpuppeteer
3e30fcd434d7ddedabd0d9eeb35620707cd5bd87
0b60d1800e31decf309311671ee5f9262ea22ca5
refs/heads/2.0
2023-07-20T14:27:19.565745
2023-07-12T17:32:48
2023-07-12T17:32:48
203,903,640
33
7
Apache-2.0
2023-07-12T17:34:26
2019-08-23T01:49:32
Java
UTF-8
Java
false
false
1,111
java
package jpuppeteer.cdp.client.constant.audits; /** * Enum indicating the reason a response has been blocked. These reasons are refinements of the net error BLOCKED_BY_RESPONSE. * experimental */ public enum BlockedByResponseReason implements jpuppeteer.cdp.client.CDPEnum { COEPFRAMERESOURCENEEDSCOEPHEADER("CoepFrameResourceNeedsCoepHeader"), COOPSANDBOXEDIFRAMECANNOTNAVIGATETOCOOPPAGE("CoopSandboxedIFrameCannotNavigateToCoopPage"), CORPNOTSAMEORIGIN("CorpNotSameOrigin"), CORPNOTSAMEORIGINAFTERDEFAULTEDTOSAMEORIGINBYCOEP("CorpNotSameOriginAfterDefaultedToSameOriginByCoep"), CORPNOTSAMESITE("CorpNotSameSite"), ; private String value; BlockedByResponseReason(String value) { this.value = value; } @Override public String value() { return value; } @Override public String toString() { return value; } public static BlockedByResponseReason findByValue(String value) { for(BlockedByResponseReason val : values()) { if (val.value.equals(value)) return val; } return null; } }
[ "jarvis.xu@vipshop.com" ]
jarvis.xu@vipshop.com
50a85bade8396b4a419c3cfee1291da65708dd16
ac26ee9d037dd08eda0415048f6105b3c2bef91d
/petclinic-selenium/src/test/java/org/petclinic/HomePageTest.java
986cc59eba16411d27beeeb7620a94add144ac5a
[]
no_license
radood/automation
9a8c4d914e24259679315c323754a2901ca0ff0f
69257ffea5f26c30a5bd8ef51849ede581b12f9d
refs/heads/master
2021-01-25T09:25:53.691466
2017-06-13T09:10:25
2017-06-13T09:10:25
93,776,836
1
0
null
null
null
null
UTF-8
Java
false
false
1,923
java
package org.petclinic; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.Assert; //import java.net.HttpStatus; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; public class HomePageTest { private String testUrl; private WebDriver driver; @Before public void prepare() { //setup chromedriver System.setProperty( "webdriver.chrome.driver", "/home/radood/automation/chromedriver"); testUrl = "localhost:8080"; // Create a new instance of the Chrome driver driver = new ChromeDriver(); //maximize window driver.manage().window().maximize(); // And now use this to visit the page // Alternatively the same thing can be done like this // driver.navigate().to(testUrl); driver.get(testUrl); } @Test public void homePageShowsUpNoErrors() { List<WebElement> hpTab = driver.findElements(By.xpath("//*[@id=\"main-navbar\"]/ul/li[2]/a")); //Click the selected tab button hpTab.get(0).click(); //Assert.assertEquals(HttpStatus.OK_200,response.getStatus()); } @After public void teardown() { try { Thread.sleep(1000); } catch(InterruptedException e){ // this part is executed when an exception (in this example InterruptedException) occurs } driver.quit(); } }
[ "radu.arsici@gmail.com" ]
radu.arsici@gmail.com
bb21e040744c00091278b091204f83e41db3e9fd
aa55ce405c522108bee3ea9628feb48688edceb2
/Personal_Projects/Kattis/kattis/Tak2Stns.java
01722b243584481650e3006359b005f7c1e6e167
[]
no_license
cstitt1/Personal_Projects
362440c35f14fc035b79e9dba7cd38695bc5b6ad
8a77321a816398258790e51fc5bac8211eafe265
refs/heads/master
2023-04-13T07:42:00.573424
2023-03-30T20:01:55
2023-03-30T20:01:55
224,098,365
1
0
null
null
null
null
UTF-8
Java
false
false
254
java
package kattis; import java.util.Scanner; public class Tak2Stns { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long stns = scan.nextInt(); System.out.println((stns%2==0)?"Bob":"Alice"); scan.close(); } }
[ "cstitt1@villanova.edu" ]
cstitt1@villanova.edu
dab00fdbcc5dd93a27ac43d613e0a7fd4a463f5d
2da6618391b665999d29f77a468fdc9470476e94
/androidFile/menshen/menshen/app/build/generated/source/apt/debug/com/lvshandian/menshen/phone/PhoneHoldUpActivity$$PermissionProxy.java
42c55fd751060d1119c243b3aad518851800d3de
[]
no_license
qinbna/ananwork
eaed8ab384dbd06552c7e9156dedbf003f7e2bad
87a36e791ee5f424b09d09a4671b4dcd9efb44d4
refs/heads/master
2021-05-11T03:29:10.669852
2017-06-26T04:05:33
2017-06-26T04:05:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
714
java
// Generated code. Do not modify! package com.lvshandian.menshen.phone; import com.zhy.m.permission.*; public class PhoneHoldUpActivity$$PermissionProxy implements PermissionProxy<PhoneHoldUpActivity> { @Override public void grant(PhoneHoldUpActivity source , int requestCode) { switch(requestCode) {case 202:source.requestSdcardSuccess();break;} } @Override public void denied(PhoneHoldUpActivity source , int requestCode) { switch(requestCode) {case 202:source.requestSdcardFailed();break;} } @Override public void rationale(PhoneHoldUpActivity source , int requestCode) { switch(requestCode) {} } @Override public boolean needShowRationale(int requestCode) { switch(requestCode) {} return false; } }
[ "m185138844" ]
m185138844
c444d5a680e86ef965c26d7d0fea009fbdca5012
45be44c44821f5674e2ba3c032e8ed4009b81190
/lts-spring/src/main/java/com/lts/spring/JobClientFactoryBean.java
533562e930dc9e4cb5a3aa7172e9567099b57ce7
[]
no_license
jackho/light-task-scheduler
954f0063e0c59e9494e9c25fd0c0e0467cf5361d
8c7fd763b426a5462f5edb6d101a9d1104803c6f
refs/heads/master
2021-01-18T12:06:01.882747
2015-09-14T11:42:47
2015-09-14T11:42:47
42,506,574
1
0
null
2015-09-15T08:55:48
2015-09-15T08:55:48
null
UTF-8
Java
false
false
4,210
java
package com.lts.spring; import com.lts.core.commons.utils.Assert; import com.lts.core.listener.MasterChangeListener; import com.lts.jobclient.JobClient; import com.lts.jobclient.RetryJobClient; import com.lts.jobclient.support.JobFinishedHandler; import com.lts.tasktracker.TaskTracker; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import java.util.Map; import java.util.Properties; /** * JobClient Spring Bean ๅทฅๅŽ‚็ฑป * @author Robert HG (254963746@qq.com) on 8/4/15. */ public class JobClientFactoryBean implements FactoryBean<JobClient>, InitializingBean, DisposableBean { private JobClient jobClient; private boolean started; /** * ้›†็พคๅ็งฐ */ private String clusterName; /** * ่Š‚็‚น็ป„ๅ็งฐ */ private String nodeGroup; /** * zookeeperๅœฐๅ€ */ private String registryAddress; /** * ๆไบคๅคฑ่ดฅไปปๅŠกๅญ˜ๅ‚จ่ทฏๅพ„ , ้ป˜่ฎค็”จๆˆทๆœจ้‚ปๅฑ… */ private String failStorePath; /** * master่Š‚็‚นๅ˜ๅŒ–็›‘ๅฌๅ™จ */ private MasterChangeListener[] masterChangeListeners; /** * ้ขๅค–ๅ‚ๆ•ฐ้…็ฝฎ */ private Properties configs = new Properties(); /** * NORMAL, RETRY */ private String type; /** * ไปปๅŠกๅฎŒๆˆๅค„็†ๆŽฅๅฃ */ private JobFinishedHandler jobFinishedHandler; @Override public JobClient getObject() throws Exception { return jobClient; } @Override public Class<?> getObjectType() { return TaskTracker.class; } @Override public boolean isSingleton() { return true; } public void checkProperties() { Assert.hasText(clusterName, "clusterName must have value."); Assert.hasText(nodeGroup, "nodeGroup must have value."); Assert.hasText(registryAddress, "registryAddress must have value."); } @Override public void afterPropertiesSet() throws Exception { checkProperties(); if ("NORMAL".equals(type)) { jobClient = new JobClient(); } else { jobClient = new RetryJobClient(); } jobClient.setClusterName(clusterName); jobClient.setFailStorePath(failStorePath); jobClient.setNodeGroup(nodeGroup); jobClient.setRegistryAddress(registryAddress); if (jobFinishedHandler != null) { jobClient.setJobFinishedHandler(jobFinishedHandler); } // ่ฎพ็ฝฎconfig for (Map.Entry<Object, Object> entry : configs.entrySet()) { jobClient.addConfig(entry.getKey().toString(), entry.getValue().toString()); } if (masterChangeListeners != null) { for (MasterChangeListener masterChangeListener : masterChangeListeners) { jobClient.addMasterChangeListener(masterChangeListener); } } } /** * ๅฏไปฅ่‡ชๅทฑๅพ—ๅˆฐJobTrackerๅฏน่ฑกๅŽ่ฐƒ็”จ๏ผŒไนŸๅฏไปฅ็›ดๆŽฅไฝฟ็”จspring้…็ฝฎไธญ็š„initๅฑžๆ€งๆŒ‡ๅฎš่ฏฅๆ–นๆณ• */ public void start() { if (!started) { jobClient.start(); started = true; } } @Override public void destroy() throws Exception { jobClient.stop(); } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setNodeGroup(String nodeGroup) { this.nodeGroup = nodeGroup; } public void setRegistryAddress(String registryAddress) { this.registryAddress = registryAddress; } public void setFailStorePath(String failStorePath) { this.failStorePath = failStorePath; } public void setMasterChangeListeners(MasterChangeListener[] masterChangeListeners) { this.masterChangeListeners = masterChangeListeners; } public void setConfigs(Properties configs) { this.configs = configs; } public void setJobFinishedHandler(JobFinishedHandler jobFinishedHandler) { this.jobFinishedHandler = jobFinishedHandler; } public void setType(String type) { this.type = type; } }
[ "254963746@qq.com" ]
254963746@qq.com
49d41e298aef604d6e7b58a236ccbcbf74d03723
a6145d39beaaface23938e9b293bf8508d871966
/src/main/java/dnd/dm/model/source/SMEquipment_ThrowRange.java
aacac31e89f85c42a36a9a241dd10d9140469ad2
[]
no_license
DevonOchman/dndm
83da1638e2b8edd30b867b9115d83de9e5d7b94f
e3f7f9f865dd56dc3a65f7f11ca227d8a8817fce
refs/heads/master
2021-08-23T16:58:47.434786
2017-11-08T20:58:30
2017-11-08T20:58:30
107,264,866
0
0
null
null
null
null
UTF-8
Java
false
false
788
java
package dnd.dm.model.source; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "long", "normal" }) public class SMEquipment_ThrowRange { @JsonProperty("long") private Object _long; @JsonProperty("normal") private Double normal; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("long") public Object getLong() { return _long; } @JsonProperty("normal") public Double getNormal() { return normal; } }
[ "Devon Ochman@DESKTOP-DNTP48F" ]
Devon Ochman@DESKTOP-DNTP48F
3052c47645a4776ebb10382e47da357d75d4710d
963599f6f1f376ba94cbb504e8b324bcce5de7a3
/sources/kotlin/collections/UIntIterator.java
683cdc99c9e14706c21c005c16289488e6d5580f
[]
no_license
NikiHard/cuddly-pancake
563718cb73fdc4b7b12c6233d9bf44f381dd6759
3a5aa80d25d12da08fd621dc3a15fbd536d0b3d4
refs/heads/main
2023-04-09T06:58:04.403056
2021-04-20T00:45:08
2021-04-20T00:45:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,480
java
package kotlin.collections; import java.util.Iterator; import kotlin.Metadata; import kotlin.UInt; import kotlin.jvm.internal.markers.KMappedMarker; @Metadata(mo51341bv = {1, 0, 3}, mo51342d1 = {"\u0000\u0010\n\u0002\u0018\u0002\n\u0002\u0010(\n\u0002\u0018\u0002\n\u0002\b\u0007\b'\u0018\u00002\b\u0012\u0004\u0012\u00020\u00020\u0001B\u0005ยข\u0006\u0002\u0010\u0003J\u0016\u0010\u0004\u001a\u00020\u0002Hย†\u0002รธ\u0001\u0000รธ\u0001\u0001ยข\u0006\u0004\b\u0005\u0010\u0006J\u0015\u0010\u0007\u001a\u00020\u0002H&รธ\u0001\u0000รธ\u0001\u0001ยข\u0006\u0004\b\b\u0010\u0006รธ\u0001\u0000ย‚\u0002\b\n\u0002\b\u0019\n\u0002\b!ยจ\u0006\t"}, mo51343d2 = {"Lkotlin/collections/UIntIterator;", "", "Lkotlin/UInt;", "()V", "next", "next-pVg5ArA", "()I", "nextUInt", "nextUInt-pVg5ArA", "kotlin-stdlib"}, mo51344k = 1, mo51345mv = {1, 4, 0}) /* compiled from: UIterators.kt */ public abstract class UIntIterator implements Iterator<UInt>, KMappedMarker { /* renamed from: nextUInt-pVg5ArA reason: not valid java name */ public abstract int m7370nextUIntpVg5ArA(); public void remove() { throw new UnsupportedOperationException("Operation is not supported for read-only collection"); } public /* bridge */ /* synthetic */ Object next() { return UInt.m7020boximpl(m7369nextpVg5ArA()); } /* renamed from: next-pVg5ArA reason: not valid java name */ public final int m7369nextpVg5ArA() { return m7370nextUIntpVg5ArA(); } }
[ "a.amirovv@mail.ru" ]
a.amirovv@mail.ru
4621a430287d80a629f8b3743975629f3d8d9df1
862269ebf259ec22142ab03d36007d0a1d452fab
/src/SortAlgorithm/Test.java
a949816fe8a4d034763e8498f293d8eb4a940038
[]
no_license
Dcwjh/Algorithm
03d9a475d73754c53cb4cf997573dcd2c5e9510e
127d37f71ee3153ca6868473c91e802068d34558
refs/heads/master
2022-04-29T21:13:59.657279
2022-03-04T06:44:54
2022-03-04T06:44:54
219,679,269
1
0
null
null
null
null
UTF-8
Java
false
false
1,507
java
package SortAlgorithm; /** * @Description TODO * @Author Jianhai Wang * @ClassName Test * @Date 2021/1/25 15:54 * @Version 1.0 */ public class Test { public void heapSort(int[] nums){ if(nums == null || nums.length < 2) return; for(int i = 0; i < nums.length; i++){ heapInsert(nums, i); } int size = nums.length - 1; while(size >= 0){ swap(nums, 0, --size); heapify(nums, size); } } private void heapInsert(int[] nums, int index){ while(nums[index] > nums[(index - 1)/2]){ // index = 0ๆ—ถ๏ผŒ (index - 1) / 2 = 0,ไธ็”จ่€ƒ่™‘็ปˆๆญขๆกไปถ swap(nums, index, (index- 1) / 2); //ๅ’Œไธ‹้ขไบ’ไธบ้€†่ฟ็ฎ— index = (index-1)/2; } } private void heapify(int[] nums, int size){ int index = 0; int left = index * 2 + 1; //ๅทฆๅญๆ ‘ while(left < size){ int larger = left + 1 <= size && nums[left + 1] > nums[left]? left + 1: left; //ๅฏ่ƒฝๆ—ถleft่ฐƒๆ•ด๏ผŒไนŸๅฏ่ƒฝๅŽปไบ†left + 1่ฐƒๆ•ด larger = nums[index] < nums[larger]? larger : index; if(index == larger){ break; } swap(nums, index, larger); index = larger; //ๅ“ช้‡Œๅ˜ๅŒ–ๅฐฑๅŽปๅ“ช้‡Œ left = index * 2 + 1; } } private void swap(int[] nums, int left, int right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
[ "503396265@qq.com" ]
503396265@qq.com
7f381811d32082eaa46a3e9be1fd239e9afbd9f2
becaf5d11229ae655966e1873b813561efe59172
/jenetics.example/src/main/java/io/jenetics/example/image/PolygonPanel.java
3d0b7fa3a10a8229fef76c2d700ee8ebfc5af26b
[ "Apache-2.0" ]
permissive
n1ay/jenetics
a6d6b17aedf943c60c497791015ce2d6d57ada7c
b60507ada298eb622cd576741ce34cb29532adfe
refs/heads/master
2020-03-28T21:51:50.365872
2018-09-07T17:04:46
2018-09-07T17:04:46
149,187,784
0
0
Apache-2.0
2018-09-17T21:03:40
2018-09-17T21:03:40
null
UTF-8
Java
false
false
2,269
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jenetics.example.image; import static java.lang.Math.min; import static java.util.Objects.requireNonNull; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; /** * Draws the given {@code PolygonChromosome}. */ final class PolygonPanel extends JPanel { private int _width; private int _height; private PolygonChromosome _chromosome; PolygonPanel(int width, int height) { _width = width; _height = height; } PolygonPanel() { this(10, 10); } public void setDimension(final int width, final int height) { _width = width; _height = height; } public Dimension getDimension() { return new Dimension(_width, _height); } public void setChromosome(final PolygonChromosome chromosome) { _chromosome = requireNonNull(chromosome); } public PolygonChromosome getChromosome() { return _chromosome; } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); if (_chromosome != null) { _chromosome.draw((Graphics2D) g, width(), height()); } else { g.setColor(Color.white); g.clearRect(0, 0, width(), height()); } } private float scaleFactor() { final float sw = getWidth()/(float)_width; final float sh = getHeight()/(float)_height; return min(sw, sh); } private int width() { return (int) (_width*scaleFactor()); } private int height() { return (int) (_height*scaleFactor()); } }
[ "franz.wilhelmstoetter@gmail.com" ]
franz.wilhelmstoetter@gmail.com
763ba44cf3cacc5ecd3e0eb57079d9f7dee91fa4
e864c8c93766b14c084fab072dd78f281f578c5d
/TSS.Java/src/tss/tpm/TPM_PT.java
822ce020227cf94febf508b27e03338d835bb71c
[ "MIT" ]
permissive
petrs/TSS.MSR
1cf05cda7b094492049185fc6bc8e1f5eb40d13e
f0c86d5193c86dd04418b71d667c3b6a488aabb6
refs/heads/master
2020-03-08T19:56:31.375322
2018-03-24T00:13:04
2018-03-24T00:13:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
21,763
java
package tss.tpm; import tss.*; import java.util.*; // -----------This is an auto-generated file: do not edit //>>> /** * The TPM_PT constants are used in TPM2_GetCapability(capability = TPM_CAP_TPM_PROPERTIES) to indicate the property being selected or returned. */ public final class TPM_PT extends TpmEnum<TPM_PT> { // Values from enum _N are only intended to be used in case labels of a switch statement using the result of this.asEnum() method as the switch condition. // However, their Java names are identical to those of the constants defined in this class further below, // so for any other usage just prepend them with the TPM_PT. qualifier. public enum _N { /** * indicates no property type */ NONE, /** * The number of properties in each group. NOTE The first group with any properties is group 1 (PT_GROUP * 1). Group 0 is reserved. */ PT_GROUP, /** * the group of fixed properties returned as TPMS_TAGGED_PROPERTY The values in this group are only changed due to a firmware change in the TPM. */ PT_FIXED, /** * a 4-octet character string containing the TPM Family value (TPM_SPEC_FAMILY) */ FAMILY_INDICATOR, /** * the level of the specification NOTE 1 For this specification, the level is zero. NOTE 2 The level is on the title page of the specification. */ LEVEL, /** * the specification Revision times 100 EXAMPLE Revision 01.01 would have a value of 101. NOTE The Revision value is on the title page of the specification. */ REVISION, /** * the specification day of year using TCG calendar EXAMPLE November 15, 2010, has a day of year value of 319 (0000013F16). NOTE The specification date is on the title page of the specification. */ DAY_OF_YEAR, /** * the specification year using the CE EXAMPLE The year 2010 has a value of 000007DA16. NOTE The specification date is on the title page of the specification. */ YEAR, /** * the vendor ID unique to each TPM manufacturer */ MANUFACTURER, /** * the first four characters of the vendor ID string NOTE When the vendor string is fewer than 16 octets, the additional property values do not have to be present. A vendor string of 4 octets can be represented in one 32-bit value and no null terminating character is required. */ VENDOR_STRING_1, /** * the second four characters of the vendor ID string */ VENDOR_STRING_2, /** * the third four characters of the vendor ID string */ VENDOR_STRING_3, /** * the fourth four characters of the vendor ID sting */ VENDOR_STRING_4, /** * vendor-defined value indicating the TPM model */ VENDOR_TPM_TYPE, /** * the most-significant 32 bits of a TPM vendor-specific value indicating the version number of the firmware. See 10.12.2 and 10.12.8. */ FIRMWARE_VERSION_1, /** * the least-significant 32 bits of a TPM vendor-specific value indicating the version number of the firmware. See 10.12.2 and 10.12.8. */ FIRMWARE_VERSION_2, /** * the maximum size of a parameter (typically, a TPM2B_MAX_BUFFER) */ INPUT_BUFFER, /** * the minimum number of transient objects that can be held in TPM RAM NOTE This minimum shall be no less than the minimum value required by the platform-specific specification to which the TPM is built. */ HR_TRANSIENT_MIN, /** * the minimum number of persistent objects that can be held in TPM NV memory NOTE This minimum shall be no less than the minimum value required by the platform-specific specification to which the TPM is built. */ HR_PERSISTENT_MIN, /** * the minimum number of authorization sessions that can be held in TPM RAM NOTE This minimum shall be no less than the minimum value required by the platform-specific specification to which the TPM is built. */ HR_LOADED_MIN, /** * the number of authorization sessions that may be active at a time A session is active when it has a context associated with its handle. The context may either be in TPM RAM or be context saved. NOTE This value shall be no less than the minimum value required by the platform-specific specification to which the TPM is built. */ ACTIVE_SESSIONS_MAX, /** * the number of PCR implemented NOTE This number is determined by the defined attributes, not the number of PCR that are populated. */ PCR_COUNT, /** * the minimum number of octets in a TPMS_PCR_SELECT.sizeOfSelect NOTE This value is not determined by the number of PCR implemented but by the number of PCR required by the platform-specific specification with which the TPM is compliant or by the implementer if not adhering to a platform-specific specification. */ PCR_SELECT_MIN, /** * the maximum allowed difference (unsigned) between the contextID values of two saved session contexts This value shall be 2n-1, where n is at least 16. */ CONTEXT_GAP_MAX, /** * the maximum number of NV Indexes that are allowed to have the TPM_NT_COUNTER attribute NOTE It is allowed for this value to be larger than the number of NV Indexes that can be defined. This would be indicative of a TPM implementation that did not use different implementation technology for different NV Index types. */ NV_COUNTERS_MAX, /** * the maximum size of an NV Index data area */ NV_INDEX_MAX, /** * a TPMA_MEMORY indicating the memory management method for the TPM */ MEMORY, /** * interval, in milliseconds, between updates to the copy of TPMS_CLOCK_INFO.clock in NV */ CLOCK_UPDATE, /** * the algorithm used for the integrity HMAC on saved contexts and for hashing the fuData of TPM2_FirmwareRead() */ CONTEXT_HASH, /** * TPM_ALG_ID, the algorithm used for encryption of saved contexts */ CONTEXT_SYM, /** * TPM_KEY_BITS, the size of the key used for encryption of saved contexts */ CONTEXT_SYM_SIZE, /** * the modulus - 1 of the count for NV update of an orderly counter The returned value is MAX_ORDERLY_COUNT. This will have a value of 2N 1 where 1 N 32 NOTE 1 An orderly counter is an NV Index with an TPM_NT of TPM_NV_COUNTER and TPMA_NV_ORDERLY SET. NOTE 2 When the low-order bits of a counter equal this value, an NV write occurs on the next increment. */ ORDERLY_COUNT, /** * the maximum value for commandSize in a command */ MAX_COMMAND_SIZE, /** * the maximum value for responseSize in a response */ MAX_RESPONSE_SIZE, /** * the maximum size of a digest that can be produced by the TPM */ MAX_DIGEST, /** * the maximum size of an object context that will be returned by TPM2_ContextSave */ MAX_OBJECT_CONTEXT, /** * the maximum size of a session context that will be returned by TPM2_ContextSave */ MAX_SESSION_CONTEXT, /** * platform-specific family (a TPM_PS value)(see Table 25) NOTE The platform-specific values for the TPM_PT_PS parameters are in the relevant platform-specific specification. In the reference implementation, all of these values are 0. */ PS_FAMILY_INDICATOR, /** * the level of the platform-specific specification */ PS_LEVEL, /** * the specification Revision times 100 for the platform-specific specification */ PS_REVISION, /** * the platform-specific specification day of year using TCG calendar */ PS_DAY_OF_YEAR, /** * the platform-specific specification year using the CE */ PS_YEAR, /** * the number of split signing operations supported by the TPM */ SPLIT_MAX, /** * total number of commands implemented in the TPM */ TOTAL_COMMANDS, /** * number of commands from the TPM library that are implemented */ LIBRARY_COMMANDS, /** * number of vendor commands that are implemented */ VENDOR_COMMANDS, /** * the maximum data size in one NV write, NV read, or NV certify command */ NV_BUFFER_MAX, /** * a TPMA_MODES value, indicating that the TPM is designed for these modes. */ MODES, /** * the maximum size of a TPMS_CAPABILITY_DATA structure returned in TPM2_GetCapability(). */ MAX_CAP_BUFFER, /** * the group of variable properties returned as TPMS_TAGGED_PROPERTY The properties in this group change because of a Protected Capability other than a firmware update. The values are not necessarily persistent across all power transitions. */ PT_VAR, /** * TPMA_PERMANENT */ PERMANENT, /** * TPMA_STARTUP_CLEAR */ STARTUP_CLEAR, /** * the number of NV Indexes currently defined */ HR_NV_INDEX, /** * the number of authorization sessions currently loaded into TPM RAM */ HR_LOADED, /** * the number of additional authorization sessions, of any type, that could be loaded into TPM RAM This value is an estimate. If this value is at least 1, then at least one authorization session of any type may be loaded. Any command that changes the RAM memory allocation can make this estimate invalid. NOTE A valid implementation may return 1 even if more than one authorization session would fit into RAM. */ HR_LOADED_AVAIL, /** * the number of active authorization sessions currently being tracked by the TPM This is the sum of the loaded and saved sessions. */ HR_ACTIVE, /** * the number of additional authorization sessions, of any type, that could be created This value is an estimate. If this value is at least 1, then at least one authorization session of any type may be created. Any command that changes the RAM memory allocation can make this estimate invalid. NOTE A valid implementation may return 1 even if more than one authorization session could be created. */ HR_ACTIVE_AVAIL, /** * estimate of the number of additional transient objects that could be loaded into TPM RAM This value is an estimate. If this value is at least 1, then at least one object of any type may be loaded. Any command that changes the memory allocation can make this estimate invalid. NOTE A valid implementation may return 1 even if more than one transient object would fit into RAM. */ HR_TRANSIENT_AVAIL, /** * the number of persistent objects currently loaded into TPM NV memory */ HR_PERSISTENT, /** * the number of additional persistent objects that could be loaded into NV memory This value is an estimate. If this value is at least 1, then at least one object of any type may be made persistent. Any command that changes the NV memory allocation can make this estimate invalid. NOTE A valid implementation may return 1 even if more than one persistent object would fit into NV memory. */ HR_PERSISTENT_AVAIL, /** * the number of defined NV Indexes that have NV the TPM_NT_COUNTER attribute */ NV_COUNTERS, /** * the number of additional NV Indexes that can be defined with their TPM_NT of TPM_NV_COUNTER and the TPMA_NV_ORDERLY attribute SET This value is an estimate. If this value is at least 1, then at least one NV Index may be created with a TPM_NT of TPM_NV_COUNTER and the TPMA_NV_ORDERLY attributes. Any command that changes the NV memory allocation can make this estimate invalid. NOTE A valid implementation may return 1 even if more than one NV counter could be defined. */ NV_COUNTERS_AVAIL, /** * code that limits the algorithms that may be used with the TPM */ ALGORITHM_SET, /** * the number of loaded ECC curves */ LOADED_CURVES, /** * the current value of the lockout counter (failedTries) */ LOCKOUT_COUNTER, /** * the number of authorization failures before DA lockout is invoked */ MAX_AUTH_FAIL, /** * the number of seconds before the value reported by TPM_PT_LOCKOUT_COUNTER is decremented */ LOCKOUT_INTERVAL, /** * the number of seconds after a lockoutAuth failure before use of lockoutAuth may be attempted again */ LOCKOUT_RECOVERY, /** * number of milliseconds before the TPM will accept another command that will modify NV This value is an approximation and may go up or down over time. */ NV_WRITE_RECOVERY, /** * the high-order 32 bits of the command audit counter */ AUDIT_COUNTER_0, /** * the low-order 32 bits of the command audit counter */ AUDIT_COUNTER_1 } private static ValueMap<TPM_PT> _ValueMap = new ValueMap<TPM_PT>(); public static final TPM_PT // These definitions provide mapping of the Java names of constants to their TPM values. NONE = new TPM_PT(0x00000000, _N.NONE), PT_GROUP = new TPM_PT(0x00000100, _N.PT_GROUP), PT_FIXED = new TPM_PT(TPM_PT.PT_GROUP.toInt() * 1, _N.PT_FIXED), FAMILY_INDICATOR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 0, _N.FAMILY_INDICATOR), LEVEL = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 1, _N.LEVEL), REVISION = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 2, _N.REVISION), DAY_OF_YEAR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 3, _N.DAY_OF_YEAR), YEAR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 4, _N.YEAR), MANUFACTURER = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 5, _N.MANUFACTURER), VENDOR_STRING_1 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 6, _N.VENDOR_STRING_1), VENDOR_STRING_2 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 7, _N.VENDOR_STRING_2), VENDOR_STRING_3 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 8, _N.VENDOR_STRING_3), VENDOR_STRING_4 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 9, _N.VENDOR_STRING_4), VENDOR_TPM_TYPE = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 10, _N.VENDOR_TPM_TYPE), FIRMWARE_VERSION_1 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 11, _N.FIRMWARE_VERSION_1), FIRMWARE_VERSION_2 = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 12, _N.FIRMWARE_VERSION_2), INPUT_BUFFER = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 13, _N.INPUT_BUFFER), HR_TRANSIENT_MIN = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 14, _N.HR_TRANSIENT_MIN), HR_PERSISTENT_MIN = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 15, _N.HR_PERSISTENT_MIN), HR_LOADED_MIN = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 16, _N.HR_LOADED_MIN), ACTIVE_SESSIONS_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 17, _N.ACTIVE_SESSIONS_MAX), PCR_COUNT = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 18, _N.PCR_COUNT), PCR_SELECT_MIN = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 19, _N.PCR_SELECT_MIN), CONTEXT_GAP_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 20, _N.CONTEXT_GAP_MAX), NV_COUNTERS_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 22, _N.NV_COUNTERS_MAX), NV_INDEX_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 23, _N.NV_INDEX_MAX), MEMORY = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 24, _N.MEMORY), CLOCK_UPDATE = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 25, _N.CLOCK_UPDATE), CONTEXT_HASH = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 26, _N.CONTEXT_HASH), CONTEXT_SYM = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 27, _N.CONTEXT_SYM), CONTEXT_SYM_SIZE = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 28, _N.CONTEXT_SYM_SIZE), ORDERLY_COUNT = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 29, _N.ORDERLY_COUNT), MAX_COMMAND_SIZE = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 30, _N.MAX_COMMAND_SIZE), MAX_RESPONSE_SIZE = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 31, _N.MAX_RESPONSE_SIZE), MAX_DIGEST = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 32, _N.MAX_DIGEST), MAX_OBJECT_CONTEXT = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 33, _N.MAX_OBJECT_CONTEXT), MAX_SESSION_CONTEXT = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 34, _N.MAX_SESSION_CONTEXT), PS_FAMILY_INDICATOR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 35, _N.PS_FAMILY_INDICATOR), PS_LEVEL = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 36, _N.PS_LEVEL), PS_REVISION = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 37, _N.PS_REVISION), PS_DAY_OF_YEAR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 38, _N.PS_DAY_OF_YEAR), PS_YEAR = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 39, _N.PS_YEAR), SPLIT_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 40, _N.SPLIT_MAX), TOTAL_COMMANDS = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 41, _N.TOTAL_COMMANDS), LIBRARY_COMMANDS = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 42, _N.LIBRARY_COMMANDS), VENDOR_COMMANDS = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 43, _N.VENDOR_COMMANDS), NV_BUFFER_MAX = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 44, _N.NV_BUFFER_MAX), MODES = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 45, _N.MODES), MAX_CAP_BUFFER = new TPM_PT(TPM_PT.PT_FIXED.toInt() + 46, _N.MAX_CAP_BUFFER), PT_VAR = new TPM_PT(TPM_PT.PT_GROUP.toInt() * 2, _N.PT_VAR), PERMANENT = new TPM_PT(TPM_PT.PT_VAR.toInt() + 0, _N.PERMANENT), STARTUP_CLEAR = new TPM_PT(TPM_PT.PT_VAR.toInt() + 1, _N.STARTUP_CLEAR), HR_NV_INDEX = new TPM_PT(TPM_PT.PT_VAR.toInt() + 2, _N.HR_NV_INDEX), HR_LOADED = new TPM_PT(TPM_PT.PT_VAR.toInt() + 3, _N.HR_LOADED), HR_LOADED_AVAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 4, _N.HR_LOADED_AVAIL), HR_ACTIVE = new TPM_PT(TPM_PT.PT_VAR.toInt() + 5, _N.HR_ACTIVE), HR_ACTIVE_AVAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 6, _N.HR_ACTIVE_AVAIL), HR_TRANSIENT_AVAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 7, _N.HR_TRANSIENT_AVAIL), HR_PERSISTENT = new TPM_PT(TPM_PT.PT_VAR.toInt() + 8, _N.HR_PERSISTENT), HR_PERSISTENT_AVAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 9, _N.HR_PERSISTENT_AVAIL), NV_COUNTERS = new TPM_PT(TPM_PT.PT_VAR.toInt() + 10, _N.NV_COUNTERS), NV_COUNTERS_AVAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 11, _N.NV_COUNTERS_AVAIL), ALGORITHM_SET = new TPM_PT(TPM_PT.PT_VAR.toInt() + 12, _N.ALGORITHM_SET), LOADED_CURVES = new TPM_PT(TPM_PT.PT_VAR.toInt() + 13, _N.LOADED_CURVES), LOCKOUT_COUNTER = new TPM_PT(TPM_PT.PT_VAR.toInt() + 14, _N.LOCKOUT_COUNTER), MAX_AUTH_FAIL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 15, _N.MAX_AUTH_FAIL), LOCKOUT_INTERVAL = new TPM_PT(TPM_PT.PT_VAR.toInt() + 16, _N.LOCKOUT_INTERVAL), LOCKOUT_RECOVERY = new TPM_PT(TPM_PT.PT_VAR.toInt() + 17, _N.LOCKOUT_RECOVERY), NV_WRITE_RECOVERY = new TPM_PT(TPM_PT.PT_VAR.toInt() + 18, _N.NV_WRITE_RECOVERY), AUDIT_COUNTER_0 = new TPM_PT(TPM_PT.PT_VAR.toInt() + 19, _N.AUDIT_COUNTER_0), AUDIT_COUNTER_1 = new TPM_PT(TPM_PT.PT_VAR.toInt() + 20, _N.AUDIT_COUNTER_1); public TPM_PT (int value) { super(value, _ValueMap); } public static TPM_PT fromInt (int value) { return TpmEnum.fromInt(value, _ValueMap, TPM_PT.class); } public static TPM_PT fromTpm (byte[] buf) { return TpmEnum.fromTpm(buf, _ValueMap, TPM_PT.class); } public static TPM_PT fromTpm (InByteBuf buf) { return TpmEnum.fromTpm(buf, _ValueMap, TPM_PT.class); } public TPM_PT._N asEnum() { return (TPM_PT._N)NameAsEnum; } public static Collection<TPM_PT> values() { return _ValueMap.values(); } private TPM_PT (int value, _N nameAsEnum) { super(value, nameAsEnum, _ValueMap); } private TPM_PT (int value, _N nameAsEnum, boolean noConvFromInt) { super(value, nameAsEnum, null); } @Override protected int wireSize() { return 4; } } //<<<
[ "Andrey.Marochko@microsoft.com" ]
Andrey.Marochko@microsoft.com
8f49950fb8bec152870a695d5b68e0cce98ed5b0
4e5f337a4f7035f5573797573e9cc0d981a2c406
/ConnectedCities/src/main/java/com/mastercard/connectedcities/application/ConnectedCitiesApplication.java
0edd36ec9fb84e086d883565e423aa8b295cfaa2
[]
no_license
rlandge2020/connectcity
b256459d62f32e1444277c4b81ea67d3ac28b509
fed1f0fad7450fdb1357c9dd07350c8a6e7fba6e
refs/heads/master
2021-02-11T05:35:51.973078
2020-03-02T19:51:34
2020-03-02T19:51:34
244,460,042
0
0
null
null
null
null
UTF-8
Java
false
false
2,006
java
package com.mastercard.connectedcities.application; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.FileCopyUtils; /** * * @author Rahul Landge * */ @SpringBootApplication @ComponentScan("com.mastercard.connectedcities.controller") public class ConnectedCitiesApplication implements CommandLineRunner { @Autowired ResourceLoader resourceLoader; @Autowired private CacheManager cacheManager; @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("cities"); } public static void main(String[] args) { SpringApplication.run(ConnectedCitiesApplication.class, args); } @Override public void run(String... args) throws Exception { Resource resource = resourceLoader.getResource("classpath:cities.txt"); InputStream inputStream = resource.getInputStream(); try { byte[] bdata = FileCopyUtils.copyToByteArray(inputStream); String data = new String(bdata, StandardCharsets.UTF_8); String[] cities = data.split("\n"); for (String city : cities) { String[] originAndDestinations = city.split(","); cacheManager.getCache("cities").put(originAndDestinations[0].trim(), (originAndDestinations[1].trim())); System.out.println(originAndDestinations[0] + ":" + originAndDestinations[1]); } } catch (IOException e) { } } }
[ "noreply@github.com" ]
rlandge2020.noreply@github.com
6fc734015ecd7f8623a9316127b285ffab9b3b67
367ad1d4fa0cb5e53ef4b8be3b380a3342742441
/command/src/main/java/com/kovalchv/interfaces/Command.java
8da4729ff0533c154e1261314b681f3ea0e619df
[]
no_license
9aN3D/design-patterns
87a244375119bbfb43155944defd7a0c525a3798
3be7ab273b3f9a7dbe192c6db6a92ca51f4fdef9
refs/heads/master
2020-12-21T04:40:15.410146
2020-02-09T18:18:13
2020-02-09T18:18:13
236,310,146
0
0
null
null
null
null
UTF-8
Java
false
false
85
java
package com.kovalchv.interfaces; public interface Command { void execute(); }
[ "v.kovalchuk.n@gmail.com" ]
v.kovalchuk.n@gmail.com
a43674ff19094ca34a41a659cda50bd203a2f0cb
466129a071eb9fcf5172c1cc367769a35f1f46bc
/app/src/main/java/com/treasure_ct/android_xt/studyfragment/studyadvance/rxjava/DoubanActivity.java
dfd019db9cb9001a6255c9af699bd1878bc0844b
[]
no_license
treasurect/Android_XT
2a800097e02526e6ad6a1408347e23bdcac71fc8
35ffe3ca2031181cfd60d3f7a84fc9822346c4df
refs/heads/master
2021-07-10T18:32:56.975458
2017-09-17T10:18:38
2017-09-17T10:18:40
103,820,529
2
0
null
null
null
null
UTF-8
Java
false
false
2,340
java
package com.treasure_ct.android_xt.studyfragment.studyadvance.rxjava; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import com.treasure_ct.android_xt.R; import com.treasure_ct.android_xt.studyfragment.studyadvance.rxjava.services.DoubanService; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; public class DoubanActivity extends AppCompatActivity { private static final String TAG = "DoubanActivity"; private DoubanService mDoubanService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_studyadvance_douban); Retrofit.Builder builder = new Retrofit.Builder(); builder.baseUrl("https://api.douban.com/v2/"); builder.addConverterFactory(ScalarsConverterFactory.create()); //ๅงๅขžๅŠ Call็ฑปๅž‹็š„่ฝฌๆขๅ™จ๏ผŒๅฏไปฅๆŠŠRetrofit ๅ’ŒRxJava ่”ๅŠจ builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())); Retrofit retrofit = builder.build(); mDoubanService = retrofit.create(DoubanService.class); } public void btnGetAPI(View view) { Observable<String> observable = mDoubanService.getMovieTop250(0, 10); observable .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Observer<String>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // // } // // @Override // public void onNext(String s) { // // } // }); .subscribe(new Action1<String>() { @Override public void call(String s) { Log.d(TAG, "list = " + s); } }); } public void btnGetMovieDetail(View view) { } }
[ "m18753377169@gmail.com" ]
m18753377169@gmail.com
9e90347f74969b213755716933b8cf79064e5ca5
5064445d057dd496ac7f65663dc20c860c613b83
/ListViewImages/src/com/jsupport/listviewimages/SingleItemMenu.java
cb5f20833a6b0d0853fa57371ebad3cd1006b0e4
[]
no_license
kramyaj13/GreatFoodApplication
87acb9e9f5aafe073c068eafd3d1eda403450fa0
7c7e69f729f47bcc4b35f29fec8bc0a62da8bdf2
refs/heads/master
2016-08-10T07:59:18.961347
2013-03-04T14:01:57
2013-03-04T14:01:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
676
java
package com.jsupport.listviewimages; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; public class SingleItemMenu extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_item_menu); Intent intent = getIntent(); String subcat = intent.getStringExtra("subcat"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_single_item_menu, menu); return true; } }
[ "jaymark.diamante@yahoo.com.ph" ]
jaymark.diamante@yahoo.com.ph
f3fb980b78d186663630af820339cf6843cecb53
b9a1df39ea9ecad57298e42fbc3ed53f5bbda18d
/WebApiUsage/app/src/androidTest/java/com/sunincha/webapiusage/ExampleInstrumentedTest.java
0f479509dbf25156f63f67d5cba963389ece4448
[]
no_license
sncvikas/AndroidBasicApps
399bda9e5f18d7fc292b8c8490fbc1e91b1a658a
1d0c97aebff7963e30e43cf063dd110dde7f75f0
refs/heads/master
2020-04-30T11:34:19.335076
2019-09-22T15:45:51
2019-09-22T15:45:51
176,804,617
1
0
null
null
null
null
UTF-8
Java
false
false
732
java
package com.sunincha.webapiusage; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.sunincha.webapiusage", appContext.getPackageName()); } }
[ "vikasncg@gmail.com" ]
vikasncg@gmail.com
38255184d5add5e912e40bdddd4084dd98e1eb64
c194bbf08d2671d8f6fd00b7e87ce67a87a28582
/src/Forum/Client/ui/events/ForumTreeRefreshEvent.java
7a743b0e6ab5ad34411a3fb2d159cb896d8443cd
[]
no_license
aofer/tapuachforum
537b306591907270e836773f47aa05ace6343575
8fff766b50a30acdf0ee6098c82cd92ce16b99c1
refs/heads/master
2021-01-22T11:58:27.401123
2010-07-26T19:38:18
2010-07-26T19:38:18
32,862,485
0
0
null
null
null
null
UTF-8
Java
false
false
963
java
package Forum.Client.ui.events; import java.awt.Component; import Forum.Client.ui.TreeView.ForumTreeHandler; /** * This event enables a component (if there is one). And updates the forum view in the GUI. * * @author Tomer Heber */ public class ForumTreeRefreshEvent implements ForumTreeEvent { private Component m_comp; private String m_forumView; public ForumTreeRefreshEvent(String forumView) { m_forumView = forumView; m_comp = null; } public ForumTreeRefreshEvent(Component comp, String forumView) { m_forumView = forumView; m_comp = comp; } /* (non-Javadoc) * @see forumtree.contol.ForumTreeEvent#respondToEvent(forumtree.ForumTree) */ @Override public void respondToEvent(ForumTreeHandler handler) { if (m_comp != null) { m_comp.setEnabled(true); } handler.refreshForum(m_forumView); } }
[ "Kipi@Kipi-PC" ]
Kipi@Kipi-PC
65e2f95320af9018f87f7f2e1f345d4e32050588
940141b1fecb89dc5b8c4c7a33988b3bf83cf6c5
/src/LZW.java
abf87d7848e0d989fdb311386b175ab22efcdef5
[]
no_license
HenrikHills/INF144_oblig
1c8768b53ba5fd9459739fdfed09f022dbc30365
074244ca12bfe0d82761b2edb982288f8bd8234b
refs/heads/master
2020-05-16T10:54:52.328316
2019-04-23T11:34:44
2019-04-23T11:34:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,146
java
import java.io.*; public class LZW { static String dictionary[]; static int point; String eventyr; String comp = ""; public LZW(String eventyr) throws FileNotFoundException { this.eventyr = eventyr; comp = compress(eventyr); PrintWriter out = new PrintWriter("src/LZW.txt"); out.println(comp); out.close(); } // public static void main(String args[]) throws FileNotFoundException { // String text = ReadFile(); // String comp = compress(text); // System.out.println("Compressed from " + text.length() + " to " + comp.length() + " chars/ " + (comp.length()*100)/text.length() + " %."); // // PrintWriter out = new PrintWriter("src/LZW.txt"); // out.println(comp); // out.close(); // // } public static String compress(String string) { initiateDictionary(string.length()); String output = ""; String w = ""; char k; while (string.length() > 0) { k = string.charAt(0); string = string.substring(1); if (Contains(w + k)) { w += k; } else { output+= DictionaryCode(w); DictionaryAdd(w + k); w = k+""; } } return output + DictionaryCode(w); } public static String decompress(String string) { initiateDictionary(string.length()+1); String output = ""; String w = ""; int k = (int)string.charAt(0); w = DictionaryChar(k); string = string.substring(1); output += w; while (string.length() > 0) { k = (int) string.charAt(0); string = string.substring(1); output += DictionaryChar(k); DictionaryAdd(w + DictionaryChar(k).charAt(0)); w = DictionaryChar(k); } return output; } private static void initiateDictionary(int size) { dictionary = new String[size]; point = 0; } private static boolean Contains(String string) { return (DictionaryCode(string).length() > 0); } private static String DictionaryCode(String string) { String code = ""; char c; int i = 0; if (string.length() == 1) { return "" + string.charAt(0); } else { while ((code.length() == 0) && (i < dictionary.length)) { if ((dictionary[i] != null) && dictionary[i].equals(string)) { c = (char)(i+256); code = "" + c; } i++; } return code; } } private static String DictionaryChar(int code) { if (code < 256) { return "" + (char)code; } else if ((code-256) < dictionary.length) { return dictionary[code-256]; } else { return ""; } } private static void DictionaryAdd(String string) { dictionary[point] = string; point++; } private static String ReadFile() { InputStreamReader inputSR = new InputStreamReader(System.in); BufferedReader bufferedR = new BufferedReader(inputSR); String text = ""; try { String line = null; File file = new File("src/Folktale.html"); bufferedR = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while((line = bufferedR.readLine()) != null){ text += line.replaceAll("\\<.*?>", "").replaceAll(" +", " ").toLowerCase(); } } catch(IOException ioe) { System.out.println("Error reading from file"); } return text; } }
[ "hto017@student.uib.no" ]
hto017@student.uib.no
6acf09836944246354c26197cb52a937dc06c5bf
01b3d422c8e75508b53188b93ac32bb801d76137
/src/main/java/java/Ball.java
8833b7e08c4cc86017476460893bf94e9c105d61
[]
no_license
MishanyG/JavaLevel_2
8b85a6d382768d1a39939a45816b73221a5d98cb
14e72e23868a924532259ec83c7835b532376fdc
refs/heads/master
2023-06-30T09:02:32.455517
2021-07-26T15:44:27
2021-07-26T15:44:27
263,797,078
0
0
null
2021-07-26T15:44:28
2020-05-14T02:40:09
Java
UTF-8
Java
false
false
1,269
java
package java; import java.awt.*; public class Ball extends Sprite { Color color = new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)); private float vX = (float) (100f + (Math.random() * 200f)); private float vY = (float) (100f + (Math.random() * 200f)); Ball() { halfHeight = 20 + (float) (Math.random() * 50f); halfWidth = halfHeight; } @Override public void update(MainCanvas canvas, float deltaTime) { x += vX * deltaTime; y += vY * deltaTime; if (getLeft() < canvas.getLeft()) { setLeft(canvas.getLeft()); vX = -vX; } if (getRight() > canvas.getRight()) { setRight(canvas.getRight()); vX = -vX; } if (getTop() < canvas.getTop()) { setTop(canvas.getTop()); vY = -vY; } if (getBottom() > canvas.getBottom()) { setBottom(canvas.getBottom()); vY = -vY; } } @Override public void render(MainCanvas canvas, Graphics g) { g.setColor(color); g.fillOval((int) getLeft(), (int) getTop(), (int) getWidth(), (int) getHeight()); } }
[ "flatron_777@mail.ru" ]
flatron_777@mail.ru
6ee9eac336a64a258efb4faf248830685d24cc5c
66c7a5371655b5fe5b7b91c11927466893ccca7c
/src/com/myfirstproject/cwh_35_PSonMethods.java
9c6c6418338bd47795175458e3dad3e67c133f5b
[]
no_license
matalha786/LearnJAVA
97ccb7a5202fb1fe1215f6f6d695bd29c409e13f
a0588b117dc135f04e1c16f4c38251dc7e05ac31
refs/heads/main
2023-06-18T07:04:35.016994
2021-07-06T12:50:51
2021-07-06T12:50:51
383,465,400
0
0
null
null
null
null
UTF-8
Java
false
false
2,897
java
package com.myfirstproject; import org.w3c.dom.ls.LSOutput; public class cwh_35_PSonMethods { static void pat1(int n ) { for (int i = 0; i < n; i++) { for (int j = 0; j < i + 1; j++) { System.out.print("*"); } System.out.println(); } } static void pat2( int n2 ) { for (int i2 = 1; i2 <= n2; i2++) { for (int j = n2; j >= i2; j--) { System.out.print("*"); } System.out.println(); } } static String pat2_rec_Question_8(int n3 ) { if (n3 > 0) { pat2_rec_Question_8(n3-1); for (int i3 = 0; i3 < n3; i3++) { System.out.print("*"); } System.out.println(); } return ""; } static String pat2_rec_Question_7(int n3 ) { if (n3 > 0) { pat2_rec_Question_7(n3-1); for (int i3 = 5; i3 > n3; i3--) { System.out.print("*"); } System.out.println(); } return ""; } public static int sum(int ...arr){ int result = 0; for (int a:arr ) { result +=a; } return result/ arr.length; } static int ab(int no){ return no; } // Problem 7 (0ยฐC ร— 9/5) + 32 = 32ยฐF static double c2f(double a) { double b = (a * 9 / 5) + 32; return b; } static int sumn(int a) { int sum = 0; for (int i = 0; i <= a; i++){ sum = sum + i;} return sum; } static int naturalNumberSum(int n) { int sum = 0; //executes until the condition becomes false for (int i = 0; i <= n; i++) //adding the value of i to the sum variable sum = sum + i; return sum; } public static void main(String[] args) { // Problem 2 // pat1(4); // System.out.println("Now In Reverse Order"); // Problem 4 // pat2(4); // Concept of return // System.out.println(ab(7)); // Problem 6 // System.out.println(sum(100,200,300)); // Problem 7 // System.out.println(pat2_rec_Question_8(4)); // Problem 7 (0ยฐC ร— 9/5) + 32 = 32ยฐF // Scanner sc = new Scanner(System.in); // System.out.println("Enter Temperature in Celsius : " ); // double a = sc.nextDouble(); // System.out.println("Temperature in Frahnhite is :" ); // System.out.println((a*9/5)+32); // System.out.println(c2f(11)); // Problem 7 int a =4; System.out.println(sumn(a)); // int n = 3; //calling method and prints the sum // System.out.println("Sum of Natural Numbers is: "+naturalNumberSum(n)); } }
[ "noreply@github.com" ]
matalha786.noreply@github.com
69dcc478a4cb63d1379eff6c42345efdf7a1b8af
28359b62c3a81eeab91217f69fbd02affbc12ce8
/java_01/src/day04/Test01.java
e6efe778aa775ebac3b73a57f7ee38a91e9428e8
[]
no_license
hsok0070/bit_java
617dd532d498ac1f655c01edde4276a25f3602bc
9b33847b4c28bb62d25544ae18324efcd92eb3e5
refs/heads/master
2020-07-03T09:50:31.800447
2019-08-29T09:44:01
2019-08-29T09:44:01
201,861,796
0
0
null
null
null
null
UTF-8
Java
false
false
810
java
package day04; import java.util.Scanner; public class Test01 { public static void main(String[] args) { System.out.println("์•ŒํŒŒ๋ฒณ ์•„์Šคํ‚ค ์ฝ”๋“œ ๊ฐ’ ํ™•์ธ"); char a = 'a'; char b = 'A'; for (int i=0; i < 26;i++) { System.out.println(a+" : "+(int)a++ +","+b+" : "+(int)b++); } /* * ๋ณ€์ˆ˜ch์— ์ €์žฅ๋œ ๋ฌธ์ž๊ฐ€ ๋Œ€๋ฌธ์ž ์ธ ๊ฒฝ์šฐ์—๋งŒ ์†Œ๋ฌธ์ž๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ์ฝ”๋“œ */ Scanner scanner = new Scanner(System.in); System.out.println("๋ฌธ์ž์—ด์„ ์ž…๋ ฅํ•˜์„ธ์š”."); String msg = scanner.nextLine(); for (int i = 0; i<msg.length() ; i++) { char ch = msg.charAt(i); char s = (ch>='A' && ch<='Z') ? (char)(ch+32) : ch ; //system.out.print(ch + " => " + a); System.out.print(s); //์†Œ๋ฌธ์ž => ๋Œ€๋ฌธ์ž //๋Œ€๋ฌธ์ž => ์†Œ๋ฌธ์ž } } }
[ "user@DESKTOP-V882PTR" ]
user@DESKTOP-V882PTR
bedfce1447853c6acef882436c6f8f18425f579e
917af0e580db40cca786732b1598003ffe4ed90b
/Practice/src/udemy/Locators.java
5d91d75967b85e3ffb7066ddcc6f4bce79caa708
[]
no_license
TechR-Source/Practice
e72735c4367fbcc9446e5c35553db83a20110aac
1a8cf181377efcd207d65c3a9ecf55482a61350a
refs/heads/master
2020-04-22T10:37:37.003673
2019-03-26T10:18:09
2019-03-26T10:18:09
170,311,308
0
0
null
null
null
null
UTF-8
Java
false
false
991
java
package udemy; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Locators { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "D:/TL/BrowserDrivers/Chrome/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); //driver.get("https://www.google.com"); driver.get("http://127.0.0.1/m2ksk/"); System.out.println(driver.getTitle()); /*//Parent - Child Relationship driver.findElement(By.xpath("//div[@id='gbw']/div/div/div/div/a")).click(); //Xpath - //tagname[@attribute='value'] driver.findElement(By.xpath("//a[@class='gmail-nav__nav-link gmail-nav__nav-link__sign-in']")).click(); Thread.sleep(3000); //CSS Selector driver.findElement(By.xpath("//input[contains(@type,'email')]")).sendKeys("TestData"); }*/ }}
[ "innoppl@innoppl-PC" ]
innoppl@innoppl-PC