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
3989041b22719c7abbe2a3f82359b8973ecab046
Java
hymss/Tetris-Agent
/PlayerSkeleton.java
UTF-8
7,264
3.140625
3
[]
no_license
import java.util.Arrays; public class PlayerSkeleton { // another State object to simulate the moves before actually playing private StateSimulator simulator; public PlayerSkeleton() { simulator = new StateSimulator(); } //implement this function to have a working system public int pickMove(State s, int[][] legalMoves) { int moveToPlay = getBestMoveBySimulation(s, legalMoves.length); System.out.println("Move to Play = " + moveToPlay); simulator.makeMove(moveToPlay); simulator.markSimulationDoneWithCurrentPiece(); return moveToPlay; } /** * @param actualState the actual state with which the game runs * @param moveChoices the legal moves allowed * @return the best move */ public int getBestMoveBySimulation(State actualState, int moveChoices) { int bestMove = 0; double bestUtility = Double.NEGATIVE_INFINITY; simulator.setNextPiece(actualState.nextPiece); // synchronize the next piece for (int currentMove = 0; currentMove < moveChoices; currentMove++) { simulator.makeMove(currentMove); double currentUtility = Heuristics.getInstance().getUtility(simulator); if (currentUtility > bestUtility) { bestMove = currentMove; bestUtility = currentUtility; } simulator.resetMove(); } return bestMove; } public static final int COLS = 10; public static final int ROWS = 21; public static final int ORIENT = 0; public static final int SLOT = 1; public static final int N_PIECES = 7; protected static int[][][] legalMoves = new int[N_PIECES][][]; private int[][] field = new int[ROWS][COLS]; private int[] top = new int[COLS]; //private int[] pOrients = new int[]; private int[][] pWidth = State.getpWidth(); private int[][] pHeight = State.getpHeight(); private int[][][] pBottom = State.getpBottom(); private int[][][] pTop = State.getpTop(); private int nextPiece; private int turn = 0; private boolean lost; private int cleared = 0; public int[][] getField() { return field; } public int[] getTop() { return top; } //public static int[] getpOrients() { return pOrients; } /* public static int[][] getpWidth() { return pWidth; } */ /* public static int[][] getpHeight() { return pHeight; } */ /* public static int[][][] getpBottom() { return pBottom; } */ public int[] getpTop() { return top; } public boolean hasLost() { return lost; } public int getRowsCleared() { return cleared; } public int getTurnNumber() { return turn; } public int getNextPiece() { return nextPiece; } public void setNextPiece(int nextPiece) { this.nextPiece = nextPiece; } public void resetState(State state) { int[][] field = state.getField(); int stateNextPiece = state.getNextPiece(); boolean stateLost = state.hasLost(); int stateCleared = state.getRowsCleared(); int stateTurn = state.getTurnNumber(); Arrays.fill(this.top,0); } public boolean makeMove(int orient, int slot) { turn++; //height if the first column makes contact int height = top[slot]-pBottom[nextPiece][orient][0]; //for each column beyond the first in the piece for(int c = 1; c < pWidth[nextPiece][orient];c++) { height = Math.max(height,top[slot+c]-pBottom[nextPiece][orient][c]); } //check if game ended if(height+pHeight[nextPiece][orient] >= ROWS) { lost = true; return false; } //for each column in the piece - fill in the appropriate blocks for(int i = 0; i < pWidth[nextPiece][orient]; i++) { //from bottom to top of brick for(int h = height+pBottom[nextPiece][orient][i]; h < height+pTop[nextPiece][orient][i]; h++) { field[h][i+slot] = turn; } } //adjust top for(int c = 0; c < pWidth[nextPiece][orient]; c++) { top[slot+c]=height+pTop[nextPiece][orient][c]; } int rowsCleared = 0; //check for full rows - starting at the top for(int r = height+pHeight[nextPiece][orient]-1; r >= height; r--) { //check all columns in the row boolean full = true; for(int c = 0; c < COLS; c++) { if(field[r][c] == 0) { full = false; break; } } //if the row was full - remove it and slide above stuff down if(full) { rowsCleared++; cleared++; //for each column for(int c = 0; c < COLS; c++) { //slide down all bricks for(int i = r; i < top[c]; i++) { field[i][c] = field[i+1][c]; } //lower the top top[c]--; while(top[c]>=1 && field[top[c]-1][c]==0) top[c]--; } } } //pick a new piece //nextPiece = randomPiece(); return true; //return super.makeMove(orient, slot); } public static class NewField { public int[][] field; public int[] top; public int height; public int turn; } //gives legal moves for public int[][] legalMoves() { return legalMoves[nextPiece]; } //make a move based on the move index - its order in the legalMoves list public void makeMove(int move) { makeMove(legalMoves[nextPiece][move]); } //make a move based on an array of orient and slot public void makeMove(int[] move) { makeMove(move[ORIENT],move[SLOT]); } public static void main(String[] args) { State s = new State(); new TFrame(s); PlayerSkeleton p = new PlayerSkeleton(); while(!s.hasLost()) { s.makeMove(p.pickMove(s,s.legalMoves())); s.draw(); s.drawNext(0,0); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("You have completed "+s.getRowsCleared()+" rows."); } public static int run() { State s = new State(); new TFrame(s); PlayerSkeleton p = new PlayerSkeleton(); while(!s.hasLost()) { s.makeMove(p.pickMove(s,s.legalMoves())); s.draw(); s.drawNext(0,0); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("You have completed "+s.getRowsCleared()+" rows."); return s.getRowsCleared(); } /// features /** * * @param s: represents the state of the game * @return number of holes in the field */ public static int numHoles(State s) { int[] topRow = s.getTop(); int[][] field = s.getField(); int numHoles = 0; boolean hasHole; for (int col = 0; col < State.COLS; col++) { // for each column, find if there is a hole hasHole = false; int topCell = topRow[col] - 1; // since s.getTop() contains topRow + 1 for (int row = topCell-1; row > 0; row--) { if (field[row][col] == 0) { hasHole = true; break; } } if (hasHole) { // if this column has a hole numHoles++; } } return numHoles; } /** * * @param s: State * @return sum of total height difference between neighbouring columns abs(height(k) - height(k+1)) */ public static int heightDiff(State s) { int[] topRow = s.getTop(); // no need to minus 1 since it gets cancelled int totalHeightDiff = 0; for (int currentCol = 0; currentCol < topRow.length-1; currentCol++) { int nextCol = currentCol+1; totalHeightDiff += Math.abs(currentCol - nextCol); } return totalHeightDiff; } /** * * @param s: State * @return the maximum height among all the columns */ public static int maxHeight(State s) { int maxHeight = -1; for (int top: s.getTop()) { maxHeight = Math.max(maxHeight, top-1); } return maxHeight; } }
true
1377d58a9173672c94bd106fa9b906efd3c39f0d
Java
Dominicane87/Navigation
/app/src/main/java/com/example/vladimir/navigation/App.java
UTF-8
735
2.296875
2
[]
no_license
package com.example.vladimir.navigation; import android.app.Application; public class App extends Application { private static AppComponent component; private static App app; public static App get(){ return app; } public App() { app = this; } public static AppComponent getComponent(){ return component; } @Override public void onCreate() { super.onCreate(); component=buildComponent(); } protected AppComponent buildComponent(){ return DaggerAppComponent.builder() .presenterNavModule(new PresenterNavModule()) .build(); } public void clearAppComponent(){ component = null; } }
true
b64117eb9b7b069a6ebd9330f0ac4ea477f6358f
Java
RauulDeRoovers/rderoovers-minesweeper-API
/src/main/java/com/rderoovers/minesweeper/domain/MinesweeperSquareMine.java
UTF-8
307
2.234375
2
[]
no_license
package com.rderoovers.minesweeper.domain; public class MinesweeperSquareMine extends MinesweeperSquareDTO { public MinesweeperSquareMine(long index) { super(index); } @Override protected MinesweeperSquareType initializeType() { return MinesweeperSquareType.MINE; } }
true
ecc03ab0f33853cb2c3996078d4ac89e9d5a07cb
Java
LDA111222/GraphScope
/interactive_engine/src/frontend/frontendservice/src/main/java/com/alibaba/maxgraph/frontendservice/exceptions/PrepareException.java
UTF-8
2,254
2.328125
2
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-elastic-license-2018", "LicenseRef-scancode-other-permissive" ]
permissive
/** * Copyright 2020 Alibaba Group Holding Limited. * * 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.alibaba.maxgraph.frontendservice.exceptions; import com.google.common.base.Preconditions; public class PrepareException extends Exception { public enum ErrorCode { Ok, alreadyPrepared, unRecognizedPrepare, persistPrepareError, fetchLockFailed, errorToPrepare, readMetaError, unknown; public int value() { return this.ordinal(); } } private ErrorCode errorCode; private Object message; public PrepareException(int error) { super(); Preconditions.checkArgument(error != 0); this.errorCode = ErrorCode.values()[error]; } public PrepareException(int error, Object message) { super(message.toString()); Preconditions.checkArgument(error != 0); if(error < 0) { this.errorCode = ErrorCode.unknown; } else { this.errorCode = ErrorCode.values()[error]; } this.message = message; } public PrepareException(ErrorCode error, Object message) { super(message.toString()); Preconditions.checkArgument(error.ordinal() != 0); this.errorCode = error; this.message = message; } public ErrorCode getErrorCode() { return this.errorCode; } public Object getErrorMessage() { return this.message; } @Override public String toString() { return this.errorCode.name() + ": " + this.message; } public static PrepareException parseFrom(int code, String message) { return new PrepareException(code, message); } }
true
3eece17f2f085142e1b1997c03bfb60ea7accdd8
Java
patrypaulino/EasyMarketApp
/app/src/main/java/com/infodat/easymarket/ListScanAdapter.java
UTF-8
2,208
2.390625
2
[]
no_license
package com.infodat.easymarket; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.infodat.easymarket.db.datasources.CodigosDataSource; import com.infodat.easymarket.db.entities.Codigo; import com.infodat.zbarscannerexample.R; import java.util.ArrayList; public class ListScanAdapter extends BaseAdapter { public Context context; private CodigosDataSource dataSource; public ListScanAdapter(Context context, CodigosDataSource dataSource) { this.context = context; this.dataSource = dataSource; } public ArrayList<Codigo> productos = new ArrayList<Codigo>(); @Override public int getCount() { return productos.size(); } @Override public Codigo getItem(int i) { return productos.get(i); } @Override public long getItemId(int i) { return 0; } public void add(Codigo producto){ productos.add(producto); this.notifyDataSetChanged(); } public void add(ArrayList<Codigo> productos){ this.productos = productos; this.notifyDataSetChanged(); } @Override public View getView(final int i, View view, ViewGroup viewGroup) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); View row; row = inflater.inflate(R.layout.row_scanned, viewGroup, false); TextView title = (TextView) row.findViewById(R.id.rText); Button b = (Button) row.findViewById(R.id.bQuitar); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Codigo removed = productos.remove(i); dataSource.borrarCodigo(removed); ListScanAdapter.this.notifyDataSetChanged(); } }); String string = getItem(i).toString(); if ( string.length() > 23 ) { string = string.substring(0, 20) + "..."; } title.setText(string); return row; } }
true
3342932fd5660fa5decb32ff81fdce6c9915bf90
Java
cyberphone/json-canonicalization
/java/deprecated/org/webpki/jcs/NumberCachedPowers.java
UTF-8
9,557
2.109375
2
[ "Apache-2.0" ]
permissive
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Ported to Java from Mozilla's version of V8-dtoa by Hannes Wallnoefer. // The original revision was 67d1049b0bf9 from the mozilla-central tree. package org.webpki.jcs; class NumberCachedPowers { static final double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10) static class CachedPower { long significand; short binaryExponent; short decimalExponent; CachedPower(long significand, short binaryExponent, short decimalExponent) { this.significand = significand; this.binaryExponent = binaryExponent; this.decimalExponent = decimalExponent; } } static int getCachedPower(int e, int alpha, int gamma, NumberDiyFp c_mk) { int kQ = NumberDiyFp.kSignificandSize; double k = Math.ceil((alpha - e + kQ - 1) * kD_1_LOG2_10); int index = (GRISU_CACHE_OFFSET + (int) k - 1) / CACHED_POWERS_SPACING + 1; CachedPower cachedPower = CACHED_POWERS[index]; c_mk.setF(cachedPower.significand); c_mk.setE(cachedPower.binaryExponent); assert ((alpha <= c_mk.e() + e) && (c_mk.e() + e <= gamma)); return cachedPower.decimalExponent; } // Code below is converted from GRISU_CACHE_NAME(8) in file "powers-ten.h" // Regexp to convert this from original C++ source: // \{GRISU_UINT64_C\((\w+), (\w+)\), (\-?\d+), (\-?\d+)\} // interval between entries of the powers cache below static final int CACHED_POWERS_SPACING = 8; static final CachedPower[] CACHED_POWERS = { new CachedPower(0xe61acf033d1a45dfL, (short) -1087, (short) -308), new CachedPower(0xab70fe17c79ac6caL, (short) -1060, (short) -300), new CachedPower(0xff77b1fcbebcdc4fL, (short) -1034, (short) -292), new CachedPower(0xbe5691ef416bd60cL, (short) -1007, (short) -284), new CachedPower(0x8dd01fad907ffc3cL, (short) -980, (short) -276), new CachedPower(0xd3515c2831559a83L, (short) -954, (short) -268), new CachedPower(0x9d71ac8fada6c9b5L, (short) -927, (short) -260), new CachedPower(0xea9c227723ee8bcbL, (short) -901, (short) -252), new CachedPower(0xaecc49914078536dL, (short) -874, (short) -244), new CachedPower(0x823c12795db6ce57L, (short) -847, (short) -236), new CachedPower(0xc21094364dfb5637L, (short) -821, (short) -228), new CachedPower(0x9096ea6f3848984fL, (short) -794, (short) -220), new CachedPower(0xd77485cb25823ac7L, (short) -768, (short) -212), new CachedPower(0xa086cfcd97bf97f4L, (short) -741, (short) -204), new CachedPower(0xef340a98172aace5L, (short) -715, (short) -196), new CachedPower(0xb23867fb2a35b28eL, (short) -688, (short) -188), new CachedPower(0x84c8d4dfd2c63f3bL, (short) -661, (short) -180), new CachedPower(0xc5dd44271ad3cdbaL, (short) -635, (short) -172), new CachedPower(0x936b9fcebb25c996L, (short) -608, (short) -164), new CachedPower(0xdbac6c247d62a584L, (short) -582, (short) -156), new CachedPower(0xa3ab66580d5fdaf6L, (short) -555, (short) -148), new CachedPower(0xf3e2f893dec3f126L, (short) -529, (short) -140), new CachedPower(0xb5b5ada8aaff80b8L, (short) -502, (short) -132), new CachedPower(0x87625f056c7c4a8bL, (short) -475, (short) -124), new CachedPower(0xc9bcff6034c13053L, (short) -449, (short) -116), new CachedPower(0x964e858c91ba2655L, (short) -422, (short) -108), new CachedPower(0xdff9772470297ebdL, (short) -396, (short) -100), new CachedPower(0xa6dfbd9fb8e5b88fL, (short) -369, (short) -92), new CachedPower(0xf8a95fcf88747d94L, (short) -343, (short) -84), new CachedPower(0xb94470938fa89bcfL, (short) -316, (short) -76), new CachedPower(0x8a08f0f8bf0f156bL, (short) -289, (short) -68), new CachedPower(0xcdb02555653131b6L, (short) -263, (short) -60), new CachedPower(0x993fe2c6d07b7facL, (short) -236, (short) -52), new CachedPower(0xe45c10c42a2b3b06L, (short) -210, (short) -44), new CachedPower(0xaa242499697392d3L, (short) -183, (short) -36), new CachedPower(0xfd87b5f28300ca0eL, (short) -157, (short) -28), new CachedPower(0xbce5086492111aebL, (short) -130, (short) -20), new CachedPower(0x8cbccc096f5088ccL, (short) -103, (short) -12), new CachedPower(0xd1b71758e219652cL, (short) -77, (short) -4), new CachedPower(0x9c40000000000000L, (short) -50, (short) 4), new CachedPower(0xe8d4a51000000000L, (short) -24, (short) 12), new CachedPower(0xad78ebc5ac620000L, (short) 3, (short) 20), new CachedPower(0x813f3978f8940984L, (short) 30, (short) 28), new CachedPower(0xc097ce7bc90715b3L, (short) 56, (short) 36), new CachedPower(0x8f7e32ce7bea5c70L, (short) 83, (short) 44), new CachedPower(0xd5d238a4abe98068L, (short) 109, (short) 52), new CachedPower(0x9f4f2726179a2245L, (short) 136, (short) 60), new CachedPower(0xed63a231d4c4fb27L, (short) 162, (short) 68), new CachedPower(0xb0de65388cc8ada8L, (short) 189, (short) 76), new CachedPower(0x83c7088e1aab65dbL, (short) 216, (short) 84), new CachedPower(0xc45d1df942711d9aL, (short) 242, (short) 92), new CachedPower(0x924d692ca61be758L, (short) 269, (short) 100), new CachedPower(0xda01ee641a708deaL, (short) 295, (short) 108), new CachedPower(0xa26da3999aef774aL, (short) 322, (short) 116), new CachedPower(0xf209787bb47d6b85L, (short) 348, (short) 124), new CachedPower(0xb454e4a179dd1877L, (short) 375, (short) 132), new CachedPower(0x865b86925b9bc5c2L, (short) 402, (short) 140), new CachedPower(0xc83553c5c8965d3dL, (short) 428, (short) 148), new CachedPower(0x952ab45cfa97a0b3L, (short) 455, (short) 156), new CachedPower(0xde469fbd99a05fe3L, (short) 481, (short) 164), new CachedPower(0xa59bc234db398c25L, (short) 508, (short) 172), new CachedPower(0xf6c69a72a3989f5cL, (short) 534, (short) 180), new CachedPower(0xb7dcbf5354e9beceL, (short) 561, (short) 188), new CachedPower(0x88fcf317f22241e2L, (short) 588, (short) 196), new CachedPower(0xcc20ce9bd35c78a5L, (short) 614, (short) 204), new CachedPower(0x98165af37b2153dfL, (short) 641, (short) 212), new CachedPower(0xe2a0b5dc971f303aL, (short) 667, (short) 220), new CachedPower(0xa8d9d1535ce3b396L, (short) 694, (short) 228), new CachedPower(0xfb9b7cd9a4a7443cL, (short) 720, (short) 236), new CachedPower(0xbb764c4ca7a44410L, (short) 747, (short) 244), new CachedPower(0x8bab8eefb6409c1aL, (short) 774, (short) 252), new CachedPower(0xd01fef10a657842cL, (short) 800, (short) 260), new CachedPower(0x9b10a4e5e9913129L, (short) 827, (short) 268), new CachedPower(0xe7109bfba19c0c9dL, (short) 853, (short) 276), new CachedPower(0xac2820d9623bf429L, (short) 880, (short) 284), new CachedPower(0x80444b5e7aa7cf85L, (short) 907, (short) 292), new CachedPower(0xbf21e44003acdd2dL, (short) 933, (short) 300), new CachedPower(0x8e679c2f5e44ff8fL, (short) 960, (short) 308), new CachedPower(0xd433179d9c8cb841L, (short) 986, (short) 316), new CachedPower(0x9e19db92b4e31ba9L, (short) 1013, (short) 324), new CachedPower(0xeb96bf6ebadf77d9L, (short) 1039, (short) 332), new CachedPower(0xaf87023b9bf0ee6bL, (short) 1066, (short) 340) }; static final int GRISU_CACHE_MAX_DISTANCE = 27; // nb elements (8): 82 static final int GRISU_CACHE_OFFSET = 308; }
true
0f02d760725d9b6f3620a57215bf8b0f6555a2b5
Java
VICTORIA-MARIEL/MiPesca
/mipesca-source1.13/app/src/main/java/mx/com/sit/pesca/dao/MunicipioDAO.java
UTF-8
3,420
2.1875
2
[]
no_license
package mx.com.sit.pesca.dao; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.realm.Realm; import io.realm.RealmResults; import mx.com.sit.pesca.dto.ComunidadList; import mx.com.sit.pesca.dto.MunicipioList; import mx.com.sit.pesca.entity.ComunidadEntity; import mx.com.sit.pesca.entity.MunicipioEntity; import mx.com.sit.pesca.services.ComunidadService; import mx.com.sit.pesca.services.MunicipioService; import mx.com.sit.pesca.util.Constantes; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MunicipioDAO { private static final String TAG = "MunicipioDAO"; private Realm realm; private Retrofit retrofit; private int usuarioId; private int pescadorId; private Context contexto; public MunicipioDAO(){ } public MunicipioDAO(int usuarioId, Context context){ Log.d(TAG, "Iniciando MunicipioDAO(int usuarioId, Context context)"); this.usuarioId = usuarioId; this.contexto = context; Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); retrofit = new Retrofit.Builder() .baseUrl(Constantes.URL_SERVIDOR_REMOTO) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); Log.d(TAG, "Terminando MunicipioDAO(int usuarioId, Context context)"); } public void insertar(MunicipioList municipios){ Log.d(TAG, "Iniciando insertar(MunicipioList municipios)"); realm = Realm.getDefaultInstance(); realm.beginTransaction(); realm.insertOrUpdate(municipios.getMunicipios()); realm.commitTransaction(); realm.close(); Log.d(TAG, "Terminando insertar(MunicipioList municipios)"); } public boolean consultarMunicipios(){ Log.d(TAG, "Iniciando consultarMunicipios()"); final StringBuilder error = new StringBuilder(); MunicipioService service = retrofit.create(MunicipioService.class); Call<MunicipioList> presCall = service.getMunicipios(); presCall.enqueue(new Callback<MunicipioList>(){ @Override public void onResponse(Call<MunicipioList> call, Response<MunicipioList> response) { MunicipioList municipios = response.body(); insertar(municipios); } @Override public void onFailure(Call<MunicipioList> call, Throwable t) { if(contexto!=null) { Toast.makeText(contexto, "Error:" + t.toString(), Toast.LENGTH_LONG).show(); error.append("0"); } } }); Log.d(TAG, "Terminando consultarMunicipios()"); return ("".equals(error.toString()))?true:false; } public int getMunicipios(){ Log.d(TAG, "Iniciando getMunicipios()"); int total = 0; realm = Realm.getDefaultInstance(); RealmResults<MunicipioEntity> list = realm.where(MunicipioEntity.class).findAll(); Log.d(TAG, "# Municipios>"+list.size()); Log.d(TAG, "Terminando getMunicipios()"); total = list.size(); realm.close(); return total; } }
true
ba6500a0691e8a660a64512d7df79d31a7840427
Java
dlhxd/bce-sdk-java
/src/test/java/com/baidubce/services/vod/ut/CreateMediaResourceTest.java
UTF-8
1,375
2.265625
2
[ "Apache-2.0" ]
permissive
package com.baidubce.services.vod.ut; import java.io.File; import java.io.FileNotFoundException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.baidubce.services.vod.AbstractVodTest; import com.baidubce.services.vod.model.CreateMediaResourceResponse; public class CreateMediaResourceTest extends AbstractVodTest { @Before public void setUp() throws Exception { super.setUp(); } @After public void tearDown() throws Exception { } @Test public void uploadSmallFileTest() throws FileNotFoundException { File file = new File("/Users/baidu/Downloads/a.mov"); String title = "Gail Sophicha"; String description = "Back To December"; CreateMediaResourceResponse response = vodClient.createMediaResource(title, description, file); String mediaId = response.getMediaId(); System.out.println("meidaId = " + mediaId); } @Test public void uploadLargeFileTest() throws FileNotFoundException { File file = new File("/Volumes/sd/video/Martian.mp4"); String title = "Gail Sophicha"; String description = "Back To December"; CreateMediaResourceResponse response = vodClient.createMediaResource(title, description, file); String mediaId = response.getMediaId(); System.out.println("meidaId = " + mediaId); } }
true
c9761a7144fabb5a58c90dece109c2ad14a92d57
Java
nitinkumartech/showroom-android
/app/src/main/java/com/ramotion/showroom/examples/garlandview/details/DetailsAdapter.java
UTF-8
1,126
2.375
2
[ "MIT" ]
permissive
package com.ramotion.showroom.examples.garlandview.details; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.ramotion.showroom.R; import com.ramotion.showroom.databinding.GvDetailsItemBinding; import java.util.List; class DetailsAdapter extends RecyclerView.Adapter<DetailsItem> { private final List<DetailsData> mData; DetailsAdapter(final List<DetailsData> data) { super(); mData = data; } @Override public DetailsItem onCreateViewHolder(ViewGroup parent, int viewType) { final LayoutInflater inflater = LayoutInflater.from(parent.getContext()); final GvDetailsItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.gv_details_item, parent, false); return new DetailsItem(binding.getRoot()); } @Override public void onBindViewHolder(DetailsItem holder, int position) { holder.setContent(mData.get(position)); } @Override public int getItemCount() { return mData.size(); } }
true
09f05f9d05ab8495d8795ad582d79f35a1c6ae72
Java
Ndjampou/helloworldmvc
/helloworldmvc/helloworldmvc.Contract/src/main/java/helloworldmvc/Contract/DAOHelloWorld.java
UTF-8
925
2.84375
3
[]
no_license
package helloworldmvc.Contract; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class DAOHelloWorld { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("D:\\HelloWorld.txt")); String line; while ((line = in.readLine()) != null) { // Afficher le contenu du fichier System.out.println (line); } in.close(); } String FileName="D:\\HelloWorld.txt"; DAOHelloWorld instance= null; String HelloWorldMessage = null; private DAOHelloWorld() { } public DAOHelloWorld getinstance() { return instance; } private void setinsistance(DAOHelloWorld insistance) { instance=this.instance; } private void readFile() { } public String getHelloWorldMessage() { return HelloWorldMessage; } public void setHelloWorldMessage(String helloWorldMessage) { } }
true
8b67306e120bed45c12b8fb04b06020fd46e9743
Java
devlopper/org.cyk.system.company
/company-business-impl-ejb/src/main/java/org/cyk/system/company/business/impl/sale/SaleCashRegisterMovementCollectionDetails.java
UTF-8
1,435
2.015625
2
[]
no_license
package org.cyk.system.company.business.impl.sale; import java.io.Serializable; import org.cyk.system.company.model.sale.SaleCashRegisterMovementCollection; import org.cyk.system.root.business.impl.AbstractCollectionDetails; import org.cyk.system.root.model.AbstractCollection; import lombok.Getter; import lombok.Setter; @Getter @Setter public class SaleCashRegisterMovementCollectionDetails extends AbstractCollectionDetails<SaleCashRegisterMovementCollection> implements Serializable { private static final long serialVersionUID = -6341285110719947720L; private String cashRegister,value,mode; public SaleCashRegisterMovementCollectionDetails(SaleCashRegisterMovementCollection saleCashRegisterMovementCollection) { super(saleCashRegisterMovementCollection); value = formatNumber(saleCashRegisterMovementCollection.getCashRegisterMovement().getMovement().getValue()); mode = formatUsingBusiness(saleCashRegisterMovementCollection.getCashRegisterMovement().getMode()); } @Override public AbstractCollection<?> getCollection() { return master; } public static final String FIELD_CASH_REGISTER = "cashRegister"; public static final String FIELD_VALUE = "value"; public static final String FIELD_MODE = "mode"; public static final String FIELD_SUPPORTING_DOCUMENT_PROVIDER = "supportingDocumentProvider"; public static final String FIELD_SUPPORTING_DOCUMENT_IDENTIFIER = "supportingDocumentIdentifier"; }
true
bfd385f536fb30dc9b7dac193ad3b689b7031828
Java
fred1573/fqms
/src/main/java/com/project/service/finance/FinanceOutNormalExportService.java
UTF-8
793
1.835938
2
[ "Apache-2.0" ]
permissive
package com.project.service.finance; import com.project.entity.finance.FinanceInnChannelSettlement; import com.project.entity.finance.FinanceInnSettlement; import com.project.entity.finance.FinanceParentOrder; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import java.util.List; /** * Created by admin on 2016/3/21. */ @Component @Transactional public interface FinanceOutNormalExportService { /** * 导出正常客栈渠道明细 */ void createFinanceExcel(HttpServletRequest request, List<FinanceInnSettlement> financeInnSettlementList, List<List<FinanceInnChannelSettlement>> financeInnChannelSettlementList)throws Exception; }
true
e0e427603d59a89a004fd8e1e123bc8ec24c94a1
Java
qadir0108/EncorePianoApp
/app/src/main/java/com/encore/piano/server/AcknowledgmentService.java
UTF-8
3,821
2.125
2
[]
no_license
package com.encore.piano.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; import android.content.Context; import com.encore.piano.enums.JsonResponseEnum; import com.encore.piano.enums.MessageEnum; import com.encore.piano.sync.SyncAssignmentEnum; import com.encore.piano.exceptions.DatabaseInsertException; import com.encore.piano.exceptions.JSONNullableException; import com.encore.piano.exceptions.NetworkStatePermissionException; import com.encore.piano.exceptions.NotConnectedException; import com.encore.piano.exceptions.UrlConnectionException; import com.encore.piano.model.BaseModel; public class AcknowledgmentService extends BaseService { Context context; public String RunsheetId = EMPTY_STRING; public String MessageId = EMPTY_STRING; JSONArray array = new JSONArray(); public AcknowledgmentService(Context context) throws UrlConnectionException, JSONException, JSONNullableException, NotConnectedException, NetworkStatePermissionException{ super(context); this.context = context; } public boolean AcknowledgeConsignment(String RunsheetId) throws UrlConnectionException, JSONException, JSONNullableException, NotConnectedException, NetworkStatePermissionException, DatabaseInsertException, ClientProtocolException, IOException{ this.RunsheetId = RunsheetId; boolean isAcknowledged = true; HttpPost postRequest = new HttpPost(ServiceUrls.GetRunsheetAckUrl(context)); postRequest.setHeader("Content-Type", "application/json"); JSONStringer jsonData = new JSONStringer(); jsonData.object(); jsonData.key(SyncAssignmentEnum.AuthToken.Value).value(Service.loginService.LoginModel.getAuthToken()); jsonData.key(SyncAssignmentEnum.RunSheetID.Value).value(this.RunsheetId); jsonData.key(SyncAssignmentEnum.Acknowledged.Value).value(isAcknowledged); jsonData.endObject(); StringEntity loginEntity = new StringEntity(jsonData.toString()); postRequest.setEntity(loginEntity); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(postRequest); HttpEntity responseEntity = httpResponse.getEntity(); if(responseEntity != null) { BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String temp = ""; StringBuilder responseStringBuilder = new StringBuilder(); while((temp = br.readLine()) != null) { responseStringBuilder.append(temp); } String response = responseStringBuilder.toString(); boolean success = setBooleanValueFromJSON(JsonResponseEnum.IsSucess.Value, getJSONData(response).getJSONObject(MessageEnum.Message.Value)); if(success) return true; else return false; } return false; } @Override public URL getServiceUrl() { String url = ServiceUrls.GetRunsheetAckUrl(context); return getURLFromString(url); } @Override public <T extends BaseModel> T decodeContent(JSONObject object) { // TODO Auto-generated method stub return null; } @Override public void setContent() throws JSONException, DatabaseInsertException { // TODO Auto-generated method stub } @Override public void fetchContent() throws UrlConnectionException, JSONException, JSONNullableException, NotConnectedException, NetworkStatePermissionException { // TODO Auto-generated method stub } }
true
79e7352f85534863726c419f067664089f8dd80d
Java
xiatiansong/kudu-sds
/nosql.kudu.sdk/src/main/java/org/bg/kudu/annotation/codec/TypeCodec.java
UTF-8
20,787
2.5
2
[ "Apache-2.0" ]
permissive
package org.bg.kudu.annotation.codec; import com.google.common.reflect.TypeToken; import org.bg.kudu.annotation.DataType; import org.bg.kudu.annotation.InvalidTypeException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public abstract class TypeCodec<T> { private static Pattern patternInteger = Pattern.compile("^[-\\+]?[\\d]*$"); private static Pattern patternFloat = Pattern.compile("^[-\\+]?[.\\d]*$"); protected final TypeToken<T> javaType; protected final DataType cqlType; protected TypeCodec(DataType cqlType, Class<T> javaClass) { this(cqlType, TypeToken.of(javaClass)); } protected TypeCodec(DataType cqlType, TypeToken<T> javaType) { checkNotNull(cqlType, "cqlType cannot be null"); checkNotNull(javaType, "javaType cannot be null"); checkArgument(!javaType.isPrimitive(), "Cannot create a codec for a primitive Java type (%s), please use the wrapper type instead", javaType); this.cqlType = cqlType; this.javaType = javaType; } public TypeToken<T> getJavaType() { return javaType; } public DataType getKuduType() { return cqlType; } public abstract Object serialize(T value) throws InvalidTypeException; public abstract T deserialize(Object object) throws InvalidTypeException; public abstract T parse(String value) throws InvalidTypeException; public abstract String format(T value) throws InvalidTypeException; public boolean accepts(TypeToken<?> javaType) { checkNotNull(javaType, "Parameter javaType cannot be null"); return this.javaType.equals(javaType.wrap()); } public boolean accepts(Class<?> javaType) { checkNotNull(javaType, "Parameter javaType cannot be null"); return accepts(TypeToken.of(javaType)); } public boolean accepts(DataType cqlType) { checkNotNull(cqlType, "Parameter cqlType cannot be null"); return this.cqlType.equals(cqlType); } public static PrimitiveBooleanCodec kboolean() { return BooleanCodec.instance; } public static PrimitiveByteCodec tinyInt() { return TinyIntCodec.instance; } public static PrimitiveShortCodec smallInt() { return SmallIntCodec.instance; } public static PrimitiveIntCodec kint() { return IntCodec.instance; } public static PrimitiveBigintCodec bigint() { return BigintCodec.instance; } public static PrimitiveFloatCodec kfloat() { return FloatCodec.instance; } public static PrimitiveDoubleCodec kdouble() { return DoubleCodec.instance; } public static PrimitiveStringCodec kstring() { return StringCodec.instance; } public static TypeCodec<BigDecimal> decimal() { return DecimalCodec.instance; } public abstract static class PrimitiveBooleanCodec extends TypeCodec<Boolean> { protected PrimitiveBooleanCodec(DataType cqlType) { super(cqlType, Boolean.class); } public abstract Object serializeNoBoxing(boolean var1); public abstract boolean deserializeNoBoxing(Object obj); public Object serialize(Boolean value) { return value == null ? null : this.serializeNoBoxing(value); } public Boolean deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveByteCodec extends TypeCodec<Byte> { protected PrimitiveByteCodec(DataType cqlType) { super(cqlType, Byte.class); } public abstract Object serializeNoBoxing(byte var1); public abstract byte deserializeNoBoxing(Object obj); public Object serialize(Byte value) { return value == null ? null : this.serializeNoBoxing(value); } public Byte deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveShortCodec extends TypeCodec<Short> { protected PrimitiveShortCodec(DataType cqlType) { super(cqlType, Short.class); } public abstract Object serializeNoBoxing(short var1); public abstract short deserializeNoBoxing(Object var1); public Object serialize(Short value) { return value == null ? null : this.serializeNoBoxing(value); } public Short deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveIntCodec extends TypeCodec<Integer> { protected PrimitiveIntCodec(DataType cqlType) { super(cqlType, Integer.class); } public abstract Object serializeNoBoxing(int var1); public abstract int deserializeNoBoxing(Object var1); public Object serialize(Integer value) { return value == null ? null : this.serializeNoBoxing(value); } public Integer deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveBigintCodec extends TypeCodec<Long> { protected PrimitiveBigintCodec(DataType cqlType) { super(cqlType, Long.class); } public abstract Object serializeNoBoxing(long var1); public abstract long deserializeNoBoxing(Object var1); public Object serialize(Long value) { return value == null ? null : this.serializeNoBoxing(value); } public Long deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveDoubleCodec extends TypeCodec<Double> { protected PrimitiveDoubleCodec(DataType cqlType) { super(cqlType, Double.class); } public abstract Object serializeNoBoxing(double var1); public abstract double deserializeNoBoxing(Object obj); public Object serialize(Double value) { return value == null ? null : this.serializeNoBoxing(value); } public Double deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveStringCodec extends TypeCodec<String> { protected PrimitiveStringCodec(DataType cqlType) { super(cqlType, String.class); } public abstract Object serializeNoBoxing(String str); public abstract String deserializeNoBoxing(Object obj); public Object serialize(String value) { return value == null ? null : this.serializeNoBoxing(value); } public String deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } public abstract static class PrimitiveFloatCodec extends TypeCodec<Float> { protected PrimitiveFloatCodec(DataType cqlType) { super(cqlType, Float.class); } public abstract Object serializeNoBoxing(float var1); public abstract float deserializeNoBoxing(Object var1); public Object serialize(Float value) { return value == null ? null : this.serializeNoBoxing(value); } public Float deserialize(Object obj) { return obj != null ? this.deserializeNoBoxing(obj) : null; } } private static class DecimalCodec extends TypeCodec<BigDecimal> { private static final DecimalCodec instance = new DecimalCodec(); private DecimalCodec() { super(DataType.DECIMAL, BigDecimal.class); } public BigDecimal parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? new BigDecimal(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse decimal value from \"%s\"", value)); } } public String format(BigDecimal value) { return value == null ? "NULL" : value.toString(); } public Object serialize(BigDecimal value) { if (value == null) { return null; } else { return value; } } public BigDecimal deserialize(Object obj) { if (obj != null) { if (!patternFloat.matcher(obj.toString()).matches() && !patternInteger.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid decimal value, expecting at least 4 bytes but got " + obj.toString()); } else { if (obj instanceof BigDecimal) { return (BigDecimal) obj; } else if (obj instanceof String) { return new BigDecimal((String) obj); } else if (obj instanceof BigInteger) { return new BigDecimal((BigInteger) obj); } else if (obj instanceof Number) { return new BigDecimal(((Number) obj).doubleValue()); } else { throw new InvalidTypeException("Not possible to coerce [" + obj + "] from class " + obj.getClass() + " into a BigDecimal."); } } } else { return null; } } } private static class BooleanCodec extends PrimitiveBooleanCodec { private static final BooleanCodec instance = new BooleanCodec(); private BooleanCodec() { super(DataType.BOOLEAN); } public Boolean parse(String value) { if (value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL")) { if (value.equalsIgnoreCase(Boolean.FALSE.toString())) { return false; } else if (value.equalsIgnoreCase(Boolean.TRUE.toString())) { return true; } else { throw new InvalidTypeException(String.format("Cannot parse boolean value from \"%s\"", value)); } } else { return null; } } public String format(Boolean value) { if (value == null) { return "NULL"; } else { return value ? "true" : "false"; } } public Object serializeNoBoxing(boolean value) { return value ? Boolean.TRUE : Boolean.FALSE; } public boolean deserializeNoBoxing(Object obj) { if (obj != null) { if (!"true".equals(obj.toString()) && !"false".equals(obj.toString())) { throw new InvalidTypeException("Invalid boolean value, expecting true/false but got " + obj.toString()); } else { return Boolean.valueOf(obj.toString()); } } else { return false; } } } private static class TinyIntCodec extends PrimitiveByteCodec { private static final TinyIntCodec instance = new TinyIntCodec(); private TinyIntCodec() { super(DataType.TINYINT); } public Byte parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Byte.parseByte(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 8-bits int value from \"%s\"", value)); } } public String format(Byte value) { return value == null ? "NULL" : Byte.toString(value); } public Object serializeNoBoxing(byte value) { return value; } public byte deserializeNoBoxing(Object obj) { if (obj != null) { if (obj instanceof Boolean) { byte trueByte = 1; byte falseByte = 0; return ((boolean) obj) ? trueByte : falseByte; } if (patternInteger.matcher(obj.toString()).matches()) { return Byte.parseByte(obj.toString()); } throw new InvalidTypeException("Invalid 8-bits integer value, expecting 1 byte but got " + obj.toString()); } else { return 0; } } } private static class SmallIntCodec extends PrimitiveShortCodec { private static final SmallIntCodec instance = new SmallIntCodec(); private SmallIntCodec() { super(DataType.SMALLINT); } public Short parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Short.parseShort(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 16-bits int value from \"%s\"", value)); } } public String format(Short value) { return value == null ? "NULL" : Short.toString(value); } public Object serializeNoBoxing(short value) { return value; } public short deserializeNoBoxing(Object obj) { if (obj != null) { if (!patternInteger.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid 16-bits integer value, expecting 2 bytes but got " + obj.toString()); } else { return Short.valueOf(obj.toString()); } } else { return 0; } } } private static class IntCodec extends PrimitiveIntCodec { private static final IntCodec instance = new IntCodec(); private IntCodec() { super(DataType.INT); } public Integer parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Integer.parseInt(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 32-bits int value from \"%s\"", value)); } } public String format(Integer value) { return value == null ? "NULL" : Integer.toString(value); } public Object serializeNoBoxing(int value) { return value; } public int deserializeNoBoxing(Object obj) { if (obj != null) { if (!patternInteger.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid 32-bits integer value, expecting 4 bytes but got " + obj.toString()); } else { return Integer.parseInt(obj.toString()); } } else { return 0; } } } private static class BigintCodec extends PrimitiveBigintCodec { private static final BigintCodec instance = new BigintCodec(); private BigintCodec() { super(DataType.BIGINT); } public Long parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Long.parseLong(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 64-bits long value from \"%s\"", value)); } } public String format(Long value) { return value == null ? "NULL" : Long.toString(value); } public Object serializeNoBoxing(long value) { return value; } public long deserializeNoBoxing(Object obj) { if (obj != null) { if (!patternInteger.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid 64-bits long value, expecting 8 bytes but got " + obj.toString()); } else { return Long.parseLong(obj.toString()); } } else { return 0L; } } } private static class FloatCodec extends PrimitiveFloatCodec { private static final FloatCodec instance = new FloatCodec(); private FloatCodec() { super(DataType.FLOAT); } public Float parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Float.parseFloat(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 32-bits float value from \"%s\"", value)); } } public String format(Float value) { return value == null ? "NULL" : Float.toString(value); } public Object serializeNoBoxing(float value) { return value; } public float deserializeNoBoxing(Object obj) { if (obj != null) { if (obj instanceof Float) { return (Float) obj; } else if (!patternFloat.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid 32-bits float value, expecting 4 bytes but got " + obj.toString()); } else { return Float.valueOf(obj.toString()); } } else { return 0.0F; } } } private static class DoubleCodec extends PrimitiveDoubleCodec { private static final DoubleCodec instance = new DoubleCodec(); private DoubleCodec() { super(DataType.DOUBLE); } public Double parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? Double.parseDouble(value) : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value)); } } public String format(Double value) { return value == null ? "NULL" : Double.toString(value); } public Object serializeNoBoxing(double value) { return value; } public double deserializeNoBoxing(Object obj) { if (obj != null) { if (obj instanceof Double) { return (Double) obj; } else if (!patternFloat.matcher(obj.toString()).matches()) { throw new InvalidTypeException("Invalid 64-bits double value, expecting 8 bytes but got " + obj.toString()); } else { return Double.valueOf(obj.toString()); } } else { return 0.0D; } } } private static class StringCodec extends PrimitiveStringCodec { private static final StringCodec instance = new StringCodec(); private StringCodec() { super(DataType.DOUBLE); } @Override public String parse(String value) { try { return value != null && !value.isEmpty() && !value.equalsIgnoreCase("NULL") ? value : null; } catch (NumberFormatException var3) { throw new InvalidTypeException(String.format("Cannot parse 64-bits double value from \"%s\"", value)); } } @Override public String format(String value) { return value == null ? "NULL" : value; } @Override public Object serializeNoBoxing(String value) { return value; } @Override public String deserializeNoBoxing(Object obj) { if (obj != null) { if (obj instanceof String) { return (String) obj; } else { return String.valueOf(obj); } } else { return null; } } } @Override public String toString() { return String.format("%s [%s <-> %s]", this.getClass().getSimpleName(), cqlType, javaType); } }
true
072277fb3e989f7efc8181ad34b8b83984635440
Java
st0le/Euler
/src/org/mechaevil/Euler/Problem114/Problem114_2.java
UTF-8
815
3.109375
3
[]
no_license
/** * */ package org.mechaevil.Euler.Problem114; import java.util.HashMap; import org.mechaevil.util.StopWatch; /** * @author 332609 * */ public class Problem114_2 { public static HashMap<Integer, Long> table = new HashMap<Integer, Long>(); /** * @param args */ public static void main(String[] args) { StopWatch timer = new StopWatch(); timer.startTimer(); //... your Code here System.out.println("P114 : " + foo(50)); timer.stopTimer(); System.out.println(timer); } private static long foo(int n) { if(n < 3) return 1; if(n == 3) return 2; if(table.containsKey(n)) return table.get(n); long s = 1; for(int red = 3; red <= n;red++) { for(int start = 0; start <= n-red;start++) { s+= foo(n - (red + start + 1)); } } table.put(n,s); return s; } }
true
8cb9e3925bc6fcaa53606318886399eb97b8f83d
Java
rodrigoborgesdeoliveira/GSS
/src/main/java/br/pucpr/gss/client/view/uibinder/GeracaoRelatorioViewImpl.java
UTF-8
2,772
2.109375
2
[]
no_license
package br.pucpr.gss.client.view.uibinder; import br.pucpr.gss.client.view.GeracaoRelatorioView; import br.pucpr.gss.client.view.MenuView; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import gwt.material.design.client.ui.MaterialCheckBox; import gwt.material.design.client.ui.MaterialDatePicker; import java.util.Date; public class GeracaoRelatorioViewImpl extends Composite implements GeracaoRelatorioView { interface GeracaoRelatorioViewImplUiBinder extends UiBinder<Widget, GeracaoRelatorioViewImpl> { } private static GeracaoRelatorioViewImplUiBinder uiBinder = GWT.create(GeracaoRelatorioViewImplUiBinder.class); private Presenter presenter; @UiField MenuView menu; @UiField MaterialDatePicker datePickerDataInicial, datePickerDataFinal; @UiField MaterialCheckBox checkBoxSolicitante, checkBoxAtendente, checkBoxGestor; public GeracaoRelatorioViewImpl() { initWidget(uiBinder.createAndBindUi(this)); // A data inicial e final não pode ser no futuro devido à data de criação datePickerDataInicial.setDateMax(new Date()); datePickerDataFinal.setDateMax(new Date()); // Não permitir que a data final seja menor que a inicial datePickerDataInicial.addCloseHandler(event -> { datePickerDataFinal.setDateMin(datePickerDataInicial.getDate() != null ? datePickerDataInicial.getDate() : new Date(0L)); }); datePickerDataFinal.addCloseHandler(event -> { datePickerDataInicial.setDateMax(datePickerDataFinal.getDate() != null ? datePickerDataFinal.getDate() : new Date()); }); } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public MenuView getMenuView() { return menu; } @UiHandler("buttonGerar") void onClickGerar(ClickEvent event) { if (presenter != null) { String htmlRelatorio = presenter.gerarRelatorio(datePickerDataInicial.getDate(), datePickerDataFinal.getDate(), checkBoxSolicitante.getValue(), checkBoxAtendente.getValue(), checkBoxGestor.getValue()); if (htmlRelatorio != null) { presenter.onGerarRelatorioClicked(htmlRelatorio); } else { Window.alert("Não foi possível gerar o relatório"); } } } }
true
1947984b58490cc73a2ea977473591f94cce40ec
Java
vinzynth/catroidCalculator
/app/src/test/java/catrobat/calculator/test/CalculationsTest.java
UTF-8
2,769
2.890625
3
[ "Apache-2.0" ]
permissive
package catrobat.calculator.test; import junit.framework.TestCase; import catrobat.calculator.Calculations; import catrobat.calculator.Parser; /** * Created by chrl on 01/06/16. * <p/> * TestClass for Calculation methods */ public class CalculationsTest extends TestCase { public void testDoAddition() { int result = Calculations.doAddition(4, 5); assertEquals(9, result); } public void testDoSubtraction() { int result = Calculations.doSubtraction(6, 5); assertEquals(1, result); } public void testDoMultiplication() { int result = Calculations.doMultiplication(4, 5); assertEquals(20, result); } public void testDoDivision() { int result = Calculations.doDivision(4, 2); assertEquals(2, result); } public void testParser() throws Exception { assertEquals(Parser.doCalculation("12*12"), 144); assertEquals(Parser.doCalculation("-12*12"), -144); assertEquals(Parser.doCalculation("12*-12"), -144); assertEquals(Parser.doCalculation("-12*-12"), 144); assertEquals(Parser.doCalculation("12/12"), 1); assertEquals(Parser.doCalculation("-12/12"), -1); assertEquals(Parser.doCalculation("-12/-12"), 1); assertEquals(Parser.doCalculation("12*12-"), 144); assertEquals(Parser.doCalculation("-12*12-"), -144); assertEquals(Parser.doCalculation("12*-12-"), -144); assertEquals(Parser.doCalculation("-12*-12-"), 144); assertEquals(Parser.doCalculation("12*12*-"), 144); assertEquals(Parser.doCalculation("-12*12*-"), -144); assertEquals(Parser.doCalculation("12*-12*-"), -144); assertEquals(Parser.doCalculation("-12*-12*-"), 144); assertEquals(Parser.doCalculation("12*12*"), 144); assertEquals(Parser.doCalculation("-12*12*"), -144); assertEquals(Parser.doCalculation("12*-12*"), -144); assertEquals(Parser.doCalculation("-12*-12*"), 144); assertEquals(Parser.doCalculation("12*12-12*12"), 0); assertEquals(Parser.doCalculation("12*12-12*-12"), 288); assertEquals(Parser.doCalculation("12*12-12*12*-"), 0); assertEquals(Parser.doCalculation("12*12-12*-12*-"), 288); assertEquals(Parser.doCalculation("12*12-12*12-"), 0); assertEquals(Parser.doCalculation("12*12-12*-12-"), 288); assertEquals(Parser.doCalculation("12*12-12*12*"), 0); assertEquals(Parser.doCalculation("12*12-12*-12*"), 288); assertEquals(Parser.doCalculation("12*12-12*-12++++++++++++++++++++////////////******************-----------------"), 288); assertEquals(Parser.doCalculation("3+4*5+6"), 29); assertEquals(Parser.doCalculation(""), 0); } }
true
78f2e9f98c444f9d072a6c5589c80e3eddfa3ed2
Java
Sebastriune/Assignment-4---User-Sign-Up-Page
/IfElseIf/src/Exercise3_4.java
UTF-8
1,061
3.765625
4
[]
no_license
import javax.swing.JOptionPane; public class Exercise3_4 { public static void main(String[] args) { String numPeople = JOptionPane.showInputDialog("Enter the number of people"); String numPlayers = JOptionPane.showInputDialog("Enter the number of players"); Short ShortNumPeople = Short.parseShort(numPeople); Short ShortNumPlayers = Short.parseShort(numPlayers); int groupSize=0; int teamSize=0; // &&, ||, !, ==, >, <, >=, <= if(ShortNumPeople>10) { groupSize = ShortNumPeople/2; } else if (ShortNumPeople>=3 && ShortNumPeople<=10) { groupSize = ShortNumPeople/3; } else { System.out.println ("The number of people has to be at least 3."); } if(ShortNumPlayers>=11 && ShortNumPlayers<=55) { teamSize = ShortNumPlayers/11; } else { teamSize = 1; } JOptionPane.showMessageDialog(null, "The number of people is " + numPeople + ".\n" + "Group size is " + groupSize + ".\n" + "The number of player is " + numPlayers + ".\n" + "Team size is " + teamSize + "."); } }
true
6f95b7b18b0de1a7763d92b4165c48138e8858cb
Java
fajarmuhf/Pemrograman-3
/UTS/FallFruit/src/Game/Sql/SaveGame.java
UTF-8
15,412
2.6875
3
[]
no_license
package Game.Sql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import Game.utility.*; public class SaveGame { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/FallFruit"; // Database credentials static final String USER = "root"; static final String PASS = ""; public void getHighscoreByLevel(int level,int indexSkor,ArrayList<Player> player ){ Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM `skor` as a,player as b WHERE a.id_player = b.id AND a.id_level = "+level+" ORDER BY skor DESC"; System.out.print(""+sql); ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set int i=0; while(rs.next()){ //Retrieve by column name if(i < indexSkor){ String Username = rs.getString("username"); int skor = rs.getInt("skor"); Player pemain = new Player(); pemain.setUsername(Username); pemain.setSkor(skor); player.add(pemain); } i++; } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try } public boolean cekPlayer(String username,String password,PlayerLevel player){ Connection conn = null; Statement stmt = null; boolean kembali=false; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM player WHERE Username='"+username+"' AND Password ='"+password+"'"; System.out.print(""+sql); ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); String Username = rs.getString("username"); String Password = rs.getString("password"); String Email = rs.getString("email"); player.setId(id); player.setUsername(Username); player.setPassword(Password); player.setEmail(Email); kembali=true; } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return kembali; } public boolean mendapatkanLevel(String username,String password,PlayerLevel player){ Connection conn = null; Statement stmt = null; boolean kembali=false; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM `detail level` as a,player as b WHERE a.id_player = b.id AND b.Username='"+username+"' AND b.Password ='"+password+"'"; System.out.print(""+sql); ResultSet rs = stmt.executeQuery(sql); player.setUnlock(new ArrayList<Integer>()); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int unlock = rs.getInt("unlock"); player.addUnlock(unlock); kembali=true; } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return kembali; } public void daftarkanPemain(String username,String password,String email){ Connection conn = null; PreparedStatement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Inserting records into the table..."); stmt = conn.prepareStatement("INSERT INTO player(`id`, `username`, `password`, `email`) SELECT COUNT(id)+1,?,?,? FROM player WHERE 1"); stmt.setString(1, username); stmt.setString(2, password); stmt.setString(3, email); stmt.executeUpdate(); stmt = conn.prepareStatement("INSERT INTO `detail level`(`id`, `id_level`, `id_player`, `unlock`) SELECT COUNT(id)+1 , ? , ? , ? FROM `detail level` WHERE 1"); stmt.setInt(1, 1); stmt.setInt(2, getIdByUsername(username,password)); stmt.setInt(3, 1); stmt.executeUpdate(); stmt = conn.prepareStatement("INSERT INTO `detail level`(`id`, `id_level`, `id_player`, `unlock`) SELECT COUNT(id)+1 , ? , ? , ? FROM `detail level` WHERE 1"); stmt.setInt(1, 2); stmt.setInt(2, getIdByUsername(username,password)); stmt.setInt(3, 0); stmt.executeUpdate(); stmt = conn.prepareStatement("INSERT INTO `detail level`(`id`, `id_level`, `id_player`, `unlock`) SELECT COUNT(id)+1 , ? , ? , ? FROM `detail level` WHERE 1"); stmt.setInt(1, 3); stmt.setInt(2, getIdByUsername(username,password)); stmt.setInt(3, 0); stmt.executeUpdate(); System.out.println("Inserted records into the table..."); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); } public int getIdByUsername(String username,String password){ Connection conn = null; Statement stmt = null; int Idplayer=0; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM player WHERE Username='"+username+"' AND Password = '"+password+"'"; System.out.print(""+sql); ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); Idplayer = id; } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return Idplayer; } public boolean daftarPlayer(String username,String password,String email){ Connection conn = null; Statement stmt = null; boolean cekUsername=true; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM player WHERE Username='"+username+"'"; System.out.print(""+sql); ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); cekUsername=false; } if(cekUsername){ daftarkanPemain(username,password,email); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return cekUsername; } public void simpanSkor(int idUser,int level,int Skor) { Connection conn = null; PreparedStatement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Inserting records into the table..."); stmt = conn.prepareStatement("INSERT INTO `skor`(`id`, `id_player`, `id_level`, `skor`, `tanggal`) SELECT count(*)+1, ? , ? , ? , ? FROM skor WHERE 1"); stmt.setInt(1, idUser); stmt.setInt(2, level); stmt.setInt(3, Skor); stmt.setString(4, new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); stmt.executeUpdate(); System.out.println("Inserted records into the table..."); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main public void naikLevel(int id, int level) { Connection conn = null; PreparedStatement stmt = null; int LevelNaik = level+1; if(LevelNaik <= 3){ try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Updating records into the table..."); String sql = "UPDATE `detail level` SET `unlock`=? WHERE `id_level`= ? AND `id_player`= ?"; stmt = conn.prepareStatement(sql); System.out.print(sql); stmt.setInt(1, 1); stmt.setInt(2, LevelNaik); stmt.setInt(3, id); stmt.executeUpdate(); System.out.println("Inserted records into the table..."); //STEP 6: Clean-up environment stmt.close(); conn.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); } } }
true
fd928384a01de9e713e387c92d43c8e8d5bab9ff
Java
iamkuaileshizhe/MRC
/app/src/main/java/com/neocom/mobilerefueling/bean/HeTongRespBean.java
UTF-8
8,450
2.203125
2
[]
no_license
package com.neocom.mobilerefueling.bean; /** * Created by admin on 2017/11/13. */ public class HeTongRespBean extends BaseBean { /** * bring : {"id":"838391cb670d4c03bb7813e9a0458283","batchNum":"HT000002","contractNum":"测试合同","fuelModel":"3","fuelCode":null,"nationalStandard":"国三","fuelPosition":null,"fuelTotal":"123","fuelDone":"723","batchStatus":"未完成提油","price":"12312","payStatus":"已付款","supplyId":"c4c8c4338cc44ee9ac4d4ab9af2449ac","supplyName":"231","supplyTel":"23123","buyTime":"2017-11-04","buyer":"231231","buyerTel":"2312","remark":"3123123","createId":null,"createTime":"2017-11-03 10:14:27","updateId":null,"updateTime":"2017-11-10 10:58:17","status":null,"fileName":null,"createName":null,"updateName":null,"fuelModelName":"-10号柴油","fileList":null} */ private BringBean bring; public BringBean getBring() { return bring; } public void setBring(BringBean bring) { this.bring = bring; } public static class BringBean { /** * id : 838391cb670d4c03bb7813e9a0458283 * batchNum : HT000002 * contractNum : 测试合同 * fuelModel : 3 * fuelCode : null * nationalStandard : 国三 * fuelPosition : null * fuelTotal : 123 * fuelDone : 723 * batchStatus : 未完成提油 * price : 12312 * payStatus : 已付款 * supplyId : c4c8c4338cc44ee9ac4d4ab9af2449ac * supplyName : 231 * supplyTel : 23123 * buyTime : 2017-11-04 * buyer : 231231 * buyerTel : 2312 * remark : 3123123 * createId : null * createTime : 2017-11-03 10:14:27 * updateId : null * updateTime : 2017-11-10 10:58:17 * status : null * fileName : null * createName : null * updateName : null * fuelModelName : -10号柴油 * fileList : null */ private String id; private String batchNum; private String contractNum; private String fuelModel; private String fuelCode; private String nationalStandard; private String fuelPosition; private String fuelTotal; private String fuelDone; private String batchStatus; private String price; private String payStatus; private String supplyId; private String supplyName; private String supplyTel; private String buyTime; private String buyer; private String buyerTel; private String remark; private String createId; private String createTime; private String updateId; private String updateTime; private String status; private String fileName; private String createName; private String updateName; private String fuelModelName; private String fileList; private String supplyCusName; public String getSupplyCusName() { return supplyCusName; } public void setSupplyCusName(String supplyCusName) { this.supplyCusName = supplyCusName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBatchNum() { return batchNum; } public void setBatchNum(String batchNum) { this.batchNum = batchNum; } public String getContractNum() { return contractNum; } public void setContractNum(String contractNum) { this.contractNum = contractNum; } public String getFuelModel() { return fuelModel; } public void setFuelModel(String fuelModel) { this.fuelModel = fuelModel; } public String getFuelCode() { return fuelCode; } public void setFuelCode(String fuelCode) { this.fuelCode = fuelCode; } public String getNationalStandard() { return nationalStandard; } public void setNationalStandard(String nationalStandard) { this.nationalStandard = nationalStandard; } public String getFuelPosition() { return fuelPosition; } public void setFuelPosition(String fuelPosition) { this.fuelPosition = fuelPosition; } public String getFuelTotal() { return fuelTotal; } public void setFuelTotal(String fuelTotal) { this.fuelTotal = fuelTotal; } public String getFuelDone() { return fuelDone; } public void setFuelDone(String fuelDone) { this.fuelDone = fuelDone; } public String getBatchStatus() { return batchStatus; } public void setBatchStatus(String batchStatus) { this.batchStatus = batchStatus; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPayStatus() { return payStatus; } public void setPayStatus(String payStatus) { this.payStatus = payStatus; } public String getSupplyId() { return supplyId; } public void setSupplyId(String supplyId) { this.supplyId = supplyId; } public String getSupplyName() { return supplyName; } public void setSupplyName(String supplyName) { this.supplyName = supplyName; } public String getSupplyTel() { return supplyTel; } public void setSupplyTel(String supplyTel) { this.supplyTel = supplyTel; } public String getBuyTime() { return buyTime; } public void setBuyTime(String buyTime) { this.buyTime = buyTime; } public String getBuyer() { return buyer; } public void setBuyer(String buyer) { this.buyer = buyer; } public String getBuyerTel() { return buyerTel; } public void setBuyerTel(String buyerTel) { this.buyerTel = buyerTel; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateId() { return updateId; } public void setUpdateId(String updateId) { this.updateId = updateId; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public String getUpdateName() { return updateName; } public void setUpdateName(String updateName) { this.updateName = updateName; } public String getFuelModelName() { return fuelModelName; } public void setFuelModelName(String fuelModelName) { this.fuelModelName = fuelModelName; } public String getFileList() { return fileList; } public void setFileList(String fileList) { this.fileList = fileList; } } }
true
eeffecc508f37973cca4b3b3349af8348ef09ca2
Java
Pratheeban233/spring-data-jpa
/src/main/java/com/jpa/repository/vehicle/ManufacturerRepository.java
UTF-8
228
1.757813
2
[]
no_license
package com.jpa.repository.vehicle; import com.jpa.model.vehicle.Manufacturer; import org.springframework.data.jpa.repository.JpaRepository; public interface ManufacturerRepository extends JpaRepository<Manufacturer,Long> { }
true
07b7694d8f39cada675ad9a0731bf91ffac0884b
Java
Geeksongs/djl-demo
/aws/lambda-model-serving/src/main/java/com/examples/Request.java
UTF-8
1,535
1.75
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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.examples; import java.util.HashMap; import java.util.Map; public class Request { private String inputImageUrl; private String artifactId; private Map<String, String> filters; public String getInputImageUrl() { return inputImageUrl; } public void setInputImageUrl(String inputImageUrl) { this.inputImageUrl = inputImageUrl; } public String getArtifactId() { if (artifactId == null) { artifactId = "ai.djl.mxnet:resnet"; if (filters == null) { filters = new HashMap<>(); } filters.putIfAbsent("layers", "18"); } return artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public Map<String, String> getFilters() { return filters; } public void setFilters(Map<String, String> filters) { this.filters = filters; } }
true
d167191acc3d09ec7bedd0591c6c58d81b95f536
Java
skbharti1/javamarch20
/Day11_0704/src/Reader_Writer_Demo1.java
UTF-8
994
2.953125
3
[]
no_license
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Reader_Writer_Demo1 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File file = new File("c:/demo/abc.txt"); FileInputStream fis = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fis); BufferedReader bfReader = new BufferedReader(reader); int data; while( (data = bfReader.read()) !=-1) { System.out.print((char)data); } bfReader.close(); // File file = new File("c:/demo/xyz.txt"); // FileOutputStream fos = new FileOutputStream(file); // OutputStreamWriter writer = new OutputStreamWriter(fos); // // writer.write("Welcome to file write..."); // writer.close(); } }
true
6901dca314db5f72f20082fb7de124d303e8b293
Java
EastUp/NDKPractice
/ffmpegmusic/src/main/java/com/east/ffmpegmusic/media/listener/MediaPreparedListener.java
UTF-8
112
1.648438
2
[]
no_license
package com.east.ffmpegmusic.media.listener; public interface MediaPreparedListener { void onPrepared(); }
true
c12f1f5e952e2302c4989f73e1306fb093b195c5
Java
hieuthinh-cse/icommerce
/iam/src/main/java/vn/icommerce/iam/infra/springsecurity/ForbiddenRequestHandler.java
UTF-8
1,526
2.234375
2
[]
no_license
package vn.icommerce.iam.infra.springsecurity; import static vn.icommerce.sharedkernel.domain.model.DomainCode.FORBIDDEN; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.entity.ContentType; import org.springframework.context.MessageSource; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import vn.icommerce.iam.infra.rest.ApiResp; /** * Handles forbidden request. */ @Component public class ForbiddenRequestHandler implements AccessDeniedHandler { private final MessageSource messageSource; private final ObjectMapper objectMapper; public ForbiddenRequestHandler( MessageSource messageSource, ObjectMapper objectMapper) { this.messageSource = messageSource; this.objectMapper = objectMapper; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { var apiResp = new ApiResp() .setCode(FORBIDDEN.value()) .setMessage(messageSource.getMessage(FORBIDDEN.valueAsString(), null, request.getLocale())); response.setContentType(ContentType.APPLICATION_JSON.toString()); var out = response.getOutputStream(); objectMapper.writeValue(out, apiResp); out.flush(); } }
true
3b2ac0090b220a9c52a8b2d467bc6c04beba08cb
Java
garybai/demo
/unnamed-demo/src/main/java/com/example/unnameddemo/io/nio/chat/ChatTest1.java
UTF-8
923
2.859375
3
[]
no_license
package com.example.unnameddemo.io.nio.chat; import java.io.IOException; import java.util.Scanner; /** * chat 测试类 * * @author Gary * @date 2020/2/28 18:31 * @since jdk1.8 **/ public class ChatTest1 { public static void main(String[] args) throws IOException { ChatClient chatClient = new ChatClient(); new Thread(){ @Override public void run(){ while (true) { try { chatClient.receiveMsg(); Thread.sleep(2000); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } }.start(); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()){ String s = scanner.nextLine(); chatClient.sendMsg(s); } } }
true
cddbede761c1932d7585fa03747274628fc16f97
Java
SVLKI/springone
/springhzel/src/main/java/com/cast/springhzel/EurekaClientConfiguration.java
UTF-8
1,065
2.078125
2
[]
no_license
package com.cast.springhzel; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.discovery.EurekaClientConfig; @Configuration public class EurekaClientConfiguration { @Bean(name = "eurekaClientConfigBean") public EurekaClientConfig eurekaClientConfig(@Value("${clientid:admin}") String uiClientId, @Value("${secret:admin}") String uiClientSecret, @Value("${eureka.client.config.defaultUrl:localhost:9761/eureka/}") String eurekaClientUri) throws Exception { EurekaClientConfigBean eurekaClientConfig = new EurekaClientConfigBean(); Map<String, String> urls = new HashMap<>(); String defaultZone = "http://" + uiClientId + ":" + uiClientSecret + "@" + eurekaClientUri; urls.put("defaultZone", defaultZone); eurekaClientConfig.setServiceUrl(urls); return eurekaClientConfig; } }
true
37e510773472b42ec1811ea114c77cfc5113e3dd
Java
guswns3371/eclipse-workspace
/guswns/src/guswns/test03.java
UTF-8
232
2.234375
2
[]
no_license
package guswns; public class test03 { public static void main(String[] args) { // TODO Auto-generated method stub float f = 0f; for (int i = 0; i < 10; i++) { f=f+0.1f; System.out.println("f="+f); } } }
true
4d5b521132689d42fda9eada31e7d637c026a017
Java
patelagni21/largestoffive
/largestoffive.java
UTF-8
337
2.9375
3
[]
no_license
public class LargestOfFive { public static void main(String args[]) { int largest = Integer.parseInt(args[0]); for(int i=1;i<args.length;i++) { if(largest<Integer.parseInt(args[i])) largest = Integer.parseInt(args[i]); } System.out.println(largest); } }
true
22e379147ddb6c65cfab0d68ac788add0c1de50f
Java
leelingco/opendental
/java/OpenDentBusiness/Mobile/DiseaseDefms.java
UTF-8
3,717
2.515625
3
[]
no_license
// // Translated by CS2J (http://www.cs2j.com): 2/15/2016 8:01:06 PM // package OpenDentBusiness.Mobile; import OpenDentBusiness.Db; import OpenDentBusiness.DiseaseDef; import OpenDentBusiness.DiseaseDefs; import OpenDentBusiness.Mobile.Crud.DiseaseDefmCrud; import OpenDentBusiness.Mobile.DiseaseDefm; import OpenDentBusiness.POut; /** * */ public class DiseaseDefms { /** * Gets one Medicationm from the db. */ public static DiseaseDefm getOne(long customerNum, long diseaseNum) throws Exception { return DiseaseDefmCrud.selectOne(customerNum,diseaseNum); } /** * The values returned are sent to the webserver. */ public static List<long> getChangedSinceDiseaseDefNums(DateTime changedSince) throws Exception { return DiseaseDefs.getChangedSinceDiseaseDefNums(changedSince); } /** * The values returned are sent to the webserver. */ public static List<DiseaseDefm> getMultDiseaseDefms(List<long> diseaseDefNums) throws Exception { List<DiseaseDef> DiseaseDefList = DiseaseDefs.GetMultDiseaseDefs(diseaseDefNums); List<DiseaseDefm> DiseaseDefmList = ConvertListToM(DiseaseDefList); return DiseaseDefmList; } /** * First use GetChangedSince. Then, use this to convert the list a list of 'm' objects. */ public static List<DiseaseDefm> convertListToM(List<DiseaseDef> list) throws Exception { List<DiseaseDefm> retVal = new List<DiseaseDefm>(); for (int i = 0;i < list.Count;i++) { retVal.Add(DiseaseDefmCrud.ConvertToM(list[i])); } return retVal; } /** * Only run on server for mobile. Takes the list of changes from the dental office and makes updates to those items in the mobile server db. Also, make sure to run DeletedObjects.DeleteForMobile(). */ public static void updateFromChangeList(List<DiseaseDefm> list, long customerNum) throws Exception { for (int i = 0;i < list.Count;i++) { list[i].CustomerNum = customerNum; DiseaseDefm diseaseDefm = DiseaseDefmCrud.SelectOne(customerNum, list[i].DiseaseDefNum); if (diseaseDefm == null) { //not in db DiseaseDefmCrud.Insert(list[i], true); } else { DiseaseDefmCrud.Update(list[i]); } } } /** * used in tandem with Full synch */ public static void deleteAll(long customerNum) throws Exception { String command = "DELETE FROM diseasedefm WHERE CustomerNum = " + POut.long(customerNum); Db.nonQ(command); } } /* Only pull out the methods below as you need them. Otherwise, leave them commented out. ///<summary></summary> public static List<DiseaseDefm> Refresh(long patNum){ string command="SELECT * FROM diseasedefm WHERE PatNum = "+POut.Long(patNum); return Crud.DiseaseDefmCrud.SelectMany(command); } ///<summary>Gets one DiseaseDefm from the db.</summary> public static DiseaseDefm GetOne(long customerNum,long diseaseDefNum){ return Crud.DiseaseDefmCrud.SelectOne(customerNum,diseaseDefNum); } ///<summary></summary> public static long Insert(DiseaseDefm diseaseDefm){ return Crud.DiseaseDefmCrud.Insert(diseaseDefm,true); } ///<summary></summary> public static void Update(DiseaseDefm diseaseDefm){ Crud.DiseaseDefmCrud.Update(diseaseDefm); } ///<summary></summary> public static void Delete(long customerNum,long diseaseDefNum) { string command= "DELETE FROM diseasedefm WHERE CustomerNum = "+POut.Long(customerNum)+" AND DiseaseDefNum = "+POut.Long(diseaseDefNum); Db.NonQ(command); } */
true
8ce8406e29ffeb5964b8ca1809f2c46d31e553a6
Java
paullewallencom/primefaces-978-1-7832-8069-8
/_src/techbuzz/src/main/java/com/packtpub/techbuzz/repositories/PostRepository.java
UTF-8
560
2.0625
2
[ "Apache-2.0" ]
permissive
/** * */ package com.packtpub.techbuzz.repositories; import java.util.List; import com.packtpub.techbuzz.entities.Post; import com.packtpub.techbuzz.entities.Rating; /** * @author skatam * */ public interface PostRepository extends GenericRepository<Integer, Post> { public List<Post> findPostsByUserId(Integer userId); public List<Post> searchPosts(String query); public List<Post> findPostsByTagLabel(String label); public void populateUserRatings(List<Post> posts); public void savePostRating(Rating rating); }
true
e04dc6b9cc7701989323ae302f8380af99df3451
Java
GabrielRossin/POO
/Aula 7/Equacao2Grau/src/Equacao.java
UTF-8
1,544
3.234375
3
[]
no_license
import Exception.DeltaNegativoEx; import Exception.SegundoGrauEx; public class Equacao { public double a; public double b; public double c; public Equacao(double a, double b, double c) throws SegundoGrauEx { if(this.getA() != 0 && this.getB() != 0 && this.getC() != 0) { this.setA(a); this.setB(b); this.setC(c); } else { if(a==0) { throw new SegundoGrauEx("Erro: Valor de a = 0!"); } } } public String calculaValor() throws DeltaNegativoEx { double delta = ((b*b)-(4*a*c)); double x1; double x2; if(delta>=0) { x1 = ( ( -b + (Math.sqrt (delta) ) ) / ( 2*a ) ); x2 = ( ( -b + (Math.sqrt (delta) ) ) / ( 2*a ) ); return "Valor de x1 ="+ x1 + " Valor de x2 ="+ x2; } else { throw new DeltaNegativoEx("Valor de delta < 0"); } } @Override public String toString() { return "Equacao{" + "a =" + this.getA() + ", b =" + this.getB() + ", c =" + this.getC() + '}'; } public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } }
true
dda11500b217b7caa82cb6b22882f023fbb6221c
Java
sunnySrc/LongquanForum-Android
/app/src/main/java/com/mobcent/discuz/ui/WebOptPopup.java
UTF-8
1,930
2.234375
2
[]
no_license
package com.mobcent.discuz.ui; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.appbyme.dev.R; /** * Created by sun on 2016/9/9. */ public class WebOptPopup extends BasePopup implements View.OnClickListener{ private final String mUrl; public WebOptPopup(Context context, String url) { super(context); setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); mUrl = url; ViewGroup viewGroup = (ViewGroup) getContentView().findViewById(R.id.post_collect).getParent(); viewGroup.setVisibility(View.GONE); getContentView().findViewById(R.id.post_browser_open).setOnClickListener(this); getContentView().findViewById(R.id.post_link_copy).setOnClickListener(this); } @Override protected int getLayoutRes() { return R.layout.topic_toolbar_panel; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.post_browser_open: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mUrl)); mContext.startActivity(intent); break; case R.id.post_link_copy: ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); // 将文本内容放到系统剪贴板里。 cm.setPrimaryClip(ClipData.newPlainText(null, mUrl)); Toast.makeText(mContext, "已复制到剪贴板", Toast.LENGTH_LONG).show(); //管理帖子 break; } dismiss(); } @Override public void dismiss() { super.dismiss(); } }
true
5fc00017feca96ff482393688becb40369800046
Java
ihmcrobotics/simulation-construction-set-2
/src/session-visualizer/java/us/ihmc/scs2/sessionVisualizer/controllers/ControllerListCell.java
UTF-8
649
2.484375
2
[ "Apache-2.0" ]
permissive
package us.ihmc.scs2.sessionVisualizer.controllers; import javafx.scene.control.ListCell; import javafx.scene.layout.Pane; public class ControllerListCell<T extends SCSDefaultUIController> extends ListCell<T> { public ControllerListCell() { } @Override protected void updateItem(T item, boolean empty) { super.updateItem(item, empty); setText(null); if (!empty && item != null) { Pane mainPane = item.getMainPane(); setGraphic(mainPane); // Somehow the width of the cell is too large... mainPane.prefWidthProperty().bind(widthProperty().subtract(20)); } } }
true
df4efc47fa1e3ddbec12d3319a4b1a68bf71138c
Java
girtel/Net2Plan
/Net2Plan-Examples/src/main/java/com/net2plan/examples/smartCity/utn/UtnConstants.java
UTF-8
1,892
2.3125
2
[ "BSD-2-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2017 Pablo Pavon Marino and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the 2-clause BSD License * which accompanies this distribution, and is available at * https://opensource.org/licenses/BSD-2-Clause * * Contributors: * Pablo Pavon Marino and others - initial API and implementation *******************************************************************************/ package com.net2plan.examples.smartCity.utn; /** This class includes several constants used in this package */ class UtnConstants { /** The name of the Net2Plan attribute for storing the V0 or C0 (free speed) parameter of a link in the user equilibrium model */ public static final String ATTRNAME_C0A = "UTN_C0A"; // the V0 or C0 (free speed) parameter of a link in the user equilibrium model /** The name of the Net2Plan attribute for storing the velocity according to the BPR model */ public static final String ATTRNAME_CA = "UTN_CA"; // the velocity according to the BPR model /** The name of the Net2Plan attribute for storing the monitored information (ground truth) coming from measures. Can appear in arcs (link) and in demands * */ public static final String ATTRNAME_MONITOREDVEHICUCLERATE = "UTN_MONITOREDVEHICLERATE"; // the monitored information (ground truth) coming for measures. Can appear in arcs and in demands /** Help method for computing the Ca according to the BPR model * @param c0 c0 parameter * @param alpha alpha parameter * @param va va parameter * @param Qa Qa parameter * @param gamma gamma parameter * @return see above */ public static double bprCaComputation (double c0 , double alpha , double va , double Qa , double gamma) { return c0 * (1 + alpha * Math.pow(va / Qa , gamma) ); } }
true
09726843685fca09eb9acc812d9026413cf6ab5f
Java
JoInJae/admin-project
/src/main/java/com/superbrain/data/constant/Role.java
UTF-8
320
2.0625
2
[]
no_license
package com.superbrain.data.constant; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum Role { S("Super", "슈퍼 관리자"), H("Hospital", "병원 관리자"), C("Center", "센터 관리자"); private final String eng; private final String kor; }
true
7e640fe9d30eb752221cd7db529da442d49401f7
Java
liyun1030/baselibrary
/basetool/src/main/java/com/common/base/tool/CollectionUtils.java
UTF-8
2,868
3.203125
3
[]
no_license
package com.common.base.tool; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * 集合工具 * Created by Yan Kai on 2016/6/13. */ public class CollectionUtils { public static boolean isEqualCollection(final Collection<?> a, final Collection<?> b) { if (a.size() != b.size()) { return false; } final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b); if (helper.cardinalityA.size() != helper.cardinalityB.size()) { return false; } for (final Object obj : helper.cardinalityA.keySet()) { if (helper.freqA(obj) != helper.freqB(obj)) { return false; } } return true; } public static <O> Map<O, Integer> getCardinalityMap(final Iterable<? extends O> coll) { final Map<O, Integer> count = new HashMap<>(); for (final O obj : coll) { final Integer c = count.get(obj); if (c == null) { count.put(obj, 1); } else { count.put(obj, c + 1); } } return count; } private static class CardinalityHelper<O> { final Map<O, Integer> cardinalityA; final Map<O, Integer> cardinalityB; public CardinalityHelper(final Iterable<? extends O> a, final Iterable<? extends O> b) { cardinalityA = CollectionUtils.getCardinalityMap(a); cardinalityB = CollectionUtils.getCardinalityMap(b); } public int freqA(final Object obj) { return getFreq(obj, cardinalityA); } public int freqB(final Object obj) { return getFreq(obj, cardinalityB); } private int getFreq(final Object obj, final Map<?, Integer> freqMap) { final Integer count = freqMap.get(obj); if (count != null) { return count; } return 0; } } /** * 对字符串进行由小到大排序 * @param str String[] 需要排序的字符串数组 */ public static String strSort(String str){ char [] b = str.toCharArray(); Arrays.sort(b); String str2 = String.copyValueOf(b); return str2; } /** * 取两个字符串中的相同字符 * @param str1 * @param str2 * @return */ public static String getSameChar(String str1, String str2) { String s=""; for(int i=0;i<str1.length();i++)//获取第一个字符串中的单个字符 for(int j=0;j<str2.length();j++)//获取第er个字符串中的单个字符 { if(str1.charAt(i)==str2.charAt(j))//判断字符是否相同 s=s+str1.charAt(i); } return s; } }
true
5811c1f70933b01ea17a10e14102f539eaacadb3
Java
r0shanbhagat/SelfieCelebriti
/commonframework/src/main/java/com/base/commonframework/preference/PreferenceManager.java
UTF-8
4,424
1.96875
2
[]
no_license
package com.base.commonframework.preference; import android.content.Context; import com.base.commonframework.baselibrary.utility.AbstractPrefUtility; /** * CommonPreferenceManager Class : * * @author Roshan Kumar * @version 3.0 * @since 1/12/18 * <p> * Kindly put the data carefully in this class as we are not going to clear this preference file even on #Logout. */ public class PreferenceManager extends AbstractPrefUtility { private static final String APP_PERSISTENT_PREF_FILE = "app_persistent.xml"; private static final int APP_PREF_VER = 1; private static final String PREF_GRADLE_PLATFORM = "gradle_platform"; private static final String PREF_DEVICE_MANUFACTURER = "pref_device_manufacturer"; private static final String PREF_DEVICE_MODEL = "pref_device_model"; private static final String PREF_DEVICE_ID = "pref_device_id"; private static final String PREF_OS_VERSION = "pref_os_version"; private static final String PREF_VERSION_CODE = "pref_version_code"; private static final String PREF_VERSION_NAME = "pref_version_name"; private static final String LANGUAGE_CODE = "language_code"; private static final String PREF_GRADLE_BASE_URL = "gradle_base_url"; private static final String PREF_GRADLE_COUNTRY_CODE = "gradle_country_code"; private static final String PREF_FlURRY_KEY = "gradle_flurry_key"; private static PreferenceManager preferenceManager; public PreferenceManager(Context ctx, Builder build) { super(ctx, build); } public static synchronized PreferenceManager getInstance(Context ctx) { if (null == preferenceManager) { preferenceManager = new PreferenceManager(ctx, new AbstractPrefUtility.Builder() .setAppPrefFile(APP_PERSISTENT_PREF_FILE) .setAppPrefVersion(APP_PREF_VER) .build()); } return preferenceManager; } public String getPlatform() { return getStringPreference(PREF_GRADLE_PLATFORM, "android"); } public void setPlatform(String platform) { setStringPreference(PREF_GRADLE_PLATFORM, platform); } public String getDeviceManufacturer() { return getStringPreference(PREF_DEVICE_MANUFACTURER, ""); } public void setDeviceManufacturer(String deviceManufacturer) { setStringPreference(PREF_DEVICE_MANUFACTURER, deviceManufacturer); } public String getDeviceModel() { return getStringPreference(PREF_DEVICE_MODEL, ""); } public void setDeviceModel(String deviceModel) { setStringPreference(PREF_DEVICE_MODEL, deviceModel); } public String getDeviceId() { return getStringPreference(PREF_DEVICE_ID, ""); } public void setDeviceId(String deviceId) { setStringPreference(PREF_DEVICE_ID, deviceId); } public String getOsVersion() { return getStringPreference(PREF_OS_VERSION, ""); } public void setOsVersion(String osVersion) { setStringPreference(PREF_OS_VERSION, osVersion); } public int getAppVersionCode() { return getIntPreference(PREF_VERSION_CODE, 0); } public void setAppVersionCode(int versionNumber) { setIntPreference(PREF_VERSION_CODE, versionNumber); } public String getAppVersionName() { return getStringPreference(PREF_VERSION_NAME, ""); } public void setAppVersionName(String versionName) { setStringPreference(PREF_VERSION_NAME, versionName); } public String getCountryCode() { return getStringPreference(PREF_GRADLE_COUNTRY_CODE, "in"); } public void setCountryCode(String countryCode) { setStringPreference(PREF_GRADLE_COUNTRY_CODE, countryCode); } public String getLanguageCode() { return getStringPreference(LANGUAGE_CODE, "en"); } public void setLanguageCode(String languageCode) { setStringPreference(LANGUAGE_CODE, languageCode); } public String getBaseUrl() { return getStringPreference(PREF_GRADLE_BASE_URL, ""); } public void setBaseUrl(String baseUrl) { setStringPreference(PREF_GRADLE_BASE_URL, baseUrl); } public String getFlurryApiKey() { return getStringPreference(PREF_FlURRY_KEY, ""); } public void setFlurryApiKey(String flurryApiKey) { setStringPreference(PREF_FlURRY_KEY, flurryApiKey); } }
true
aa1342f35535374f1794320b6584849fc67d8099
Java
luojbin/designPattern
/src/main/java/com/luojbin/designPattern/p4_factory/pizza/CheesePizza.java
UTF-8
469
3.359375
3
[]
no_license
package com.luojbin.designPattern.p4_factory.pizza; public class CheesePizza extends Pizza { @Override public void prepare() { System.out.println("准备一个芝士饼底"); } @Override public void bake() { System.out.println("烤10分钟"); } @Override public void cut() { System.out.println("切成6块"); } @Override public void box() { System.out.println("装在1号盒子"); } }
true
28d4ea41cb2d263d0a139b4cd61250d364396c96
Java
metav0id/QuickTipp
/src/main/java/de/defdesign/quicktipp/ux/UxUtilities.java
UTF-8
796
2.8125
3
[]
no_license
package de.defdesign.quicktipp.ux; import java.sql.SQLOutput; public class UxUtilities { /** * Einfache Utility-Methoden für die Darstellung der User-Interfaces */ public static void clearScreen() { for(int i = 0; i<20; i++) { System.out.println(); } } public static void waitSeconds(int miliseconds) { try { Thread.sleep(miliseconds); } catch (InterruptedException ie) { // kann nicht auftreten, da lediglich als Warteschleife genutzt } } public static void separator() { System.out.println("----------------------------------------------------"); System.out.println("----------------------------------------------------"); System.out.println(); } }
true
c50ec328a00ad5aff48961b8e053d231f2edba85
Java
ANNASBlackHat/Learn-oop
/src/main/Main.java
UTF-8
714
2.890625
3
[]
no_license
package main; import entity.Category; import entity.Product; import implement.ProductImplement; public class Main { public static void main(String[] args) { ProductImplement implement = new ProductImplement(); Product product = new Product(); product.setId(1); product.setName("Coffe cappucino"); product.setPrice(40000); product.setSku("PRD001"); Category category = new Category(); category.setId(1); category.setName("Beverage"); product.setCategory(category); implement.insert(product); Product product1 = (Product) implement.getData(); System.out.println("Nama Produk : "+product1.getName()); } }
true
5a24e293c64388f086dcc6cfe66f9b41efa684db
Java
AutohomeCorp/frostmourne
/frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/service/core/template/AlertTemplateService.java
UTF-8
6,677
2.046875
2
[ "MIT" ]
permissive
package com.autohome.frostmourne.monitor.service.core.template; import java.util.*; import java.util.stream.Collectors; import javax.annotation.Resource; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate.AlertTemplate; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate.DataSource; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.autohome.frostmourne.common.contract.PagerContract; import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.repository.IAlertTemplateRepository; import com.autohome.frostmourne.monitor.model.contract.*; import com.autohome.frostmourne.monitor.model.enums.TemplateType; import com.autohome.frostmourne.monitor.model.enums.DataSourceType; import com.autohome.frostmourne.monitor.service.admin.IDataAdminService; import com.autohome.frostmourne.monitor.transform.AlertTemplateTransformer; import com.github.pagehelper.PageInfo; @Service public class AlertTemplateService implements IAlertTemplateService { @Resource private IAlertTemplateRepository alertTemplateRepository; @Lazy @Resource private IDataAdminService dataAdminService; @Override public void save(AlertTemplateSaveForm form, String account) { AlertTemplate alertTemplate = AlertTemplateTransformer.saveForm2Model(form); alertTemplate.setModifier(account); if (alertTemplate.getId() == null || alertTemplate.getId() == 0L) { // 新增 alertTemplate.setCreator(account); alertTemplateRepository.insertSelective(alertTemplate); } else { alertTemplateRepository.updateByPrimaryKeySelective(alertTemplate); } } @Override public Optional<AlertTemplateContract> getContract(Long id) { return alertTemplateRepository.getById(id).map(r -> { AlertTemplateContract contract = AlertTemplateTransformer.model2Contract(r); this.fillExtend2Contracts(Collections.singletonList(contract)); return contract; }); } @Override public PagerContract<AlertTemplateContract> findContract(AlertTemplateQueryForm form) { PageInfo<AlertTemplate> recordPage = alertTemplateRepository.find(form); List<AlertTemplateContract> contracts = AlertTemplateTransformer.model2Contract(recordPage.getList()); this.fillExtend2Contracts(contracts); return new PagerContract<>(contracts, recordPage.getPageSize(), recordPage.getPageNum(), (int)recordPage.getTotal()); } private void fillExtend2Contracts(List<AlertTemplateContract> contracts) { if (CollectionUtils.isEmpty(contracts)) { return; } this.fillTemplateTypeTreeExtend2Contracts(contracts); } private void fillTemplateTypeTreeExtend2Contracts(List<AlertTemplateContract> contracts) { this.fillTemplateTypeTreeCommonExtend2Contracts(contracts); this.fillTemplateTypeTreeDataNameExtend2Contracts(contracts); } private void fillTemplateTypeTreeCommonExtend2Contracts(List<AlertTemplateContract> contracts) { contracts.stream().filter(item -> TemplateType.COMMON.equals(item.getTemplateType())).forEach(item -> { item.setTemplateTypeTreeValues(Collections.singletonList(TemplateType.COMMON.name())); item.setTemplateTypeTreeLabels(Collections.singletonList(TemplateType.COMMON.getDisplayName())); }); } private void fillTemplateTypeTreeDataNameExtend2Contracts(List<AlertTemplateContract> contracts) { // 关联数据名 List<AlertTemplateContract> dataNameContracts = contracts.stream().filter(item -> TemplateType.DATA_NAME.equals(item.getTemplateType())).collect(Collectors.toList()); if (CollectionUtils.isEmpty(dataNameContracts)) { return; } List<String> unionCodes = dataNameContracts.stream().map(AlertTemplateContract::getTemplateUnionCode).distinct().collect(Collectors.toList()); Map<String, DataNameContract> dataNameMap = dataAdminService.mapDataNameByNames(unionCodes); // 获取数据源名称 List<Long> dataSourceIds = dataNameMap.values().stream().map(DataNameContract::getDataSourceId).collect(Collectors.toList()); Map<Long, DataSource> dataSourceMap = dataAdminService.mapDataSourceByIds(dataSourceIds); dataNameContracts.forEach(item -> { if (DataSourceType.http.name().equalsIgnoreCase(item.getTemplateUnionCode())) { // http item.setTemplateTypeTreeValues(Arrays.asList(TemplateType.DATA_NAME.name(), DataSourceType.http.name())); item.setTemplateTypeTreeLabels(Arrays.asList(TemplateType.DATA_NAME.getDisplayName(), DataSourceType.http.name())); } else { DataNameContract contract = dataNameMap.get(item.getTemplateUnionCode()); if (contract == null) { item.setTemplateTypeTreeValues(Arrays.asList(TemplateType.DATA_NAME.name(), item.getTemplateUnionCode())); item.setTemplateTypeTreeLabels(Arrays.asList(TemplateType.DATA_NAME.getDisplayName(), item.getTemplateUnionCode())); } else { item.setTemplateTypeTreeValues(Arrays.asList(TemplateType.DATA_NAME.name(), contract.getDatasourceType().name(), String.valueOf(contract.getDataSourceId()), contract.getDataName())); item.setTemplateTypeTreeLabels(Arrays.asList(TemplateType.DATA_NAME.getDisplayName(), contract.getDatasourceType().name(), Optional.ofNullable(dataSourceMap.get(contract.getDataSourceId())).map(DataSource::getDatasourceName) .orElse(String.valueOf(contract.getDataSourceId())), contract.getDisplayName())); } } }); } @Override public List<TreeDataOption> listTemplateTypeOptions() { return Arrays.stream(TemplateType.values()).map(this::parseTemplateTypeOption).collect(Collectors.toList()); } private TreeDataOption parseTemplateTypeOption(TemplateType templateType) { TreeDataOption option = new TreeDataOption(templateType.name(), templateType.getDisplayName()); if (templateType == TemplateType.DATA_NAME) { option.setChildren(this.listTemplateTypeOptionDataName()); } return option; } private List<TreeDataOption> listTemplateTypeOptionDataName() { return dataAdminService.listDataOptions(); } }
true
dc8fe90584e3588727abfc29027e4c769c03b55c
Java
JesusESD/EDA-P8
/Menu.java
UTF-8
4,007
3.328125
3
[]
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 arboles; import java.util.Scanner; /** * * @author Patch */ public class Menu { public void mainMenu(){ int op; Scanner sc = new Scanner(System.in); System.out.println("¿Qué tipo de árbol deseas emplear?"); System.out.println("1.- Árbol binario"); System.out.println("2.- Árbol binario de búsqueda"); op = sc.nextInt(); switch(op){ case 1: menuArbolBinario(); break; case 2: break; } } public void menuArbolBinario(){ int op1 = 1, clave, clave2, iter = 0, lado; Scanner sc1 = new Scanner(System.in); System.out.println("¿Cuál es la raíz de tu árbol?"); clave = sc1.nextInt(); Nodo parent = new Nodo(clave); ArbolBin aB = new ArbolBin(parent); do{ System.out.println("¿Qué desea realizar?"); System.out.println("0.- Terminar la ejecución"); System.out.println("1.- Agregar nodo"); System.out.println("2.- Buscar nodo"); System.out.println("3.- BFS"); System.out.println("4.- Notación Prefija"); System.out.println("5.- Notación Infija"); System.out.println("6.- Notación Postfija"); op1 = sc1.nextInt(); switch(op1){ case 0: break; case 1: if(iter == 0) agregarInicial(aB); else{ System.out.println("¿Cuál es la clave de su nodo?"); clave = sc1.nextInt(); System.out.println("¿Cuál es el padre de su nodo?"); clave2 = sc1.nextInt(); System.out.println("¿Su hijo es izquierdo (0) o derecho (1)?"); lado = sc1.nextInt(); aB.add(aB.busqueda(clave2), new Nodo(clave), lado); } break; case 2: System.out.println("¿Qué clave desea buscar?"); clave = sc1.nextInt(); if(aB.busqueda(clave) != null) System.out.println("La clave existe dentro del árbol"); else System.out.println("La clave no existe dentro del árbol"); break; case 3: aB.breadthFirst(); break; case 4: aB.prefija(); break; case 5: aB.infija(); break; case 6: aB.posfija(); break; default: break; } iter++; }while(op1 != 0); } public void agregarInicial(ArbolBin aB){ Scanner sc1 = new Scanner(System.in); int clave, lado, hermano; String bro; System.out.println("Estos nodos son hijos de la raíz"); System.out.println("¿Cuál es la clave de su nodo?"); clave = sc1.nextInt(); Nodo son = new Nodo(clave); System.out.println("¿Su nodo es hijo izquierdo (0) o derecho (1)?"); lado = sc1.nextInt(); aB.add(aB.root, son, lado); System.out.println("¿Su nodo tiene hermano? \n1.- Sí \n2.- No"); bro = sc1.next(); if("1".equals(bro)){ System.out.println("¿Cuál es la clave del nodo hermano?"); hermano = sc1.nextInt(); if(lado == 0) aB.add(aB.root, new Nodo(hermano), 1); else aB.add(aB.root, new Nodo(hermano), 0); } } }
true
51018d8b1f30f500565d5d4828e3a940532223b9
Java
Blackghost56/SelectUser
/app/src/main/java/com/selectuser/EmployeeModel.java
UTF-8
1,154
2.375
2
[]
no_license
package com.selectuser; import androidx.databinding.ObservableBoolean; import androidx.databinding.ObservableField; import androidx.databinding.ObservableLong; public class EmployeeModel { public ObservableLong id = new ObservableLong(); public ObservableField<String> name = new ObservableField<>(); public ObservableField<String> surname = new ObservableField<>(); public ObservableField<String> organization = new ObservableField<>(); public ObservableField<String> positionO = new ObservableField<>(); public ObservableBoolean isSelected = new ObservableBoolean(false); private final Employee employee; public EmployeeModel(Employee employee){ this.employee = employee; id.set(employee.id); name.set(employee.name); surname.set(employee.surname); organization.set(employee.organizationName); positionO.set(employee.position); } public Employee getEmployee() { return employee; } public boolean isSelected() { return isSelected.get(); } public void setSelected(boolean selected) { isSelected.set(selected); } }
true
46bfd34fa8549d030a473052f893fdd86183afff
Java
seges/acris
/acris-showcase/acris-showcase-appconstructor/src/main/java/sk/seges/acris/scaffold/mvp/DefaultViewConfiguration.java
UTF-8
914
2.15625
2
[]
no_license
/** * */ package sk.seges.acris.scaffold.mvp; import java.util.Date; import java.util.HashMap; import java.util.Map; import sk.seges.acris.scaffold.model.view.compose2.Singleselect; import sk.seges.pap.printer.table.column.TextColumnPrinter; /** * @author ladislav.gazo */ public class DefaultViewConfiguration { private Map<Class<?>, Map<String, Class<?>>> renderComponents = new HashMap<Class<?>, Map<String,Class<?>>>(); public DefaultViewConfiguration() { HashMap<String, Class<?>> tableRenderComponents = new HashMap<String, Class<?>>(); tableRenderComponents.put(String.class.getName(), TextColumnPrinter.class); tableRenderComponents.put(Date.class.getName(), TextColumnPrinter.class); renderComponents.put(Singleselect.class, tableRenderComponents); } public Class<?> getRenderComponent(Class<?> type, String returnType) { return renderComponents.get(type).get(returnType); } }
true
8885d78f0a1237a689219ad33effbcd68c08a7a9
Java
Alexst1989/ocp7-preparing
/Java7OCP/src/main/java/ru/alexst/certification/ocp/par14/concurrency/executors/FutureExecutorsAndCallable.java
UTF-8
1,197
3.546875
4
[]
no_license
package ru.alexst.certification.ocp.par14.concurrency.executors; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; public class FutureExecutorsAndCallable { public static void main(String[] args) { Callable<Integer> c = new MyCallable(); ExecutorService ex = Executors.newCachedThreadPool(); Future<Integer> f = ex.submit(c); // finishes in the future try { Integer v = f.get(); // blocks until done System.out.println("Ran:" + v); } catch (InterruptedException | ExecutionException iex) { System.out.println("Failed"); } } } class MyCallable implements Callable<Integer> { @Override public Integer call() { // Obtain a random number from 1 to 10 int count = ThreadLocalRandom.current().nextInt(1, 110); for (int i = 1; i <= count; i++) { System.out.println("Running..." + i); } return count; } }
true
213dcc53cd2b0312af04a0393b91a21a1f1d3432
Java
yournameincode/orderingsystem
/clientfeign/src/main/java/com/southwind/ClientFeignApplication.java
UTF-8
829
1.703125
2
[]
no_license
package com.southwind; import com.myrule.MyRule; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients @ServletComponentScan @EnableHystrix @EnableHystrixDashboard @RibbonClient(name = "menu",configuration = MyRule.class ) public class ClientFeignApplication { public static void main(String[] args) { SpringApplication.run(ClientFeignApplication.class,args); } }
true
fd366669c34568d7e7068e045af9b93c56dcadae
Java
ciberscanner/RappiPeliculas
/Android/app/src/main/java/com/kiwabolab/rappipeliculas/vista/activity/Detalle.java
UTF-8
5,585
2.015625
2
[]
no_license
package com.kiwabolab.rappipeliculas.vista.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.kiwabolab.rappipeliculas.R; import com.kiwabolab.rappipeliculas.modelo.Pelicula; import com.kiwabolab.rappipeliculas.modelo.PeliculaFull; import com.kiwabolab.rappipeliculas.network.Servidor; import com.kiwabolab.rappipeliculas.presentacion.detalle.ItemContrato; import com.kiwabolab.rappipeliculas.presentacion.detalle.ItemPresenter; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; import de.mateware.snacky.Snacky; public class Detalle extends AppCompatActivity implements ItemContrato.VistaItem { //---------------------------------------------------------------------------------------------- //Variables public static final String EXTRA_PELICULA = "EXTRA_PELICULA"; private Pelicula pelicula; private String idvideo=""; private Servidor servidor; @BindView(R.id.img_movie_image) ImageView banner; @BindView(R.id.img_movie_image2) ImageView completa; @BindView(R.id.fab_star)FloatingActionButton fab_star; @BindView(R.id.containeritem) LinearLayout view; @BindView(R.id.txt_movie_description)TextView descripcion; @BindView(R.id.txt_movie_title) CollapsingToolbarLayout title; @BindView(R.id.txtestrellas) TextView estrellas; @BindView(R.id.txt_movie_title2) TextView title2; @BindView(R.id.txtvotos) TextView votos; @BindView(R.id.txt_movie_date) TextView calendar; private ItemPresenter presenter; //---------------------------------------------------------------------------------------------- // @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalle); ButterKnife.bind(this); servidor = new Servidor(); displayHomeAsUpEnabled(); presenter = new ItemPresenter(this); getExtrasFromIntent(); } //---------------------------------------------------------------------------------------------- //Constructor private void displayHomeAsUpEnabled() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } //---------------------------------------------------------------------------------------------- // private void getExtrasFromIntent() { pelicula = (Pelicula) getIntent().getSerializableExtra(EXTRA_PELICULA); getInfoMovie(pelicula.id+"", this); //title.setTitle(pelicula.title); title2.setText(pelicula.title); votos.setText(pelicula.voteCount+""); calendar.setText(pelicula.releaseDate); estrellas.setText(pelicula.voteAverage+"/10"); descripcion.setText(pelicula.overview); Picasso.with(getApplicationContext()).load(servidor.getImg(pelicula.backdropPath)).into(banner); Picasso.with(getApplicationContext()).load(servidor.getImg(pelicula.posterPath)).into(completa); } //---------------------------------------------------------------------------------------------- // @Override public void getInfoMovie(String id, Context context) { presenter.getInfoMovie(id,context); } //---------------------------------------------------------------------------------------------- // @Override public void mostrarErrorInfoMovie() { } //---------------------------------------------------------------------------------------------- // @Override public void setInfoMovie(PeliculaFull info) { if(info.getVideos().getResults().size()==0){ showWarning("Esta pelicula no tiene videos"); }else{ idvideo = info.getVideos().getResults().get(0).getKey(); /*if(!memoria.botonVideo()){ tutorial(); }*/ } } //---------------------------------------------------------------------------------------------- // public void ShowVideo(View view){ if(idvideo.isEmpty()){ showWarning("Estamos consultando los videos itenta en un momento"); }else{ Intent i = new Intent(this, Video.class); i.putExtra("video", idvideo); startActivity(i); } } //---------------------------------------------------------------------------------------------- // private void showError(String msg){ Snacky.builder() .setView(view) .setText(msg) .setDuration(Snacky.LENGTH_INDEFINITE) .setActionText(android.R.string.ok) .error() .show(); } //---------------------------------------------------------------------------------------------- // private void showWarning(String msg){ Snacky.builder() .setView(view) .setText(msg) .setDuration(Snacky.LENGTH_INDEFINITE) .setActionText(android.R.string.ok) .warning() .show(); } }
true
e3b7b8e17049e5827efead90dfaf2c2e7703dd64
Java
tichen47/Leetcode
/src/linked_list/ListNode.java
UTF-8
1,135
3.78125
4
[]
no_license
package linked_list; //Definition for singly-linked list. public class ListNode { public int val; public ListNode next = null; public ListNode(int x) { val = x; } // Create a linked list by array public ListNode(int[] arr) { if (arr == null || arr.length == 0) throw new IllegalArgumentException("arr can not be empty"); this.val = arr[0]; ListNode curNode = this; for (int i = 1; i < arr.length; i++) { curNode.next = new ListNode(arr[i]); curNode = curNode.next; } } @Override public String toString() { StringBuilder s = new StringBuilder(""); ListNode curNode = this; while (curNode != null) { s.append(Integer.toString(curNode.val)); s.append(" -> "); curNode = curNode.next; } s.append("NULL"); return s.toString(); } // Test public static void main(String[] args) { int[] array = new int[] { 1, 2, 3, 4, 5 }; ListNode head = new ListNode(array); System.out.println(head); } }
true
0b3a836e353b4496ff07146f1de9c07490d8e095
Java
kri225/virgingames_api
/src/main/java/com/virgingames/constants/Path.java
UTF-8
210
1.6875
2
[]
no_license
package com.virgingames.constants; /** * Created by Jay */ public class Path { public static final String BINGO= "/bingo";// this is called constant in java, which is variable with you cant change }
true
2319b5c848b761d2e3ac25c5ebb31483f2dbc056
Java
shaath/Kiran
/PrimusBank/src/com/PrimusBank/Tests/LoginTC.java
UTF-8
636
1.8125
2
[]
no_license
package com.PrimusBank.Tests; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class LoginTC { public static void main(String[] args) { WebDriver driver=new FirefoxDriver(); driver.get("http://primusbank.qedgetech.com/"); driver.manage().window().maximize(); driver.findElement(By.id("txtuId")).sendKeys("Admin"); driver.findElement(By.id("txtPword")).sendKeys("Admin"); driver.findElement(By.id("login")).click(); driver.findElement(By.xpath("//*[@id='Table_02']/tbody/tr/td[3]/a/img")).click(); driver.close(); } }
true
16b2e1b2693c822fd60033448afc2f6a4fc4bd97
Java
yuanguojie/new1
/Hospital_Fixed_Asset_Management_System/src/main/java/Mapper/T_InStockDtlMapper.java
UTF-8
459
1.804688
2
[]
no_license
package Mapper; import java.util.List; import domain.T_InStockDtl; public interface T_InStockDtlMapper { int deleteByPrimaryKey(Integer id); int insert(T_InStockDtl record); int insertSelective(T_InStockDtl record); T_InStockDtl selectByPrimaryKey(Integer id); List<T_InStockDtl> selectByAssetId(T_InStockDtl record); int updateByPrimaryKeySelective(T_InStockDtl record); int updateByPrimaryKey(T_InStockDtl record); }
true
b131193e89e27e49aa7447c33c5af1405d1b8119
Java
wangjianxins/rediswang
/src/main/java/com/wang/redis/config/RedisWangAuthConfigure.java
UTF-8
2,389
2.140625
2
[]
no_license
package com.wang.redis.config; import com.wang.redis.Exception.RedisWangException; import com.wang.redis.aop.HotKeyIntercepter; import com.wang.redis.client.host.AbstractExecute; import com.wang.redis.client.host.DefaultExecute; import com.wang.redis.client.host.RedisWangClient; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Arrays; import java.util.HashSet; //自动装配类 @Configuration @ConditionalOnClass(RedisWangClient.class) @EnableConfigurationProperties(RedisWangProperties.class) public class RedisWangAuthConfigure { private static final Logger logger = Logger.getLogger(RedisWangAuthConfigure.class); @Autowired private RedisWangProperties redisWangProperties; @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "redis",value = "enabled",havingValue = "true") public RedisWangClient getClient(){ String type = redisWangProperties.getType(); if(null == type){ throw new RedisWangException("配置参数redis.type未配置"); } RedisWangClient redisWangClient = null; switch (type){ case "host": redisWangClient= new RedisWangClient(redisWangProperties.getAddress(),redisWangProperties.getPort()); break; case "sentinel": redisWangClient = new RedisWangClient(redisWangProperties.getMasterName(),redisWangProperties.getSentinels()); break; case "cluster": String clusterHost = redisWangProperties.getClusterHost(); String[] clusterArray = clusterHost.split(","); redisWangClient = new RedisWangClient(new HashSet(Arrays.asList(clusterArray)),15000); break; } return redisWangClient; } @Bean public HotKeyIntercepter hotKeyIntercepter(){ return new HotKeyIntercepter(); } }
true
5f726a114a44f59eade420405866d7231743b734
Java
intesar/timesheet-management-community
/Timesheet-DAO/src/com/abbh/timesheet/daoImpl/ValueListHandlerDAOImpl.java
UTF-8
2,047
2.171875
2
[]
no_license
/* * ValueListHandlerDAOImpl.java * * Created on Aug 13, 2007, 10:21:04 PM * * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.abbh.timesheet.daoImpl; import com.abbhsoft.framework.valueListHandler.ValueListHandlerDAO; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.PersistenceException; import javax.persistence.Query; import org.springframework.orm.jpa.JpaCallback; import org.springframework.orm.jpa.JpaTemplate; /** * * @author shannan */ public class ValueListHandlerDAOImpl extends JpaTemplate implements ValueListHandlerDAO { public ValueListHandlerDAOImpl() { } public Long getCount(final String ql, final Map<String, Object> params) { return (Long) execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Query query = em.createNamedQuery(ql); Set<String> keys = params.keySet(); for ( String key : keys ) { query.setParameter(key, params.get(key)); } Long result = (Long) query.getSingleResult(); return result; } }); } public List find(final String ql, final Map<String, Object> params, final int min, final int max) { return (List) execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Query query = em.createNamedQuery(ql); Set<String> keys = params.keySet(); for ( String key : keys ) { query.setParameter(key, params.get(key)); } query.setFirstResult(min); query.setMaxResults(max); List result = query.getResultList(); return result; } }); } }
true
2c0f6f24a473afe01006f82c928565a0486c5c41
Java
shahmansi279/NyBestSellersApp
/TestApps/Apps/NyTimesBestSellersApp/app/src/main/java/project/com/nybestsellerbooksapp/model/BSFavoriteBookItem.java
UTF-8
702
2.03125
2
[]
no_license
package project.com.nybestsellerbooksapp.model; /** * Created by Mansi on 1/18/18. */ public class BSFavoriteBookItem { private String bookIsbn; private String bookTitle; private String bookAuthor; public String getBookIsbn() { return bookIsbn; } public void setBookIsbn(String bookIsbn) { this.bookIsbn = bookIsbn; } public String getBookTitle() { return bookTitle; } public void setBookTitle(String bookTitle) { this.bookTitle = bookTitle; } public String getBookAuthor() { return bookAuthor; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } }
true
9d316e38b912e6ff5a653d12163a6f05998cebc6
Java
aaa2550/numberone-auth-Maven
/src/main/java/com/numberONe/tempEntity/ProviderInfo.java
UTF-8
2,987
2
2
[]
no_license
package com.numberONe.tempEntity; import java.util.Date; public class ProviderInfo { private Integer id; private Date createTime; private Date updateTime; private String companyName; private String name; private String province; private String city; private String address; private String linkmanName; private String linkmanTel; private String email; private String remark; private String provinceName; private String cityName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName == null ? null : companyName.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } public String getCity() { return city; } public void setCity(String city) { this.city = city == null ? null : city.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getLinkmanName() { return linkmanName; } public void setLinkmanName(String linkmanName) { this.linkmanName = linkmanName == null ? null : linkmanName.trim(); } public String getLinkmanTel() { return linkmanTel; } public void setLinkmanTel(String linkmanTel) { this.linkmanTel = linkmanTel == null ? null : linkmanTel.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName == null ? null : provinceName.trim(); } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName == null ? null : cityName.trim(); } }
true
37ae292afc0d2dee051ab78bf614d115d11c4ebe
Java
arifshaikh789/hibernate
/hibernateCompleteOpration/src/hibernateCompletePackage/StudentTest.java
UTF-8
707
2.40625
2
[]
no_license
package hibernateCompletePackage; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class StudentTest { public static void main(String ar[]) { Configuration cf=new Configuration(); cf.configure("cfg.xml"); SessionFactory factory = cf.buildSessionFactory(); Session session = factory.openSession(); StudentDto sd=new StudentDto(); sd.setSid(1); sd.setSname("arif"); sd.setAddress("indore"); Transaction tx = session.beginTransaction(); session.save(sd); System.out.println("Object saved successfully.....!!"); tx.commit(); session.close(); factory.close(); } }
true
c01dc3010e81a7cc07ef81cc93971a2749576d7c
Java
Romain-P/Dofus-2.44.0-JProtocol
/network/com/ankamagames/dofus/network/messages/game/idol/IdolListMessage.java
UTF-8
3,194
2.28125
2
[]
no_license
// Created by Heat the 2017-10-20 01:53:25+02:00 package com.ankamagames.dofus.network.messages.game.idol; import org.heat.dofus.network.NetworkType; import org.heat.dofus.network.NetworkMessage; import org.heat.shared.io.DataWriter; import org.heat.shared.io.DataReader; import org.heat.shared.io.BooleanByteWrapper; import com.ankamagames.dofus.network.InternalProtocolTypeManager; @SuppressWarnings("all") public class IdolListMessage extends NetworkMessage { public static final int PROTOCOL_ID = 6585; // array,vi16 public short[] chosenIdols; // array,vi16 public short[] partyChosenIdols; // array,com.ankamagames.dofus.network.types.game.idol.PartyIdol public com.ankamagames.dofus.network.types.game.idol.PartyIdol[] partyIdols; public IdolListMessage() {} public IdolListMessage( short[] chosenIdols, short[] partyChosenIdols, com.ankamagames.dofus.network.types.game.idol.PartyIdol[] partyIdols) { this.chosenIdols = chosenIdols; this.partyChosenIdols = partyChosenIdols; this.partyIdols = partyIdols; } public IdolListMessage( short[] chosenIdols, short[] partyChosenIdols, java.util.stream.Stream<com.ankamagames.dofus.network.types.game.idol.PartyIdol> partyIdols) { this.chosenIdols = chosenIdols; this.partyChosenIdols = partyChosenIdols; this.partyIdols = partyIdols.toArray(com.ankamagames.dofus.network.types.game.idol.PartyIdol[]::new); } @Override public int getProtocolId() { return 6585; } @Override public void serialize(DataWriter writer) { writer.write_ui16(chosenIdols.length); writer.write_array_vi16(this.chosenIdols); writer.write_ui16(partyChosenIdols.length); writer.write_array_vi16(this.partyChosenIdols); writer.write_ui16(partyIdols.length); for (int i = 0; i < partyIdols.length; i++) { writer.write_ui16(partyIdols[i].getProtocolId()); partyIdols[i].serialize(writer); } } @Override public void deserialize(DataReader reader) { int chosenIdols_length = reader.read_ui16(); this.chosenIdols = reader.read_array_vi16(chosenIdols_length); int partyChosenIdols_length = reader.read_ui16(); this.partyChosenIdols = reader.read_array_vi16(partyChosenIdols_length); int partyIdols_length = reader.read_ui16(); this.partyIdols = new com.ankamagames.dofus.network.types.game.idol.PartyIdol[partyIdols_length]; for (int i = 0; i < partyIdols_length; i++) { int partyIdols_it_typeId = reader.read_ui16(); com.ankamagames.dofus.network.types.game.idol.PartyIdol partyIdols_it = (com.ankamagames.dofus.network.types.game.idol.PartyIdol) InternalProtocolTypeManager.get(partyIdols_it_typeId); partyIdols_it.deserialize(reader); this.partyIdols[i] = partyIdols_it; } } @Override public String toString() { return "IdolListMessage(" + "chosenIdols=" + java.util.Arrays.toString(this.chosenIdols) + ", partyChosenIdols=" + java.util.Arrays.toString(this.partyChosenIdols) + ", partyIdols=" + java.util.Arrays.toString(this.partyIdols) + ')'; } }
true
e0ebbd514d718d9cee36877db401af5b9aa6ff75
Java
andersonfarias/matching
/src/main/java/farias/anderson/challenges/sortable/matching/data/clean/StringCleaner.java
UTF-8
840
3.703125
4
[ "MIT" ]
permissive
package farias.anderson.challenges.sortable.matching.data.clean; /** * Utility class to perform some "clean" operations on String objects. By * "clean", I mean operations that remove special characters, unnecessary * white-spaces, convert the String to lower case and so on. * * @author Anderson Farias */ public final class StringCleaner { /** * Characters to replace for white-space */ private static final String CLEAR_PATTERN = "[_\\-,;:%^]"; /** * Remove special characters of the given string, convert it to lower case * and remove unnecessary white-spaces * * @param s * string to clean * @return cleaned string */ public static final String clean( String s ) { return s.trim().toLowerCase().replaceAll( CLEAR_PATTERN, " " ); } /** * Private constructor */ private StringCleaner() { } }
true
0115e1b7c73fbabc3cdfc063f8fd9f8be58d193b
Java
bellmit/blackbox
/bb-core/src/main/java/com/blackbox/ids/core/repository/ocr/OCRClientMappingRepository.java
UTF-8
422
1.773438
2
[]
no_license
package com.blackbox.ids.core.repository.ocr; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import com.blackbox.ids.core.model.ocr.OCRClientMapping; public interface OCRClientMappingRepository extends JpaRepository<OCRClientMapping, Long>, QueryDslPredicateExecutor<OCRClientMapping> { public OCRClientMapping findById(Long id); }
true
9a80e8caa5472dc44abfae1c7db187dd5da0bc40
Java
eglrp/TR-Flink
/map-matching/src/main/java/com/konfuse/TestFmm.java
UTF-8
7,656
2.25
2
[]
no_license
package com.konfuse; import com.konfuse.fmm.FmmMatcher; import com.konfuse.road.*; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * @Auther todd * @Date 2020/1/8 */ public class TestFmm { public static long points_search_time = 0L; public static long points = 0L; public static void main(String[] args) throws Exception{ long memory = 0; String udobtPath = "udobt1.table"; // new ShapeFileRoadReader("C:\\Users\\Konfuse\\Desktop\\shapefile\\output\\network_dual.shp") RoadMap map = RoadMap.Load(new PostgresRoadReader()); map.construct(); FmmMatcher fmmMatcher = new FmmMatcher(2); System.out.println("read ubodt table."); System.gc(); memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long start = System.currentTimeMillis(); fmmMatcher.readUDOBTFile(udobtPath, map); long end = System.currentTimeMillis(); long build_time = end - start; System.out.println("UBODT read time :" + build_time + "ms"); System.gc(); memory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) - memory; System.out.println(Math.max(0, Math.round(memory)) + " bits used for UBODT table (estimate)" ); testMatch("D:\\SchoolWork\\HUST\\DataBaseGroup\\Roma\\experiment", fmmMatcher, map); System.out.println("coordinate convert time: " + RoadMap.convertTime + "ms"); System.out.println("Total search time: " + points_search_time / 1000.0 + "s"); System.out.println("Search speed: " + points * 1000.0 / points_search_time + "pt/s"); // GenerateTestGPSPoint test = new GenerateTestGPSPoint(); // List<GPSPoint> testRoads = test.generateTestGPSPoint(map); // List<GPSPoint> testGPSPoint = test.generateTestCase(testRoads); // List<GPSPoint> testGPSPoint = readGPSPoint("199_2014-02-28.txt"); // List<Road> c_path = fmmMatcher.constructCompletePathOptimized(matchedRoadPoints, map); // List<GPSPoint> c_path_gps = fmmMatcher.getCompletePathGPS(c_path); // System.out.println("************road***********"); // test.writeAsTxt(testRoads, "output/road.txt"); // System.out.println("***************************"); // System.out.println("************trajectory***********"); // test.writeAsTxt(testGPSPoint, "output/trajectory.txt"); // System.out.println("***************************"); // // System.out.println("************matched***********"); // write(matchedRoadPoints, "output/matched.txt"); // System.out.println("***************************"); // // System.out.println("*******complete path*******"); // test.writeAsTxt(c_path_gps, "output/c_path.txt"); // System.out.println("***************************"); } public static List<GPSPoint> readGPSPoint(String path) { List<GPSPoint> gpsPoints = new ArrayList<>(); BufferedReader reader; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { reader = new BufferedReader(new FileReader(path)); String line; while ((line = reader.readLine()) != null) { String[] items = line.split(";"); double x = Double.parseDouble(items[0]); double y = Double.parseDouble(items[1]); long time = simpleDateFormat.parse(items[2]).getTime() / 1000; gpsPoints.add(new GPSPoint(time, x, y)); } } catch (IOException | ParseException e) { e.printStackTrace(); } return gpsPoints; } public static void write(List<RoadPoint> points, String path) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(path)); for (RoadPoint point : points) { double x = point.point().getX(); double y = point.point().getY(); System.out.println(x + ";" + y); writer.write(x + ";" + y); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void testMatch(String path, FmmMatcher fmmMatcher, RoadMap map) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<GPSPoint> gpsPoints = new ArrayList<>(); File[] fileList = new File(path).listFiles(); BufferedReader reader = null; long search_time = 0; int trajectoryCount = 0, exceptCount = 0; long pointCount = 0, currentTrajectoryPointCount; for (File file : fileList) { currentTrajectoryPointCount = 0; // if (trajectoryCount == 1000) { // break; // } System.out.println("the " + (++trajectoryCount) + "th trajectory is being processed: " + file.getName()); try { reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { String[] items = line.split(";"); double x = Double.parseDouble(items[0]); double y = Double.parseDouble(items[1]); long time = simpleDateFormat.parse(items[2]).getTime() / 1000; gpsPoints.add(new GPSPoint(time, x, y)); ++currentTrajectoryPointCount; } } catch (IOException | ParseException e) { e.printStackTrace(); } try { long start = System.currentTimeMillis(); fmmMatcher.match(gpsPoints, map, 20, 0.002); long end = System.currentTimeMillis(); search_time += end - start; pointCount += currentTrajectoryPointCount; } catch (Exception e) { e.printStackTrace(); ++exceptCount; System.out.println((trajectoryCount) + "th trajectory failed"); // if (reader != null) { // try { // reader.close(); // } catch (IOException e2) { // e2.printStackTrace(); // } // } // // try{ // if(file.delete()) { // System.out.println(file.getName() + " 文件已被删除!"); // } else { // System.out.println("文件删除失败!"); // } // } catch(Exception e3){ // e3.printStackTrace(); // } } gpsPoints.clear(); } points = pointCount; points_search_time = search_time; System.out.println("trajectories processed: " + trajectoryCount); System.out.println("trajectories failed: " + exceptCount); System.out.println("trajectory points matched: " + pointCount); System.out.println("candidate search time: " + FmmMatcher.candidateSearchTime / 1000.0 + "s"); System.out.println("viterbi every step time: " + FmmMatcher.viterbiStepTime / 1000.0 + "s"); } }
true
3247327d1e33b5777dad4945dcbe4ca5efb014f4
Java
214140846/hackerda
/web/src/main/java/com/hackerda/platform/domain/grade/GradeFetchTask.java
UTF-8
1,163
2.328125
2
[ "MIT" ]
permissive
package com.hackerda.platform.domain.grade; import com.hackerda.platform.domain.student.StudentUserBO; import lombok.Data; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * 成绩抓取任务 */ @Getter @ToString public class GradeFetchTask { private final boolean tigerByUser; private final StudentUserBO tigerStudent; public GradeFetchTask(boolean tigerByUser, StudentUserBO tigerStudent) { this.tigerByUser = tigerByUser; this.tigerStudent = tigerStudent; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GradeFetchTask that = (GradeFetchTask) o; return new EqualsBuilder() .append(tigerStudent.getUrpClassNum(), that.tigerStudent.getUrpClassNum()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(tigerStudent.getUrpClassNum()) .toHashCode(); } }
true
bfd5cc3a7c98b474a3c93aaa3c7a41ffba0581c5
Java
EarunWu/order
/src/main/java/com/example/oder_putout/controller/AdminController.java
UTF-8
1,459
1.921875
2
[]
no_license
package com.example.oder_putout.controller; import com.example.oder_putout.entity.Goods; import com.example.oder_putout.respository.GoodsDao; import com.example.oder_putout.service.impl.AdminServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AdminController { @Autowired private AdminServiceImpl adminService; @Autowired private GoodsDao goodsDao; @RequestMapping("/goods_add") public String test(Model model){ return "goods_add"; } @RequestMapping("/goods_update") public String goodsUpdate(Model model,int gId,int orderId){ Goods goods=goodsDao.findgoodsById(gId); model.addAttribute("goods",goods); model.addAttribute("orderId",orderId); return "goods_update"; } @RequestMapping("/index") public String toIndex(Model model){ return "index"; } @RequestMapping("/tologin") public String tologin(int id,String password){ if(adminService.login(id,password)==1){ return "redirect:index"; } else return "login"; } @RequestMapping("/login") public String login(){ return "login"; } @RequestMapping("/qdAPI") public String qdAPI(){ return "qdAPI"; } }
true
c5d881055de5925169dd402adde5275f3da61a14
Java
Aivech/tau
/src/main/java/com/aivech/tau/power/GridUpdate.java
UTF-8
3,354
2.421875
2
[ "MIT" ]
permissive
package com.aivech.tau.power; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import java.util.Arrays; import java.util.Collection; public class GridUpdate { final UpdateAction action; RotaryNode node; BlockPos pos; Direction dir; private GridUpdate(UpdateAction action, RotaryNode node, BlockPos pos, Direction dir) { this.node = node; this.action = action; this.pos = pos; this.dir = dir; } public static void add(IRotaryBE block, World world, BlockPos blockPos, Direction orient, Collection<Direction> connectsTo) { RotaryNode node; if (block instanceof IRotaryUser) { node = new RotaryNode.Sink(blockPos, orient, connectsTo, block.getPowerVars()); } else if (block instanceof IRotarySource) { node = new RotaryNode.Source(blockPos, orient, connectsTo, block.getPowerVars()); } else if (block instanceof IRotaryTransform) { IRotaryTransform xform = (IRotaryTransform)block; node = new RotaryNode.Transform(blockPos, orient, connectsTo, xform.getTorqueFactor(), xform.getSpeedFactor(), block.getPowerVars()); } else if (block instanceof IRotaryClutch) { IRotaryClutch clutch = (IRotaryClutch)block; node = new RotaryNode.Clutch(blockPos, orient, connectsTo, clutch.isEngaged(), block.getPowerVars()); } else if (block instanceof IRotaryJunction) { node = new RotaryNode.Junction(blockPos, orient, connectsTo, ((IRotaryJunction)block).isMerge(), block.getPowerVars()); } else { node = new RotaryNode.Path(blockPos, orient, connectsTo, block.getPowerVars()); } Identifier id = DimensionType.getId(world.getDimension().getType()); RotaryGrid dimGrid = RotaryGrid.GRIDS.get(id); dimGrid.changeQueue.add(new GridUpdate(UpdateAction.ADD, node, null, null)); synchronized (dimGrid.lock) { dimGrid.lock.notifyAll(); } } // convenience method because Direction.ALL is an array public static void add(IRotaryBE block, World world, BlockPos blockPos, Direction orient, Direction[] connectsTo) { add(block, world, blockPos, orient, Arrays.asList(connectsTo)); } public static void remove(World world, BlockPos pos, Direction orient) { Identifier id = DimensionType.getId(world.getDimension().getType()); RotaryGrid dimGrid = RotaryGrid.GRIDS.get(id); dimGrid.changeQueue.add(new GridUpdate(UpdateAction.DEL, null, pos, orient)); synchronized (dimGrid.lock) { dimGrid.lock.notifyAll(); } } public static void removeAll(World world, BlockPos pos) { remove(world, pos, null); } public static void update(World world, BlockPos pos, Direction orient) { Identifier id = DimensionType.getId(world.getDimension().getType()); RotaryGrid dimGrid = RotaryGrid.GRIDS.get(id); dimGrid.changeQueue.add(new GridUpdate(UpdateAction.UPDATE, null, pos, orient)); synchronized (dimGrid.lock) { dimGrid.lock.notifyAll(); } } enum UpdateAction { ADD, DEL, UPDATE } }
true
06a25b1ad70d68c2a4b3a32886014b4444ab6655
Java
datacoper/dc-codegenerator
/src/main/java/com/datacoper/maven/generators/impl/EaoImplGenerator.java
UTF-8
704
2.046875
2
[]
no_license
package com.datacoper.maven.generators.impl; import com.datacoper.maven.generators.AbstractJavaGenerator; import com.datacoper.maven.metadata.TemplateModel; import com.datacoper.maven.util.StringUtil; public class EaoImplGenerator extends AbstractJavaGenerator { public EaoImplGenerator(TemplateModel templateModel) { super(templateModel); } @Override public String getTemplateName() { return "eaoImpl"; } @Override public String getPackage() { return StringUtil.format("com.{0}.cooperate.{1}.server.eao.impl", getCompany().getPackageName(), getModulePackageName()); } @Override public String getClassName() { return getEntityName()+"EAOImpl"; } }
true
8416ed1eaa9b30cc4912a6ee4d9600161e193fa9
Java
alexbrk/smoketest
/src/test/java/com/smoketest/tests/SearchTest.java
UTF-8
444
1.9375
2
[]
no_license
package com.smoketest.tests; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import com.smoketest.pages.SearchResultPage; import com.smoketest.pages.WishlistPage; import com.smoketest.util.Browser; public class SearchTest extends Browser { @Test public void searchDefaultItem() { SearchResultPage result = homePage.searchDefaultItem(); assertTrue(result.isSearchSuccessful()); } }
true
86b9cc736e59e118896aa402a7de55920c05bdb3
Java
Hangalik/projektlabor
/hu/bme/annaATbarbies/sokoban/view/ResultWindow.java
UTF-8
1,796
2.84375
3
[]
no_license
package hu.bme.annaATbarbies.sokoban.view; import hu.bme.annaATbarbies.sokoban.model.Floor; import hu.bme.annaATbarbies.sokoban.model.pushable.Controller; import org.apache.log4j.Logger; import javax.swing.*; import javax.swing.table.JTableHeader; import java.awt.*; import java.util.Collections; import java.util.List; public class ResultWindow extends JFrame { private JTable table; private JScrollPane scrollPane; private String[] columnNames = {"Place", "Player ID", "Points"}; private Object[][] data = { {0, "", 0}, {0, "", 0}, {0, "", 0}, {0, "", 0} }; public ResultWindow() { super("Results"); setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setLayout(new BorderLayout()); setMinimumSize(new Dimension(600, 280)); createAndShow(); Font f = new Font("Zapfino", Font.BOLD, 30); JTableHeader header = table.getTableHeader(); header.setFont(f); table.setFont(f); table.setRowHeight(50); this.add(scrollPane); setVisible(true); } private static final Logger logger = Logger.getLogger(ResultWindow.class); public void createAndShow() { List<Controller> workers = Floor.getInstance().getAllWorkers(); Collections.sort(workers); for (int i = 0; i < workers.size(); i++) { Controller wor = workers.get(i); data[i][0] = i + 1; data[i][1] = wor.getID(); data[i][2] = wor.getPoint(); logger.debug(String.format("%d. place: player%d with %d points.", i + 1, wor.getID(), wor.getPoint())); } table = new JTable(data, columnNames); scrollPane = new JScrollPane(table); } }
true
0f8f1ad5a3f185899d1a0a95218ab74150858290
Java
javarishi/LearnJMS
/src/main/java/com/h2kinfosys/learn/jms/TestMessageProducer.java
UTF-8
1,562
2.703125
3
[]
no_license
package com.h2kinfosys.learn.jms; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; public class TestMessageProducer { static String brokerURL = "tcp://localhost:61616"; public static void main(String[] args) throws JMSException { Connection conn = null; Session session = null; try { // Step 1 = Create ConnectionFactory ActiveMQConnectionFactory acf = new ActiveMQConnectionFactory(brokerURL); // Step 2 = createConnection conn = acf.createConnection(); conn.start(); //Step 3 - Create Session - Auto Commit // Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); session = conn.createSession(true, Session.SESSION_TRANSACTED); //Step 4 - Create Destination Destination queue = session.createQueue("TEST.H2K.Q1"); // Step 5 - Create Message Producer MessageProducer producer = session.createProducer(queue); // Step 6 - Create Message Message message = session.createTextMessage("Test String for Queue 1"); // Step 7 - send the message producer.send(message); // Step 8 - Session commit session.commit(); System.out.println("Message sent successfully"); }catch (JMSException e) { e.printStackTrace(); session.rollback(); }finally { if(conn != null) conn.close(); System.out.println("Connection closed"); } } }
true
26af61880d722133f617252a57c683c625bc9bfa
Java
ruixiangliu/ondex-knet-builder
/modules/cyjs_json/src/main/java/net/sourceforge/ondex/export/cyjsJson/ConceptType.java
UTF-8
477
1.539063
2
[]
no_license
package net.sourceforge.ondex.export.cyjsJson; /** * @author Ajit Singh * @version 07/03/17 */ public enum ConceptType { Gene, Protein, Compound, SNP, Cellular_Component, Pathway, Reaction, Enzyme, Enzyme_Classification, Phenotype, Publication, Biological_Process, Molecular_Function, Scaffold, Trait, Chromosome, RNA, Protein_Complex, Transport, Disease, Drug, DGES // , Protein Domain, Trait Ontology, Quantitative Trait Locus, Enzyme Classification, Protein Complex }
true
b969b2dd10175b23b2cb853cfe2f48286b6b7c7d
Java
js-superion/gomall.la
/legendshop_core/src/java/com/legendshop/core/security/AuthServiceImpl.java
UTF-8
7,741
2.21875
2
[ "Apache-2.0" ]
permissive
/* * * LegendShop 多用户商城系统 * * 版权所有,并保留所有权利。 * */ package com.legendshop.core.security; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.legendshop.core.security.model.UserDetail; import com.legendshop.model.entity.Function; import com.legendshop.model.entity.Role; import com.legendshop.model.entity.UserEntity; import com.legendshop.util.AppUtils; /** * 权限管理服务类 * * LegendShop 版权所有 2009-2011,并保留所有权利。 * * 官方网站:http://www.legendesign.net * */ public class AuthServiceImpl implements AuthService { /** The log. */ Logger log = LoggerFactory.getLogger(AuthServiceImpl.class); /** The jdbc template. */ private JdbcTemplate jdbcTemplate; /** * 从数据库中查找该用户User以及所拥有的角色和权限. * * @param username * the username * @return the user details * @throws UsernameNotFoundException * the username not found exception * @throws DataAccessException * the data access exception */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { // 获取用户信息 UserEntity user = null; try { user = findUserByName(username); } catch (Exception e) { log.error("can not load user by user name {}, exception message {}", username, e.getMessage()); } if (log.isDebugEnabled()) { log.debug("getUserByName calling with name {}, result {}", username, user); } if (AppUtils.isBlank(user)) { return null; } // 获取角色信息 Collection<GrantedAuthority> roles = findRolesByUser(user.getId()); if (AppUtils.isBlank(roles)) { throw new UsernameNotFoundException("User has no GrantedAuthority"); } // 获取权限信息 Collection<GrantedFunction> functoins = findFunctionsByUser(user.getId()); User minuser = new UserDetail(username, user.getPassword(), getBoolean(user.getEnabled()), true, true, true, roles, functoins, user.getId()); return minuser; } /** * * 拿到角色集合对应的权限集合 * */ @Cacheable(value = "GrantedFunction") public Collection<GrantedFunction> getFunctionsByRoles(Collection<? extends GrantedAuthority> roles) { log.debug("getFunctionsByRoles calling {}", roles); if (null == roles) { throw new IllegalArgumentException("Granted Roles cannot be null"); } Collection<GrantedFunction> grantedFunctions = new HashSet<GrantedFunction>(); for (GrantedAuthority grantedAuthority : roles) { Role role = getGrantedAuthority(grantedAuthority.getAuthority()); if (role != null) { List<Function> functions = role.getFunctions(); for (Function function : functions) { grantedFunctions.add(new GrantedFunctionImpl(function.getName())); } } } return grantedFunctions; } /** * Gets the boolean. * * @param b * the b * @return the boolean */ private boolean getBoolean(String b) { return "1".endsWith(b) ? true : false; } /** * Find functions by user. * * @param user * the user * @return the list */ private List<GrantedFunction> findFunctionsByUser(String userId) { String sql = "select DISTINCT f.name from ls_usr_role ur ,ls_role r,ls_perm p, ls_func f where r.enabled = '1' and ur.user_id= ? and ur.role_id=r.id and r.id=p.role_id and p.function_id=f.id"; log.debug("findFunctionsByUser,run sql {}, userId {}", sql, userId); return jdbcTemplate.query(sql, new Object[] { userId }, new RowMapper<GrantedFunction>() { public GrantedFunction mapRow(ResultSet rs, int index) throws SQLException { return new GrantedFunctionImpl(rs.getString("name")); } }); } /** * 找到用户 */ private UserEntity findUserByName(String name) { String sql = "select * from ls_user where enabled = '1' and name = ?"; log.debug("findUserByName, run sql {}, name {}", sql, name); return jdbcTemplate.queryForObject(sql, new Object[] { name }, new RowMapper<UserEntity>() { public UserEntity mapRow(ResultSet rs, int index) throws SQLException { UserEntity user = new UserEntity(); user.setEnabled(rs.getString("enabled")); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setNote(rs.getString("note")); user.setPassword(rs.getString("password")); return user; } }); } /** * 根据用户ID取得对应的角色 */ private List<GrantedAuthority> findRolesByUser(String userId) { String sql = "select distinct r.name from ls_usr_role ur ,ls_role r where r.enabled ='1' and ur.user_id= ? and ur.role_id=r.id"; log.debug("findRolesByUser,run sql {}, userId {}", sql, userId); return jdbcTemplate.query(sql, new Object[] { userId }, new RowMapper<GrantedAuthority>() { public GrantedAuthority mapRow(ResultSet rs, int index) throws SQLException { return new GrantedAuthorityImpl(rs.getString("name")); } }); } /** * 根据角色名拿到角色对象,包括角色对应的权限 */ private Role getGrantedAuthority(String authority) { log.debug("getgrantedAuthority calling {}", authority); List<Role> roles = findRoleByName(authority); if (AppUtils.isBlank(roles)) { log.warn("authority {} can not get Role", authority); return null; } else { Role role = roles.iterator().next(); if (role != null) { role.setFunctions(findFunctionsByRole(role)); return role; } else { return null; } } } /** * 根据用户名拿到对应的角色 */ private List<Role> findRoleByName(String authority) { String sql = "select * from ls_role where enabled = '1' and name = ?"; log.debug("findRoleByName run sql {}, authority {}", authority); return jdbcTemplate.query(sql, new Object[] { authority }, new RowMapper<Role>() { public Role mapRow(ResultSet rs, int index) throws SQLException { Role role = new Role(); role.setEnabled(rs.getString("enabled")); role.setId(rs.getString("id")); role.setName(rs.getString("name")); role.setNote(rs.getString("note")); role.setRoleType(rs.getString("role_type")); return role; } }); } /** * 根据角色拿到对应的权限 */ private List<Function> findFunctionsByRole(Role role) { String sql = "select f.* from ls_perm p ,ls_func f where p.role_id= ? and p.function_id=f.id"; log.debug("findFunctionsByRole,run sql {}, role {}", sql, role.getName()); return jdbcTemplate.query(sql, new Object[] { role.getId() }, new RowMapper<Function>() { public Function mapRow(ResultSet rs, int index) throws SQLException { Function function = new Function(); function.setId(rs.getString("id")); function.setName(rs.getString("name")); function.setNote(rs.getString("note")); function.setProtectFunction(rs.getString("protect_function")); function.setUrl(rs.getString("url")); return function; } }); } /** * Sets the jdbc template. * * @param jdbcTemplate * the new jdbc template */ public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
true
7c30e6373b05c6a7725ee3ab6b65716e25f6d67b
Java
edjaz/bfb-test
/src/main/java/com/bforbank/testing/service/TicketService.java
UTF-8
1,343
2.40625
2
[]
no_license
package com.bforbank.testing.service; import com.bforbank.testing.domain.Ticket; import com.bforbank.testing.service.dto.TicketDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; import java.util.Set; /** * Service Interface for managing Ticket. */ public interface TicketService { /** * Save a ticket. * * @param ticketDTO the entity to save * @return the persisted entity */ TicketDTO save(TicketDTO ticketDTO); /** * Get all the tickets. * * @param pageable the pagination information * @return the list of entities */ Page<TicketDTO> findAll(Pageable pageable); /** * Get all the Ticket with eager load of many-to-many relationships. * * @return the list of entities */ Page<TicketDTO> findAllWithEagerRelationships(Pageable pageable); /** * Get the "id" ticket. * * @param id the id of the entity * @return the entity */ Optional<TicketDTO> findOne(Long id); /** * Delete the "id" ticket. * * @param id the id of the entity */ void delete(Long id); /** * Get the near future ticket to finish * @param limit * @return */ Set<TicketDTO> findNextDueDate(int limit); }
true
734a7c69e615dcda6b1eb32d228d13646e020715
Java
kenguru33/NetMon
/src/cx/virtlab/netmon/ProbeServiceStore.java
UTF-8
779
1.96875
2
[]
no_license
package cx.virtlab.netmon; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; import java.util.List; /** * Created by bernt on 26.05.15. */ public class ProbeServiceStore { private ObservableList<ProbeService> probeServiceList; public ObservableList<ProbeService> getProbeServiceList() { return probeServiceList; } private ProbeServiceStore() { this.probeServiceList = FXCollections.observableArrayList(); } public static ProbeServiceStore createProbeServiceStore() { return new ProbeServiceStore(); } public void load(String filename) { dummyData(); } public void save(String filename) { } public void dummyData() { } }
true
3ba13047c554dfc05b1a337f85a4de9161350743
Java
gyhdx/Algorithm
/src/wf/leetcode/_34_在排序数组中查找元素的第一个和最后一个位置.java
UTF-8
757
3.265625
3
[]
no_license
package wf.leetcode; /* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值,返回 [-1, -1]。 */ public class _34_在排序数组中查找元素的第一个和最后一个位置 { public static void main(String[] args) { } public int[] searchRange(int[] nums, int target) { if (nums == null || nums.length==0) return new int[]{-1,-1}; // int start = 0,end = nums.length-1,mid; // int loca=-1; // boolean flag = true; // while (start <= end){ // // } return new int[]{-1,-1}; } }
true
aab46c9651eb193fabc3af95e7c5c2285fc9a4b4
Java
BeYkeRYkt/MinecraftServerDec
/src/net/minecraft/DataWatcher.java
UTF-8
6,742
2.265625
2
[]
no_license
package net.minecraft; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang3.ObjectUtils; public class DataWatcher { private final Entity a; private boolean b = true; private static final Map c = Maps.newHashMap(); private final Map d = Maps.newHashMap(); private boolean e; private ReadWriteLock f = new ReentrantReadWriteLock(); public DataWatcher(Entity var1) { this.a = var1; } public void a(int var1, Object var2) { Integer var3 = (Integer) c.get(var2.getClass()); if (var3 == null) { throw new IllegalArgumentException("Unknown data type: " + var2.getClass()); } else if (var1 > 31) { throw new IllegalArgumentException("Data value id is too big with " + var1 + "! (Max is " + 31 + ")"); } else if (this.d.containsKey(Integer.valueOf(var1))) { throw new IllegalArgumentException("Duplicate id value for " + var1 + "!"); } else { xw var4 = new xw(var3.intValue(), var1, var2); this.f.writeLock().lock(); this.d.put(Integer.valueOf(var1), var4); this.f.writeLock().unlock(); this.b = false; } } public void a(int var1, int var2) { xw var3 = new xw(var2, var1, (Object) null); this.f.writeLock().lock(); this.d.put(Integer.valueOf(var1), var3); this.f.writeLock().unlock(); this.b = false; } public byte a(int var1) { return ((Byte) this.j(var1).b()).byteValue(); } public short b(int var1) { return ((Short) this.j(var1).b()).shortValue(); } public int c(int var1) { return ((Integer) this.j(var1).b()).intValue(); } public float getData(int var1) { return ((Float) this.j(var1).b()).floatValue(); } public String e(int var1) { return (String) this.j(var1).b(); } public ItemStack f(int var1) { return (ItemStack) this.j(var1).b(); } private xw j(int var1) { this.f.readLock().lock(); xw var2; try { var2 = (xw) this.d.get(Integer.valueOf(var1)); } catch (Throwable var6) { CrashReport var4 = CrashReport.generateCrashReport(var6, "Getting synched entity data"); CrashReportSystemDetails var5 = var4.generateSystemDetails("Synched entity data"); var5.addDetails("Data ID", (Object) Integer.valueOf(var1)); throw new ReportedException(var4); } this.f.readLock().unlock(); return var2; } public fa h(int var1) { return (fa) this.j(var1).b(); } public void b(int var1, Object var2) { xw var3 = this.j(var1); if (ObjectUtils.notEqual(var2, var3.b())) { var3.a(var2); this.a.i(var1); var3.a(true); this.e = true; } } public void i(int var1) { xw.a(this.j(var1), true); this.e = true; } public boolean a() { return this.e; } public static void writeData(List var0, PacketDataSerializer var1) { if (var0 != null) { Iterator var2 = var0.iterator(); while (var2.hasNext()) { xw var3 = (xw) var2.next(); a(var1, var3); } } var1.writeByte(127); } public List b() { ArrayList var1 = null; if (this.e) { this.f.readLock().lock(); Iterator var2 = this.d.values().iterator(); while (var2.hasNext()) { xw var3 = (xw) var2.next(); if (var3.d()) { var3.a(false); if (var1 == null) { var1 = Lists.newArrayList(); } var1.add(var3); } } this.f.readLock().unlock(); } this.e = false; return var1; } public void writeData(PacketDataSerializer var1) { this.f.readLock().lock(); Iterator var2 = this.d.values().iterator(); while (var2.hasNext()) { xw var3 = (xw) var2.next(); a(var1, var3); } this.f.readLock().unlock(); var1.writeByte(127); } public List c() { ArrayList var1 = null; this.f.readLock().lock(); xw var3; for (Iterator var2 = this.d.values().iterator(); var2.hasNext(); var1.add(var3)) { var3 = (xw) var2.next(); if (var1 == null) { var1 = Lists.newArrayList(); } } this.f.readLock().unlock(); return var1; } private static void a(PacketDataSerializer var0, xw var1) { int var2 = (var1.c() << 5 | var1.a() & 31) & 255; var0.writeByte(var2); switch (var1.c()) { case 0: var0.writeByte(((Byte) var1.b()).byteValue()); break; case 1: var0.writeShort(((Short) var1.b()).shortValue()); break; case 2: var0.writeInt(((Integer) var1.b()).intValue()); break; case 3: var0.writeFloat(((Float) var1.b()).floatValue()); break; case 4: var0.writeString((String) var1.b()); break; case 5: ItemStack var3 = (ItemStack) var1.b(); var0.writeItemStack(var3); break; case 6: Position var4 = (Position) var1.b(); var0.writeInt(var4.getX()); var0.writeInt(var4.getY()); var0.writeInt(var4.getZ()); break; case 7: fa var5 = (fa) var1.b(); var0.writeFloat(var5.b()); var0.writeFloat(var5.c()); var0.writeFloat(var5.d()); } } public static List readData(PacketDataSerializer var0) throws IOException { ArrayList var1 = null; for (byte var2 = var0.readByte(); var2 != 127; var2 = var0.readByte()) { if (var1 == null) { var1 = Lists.newArrayList(); } int var3 = (var2 & 224) >> 5; int var4 = var2 & 31; xw var5 = null; switch (var3) { case 0: var5 = new xw(var3, var4, Byte.valueOf(var0.readByte())); break; case 1: var5 = new xw(var3, var4, Short.valueOf(var0.readShort())); break; case 2: var5 = new xw(var3, var4, Integer.valueOf(var0.readInt())); break; case 3: var5 = new xw(var3, var4, Float.valueOf(var0.readFloat())); break; case 4: var5 = new xw(var3, var4, var0.readString(32767)); break; case 5: var5 = new xw(var3, var4, var0.readItemStack()); break; case 6: int var6 = var0.readInt(); int var7 = var0.readInt(); int var8 = var0.readInt(); var5 = new xw(var3, var4, new Position(var6, var7, var8)); break; case 7: float var9 = var0.readFloat(); float var10 = var0.readFloat(); float var11 = var0.readFloat(); var5 = new xw(var3, var4, new fa(var9, var10, var11)); } var1.add(var5); } return var1; } public boolean d() { return this.b; } public void e() { this.e = false; } static { c.put(Byte.class, Integer.valueOf(0)); c.put(Short.class, Integer.valueOf(1)); c.put(Integer.class, Integer.valueOf(2)); c.put(Float.class, Integer.valueOf(3)); c.put(String.class, Integer.valueOf(4)); c.put(ItemStack.class, Integer.valueOf(5)); c.put(Position.class, Integer.valueOf(6)); c.put(fa.class, Integer.valueOf(7)); } }
true
9405845b4615f57772b2e1c93f39afb00c324d23
Java
tmancill/newrelic-jfr-core
/jfr-mappers/src/main/java/com/newrelic/jfr/tosummary/NetworkWriteSummarizer.java
UTF-8
1,642
1.851563
2
[ "Apache-2.0" ]
permissive
/* * * * Copyright 2020 New Relic Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * */ package com.newrelic.jfr.tosummary; import com.newrelic.jfr.Workarounds; import java.util.Optional; import jdk.jfr.consumer.RecordedEvent; // jdk.SocketWrite { // startTime = 20:22:57.161 // duration = 87.4 ms // host = "mysql-staging-agentdb-2" // address = "10.31.1.15" // port = 3306 // bytesWritten = 34 bytes // eventThread = "ActivityWriteDaemon" (javaThreadId = 252) // stackTrace = [ // java.net.SocketOutputStream.socketWrite(byte[], int, int) line: 68 // java.net.SocketOutputStream.write(byte[], int, int) line: 150 // java.io.BufferedOutputStream.flushBuffer() line: 81 // java.io.BufferedOutputStream.flush() line: 142 // com.mysql.cj.protocol.a.SimplePacketSender.send(byte[], int, byte) line: 55 // ... // ] // } public class NetworkWriteSummarizer extends AbstractThreadDispatchingSummarizer { public static final String EVENT_NAME = "jdk.SocketWrite"; @Override public void accept(RecordedEvent ev) { Optional<String> possibleThreadName = Workarounds.getThreadName(ev); possibleThreadName.ifPresent( threadName -> { if (perThread.get(threadName) == null) { perThread.put( threadName, new PerThreadNetworkWriteSummarizer(threadName, ev.getStartTime().toEpochMilli())); } perThread.get(threadName).accept(ev); }); } @Override public String getEventName() { return EVENT_NAME; } }
true
a0a3edab767e8856e0d6b262f1543d7586fa714e
Java
Linshiq/private-project
/algorithm/src/com/lsq/problem/Solution617.java
UTF-8
2,211
3.40625
3
[]
no_license
package com.lsq.problem; import java.util.Arrays; /** * @author Linshiq: * @date 创建时间:2018年1月26日 上午9:26:31 * @version 1.0 * @parameter * @since * @return */ /** * <p> * 文件功能说明: * * </p> * * @Author linshiqin * <p> * <li>2018年1月26日-上午9:26:31</li> * <li>修改记录</li> * <li>-----------------------------------------------------------</li> * <li>标记:修订内容</li> * <li>linshiqin:创建注释模板</li> * <li>-----------------------------------------------------------</li> * </p> */ public class Solution617 { /* * @param nums: an array with positive and negative numbers * * @param k: an integer * * @return: the maximum average */ public static double maxAverage(int[] nums, int k) { // write your code here /* * 给出一个整数数组,有正有负。找到这样一个子数组,他的长度大于等于 k,且平均值最大。 * * 注意事项 保证数组的大小 >= k * * 您在真实的面试中是否遇到过这个题? Yes 样例 给出 nums = [1, 12, -5, -6, 50, 3], k = 3 * * 返回 15.667 // (-6 + 50 + 3) / 3 = 15.667 */ if (k > nums.length) { Arrays.sort(nums); return nums.length > 0 ? nums[0] : -1; } double max = Integer.MIN_VALUE; double sum = 0; double index = 0; for (int i = 0; i < nums.length ; i++) { // for (int j = i; j < nums.length; j++) { // // sum += nums[j]; // // // index++; // // if (index >= k && (sum / k) > max) { // // max = sum / index; // } // } // // sum = 0; // index = 0; if(sum <= 0){ sum = nums[i]; index = 1; }else { index ++; sum = ( sum + nums[i] ) / index; } if ( index >= k && sum > max) { max = sum ; System.out.println(sum); } } return max; } public static void main(String[] args) { long startTime = System.currentTimeMillis() ; System.out.println(maxAverage(new int[] { 1, 12, -5, -6, 50, 3 }, 3)); long endTime = System.currentTimeMillis() ; System.out.println((endTime - startTime)+"ms"); } }
true
8b7755ae4f98c276aa9481c1f0c60db06eb4c51e
Java
JetBrains/MPS
/testbench/testsolutions/bl.tuples.test/source_gen/jetbrains/mps/baseLanguage/tuples/test/ExtendedNamedTuples.java
UTF-8
3,008
2.34375
2
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package jetbrains.mps.baseLanguage.tuples.test; /*Generated by MPS */ import jetbrains.mps.baseLanguage.tuples.runtime.MultiTuple; import jetbrains.mps.baseLanguage.tuples.runtime.Tuples; public class ExtendedNamedTuples { public ExtendedNamedTuples() { } public static class Foo extends MultiTuple._2<Integer, String> { public Foo() { super(); } public Foo(Integer num, String str) { super(num, str); } public Integer num(Integer value) { return super._0(value); } public String str(String value) { return super._1(value); } public Integer num() { return super._0(); } public String str() { return super._1(); } } public static class Bar extends Foo implements Tuples._4<Integer, String, String, Double> { private final Tuples._2<String, Double> tuple; public Bar() { super(); this.tuple = MultiTuple.<String,Double>empty2(); } public Bar(Integer num, String str, String id, Double size) { super(num, str); this.tuple = MultiTuple.<String,Double>from(id, size); } public String id(String value) { return this._2(value); } public Double size(Double value) { return this._3(value); } public String id() { return this._2(); } public Double size() { return this._3(); } public String _2(String id) { return tuple._0(id); } public Double _3(Double size) { return tuple._1(size); } public String _2() { return tuple._0(); } public Double _3() { return tuple._1(); } public Tuples._3<Integer, String, String> assign(Tuples._3<? extends Integer, ? extends String, ? extends String> from) { super.assign(from); tuple._0(from._2()); return this; } public Tuples._4<Integer, String, String, Double> assign(Tuples._4<? extends Integer, ? extends String, ? extends String, ? extends Double> from) { super.assign(from); tuple._0(from._2()); tuple._1(from._3()); return this; } } public static class Qux extends Bar implements Tuples._5<Integer, String, String, Double, String> { private final Tuples._1<String> tuple; public Qux() { super(); this.tuple = MultiTuple.<String>empty1(); } public Qux(Integer num, String str, String id, Double size, String field) { super(num, str, id, size); this.tuple = MultiTuple.<String>from(field); } public String field(String value) { return this._4(value); } public String field() { return this._4(); } public String _4(String field) { return tuple._0(field); } public String _4() { return tuple._0(); } public Tuples._5<Integer, String, String, Double, String> assign(Tuples._5<? extends Integer, ? extends String, ? extends String, ? extends Double, ? extends String> from) { super.assign(from); tuple._0(from._4()); return this; } } }
true
b02a060db8cfee73453c7e42c1d8846c532199f7
Java
anishareddy20/DROPS
/upload.java
UTF-8
3,315
2.4375
2
[]
no_license
package com.drops.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.drops.beanclass.UploadBean; import com.drops.interfaces.SqlMethodImplementation; import com.oreilly.servlet.multipart.FilePart; import com.oreilly.servlet.multipart.MultipartParser; import com.oreilly.servlet.multipart.ParamPart; import com.oreilly.servlet.multipart.Part; @WebServlet("/UploadFile") public class UploadFile extends HttpServlet { private static final long serialVersionUID = 1L; public UploadFile() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part part=null; ParamPart paramPart=null; FilePart filePart=null; String fileName=null; String filePath=null; String fileType=null; File file=null; double fileSize = 0; HttpSession session=request.getSession(); String userName=(String) session.getAttribute("username"); System.out.println("user\t"+userName); MultipartParser parser=new MultipartParser(request, 99999999); String StoringPath=request.getSession().getServletContext().getRealPath("/"); int a=StoringPath.indexOf('.'); String path=StoringPath.substring(0, a); filePath=path+"drops\\WebContent\\userfile\\"+userName+"\\"; UploadBean ub=new UploadBean(); while((part=parser.readNextPart())!=null){ if(part.isFile()){ filePart=(FilePart) part; fileName=filePart.getFileName(); fileType=filePart.getContentType(); filePath=filePath+fileName; System.out.println("file path\t"+filePath); file=new File(filePath); fileSize=filePart.writeTo(file); System.out.println("file size\t"+fileSize); FileInputStream fis=new FileInputStream(file); ub.setUploadContent(fis); } else if (part.isParam()) { paramPart=(ParamPart) part; String tagname=paramPart.getName(); System.out.println(tagname+"tagname"); String tagValue=paramPart.getStringValue(); System.out.println("tag value"+tagValue); } } Date d= new Date(); String date=d.toString(); Random r=new Random(); int fileKey=r.nextInt(100000); String displayKey=""+fileKey; ArrayList<Object> al=new ArrayList<>(); System.out.println(date); al.add(userName); al.add(fileName); al.add(fileType); al.add(fileSize); al.add(filePath); al.add(date); al.add(displayKey); SqlMethodImplementation implementation=SqlMethodImplementation.getImplementation(); int status=implementation.upload(al); if(status>0){ HttpSession session2=request.getSession(); session2.setAttribute("filename", fileName); HttpSession hs=request.getSession(); hs.setAttribute("filekey", displayKey); request.getRequestDispatcher("split.jsp").forward(request, response); } else{ request.getRequestDispatcher("error.jsp").forward(request, response); } } }
true
131faa36de3b279336b7431cda1d0c906822849f
Java
omar20alaa/VAComputingTask
/app/src/main/java/app/task/EquationAdapter.java
UTF-8
2,684
2.28125
2
[]
no_license
package app.task; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import app.task.databinding.EquationItemBinding; public class EquationAdapter extends RecyclerView.Adapter<EquationAdapter.viewHolder> { private Context context; private List<Equation> equations; EquationItemBinding binding; public EquationAdapter(Context context, List<Equation> equations) { this.context = context; this.equations = equations; } public class viewHolder extends RecyclerView.ViewHolder { private EquationItemBinding binding; public viewHolder(@NonNull EquationItemBinding itemView) { super(itemView.getRoot()); this.binding = itemView; } } @NonNull @Override public EquationAdapter.viewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { binding = EquationItemBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false); return new EquationAdapter.viewHolder(binding); } @Override public void onBindViewHolder(@NonNull EquationAdapter.viewHolder viewHolder, final int position) { if (equations.get(position).isCompleted()) { binding.btnStatus.setText("Completed"); binding.btnStatus.setTextColor(Color.parseColor("#00ff00")); binding.equal.setVisibility(View.VISIBLE); binding.tvResult.setVisibility(View.VISIBLE); } else { binding.btnStatus.setText("Pending"); binding.btnStatus.setTextColor(Color.parseColor("#ff0000")); binding.equal.setVisibility(View.GONE); binding.tvResult.setVisibility(View.GONE); } binding.tvFirstNum.setText(equations.get(position).getFirst_num() + ""); binding.tvSecNum.setText(equations.get(position).getSec_num() + ""); binding.tvSign.setText(equations.get(position).getSign() + ""); binding.tvResult.setText(equations.get(position).getResult() + ""); } @Override public int getItemCount() { return (equations == null) ? 0 : equations.size(); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } }
true
83f3c3eb2eb97755ffa55c46aecb2da0ffdc82d5
Java
wabir/AcsUtils
/library/src/main/java/acs/Text.java
UTF-8
5,392
2.03125
2
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
package acs; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import acs.utils.Acs; import acs.utils.R; public class Text extends TextView { private static final int COLOR_NONE = -1100; private int mBgColor; private int mBgColorFocus; private int mBgColorDisabled; private int mBorderColor; private int mBorderColorFocus; private int mBorderColorDisabled; private int mBorderWidth; private int mBorderWidthFocus; private int mRadius; public Text(Context context) { super(context); this.init(); } public Text(Context context, AttributeSet attrs) { super(context, attrs); this.initAttrs(attrs); this.init(); } private void initAttrs(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Text); mBgColor = a.getColor(R.styleable.Text__bgColor, COLOR_NONE); mBgColorFocus = a.getColor(R.styleable.Text__bgColorFocus, COLOR_NONE); mBgColorDisabled = a.getColor(R.styleable.Text__bgColorDisabled, COLOR_NONE); mRadius = (int) a.getDimension(R.styleable.Text__radius, 0); mBorderWidth = (int) a.getDimension(R.styleable.Text__borderWidth, 0); mBorderWidthFocus = (int) a.getDimension(R.styleable.Text__borderWidthFocus, 0); mBorderColor = a.getColor(R.styleable.Text__borderColor, COLOR_NONE); mBorderColorFocus = a.getColor(R.styleable.Text__borderColorFocus, COLOR_NONE); mBorderColorDisabled = a.getColor(R.styleable.Text__borderColorDisabled, COLOR_NONE); Acs.setFont(getContext(), this, a.getString(R.styleable.Text__font), getTypeface().getStyle()); a.recycle(); } private void init() { setupBackground(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); setupBackground(); } @Override public void setOnClickListener(@Nullable OnClickListener l) { super.setOnClickListener(l); setupBackground(); } private void setupBackground() { if (mBgColor == COLOR_NONE) return; if (mBgColorFocus == COLOR_NONE) { mBgColorFocus = mBgColor; } if (mBorderColor != COLOR_NONE && mBorderColorFocus == COLOR_NONE) { mBorderColorFocus = mBorderColor; } // Default Drawable GradientDrawable _default = new GradientDrawable(); _default.setCornerRadius(mRadius); _default.setColor(mBgColor); if (mBorderWidth > 0) { _default.setStroke(mBorderWidth, mBorderColor); } //Focus Drawable GradientDrawable _focus = new GradientDrawable(); _focus.setCornerRadius(mRadius); _focus.setColor(mBgColorFocus); _focus.setStroke(mBorderWidthFocus > 0 ? mBorderWidthFocus : mBorderWidth, mBorderColorFocus); // Disabled Drawable GradientDrawable _disabled = new GradientDrawable(); _disabled.setCornerRadius(mRadius); _disabled.setColor(mBgColorDisabled == COLOR_NONE ? mBgColor : mBgColorDisabled); _disabled.setStroke(mBorderWidth, mBorderColorDisabled == COLOR_NONE ? mBorderColor : mBorderColorDisabled); this.setBackground(getBG(_default, _focus, _disabled)); if (isClickable()) { this.setTextColor(new ColorStateList( new int[][]{ new int[]{android.R.attr.state_pressed}, new int[]{} }, new int[]{ Acs.alphaColor(getCurrentTextColor(), 0.5f), getCurrentTextColor() } )); } } private Drawable getBG(Drawable _default, Drawable _focus, Drawable _disabled) { if (!isEnabled()) { return _disabled; } else { StateListDrawable states = new StateListDrawable(); if (mBgColorFocus != COLOR_NONE) { states.addState(new int[]{android.R.attr.state_pressed}, _focus); } states.addState(new int[]{}, _default); return states; } } /** * Asignar valores */ // Fondo Normal public void setBgColor(int color) { mBgColor = color; setupBackground(); } public void setBgColorDisabled(int color) { mBgColorDisabled = color; setupBackground(); } // Border public void setBorderColor(int color) { mBorderColor = color; setupBackground(); } public void setBorderColorDisabled(int color) { mBorderColorDisabled = color; setupBackground(); } //Obtener valores public int getBgColor() { return mBgColor; } public int getBgColorDisabled() { return mBgColorDisabled; } public int getBorderColor() { return mBorderColor; } }
true
4b289bf807f3e75cdd01638744c71508e7060047
Java
Duleeka/finalproject
/src/main/java/com/gn/app/service/settings/ReligionRegister/ReligionRegisterService.java
UTF-8
615
1.921875
2
[]
no_license
package com.gn.app.service.settings.ReligionRegister; import com.gn.app.dto.settings.ReligionRegister.ReligionRegisterDTO; import org.springframework.data.jpa.datatables.mapping.DataTablesInput; import org.springframework.data.jpa.datatables.mapping.DataTablesOutput; import java.util.List; public interface ReligionRegisterService { DataTablesOutput<ReligionRegisterDTO> findAllDataTable(DataTablesInput input); List<ReligionRegisterDTO> findAll(); ReligionRegisterDTO create(ReligionRegisterDTO religionRegisterDTO); ReligionRegisterDTO findById(Integer id); void delete(Integer id); }
true
d2a6e820d547931f2dad4969d29788bc7c18cd75
Java
lipycabral/UFAC
/IntroducaoJPA/src/br/ufac/academico/entidades/PessoaJuridica.java
UTF-8
390
2.453125
2
[]
no_license
package br.ufac.academico.entidades; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue(value="Juridica") public class PessoaJuridica extends Pessoa{ @Column(length=14) private String cnpj; public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } }
true
8c95610e1f964759c65953bfa36ff500a897f614
Java
danielcompufu/minhasfinancas
/src/main/java/com/minhasfinancas/model/entity/Usuario.java
UTF-8
613
2.03125
2
[]
no_license
package com.minhasfinancas.model.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotBlank; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Usuario { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotBlank private String nome; @NotBlank private String email; @NotBlank private String senha; }
true
3ef6e1186f2a230edd12fed47a718e5301ec67a3
Java
AntonJohansson/EDAA01
/edaa01-workspace/lab3/src/lab3/BookReaderController.java
UTF-8
4,005
3.203125
3
[]
no_license
package lab3; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.stage.Stage; import textproc.GeneralWordCounter; /* * D10 * * - JavaFX använder mycket callbacks för ge funktionalitet. * Ex. användningen av lambdauttryck för att ge en responsiv * design. * * - ObservableList tillåter programmet att registrera "listeners" * som anropas då ändringar sker i listan. Antar här att ListView * registrerar listeners för dessa events -> ListViewen uppdateras * då ändringar sker i listan. */ public class BookReaderController extends Application { /* * Läs in en bok från en fil och mata in den till en TextProcessor * som räknar antalet ord. */ private GeneralWordCounter process_book(String book_file, String bad_words_file) throws FileNotFoundException{ // Read in bad words. Scanner bad_words = new Scanner(new File(bad_words_file)); GeneralWordCounter word_counter = new GeneralWordCounter(bad_words, /*lower bound*/ 200); Scanner s = new Scanner(new File(book_file)); s.useDelimiter("(\\s|,|\\.|:|;|!|\\?|'|\\\")+"); // se handledning // Process words in book while (s.hasNext()) { String word = s.next().toLowerCase(); word_counter.process(word); } s.close(); return word_counter; } @Override public void start(Stage primaryStage) throws Exception { // Initilaize empty window. BorderPane root = new BorderPane(); Scene scene = new Scene(root); primaryStage.setTitle("Book Reader"); primaryStage.setScene(scene); primaryStage.show(); // Get word counter object. GeneralWordCounter counter = process_book("../lab3/nilsholg.txt", "../lab3/undantagsord.txt"); // Create observable list. ObservableList<Map.Entry<String, Integer>> words = FXCollections.observableArrayList(counter.getWords()); // Create list view. ListView<Map.Entry<String, Integer>> listview = new ListView<Map.Entry<String, Integer>>(words); // Create buttons. Button b_alphabetic = new Button("Alphabetic"); Button b_frequency = new Button("Frequency"); Button b_find = new Button("Find"); TextField textfield = new TextField(); b_alphabetic.setOnAction((value) -> words.sort((e1, e2) -> e1.getKey().compareTo(e2.getKey()))); b_frequency.setOnAction((value) -> words.sort((e1, e2) -> e2.getValue() - e1.getValue())); b_find.setOnAction((value) -> { String text = textfield.getText().toLowerCase(); // Skapa en sublista inehållande alla par som uppfyller // nyckeln är lika med texten i textfieldet. FilteredList<Map.Entry<String, Integer>> list = words.filtered((pair) -> pair.getKey().equals(text)); // Om listan innehåller minst ett värde så // har vi hittat nåt. if(list.size() > 0){ // Scrolla till objektet istället för att // skrolla till raden. listview.scrollTo(list.get(0)); } }); // Make button fire on enter. /*textfield.setOnKeyPressed((event) -> { if(event.getCode().equals(KeyCode.ENTER)){ b_find.fire(); } });*/ b_find.setDefaultButton(true); // Add elements to hbox. HBox hbox = new HBox(b_alphabetic, b_frequency, textfield, b_find); // Ändra alltid storleken på textfieldet för att passa fönstret. HBox.setHgrow(textfield, Priority.ALWAYS); // Display root.setCenter(listview); root.setBottom(hbox); } public static void main(String[] args) { Application.launch(args); } }
true
0c4df70a3435c14c7c4bb20385867cfd9e0a6155
Java
Team-Fruit/ProjectRTM
/src/main/java/net/teamfruit/projectrtm/rtm/entity/vehicle/EntityShip.java
UTF-8
1,405
2.28125
2
[ "MIT" ]
permissive
package net.teamfruit.projectrtm.rtm.entity.vehicle; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.teamfruit.projectrtm.rtm.RTMItem; public class EntityShip extends EntityVehicle { public EntityShip(World world) { super(world); this.stepHeight = 0.5F; } @Override protected boolean shouldUpdateMotion() { return this.inWater; } @Override protected void updateMotion(EntityLivingBase entity, float moveStrafe, float moveForward) { super.updateMotion(entity, moveStrafe, moveForward); if (this.speed>0.0D&&this.inWater) { this.rotationRoll = moveStrafe*(float) (this.speed/this.getModelSet().getConfig().getMaxSpeed(this.onGround))*-5.0F; } } @Override protected void updateFallState() { if (!this.inWater&&!this.onGround) { this.motionY -= 0.05D; } else { AxisAlignedBB aabb = this.boundingBox.copy(); aabb.minY += 0.0625D; if (this.worldObj.isAABBInMaterial(aabb, Material.water)) { this.motionY += 0.05D; } else { this.motionY = 0.0D; } } } @Override public String getDefaultName() { return "WoodBoat"; } @Override protected ItemStack getVehicleItem() { return new ItemStack(RTMItem.itemVehicle, 1, 1); } }
true
ba7e26bafb7b9f89a01073394cd888bb0bd456b4
Java
Lianite/wurm-server-reference
/impl/org/controlsfx/tools/rectangle/change/AbstractFixedEdgeChangeStrategy.java
UTF-8
1,902
2.34375
2
[]
no_license
// // Decompiled by Procyon v0.5.30 // package impl.org.controlsfx.tools.rectangle.change; import impl.org.controlsfx.tools.rectangle.Rectangles2D; import javafx.geometry.Point2D; import impl.org.controlsfx.tools.rectangle.Edge2D; import javafx.geometry.Rectangle2D; abstract class AbstractFixedEdgeChangeStrategy extends AbstractRatioRespectingChangeStrategy { private final Rectangle2D bounds; private Edge2D fixedEdge; protected AbstractFixedEdgeChangeStrategy(final boolean ratioFixed, final double ratio, final Rectangle2D bounds) { super(ratioFixed, ratio); this.bounds = bounds; } protected abstract Edge2D getFixedEdge(); private final Rectangle2D createFromEdges(final Point2D point) { final Point2D pointInBounds = Rectangles2D.inRectangle(this.bounds, point); if (this.isRatioFixed()) { return Rectangles2D.forEdgeAndOpposingPointAndRatioWithinBounds(this.fixedEdge, pointInBounds, this.getRatio(), this.bounds); } return Rectangles2D.forEdgeAndOpposingPoint(this.fixedEdge, pointInBounds); } @Override protected final Rectangle2D doBegin(final Point2D point) { final boolean startPointNotInBounds = !this.bounds.contains(point); if (startPointNotInBounds) { throw new IllegalArgumentException("The change's start point (" + point + ") must lie within the bounds (" + this.bounds + ")."); } this.fixedEdge = this.getFixedEdge(); return this.createFromEdges(point); } @Override protected Rectangle2D doContinue(final Point2D point) { return this.createFromEdges(point); } @Override protected final Rectangle2D doEnd(final Point2D point) { final Rectangle2D newRectangle = this.createFromEdges(point); this.fixedEdge = null; return newRectangle; } }
true
1878a1b0baab748462ed684c197e837125db0831
Java
weimingtom/NLiveRoid
/src/nliveroid/nlr/main/parser/SecondEdit_GetLVParser.java
UTF-8
4,846
2.140625
2
[]
no_license
package nliveroid.nlr.main.parser; import java.util.regex.Matcher; import java.util.regex.Pattern; import nliveroid.nlr.main.ErrorCode; import nliveroid.nlr.main.LiveTab.SecondSendForm_GetLVTask; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import android.util.Log; /** * 放送開始した際に * 放送情報を取得する * LiveTabのみで利用される * @author Owner * */ public class SecondEdit_GetLVParser implements ContentHandler { private StringBuilder innerText = new StringBuilder(1024); private boolean parseTarget = false; private boolean ancherTarget = false; private boolean lvFinded = false; private String[] ulck_desc = new String[2];//[0]ulck,[1]description private SecondSendForm_GetLVTask task; public SecondEdit_GetLVParser(SecondSendForm_GetLVTask task,ErrorCode error){ this.task = task; } private String getInnerText(char[] arg0,int arg2){ innerText = innerText.delete(0,arg0.length); innerText.append(arg0, 0, arg2); return innerText.toString(); } @Override public void characters(char[] arg0, int arg1, int arg2) throws SAXException { // Log.d("NLR","INNER ------- " + aa); if(parseTarget){ String inner = getInnerText(arg0,arg2); // Log.d("log","TASK FINISH ------- " + inner); if(inner.contains("既にこの時間に予約をしている")||inner.contains("配信開始を押すまで、一覧には表示されません")){ ancherTarget = true; }else if(inner.contains("既に順番待ちに並んでいるか")){ ancherTarget = true; }else if(inner.contains("WEBページの有効期限が切れています")){ lvFinded = true;//後のリトライをさせない為 task.finishCallBack("RETRYW"+ulck_desc[0]); }else if(inner.contains("混み合っております")){ lvFinded = true;//後のリトライをさせない為 try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } task.finishCallBack("RETRYC"); }else{ lvFinded = true;//後のリトライをさせない為 task.finishCallBack(inner); } parseTarget = false; } if(ancherTarget){ getInnerText(arg0,arg2);//Getting innerText } } @Override public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { // Log.d("NLR","1elem " + arg1); // Log.d("NLR","2elem " + arg2); if(arg1.equals("li") && arg3 != null && arg3.getLength()>0){ for(int i = 0; i < arg3.getLength(); i++){ if(arg3.getValue(i).equals("error_message")){ Log.d("NLR","SECOND error_message --- "); parseTarget = true; } } } if(arg1.equals("input")){ for(int i = 0; i < arg3.getLength(); i++){ if(arg3.getLocalName(i).equals("name")){ if(arg3.getValue(i).equals("description")){ for(int j = 0; j < arg3.getLength(); j++){ if(arg3.getLocalName(j).equals("value")){ ulck_desc[1] = arg3.getValue(j); } } }else if(arg3.getValue(i).equals("usecoupon")||arg3.getValue(i).equals("confirm")){ Pattern pt = Pattern.compile("ulck_[0-9]+"); Matcher mc = null; for(int j = 0; j < arg3.getLength(); j++){ mc = pt.matcher(arg3.getValue(j)); if(mc.find()){ ulck_desc[0] = mc.group(); } } } } } } if(arg1.equals("div")&&arg3!=null){ for(int i = 0; i < arg3.getLength()&&!lvFinded; i++){ // Log.d("NLR","DIV --- val " + arg3.getValue(i)); if(arg3.getValue(i).equals("page_footer")){ task.finishCallBack("RETRY");//ulckなし+ページ終わり=枠取り失敗 これが不明 } } } } @Override public void endElement(String arg0, String arg1, String arg2)throws SAXException { if(ancherTarget){ Matcher glmc = Pattern.compile("lv[0-9]+").matcher(innerText); if(glmc.find()){ Log.d("NLR","find" ); String lv = glmc.group(); lvFinded = true; parseTarget = false; ancherTarget = false; task.finishCallBack(lv); } } if(ulck_desc!=null&&ulck_desc[0] != null && !ulck_desc[0].equals("")&&ulck_desc[1]!=null&&!ulck_desc[1].equals(""))task.finishCallBack(ulck_desc); } @Override public void endDocument() throws SAXException {} @Override public void endPrefixMapping(String arg0) throws SAXException {} @Override public void ignorableWhitespace(char[] arg0, int arg1, int arg2)throws SAXException {} @Override public void processingInstruction(String arg0, String arg1)throws SAXException {} @Override public void setDocumentLocator(Locator arg0) {} @Override public void skippedEntity(String arg0) throws SAXException {} @Override public void startDocument() throws SAXException {} @Override public void startPrefixMapping(String arg0, String arg1)throws SAXException {} }
true
facedead2f1b0c763765ce19c03f130efe37fc02
Java
ddeko/0274
/app/src/main/java/plbtw/plbtw_0274/API/GoogleSearchAPI.java
UTF-8
676
1.804688
2
[]
no_license
package plbtw.plbtw_0274.API; import plbtw.plbtw_0274.Model.address.ArrayofSearchResultBean; import retrofit.http.GET; import retrofit.http.Query; /** * Created by dedeeko on 1/4/16. */ public interface GoogleSearchAPI { @GET("/maps/api/geocode/json?result_type=route&key="+ "AIzaSyD5DmVoxPVbnHe242CMcdMMnmvo3Bn54Jk") public ArrayofSearchResultBean getLocation(@Query("latlng") String latlng); @GET("/maps/api/geocode/json?result_type=route&key="+ "AIzaSyD5DmVoxPVbnHe242CMcdMMnmvo3Bn54Jk") public ArrayofSearchResultBean getLatLng(@Query("address") String address); @GET("/maps/api/geocode/json?result_type=locality&key="+ "AIzaSyD5DmVoxPVbnHe242CMcdMMnmvo3Bn54Jk") public ArrayofSearchResultBean getCity(@Query("latlng") String address); }
true
9080060232a3be8d1afce9fb1d4234f279be0e24
Java
MikhailSap/cookstarter
/cookstarter-bot/src/main/java/ru/guteam/bot/handler/RequestHandler.java
UTF-8
985
1.945313
2
[]
no_license
package ru.guteam.bot.handler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import ru.guteam.bot.service.CustomerService; import ru.guteam.bot.service.OrderService; import ru.guteam.bot.service.PictureService; import ru.guteam.bot.service.RestaurantService; @Component public class RequestHandler { private RestaurantService restaurantService; private CustomerService customerService; private OrderService orderService; private PictureService pictureService; @Autowired public RequestHandler(RestaurantService restaurantService, CustomerService customerService, OrderService orderService, PictureService pictureService) { this.restaurantService = restaurantService; this.customerService = customerService; this.orderService = orderService; this.pictureService = pictureService; } }
true
154000fa8f23cbc1e1a467e4ec55d7bc997ce9ac
Java
guoyx990403/XuankeSystemStudent
/xuanke3/src/xuanke/StudentSystem.java
GB18030
1,500
2.859375
3
[]
no_license
package xuanke; import java.util.Scanner; import po.Student; import view.StudentView; import view.impl.StudentViewimpl; public class StudentSystem { private Scanner input = new Scanner(System.in); private StudentView sview = new StudentViewimpl(); public void work() { System.out.println("ӭ½ѧѡιϵͳ"); int num = 0; while(num != 3) { System.out.println("-----------------1.ѧע 2.ѧ¼ 3.˳ϵͳ-----------------"); num = input.nextInt(); switch (num) { case 1: sview.saveStudent(); break; case 2: Student student = sview.studentLogin(); if(student != null) { studentMange(student); }else { System.out.println("ѧѧźѧƥ䣬¼ʧܣ"); } break; case 3: System.out.println("ллʹöѧѡϵͳ"); break; default: break; } } } public void studentMange(Student student) { int num = 0; while(num != 3) { System.out.println("-----------------ѧѡι1.ѧѡ 2.ѯѡγ 3.һ-----------------"); num = input.nextInt(); switch (num) { case 1: sview.student_course(student); break; case 2: sview.liststudent_course(student); break; case 3: break; default: break; } } } public static void main(String[] args) { // TODO Auto-generated method stub new StudentSystem().work(); } }
true
84495df2f9a91e758a28c2420aaa165a3f92f881
Java
MaisonWan/AndroidToy
/app/src/main/java/com/domker/androidtoy/adapter/MenuActionProvider.java
UTF-8
1,557
2.328125
2
[]
no_license
/** * */ package com.domker.androidtoy.adapter; import android.content.Context; import android.support.v4.view.ActionProvider; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.Toast; import com.domker.androidtoy.R; /** * * @author wanlipeng 2016年12月20日 */ public class MenuActionProvider extends ActionProvider { private Context mContext = null; @Override public boolean hasSubMenu() { return true; } @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); subMenu.add("sub item1") .setIcon(R.drawable.f009) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(mContext, "item1", Toast.LENGTH_SHORT).show(); return false; } }); subMenu.add("sub item2") .setIcon(R.drawable.f010) .setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(mContext, "item2", Toast.LENGTH_SHORT).show(); return false; } }); super.onPrepareSubMenu(subMenu); } /** * @param context */ public MenuActionProvider(Context context) { super(context); this.mContext = context; } /* * (non-Javadoc) * * @see android.support.v4.view.ActionProvider#onCreateActionView() */ @Override public View onCreateActionView() { return null; } }
true
cf585fd8e4d80e2962872776abbf0f370eca9b42
Java
bellmit/sunbird-cb-rulengine
/ruleenginecore/src/main/java/org/sunbird/ruleengine/rest/JobDetailRest.java
UTF-8
3,859
2.015625
2
[ "MIT" ]
permissive
package org.sunbird.ruleengine.rest; import java.security.Principal; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.sunbird.ruleengine.model.JobDetail; import org.sunbird.ruleengine.service.ClientService; import org.sunbird.ruleengine.service.JobDetailService; import org.sunbird.ruleengine.common.Response; import org.sunbird.ruleengine.common.rest.GenericMultiTenantRoleBasedSecuredRest; import org.sunbird.ruleengine.service.GenericService; @RestController @RequestMapping("{clientCode}/jobDetailRest") public class JobDetailRest extends GenericMultiTenantRoleBasedSecuredRest<JobDetail, JobDetail> { public JobDetailRest() { super(JobDetail.class, JobDetail.class); } @Autowired JobDetailService jobDetailService; @Autowired ClientService clientService; @Override public GenericService<JobDetail, JobDetail> getService() { return jobDetailService; } @Override public GenericService<JobDetail, JobDetail> getUserService() { return jobDetailService; } @Override public String rolePrefix() { return "jobDetail"; } @RequestMapping(value = "/getJobDetailEnums", method = RequestMethod.GET) public @ResponseBody Object getStepType(@PathVariable("clientCode") String clientCode, Principal principal) { Object[] objects = new Object[3]; objects[0] = JobDetail.Status.values(); objects[1] = JobDetail.IntervalType.values(); objects[2] = JobDetail.TimeIntervalType.values(); return objects; } @RequestMapping(value = "/getJobDetail", method = RequestMethod.GET) public @ResponseBody Object getJobDetail(@PathVariable("clientCode") String clientCode, @ModelAttribute JobDetail t, @RequestParam(value = "firstResult", required = false) int firstResult, @RequestParam(value = "maxResult", required = false) int maxResult, Principal principal) { t.setClientId(clientService.getClientCodeById(clientCode,t.getClientId())); super.validateAuthorization(clientCode, principal); return getService().getListByCriteria(t, "select jd.ID,jd.JOB_INTERVAL,jd.JOB_NAME,jd.LAST_END_TIME,jd.LAST_START_TIME,jd.NEXT_RUN_TIME,jd.JOB_STATUS,jd.CLIENT_ID,jd.VERSION,jd.INTERVAL_TYPE,jd.RETRY_ENABLED from JOB_DETAIL jd where 1=1 ", "order by jd.ID desc", firstResult, maxResult); } @Override @RequestMapping(method = RequestMethod.PUT) public @ResponseBody Response<JobDetail> update(@PathVariable("clientCode") String clientCode, @Valid @RequestBody JobDetail t, Principal principal) { t.setClientId(clientService.getClientCodeById(clientCode,t.getClientId())); return super.update(clientCode, t, principal); } @Override @RequestMapping(method = RequestMethod.POST) public @ResponseBody Response<JobDetail> save(@PathVariable("clientCode") String clientCode, @Valid @RequestBody JobDetail t, Principal principal) { t.setClientId(clientService.getClientCodeById(clientCode,t.getClientId())); return super.save(clientCode, t, principal); } @Override @RequestMapping(value = "/count", method = RequestMethod.GET) public @ResponseBody Long count(@PathVariable("clientCode") String clientCode, @ModelAttribute JobDetail t, Principal principal) { t.setClientId(clientService.getClientCodeById(clientCode,t.getClientId())); return getService().getCount(t, "select count(jd.ID) from JOB_DETAIL jd where 1=1 ").longValue(); } }
true
a3f57812dc3eb6de018070c603ff44d6d2d878b7
Java
Wangechi-waweru/Android-Intent-Activity
/app/src/main/java/com/example/saturdayclass/IntentActivity.java
UTF-8
4,897
1.929688
2
[]
no_license
package com.example.saturdayclass; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; public class IntentActivity extends AppCompatActivity { //Declaring variables Button mBtnSMS, mBtnStk, mBtnEmail, mBtnDial, mBtnShare, mBtnCamera, mBtnCall; EditText mEdPhonenum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intent); //Set find view by Id for each button. mBtnSMS = findViewById(R.id.btn_sms); mBtnStk = findViewById(R.id.btn_stk); mBtnEmail = findViewById(R.id.btn_email); mBtnDial = findViewById(R.id.btn_dial); mBtnShare = findViewById(R.id.btn_share); mBtnCamera = findViewById(R.id.btn_camera); mBtnCall = findViewById(R.id.btn_call); //Set onclick listener for each button mBtnSMS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse(("smsto:0700000000")); Intent intent = new Intent(Intent.ACTION_SENDTO,uri); intent.putExtra("sms_body","Hello, Sir. I won't be able to make it to ......."); startActivity(intent); } }); mBtnStk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent simToolKitLaunchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.android.stk"); if(simToolKitLaunchIntent != null){ startActivity(simToolKitLaunchIntent); } } }); mBtnEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO,Uri.fromParts("mailto","king@gmail.com",null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "KUOMBA KAZI"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Hsujambo mkurugenzi mpendwa, naadika ujumbe huu ilimradi kuomba kazi...."); startActivity(Intent.createChooser(emailIntent, "SENDING EMAIL")); } }); mBtnDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phone = "+2547"; Intent intent = new Intent(Intent.ACTION_DIAL,Uri.fromParts("tel",phone,null)); startActivity(intent); } }); mBtnShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent shareIntent= new Intent(Intent.ACTION_SEND); shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT,"Hello there, please click on https://www.mywebsite.com/playstore to download my app"); startActivity(shareIntent); } }); mBtnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePictureIntent, 1); } }); mBtnCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Receive a phone number from the phone number field String phone = mEdPhonenum.getText().toString(); if (phone.isEmpty()) { mEdPhonenum.setError("Please enter phone number"); }else if (phone.length()<10){ mEdPhonenum.setError("Please enter valid phone number"); }else{ Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ phone)); if (ContextCompat.checkSelfPermission(IntentActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(IntentActivity.this, new String[]{Manifest.permission.CALL_PHONE},1); }else{ startActivity(intent); } } } }); } }
true
d6884d1737fd6236b3c34b4ec2fc61cefc6d130c
Java
gerritcap/sitebuilder
/src/main/java/org/apache/sling/sitebuilder/internal/scriptstackresolver/ScriptContainerResolvingPathInfo.java
UTF-8
3,220
2.046875
2
[]
no_license
package org.apache.sling.sitebuilder.internal.scriptstackresolver; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.request.RequestPathInfo; import org.apache.sling.api.resource.Resource; public class ScriptContainerResolvingPathInfo implements RequestPathInfo { private String suffix; private Resource includeResource; private String resourcePath; private String selectorString; private String[] selectors; private RequestPathInfo rpi; private boolean removeExtension; private String originalExtension; public ScriptContainerResolvingPathInfo(SlingHttpServletRequest request, boolean removeExtension){ this.removeExtension = removeExtension; init(request); } public ScriptContainerResolvingPathInfo(SlingHttpServletRequest request, String resourcePath, boolean removeExtension){ this.removeExtension = removeExtension; this.resourcePath = resourcePath; init(request); } public ScriptContainerResolvingPathInfo(SlingHttpServletRequest request, Resource includeResource, String replaceSelectors, String addSelectors, String replaceSuffix, boolean removeExtension) { this.removeExtension = removeExtension; this.includeResource = includeResource; // see SlingRequestDispatcher.getMergedRequestPathInfo() and public SlingRequestPathInfo(Resource r) resourcePath = includeResource.getResourceMetadata().getResolutionPath(); // see SlingRequestPathInfo.merge(options) if (replaceSelectors != null) { this.selectorString = replaceSelectors; } if (addSelectors != null) { if (this.selectorString != null) { this.selectorString += "." + addSelectors; } else { this.selectorString = addSelectors; } } if (replaceSuffix != null) { this.suffix = replaceSuffix; } this.selectors = (selectorString != null) ? selectorString.split("\\.") : new String[0]; init(request); } private void init(SlingHttpServletRequest request) { this.rpi = request.getRequestPathInfo(); if (this.removeExtension){ String url = request.getRequestURI(); int lastDot = url.lastIndexOf("."); int dotBeforeLast = url.lastIndexOf(".", lastDot-1); originalExtension = url.substring(dotBeforeLast+1, lastDot); } } @Override public String getSelectorString() { return this.selectorString != null ? this.selectorString : rpi.getSelectorString(); } @Override public String[] getSelectors() { return this.selectors != null ? this.selectors : rpi.getSelectors(); } @Override public String getSuffix() { return this.suffix != null ? this.suffix : rpi.getSuffix(); } @Override public Resource getSuffixResource() { // see SlingRequestPathInfo.getSuffixResource(); if (this.suffix != null) { return includeResource.getResourceResolver().getResource(this.suffix); } return null; } @Override public String getResourcePath() { return this.resourcePath != null ? this.resourcePath : rpi.getResourcePath(); } @Override public String getExtension() { return this.removeExtension ? this.originalExtension : this.rpi.getExtension(); } }
true
25c5ddbc70be48465f09488416369ba7e2ca2ac1
Java
benjiazhen/algorithm010
/Week04/二叉树层序遍历.java
UTF-8
1,282
3.5625
4
[]
no_license
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { return method1(root); } /** * 时间复杂度O(n) * 空间复杂度O(n) */ public List<List<Integer>> method1(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new ArrayDeque<>(); queue.add(root); Set<TreeNode> visited = new HashSet<>(); while (!queue.isEmpty()) { List<Integer> level = new ArrayList<>(); int size = queue.size(); for(int i = 0;i< size;i++) { TreeNode first = queue.remove(); if (!visited.contains(first)) { visited.add(first); level.add(first.val); } if (first.left != null && !visited.contains(first.left)) { queue.add(first.left); } if (first.right != null && !visited.contains(first.right)) { queue.add(first.right); } } if (!level.isEmpty()) { result.add(level); } } return result; } }
true
f547eba4a2bf2e719448f091f594a9a8742b02c3
Java
fazihassan/Dry_clean
/app/src/main/java/com/androidfree/myapplication/Model/ServiceType.java
UTF-8
633
2.546875
3
[]
no_license
package com.androidfree.myapplication.Model; public class ServiceType { private String serviceName; private int serviceImage; public ServiceType(String serviceName, int serviceImage) { this.serviceName = serviceName; this.serviceImage = serviceImage; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public int getServiceImage() { return serviceImage; } public void setServiceImage(int serviceImage) { this.serviceImage = serviceImage; } }
true
134adafc40af0f63d6666fec91a8e03550e3f0e8
Java
noctarius/tengi
/java/tengi-server/src/main/java/com/noctarius/tengi/server/spi/transport/Endpoint.java
UTF-8
1,722
2.03125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2015-2016, Christoph Engelbert (aka noctarius) and * contributors. All rights reserved. * * 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.noctarius.tengi.server.spi.transport; public final class Endpoint { private final int port; private final ServerTransportLayer transportLayer; public Endpoint(int port, ServerTransportLayer transportLayer) { this.port = port; this.transportLayer = transportLayer; } public int getPort() { return port; } public ServerTransportLayer getTransportLayer() { return transportLayer; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Endpoint)) { return false; } Endpoint that = (Endpoint) o; if (port != that.port) { return false; } return transportLayer != null ? transportLayer.equals(that.transportLayer) : that.transportLayer == null; } @Override public int hashCode() { int result = port; result = 31 * result + (transportLayer != null ? transportLayer.hashCode() : 0); return result; } }
true
223731cfc75e9313076fb574e9e725a882187b10
Java
MarsStirner/core
/core/common/src/main/java/ru/korus/tmis/core/exception/NoSuchEntityException.java
UTF-8
378
2.15625
2
[]
no_license
package ru.korus.tmis.core.exception; public class NoSuchEntityException extends CoreException { final int entityId; public NoSuchEntityException(final int errorCode, final int entityId, final String message) { super(errorCode, message); this.entityId = entityId; } }
true
7129d502ccdda25a1de64395e091605710937af9
Java
ericlucena6485/POO2021
/tarefanove/fornecedor.java
UTF-8
746
2.421875
2
[]
no_license
package tarefanove; public class fornecedor extends operacoes{ private String cnpj; private String razaoSocial; public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } @Override public void inserir() { System.out.println("dados do fornecedor inseridos com sucesso"); } @Override public void excluir() { System.out.println("dados do fornecedor excluidos com sucesso"); } @Override public void localizar() { System.out.println("dados do fornecedor localizados com sucesso"); } }
true
8d503f4c15b840d15bb6de576b04e307e6b6ea47
Java
jinyx728/SE228-Web-Development
/src/main/java/action/AddUserAction.java
UTF-8
1,585
2.390625
2
[]
no_license
package action; import model.User; import model.UserDes; import model.UserImg; import service.AppService; import service.DetailService; import java.io.File; public class AddUserAction extends BaseAction { private static final long serialVersionUID = 1L; private String username; private String password; private String role; private String description; private File image; private AppService appService; private DetailService detailService; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public void setAppService(AppService appService) { this.appService = appService; } public void setDetailService(DetailService detailService) { this.detailService = detailService; } @Override public String execute() throws Exception { User user = new User(username, password, role); int id = appService.addUser(user); UserDes userDes = new UserDes(id, description); UserImg userImg = new UserImg(id, image); detailService.updateUserProfile(userDes, userImg); return SUCCESS; } }
true