text
stringlengths
10
2.72M
package httpClient; import com.atlassian.tutorial.constant.Urls; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Test; public class JsonTest { @Test public void test() throws Exception { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(String.format(Urls.DEP_SEARCH_ALL_API,"测试")); request.addHeader("accept", "application/json"); //request.addHeader("Cookie","__spider__visitorid=f9d31f1112084ed0; UM_distinctid=177dd9ab83d636-0c895fc659464a-33687709-fa000-177dd9ab83e3d8; wdr-ticket=8da6e369b11e807d402632bca66ad517-7abb8c5f6a3c1bc454f11d28f9158c29; sso-ticket=03ef46d3ecb9d47845e21f3485fc2ccf-1226a6db34f7a928df46cb29549e978e; JSESSIONID=99469E1DD0CD80C66E35DAF58D8FAFE5"); HttpResponse response = client.execute(request); int total = Integer.valueOf(response.getHeaders("X-Total-Count")[0].getValue()); String json = IOUtils.toString(response.getEntity().getContent()); System.out.println(json); } }
package com.maspain.snake.entity; import com.maspain.snake.graphics.Sprite; import com.maspain.snake.level.PixelCoordinate; public class SnakeFood extends SnakeSegment { public SnakeFood(PixelCoordinate position) { super(position, Sprite.snakeFoodSprite); } }
package com.duanxr.yith.easy; import java.util.ArrayList; import java.util.List; /** * @author 段然 2021/5/11 */ public class ArmstrongNumber { /** * Given an integer n, return true if and only if it is an Armstrong number. * * The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n. * *   * * Example 1: * * Input: n = 153 * Output: true * Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33. * Example 2: * * Input: n = 123 * Output: false * Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36. *   * * Constraints: * * 1 <= n <= 108 * * 假设存在一个 k 位数 N,其每一位上的数字的 k 次幂的总和也是 N,那么这个数是阿姆斯特朗数。 * * 给你一个正整数 N,让你来判定他是否是阿姆斯特朗数,是则返回 true,不是则返回 false。 * *   * * 示例 1: * * 输入:153 * 输出:true * 示例: * 153 是一个 3 位数,且 153 = 1^3 + 5^3 + 3^3。 * 示例 2: * * 输入:123 * 输出:false * 解释: * 123 是一个 3 位数,且 123 != 1^3 + 2^3 + 3^3 = 36。 *   * * 提示: * * 1 <= N <= 10^8 * */ class Solution { public boolean isArmstrong(int n) { List<Integer> list = new ArrayList<>(); int tn = n; while (tn != 0) { list.add(tn % 10); tn /= 10; } int s = 0; for (Integer integer : list) { s += Math.pow(integer, list.size()); } return n == s; } } }
package org.simpleflatmapper.csv.parser; public class UnescapeCellPreProcessor extends CellPreProcessor { private final TextFormat textFormat; public UnescapeCellPreProcessor(TextFormat textFormat) { this.textFormat = textFormat; } public final void newCell(char[] chars, int start, int end, CellConsumer cellConsumer, int state) { if ((state & CharConsumer.ESCAPED) == 0) { cellConsumer.newCell(chars, start, end - start); } else { unescape(chars, start + 1, end, cellConsumer); } } private void unescape(final char[] chars, int start, int end, CellConsumer cellConsumer) { char escapeChar = textFormat.escapeChar; for(int i = start; i < end - 1; i++) { if (chars[i] == escapeChar) { int destIndex = i; boolean escaped = true; for(i = i +1 ;i < end; i++) { char c = chars[i]; if (c != escapeChar || escaped) { chars[destIndex++] = c; escaped = false; } else { escaped = true; } } cellConsumer.newCell(chars, start, destIndex - start); return; } } int l = end - start; if (l >0 && chars[end -1] == escapeChar) { l --; } cellConsumer.newCell(chars, start, l); } @Override public final boolean ignoreLeadingSpace() { return false; } }
package com.ak.profile_management.concepts; public class Location { String name; public Location(String name) { super(); this.name = name; } public Location() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.tencent.mm.modelvoiceaddr; import com.tencent.mm.e.b.c.a; import com.tencent.mm.sdk.platformtools.x; class f$1 implements a { short[] eqH; final /* synthetic */ f eqI; f$1(f fVar) { this.eqI = fVar; } public final void s(byte[] bArr, int i) { int i2 = 0; x.d("MicroMsg.SceneVoiceInputAddr", "OnRecPcmDataReady len: %s time: %s", new Object[]{Integer.valueOf(i), Long.valueOf(System.currentTimeMillis())}); if (this.eqH == null || this.eqH.length < i / 2) { this.eqH = new short[(i / 2)]; } while (i2 < i / 2) { this.eqH[i2] = (short) ((bArr[i2 * 2] & 255) | (bArr[(i2 * 2) + 1] << 8)); i2++; } f.a(this.eqI, this.eqH, i / 2); if (f.d(this.eqI) != null) { f.d(this.eqI).d(this.eqH, i / 2); return; } this.eqI.bs(9, -1); x.e("MicroMsg.SceneVoiceInputAddr", "mVoiceSilentDetectAPI is null"); } public final void aN(int i, int i2) { x.e("MicroMsg.SceneVoiceInputAddr", "onRecError state = %s detailState = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); this.eqI.bs(10, -1); } }
package training.preview_data; import routines.DataOperation; import routines.TalendDataGenerator; import routines.DataQuality; import routines.Relational; import routines.DataQualityDependencies; import routines.Mathematical; import routines.SQLike; import routines.Numeric; import routines.TalendStringUtil; import routines.TalendString; import routines.DQTechnical; import routines.MDM; import routines.StringHandling; import routines.DataMasking; import routines.TalendDate; import routines.DqStringHandling; import routines.system.*; import routines.system.api.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.math.BigDecimal; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Comparator; @SuppressWarnings("unused") /** * Job: Preview_Data Purpose: <br> * Description: <br> * @author * @version 7.1.1.20181026_1147 * @status */ public class Preview_Data implements TalendJob { protected static void logIgnoredError(String message, Throwable cause) { System.err.println(message); if (cause != null) { cause.printStackTrace(); } } public final Object obj = new Object(); // for transmiting parameters purpose private Object valueObject = null; public Object getValueObject() { return this.valueObject; } public void setValueObject(Object valueObject) { this.valueObject = valueObject; } private final static String defaultCharset = java.nio.charset.Charset .defaultCharset().name(); private final static String utf8Charset = "UTF-8"; // contains type for every context property public class PropertiesWithType extends java.util.Properties { private static final long serialVersionUID = 1L; private java.util.Map<String, String> propertyTypes = new java.util.HashMap<>(); public PropertiesWithType(java.util.Properties properties) { super(properties); } public PropertiesWithType() { super(); } public void setContextType(String key, String type) { propertyTypes.put(key, type); } public String getContextType(String key) { return propertyTypes.get(key); } } // create and load default properties private java.util.Properties defaultProps = new java.util.Properties(); // create application properties with default public class ContextProperties extends PropertiesWithType { private static final long serialVersionUID = 1L; public ContextProperties(java.util.Properties properties) { super(properties); } public ContextProperties() { super(); } public void synchronizeContext() { if (AdventureWorks2016_Schema != null) { this.setProperty("AdventureWorks2016_Schema", AdventureWorks2016_Schema.toString()); } if (AdventureWorks2016_Database != null) { this.setProperty("AdventureWorks2016_Database", AdventureWorks2016_Database.toString()); } if (AdventureWorks2016_Login != null) { this.setProperty("AdventureWorks2016_Login", AdventureWorks2016_Login.toString()); } if (AdventureWorks2016_Password != null) { this.setProperty("AdventureWorks2016_Password", AdventureWorks2016_Password.toString()); } if (AdventureWorks2016_AdditionalParams != null) { this.setProperty("AdventureWorks2016_AdditionalParams", AdventureWorks2016_AdditionalParams.toString()); } if (AdventureWorks2016_Server != null) { this.setProperty("AdventureWorks2016_Server", AdventureWorks2016_Server.toString()); } if (AdventureWorks2016_Port != null) { this.setProperty("AdventureWorks2016_Port", AdventureWorks2016_Port.toString()); } } public String AdventureWorks2016_Schema; public String getAdventureWorks2016_Schema() { return this.AdventureWorks2016_Schema; } public String AdventureWorks2016_Database; public String getAdventureWorks2016_Database() { return this.AdventureWorks2016_Database; } public String AdventureWorks2016_Login; public String getAdventureWorks2016_Login() { return this.AdventureWorks2016_Login; } public java.lang.String AdventureWorks2016_Password; public java.lang.String getAdventureWorks2016_Password() { return this.AdventureWorks2016_Password; } public String AdventureWorks2016_AdditionalParams; public String getAdventureWorks2016_AdditionalParams() { return this.AdventureWorks2016_AdditionalParams; } public String AdventureWorks2016_Server; public String getAdventureWorks2016_Server() { return this.AdventureWorks2016_Server; } public String AdventureWorks2016_Port; public String getAdventureWorks2016_Port() { return this.AdventureWorks2016_Port; } } private ContextProperties context = new ContextProperties(); public ContextProperties getContext() { return this.context; } private final String jobVersion = "null"; private final String jobName = "Preview_Data"; private final String projectName = "TRAINING"; public Integer errorCode = null; private String currentComponent = ""; private final java.util.Map<String, Object> globalMap = new java.util.HashMap<String, Object>(); private final static java.util.Map<String, Object> junitGlobalMap = new java.util.HashMap<String, Object>(); private final java.util.Map<String, Long> start_Hash = new java.util.HashMap<String, Long>(); private final java.util.Map<String, Long> end_Hash = new java.util.HashMap<String, Long>(); private final java.util.Map<String, Boolean> ok_Hash = new java.util.HashMap<String, Boolean>(); public final java.util.List<String[]> globalBuffer = new java.util.ArrayList<String[]>(); // OSGi DataSource private final static String KEY_DB_DATASOURCES = "KEY_DB_DATASOURCES"; private final static String KEY_DB_DATASOURCES_RAW = "KEY_DB_DATASOURCES_RAW"; public void setDataSources( java.util.Map<String, javax.sql.DataSource> dataSources) { java.util.Map<String, routines.system.TalendDataSource> talendDataSources = new java.util.HashMap<String, routines.system.TalendDataSource>(); for (java.util.Map.Entry<String, javax.sql.DataSource> dataSourceEntry : dataSources .entrySet()) { talendDataSources.put( dataSourceEntry.getKey(), new routines.system.TalendDataSource(dataSourceEntry .getValue())); } globalMap.put(KEY_DB_DATASOURCES, talendDataSources); globalMap .put(KEY_DB_DATASOURCES_RAW, new java.util.HashMap<String, javax.sql.DataSource>( dataSources)); } private final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); private final java.io.PrintStream errorMessagePS = new java.io.PrintStream( new java.io.BufferedOutputStream(baos)); public String getExceptionStackTrace() { if ("failure".equals(this.getStatus())) { errorMessagePS.flush(); return baos.toString(); } return null; } private Exception exception; public Exception getException() { if ("failure".equals(this.getStatus())) { return this.exception; } return null; } private class TalendException extends Exception { private static final long serialVersionUID = 1L; private java.util.Map<String, Object> globalMap = null; private Exception e = null; private String currentComponent = null; private String virtualComponentName = null; public void setVirtualComponentName(String virtualComponentName) { this.virtualComponentName = virtualComponentName; } private TalendException(Exception e, String errorComponent, final java.util.Map<String, Object> globalMap) { this.currentComponent = errorComponent; this.globalMap = globalMap; this.e = e; } public Exception getException() { return this.e; } public String getCurrentComponent() { return this.currentComponent; } public String getExceptionCauseMessage(Exception e) { Throwable cause = e; String message = null; int i = 10; while (null != cause && 0 < i--) { message = cause.getMessage(); if (null == message) { cause = cause.getCause(); } else { break; } } if (null == message) { message = e.getClass().getName(); } return message; } @Override public void printStackTrace() { if (!(e instanceof TalendException || e instanceof TDieException)) { if (virtualComponentName != null && currentComponent.indexOf(virtualComponentName + "_") == 0) { globalMap.put(virtualComponentName + "_ERROR_MESSAGE", getExceptionCauseMessage(e)); } globalMap.put(currentComponent + "_ERROR_MESSAGE", getExceptionCauseMessage(e)); System.err.println("Exception in component " + currentComponent + " (" + jobName + ")"); } if (!(e instanceof TDieException)) { if (e instanceof TalendException) { e.printStackTrace(); } else { e.printStackTrace(); e.printStackTrace(errorMessagePS); Preview_Data.this.exception = e; } } if (!(e instanceof TalendException)) { try { for (java.lang.reflect.Method m : this.getClass() .getEnclosingClass().getMethods()) { if (m.getName().compareTo(currentComponent + "_error") == 0) { m.invoke(Preview_Data.this, new Object[] { e, currentComponent, globalMap }); break; } } if (!(e instanceof TDieException)) { } } catch (Exception e) { this.e.printStackTrace(); } } } } public void tDBInput_1_error(Exception exception, String errorComponent, final java.util.Map<String, Object> globalMap) throws TalendException { end_Hash.put(errorComponent, System.currentTimeMillis()); status = "failure"; tDBInput_1_onSubJobError(exception, errorComponent, globalMap); } public void tJavaRow_gen_error(Exception exception, String errorComponent, final java.util.Map<String, Object> globalMap) throws TalendException { end_Hash.put(errorComponent, System.currentTimeMillis()); status = "failure"; tDBInput_1_onSubJobError(exception, errorComponent, globalMap); } public void tSocketOutput_gen_error(Exception exception, String errorComponent, final java.util.Map<String, Object> globalMap) throws TalendException { end_Hash.put(errorComponent, System.currentTimeMillis()); status = "failure"; tDBInput_1_onSubJobError(exception, errorComponent, globalMap); } public void tDBInput_1_onSubJobError(Exception exception, String errorComponent, final java.util.Map<String, Object> globalMap) throws TalendException { resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", Thread .currentThread().getId() + "", "FATAL", "", exception.getMessage(), ResumeUtil.getExceptionStackTrace(exception), ""); } public static class rowDataFromtJavaRow_genStruct implements routines.system.IPersistableRow<rowDataFromtJavaRow_genStruct> { final static byte[] commonByteArrayLock_TRAINING_Preview_Data = new byte[0]; static byte[] commonByteArray_TRAINING_Preview_Data = new byte[0]; protected static final int DEFAULT_HASHCODE = 1; protected static final int PRIME = 31; protected int hashCode = DEFAULT_HASHCODE; public boolean hashCodeDirty = true; public String loopKey; public int AddressID; public int getAddressID() { return this.AddressID; } public String AddressLine1; public String getAddressLine1() { return this.AddressLine1; } public String AddressLine2; public String getAddressLine2() { return this.AddressLine2; } public String City; public String getCity() { return this.City; } public int StateProvinceID; public int getStateProvinceID() { return this.StateProvinceID; } public String PostalCode; public String getPostalCode() { return this.PostalCode; } public String SpatialLocation; public String getSpatialLocation() { return this.SpatialLocation; } public Object rowguid; public Object getRowguid() { return this.rowguid; } public java.util.Date ModifiedDate; public java.util.Date getModifiedDate() { return this.ModifiedDate; } @Override public int hashCode() { if (this.hashCodeDirty) { final int prime = PRIME; int result = DEFAULT_HASHCODE; result = prime * result + (int) this.AddressID; this.hashCode = result; this.hashCodeDirty = false; } return this.hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final rowDataFromtJavaRow_genStruct other = (rowDataFromtJavaRow_genStruct) obj; if (this.AddressID != other.AddressID) return false; return true; } public void copyDataTo(rowDataFromtJavaRow_genStruct other) { other.AddressID = this.AddressID; other.AddressLine1 = this.AddressLine1; other.AddressLine2 = this.AddressLine2; other.City = this.City; other.StateProvinceID = this.StateProvinceID; other.PostalCode = this.PostalCode; other.SpatialLocation = this.SpatialLocation; other.rowguid = this.rowguid; other.ModifiedDate = this.ModifiedDate; } public void copyKeysDataTo(rowDataFromtJavaRow_genStruct other) { other.AddressID = this.AddressID; } private String readString(ObjectInputStream dis) throws IOException { String strReturn = null; int length = 0; length = dis.readInt(); if (length == -1) { strReturn = null; } else { if (length > commonByteArray_TRAINING_Preview_Data.length) { if (length < 1024 && commonByteArray_TRAINING_Preview_Data.length == 0) { commonByteArray_TRAINING_Preview_Data = new byte[1024]; } else { commonByteArray_TRAINING_Preview_Data = new byte[2 * length]; } } dis.readFully(commonByteArray_TRAINING_Preview_Data, 0, length); strReturn = new String(commonByteArray_TRAINING_Preview_Data, 0, length, utf8Charset); } return strReturn; } private void writeString(String str, ObjectOutputStream dos) throws IOException { if (str == null) { dos.writeInt(-1); } else { byte[] byteArray = str.getBytes(utf8Charset); dos.writeInt(byteArray.length); dos.write(byteArray); } } private java.util.Date readDate(ObjectInputStream dis) throws IOException { java.util.Date dateReturn = null; int length = 0; length = dis.readByte(); if (length == -1) { dateReturn = null; } else { dateReturn = new Date(dis.readLong()); } return dateReturn; } private void writeDate(java.util.Date date1, ObjectOutputStream dos) throws IOException { if (date1 == null) { dos.writeByte(-1); } else { dos.writeByte(0); dos.writeLong(date1.getTime()); } } public void readData(ObjectInputStream dis) { synchronized (commonByteArrayLock_TRAINING_Preview_Data) { try { int length = 0; this.AddressID = dis.readInt(); this.AddressLine1 = readString(dis); this.AddressLine2 = readString(dis); this.City = readString(dis); this.StateProvinceID = dis.readInt(); this.PostalCode = readString(dis); this.SpatialLocation = readString(dis); this.rowguid = (Object) dis.readObject(); this.ModifiedDate = readDate(dis); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException eCNFE) { throw new RuntimeException(eCNFE); } } } public void writeData(ObjectOutputStream dos) { try { // int dos.writeInt(this.AddressID); // String writeString(this.AddressLine1, dos); // String writeString(this.AddressLine2, dos); // String writeString(this.City, dos); // int dos.writeInt(this.StateProvinceID); // String writeString(this.PostalCode, dos); // String writeString(this.SpatialLocation, dos); // Object dos.writeObject(this.rowguid); // java.util.Date writeDate(this.ModifiedDate, dos); } catch (IOException e) { throw new RuntimeException(e); } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("["); sb.append("AddressID=" + String.valueOf(AddressID)); sb.append(",AddressLine1=" + AddressLine1); sb.append(",AddressLine2=" + AddressLine2); sb.append(",City=" + City); sb.append(",StateProvinceID=" + String.valueOf(StateProvinceID)); sb.append(",PostalCode=" + PostalCode); sb.append(",SpatialLocation=" + SpatialLocation); sb.append(",rowguid=" + String.valueOf(rowguid)); sb.append(",ModifiedDate=" + String.valueOf(ModifiedDate)); sb.append("]"); return sb.toString(); } /** * Compare keys */ public int compareTo(rowDataFromtJavaRow_genStruct other) { int returnValue = -1; returnValue = checkNullsAndCompare(this.AddressID, other.AddressID); if (returnValue != 0) { return returnValue; } return returnValue; } private int checkNullsAndCompare(Object object1, Object object2) { int returnValue = 0; if (object1 instanceof Comparable && object2 instanceof Comparable) { returnValue = ((Comparable) object1).compareTo(object2); } else if (object1 != null && object2 != null) { returnValue = compareStrings(object1.toString(), object2.toString()); } else if (object1 == null && object2 != null) { returnValue = 1; } else if (object1 != null && object2 == null) { returnValue = -1; } else { returnValue = 0; } return returnValue; } private int compareStrings(String string1, String string2) { return string1.compareTo(string2); } } public static class rowDataFromtDBInput_1Struct implements routines.system.IPersistableRow<rowDataFromtDBInput_1Struct> { final static byte[] commonByteArrayLock_TRAINING_Preview_Data = new byte[0]; static byte[] commonByteArray_TRAINING_Preview_Data = new byte[0]; protected static final int DEFAULT_HASHCODE = 1; protected static final int PRIME = 31; protected int hashCode = DEFAULT_HASHCODE; public boolean hashCodeDirty = true; public String loopKey; public int AddressID; public int getAddressID() { return this.AddressID; } public String AddressLine1; public String getAddressLine1() { return this.AddressLine1; } public String AddressLine2; public String getAddressLine2() { return this.AddressLine2; } public String City; public String getCity() { return this.City; } public int StateProvinceID; public int getStateProvinceID() { return this.StateProvinceID; } public String PostalCode; public String getPostalCode() { return this.PostalCode; } public String SpatialLocation; public String getSpatialLocation() { return this.SpatialLocation; } public Object rowguid; public Object getRowguid() { return this.rowguid; } public java.util.Date ModifiedDate; public java.util.Date getModifiedDate() { return this.ModifiedDate; } @Override public int hashCode() { if (this.hashCodeDirty) { final int prime = PRIME; int result = DEFAULT_HASHCODE; result = prime * result + (int) this.AddressID; this.hashCode = result; this.hashCodeDirty = false; } return this.hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final rowDataFromtDBInput_1Struct other = (rowDataFromtDBInput_1Struct) obj; if (this.AddressID != other.AddressID) return false; return true; } public void copyDataTo(rowDataFromtDBInput_1Struct other) { other.AddressID = this.AddressID; other.AddressLine1 = this.AddressLine1; other.AddressLine2 = this.AddressLine2; other.City = this.City; other.StateProvinceID = this.StateProvinceID; other.PostalCode = this.PostalCode; other.SpatialLocation = this.SpatialLocation; other.rowguid = this.rowguid; other.ModifiedDate = this.ModifiedDate; } public void copyKeysDataTo(rowDataFromtDBInput_1Struct other) { other.AddressID = this.AddressID; } private String readString(ObjectInputStream dis) throws IOException { String strReturn = null; int length = 0; length = dis.readInt(); if (length == -1) { strReturn = null; } else { if (length > commonByteArray_TRAINING_Preview_Data.length) { if (length < 1024 && commonByteArray_TRAINING_Preview_Data.length == 0) { commonByteArray_TRAINING_Preview_Data = new byte[1024]; } else { commonByteArray_TRAINING_Preview_Data = new byte[2 * length]; } } dis.readFully(commonByteArray_TRAINING_Preview_Data, 0, length); strReturn = new String(commonByteArray_TRAINING_Preview_Data, 0, length, utf8Charset); } return strReturn; } private void writeString(String str, ObjectOutputStream dos) throws IOException { if (str == null) { dos.writeInt(-1); } else { byte[] byteArray = str.getBytes(utf8Charset); dos.writeInt(byteArray.length); dos.write(byteArray); } } private java.util.Date readDate(ObjectInputStream dis) throws IOException { java.util.Date dateReturn = null; int length = 0; length = dis.readByte(); if (length == -1) { dateReturn = null; } else { dateReturn = new Date(dis.readLong()); } return dateReturn; } private void writeDate(java.util.Date date1, ObjectOutputStream dos) throws IOException { if (date1 == null) { dos.writeByte(-1); } else { dos.writeByte(0); dos.writeLong(date1.getTime()); } } public void readData(ObjectInputStream dis) { synchronized (commonByteArrayLock_TRAINING_Preview_Data) { try { int length = 0; this.AddressID = dis.readInt(); this.AddressLine1 = readString(dis); this.AddressLine2 = readString(dis); this.City = readString(dis); this.StateProvinceID = dis.readInt(); this.PostalCode = readString(dis); this.SpatialLocation = readString(dis); this.rowguid = (Object) dis.readObject(); this.ModifiedDate = readDate(dis); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException eCNFE) { throw new RuntimeException(eCNFE); } } } public void writeData(ObjectOutputStream dos) { try { // int dos.writeInt(this.AddressID); // String writeString(this.AddressLine1, dos); // String writeString(this.AddressLine2, dos); // String writeString(this.City, dos); // int dos.writeInt(this.StateProvinceID); // String writeString(this.PostalCode, dos); // String writeString(this.SpatialLocation, dos); // Object dos.writeObject(this.rowguid); // java.util.Date writeDate(this.ModifiedDate, dos); } catch (IOException e) { throw new RuntimeException(e); } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append("["); sb.append("AddressID=" + String.valueOf(AddressID)); sb.append(",AddressLine1=" + AddressLine1); sb.append(",AddressLine2=" + AddressLine2); sb.append(",City=" + City); sb.append(",StateProvinceID=" + String.valueOf(StateProvinceID)); sb.append(",PostalCode=" + PostalCode); sb.append(",SpatialLocation=" + SpatialLocation); sb.append(",rowguid=" + String.valueOf(rowguid)); sb.append(",ModifiedDate=" + String.valueOf(ModifiedDate)); sb.append("]"); return sb.toString(); } /** * Compare keys */ public int compareTo(rowDataFromtDBInput_1Struct other) { int returnValue = -1; returnValue = checkNullsAndCompare(this.AddressID, other.AddressID); if (returnValue != 0) { return returnValue; } return returnValue; } private int checkNullsAndCompare(Object object1, Object object2) { int returnValue = 0; if (object1 instanceof Comparable && object2 instanceof Comparable) { returnValue = ((Comparable) object1).compareTo(object2); } else if (object1 != null && object2 != null) { returnValue = compareStrings(object1.toString(), object2.toString()); } else if (object1 == null && object2 != null) { returnValue = 1; } else if (object1 != null && object2 == null) { returnValue = -1; } else { returnValue = 0; } return returnValue; } private int compareStrings(String string1, String string2) { return string1.compareTo(string2); } } public void tDBInput_1Process(final java.util.Map<String, Object> globalMap) throws TalendException { globalMap.put("tDBInput_1_SUBPROCESS_STATE", 0); final boolean execStat = this.execStat; String iterateId = ""; String currentComponent = ""; java.util.Map<String, Object> resourceMap = new java.util.HashMap<String, Object>(); try { // TDI-39566 avoid throwing an useless Exception boolean resumeIt = true; if (globalResumeTicket == false && resumeEntryMethodName != null) { String currentMethodName = new java.lang.Exception() .getStackTrace()[0].getMethodName(); resumeIt = resumeEntryMethodName.equals(currentMethodName); } if (resumeIt || globalResumeTicket) { // start the resume globalResumeTicket = true; rowDataFromtDBInput_1Struct rowDataFromtDBInput_1 = new rowDataFromtDBInput_1Struct(); rowDataFromtJavaRow_genStruct rowDataFromtJavaRow_gen = new rowDataFromtJavaRow_genStruct(); /** * [tSocketOutput_gen begin ] start */ ok_Hash.put("tSocketOutput_gen", false); start_Hash.put("tSocketOutput_gen", System.currentTimeMillis()); currentComponent = "tSocketOutput_gen"; int tos_count_tSocketOutput_gen = 0; java.net.Socket sockettSocketOutput_gen = null; int nb_line_tSocketOutput_gen = 0; boolean retrytSocketOutput_gen = true; java.net.ConnectException exception_tSocketOutput_gen = null; for (int i = 0; i < 10 - 1; i++) { if (retrytSocketOutput_gen) { try { sockettSocketOutput_gen = new java.net.Socket( "127.0.0.1", 44716); retrytSocketOutput_gen = false; } catch (java.net.ConnectException etSocketOutput_gen) { exception_tSocketOutput_gen = etSocketOutput_gen; Thread.sleep(1000); } } } if (retrytSocketOutput_gen && (exception_tSocketOutput_gen != null)) { throw exception_tSocketOutput_gen; } com.talend.csv.CSVWriter CsvWritertSocketOutput_gen = new com.talend.csv.CSVWriter( new java.io.BufferedWriter( new java.io.OutputStreamWriter( sockettSocketOutput_gen .getOutputStream(), "UTF-8"))); CsvWritertSocketOutput_gen.setSeparator(';'); /** * [tSocketOutput_gen begin ] stop */ /** * [tJavaRow_gen begin ] start */ ok_Hash.put("tJavaRow_gen", false); start_Hash.put("tJavaRow_gen", System.currentTimeMillis()); currentComponent = "tJavaRow_gen"; int tos_count_tJavaRow_gen = 0; int nb_line_tJavaRow_gen = 0; /** * [tJavaRow_gen begin ] stop */ /** * [tDBInput_1 begin ] start */ ok_Hash.put("tDBInput_1", false); start_Hash.put("tDBInput_1", System.currentTimeMillis()); currentComponent = "tDBInput_1"; int tos_count_tDBInput_1 = 0; org.talend.designer.components.util.mssql.MSSqlGenerateTimestampUtil mssqlGTU_tDBInput_1 = org.talend.designer.components.util.mssql.MSSqlUtilFactory .getMSSqlGenerateTimestampUtil(); java.util.List<String> talendToDBList_tDBInput_1 = new java.util.ArrayList(); String[] talendToDBArray_tDBInput_1 = new String[] { "FLOAT", "NUMERIC", "NUMERIC IDENTITY", "DECIMAL", "DECIMAL IDENTITY", "REAL" }; java.util.Collections.addAll(talendToDBList_tDBInput_1, talendToDBArray_tDBInput_1); int nb_line_tDBInput_1 = 0; java.sql.Connection conn_tDBInput_1 = null; String driverClass_tDBInput_1 = "net.sourceforge.jtds.jdbc.Driver"; java.lang.Class.forName(driverClass_tDBInput_1); String dbUser_tDBInput_1 = context.AdventureWorks2016_Login; final String decryptedPassword_tDBInput_1 = context.AdventureWorks2016_Password; String dbPwd_tDBInput_1 = decryptedPassword_tDBInput_1; String port_tDBInput_1 = context.AdventureWorks2016_Port; String dbname_tDBInput_1 = context.AdventureWorks2016_Database; String url_tDBInput_1 = "jdbc:jtds:sqlserver://" + context.AdventureWorks2016_Server; if (!"".equals(port_tDBInput_1)) { url_tDBInput_1 += ":" + context.AdventureWorks2016_Port; } if (!"".equals(dbname_tDBInput_1)) { url_tDBInput_1 += "//" + context.AdventureWorks2016_Database; } url_tDBInput_1 += ";appName=" + projectName + ";" + context.AdventureWorks2016_AdditionalParams; String dbschema_tDBInput_1 = context.AdventureWorks2016_Schema; conn_tDBInput_1 = java.sql.DriverManager.getConnection( url_tDBInput_1, dbUser_tDBInput_1, dbPwd_tDBInput_1); java.sql.Statement stmt_tDBInput_1 = conn_tDBInput_1 .createStatement(); String dbquery_tDBInput_1 = "SELECT [AddressID]\n ,[AddressLine1]\n ,[AddressLine2]\n ,[City]\n ,[StateProvinceID]\n ,[Post" + "alCode]\n ,[SpatialLocation]\n ,[rowguid]\n ,[ModifiedDate]\n FROM [Person].[Address]"; globalMap.put("tDBInput_1_QUERY", dbquery_tDBInput_1); java.sql.ResultSet rs_tDBInput_1 = null; try { rs_tDBInput_1 = stmt_tDBInput_1 .executeQuery(dbquery_tDBInput_1); java.sql.ResultSetMetaData rsmd_tDBInput_1 = rs_tDBInput_1 .getMetaData(); int colQtyInRs_tDBInput_1 = rsmd_tDBInput_1 .getColumnCount(); String tmpContent_tDBInput_1 = null; while (rs_tDBInput_1.next()) { nb_line_tDBInput_1++; if (colQtyInRs_tDBInput_1 < 1) { rowDataFromtDBInput_1.AddressID = 0; } else { if (rs_tDBInput_1.getObject(1) != null) { rowDataFromtDBInput_1.AddressID = rs_tDBInput_1 .getInt(1); } else { throw new RuntimeException( "Null value in non-Nullable column"); } } if (colQtyInRs_tDBInput_1 < 2) { rowDataFromtDBInput_1.AddressLine1 = null; } else { tmpContent_tDBInput_1 = rs_tDBInput_1.getString(2); if (tmpContent_tDBInput_1 != null) { if (talendToDBList_tDBInput_1 .contains(rsmd_tDBInput_1 .getColumnTypeName(2) .toUpperCase( java.util.Locale.ENGLISH))) { rowDataFromtDBInput_1.AddressLine1 = FormatterUtils .formatUnwithE(tmpContent_tDBInput_1); } else { rowDataFromtDBInput_1.AddressLine1 = tmpContent_tDBInput_1; } } else { rowDataFromtDBInput_1.AddressLine1 = null; } } if (colQtyInRs_tDBInput_1 < 3) { rowDataFromtDBInput_1.AddressLine2 = null; } else { tmpContent_tDBInput_1 = rs_tDBInput_1.getString(3); if (tmpContent_tDBInput_1 != null) { if (talendToDBList_tDBInput_1 .contains(rsmd_tDBInput_1 .getColumnTypeName(3) .toUpperCase( java.util.Locale.ENGLISH))) { rowDataFromtDBInput_1.AddressLine2 = FormatterUtils .formatUnwithE(tmpContent_tDBInput_1); } else { rowDataFromtDBInput_1.AddressLine2 = tmpContent_tDBInput_1; } } else { rowDataFromtDBInput_1.AddressLine2 = null; } } if (colQtyInRs_tDBInput_1 < 4) { rowDataFromtDBInput_1.City = null; } else { tmpContent_tDBInput_1 = rs_tDBInput_1.getString(4); if (tmpContent_tDBInput_1 != null) { if (talendToDBList_tDBInput_1 .contains(rsmd_tDBInput_1 .getColumnTypeName(4) .toUpperCase( java.util.Locale.ENGLISH))) { rowDataFromtDBInput_1.City = FormatterUtils .formatUnwithE(tmpContent_tDBInput_1); } else { rowDataFromtDBInput_1.City = tmpContent_tDBInput_1; } } else { rowDataFromtDBInput_1.City = null; } } if (colQtyInRs_tDBInput_1 < 5) { rowDataFromtDBInput_1.StateProvinceID = 0; } else { if (rs_tDBInput_1.getObject(5) != null) { rowDataFromtDBInput_1.StateProvinceID = rs_tDBInput_1 .getInt(5); } else { throw new RuntimeException( "Null value in non-Nullable column"); } } if (colQtyInRs_tDBInput_1 < 6) { rowDataFromtDBInput_1.PostalCode = null; } else { tmpContent_tDBInput_1 = rs_tDBInput_1.getString(6); if (tmpContent_tDBInput_1 != null) { if (talendToDBList_tDBInput_1 .contains(rsmd_tDBInput_1 .getColumnTypeName(6) .toUpperCase( java.util.Locale.ENGLISH))) { rowDataFromtDBInput_1.PostalCode = FormatterUtils .formatUnwithE(tmpContent_tDBInput_1); } else { rowDataFromtDBInput_1.PostalCode = tmpContent_tDBInput_1; } } else { rowDataFromtDBInput_1.PostalCode = null; } } if (colQtyInRs_tDBInput_1 < 7) { rowDataFromtDBInput_1.SpatialLocation = null; } else { tmpContent_tDBInput_1 = rs_tDBInput_1.getString(7); if (tmpContent_tDBInput_1 != null) { if (talendToDBList_tDBInput_1 .contains(rsmd_tDBInput_1 .getColumnTypeName(7) .toUpperCase( java.util.Locale.ENGLISH))) { rowDataFromtDBInput_1.SpatialLocation = FormatterUtils .formatUnwithE(tmpContent_tDBInput_1); } else { rowDataFromtDBInput_1.SpatialLocation = tmpContent_tDBInput_1; } } else { rowDataFromtDBInput_1.SpatialLocation = null; } } if (colQtyInRs_tDBInput_1 < 8) { rowDataFromtDBInput_1.rowguid = null; } else { if (rs_tDBInput_1.getObject(8) != null) { rowDataFromtDBInput_1.rowguid = rs_tDBInput_1 .getObject(8); } else { throw new RuntimeException( "Null value in non-Nullable column"); } } if (colQtyInRs_tDBInput_1 < 9) { rowDataFromtDBInput_1.ModifiedDate = null; } else { rowDataFromtDBInput_1.ModifiedDate = mssqlGTU_tDBInput_1 .getDate(rsmd_tDBInput_1, rs_tDBInput_1, 9); } /** * [tDBInput_1 begin ] stop */ /** * [tDBInput_1 main ] start */ currentComponent = "tDBInput_1"; tos_count_tDBInput_1++; /** * [tDBInput_1 main ] stop */ /** * [tDBInput_1 process_data_begin ] start */ currentComponent = "tDBInput_1"; /** * [tDBInput_1 process_data_begin ] stop */ /** * [tJavaRow_gen main ] start */ currentComponent = "tJavaRow_gen"; rowDataFromtJavaRow_gen.AddressID = rowDataFromtDBInput_1.AddressID; rowDataFromtJavaRow_gen.AddressLine1 = rowDataFromtDBInput_1.AddressLine1; rowDataFromtJavaRow_gen.AddressLine2 = rowDataFromtDBInput_1.AddressLine2; rowDataFromtJavaRow_gen.City = rowDataFromtDBInput_1.City; rowDataFromtJavaRow_gen.StateProvinceID = rowDataFromtDBInput_1.StateProvinceID; rowDataFromtJavaRow_gen.PostalCode = rowDataFromtDBInput_1.PostalCode; rowDataFromtJavaRow_gen.SpatialLocation = rowDataFromtDBInput_1.SpatialLocation; rowDataFromtJavaRow_gen.rowguid = rowDataFromtDBInput_1.rowguid; rowDataFromtJavaRow_gen.ModifiedDate = rowDataFromtDBInput_1.ModifiedDate; if (nb_line_tJavaRow_gen >= 1000) { break; } nb_line_tJavaRow_gen++; tos_count_tJavaRow_gen++; /** * [tJavaRow_gen main ] stop */ /** * [tJavaRow_gen process_data_begin ] start */ currentComponent = "tJavaRow_gen"; /** * [tJavaRow_gen process_data_begin ] stop */ /** * [tSocketOutput_gen main ] start */ currentComponent = "tSocketOutput_gen"; CsvWritertSocketOutput_gen.setEscapeChar('\\'); CsvWritertSocketOutput_gen.setQuoteChar('"'); CsvWritertSocketOutput_gen .setQuoteStatus(com.talend.csv.CSVWriter.QuoteStatus.FORCE); String[] rowtSocketOutput_gen = new String[9]; rowtSocketOutput_gen[0] = String .valueOf(rowDataFromtJavaRow_gen.AddressID); if (rowDataFromtJavaRow_gen.AddressLine1 == null) { rowtSocketOutput_gen[1] = ""; } else { rowtSocketOutput_gen[1] = rowDataFromtJavaRow_gen.AddressLine1; } if (rowDataFromtJavaRow_gen.AddressLine2 == null) { rowtSocketOutput_gen[2] = ""; } else { rowtSocketOutput_gen[2] = rowDataFromtJavaRow_gen.AddressLine2; } if (rowDataFromtJavaRow_gen.City == null) { rowtSocketOutput_gen[3] = ""; } else { rowtSocketOutput_gen[3] = rowDataFromtJavaRow_gen.City; } rowtSocketOutput_gen[4] = String .valueOf(rowDataFromtJavaRow_gen.StateProvinceID); if (rowDataFromtJavaRow_gen.PostalCode == null) { rowtSocketOutput_gen[5] = ""; } else { rowtSocketOutput_gen[5] = rowDataFromtJavaRow_gen.PostalCode; } if (rowDataFromtJavaRow_gen.SpatialLocation == null) { rowtSocketOutput_gen[6] = ""; } else { rowtSocketOutput_gen[6] = rowDataFromtJavaRow_gen.SpatialLocation; } if (rowDataFromtJavaRow_gen.rowguid == null) { rowtSocketOutput_gen[7] = ""; } else { rowtSocketOutput_gen[7] = String .valueOf(rowDataFromtJavaRow_gen.rowguid); } if (rowDataFromtJavaRow_gen.ModifiedDate == null) { rowtSocketOutput_gen[8] = ""; } else { rowtSocketOutput_gen[8] = FormatterUtils .format_Date( rowDataFromtJavaRow_gen.ModifiedDate, "dd-MM-yyyy"); } CsvWritertSocketOutput_gen .writeNext(rowtSocketOutput_gen); CsvWritertSocketOutput_gen.flush(); nb_line_tSocketOutput_gen++; tos_count_tSocketOutput_gen++; /** * [tSocketOutput_gen main ] stop */ /** * [tSocketOutput_gen process_data_begin ] start */ currentComponent = "tSocketOutput_gen"; /** * [tSocketOutput_gen process_data_begin ] stop */ /** * [tSocketOutput_gen process_data_end ] start */ currentComponent = "tSocketOutput_gen"; /** * [tSocketOutput_gen process_data_end ] stop */ /** * [tJavaRow_gen process_data_end ] start */ currentComponent = "tJavaRow_gen"; /** * [tJavaRow_gen process_data_end ] stop */ /** * [tDBInput_1 process_data_end ] start */ currentComponent = "tDBInput_1"; /** * [tDBInput_1 process_data_end ] stop */ /** * [tDBInput_1 end ] start */ currentComponent = "tDBInput_1"; } } finally { if (rs_tDBInput_1 != null) { rs_tDBInput_1.close(); } if (stmt_tDBInput_1 != null) { stmt_tDBInput_1.close(); } if (conn_tDBInput_1 != null && !conn_tDBInput_1.isClosed()) { conn_tDBInput_1.close(); } } globalMap.put("tDBInput_1_NB_LINE", nb_line_tDBInput_1); ok_Hash.put("tDBInput_1", true); end_Hash.put("tDBInput_1", System.currentTimeMillis()); /** * [tDBInput_1 end ] stop */ /** * [tJavaRow_gen end ] start */ currentComponent = "tJavaRow_gen"; globalMap.put("tJavaRow_gen_NB_LINE", nb_line_tJavaRow_gen); ok_Hash.put("tJavaRow_gen", true); end_Hash.put("tJavaRow_gen", System.currentTimeMillis()); /** * [tJavaRow_gen end ] stop */ /** * [tSocketOutput_gen end ] start */ currentComponent = "tSocketOutput_gen"; if (sockettSocketOutput_gen != null) { sockettSocketOutput_gen.close(); } if (CsvWritertSocketOutput_gen != null) { CsvWritertSocketOutput_gen.close(); } globalMap.put("tSocketOutput_gen_NB_LINE", nb_line_tSocketOutput_gen); ok_Hash.put("tSocketOutput_gen", true); end_Hash.put("tSocketOutput_gen", System.currentTimeMillis()); /** * [tSocketOutput_gen end ] stop */ }// end the resume } catch (java.lang.Exception e) { TalendException te = new TalendException(e, currentComponent, globalMap); throw te; } catch (java.lang.Error error) { throw error; } finally { try { /** * [tDBInput_1 finally ] start */ currentComponent = "tDBInput_1"; /** * [tDBInput_1 finally ] stop */ /** * [tJavaRow_gen finally ] start */ currentComponent = "tJavaRow_gen"; /** * [tJavaRow_gen finally ] stop */ /** * [tSocketOutput_gen finally ] start */ currentComponent = "tSocketOutput_gen"; /** * [tSocketOutput_gen finally ] stop */ } catch (java.lang.Exception e) { // ignore } catch (java.lang.Error error) { // ignore } resourceMap = null; } globalMap.put("tDBInput_1_SUBPROCESS_STATE", 1); } public String resuming_logs_dir_path = null; public String resuming_checkpoint_path = null; public String parent_part_launcher = null; private String resumeEntryMethodName = null; private boolean globalResumeTicket = false; public boolean watch = false; // portStats is null, it means don't execute the statistics public Integer portStats = null; public int portTraces = 4334; public String clientHost; public String defaultClientHost = "localhost"; public String contextStr = "Default"; public boolean isDefaultContext = true; public String pid = "0"; public String rootPid = null; public String fatherPid = null; public String fatherNode = null; public long startTime = 0; public boolean isChildJob = false; public String log4jLevel = ""; private boolean execStat = true; private ThreadLocal<java.util.Map<String, String>> threadLocal = new ThreadLocal<java.util.Map<String, String>>() { protected java.util.Map<String, String> initialValue() { java.util.Map<String, String> threadRunResultMap = new java.util.HashMap<String, String>(); threadRunResultMap.put("errorCode", null); threadRunResultMap.put("status", ""); return threadRunResultMap; }; }; private PropertiesWithType context_param = new PropertiesWithType(); public java.util.Map<String, Object> parentContextMap = new java.util.HashMap<String, Object>(); public String status = ""; public static void main(String[] args) { final Preview_Data Preview_DataClass = new Preview_Data(); int exitCode = Preview_DataClass.runJobInTOS(args); System.exit(exitCode); } public String[][] runJob(String[] args) { int exitCode = runJobInTOS(args); String[][] bufferValue = new String[][] { { Integer.toString(exitCode) } }; return bufferValue; } public boolean hastBufferOutputComponent() { boolean hastBufferOutput = false; return hastBufferOutput; } public int runJobInTOS(String[] args) { // reset status status = ""; String lastStr = ""; for (String arg : args) { if (arg.equalsIgnoreCase("--context_param")) { lastStr = arg; } else if (lastStr.equals("")) { evalParam(arg); } else { evalParam(lastStr + " " + arg); lastStr = ""; } } if (clientHost == null) { clientHost = defaultClientHost; } if (pid == null || "0".equals(pid)) { pid = TalendString.getAsciiRandomString(6); } if (rootPid == null) { rootPid = pid; } if (fatherPid == null) { fatherPid = pid; } else { isChildJob = true; } try { // call job/subjob with an existing context, like: // --context=production. if without this parameter, there will use // the default context instead. java.io.InputStream inContext = Preview_Data.class.getClassLoader() .getResourceAsStream( "training/preview_data/contexts/" + contextStr + ".properties"); if (inContext == null) { inContext = Preview_Data.class .getClassLoader() .getResourceAsStream( "config/contexts/" + contextStr + ".properties"); } if (inContext != null) { // defaultProps is in order to keep the original context value defaultProps.load(inContext); inContext.close(); context = new ContextProperties(defaultProps); } else if (!isDefaultContext) { // print info and job continue to run, for case: context_param // is not empty. System.err.println("Could not find the context " + contextStr); } if (!context_param.isEmpty()) { context.putAll(context_param); // set types for params from parentJobs for (Object key : context_param.keySet()) { String context_key = key.toString(); String context_type = context_param .getContextType(context_key); context.setContextType(context_key, context_type); } } context.setContextType("AdventureWorks2016_Schema", "id_String"); context.AdventureWorks2016_Schema = (String) context .getProperty("AdventureWorks2016_Schema"); context.setContextType("AdventureWorks2016_Database", "id_String"); context.AdventureWorks2016_Database = (String) context .getProperty("AdventureWorks2016_Database"); context.setContextType("AdventureWorks2016_Login", "id_String"); context.AdventureWorks2016_Login = (String) context .getProperty("AdventureWorks2016_Login"); context.setContextType("AdventureWorks2016_Password", "id_Password"); String pwd_AdventureWorks2016_Password_value = context .getProperty("AdventureWorks2016_Password"); context.AdventureWorks2016_Password = null; if (pwd_AdventureWorks2016_Password_value != null) { if (context_param.containsKey("AdventureWorks2016_Password")) {// no // need // to // decrypt // if // it // come // from // program // argument // or // parent // job // runtime context.AdventureWorks2016_Password = pwd_AdventureWorks2016_Password_value; } else if (!pwd_AdventureWorks2016_Password_value.isEmpty()) { try { context.AdventureWorks2016_Password = routines.system.PasswordEncryptUtil .decryptPassword(pwd_AdventureWorks2016_Password_value); context.put("AdventureWorks2016_Password", context.AdventureWorks2016_Password); } catch (java.lang.RuntimeException e) { // do nothing } } } context.setContextType("AdventureWorks2016_AdditionalParams", "id_String"); context.AdventureWorks2016_AdditionalParams = (String) context .getProperty("AdventureWorks2016_AdditionalParams"); context.setContextType("AdventureWorks2016_Server", "id_String"); context.AdventureWorks2016_Server = (String) context .getProperty("AdventureWorks2016_Server"); context.setContextType("AdventureWorks2016_Port", "id_String"); context.AdventureWorks2016_Port = (String) context .getProperty("AdventureWorks2016_Port"); } catch (java.io.IOException ie) { System.err.println("Could not load context " + contextStr); ie.printStackTrace(); } // get context value from parent directly if (parentContextMap != null && !parentContextMap.isEmpty()) { if (parentContextMap.containsKey("AdventureWorks2016_Schema")) { context.AdventureWorks2016_Schema = (String) parentContextMap .get("AdventureWorks2016_Schema"); } if (parentContextMap.containsKey("AdventureWorks2016_Database")) { context.AdventureWorks2016_Database = (String) parentContextMap .get("AdventureWorks2016_Database"); } if (parentContextMap.containsKey("AdventureWorks2016_Login")) { context.AdventureWorks2016_Login = (String) parentContextMap .get("AdventureWorks2016_Login"); } if (parentContextMap.containsKey("AdventureWorks2016_Password")) { context.AdventureWorks2016_Password = (java.lang.String) parentContextMap .get("AdventureWorks2016_Password"); } if (parentContextMap .containsKey("AdventureWorks2016_AdditionalParams")) { context.AdventureWorks2016_AdditionalParams = (String) parentContextMap .get("AdventureWorks2016_AdditionalParams"); } if (parentContextMap.containsKey("AdventureWorks2016_Server")) { context.AdventureWorks2016_Server = (String) parentContextMap .get("AdventureWorks2016_Server"); } if (parentContextMap.containsKey("AdventureWorks2016_Port")) { context.AdventureWorks2016_Port = (String) parentContextMap .get("AdventureWorks2016_Port"); } } // Resume: init the resumeUtil resumeEntryMethodName = ResumeUtil .getResumeEntryMethodName(resuming_checkpoint_path); resumeUtil = new ResumeUtil(resuming_logs_dir_path, isChildJob, rootPid); resumeUtil.initCommonInfo(pid, rootPid, fatherPid, projectName, jobName, contextStr, jobVersion); List<String> parametersToEncrypt = new java.util.ArrayList<String>(); parametersToEncrypt.add("AdventureWorks2016_Password"); // Resume: jobStart resumeUtil.addLog("JOB_STARTED", "JOB:" + jobName, parent_part_launcher, Thread.currentThread().getId() + "", "", "", "", "", resumeUtil.convertToJsonText(context, parametersToEncrypt)); java.util.concurrent.ConcurrentHashMap<Object, Object> concurrentHashMap = new java.util.concurrent.ConcurrentHashMap<Object, Object>(); globalMap.put("concurrentHashMap", concurrentHashMap); long startUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long endUsedMemory = 0; long end = 0; startTime = System.currentTimeMillis(); this.globalResumeTicket = true;// to run tPreJob this.globalResumeTicket = false;// to run others jobs try { errorCode = null; tDBInput_1Process(globalMap); if (!"failure".equals(status)) { status = "end"; } } catch (TalendException e_tDBInput_1) { globalMap.put("tDBInput_1_SUBPROCESS_STATE", -1); e_tDBInput_1.printStackTrace(); } this.globalResumeTicket = true;// to run tPostJob end = System.currentTimeMillis(); if (watch) { System.out.println((end - startTime) + " milliseconds"); } endUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (false) { System.out.println((endUsedMemory - startUsedMemory) + " bytes memory increase when running : Preview_Data"); } int returnCode = 0; if (errorCode == null) { returnCode = status != null && status.equals("failure") ? 1 : 0; } else { returnCode = errorCode.intValue(); } resumeUtil.addLog("JOB_ENDED", "JOB:" + jobName, parent_part_launcher, Thread.currentThread().getId() + "", "", "" + returnCode, "", "", ""); return returnCode; } // only for OSGi env public void destroy() { } private java.util.Map<String, Object> getSharedConnections4REST() { java.util.Map<String, Object> connections = new java.util.HashMap<String, Object>(); return connections; } private void evalParam(String arg) { if (arg.startsWith("--resuming_logs_dir_path")) { resuming_logs_dir_path = arg.substring(25); } else if (arg.startsWith("--resuming_checkpoint_path")) { resuming_checkpoint_path = arg.substring(27); } else if (arg.startsWith("--parent_part_launcher")) { parent_part_launcher = arg.substring(23); } else if (arg.startsWith("--watch")) { watch = true; } else if (arg.startsWith("--stat_port=")) { String portStatsStr = arg.substring(12); if (portStatsStr != null && !portStatsStr.equals("null")) { portStats = Integer.parseInt(portStatsStr); } } else if (arg.startsWith("--trace_port=")) { portTraces = Integer.parseInt(arg.substring(13)); } else if (arg.startsWith("--client_host=")) { clientHost = arg.substring(14); } else if (arg.startsWith("--context=")) { contextStr = arg.substring(10); isDefaultContext = false; } else if (arg.startsWith("--father_pid=")) { fatherPid = arg.substring(13); } else if (arg.startsWith("--root_pid=")) { rootPid = arg.substring(11); } else if (arg.startsWith("--father_node=")) { fatherNode = arg.substring(14); } else if (arg.startsWith("--pid=")) { pid = arg.substring(6); } else if (arg.startsWith("--context_type")) { String keyValue = arg.substring(15); int index = -1; if (keyValue != null && (index = keyValue.indexOf('=')) > -1) { if (fatherPid == null) { context_param.setContextType(keyValue.substring(0, index), replaceEscapeChars(keyValue.substring(index + 1))); } else { // the subjob won't escape the especial chars context_param.setContextType(keyValue.substring(0, index), keyValue.substring(index + 1)); } } } else if (arg.startsWith("--context_param")) { String keyValue = arg.substring(16); int index = -1; if (keyValue != null && (index = keyValue.indexOf('=')) > -1) { if (fatherPid == null) { context_param.put(keyValue.substring(0, index), replaceEscapeChars(keyValue.substring(index + 1))); } else { // the subjob won't escape the especial chars context_param.put(keyValue.substring(0, index), keyValue.substring(index + 1)); } } } else if (arg.startsWith("--log4jLevel=")) { log4jLevel = arg.substring(13); } } private static final String NULL_VALUE_EXPRESSION_IN_COMMAND_STRING_FOR_CHILD_JOB_ONLY = "<TALEND_NULL>"; private final String[][] escapeChars = { { "\\\\", "\\" }, { "\\n", "\n" }, { "\\'", "\'" }, { "\\r", "\r" }, { "\\f", "\f" }, { "\\b", "\b" }, { "\\t", "\t" } }; private String replaceEscapeChars(String keyValue) { if (keyValue == null || ("").equals(keyValue.trim())) { return keyValue; } StringBuilder result = new StringBuilder(); int currIndex = 0; while (currIndex < keyValue.length()) { int index = -1; // judege if the left string includes escape chars for (String[] strArray : escapeChars) { index = keyValue.indexOf(strArray[0], currIndex); if (index >= 0) { result.append(keyValue.substring(currIndex, index + strArray[0].length()).replace(strArray[0], strArray[1])); currIndex = index + strArray[0].length(); break; } } // if the left string doesn't include escape chars, append the left // into the result if (index < 0) { result.append(keyValue.substring(currIndex)); currIndex = currIndex + keyValue.length(); } } return result.toString(); } public Integer getErrorCode() { return errorCode; } public String getStatus() { return status; } ResumeUtil resumeUtil = null; } /************************************************************************************************ * 60377 characters generated by Talend Data Fabric on the December 14, 2018 * 10:03:50 AM EST ************************************************************************************************/
package response.helpers.classes; import java.util.List; public class Error { private List<String> errors; public Error() { super(); } public Error(List<String> errors) { this(); this.errors = errors; } public List<String> getErrors() { return errors; } public void setErrors(List<String> errors) { this.errors = errors; } public String getErrorMessage() { String result = ""; for (String error: errors) { result += "- " + error + "\n"; } return result; } }
package com.fepoc.nextgen.ds; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class ptenp0m0 { public static void main(String[] args) { // TODO Auto-generated method stub try { if (!args[0].equals(null)) { if (args[0].substring(0, 1).equals("Y")) { if (new checkParm().validateDateFormat(args[0].substring(1, 8))) { String HoldCaptureFrom = "PARM"; } } } File f = new File("c:\\eob.txt"); BufferedReader b = new BufferedReader(new FileReader(f)); if (new ReadEob(b.readLine()).isTotalRecord()) { boolean endOfEobInpt = true; boolean fileTotalRead = false; } new ReadEod().checkEod(); String readLine = ""; while ((readLine = b.readLine()) != null) { System.out.println(readLine); } b.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.mx.profuturo.bolsa.model.service.candidates.dto; import java.util.ArrayList; import com.mx.profuturo.bolsa.model.vo.common.BasicCatalogVO; public class GetVacantResponseBean { private boolean success; private ArrayList<BasicCatalogVO> data = new ArrayList<BasicCatalogVO>(); public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public ArrayList<BasicCatalogVO> getData() { return data; } public void setData(ArrayList<BasicCatalogVO> data) { this.data = data; } }
package concurrent_test; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Description: * * @author Baltan * @date 2018/9/30 10:06 */ public class ReentrantLockWithFairnessPolicyTest { // private static final Lock LOCK = new ReentrantLock(); private static final Lock LOCK = new ReentrantLock(true); // 公平锁,哪个线程等候的时间长,哪个线程就能得到锁 public static void main(String[] args) { new Thread(() -> { for (int i = 0; i < 1000; i++) { LOCK.lock(); try { System.out.println("线程1:" + i); } finally { LOCK.unlock(); } } }).start(); new Thread(() -> { for (int i = 0; i < 1000; i++) { LOCK.lock(); try { System.out.println("线程2:" + i); } finally { LOCK.unlock(); } } }).start(); } }
package com.example.rnztx.donors.feeds.intro; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.example.rnztx.donors.R; import com.example.rnztx.donors.feeds.intro.auth.SigninActivity; public class SplashScreenActivity extends AppCompatActivity { private static final int STOPSPLASH = 0; //time duration in millisecond for which your splash screen should visible to //user. here i have taken half second private static final long SPLASHTIME = 3000; TextView bannertxt; //handler for splash screen private Handler splashHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case STOPSPLASH: //Generating and Starting new intent on splash time out Intent intent = new Intent(getApplicationContext(), SigninActivity.class); startActivity(intent); SplashScreenActivity.this.finish(); break; } super.handleMessage(msg); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); bannertxt=(TextView)findViewById(R.id.banner); bannertxt.setText("Be Positive"); Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/SimplyRoundedBold.ttf"); bannertxt.setTypeface(typeface); //Generating message and sending it to splash handle Message msg = new Message(); msg.what = STOPSPLASH; splashHandler.sendMessageDelayed(msg, SPLASHTIME); } }
package ba.bitcamp.LabS09D03.predavanje; public class Engine { Truck next; public void attach(Truck other) { this.next = other; } public Truck getNext() { return next; } }
package com.sample.bitnotifier.utils; public class Constants { }
package scriptinterface.execution.parseerrors; import java.util.LinkedList; /** * Occurs, when the a string to parse is not a word of the language. * * @author Andreas Fender */ public class SyntaxNotAccepted extends SyntaxError { LinkedList<?> expected; public SyntaxNotAccepted(LinkedList<?> expected) { super("UNEXPECTED_SYMBOL"); this.expected = expected; } @Override public String toString() { String res = "Unexpected symbol"; if (expected != null) res += ": expected was " + expected; return res; } }
package com.tencent.mm.ui.contact; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.platformtools.ai; class SelectContactUI$11 implements OnClickListener { final /* synthetic */ SelectContactUI ulL; SelectContactUI$11(SelectContactUI selectContactUI) { this.ulL = selectContactUI; } public final void onClick(View view) { if (!this.ulL.cyC()) { Intent intent = new Intent(); intent.setClassName(this.ulL, "com.tencent.mm.ui.contact.GroupCardSelectUI"); intent.putExtra("group_select_type", true); boolean fb = s.fb(SelectContactUI.a(this.ulL), 16384); intent.putExtra("group_select_need_result", fb); if (!fb) { this.ulL.startActivity(intent); } else if (SelectContactUI.b(this.ulL) == 14) { intent.putExtra("group_multi_select", true); intent.putExtra("already_select_contact", ai.c(SelectContactUI.a(this.ulL, true), ",")); intent.putExtra("max_limit_num", this.ulL.getIntent().getIntExtra("max_limit_num", 9)); this.ulL.startActivityForResult(intent, 4); } else { this.ulL.startActivityForResult(intent, 0); } } } }
public class CalculationException extends Exception{ public CalculationException(String message) { super(message); } public CalculationException(Throwable throwable) { super(throwable); } public CalculationException(String message, Throwable throwable) { super(message, throwable); } }
package com.yekong.rxmobile.rx; import com.google.gson.Gson; /** * Created by baoxiehao on 16/1/18. */ public class RxAction { private static final Gson sGson = new Gson(); public String type; public Object data; private RxAction(String type, Object data) { this.type = type; this.data = data; } @Override public String toString() { return sGson.toJson(this); } public static RxAction create(String type, Object data) { return new RxAction(type, data); } public static boolean equals(RxAction action1, RxAction action2) { if (action1 == null && action2 == null) { return true; } else if (action1 != null && action2 != null) { return action1.type.equals(action2.type) && action1.data.equals(action2.data); } else { return false; } } }
package DesktopApp; import static java.net.URLEncoder.encode; import javax.json.Json; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; /** * Η κλάση addUser δημιουργεί το GUI της εισαγωγής νέου χρήστη και καλεί τον client * για την μετέπειτα κλήση του webService. * * @author Ioulios Tsiko: cs131027 * @author Theofilos Axiotis: cs131011 */ public class addUser extends javax.swing.JFrame { //constructor στον οποίο δίδεται σαν παράμετρος ένα reference στο αρχικό //instance του αντικειμένου της adminMain. adminMain adm; public addUser(adminMain obj) { adm=obj; initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox<>(); jLabel6 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Εισαγωγή"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Πίσω"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Όνομα:"); jLabel2.setText("Επώνυμο:"); jLabel3.setText("Password:"); jLabel4.setText("Username:"); jLabel5.setText("Ρόλος:"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Admin","Secretary" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jLabel6.setText("Τηλέφωνο:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(41, 41, 41) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField5) .addGroup(layout.createSequentialGroup() .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE) .addGap(31, 31, 31) .addComponent(jButton1)) .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(174, 174, 174)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap(34, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: this.setVisible(false); adm.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String name=jTextField1.getText(); String last_name=jTextField2.getText(); String username=jTextField3.getText(); String password=jTextField4.getText(); String phone=jTextField5.getText(); String roleStr=jComboBox1.getSelectedItem().toString(); String role=null; //έλεγχος της επιλεγμένης τιμής απο το jComboBox και κατάλληλη αντιστοίχιση της //με τον αντίστοιχο κωδικό για την εισαγωγή στη βάση if(roleStr.equals("Admin")){ role="1"; }else role="2"; //δημιουργία json JsonBuilderFactory factory=Json.createBuilderFactory(null); JsonObjectBuilder json = factory.createObjectBuilder(); JsonObject myJson; json= json.add("student", factory.createObjectBuilder() .add("name", name) .add("last_name", last_name) .add("role", role) .add("phone", phone) .add("username", username) .add("password", password)); myJson = json.build(); //debugging System.out.println("THE KEY IS :"+User.getKey()); System.out.println(myJson.toString()); //Μορφοποίηση του json ως string και encode της για εισαγωγή στο URI String url = myJson.toString(); String urlSafe = encode(url); //debugging System.out.println("URL:"+urlSafe); //κλήση της addUserClient και της μεθόδου putUser() ώστε να γίνει η εισαγωγή του //χρήστη addUserClient userCl = new addUserClient(); String response=userCl.putUser(User.getUsername(),urlSafe,User.getKey()); //debugging System.out.println("response from server:"+response); System.out.println(User.getRole()); jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); jTextField4.setText(""); }//GEN-LAST:event_jButton1ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox1ActionPerformed public void init(){ /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(addUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(addUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(addUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(addUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; // End of variables declaration//GEN-END:variables }
public class CompanyDemo { public static void main(String[] args) { Employee bob = new Employee("Bob", "123-A", "12/23/2000"); Employee bob2 = new Employee("BOB2", "123-B", "12/9/2008"); ProductionWorker bill = new ProductionWorker("Bill", "234-B", "2/28/1994", 1, 12); System.out.println(bill.toString()); } }
package org.art.soft.tasks.photocollection; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * Created by artur.skrzydlo on 2017-11-16. */ public class Photo { private String name; private String placeTaken; private LocalDateTime dateOfCreation; public Photo(String name, String placeTaken, LocalDateTime dateOfCreation) { this.name = name; this.placeTaken = placeTaken; this.dateOfCreation = dateOfCreation; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPlaceTaken() { return placeTaken; } public void setPlaceTaken(String placeTaken) { this.placeTaken = placeTaken; } public LocalDateTime getDateOfCreation() { return dateOfCreation; } public void setDateOfCreation(LocalDateTime dateOfCreation) { this.dateOfCreation = dateOfCreation; } @Override public String toString() { return name + ',' + placeTaken + ',' + dateOfCreation.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ; } }
public class MRecursivo{ //Atributos de clase private char[][] arreglo; private int areaFinal = 1; //Inicada con 1 por el mayor numero posible si es que no existiese triangulo formado //Construimos la matriz para usar en esta clase public MRecursivo(char[][] matriz) { arreglo = matriz; } //Metodo para calcular area public int AreaMayor() { return areaFinal; } }
package com.cs4125.bookingapp.ui.main; import android.content.Context; import android.widget.Toast; public class Utilities { public static void showToast (Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } }
package generic; import java.util.ArrayList; import java.util.List; public class generic { public class Fruit { public void printout(){ System.out.println("this is fruit"); } } public class Apple extends Fruit{ @Override public void printout(){ System.out.println("this is apple"); } } public class Orange extends Fruit{ @Override public void printout(){ System.out.println("this is orange"); } } public static void main (String [] args) { generic c = new generic(); List<Apple> apples = new ArrayList<>(); List<? extends Fruit> fruits = apples; Apple apple = c.new Apple(); apples.add(apple); Fruit fruit = fruits.get(0); Apple apple2 = (Apple) fruits.get(0); System.out.println(fruit); weekday today = weekday.Monday; } }
package com.company.c4q.unit08practice; public class BigDiff { public static void main(String[] args) { System.out.println(difference(new int[]{8})); } public static int difference(int[] ints) { if(ints.length == 1) return 0; int smallest = ints[0]; int largest = ints[0]; for (int i = 1; i < ints.length; i++) { if (ints[i] > largest) { largest = ints[i]; } else if (ints[i] < smallest) { smallest = ints[i]; } } return largest - smallest; } }
package comm.example; import java.io.*; import java.sql.SQLException; import comm.example.model.Employee; import comm.example.service.EmployeeService; import comm.example.service.EmployeeServiceImpl; public class FilestreamWithDB { public static void main(String[] args) throws SQLException, IOException { try { EmployeeService service=new EmployeeServiceImpl(); BufferedReader reader=new BufferedReader(new FileReader("FileStreamDB.txt")); String line=reader.readLine(); while(line!=null) { String[] db=line.split(" "); service.createEmployee(new Employee(Integer.parseInt(db[0]),db[1],db[2],db[3])); line=reader.readLine(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program 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 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.util; import jashi.JaSHi; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.io.IOUtils; import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeException; import org.artofsolving.jodconverter.office.OfficeManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bsh.EvalError; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.html.simpleparser.HTMLWorker; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.pdf.RandomAccessFileOrArray; import com.lowagie.text.pdf.codec.TiffImage; import com.openkm.api.OKMDocument; import com.openkm.automation.AutomationException; import com.openkm.bean.ExecutionResult; import com.openkm.bean.Repository; import com.openkm.core.AccessDeniedException; import com.openkm.core.Config; import com.openkm.core.ConversionException; import com.openkm.core.DatabaseException; import com.openkm.core.FileSizeExceededException; import com.openkm.core.ItemExistsException; import com.openkm.core.LockException; import com.openkm.core.MimeTypeConfig; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.core.UnsupportedMimeTypeException; import com.openkm.core.UserQuotaExceededException; import com.openkm.core.VersionException; import com.openkm.core.VirusDetectedException; import com.openkm.extension.core.ExtensionException; import com.openkm.extractor.PdfTextExtractor; import freemarker.template.TemplateException; public class DocConverter { private static Logger log = LoggerFactory.getLogger(DocConverter.class); public static ArrayList<String> validOpenOffice = new ArrayList<String>(); public static ArrayList<String> validImageMagick = new ArrayList<String>(); private static ArrayList<String> validGhoscript = new ArrayList<String>(); private static ArrayList<String> validInternal = new ArrayList<String>(); private static DocConverter instance = null; private static OfficeManager officeManager = null; private DocConverter() { // Basic validOpenOffice.add("text/plain"); validOpenOffice.add("text/html"); validOpenOffice.add("text/csv"); validOpenOffice.add("application/rtf"); // OpenOffice.org OpenDocument validOpenOffice.add("application/vnd.oasis.opendocument.text"); validOpenOffice.add("application/vnd.oasis.opendocument.presentation"); validOpenOffice.add("application/vnd.oasis.opendocument.spreadsheet"); validOpenOffice.add("application/vnd.oasis.opendocument.graphics"); validOpenOffice.add("application/vnd.oasis.opendocument.database"); // Microsoft Office validOpenOffice.add("application/msword"); validOpenOffice.add("application/vnd.ms-excel"); validOpenOffice.add("application/vnd.ms-powerpoint"); // Microsoft Office 2007 validOpenOffice.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); validOpenOffice.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); validOpenOffice.add("application/vnd.openxmlformats-officedocument.presentationml.presentation"); // Postcript validGhoscript.add("application/postscript"); // Images validImageMagick.add("image/jpeg"); validImageMagick.add("image/png"); validImageMagick.add("image/gif"); validImageMagick.add("image/tiff"); validImageMagick.add("image/bmp"); validImageMagick.add("image/svg+xml"); validImageMagick.add("image/x-psd"); // Internal conversion validInternal.add(MimeTypeConfig.MIME_ZIP); validInternal.add(MimeTypeConfig.MIME_XML); validInternal.add(MimeTypeConfig.MIME_SQL); validInternal.add(MimeTypeConfig.MIME_JAVA); validInternal.add(MimeTypeConfig.MIME_PHP); validInternal.add(MimeTypeConfig.MIME_BSH); validInternal.add(MimeTypeConfig.MIME_SH); } /** * Retrieve class instance */ public static synchronized DocConverter getInstance() { if (instance == null) { instance = new DocConverter(); if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) { log.info("*** Build Office Manager ***"); log.info("{}={}", Config.PROPERTY_SYSTEM_OPENOFFICE_PATH, Config.SYSTEM_OPENOFFICE_PATH); log.info("{}={}", Config.PROPERTY_SYSTEM_OPENOFFICE_TASKS, Config.SYSTEM_OPENOFFICE_TASKS); log.info("{}={}", Config.PROPERTY_SYSTEM_OPENOFFICE_PORT, Config.SYSTEM_OPENOFFICE_PORT); officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(Config.SYSTEM_OPENOFFICE_PATH) .setMaxTasksPerProcess(Config.SYSTEM_OPENOFFICE_TASKS).setPortNumber(Config.SYSTEM_OPENOFFICE_PORT) .buildOfficeManager(); } else { log.warn("{} not configured", Config.PROPERTY_SYSTEM_OPENOFFICE_PATH); if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) { log.warn("but {} is configured", Config.PROPERTY_SYSTEM_OPENOFFICE_SERVER); log.info("{}={}", Config.PROPERTY_SYSTEM_OPENOFFICE_SERVER, Config.SYSTEM_OPENOFFICE_SERVER); } else { log.warn("and also {} not configured", Config.PROPERTY_SYSTEM_OPENOFFICE_SERVER); } } } return instance; } /** * Start OpenOffice instance */ public void start() { if (officeManager != null) { officeManager.start(); } } /** * Stop OpenOffice instance */ public void stop() { if (officeManager != null) { officeManager.stop(); } } /** * Obtain OpenOffice Manager */ public OfficeManager getOfficeManager() { return officeManager; } /** * Test if a MIME document can be converted to PDF */ public boolean convertibleToPdf(String from) { log.trace("convertibleToPdf({})", from); boolean ret = false; if (!Config.REMOTE_CONVERSION_SERVER.equals("") && (validOpenOffice.contains(from) || validImageMagick.contains(from) || validGhoscript.contains(from))) { ret = true; } else if ((!Config.SYSTEM_OPENOFFICE_PATH.equals("") || !Config.SYSTEM_OPENOFFICE_SERVER.equals("")) && validOpenOffice.contains(from)) { ret = true; } else if (!Config.SYSTEM_IMAGEMAGICK_CONVERT.equals("") && validImageMagick.contains(from)) { ret = true; } else if (!Config.SYSTEM_GHOSTSCRIPT.equals("") && validGhoscript.contains(from)) { ret = true; } else if (validInternal.contains(from)) { ret = true; } log.trace("convertibleToPdf: {}", ret); return ret; } /** * Test if a MIME document can be converted to SWF */ public boolean convertibleToSwf(String from) { log.trace("convertibleToSwf({})", from); boolean ret = false; if (!Config.REMOTE_CONVERSION_SERVER.equals("") && (MimeTypeConfig.MIME_PDF.equals(from) || validOpenOffice.contains(from) || validImageMagick.contains(from) || validGhoscript.contains(from))) { ret = true; } else if (!Config.SYSTEM_SWFTOOLS_PDF2SWF.equals("") && (MimeTypeConfig.MIME_PDF.equals(from) || convertibleToPdf(from))) { ret = true; } log.trace("convertibleToSwf: {}", ret); return ret; } /** * Convert a document format to another one. */ public void convert(File inputFile, String mimeType, File outputFile) throws ConversionException { log.debug("convert({}, {}, {})", new Object[] { inputFile, mimeType, outputFile }); if (Config.SYSTEM_OPENOFFICE_PATH.equals("") && Config.SYSTEM_OPENOFFICE_SERVER.equals("")) { throw new ConversionException(Config.PROPERTY_SYSTEM_OPENOFFICE_PATH + " or " + Config.PROPERTY_SYSTEM_OPENOFFICE_SERVER + " not configured"); } if (!validOpenOffice.contains(mimeType)) { throw new ConversionException("Invalid document conversion MIME type: " + mimeType); } try { if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) { // Document conversion managed by local OO instance OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(inputFile, outputFile); } else if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) { // Document conversion managed by remote conversion server remoteConvert(Config.SYSTEM_OPENOFFICE_SERVER, inputFile, mimeType, outputFile, MimeTypeConfig.MIME_PDF); } } catch (OfficeException e) { throw new ConversionException("Error converting document: " + e.getMessage()); } } /** * Handle remote OpenOffice server conversion */ public void remoteConvert(String uri, File inputFile, String srcMimeType, File outputFile, String dstMimeType) throws ConversionException { PostMethod post = new PostMethod(uri); try { Part[] parts = { new FilePart(inputFile.getName(), inputFile), new StringPart("src_mime", srcMimeType), new StringPart("dst_mime", dstMimeType), new StringPart("okm_uuid", Repository.getUuid()) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient httpclient = new HttpClient(); int rc = httpclient.executeMethod(post); log.info("Response Code: {}", rc); if (rc == HttpStatus.SC_OK) { FileOutputStream fos = new FileOutputStream(outputFile); BufferedInputStream bis = new BufferedInputStream(post.getResponseBodyAsStream()); IOUtils.copy(bis, fos); bis.close(); fos.close(); } else { throw new IOException("Error in conversion: " + rc); } } catch (HttpException e) { throw new ConversionException("HTTP exception", e); } catch (FileNotFoundException e) { throw new ConversionException("File not found exeption", e); } catch (IOException e) { throw new ConversionException("IO exception", e); } finally { post.releaseConnection(); } } /** * Convert document to PDF. */ public void doc2pdf(File input, String mimeType, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from {} to PDF **", mimeType); FileOutputStream fos = null; try { long start = System.currentTimeMillis(); convert(input, mimeType, output); log.debug("Elapse doc2pdf time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start)); } catch (Exception e) { throw new ConversionException("Error in " + mimeType + " to PDF conversion", e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert a document from repository and put the result in the repository. * * @param token Authentication info. * @param docId The path that identifies an unique document or its UUID. * @param dstPath The path of the resulting PDF document (with the name). */ public static void doc2pdf(String token, String docId, String dstPath) throws RepositoryException, PathNotFoundException, DatabaseException, AccessDeniedException, IOException, ConversionException, UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException, VirusDetectedException, ItemExistsException, ExtensionException, AutomationException, DocumentException, EvalError, LockException, VersionException { File docIn = null; File docOut = null; InputStream docIs = null; OutputStream docOs = null; try { // Get document content com.openkm.bean.Document doc = OKMDocument.getInstance().getProperties(token, docId); docIs = OKMDocument.getInstance().getContent(token, docId, false); String mimeType = doc.getMimeType(); // Store in filesystem docIn = FileUtils.createTempFileFromMime(mimeType); docOut = FileUtils.createTempFileFromMime(MimeTypeConfig.MIME_PDF); docOs = new FileOutputStream(docIn); IOUtils.copy(docIs, docOs); IOUtils.closeQuietly(docIs); IOUtils.closeQuietly(docOs); // Convert to PDF DocConverter.getInstance().doc2pdf(docIn, mimeType, docOut); // Upload to OpenKM try { docIs = new FileInputStream(docOut); OKMDocument.getInstance().createSimple(token, dstPath, docIs); } catch (ItemExistsException e) { IOUtils.closeQuietly(docIs); docIs = new FileInputStream(docOut); OKMDocument.getInstance().checkout(token, dstPath); OKMDocument.getInstance().checkin(token, dstPath, docIs, "Document to PDF"); } } finally { IOUtils.closeQuietly(docIs); IOUtils.closeQuietly(docOs); FileUtils.deleteQuietly(docIn); FileUtils.deleteQuietly(docOut); } } /** * Convert document to TXT. */ public void doc2txt(InputStream input, String mimeType, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from {} to TXT **", mimeType); File tmp = FileUtils.createTempFileFromMime(mimeType); FileOutputStream fos = new FileOutputStream(tmp); try { long start = System.currentTimeMillis(); if (MimeTypeConfig.MIME_PDF.equals(mimeType)) { Reader r = new PdfTextExtractor().extractText(input, mimeType, "utf-8"); fos.close(); fos = new FileOutputStream(output); IOUtils.copy(r, fos); } else if (validOpenOffice.contains(mimeType)) { IOUtils.copy(input, fos); fos.flush(); fos.close(); convert(tmp, mimeType, output); } log.debug("Elapse doc2txt time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start)); } catch (Exception e) { throw new ConversionException("Error in " + mimeType + " to TXT conversion", e); } finally { FileUtils.deleteQuietly(tmp); IOUtils.closeQuietly(fos); } } /** * Convert RTF to HTML. */ public void rtf2html(InputStream input, OutputStream output) throws ConversionException { File docIn = null; File docOut = null; InputStream docIs = null; OutputStream docOs = null; try { docIn = FileUtils.createTempFileFromMime(MimeTypeConfig.MIME_RTF); docOut = FileUtils.createTempFileFromMime(MimeTypeConfig.MIME_HTML); docOs = new FileOutputStream(docIn); IOUtils.copy(input, docOs); IOUtils.closeQuietly(docOs); // Conversion rtf2html(docIn, docOut); docIs = new FileInputStream(docOut); IOUtils.copy(docIs, output); } catch (DatabaseException e) { throw new ConversionException("Database exception", e); } catch (IOException e) { throw new ConversionException("IO exception", e); } finally { IOUtils.closeQuietly(docIs); IOUtils.closeQuietly(docOs); FileUtils.deleteQuietly(docIn); FileUtils.deleteQuietly(docOut); } } /** * Convert RTF to HTML. */ public void rtf2html(File input, File output) throws ConversionException { log.debug("** Convert from RTF to HTML **"); FileOutputStream fos = null; try { long start = System.currentTimeMillis(); convert(input, MimeTypeConfig.MIME_RTF, output); log.debug("Elapse rtf2html time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start)); } catch (Exception e) { throw new ConversionException("Error in RTF to HTML conversion", e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert PS to PDF (for document preview feature). */ public void ps2pdf(File input, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from PS to PDF **"); FileOutputStream fos = null; String cmd = null; if (!input.getName().toLowerCase().endsWith(".ps")) { log.warn("ps2pdf conversion needs *.ps as input file"); } try { // Performs conversion HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("fileIn", input.getPath()); hm.put("fileOut", output.getPath()); String tpl = Config.SYSTEM_GHOSTSCRIPT + " ${fileIn} ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_GHOSTSCRIPT_PS2PDF", tpl, hm); ExecutionResult er = ExecutionUtils.runCmd(cmd); if (er.getExitValue() != 0) { throw new ConversionException(er.getStderr()); } } catch (SecurityException e) { throw new ConversionException("Security exception executing command: " + cmd, e); } catch (InterruptedException e) { throw new ConversionException("Interrupted exception executing command: " + cmd, e); } catch (IOException e) { throw new ConversionException("IO exception executing command: " + cmd, e); } catch (TemplateException e) { throw new ConversionException("Template exception", e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert IMG to PDF (for document preview feature). * * [0] => http://www.rubblewebs.co.uk/imagemagick/psd.php */ public void img2pdf(File input, String mimeType, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from {} to PDF **", mimeType); FileOutputStream fos = null; String cmd = null; try { // Performs conversion HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("fileIn", input.getPath()); hm.put("fileOut", output.getPath()); if (MimeTypeConfig.MIME_PSD.equals(mimeType)) { String tpl = Config.SYSTEM_IMAGEMAGICK_CONVERT + " ${fileIn}[0] ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_IMAGEMAGICK_CONVERT", tpl, hm); } else { String tpl = Config.SYSTEM_IMAGEMAGICK_CONVERT + " ${fileIn} ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_IMAGEMAGICK_CONVERT", tpl, hm); } ExecutionResult er = ExecutionUtils.runCmd(cmd); if (er.getExitValue() != 0) { throw new ConversionException(er.getStderr()); } } catch (SecurityException e) { throw new ConversionException("Security exception executing command: " + cmd, e); } catch (InterruptedException e) { throw new ConversionException("Interrupted exception executing command: " + cmd, e); } catch (IOException e) { throw new ConversionException("IO exception executing command: " + cmd, e); } catch (TemplateException e) { throw new ConversionException("Template exception", e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert HTML to PDF */ public void html2pdf(File input, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from HTML to PDF **"); FileOutputStream fos = null; try { fos = new FileOutputStream(output); // Make conversion Document doc = new Document(PageSize.A4); PdfWriter.getInstance(doc, fos); doc.open(); HTMLWorker html = new HTMLWorker(doc); html.parse(new FileReader(input)); doc.close(); } catch (DocumentException e) { throw new ConversionException("Exception in conversion: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert TXT to PDF */ public void txt2pdf(InputStream is, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from TXT to PDF **"); FileOutputStream fos = null; String line = null; try { fos = new FileOutputStream(output); // Make conversion BufferedReader br = new BufferedReader(new InputStreamReader(is)); Document doc = new Document(PageSize.A4); PdfWriter.getInstance(doc, fos); doc.open(); while ((line = br.readLine()) != null) { doc.add(new Paragraph(12F, line)); } doc.close(); } catch (DocumentException e) { throw new ConversionException("Exception in conversion: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert ZIP to PDF */ @SuppressWarnings("rawtypes") public void zip2pdf(File input, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from ZIP to PDF **"); FileOutputStream fos = null; ZipFile zipFile = null; try { fos = new FileOutputStream(output); // Make conversion zipFile = new ZipFile(input); Document doc = new Document(PageSize.A4); PdfWriter.getInstance(doc, fos); doc.open(); for (Enumeration e = zipFile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); doc.add(new Paragraph(12F, entry.getName())); } doc.close(); zipFile.close(); } catch (ZipException e) { throw new ConversionException("Exception in conversion: " + e.getMessage(), e); } catch (DocumentException e) { throw new ConversionException("Exception in conversion: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert SRC to PDF */ public void src2pdf(File input, File output, String lang) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from SRC to PDF **"); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(output); fis = new FileInputStream(input); // Make syntax highlight String source = IOUtils.toString(fis); JaSHi jashi = new JaSHi(source, lang); // jashi.EnableLineNumbers(1); String parsed = jashi.ParseCode(); // Make conversion to PDF Document doc = new Document(PageSize.A4.rotate()); PdfWriter.getInstance(doc, fos); doc.open(); HTMLWorker html = new HTMLWorker(doc); html.parse(new StringReader(parsed)); doc.close(); } catch (DocumentException e) { throw new ConversionException("Exception in conversion: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(fos); } } /** * Convert PDF to SWF (for document preview feature). */ public void pdf2swf(File input, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from PDF to SWF **"); BufferedReader stdout = null; String cmd = null; try { // Performs conversion HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("fileIn", input.getPath()); hm.put("fileOut", output.getPath()); cmd = TemplateUtils.replace("SYSTEM_PDF2SWF", Config.SYSTEM_SWFTOOLS_PDF2SWF, hm); ExecutionResult er = ExecutionUtils.runCmd(cmd); if (er.getExitValue() != 0) { throw new ConversionException(er.getStderr()); } } catch (SecurityException e) { throw new ConversionException("Security exception executing command: " + cmd, e); } catch (InterruptedException e) { throw new ConversionException("Interrupted exception executing command: " + cmd, e); } catch (IOException e) { throw new ConversionException("IO exception executing command: " + cmd, e); } catch (TemplateException e) { throw new ConversionException("Template exception", e); } finally { IOUtils.closeQuietly(stdout); } } /** * Convert PDF to IMG (for document preview feature). */ public void pdf2img(File input, File output) throws ConversionException, DatabaseException, IOException { log.debug("** Convert from PDF to IMG **"); File tmpDir = FileUtils.createTempDir(); String cmd = null; try { // Performs step 1: split pdf into several images HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("fileIn", input.getPath()); hm.put("fileOut", tmpDir + File.separator + "out.jpg"); String tpl = Config.SYSTEM_IMAGEMAGICK_CONVERT + " -bordercolor #666 -border 2x2 ${fileIn} ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_IMG2PDF", tpl, hm); ExecutionResult er = ExecutionUtils.runCmd(cmd); if (er.getExitValue() != 0) { throw new ConversionException(er.getStderr()); } // Performs step 2: join split images into a big one hm = new HashMap<String, Object>(); StringBuilder sb = new StringBuilder(); File files[] = tmpDir.listFiles(); Arrays.sort(files, new FileOrderComparator()); for (File f : files) { sb.append(f.getPath()).append(" "); } hm.put("fileIn", sb.toString()); hm.put("fileOut", output.getPath()); tpl = Config.SYSTEM_IMAGEMAGICK_CONVERT + " ${fileIn}-append ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_IMG2PDF", tpl, hm); er = ExecutionUtils.runCmd(cmd); if (er.getExitValue() != 0) { throw new ConversionException(er.getStderr()); } } catch (SecurityException e) { throw new ConversionException("Security exception executing command: " + cmd, e); } catch (InterruptedException e) { throw new ConversionException("Interrupted exception executing command: " + cmd, e); } catch (IOException e) { throw new ConversionException("IO exception executing command: " + cmd, e); } catch (TemplateException e) { throw new ConversionException("Template exception", e); } finally { org.apache.commons.io.FileUtils.deleteQuietly(tmpDir); } } /** * User by pdf2img */ private class FileOrderComparator implements Comparator<File> { @Override public int compare(File o1, File o2) { // Filenames are out-1.jpg, out-2.jpg, ..., out-10.jpg, ... int o1Ord = Integer.parseInt((o1.getName().split("\\.")[0]).split("-")[1]); int o2Ord = Integer.parseInt((o2.getName().split("\\.")[0]).split("-")[1]); if (o1Ord > o2Ord) return 1; else if (o1Ord < o2Ord) return -1; else return 0; } } /** * TIFF to PDF conversion */ public void tiff2pdf(File input, File output) throws ConversionException { RandomAccessFileOrArray ra = null; Document doc = null; try { // Open PDF doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output)); PdfContentByte cb = writer.getDirectContent(); doc.open(); // int pages = 0; // Open TIFF ra = new RandomAccessFileOrArray(input.getPath()); int comps = TiffImage.getNumberOfPages(ra); for (int c = 0; c < comps; ++c) { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { log.debug("tiff2pdf - page {}", c + 1); if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) { img.scaleToFit(500, 700); } img.setAbsolutePosition(20, 20); // doc.add(new Paragraph("page " + (c + 1))); cb.addImage(img); doc.newPage(); // ++pages; } } } catch (FileNotFoundException e) { throw new ConversionException("File not found: " + e.getMessage(), e); } catch (DocumentException e) { throw new ConversionException("Document exception: " + e.getMessage(), e); } catch (IOException e) { throw new ConversionException("IO exception: " + e.getMessage(), e); } finally { if (ra != null) { try { ra.close(); } catch (IOException e) { // Ignore } } if (doc != null) { doc.close(); } } } /** * Rotate an image. * * @param imgIn Image to rotate. * @param imgOut Image rotated. * @param angle Rotation angle. * @throws IOException */ public void rotateImage(File imgIn, File imgOut, double angle) throws ConversionException { String cmd = null; try { // Performs conversion HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("fileIn", imgIn.getPath()); hm.put("fileOut", imgOut.getPath()); String tpl = Config.SYSTEM_IMAGEMAGICK_CONVERT + " -rotate " + angle + " ${fileIn} ${fileOut}"; cmd = TemplateUtils.replace("SYSTEM_IMG2PDF", tpl, hm); ExecutionUtils.runCmd(cmd); } catch (SecurityException e) { throw new ConversionException("Security exception executing command: " + cmd, e); } catch (InterruptedException e) { throw new ConversionException("Interrupted exception executing command: " + cmd, e); } catch (IOException e) { throw new ConversionException("IO exception executing command: " + cmd, e); } catch (TemplateException e) { throw new ConversionException("Template exception", e); } } }
package com.gcipriano.katas.salestaxes.receipt; import java.util.ArrayList; import java.util.List; public class BulletPointReceiptBuilder implements Receipt { private String taxTotal; private String total; private List<PresentableProduct> products = new ArrayList<>(); @Override public void addProduct(PresentableProduct product) { products.add(product); } @Override public void total(String amount) { total = amount; } @Override public void taxTotal(String amount) { taxTotal = amount; } @Override public String render() { return products() + salesTaxes() + total(); } private String products() { String productsLines = ""; for (PresentableProduct product : products) { productsLines += render(product); } return productsLines; } private String total() { return "Total: " + total; } private String salesTaxes() { return "Sales Taxes: " + taxTotal + "\n"; } private String render(PresentableProduct product) { return "1 " + product.description() + ": " + product.amount() + "\n"; } }
int main() { printInt(0); return 0; }
package micronaut.starter.kit; public class ProcessMetadataValuesNode { }
package com.github.ganity.oauth2.shiro; import org.springframework.context.annotation.Configuration; @Configuration public class ShiroOAuth2Configuration { }
package ewaMemory.memoryTable.beans; import FacebookConnector.Score; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; public class MemoryTable { private static final Logger log = Logger.getLogger(MemoryTable.class.getSimpleName()); private final static int MAXUSERS = 2; private List<List<MemoryCard>> cards; private MemoryCard lastRevealedCard; private int remainingPairs; private List<MemoryCard> cardsToUnreveal = new LinkedList<MemoryCard>(); private String[] users = new String[MAXUSERS]; private Map<String, Integer> points = new HashMap<String, Integer>(); private Map<String, Integer> attempts = new HashMap<String, Integer>(); private long timeStart = (long) 0; private Map<String, Long> usersPlayTimeInSeconds = new HashMap<String, Long>(); private Map<String, Integer> ranking = new HashMap<String, Integer>(); private List<Score> allRankings = new ArrayList<Score>(); private int turnId = 0; private boolean gameHasStarted = false; private boolean gameOver; private Map<String, Outcome> outcome; private final int CARD_WIDTH = 110; private final int TABLE_PADDING = 25; public MemoryTable(List<String> usernames) { int id = 0; for (String username : usernames) { points.put(username, 0); attempts.put(username, 0); usersPlayTimeInSeconds.put(username, 0L); users[id++] = username; } } public List<List<MemoryCard>> getRows() { return cards; } public void setCards(List<List<MemoryCard>> memoryCards) { cards = memoryCards; } public MemoryCard getLastRevealedCard() { return lastRevealedCard; } public void setEndTime(long endTime) { log.fine("nextTurn"); long playTime = (endTime - timeStart) / 1000; log.fine("playTime: " + playTime); long oldPlayTime = usersPlayTimeInSeconds.get(users[turnId]); log.fine("oldPlayTime: " + oldPlayTime); long newPlayTime = oldPlayTime + playTime; log.fine("newPlayTime: " + newPlayTime); usersPlayTimeInSeconds.put(users[turnId], newPlayTime); timeStart = endTime; } public void setLastRevealedCard(MemoryCard card) { lastRevealedCard = card; } public void incrementPoints(String username) { points.put(username, points.get(username) + 1); } public Integer getPoints(String username) { return points.get(username); } public void incrementAttempts(String username) { attempts.put(username, attempts.get(username) + 1); } public Integer getAttempts(String username) { return attempts.get(username); } public void decrementRemainingPairs() { remainingPairs--; // if (remainingPairs == 0) { // gameOver = true; // String strLoosers = ""; // String strWinners = ""; // // //TODO this is the only part in this class which makes us of the game having only two players // // outcome = new HashMap<String,Outcome>(); // // if(points.get(users[0]) > points.get(users[1])) { // outcome.put(users[0], Outcome.WIN); // outcome.put(users[1], Outcome.LOOSE); // } else if(points.get(users[0]) == points.get(users[1])) { // outcome.put(users[0], Outcome.DRAW); // outcome.put(users[1], Outcome.DRAW); // } else { // outcome.put(users[0], Outcome.LOOSE); // outcome.put(users[1], Outcome.WIN); // } // // log.info("Game over - outcome: "+users[0]+":"+outcome.get(users[0])+"; "+users[1]+":"+outcome.get(users[1])); // } } public int getRemainingPairs() { //number of all pairs; set only once if (sum(points.values()) == 0) { if (cards.isEmpty()) { remainingPairs = 0; } else { remainingPairs = cards.size() * cards.get(0).size() / 2; } } return remainingPairs; } public void addToCardsToUnreveal(MemoryCard card) { cardsToUnreveal.add(card); } public void unrevealCardsToUnreveal() { for (MemoryCard c : cardsToUnreveal) { c.setVisible(false); } cardsToUnreveal.clear(); } public String getPlayTime(String username) { long playTimeInSeconds = usersPlayTimeInSeconds.get(username); if (playTimeInSeconds == 0L) { return "0:00"; } long minutes = (long) ((int) playTimeInSeconds / 60); long seconds = playTimeInSeconds % 60; if (seconds < 10) { return minutes + ":0" + seconds; } return minutes + ":" + seconds; } public int getPlayTimeInSeconds(String username) { return usersPlayTimeInSeconds.get(username).intValue(); } private int sum(Collection<Integer> values) { int sum = 0; for (Integer n : values) { sum += n; } return sum; } public boolean isUserTurn(String username) { return users[turnId].equals(username); } public String[] getUsernames() { return users; } public void nextTurn() { turnId = (turnId + 1) % MAXUSERS; } public String getUsernameTurn() { return users[turnId]; } public void startGame() { gameHasStarted = true; timeStart = new Date().getTime(); } /** * @return the gameHasStarted */ public boolean isGameHasStarted() { return gameHasStarted; } /** * @return the gameOver */ public boolean isGameOver() { return gameOver; } public Outcome getOutcome(String username) { return outcome.get(username); } public int getHighscore(String username) { // x = 300 - (sec / pairs) if (getPoints(username) < 1) { return 0; } return 300 - (getPlayTimeInSeconds(username) / getPoints(username)); } //gets highscores from users public Map<String, Integer> getAllHighscores() { Map<String, Integer> scores = new HashMap<String, Integer>(); for (String username : users) { scores.put(username, getHighscore(username)); } return scores; } public void setRanking(String username, int rank) { ranking.put(username, rank); } public Integer getRanking(String username) { return ranking.get(username); } /** * requires descending sorted list * @return list with top ten ranking */ public List<Score> getTopTenRanking() { List<Score> topScores = new ArrayList<Score>(); for (int i = 0; i < 10 && i < allRankings.size(); i++) { topScores.add(allRankings.get(i)); } return topScores; } public void setAllRankings(List<Score> ranking) { allRankings = ranking; } public int getDisplayWidth() { return CARD_WIDTH * cards.get(0).size() + 2 * TABLE_PADDING; } public void calulateOutcome() { //TODO this is the only part in this class which makes us of the game having only two players outcome = new HashMap<String, Outcome>(); if (points.get(users[0]) > points.get(users[1])) { outcome.put(users[0], Outcome.WIN); outcome.put(users[1], Outcome.LOOSE); } else if (points.get(users[0]) == points.get(users[1])) { outcome.put(users[0], Outcome.DRAW); outcome.put(users[1], Outcome.DRAW); } else { outcome.put(users[0], Outcome.LOOSE); outcome.put(users[1], Outcome.WIN); } log.info("Game over - outcome: " + users[0] + ":" + outcome.get(users[0]) + "; " + users[1] + ":" + outcome.get(users[1])); } public void setGameOver(boolean gameOverStatus) { gameOver = gameOverStatus; } }
package zm.gov.moh.app; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import zm.gov.moh.app.view.HomeActivity; import zm.gov.moh.cervicalcancer.CervicalCancerModule; import zm.gov.moh.cervicalcancer.submodule.cervicalcancer.view.CervicalCancerActivity; import zm.gov.moh.cervicalcancer.submodule.enrollment.view.CervicalCancerEnrollmentActivity; import zm.gov.moh.common.submodule.dashboard.client.view.ClientDashboardActivity; import zm.gov.moh.common.submodule.form.view.FormActivity; import zm.gov.moh.common.submodule.login.view.LoginActivity; import zm.gov.moh.common.submodule.register.view.RegisterActivity; import zm.gov.moh.common.submodule.visit.view.Visit; import zm.gov.moh.common.submodule.settings.view.Settings; import zm.gov.moh.common.submodule.vitals.view.VitalsActivity; import zm.gov.moh.core.model.Criteria; import zm.gov.moh.core.model.submodule.BasicModule; import zm.gov.moh.core.model.submodule.BasicModuleGroup; import zm.gov.moh.core.model.submodule.ModuleGroup; import zm.gov.moh.core.utils.BaseApplication; public class ApplicationContext extends BaseApplication { @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); this.buildName = BuildConfig.VERSION_NAME +" "+ zm.gov.moh.core.BuildConfig.BUILD_DATE; //Load common modules registerModule(CoreModule.CLIENT_DASHOARD, new BasicModule("Client Dashboard",ClientDashboardActivity.class)); registerModule(CoreModule.REGISTER, new BasicModule("Register",RegisterActivity.class)); registerModule(CoreModule.HOME, new BasicModule("home",HomeActivity.class)); registerModule(CoreModule.LOGIN, new BasicModule("Login",LoginActivity.class)); registerModule(CoreModule.VITALS, new BasicModule("Vitals",VitalsActivity.class)); registerModule(CoreModule.FORM, new BasicModule("FormModel", FormActivity.class)); registerModule(CoreModule.VISIT, new BasicModule("Visit", Visit.class)); registerModule(CoreModule.BOOTSTRAP, new BasicModule("Bootstrap", BootstrapActivity.class)); registerModule(CoreModule.SETTINGS, new BasicModule("Settings", Settings.class)); //Load healthcare service modules zm.gov.moh.core.model.submodule.Module cervicalCancerEnrollment = new BasicModule("Client Enrollment", CervicalCancerEnrollmentActivity.class); zm.gov.moh.core.model.submodule.Module cervicalCancerRegister = new BasicModule("Client Register", zm.gov.moh.cervicalcancer.submodule.register.view.RegisterActivity.class); zm.gov.moh.core.model.submodule.Module cervicalCancerPatientDashboard = new BasicModule("Patient Dashboard", zm.gov.moh.cervicalcancer.submodule.dashboard.patient.view.PatientDashboardActivity.class); registerModule(CervicalCancerModule.Submodules.CLIENT_ENROLLMENT, cervicalCancerEnrollment); registerModule(CervicalCancerModule.Submodules.CLIENT_REGISTER, cervicalCancerRegister); registerModule(CervicalCancerModule.Submodules.PATIENT_DASHBOARD, cervicalCancerPatientDashboard); //Add to module group List<zm.gov.moh.core.model.submodule.Module> cervicalCancerModules = new ArrayList<>(); cervicalCancerModules.add(cervicalCancerEnrollment); cervicalCancerModules.add(cervicalCancerRegister); cervicalCancerModules.add(cervicalCancerPatientDashboard); ModuleGroup cervicalCancer = new BasicModuleGroup("Cervical Cancer", CervicalCancerActivity.class, cervicalCancerModules); registerModule(CervicalCancerModule.MODULE, cervicalCancer); loadFirstPointOfCareSubmodule(cervicalCancer); } }
package com.jidouauto.mvvm.http.exception; /** * @author leosun */ public class CodeException extends BaseException { public CodeException(int code) { super(code); } public CodeException(int code, String message) { super(code, message); } public CodeException(int code, String message, Throwable cause) { super(code, message, cause); } public CodeException(int code, Throwable cause) { super(code, cause); } }
package fr.cp.reseau.actor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import fr.cp.reseau.api.GetReseau; public class ReseauCalcul { private final static ActorSystem SYSTEM = ActorSystem .create("reseauSystem"); private final static Logger LOG = LoggerFactory .getLogger(ReseauCalcul.class); private static final long NUMBERCYCLE = 20; public static void main(String[] args) throws InterruptedException { LOG.info("" + Thread.currentThread()); System.gc(); System.gc(); System.gc(); System.gc(); Thread.sleep(2000); final ActorRef listener = SYSTEM.actorOf( Props.create(ListenerReseau.class), "listener"); final ActorRef reseauActorRef = SYSTEM.actorOf( Props.create(ReseauActor.class, listener), "reseau"); for (int i = 0; i < NUMBERCYCLE; i++) { reseauActorRef.tell(new GetReseau(1, 1), ActorRef.noSender()); } LOG.info("end main -- continue"); LOG.info("do something else"); } }
package thsst.calvis.editor.controller; import javafx.scene.control.Tab; import javafx.scene.input.KeyCode; import thsst.calvis.configuration.model.engine.*; import thsst.calvis.configuration.model.exceptions.*; import thsst.calvis.editor.view.AssemblyComponent; import thsst.calvis.editor.view.ConsoleTextArea; import java.math.BigInteger; /** * Created by Jennica on 07/02/2016. */ public class ConsoleController extends AssemblyComponent { private ConsoleTextArea textArea; private Tab tab; private int lineBefore; private CalvisFormattedInstruction currentInstruction; public ConsoleController() { this.lineBefore = 0; this.textArea = new ConsoleTextArea(false); this.tab = new Tab(); this.tab.setText("Console"); this.tab.setContent(textArea); } public Tab getTab() { return tab; } @Override public void update(CalvisFormattedInstruction currentInstruction, int lineNumber) { if ( currentInstruction != null ) { String name = currentInstruction.getName(); if ( name.matches("PRINTF|SCANF|CLS") ) { attachCalvisInstruction(currentInstruction); currentInstruction.setConsole(this); currentInstruction.getInstruction().consoleExecute(sysCon.getRegisterState(), sysCon.getMemoryState(), this); } } } @Override public void refresh() { cls(); } @Override public void build() { this.textArea.setOnKeyPressed(keyEvent -> { if ( keyEvent.getCode() == KeyCode.ENTER ) { if ( currentInstruction != null && textArea.getState() == true ) { try { currentInstruction = null; String retrieved = retrieveScanned(); executeScan(retrieved); sysCon.resumeFromConsole(); } catch ( Exception e ) { sysCon.reportError(e); } } } }); } public void printf(String text) { this.textArea.setState(true); this.textArea.appendText(text); this.textArea.setState(false); } public void scanf() { this.sysCon.pauseFromConsole(); this.textArea.setState(true); lineBefore = textArea.getText().length(); } public String retrieveScanned() { String text = textArea.getText(); text = textArea.getText(lineBefore, text.length()); this.textArea.setState(false); return text; } public void cls() { this.textArea.setState(true); this.textArea.clear(); this.textArea.setState(false); this.lineBefore = 0; } public void stopConsole() { this.textArea.setState(false); } public void attachCalvisInstruction(CalvisFormattedInstruction CalvisInstruction) { this.currentInstruction = CalvisInstruction; } public void executeScan(String input) throws StackPopException, MemoryReadException, MemoryWriteException, DataTypeMismatchException, MemoryAlignmentException { RegisterList registers = this.sysCon.getRegisterState(); Memory memory = this.sysCon.getMemoryState(); String stackPointer = registers.getStackPointer(); String pointingTo = memory.read(stackPointer, 32); BigInteger pointer = new BigInteger(pointingTo, 16); String scanFormat = ""; // Read the format; assume it's only 1 while ( !memory.read(pointer.toString(16), 8).equals("00") ) { // get one byte String first = memory.read(pointer.toString(16), 8); char ascii = (char) Integer.parseInt(first, 16); pointer = pointer.add(new BigInteger("1")); scanFormat += ascii; } // Get base address of where we store the scanned number // always add 4 to stack pointer since we're dealing with addresses BigInteger stackAddress = new BigInteger(stackPointer, 16); BigInteger offset = new BigInteger("4"); stackAddress = stackAddress.add(offset); if ( stackAddress.compareTo(new BigInteger("FFFE", 16)) == 1 ) { throw new StackPopException(offset.intValue()); } else { String storeToAddress = memory.read(stackAddress.toString(16), 32); storeToMemory(memory, scanFormat, input, storeToAddress); } } private void storeToMemory(Memory memory, String format, String input, String baseAddress) throws MemoryWriteException, DataTypeMismatchException, MemoryReadException, MemoryAlignmentException { if ( format.matches("%d") ) { Short realShort = Short.parseShort(input); String shortToHex = Integer.toHexString(realShort.intValue()); memory.write(baseAddress, shortToHex, 16); } else if ( format.matches("%ld") ) { BigInteger realInt = new BigInteger(input); String intToHex = Integer.toHexString(realInt.intValue()); memory.write(baseAddress, intToHex, 32); } else if ( format.matches("%u") ) { BigInteger b = new BigInteger(input); String unsigned = getUnsigned(16, b.toString(2)); BigInteger b2 = new BigInteger(unsigned); if ( b2.compareTo(new BigInteger("65535")) == 1 || b2.signum() == -1 ) { throw new NumberFormatException("Value out of range. Value:" + input + " Type: %u"); } String unsigned16 = Integer.toHexString(b2.intValue()); memory.write(baseAddress, unsigned16, 16); } else if ( format.matches("%lu") ) { BigInteger b = new BigInteger(input); String unsigned = getUnsigned(32, b.toString(2)); BigInteger b2 = new BigInteger(unsigned); if ( b2.compareTo(new BigInteger("4,294,967,295")) == 1 || b2.signum() == -1 ) { throw new NumberFormatException("Value out of range. Value:" + input + " Type: %lu"); } else { String unsigned32 = Long.toHexString(b2.longValue()); memory.write(baseAddress, unsigned32, 32); } } else if ( format.matches("%x") ) { if ( !input.matches(PatternList.hexPattern) ) { throw new NumberFormatException("Value is not a hex Value:" + input + " Type: %x"); } else if ( input.length() > 6 ) { throw new NumberFormatException("Value out of range. Value:" + input + " Type: %x"); } else { String formatHex = input.substring(2); memory.write(baseAddress, formatHex, 16); } } else if ( format.matches("%lx") ) { if ( !input.matches(PatternList.hexPattern) ) { throw new NumberFormatException("Value is not a hex Value:" + input + " Type: %lx"); } else if ( input.length() > 10 ) { throw new NumberFormatException("Value out of range. Value:" + input + " Type: %lx"); } else { String formatHex = input.substring(2); memory.write(baseAddress, formatHex, 32); } } else if ( format.matches("%f") ) { float floatValue = Float.parseFloat(input); String representation = Integer.toHexString(Float.floatToIntBits(floatValue)); memory.write(baseAddress, representation, 32); } else if ( format.matches("%lf") ) { Double doubleValue = Double.parseDouble(input); String representation = Long.toHexString(Double.doubleToLongBits(doubleValue)); memory.write(baseAddress, representation, 64); } else if ( format.matches("%c") ) { if ( input.length() > 1 ) { throw new NumberFormatException("Not a character: " + input + " Type: %c"); } else { byte[] realChar = input.getBytes(); String asciiHexValue = String.format("%2X", realChar[0]); memory.write(baseAddress, asciiHexValue, 16); } } else if ( format.matches("%s") ) { byte[] bytes = input.getBytes(); BigInteger stringPointer = new BigInteger(baseAddress, 16); for ( int i = 0; i < bytes.length; i++ ) { String asciiHexValue = String.format("%2X", bytes[i]); String address = stringPointer.toString(16); address = MemoryAddressCalculator.extend(address, 32, "0"); memory.write(address, asciiHexValue, 8); stringPointer = stringPointer.add(new BigInteger("1")); } // add last 0 to end of scanned string String lastAddress = stringPointer.toString(16); lastAddress = MemoryAddressCalculator.extend(lastAddress, 32, "0"); memory.write(lastAddress, "00", 8); } } private String getUnsigned(int size, String stringBits) { String temp = stringBits; // zero extend while ( temp.length() < 16 ) { temp = "0" + temp; } StringBuilder tempBit = new StringBuilder(temp); String returnable = ""; if ( tempBit.charAt(0) == '1' ) { tempBit.setCharAt(0, '0'); tempBit.insert(1, "1"); BigInteger bi = new BigInteger(tempBit.toString(), 2); returnable = bi.toString(10); } else { BigInteger bi = new BigInteger(tempBit.toString(), 2); returnable = bi.toString(10); } return returnable; } }
package com.commercetools.pspadapter.payone.transaction.common; import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder; import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike; import com.commercetools.pspadapter.payone.domain.ctp.TypeCacheLoader; import com.commercetools.pspadapter.payone.domain.payone.PayonePostService; import com.commercetools.pspadapter.payone.mapping.PayoneRequestFactory; import com.github.benmanes.caffeine.cache.Caffeine; import io.sphere.sdk.carts.Cart; import io.sphere.sdk.client.BlockingSphereClient; import io.sphere.sdk.payments.Payment; import io.sphere.sdk.payments.Transaction; import io.sphere.sdk.payments.TransactionState; import io.sphere.sdk.queries.PagedQueryResult; import io.sphere.sdk.types.Type; import io.sphere.sdk.types.queries.TypeQuery; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import util.PaymentTestHelper; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import static util.JvmSdkMockUtil.pagedQueryResultsMock; /** * @author fhaertig * @since 13.01.16 */ @RunWith(MockitoJUnitRunner.class) public class AuthorizationTransactionExecutorTest { private static final Cart UNUSED_CART = null; @Mock private PayoneRequestFactory requestFactory; @Mock private PayonePostService postService; @Mock private BlockingSphereClient client; private final PaymentTestHelper testHelper = new PaymentTestHelper(); private AuthorizationTransactionExecutor testee; @Before public void setUp() { when(client.executeBlocking(any(TypeQuery.class))).then(a -> { PagedQueryResult<Type> customTypes = testHelper.getCustomTypes(); String queryString = Arrays.asList(a.getArguments()).get(0).toString(); if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_RESPONSE)) { return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_RESPONSE, customTypes)); } else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION)) { return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION, customTypes)); } else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_REDIRECT)) { return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_REDIRECT, customTypes)); } else if (queryString.contains(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST)) { return pagedQueryResultsMock(findCustomTypeByKey(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST, customTypes)); } return PagedQueryResult.empty(); }); testee = new AuthorizationTransactionExecutor( Caffeine.newBuilder().build(new TypeCacheLoader(client)), requestFactory, postService, client ); } @Test public void pendingAuthorizationNotExecuted() throws Exception { Payment payment = testHelper.dummyPaymentOneAuthPending20EuroCC(); Transaction transaction = payment.getTransactions().stream().filter(t -> t.getState().equals(TransactionState.PENDING)).findFirst().get(); PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(payment, UNUSED_CART); assertThat(testee.wasExecuted(paymentWithCartLike, transaction)).as("transactionExecutor wasExecuted result").isFalse(); } @Test public void pendingAuthorizationWasExecutedStillPending() throws Exception { Payment paymentPendingResponse = testHelper.dummyPaymentOneAuthPending20EuroPendingResponse(); Transaction transaction1 = paymentPendingResponse.getTransactions().stream().filter(t -> t.getState().equals(TransactionState.PENDING)).findFirst().get(); PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(paymentPendingResponse, UNUSED_CART); assertThat(testee.wasExecuted(paymentWithCartLike, transaction1)).as("transactionExecutor wasExecuted result").isTrue(); } @Test public void pendingAuthorizationWasExecutedRedirect() throws Exception { Payment paymentRedirectResponse = testHelper.dummyPaymentOneAuthPending20EuroRedirectResponse(); Transaction transaction2 = paymentRedirectResponse.getTransactions().stream().filter(t -> t.getState().equals(TransactionState.PENDING)).findFirst().get(); PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(paymentRedirectResponse, UNUSED_CART); assertThat(testee.wasExecuted(paymentWithCartLike, transaction2)).as("transactionExecutor wasExecuted result").isTrue(); } @Test public void pendingAuthorizationCreatedByNotification() throws Exception { Payment payment = testHelper.dummyPaymentCreatedByNotification(); Transaction transaction = payment.getTransactions().stream().filter(t -> t.getState().equals(TransactionState.PENDING)).findFirst().get(); PaymentWithCartLike paymentWithCartLike = new PaymentWithCartLike(payment, UNUSED_CART); assertThat(testee.wasExecuted(paymentWithCartLike, transaction)).as("transactionExecutor wasExecuted result").isTrue(); } private Type findCustomTypeByKey(String key, PagedQueryResult<Type> customTypes) { return customTypes .getResults() .stream() .filter(p -> p.getKey().equals(key)) .findFirst() .get(); } }
package x.format; import x.ctrl.SourceCodeFile; public interface CodeSnippet { String toSourceString(SourceCodeFile file); }
package com.lins.myzoom.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; /** * @ClassName MD5Utils * @Description TODO * @Author lin * @Date 2021/2/2 15:18 * @Version 1.0 **/ public class MD5Utils { public static String code(String string) { MessageDigest messageDigest= null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.update(string.getBytes()); byte[] bytes=messageDigest.digest(); int i; StringBuffer stringBuffer=new StringBuffer(""); for (int offset=0;offset<bytes.length;offset++){ i=bytes[offset]; if(i<0) i+=256; if(i<16) stringBuffer.append(0); stringBuffer.append(Integer.toHexString(i)); } //32位加密 return stringBuffer.toString(); //16位加密 // return stringBuffer.toString().substring(8,24); } public static void main(String[] args){ System.out.println(code("yinhuilin123")); } }
package org.jfree.data.test; import static org.junit.Assert.*; import org.jfree.data.DataUtilities; import org.jfree.data.KeyedValues; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.*; /** * A Test Suite for the function getCummulativePercentage from DataUtilities class * * @author Group 8 - Quan, Alex, Sebastian, Carlos * */ public class DataUtilitiesTestCummulativePercentage{ Mockery mockingContext; @Before public void setup(){ mockingContext = new Mockery(); } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * 0 3 * 1 4 * 2 5 */ @Test public void getCummulativePercentagesWithThreeNumbers() { //Fails //setup KeyedValues data = mockingContext.mock(KeyedValues.class); mockingContext.checking(new Expectations() { { atLeast(1).of(data).getItemCount(); will(returnValue(3)); //simulates item # 1 atLeast(1).of(data).getKey(0); will(returnValue(0)); atLeast(1).of(data).getValue(0); will(returnValue(3)); //simulates item # 2 atLeast(1).of(data).getKey(1); will(returnValue(1)); atLeast(1).of(data).getValue(1); will(returnValue(4)); //simulates item # 3 atLeast(1).of(data).getKey(2); will(returnValue(2)); atLeast(1).of(data).getValue(2); will(returnValue(5)); } }); KeyedValues result = DataUtilities.getCumulativePercentages(data); mockingContext.assertIsSatisfied(); Number[] expecteds = {(3.0/(3.0+4.0+5.0)),((3.0+4.0)/(3.0+4.0+5.0)),1.0}; Number[] actuals = {0.0,0.0,0.0}; if(result.getItemCount() != 3) fail("Wrong amount of key returned"); for(int index = 0; index < result.getItemCount(); index++){ actuals[index] = result.getValue(index); } assertArrayEquals(expecteds, actuals); } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * 0 -3 * 1 4 * 2 5 */ @Test public void getCummulativePercentagesWithMixedPositivesAndNegatives() { //Fails //setup KeyedValues data = mockingContext.mock(KeyedValues.class); mockingContext.checking(new Expectations() { { atLeast(1).of(data).getItemCount(); will(returnValue(3)); //simulates item # 1 atLeast(1).of(data).getKey(0); will(returnValue(0)); atLeast(1).of(data).getValue(0); will(returnValue(-3)); //simulates item # 2 atLeast(1).of(data).getKey(1); will(returnValue(1)); atLeast(1).of(data).getValue(1); will(returnValue(4)); //simulates item # 3 atLeast(1).of(data).getKey(2); will(returnValue(2)); atLeast(1).of(data).getValue(2); will(returnValue(5)); } }); KeyedValues result = DataUtilities.getCumulativePercentages(data); mockingContext.assertIsSatisfied(); Number[] expecteds = {((-3.0)/((-3.0)+4.0+5.0)),(((-3.0)+4.0)/((-3.0)+4.0+5.0)),1.0}; Number[] actuals = {0.0,0.0,0.0}; if(result.getItemCount() != 3) fail("Wrong amount of key returned"); for(int index = 0; index < result.getItemCount(); index++){ actuals[index] = result.getValue(index); } assertArrayEquals(expecteds, actuals); } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * 0 0 * 1 0 * 2 0 */ @Test public void getCummulativePercentagesWithZeros() { //Pass //setup KeyedValues data = mockingContext.mock(KeyedValues.class); mockingContext.checking(new Expectations() { { atLeast(1).of(data).getItemCount(); will(returnValue(3)); //simulates item # 1 atLeast(1).of(data).getKey(0); will(returnValue(0)); atLeast(1).of(data).getValue(0); will(returnValue(0)); //simulates item # 2 atLeast(1).of(data).getKey(1); will(returnValue(1)); atLeast(1).of(data).getValue(1); will(returnValue(0)); //simulates item # 3 atLeast(1).of(data).getKey(2); will(returnValue(2)); atLeast(1).of(data).getValue(2); will(returnValue(0)); } }); KeyedValues result = DataUtilities.getCumulativePercentages(data); mockingContext.assertIsSatisfied(); Number[] expecteds = {Double.NaN,Double.NaN,Double.NaN}; Number[] actuals = {0.0,0.0,0.0}; if(result.getItemCount() != 3) fail("Wrong amount of key returned"); for(int index = 0; index < result.getItemCount(); index++){ actuals[index] = result.getValue(index); } assertArrayEquals(expecteds, actuals); } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * 0 -3 * 1 1 * 2 2 */ @Test public void getCummulativePercentagesWithZeroSum() { //Fails //setup KeyedValues data = mockingContext.mock(KeyedValues.class); mockingContext.checking(new Expectations() { { atLeast(1).of(data).getItemCount(); will(returnValue(3)); //simulates item # 1 atLeast(1).of(data).getKey(0); will(returnValue(0)); atLeast(1).of(data).getValue(0); will(returnValue(-3)); //simulates item # 2 atLeast(1).of(data).getKey(1); will(returnValue(1)); atLeast(1).of(data).getValue(1); will(returnValue(1)); //simulates item # 3 atLeast(1).of(data).getKey(2); will(returnValue(2)); atLeast(1).of(data).getValue(2); will(returnValue(2)); } }); KeyedValues result = DataUtilities.getCumulativePercentages(data); mockingContext.assertIsSatisfied(); Number[] expecteds = {Double.NEGATIVE_INFINITY,Double.NEGATIVE_INFINITY,Double.NaN}; Number[] actuals = {0.0,0.0,0.0}; if(result.getItemCount() != 3) fail("Wrong amount of key returned"); for(int index = 0; index < result.getItemCount(); index++){ actuals[index] = result.getValue(index); } assertArrayEquals(expecteds, actuals); } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * 0 2 * 1 null * 2 2 */ // @Test // public void getCummulativePercentagesWithANullIndexValue() { //Fails // //setup // KeyedValues data = mockingContext.mock(KeyedValues.class); // mockingContext.checking(new Expectations() { // { // atLeast(1).of(data).getItemCount(); // will(returnValue(3)); // //simulates item # 1 // atLeast(1).of(data).getKey(0); // will(returnValue(0)); // atLeast(1).of(data).getValue(0); // will(returnValue(-3)); // //simulates item # 2 // atLeast(1).of(data).getKey(1); // will(returnValue(1)); // atLeast(1).of(data).getValue(1); // will(returnValue(null)); // //simulates item # 3 // atLeast(1).of(data).getKey(2); // will(returnValue(2)); // atLeast(1).of(data).getValue(2); // will(returnValue(2)); // } // }); // KeyedValues result = DataUtilities.getCumulativePercentages(data); // mockingContext.assertIsSatisfied(); // Number[] expecteds = {0.5,0.5,1.0}; // Number[] actuals = {0.0,0.0,0.0}; // if(result.getItemCount() != 3) fail("Wrong amount of key returned"); // for(int index = 0; index < result.getItemCount(); index++){ // actuals[index] = result.getValue(index); // } // assertArrayEquals(expecteds, actuals); // } /** * calling getCummulativePercentages() function from DataUtility using mocked KeyedValues. * Mocking a normal set of keys and values as followed: * key value * Null Null */ @Test(expected = IllegalArgumentException.class) public void getCummulativePercentagesWithNullPointerForData() { //Passed KeyedValues data = null; DataUtilities.getCumulativePercentages(data); } }
package com.janfranco.datifysongbasedmatchapplication; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class UserSelectListRecyclerAdapter extends RecyclerView.Adapter<UserSelectListRecyclerAdapter.UserHolder> { private ArrayList<User> users; private static Typeface metropolisLight; UserSelectListRecyclerAdapter(Context context, ArrayList<User> users) { metropolisLight = Typeface.createFromAsset(context.getAssets(), "fonts/Metropolis-Light.otf"); this.users = users; } @NonNull @Override public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.select_user_row, parent, false); return new UserHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull UserHolder holder, int position) { User user = users.get(position); if (!user.getAvatarUrl().equals("default")) Picasso.get().load(user.getAvatarUrl()).into(holder.avatar); holder.username.setText(user.getUsername()); holder.bio.setText(user.getBio()); } @Override public int getItemCount() { return users.size(); } static class UserHolder extends RecyclerView.ViewHolder { ImageView avatar; TextView username, bio; UserHolder(@NonNull View itemView) { super(itemView); avatar = itemView.findViewById(R.id.userSelectListAvatar); username = itemView.findViewById(R.id.userSelectListUsername); bio = itemView.findViewById(R.id.userSelectListBio); username.setTypeface(metropolisLight); bio.setTypeface(metropolisLight); } } }
package data; //A task class is what is needed to be done public class Task { private String mTodo; public Task(String todo) { mTodo = todo; } }
package cn.canlnac.onlinecourse.presentation.presenter; import android.support.annotation.NonNull; import javax.inject.Inject; import cn.canlnac.onlinecourse.data.exception.ResponseStatusException; import cn.canlnac.onlinecourse.domain.CommentList; import cn.canlnac.onlinecourse.domain.interactor.DefaultSubscriber; import cn.canlnac.onlinecourse.domain.interactor.UseCase; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import cn.canlnac.onlinecourse.presentation.mapper.CommentListModelDataMapper; import cn.canlnac.onlinecourse.presentation.ui.activity.CommentActivity; @PerActivity public class GetCommentsInChatPresenter implements Presenter { CommentActivity getCommentsInChatActivity; private final UseCase getCommentsInChatUseCase; private final CommentListModelDataMapper commentListModelDataMapper; private int state; @Inject public GetCommentsInChatPresenter(UseCase getCommentsInChatUseCase, CommentListModelDataMapper commentListModelDataMapper) { this.getCommentsInChatUseCase = getCommentsInChatUseCase; this.commentListModelDataMapper = commentListModelDataMapper; } public void setView(@NonNull CommentActivity getCommentsInChatActivity, int state) { this.getCommentsInChatActivity = getCommentsInChatActivity; this.state = state; } public void initialize() { this.getCommentsInChatUseCase.execute(new GetCommentsInChatPresenter.GetCommentsInChatSubscriber()); } @Override public void resume() { } @Override public void pause() { } @Override public void destroy() { this.getCommentsInChatUseCase.unsubscribe(); } private final class GetCommentsInChatSubscriber extends DefaultSubscriber<CommentList> { @Override public void onCompleted() { } @Override public void onError(Throwable e) { if (e instanceof ResponseStatusException) { switch (((ResponseStatusException)e).code) { case 400: if (state == 0) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showRefreshError("参数错误"); } break; case 404: if (state == 0) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showRefreshError("没有评论"); } break; default: if (state == 0) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showRefreshError("加载失败"); } GetCommentsInChatPresenter.this.getCommentsInChatActivity.showToastMessage("服务器错误:"+((ResponseStatusException)e).code); } } else { e.printStackTrace(); if (state == 0) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showRefreshError("加载失败"); } GetCommentsInChatPresenter.this.getCommentsInChatActivity.showToastMessage("网络连接错误"); } } @Override public void onNext(CommentList commentList) { if (state == 0) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showRefreshComments(commentListModelDataMapper.transform(commentList)); } else if (state == 1) { GetCommentsInChatPresenter.this.getCommentsInChatActivity.showLoadMoreComments(commentListModelDataMapper.transform(commentList)); } } } }
package cd.com.a.model; import java.io.Serializable; public class SelectedCardInfoDto implements Serializable { private String card_bin; private int install_month; private String card_corp_name; private String interest_free_install; public SelectedCardInfoDto() { } public SelectedCardInfoDto(String card_bin, int install_month, String card_corp_name, String interest_free_install) { super(); this.card_bin = card_bin; this.install_month = install_month; this.card_corp_name = card_corp_name; this.interest_free_install = interest_free_install; } public String getCard_bin() { return card_bin; } public void setCard_bin(String card_bin) { this.card_bin = card_bin; } public int getInstall_month() { return install_month; } public void setInstall_month(int install_month) { this.install_month = install_month; } public String getCard_corp_name() { return card_corp_name; } public void setCard_corp_name(String card_corp_name) { this.card_corp_name = card_corp_name; } public String getInterest_free_install() { return interest_free_install; } public void setInterest_free_install(String interest_free_install) { this.interest_free_install = interest_free_install; } @Override public String toString() { return "Selected_card_info [card_bin=" + card_bin + ", install_month=" + install_month + ", card_corp_name=" + card_corp_name + ", interest_free_install=" + interest_free_install + "]"; } }
package com.allianz.ExpenseTracker.Reports; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import com.allianz.ExpenseTracker.Objects.ObjectsExpenseReport; import com.allianz.ExpenseTracker.Panels.PnlBankItemDetailsAnzeigen; import com.allianz.ExpenseTracker.Panels.PnlItemDetailsAnzeigen; @SuppressWarnings("serial") public class PumBankTrackerReport extends JPopupMenu { ObjectsExpenseReport objReport = new ObjectsExpenseReport(); JMenuItem item1; JMenuItem item2; public PumBankTrackerReport() { } public PumBankTrackerReport(ObjectsExpenseReport objReport) { this.objReport = objReport; item1 = new JMenuItem("Edit "); item1.setEnabled(true); item1.setFont(new Font("Arial", Font.BOLD, 12)); item1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub PnlBankItemDetailsAnzeigen details = new PnlBankItemDetailsAnzeigen(objReport,"Y"); details.getFrmItemDetails().setVisible(true); } }); add(item1); item2 = new JMenuItem("Delete "); item2.setEnabled(true); item2.setFont(new Font("Arial", Font.BOLD, 12)); item2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub PnlBankItemDetailsAnzeigen details = new PnlBankItemDetailsAnzeigen(objReport,"D"); details.getFrmItemDetails().setVisible(true); } }); add(item2); show(objReport.getEditor(), objReport.getPosX(), objReport.getPosY()); } }
package lt.kvk.i11.radiukiene.utils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import lt.kvk.i11.radiukiene.controller.ReminderActivity; /** * Created by Vita on 4/23/2018. */ public class AlarmReceiver extends BroadcastReceiver { String TAG = "AlarmReceiver"; String street_id; DatabaseHandler databaseHandler; ArrayList<GS> notif = new ArrayList<>(); SessionManager sessionManager; HashMap<String, String> user; ReminderData localData; @Override public void onReceive(Context context, Intent intent) { databaseHandler = new DatabaseHandler(context); sessionManager = new SessionManager(context); user = sessionManager.getStreetDetails(); street_id = user.get(sessionManager.KEY_ID); notif = databaseHandler.getRemainderDb(street_id); localData = new ReminderData(context); if (intent.getAction() != null && context != null) { if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { // Set the alarm here. Log.d(TAG, "onReceive: BOOT_COMPLETED"); if (notif.size() > 0){ for (int i = 0; i<notif.size();i++){ NotificationScheduler.setReminder(context, AlarmReceiver.class, localData.get_hour(), localData.get_min()); } } return; } } Log.d(TAG, "onReceive: "); //Trigger the notification if (notif.size() > 0){ Calendar c = Calendar.getInstance(); System.out.println("Current time => " + c.getTime()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); c.add(Calendar.DATE, 1); String formattedDate = df.format(c.getTime()); for (int i = 0; i<notif.size();i++){ if (notif.get(i).wasteCollect_date.contains(formattedDate)) { NotificationScheduler.showNotification(context, ReminderActivity.class, "Kretingos komunalininkas", "Ryt išvežamos " + notif.get(i).title + " atliekos."); } } } } }
package zm.gov.moh.core.repository.database.entity.derived; import androidx.room.*; import com.squareup.moshi.Json; import org.threeten.bp.LocalDateTime; import androidx.room.ColumnInfo; import androidx.room.Entity; @Entity public class Client { @ColumnInfo(name = "patient_id") @Json(name = "patient_id") private long patientId; @ColumnInfo(name = "identifier") @Json(name = "identifier") private String identifier; @ColumnInfo(name = "given_name") @Json(name = "given_name") private String givenName; @ColumnInfo(name = "family_name") @Json(name = "family_name") private String familyName; @ColumnInfo(name = "gender") @Json(name = "gender") private String gender; @ColumnInfo(name = "birthdate") @Json(name = "birthdate") private LocalDateTime birthDate; public long getPatientId() { return patientId; } public void setPatientId(long patientId) { this.patientId = patientId; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public LocalDateTime getBirthDate() { return birthDate; } public void setBirthDate(LocalDateTime birthDate) { this.birthDate = birthDate; } }
package com.qunchuang.carmall.service.impl; import com.qunchuang.carmall.domain.Admin; import com.qunchuang.carmall.domain.privilege.Privilege; import com.qunchuang.carmall.domain.privilege.PrivilegeItem; import com.qunchuang.carmall.domain.privilege.Role; import com.qunchuang.carmall.domain.privilege.RoleItem; import com.qunchuang.carmall.enums.CarMallExceptionEnum; import com.qunchuang.carmall.enums.PrivilegeAuthorityEnum; import com.qunchuang.carmall.enums.RoleEnum; import com.qunchuang.carmall.exception.CarMallException; import com.qunchuang.carmall.repository.AdminRepository; import com.qunchuang.carmall.repository.PrivilegeRepository; import com.qunchuang.carmall.repository.RoleRepository; import com.qunchuang.carmall.service.AdminService; import com.qunchuang.carmall.utils.BeanCopyUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.session.jdbc.JdbcOperationsSessionRepository; import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestContextHolder; import java.util.*; /** * @author Curtain * @date 2019/1/16 9:39 */ @Service @Slf4j public class AdminServiceImpl implements AdminService { @Autowired private AdminRepository adminRepository; @Autowired RoleRepository roleRepository; @Autowired PrivilegeRepository privilegeRepository; @Autowired JdbcOperationsSessionRepository jdbcOperationsSessionRepository; @Override @PreAuthorize("hasAuthority('STORE_MANAGEMENT')") public Admin storeAdministrator(Admin admin) { return register(admin, RoleEnum.STORE_ADMINISTRATOR.getRoleName()); } @Override public void existsById(String id) { boolean sales = adminRepository.existsById(id); if (!sales) { log.error("分配失败,销售人员不存在 salesId = {}", id); throw new CarMallException(CarMallExceptionEnum.SALES_CONSULTANT_NOT_EXISTS); } } @Override public Admin changePassword(String oldPassword, String newPassword) { Admin admin = Admin.getAdmin(); // oldPassword = MD5Util.generate(oldPassword); if (oldPassword.equals(admin.getPassword())){ // admin.setPassword(MD5Util.generate(newPassword)); admin.setPassword(newPassword); //使源账号失效 jdbcOperationsSessionRepository.deleteById(RequestContextHolder.currentRequestAttributes().getSessionId()); return adminRepository.save(admin); } throw new CarMallException(CarMallExceptionEnum.PASSWORD_WRONG); } @Override public Admin changeOtherPassword(String username, String password) { //超级管理员改所有 门店管理员改旗下的销售员 Admin operator = Admin.getAdmin(); Optional<Admin> adminOptional = adminRepository.findByUsername(username); if (!adminOptional.isPresent()) { log.error("用户不存在,用户名 = {}", username); throw new CarMallException(CarMallExceptionEnum.ADMIN_NOT_EXISTS); } Admin admin = adminOptional.get(); //是否是超级管理员 boolean isSuperAdmin = operator.superAdmin(); //是否是门店管理员 并修改的是所属账号 boolean isStoreAdmin = operator.storeAdmin() && operator.getStore().getId().equals(admin.getStore().getId()); //符合修改条件 if (isSuperAdmin || isStoreAdmin) { //todo 加密 admin.setPassword(password); // admin.setPassword(MD5Util.generate(password)); Map map = jdbcOperationsSessionRepository.findByIndexNameAndIndexValue("org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME", admin.getUsername()); map.keySet().forEach(key->jdbcOperationsSessionRepository.deleteById((String) key)); return adminRepository.save(admin); } else { log.error("修改其他账号密码,无权限。 被修改用户名 = {}, 操作人用户名 = {}",admin.getName(),operator.getName()); throw new AccessDeniedException("权限不足"); } } @Override @PreAuthorize("hasAuthority('SALES_CONSULTANT_MANAGEMENT')") public Admin salesConsultant(Admin admin) { return register(admin, RoleEnum.SALES_CONSULTANT_ADMINISTRATOR.getRoleName()); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<Admin> admin = adminRepository.findByUsername(username); if (!admin.isPresent()) { log.error("登录失败,用户名不存在 username = ", username); throw new UsernameNotFoundException("user not exist"); } return admin.get(); } @Override @PreAuthorize("hasAuthority('PLATFORM_MANAGEMENT')") public Admin platformAdministrator(Admin admin) { //平台管理员无任何操作权限 只能浏览 return register(admin, RoleEnum.PLATFORM_ADMINISTRATOR.getRoleName()); } private Admin register(Admin admin, String roleName) { Admin rs = new Admin(); Role role = new Role(); Optional<Role> roleOptional; RoleItem roleItem = new RoleItem(); Optional<Admin> result = adminRepository.findByUsername(admin.getUsername()); if (result.isPresent()) { log.error("用户名已被注册,username = {}", admin.getUsername()); throw new CarMallException(CarMallExceptionEnum.USERNAME_IS_EXISTS); } switch (roleName) { case "平台管理员": roleOptional = roleRepository.findByName(RoleEnum.PLATFORM_ADMINISTRATOR.getRoleName()); if (!roleOptional.isPresent()) { role.setName(RoleEnum.PLATFORM_ADMINISTRATOR.getRoleName()); role = roleRepository.save(role); } else { role = roleOptional.get(); } break; case "销售顾问": roleOptional = roleRepository.findByName(RoleEnum.SALES_CONSULTANT_ADMINISTRATOR.getRoleName()); if (!roleOptional.isPresent()) { role.setName(RoleEnum.SALES_CONSULTANT_ADMINISTRATOR.getRoleName()); Optional<Privilege> privilege = privilegeRepository.findByPrivilege(PrivilegeAuthorityEnum.CUSTOMER_MANAGEMENT.getIdentifier()); PrivilegeItem privilegeItem = new PrivilegeItem(); privilegeItem.setPrivilege(privilege.get()); role.getPrivilegeItems().add(privilegeItem); role = roleRepository.save(role); } else { role = roleOptional.get(); } //绑定所属门店 Admin principal = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); rs.setStore(principal.getStore()); break; case "门店管理员": roleOptional = roleRepository.findByName(RoleEnum.STORE_ADMINISTRATOR.getRoleName()); if (!roleOptional.isPresent()) { role.setName(RoleEnum.STORE_ADMINISTRATOR.getRoleName()); Optional<Privilege> privilege = privilegeRepository.findByPrivilege(PrivilegeAuthorityEnum.SALES_CONSULTANT_MANAGEMENT.getIdentifier()); PrivilegeItem privilegeItem1 = new PrivilegeItem(); PrivilegeItem privilegeItem2 = new PrivilegeItem(); privilegeItem1.setPrivilege(privilege.get()); role.getPrivilegeItems().add(privilegeItem1); privilege = privilegeRepository.findByPrivilege(PrivilegeAuthorityEnum.CUSTOMER_MANAGEMENT.getIdentifier()); privilegeItem2.setPrivilege(privilege.get()); role.getPrivilegeItems().add(privilegeItem2); role = roleRepository.save(role); } else { role = roleOptional.get(); } //绑定门店 rs.setStore(admin.getStore()); break; default: break; } rs.setPhone(admin.getPhone()); rs.setUsername(admin.getUsername()); rs.setPassword(admin.getPassword()); //todo 加密 暂时注释 // rs.setPassword(MD5Util.generate(admin.getPassword())); rs.setName(admin.getName()); roleItem.setRole(role); rs.getRoleItems().add(roleItem); return adminRepository.save(rs); } @Override public String init(String curtain) { if (curtain.equals("wcp")) { Admin admin = new Admin(); admin.setUsername("test"); admin.setPassword("1"); admin.setPhone("13512343422"); PrivilegeItem privilegeItem1 = new PrivilegeItem(); PrivilegeItem privilegeItem2 = new PrivilegeItem(); PrivilegeItem privilegeItem3 = new PrivilegeItem(); PrivilegeItem privilegeItem4 = new PrivilegeItem(); PrivilegeItem privilegeItem5 = new PrivilegeItem(); Privilege privilege1 = new Privilege(); privilege1.setPrivilege(PrivilegeAuthorityEnum.CUSTOMER_MANAGEMENT.getIdentifier()); privilege1.setCategory(1); privilege1.setName("客户管理"); Privilege privilege2 = new Privilege(); privilege2.setPrivilege(PrivilegeAuthorityEnum.SALES_CONSULTANT_MANAGEMENT.getIdentifier()); privilege2.setName("销售顾问管理"); privilege2.setCategory(2); Privilege privilege3 = new Privilege(); privilege3.setPrivilege(PrivilegeAuthorityEnum.VEHICLE_MANAGEMENT.getIdentifier()); privilege3.setCategory(3); privilege3.setName("车辆管理"); Privilege privilege4 = new Privilege(); privilege4.setPrivilege(PrivilegeAuthorityEnum.STORE_MANAGEMENT.getIdentifier()); privilege4.setCategory(4); privilege4.setName("门店管理"); Privilege privilege5 = new Privilege(); privilege5.setPrivilege(PrivilegeAuthorityEnum.PLATFORM_MANAGEMENT.getIdentifier()); privilege5.setCategory(5); privilege5.setName("平台管理"); privilege1 = privilegeRepository.save(privilege1); privilege2 = privilegeRepository.save(privilege2); privilege3 = privilegeRepository.save(privilege3); privilege4 = privilegeRepository.save(privilege4); privilege5 = privilegeRepository.save(privilege5); privilegeItem1.setPrivilege(privilege1); privilegeItem2.setPrivilege(privilege2); privilegeItem3.setPrivilege(privilege3); privilegeItem4.setPrivilege(privilege4); privilegeItem5.setPrivilege(privilege5); Role role1 = new Role(); role1.setName("超级管理员"); role1.getPrivilegeItems().add(privilegeItem1); role1.getPrivilegeItems().add(privilegeItem2); role1.getPrivilegeItems().add(privilegeItem3); role1.getPrivilegeItems().add(privilegeItem4); role1.getPrivilegeItems().add(privilegeItem5); role1 = roleRepository.save(role1); RoleItem roleItem1 = new RoleItem(); roleItem1.setRole(role1); admin.getRoleItems().add(roleItem1); adminRepository.save(admin); return "初始化成功"; } return "操作失败"; } @Override // @PreAuthorize("authenticated && (#user.id==authentication.principal.id || hasAuthority('B1'))") public Admin delete(String id) { Admin admin = findOne(id); //将权限清空 admin.getRoleItems().clear(); //门店清空 admin.setStore(null); //将用户名无效化 admin.setUsername("invalid"+admin.getUsername() + admin.getCreatetime()); //拉黑 admin.isAble(); return adminRepository.save(admin); } @Override public Admin findOne(String id) { Optional<Admin> admin = adminRepository.findById(id); if (!admin.isPresent()) { log.error("查找管理员:用户不存在 id = ", id); throw new CarMallException(CarMallExceptionEnum.ADMIN_NOT_EXISTS); } return admin.get(); } /** * 配置了修改权限 只有用户本身能修改 或者 包含(管理这个权限) * * @param admin * @return */ @Override // @PreAuthorize("authenticated && (#user.id==authentication.principal.id || hasAuthority('B1'))") public Admin update(Admin admin) { //todo 只有用户管理员可以修改 或者 自己改自己本身的 password 不能被修改 //todo 超级管理员admin的权限和角色不允许修改 Admin result = findOne(admin.getId()); Set<String> filter = new HashSet<>(); filter.add("password"); filter.add("store"); filter.add("roleItems"); filter.add("username"); BeanUtils.copyProperties(admin, result, BeanCopyUtil.filterProperty(admin, filter)); admin.privilegeCheck(); return adminRepository.save(result); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.vaidya.statistics.job; import java.util.ArrayList; import org.apache.hadoop.mapred.JobConf; public interface JobStatisticsInterface { /** * Get job configuration (job.xml) values */ public JobConf getJobConf(); /* * Get Job Counters of type long */ public long getLongValue(Enum key); /* * Get job Counters of type Double */ public double getDoubleValue(Enum key); /* * Get Job Counters of type String */ public String getStringValue(Enum key); /* * Set key value of type long */ public void setValue(Enum key, long value); /* * Set key value of type double */ public void setValue(Enum key, double valye); /* * Set key value of type String */ public void setValue(Enum key, String value); /** * @return mapTaskList : ArrayList of MapTaskStatistics * @param mapTaskSortKey : Specific counter key used for sorting the task list * @param dataType : indicates the data type of the counter key used for sorting * If sort key is null then by default map tasks are sorted using map task ids. */ public ArrayList<MapTaskStatistics> getMapTaskList(Enum mapTaskSortKey, KeyDataType dataType); /** * @return reduceTaskList : ArrayList of ReduceTaskStatistics * @param reduceTaskSortKey : Specific counter key used for sorting the task list * @param dataType : indicates the data type of the counter key used for sorting * If sort key is null then, by default reduce tasks are sorted using task ids. */ public ArrayList<ReduceTaskStatistics> getReduceTaskList(Enum reduceTaskSortKey, KeyDataType dataType); /* * Print the Job Execution Statistics */ public void printJobExecutionStatistics(); /* * Job and Task statistics Key data types */ public static enum KeyDataType { STRING, LONG, DOUBLE } /** * Job Keys */ public static enum JobKeys { JOBTRACKERID, JOBID, JOBNAME, JOBTYPE, USER, SUBMIT_TIME, CONF_PATH, LAUNCH_TIME, TOTAL_MAPS, TOTAL_REDUCES, STATUS, FINISH_TIME, FINISHED_MAPS, FINISHED_REDUCES, FAILED_MAPS, FAILED_REDUCES, LAUNCHED_MAPS, LAUNCHED_REDUCES, RACKLOCAL_MAPS, DATALOCAL_MAPS, HDFS_BYTES_READ, HDFS_BYTES_WRITTEN, FILE_BYTES_READ, FILE_BYTES_WRITTEN, COMBINE_OUTPUT_RECORDS, COMBINE_INPUT_RECORDS, REDUCE_INPUT_GROUPS, REDUCE_INPUT_RECORDS, REDUCE_OUTPUT_RECORDS, MAP_INPUT_RECORDS, MAP_OUTPUT_RECORDS, MAP_INPUT_BYTES, MAP_OUTPUT_BYTES, MAP_HDFS_BYTES_WRITTEN, JOBCONF, JOB_PRIORITY, SHUFFLE_BYTES, SPILLED_RECORDS } /** * Map Task Keys */ public static enum MapTaskKeys { TASK_ID, TASK_TYPE, START_TIME, STATUS, FINISH_TIME, HDFS_BYTES_READ, HDFS_BYTES_WRITTEN, FILE_BYTES_READ, FILE_BYTES_WRITTEN, COMBINE_OUTPUT_RECORDS, COMBINE_INPUT_RECORDS, OUTPUT_RECORDS, INPUT_RECORDS, INPUT_BYTES, OUTPUT_BYTES, NUM_ATTEMPTS, ATTEMPT_ID, HOSTNAME, SPLITS, SPILLED_RECORDS, TRACKER_NAME, STATE_STRING, HTTP_PORT, ERROR, EXECUTION_TIME } /** * Reduce Task Keys */ public static enum ReduceTaskKeys { TASK_ID, TASK_TYPE, START_TIME, STATUS, FINISH_TIME, HDFS_BYTES_READ, HDFS_BYTES_WRITTEN, FILE_BYTES_READ, FILE_BYTES_WRITTEN, COMBINE_OUTPUT_RECORDS, COMBINE_INPUT_RECORDS, OUTPUT_RECORDS, INPUT_RECORDS, NUM_ATTEMPTS, ATTEMPT_ID, HOSTNAME, SHUFFLE_FINISH_TIME, SORT_FINISH_TIME, INPUT_GROUPS, TRACKER_NAME, STATE_STRING, HTTP_PORT, SPLITS, SHUFFLE_BYTES, SPILLED_RECORDS, EXECUTION_TIME } }
package com.techelevator; import org.junit.Test; import org.junit.Assert; public class KataStringCalculatorTest { @Test public void empty_string_returns_zero() { // arrange final String emptyString = ""; final int expectedNumber = 0; // act int output = KataStringCalculator.add(emptyString); // assert Assert.assertEquals("Empty string needs to return zero", expectedNumber, output); } @Test public void single_number_returns_itself() { // arrange final String soloNumber = "1"; final int expectedNumber = 1; // act int output = KataStringCalculator.add(soloNumber); // assert Assert.assertEquals("Single number passed in needs to return itself as a int", expectedNumber, output); } @Test public void two_string_numbers_return_an_int_sum() { // arrange final String twoNumbers = "1,2"; final int expectedNumber = 3; // act int output = KataStringCalculator.add(twoNumbers); // assert Assert.assertEquals("Two numbers passed are added and a sum int is returned", expectedNumber, output); } @Test public void three_string_numbers_return_an_int_sum() { final String threeNumbers = "5,7,12"; final int expectedNumber = 24; int output = KataStringCalculator.add(threeNumbers); Assert.assertEquals("Three numbers passed are added and a sum int is returned", expectedNumber, output); } @Test public void four_string_numbers_return_an_int_sum() { final String fourNumbers = "6,2,1,8"; final int expectedNumber = 17; int output = KataStringCalculator.add(fourNumbers); Assert.assertEquals("Four numbers passed are added and a sum int is returned", expectedNumber, output); } @Test public void new_line_divided_string_numbers_return_an_int_sum_three_numbers() { final String newLineNumbers = "5\n3,2"; final int expectedNumber = 10; int output = KataStringCalculator.add(newLineNumbers); Assert.assertEquals("Three numbers passed are added and a sum int is returned", expectedNumber, output); } @Test public void new_line_divided_string_numbers_return_an_int_sum_four_numbers() { final String newLineNumbers = "3\n5\n2,4"; final int expectedNumber = 14; int output = KataStringCalculator.add(newLineNumbers); Assert.assertEquals("Four numbers passed are added and a sum int is returned", expectedNumber, output); } /* @Test public void semicoma_divided_string_numbers_return_an_int_sum_two_numbers() { final String newDelimeatsNumbers = "//;\n1;2"; final int expectedNumber = 3; int output = KataStringCalculator.add(newDelimeatsNumbers); Assert.assertEquals("two numbers passed are added and a sum int is returned when there are semicolans and weirdness", expectedNumber, output); } */ }
/** * */ package died.guia06; /** * @author yamil * */ public class RegistroAuditoriaException extends Exception { public RegistroAuditoriaException(String mensaje) { super (mensaje); } }
package jneiva.hexbattle.componente; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import jneiva.hexbattle.Constantes; import jneiva.hexbattle.ControladorEstrutura; import jneiva.hexbattle.TipoUnidade; import jneiva.hexbattle.unidade.Estrutura; public class Quartel extends Componente { private Skin skin; private Stage cena; private ControladorEstrutura controladorEstrutura; public Quartel(Stage cena, ControladorEstrutura controladorEstrutura) { this.cena = cena; this.controladorEstrutura = controladorEstrutura; } @Override public void acordar() { super.acordar(); skin = new Skin(Gdx.files.internal(Constantes.caminhoSkin)); } public void abrirJanela() { Estrutura estrutura = (Estrutura) this.getEntidade(); Dialog janela = new Dialog("Castelo", skin) { public void result(Object obj) { if (!obj.equals("cancelar")) { controladorEstrutura.unidadeEscolhida((String) obj, estrutura); } } }; janela.text("Escolha uma unidade"); janela.button("Guerreiro\n100 gold", "guerreiro"); janela.button("Arqueiro\n200 gold", "arqueiro"); janela.button("Assassino\n250 gold", "assassino"); janela.button("Gigante\n350 gold", "gigante"); janela.button("Cancelar", "cancelar"); janela.show(cena); } }
package com.meroapp.meroblog.dao; import java.util.List; import com.meroapp.meroblog.model.Feedback; public interface FeedbackDao { public void insertFeedback(Feedback fb) ; public List<Feedback> getAllFeedback(); }
package com.smxknfie.jms.demo01; import javax.jms.*; public class Chat implements MessageListener { private TopicSession session; private TopicPublisher publisher; private TopicConnection connection; private String userName; public Chat(String topicFactory, String topicName, String userName) { } @Override public void onMessage(Message message) { } }
package com.gmail.merikbest2015.ecommerce.controller; import com.gmail.merikbest2015.ecommerce.domain.Perfume; import com.gmail.merikbest2015.ecommerce.domain.User; import com.gmail.merikbest2015.ecommerce.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; /** * Customer shopping cart controller class. * This controller and related pages can be accessed by all users, regardless of their roles. * The @Controller annotation serves to inform Spring that this class is a bean and must be * loaded when the application starts. * * @author Miroslav Khotinskiy (merikbest2015@gmail.com) * @version 1.0 * @see User * @see UserService */ @Controller public class CartController { /** * Service object for working with customer shopping cart. */ private final UserService userService; /** * Constructor for initializing the main variables of the cart controller. * The @Autowired annotation will allow Spring to automatically initialize objects. * * @param userService service object for working with user shopping cart. */ @Autowired public CartController(UserService userService) { this.userService = userService; } /** * Returns customer shopping cart. * URL request {"/cart"}, method GET. * * @param userSession requested Authenticated customer. * @param model class object {@link Model}. * @return cart page with model attributes. */ @GetMapping("/cart") public String getCart(@AuthenticationPrincipal User userSession, Model model) { User userFromDB = userService.findByUsername(userSession.getUsername()); model.addAttribute("perfumes", userFromDB.getPerfumeList()); return "cart"; } /** * Adds a product to the customer shopping cart and redirects it to "/cart". * URL request {"/cart/add"}, method POST. * * @param perfume the product to add to the cart. * @param userSession request Authenticated customer. * @return redirect to cart page. */ @PostMapping("/cart/add") public String addToCart( @RequestParam("add") Perfume perfume, @AuthenticationPrincipal User userSession ) { User user = userService.findByUsername(userSession.getUsername()); user.getPerfumeList().add(perfume); userService.save(user); return "redirect:/cart"; } /** * Remove product from customer shopping cart and redirects it to "/cart". * URL request {"/cart/remove"}, method POST. * * @param perfume the product to be removed from the customer shopping cart. * @param userSession request Authenticated customer. * @return redirect to cart page. */ @PostMapping("/cart/remove") public String removeFromCart( @RequestParam(value = "perfumeId") Perfume perfume, @AuthenticationPrincipal User userSession ) { User user = userService.findByUsername(userSession.getUsername()); if (perfume != null) { user.getPerfumeList().remove(perfume); } userService.save(user); return "redirect:/cart"; } }
package de.rwth.i9.palm.persistence; import java.util.List; import java.util.Map; import de.rwth.i9.palm.model.EventGroup; public interface EventGroupDAO extends GenericDAO<EventGroup>, InstantiableDAO { /** * Trigger batch indexing using Hibernate search powered by Lucene * * @throws InterruptedException */ public void doReindexing() throws InterruptedException; /** * Get Event Group by name or notation * * @param eventNameOrNotation * @return */ public EventGroup getEventGroupByEventNameOrNotation( String eventNameOrNotation ); /** * Get event group as list based on given parameters * * @param queryString * @param type * @param pageNo * @param maxResult * @param addedVenue * @return */ public List<EventGroup> getEventGroupListWithPaging( String queryString, String type, int pageNo, int maxResult, String addedVenue ); /** * Get event group as map based on given parameters * * @param queryString * @param type * @param pageNo * @param maxResult * @return */ public Map<String, Object> getEventGroupMapWithPaging( String queryString, String type, int pageNo, int maxResult, String addedVenue ); /** * Get event group as list based on given parameters, with full text search * * @param queryString * @param type * @param pageNo * @param maxResult * @return */ public List<EventGroup> getEventGroupListFullTextSearchWithPaging( String queryString, String type, int pageNo, int maxResult, String addedVenue ); /** * Get event group as map based on given parameters, with full text search * * @param queryString * @param notation * @param type * @param pageNo * @param maxResult * @param addedVenue * @return */ public Map<String, Object> getEventGroupMapFullTextSearchWithPaging( String queryString, String notation, String type, int pageNo, int maxResult, String addedVenue ); /** * Get similar eventGroup, given EventGroup to be compared * * @param evemntGroupCompareTo * @return */ public EventGroup getSimilarEventGroup( EventGroup eventGroupCompareTo ); }
package com.tencent.mm.plugin.honey_pay.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.protocal.c.amn; class HoneyPayMainUI$5 implements OnClickListener { final /* synthetic */ HoneyPayMainUI klC; final /* synthetic */ amn klF; HoneyPayMainUI$5(HoneyPayMainUI honeyPayMainUI, amn amn) { this.klC = honeyPayMainUI; this.klF = amn; } public final void onClick(View view) { HoneyPayMainUI.a(this.klC, this.klF.rIw, this.klF.hwg); } }
package my.application.controller; import my.application.entity.DailyBalance; import my.application.entity.Meal; import my.application.entity.User; import my.application.helper.ContextHelper; import my.application.helper.DailyBalanceHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import my.application.helper.NumberHelper; import my.application.pojo.DailyBalanceData; import my.application.pojo.ExtendMacro; import my.application.pojo.GraphResult; import my.application.repository.DailyBalanceRepository; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @RequestMapping("/diet/daily") @Controller public class DailyBalanceController { @Autowired private DailyBalanceRepository dailyBalanceRepository; @Autowired private DailyBalanceHelper dailyBalanceHelper; @Autowired private NumberHelper numberHelper; @RequestMapping("/actual") public String actualBalance(Model model){ User user = ContextHelper.getUserFromContext(); double totalProtein = user.getTotalProtein(); double totalCarbohydrates = user.getTotalCarbohydrates(); double totalFat = user.getTotalFat(); int totalCalories = user.getTotalCalories(); if(dailyBalanceRepository.findTopByUserIdAndDate(user.getId(), Date.valueOf(LocalDate.now())) == null){ model.addAttribute("balance", "balance"); model.addAttribute("exist", null); return "home"; } ExtendMacro extendMacro = new ExtendMacro(); DailyBalance dailyBalance = dailyBalanceRepository.findTopByUserIdAndDate(user.getId(), Date.valueOf(LocalDate.now())); List<Meal> meals = dailyBalance.getMeals(); meals.sort((m1, m2) -> Integer.compare(m1.getMealNumber(), m2.getMealNumber())); List<Double> glycemicCharges = new ArrayList<>(); meals.forEach(m -> { extendMacro.setProtein(extendMacro.getProtein() + m.getTotalProtein()); extendMacro.setCarbohydrates(extendMacro.getCarbohydrates() + m.getTotalCarbohydrates()); extendMacro.setFat(extendMacro.getFat() + m.getTotalFat()); extendMacro.setCalories(extendMacro.getCalories() + m.getTotalCalories()); glycemicCharges.add(m.getGlycemicCharge()); }); int protein = (int) (extendMacro.getProtein() * 100 / totalProtein); int carbohydrates = (int) (extendMacro.getCarbohydrates() * 100 / totalCarbohydrates); int fat = (int) (extendMacro.getFat() * 100 / totalFat); int calories = extendMacro.getCalories() * 100 / totalCalories; List<GraphResult> results = new ArrayList<>(); results.add(new GraphResult("Białko: " + formatMacroData(extendMacro.getProtein(), totalProtein), protein + "%", "width: " + (protein * 3) + "px; background-color: green;", true)); results.add(new GraphResult("Węglowodany: " + formatMacroData(extendMacro.getCarbohydrates(), totalCarbohydrates), carbohydrates + "%", "width: " + (carbohydrates * 3) + "px; background-color: red;", true)); results.add(new GraphResult("Tłuszcz: " + formatMacroData(extendMacro.getFat(), totalFat), fat + "%", "width: " + (fat * 3) + "px; background-color: yellow;", true)); results.add(new GraphResult("Kalorie: " + extendMacro.getCalories() + "/" + totalCalories, calories + "%", "width: " + (calories * 3) + "px; background-color: blue;", true)); results.add(new GraphResult("%", "", "", false)); for(int i = 0; i < glycemicCharges.size(); i++){ results.add(new GraphResult("Posiłek " + (i + 1), numberHelper.roundDouble(glycemicCharges.get(i)) + "","width: " + ((int)(glycemicCharges.get(i) * 30) / 2) + "px; background-color: orange;", true)); } results.add(new GraphResult("", "", "", false)); model.addAttribute("results", results); model.addAttribute("exist", "exist"); model.addAttribute("balance", "balance"); return "home"; } @RequestMapping(value = "/weekly") public String last(Model model){ User user = ContextHelper.getUserFromContext(); Object dailyObject = dailyBalanceRepository.findAllByUserToDate(user, Date.valueOf(LocalDate.now()), Date.valueOf(LocalDate.now().minusDays(7))); if(dailyObject == null || ((List) dailyObject).size() == 0){ model.addAttribute("balance", "balance"); model.addAttribute("exist", null); model.addAttribute("days", 0); return "home"; } List<DailyBalance> dailyBalances = (List<DailyBalance>)dailyObject; int days = dailyBalances.size(); DailyBalanceData data = dailyBalanceHelper.getBalance(dailyBalances, true); if((data.getNeededMacro().getProtein() == 0) || (data.getNeededMacro().getCarbohydrates() == 0) || (data.getNeededMacro().getFat() == 0) || (data.getNeededMacro().getCalories() == 0)){ model.addAttribute("balance", "balance"); model.addAttribute("exist", null); model.addAttribute("days", 0); return "home"; } int protein = (int) (data.getReceivedMacro().getProtein() * 100 / data.getNeededMacro().getProtein()); int carbohydrates = (int) (data.getReceivedMacro().getCarbohydrates() * 100 / data.getNeededMacro().getCarbohydrates()); int fat = (int) (data.getReceivedMacro().getFat() * 100 / data.getNeededMacro().getFat()); int calories = data.getReceivedMacro().getCalories() * 100 / data.getNeededMacro().getCalories(); List<GraphResult> results = new ArrayList<>(); results.add(new GraphResult("Białko: " + formatMacroData(data.getReceivedMacro().getProtein(), data.getNeededMacro().getProtein()), protein + "%", "width: " + (protein * 3) + "px; background-color: green;", true)); results.add(new GraphResult("Węglowodany: " + formatMacroData(data.getReceivedMacro().getCarbohydrates(), data.getNeededMacro().getCarbohydrates()), carbohydrates + "%", "width: " + (carbohydrates * 3) + "px; background-color: red;", true)); results.add(new GraphResult("Tłuszcz: " + formatMacroData(data.getReceivedMacro().getFat(), data.getNeededMacro().getFat()), fat + "%", "width: " + (fat * 3) + "px; background-color: yellow;", true)); results.add(new GraphResult("Kalorie: " + data.getReceivedMacro().getCalories() + "/" + data.getNeededMacro().getCalories(), calories + "%", "width: " + (calories * 3) + "px; background-color: blue;", true)); results.add(new GraphResult("%", "", "", false)); List<Object> objectsList = data.getDataList(); for(int i = 0; i < objectsList.size(); i++){ double number = (Double) objectsList.get(i); results.add(new GraphResult("Dzień " + (i + 1), numberHelper.roundDouble(number) + "","width: " + ((int)(number * 30) / 2) + "px; background-color: orange;", true)); } results.add(new GraphResult("", "", "", false)); data.clearAll(); model.addAttribute("results", results); model.addAttribute("exist", "exist"); model.addAttribute("balance", "balance"); model.addAttribute("days", days); return "home"; } @RequestMapping(value = "/long") public String longBalance(Model model){ User user = ContextHelper.getUserFromContext(); Object dailyObject = dailyBalanceRepository.findAllByUserToDate(user, Date.valueOf(LocalDate.now()), Date.valueOf(LocalDate.now().minusDays(30))); if(dailyObject == null || ((List) dailyObject).size() == 0){ model.addAttribute("longBalance", "longBalance"); model.addAttribute("exist", null); return "home"; } List<DailyBalance> dailyBalances = (List<DailyBalance>)dailyObject; int days = dailyBalances.size(); Collections.reverse(dailyBalances); DailyBalanceData data = dailyBalanceHelper.getBalance(dailyBalances, false); if((data.getNeededMacro().getProtein() == 0) || (data.getNeededMacro().getCarbohydrates() == 0) || (data.getNeededMacro().getFat() == 0) || (data.getNeededMacro().getCalories() == 0)){ model.addAttribute("longBalance", "longBalance"); model.addAttribute("exist", null); return "home"; } int avgProtein = (int)((data.getReceivedMacro().getProtein() / data.getNeededMacro().getProtein()) * 100); int avgCarbohydrates = (int)((data.getReceivedMacro().getCarbohydrates() / data.getNeededMacro().getCarbohydrates()) * 100); int avgFat = (int)((data.getReceivedMacro().getFat() / data.getNeededMacro().getFat()) * 100 ); int avgCalories = (data.getReceivedMacro().getCalories() * 100) / data.getNeededMacro().getCalories(); data.clearAll(); model.addAttribute("avgProtein", avgProtein); model.addAttribute("avgCarbohydrates", avgCarbohydrates); model.addAttribute("avgFat", avgFat); model.addAttribute("avgCalories", avgCalories); model.addAttribute("balances", dailyBalances); model.addAttribute("exist", "exist"); model.addAttribute("longBalance", "longBalance"); model.addAttribute("days", days); return "home"; } @RequestMapping(value = "/option", method = RequestMethod.GET) public String option(Model model){ model.addAttribute("balanceOption","balanceOption"); return "home"; } private String formatMacroData(double received, double total){ return numberHelper.roundDouble(received) + "/" + numberHelper.roundDouble(total); } }
/** */ package contain.impl; import contain.*; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class ContainFactoryImpl extends EFactoryImpl implements ContainFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ContainFactory init() { try { ContainFactory theContainFactory = (ContainFactory)EPackage.Registry.INSTANCE.getEFactory("http://www.example.com/contain"); if (theContainFactory != null) { return theContainFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new ContainFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ContainFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case ContainPackage.E1: return createE1(); case ContainPackage.E2: return createE2(); case ContainPackage.E3: return createE3(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public E1 createE1() { E1Impl e1 = new E1Impl(); return e1; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public E2 createE2() { E2Impl e2 = new E2Impl(); return e2; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public E3 createE3() { E3Impl e3 = new E3Impl(); return e3; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ContainPackage getContainPackage() { return (ContainPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static ContainPackage getPackage() { return ContainPackage.eINSTANCE; } } //ContainFactoryImpl
package servlet; import java.sql.Date; public class ValoriGlicemici { public ValoriGlicemici(int mattina, int pomeriggio, int sera, String email, Date data) { super(); this.mattina = mattina; this.pomeriggio = pomeriggio; this.sera = sera; this.email = email; this.data = data; } public int getMattina() { return mattina; } public void setMattina(int mattina) { this.mattina = mattina; } public int getPomeriggio() { return pomeriggio; } public void setPomeriggio(int pomeriggio) { this.pomeriggio = pomeriggio; } public int getSera() { return sera; } public void setSera(int sera) { this.sera = sera; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } private int mattina, pomeriggio, sera; private String email; private Date data; }
package communication.packets.request.admin; import communication.enums.PacketType; import communication.packets.AuthenticatedRequestPacket; import communication.packets.Packet; import communication.packets.response.DownloadFileResponsePacket; import communication.wrapper.Connection; import main.Conference; import user.Attendee; /** * This packet can be used by an admin to request a QR-Code file download for a single attendee. * Responds with a {@link DownloadFileResponsePacket}. */ public class DownloadQRRequestPacket extends AuthenticatedRequestPacket { private int id; /** * @param id the id of the attendee to download a qr file for */ public DownloadQRRequestPacket(int id) { super(PacketType.DOWNLOAD_QR_REQUEST); this.id = id; } @Override public void handle(Conference conference, Connection connection) { if(isPermitted(conference, connection, true)) { Attendee attendee = conference.getAttendeeData(id); byte[] qrFile = conference.getQrCode(id); Packet response = new DownloadFileResponsePacket(qrFile, attendee.getUserName().replace(" ", "_") + ".png"); response.send(connection); } } }
package com.example.custom; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; import com.example.custom.widget.DrawRelativeLayout; /** * Created by ouyangshen on 2017/10/14. */ public class ShowDrawActivity extends AppCompatActivity { private DrawRelativeLayout drl_content; // 声明一个绘画布局对象 private Button btn_center; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_draw); // 从布局文件中获取名叫drl_content的绘画布局 drl_content = findViewById(R.id.drl_content); btn_center = findViewById(R.id.btn_center); initTypeSpinner(); } // 初始化绘图方式的下拉框 private void initTypeSpinner() { ArrayAdapter<String> drawAdapter = new ArrayAdapter<String>(this, R.layout.item_select, descArray); Spinner sp_draw = findViewById(R.id.sp_draw); sp_draw.setPrompt("请选择绘图方式"); sp_draw.setAdapter(drawAdapter); sp_draw.setOnItemSelectedListener(new DrawSelectedListener()); sp_draw.setSelection(0); } private String[] descArray = {"不画图", "画矩形", "画圆角矩形", "画圆圈", "画椭圆", "onDraw画叉叉", "dispatchDraw画叉叉"}; private int[] typeArray = {0, 1, 2, 3, 4, 5, 6}; class DrawSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { int type = typeArray[arg2]; if (type == 5 || type == 6) { btn_center.setVisibility(View.VISIBLE); } else { btn_center.setVisibility(View.GONE); } // 设置绘图布局的绘制类型 drl_content.setDrawType(type); } public void onNothingSelected(AdapterView<?> arg0) {} } }
package com.tencent.mm.ipcinvoker; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.os.Process; import android.util.Log; import com.tencent.mm.ipcinvoker.h.b; import java.io.FileInputStream; import java.util.List; import junit.framework.Assert; public final class e { public static Context dmA; private static String dmB; public static Context getContext() { Assert.assertNotNull("IPCInvoker not initialize.", dmA); return dmA; } public static boolean fC(String str) { return str != null && str.equals(Cs()); } public static String Cs() { if (dmB == null || dmB.length() == 0) { dmB = t(dmA, Process.myPid()); } return dmB; } private static String t(Context context, int i) { Throwable e; if (context == null) { return null; } ActivityManager activityManager = (ActivityManager) context.getSystemService("activity"); if (activityManager != null) { List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses(); if (!(runningAppProcesses == null || runningAppProcesses.isEmpty())) { for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) { if (runningAppProcessInfo.pid == i) { return runningAppProcessInfo.processName; } } } } byte[] bArr = new byte[128]; FileInputStream fileInputStream; try { fileInputStream = new FileInputStream("/proc/" + i + "/cmdline"); try { int read = fileInputStream.read(bArr); if (read > 0) { int i2 = 0; while (i2 < read) { if (bArr[i2] > Byte.MIN_VALUE || bArr[i2] <= (byte) 0) { read = i2; break; } i2++; } String str = new String(bArr, 0, read); try { fileInputStream.close(); return str; } catch (Exception e2) { return str; } } try { fileInputStream.close(); } catch (Exception e3) { } return null; } catch (Exception e4) { e = e4; try { b.e("IPC.IPCInvokeLogic", "get running process error : %s", new Object[]{Log.getStackTraceString(e)}); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e5) { } } return null; } catch (Throwable th) { e = th; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e6) { } } throw e; } } } catch (Exception e7) { e = e7; fileInputStream = null; b.e("IPC.IPCInvokeLogic", "get running process error : %s", new Object[]{Log.getStackTraceString(e)}); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e52) { } } return null; } catch (Throwable th2) { e = th2; fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e62) { } } throw e; } } }
package leetcode; import java.text.DecimalFormat; import java.util.Random; /** * @Author: Mr.M * @Date: 2019-02-26 20:34 * @Description: https://leetcode-cn.com/problems/sqrtx/solution/ **/ public class T69x的平方根 { // public static int mySqrt(int x) { // if (x == 0 || x == 1) { // return x; // } // int l = 1, r = x, res = 0; // while (l <= r) { // int m = (l + r) / 2; // if (m == x / m) { // return m; // } else if (m > x / m) { // r = m - 1; // } else { // l = m + 1; // res = m; // } // } // return res; // } public static double mySqrt(double x) { if (x == 0 || x == 1) { return x; } double l = 0, r = x, res = 0; while (r - l > 0.0000001) { // while (r - l > 0.00000000000000001) { double m = (l + r) / 2; if (m == x / m) { return m; } else if (m > x / m) { // r = m - 1; r = m; } else { // l = m + 1; l = m; // res = m; } } return (r+l)/2; } public static void main(String[] args) { DecimalFormat df = new DecimalFormat("0.000000"); System.out.println(df.format(mySqrt(8))); System.out.println(df.format(Math.sqrt(8)) ); } }
package com.ev.srv.demopai.service; import com.evo.api.springboot.exception.ApiException; import com.ev.srv.demopai.model.GeneralProperties; import java.util.Map; import com.ev.srv.demopai.model.RequestWrapperGeneralProperties; import com.ev.srv.demopai.model.RequestWrapperInbox; import com.ev.srv.demopai.model.RequestWrapperMapStringString; import com.evo.api.springboot.exception.ApiException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Optional; /** * A delegate to be called by the {@link PropertiesController}}. * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ public interface PropertiesService { /** * Delete an inbox of the user. * * @return */ String deleteInbox(String inbox,String codigoEntidad,String usuarioBE,String acuerdoBE) throws ApiException; /** * Delete a property of the user. * * @return */ String deleteProperty(String property,String codigoEntidad,String usuarioBE,String acuerdoBE) throws ApiException; /** * Return the requested property. * * @return */ Map<String, Map<String> getProfile(String codigoEntidad,String usuarioBE,String othersAssociatedEB) throws ApiException; /** * Return the user properties. * * @return */ GeneralProperties getProperties(String codigoEntidad,String usuarioBE,String acuerdoBE) throws ApiException; /** * Create a new inbox. * * @return */ GeneralProperties newInbox(RequestWrapperInbox body) throws ApiException; /** * Create a property of the user if it doesn?t exists or modify it if it does. * * @return */ GeneralProperties newProperty(RequestWrapperMapStringString body) throws ApiException; /** * Modify properties of the user. * * @return */ GeneralProperties updateProperties(RequestWrapperGeneralProperties body) throws ApiException; }
package com.cnk.travelogix.supplier.mappings.services; import com.cnk.travelogix.supplier.mappings.country.model.SupplierCountryMappingModel; /** * The Interface SupplierCountryMappingService. */ public interface SupplierCountryMappingService extends SupplierMappingService<SupplierCountryMappingModel> { }
package foundation.privacybydesign.ideal.common; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; public class IDealResponse extends IDealMessage { public IDealResponse(Document doc) { super(doc); } public static IDealResponse get(InputStream stream) throws IOException, SAXException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().parse(stream); String name = doc.getDocumentElement().getLocalName(); if (name.equals("AcquirerErrorRes")) { return new IDealErrorResponses(doc); } else { // TODO: more response types return new IDealResponse(doc); } } catch (ParserConfigurationException e) { throw new RuntimeException("unexpected XML exception"); } } }
package de.raidcraft.skillsandeffects.pvp.effects.debuff; import de.raidcraft.skills.api.character.CharacterTemplate; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.effect.EffectInformation; import de.raidcraft.skills.api.effect.types.ExpirableEffect; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.persistance.EffectData; import de.raidcraft.skillsandeffects.pvp.skills.healing.Layhands; /** * @author Silthus */ @EffectInformation( name = "Lay Hands", description = "Verhindert dass du in der nächsten Zeit von Handauflegen betroffen sein kannst.", types = {EffectType.DEBUFF} ) public class LayhandsEffect extends ExpirableEffect<Layhands> { public LayhandsEffect(Layhands source, CharacterTemplate target, EffectData data) { super(source, target, data); } @Override protected void apply(CharacterTemplate target) throws CombatException { } @Override protected void renew(CharacterTemplate target) throws CombatException { } @Override protected void remove(CharacterTemplate target) throws CombatException { } }
/* */ package com.cleverfishsoftware.loadgenerator.sender.jms.spring; import com.cleverfishsoftware.loadgenerator.MessageSender; /** * * @author peter */ public class SpringJMSMessender implements MessageSender { @Override public void send(String payload) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package org.ah.minecraft.armour.mobs; import java.util.ArrayList; import java.util.List; import org.ah.minecraft.armour.utils.ArmourUtil; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Skeleton; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; public class SkeletonWariorController extends CustomEntityController { public SkeletonWariorController(int weight) { super(weight); } @Override public LivingEntity spawn(Location loc) { Skeleton skeleton = (Skeleton) loc.getWorld().spawnEntity(loc, EntityType.SKELETON); EntityEquipment eqip = skeleton.getEquipment(); ItemStack helmet = ArmourUtil.createWariorHelmet(); eqip.setHelmet(helmet); eqip.setHelmetDropChance(1.0F); eqip.setItemInMainHand(new ItemStack(Material.STONE_SWORD)); eqip.setItemInMainHandDropChance(1.0F); skeleton.setCustomName("Skeleton Warior"); skeleton.setCustomNameVisible(false); return skeleton; } @Override public void update(LivingEntity e) { } @Override public boolean canSpawnThere(Block b) { return (b.getY() > 63) && (b.getY() < 65); } @Override public boolean isOne(LivingEntity e) { return ("Skeleton Warior".equalsIgnoreCase(e.getCustomName())) && ((e instanceof Skeleton)); } @Override public List<ItemStack> getDrops() { List<ItemStack> drops = new ArrayList(); drops.add(DropGenerator.i(Material.BONE, 5)); if (Math.random() < 0.10000000149011612D) { drops.add(ArmourUtil.createWariorHelmet()); } return drops; } }
/** * Helios, OpenSource Monitoring * Brought to you by the Helios Development Group * * Copyright 2007, Helios Development Group and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.heliosapm.script.executable; import java.io.Closeable; import java.io.File; import java.util.Map; import java.util.Set; import javax.script.Bindings; import javax.script.CompiledScript; import javax.script.Invocable; import javax.script.ScriptContext; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import com.heliosapm.script.AbstractDeployedScript; import com.heliosapm.script.DeploymentStatus; /** * <p>Title: JSR223DeployedScript</p> * <p>Description: A deployment for JSR233 scripted deployments</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.script.JSR223DeployedScript</code></p> */ public class JSR223DeployedScript extends AbstractDeployedScript<CompiledScript> implements DeployedExecutableMXBean { static { ContextFactory.initGlobal(new ContextFactory() { protected Context makeContext() { Context cx = super.makeContext(); cx.setOptimizationLevel(9); return cx; } }); } /** * Creates a new JSR223DeployedScript * @param sourceFile The source file * @param cs The compiled script */ public JSR223DeployedScript(final File sourceFile, final CompiledScript cs) { super(sourceFile); executable = cs; initExcutable(); locateConfigFiles(sourceFile, rootDir, pathSegments); } @Override protected void closeOldExecutable(final CompiledScript executable) { if(executable!=null) { final Bindings binding = executable.getEngine().getBindings(ScriptContext.ENGINE_SCOPE); if(binding!=null) { for(Object var: binding.values()) { if(var==null) continue; if(var instanceof Closeable) { try { ((Closeable)var).close(); log.info("[Executable Recycle]: Closed instance of [{}]", var.getClass().getSimpleName()); } catch (Exception x) { /* No Op */ } } } } } } /** * {@inheritDoc} * @see com.heliosapm.script.AbstractDeployedScript#initExcutable() */ @Override public void initExcutable() { if(executable!=null) { executable.getEngine().setBindings(config, ScriptContext.ENGINE_SCOPE); setStatus(DeploymentStatus.READY); } log.info("Output: [{}]", executable.getEngine().getFactory().getOutputStatement("foo")); super.initExcutable(); } /** * {@inheritDoc} * @see com.heliosapm.script.AbstractDeployedScript#onConfigurationItemChange(java.lang.String, java.lang.String) */ @Override public final void onConfigurationItemChange(final String key, final String value) { // none required. } /** * {@inheritDoc} * @see com.heliosapm.script.DeployedScript#getInvocables() */ @Override public Set<String> getInvocables() { return getExecutable().getEngine().getContext().getBindings(ScriptContext.ENGINE_SCOPE).keySet(); } /** * {@inheritDoc} * @see com.heliosapm.script.AbstractDeployedScript#doExecute() */ @Override public Object doExecute() throws Exception { return getExecutable().eval(); } /** * {@inheritDoc} * @see com.heliosapm.script.DeployedScript#invoke(java.lang.String, java.lang.Object[]) */ @Override public Object invoke(String name, Object... args) { try { Invocable inv = (Invocable)getExecutable(); return inv.invokeFunction(name, args); } catch (Exception ex) { throw new RuntimeException("Failed to execute invocable [" + name + "] in script [" + this.getFileName() + "]", ex); } } }
package knx; import esir.dom11.nsoc.model.DataType; import org.kevoree.annotation.*; import org.kevoree.framework.AbstractComponentType; import tuwien.auto.calimero.link.KNXNetworkLinkIP; /** * Created by IntelliJ IDEA. * User: michel * Date: 09/01/12 * Time: 12:07 * To change this template use File | Settings | File Templates. */ @Provides({ @ProvidedPort(name = "ConnectionKNX", type = PortType.SERVICE, className = IntToConnect.class) }) @DictionaryType({ @DictionaryAttribute(name = "ADRESSE_PC", defaultValue = "192.168.1.127", optional = true), }) @Library(name = "NSOC_2011") @ComponentType public class ConnectionKNX extends AbstractComponentType implements IntToConnect { private ToConnect connection; @Start public void startComponent() { System.out.println("ConnectionKNX: Start"); String adressePC = this.getDictionary().get("ADRESSE_PC").toString(); System.out.println("ConnectionKNX: " + "adressePC:" + adressePC); connection = new ToConnect(adressePC); connection.connected(); } @Stop public void stopComponent() { System.out.println("ConnectionKNX: Stop"); } @Update public void updateComponent() { System.out.println("ConnectionKNX: Update"); } @Override @Port(name = "ConnectionKNX", method = "connected") public void connected() { System.out.println("ConnectionKNX: Connected"); connection.connected(); } @Override @Port(name = "ConnectionKNX", method = "disconnected") public void disconnected() { System.out.println("ConnectionKNX: disonnected"); connection.disconnected(); } @Override @Port(name = "ConnectionKNX", method = "read") public String read(String adresseGroupe, DataType dataType) { // System.out.println("ConnectionKNX: read"); return connection.read(adresseGroupe, dataType); } @Override @Port(name = "ConnectionKNX", method = "write") public void write(String adresseGroupe, boolean bool) { System.out.println("ConnectionKNX: write Address : " + adresseGroupe); connection.write(adresseGroupe, bool); } @Override @Port(name = "ConnectionKNX", method = "listener") public void listener(String adresse) { System.out.println("ConnectionKNX: listener"); connection.listener(adresse); } @Override @Port(name = "ConnectionKNX", method = "searchSketch") public String searchSketch() { System.out.println("ConnectionKNX: searchSketch"); return connection.searchSketch(); } @Override @Port(name = "ConnectionKNX", method = "getProtocol") public String getProtocol() { return "knx"; } @Override @Port(name = "ConnectionKNX", method = "getNetLink") public KNXNetworkLinkIP getNetLink() { return connection.getNetLink(); //To change body of implemented methods use File | Settings | File Templates. } }
package net.lin.www; import com.google.gson.Gson; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; /** * Created by Lin on 1/13/16. */ public class YelpCrawler { static String startUrl = ""; static String category = ""; static String city = ""; static String host = ""; static String filename; static String filePath = "./data/Yelp/Activity/"; static String rawDataPath = "./data/Yelp/rawData/" + city + "/"; static int version = 1; public static void main(String[] args) { YelpCrawler yelpCrawler = new YelpCrawler(); yelpCrawler.getActivity(startUrl); } YelpCrawler() { this.filename = filePath + "Yelp-" + city + "-" + category + "-" + version + ".txt"; File file = new File(filename); while(file.exists()) { version ++; this.filename = filePath + "Yelp-" + city + "-" + category + "-" + version + ".txt"; file = new File(filename); } System.out.println("Use File: " + filename); } public void getActivity(String startUrl) { String nextUrl = startUrl; while(nextUrl != null) { System.out.println(nextUrl); Document document = PageLoader.getPage(nextUrl); if(document == null) { System.out.println("null document"); break; } Elements nextPage = document.select("a.next"); if(nextPage == null || nextPage.isEmpty()) nextUrl = null; else nextUrl = host + nextPage.first().attr("href"); Elements biz_names = document.getElementsByClass("biz-name"); biz_names.remove(0); for(Element biz_name : biz_names) { String pageUrl = host + biz_name.attr("href"); System.out.println(pageUrl); document = PageLoader.getPage(pageUrl); if(document == null) continue; Activity activity = new Activity("Yelp", city, category); activity.vendorName = document.getElementsByClass("biz-page-title").first().text(); activity.activityName = activity.vendorName + " " + category; activity.activityURL = pageUrl; activity.activityPhone = document.getElementsByClass("biz-phone").first().text(); activity.price = document.getElementsByClass("i-24x24_deal_c-common_sprite-wrap").first().text(); activity.print(); writeActivityToJson(activity); } } } public void writeActivityToJson(Activity activity) { Gson gson = new Gson(); String activityString = gson.toJson(activity); FileOperator.printFile_AddOn(filename, activityString); } }
package com.movietoy.api.domain.movieInfo.Object; import lombok.Data; @Data public class Genres { /*장르명*/ private String genreNm; }
package com.example.jkl.service; import com.example.jkl.pojo.Car; import java.util.List; public interface CarService { Integer addCar(Car car); Integer deleteCar(Integer id); List<Car> findAllCar(); Integer deleteCarList(List<Integer> ids); }
package com.project.linkedindatabase.service.model.skill; import com.project.linkedindatabase.domain.skill.Endorsement; import com.project.linkedindatabase.jsonToPojo.EndorsementPoJo; import com.project.linkedindatabase.service.BaseService; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public interface EndorsementService extends BaseService<Endorsement,Long> { public Endorsement editById(Long id, Long skillId, Long skillLevel, Long relationKnowledge, Long endorserId) throws SQLException; public void updateWithProfileId(Endorsement endorsement) throws SQLException; public void deleteById(Long id) throws SQLException; public List<Endorsement> getAllById(long id) throws SQLException; public List<Endorsement> getAllByProfileId(long profileId) throws SQLException; public List<Endorsement> getAllBySkillId(long skillId) throws SQLException; public List<EndorsementPoJo> getAllBySkillIdJson(long skillId) throws SQLException; public boolean isThereAnotherEndorsement(Endorsement endorsement) throws SQLException; public void deleteAllBySkillId(Long skillId) throws SQLException; }
package br.com.caelum.financas.teste; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import br.com.caelum.financas.modelo.Conta; import br.com.caelum.financas.modelo.Movimentacao; import br.com.caelum.financas.util.JPAUtil; public class TesteTodasAsMovimentacoesDasContas { public static void main(String[] args) { EntityManager entityManager = new JPAUtil().getEntityManager(); entityManager.getTransaction().begin(); TypedQuery<Conta> query = entityManager.createQuery("SELECT distinct c FROM Conta c left join fetch c.movimentacoes", Conta.class); List<Conta> todasAsContas = query.getResultList(); for (Conta conta : todasAsContas) { System.out.println("Titular: " + conta.getTitular() + ", Conta.id: " + conta.getId() + "\nMovimentacoes:"); for (Movimentacao movimentacao : conta.getMovimentacoes()) { System.out.println(movimentacao); } } entityManager.getTransaction().commit(); entityManager.close(); } }
package com.tencent.mm.plugin.luckymoney.ui; import android.view.View; import android.view.View.OnClickListener; class LuckyMoneyDetailUI$15 implements OnClickListener { final /* synthetic */ LuckyMoneyDetailUI kVo; LuckyMoneyDetailUI$15(LuckyMoneyDetailUI luckyMoneyDetailUI) { this.kVo = luckyMoneyDetailUI; } public final void onClick(View view) { LuckyMoneyDetailUI.n(this.kVo); } }
package com.epam.bar.entity; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; /** * The representation of Cocktail * * @author Kirill Karalionak * @version 1.0.0 */ @EqualsAndHashCode(callSuper = true) @Data @Builder(setterPrefix = "with") public class Cocktail extends Entity { private int id; private String name; private String composition; private Alcohol alcohol; private double rate; private User author; private String imgName; private boolean approved; }
package dev.felicity.felicity; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.content.Intent; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.time.LocalDateTime; import java.util.HashMap; public class ThoughtDescription extends AppCompatActivity { private ImageButton mNext; private RadioGroup mGroup; private RadioButton mYes; private RadioButton mNo; private TextView mText; private EditText mEdit; private HashMap<String,Object> mInfo; private String info1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thought_description); mNext = findViewById(R.id.next); mText=findViewById(R.id.textView2); mEdit=findViewById(R.id.textView3); mInfo = (HashMap<String,Object>)getIntent().getSerializableExtra("mInfo"); mYes=findViewById(R.id.yes); mNo=findViewById(R.id.no); mGroup=findViewById(R.id.group); mNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { info1=mEdit.getText().toString(); if(info1.equals("")){ Toast.makeText(ThoughtDescription.this,"Fields cannot be empty",Toast.LENGTH_LONG).show(); } else { mInfo.put("ThoughtDescription1",info1); Intent intentLoadNewActivity = new Intent(ThoughtDescription.this, ThoughtSituation.class); intentLoadNewActivity.putExtra("mInfo", mInfo); startActivity(intentLoadNewActivity); } } }); mGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected View radioButton = group.findViewById(checkedId); int index = group.indexOfChild(radioButton); switch (index) { case 0: // first button mText.setVisibility(View.VISIBLE); mEdit.setVisibility(View.VISIBLE); break; case 1: // secondbutton popDialog(); break; } } }); } public void popDialog(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Would you like to exit the form, or continue practicing CBT with a negative memory?"); alertDialogBuilder.setPositiveButton("Continue", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { mText.setVisibility(View.VISIBLE); mEdit.setVisibility(View.VISIBLE); } }); alertDialogBuilder.setNegativeButton("Exit",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LocalDateTime now = LocalDateTime.now(); String date= now.getMonth().toString()+" "+now.getDayOfMonth()+", "+now.getYear(); DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference(); String mUser= FirebaseAuth.getInstance().getCurrentUser().getUid(); mDatabase.child("Users").child(mUser).child("email").setValue(FirebaseAuth.getInstance().getCurrentUser().getEmail()); String key = mDatabase.child("Users").child(mUser).child("Journal").child(date).push().getKey(); mDatabase.child("Users").child(mUser).child("Journal").child(date).child(key).setValue(now.toString()); mDatabase.child("Journal").child(key).setValue(mInfo); mInfo.clear(); Intent intentLoadNewActivity = new Intent(ThoughtDescription.this, LandingPage.class); intentLoadNewActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intentLoadNewActivity); finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
package com.fnsvalue.skillshare.daoimpl; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fnsvalue.skillshare.dao.LoginDAO; import com.fnsvalue.skillshare.dto.User; import com.fnsvalue.skillshare.mapper.BoardMapper; import com.fnsvalue.skillshare.mapper.LoginMapper; @Component public class LoginDAOImpl implements LoginDAO { @Autowired private SqlSession sqlSession; public User findByUserIdAndPassword(User user) { User result = new User(); LoginMapper loginMapper = sqlSession.getMapper(LoginMapper.class); result = loginMapper.findByUserIdAndPassword(user); return result; } public int checkLogin(String IP,String USER_ID_PK) { int result; LoginMapper loginMapper = sqlSession.getMapper(LoginMapper.class); result=loginMapper.checkLogin(IP,USER_ID_PK); return result; } public int checkDetail(String USER_ID_PK,String ACCLOG_SQ_PK,String IP,String ACCLOG_PAGE,String ACCLOG_INF) { int result; LoginMapper loginMapper = sqlSession.getMapper(LoginMapper.class); result=loginMapper.checkDetail(USER_ID_PK,ACCLOG_SQ_PK,IP,ACCLOG_PAGE,ACCLOG_INF); return result; } @Override public User getUsersByID(String user_id_pk) { User result = new User(); LoginMapper loginMapper = sqlSession.getMapper(LoginMapper.class); result = loginMapper.getUsersByID(user_id_pk); return null; } }
/* 1: */ package com.kaldin.user.adminprofile.action; /* 2: */ /* 3: */ import com.kaldin.user.adminprofile.DAO.EmailSettingDAO; /* 4: */ import com.kaldin.user.adminprofile.form.EmailSettingForm; /* 5: */ import javax.servlet.http.HttpServletRequest; /* 6: */ import javax.servlet.http.HttpServletResponse; /* 7: */ import org.apache.struts.action.Action; /* 8: */ import org.apache.struts.action.ActionForm; /* 9: */ import org.apache.struts.action.ActionForward; /* 10: */ import org.apache.struts.action.ActionMapping; /* 11: */ /* 12: */ public class EmailSettingAction /* 13: */ extends Action /* 14: */ { /* 15: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) /* 16: */ { /* 17:20 */ EmailSettingDAO dao = new EmailSettingDAO(); /* 18:21 */ EmailSettingForm emailForm = (EmailSettingForm)form; /* 19: */ /* 20:23 */ String result = "success"; /* 21:25 */ if (emailForm.getAction().equals("add")) /* 22: */ { /* 23:26 */ dao.addEmailSettings(emailForm); /* 24:27 */ result = "dashboard"; /* 25:28 */ emailForm.setAction(""); /* 26: */ } /* 27:29 */ else if (emailForm.getAction().equals("update")) /* 28: */ { /* 29:30 */ dao.updateEmailSettins(emailForm); /* 30:31 */ emailForm.setAction(""); /* 31:32 */ result = "dashboard"; /* 32: */ } /* 33: */ else /* 34: */ { /* 35:34 */ dao.getEmailSetting(emailForm); /* 36: */ } /* 37:37 */ return mapping.findForward(result); /* 38: */ } /* 39: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.user.adminprofile.action.EmailSettingAction * JD-Core Version: 0.7.0.1 */
package org.sid.dao; import org.sid.entities.Employe; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeRepository extends JpaRepository<Employe, Long> { public Page<Employe> findByNomContains(String mc ,Pageable pageable); }
public interface AbstractGasStationView { void registerListener(GasStationUIEventListener listener); public void addCar(); public void fillMainFuelPool(); public void showStats(); public void endWorkDay(); }
package com.bvan.javastart.lessons7_8.storing; /** * @author bvanchuhov */ public class NullExample { public static void main(String[] args) { String s = ""; if (s != null) { System.out.println(s.length()); } } public static void printLength(String s) { if (s == null) { throw new IllegalArgumentException("null value"); } System.out.println(s.length()); } }
package gui; import java.awt.*; import javax.swing.*; public class SecondGui extends JFrame { private JLabel label; private JButton button; private JTextField textfield; public SecondGui() { setLayout(new FlowLayout()); label = new JLabel("Hi"); add(label); textfield = new JTextField(15); add(textfield); button = new JButton("Click"); add(button); } public static void main(String[] args) { SecondGui gui = new SecondGui(); gui.setDefaultCloseOperation(EXIT_ON_CLOSE); gui.setSize(300, 300); gui.setVisible(true); gui.setTitle("My Titile"); } }
package com.github.manage.result; import com.github.manage.result.dtos.rsp.RspPageData; import lombok.Data; import java.util.List; /** * @ProjectName: spring-cloud-examples * @Package: com.github.manage.result * @Description: 列表返回结果集 * @Author: Vayne.Luo * @date 2019/01/23 */ @Data public class PageResult<T> extends GeneralResult{ private static final long serialVersionUID = 7251515307280186650L; private RspPageData<T> rspPageData; public PageResult(){} public PageResult(RspPageData<T> rspPageData) { super(); this.rspPageData = rspPageData; } public PageResult(Integer pageSize,Long totalNum,int currentPage,List<T> list) { super(); this.rspPageData = new RspPageData<T>(totalNum,currentPage,pageSize,list); } }
package com.walkerwang.algorithm.swordoffer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc, * 则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。 输入描述: 输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。 *递归体:从每个子串的第二个字符开始依次与第一个字符交换,然后继续处理子串 *递归出口:只剩一个字符的时候,就不用交换 * */ public class StringPermutation { static List<String> list = new ArrayList<>(); static int count = 0; public static void main(String[] args) { String str = "abc"; int start = 0; int end = str.length()-1; permutation(str, start, end); Iterator<String> iter = list.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } System.out.println(count); } /* * 将字符串第一位与其他位不断交换,交换一个后递归 * (字符串中有重复字符没有考虑到) */ public static void permutation(String str, int start, int end) { //递归的出口 if(start == end){ list.add(str); count++; }else{ for(int i=start; i<=end; i++) { char tmp1 = str.charAt(start); char tmp2 = str.charAt(i); String str1 = str.replace(tmp2, tmp1); str = str1.replaceFirst(String.valueOf(tmp1), String.valueOf(tmp2)); permutation(str, start+1, end); tmp1 = str.charAt(start); tmp2 = str.charAt(i); str1 = str.replace(tmp2, tmp1); str = str1.replaceFirst(String.valueOf(tmp1), String.valueOf(tmp2)); } } } }
package com.filiereticsa.arc.augmentepf.localization; import android.util.Pair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by ARC© Team for AugmentEPF project on 25/05/2017. */ public class FloorAccess { public static final String FLOOR_ACCESS_TYPE = "floorAccessType"; public static final String FLOOR_ACCESS_X_POS = "floorAccessXPos"; public static final String FLOOR_ACCESS_Y_POS = "floorAccessYPos"; public static final String FLOOR_POSSIBILITY = "floorPossibility"; public static final String FLOOR_ACCESS_POSSIBILITIES = "floorAccessPossibilities"; private Pair<Integer, Integer> position; private FloorAccessType floorAccessType; private ArrayList<Integer> floorsPossibilities; public FloorAccess(Pair<Integer, Integer> position, FloorAccessType floorAccessType, ArrayList<Integer> floorsPossibilities) { this.position = position; this.floorAccessType = floorAccessType; this.floorsPossibilities = floorsPossibilities; } public FloorAccess(JSONObject currentFloorAccess) { try { int xPos = currentFloorAccess.getInt(FLOOR_ACCESS_X_POS); int yPos = currentFloorAccess.getInt(FLOOR_ACCESS_Y_POS); this.position = new Pair<>(xPos, yPos); this.floorAccessType = FloorAccessType.valueOf(currentFloorAccess.getString(FLOOR_ACCESS_TYPE)); JSONArray floorPossibilitiesJsonArray = currentFloorAccess.getJSONArray(FLOOR_ACCESS_POSSIBILITIES); this.floorsPossibilities = new ArrayList<>(); for (int i = 0; i < floorPossibilitiesJsonArray.length(); i++) { this.floorsPossibilities.add(floorPossibilitiesJsonArray.getJSONObject(i).getInt(FLOOR_POSSIBILITY)); } } catch (JSONException e) { e.printStackTrace(); } } public Pair<Integer, Integer> getPosition() { return position; } public FloorAccessType getFloorAccessType() { return floorAccessType; } public ArrayList<Integer> getFloorsPossibilities() { return floorsPossibilities; } public enum FloorAccessType { STAIRS, ELEVATOR } }
package servlets; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; @WebServlet(name = "asyncServlet", urlPatterns = "/async", asyncSupported = true) public class AsyncServlet extends HttpServlet { private static AtomicInteger id = new AtomicInteger(0); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final int curId = id.getAndIncrement(); System.out.println("Inside AsyncServlet.doGet id : " + curId + " and isAsyncStarted : " + request.isAsyncStarted()); final AsyncContext asyncContext = request.getParameter("unwrap") == null ? request.startAsync() : request.startAsync(request, response); final long timeout = request.getParameter("timeout") == null ? 5000L : Long.parseLong(request.getParameter("timeout")); asyncContext.setTimeout(timeout); System.out.println("Starting async thread for id : " + id); asyncContext.start(() -> asyncTask(curId, asyncContext)); } private static void asyncTask(final int id, final AsyncContext asyncContext) { System.out.println("Async Thread started for id : " + id); try { Thread.sleep(5000L); } catch (InterruptedException e) { e.printStackTrace(); } final HttpServletRequest httpServletRequest = (HttpServletRequest) asyncContext.getRequest(); System.out.println("Finished sleeping 5 seconds for id : " + id + " which maps to URL : " + httpServletRequest.getRequestURL()); System.out.println("running asyncContext.dispatch(\"/WEB-INF/jsp/async.jsp\") for id : " + id); asyncContext.dispatch("/WEB-INF/jsp/async.jsp"); System.out.println("Async Thread finished for id " + id); } }
package zen.teste; import java.util.Scanner; public class Principal { public static void main(String[] args) { // Classe TESTE Controller ctrl = new Controller(); Scanner sc = new Scanner(System.in); boolean continuar = true; while(continuar) { ctrl.menu(); System.out.print("DIGITE A OPÇÃO: "); int op = sc.nextInt(); ctrl.execute(op); System.out.println("DESEJA CONTINUAR[S/N]: "); String vai = sc.next(); if (vai.toUpperCase().startsWith("N")) { continuar = false; } } sc.close(); } }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package ttyy.com.coder.scanner.camera; import android.hardware.Camera; import android.util.Log; import ttyy.com.coder.scanner.decode.DecodeCallback; import ttyy.com.coder.scanner.decode.ZXingDecoder; public final class JinPreviewCallback implements Camera.PreviewCallback { private static final String TAG = JinPreviewCallback.class.getName(); private CameraConfigurationManager mConfigManager; private DecodeCallback mDecodeCallback; JinPreviewCallback(CameraConfigurationManager configManager) { this.mConfigManager = configManager; } public JinPreviewCallback setDecodeCallback(DecodeCallback callback){ this.mDecodeCallback = callback; return this; } public DecodeCallback getDecodeCallback(){ return this.mDecodeCallback; } @Override public void onPreviewFrame(byte[] data, Camera camera) { Log.i(TAG, "byte datas ready to decode"); Camera.Size cameraResolution = mConfigManager.getCameraResolution(); if (mDecodeCallback != null) { ZXingDecoder.get().decode(data, cameraResolution.width, cameraResolution.height, mDecodeCallback); } else { Log.w(TAG, "Hasn't Set Decode Result Callback"); } } }
/* * created 08.10.2005 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: CircleDecoration.java 3 2005-11-02 03:04:20Z csell $ */ package com.byterefinery.rmbench.figures; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.Ellipse; import org.eclipse.draw2d.RotatableDecoration; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; /** * circle decoration to be placed on the child (source) end of a connection * * @author cse */ public class CircleDecoration extends Ellipse implements RotatableDecoration { private static final int DIAMETER = 10; private static final int RADIUS = 5; public CircleDecoration() { setBounds(new Rectangle(0, 0, DIAMETER, DIAMETER)); setOpaque(true); setBackgroundColor(ColorConstants.black); } public void setReferencePoint(Point ref) { Point location = getLocation(); if(ref.x == location.x) location.x -= RADIUS; else if(ref.x < location.x) location.x -= DIAMETER; if(ref.y == location.y) location.y -= RADIUS; else if(ref.y < location.y) location.y -= DIAMETER; setLocation(location); } }
package problemas; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Map.Entry; import java.util.Scanner; import javax.management.openmbean.OpenDataException; public class SafeSecret { ArrayList<Tupla<Integer, Character>> valores; public SafeSecret( int numTuplas, String s ) { this.valores = new ArrayList<>(); Scanner sc = new Scanner( s ); for ( int i = 0; i < numTuplas; i++ ) { int n = sc.nextInt(); char c = sc.next().charAt( 0 ); this.valores.add( new Tupla<Integer, Character>( n, c ) ); } } public String getSecretCode() { HashMap<Operaciones, HashSet<Integer>> pasadaNueva = new HashMap<SafeSecret.Operaciones, HashSet<Integer>>(); HashMap<Operaciones, Tupla<Integer, Integer>> pasadasAnteriores = new HashMap<SafeSecret.Operaciones, Tupla<Integer, Integer>>( 9999999 ); HashMap<Operaciones, HashSet<Integer>> pasadaInicial = new HashMap<SafeSecret.Operaciones, HashSet<Integer>>(); int l = this.valores.size(); for ( int i = 0; i < l; i++ ) { LinkedList<Integer> valores = new LinkedList<>(); LinkedList<Character> operadores = new LinkedList<Character>(); for ( int j = 0; j < l; j++ ) { Tupla<Integer, Character> tp = this.valores.get( ( i + j ) % l ); valores.add( tp.x ); operadores.add( tp.y ); } operadores.pollLast(); Operaciones op = new Operaciones(valores, operadores); HashSet<Integer> hs = pasadaNueva.get( op ); if ( hs == null ) hs = new HashSet<>(); hs.add( i ); pasadaNueva.put( op, hs ); } for ( Entry<Operaciones, HashSet<Integer>> e : pasadaNueva.entrySet() ) { addCombinaciones(pasadaInicial, e.getValue(), e.getKey(), this.valores.size()-2); } ArrayList<Tupla<Integer, Integer>> valoresMinMax = new ArrayList<Tupla<Integer,Integer>>( l ); for ( int i = 0; i < l; i++ ) valoresMinMax.add( new Tupla<Integer, Integer>( Integer.MAX_VALUE, Integer.MIN_VALUE)); int nivel = 0; for ( Entry<Operaciones, HashSet<Integer>> e : pasadaInicial.entrySet() ) { System.out.println( "Nivel " + nivel++ ); e.getKey().resetOp(); Tupla<Integer, Integer> tp; Tupla<Integer, Integer> vMinMax = calcularMinMax( e.getKey(), pasadasAnteriores, 0 ); for ( Integer i : e.getValue() ) { tp = valoresMinMax.get( i ); tp.x = Math.min( tp.x, vMinMax.x ); tp.y = Math.max( tp.y, vMinMax.y ); } } String clave = ""; for ( Tupla<Integer, Integer> tp : valoresMinMax ) { clave += String.valueOf( Math.abs( tp.x ) ) + String.valueOf( Math.abs( tp.y ) ); } return clave; } private Tupla<Integer, Integer> calcularMinMax( Operaciones op, HashMap<Operaciones, Tupla<Integer, Integer>> valoresMinMax, int nivel ) { Tupla<Integer, Integer> vMinMaxCache = valoresMinMax.get( op ); if ( vMinMaxCache != null ) { return vMinMaxCache; } Integer v = op.valor(); if ( v != null ) { return new Tupla<>( v, v ); } Tupla<Integer, Integer> vMinMax = new Tupla<Integer, Integer>( Integer.MAX_VALUE, Integer.MIN_VALUE ); for ( Operaciones opHija : op.generaSucesores() ) { Tupla<Integer, Integer> tp = calcularMinMax( opHija, valoresMinMax, nivel+1 ); vMinMax.x = Math.min( vMinMax.x, tp.x ); vMinMax.y = Math.max( vMinMax.y, tp.y ); } valoresMinMax.put( op, vMinMax ); if ( valoresMinMax.size() > 50000 ) valoresMinMax.clear(); return vMinMax; } private void addCombinaciones( HashMap<Operaciones, HashSet<Integer>> resultado, HashSet<Integer> padres, Operaciones opIncompleta, int nivel ) { if ( nivel < 0 ) { HashSet<Integer> hs = resultado.get( opIncompleta ); if ( hs == null ) hs = new HashSet<>(); hs.addAll( padres ); resultado.put( opIncompleta.clone(), hs ); return; } if ( opIncompleta.operadores.get( nivel ) == '?' ) { char[] caracteres = {'+', '-', '*'}; for ( char c : caracteres ) { opIncompleta.operadores.set( nivel, c ); addCombinaciones(resultado, padres, opIncompleta, nivel-1); } opIncompleta.operadores.set(nivel, '?'); } else { addCombinaciones(resultado, padres, opIncompleta, nivel-1); } } private class Operaciones { LinkedList<Integer> valores; LinkedList<Character> operadores; int[] nOperadores; private Integer hcode; private String eq; public Operaciones(LinkedList<Integer> valores, LinkedList<Character> operadores, int[] nOperadores) { this.valores = valores; this.operadores = operadores; this.hcode = null; this.eq = null; this.nOperadores = nOperadores; } public Operaciones(LinkedList<Integer> valores, LinkedList<Character> operadores ) { this.valores = valores; this.operadores = operadores; this.hcode = null; this.eq = null; this.nOperadores = new int[ 2 ]; resetOp(); } public void resetOp() { for ( int i = 0; i < 2; i++ ) this.nOperadores[ i ] = 0; for ( Character c : this.operadores ) this.nOperadores[ ( c == '*' ) ? 0 : 1 ]++; } public Integer valor() { if ( this.operadores.size() == 0 ) return this.valores.peek(); Character c = this.operadores.peek(); if ( c == '*' && nOperadores[1] == 0 ) { int r = 1; for ( Integer v : this.valores ) { r *= v; } return r; } else if ( c != '*' && nOperadores[0] == 0 ){ int r = this.valores.peek(); for ( int i = 0; i < this.operadores.size(); i++ ) { if ( this.operadores.get( i ) == '-' ) { r -= this.valores.get( i+1 ); } else { r += this.valores.get( i+1 ); } } return r; } return null; } private String getEq() { if ( this.eq == null ) this.eq = this.toString(); return this.eq; } @Override public String toString() { String s = ""; for ( int i = 0; i < this.operadores.size(); i++ ) { s += this.valores.get( i ) + " " + this.operadores.get( i ) + " "; } s += this.valores.peekLast(); return s; } public ArrayList<Operaciones> generaSucesores() { ArrayList<Operaciones> operaciones = new ArrayList<>(); int l = this.operadores.size(); for ( int i = 0; i < l; i++ ) { Operaciones op = clone(); Character operador = op.operadores.remove( i ); Integer r = op.valores.remove( i ); Integer v = op.valores.get( i ); switch ( operador ) { case '*': r *= v; break; case '+': r += v; break; case '-': r -= v; break; } op.valores.set( i, r ); op.nOperadores[ ( operador == '*' ) ? 0 : 1 ]--; operaciones.add( op ); } return operaciones; } @Override public int hashCode() { if ( this.hcode == null ) { hashMe(); } return this.hcode; } public void hashMe() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((operadores == null) ? 0 : operadores.hashCode()); result = prime * result + ((valores == null) ? 0 : valores.hashCode()); this.hcode = result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Operaciones other = (Operaciones) obj; if (!getOuterType().equals(other.getOuterType())) return false; return getEq().equals( other.getEq() ); } public Operaciones clone () { return new Operaciones( ( LinkedList<Integer> ) this.valores.clone(), ( LinkedList<Character> ) this.operadores.clone(), this.nOperadores.clone() ); } private SafeSecret getOuterType() { return SafeSecret.this; } } }
package com.beiyelin.account.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Embeddable; import static com.beiyelin.commonsql.constant.Repository.*; /** * @Description: 账户 * @Author: newmann * @Date: Created in 16:02 2018-02-21 */ @Data @Embeddable @NoArgsConstructor @AllArgsConstructor public class EmbeddableAccount { @Column(nullable = true,length = PRIMARY_ID_LENGTH) private String accountId; @Column(nullable = true,length = CODE_LENGTH) private String accountCode; @Column(nullable = true,length = NAME_LENGTH) private String accountName; }
package com.edu.miusched.controller; import com.edu.miusched.domain.Entry; import com.edu.miusched.domain.Student; import com.edu.miusched.domain.Student; import com.edu.miusched.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.ArrayList; import java.util.List; @Controller public class StudentAdminController { @Autowired StudentService studentService; @RequestMapping(value = {"/admin/student"}, method = RequestMethod.GET) public String getStudentHome(@ModelAttribute("newStudent") Student student, Model model) { // AjaxResponse response = new AjaxResponse(); //response.success =false ?false :true; Student student1 = new Student(); List<Student> students = new ArrayList<Student>(); students.addAll(studentService.getAllStudents()); model.addAttribute("students", students); model.addAttribute("newStudent", student); model.addAttribute("student1",student1); return "Admin/ManageStudent"; } @RequestMapping(value = "/admin/student/new") public String studentRegForm(@ModelAttribute("newStudent") Student student,BindingResult result, Model model) { if(result.hasErrors()){ model.addAttribute("errors", result.getAllErrors()); return "Admin/ManageStudent"; }else{ studentService.save(student); return "redirect:/admin/student"; } } @RequestMapping("/admin/student/view/{id}") public String getProduct(@PathVariable Long id, Model model) { model.addAttribute("student", studentService.getStudentById(id)); return "redirect:/admin/student"; } @RequestMapping("/admin/student/delete/{id}") public String delete(@PathVariable Long id) { studentService.deleteStudentById(id); return "redirect:/admin/student"; } @RequestMapping(value = "/admin/student/edit/{id}",method = RequestMethod.GET) public String edit(@PathVariable Long id, ModelMap model){ Student student = new Student(); model.addAttribute("entry", studentService.getStudentById(id)); return "Admin/ManageStudent"; } @RequestMapping(value="/admin/student/update",method=RequestMethod.POST) public String saveUpdate (@ModelAttribute("student") Student studentupdate, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "Admin/ManageEntry"; } studentService.save(studentupdate); return "redirect:/admin/student"; } }
package com.tencent.mm.q.a; import android.content.Context; import com.tencent.mm.plugin.fts.a.d.e; import com.tencent.mm.plugin.fts.a.d.e.b; public final class a extends com.tencent.mm.plugin.fts.a.d.a { public final e a(Context context, b bVar, int i) { return new b(context, bVar, i); } public final int getType() { return 33; } public final int getPriority() { return 33; } }
package com.ibiscus.myster.model.survey.data; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity(name = "DiscreteResponse") @DiscriminatorValue("DISCRETE") public class DiscreteResponse extends Response { @Column(name = "choice_id") private long choiceId; DiscreteResponse() {} public DiscreteResponse(long assignmentId, long surveyItemId, long choiceId) { super(assignmentId, surveyItemId); this.choiceId = choiceId; } public DiscreteResponse(long id, long assignmentId, long surveyItemId, long choiceId) { super(id, assignmentId, surveyItemId); this.choiceId = choiceId; } @Override public String getValue() { return String.valueOf(choiceId); } }
package com.espendwise.manta.web.forms; import java.io.Serializable; public class DeliveryScheduleForm implements Serializable { private String scheduleId; private String scheduleName; private String nextDelivery; private String intervalHour; private String cutoffTime; public String getScheduleId() { return scheduleId; } public void setScheduleId(String scheduleId) { this.scheduleId = scheduleId; } public String getScheduleName() { return scheduleName; } public void setScheduleName(String scheduleName) { this.scheduleName = scheduleName; } public String getNextDelivery() { return nextDelivery; } public void setNextDelivery(String nextDelivery) { this.nextDelivery = nextDelivery; } public String getIntervalHour() { return intervalHour; } public void setIntervalHour(String intervalHour) { this.intervalHour = intervalHour; } public String getCutoffTime() { return cutoffTime; } public void setCutoffTime(String cutoffTime) { this.cutoffTime = cutoffTime; } }
package com.example.appdev; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; public class SignUpActivity extends AppCompatActivity { EditText RegisterEmail, RegisterPassword; private FirebaseAuth mAuth; @Override public <T extends View> T findViewById(int id) { return super.findViewById(id); } private void registerUser(){ String email = RegisterEmail.getText().toString().trim(); String password = RegisterPassword.getText().toString().trim(); if(email.isEmpty()){ RegisterEmail.setError("Email is required"); RegisterEmail.requestFocus(); return; } if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){ RegisterEmail.setError("Email a valid Email"); RegisterEmail.requestFocus(); return; } if(password.isEmpty()){ RegisterPassword.setError("Password is required"); RegisterPassword.requestFocus(); return; } if(password.length()<6){ RegisterPassword.setError("Password length should be greater than 6"); RegisterPassword.requestFocus(); return; } mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) {//@org.jetbrains.annotations.NotNull if(task.isSuccessful()){ Intent signIntent = new Intent(getApplicationContext(), ProfileActivity.class); signIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(signIntent); } else { if(task.getException() instanceof FirebaseAuthUserCollisionException){ Toast.makeText(SignUpActivity.this, "Already registered", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); mAuth = FirebaseAuth.getInstance(); RegisterEmail = findViewById(R.id.RegisterEmail); RegisterPassword = findViewById(R.id.RegisterPassWord); Button goSign = findViewById(R.id.goSignIn);//(Button) goSign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent goLogInIntent = new Intent(getApplicationContext(),MainActivity.class); startActivity(goLogInIntent); } }); Button Register = findViewById(R.id.Register); Register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerUser(); } }); } }