blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
74e31f0d41b5f9142dba469701ef321285db438a
Java
Catfeeds/GymEquipment
/app/src/main/java/com/saiyi/gymequipment/home/model/request/GetTimesTotalService.java
UTF-8
524
1.789063
2
[]
no_license
package com.saiyi.gymequipment.home.model.request; import com.saiyi.gymequipment.home.model.bean.FitnessData; import com.saiyi.libfast.http.BaseResponse; import io.reactivex.Observable; import okhttp3.RequestBody; import retrofit2.http.Body; import retrofit2.http.Header; import retrofit2.http.POST; public interface GetTimesTotalService { @POST("OutdoorFitness/app/user/fitness/getTimesTotalRecords") Observable<BaseResponse<FitnessData>> getTimesTotal(@Header("token") String token, @Body RequestBody body); }
true
ba1eea84e48ea1ebb5e21ccbaf3c9c0ba2f3e869
Java
Pverdi/SCVet
/src/java/dao/EstoqueDAO.java
UTF-8
3,276
2.796875
3
[]
no_license
package dao; import static dao.DAO.fecharConexao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; import model.Estoque; /** * * @author lucsd */ public class EstoqueDAO { public static Estoque obterEstoque(int codEstoque) throws ClassNotFoundException, SQLException { Connection conexao = null; Statement comando = null; Estoque estoque = null; try { conexao = BD.getConexao(); comando = conexao.createStatement(); ResultSet rs = comando.executeQuery("select * from estoque where codEstoque = " + codEstoque); rs.first(); estoque = instanciarEstoque(rs); } finally { fecharConexao(conexao, comando); } return estoque; } public static List<Estoque> obterEstoques() throws ClassNotFoundException, SQLException { Connection conexao = null; Statement comando = null; List<Estoque> estoques = new ArrayList<>(); Estoque estoque = null; try { conexao = BD.getConexao(); comando = conexao.createStatement(); ResultSet rs = comando.executeQuery("select * from estoque"); while (rs.next()) { estoque = instanciarEstoque(rs); estoques.add(estoque); } } finally { fecharConexao(conexao, comando); } return estoques; } public static void gravar(Estoque estoque) throws ClassNotFoundException, SQLException { Connection conexao = null; PreparedStatement comando = null; try { conexao = BD.getConexao(); comando = conexao.prepareStatement( "insert into estoque (codEstoque, nome, lote, vencimento, tipo)" + " values (?,?,?,?,?)"); comando.setInt(1, estoque.getCodEstoque()); comando.setString(2, estoque.getNome()); comando.setString(3, estoque.getLote()); comando.setString(4, estoque.getVencimento()); comando.setString(5, estoque.getTipo()); comando.executeUpdate(); } finally { fecharConexao(conexao, comando); } } public static void excluir(Estoque estoque) throws ClassNotFoundException, SQLException { Connection conexao = null; Statement comando = null; String stringSQL; try { conexao = BD.getConexao(); comando = conexao.createStatement(); stringSQL = "delete from estoque where codEstoque = " + estoque.getCodEstoque(); comando.execute(stringSQL); } finally { fecharConexao(conexao, comando); } } private static Estoque instanciarEstoque(ResultSet rs) throws SQLException, ClassNotFoundException { Estoque estoque = new Estoque(rs.getInt("codEstoque"), rs.getString("nome"), rs.getString("lote"), rs.getString("data"), rs.getString("tipo")); return estoque; } }
true
21d3e3bd768158f9052e3fb785594379cfea72d1
Java
oper-V/concurrency
/src/m2/e0/Main.java
UTF-8
1,456
3.09375
3
[]
no_license
package m2.e0; import java.util.concurrent.Callable; public class Main { public static void main(String... args) { testArray(new Integer[0], 0); testArray(new Integer[]{1, 4, 10, 2}, 10); testArray(new Integer[]{1, 4, -10, 2}, 4); testArray(new Integer[]{1}, 1); } private static void testArray(final Integer[] inputArray, final int expectedResult) { final int actualResult = new MaxFinder(inputArray).call(); if (actualResult != expectedResult) { throw new RuntimeException( String.format( "Actual max: %d, expected max: %d", actualResult, expectedResult)); } } // BEGIN (write your solution here) public static class MaxFinder implements Callable<Integer> { private Integer[] array; private Integer result; public MaxFinder(final Integer[] inputArray) { this.array= inputArray; result = 0; } @Override public Integer call() { if (array.equals(null)) { result = 0; } else { //result = array[0]; for (Integer i : array) { if (i > result) { result = i; } } } return result; } } // END }
true
9fd61a8cf7d7dd1c4697c623c53f3775f0c3f4ab
Java
bellmit/marketing-cloud
/marketing-tool-vo/src/main/java/cn/rongcapital/mkt/vo/out/TodayOut.java
UTF-8
761
1.890625
2
[]
no_license
package cn.rongcapital.mkt.vo.out; import org.codehaus.jackson.annotate.JsonProperty; /** * Created by byf on 10/28/16. */ public class TodayOut { private String starDate; private String today; private String endDate; @JsonProperty("StarDate") public String getStarDate() { return starDate; } public void setStarDate(String starDate) { this.starDate = starDate; } @JsonProperty("Today") public String getToday() { return today; } public void setToday(String today) { this.today = today; } @JsonProperty("EndDate") public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } }
true
515b535043ef9138fad5ba8fa7917443bdb4505b
Java
EduardF1/SDJ3
/Session2/src/main/java/shared/clientserver/CustomerTransaction.java
UTF-8
285
2.046875
2
[]
no_license
package shared.clientserver; import java.rmi.Remote; import java.rmi.RemoteException; public interface CustomerTransaction extends Remote { void customerWithdraw(double amount, int accountNo) throws RemoteException; double getBalance(int account) throws RemoteException; }
true
93ee6e458f880073c9c5c48fb70c849276fd54e9
Java
AlexWorx/ALox-Logging-Library
/src.java/alib/com/aworx/lib/config/CLIArgs.java
UTF-8
7,040
2.71875
3
[ "BSL-1.0" ]
permissive
// ################################################################################################# // ALib - A-Worx Utility Library // // Copyright 2013-2019 A-Worx GmbH, Germany // Published under 'Boost Software License' (a free software license, see LICENSE.txt) // ################################################################################################# package com.aworx.lib.config; import com.aworx.lib.lang.Case; import com.aworx.lib.lang.Whitespaces; import com.aworx.lib.strings.Substring; import java.util.ArrayList; /** ************************************************************************************************ * Specialization of abstract interface class #ConfigurationPlugin, which takes all command line * parameters in the constructor and reads variable values from those parameters on request. * Its priority value usually is \alib{config,Configuration.PRIO_CLI_ARGS}, which is higher * than all other default plug-ins provided. * * Variable categories are used as a prefix together with an underscore \c '_'. * This means, if variable <em>LOCALE</em> in category <em>ALIB</em> is accessed, the command line * parameter <em>--ALIB_LOCALE=xyz</em> is read. * * Category and Variable names are insensitive in respect to character case. * * Command line variables may be passed with either one hyphen ('-') or two ('--'). * Both are accepted. * * An application can specify one or more "default categories" by adding their string names to * public field #defaultCategories. Variables of these categories are recognized by the plug-in * also when given without the prefix of category name and underscore \c '_'. * * Furthermore, an application may set public field #allowedMinimumShortCut to a value greater than * \c 0. In this case, the plug-in recognizes variables in CLI arguments already when at least * this amount of characters is provided. In other words, when reading an argument as many * characters of the variable name as possible are 'consumed' and if a minimum number is given with * #allowedMinimumShortCut, such minimum is sufficient. If the remaining part of the argument * string is either empty or continues with an equal sign \c '=', then the variable is recognized * (with an empty value or the value after the equal sign).<br> * Fields #allowedMinimumShortCut and #defaultCategories may also be used in combination. **************************************************************************************************/ public class CLIArgs extends ConfigurationPlugin { /** The list of command line arguments. */ protected String[] args; /** One time created, reused variable. */ protected Substring cliArg= new Substring(); /** * An application can specify one or more "default categories" by adding the category names * here. Variables of these categories are recognized by the plug-in * also when given without the prefix of <c>category_</c>. */ public ArrayList<String> defaultCategories = new ArrayList<String>(); /** * If this field is set to a value greater than \c 0, this plug-in recognizes variables in * CLI arguments already when at least this amount of characters is provided. * If the remaining part of the argument string is either empty or continues with an equal * sign \c '=', then the variable is recognized. */ public int allowedMinimumShortCut = 0; /** ******************************************************************************************** * Sets the command line argument list. Needs to be called once after construction. * Should not be invoked directly. Rather use \alib{config,Configuration.setCommandLineArgs}. * *\note In standard application scenarios, this method is invoked by method * \ref com.aworx.lib.ALIB.init "ALIB.init" for the singleton of this class found in * \ref com.aworx.lib.ALIB.config "ALIB.config". * * @param args Parameters taken from <em>standard Java</em> method \c main() * (the list of command line arguments). Accepts \c null to ignore * command line parameters. **********************************************************************************************/ public void setArgs( String[] args ) { this.args= args; } /** ******************************************************************************************** * Searches the variable in the command line parameters. * * @param variable The variable to retrieve. * @param searchOnly If \c true, the variable is not set. Defaults to \c false. * @return \c true if variable was found, \c false if not. **********************************************************************************************/ @Override public boolean load( Variable variable, boolean searchOnly) { if ( args == null ) return false; String variableFullname= variable.fullname.toString(); String variableName = variable.name.toString(); // check if category may me left out boolean allowWithoutCategory= false; for (String defaultCategory : defaultCategories ) if( (allowWithoutCategory= variable.category.equals( defaultCategory )) ) break; for ( int i= 0; i < args.length ; i++ ) { // remove whitespaces (if somebody would work with quotation marks...) // and request '-' and allow a second '-' if ( !cliArg.set( args[i]).trim().consumeChar('-') ) continue; cliArg.consumeChar('-'); // try names if ( ! cliArg.consumeString( variableFullname, Case.IGNORE ) && !( allowWithoutCategory && cliArg.consumeString( variableName , Case.IGNORE ) ) && !( allowedMinimumShortCut > 0 && ( 0 < cliArg.consumePartOf( variableFullname, allowedMinimumShortCut + 1 + variable.category.length() ) ||( allowWithoutCategory && 0 < cliArg.consumePartOf( variableName , allowedMinimumShortCut ) ) ) ) ) continue; // next arg // found --CAT_NAME. If rest is empty or continues with '=', we set if ( cliArg.isEmpty() ) { if ( !searchOnly ) variable.add(); return true; } if ( cliArg.consumeChar( '=', Case.SENSITIVE, Whitespaces.TRIM ) ) { if ( !searchOnly ) stringConverter.loadFromString( variable, cliArg ); return true; } } return false; } }
true
551462c186adb07f2b453aa5dd46da78614772f2
Java
javalibrary/Orienteer
/orienteer-core/src/main/java/org/orienteer/core/dao/DAOIndexes.java
UTF-8
374
2.09375
2
[ "Apache-2.0" ]
permissive
package org.orienteer.core.dao; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotation to collect multiple {@link DAOIndex} */ @Retention(RUNTIME) @Target({ TYPE }) public @interface DAOIndexes { DAOIndex[] value(); }
true
b4574b892b2d4c1d9aa6ec06f85a0a98c223c955
Java
QuiltMC/quilt-loader
/src/test/java/org/quiltmc/test/lambda_strip/LambdaStripTester.java
UTF-8
3,420
2.390625
2
[ "Apache-2.0", "CC-BY-3.0", "JSON" ]
permissive
/* * Copyright 2022, 2023 QuiltMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.quiltmc.test.lambda_strip; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.HashSet; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.util.TraceClassVisitor; import org.quiltmc.loader.impl.QuiltLoaderImpl; import org.quiltmc.loader.impl.transformer.ClassStripper; import org.quiltmc.loader.impl.transformer.EnvironmentStrippingData; import org.quiltmc.loader.impl.transformer.LambdaStripCalculator; import net.fabricmc.api.EnvType; public class LambdaStripTester { // Not a real test, since I'm not quite sure how to check for "no lambda present" // Perhaps just "the class contains no additional unexpected methods"? public static void main(String[] args) throws IOException { String[] files = { // "bin/test/org/quiltmc/test/lambda_strip/on/ClassWithLambda.class", // "bin/test/org/quiltmc/test/lambda_strip/on/ClassWithCaptureLambda.class", // "bin/test/org/quiltmc/test/lambda_strip/on/ClassWithMethodReference.class"// }; for (String path : files) { System.out.println(""); System.out.println( "=========================================================================================" ); System.out.println(""); System.out.println("ORIGINAL:"); byte[] bytes = Files.readAllBytes(Paths.get(path)); ClassReader reader = new ClassReader(bytes); reader.accept( new TraceClassVisitor(new PrintWriter(System.out, true)), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES ); EnvironmentStrippingData stripData = new EnvironmentStrippingData(Opcodes.ASM9, EnvType.SERVER); reader.accept(stripData, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); Collection<String> stripMethods = stripData.getStripMethods(); LambdaStripCalculator calc = new LambdaStripCalculator(Opcodes.ASM9, stripData.getStripMethodLambdas()); reader.accept(calc, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); Collection<String> additionalStripMethods = calc.computeAdditionalMethodsToStrip(); if (!additionalStripMethods.isEmpty()) { stripMethods = new HashSet<>(stripMethods); stripMethods.addAll(additionalStripMethods); } ClassWriter classWriter = new ClassWriter(null, 0); ClassStripper visitor = new ClassStripper( QuiltLoaderImpl.ASM_VERSION, classWriter, stripData.getStripInterfaces(), stripData.getStripFields(), stripMethods ); reader.accept(visitor, 0); System.out.println("TRANSFORMED:"); ClassReader r2 = new ClassReader(classWriter.toByteArray()); r2.accept( new TraceClassVisitor(new PrintWriter(System.out, true)), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES ); } } }
true
bc888ed93d5e62201906856a9380ad89966b6be8
Java
davibrandao18/Algesd
/src/fila/Coracao.java
UTF-8
2,221
3.140625
3
[]
no_license
package fila; public class Coracao { public static void main(String args[]) { int mat[][]= { {0,0,1,1,1,1,0,0,1,1,1,1,0,0}, {0,1,0,0,0,0,1,1,0,0,0,0,1,0}, {1,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,1}, {0,1,0,0,0,0,0,0,0,0,0,0,1,0}, {0,0,1,0,0,0,0,0,0,0,0,1,0,0}, {0,0,0,1,0,0,0,0,0,0,1,0,0,0}, {0,0,0,0,1,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,1,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0}}; mostrarMatriz(mat); int x=3, y=7; //ponto de inicio da pintura System.out.println("Coordenadas iniciais: x = " + x + ", y = " + y + "\n\n"); Fila f = new Fila(1000); f.enfileirar(x); f.enfileirar(y); while(!f.vazia()) { x=f.desenfileirar(); y=f.desenfileirar(); if(mat[x][y] == 0) //pode ser pintado? { mat[x][y] = 2; //pintei if((x+1)<mat.length && mat[x+1][y] == 0) //baixo { f.enfileirar(x+1); f.enfileirar(y); } if((x-1)>=0 && mat[x-1][y] == 0) //cima { f.enfileirar(x-1); f.enfileirar(y); } if((y+1)<mat[0].length && mat[x][y+1] == 0) //direita { f.enfileirar(x); f.enfileirar(y+1); } if((y-1)<mat[0].length && mat[x][y-1] == 0) //esquerda { f.enfileirar(x); f.enfileirar(y-1); } } } mostrarMatriz(mat); } public static void mostrarMatriz(int mat[][]) { for (int l = 0 ; l < mat.length ; l++) { //-> linha for (int c = 0 ; c < mat[0].length ; c++) { // _> coluna if (mat[l][c] == 0 ) { System.out.print(" "); } else if (mat[l][c] == 1) { System.out.print("-"); } else if (mat[l][c] == 2) {System.out.print("*");} } System.out.println(); } } }
true
833d68caae91a6e6348434f533e7dcdc3af370da
Java
coderbyheart/mobcomp-uebungen
/Uebung_02-Aufgabe_04/src/de/hsrm/medieninf/mobcomp/ueb02/aufg03/CurrencyDbAdapter.java
UTF-8
5,577
2.53125
3
[]
no_license
package de.hsrm.medieninf.mobcomp.ueb02.aufg03; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class CurrencyDbAdapter { private static final String TAG = "CurrencyDbAdapter"; private static final String DB_FILENAME = "currencies.db"; private static final int DB_VERSION = 1; private static final String CURRENCY_TABLE = "currency"; public static final int CURRENCY_COL_ID = 0; public static final int CURRENCY_COL_SYMBOL = 1; public static final int CURRENCY_COL_RATE = 2; public static final int CURRENCY_COL_NAME = 3; public static final String CURRENCY_KEY_ID = "_id"; public static final String CURRENCY_KEY_SYMBOL = "symbol"; public static final String CURRENCY_KEY_RATE = "rate"; public static final String CURRENCY_KEY_NAME = "name"; private SQLiteDatabase db; private CurrencyDBHelper dbHelper; // SQL Anweisungen um DB zu erstellen. private static final String CURRENCY_SQL_CREATE = "CREATE TABLE " + CURRENCY_TABLE + "(" + CURRENCY_KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + ", " + CURRENCY_KEY_SYMBOL + " TEXT NOT NULL" + ", " + CURRENCY_KEY_RATE + " DOUBLE NOT NULL" + ", " + CURRENCY_KEY_NAME + " TEXT NOT NULL" + ")"; public CurrencyDbAdapter(Context context) { dbHelper = new CurrencyDBHelper(context, DB_FILENAME, null, DB_VERSION); } public CurrencyDbAdapter open() throws SQLException { if (db == null) { Log.v(TAG, "Öffne Datenbank..."); try { db = dbHelper.getWritableDatabase(); Log.v(TAG, "Datenbank zum Schreiben geöffnet."); } catch (SQLException e) { db = dbHelper.getReadableDatabase(); Log.v(TAG, "Datenbank zum Lesen geöffnet."); } } else { Log.v(TAG, "Datenbank bereits geöffnet."); } return this; } public CurrencyDbAdapter close() { if (db != null) { Log.v(TAG, "Schließe Datenbank."); db.close(); } else { Log.v(TAG, "Datenbank bereits geschlossen."); } db = null; return this; } protected SQLiteDatabase getDb() { open(); return db; } public Cursor getCurrenciesCursor() { String[] cols = new String[] { CURRENCY_KEY_ID, CURRENCY_KEY_SYMBOL, CURRENCY_KEY_RATE, CURRENCY_KEY_NAME }; return getDb() .query(CURRENCY_TABLE, cols, null, null, null, null, null); } private static class CurrencyDBHelper extends SQLiteOpenHelper { private Context ctx; public CurrencyDBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); ctx = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CURRENCY_SQL_CREATE); Rechner rechner = new Rechner(ctx); for (Currency waehrung : rechner.getDefaultCurrencies()) { ContentValues currencyValues = new ContentValues(); currencyValues.put(CURRENCY_KEY_NAME, waehrung.getName()); currencyValues.put(CURRENCY_KEY_RATE, waehrung.getRate()); currencyValues.put(CURRENCY_KEY_SYMBOL, waehrung.getSymbol()); db.insert(CURRENCY_TABLE, null, currencyValues); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + CURRENCY_TABLE); onCreate(db); } } public Currency getCurrency(int currencyId) { String[] cols = new String[] { CURRENCY_KEY_ID, CURRENCY_KEY_SYMBOL, CURRENCY_KEY_RATE, CURRENCY_KEY_NAME }; Cursor result = getDb().query(CURRENCY_TABLE, cols, CURRENCY_KEY_ID + "=" + currencyId, null, null, null, null); result.moveToFirst(); if (result.isAfterLast()) { Log.v(TAG, "Währung #" + currencyId + " nicht gefunden."); return null; } Currency waehrung = new Currency(); waehrung.setId(currencyId); waehrung.setName(result.getString(CURRENCY_COL_NAME)); waehrung.setRate(result.getDouble(CURRENCY_COL_RATE)); waehrung.setSymbol(result.getString(CURRENCY_COL_SYMBOL)); return waehrung; } public List<Currency> getCurrencies() { String[] cols = new String[] { CURRENCY_KEY_ID, CURRENCY_KEY_SYMBOL, CURRENCY_KEY_RATE, CURRENCY_KEY_NAME }; Cursor result = getDb().query(CURRENCY_TABLE, cols, null, null, null, null, null); result.moveToFirst(); if (result.isAfterLast()) { Log.v(TAG, "Keine Währungen gefunden."); return null; } ArrayList<Currency> currencies = new ArrayList<Currency>(); do { Currency waehrung = new Currency(); waehrung.setId(result.getInt(CURRENCY_COL_ID)); waehrung.setName(result.getString(CURRENCY_COL_NAME)); waehrung.setRate(result.getDouble(CURRENCY_COL_RATE)); waehrung.setSymbol(result.getString(CURRENCY_COL_SYMBOL)); currencies.add(waehrung); } while(result.moveToNext()); return currencies; } public Currency persist(Currency c) { ContentValues cValues = new ContentValues(); cValues.put(CURRENCY_KEY_NAME, c.getName()); cValues.put(CURRENCY_KEY_SYMBOL, c.getSymbol()); cValues.put(CURRENCY_KEY_RATE, c.getRate()); if (c.getId() > 0) { cValues.put(CURRENCY_KEY_ID, c.getId()); db.update(CURRENCY_TABLE, cValues, CURRENCY_KEY_ID + "=" + c.getId(), null); } else { int id = (int) db.insert(CURRENCY_TABLE, null, cValues); c.setId(id); } return c; } public void remove(Currency currency) { db.delete(CURRENCY_TABLE, CURRENCY_KEY_ID + "=" + currency.getId(), null); } }
true
41d221773b2afea3bb231d10d4d1af0c88784711
Java
agaveplatform/science-apis
/agave-profiles/profiles-api/src/main/java/org/iplantc/service/profile/ProfileApplication.java
UTF-8
662
2.078125
2
[ "BSD-3-Clause" ]
permissive
package org.iplantc.service.profile; import org.iplantc.service.profile.resource.impl.InternalUserResourceImpl; import org.iplantc.service.profile.resource.impl.ProfileResourceImpl; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; public class ProfileApplication extends Application { /** * @see javax.ws.rs.core.Application#getClasses() */ @Override public Set<Class<?>> getClasses() { final Set<Class<?>> rrcs = new HashSet<Class<?>>(); // add all the resource beans rrcs.add(ProfileResourceImpl.class); rrcs.add(InternalUserResourceImpl.class); return rrcs; } }
true
25b304f13ee403e8c1a995749efeaf2027515a35
Java
federix8190/Silv
/back/main/java/py/com/ceamso/gestion/resource/CptCargosController.java
UTF-8
714
2.109375
2
[]
no_license
package py.com.ceamso.gestion.resource; import py.com.ceamso.base.WritableResource; import py.com.ceamso.gestion.model.CptCargos; import py.com.ceamso.gestion.service.CptCargosService; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/cpt-cargos") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @RequestScoped public class CptCargosController extends WritableResource<CptCargos, CptCargosService> { @EJB private CptCargosService service; @Override public CptCargosService getService() { return service; } }
true
403d84a0f5a33ab02cae1d43b7851997767ce4c4
Java
yesamer/drools
/drools-impact-analysis/drools-impact-analysis-model/src/main/java/org/drools/impact/analysis/model/right/InsertedProperty.java
UTF-8
492
2.203125
2
[ "Apache-2.0" ]
permissive
package org.drools.impact.analysis.model.right; public class InsertedProperty extends ModifiedProperty { public InsertedProperty( String property ) { this(property, null); } public InsertedProperty( String property, Object value ) { super(property, value); } @Override public String toString() { return "InsertedProperty{" + "property='" + property + '\'' + ", value=" + value + '}'; } }
true
0f143993d2ab7d9a589c9fdb4acb9712fdcadcb5
Java
sacra62/nfc-logistiikka-server
/nfc/src/nfc/logistics/controllers/CommunicationController.java
UTF-8
679
2.203125
2
[]
no_license
package nfc.logistics.controllers; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.FormParam; import javax.ws.rs.core.MediaType; import nfc.logistics.models.*; @Produces({ MediaType.TEXT_XML }) @Path("/") public class CommunicationController { private ResourceController rsc; public CommunicationController() { this.rsc = new ResourceController(); } @POST @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) @Path("getInitialSettings") public Response getXML(@FormParam("xmlRequest") String xml) { return this.rsc.produceInitialSettingsXmlResponse(xml); } }
true
82a808b6a9be0ca5eaadbbc207250779737a790b
Java
haifeiforwork/tuotiansudai
/ttsd-mobile-api/src/test/java/com/tuotiansudai/api/service/MobileAppSendSmsServiceTest.java
UTF-8
5,589
2.171875
2
[]
no_license
package com.tuotiansudai.api.service; import com.tuotiansudai.api.dto.v1_0.BaseResponseDto; import com.tuotiansudai.api.dto.v1_0.ReturnMessage; import com.tuotiansudai.api.dto.v1_0.SendSmsCompositeRequestDto; import com.tuotiansudai.api.dto.v1_0.VerifyCaptchaRequestDto; import com.tuotiansudai.api.service.v1_0.impl.MobileAppSendSmsServiceImpl; import com.tuotiansudai.dto.BaseDto; import com.tuotiansudai.dto.SmsDataDto; import com.tuotiansudai.enums.SmsCaptchaType; import com.tuotiansudai.service.SmsCaptchaService; import com.tuotiansudai.service.UserService; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import static junit.framework.TestCase.assertEquals; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; public class MobileAppSendSmsServiceTest extends ServiceTestBase{ @InjectMocks private MobileAppSendSmsServiceImpl mobileAppSendSmsService; @Mock private UserService userService; @Mock private SmsCaptchaService smsCaptchaService; @Test public void shouldSendSmsByRegisterCaptchaMobileIsDuplicate(){ SendSmsCompositeRequestDto sendSmsRequestDto = new SendSmsCompositeRequestDto(); sendSmsRequestDto.setPhoneNum("12312312312"); sendSmsRequestDto.setType(SmsCaptchaType.REGISTER_CAPTCHA); when(userService.mobileIsExist(anyString())).thenReturn(true); BaseResponseDto baseResponseDto = mobileAppSendSmsService.sendSms(sendSmsRequestDto, "127.0.0.1"); assertEquals(ReturnMessage.MOBILE_NUMBER_IS_EXIST.getCode(),baseResponseDto.getCode()); } @Test public void shouldSendSmsByRetrievePasswordMobileNotExistCaptcha(){ SendSmsCompositeRequestDto sendSmsRequestDto = new SendSmsCompositeRequestDto(); sendSmsRequestDto.setPhoneNum("12312312312"); sendSmsRequestDto.setType(SmsCaptchaType.RETRIEVE_PASSWORD_CAPTCHA); when(userService.mobileIsExist(anyString())).thenReturn(false); BaseResponseDto baseResponseDto = mobileAppSendSmsService.sendSms(sendSmsRequestDto, "127.0.0.1"); assertEquals(ReturnMessage.MOBILE_NUMBER_NOT_EXIST.getCode(),baseResponseDto.getCode()); } @Test public void shouldSendSmsByRegisterCaptchaIsSuccess(){ String ip = "127.0.0.1"; SendSmsCompositeRequestDto sendSmsRequestDto = new SendSmsCompositeRequestDto(); sendSmsRequestDto.setPhoneNum("12312312312"); sendSmsRequestDto.setType(SmsCaptchaType.REGISTER_CAPTCHA); BaseDto<SmsDataDto> smsDto = new BaseDto<>(); SmsDataDto smsDataDto = new SmsDataDto(); smsDataDto.setStatus(true); smsDto.setSuccess(true); smsDto.setData(smsDataDto); when(userService.mobileIsExist(anyString())).thenReturn(false); when(smsCaptchaService.sendRegisterCaptcha(anyString(), anyBoolean(), anyString())).thenReturn(smsDto); BaseResponseDto baseResponseDto = mobileAppSendSmsService.sendSms(sendSmsRequestDto, ip); assertEquals(ReturnMessage.SUCCESS.getCode(),baseResponseDto.getCode()); } @Test public void shouldSendSmsByRetrievePasswordCaptchaIsSuccess(){ String ip = "127.0.0.1"; SendSmsCompositeRequestDto sendSmsRequestDto = new SendSmsCompositeRequestDto(); sendSmsRequestDto.setPhoneNum("12312312312"); sendSmsRequestDto.setType(SmsCaptchaType.RETRIEVE_PASSWORD_CAPTCHA); BaseDto<SmsDataDto> smsDto = new BaseDto<>(); SmsDataDto smsDataDto = new SmsDataDto(); smsDataDto.setStatus(true); smsDto.setSuccess(true); smsDto.setData(smsDataDto); when(userService.mobileIsExist(anyString())).thenReturn(true); when(smsCaptchaService.sendRetrievePasswordCaptcha(anyString(), anyBoolean(), anyString())).thenReturn(smsDto); BaseResponseDto baseResponseDto = mobileAppSendSmsService.sendSms(sendSmsRequestDto, ip); assertEquals(ReturnMessage.SUCCESS.getCode(),baseResponseDto.getCode()); } @Test public void shouldSendSmsByTurnOffNoPasswordInvestIsSuccess(){ String ip = "127.0.0.1"; SendSmsCompositeRequestDto sendSmsRequestDto = new SendSmsCompositeRequestDto(); sendSmsRequestDto.setPhoneNum("12312312312"); sendSmsRequestDto.setType(SmsCaptchaType.NO_PASSWORD_INVEST); BaseDto<SmsDataDto> smsDto = new BaseDto<>(); SmsDataDto smsDataDto = new SmsDataDto(); smsDataDto.setStatus(true); smsDto.setSuccess(true); smsDto.setData(smsDataDto); when(userService.mobileIsExist(anyString())).thenReturn(true); when(smsCaptchaService.sendNoPasswordInvestCaptcha(anyString(), anyBoolean(), anyString())).thenReturn(smsDto); BaseResponseDto baseResponseDto = mobileAppSendSmsService.sendSms(sendSmsRequestDto, ip); assertEquals(ReturnMessage.SUCCESS.getCode(),baseResponseDto.getCode()); } @Test public void shouldValidateCaptchaIsSuccess() { VerifyCaptchaRequestDto requestDto = new VerifyCaptchaRequestDto(); requestDto.setPhoneNum("13800138000"); requestDto.setCaptcha("123456"); requestDto.setType(SmsCaptchaType.RETRIEVE_PASSWORD_CAPTCHA); when(smsCaptchaService.verifyMobileCaptcha(anyString(), anyString(), eq(SmsCaptchaType.RETRIEVE_PASSWORD_CAPTCHA))).thenReturn(true); BaseResponseDto responseDto = mobileAppSendSmsService.validateCaptcha(requestDto); assert responseDto.isSuccess(); } }
true
b2544ea1d4871f4e7d8431e07e8c7f0ef8e1df30
Java
linux10000/goku-food
/src/main/java/com/akiratoriyama/gokufoodapi/enums/AddressType.java
UTF-8
1,400
2.3125
2
[]
no_license
package com.akiratoriyama.gokufoodapi.enums; import java.math.BigInteger; import java.util.Optional; import java.util.stream.Stream; import lombok.Getter; @Getter public enum AddressType implements I18nEnum { DELIVERY(BigInteger.ONE, Consts.PERSONADDRESS_TABLE, Consts.LEGAL_TYPE_FIELD, Consts.I18N_PREFIX + "DELIVERY"), BILLING(BigInteger.valueOf(2), Consts.PERSONADDRESS_TABLE, Consts.LEGAL_TYPE_FIELD, Consts.I18N_PREFIX + "BILLING"), NOT_AVAILIBLE(BigInteger.valueOf(3), Consts.PERSONADDRESS_TABLE, Consts.LEGAL_TYPE_FIELD, Consts.I18N_PREFIX + "NOT_AVAILIBLE"); private static final class Consts { public static final String PERSONADDRESS_TABLE = "personaddress"; public static final String LEGAL_TYPE_FIELD = "pedndomtype"; public static final String I18N_PREFIX = PERSONADDRESS_TABLE + "." + LEGAL_TYPE_FIELD + "."; } private static final AddressType[] _VALUES = values(); private BigInteger id; private String table; private String field; private String i18nKey; AddressType(BigInteger id, String table, String field, String i18nKey) { AddressType. this.id = id; this.table = table; this.field = field; this.i18nKey = i18nKey; } public static Optional<AddressType> getFromId(BigInteger id) { return Stream.of(_VALUES) .filter(v -> v.getId().equals(id)) .findFirst(); } @Override public String getI18nKey() { return this.i18nKey; } }
true
4f89cdaf3bf74309b480b724b3f6eaddc693bb69
Java
petro-ushchuk/dissys-parcom
/src/main/java/lab4/exception/BadConnectionException.java
UTF-8
181
2.34375
2
[]
no_license
package lab4.exception; public class BadConnectionException extends Exception{ public BadConnectionException(String message) { super(message, new Throwable()); } }
true
f0b2dd4dcab1ba1bb67294e15af9f3315c6f9999
Java
hyewon0218/java_src
/javase_prj/src/day1115/work16.java
UHC
714
3.46875
3
[]
no_license
class Homework { public static void main(String[] args) { //1 int i = -10; int j = 2147483647; boolean flag1=false, flag2=false, flag3=false, flag4=false; System.out.println("Էµ ̸ 2 ̸ ~ ̿Ͽ 10 = " + ( i >= 0 ? Integer.toBinaryString(i) : ~i+1 )); //2 j >>= 16; System.out.println(" 2byte = " + j); j = 2147483647; j <<= 16; System.out.println(" 2byte = " + ~j); //3 flag3=((flag1=4>3) || (flag2=5>4)); // Ǿ flag2 true Ǿ ½ false ȴ. System.out.println(" : " + flag1 + " , : " + flag2+ " , : " + flag3); } }
true
d5942956539f762b9c037c79da233bc09838e12f
Java
zt713/RobotClient
/unoEye/src/main/java/com/chinatel/robot/RTCTest.java
UTF-8
1,024
2
2
[]
no_license
package com.chinatel.robot; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.chinatel.robot.bean.HomeMemberInfo; import com.chinatel.robot.db.dao.HomeMemberDao; public class RTCTest extends AndroidTestCase { private static final String TAG = "DBTest"; private HomeMemberDao dao; public void testFetchMember() { this.dao = new HomeMemberDao(getContext()); List<HomeMemberInfo> members = dao.findNoIntercept(); // List<HomeMemberInfo> members = dao.findAll(); for (HomeMemberInfo member : members) { Log.e(TAG, "=================" + member.getName() + "" + member.getKeycode()); } } public void testAddMember() { this.dao = new HomeMemberDao(getContext()); /* * localHomeMemberInfo.setImguri(str1); * localHomeMemberInfo.setName(str2); * localHomeMemberInfo.setDevice(str3); * localHomeMemberInfo.setMode(str4); * localHomeMemberInfo.setKeycode(str5); */ dao.add("", "papa", "IPHONE8S 土豪金", "1", "1002"); } }
true
ccb579e31330b498a98e3e67310a08a3388457be
Java
jelenas93/baby_shop
/src/tabele/TabelaKasa.java
UTF-8
1,865
2.796875
3
[]
no_license
package tabele; public class TabelaKasa { private String barkod, sifra, naziv; private Integer kolicina; private Double cijena, vrijednost; public TabelaKasa(){} public TabelaKasa(String barkod, String sifra, String naziv, Integer kolicina, Double cijena, Double vrijednost) { this.barkod = barkod; this.sifra = sifra; this.naziv = naziv; this.kolicina = kolicina; this.cijena = Double.parseDouble(String.format("%.2f", cijena)); this.vrijednost = Double.parseDouble(String.format("%.2f", vrijednost)); } public String getBarkod() { return barkod; } public void setBarkod(String barkod) { this.barkod = barkod; } public String getSifra() { return sifra; } public void setSifra(String sifra) { this.sifra = sifra; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } public Integer getKolicina() { return kolicina; } public void setKolicina(Integer kolicina) { this.kolicina = kolicina; } public Double getCijena() { return cijena; } public void setCijena(Double cijena) { this.cijena = Double.parseDouble(String.format("%.2f", cijena)); } public Double getVrijednost() { return vrijednost; } public void setVrijednost(Double vrijednost) { this.vrijednost = Double.parseDouble(String.format("%.2f", vrijednost));; } @Override public String toString() { return "TabelaKasa{" + "barkod=" + barkod + ", sifra=" + sifra + ", naziv=" + naziv + ", kolicina=" + kolicina + ", cijena=" + cijena + ", vrijednost=" + vrijednost + '}'; } }
true
f34734f33befadd35bb69bc5afbd0d0b60597b40
Java
robinrastogi/learningJava
/CoreJava/sample_Project/src/jdbc_javaTpoint/InsertMultiplePrepared.java
UTF-8
1,790
3.140625
3
[]
no_license
package jdbc_javaTpoint; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.io.*; public class InsertMultiplePrepared { public static void main(String args[]) { Connection con = null; try { // Class.forName("oracle.jdbc.driver.OracleDriver"); // // Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres","postgres", "postgres"); // con.setAutoCommit(false); System.out.println("Opened database successfully"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PreparedStatement stmt=con.prepareStatement("insert into COMPANY values(?,?,?,?,?)"); // columns: ID, NAME, AGE, ADDRESS, SALARY do { System.out.println("enter id:"); int id=Integer.parseInt(br.readLine()); System.out.println("enter name:"); String name=br.readLine(); System.out.println("enter age:"); int age=Integer.parseInt(br.readLine()); System.out.println("enter address:"); String address=br.readLine(); System.out.println("enter salary:"); float salary=Float.parseFloat(br.readLine()); stmt.setInt(1,id);//1 specifies the first parameter in the query stmt.setString(2,name); stmt.setInt(3,age); stmt.setString(4,address); stmt.setFloat(5,salary); int i=stmt.executeUpdate(); System.out.println(i+" records affected"); System.out.println("Do you want to continue: y/n"); String s=br.readLine(); if(s.startsWith("n")) { break; } }while(true); con.close(); } catch(Exception e){ System.out.println(e); } } }
true
8a8250ae8a129e67c42902c63eb5671f5533befd
Java
4aka/Examples___Java
/J_UseKeyboardsKeys/Test.java
UTF-8
539
2.328125
2
[]
no_license
package J_UseKeyboardsKeys; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; public class Test { public static void main() throws AWTException { Robot robot = new Robot(); try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } robot.keyPress(KeyEvent.VK_ESCAPE); robot.keyRelease(KeyEvent.VK_ESCAPE); robot.keyPress(KeyEvent.VK_END); robot.keyRelease(KeyEvent.VK_END); } }
true
c977f7014c581fb600b9b7fd86da8764b4d1395c
Java
Lichio/beldon
/core/src/main/java/belog/annotation/Column.java
UTF-8
552
2.359375
2
[]
no_license
package belog.annotation; /** * 字段注解 * Created by Beldon. * Copyright (c) 2016, All Rights Reserved. * http://beldon.me */ public @interface Column { /** * 字段名称 * * @return String */ String name() default ""; /** * 默认值 * * @return String */ String defaultValue() default ""; /** * 自读类型 * * @return String */ String type() default ""; /** * 字段长度 * * @return int */ int length() default 255; }
true
6323c581b16c16f621c11c393ca5f85d6fd76e50
Java
thmarx/dataFilter
/src6/main/java/net/mad/data/datafilter/function/ValueAccessorFunktion.java
UTF-8
117
1.726563
2
[]
no_license
package net.mad.data.datafilter.function; public interface ValueAccessorFunktion<T, V> { public V value(T type); }
true
27b5903693a881a297e4dfed3feb9f525e1fb032
Java
kjones-grand-circus/Lab15
/src/CountriesTextFile.java
UTF-8
2,424
3.140625
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CountriesTextFile { public CountriesTextFile(String countryName) { super(); this.countryName = countryName; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String countryName; public static void readFromFile() { Path writeFile = Paths.get("countries.txt"); File file = writeFile.toFile(); try { FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } catch (IOException e) { System.out.println("There were no countries!"); } } public static String fileAsString () { Path writeFile = Paths.get("countries.txt"); File file = writeFile.toFile(); try { FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr); String line = reader.readLine(); while(line!=null) { System.out.println(line); line += reader.readLine() + ","; } reader.close(); return line; } catch (IOException e) { e.printStackTrace(); return "ERROR"; } } public static void writeToFile(String name) { Path writeFile = Paths.get("countries.txt"); File file = writeFile.toFile(); try { PrintWriter out = new PrintWriter(new FileOutputStream(file, true)); out.println( name); out.close(); } catch (FileNotFoundException e) { createFile("countries.txt"); try { PrintWriter out = new PrintWriter(new FileOutputStream(file, true)); out.println( name); out.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } } } public static void createFile(String fileString) { Path filePath = Paths.get(fileString); if (Files.notExists(filePath)) { try { Files.createFile(filePath); System.out.println("Your file was cerated successfully"); } catch (IOException e) { System.out.println("Something went wrong with file creation "); e.printStackTrace(); } } } }
true
6832c63838472a37da2ebab0a2b7d2d4d21011ef
Java
Eva3ds/MuSC-Tool-Demo-repo
/mutestdemo/src/main/java/cn/edu/nju/mutestdemo/Model/StateVariable.java
UTF-8
2,359
2.8125
3
[]
no_license
package cn.edu.nju.mutestdemo.Model; import cn.edu.nju.mutestdemo.ASTMutation.Mutant; import cn.edu.nju.mutestdemo.EnumType.MuType; import java.util.ArrayList; public class StateVariable extends Var { private boolean isIndexed; private Object expression; private String visibility; private boolean isStateVar; private boolean isDeclaredConst; public boolean isIndexed() { return isIndexed; } public void setIndexed(boolean indexed) { isIndexed = indexed; } public Object getExpression() { return expression; } public void setExpression(Object expression) { this.expression = expression; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { this.visibility = visibility; } public boolean isStateVar() { return isStateVar; } public void setStateVar(boolean stateVar) { isStateVar = stateVar; } public boolean isDeclaredConst() { return isDeclaredConst; } public void setDeclaredConst(boolean declaredConst) { isDeclaredConst = declaredConst; } public void output(int space){ for(int i=0;i<space;i++) System.out.print(" "); if(getTypeName()!=null) printType(); if(!visibility.equals("default")) System.out.print(" "+visibility); if(isDeclaredConst()) System.out.print(" constant"); System.out.print(" "+getName()); if(expression!=null){ System.out.print(" = "); ExpressionStatement.printPart(expression); } System.out.println(";"); } public void addToMutant(ArrayList<MuType> types, int space){ String content=""; if(getTypeName()!=null) content=printTypeToLine(); if(!visibility.equals("default")) content+=" "+visibility; if(isDeclaredConst()) content+=" constant"; content+=" "+getName(); if(expression!=null){ content+=" = "; content+=ExpressionStatement.printPartToLine(new ArrayList<MuType>(),expression); } content+=";"; Mutant.lines.add(new Line(content,new ArrayList<MuType>(),space)); Statement.lineContent=""; } }
true
4d7cc3c71a113a1722622bb1675e95f13e110394
Java
Weathiel/secondhand_car_back
/src/main/java/eu/rogowski/dealer/payload/ResponseJSON.java
UTF-8
311
2.109375
2
[]
no_license
package eu.rogowski.dealer.payload; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ResponseJSON { String message; int responseCode; public ResponseJSON(String message, int responseCode) { this.message = message; this.responseCode = responseCode; } }
true
9a8449bc11d6249ec6651b54133695e641b00d5f
Java
Reymond2012/RocketLunchApi
/app/src/main/java/com/example/rocketlunchapi/model/DataSource.java
UTF-8
254
2.03125
2
[]
no_license
package com.example.rocketlunchapi.model; public interface DataSource { void getLaunchData(String date); interface DataListener{ void onLaunchRetrieval(RocketResponse rocketResponse); void onError(Throwable throwable); } }
true
232e43da0f69abd7ee7869c90a26edd7d61f1512
Java
AngelosDv/guessWho
/src/guesswho1/Game.java
UTF-8
15,365
3.6875
4
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package guesswho1; import java.util.Scanner; /** * * @author angel */ public class Game { Scanner scanInput = new Scanner(System.in); //here, we basically initialize the game: private int playerTurn = 0; private int players1left, players2left; private final Player player1 = new Player(); private final Player player2 = new Player(); private final PersonList board1 = new PersonList(); private final PersonList board2 = new PersonList(); private Person player1char = new Person("", "", "", "", true, true, true); private Person player2char = new Person("", "", "", "", true, true, true); //function to get player's names: public void startGame() { System.out.println("~~~~~~~~~~~~~~~~~~~~ GUESS WHO ~~~~~~~~~~~~~~~~~~~~"); System.out.println("Questions should be close-ended (Yes/No)." + "\n" + "Insert first the characteristic as written on your board e.g. 'Hair'!" + "\n" + "Then take a guess by inserting the value e.g.'Brown', again as written on your board!"); System.out.println(); System.out.println("Player 1 insert your name:"); String player1name = scanInput.next(); player1.SetName(player1name); System.out.println(); System.out.println("Player 2 insert your name:"); String player2name = scanInput.next(); player2.SetName(player2name); System.out.println(); } //function for player 1 to select character-person to "hide": public void player1selectCharacter() { board1.printPerson(); System.out.println(); System.out.println("---------- " + player1.GetName() + " select your character by instering his/her name:"); boolean chooseChar = false; while (!chooseChar) { String char1 = scanInput.next(); if ("matched".equals(board1.checkNameInList(char1))) { player1char = new Person(char1, board1.getSelectedCharHair(char1), board1.getSelectedCharShirt(char1), board1.getSelectedCharEyes(char1), board1.getSelectedGlasses(char1), board1.getSelectedSmile(char1), board1.getSelectedHat(char1)); chooseChar = true; } else { System.out.println("Name must be written as above! Select again:"); } } System.out.println(); } //function for player 2 to select character-person to "hide": public void player2selectCharacter() { board2.printPerson(); System.out.println(); System.out.println("---------- " + player2.GetName() + " select your character by instering his/her name:"); boolean chooseChar = false; while (!chooseChar) { String char2 = scanInput.next(); if ("matched".equals(board2.checkNameInList(char2))) { player2char = new Person(char2, board2.getSelectedCharHair(char2), board2.getSelectedCharShirt(char2), board2.getSelectedCharEyes(char2), board2.getSelectedGlasses(char2), board2.getSelectedSmile(char2), board2.getSelectedHat(char2)); chooseChar = true; } else { System.out.println("Name must be written as above! Select again:"); } } System.out.println(); } //this is actully the game function - players guess in turns until someone wins: public void playGame(){ while(!player1.GetWin() && !player2.GetWin()){ playInTurns(); } System.out.println("***** GAME OVER *****"); if (player1.GetWin()){ System.out.println(player1.GetName()+" wins!"); } else{ System.out.println(player2.GetName()+" wins!"); } } //function to allow players to play in turns: public void playInTurns(){ if((playerTurn%2)==0){ System.out.println(); System.out.println(); System.out.println("---------- " + player1.GetName() + " it's your turn!"); player1guess(); players1left = board1.getPersonListLength(); if(players1left == 1){ player1.SetWin(); } } else{ System.out.println(); System.out.println(); System.out.println("---------- " + player2.GetName() + " it's your turn!"); player2guess(); players2left = board2.getPersonListLength(); if(players2left == 1){ player2.SetWin(); } } playerTurn ++; } //function for player 1 to take a guess: //we check his/her inputs and delete the characters-persons that are on his/her board based on his/her guess //and if he/she guessed right. public void player1guess() { board1.printPerson(); System.out.println("~~~~~ TAKE A GUESS!"); boolean chooseChar = false; while (!chooseChar) { System.out.println("characteristic:"); String characteristic = scanInput.next(); if ("Name".equals(characteristic)) { boolean chooseName = false; while (!chooseName) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board1.checkNameInList(guess))) { board1.deleteName(player2char.getName(), guess); chooseName = true; } else { System.out.println("Insert exactly one of the names above! Guess again!"); } chooseChar = true; } } else if ("Hair".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board1.checkHair(guess))) { board1.deleteHair(player2char.getHair(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } chooseChar = true; } } else if ("Shirt".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board1.checkShirt(guess))) { board1.deleteShirt(player2char.getShirt(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } } chooseChar = true; } else if ("Eyes".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board1.checkEyes(guess))) { board1.deleteEyes(player2char.getEyes(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } } chooseChar = true; } else if ("Glasses".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board1.deleteGlasses(player2char.getGlasses(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else if ("Smile".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board1.deleteSmile(player2char.getSmiling(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else if ("Hat".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board1.deleteHat(player2char.getHat(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else { System.out.println("Characteristics must be written as above! Guess again!"); } } board1.printPerson(); } //function for player 2 to take a guess: //we check his/her inputs and delete the characters-persons that are on his/her board based on his/her guess //and if he/she guessed right. public void player2guess() { board2.printPerson(); System.out.println("~~~~~ TAKE A GUESS!"); boolean chooseChar = false; while (!chooseChar) { System.out.println("characteristic:"); String characteristic = scanInput.next(); if ("Name".equals(characteristic)) { boolean chooseName = false; while (!chooseName) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board2.checkNameInList(guess))) { board2.deleteName(player1char.getName(), guess); chooseName = true; } else { System.out.println("Insert exactly one of the names above! Guess again!"); } chooseChar = true; } } else if ("Hair".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board2.checkHair(guess))) { board2.deleteHair(player1char.getHair(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } chooseChar = true; } } else if ("Shirt".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board2.checkShirt(guess))) { board2.deleteShirt(player1char.getShirt(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } } chooseChar = true; } else if ("Eyes".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("matched".equals(board2.checkEyes(guess))) { board2.deleteEyes(player1char.getEyes(), guess); chooseColour = true; } else { System.out.println("Insert exactly one of the colours above! Guess again!"); } } chooseChar = true; } else if ("Glasses".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board2.deleteGlasses(player1char.getGlasses(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else if ("Smile".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board2.deleteSmile(player1char.getSmiling(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else if ("Hat".equals(characteristic)) { boolean chooseColour = false; while (!chooseColour) { System.out.println("guess:"); String guess = scanInput.next(); if ("Yes".equals(guess) || "No".equals(guess)) { board2.deleteHat(player1char.getHat(), guess); chooseColour = true; } else { System.out.println("Enter 'Yes' or 'No'! Guess again!"); } } chooseChar = true; } else { System.out.println("Characteristics must be written as above! Guess again!"); } } board2.printPerson(); } }
true
de7a6a374b4b4fda96d76b9e7ce336c91dc9b55e
Java
mohanrajanna15/blackduck-alert
/src/main/java/com/synopsys/integration/alert/provider/blackduck/issues/BlackDuckProviderIssueModel.java
UTF-8
1,834
1.921875
2
[ "Apache-2.0" ]
permissive
/** * blackduck-alert * * Copyright (c) 2020 Synopsys, Inc. * * 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 com.synopsys.integration.alert.provider.blackduck.issues; public class BlackDuckProviderIssueModel { public static final String DEFAULT_ASSIGNEE = "Alert User"; private final String key; private final String status; private final String summary; private final String link; private String assignee = DEFAULT_ASSIGNEE; public BlackDuckProviderIssueModel(String key, String status, String summary, String link) { this.key = key; this.status = status; this.summary = summary; this.link = link; } public String getKey() { return key; } public String getStatus() { return status; } public String getSummary() { return summary; } public String getLink() { return link; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } }
true
af7b3f118870e2ccc69d8e5120b84224fbe8e0ab
Java
drrilll/AI-Robot
/src/dang/AIrobot/AlgoThread.java
UTF-8
106
1.757813
2
[]
no_license
package dang.AIrobot; public abstract class AlgoThread extends Thread { abstract Move getFinalMove(); }
true
474bc22b18b08836348b3f681030aa206c1e9e5a
Java
TadeudeCampos/SistemasDistribuidos01
/src/aula/pkg1/lab/menosDois.java
UTF-8
485
2.421875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aula.pkg1.lab; import java.util.Iterator; import javax.swing.JOptionPane; /** * * @author Theparanoic */ public class menosDois { public static void main(String[] args) { for(int x=20; x >=0 ;x -=2){ JOptionPane.showMessageDialog(null, x); } } }
true
dd42291cd6e1bd29bff852de7cf2843f58cbcaa7
Java
elBukkit/MagicPlugin
/Magic/src/main/java/com/elmakers/mine/bukkit/tasks/DropActionTask.java
UTF-8
333
2.46875
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.elmakers.mine.bukkit.tasks; import com.elmakers.mine.bukkit.wand.Wand; public class DropActionTask implements Runnable { private final Wand wand; public DropActionTask(Wand wand) { this.wand = wand; } @Override public void run() { wand.performAction(wand.getDropAction()); } }
true
e8a5f4179a4c8dd9b4dc9fda49cf4e08425aa833
Java
XRiver/DevOpsTeachingPlatform
/DevOpsStaticCheck/src/main/java/nju/wqy/entity/IntegratedData.java
UTF-8
1,220
2.0625
2
[]
no_license
package nju.wqy.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Data @Entity @Table(name = "integratedData") public class IntegratedData { @Id @Column(name = "projectKey") private String projectKey; @Column(name = "lastAnalysis") private String lastAnalysis; @Column(name = "healthDegree") private int healthDegree; @Column(name = "risk") private int risk; @Column(name = "problemNo") private int problemNo; public String getProjectKey() { return projectKey; } public void setProjectKey(String projectKey) { this.projectKey = projectKey; } public String getLastAnalysis() { return lastAnalysis; } public void setLastAnalysis(String lastAnalysis) { this.lastAnalysis = lastAnalysis; } public int getHealthDegree() { return healthDegree; } public void setHealthDegree(int healthDegree) { this.healthDegree = healthDegree; } public int getRisk() { return risk; } public void setRisk(int risk) { this.risk = risk; } public int getProblemNo() { return problemNo; } public void setProblemNo(int problemNo) { this.problemNo = problemNo; } }
true
049f654ec1f537123eed40bf4d19db29294f4790
Java
sevenzerolee/AndroidTest
/src/org/sevenzero/activity/MenuIconActivity.java
UTF-8
4,539
2.34375
2
[]
no_license
package org.sevenzero.activity; import java.util.ArrayList; import java.util.List; import org.sevenzero.R; import org.sevenzero.menu.SettingMenu; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.PopupWindow.OnDismissListener; import android.widget.TextView; import com.foxit.util.Util; public class MenuIconActivity extends Activity { private static final String tag = MenuIconActivity.class.getSimpleName(); private TextView menu; private SettingMenu settingMenu; private List<String> menuName; class PopWindowDismiss implements OnDismissListener { @Override public void onDismiss() { Util.printLog(tag, "### 退出菜单"); showMenu(); } } class ItemClickEvent implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // 显示点击的是哪个菜单哪个选项。 String name = menuName.get(arg2); // 设置服务地址 if (menuName.get(0).equals(name)) { } // 设置用户信息 else if (menuName.get(1).equals(name)) { } // 检查更新 else if (menuName.get(2).equals(name)) { } settingMenu.dismiss(); } } List<String> addItems(String[] values) { List<String> list = new ArrayList<String>(); for (String var : values) { list.add(var); } return list; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_icon); menu = (TextView) findViewById(R.id.menu); menu.setOnClickListener(listener); viewX = menu.getX(); viewY = menu.getY(); Util.printLog(tag, "onCreate View: " + viewX + ", " + viewY); menuName = addItems(new String[]{ "服务地址", "用户信息", "检查更新"}); settingMenu = new SettingMenu(this, menuName, new ItemClickEvent(), new PopWindowDismiss()); } private boolean first = true; void initViewCoordinate() { if (first) { viewX = menu.getX(); viewY = menu.getY(); Util.printLog(tag, "初始化坐标 View: " + viewX + ", " + viewY); first = false; } } private float viewX, viewY; private boolean click = false; // 显示菜单 void showMenu() { if (click) { click = false; if (null != menu) { menu.setVisibility(View.VISIBLE); } } } // 隐藏菜单 void hideMenu() { if (!click) { click = true; if (null != menu) { menu.setVisibility(View.GONE); } if (null != settingMenu) { settingMenu.showAtLocation(findViewById(R.id.root_layout), Gravity.BOTTOM, 0,0); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { Util.printLog(tag, "### == > onCreateOptionsMenu"); return true; } public boolean onMenuOpened(int featureId, Menu menu) { Util.printLog(tag, "### == > onMenuOpened"); hideMenu(); return false; } private OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { // initViewCoordinate(); switch (v.getId()) { case R.id.menu: Util.printLog(tag, "" + click); if (!click) { // click = true; hideMenu(); // RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( // RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); // rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); // rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); // menu.setLayoutParams(rlp); // menu.setX(viewX); // menu.setY(viewY - 200); // LayoutParams lp = (LayoutParams) rootLayout.getLayoutParams(); // lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); // lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); // addContentView(menu, rlp); } // else { // click = false; // RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( // RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); // rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP); // rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // menu.setLayoutParams(rlp); // menu.setX(viewX); // menu.setY(viewY); // } break; default: break; } } }; }
true
8e05ee8fb2e4ea88a33ec41d3d4f345284f73270
Java
sotowang/leetcode
/src/main/数组/t1128/NumEquivDominoPairs.java
UTF-8
1,116
3.34375
3
[]
no_license
package 数组.t1128; import java.util.*; /** * @auther: sotowang * @date: 2019/12/31 16:04 */ public class NumEquivDominoPairs { public int numEquivDominoPairs(int[][] dominoes) { Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i = 0; i < dominoes.length; i++) { int val = Math.min(dominoes[i][0] * 10 + dominoes[i][1], dominoes[i][1] * 10 + dominoes[i][0]); map.put(val, map.getOrDefault(val, 0) + 1); } Iterator<Integer> iterator = map.values().iterator(); while (iterator.hasNext()) { int value = iterator.next(); count += value * (value - 1) / 2; } return count; } public static void main(String[] args) { int[][] dominoes1 = {{1, 2}, {1, 2}, {1, 1}, {1, 2}, {2, 2}}; assert new NumEquivDominoPairs().numEquivDominoPairs(dominoes1) == 3; System.out.println(); int[][] dominoes = {{1, 2}, {2, 1}, {3, 4}, {5, 6}}; assert new NumEquivDominoPairs().numEquivDominoPairs(dominoes) == 1; System.out.println(); } }
true
6dd4a100678f6ec754a474d7a23a3bfee4db9d02
Java
smeup/asup
/org.smeup.sys.os.cmd/src/org/smeup/sys/os/cmd/QOperatingSystemCommandPackage.java
UTF-8
38,345
1.617188
2
[]
no_license
/** * Copyright (c) 2012, 2016 Sme.UP and others. * 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 */ package org.smeup.sys.os.cmd; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.smeup.sys.il.core.QIntegratedLanguageCorePackage; import org.smeup.sys.il.data.term.QIntegratedLanguageDataTermPackage; import org.smeup.sys.os.type.QOperatingSystemTypePackage; /** * <!-- begin-user-doc --> The <b>Package</b> for the model. It contains * accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.QOperatingSystemCommandFactory * @model kind="package" * @generated */ public interface QOperatingSystemCommandPackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ String eNAME = "cmd"; /** * The package namespace URI. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ String eNS_URI = "http://www.smeup.org/asup/os/cmd"; /** * The package namespace name. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ String eNS_PREFIX = "os-cmd"; /** * The singleton instance of the package. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ QOperatingSystemCommandPackage eINSTANCE = org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl.init(); /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CallableCommandImpl <em>Callable Command</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CallableCommandImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCallableCommand() * @generated */ int CALLABLE_COMMAND = 0; /** * The feature id for the '<em><b>Command</b></em>' reference. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int CALLABLE_COMMAND__COMMAND = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Command String</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int CALLABLE_COMMAND__COMMAND_STRING = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 1; /** * The feature id for the '<em><b>Variables</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int CALLABLE_COMMAND__VARIABLES = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 2; /** * The feature id for the '<em><b>Data Container</b></em>' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int CALLABLE_COMMAND__DATA_CONTAINER = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 3; /** * The number of structural features of the '<em>Callable Command</em>' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int CALLABLE_COMMAND_FEATURE_COUNT = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CommandImpl <em>Command</em>}' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommand() * @generated */ int COMMAND = 1; /** * The feature id for the '<em><b>Application</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__APPLICATION = QOperatingSystemTypePackage.TYPED_OBJECT__APPLICATION; /** * The feature id for the '<em><b>Facets</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND__FACETS = QOperatingSystemTypePackage.TYPED_OBJECT__FACETS; /** * The feature id for the '<em><b>Name</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__NAME = QOperatingSystemTypePackage.TYPED_OBJECT__NAME; /** * The feature id for the '<em><b>Text</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__TEXT = QOperatingSystemTypePackage.TYPED_OBJECT__TEXT; /** * The feature id for the '<em><b>Creation Info</b></em>' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND__CREATION_INFO = QOperatingSystemTypePackage.TYPED_OBJECT__CREATION_INFO; /** * The feature id for the '<em><b>Address</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__ADDRESS = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Allow Batch</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__ALLOW_BATCH = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 1; /** * The feature id for the '<em><b>Class CMD</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__CLASS_CMD = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 2; /** * The feature id for the '<em><b>Parameters</b></em>' containment reference list. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND__PARAMETERS = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 3; /** * The feature id for the '<em><b>Program</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__PROGRAM = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 4; /** * The feature id for the '<em><b>Source</b></em>' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND__SOURCE = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 5; /** * The feature id for the '<em><b>Status</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__STATUS = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 6; /** * The feature id for the '<em><b>Type Name</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND__TYPE_NAME = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 7; /** * The number of structural features of the '<em>Command</em>' class. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_FEATURE_COUNT = QOperatingSystemTypePackage.TYPED_OBJECT_FEATURE_COUNT + 8; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CommandContainerImpl <em>Command Container</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandContainerImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandContainer() * @generated */ int COMMAND_CONTAINER = 2; /** * The feature id for the '<em><b>Contents</b></em>' containment reference list. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_CONTAINER__CONTENTS = QOperatingSystemTypePackage.TYPED_CONTAINER__CONTENTS; /** * The feature id for the '<em><b>Type Name</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_CONTAINER__TYPE_NAME = QOperatingSystemTypePackage.TYPED_CONTAINER_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Command Container</em>' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_CONTAINER_FEATURE_COUNT = QOperatingSystemTypePackage.TYPED_CONTAINER_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CommandDataImpl <em>Command Data</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandDataImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandData() * @generated */ int COMMAND_DATA = 3; /** * The feature id for the '<em><b>Facets</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__FACETS = QIntegratedLanguageDataTermPackage.DATA_TERM__FACETS; /** * The feature id for the '<em><b>Based</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__BASED = QIntegratedLanguageDataTermPackage.DATA_TERM__BASED; /** * The feature id for the '<em><b>Cardinality</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__CARDINALITY = QIntegratedLanguageDataTermPackage.DATA_TERM__CARDINALITY; /** * The feature id for the '<em><b>Constant</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__CONSTANT = QIntegratedLanguageDataTermPackage.DATA_TERM__CONSTANT; /** * The feature id for the '<em><b>Default</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__DEFAULT = QIntegratedLanguageDataTermPackage.DATA_TERM__DEFAULT; /** * The feature id for the '<em><b>Definition</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__DEFINITION = QIntegratedLanguageDataTermPackage.DATA_TERM__DEFINITION; /** * The feature id for the '<em><b>Key</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__KEY = QIntegratedLanguageDataTermPackage.DATA_TERM__KEY; /** * The feature id for the '<em><b>Initialized</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__INITIALIZED = QIntegratedLanguageDataTermPackage.DATA_TERM__INITIALIZED; /** * The feature id for the '<em><b>Like</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__LIKE = QIntegratedLanguageDataTermPackage.DATA_TERM__LIKE; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__NAME = QIntegratedLanguageDataTermPackage.DATA_TERM__NAME; /** * The feature id for the '<em><b>Restricted</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__RESTRICTED = QIntegratedLanguageDataTermPackage.DATA_TERM__RESTRICTED; /** * The feature id for the '<em><b>Text</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA__TEXT = QIntegratedLanguageDataTermPackage.DATA_TERM__TEXT; /** * The number of structural features of the '<em>Command Data</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_DATA_FEATURE_COUNT = QIntegratedLanguageDataTermPackage.DATA_TERM_FEATURE_COUNT + 0; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.QCommandManager <em>Command Manager</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.QCommandManager * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandManager() * @generated */ int COMMAND_MANAGER = 4; /** * The number of structural features of the '<em>Command Manager</em>' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_MANAGER_FEATURE_COUNT = 0; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CommandParameterImpl <em>Command Parameter</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandParameterImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandParameter() * @generated */ int COMMAND_PARAMETER = 5; /** * The feature id for the '<em><b>Allow Variable</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_PARAMETER__ALLOW_VARIABLE = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Data Term</b></em>' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_PARAMETER__DATA_TERM = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 1; /** * The feature id for the '<em><b>Name</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_PARAMETER__NAME = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 2; /** * The feature id for the '<em><b>Position</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_PARAMETER__POSITION = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 3; /** * The feature id for the '<em><b>Status</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_PARAMETER__STATUS = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 4; /** * The feature id for the '<em><b>Hidden</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_PARAMETER__HIDDEN = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 5; /** * The number of structural features of the '<em>Command Parameter</em>' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_PARAMETER_FEATURE_COUNT = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 6; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.impl.CommandSourceImpl <em>Command Source</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandSourceImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandSource() * @generated */ int COMMAND_SOURCE = 6; /** * The feature id for the '<em><b>Type</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_SOURCE__TYPE = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Content</b></em>' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ int COMMAND_SOURCE__CONTENT = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Command Source</em>' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated * @ordered */ int COMMAND_SOURCE_FEATURE_COUNT = QIntegratedLanguageCorePackage.OBJECT_FEATURE_COUNT + 2; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.CommandStatus * <em>Command Status</em>}' enum. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see org.smeup.sys.os.cmd.CommandStatus * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandStatus() * @generated */ int COMMAND_STATUS = 7; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.CommandParameterOrder <em>Command Parameter Order</em>}' enum. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.CommandParameterOrder * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandParameterOrder() * @generated */ int COMMAND_PARAMETER_ORDER = 8; /** * The meta object id for the '{@link org.smeup.sys.os.cmd.CommandOrder * <em>Command Order</em>}' enum. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see org.smeup.sys.os.cmd.CommandOrder * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandOrder() * @generated */ int COMMAND_ORDER = 9; /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCallableCommand <em>Callable Command</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Callable Command</em>'. * @see org.smeup.sys.os.cmd.QCallableCommand * @generated */ EClass getCallableCommand(); /** * Returns the meta object for the reference '{@link org.smeup.sys.os.cmd.QCallableCommand#getCommand <em>Command</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the reference '<em>Command</em>'. * @see org.smeup.sys.os.cmd.QCallableCommand#getCommand() * @see #getCallableCommand() * @generated */ EReference getCallableCommand_Command(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCallableCommand#getCommandString <em>Command String</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Command String</em>'. * @see org.smeup.sys.os.cmd.QCallableCommand#getCommandString() * @see #getCallableCommand() * @generated */ EAttribute getCallableCommand_CommandString(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCallableCommand#getVariables <em>Variables</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Variables</em>'. * @see org.smeup.sys.os.cmd.QCallableCommand#getVariables() * @see #getCallableCommand() * @generated */ EAttribute getCallableCommand_Variables(); /** * Returns the meta object for the containment reference '{@link org.smeup.sys.os.cmd.QCallableCommand#getDataContainer <em>Data Container</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Data Container</em>'. * @see org.smeup.sys.os.cmd.QCallableCommand#getDataContainer() * @see #getCallableCommand() * @generated */ EReference getCallableCommand_DataContainer(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommand <em>Command</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Command</em>'. * @see org.smeup.sys.os.cmd.QCommand * @generated */ EClass getCommand(); /** * Returns the meta object for the attribute ' * {@link org.smeup.sys.os.cmd.QCommand#getAddress <em>Address</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for the attribute '<em>Address</em>'. * @see org.smeup.sys.os.cmd.QCommand#getAddress() * @see #getCommand() * @generated */ EAttribute getCommand_Address(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommand#isAllowBatch <em>Allow Batch</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Allow Batch</em>'. * @see org.smeup.sys.os.cmd.QCommand#isAllowBatch() * @see #getCommand() * @generated */ EAttribute getCommand_AllowBatch(); /** * Returns the meta object for the containment reference list '{@link org.smeup.sys.os.cmd.QCommand#getParameters <em>Parameters</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Parameters</em>'. * @see org.smeup.sys.os.cmd.QCommand#getParameters() * @see #getCommand() * @generated */ EReference getCommand_Parameters(); /** * Returns the meta object for the attribute ' * {@link org.smeup.sys.os.cmd.QCommand#getProgram <em>Program</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for the attribute '<em>Program</em>'. * @see org.smeup.sys.os.cmd.QCommand#getProgram() * @see #getCommand() * @generated */ EAttribute getCommand_Program(); /** * Returns the meta object for the containment reference ' * {@link org.smeup.sys.os.cmd.QCommand#getSource <em>Source</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for the containment reference '<em>Source</em>'. * @see org.smeup.sys.os.cmd.QCommand#getSource() * @see #getCommand() * @generated */ EReference getCommand_Source(); /** * Returns the meta object for the attribute ' * {@link org.smeup.sys.os.cmd.QCommand#getStatus <em>Status</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for the attribute '<em>Status</em>'. * @see org.smeup.sys.os.cmd.QCommand#getStatus() * @see #getCommand() * @generated */ EAttribute getCommand_Status(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommand#getTypeName <em>Type Name</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Type Name</em>'. * @see org.smeup.sys.os.cmd.QCommand#getTypeName() * @see #getCommand() * @generated */ EAttribute getCommand_TypeName(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommand#isClassCMD <em>Class CMD</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Class CMD</em>'. * @see org.smeup.sys.os.cmd.QCommand#isClassCMD() * @see #getCommand() * @generated */ EAttribute getCommand_ClassCMD(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommandContainer <em>Command Container</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Command Container</em>'. * @see org.smeup.sys.os.cmd.QCommandContainer * @generated */ EClass getCommandContainer(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandContainer#getTypeName <em>Type Name</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Type Name</em>'. * @see org.smeup.sys.os.cmd.QCommandContainer#getTypeName() * @see #getCommandContainer() * @generated */ EAttribute getCommandContainer_TypeName(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommandData <em>Command Data</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Command Data</em>'. * @see org.smeup.sys.os.cmd.QCommandData * @generated */ EClass getCommandData(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommandManager <em>Command Manager</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Command Manager</em>'. * @see org.smeup.sys.os.cmd.QCommandManager * @generated */ EClass getCommandManager(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommandParameter <em>Command Parameter</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Command Parameter</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter * @generated */ EClass getCommandParameter(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandParameter#isAllowVariable <em>Allow Variable</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Allow Variable</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#isAllowVariable() * @see #getCommandParameter() * @generated */ EAttribute getCommandParameter_AllowVariable(); /** * Returns the meta object for the containment reference '{@link org.smeup.sys.os.cmd.QCommandParameter#getDataTerm <em>Data Term</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Data Term</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#getDataTerm() * @see #getCommandParameter() * @generated */ EReference getCommandParameter_DataTerm(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandParameter#getName <em>Name</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#getName() * @see #getCommandParameter() * @generated */ EAttribute getCommandParameter_Name(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandParameter#getPosition <em>Position</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Position</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#getPosition() * @see #getCommandParameter() * @generated */ EAttribute getCommandParameter_Position(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandParameter#getStatus <em>Status</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Status</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#getStatus() * @see #getCommandParameter() * @generated */ EAttribute getCommandParameter_Status(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandParameter#isHidden <em>Hidden</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Hidden</em>'. * @see org.smeup.sys.os.cmd.QCommandParameter#isHidden() * @see #getCommandParameter() * @generated */ EAttribute getCommandParameter_Hidden(); /** * Returns the meta object for class '{@link org.smeup.sys.os.cmd.QCommandSource <em>Command Source</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for class '<em>Command Source</em>'. * @see org.smeup.sys.os.cmd.QCommandSource * @generated */ EClass getCommandSource(); /** * Returns the meta object for the attribute ' * {@link org.smeup.sys.os.cmd.QCommandSource#getType <em>Type</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for the attribute '<em>Type</em>'. * @see org.smeup.sys.os.cmd.QCommandSource#getType() * @see #getCommandSource() * @generated */ EAttribute getCommandSource_Type(); /** * Returns the meta object for the attribute '{@link org.smeup.sys.os.cmd.QCommandSource#getContent <em>Content</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * @return the meta object for the attribute '<em>Content</em>'. * @see org.smeup.sys.os.cmd.QCommandSource#getContent() * @see #getCommandSource() * @generated */ EAttribute getCommandSource_Content(); /** * Returns the meta object for enum ' * {@link org.smeup.sys.os.cmd.CommandStatus <em>Command Status</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for enum '<em>Command Status</em>'. * @see org.smeup.sys.os.cmd.CommandStatus * @generated */ EEnum getCommandStatus(); /** * Returns the meta object for enum '{@link org.smeup.sys.os.cmd.CommandParameterOrder <em>Command Parameter Order</em>}'. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @return the meta object for enum '<em>Command Parameter Order</em>'. * @see org.smeup.sys.os.cmd.CommandParameterOrder * @generated */ EEnum getCommandParameterOrder(); /** * Returns the meta object for enum ' * {@link org.smeup.sys.os.cmd.CommandOrder <em>Command Order</em>}'. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the meta object for enum '<em>Command Order</em>'. * @see org.smeup.sys.os.cmd.CommandOrder * @generated */ EEnum getCommandOrder(); /** * Returns the factory that creates the instances of the model. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @return the factory that creates the instances of the model. * @generated */ QOperatingSystemCommandFactory getOperatingSystemCommandFactory(); /** * <!-- begin-user-doc --> Defines literals for the meta objects that * represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each operation of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CallableCommandImpl <em>Callable Command</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CallableCommandImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCallableCommand() * @generated */ EClass CALLABLE_COMMAND = eINSTANCE.getCallableCommand(); /** * The meta object literal for the '<em><b>Command</b></em>' reference feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EReference CALLABLE_COMMAND__COMMAND = eINSTANCE.getCallableCommand_Command(); /** * The meta object literal for the '<em><b>Command String</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute CALLABLE_COMMAND__COMMAND_STRING = eINSTANCE.getCallableCommand_CommandString(); /** * The meta object literal for the '<em><b>Variables</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute CALLABLE_COMMAND__VARIABLES = eINSTANCE.getCallableCommand_Variables(); /** * The meta object literal for the '<em><b>Data Container</b></em>' containment reference feature. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ EReference CALLABLE_COMMAND__DATA_CONTAINER = eINSTANCE.getCallableCommand_DataContainer(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CommandImpl <em>Command</em>}' class. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommand() * @generated */ EClass COMMAND = eINSTANCE.getCommand(); /** * The meta object literal for the '<em><b>Address</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__ADDRESS = eINSTANCE.getCommand_Address(); /** * The meta object literal for the '<em><b>Allow Batch</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__ALLOW_BATCH = eINSTANCE.getCommand_AllowBatch(); /** * The meta object literal for the '<em><b>Parameters</b></em>' containment reference list feature. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ EReference COMMAND__PARAMETERS = eINSTANCE.getCommand_Parameters(); /** * The meta object literal for the '<em><b>Program</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__PROGRAM = eINSTANCE.getCommand_Program(); /** * The meta object literal for the '<em><b>Source</b></em>' containment reference feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EReference COMMAND__SOURCE = eINSTANCE.getCommand_Source(); /** * The meta object literal for the '<em><b>Status</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__STATUS = eINSTANCE.getCommand_Status(); /** * The meta object literal for the '<em><b>Type Name</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__TYPE_NAME = eINSTANCE.getCommand_TypeName(); /** * The meta object literal for the '<em><b>Class CMD</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND__CLASS_CMD = eINSTANCE.getCommand_ClassCMD(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CommandContainerImpl <em>Command Container</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandContainerImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandContainer() * @generated */ EClass COMMAND_CONTAINER = eINSTANCE.getCommandContainer(); /** * The meta object literal for the '<em><b>Type Name</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_CONTAINER__TYPE_NAME = eINSTANCE.getCommandContainer_TypeName(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CommandDataImpl <em>Command Data</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandDataImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandData() * @generated */ EClass COMMAND_DATA = eINSTANCE.getCommandData(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.QCommandManager <em>Command Manager</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.QCommandManager * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandManager() * @generated */ EClass COMMAND_MANAGER = eINSTANCE.getCommandManager(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CommandParameterImpl <em>Command Parameter</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandParameterImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandParameter() * @generated */ EClass COMMAND_PARAMETER = eINSTANCE.getCommandParameter(); /** * The meta object literal for the '<em><b>Allow Variable</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_PARAMETER__ALLOW_VARIABLE = eINSTANCE.getCommandParameter_AllowVariable(); /** * The meta object literal for the '<em><b>Data Term</b></em>' containment reference feature. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ EReference COMMAND_PARAMETER__DATA_TERM = eINSTANCE.getCommandParameter_DataTerm(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_PARAMETER__NAME = eINSTANCE.getCommandParameter_Name(); /** * The meta object literal for the '<em><b>Position</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_PARAMETER__POSITION = eINSTANCE.getCommandParameter_Position(); /** * The meta object literal for the '<em><b>Status</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_PARAMETER__STATUS = eINSTANCE.getCommandParameter_Status(); /** * The meta object literal for the '<em><b>Hidden</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_PARAMETER__HIDDEN = eINSTANCE.getCommandParameter_Hidden(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.impl.CommandSourceImpl <em>Command Source</em>}' class. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.impl.CommandSourceImpl * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandSource() * @generated */ EClass COMMAND_SOURCE = eINSTANCE.getCommandSource(); /** * The meta object literal for the '<em><b>Type</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_SOURCE__TYPE = eINSTANCE.getCommandSource_Type(); /** * The meta object literal for the '<em><b>Content</b></em>' attribute feature. * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ EAttribute COMMAND_SOURCE__CONTENT = eINSTANCE.getCommandSource_Content(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.CommandStatus <em>Command Status</em>}' enum. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.CommandStatus * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandStatus() * @generated */ EEnum COMMAND_STATUS = eINSTANCE.getCommandStatus(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.CommandParameterOrder <em>Command Parameter Order</em>}' enum. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see org.smeup.sys.os.cmd.CommandParameterOrder * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandParameterOrder() * @generated */ EEnum COMMAND_PARAMETER_ORDER = eINSTANCE.getCommandParameterOrder(); /** * The meta object literal for the '{@link org.smeup.sys.os.cmd.CommandOrder <em>Command Order</em>}' enum. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see org.smeup.sys.os.cmd.CommandOrder * @see org.smeup.sys.os.cmd.impl.OperatingSystemCommandPackageImpl#getCommandOrder() * @generated */ EEnum COMMAND_ORDER = eINSTANCE.getCommandOrder(); } } // QOperatingSystemCommandPackage
true
cd2907ddebcc92924084bfa5d8e3fe3e5e0b3941
Java
Another7/CloudMusicBack-end
/src/main/java/star/sky/another/service/impl/MomentsServiceInterfaceImpl.java
UTF-8
1,305
2.25
2
[]
no_license
package star.sky.another.service.impl; import org.springframework.stereotype.Service; import star.sky.another.dao.FollowMapper; import star.sky.another.dao.MomentsMapper; import star.sky.another.model.entity.Moments; import star.sky.another.service.MomentsServiceInterface; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @Description * @Author Another * @Date 2020/4/25 20:59 **/ @Service public class MomentsServiceInterfaceImpl implements MomentsServiceInterface { private final MomentsMapper momentsMapper; private final FollowMapper followMapper; public MomentsServiceInterfaceImpl(MomentsMapper momentsMapper, FollowMapper followMapper) { this.momentsMapper = momentsMapper; this.followMapper = followMapper; } @Override public int insertMoments(Moments moments) { return momentsMapper.insert(moments); } @Override public List<Moments> selectMomentsByUserId(Long userId) { // 1.查询用户关注的其他用户 // 2.查询其他用户的动态 Set<Long> followerIdSet = followMapper.selectFollower(userId); if (followerIdSet.size() > 0) { return momentsMapper.selectMomentsByCreatorId(followerIdSet); } return new ArrayList<>(); } }
true
a7af2ef41787122f58ec1cdcf47f2fd34fa3ffe4
Java
Nonlone/newAdmin
/mop/src/main/java/com/feitai/admin/mop/advert/vo/AdvertGroupVo.java
UTF-8
694
2.109375
2
[]
no_license
package com.feitai.admin.mop.advert.vo; import com.feitai.admin.mop.advert.dao.entity.AdvertGroup; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import java.util.List; @Data public class AdvertGroupVo extends AdvertGroup { private String groupIds; public static AdvertGroupVo build(AdvertGroup advertGroup, List<Long> groupIdsList) { AdvertGroupVo advertGroupVo = new AdvertGroupVo(); BeanUtils.copyProperties(advertGroup, advertGroupVo); if (!groupIdsList.isEmpty()) { advertGroupVo.setGroupIds(StringUtils.join(groupIdsList, ",")); } return advertGroupVo; } }
true
e074d0d45bdeee00dd5560af23ccef79eda25a4c
Java
AppExperts2005/spring-boot-aws
/note-analysis-function/src/main/java/dev/jozefowicz/companydashboard/function/NoteAnalysisHandler.java
UTF-8
2,798
2.359375
2
[]
no_license
package dev.jozefowicz.companydashboard.function; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.fasterxml.jackson.databind.ObjectMapper; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.DetectSentimentRequest; import software.amazon.awssdk.services.comprehend.model.DetectSentimentResponse; import software.amazon.awssdk.services.comprehend.model.LanguageCode; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; public class NoteAnalysisHandler implements RequestHandler<SQSEvent, Void> { private final static String RESPONSE_QUEUE_URL = System.getenv("RESPONSE_QUEUE_URL"); private final static Region REGION = Region.of(System.getenv("AWS_REGION")); private final ComprehendClient comprehendClient = ComprehendClient.builder() .region(REGION) .build(); private final SqsClient sqsClient = SqsClient.builder() .region(REGION) .build(); private final ObjectMapper objectMapper = new ObjectMapper(); public Void handleRequest(SQSEvent sqsEvent, Context context) { sqsEvent.getRecords().forEach(record -> { try { NoteAnalysisRequest noteAnalysisRequest = objectMapper.readValue(record.getBody(), NoteAnalysisRequest.class); DetectSentimentRequest sentimentRequest = DetectSentimentRequest .builder().languageCode(LanguageCode.EN).text(noteAnalysisRequest.getBody()).build(); final DetectSentimentResponse sentimentResponse = comprehendClient.detectSentiment(sentimentRequest); NoteAnalysisResponse response = new NoteAnalysisResponse(); response.setNoteId(noteAnalysisRequest.getNoteId()); response.setSentiment(sentimentResponse.sentimentAsString()); SendMessageRequest messageRequest = SendMessageRequest .builder() .messageDeduplicationId(noteAnalysisRequest.getNoteId()) .messageGroupId(noteAnalysisRequest.getNoteId()) .messageBody(objectMapper.writeValueAsString(response)) .queueUrl(RESPONSE_QUEUE_URL).build(); sqsClient.sendMessage(messageRequest); } catch (Exception e) { e.printStackTrace(); context.getLogger().log(String.format("Unable to analyse note %s", record.getBody())); } }); return null; } }
true
520dcab6b58f7fbb099eab68c9833f020d982f39
Java
bitterbit/Parse-Dashboard-Android
/Parse/src/main/java/com/parse/ParseSchemaController.java
UTF-8
1,210
2.328125
2
[]
no_license
package com.parse; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import bolts.Continuation; import bolts.Task; /* Package */ class ParseSchemaController { private final ParseHttpClient restClient; public ParseSchemaController(ParseHttpClient restClient){ this.restClient = restClient; } public Task<List<ParseSchema>> getSchemasInBackground(String sessionToken){ ParseRESTCommand command = ParseRESTSchemaCommand.getParseSchemasCommand(sessionToken); return command.executeAsync(restClient, null).onSuccess(new Continuation<JSONObject, List<ParseSchema>>() { @Override public List<ParseSchema> then(Task<JSONObject> task) throws Exception { JSONObject json = task.getResult(); JSONArray arr = json.getJSONArray("results"); List<ParseSchema> schemas = new ArrayList<>(); for (int i=0; i<arr.length(); i++){ ParseSchema schema = new ParseSchema(arr.getJSONObject(i)); schemas.add(schema); } return schemas; } }); } }
true
0b3cd0194f41b21661bb95295e9cd565ccb66719
Java
percussion/percussioncms
/system/src/main/java/com/percussion/install/RxAppConverter.java
UTF-8
20,053
1.828125
2
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0", "OFL-1.1", "LGPL-2.0-or-later" ]
permissive
/* * Copyright 1999-2023 Percussion Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package com.percussion.install; import com.percussion.util.PSCharSets; import com.percussion.utils.xml.PSEntityResolver; import com.percussion.xml.PSXmlDocumentBuilder; import com.percussion.xml.PSXmlTreeWalker; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Properties; import java.util.StringTokenizer; /** * * This is a simple utility class that converts existing Rhythmyx applications * to point to a new backend database. It searches and replaces for driver, * server, database and origin fields in the applications with those specified * in the properties file. Please note that this is usefull only if all the * resources use the same backend database source. * */ public class RxAppConverter { /** * Empty constructor */ public RxAppConverter() { } /** * The only static method that actually converts the application. * * @param props - JAVA Properties file that has all the new field values. * * @param root - The Rhythmyx root directory name. e.g. c:/Rhythmyx * * @param appName - The Rhythmyx application name. e.g. WFEditor in * (ObjectStore/WFEditor.xml). * * @param bModifyCredential <code>true</code> if credentials need to be * modified false otherwise. * * @param sPort new port number for existing workflow applications, can be * <code>null</code> * * @throws IOException - if file is invalid or inaccessible * * @throws SAXException - if the application file is not parseable XML * document * */ static public void updateRxApp(Properties props, String root, String appName, boolean bModifyCredential, String sPort) throws IOException, SAXException { updateRxApp(props, root, appName, bModifyCredential, sPort, false, false); } /** * The only static method that actually converts the application. * * @param props - JAVA Properties file that has all the new field values. * * @param root - The Rhythmyx root directory name. e.g. c:/Rhythmyx * * @param appName - The Rhythmyx application name. e.g. WFEditor in * (ObjectStore/WFEditor.xml). * * @param bModifyCredential <code>true</code> if credentials need to be * modified false otherwise. * * @param sPort new port number for existing workflow applications, can be * <code>null</code> * * @param bEnable <code>true</code> if the app should be activated. * * @param bUpdateNativeStatement - <code>true</code>if the native statement * should be converted. * * @throws IOException - if file is invalid or inaccessible * * @throws SAXException - if the application file is not parseable XML * document * */ static public void updateRxApp(Properties props, String root, String appName, boolean bModifyCredential, String sPort, boolean bEnable, boolean bUpdateNativeStatement) throws IOException, SAXException { String fileName = root + File.separator + "ObjectStore" + File.separator + appName + ".xml"; updateRxApp(props, root, fileName, bModifyCredential, sPort, bEnable, true, null, bUpdateNativeStatement); } /** * The only static method that actually converts the application. * * @param props - JAVA Properties file that has all the new field values. * * @param root - The Rhythmyx root directory name. e.g. c:/Rhythmyx * * @param appName - The Rhythmyx application name. e.g. WFEditor in * (ObjectStore/WFEditor.xml). * * @param bModifyCredential <code>true</code> if credentials need to be * modified false otherwise. * * @param sPort new port number for existing workflow applications, can be * <code>null</code> * * @param bEnable <code>true</code> if the app should be activated. * * @param bAppConv <code>true</code> if the app should be converted * * @param strUpdateSecProv the security provider to update. * * @param bUpdateNativeStatement - <code>true</code>if the native statement * should be converted. * * @throws IOException - if file is invalid or inaccessible * * @throws SAXException - if the application file is not parseable XML * document * */ static public void updateRxApp(Properties props, String root, String fileName, boolean bModifyCredential, String sPort, boolean bEnable, boolean bAppConv, String strUpdateSecProv, boolean bUpdateNativeStatement) throws IOException, SAXException { DocumentBuilder db = PSXmlDocumentBuilder.getDocumentBuilder(false); Document doc = null; NodeList nl = null; Element elem = null; Text text = null; String driver = props.getProperty(DB_DRIVER_NAME, ""); String server = props.getProperty(DB_SERVER, ""); String schema = props.getProperty(DB_SCHEMA, ""); String database = props.getProperty(DB_NAME, ""); String uid = props.getProperty(DB_UID, ""); String pwd = props.getProperty(DB_PWD, ""); String backend = props.getProperty(DB_BACKEND, ""); File f = new File(fileName); if (f.exists()) { doc = db.parse(f); } else { return; } //enable if specified if(bEnable) { Element elemRoot = doc.getDocumentElement(); if(elemRoot != null) { elemRoot.setAttribute("enabled", "yes"); } } if(bAppConv) { nl = doc.getElementsByTagName(DRIVER); setChildNode(doc, nl, driver); nl = doc.getElementsByTagName(SERVER); setChildNode(doc, nl, server); nl = doc.getElementsByTagName(ORIGIN); setChildNode(doc, nl, schema); nl = doc.getElementsByTagName(DATABASE); setChildNode(doc, nl, database); } //modify credentials if asked if(bModifyCredential) { nl = doc.getElementsByTagName("PSXTableLocator"); if(null != nl && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { elem = (Element)nl.item(i); setElementData(elem, "Database", database); setElementData(elem, "Origin", schema); } } nl = doc.getElementsByTagName("PSXBackEndCredential"); if(null != nl && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { elem = (Element)nl.item(i); setElementData(elem, DRIVER, driver); setElementData(elem, SERVER, server); setElementData(elem, USERID, uid); //set the attribute "encrypted" to "yes" Element pwdElem = setElementData(elem, PASSWORD, pwd); pwdElem.setAttribute(ATTRIB_ENCRYPTED, "yes"); } } } //update specified security provider if(strUpdateSecProv != null && strUpdateSecProv.length() > 0) { nl = doc.getElementsByTagName("PSXSecurityProviderInstance"); if(null != nl && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { elem = (Element)nl.item(i); //System.out.println("found security provider..."); //match the name NodeList childs = elem.getElementsByTagName("name"); if(childs != null && childs.getLength() > 0) { //System.out.println("getting name..."); Element childElem = (Element)childs.item(0); Node child = childElem.getFirstChild(); if(null != child && Node.TEXT_NODE == child.getNodeType()) { String data = (String)((Text)child).getData(); //System.out.println("name is... " + data); if(data != null && data.equals(strUpdateSecProv)) { nl = elem.getElementsByTagName("Properties"); if(null != nl && nl.getLength() > 0) { //System.out.println("found properties..."); elem = (Element)nl.item(0); setElementData(elem, "driverName", driver); setElementData(elem, "loginId", uid); setElementData(elem, "databaseName", database); setElementData(elem, "serverName", server); setElementData(elem, "schemaName", schema); //assumes the attribute "encrypted" is always set to "yes" //and is already encrypted setElementData(elem, "loginPw", pwd); //System.out.println("setting password: " + pwd); } break; } } } } } } //modify the port numbers if required //This is temporary fix till MakeLink is modfied - Ram //This can only search an replace and cannot insert if there is port specified!!! modifyPort(sPort, doc); if(bUpdateNativeStatement) { String nativeStatement = NATIVE_STATEMENT_MSSQL; if(backend.equalsIgnoreCase("ORACLE")) nativeStatement = NATIVE_STATEMENT_ORACLE; nl = doc.getElementsByTagName("nativeStatement"); if(null!=nl) { elem = (Element)nl.item(0); text = (Text)elem.getFirstChild(); if(null == text) { text = doc.createTextNode(nativeStatement); elem.appendChild(text); } else text.setData(nativeStatement); } } Writer writer = null; try { PSXmlTreeWalker walker = new PSXmlTreeWalker(doc); walker.setConvertXmlEntities(true); FileOutputStream os = new FileOutputStream(fileName); writer = new OutputStreamWriter(os, PSCharSets.rxJavaEnc()); walker.write(writer); } finally { try { if (writer != null) writer.close(); } catch (Exception e) { } } } public static void setChildNode(Document doc, NodeList nl, String server) { Element elem; Text text; if(null!=nl && null != server) { for(int j=0; j<nl.getLength(); j++) { elem = (Element)nl.item(j); text = (Text)elem.getFirstChild(); if(null == text) { text = doc.createTextNode(server); elem.appendChild(text); } else text.setData(server); } } } public static void modifyPort(String sPort, Document doc) { NodeList nl; Element elem; if(null != sPort) //ignore if port is null { String searchPort = null; String replacePort = ""; //if port is 80 then empty it; if(!sPort.equals("80")) replacePort = new String(":" + sPort); nl = doc.getElementsByTagName("text"); String url = null; String left = null; String right= null; Node node = null; int loc = -1; int locEnd = -1; for(int i=0; (null != nl) && i<nl.getLength(); i++) { elem = (Element)nl.item(i); node = elem.getFirstChild(); if(null == node || !(node instanceof Text)) continue; url = ((Text)node).getData(); if(!url.startsWith("http")) continue; loc = url.indexOf(':', 7); //skip the one after http or https if(loc < 1) continue; locEnd = url.indexOf('/', loc); if(locEnd < loc) continue; searchPort = url.substring(loc, locEnd); left = url.substring(0, loc); right = url.substring(loc+searchPort.length()); left = url.substring(0, loc); right = url.substring(loc+searchPort.length()); ((Text)node).setData(left+replacePort+right); } } } private static Element setElementData(Element parent, String elemName, String elemValue) { NodeList childs = parent.getElementsByTagName(elemName); if(null == childs || childs.getLength() < 1) return null; Element elem = (Element)childs.item(0); Node child = elem.getFirstChild(); if(null != child && Node.TEXT_NODE == child.getNodeType()) { ((Text)child).setData(elemValue); } else { Text text = parent.getOwnerDocument().createTextNode(elemValue); elem.appendChild(text); } return elem; } /** * The DB_DRIVER_NAME field name in the properties file. * The syntax should be like - [DB_DRIVER_NAME=oracle:thin] */ static public String DB_DRIVER_NAME = "DB_DRIVER_NAME"; /** * The DB_SERVER field name in the properties file. * The syntax should be like - [DB_SERVER=@38.222.12.13:1521:ORCL] */ static public String DB_SERVER = "DB_SERVER"; /** * The DB_SCHEMA name in the properties file. * The syntax should be like - [DB_SCHEMA=dbo] */ static public String DB_SCHEMA = "DB_SCHEMA"; /** * The DB_NAME name in the properties file. * The syntax should be like - [DB_NAME=RxWorkflow] */ static public String DB_NAME = "DB_NAME"; /** * The UID name in the properties file. * The syntax should be like - [UID=username] */ static public String DB_UID = "UID"; /** * The PWD name in the properties file. * The syntax should be like - [PWD=password] */ static public String DB_PWD = "PWD"; /** * The BACKEND name in the properties file. */ static public String DB_BACKEND = "DB_BACKEND"; /** * The "driver" field name in the application XML Document. This field value * will be replaced with DB_DRIVER_NAME field value in the properties file. * */ static public String DRIVER = "driver"; /** * The "server" field name in the application XML Document. This field value * will be replaced with DB_SERVER field value in the properties file. * */ static public String SERVER = "server"; /** * The "origin" field name in the application XML Document. This field value * will be replaced with DB_SCHEMA field value in the properties file. * */ static public String ORIGIN = "origin"; /** * The "database" field name in the application XML Document. This field value * will be replaced with DB_NAME field value in the properties file. * */ static public String DATABASE = "database"; /** * The "userId" field name in the application XML Document. This field value * will be replaced with UID field value in the properties file. * */ static public String USERID = "userId"; /** * The "password" field name in the application XML Document. This field value * will be replaced with PWD field value in the properties file. * */ static public String PASSWORD = "password"; /** * The "encrypted" attribute in the application XML Document. * */ static public String ATTRIB_ENCRYPTED = "encrypted"; /** * Native statement required in the application for ORACLE. */ static public String NATIVE_STATEMENT_ORACLE = "SELECT DISTINCT * FROM WORKFLOWAPPS, STATES, TRANSITIONS WHERE "+ "WORKFLOWAPPS.WORKFLOWAPPID=STATES.WORKFLOWAPPID AND (STATES.STATEID="+ "TRANSITIONS.TRANSITIONFROMSTATEID(+) AND STATES.WORKFLOWAPPID="+ "TRANSITIONS.WORKFLOWAPPID (+)) AND WORKFLOWAPPS.WORKFLOWAPPID= "+ ":\"PSXParam/workflowid\""; /** * Native statement required in the application for MSSQL or MSACCESS. */ static public String NATIVE_STATEMENT_MSSQL = "SELECT WORKFLOWAPPS.*, STATES.*, TRANSITIONS.* FROM WORKFLOWAPPS "+ "INNER JOIN ( STATES LEFT OUTER JOIN TRANSITIONS ON TRANSITIONS."+ "TRANSITIONFROMSTATEID=STATES.STATEID AND TRANSITIONS.WORKFLOWAPPID="+ "STATES.WORKFLOWAPPID ) ON WORKFLOWAPPS.WORKFLOWAPPID="+ "STATES.WORKFLOWAPPID WHERE WORKFLOWAPPS.WORKFLOWAPPID= "+ ":\"PSXParam/workflowid\""; /** * The main method. This takes two command line parameters. The first one is * the Properties file name (absolute path). Second one is the comma separated * list of Rhythmyx application names (without any path specification and * extension) to be converted. * */ public static void main(String[] args) { if(args.length < 3) { System.out.println("Usage: "); System.out.println(" RxAppConverter <Properties file name> "+ "<Rhythmyx RootDir> <Application list (comma separated)> [port]"); System.out.println("Press ENTER to continue..."); try {System.in.read();}catch(Exception e){} System.exit(1); } Properties props = new Properties(); loadProps(args, props); File rxRoot = new File(args[1]); if (rxRoot.isDirectory()) PSEntityResolver.getInstance().setResolutionHome(rxRoot); StringTokenizer tokenizer = new StringTokenizer(args[2], ","); RxAppConverter appConverter = new RxAppConverter(); String temp = null; String port = null; if(args.length > 3) port = args[3]; while(tokenizer.hasMoreElements()) { temp = tokenizer.nextElement().toString(); if(null == temp) continue; temp = temp.trim(); try { RxAppConverter.updateRxApp(props, args[1], temp, true, port); } catch(Exception e) { System.out.println("Failed to covert application '" + temp + "' Error: " + e.getMessage()); } } System.exit(1); } public static void loadProps(String[] args, Properties props) { try { props.load(new FileInputStream(args[0])); } catch(IOException ioe) { System.out.println("Failed to load properties file '" + args[0] + "' Error: " + ioe.getMessage()); System.out.println("Press ENTER to continue..."); try {System.in.read();}catch(Exception e){} System.exit(1); } } }
true
f8876044b4a720ada1d3d8845041ebed12bdaf53
Java
AbsoluteChad/Skystone2020
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/subsystems/DriveTrain.java
UTF-8
10,177
2.765625
3
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode.subsystems; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.PIDCoefficients; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.RobotMain; import org.firstinspires.ftc.teamcode.libs.drive.PIDController; public class DriveTrain extends Subsystem { //Declare private instance private static final Subsystem instance = new DriveTrain(); //Declare motors public DcMotor topLeft; public DcMotor bottomLeft; public DcMotor topRight; public DcMotor bottomRight; //Declare constants private static final double VIDIPT_DRIVE_CONTROL = 1; private static final double WHEEL_CIRCUMFERENCE = 4 * Math.PI; private static final int TICKS_PER_ROTATION = 1120; //change to 1440 for torquenado motor private static final double GEAR_RATIO = 1; private static final double ENCODER_TOLERANCE = 20; //Declare PID members private PIDCoefficients PIDcoeffs; private PIDController PIDController; //Misc private ElapsedTime timer; //Private constructor private DriveTrain() { //Init misc timer = new ElapsedTime(); } @Override public void subsystemInit(HardwareMap hardwareMap) { //Init motors topLeft = hardwareMap.get(DcMotor.class, "topLeft"); bottomLeft = hardwareMap.get(DcMotor.class, "bottomLeft"); topRight = hardwareMap.get(DcMotor.class, "topRight"); bottomRight = hardwareMap.get(DcMotor.class, "bottomRight"); //Set motors to break topLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); bottomLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); topRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); bottomRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); //Reverse left side motors topLeft.setDirection(DcMotorSimple.Direction.REVERSE); bottomLeft.setDirection(DcMotorSimple.Direction.REVERSE); //Enable & reset encoders setEncoderMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); setEncoderMode(DcMotor.RunMode.RUN_USING_ENCODER); //Init PID members PIDcoeffs = new PIDCoefficients(0, 0, 0); DcMotor[] motors = {topLeft, bottomLeft, topRight, bottomRight}; PIDController = new PIDController(motors, PIDcoeffs, 6); } @Override public void teleopTick() { double thrust = -RobotMain.gamepad1.left_stick_y; double strafe = RobotMain.gamepad1.left_stick_x; double turn = RobotMain.gamepad1.right_stick_x; driveMecanum(thrust, strafe, turn, false); } /** * Basic tank drive that controls left wheels and right wheels independently * * @param leftPower power applied to left wheels * @param rightPower power applied to right wheels */ public void driveTank(double leftPower, double rightPower) { topLeft.setPower(leftPower * VIDIPT_DRIVE_CONTROL); bottomLeft.setPower(leftPower * VIDIPT_DRIVE_CONTROL); topRight.setPower(rightPower * VIDIPT_DRIVE_CONTROL); bottomRight.setPower(rightPower * VIDIPT_DRIVE_CONTROL); } /** * Determines mecanum wheel powers with given components. Feed in joystick values to drive in * desired direction. * * @param thrust y component of requested vector * @param strafe x component of requested vector * @param turn turn component (z axis) of robot while traveling along requested vector * @param fieldCentric whether robot should move relative to field or drivers * (true = relative to field; false = relative to drivers) */ public void driveMecanum(double thrust, double strafe, double turn, boolean fieldCentric) { //If field centric -- does nothing yet if (fieldCentric) { thrust = thrust; strafe = strafe; } //Determining wheel powers double topLeftPower = thrust + strafe + turn; double bottomLeftPower = thrust - strafe + turn; double topRightPower = thrust - strafe - turn; double bottomRightPower = thrust + strafe - turn; //Scale based off max power double maxPower = Math.max(Math.max(Math.max(topLeftPower, bottomLeftPower), topRightPower), bottomRightPower); if (Math.abs(maxPower) > 1.0) { topLeftPower /= Math.abs(maxPower); bottomLeftPower /= Math.abs(maxPower); topRightPower /= Math.abs(maxPower); bottomRightPower /= Math.abs(maxPower); } //Vidipt control topLeftPower *= VIDIPT_DRIVE_CONTROL; bottomLeftPower *= VIDIPT_DRIVE_CONTROL; topRightPower *= VIDIPT_DRIVE_CONTROL; bottomRightPower *= VIDIPT_DRIVE_CONTROL; //Set powers topLeft.setPower(topLeftPower); bottomLeft.setPower(bottomLeftPower); topRight.setPower(topRightPower); bottomRight.setPower(bottomRightPower); } /** * Drives a certain distance in a forward/backward/left/right direction using encoders * * @param power power applied to all motors * @param inches distance traveled by each wheel of drivetrain * @param degreeDirection direction requested to travel by robot * 0, 90, 180, and 270 will travel distance; * any other angle will not do anything. * @param PID whether or not to use PID */ public void driveDistance(double power, int inches, double degreeDirection, boolean PID) { //Only F, B, L, and R directions if (degreeDirection % 90 != 0) { return; } //Determine component values double thrust = Math.sin(Math.toRadians(degreeDirection)) * power; double strafe = Math.cos(Math.toRadians(degreeDirection)) * power; //Ready encoders & set target positions (TLBR = topLeft & bottomRight motors; BLTR = bottomLeft & topRight motors) int setPoint = toTicks(inches); setEncoderMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); int TLBRSetpt = thrust + strafe > 0 ? setPoint : -setPoint; int BLTRSetpt = thrust - strafe > 0 ? setPoint : -setPoint; boolean[] motorDirections = new boolean[4]; if (TLBRSetpt < 0) { motorDirections[0] = true; motorDirections[3] = true; } if (BLTRSetpt < 0) { motorDirections[1] = true; motorDirections[2] = true; } topLeft.setTargetPosition(TLBRSetpt); bottomLeft.setTargetPosition(BLTRSetpt); topRight.setTargetPosition(BLTRSetpt); bottomRight.setTargetPosition(TLBRSetpt); setEncoderMode(DcMotor.RunMode.RUN_TO_POSITION); if (PID) { PIDController.drive(setPoint, ENCODER_TOLERANCE, motorDirections); } else { driveMecanum(thrust, strafe, 0, false); while (topLeft.isBusy() || bottomLeft.isBusy() || topRight.isBusy() || bottomRight.isBusy()) { //yeet } driveTank(0, 0); } setEncoderMode(DcMotor.RunMode.RUN_USING_ENCODER); } /** * Used to drive in a certain direction (not F, B, L, or R -- use driveDistance() w/ dist instead of time) * for a certain amount of time * * @param power fraction of max power to drive with * @param degreeDirection unit circle direction requested to travel * @param milliseconds amount of time to travel for in milliseconds */ public void driveMecanum(double power, double degreeDirection, double milliseconds) { //Calculate component values double thrust = Math.sin(Math.toRadians(degreeDirection)) * power; double strafe = Math.cos(Math.toRadians(degreeDirection)) * power; //Start timer timer.reset(); while (timer.milliseconds() < milliseconds) { driveMecanum(thrust, strafe, 0, false); } driveTank(0, 0); } /** * Used to rotate a certain number of degrees about unit circle using encoders * * @param power the power at which to travel * @param degrees degree amount to turn * negative value = clockwise * positive value = counterclockwise */ public void rotateDegrees(double power, double degrees) { int setPoint = (int) ((degrees / 360) * TICKS_PER_ROTATION); if (Math.abs(setPoint) < ENCODER_TOLERANCE) { return; } setEncoderMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); topLeft.setTargetPosition(-setPoint); bottomLeft.setTargetPosition(-setPoint); topRight.setTargetPosition(setPoint); bottomRight.setTargetPosition(setPoint); setEncoderMode(DcMotor.RunMode.RUN_TO_POSITION); if (setPoint < 0) { driveTank(power, -power); } else if (setPoint > 0) { driveTank(-power, power); } while (topLeft.isBusy() || bottomLeft.isBusy() || topRight.isBusy() || bottomRight.isBusy()) { //Yeet } driveTank(0, 0); setEncoderMode(DcMotor.RunMode.RUN_USING_ENCODER); } /** * Used to set mode of all drive encoders * * @param mode mode for encoders to be set to */ public void setEncoderMode(DcMotor.RunMode mode) { topLeft.setMode(mode); bottomLeft.setMode(mode); topRight.setMode(mode); bottomRight.setMode(mode); } /** * @param inches distance in inches * @return <i>inches</i> converted to encoder ticks */ public int toTicks(double inches) { double rotations = inches / WHEEL_CIRCUMFERENCE; return (int) (rotations * TICKS_PER_ROTATION / GEAR_RATIO); } /** * @return the singleton instance of the subsystem */ public static Subsystem getInstance() { return instance; } }
true
f6fdad52245982f38d538c977dc9f2e8b975fbae
Java
helloV7/cxd_kehuduan
/app/src/main/java/com/cxd/khd/adapter/SKOrderListAdapter.java
UTF-8
708
2.140625
2
[]
no_license
package com.cxd.khd.adapter; import android.view.ViewGroup; import com.cxd.khd.view.viewholder.BaseViewHolder; import com.cxd.khd.view.viewholder.SKOrderListItemViewHolder; /** * Created by chenweiqi on 2017/6/19. */ public class SKOrderListAdapter extends BaseRcvAdapter { @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { SKOrderListItemViewHolder holder = new SKOrderListItemViewHolder(parent); holder.setOnViewHolderClickListener(onViewHolderClickListener); return holder; } @Override public void onBindViewHolder(BaseViewHolder holder, int position) { holder.setData(dataList.get(position),position); } }
true
cfdc6342cea999947de8db681da4ad21f6799913
Java
windcaller31/algorithm_practise
/src/main/java/leetcode/leetcode121.java
UTF-8
718
4.03125
4
[]
no_license
package leetcode; public class leetcode121 { public static void main(String args[]) { int[] prices = {7,1,5,3,6,4}; System.out.print(maxProfit(prices)); } //模拟每天买第二天卖掉,则会发现相隔n天的收益值等于每天的差值累加: // 1 2 4 3 对应第二天卖掉第一天股票:0 1 2 -1 则 1 3 这相隔的两天正好是 0+1+2-1=2 public static int maxProfit(int[] prices) { int max = 0; int profit = 0; for(int i=1;i<prices.length;i++) { int s = profit+prices[i]-prices[i-1]; //买入天到这天的收益 profit=Math.max(0,s); //如果已经赔本,则从新买入 max = Math.max(max, profit); //计算这整个数组中区间最大的 } return max; } }
true
998b9ecd783350046bdaafa833f2cb5a264d3d2e
Java
AlexandraAncuta13/Tema1POO
/src/main/SortFavoriteShows.java
UTF-8
408
2.53125
3
[]
no_license
package main; import fileio.SerialInputData; import java.util.Comparator; public class SortFavoriteShows implements Comparator<SerialInputData> { /** * Sortez serialele dupa numarul de aparitii in listele de favorite */ public final int compare(final SerialInputData serial1, final SerialInputData serial2) { return serial1.getNrFavorites() - serial2.getNrFavorites(); } }
true
4bbb67e5f531b873baac0751711808e66aa45ecf
Java
jjljjl/pets-town
/src/main/java/pet/dao/AdminMapper.java
UTF-8
524
1.84375
2
[]
no_license
package pet.dao; import org.apache.ibatis.annotations.Param; import pet.model.Admin; import java.util.List; public interface AdminMapper { int deleteByPrimaryKey(Integer id); int insert(Admin record); int insertSelective(Admin record); List<Admin> selectAdminByName(@Param("adminName") String adminName); int updateByPrimaryKeySelective(Admin record); int updateByPrimaryKey(Admin record); Admin selectByNameAnPwd(@Param("adminName") String adminName,@Param("adminPwd") String adminPwd); }
true
bde541d916a6fcb2cc582051e2748da32460f938
Java
Veeresh8/Hooked
/app/src/main/java/veer/com/hooked/database/Collaborators.java
UTF-8
2,557
2.375
2
[]
no_license
package veer.com.hooked.database; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; @Entity public class Collaborators { @PrimaryKey(autoGenerate = true) private int id; private String UID; private String author; private String date; private String message; private long timestamp; private int wordCount; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUID() { return UID; } public void setUID(String UID) { this.UID = UID; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Collaborators that = (Collaborators) o; if (id != that.id) return false; if (timestamp != that.timestamp) return false; if (wordCount != that.wordCount) return false; if (UID != null ? !UID.equals(that.UID) : that.UID != null) return false; if (author != null ? !author.equals(that.author) : that.author != null) return false; if (date != null ? !date.equals(that.date) : that.date != null) return false; return message != null ? message.equals(that.message) : that.message == null; } @Override public int hashCode() { int result = id; result = 31 * result + (UID != null ? UID.hashCode() : 0); result = 31 * result + (author != null ? author.hashCode() : 0); result = 31 * result + (date != null ? date.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); result = 31 * result + wordCount; return result; } }
true
537a2080b570c7e73fbe8534b2721c8f9f669d9a
Java
kkoshman/Labs
/OrderHandling/test/bsu/orderhandling/test/OrderHandlingTest.java
UTF-8
2,419
2.484375
2
[]
no_license
package bsu.orderhandling.test; import static org.junit.Assert.*; import java.util.HashMap; import org.junit.Test; import bsu.orderhandling.command.Command; import bsu.orderhandling.command.order.AddProductCommand; import bsu.orderhandling.command.ICommandState; import bsu.orderhandling.command.UserMessage; import bsu.orderhandling.command.UserMessageType; import bsu.orderhandling.order.Order; import bsu.orderhandling.request.Request; import bsu.orderhandling.request.RequestHandler; public class OrderHandlingTest { @Test public void test() { Order order = new Order(); RequestHandler handler = RequestHandler.getInstance(); UserMessage message = null; Request request = new Request(); request.action = RequestHandler.ADD_PRODUCT; request.params = new HashMap<String, Object>(); request.params.put(Request.ORDER, order); message = handler.handleRequest(request); System.out.println(message); assertTrue(order.getProductQuantity() == 1); request = new Request(); request.action = RequestHandler.REMOVE_PRODUCT; request.params = new HashMap<String, Object>(); request.params.put(Request.ORDER, order); message = handler.handleRequest(request); System.out.println(message); assertTrue(order.getProductQuantity() == 0); request = new Request(); request.action = RequestHandler.REMOVE_PRODUCT; request.params = new HashMap<String, Object>(); request.params.put(Request.ORDER, order); message = handler.handleRequest(request); System.out.println(message); assertTrue(message.getType() == UserMessageType.ERROR); assertTrue(order.getProductQuantity() == 0); request = new Request(); request.action = RequestHandler.REVERT_LAST_COMMAND; request.params = new HashMap<String, Object>(); message = handler.handleRequest(request); System.out.println(message); assertTrue(message.getType() == UserMessageType.SUCCESS); assertTrue(order.getProductQuantity() == 1); } @Test public void testMemento() { Command command = AddProductCommand.getInstance(); ICommandState state = command.returnState(null); // ICommandState interface have no methods // and you have not access to class Command.CommandMemento //state = (Command.CommandMemento)state; //compilation error // then you cannot get or update inner memento data from the outside Command class } }
true
389f61720ec0c6e6c6bfa710bc54956d453557f9
Java
dotob/ovt-java
/tools/Mailer.java
UTF-8
8,121
2.25
2
[]
no_license
package tools; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.nio.charset.Charset; import java.util.Properties; //import org.columba.ristretto.auth.AuthenticationException; //import org.columba.ristretto.auth.AuthenticationFactory; //import org.columba.ristretto.auth.NoSuchAuthenticationException; //import org.columba.ristretto.composer.MimeTreeRenderer; //import org.columba.ristretto.io.CharSequenceSource; //import org.columba.ristretto.message.Address; //import org.columba.ristretto.message.BasicHeader; //import org.columba.ristretto.message.Header; //import org.columba.ristretto.message.LocalMimePart; //import org.columba.ristretto.message.MimeHeader; //import org.columba.ristretto.message.MimeType; //import org.columba.ristretto.parser.AddressParser; //import org.columba.ristretto.parser.ParserException; //import org.columba.ristretto.smtp.SMTPException; //import org.columba.ristretto.smtp.SMTPProtocol; import java.util.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class Mailer { private static String smtpserver = SettingsReader.getString("MailSettings.smtpserver"); private static String smtpuser = SettingsReader.getString("MailSettings.smtpuser"); private static String smtppass = SettingsReader.getString("MailSettings.smtppasswort"); private static String fromaddress = SettingsReader.getString("MailSettings.fromaddress"); public static void mailTo(String toaddress, String msgTxt, String attachTxt){ // // Parse and check the given to- and from-address // Address fromAddress; // try { // fromAddress = AddressParser.parseAddress(fromaddress); // } catch (ParserException e) { // System.err.println("Invalid from-address : " + e.getSource()); // return; // } // // Address toAddress; // try { // toAddress = AddressParser.parseAddress(toaddress); // } catch (ParserException e) { // System.err.println("Invalid to-address : " + e.getSource()); // return; // } // // String subject = "MaFo-Manager is mailing!!"; // // // PART 1 : Composing a message // // // Header is the actual header while BasicHeader wraps // // a Header object to give easy access to the Header. // Header header = new Header(); // BasicHeader basicHeader = new BasicHeader(header); // // // Add the fields to the header // // Note that the basicHeader is only a convienience wrapper // // for our header object. // basicHeader.setFrom(fromAddress); // basicHeader.setTo(new Address[] { toAddress }); // basicHeader.setSubject(subject, Charset.forName("ISO-8859-1")); // basicHeader.set("X-Mailer", "OVT MaFo-Manager / Ristretto API"); // // // Now a mimepart is prepared which actually holds the message // // The mimeHeader is another convienice wrapper for the header // // object // MimeHeader mimeHeader = new MimeHeader(header); // mimeHeader.set("Mime-Version", "1.0"); // LocalMimePart root = new LocalMimePart(mimeHeader); // // LocalMimePart textPart; // // // We have an attachment we must compose a multipart message // mimeHeader.setMimeType(new MimeType("multipart", "mixed")); // // textPart = new LocalMimePart(new MimeHeader()); // root.addChild(textPart); // // // Now we can add some message text // MimeHeader textHeader = textPart.getHeader(); // textHeader.setMimeType(new MimeType("text", "plain")); // root.setBody(new CharSequenceSource(msgTxt)); // // // Now we compose the attachment // MimeHeader attachmentHeader = new MimeHeader("application", "octet-stream"); // attachmentHeader.setContentTransferEncoding("base64"); //// attachmentHeader.putDispositionParameter("filename", "mafodata.xml"); // LocalMimePart attachmentPart = new LocalMimePart(attachmentHeader); // attachmentPart.setBody(new CharSequenceSource(attachTxt)); // root.addChild(attachmentPart); // // InputStream messageSource; // try { // // Finally we render the message to an inputstream // messageSource = MimeTreeRenderer.getInstance().renderMimePart( root ); // } catch (Exception e2) { // System.err.println(e2.getLocalizedMessage()); // return; // } // // // Part 2 : Sending the message // // // Construct the protocol that is bound to the SMTP server // System.out.println(smtpserver+" : "+smtpuser+" : "+smtppass+" : "+fromaddress); // SMTPProtocol protocol = new SMTPProtocol(smtpserver); // try { // // Open the port // protocol.openPort(); // // // The EHLO command gives us the capabilities of the server // String capabilities[] = protocol.ehlo(InetAddress.getLocalHost()); // // // Authenticate // if(smtpuser != null ) { // String authCapability = null; // for( int i=0; i<capabilities.length; i++) { //// System.out.println("capabilities: "+capabilities[i]); // if( capabilities[i].startsWith("AUTH")) { // authCapability = capabilities[i]; // break; // } // } // if( authCapability != null ) { // try { // System.out.println(AuthenticationFactory.getInstance().getSecurestMethod( authCapability )+" authCapability: "+authCapability); //// protocol.auth( "PLAIN", smtpuser, smtppass.toCharArray() ); // protocol.auth( AuthenticationFactory.getInstance().getSecurestMethod( authCapability ), smtpuser, smtppass.toCharArray() ); // System.out.println(protocol.authReceive()); // } catch (NoSuchAuthenticationException e3) { // System.err.println("error 1"); // System.err.println(e3.getLocalizedMessage()); // return; // } catch ( AuthenticationException e ) { // System.err.println("error 2"); // System.err.println(e.getMessage()); // System.err.println(e.getStackTrace()); // return; // } // } else { // System.err.println("Server does not support Authentication!"); // return; // } // } // // // Setup from and recipient // protocol.mail(fromAddress); // protocol.rcpt(toAddress); // // // Finally send the data // protocol.data(messageSource); // // // And close the session // protocol.quit(); // // } catch (IOException e1) { // System.err.println("error 3"); // System.err.println(e1.getLocalizedMessage()); // return; // } catch (SMTPException e1) { // System.err.println("error 4"); // System.err.println(e1.getMessage()); // System.err.println(e1.getCode()); // return; // } } // public static void mailToSun(String toaddress, String msgTxt, String attachTxt){ // String to = toaddress; // String from = fromaddress; // String host = smtpserver; // boolean debug = false; // // // create some properties and get the default Session // Properties props = new Properties(); // props.put("mail.smtp.host", host); // // Session session = Session.getInstance(props, null); // session.setDebug(debug); // // try { // // create a message // MimeMessage msg = new MimeMessage(session); // msg.setFrom(new InternetAddress(from)); // InternetAddress[] address = {new InternetAddress(to)}; // msg.setRecipients(Message.RecipientType.TO, address); // msg.setSubject("JavaMail APIs Multipart Test"); // msg.setSentDate(new Date()); // // // create and fill the first message part // MimeBodyPart mbp1 = new MimeBodyPart(); // mbp1.setText(msgText1); // // // create and fill the second message part // MimeBodyPart mbp2 = new MimeBodyPart(); // // Use setText(text, charset), to show it off ! // mbp2.setText(msgText2, "us-ascii"); // // // create the Multipart and its parts to it // Multipart mp = new MimeMultipart(); // mp.addBodyPart(mbp1); // mp.addBodyPart(mbp2); // // // add the Multipart to the message // msg.setContent(mp); // // // send the message // Transport.send(msg); // } catch (MessagingException mex) { // mex.printStackTrace(); // Exception ex = null; // if ((ex = mex.getNextException()) != null) { // ex.printStackTrace(); // } // } // } }
true
0f12485d1da50dfb2c3f316709c3093c48e690c0
Java
bory1309/MyStore
/Copy (2) of store/src/main/java/ua/repository/FirstNameRepository.java
UTF-8
248
1.859375
2
[]
no_license
package ua.repository; import org.springframework.data.jpa.repository.JpaRepository; import ua.entity.FirstName; public interface FirstNameRepository extends JpaRepository<FirstName, Integer>{ FirstName findByName(String name); }
true
0c1753131e782138b62a25e971f221570d50adca
Java
njmube/santanderBatch
/src/com/interfactura/firmalocal/datamodel/CfdiReceptor.java
UTF-8
1,447
1.757813
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.interfactura.firmalocal.datamodel; /** * * @author Maximino Llovera */ public class CfdiReceptor { private String nombre; private String numRegIdTrib; private String residenciaFiscal; private String rfc; private String usoCFDI; private CfdiDomicilio domicilio; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getNumRegIdTrib() { return numRegIdTrib; } public void setNumRegIdTrib(String numRegIdTrib) { this.numRegIdTrib = numRegIdTrib; } public String getResidenciaFiscal() { return residenciaFiscal; } public void setResidenciaFiscal(String residenciaFiscal) { this.residenciaFiscal = residenciaFiscal; } public String getRfc() { return rfc; } public void setRfc(String rfc) { this.rfc = rfc; } public String getUsoCFDI() { return usoCFDI; } public void setUsoCFDI(String usoCFDI) { this.usoCFDI = usoCFDI; } public CfdiDomicilio getDomicilio() { return domicilio; } public void setDomicilio(CfdiDomicilio domicilio) { this.domicilio = domicilio; } }
true
c2c4b9d0fe3d02d56d28832769b02d694138afb9
Java
facebook/buck
/test/com/facebook/buck/versions/VersionMatchedCollectionTest.java
UTF-8
6,537
1.640625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.versions; import static org.junit.Assert.assertThat; import com.facebook.buck.core.cell.CellPathResolver; import com.facebook.buck.core.cell.TestCellBuilder; import com.facebook.buck.core.cell.TestCellPathResolver; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BaseName; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem; import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory; import com.facebook.buck.rules.coercer.VersionMatchedCollection; import com.facebook.buck.util.types.Pair; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Optional; import org.hamcrest.Matchers; import org.junit.Test; public class VersionMatchedCollectionTest { private static final BuildTarget A = BuildTargetFactory.newInstance("//:a"); private static final BuildTarget B = BuildTargetFactory.newInstance("//:b"); private static final Version V1 = Version.of("1.0"); private static final Version V2 = Version.of("2.0"); private static final VersionMatchedCollection<String> COLLECTION = VersionMatchedCollection.<String>builder() .add(ImmutableMap.of(A, V1, B, V1), "a-1.0,b-1.0") .add(ImmutableMap.of(A, V1, B, V2), "a-1.0,b-2.0") .add(ImmutableMap.of(A, V2, B, V1), "a-2.0,b-1.0") .add(ImmutableMap.of(A, V2, B, V2), "a-2.0,b-2.0") .build(); private static final CellPathResolver CELL_PATH_RESOLVER = TestCellPathResolver.get(new FakeProjectFilesystem()); @Test public void testGetMatchingValues() { assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V1)), Matchers.equalTo(ImmutableList.of("a-1.0,b-1.0", "a-1.0,b-2.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V2)), Matchers.equalTo(ImmutableList.of("a-2.0,b-1.0", "a-2.0,b-2.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(B, V1)), Matchers.equalTo(ImmutableList.of("a-1.0,b-1.0", "a-2.0,b-1.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(B, V2)), Matchers.equalTo(ImmutableList.of("a-1.0,b-2.0", "a-2.0,b-2.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V1, B, V1)), Matchers.equalTo(ImmutableList.of("a-1.0,b-1.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V1, B, V2)), Matchers.equalTo(ImmutableList.of("a-1.0,b-2.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V2, B, V1)), Matchers.equalTo(ImmutableList.of("a-2.0,b-1.0"))); assertThat( COLLECTION.getMatchingValues(ImmutableMap.of(A, V2, B, V2)), Matchers.equalTo(ImmutableList.of("a-2.0,b-2.0"))); } @Test public void testGetOnlyMatchingValue() { assertThat( COLLECTION.getOnlyMatchingValue("test", ImmutableMap.of(A, V1, B, V1)), Matchers.equalTo("a-1.0,b-1.0")); } @Test(expected = HumanReadableException.class) public void testGetOnlyMatchingValueThrowsOnTooManyValues() { System.out.println(COLLECTION.getOnlyMatchingValue("test", ImmutableMap.of(A, V1))); } @Test(expected = HumanReadableException.class) public void testGetOnlyMatchingValueThrowsOnNoMatches() { System.out.println( COLLECTION.getOnlyMatchingValue("test", ImmutableMap.of(A, Version.of("3.0")))); } @Test public void translatedTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); BuildTarget newTarget = BuildTargetFactory.newInstance("//something:else"); TargetNodeTranslator translator = new FixedTargetNodeTranslator( new DefaultTypeCoercerFactory(), ImmutableMap.of(target, newTarget), new TestCellBuilder().build()); VersionMatchedCollection<BuildTarget> collection = VersionMatchedCollection.<BuildTarget>builder().add(ImmutableMap.of(), target).build(); assertThat( translator .translate(CELL_PATH_RESOLVER.getCellNameResolver(), BaseName.ROOT, collection) .map(VersionMatchedCollection::getValues), Matchers.equalTo(Optional.of(ImmutableList.of(newTarget)))); } @Test public void translatedTargetsInVersionMapAreNotTranslated() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); BuildTarget newTarget = BuildTargetFactory.newInstance("//something:else"); TargetNodeTranslator translator = new FixedTargetNodeTranslator( new DefaultTypeCoercerFactory(), ImmutableMap.of(target, newTarget), new TestCellBuilder().build()); VersionMatchedCollection<BuildTarget> collection = VersionMatchedCollection.<BuildTarget>builder() .add(ImmutableMap.of(target, V1), target) .build(); assertThat( translator .translate(CELL_PATH_RESOLVER.getCellNameResolver(), BaseName.ROOT, collection) .map(VersionMatchedCollection::getValuePairs), Matchers.equalTo( Optional.of(ImmutableList.of(new Pair<>(ImmutableMap.of(target, V1), newTarget))))); } @Test public void untranslatedTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); TargetNodeTranslator translator = new FixedTargetNodeTranslator( new DefaultTypeCoercerFactory(), ImmutableMap.of(), new TestCellBuilder().build()); VersionMatchedCollection<BuildTarget> collection = VersionMatchedCollection.<BuildTarget>builder().add(ImmutableMap.of(), target).build(); assertThat( translator.translate(CELL_PATH_RESOLVER.getCellNameResolver(), BaseName.ROOT, collection), Matchers.equalTo(Optional.empty())); } }
true
15712d64dab8ab7f0452f331dd9c7aef5f2c1d3a
Java
kamontat/Converter
/src/main/java/com/kamontat/example/ConvM2H.java
UTF-8
1,056
2.65625
3
[ "MIT" ]
permissive
package com.kamontat.example; import com.kamontat.convert.Converter; import com.kamontat.convert.Result; import com.kamontat.constance.Protocol; import com.kamontat.utilities.FilesUtil; import com.kamontat.utilities.URLManager; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * HTML to Markdown * * @author kamontat * @version 1.0 * @since Tue 14/Mar/2017 - 12:30 PM */ public class ConvM2H { private static Converter c = Converter.by(Converter.Type.MD2HTML); public static void main(String[] args) throws IOException { // file File f = FilesUtil.getFileFromRoot("src", "resource", "test_file.md"); // url URL url = URLManager.getUrl(Protocol.HTTPS, "raw.githubusercontent.com/kamontat/CheckIDNumber/master/Readme.md").getUrl(); // string String md = "Error `Exception...` will appear when you **don't** install *JRE*"; String s = c.convert(f).toString(); InputStream stream = c.convert(url).toInputStream(); Result r = c.convert(md); System.out.println(s); } }
true
a872251df50fff99e4852c0baa984dac2bc3d57c
Java
tim-deh/lms
/test/com/ss/training/publisher/PublisherTest.java
UTF-8
808
2.578125
3
[]
no_license
/** * */ package com.ss.training.publisher; import static org.junit.Assert.*; import com.ss.training.publisher.Publisher; import org.junit.Test; /** * @author nrdxp * */ public class PublisherTest { Publisher pub = new Publisher("penguin", "1243 Angst Ave"); Publisher pub2 = new Publisher("Random House", "1243 Boulder Ave"); Publisher pub3 = new Publisher("penguin", "1243 Angst Ave"); @Test public void uniqueId() { assertNotEquals(pub.getId(), pub2.getId()); } @Test public void testEquals() { assertEquals(pub, pub); assertEquals(pub, pub3); assertNotEquals(pub, pub2); assertNotEquals(pub, "foobar"); assertNotEquals(pub, null); } @Test public void testGetters() { assertEquals(pub.getName(), "penguin"); assertEquals(pub.getAddress(), "1243 Angst Ave"); } }
true
5dff7ca6232dff40635baf66be75552f87be04b2
Java
AzuraGroup/hevelian-olastic
/olastic-core/src/main/java/com/hevelian/olastic/core/utils/ApplyOptionUtils.java
UTF-8
2,931
2.546875
3
[ "Apache-2.0" ]
permissive
package com.hevelian.olastic.core.utils; import org.apache.olingo.server.api.uri.queryoption.ApplyItem; import org.apache.olingo.server.api.uri.queryoption.ApplyOption; import org.apache.olingo.server.api.uri.queryoption.apply.Aggregate; import org.apache.olingo.server.api.uri.queryoption.apply.Filter; import org.apache.olingo.server.api.uri.queryoption.apply.GroupBy; import org.apache.olingo.server.api.uri.queryoption.apply.Search; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * Utility class with methods to work with {@link ApplyOption} system query. * * @author rdidyk */ public final class ApplyOptionUtils { private ApplyOptionUtils() { } /** * Get's {@link Search} list from {@link ApplyOption} option. * * @param applyOption * apply option * @return item list */ public static List<Search> getSearchItems(ApplyOption applyOption) { return getItems(applyOption, e -> e.getKind() == ApplyItem.Kind.SEARCH, Search.class); } /** * Get's {@link Filter} list from {@link ApplyOption} option. * * @param applyOption * apply option * @return item list */ public static List<Filter> getFilters(ApplyOption applyOption) { return getItems(applyOption, e -> e.getKind() == ApplyItem.Kind.FILTER, Filter.class); } /** * Get's {@link Aggregate} list from {@link ApplyOption} option. * * @param applyOption * apply option * @return item list */ public static List<Aggregate> getAggregations(ApplyOption applyOption) { return getItems(applyOption, e -> e.getKind() == ApplyItem.Kind.AGGREGATE, Aggregate.class); } /** * Get's {@link GroupBy} list from {@link ApplyOption} option. * * @param applyOption * apply option * @return item list */ public static List<GroupBy> getGroupByItems(ApplyOption applyOption) { return getItems(applyOption, e -> e.getKind() == ApplyItem.Kind.GROUP_BY, GroupBy.class); } /** * Get's item list from {@link ApplyOption} by predicate. * * @param applyOption * apply option * @param predicate * predicate for filter * @param clazz * item class * @param <T> type of item * @return list of items math to predicate and class */ public static <T> List<T> getItems(ApplyOption applyOption, Predicate<ApplyItem> predicate, Class<T> clazz) { List<T> itemsList = new ArrayList<>(); if (applyOption != null) { applyOption.getApplyItems().stream().filter(predicate).map(clazz::cast) .forEach(itemsList::add); } return itemsList; } }
true
be23cbd9dc2a03fe9fe6a787d98d3bdb9f136fdd
Java
IMIercY/IDictionary
/app/src/main/java/com/mercy/idictionary/activities/MainActivity.java
UTF-8
6,138
2.171875
2
[]
no_license
package com.mercy.idictionary.activities; import android.app.SearchManager; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.widget.ContentLoadingProgressBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreSettings; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.mercy.idictionary.R; import com.mercy.idictionary.adapters.WordAdapter; import com.mercy.idictionary.database.DatabaseUtils; import com.mercy.idictionary.models.Word; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements WordAdapter.ItemClickListener, SearchView.OnQueryTextListener { private WordAdapter adapter; private List<Word> wordsToShow = new ArrayList<>(); private List<Word> allWords = new ArrayList<>(); private ContentLoadingProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = findViewById(R.id.progress_bar); SearchView searchView = findViewById(R.id.main_search_view); RecyclerView recyclerView = findViewById(R.id.main_recycler_view); adapter = new WordAdapter(allWords); adapter.setOnItemClickListener(this); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.setAdapter(adapter); searchView.setOnQueryTextListener(this); if (isFirstRun()) { Log.d("app", "is first run = " + isFirstRun()); loadDataFromFirebase(); } else { allWords = DatabaseUtils.getInstance(getApplicationContext()).getAllItems(); adapter.setData(allWords); } } public void loadDataFromFirebase() { progressBar.show(); FirebaseFirestore db = FirebaseFirestore.getInstance(); FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() .setTimestampsInSnapshotsEnabled(true) .build(); db.setFirestoreSettings(settings); db.collection("words").orderBy("titleFire").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot querySnapshot) { allWords.clear(); for (QueryDocumentSnapshot query : querySnapshot) { allWords.add(query.toObject(Word.class)); } adapter.setData(allWords); progressBar.hide(); saveDataToLocalDatabase(allWords); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressBar.hide(); Toast.makeText(getApplicationContext(), R.string.err_loading_word, Toast.LENGTH_LONG).show(); Log.d("app", "addOnFailureListener ", e.fillInStackTrace()); } }); } public void saveDataToLocalDatabase(List<Word> words) { DatabaseUtils.getInstance(getApplicationContext()).insertAllItems(words); } // private boolean isNetworkConnected() { // boolean connected = false; // ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivityManager != null) { // isConnected = connectivityManager.getActiveNetworkInfo().isConnected(); // } // return connected; // } public boolean isFirstRun() { boolean firstRun = false; SharedPreferences preferences = getSharedPreferences("com.mercy.idictionary", MODE_PRIVATE); if (preferences.getBoolean("firstRun", true)) { preferences.edit().putBoolean("firstRun", false).apply(); firstRun = true; } return firstRun; } @Override public void onItemClick(View view, int position) { if (wordsToShow.size() != 0) { startActivity(new Intent(getApplicationContext(), DetailActivity.class) .putExtra("word", wordsToShow.get(position))); overridePendingTransition(R.anim.enter_slide_to_left, R.anim.fix_enter_exit); } Log.d("app", " click position " + position + "/ adapter size " + wordsToShow.size()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); Log.d("app", "onNewIntent "+query); } } @Override public boolean onQueryTextSubmit(String query) { wordsToShow = adapter.filter(allWords, query); adapter.setData(wordsToShow); return false; } @Override public boolean onQueryTextChange(String newText) { wordsToShow = adapter.filter(allWords, newText); adapter.setData(wordsToShow); return false; } @Override protected void onStart() { super.onStart(); if (wordsToShow.size() == 0) { wordsToShow = DatabaseUtils.getInstance(getApplicationContext()).getAllItems(); adapter.setData(wordsToShow); } } // end of file }
true
437788c59f25768dca0518c4c70856537d817a59
Java
mateusz93/Book-rental
/app/src/main/java/project/bookrental/models/BorrowedBookModel.java
UTF-8
887
2.59375
3
[]
no_license
package project.bookrental.models; import java.util.Date; /** * Created by Mateusz on 05.01.2018. */ public class BorrowedBookModel { private Long bookId; private String userId; private Date borrowDate; public BorrowedBookModel() { } public BorrowedBookModel(Long bookId, String userId, Date borrowDate) { this.bookId = bookId; this.userId = userId; this.borrowDate = borrowDate; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getBorrowDate() { return borrowDate; } public void setBorrowDate(Date borrowDate) { this.borrowDate = borrowDate; } }
true
c9c48b62055c1c05ff54c9dadc9d1dd1058725f2
Java
iFocused/iFocused
/DaemonBlocker/src/application/entities/TaskStatus.java
UTF-8
92
1.726563
2
[]
no_license
package application.entities; public enum TaskStatus { INITALIZED, COMPLETED, REMOVED }
true
70e597d8a952b4cb99a086c370c809758bd969e6
Java
febagni/project-pacman
/src/AudioPlayer.java
UTF-8
4,320
3.0625
3
[]
no_license
/* * @file AudioPlayer.java * * @brief Class to implement audio (music and sfx) for the game * * @author Alexandre Marques Carrer <alexandrecarrer@usp.br> * @author Felipe Bagni <febagni@usp.br> * @author Gabriel Yugo Kishida <gabriel.kishida@usp.br> * @author Gustavo Azevedo Correa <guazco@usp.br> * * @date 06/2020 */ import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; public class AudioPlayer { static final float initVolume = -20.0f; //Initial volume static final String effectFile = "Effects/"; Long currentFrame; //Current frame of the song Clip clip; //Clip that plays the song String status; //status (whether the game is paused or playing) AudioInputStream audioInputStream; //Inputstream for the AudioFile String mainFolder = "audio/"; //Mainfolder of the audio files String filePath = "dif1.aif"; //File path for the current level static String sourceFolder = "Classic/";//Source folder of the current look and feel static float volume = initVolume; //Volume that is playing on the game right now FloatControl gainControl; //FloatControl to set the volume /* * @brief Constructor for song audio players (has a different song for each level) */ AudioPlayer(int level) { filePath = "dif" + Integer.toString(level) + ".aif"; try { audioInputStream = AudioSystem.getAudioInputStream(new File(mainFolder + sourceFolder + filePath).getAbsoluteFile()); clip = AudioSystem.getClip(); clip.open(audioInputStream); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); changeSound(volume); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (Exception e) { e.printStackTrace(); } } /* * @brief Constructor for the sound effects. Receives the path of the sound effect and plays it once */ AudioPlayer(String effectPath) { try { audioInputStream = AudioSystem.getAudioInputStream(new File(mainFolder + effectFile + effectPath).getAbsoluteFile()); clip = AudioSystem.getClip(); clip.open(audioInputStream); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); changeSound(volume); play(); } catch (Exception e) { e.printStackTrace(); } } /* * @brief Method to change the volume of the object audioPlayer */ public void changeSound(float decibes) { volume = decibes; gainControl.setValue(volume); } /* * @brief Method to play the audio */ public void play() { clip.start(); status = "play"; } /* * @brief Method to start the audio all over again */ public void restart() { clip.stop(); clip.close(); resetAudioStream(); currentFrame = 0L; clip.setMicrosecondPosition(0); play(); } /* * @brief Method to stop the audio from playing */ public void stop() { currentFrame = 0L; clip.stop(); clip.close(); } /* * @brief Method that resets the audio stream from which the audio is read */ public void resetAudioStream() { try { audioInputStream = AudioSystem.getAudioInputStream(new File(mainFolder + sourceFolder + filePath).getAbsoluteFile()); clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (Exception e) { e.printStackTrace(); } } /* * @brief Pauses the song to continue later */ public void pause() { if(status.equals("paused")) return; currentFrame = clip.getMicrosecondPosition(); clip.stop(); status = "paused"; } /* * @brief Resumes audio from where it was playing */ public void resumeAudio() { if (status.equals("play")) return; clip.close(); resetAudioStream(); clip.setMicrosecondPosition(currentFrame); play(); status = "play"; } /* * @brief sets current media path, changing it while the object is still there */ public void setMediaPath(String path) { filePath = path; } }
true
fe59cfad8b240629240fff7a22a9f05c1a0ec477
Java
KekemonBS/PMS
/LAB_8/app/src/main/java/ua/kpi/comsys/iv8106/tools/database/DBHelper.java
UTF-8
1,307
2.484375
2
[]
no_license
package ua.kpi.comsys.iv8106.tools.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class DBHelper extends SQLiteOpenHelper { public DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { //Pic list, movie list String createMain = "CREATE TABLE %s (" + "no INTEGER PRIMARY KEY AUTOINCREMENT," + "query TEXT," + "json TEXT" + ");"; //Movie desc String createSecondary = "CREATE TABLE %s (" + "no INTEGER PRIMARY KEY AUTOINCREMENT," + "id TEXT," + "json TEXT" + ");"; db.execSQL(String.format(createMain, "imageList")); db.execSQL(String.format(createMain, "movieList")); db.execSQL(String.format(createSecondary, "movieDescList")); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("Upgrade, IDK do something."); } }
true
202105bc327883df9d6c7e55120f41ce8bd8f36e
Java
Solkan04/Java
/Strings_Programs/stringClassMethods/Substring.java
UTF-8
357
3.15625
3
[]
no_license
package stringClassMethods; public class Substring { public static void main(String[] args) { subStringDemo(); } static void subStringDemo() { String str="Welcome to JAVA"; String strRes1=str.substring(11); System.out.println(strRes1); //========================= String strRes2=str.substring(0, 7); System.out.println(strRes2); } }
true
773d4746090643e8334be8f42b5b43c212c05e23
Java
seba3c/java-coding-challenges
/src/hackerRank/strings/CamelCase.java
UTF-8
844
3.796875
4
[]
no_license
package hackerRank.strings; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Scanner; /** * @link https://www.hackerrank.com/challenges/camelcase/problem */ public class CamelCase { static int camelCase(String s) { int count = 0; if (s == null || s.trim() == "") { return count; } if (Character.isLowerCase(s.charAt(0))) { count += 1; } CharacterIterator it = new StringCharacterIterator(s); while (it.current() != CharacterIterator.DONE) { Character c = it.next(); if (Character.isUpperCase(c)) { count += 1; } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int result = camelCase(s); System.out.println(result); in.close(); } }
true
bafc35039fb57891a8ce668199ccf273a5c66b58
Java
Taddeus10/Curso_de_Mobile
/Aula8/src/br/com/digitalhouse/Exercicio1.java
UTF-8
273
2.359375
2
[]
no_license
package br.com.digitalhouse; public class Exercicio1 { private String lot; public Exercicio1(String lot) { this.lot = lot; } public String getLot() { return lot; } public void setLot(String lot) { this.lot = lot; } }
true
a2e6f3295ad9699274c379f5a08be10c675a8c60
Java
murali3313/expendio
/app/src/main/java/com/thriwin/expendio/PieChartEntryClickLoader.java
UTF-8
1,150
2.359375
2
[]
no_license
package com.thriwin.expendio; import android.os.Handler; import android.os.Message; import java.util.Date; import java.util.HashMap; import java.util.Map; import static com.thriwin.expendio.Utils.isNull; public class PieChartEntryClickLoader extends Thread { private String label; private Map<String, Expenses> viewableTagExpenses; private Handler handler; Map<String, Object> dataMap = new HashMap<>(); public PieChartEntryClickLoader(String label, Map<String, Expenses> viewableTagExpenses, Handler handler) { this.label = label; this.viewableTagExpenses = viewableTagExpenses; this.handler = handler; } @Override public void run() { Expenses tagBasedExpenses = this.viewableTagExpenses.get(label); if (isNull(tagBasedExpenses)) { tagBasedExpenses = new Expenses(new Expense(new Date(viewableTagExpenses.get(label).getSpentOnDate()))); } dataMap.put("TagWiseExpenses", Utils.getSerializedExpenses(tagBasedExpenses)); Message msg = new Message(); msg.obj = this.dataMap; this.handler.sendMessage(msg); } }
true
144aaa2785e8a73a012849894abbcdb7c9e4af69
Java
nerellaanusha/car-rental-java
/src/main/java/com/carrental/controller/UserController.java
UTF-8
8,163
2.25
2
[]
no_license
package com.carrental.controller; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.carrental.dao.BookingDao; import com.carrental.dao.CarRepo; import com.carrental.dao.CouponDao; import com.carrental.dao.QuoteDao; import com.carrental.message.request.BookingReq; import com.carrental.message.request.HomePageRequest; import com.carrental.message.request.QuoteReq; import com.carrental.message.response.CarResponse; import com.carrental.message.response.NearByCar; import com.carrental.message.response.ResponseMessage; import com.carrental.message.response.ZipCodeResponse; import com.carrental.message.response.Zipcode; import com.carrental.model.Booking; import com.carrental.model.Car; import com.carrental.model.Coupon; import com.carrental.model.Quote; import com.carrental.security.services.NextSequenceService; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/user") public class UserController { @Autowired CarRepo carRepo; @Autowired CouponDao couponDao; @Autowired NextSequenceService nextSequenceService; @Autowired BookingDao bookingDao; @Autowired QuoteDao quoteDao; @Autowired private JavaMailSender javaMailSender; @PostMapping("/getCarsOnZipcode") public ResponseEntity<?> getCarsByZipcode(@RequestBody HomePageRequest homepageReq){ List<CarResponse> carsResp= new ArrayList<CarResponse>(); try { String apiKey = "ogNnaGqAGPRh5dkjowTER8gLUdnQwgYqF69PEf2EttNL5f7rEdDmVf0QkpkJT0D9"; String uri = "https://www.zipcodeapi.com/rest/"+apiKey+"/radius.json/"+homepageReq.getPickUpLoc()+"/20/mile"; RestTemplate restTemplate = new RestTemplate(); ZipCodeResponse result = restTemplate.getForObject(uri, ZipCodeResponse.class); List<Zipcode> zipcodeObjs = result.getZip_codes(); List<Integer> zipcodes = zipcodeObjs.stream().map(zip -> Integer.valueOf(zip.getZip_code())).collect(Collectors.toList()); zipcodes.add(homepageReq.getPickUpLoc()); List<Car> cars = this.carRepo.getCarsByZipcode(zipcodes); if(cars.size() > 1) { long difference = (homepageReq.getDropOffDate().getTime()-homepageReq.getPickUpDate().getTime())/86400000; long days = Math.abs(difference); CarResponse carRes = null; for(Car car: cars) { if(homepageReq.getPickUpLoc().equals(car.getZipcode())) { carRes = new CarResponse(); carRes.setBaggage(car.getBaggage()); carRes.setCapacity(car.getCapacity()); carRes.setCarMake(car.getCarMake()); carRes.setCarModel(car.getCarModel()); carRes.setImage(car.getImage()); carRes.setPrice(car.getPrice()); carRes.setTotalPrice(days * car.getPrice()); carRes.setTotalPriceWithTax(days * car.getPrice() + (days * car.getPrice()* 0.10)); carRes.setType(car.getType()); carRes.setVin(car.getVin()); carRes.setTax(new Float(10)); carRes.setZipcode(car.getZipcode()); for(Car veh: cars) { if(veh.getCarModel().equalsIgnoreCase(car.getCarModel()) && !veh.getZipcode().equals(car.getZipcode())) { NearByCar nearByCar = new NearByCar(); nearByCar.setPrice(veh.getPrice()); nearByCar.setZipcode(veh.getZipcode()); carRes.getNearByCars().add(nearByCar); } } carsResp.add(carRes); } } } }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(new ResponseMessage("Error While Fetching Cars"), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(new ResponseMessage("Found Cars"), HttpStatus.OK).ok(carsResp); } @GetMapping("/coupon/{code}") public ResponseEntity<?> getCoupon(@PathVariable String code) { Coupon coupon = this.couponDao.getCouponByCode(code); if(coupon == null) { return new ResponseEntity<>(new ResponseMessage("No Coupon"), HttpStatus.EXPECTATION_FAILED); } return new ResponseEntity<>(new ResponseMessage("Coupon Found"), HttpStatus.OK).ok(coupon); } @PostMapping("/reserveCar") public ResponseEntity<?> reserveCar(@RequestBody BookingReq bookingReq){ Booking booking = new Booking(); booking.setBookingId(nextSequenceService.getNextSequence(Booking.SEQUENCE_NAME)); booking.setBookingStatus("CONFIRMED"); booking.setContactNumber(bookingReq.getContactNumber()); booking.setCustomerId(bookingReq.getCustomerId()); booking.setDropOffDate(bookingReq.getDropOffDate()); booking.setDropOffloc(bookingReq.getDropOffloc()); booking.setEmail(bookingReq.getEmail()); booking.setFirstName(bookingReq.getFirstName()); booking.setLastName(bookingReq.getLastName()); booking.setPickUpDate(bookingReq.getPickUpDate()); booking.setPickUpLoc(bookingReq.getPickUpLoc()); booking.setTotalPrice(bookingReq.getTotalPrice()); bookingDao.reserveCar(booking); try { SimpleMailMessage msg = new SimpleMailMessage(); msg.setTo(bookingReq.getEmail()); msg.setSubject("Car Rental Confirmation"); msg.setText("Your reservation is confirmed. Booking Reference Number:"+booking.getBookingId()); javaMailSender.send(msg); }catch(Exception e) { return new ResponseEntity<>(new ResponseMessage("Error While Sending Email"), HttpStatus.PARTIAL_CONTENT); } return new ResponseEntity<>(new ResponseMessage("Booking Succesfull"), HttpStatus.OK).ok(booking.getBookingId()); } @GetMapping("/retreiveBookings/{customerId}") public List<Booking> retreiveBookings(@PathVariable Long customerId) { return bookingDao.getBookingsByCustomer(customerId); } @PostMapping("/submitQuote") public ResponseEntity<?> submitQuote(@RequestBody QuoteReq quoteReq){ Quote quote = new Quote(); quote.setContactNumber(quoteReq.getContactNumber()); quote.setCustomerId(quoteReq.getCustomerId()); quote.setDropOffDate(quoteReq.getDropOffDate()); quote.setDropOffloc(quoteReq.getDropOffloc()); quote.setPickUpDate(quoteReq.getPickUpDate()); quote.setPickUpLoc(quoteReq.getPickUpLoc()); quote.setEmail(quoteReq.getEmail()); quote.setFirstName(quoteReq.getFirstName()); quote.setLastName(quoteReq.getLastName()); quote.setQuoteStatus("PENDING"); quote.setVin(quoteReq.getVin()); quote.setTotalPrice(quoteReq.getActualPrice()); quote.setUserPrice(quoteReq.getUserPrice()); quote.setEmail(quoteReq.getEmail()); quote.setQuoteId(nextSequenceService.getNextSequence(Quote.SEQUENCE_NAME)); quoteDao.submitQuote(quote); try { SimpleMailMessage msg = new SimpleMailMessage(); msg.setTo(quoteReq.getEmail()); msg.setSubject("Car Rental - Quote Submitted"); StringBuilder result = new StringBuilder(); result.append("Your quote is submitted. Quote Reference Number:"+quote.getQuoteId()); result.append(System.getProperty("line.separator")); result.append("Please allow 2-3 business days to get response and you will receive an email when quote is approved/declined"); msg.setText(result.toString()); javaMailSender.send(msg); }catch(Exception e) { return new ResponseEntity<>(new ResponseMessage("Error While Sending Email"), HttpStatus.PARTIAL_CONTENT); } return new ResponseEntity<>(new ResponseMessage("Quote Submitted Succesfully"), HttpStatus.OK); } }
true
e874168cabf577ea861b8131f719f7d3555c630a
Java
JuanJsPM/Extraordinaria-IS2
/src/view/CatalogueLoader.java
UTF-8
113
1.84375
2
[]
no_license
package view; import model.Catalogue; public interface CatalogueLoader { public Catalogue load(); }
true
7bfcbab69375086859b90927d22d8fc6c4e58c9f
Java
Abel-ylj/dubbo_demo
/provider_api/src/main/java/cn/ylj/api/IUserSerivce.java
UTF-8
235
1.789063
2
[]
no_license
package cn.ylj.api; import cn.ylj.entity.UserEntity; import java.util.List; /** * @author : yanglujian * create at: 2021/1/15 4:46 下午 */ public interface IUserSerivce { List<UserEntity> findAll(); void update(); }
true
1829f391a1e078e324c578acb39c600f972856cd
Java
jinxTelesis/bcs345
/class3Inport/src/MyJFrame.java
UTF-8
1,050
3.046875
3
[]
no_license
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; public class MyJFrame extends JFrame{ public MyJFrame(){ //in here I will... JPanel allContent = new JPanel();//A- create a JPanel that will hold multiple components //allContent.setLayout(new GridLayout(1,2)); //allContent.setLayout(new BorderLayout());//N,S,E,W,C MyJPanel myJP = new MyJPanel();//1 create an instance of MyJPanel myJP.setBackground(Color.YELLOW); // MyJPanel myJP2 = new MyJPanel();//1 create an instance of MyJPanel // myJP2.setBackground(Color.MAGENTA); allContent.add(myJP);//2 add the MyJPanel object to the allContent JPanel // allContent.add(myJP2);//2 add the MyJPanel object to the allContent JPanel // allContent.add(myJP, BorderLayout.NORTH); // allContent.add(myJP2, BorderLayout.SOUTH); add(allContent);//B- add the allContent object to this current JFrame setVisible(true); setSize(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
true
d962ae3b55332931f79ed8fa5dac7077ef0c7b05
Java
Craftizz/mNPC
/src/main/java/io/github/craftizz/mnpc/managers/NPCManager.java
UTF-8
2,105
2.640625
3
[]
no_license
package io.github.craftizz.mnpc.managers; import io.github.craftizz.mnpc.MNPC; import io.github.craftizz.mnpc.npc.Page; import io.github.craftizz.mnpc.npc.SocialNPC; import io.github.craftizz.mnpc.npc.UserData; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.UUID; public class NPCManager { private final HashMap<Integer, SocialNPC> npcMap; private final HashMap<UUID, UserData> userMap; public NPCManager() { this.npcMap = new HashMap<>(); this.userMap = new HashMap<>(); } public void addSocialNPC(final @NotNull SocialNPC npc) { npcMap.put(npc.getNpcId(), npc); } public void addPlayerData(final @NotNull UserData userData) { userMap.put(userData.getUniqueId(), userData); } public void handleSocialNPC(final @NotNull Player player, final int npcId) { final SocialNPC socialNPC = npcMap.get(npcId); if (socialNPC == null) { return; } if (!socialNPC.meetsRequirement(player)) { return; } final UserData userData = getPlayerData(player); final Integer pageData = userData.getPageData(npcId); final Page page; if (pageData == null) { page = socialNPC.getFirstClickPage(); userData.setPageData(npcId, 0); } else { page = socialNPC.getPage(pageData); userData.setPageData(npcId, pageData + 1); } if (page != null) { page.play(player); } } public UserData getPlayerData(final @NotNull Player player) { UserData userData = userMap.get(player.getUniqueId()); if (userData != null) { return userData; } userData = new UserData(player.getUniqueId()); userMap.put(player.getUniqueId(), userData); return userData; } public HashMap<Integer, SocialNPC> getNpcMap() { return npcMap; } public void clearNPCs() { npcMap.clear(); } }
true
bdd8bfe6fc93f89dc880365b8d44d2b5f38781a1
Java
DottaPaperella/TALight
/TAL_lib/Java/Env.java
UTF-8
2,053
2.71875
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication17; import java.util.List; import java.util.ArrayList; import java.util.Map; /** * * @author UTENTE */ import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * * @author UTENTE */ public class Env { private Map<String,Object> item = new HashMap(); private Map<String,String> environment_variables=new HashMap(); private String meta_data=System.getenv("TAL_META_DIR"); private String problem=""; private String service=""; private Object [] arg = {}; public Env(String problem,String service,Map<String,String>args){ this.problem=problem; this.service=service; this.environment_variables=args; this.item=ENV(environment_variables); } private Map<String,Object> ENV(Map<String,String>args) { for (Map.Entry <String, String> entry: args.entrySet()) { switch(entry.getValue()) { case "int": item.put(entry.getKey(),Integer.parseInt(System.getenv("TAL_"+entry.getKey()))); break; case "String": item.put(entry.getKey(),System.getenv("TAL_"+entry.getKey())); break; case "Float": item.put(entry.getKey(),Float.parseFloat(System.getenv("TAL_"+entry.getKey()))); break; default: System.out.println("# Unrecoverable Error: type "+entry.getValue()+"not yet supported in args list. Used to interpret arg "+entry.getKey()+"."); } } return item; } public Object ENV(String var) { for (Map.Entry <String, Object> entry: item.entrySet()) { if(entry.getKey().equals(var)) return entry.getValue(); } return null; } }
true
b996ba2e68174c515f5297d32c64e904facfc94f
Java
chiirz/TestProjectFingerMenu
/src/de/main/main.java
ISO-8859-1
5,316
2.515625
3
[]
no_license
package de.main; import java.io.Console; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.AbsoluteLayout; import android.widget.ImageButton; import android.widget.RelativeLayout.LayoutParams; public class main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Die ganzen Buttons initialisieren und onClick methode bereitstellen final ImageButton b1 = new ImageButton(getBaseContext()); b1.setBackgroundResource(R.drawable.red); b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { drawSubmenu(1); } } ); final ImageButton b2 = new ImageButton(getBaseContext()); b2.setBackgroundResource(R.drawable.red); b2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { drawSubmenu(2); } } ); final ImageButton b3 = new ImageButton(getBaseContext()); b3.setBackgroundResource(R.drawable.red); b3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { drawSubmenu(3); } } ); final ImageButton b4 = new ImageButton(getBaseContext()); b4.setBackgroundResource(R.drawable.red); b4.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { drawSubmenu(4); } } ); //Absolute layout will Google nichtmehr sehen, aber anders gehts nicht mit dem positionieren beim finger @SuppressWarnings("deprecation") //Hier hole ich mir das Layout aus dem main.xml, mehr hab ich mit dem editor nicht gemacht final AbsoluteLayout abs = (AbsoluteLayout) findViewById(R.id.abs1); abs.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { //Finger aufs display -> alle alten views(imagebuttons) lschen abs.removeAllViewsInLayout(); //Koordinate des touch events int pos_x = (int)event.getX(); int pos_y = (int)event.getY(); Log.v("TAG", "X-Koordinate: "+pos_x); Log.v("TAG", "Y-Koordinate:"+pos_y); //Parameter fr die Positionen der Buttons setzen AbsoluteLayout.LayoutParams absParam = null;// = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pos_x-50, pos_y-50 ); AbsoluteLayout.LayoutParams absParam2 = null;// = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pos_x, pos_y +50 ); AbsoluteLayout.LayoutParams absParam3 = null;// = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pos_x-40, pos_y +70 ); AbsoluteLayout.LayoutParams absParam4 = null;// = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pos_x+70, pos_y +70 ); double step = (2.0 * Math.PI) / (1.0 * 4);//(items.length)); double rotation = (90 / 180) * Math.PI; double radius = 35;//Math.sqrt(this.itemWidth) * Math.sqrt(items.length) * 2.5; for(int i=0; i<4; i++) { double x = pos_x - Math.cos(i*step - rotation) * radius - 50;//(this.itemWidth / 2); double y = pos_y- Math.sin(i*step - rotation) * radius - 50;//(this.itemHeight / 2); if(i==0) { absParam = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, (int)Math.round(x), (int)Math.round(y) ); } else if(i==1) { absParam2 = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, (int)Math.round(x), (int)Math.round(y) ); } else if(i==2) { absParam3 = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, (int)Math.round(x), (int)Math.round(y) ); } else if(i==3) { absParam4 = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, (int)Math.round(x), (int)Math.round(y) ); } } //Buttons mit den Parametern dem View hinzufgen abs.addView(b1, absParam); abs.addView(b2, absParam2); abs.addView(b3, absParam3); abs.addView(b4, absParam4); return false; } }); } /******************************************************************************************************************** * Hier muss dann das Untermen gemacht werden * * @param buttonId, die Id des Buttons der gedrckt wurde *******************************************************************************************************************/ private void drawSubmenu(int buttonId) { Log.v("TAG", "Button pressen, Id: "+buttonId); } }
true
fa93866de86506ee1998a1e53d5338e8062afffe
Java
TetsuoCologne/mathe-prog
/src/FiedlerKrebs/EuDModel.java
UTF-8
1,548
3.140625
3
[]
no_license
package FiedlerKrebs; import java.util.Observable; /** * Diese Klasse berechnet den größten gemeinsamen Teiler und die Bezout Koeffizienten nach dem Erweiterten * Euklidischen Algorithmus. * @author Marc Fiedler, Franziska Krebs * */ public class EuDModel extends Observable { private int a, b, ggt,bezoutA, bezoutB; public int getBezoutA() { return bezoutA; } public int getBezoutB() { return bezoutB; } public void setA(int a) { this.a = a; } public void setB(int b) { this.b = b; } public int getGgt() { return ggt; } public EuDModel(int a, int b) { super(); this.a = a; this.b = b; } public EuDModel() { super(); a = 0; b = 0; } // Methode zur Berechnung /** * * @throws ZeroException Bei der Eingabe zweier Nullen wird eine Exception geworfen. * @throws NegativeEingabeException Ist eine der eingegebenen Zahl kleiner als 0, wird ebenfalls eine Exception * geworfen. Die Festlegung des Fehlertextes erfolgt in der Klasse EuDView. */ public void berechneGgT() throws ZeroException, NegativeEingabeException{ int q, r, s, t; q=0; r=0; bezoutA=t=1; bezoutB=s=0; if(a==0 && b==0) throw new ZeroException(); else if(a<0 || b<0) throw new NegativeEingabeException(); else{ while(b>0) { q=a/b; r=a-q*b; a=b; b=r; r=bezoutA-q*s; bezoutA=s; s=r; r=bezoutB-q*t; bezoutB=t; t=r; } ggt=a; } setChanged(); notifyObservers(); } }
true
67b611b87fa2645a64b2fbcbfbd0e1ed73203d14
Java
pixelationteam/dietfix-project
/src/pup/thesis/nlu/WordSynonym.java
UTF-8
2,171
2.46875
2
[]
no_license
package pup.thesis.nlu; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import net.didion.jwnl.JWNLException; import net.didion.jwnl.data.IndexWord; import net.didion.jwnl.data.POS; import net.didion.jwnl.data.PointerType; import net.didion.jwnl.data.Synset; import net.didion.jwnl.data.Word; import net.didion.jwnl.data.relationship.Relationship; import pup.thesis.helper.JwnlHelper; import pup.thesis.helper.MysqlHelper; import pup.thesis.learning.reinforcement.ReinforcementLearning; import pup.thesis.logging.App; import com.mysql.jdbc.log.Log; /** * Class that will determine whether * a word exist on the database. If the * word doesn't exist in the database, it will * find the synonyms of that word which could * possibly be on the database. * * This class also utilizes Reinforcement Learning * * * @since 05-20-2013 * @author paulzed * */ public class WordSynonym extends ReinforcementLearning { private JwnlHelper helper; private MysqlHelper sqlHelper; private Log log; /** * * Checks whether the word exist in the list of known_words * in the database * * @param word * @return * @throws SQLException */ public boolean isWordExistInDb(RelatedWord word) throws SQLException { ArrayList<RelatedWord> kWords = new ArrayList<RelatedWord>(); kWords = iterateInDb(""); Iterator<RelatedWord> i = kWords.iterator(); RelatedWord _word = word; while(i.hasNext()) { RelatedWord kWord = i.next(); if(isSame(_word.getLabel(), _word.getTag(), kWord.getLabel(), kWord.getTag())) { return true; } } return false; } /** * * Converts the Arraylist of synset to Arraylist of String * * @param sets * @return */ public ArrayList<String> synset2String(ArrayList<Synset> sets) { ArrayList<String> synsets = new ArrayList<String>(); Iterator<Synset> i = sets.iterator(); while(i.hasNext()) { Synset synset = i.next(); Word[] words = synset.getWords(); for(int x = 0; x < words.length; x++) { synsets.add(words[x].getLemma()); } } return synsets; } }
true
2366e7f23b2ad77e44f298f4ebe2377766658c13
Java
gtdocker/ivory
/gtsoftware/ivoryserver4j/resourceadapters/samples/src/gtsoft/ivory/samples/jca/InstallationVerificationServlet.java
UTF-8
8,614
2.234375
2
[]
no_license
/**********************************************************************/ /* */ /* Copyright 2012, GT Software, Inc. */ /* All rights reserved. */ /* */ /* #Description# */ /* */ /* Sample servlet to execute the Ivory resource adapter */ /* installation verification program. The installation */ /* verfication program will return an HTML document which may */ /* be displayed in a web browser. */ /* */ /**********************************************************************/ package gtsoft.ivory.samples.jca; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.*; import javax.resource.cci.*; import gtsoft.ivory.server.jca.cci.IvoryInteractionSpec; import gtsoft.ivory.server.jca.cci.IvoryStringRecord; import gtsoft.ivory.server.jca.cci.IvoryLocalConnectionSpec; /** * <code>InstallationVerificationServlet</code> * is a sample servlet which will execute the Ivory JCA resource * adapter installation verification functionality * * @author GT Software */ public class InstallationVerificationServlet extends HttpServlet { private static final String CONTENT_TYPE_HTML = "text/html; charset=utf-8"; /** * Implementation of servlet init method. * * @param config servlet config object * @throws ServletException */ public void init(ServletConfig config) throws ServletException { super.init(config); } /** * Implementation of servlet doGet method. * * @param request request object * @param response respons object * @throws ServletException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { doInstallationVerification(request,response); } /** * Implementation of servlet doPost method. * * @param request request object * @param response respons object * @throws ServletException */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { doInstallationVerification(request,response); } /** * Perform the actual installation verification. * * @param request request object * @param response respons object * @throws ServletException */ public void doInstallationVerification(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { ConnectionFactory cf = null; StringBuffer errBuff = new StringBuffer(); String retHtml = null; String jndiName = getServletContext().getInitParameter("IvoryConnectionFactoryName"); do { // Make sure a <context-param> was supplied for IvoryConnectionFactoryName if ((jndiName == null) || (jndiName.length() == 0)) { errBuff.append("<p>Mandatory web application context parameter IvoryConnectionFactoryName was not supplied. Please add to web.xml.</p>"); break; } // Get a ConnectionFactory object try { javax.naming.Context ic = new javax.naming.InitialContext(); cf = (ConnectionFactory) ic.lookup(jndiName); } // The lookup did not work, cannot find a ConnectionFactory object with the // supplied jndi name catch (Exception e) { errBuff.append("<p>Context.lookup() failed, cannot allocate ConnectionFactory with name " + jndiName + ". Exception occurred: " + e.getMessage() + "</p>"); break; } // An exception did not occur but make sure we actually did get a // ConnectionFactory if (cf == null) { errBuff.append("<p>Could not get connection factory</p>"); break; } // We have a ConnectionFactory, from it get a Connection object Connection ivConnection; try { // Create a local connection spec since the installation // verification is going to be performed locally IvoryLocalConnectionSpec cSpec = new IvoryLocalConnectionSpec(); ivConnection = (Connection)cf.getConnection(cSpec); } // Unable to create a Connection catch (Exception e) { errBuff.append("<p>Unable to create a Connection. Exception occurred: " + e.getMessage() + "</p>"); break; } // We have a Connection, from it get an Interaction object Interaction ivInteraction; try { ivInteraction = (Interaction)ivConnection.createInteraction(); } // Unable to create an Interaction catch (Exception e) { errBuff.append("<p>Unable to create an Interaction. Exception occurred: " + e.getMessage() + "</p>"); break; } // Create an IvoryInteractionSpec and most importantly set the endpoint // to ivp.srv. This will tell the JCA adapter to perform an installation // verification IvoryInteractionSpec ivInteractionSpec = new IvoryInteractionSpec(); ivInteractionSpec.setRequestID("InstallationVerificationServlet"); ivInteractionSpec.setEndpoint("ivp.srv"); ivInteractionSpec.setFunctionName("InstallationVerification"); // IvoryStringRecord is a generalized implementation of Record to hold // a String request and/or String response. Since installation verification // does not require any real input, reuse the same IvoryStringRecord for // both input and output IvoryStringRecord ivRecord = new IvoryStringRecord(); try { // Perform the installation verification ivInteraction.execute(ivInteractionSpec,ivRecord,ivRecord); } // Something went wrong during the execution catch (Exception e) { errBuff.append("<p>Error during execution of Ivory Server resource adapter. Exception occurred: " + e.getMessage() + "</p>"); break; } // Installation verification will return an HTML document. It is stored // inside the output Record. Get the response and close both the // Interaction and the Connection. try { retHtml = ivRecord.getString(); ivInteraction.close(); ivConnection.close(); } // Something went wrong catch (Exception e) { errBuff.append("<p>Error while attempting to close either the Interaction or Connection. Exception occurred: " + e.getMessage() + "</p>"); break; } } while (false); // Write out the HTML response response.setContentType(CONTENT_TYPE_HTML); response.setHeader("Expires","-1"); response.setHeader("Pragma","no-cache"); PrintWriter out = response.getWriter(); // If there was an error generate our own HTML document if (errBuff.length() > 0) { out.println("<html>"); out.println("<head><title>Ivory Server Resource Adapter Installation Verification Results</title></head>"); out.println("<body>"); out.println(errBuff.toString()); out.println("</body></html>"); } // No error and the installation verification returned HTML. Write all the // HTML out else if (retHtml != null) { out.println(retHtml); } out.close(); } }
true
2a5e0dedc8d28e7aea8b2dabd9ad199d1ada4578
Java
saffyA/shopoholics
/src/main/java/com/vapasians/shopoholics/model/CartItem.java
UTF-8
1,000
2.265625
2
[]
no_license
package com.vapasians.shopoholics.model; import javax.persistence.*; import java.util.Set; @Entity @Table(name="cartitem") public class CartItem { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "cartitemid") private int cartItemId; @Column(name = "userid") private int userId; @Column(name = "productid") private int productId; public CartItem() { } public CartItem(int userId, int productId) { this.userId = userId; this.productId = productId; } public int getCartItemId() { return cartItemId; } public void setCartItemId(int cartItemId) { this.cartItemId = cartItemId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } }
true
f908c300756a9307b26c9a574204d8e307daa701
Java
NoobsDevelopers/L2Nextgen
/java/l2n/game/network/clientpackets/RequestHandOverPartyMaster.java
UTF-8
688
2.421875
2
[]
no_license
package l2n.game.network.clientpackets; import l2n.game.model.actor.L2Player; public class RequestHandOverPartyMaster extends L2GameClientPacket { private final static String _C__0C_REQUESTHANDOVERPARTYMASTER = "[C] 0c RequestHandOverPartyMaster"; private String _name; @Override public void readImpl() { _name = readS(); } @Override public void runImpl() { final L2Player activeChar = getClient().getActiveChar(); if(activeChar == null) return; if(activeChar.isInParty() && activeChar.getParty().isLeader(activeChar)) activeChar.getParty().changePartyLeader(_name); } @Override public String getType() { return _C__0C_REQUESTHANDOVERPARTYMASTER; } }
true
3d3be89d4b04a6e03fe2cb88f6e63cab050e5a69
Java
qq877693928/Program_Algorithm
/app/src/main/java/joneslee/android/com/algorithm/Tree_All_OrderTrav.java
UTF-8
2,200
3.78125
4
[]
no_license
package joneslee.android.com.algorithm; import java.util.Stack; /** * Description:树的先中后序排序,非递归 * Reference:http://biaobiaoqi.github.io/blog/2013/04/27/travsal-binary-tree/ * * @author lizhenhua9@wanda.cn (lzh) * @date 16/4/5 16:53 */ public class Tree_All_OrderTrav { private TreeNode root; public static void main(String[] args) { Tree_All_OrderTrav tree = new Tree_All_OrderTrav(); tree.preOrderTrav(tree.root); System.out.println(); tree.preOrderTravNoRecur(tree.root); } public Tree_All_OrderTrav() { root = initTree(); } /* * 构建二叉树 * 1 * / \ * 3 4 * \ /\ * 2 7 6 * / * 9 */ private TreeNode initTree() { TreeNode root = new TreeNode(1); root.mLeftNode = new TreeNode(3); root.mRightNode = new TreeNode(4); //=============== root.mLeftNode.mRightNode = new TreeNode(2); root.mRightNode.mLeftNode = new TreeNode(7); root.mRightNode.mRightNode = new TreeNode(6); //=============== root.mRightNode.mLeftNode.mLeftNode = new TreeNode(9); return root; } /** * 前序遍历,递归 * @param root */ private void preOrderTrav(TreeNode root){ if(root == null){ return; } System.out.print(root.value + " "); preOrderTrav(root.mLeftNode); preOrderTrav(root.mRightNode); } private void preOrderTravNoRecur(TreeNode root){ if(root == null){ return; } Stack<TreeNode> s = new Stack<TreeNode>(); while (root != null | !s.empty()){ while (root!=null ){ System.out.print(root.value + " "); s.add(root); root = root.mLeftNode; } root = s.pop(); root = root.mRightNode; } System.out.println(); } /** * 二叉树数据结构 */ public class TreeNode { int value; TreeNode mLeftNode; TreeNode mRightNode; public TreeNode(int i) { value = i; } } }
true
76b45fd96df89166c3be6104043820b53a6d6e5e
Java
vostok/hercules
/hercules-sink/src/test/java/ru/kontur/vostok/hercules/sink/filter/PatternTreeTest.java
UTF-8
5,297
2.625
3
[ "MIT" ]
permissive
package ru.kontur.vostok.hercules.sink.filter; import org.junit.jupiter.api.Test; import ru.kontur.vostok.hercules.protocol.Type; import ru.kontur.vostok.hercules.protocol.Variant; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Anton Akkuzin */ public class PatternTreeTest { @Test public void shouldNotInitializeWithNonPrimitiveTypes() { Exception exception = null; try { new PatternTree(List.of(Type.STRING, Type.VECTOR)); } catch (IllegalArgumentException ex) { exception = ex; } assert exception != null; assertEquals("Type 'VECTOR' is not primitive.", exception.getMessage()); } @Test public void shouldThrowWhenPatternSizeIsDifferentFromTypesSize() { PatternTree patternTree = new PatternTree(List.of(Type.STRING, Type.INTEGER, Type.FLOAT)); Exception exception = null; try { patternTree.put("some_str:1234"); } catch (IllegalArgumentException ex) { exception = ex; } assert exception != null; assertEquals("Pattern size should be equal to paths size.", exception.getMessage()); } @Test public void shouldThrowWhenWrongType() { PatternTree patternTree = new PatternTree(List.of(Type.INTEGER)); boolean thrown = false; try { patternTree.put("not_a_number"); } catch (Exception ex) { thrown = true; } assertTrue(thrown); } @Test public void shouldMatchCorrectPatterns() { PatternTree patternTree = new PatternTree(List.of(Type.STRING, Type.INTEGER, Type.FLOAT)); String[] patterns = { "a:99:105.9", "a:*:999.9", "b:99:*", "*:1234:*", }; for (String pattern : patterns) { patternTree.put(pattern); } assertTrue(patternTree.matches(List.of( Variant.ofString("a"), Variant.ofInteger(99), Variant.ofFloat(105.9f) ))); assertTrue(patternTree.matches(List.of( Variant.ofString("a"), Variant.ofInteger(99), Variant.ofFloat(999.9f) ))); assertTrue(patternTree.matches(List.of( Variant.ofString("a"), Variant.ofInteger(99), Variant.ofFloat(105.9f) ))); assertTrue(patternTree.matches(List.of( Variant.ofString("b"), Variant.ofInteger(99), Variant.ofFloat(3.14f) ))); assertTrue(patternTree.matches(List.of( Variant.ofString("b"), Variant.ofInteger(99), Variant.ofFloat(1) ))); assertTrue(patternTree.matches(List.of( Variant.ofString("c"), Variant.ofInteger(1234), Variant.ofFloat(999.9f) ))); assertFalse(patternTree.matches(List.of( Variant.ofString("a"), Variant.ofInteger(99), Variant.ofFloat(666) ))); } @Test public void shouldMatchStarWhenVariantIsMissing() { PatternTree patternTree = new PatternTree(List.of(Type.STRING, Type.INTEGER, Type.FLOAT)); String[] patterns = { "b:99:*", "*:1234:*", }; for (String pattern : patterns) { patternTree.put(pattern); } ArrayList<Variant> variants = new ArrayList<>(); variants.add(null); variants.add(Variant.ofInteger(1234)); variants.add(null); assertTrue(patternTree.matches(variants)); } @Test public void shouldMatchToAllPrimitiveTypes() { assertTrue(matchesToPrimitiveType(Type.BYTE, "123", Variant.ofByte((byte) 123))); assertTrue(matchesToPrimitiveType(Type.SHORT, "123", Variant.ofShort((short) 123))); assertTrue(matchesToPrimitiveType(Type.INTEGER, "1234", Variant.ofInteger(1234))); assertTrue(matchesToPrimitiveType(Type.LONG, "123456789", Variant.ofLong(123456789))); assertTrue(matchesToPrimitiveType(Type.FLAG, "true", Variant.ofFlag(true))); assertTrue(matchesToPrimitiveType(Type.FLAG, "false", Variant.ofFlag(false))); assertTrue(matchesToPrimitiveType(Type.FLOAT, "3.14", Variant.ofFloat(3.14f))); assertTrue(matchesToPrimitiveType(Type.DOUBLE, "3.14", Variant.ofDouble(3.14))); assertTrue(matchesToPrimitiveType(Type.STRING, "some_str", Variant.ofString("some_str"))); assertTrue(matchesToPrimitiveType(Type.NULL, "null", Variant.ofNull())); UUID uuid = UUID.randomUUID(); assertTrue(matchesToPrimitiveType(Type.UUID, uuid.toString(), Variant.ofUuid(uuid))); } private boolean matchesToPrimitiveType(Type type, String pattern, Variant variant) { PatternTree patternTree = new PatternTree(List.of(type)); patternTree.put(pattern); return patternTree.matches(List.of(variant)); } }
true
0780715205a571f287700da55c1f9a471d2d7fbf
Java
kingking888/jun_java_plugin
/java_plugin/jun_dbutil/jun_jdbc/doc/day18_jdbc/day18_jdbc/源码/day18_01_tx2/src/com/itheima/dao/impl/AccountDaoImpl.java
UTF-8
921
2.453125
2
[]
no_license
package com.itheima.dao.impl; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import com.itheima.dao.AccountDao; import com.itheima.domain.Account; public class AccountDaoImpl implements AccountDao { private QueryRunner qr = new QueryRunner(); private Connection conn; public AccountDaoImpl(Connection conn){ this.conn = conn; } public Account findByName(String accountName) { try { return qr.query(conn,"select * from account where name=?", new BeanHandler<Account>(Account.class),accountName); } catch (SQLException e) { throw new RuntimeException(e); } } public void updateAcount(Account account) { try { qr.update(conn,"update account set money=? where id=?", account.getMoney(),account.getId()); } catch (SQLException e) { throw new RuntimeException(e); } } }
true
c9437bef9da996b58d57c5dfce3506c03e2c5899
Java
pradyot-09/NegotiationAgent
/src/ai2017/Group19.java
UTF-8
4,221
2.296875
2
[]
no_license
package ai2017; import java.util.List; import negotiator.AgentID; import negotiator.Bid; import negotiator.Deadline; import negotiator.actions.Accept; import negotiator.actions.Action; import negotiator.actions.Offer; import negotiator.bidding.BidDetails; import negotiator.parties.AbstractNegotiationParty; import negotiator.parties.NegotiationInfo; import negotiator.persistent.PersistentDataContainer; import negotiator.timeline.TimeLineInfo; import negotiator.utility.AbstractUtilitySpace; import negotiator.boaframework.Actions; import negotiator.boaframework.SortedOutcomeSpace; import ai2017.SessionInfo; import ai2017.NegoStrat; /** * This is your negotiation party. */ public class Group19 extends AbstractNegotiationParty { private Bid lastReceivedBid = null; private AgentID lastSender = null; private SortedOutcomeSpace sortedOutcome; private SessionInfo sessionInfo; private NegoStrat negoStrat; private int cnt = 0; @Override public void init(NegotiationInfo info) { super.init(info); System.out.println("Discount Factor is " + info.getUtilitySpace().getDiscountFactor()); System.out.println("Reservation Value is " + info.getUtilitySpace().getReservationValueUndiscounted()); // if you need to initialize some variables, please initialize them below sortedOutcome = new SortedOutcomeSpace(info.getUtilitySpace()); sessionInfo = new SessionInfo(info.getUtilitySpace(), info.getTimeline(), sortedOutcome); negoStrat = new NegoStrat(sessionInfo); } /** * @param validActions * Either a list containing both accept and offer or only offer. * @return The chosen action. */ @Override public Action chooseAction(List<Class<? extends Action>> validActions) { BidDetails nextBid; if(lastReceivedBid == null || !validActions.contains(Accept.class)) { nextBid = negoStrat.determineOpeningBid(); return new Offer(getPartyId(), nextBid.getBid()); } else { //double prevMaxUtil = 0; //if(nextBid.getMyUndiscountedUtil() < prevMaxUtil) //determine next bid AgentID nextAgent = null; int nextOrderIdx = (sessionInfo.getOpponents().get(lastSender).getOrder() == sessionInfo.getOpponents().size()-1)? 0:sessionInfo.getOpponents().get(lastSender).getOrder()+1; for (AgentID agent:sessionInfo.getOpponents().keySet()) { if(sessionInfo.getOpponents().get(agent).getOrder() == nextOrderIdx) { nextAgent = agent; break; } } nextBid = negoStrat.determineNextBid(lastSender, nextAgent); if(lastReceivedBid != null && (negoStrat.myAcceptanceStrategy(lastReceivedBid, nextBid) == Actions.Accept)) { return new Accept(getPartyId(), lastReceivedBid); } else { sessionInfo.getMyBidHistory().add(nextBid); return new Offer(getPartyId(), nextBid.getBid()); } } } /** * All offers proposed by the other parties will be received as a message. * You can use this information to your advantage, for example to predict * their utility. * * @param sender * The party that did the action. Can be null. * @param action * The action that party did. */ @Override public void receiveMessage(AgentID sender, Action action) { super.receiveMessage(sender, action); if (action instanceof Offer) { lastReceivedBid = ((Offer) action).getBid(); lastSender = sender; } if(sender == null) return; if(!sessionInfo.getOpponents().containsKey(sender)) { OpponentModel o = new OpponentModel(sessionInfo,sender); if (action instanceof Offer) { o.addBidToHistory(lastReceivedBid); } else if(action instanceof Accept) { o.addAcceptedBid(lastReceivedBid); } o.setOrder(cnt); sessionInfo.getOpponents().put(sender, o); cnt += 1; } else { if (action instanceof Offer) { sessionInfo.getOpponents().get(sender).addBidToHistory(lastReceivedBid); if(sessionInfo.getOpponents().get(sender).getBidHistory().size() <= 100){ sessionInfo.getOpponents().get(sender).updateModel(); } } else if(action instanceof Accept) { sessionInfo.getOpponents().get(sender).addAcceptedBid(lastReceivedBid); } } } @Override public String getDescription() { return "agent group 19"; } }
true
0a5a4976550da620e2ee646290fc1b495d3ad243
Java
chinthakadd/fast-money-transfer
/src/main/java/com/chinthakad/samples/fmt/api/AccountHandlerProvider.java
UTF-8
4,701
2.265625
2
[]
no_license
package com.chinthakad.samples.fmt.api; import com.chinthakad.samples.fmt.core.model.dto.AccountListHolder; import com.chinthakad.samples.fmt.core.model.dto.TransferListHolder; import com.chinthakad.samples.fmt.core.model.dto.TransferRequestDto; import com.chinthakad.samples.fmt.seedwork.queue.AccountSvcMessage; import com.chinthakad.samples.fmt.seedwork.queue.QueueConfig; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.Message; import io.vertx.core.json.Json; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import lombok.extern.slf4j.Slf4j; @Slf4j public class AccountHandlerProvider { private Vertx vertx; public AccountHandlerProvider(Vertx vertx) { this.vertx = vertx; } public Handler<RoutingContext> getAccounts() { return routingContext -> { log.info("GET /accounts"); vertx.eventBus().request(QueueConfig.CONFIG_ACCOUNT_SERVICE_QUEUE, AccountSvcMessage.builder().action(AccountSvcMessage.ActionType.LIST_ACCOUNTS).build(), (Handler<AsyncResult<Message<AccountListHolder>>>) reply -> { if (reply.succeeded()) { JsonArray accountAry = new JsonArray(); reply.result().body().getAccounts() .stream().forEach( account -> accountAry.add( new JsonObject().put("accountNumber", account.getAccountNumber()) .put("name", account.getDisplayName()) .put("availableBalance", account.getAvailableBalance().toPlainString()) .put("currentBalance", account.getCurrentBalance().toPlainString()) .put("lastUpdatedOn", account.getLastUpdatedTimestamp()) ) ); routingContext.response().end(Json.encodePrettily(accountAry)); } else { // TODO: Handle error. // TODO: Lets adopt JSEND. reply.cause().printStackTrace(); routingContext.fail(500); } }); }; } public Handler<RoutingContext> transferMoney() { return routingContext -> { log.info("POST /accounts/transfers"); // TODO: Dont use TransferRequest. Use a presentation DTO. routingContext.request().bodyHandler(reqBuf -> { TransferRequestDto transferRequest = Json.decodeValue(reqBuf, TransferRequestDto.class); log.info("received request: {}", transferRequest); vertx.eventBus() .request( QueueConfig.CONFIG_ACCOUNT_SERVICE_QUEUE, AccountSvcMessage.builder().action(AccountSvcMessage.ActionType.TRANSFER).data(transferRequest).build(), // TODO: Payload can be made better. (Handler<AsyncResult<Message<Boolean>>>) reply -> { if (reply.succeeded()) { Boolean response = reply.result().body(); log.info("RESPONSE: {}", response); if (response) { routingContext.response().setStatusCode(202).end(); } else { routingContext.fail(500); } } else { reply.cause().printStackTrace(); routingContext.fail(500); } }); }); }; } public Handler<RoutingContext> getTransfers() { return routingContext -> { log.info("GET /accounts/transfers"); vertx.eventBus().request(QueueConfig.CONFIG_ACCOUNT_SERVICE_QUEUE, AccountSvcMessage.builder().action(AccountSvcMessage.ActionType.LIST_TRANSFERS).build(), (Handler<AsyncResult<Message<TransferListHolder>>>) reply -> { if (reply.succeeded()) { JsonArray transfersAry = new JsonArray(); reply.result().body().getTransfers() .stream().forEach( transfer -> transfersAry.add( new JsonObject().put("id", transfer.getId()) .put("fromAccountNumber", transfer.getFromAccount().getAccountNumber()) .put("toAccountNumber", transfer.getToAccount().getAccountNumber()) .put("amount", transfer.getAmount().toPlainString()) .put("status", transfer.getTransferStatus().name()) .put("lastUpdatedOn", transfer.getLastUpdatedTimestamp()) ) ); routingContext.response().end(Json.encodePrettily(transfersAry)); } else { // TODO: Handle error. // TODO: Lets adopt JSEND. reply.cause().printStackTrace(); routingContext.fail(500); } }); }; } }
true
62da294839ff023e508cbea25dbc2408f1c4b3a4
Java
chenjie112358/my20201218
/socialnetworkanalysis.java
UTF-8
624
2.578125
3
[]
no_license
class SocialNetworkAnalysis { public static void main(String[] args) { String questionStatus = "XX"; System.out.print("For the STATUS I chose question " + questionStatus + " and my answer is: "); System.out.println("NONE"); String questionUser = "XX"; System.out.print("For the USER I chose question "+ questionUser + " and my answer is: "); System.out.println("NONE"); String questionLocation = "XX"; System.out.print("For the LOCATION I chose question " + questionLocation + " and my answer is: "); System.out.println("NONE"); } }
true
2da829579b0a6e088936382b7f6d3158c5d4410a
Java
julianGoh17/DistributedBlackboxOperations
/gossip/src/test/java/io/julian/gossip/models/SynchronizeUpdateTest.java
UTF-8
2,717
2.421875
2
[]
no_license
package io.julian.gossip.models; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.junit.Assert; import org.junit.Test; import tools.AbstractHandlerTest; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; public class SynchronizeUpdateTest extends AbstractHandlerTest { private final static JsonObject MESSAGE = new JsonObject().put("nested", new JsonObject().put("json", "object")); private final static int ITEMS = 2; @Test public void TestToJson() { List<MessageUpdate> messages = new ArrayList<>(); Set<String> deletedIdsSet = new HashSet<>(); SynchronizeUpdate update = new SynchronizeUpdate(messages, deletedIdsSet); for (int i = 0; i < ITEMS; i++) { messages.add(new MessageUpdate(UUID.randomUUID().toString(), MESSAGE)); deletedIdsSet.add(UUID.randomUUID().toString()); } JsonObject json = update.toJson(); JsonArray messageUpdates = json.getJsonArray("messages"); JsonArray deletedIds = json.getJsonArray("deletedIds"); Assert.assertEquals(ITEMS, messageUpdates.size()); for (int i = 0; i < ITEMS; i++) { Assert.assertEquals(messages.get(i).getMessageId(), messageUpdates.getJsonObject(i).getString(MessageUpdate.MESSAGE_ID_KEY)); Assert.assertEquals(MESSAGE.encodePrettily(), messageUpdates.getJsonObject(i).getJsonObject(MessageUpdate.MESSAGE_KEY).encodePrettily()); } Assert.assertEquals(ITEMS, deletedIds.size()); for (int i = 0; i < ITEMS; i++) Assert.assertTrue(deletedIdsSet.contains(deletedIds.getString(i))); } @Test public void TestFromJson() { JsonArray messages = new JsonArray(); for (int i = 0; i < ITEMS; i++) messages.add(new MessageUpdate(UUID.randomUUID().toString(), MESSAGE).toJson()); JsonArray deletedIds = new JsonArray(); for (int i = 0; i < ITEMS; i++) deletedIds.add(UUID.randomUUID().toString()); JsonObject json = new JsonObject() .put("messages", messages) .put("deletedIds", deletedIds); SynchronizeUpdate update = SynchronizeUpdate.fromJson(json); Assert.assertEquals(2, update.getDeletedIds().size()); for (int i = 0; i < ITEMS; i++) { Assert.assertTrue(update.getDeletedIds().contains(deletedIds.getString(i))); } Assert.assertEquals(2, update.getMessages().size()); for (int i = 0; i < ITEMS; i++) { Assert.assertEquals(messages.getJsonObject(i).encodePrettily(), update.getMessages().get(i).toJson().encodePrettily()); } } }
true
55a2e026a0d49c2acf33cdb71a3908b0b4f925af
Java
KrivonosMS/otus-spring-framework-2020-02
/homework-02/src/main/java/ru/otus/krivonos/exam/infrastructore/ScanReader.java
UTF-8
114
1.75
2
[]
no_license
package ru.otus.krivonos.exam.infrastructure; public interface ScanReader { String nextLine(); void close(); }
true
200663bbd8474f5114cbd14340a5d06c616559d0
Java
sagarnikam123/learnNPractice
/codeChef/src/medium/unsolved/PowerfulSum.java
UTF-8
837
3.3125
3
[ "MIT" ]
permissive
/** The powerful sum Let us calculate the sum of k-th powers of natural numbers from 1 to n. As the result can be quite large, output the result modulo some integer p. Input First t<=10 - the number of test cases. Each test case consist of numbers: 1<=n<=1000000000, 1<=k<=100, 1<=p<=1000000000. Output For each test case, output the value: (1k+2k+...+nk) mod p. *********************************************************************************************************************** Example For input: 4 10 1 1000000 10 2 1000000 10 3 1000000 10 4 1000000 the correct output is: 55 385 3025 25333 **********************************************************************************************************************/ package medium.unsolved; public class PowerfulSum { public static void main(String[] args) { } }
true
846327254f71399d153892ffdeb95fc345d94f03
Java
wuranjia/mercury
/src/main/java/com/hy/lang/mercury/service/impl/SmsService.java
UTF-8
5,019
1.945313
2
[]
no_license
package com.hy.lang.mercury.service.impl; import com.hy.lang.mercury.client.cmpp.mina.cmpp.client.SmsSendService; import com.hy.lang.mercury.client.ws.SmsStatus; import com.hy.lang.mercury.common.Constants; import com.hy.lang.mercury.common.entity.PageList; import com.hy.lang.mercury.dao.SmsDeliverMapper; import com.hy.lang.mercury.dao.SmsInfoMapper; import com.hy.lang.mercury.dao.SmsViewMapper; import com.hy.lang.mercury.pojo.SmsDeliver; import com.hy.lang.mercury.pojo.SmsInfo; import com.hy.lang.mercury.pojo.SmsView; import com.hy.lang.mercury.pojo.enums.SmsViewType; import com.hy.lang.mercury.resource.req.MatrixReq; import com.hy.lang.mercury.resource.req.SmsDeliverReq; import com.hy.lang.mercury.resource.req.SmsInfoReq; import com.hy.lang.mercury.resource.req.SmsViewReq; import com.hy.lang.mercury.resource.resp.MatrixResp; import com.hy.lang.mercury.service.SmsAble; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class SmsService implements SmsAble { @Autowired private SmsInfoMapper smsInfoMapper; @Autowired private SmsDeliverMapper smsDeliverMapper; @Autowired private SmsSendService smsSendService; @Autowired private SmsViewMapper smsViewMapper; /** * 发消息 * * @param receiveIds 逗号分隔 * @param smsContent 消息内容 * @param userId 用户ID * @return */ @Override public int sendSms(String receiveIds, String smsContent, Long userId) { String[] receivedArray = StringUtils.split(receiveIds, Constants.分号); if (userId == null) userId = Constants.L_负_1; //调用client,发送消息 int i = 0; try { for (String dest : receivedArray) { SmsInfo smsInfo = new SmsInfo(dest, smsContent, userId, null); int seq = smsInfoMapper.insert(smsInfo); smsViewMapper.insert(new SmsView(smsInfo.getSmsId(), dest, smsContent, SmsViewType.发送, SmsStatus.发送中.name())); int requestId = smsSendService.send(dest, smsInfo.getSmsId(), smsContent); smsInfoMapper.updateSmsOtherNo(smsInfo.getSmsId(), String.valueOf(requestId)); i = i + seq; } } catch (Exception e) { e.printStackTrace(); } //组装消息体,落地 return i; } @Override public PageList<SmsInfo> listSms(SmsInfoReq smsInfoReq, Long userId) { smsInfoReq.setUserId(userId); int total = smsInfoMapper.countByParams(smsInfoReq); //查询 List<SmsInfo> list = smsInfoMapper.selectByParams(smsInfoReq); PageList<SmsInfo> pageList = new PageList<SmsInfo>(); pageList.setCurrent(smsInfoReq.getPage()); pageList.setPageSize(smsInfoReq.getLimit()); pageList.setDraw(smsInfoReq.getDraw()); pageList.setTotal(total); pageList.setItems(list); return pageList; } @Override public PageList<SmsDeliver> listSms(SmsDeliverReq smsInfoReq, Long userId) { smsInfoReq.setUserId(userId); int total = smsDeliverMapper.countByParams(smsInfoReq); //查询 List<SmsDeliver> list = smsDeliverMapper.selectByParams(smsInfoReq); PageList<SmsDeliver> pageList = new PageList<SmsDeliver>(); pageList.setCurrent(smsInfoReq.getPage()); pageList.setPageSize(smsInfoReq.getLimit()); pageList.setDraw(smsInfoReq.getDraw()); pageList.setTotal(total); pageList.setItems(list); return pageList; } @Override public int updateSms(Long smsId, SmsStatus status) { return smsInfoMapper.updateSmsStatus(smsId, status.getCode()); } @Override public PageList<SmsView> listView(SmsViewReq smsViewReq) { int total = smsViewMapper.countByParams(smsViewReq); List<SmsView> list = smsViewMapper.selectByParams(smsViewReq); PageList<SmsView> pageList = new PageList<SmsView>(); pageList.setCurrent(smsViewReq.getPage()); pageList.setPageSize(smsViewReq.getLimit()); pageList.setDraw(smsViewReq.getDraw()); pageList.setTotal(total); pageList.setItems(list); return pageList; } @Override public Map<String, String[]> matrix(MatrixReq req) { List<MatrixResp> list = smsInfoMapper.matrix(req.getUserId()); String[] day = new String[list.size()]; String[] num = new String[list.size()]; for (int i = 0; i < list.size(); i++) { MatrixResp matrixResp = list.get(i); day[i] = matrixResp.getDay(); num[i] = matrixResp.getNum(); } Map<String, String[]> result = new HashMap<String, String[]>(); result.put("day", day); result.put("num", num); return result; } }
true
25cdd829cbe6dfbfe0bd6047e3dcf8ccdc12a219
Java
744719042/MyApp
/order/src/main/java/com/example/order/adapter/OrderAdapter.java
UTF-8
1,253
2.21875
2
[]
no_license
package com.example.order.adapter; import android.content.Context; import android.widget.ImageView; import com.example.base.recycler.BaseRecyclerAdapter; import com.example.base.recycler.BaseRecyclerViewHolder; import com.example.imagefetcher.ImageFetcher; import com.example.order.R; import com.example.order.model.Order; import com.example.provider.ImageFetcherProvider; import java.util.List; public class OrderAdapter extends BaseRecyclerAdapter<Order> { public OrderAdapter(List<Order> data, Context context) { super(data, context, R.layout.order_item); } @Override protected void bindView(BaseRecyclerViewHolder holder, Order order, int position) { holder.setText(R.id.shop_name, order.getName()); holder.setText(R.id.order_status, order.getStatus()); holder.setText(R.id.goods_name, order.getGoodsName()); holder.setText(R.id.order_time, order.getOrderTime()); holder.setText(R.id.total_price, order.getTotalPrice()); ImageView imageView = holder.getView(R.id.image); ImageFetcher imageFetcher = ImageFetcherProvider.getInstance().getImageFetcher(); imageFetcher.load(order.getUrl()).placeHolder(R.drawable.order_place_holder).into(imageView); } }
true
ac77c30ccbb0326af09963f14eb7e8582afc74cb
Java
nitishgoyal13/revolver
/revolver-model/src/main/java/io/dropwizard/revolver/optimizer/utils/OptimizerUtils.java
UTF-8
2,815
2.1875
2
[ "Apache-2.0" ]
permissive
package io.dropwizard.revolver.optimizer.utils; import com.google.common.collect.Lists; import io.dropwizard.revolver.optimizer.config.OptimizerConcurrencyConfig; import io.dropwizard.revolver.optimizer.config.OptimizerConfig; import io.dropwizard.revolver.optimizer.config.OptimizerConfigUpdaterConfig; import io.dropwizard.revolver.optimizer.config.OptimizerMetricsCollectorConfig; import io.dropwizard.revolver.optimizer.config.OptimizerTimeConfig; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /*** Created by nitish.goyal on 29/03/19 ***/ public class OptimizerUtils { public static final String ROLLING_MAX_ACTIVE_THREADS = "rollingMaxActiveThreads"; public static final String THREAD_POOL_PREFIX = "HystrixThreadPool"; public static final String LATENCY_PERCENTILE_99 = "latencyExecute_percentile_99"; public static final String LATENCY_PERCENTILE_995 = "latencyExecute_percentile_995"; public static final String LATENCY_PERCENTILE_50 = "latencyExecute_percentile_50"; public static final String LATENCY_PERCENTILE_75 = "latencyExecute_percentile_75"; private static final List<String> METRICS_TO_READ = Lists .newArrayList("propertyValue_maximumSize", ROLLING_MAX_ACTIVE_THREADS); public static List<String> getMetricsToRead() { return Collections.unmodifiableList(METRICS_TO_READ); } public static OptimizerConfig getDefaultOptimizerConfig() { return OptimizerConfig.builder().initialDelay(2).timeUnit(TimeUnit.MINUTES) .concurrencyConfig( OptimizerConcurrencyConfig.builder().bandwidth(1.4).minThreshold(0.5) .maxThreshold(0.85).enabled(true).maxPoolExpansionLimit(1.8).build()) .configUpdaterConfig(OptimizerConfigUpdaterConfig.builder().repeatAfter(2) .timeUnit(TimeUnit.MINUTES).build()).metricsCollectorConfig( OptimizerMetricsCollectorConfig.builder().repeatAfter(30) .timeUnit(TimeUnit.SECONDS).cachingWindowInMinutes(15) .concurrency(3).build()).timeConfig( OptimizerTimeConfig.builder().allMethodTimeoutBuffer(1.5) .getMethodTimeoutBuffer(1.3).latencyMetrics( Lists.newArrayList(LATENCY_PERCENTILE_99, LATENCY_PERCENTILE_995, LATENCY_PERCENTILE_50, LATENCY_PERCENTILE_75)) .timeoutMetric(LATENCY_PERCENTILE_99) .apiLatencyMetric(LATENCY_PERCENTILE_75) .appLatencyMetric(LATENCY_PERCENTILE_995).build()).enabled(true) .build(); } }
true
85679e2af1f870d6d6670c2335eac3b26d150faa
Java
phamvanhai-auto/mvn-hybrid-mixproject
/src/main/java/pageUIs/hrm/MyInfoUI.java
UTF-8
444
1.515625
2
[]
no_license
package pageUIs.hrm; public class MyInfoUI { public static final String EMPLOYEE_LIST_LINK = "//a[normalize-space()='Employee List']"; public static final String CHANGE_AVATAR = "//img[@id='empPic']"; public static final String SELECT_PICTURE = "//input[@id='photofile']"; public static final String AVATAR_IMG = "//img[@id='empPic']"; public static final String ITEMS_AT_SIDEBAR_BY_NAME = "//div[@id='sidebar']//a[text()='%s']"; }
true
b198ff4a1057b393d72a116a4408fa05c19a3fe8
Java
yeoman-projects/generator-jhipster-file-handling
/generators/app/templates/src/test/java/package/internal/model/sampleDataModel/CurrencyTableMapperTest.java
UTF-8
613
1.976563
2
[ "Apache-2.0" ]
permissive
package <%= packageName %>.internal.model.sampleDataModel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class CurrencyTableMapperTest { private CurrencyTableMapper currencyTableMapper; @BeforeEach public void setUp() { currencyTableMapper = new CurrencyTableMapperImpl(); } @Test public void testEntityFromId() { Long id = 1L; assertThat(currencyTableMapper.fromId(id).getId()).isEqualTo(id); assertThat(currencyTableMapper.fromId(null)).isNull(); } }
true
10f1632be07ad00fd42c07b306f2c990c4595bd2
Java
hkmujj/looker-core
/looker-core/src/main/java/com/looker/core/controller/GfaAuthController.java
UTF-8
8,225
2.296875
2
[]
no_license
package com.looker.core.controller; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.looker.core.util.DateUtils; import com.niwodai.tech.base.util.StringUtil; /** * 给数据平台提供的接口 * 主要功能是:数据平台传递授权码和产品编码两个参数,在产品授权表中筛选出对应的产品是否授权,授权是否过期、授权次数这些结果 * */ @Controller public class GfaAuthController { private final Log logger = LogFactory.getLog(getClass()); @ResponseBody @RequestMapping("/gfaAuth") public JSONObject gfaAuth(HttpServletRequest request,HttpServletResponse response) throws Exception{ JSONObject retJson = new JSONObject(); int resCode = 0; String resMsg = "success"; //授权码 String authCode = request.getParameter("authCode"); //产品编码 String productCode = request.getParameter("productCode"); logger.info("authCode为["+authCode + "]-------------productCode为["+productCode+"],身份认证"); try { if(StringUtil.isEmpty(authCode)){ retJson.put("resCode", -1001); retJson.put("resMsg", "授权码为空!"); return retJson; } //查询出产品授权表中所有对应的authCode的记录 Map<String, Object> params = new HashMap<String, Object>(); params.put("authCode", authCode); params.put("notInStates", "2");//授权未停用的 params.put("state", "9");//已开通的才可用 //params.put("authTime", DateUtils.getDate(new Date()));//当前时间是不是在授权时间内 List<Map<String, Object>> productList = new ArrayList<Map<String,Object>>(); //根据授权码未获取到授权记录 if(productList == null || productList.size() <= 0){ logger.info("----------对应authCode["+authCode + "]没有授权,或者授权了但是未开通----------"); retJson.put("resCode", -1001); retJson.put("resMsg", "身份验证失败!"); return retJson; }else{ if(StringUtil.isEmpty(productCode)){ retJson.put("resCode", -1001); retJson.put("resMsg", "产品编码为空!"); return retJson; } //移除list中不包含当前参数中productCode的记录 removeProuctList(productList,productCode); //获得新的List,只包含当前productCode的记录 if(productList != null && productList.size() >0){ //先判断有没有过期的 if(isProductExpire(productList,productCode)){ resCode = -1003; resMsg = "授权时间过期!"; }else{ Map<String, Object> data = new HashMap<String, Object>(); //授权可能有多条,但是在当前时间内的一定只有一条,这个list中只有一条数据,如果出现多条选择最新的一条 if(productList != null && productList.size() > 0){ String authNum = (String)productList.get(0).get("AUTH_NUM"); String channelCode = (String)productList.get(0).get("CHANNEL_CODE"); String channelName = (String)productList.get(0).get("CHANNEL_NAME"); //可调用次数 Long totalCount = (Long)productList.get(0).get("TOTAL_COUNT"); if(isProductAuthorize(authNum,channelCode,productCode,totalCount)){ resCode = -1004; resMsg = "授权次数不足!"; }else{ data.put("channelCode", channelCode); data.put("channelName", channelName); retJson.put("data", data); } //在正确的数据情况下以下的情况不会出现 }else{ resCode = -2; resMsg = "授权异常!"; logger.error("授权记录出错,请查看authCode为["+authCode + "],productCode为["+productCode+"]的授权记录"); } if(productList != null && productList.size() > 1){ logger.error("授权记录出错,请查看authCode为["+authCode + "],productCode为["+productCode+"]的授权记录,有效时间内授权了多次!"); } } }else{ logger.info("当前产品["+productCode+"]未授权"); resCode = -1002; resMsg = "权限不足!"; } } } catch (Exception e) { resCode = -2; resMsg = "系统异常!"; logger.error(e); } retJson.put("resCode", resCode); retJson.put("resMsg", resMsg); return retJson; } /** * 通过筛选把包含参数中的productCode的记录留下,其余的去除掉 */ private void removeProuctList(List<Map<String, Object>> productList,String productCode){ List<Map<String, Object>> removeList = new ArrayList<Map<String,Object>>(); for(Map<String, Object> mangerInfo : productList){ String pCode = (String)mangerInfo.get("PRODUCT_CODE"); if(!pCode.equalsIgnoreCase(productCode)){ removeList.add(mangerInfo); } } productList.removeAll(removeList); } /** * 校验当前产品授权中对应的产品是否过期 * @param productList * @param productCode * @return */ private boolean isProductExpire(List<Map<String, Object>> productList,String productCode) throws Exception{ boolean isExpire = true; //当前时间 String date = DateUtils.getDate(new Date()); List<Map<String, Object>> removeList = new ArrayList<Map<String,Object>>(); for(Map<String, Object> mangerInfo : productList){ //产品编码 String pCode = (String)mangerInfo.get("PRODUCT_CODE"); //授权开始时间 String authBeginTime = (String)mangerInfo.get("AUTH_BEGIN_TIME"); //授权结束时间 String authEndTime = (String)mangerInfo.get("AUTH_END_TIME"); //匹配产品编码 if(pCode.equalsIgnoreCase(productCode)){ //如果产品存在,判断有没有过期 //比较当前授权的是否过期 if(date.compareTo(authBeginTime) >= 0 && date.compareTo(authEndTime) <= 0){ isExpire = false; }else{ removeList.add(mangerInfo); } } } productList.removeAll(removeList);//再次移除掉过期的记录 return isExpire; } /** * 判断当前授权次数还够不够 * @param authNum 授权次数 * @param channelCode * @param productCode * @param usedCount 可调用次数 * @return boolean isUsedUp */ private boolean isProductAuthorize(String authNum,String channelCode,String productCode,Long totalCount){ boolean isUsedUp = false; //-1是无限次 if((Long.valueOf(authNum) == -1 || Long.valueOf(authNum) > 0) && totalCount > 0 ){ //没有过期则比较接口调用次数有没有超过总次数 Map<String, Object> statisParams = new HashMap<String, Object>(); statisParams.put("channelCode", channelCode); statisParams.put("productCode", productCode); List<Map<String, Object>> queryStatistics = new ArrayList<Map<String, Object>>(); if(queryStatistics != null && queryStatistics.size() > 0){ //已调用次数 BigDecimal usedCount = (BigDecimal) queryStatistics.get(0).get("totalCount"); //次数没有用完可以继续 if((Long.valueOf(authNum) == -1 || new BigDecimal(authNum).compareTo(usedCount) == 1) && new BigDecimal(totalCount).compareTo(usedCount) == 1){ isUsedUp = false; logger.info("----------授权次数上限["+authNum+"],已购买次数["+totalCount+"],已使用次数["+usedCount+"]"); }else{ logger.info("----------授权使用次数已达上限["+authNum+"],或者已购买次数["+totalCount+"]已经用完,已用["+usedCount+"]次----------"); isUsedUp = true; } }else{//如果没有数据说明一次也没调用过,并且也授权次数有,可以通过,数据平台在调用成功之后会insert记录到数据库里 isUsedUp = false; } }else{ isUsedUp = true; } return isUsedUp; } }
true
b76ffd443c466f6114958bc95338f54a10831e34
Java
YuryHuseu/restTest
/JAX-RS-SERVER-PROJECT/src/main/java/com/rest/server/testData/TestData.java
UTF-8
140
1.609375
2
[]
no_license
package com.rest.server.testData; import java.util.List; public interface TestData<T> { List<T> getEntities(); T getEntity(); }
true
9e136fa858176e0d55d9bb4f9faa0b1c0f3a8a39
Java
echirinosmayaudon/DAG-RICHIESTA-BADGE
/dag-intranet-20/modules/scadenze-badge/scadenze-badge-api/src/main/java/com/intranet/mef/scadenze/badge/costants/ScadenzeBadgeDestinationNames.java
UTF-8
182
1.609375
2
[]
no_license
package com.intranet.mef.scadenze.badge.costants; public class ScadenzeBadgeDestinationNames { public static final String SCADENZE_BADGE = "intranet/mef/scadenze_badge"; }
true
97bc2edb95e8ae2d454ef97e51917c74632977c8
Java
gabrysg/restaurant
/src/main/java/com/restaurant/controller/RestaurantExceptionController.java
UTF-8
1,901
2.28125
2
[]
no_license
package com.restaurant.controller; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.mail.MailSendException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.restaurant.exception.RestaurantException; import lombok.extern.slf4j.Slf4j; @ControllerAdvice @Slf4j public class RestaurantExceptionController { @ExceptionHandler(MessagingException.class) public void handleMessagingException(MessagingException ex) { log.error("MessagingException occured.", ex); } @ExceptionHandler(MailSendException.class) public ModelAndView handleMailSendException(MailSendException ex) { log.error("MailSendException occured. {}, {}", ex.getMessage(), ex.getFailedMessages().toString()); log.debug("RestaurantException with reason={}", ex.getMessage()); ModelAndView mav = new ModelAndView(); mav.addObject("exception", ex); mav.addObject("status", HttpStatus.BAD_REQUEST); mav.addObject("message", ex.getFailedMessages().toString()); mav.setViewName("error"); return mav; } @ExceptionHandler(RestaurantException.class) public ModelAndView handleRestaurantException(HttpServletRequest request, RestaurantException ex) { log.info("RestaurantException occured:: URL={}", request.getRequestURL()); log.debug("RestaurantException with reason={}", ex.getMessage(), ex); ModelAndView mav = new ModelAndView(); mav.addObject("exception", ex); mav.addObject("status", ex.getStatus()); mav.setViewName("error"); return mav; } @ExceptionHandler(Exception.class) public String handleException(HttpServletRequest request, Exception ex) { log.info("Exception occured:: URL={}", request.getRequestURL()); return "error"; } }
true
5189bc282f50ca4e342a3306f053c3bfecc0812b
Java
anboralabs/gps-component
/gps-component/src/main/java/co/anbora/component/location/UtilPermission.java
UTF-8
578
2.109375
2
[ "MIT" ]
permissive
package co.anbora.component.location; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import androidx.core.content.ContextCompat; /** * Created by dalgarins on 03/10/18. */ public class UtilPermission { private UtilPermission(){ } /** * Check location permission * @return */ public static boolean checkLocationPermission(Context context) { return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } }
true
23e07d765409c50a57f7098c729242741b492049
Java
haniyeka/QBF_Experiments
/QBF_solve_inst/feature_extraction/QbfFeatureDistribution.java
UTF-8
2,001
2.0625
2
[]
no_license
/* QbfFeatureDistribution - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ class QbfFeatureDistribution extends Feature { public QbfFeatureDistribution() { feature_.put("EXIST_LIT_PER_CLAUSE", new Integer(0)); feature_.put("FORALL_LIT_PER_CLAUSE", new Integer(1)); feature_.put("LIT_PER_CLAUSE", new Integer(2)); feature_.put("VARS_PER_SET", new Integer(3)); feature_.put("EXIST_VARS_PER_SET", new Integer(4)); feature_.put("FORALL_VARS_PER_SET", new Integer(5)); feature_.put("POS_LITS_PER_CLAUSE", new Integer(6)); feature_.put("FORALL_POS_LITS_PER_CLAUSE", new Integer(7)); feature_.put("EXIST_POS_LITS_PER_CLAUSE", new Integer(8)); feature_.put("NEG_LITS_PER_CLAUSE", new Integer(9)); feature_.put("FORALL_NEG_LITS_PER_CLAUSE", new Integer(10)); feature_.put("EXIST_NEG_LITS_PER_CLAUSE", new Integer(11)); feature_.put("OCCS_NO_PER_VAR", new Integer(12)); feature_.put("OCCS_POS_NO_PER_VAR", new Integer(13)); feature_.put("OCCS_NEG_NO_PER_VAR", new Integer(14)); feature_.put("OCCS_EXIST_NO_PER_VAR", new Integer(15)); feature_.put("OCCS_FORALL_NO_PER_VAR", new Integer(16)); feature_.put("OCCS_EXIST_POS_NO_PER_VAR", new Integer(17)); feature_.put("OCCS_EXIST_NEG_NO_PER_VAR", new Integer(18)); feature_.put("OCCS_FORALL_POS_NO_PER_VAR", new Integer(19)); feature_.put("OCCS_FORALL_NEG_NO_PER_VAR", new Integer(20)); feature_.put("W_OCCS_NO_PER_VAR", new Integer(21)); feature_.put("W_OCCS_POS_NO_PER_VAR", new Integer(22)); feature_.put("W_OCCS_NEG_NO_PER_VAR", new Integer(23)); feature_.put("W_OCCS_EXIST_NO_PER_VAR", new Integer(24)); feature_.put("W_OCCS_FORALL_NO_PER_VAR", new Integer(25)); feature_.put("W_OCCS_EXIST_POS_NO_PER_VAR", new Integer(26)); feature_.put("W_OCCS_EXIST_NEG_NO_PER_VAR", new Integer(27)); feature_.put("W_OCCS_FORALL_POS_NO_PER_VAR", new Integer(28)); feature_.put("W_OCCS_FORALL_NEG_NO_PER_VAR", new Integer(29)); feature_.put("PRODUCTS", new Integer(30)); feature_.put("W_PRODUCTS", new Integer(31)); } }
true
c4a3e554665a03f2c07b98ad451ee5a6d18f7459
Java
MrWen1991/myproject
/src/main/java/top/winkin/http/Method.java
UTF-8
99
1.6875
2
[]
no_license
package top.winkin.http; /** */ public enum Method { //目前仅支持两个 POST, GET }
true
21f473299a38ceb5b03198ba01285d7a69cec41e
Java
honeyflyfish/com.tencent.mm
/src/com/tencent/mm/plugin/sns/i/a/a/a/c$a$3$1$1.java
UTF-8
664
1.53125
2
[]
no_license
package com.tencent.mm.plugin.sns.i.a.a.a; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; final class c$a$3$1$1 implements Animation.AnimationListener { c$a$3$1$1(c.a.3.1 param1) {} public final void onAnimationEnd(Animation paramAnimation) { hft.hfs.hfr.setAlpha(0.0F); } public final void onAnimationRepeat(Animation paramAnimation) {} public final void onAnimationStart(Animation paramAnimation) {} } /* Location: * Qualified Name: com.tencent.mm.plugin.sns.i.a.a.a.c.a.3.1.1 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
a60c17778f3ff1e10216cc53495b4110575db754
Java
nirvanarsc/EPI
/epi/HonorsClass/RotateArray.java
UTF-8
1,077
2.6875
3
[]
no_license
package epi.HonorsClass; import java.util.ArrayList; import java.util.Collections; import java.util.List; import epi.test_framework.EpiTest; import epi.test_framework.TimedExecutor; import epi.utils.TestRunner; public final class RotateArray { public static void rotateArray(int rotateAmount, List<Integer> list) { rotateAmount %= list.size(); Collections.reverse(list); Collections.reverse(list.subList(0, rotateAmount)); Collections.reverse(list.subList(rotateAmount, list.size())); } @EpiTest(testDataFile = "rotate_array.tsv") public static List<Integer> rotateArrayWrapper(TimedExecutor executor, List<Integer> list, int rotateAmount) throws Exception { final List<Integer> aCopy = new ArrayList<>(list); executor.run(() -> rotateArray(rotateAmount, aCopy)); return aCopy; } public static void main(String[] args) { TestRunner.run(args); } private RotateArray() {} }
true