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
8ac4aa99bda7473ffbae6d67ed6c674055d4683e
Java
Oss21/MagicSquare
/src/model/Tablero.java
UTF-8
13,396
3.65625
4
[]
no_license
package model; import exception.*; public class Tablero { /* * CONSTANTES */ //Direccion Nororiente. public final static String NO = "Nororiente"; //Direccion Noroeste. public final static String NE = "Noroeste"; //Direccion Suroriente. public final static String SO = "Suroriente"; //Direccion Suroeste. public final static String SE = "Suroeste"; //Fila 0 de la matriz. public final static String UP = "Arriba"; //Ultima Columna de la matriz. public final static String RIGHT = "Derecho"; //Columna 0 de la matriz. public final static String LEFT = "Izquierdo"; //Ultima fila de la matriz. public final static String DOWN = "Abajo"; //Define la constante fila. public final static String ROW = "Row"; //Define la constante columna public final static String COLUMN = "Column"; /** * Atributos */ // Dimension del tablero. private int row; private int column; private int[][] matriz; /** * Constructor. */ public Tablero() { } public void inicializar() { row = 0; column = 0; } // Fila de la matriz. public int getRow() { return row; } // Permite cambiar la fila de la matriz. public void setRow(int row) throws NumberParException{ if ((row % 2) == 0) throw new NumberParException("El número debe ser impar"); this.row = row; } // Columna de la matriz. public int getColumn() throws NumberParException{ if ((row % 2) == 0) throw new NumberParException("El número debe ser impar"); return column; } // Permite cambiar la columna de la matriz. public void setColumn(int column) { this.column = column; } // Matriz de enteros. public int[][] getMatriz() { return matriz; } // Permite cambiar la matriz. public void setMatriz(int[][] matriz) { this.matriz = matriz; } /** * Permite checkear si la dimensiones de la matriz es cuadrada. * @return verdadero: si las dimensiones son iguales. * false : si las dimensiones son distintas. */ public boolean checkDimension() { return (row == column)? true:false; } /** * Permite calcular la constante magica de la matriz, la cual es la sumatoria de las filas, * columnas o diagonales. * @return valor de la constante magica. */ public int magicCostan() { return (row *(int)((Math.pow(row, 2)+ 1)))/ 2; } //Establece la dimension de la matriz private int getDimension() { return (int)Math.pow(matriz.length, 2); } // Ubica la posicion central de la primera o ultima fila, y primera o ultima columna. private int getposicion() { return matriz.length/2; } //Ubica la ultima fila o columna(){ private int getLastRoworColumn() { return getposicion()*2; } // Establece el tamaño maximo que tiene la fila y la columna. private int getTamahno() { return matriz.length-1; } /** * Permite verificar si la suma de todas las filas o columnas son iguales, si lo son es cuadrado magico. * @param posicion * @return */ public boolean checkRow_Column(String posicion ) { boolean perfecto = false; int contador = 0; int suma = 0; int comparar = 0; for (int i = 0; i < matriz.length; i++) { suma = 0; for (int j = 0; j < matriz[i].length; j++) { if (posicion.equals("Row") ) { suma += matriz[j][i]; if(comparar == suma){ contador++; } }else { suma += matriz[i][j]; if(comparar == suma){ contador++; } } } if (comparar == 0) { comparar = suma; } } if (contador == matriz.length-1) { perfecto = true; } return perfecto; } /** * Establece la coordenada inicial en la matriz. * @param ubicacion primera fila(Arriba) - columna(Izquierdo) o ultima fila(Abajo) - columna(Derecho). * @param direccion dirección de desplazamiento del llenado de la matriz. * @throws UpAddressException lanza una excepción si la dirección de desplazamiento es diferente NE-NO. * @throws RightAddressException lanza una excepción si la dirección de desplazamiento es diferente NE-SE. * @throws LeftAddressException lanza una excepción si la dirección de desplazamiento es diferente NO-S0. * @throws DownAddressException lanza una excepción si la dirección de desplazamiento es diferente SE-SO. */ public void locateStart(String ubicacion,String direccion) throws UpAddressException, RightAddressException, LeftAddressException, DownAddressException, CompleteFieldException { matriz=new int[row][column]; int contador = 0; // Filas. int i = 0; // Columnas int j = 0; //Verificaciones. // Verifica que los valores por parametros existen. if (ubicacion == null || direccion == null) { throw new CompleteFieldException("Debe completar todos los campos para generar el cuadrado magico"); }else if(ubicacion.equals(UP)) { j = getposicion(); contador += 1; matriz[i][j] = contador; //Permite establecer la dirrecion de llenado. if (direccion.equals(NO)) { getNorthEastDirectionUp(contador); }else if (direccion.equals(NE)) { getNorthWestDirectionUp(contador); }else { throw new UpAddressException("Los valores ingresados deben ser"+"\n"+": Nororiente o Noroeste"); } }else if (ubicacion.equals(RIGHT)) { i = getposicion(); j = getTamahno(); contador += 1; matriz[i][j] = contador; //Permite establecer la dirrecion de llenado. if (direccion.equals(NE)) { getNorthWestDirectionRight(contador); }else if (direccion.equals(SE)) { getSouthWestDirectionRight(contador); }else { throw new RightAddressException("Los valores ingresados deben ser"+"\n"+": Noreste o Suroeste"); } }else if (ubicacion.equals(LEFT)) { i = getposicion(); j = 0; contador +=1; matriz[i][j] = contador; //Permite establecer la dirrecion de llenado. if (direccion.equals(NO)) { getNorthEastDirectionLeft(contador); }else if (direccion.equals(SO)) { getSouthEastDirectionLeft(contador); }else { throw new LeftAddressException("Los valores ingresados deben ser"+"\n"+": Nororiente o Suroriente"); } }else if (ubicacion.equals(DOWN)) { i = getTamahno(); j = getposicion(); contador+=1; matriz[i][j] = contador; //Permite establecer la dirrecion de llenado. if (direccion.equals(SO)) { getSouthEastDirectionDown(contador); }else if (direccion.equals(SE)) { getSouthWestDirectionDown(contador); }else { throw new DownAddressException("\"Los valores ingresados deben ser"+"\n"+": Suroriente o Suroeste\""); } } } //Metodos de la parte superior de la matriz. /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección nororiental desde la parte superior * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getNorthEastDirectionUp(int contador) { int h = 0; int w = getposicion(); while(contador < getDimension()) { if((h-1) < 0 && (w-1) < 0) { h += 1; matriz[h][w] = ++contador; }else if ((w-1) < 0) { h -= 1; w = getLastRoworColumn(); matriz[h][w] = ++contador; }else if((h-1) < 0) { h = getLastRoworColumn(); w -= 1; matriz[h][w] = ++contador; }else if (matriz[h-1][w-1] == 0) { h -= 1; w -= 1; matriz[h][w] = ++contador; }else { h += 1; matriz[h][w] = ++contador; } } } /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección noroccidental desde la parte superior * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getNorthWestDirectionUp(int contador) { int h = 0; int w = getposicion(); while(contador < getDimension()) { if ((h-1) < 0 && (w+1) > getTamahno()) { h += 1; matriz[h][w] = ++contador; }else if ((h-1) < 0) { h = getLastRoworColumn(); w += 1; matriz[h][w] = ++contador; }else if ((w+1) > getTamahno()) { h -= 1; w = 0; matriz[h][w] = ++contador; }else if (matriz[h-1][w+1] != 0) { h += 1; matriz[h][w] = ++contador; }else { h -=1 ; w += 1; matriz[h][w] = ++contador; } } } // Metodos de la parte derecha de la matriz. /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección noroccidental desde la posición lateral derecho. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getNorthWestDirectionRight(int contador) { int h = getposicion(); int w = getLastRoworColumn(); while(contador < getDimension()) { if ((h-1) < 0 && (w+1) > getTamahno()) { w -= 1; matriz[h][w] = ++contador; }else if ((h-1) < 0) { h = getLastRoworColumn(); w += 1; matriz[h][w] = ++contador; }else if ((w+1) > getTamahno()) { h -= 1; w = 0; matriz[h][w] = ++contador; }else if (matriz[h-1][w+1] != 0) { w -= 1; matriz[h][w] = ++contador; }else { h -=1 ; w += 1; matriz[h][w] = ++contador; } } } /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección suroccidental desde la posición lateral derecho. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getSouthWestDirectionRight(int contador) { int h = getposicion(); int w = getLastRoworColumn(); while (contador < getDimension()) { if((h+1) > getTamahno() && (w+1) > getTamahno()) { w -= 1; contador++; matriz[h][w] = contador; }else if((w+1) > getTamahno()) { h += 1; w = 0; contador++; matriz[h][w] = contador; }else if ((h+1)> getTamahno()) { h = 0; w +=1; contador++; matriz[h][w] = contador; }else if(matriz[h+1][w+1] == 0) { h +=1; w +=1; contador++; matriz[h][w] = contador; }else { w -=1; contador++; matriz[h][w] = contador; } } } // Metodos de la parte izquierda de la matriz. /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección nororiental desde la posición lateral Izquierdo. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getNorthEastDirectionLeft(int contador) { int h = getposicion(); int w = 0; while(contador < getDimension()) { if ((h-1) < 0 && (w-1) < 0) { w += 1; matriz[h][w] = ++contador; }else if ((h-1) < 0) { h = getLastRoworColumn(); w -= 1; matriz[h][w] = ++contador; }else if ((w-1) < 0) { h -=1; w = getLastRoworColumn(); matriz[h][w] = ++contador; }else if (matriz[h-1][w-1] != 0) { w += 1; matriz[h][w] = ++contador; }else { h -= 1; w -= 1; matriz[h][w] = ++contador; } } } /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección suroriental desde la posición lateral Izquierdo. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getSouthEastDirectionLeft(int contador) { int h = getposicion(); int w = 0; while(contador < getDimension()) { if ((h+1) > getTamahno() && (w-1) < 0) { w += 1; matriz[h][w] = ++contador; }else if ((h+1) > getTamahno()) { h = 0; w -= 1; matriz[h][w] = ++contador; }else if ((w-1) < 0) { h += 1; w = getLastRoworColumn(); matriz[h][w] = ++contador; }else if (matriz[h+1][w-1] == 0) { h += 1; w -= 1; matriz[h][w] = ++contador; }else { w+=1; matriz[h][w] = ++contador; } } } // Metodo de la parte inferior de la matriz. /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección suroriental desde la parte inferior. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getSouthEastDirectionDown(int contador) { int h = getLastRoworColumn() ; int w = getposicion(); while(contador < getDimension()) { if((h+1) > getTamahno() && (w-1)<0) { h -= 1; contador++; matriz[h][w] = contador; }else if ((w-1) < 0) { w = getLastRoworColumn(); h += 1; contador++; matriz[h][w] = contador; }else if ((h+1) > getTamahno()) { h = 0; w -= 1 ; contador++; matriz[h][w] = contador; }else if (matriz[h+1][w-1] != 0) { h -= 1; contador++; matriz[h][w] = contador; }else { h += 1; w -= 1; contador++; matriz[h][w] = contador; } } } /** * <br>Pre:</br> El contador fue modificado (contador = 1). * LLena la matriz en dirección surocciental desde la parte inferior. * @param contador define la sumatoria hasta la dimensión de la matriz. */ private void getSouthWestDirectionDown(int contador) { int h = getLastRoworColumn(); int w = getposicion(); while(contador < getDimension()) { if((h+1) > getTamahno() && (w+1) > getTamahno()) { h -=1; contador++; matriz[h][w] = contador; }else if((w+1) > getTamahno()) { h +=1; w = 0; contador++; matriz[h][w] = contador; }else if ((h+1) > getTamahno()) { h = 0; w += 1; contador++; matriz[h][w] = contador; }else if (matriz[h+1][w+1] != 0) { h -= 1; contador++; matriz[h][w] = contador; }else { h +=1; w += 1; contador++; matriz[h][w] = contador; } } } }
true
d05a90a9da67377b45905e867633c94986e72e49
Java
cnnu/RBAC
/src/main/java/cn/wolfcode/domain/Role.java
UTF-8
761
2.171875
2
[]
no_license
package cn.wolfcode.domain; import java.util.List; public class Role { private Long id; private String name; private String sn; private List<Permission> permissionList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } public List<Permission> getPermissionList() { return permissionList; } public void setPermissionList(List<Permission> permissionList) { this.permissionList = permissionList; } }
true
26cb1bd8f74558d4838914ee292838bf74ffca8c
Java
heliu0/springcloud-k8s
/springcloud-k8s-customer/src/main/java/com/yayiyo/client/ProducerClient.java
UTF-8
654
2.046875
2
[]
no_license
package com.yayiyo.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name = "http://producer-service:8082", url = "http://producer-service:8082", fallback = ProducerClientFallback.class) public interface ProducerClient { @RequestMapping(value = "/ping", method = RequestMethod.GET) String ping(); } @Component class ProducerClientFallback implements ProducerClient{ @Override public String ping() { return "Error"; } }
true
1c537e0ba81cc12d097347781ba6ff5e35d30c40
Java
igneoman/DataAndroid
/app/src/main/java/com/example/gestor/EliminarProveedor.java
UTF-8
1,652
2.234375
2
[]
no_license
package com.example.gestor; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class EliminarProveedor extends AppCompatActivity { Connection conexion=null; PreparedStatement preparedStatement=null; EditText Cif; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_eliminar_proveedor); Cif = (EditText) findViewById(R.id.inNumf2); } public void elp(View view){ try { conexion = Connect.conecta(); preparedStatement = conexion.prepareStatement("Delete from prov_comp where CIF_PROVEEDOR=?"); preparedStatement.setString(1, Cif.getText().toString()); int ok = preparedStatement.executeUpdate(); if (ok > 0) { Toast.makeText(getApplicationContext(),"Dato quitado", Toast.LENGTH_SHORT).show(); conexion.close(); } else if(conexion==null) { Toast.makeText(getApplicationContext(),"Error eliminar, valor nulo", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"Error eliminar", Toast.LENGTH_SHORT).show(); } } catch (SQLException e1) { e1.printStackTrace(); } } public void canp(View view){ finish(); } }
true
b0f97d72d7e6e21b9c25053e50ac70cc9e7eabb0
Java
mmaeller/parcelshop-api
/src/main/java/de/maeller/parcelshop/bean/hermes/HermesParcelShop.java
UTF-8
601
1.625
2
[]
no_license
package de.maeller.parcelshop.bean.hermes; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class HermesParcelShop { private HermesAddress address; @JsonProperty("dist") private long distance; private String description; private String shopOwner; private long parcelShopNumber; private List<HermesOpening> businessHours; private boolean acceptSuitcases; private boolean sellsBoxes; private String externalId; private String salesforceID; private long typeID; private long sortCode1; }
true
b9022adf51eccabbd20700a03d6a31bb89a79969
Java
MobileGuru1013/Kiosk
/src/org/ubt/kiosk/ui/Main.java
UTF-8
2,096
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.ubt.kiosk.ui; import org.ubt.kiosk.ui.EventHandling.MouseAdapterBackFromEditScreen; import org.ubt.kiosk.ui.EventHandling.MouseAdapterCloseWindows; import org.ubt.kiosk.ui.EventHandling.MouseAdapterEditScreen; import org.ubt.kiosk.ui.EventHandling.MouseAdapterLogOut; import org.ubt.kiosk.ui.EventHandling.MouseAdapterLogin; import org.ubt.kiosk.ui.EventHandling.MouseAdapterUpdateStudentEditScreen; import org.ubt.kiosk.ui.EventHandling.MouseAdapterViewSchedule; /** * * @author F * Starts the main Gui app, and assigns the listeners for each * components start the application */ public class Main { public static void main(String[] args) { JPMain jpMain = new JPMain(); JPLoginScreen jpLoginScreen = new JPLoginScreen(); JPInformationScreen jpStudentInformation = new JPInformationScreen(); JPViewScheduleScreen jpViewScheduleScreen = new JPViewScheduleScreen(); JPStudentEditScreen jpStudentEditScreen = new JPStudentEditScreen(); JFMain jfMain = new JFMain(jpMain, jpLoginScreen, jpStudentInformation, jpViewScheduleScreen, jpStudentEditScreen); jpLoginScreen.addCloseMainWindowsMouseAdapter(new MouseAdapterCloseWindows(jfMain)); jpLoginScreen.addLoginMouseAdapter(new MouseAdapterLogin(jfMain)); jpStudentInformation.addEditStudentMouseAdapter(new MouseAdapterEditScreen(jfMain)); jpStudentInformation.addViewScheduleScreenListener(new MouseAdapterViewSchedule(jfMain)); jpStudentInformation.addLogOutAdapter(new MouseAdapterLogOut(jfMain)); jpStudentEditScreen.addBackMouseAdapter(new MouseAdapterBackFromEditScreen(jfMain)); jpStudentEditScreen.addUpdateMouseAdapter(new MouseAdapterUpdateStudentEditScreen(jfMain)); jpViewScheduleScreen.addBackMouseAdapter(new MouseAdapterBackFromEditScreen(jfMain)); jfMain.setSize(800, 800); } }
true
efed221fe8e6a7e9cba58d21d34a0cac2b0d9ba5
Java
haphan2014/idle_heroes
/com/applovin/impl/sdk/bq.java
UTF-8
728
1.78125
2
[]
no_license
package com.applovin.impl.sdk; import com.applovin.nativeAds.AppLovinNativeAdLoadListener; import java.util.List; class bq implements AppLovinNativeAdLoadListener { final /* synthetic */ AppLovinNativeAdLoadListener f493a; final /* synthetic */ bk f494b; bq(bk bkVar, AppLovinNativeAdLoadListener appLovinNativeAdLoadListener) { this.f494b = bkVar; this.f493a = appLovinNativeAdLoadListener; } public void onNativeAdsFailedToLoad(int i) { if (this.f493a != null) { this.f493a.onNativeAdsFailedToLoad(i); } } public void onNativeAdsLoaded(List list) { if (this.f493a != null) { this.f493a.onNativeAdsLoaded(list); } } }
true
88a301d0ef80cd88a487c4e09186a67fb4f794c2
Java
mpas97/cineast
/cineast-core/src/main/java/org/vitrivr/cineast/core/data/ExistenceCheck.java
UTF-8
98
1.734375
2
[ "MIT" ]
permissive
package org.vitrivr.cineast.core.data; public interface ExistenceCheck { boolean exists(); }
true
676d37226293cadfba11d962dd19f166b1ff4551
Java
nagi-git/Studying
/src/minami2/ExToday.java
UTF-8
837
3.265625
3
[]
no_license
package minami2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; public class ExToday { public static void main (String[] args) throws IOException { Calendar today = Calendar.getInstance(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("何月?==>"); String strMonth = br.readLine(); int inputMonth = Integer.parseInt(strMonth); System.out.print("何日?==>"); String strDay = br.readLine(); int inputDay = Integer.parseInt(strDay); int todayMonth = today.get(Calendar.MONTH) + 1; int todayDay = today.get(Calendar.DATE); if(todayMonth == inputMonth && todayDay == inputDay) { System.out.println("正解!!"); } else { System.out.println("間違っています"); } } }
true
32d83250e7b8204d520ad45077de353300509ab8
Java
git-sky/spring-mvc-demo
/src/main/java/cn/com/sky/custom/MyHandler.java
UTF-8
327
1.78125
2
[]
no_license
package cn.com.sky.custom; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义handler */ public interface MyHandler { ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response); }
true
cc49ad528c525d0b0d0247129d31855e61be0611
Java
dsuru1499/situation_exchange
/src/main/java/situation_exchange/common/errors/factories/CapabilityNotSupportedErrorFactory.java
UTF-8
962
2.171875
2
[]
no_license
package situation_exchange.common.errors.factories; import org.apache.commons.lang3.exception.ExceptionUtils; import situation_exchange.common.errors.CapabilityNotSupportedError; import uk.org.siri.siri.CapabilityNotSupportedErrorStructure; import uk.org.siri.siri.ErrorConditionStructure; public class CapabilityNotSupportedErrorFactory extends ErrorConditionFactory<CapabilityNotSupportedError> { static { _factories.put(CapabilityNotSupportedError.class, new CapabilityNotSupportedErrorFactory()); } @Override protected ErrorConditionStructure createErrorCondition(CapabilityNotSupportedError e) { ErrorConditionStructure result = _factory.createErrorConditionStructure(); CapabilityNotSupportedErrorStructure error = _factory.createCapabilityNotSupportedErrorStructure(); error.setErrorText(ExceptionUtils.getMessage(e)); error.setCapabilityRef(e.getCapabilityRef()); result.setCapabilityNotSupportedError(error); return result; } }
true
909b216e331e6fbe6758bb2bd78db534cdd06859
Java
huojun17603/ICH-Core
/src/main/java/com/ich/core/http/entity/EasyUITreeNode.java
UTF-8
1,549
2.328125
2
[]
no_license
package com.ich.core.http.entity; import java.util.List; /** * easyUI树形控件节点格式 * <p>Title: EUTreeNode</p> * <p>Description: </p> * @version 1.0 */ public class EasyUITreeNode { private String id; //节点id private String text; //节点的内容 private String state; //节点的状态(open:打开;closed) private String parent_id; //节点的父id private Integer checked; //1 表示选中 0表示不选中 private List<?> children; //其子内容 private String iconCls; //图标 private List<String> attributes; //属性 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getParent_id() { return parent_id; } public void setParent_id(String parent_id) { this.parent_id = parent_id; } public Integer getChecked() { return checked; } public void setChecked(Integer checked) { this.checked = checked; } public List<?> getChildren() { return children; } public void setChildren(List<?> children) { this.children = children; } public String getIconCls() { return iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } public List<String> getAttributes() { return attributes; } public void setAttributes(List<String> attributes) { this.attributes = attributes; } }
true
1e1df1094303ea68f0f4839338ab610c6a94b3bc
Java
JoseMariaMorenoRueda/Triangles
/src/print/PrintTriangles.java
UTF-8
3,635
3.984375
4
[]
no_license
package print; public class PrintTriangles { public static void printPowerOf2Triangle(int size) { System.out.println("\nModel PowerOf2Triangle\n"); int counter1 = size - 1; int aux1 = 0, aux2, aux3; for (int i = 0; i < size; i++) { for (int j = 0; j < counter1; j++) { System.out.print(" "); } for (int k = 1; k <= i + 1; k++) { if (k < 3) { aux2 = k; } else { aux2 = aux1 * 2; } aux1 = aux2; if (aux1 < 10) { System.out.print(" " + aux1 + " "); } else { if (aux1 < 100) { System.out.print(" " + aux1 + " "); } else { System.out.print(aux1 + " "); } } } aux3 = aux1; for (int l = i; l >= 1; l--) { if (l < 3) { aux2 = l; } else { aux2 = aux3 / 2; } aux3 = aux2; if (aux3 < 10) { System.out.print(" " + aux3 + " "); } else { System.out.print(" " + aux3 + " "); } } counter1--; System.out.println(); } } public static void printPascalTriangle1(int size) { System.out.println("\nModel PascalTriangle1\n"); int[] arrayNumbers = new int[size]; for (int i = 0; i < size; i++) { // In this way, an auxiliary array is created whose number of elements is the amount // that we pass as a parameter and with all its elements to zero int[] arrayAuxNumbers = new int[size]; for (int j = 0; j < size; j++) { arrayAuxNumbers[j] = 0; } for (int k = 0; k <= i; k++) { if (k == 0 || k == i ) { arrayAuxNumbers[k] = 1; } else { arrayAuxNumbers[k] = arrayNumbers[k] + arrayNumbers[k - 1]; } System.out.print(arrayAuxNumbers[k] + " "); } arrayNumbers = arrayAuxNumbers; System.out.println(); } } public static void printPascalTriangle2(int size) { System.out.println("\nModel PascalTriangle2\n"); int[] arrayNumbers = new int[size]; int counter = size; for (int i = 0; i < size; i++) { int[] arrayAuxNumbers = new int[size]; for (int j = 0; j < size; j++) { arrayAuxNumbers[j] = 0; } for (int k = counter; k >= 0; k--) { System.out.print(" "); } for (int l = 0; l <= i; l++) { if (l == 0 || l == i ) { arrayAuxNumbers[l] = 1; } else { arrayAuxNumbers[l] = arrayNumbers[l] + arrayNumbers[l - 1]; } if (arrayAuxNumbers[l] > 9) { System.out.print(arrayAuxNumbers[l] + " "); } else { System.out.print(arrayAuxNumbers[l] + " "); } } counter--; arrayNumbers = arrayAuxNumbers; System.out.println(); } } public static void main(String[] argv) { printPowerOf2Triangle(8); printPascalTriangle1(7); printPascalTriangle2(7); } }
true
73c4b5742944696e0a4fd866b0f9bc7b318caab3
Java
avektor/Cybertekt-Engine-1.1
/test/net/cybertekt/gui/ElementTest2.java
UTF-8
4,447
2.328125
2
[]
no_license
package net.cybertekt.gui; import net.cybertekt.gui.element.Element_Old; import net.cybertekt.app.AppSettings; import net.cybertekt.app.Application; import net.cybertekt.asset.AssetManager; import net.cybertekt.asset.AssetType; import net.cybertekt.asset.shader.GLSLShader; import net.cybertekt.asset.shader.ShaderLoader; import net.cybertekt.app.listener.DisplayListener; import net.cybertekt.app.display.DisplaySettings; import net.cybertekt.app.listener.UpdateListener; import net.cybertekt.ogl.shader.GLShader; import net.cybertekt.render.Renderer; import org.joml.Matrix4f; import org.joml.Vector2i; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Vektor */ public class ElementTest2 extends Application implements UpdateListener, DisplayListener, Renderer { private static final Logger LOG = LoggerFactory.getLogger(ElementTest2.class); private GLShader shader; private Matrix4f projectionMatrix; public static final void main(final String[] args) { ElementTest2 app = new ElementTest2(); AppSettings appSettings = new AppSettings("Element Test", "1.0"); DisplaySettings displaySettings = new DisplaySettings("Element Test", new Vector2i(800, 600)); app.initialize(appSettings, displaySettings); } @Override public final void init() { // Attach Listeners // addUpdateListener(this); addDisplayListener(this); addRenderer(this); // Register Shader Loader // AssetManager.registerLoader(ShaderLoader.class, AssetType.getType("VERT"), AssetType.getType("FRAG")); // Load Element Shader // shader = new GLShader(AssetManager.get(GLSLShader.class, "Shaders/element.vert", "Shaders/element.frag")); // Initialize Projection Matrix // projectionMatrix = new Matrix4f().ortho2D(0, getWidth(), getHeight(), 0); Element elementA = new Element("A", Element.ChildLayout.HORIZONTAL, Element.ChildHAlign.LEFT, Element.ChildVAlign.TOP); elementA.setWidth("800px"); elementA.setHeight("600px"); Element elementB = new Element("B", Element.ChildLayout.HORIZONTAL, Element.ChildHAlign.LEFT, Element.ChildVAlign.TOP); elementB.setWidth("50%"); elementB.setHeight("50%"); elementA.attachChild(elementB); elementA.calculateSize(); elementB.calculateSize(); LOG.info("Size of A: {}x{}", (int) elementA.getSize().x, (int) elementA.getSize().y); LOG.info("Size of B: {}x{}", (int) elementB.getSize().x, (int) elementB.getSize().y); } @Override public final void update(final double tpf) { } @Override public final void update() { } @Override public final void render() { // Bind Shader // shader.bind(); shader.setUniform(0, projectionMatrix); //glPointSize(10f); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Render Mesh // //render(rootElement); //for (Element_Old e : rootElement.getChildren()) { // render(e); //} } public final void render(final Element_Old element) { //shader.setUniform(1, element.getTransform()); //shader.setUniform(2, element.getColor()); //for (final GLMesh mesh : element.getMeshList()) { // mesh.bind(); // if (mesh.hasBuffer(GLBuffer.Type.Indices)) { // glDrawElements(mesh.getMode().ID, mesh.getIndexCount(), mesh.getBuffer(GLBuffer.Type.Indices).getFormat().ID, 0); // } else if (mesh.hasBuffer(GLBuffer.Type.Positions)) { // glDrawArrays(mesh.getMode().ID, 0, mesh.getVertexCount()); // } //} } @Override public final void exit() { } @Override public void onFocus(final boolean focused) { } @Override public void onIconify(final boolean iconified) { } @Override public void onMove(final int xPos, final int yPos) { } @Override public void onResize(final int width, final int height) { } @Override public void onClose() { stop(); } }
true
32a934acb113fd09a2b2424d38155192a7cc48a2
Java
jadery/experi
/src/main/java/com/example/experi/cmq_test/CmqService.java
UTF-8
872
2.140625
2
[]
no_license
package com.example.experi.cmq_test; import cn.wesure.cmq.CmqTemplate; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CmqService { @Autowired private CmqTemplate cmqTemplate; public void sendCmq(String queueName, String cmqMsg) { try { cmqTemplate.sendQueue(queueName,cmqMsg); } catch (Exception e) { System.out.println("发送消息错误"); e.printStackTrace(); } } public void sendCmqJson(String queueName, JSONObject cmqJson) { try { cmqTemplate.sendQueue(queueName,cmqJson.toJSONString()); } catch (Exception e) { System.out.println("发送 json 消息错误"); e.printStackTrace(); } } }
true
3aa59af875ef0cfc710a146e14f04fade678b25c
Java
ramoncgusmao/URI-test
/src/strings/Led_1168.java
UTF-8
1,300
3.234375
3
[]
no_license
package strings; import java.util.Scanner; public class Led_1168 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tamanho = 0; String vetor[] = null; int i = 0; try { while(sc.hasNext()) { if(tamanho == 0) { tamanho = Integer.parseInt(sc.nextLine()); if(tamanho >= 1 && tamanho <= 2000) { vetor = new String[tamanho]; }else { break; } } if(vetor != null) { vetor[i] = sc.next(); System.out.println(mensagem(vetor[i]) + " leds"); i++; if(i == tamanho) { break; } } } } catch (Exception e) { // TODO: handle exception } sc.close(); } public static int mensagem(String msg) { int total = 0; for (int i = 0; i < msg.length(); i++) { total += quantidadeLed(msg.charAt(i)); } return total; } public static int quantidadeLed(char ch) { int valor = 0; int numero = Character.getNumericValue(ch); switch(numero) { case 1: valor = 2; break; case 2: case 3: case 5: valor = 5; break; case 4: valor = 4; break; case 6: case 0: case 9: valor = 6; break; case 7: valor = 3; break; case 8: valor = 7; break; } return valor; } }
true
64fc3574d7e449cb81be4bacab98f61f620fe328
Java
mattsidesinger/words-with-core
/src/test/java/com/wordswithcheats/board/TileTest.java
UTF-8
3,845
3.09375
3
[]
no_license
package com.wordswithcheats.board; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; /** * Test case for the {@link Tile} class. * * @author Matt Sidesinger */ public class TileTest { @Test public void testTile() { Tile t = new Tile('a'); assertEquals('a', t.getLetter()); t = new Tile('A'); assertEquals('a', t.getLetter()); try { t = new Tile('4'); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // success } try { t = new Tile((char) 0); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // success } } @Test public void testgetPointValue() { assertEquals(1, Tile.valueOf('a').getPointValue()); assertEquals(3, Tile.valueOf('b').getPointValue()); assertEquals(3, Tile.valueOf('c').getPointValue()); assertEquals(2, Tile.valueOf('d').getPointValue()); assertEquals(1, Tile.valueOf('e').getPointValue()); assertEquals(4, Tile.valueOf('f').getPointValue()); assertEquals(2, Tile.valueOf('g').getPointValue()); assertEquals(4, Tile.valueOf('h').getPointValue()); assertEquals(1, Tile.valueOf('i').getPointValue()); assertEquals(8, Tile.valueOf('j').getPointValue()); assertEquals(5, Tile.valueOf('k').getPointValue()); assertEquals(1, Tile.valueOf('l').getPointValue()); assertEquals(3, Tile.valueOf('m').getPointValue()); assertEquals(1, Tile.valueOf('n').getPointValue()); assertEquals(1, Tile.valueOf('o').getPointValue()); assertEquals(3, Tile.valueOf('p').getPointValue()); assertEquals(10, Tile.valueOf('q').getPointValue()); assertEquals(1, Tile.valueOf('r').getPointValue()); assertEquals(1, Tile.valueOf('s').getPointValue()); assertEquals(1, Tile.valueOf('t').getPointValue()); assertEquals(1, Tile.valueOf('u').getPointValue()); assertEquals(4, Tile.valueOf('v').getPointValue()); assertEquals(4, Tile.valueOf('w').getPointValue()); assertEquals(8, Tile.valueOf('x').getPointValue()); assertEquals(4, Tile.valueOf('y').getPointValue()); assertEquals(10, Tile.valueOf('z').getPointValue()); } @Test public void testValueOf() { assertTrue(Tile.valueOf('a') == Tile.valueOf('a')); assertTrue(Tile.valueOf('A') == Tile.valueOf('a')); assertTrue(Tile.valueOf('a') != new Tile('a')); } @Test public void testClone() throws Exception { Tile t1 = new Tile('a'); Tile t2 = (Tile) t1.clone(); assertEquals(t1, t2); assertTrue(t1 != t2); t1 = Tile.valueOf('a'); t2 = (Tile) t1.clone(); assertEquals(t1, t2); assertTrue(t1 != t2); } @Test public void testToChar() { Tile t = new Tile('a'); assertEquals('A', t.toChar()); t = new Tile('A'); assertEquals('A', t.toChar()); t = Tile.valueOf('a'); assertEquals('A', t.toChar()); t = Tile.valueOf('A'); assertEquals('A', t.toChar()); } @Test public void testToString() { Tile t = Tile.valueOf('a'); assertEquals("[A:1]", t.toString()); t = Tile.valueOf('A'); assertEquals("[A:1]", t.toString()); t = Tile.valueOf('q'); assertEquals("[Q:10]", t.toString()); } @Test public void testEquals() { Tile t1 = new Tile('a'); Tile t2 = new Tile('a'); assertTrue(t1.equals(t2)); t1 = Tile.valueOf('a'); t2 = Tile.valueOf('a'); assertTrue(t1.equals(t2)); t1 = new Tile('a'); t2 = Tile.valueOf('a'); assertTrue(t1.equals(t2)); t1 = Tile.valueOf('a'); t2 = null; assertFalse(t1.equals(t2)); t1 = Tile.valueOf('a'); t2 = Tile.valueOf('b'); assertFalse(t1.equals(t2)); } }
true
c6c021c5420bf621ac517edec3e24e8c9990da85
Java
jaeseongDev/java-chess-practice
/src/main/java/chess/domain/piece/moveStrategy/RookMoveStrategy.java
UTF-8
100
1.515625
2
[]
no_license
package chess.domain.piece.moveStrategy; public class RookMoveStrategy implements MoveStrategy { }
true
40ba88a3bb1ea4fd7bd0c22291845bab3488be00
Java
aprax11/Prog3_final
/tst/view/AllergenBeobachterTest.java
UTF-8
2,544
2.484375
2
[]
no_license
package view; import automat.*; import automat.Beobachter; import automat.Container; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.math.BigDecimal; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; public class AllergenBeobachterTest { @Test public void allergenAddBeobachterTest() { GeschäftslogikImpl gl = new GeschäftslogikImpl(3); Hersteller hersteller = new HerstellerImpl("paul"); Beobachter beobachter = new AllergenBeobachter(gl); Duration duration = Duration.ofDays(32); BigDecimal preis = new BigDecimal("4.20"); Collection<Allergen> allergens = new HashSet<>(); allergens.add(Allergen.Gluten); gl.addHersteller(hersteller); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(byteArrayOutputStream)); gl.addKuchen(new ArrayList<>(), new Container(hersteller, allergens, 123, duration, preis, "krem", KuchenTypen.Kremkuchen)); assertEquals("allergen(e) hinzugefügt [Gluten]"+System.lineSeparator(), byteArrayOutputStream.toString()); try { byteArrayOutputStream.close(); } catch (IOException e) { fail(); } System.setOut(System.out); } @Test public void allergenRemoveBeobachterTest() { GeschäftslogikImpl gl = new GeschäftslogikImpl(3); Hersteller hersteller = new HerstellerImpl("paul"); Beobachter beobachter = new AllergenBeobachter(gl); Duration duration = Duration.ofDays(32); BigDecimal preis = new BigDecimal("4.20"); Collection<Allergen> allergens = new HashSet<>(); allergens.add(Allergen.Gluten); gl.addHersteller(hersteller); gl.addKuchen(new ArrayList<>(), new Container(hersteller, allergens, 123, duration, preis, "krem", KuchenTypen.Kremkuchen)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(byteArrayOutputStream)); gl.löscheKuchen(0); assertEquals("allergen(e) entfernt [Gluten]"+System.lineSeparator(), byteArrayOutputStream.toString()); try { byteArrayOutputStream.close(); } catch (IOException e) { fail(); } System.setOut(System.out); } }
true
3b534e2228cac086f180f53673f4c2e2fd41d36a
Java
LucynaB/Computer
/src/ComputerAssembly.java
UTF-8
384
2.703125
3
[]
no_license
class ComputerAssembly { Computer assembly(String compName, String procName, String procModel, double cpuClock, String memName, String memModel, double memSize, double memClock ){ Procesor proc = new Procesor(procName, procModel, cpuClock); Memory mem = new Memory(memName, memModel, memSize, memClock); return new Computer(compName, proc, mem); } }
true
67c8e10b2cbb7d2ef403344c31a0ec956b6adee0
Java
ManonGros/registry
/registry-doi/src/main/java/org/gbif/registry/doi/registration/DoiRegistrationService.java
UTF-8
810
2.421875
2
[ "Apache-2.0" ]
permissive
package org.gbif.registry.doi.registration; import org.gbif.api.model.common.DOI; import org.gbif.api.model.common.DoiData; import org.gbif.registry.doi.DoiType; /** * Specifies the contract of a service that manages DOI registrations. */ public interface DoiRegistrationService { /** * Generates a new DOI based on the DoiType. */ DOI generate(DoiType doiType); /** * Retrieves the DOI information. */ DoiData get(String prefix, String suffix); /** * Register a new DOI, if the registration object doesn't contain a DOI a new DOI is generated. */ DOI register(DoiRegistration doiRegistration); /** * Update a DOI registration data. */ DOI update(DoiRegistration doiRegistration); /** * Deletes a DOI. */ void delete(String prefix, String suffix); }
true
9cac6d93908bf078b0f368b47d67d711e47dc656
Java
HadiSDev/AddressAflevering
/src/Model/Address.java
UTF-8
2,791
3.09375
3
[]
no_license
package Model; import java.util.regex.*; import Exception.AddressNotFoundException; public class Address { private final String street, house, floor, side, postcode, city; private Address(String _street, String _house, String _floor, String _side, String _postcode, String _city) { this.street = _street; this.house = _house; this.floor = _floor; this.side = _side; this.postcode = _postcode; this.city = _city; } @Override public String toString() { return (street != null ? street + " " : "") + (house != null ? house + " " : "") + (floor != null ? floor + " " : "") + (side != null ? side + " " : "") + (postcode != null ? postcode + " " : "") + (city != null ? city + " " : ""); } public static class Builder { private String street = "Unknown", house, floor, side, postcode, city; public Builder street(String _street) { street = _street; return this; } public Builder house(String _house) { house = _house; return this; } public Builder floor(String _floor) { floor = _floor; return this; } public Builder side(String _side) { side = _side; return this; } public Builder postcode(String _postcode) { postcode = _postcode; return this; } public Builder city(String _city) { city = _city; return this; } public Address build() { return new Address(street, house, floor, side, postcode, city); } } public String street() { return street; } public String house() { return house; } public String floor() { return floor; } public String side() { return side; } public String postcode() { return postcode; } public String city() { return city; } public static Address parse(String s) { final String regex = "(?<street>([0-9.]{1,3})?[a-zA-ZåæøÅÆØ. ]+)?\\s*(?<house>\\d{1,3}[A-Z]?)?\\s*[,]*\\s*(?<floor>(st|k(\\d{1,2})?|[1-9]{1,2}))?\\s*[,]*\\s*(?<side>(tv|th|mf|[1-9]{1,2}))?\\s*[,]*\\s*(?<postcode>\\d{4})?\\s*(?<city>[a-zA-ZåæøÅÆØ., ]+)?"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(s); Builder b = new Builder(); if (matcher.matches()) { return b.city(matcher.group("city")). house(matcher.group("house")). floor(matcher.group("floor")). side(matcher.group("side")). postcode(matcher.group("postcode")). street(matcher.group("street").trim()).build(); } throw new AddressNotFoundException("Address not typed correctly!",s); } }
true
ea567be31d9663e5d9f23fe2d5b7b992056fe4b7
Java
wyc3146/maven_web_simple
/src/main/java/com/wyc/web/HelloServlet.java
UTF-8
1,260
2.46875
2
[]
no_license
package com.wyc.web;/** * Created by wyc on 2017/01/13. */ import com.wyc.web.config.CommonConfig; import com.wyc.web.spring.SpringBeanManager; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author wangyongcan * @Date 2017/01/13 14:52 */ public class HelloServlet extends HttpServlet { private String message; public void init() throws ServletException { // 执行必需的初始化 } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { CommonConfig commonConfig = SpringBeanManager.getBean("commonConfig", CommonConfig.class); // 设置响应内容类型 response.setContentType("text/html"); // 实际的逻辑是在这里 PrintWriter out = response.getWriter(); out.println("<h1>" + commonConfig.getInitMessage() + "</h1>"); } public void destroy() { // 什么也不做 } }
true
2b47fee5fdec8cff9831121aae31a18398b83f87
Java
whywuzeng/choerodon-iam
/src/main/java/io/choerodon/iam/infra/dto/DashboardDTO.java
UTF-8
3,208
2.078125
2
[]
no_license
package io.choerodon.iam.infra.dto; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.validation.constraints.NotBlank; import io.choerodon.mybatis.domain.AuditDomain; import io.choerodon.mybatis.annotation.ModifyAudit; import io.choerodon.mybatis.annotation.VersionAudit; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hzero.starter.keyencrypt.core.Encrypt; /** * @author jian.zhang02@hand-china.com 2021-07-08 10:05:56 */ @ApiModel("") @VersionAudit @ModifyAudit @Table(name = "fd_dashboard") public class DashboardDTO extends AuditDomain { public static final String FIELD_DASHBOARD_ID = "dashboardId"; public static final String FIELD_DASHBOARD_TYPE = "dashboardType"; public static final String FIELD_DASHBOARD_NAME = "dashboardName"; public static final String FIELD_DEFAULT_FLAG = "defaultFlag"; // // 业务方法(按public protected private顺序排列) // ------------------------------------------------------------------------------ // // 数据库字段 // ------------------------------------------------------------------------------ @ApiModelProperty("面板ID") @Id @GeneratedValue @Encrypt private Long dashboardId; @ApiModelProperty(value = "面板类型(CUSTOMIZE/自定义;INTERNAL/内置)") private String dashboardType; @ApiModelProperty(value = "面板名称", required = true) @NotBlank private String dashboardName; @ApiModelProperty(value = "默认面板") private Integer defaultFlag; @Transient private Long dashboardUserId; // // 非数据库字段 // ------------------------------------------------------------------------------ // // getter/setter // ------------------------------------------------------------------------------ /** * @return 面板ID */ public Long getDashboardId() { return dashboardId; } public DashboardDTO setDashboardId(Long dashboardId) { this.dashboardId = dashboardId; return this; } /** * @return 面板类型(CUSTOMIZE / 自定义 ; INTERNAL / 内置) */ public String getDashboardType() { return dashboardType; } public DashboardDTO setDashboardType(String dashboardType) { this.dashboardType = dashboardType; return this; } /** * @return 面板名称 */ public String getDashboardName() { return dashboardName; } public DashboardDTO setDashboardName(String dashboardName) { this.dashboardName = dashboardName; return this; } /** * @return 默认面板 */ public Integer getDefaultFlag() { return defaultFlag; } public DashboardDTO setDefaultFlag(Integer defaultFlag) { this.defaultFlag = defaultFlag; return this; } public Long getDashboardUserId() { return dashboardUserId; } public void setDashboardUserId(Long dashboardUserId) { this.dashboardUserId = dashboardUserId; } }
true
b6c475297cd8db46bdd40518a25d6e572cb46cd9
Java
Finomnis/FFTImageEditor
/jogamp/src/jogl/com/jogamp/graph/curve/opengl/TextRegionUtil.java
UTF-8
16,915
2.109375
2
[]
no_license
/** * Copyright 2014 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package com.jogamp.graph.curve.opengl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import javax.media.opengl.GL2ES2; import javax.media.opengl.GLException; import jogamp.graph.geom.plane.AffineTransform; import com.jogamp.graph.curve.OutlineShape; import com.jogamp.graph.curve.Region; import com.jogamp.graph.font.Font; import com.jogamp.graph.font.Font.Glyph; import com.jogamp.graph.geom.Vertex; import com.jogamp.graph.geom.Vertex.Factory; /** * Text {@link GLRegion} Utility Class */ public class TextRegionUtil { public final int renderModes; public TextRegionUtil(final int renderModes) { this.renderModes = renderModes; } public static interface ShapeVisitor { /** * Visiting the given {@link OutlineShape} with it's corresponding {@link AffineTransform}. * @param shape may be used as is, otherwise a copy shall be made if intended to be modified. * @param t may be used immediately as is, otherwise a copy shall be made if stored. */ public void visit(final OutlineShape shape, final AffineTransform t); } public static int getCharCount(final String s, final char c) { final int sz = s.length(); int count = 0; for(int i=0; i<sz; i++) { if( s.charAt(i) == c ) { count++; } } return count; } /** * Visit each {@link Font.Glyph}'s {@link OutlineShape} with the given {@link ShapeVisitor} * additionally passing the progressed {@link AffineTransform}. * The latter reflects the given font metric, pixelSize and hence character position. * @param visitor * @param transform optional given transform * @param font the target {@link Font} * @param pixelSize Use {@link Font#getPixelSize(float, float)} for resolution correct pixel-size. * @param str string text * @param temp1 temporary AffineTransform storage, mandatory, will be passed to {@link ShapeVisitor#visit(OutlineShape, AffineTransform)} and can be modified. * @param temp2 temporary AffineTransform storage, mandatory, can be re-used in {@link ShapeVisitor#visit(OutlineShape, AffineTransform)} by user code. */ public static void processString(final ShapeVisitor visitor, final AffineTransform transform, final Font font, final float pixelSize, final CharSequence str, final AffineTransform temp1, final AffineTransform temp2) { final int charCount = str.length(); // region.setFlipped(true); final Font.Metrics metrics = font.getMetrics(); final float lineHeight = font.getLineHeight(pixelSize); final float scale = metrics.getScale(pixelSize); float y = 0; float advanceTotal = 0; for(int i=0; i< charCount; i++) { final char character = str.charAt(i); if( '\n' == character ) { y -= lineHeight; advanceTotal = 0; } else if (character == ' ') { advanceTotal += font.getAdvanceWidth(Glyph.ID_SPACE, pixelSize); } else { if(Region.DEBUG_INSTANCE) { System.err.println("XXXXXXXXXXXXXXx char: "+character+", scale: "+scale+"; translate: "+advanceTotal+", "+y); } // reset transform if( null != transform ) { temp1.setTransform(transform); } else { temp1.setToIdentity(); } temp1.translate(advanceTotal, y, temp2); temp1.scale(scale, scale, temp2); final Font.Glyph glyph = font.getGlyph(character); final OutlineShape glyphShape = glyph.getShape(); if( null == glyphShape ) { continue; } visitor.visit(glyphShape, temp1); advanceTotal += glyph.getAdvance(pixelSize, true); } } } /** * Add the string in 3D space w.r.t. the font and pixelSize at the end of the {@link GLRegion}. * @param region the {@link GLRegion} sink * @param vertexFactory vertex impl factory {@link Factory} * @param font the target {@link Font} * @param pixelSize Use {@link Font#getPixelSize(float, float)} for resolution correct pixel-size. * @param str string text * @param rgbaColor if {@link Region#hasColorChannel()} RGBA color must be passed, otherwise value is ignored. * @param temp1 temporary AffineTransform storage, mandatory * @param temp2 temporary AffineTransform storage, mandatory */ public static void addStringToRegion(final GLRegion region, final Factory<? extends Vertex> vertexFactory, final Font font, final float pixelSize, final CharSequence str, final float[] rgbaColor, final AffineTransform temp1, final AffineTransform temp2) { final ShapeVisitor visitor = new ShapeVisitor() { public final void visit(final OutlineShape shape, final AffineTransform t) { region.addOutlineShape(shape, t, region.hasColorChannel() ? rgbaColor : null); } }; processString(visitor, null, font, pixelSize, str, temp1, temp2); } /** * Render the string in 3D space w.r.t. the font and pixelSize * using a cached {@link GLRegion} for reuse. * <p> * Cached {@link GLRegion}s will be destroyed w/ {@link #clear(GL2ES2)} or to free memory. * </p> * @param gl the current GL state * @param renderer TODO * @param font {@link Font} to be used * @param pixelSize Use {@link Font#getPixelSize(float, float)} for resolution correct pixel-size. * @param str text to be rendered * @param rgbaColor if {@link Region#hasColorChannel()} RGBA color must be passed, otherwise value is ignored. * @param sampleCount desired multisampling sample count for msaa-rendering. * The actual used scample-count is written back when msaa-rendering is enabled, otherwise the store is untouched. * @throws Exception if TextRenderer not initialized */ public void drawString3D(final GL2ES2 gl, final RegionRenderer renderer, final Font font, final float pixelSize, final CharSequence str, final float[] rgbaColor, final int[/*1*/] sampleCount) { if( !renderer.isInitialized() ) { throw new GLException("TextRendererImpl01: not initialized!"); } final int special = 0; GLRegion region = getCachedRegion(font, str, pixelSize, special); if(null == region) { region = GLRegion.create(renderModes, null); addStringToRegion(region, renderer.getRenderState().getVertexFactory(), font, pixelSize, str, rgbaColor, tempT1, tempT2); addCachedRegion(gl, font, str, pixelSize, special, region); } region.draw(gl, renderer, sampleCount); } /** * Render the string in 3D space w.r.t. the font and pixelSize * using a temporary {@link GLRegion}, which will be destroyed afterwards. * <p> * In case of a multisampling region renderer, i.e. {@link Region#VBAA_RENDERING_BIT}, recreating the {@link GLRegion} * is a huge performance impact. * In such case better use {@link #drawString3D(GL2ES2, GLRegion, RegionRenderer, Font, float, CharSequence, float[], int[], AffineTransform, AffineTransform)} * instead. * </p> * @param gl the current GL state * @param renderModes TODO * @param font {@link Font} to be used * @param pixelSize Use {@link Font#getPixelSize(float, float)} for resolution correct pixel-size. * @param str text to be rendered * @param rgbaColor if {@link Region#hasColorChannel()} RGBA color must be passed, otherwise value is ignored. * @param sampleCount desired multisampling sample count for msaa-rendering. * The actual used scample-count is written back when msaa-rendering is enabled, otherwise the store is untouched. * @param temp1 temporary AffineTransform storage, mandatory * @param temp2 temporary AffineTransform storage, mandatory * @throws Exception if TextRenderer not initialized */ public static void drawString3D(final GL2ES2 gl, final int renderModes, final RegionRenderer renderer, final Font font, final float pixelSize, final CharSequence str, final float[] rgbaColor, final int[/*1*/] sampleCount, final AffineTransform temp1, final AffineTransform temp2) { if(!renderer.isInitialized()){ throw new GLException("TextRendererImpl01: not initialized!"); } final GLRegion region = GLRegion.create(renderModes, null); addStringToRegion(region, renderer.getRenderState().getVertexFactory(), font, pixelSize, str, rgbaColor, temp1, temp2); region.draw(gl, renderer, sampleCount); region.destroy(gl); } /** * Render the string in 3D space w.r.t. the font and pixelSize * using the given {@link GLRegion}, which will {@link GLRegion#clear(GL2ES2) cleared} beforehand. * @param gl the current GL state * @param font {@link Font} to be used * @param pixelSize Use {@link Font#getPixelSize(float, float)} for resolution correct pixel-size. * @param str text to be rendered * @param rgbaColor if {@link Region#hasColorChannel()} RGBA color must be passed, otherwise value is ignored. * @param sampleCount desired multisampling sample count for msaa-rendering. * The actual used scample-count is written back when msaa-rendering is enabled, otherwise the store is untouched. * @param temp1 temporary AffineTransform storage, mandatory * @param temp2 temporary AffineTransform storage, mandatory * @throws Exception if TextRenderer not initialized */ public static void drawString3D(final GL2ES2 gl, final GLRegion region, final RegionRenderer renderer, final Font font, final float pixelSize, final CharSequence str, final float[] rgbaColor, final int[/*1*/] sampleCount, final AffineTransform temp1, final AffineTransform temp2) { if(!renderer.isInitialized()){ throw new GLException("TextRendererImpl01: not initialized!"); } region.clear(gl); addStringToRegion(region, renderer.getRenderState().getVertexFactory(), font, pixelSize, str, rgbaColor, temp1, temp2); region.draw(gl, renderer, sampleCount); } /** * Clear all cached {@link GLRegions}. */ public void clear(final GL2ES2 gl) { // fluchCache(gl) already called final Iterator<GLRegion> iterator = stringCacheMap.values().iterator(); while(iterator.hasNext()){ final GLRegion region = iterator.next(); region.destroy(gl); } stringCacheMap.clear(); stringCacheArray.clear(); } /** * <p>Sets the cache limit for reusing GlyphString's and their Region. * Default is {@link #DEFAULT_CACHE_LIMIT}, -1 unlimited, 0 turns cache off, >0 limited </p> * * <p>The cache will be validate when the next string rendering happens.</p> * * @param newLimit new cache size * * @see #DEFAULT_CACHE_LIMIT */ public final void setCacheLimit(final int newLimit ) { stringCacheLimit = newLimit; } /** * Sets the cache limit, see {@link #setCacheLimit(int)} and validates the cache. * * @see #setCacheLimit(int) * * @param gl current GL used to remove cached objects if required * @param newLimit new cache size */ public final void setCacheLimit(final GL2ES2 gl, final int newLimit ) { stringCacheLimit = newLimit; validateCache(gl, 0); } /** * @return the current cache limit */ public final int getCacheLimit() { return stringCacheLimit; } /** * @return the current utilized cache size, <= {@link #getCacheLimit()} */ public final int getCacheSize() { return stringCacheArray.size(); } protected final void validateCache(final GL2ES2 gl, final int space) { if ( getCacheLimit() > 0 ) { while ( getCacheSize() + space > getCacheLimit() ) { removeCachedRegion(gl, 0); } } } protected final GLRegion getCachedRegion(final Font font, final CharSequence str, final float pixelSize, final int special) { return stringCacheMap.get(getKey(font, str, pixelSize, special)); } protected final void addCachedRegion(final GL2ES2 gl, final Font font, final CharSequence str, final float pixelSize, final int special, final GLRegion glyphString) { if ( 0 != getCacheLimit() ) { final String key = getKey(font, str, pixelSize, special); final GLRegion oldRegion = stringCacheMap.put(key, glyphString); if ( null == oldRegion ) { // new entry .. validateCache(gl, 1); stringCacheArray.add(stringCacheArray.size(), key); } /// else overwrite is nop .. } } protected final void removeCachedRegion(final GL2ES2 gl, final Font font, final CharSequence str, final int pixelSize, final int special) { final String key = getKey(font, str, pixelSize, special); final GLRegion region = stringCacheMap.remove(key); if(null != region) { region.destroy(gl); } stringCacheArray.remove(key); } protected final void removeCachedRegion(final GL2ES2 gl, final int idx) { final String key = stringCacheArray.remove(idx); if( null != key ) { final GLRegion region = stringCacheMap.remove(key); if(null != region) { region.destroy(gl); } } } protected final String getKey(final Font font, final CharSequence str, final float pixelSize, final int special) { final StringBuilder sb = new StringBuilder(); return font.getName(sb, Font.NAME_UNIQUNAME) .append(".").append(str.hashCode()).append(".").append(Float.floatToIntBits(pixelSize)).append(special).toString(); } /** Default cache limit, see {@link #setCacheLimit(int)} */ public static final int DEFAULT_CACHE_LIMIT = 256; public final AffineTransform tempT1 = new AffineTransform(); public final AffineTransform tempT2 = new AffineTransform(); private final HashMap<String, GLRegion> stringCacheMap = new HashMap<String, GLRegion>(DEFAULT_CACHE_LIMIT); private final ArrayList<String> stringCacheArray = new ArrayList<String>(DEFAULT_CACHE_LIMIT); private int stringCacheLimit = DEFAULT_CACHE_LIMIT; }
true
9ec88d27d9dac678a8f518ec1d1fcea73066950d
Java
mutuz786/swabhav
/OOP/account-equality-app/src/com/techlabs/model/test/AccountToString.java
UTF-8
263
2.40625
2
[]
no_license
package com.techlabs.model.test; import com.techlabs.model.Account; public class AccountToString { public static void main(String[] args) { Account acc1=new Account(100,"Murtaza",1000); System.out.println(acc1); System.out.println(acc1.toString()); } }
true
ba9928c3d37a87b4b86a679c1f02cf0b20fc9b1b
Java
tblsoft/solr-cmd-utils
/src/main/java/de/tblsoft/solr/pipeline/HtmlFileReader.java
UTF-8
997
2.1875
2
[ "MIT" ]
permissive
package de.tblsoft.solr.pipeline; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.util.IOUtils; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; /** * Read a html from a file. * It's for testing purpose. */ public class HtmlFileReader extends AbstractReader { public void read() { String fieldName = getProperty("fieldName", "http_payload"); String filename = getProperty("filename", null); String absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), filename); String charset = getProperty("charset", StandardCharsets.UTF_8.name()); try { String html = IOUtils.getString(absoluteFilename); Document document = new Document(); document.setField(fieldName, html); executer.document(document); } catch (Exception e) { throw new RuntimeException(e); } } }
true
b5ae467dd23bcfac8fb04fb398a8c9ed6d0f6537
Java
utkuertunc/ExceptionHandling
/src/main/java/com/exceptionhandling/exceptionhandling/exception/ApiExceptionHandler.java
UTF-8
510
2.125
2
[]
no_license
package com.exceptionhandling.exceptionhandling.exception; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler({EntityNotfoundException.class}) public String entityNotFound() { return "Kayit Bulunamadi"; } @ExceptionHandler({IllegalArgumentException.class}) public String iaException() { return "Yanlis Parametre"; } }
true
211f79bd93c381c2b7112c8fea00978694d75169
Java
jefersonleon/IntroducaoPOO
/src/projetooo/Carro.java
UTF-8
1,157
3.375
3
[]
no_license
package projetooo; /** * @author Jeferson */ public class Carro { //atributos == caracteristicas public String modelo; public String marca; public String cor; public int ano; public boolean completo; public String tipoCombustivel; //métodos == ações public void andar(){ System.out.println("Carro andando"); } public void buzinar(){ System.out.println("Carro buzinando"); } public void ligarFarol(){ System.out.println("Carro com os farois ligado"); } public void desligarFarol(){ System.out.println("Carro com os farois desligado"); } public void desligar(){ System.out.println("Carro desligado!!"); } public void ligar(){ System.out.println("Carro Ligado"); } public void mostrarCarro(){ System.out.println("Modelo: "+modelo+" Marca: "+marca+" Cor: "+cor); System.out.println("Combustivel:"+ tipoCombustivel +" Ano:"+ano); if(completo){ System.out.println("Carro Completinho"); }else{ System.out.println("Carro péladinho"); } } }
true
60ab4b2415b4b0ba8ba887aafdb4b1b8df235b77
Java
rockseller2/runescape-server-csharp
/Runescape 530 Client/source/Class67_Sub5_Sub16.java
UTF-8
8,845
1.945313
2
[]
no_license
/* Class67_Sub5_Sub16 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ public class Class67_Sub5_Sub16 extends Class67_Sub5 { public static int anInt4760; public static int anInt4761; public Class66 aClass66_4762; public static int anInt4763; public static Class137 aClass137_4764; public static int anInt4765; public boolean aBoolean4766; public static int anInt4767; public int anInt4768; public static RSString aRSString_4769 = Class134.method1914("Konfig geladen)3", (byte) 16); public static int anInt4770; public float aFloat4771; public int[] anIntArray4772; public boolean aBoolean4773 = false; public boolean aBoolean4774; public static int anInt4775; public static int anInt4776 = -1; public int anInt4777; public static int anInt4778; public static RSString aRSString_4779; public static int anInt4780; public static RSString aRSString_4781; public static int anInt4782; public static boolean aBoolean4783; public boolean method982(Class9 arg0, byte arg1, Interface3 arg2) { try { anInt4780++; if (arg1 >= -34) method986(true, 97); return aClass66_4762.method598(arg2, (byte) 115, arg0); } catch (RuntimeException runtimeexception) { throw Class67_Sub1_Sub21.method718(runtimeexception, ("qi.A(" + (arg0 != null ? "{...}" : "null") + ',' + arg1 + ',' + (arg2 != null ? "{...}" : "null") + ')')); } } public static boolean method983(int arg0, int arg1) { int i = 96 % ((arg0 - 37) / 53); anInt4765++; if ((arg1 < 97 || arg1 > 122) && ((arg1 ^ 0xffffffff) > -66 || (arg1 ^ 0xffffffff) < -91)) return false; return true; } public static void method984(int arg0) { aClass137_4764 = null; aRSString_4781 = null; aRSString_4779 = null; aRSString_4769 = null; if (arg0 != -22760) aRSString_4781 = null; } public static void method985(Class67_Sub5 arg0, int arg1, Class67_Sub5 arg2) { try { if (arg1 != 1) anInt4782 = 37; anInt4770++; if (arg2.aClass67_Sub5_2867 != null) arg2.method821(24120); arg2.aClass67_Sub5_2867 = arg0; arg2.aClass67_Sub5_2861 = arg0.aClass67_Sub5_2861; arg2.aClass67_Sub5_2867.aClass67_Sub5_2861 = arg2; arg2.aClass67_Sub5_2861.aClass67_Sub5_2867 = arg2; } catch (RuntimeException runtimeexception) { throw Class67_Sub1_Sub21.method718(runtimeexception, ("qi.B(" + (arg0 != null ? "{...}" : "null") + ',' + arg1 + ',' + (arg2 != null ? "{...}" : "null") + ')')); } } public void finalize() throws Throwable { anInt4761++; super.finalize(); } public void method986(boolean arg0, int arg1) { anInt4767++; if (arg0 == true && anIntArray4772 != null) { if (anInt4768 != 0 || anInt4777 != 0) { if (Class67_Sub1_Sub18.anIntArray4107 == null || ((Class67_Sub1_Sub18.anIntArray4107.length ^ 0xffffffff) > (anIntArray4772.length ^ 0xffffffff))) Class67_Sub1_Sub18.anIntArray4107 = new int[anIntArray4772.length]; int i = anIntArray4772.length == 4096 ? 64 : 128; int i_0_ = anIntArray4772.length; int i_1_ = -1 + i; int i_2_ = anInt4777 * arg1; int i_3_ = i * (arg1 * anInt4768); int i_4_ = i_0_ - 1; for (int i_5_ = 0; (i_0_ ^ 0xffffffff) < (i_5_ ^ 0xffffffff); i_5_ += i) { int i_6_ = i_3_ + i_5_ & i_4_; for (int i_7_ = 0; (i ^ 0xffffffff) < (i_7_ ^ 0xffffffff); i_7_++) { int i_8_ = i_5_ - -i_7_; int i_9_ = i_6_ - -(i_1_ & i_2_ + i_7_); Class67_Sub1_Sub18.anIntArray4107[i_8_] = anIntArray4772[i_9_]; } } int[] is = anIntArray4772; anIntArray4772 = Class67_Sub1_Sub18.anIntArray4107; Class67_Sub1_Sub18.anIntArray4107 = is; } } } public static void method987(byte arg0) { anInt4760++; int i = -38 / ((52 - arg0) / 56); Class96_Sub1.aClass136_3381.method1922(0); } public int[] method988(boolean arg0, byte arg1, Interface3 arg2, Class9 arg3) { try { anInt4775++; if (!aClass66_4762.method598(arg2, (byte) 115, arg3)) return null; if (arg1 < 27) anInt4768 = -42; int i = arg0 ? 64 : 128; return aClass66_4762.method603(arg2, arg3, 71, aBoolean4766, i, false, 1.0, i); } catch (RuntimeException runtimeexception) { throw Class67_Sub1_Sub21.method718(runtimeexception, ("qi.C(" + arg0 + ',' + arg1 + ',' + (arg2 != null ? "{...}" : "null") + ',' + (arg3 != null ? "{...}" : "null") + ')')); } } public int[] method989(Class9 arg0, Interface3 arg1, int arg2, float arg3, boolean arg4) { try { anInt4763++; if (anIntArray4772 == null || aFloat4771 != arg3) { if (!aClass66_4762.method598(arg1, (byte) 115, arg0)) return null; int i = arg4 ? 64 : 128; anIntArray4772 = aClass66_4762.method603(arg1, arg0, arg2 ^ ~0x781a, aBoolean4766, i, true, (double) arg3, i); aFloat4771 = arg3; if (aBoolean4774) { int[] is = new int[i]; int[] is_10_ = new int[i]; int[] is_11_ = new int[i]; int[] is_12_ = new int[i * i]; int i_13_ = i; int i_15_; int i_14_ = i_15_ = i_13_; int i_16_ = i; int i_17_ = -1 + i_13_; int i_18_ = i_16_ + -1; int i_19_ = i_16_ * i_13_; for (int i_20_ = 2; i_20_ >= 0; i_20_--) { for (int i_21_ = i_17_; i_21_ >= 0; i_21_--) { int i_22_ = anIntArray4772[--i_15_]; is[i_21_] += (Class75.method1379(i_22_, 16751932) >> 1657988944); is_10_[i_21_] += (Class75.method1379(i_22_, 65307) >> 2134278472); is_11_[i_21_] += Class75.method1379(255, i_22_); } if (i_15_ == 0) i_15_ = i_19_; } int i_23_ = i_19_; for (int i_24_ = i_18_; i_24_ >= 0; i_24_--) { int i_25_ = 1; int i_26_ = 1; int i_28_; int i_29_; int i_27_ = i_28_ = i_29_ = 0; for (int i_30_ = 2; (i_30_ ^ 0xffffffff) <= -1; i_30_--) { i_25_--; i_27_ += is[i_25_]; i_28_ += is_11_[i_25_]; i_29_ += is_10_[i_25_]; if (i_25_ == 0) i_25_ = i_13_; } for (int i_31_ = i_17_; i_31_ >= 0; i_31_--) { int i_32_ = i_29_ / 9; int i_33_ = i_28_ / 9; int i_34_ = i_27_ / 9; is_12_[--i_23_] = (Class67_Sub20.method1273 (Class67_Sub20.method1273((i_32_ << -1368686456), (i_34_ << -403265424)), i_33_)); i_26_--; i_25_--; i_27_ += -is[i_26_] + is[i_25_]; i_28_ += is_11_[i_25_] - is_11_[i_26_]; i_29_ += -is_10_[i_26_] + is_10_[i_25_]; if (i_25_ == 0) i_25_ = i_13_; if ((i_26_ ^ 0xffffffff) == -1) i_26_ = i_13_; } for (int i_35_ = i_17_; i_35_ >= 0; i_35_--) { int i_36_ = anIntArray4772[--i_14_]; int i_37_ = anIntArray4772[--i_15_]; is[i_35_] += (-(Class75.method1379(16739253, i_36_) >> -1199696) + Class75.method1379(255, i_37_ >> 380488272)); is_10_[i_35_] += (Class75.method1379(i_37_ >> -838611928, 255) - Class75.method1379(255, i_36_ >> 294959432)); is_11_[i_35_] += (-Class75.method1379(255, i_36_) + Class75.method1379(i_37_, 255)); } if (i_15_ == 0) i_15_ = i_19_; if (i_14_ == 0) i_14_ = i_19_; } anIntArray4772 = is_12_; } } if (arg2 != -30813) return null; return anIntArray4772; } catch (RuntimeException runtimeexception) { throw Class67_Sub1_Sub21.method718(runtimeexception, ("qi.G(" + (arg0 != null ? "{...}" : "null") + ',' + (arg1 != null ? "{...}" : "null") + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')')); } } public Class67_Sub5_Sub16(Stream arg0) { aClass66_4762 = new Class66(arg0); aBoolean4774 = (arg0.readByte((byte) -22) ^ 0xffffffff) == -2; aBoolean4766 = arg0.readByte((byte) -125) == 1; arg0.readByte((byte) -55); arg0.readByte((byte) 95); int i = 0x3 & arg0.readByte((byte) -40); anInt4777 = arg0.readByte2((byte) 1); anInt4768 = arg0.readByte2((byte) 1); arg0.readByte((byte) 93); arg0.readByte((byte) 79); } static { aClass137_4764 = new Class137(64); aRSString_4779 = Class134.method1914("Opened title screen", (byte) 94); aRSString_4781 = aRSString_4779; aBoolean4783 = false; } }
true
b5dff763fb36f62b02f81a0c2c4a6e6fb141b2a8
Java
chamanbharti/spring-project
/java-servlet-angular-application/src/main/java/com/servlet/angular/service/UserServiceImpl.java
UTF-8
814
2.515625
3
[]
no_license
package com.servlet.angular.service; import java.util.List; import com.servlet.angular.dao.UserDAO; import com.servlet.angular.dao.UserDAOImpl; import com.servlet.angular.model.User; public class UserServiceImpl implements UserService{ private UserDAO userDAO=null; public UserServiceImpl(){ userDAO=new UserDAOImpl(); } @Override public int createUser(User user) { System.out.println("Entering createUser("+user+") service layer..."); return userDAO.createUser(user); } @Override public List<User> fetchAllUsers() { System.out.println("Entering fetchAllUsers() service layer..."); return userDAO.fetchAllUsers(); } public int updateUser(User user) { return userDAO.updateUser(user); } @Override public int deleteUser(int id) { return userDAO.deleteUser(id); } }
true
0469e7ad7b495439eb5ea2a83e808eebb6e6a531
Java
skiyooka/blackduck-alert
/alert-common/src/test/java/com/synopsys/integration/alert/common/rest/model/JobFieldErrorsTest.java
UTF-8
1,322
2.1875
2
[ "Apache-2.0" ]
permissive
package com.synopsys.integration.alert.common.rest.model; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class JobFieldErrorsTest { @Test public void getFieldErrorsTest() { String fieldErrorKey = "key"; String fieldErrorValue = "value"; Map<String, String> fieldError = new HashMap<>(); fieldError.put(fieldErrorKey, fieldErrorValue); Map<String, String> testResult = new JobFieldErrors(fieldError).getFieldErrors(); assertEquals(fieldError, testResult); } @Test public void getFieldErrorsWithIdTest() { String fieldErrorKey = "key"; String fieldErrorValue = "value"; String configId = "testID"; String newConfigId = "newTestID"; Map<String, String> fieldError = new HashMap<>(); fieldError.put(fieldErrorKey, fieldErrorValue); JobFieldErrors jobFieldError = new JobFieldErrors(configId, fieldError); Map<String, String> testResult = jobFieldError.getFieldErrors(); assertEquals(testResult, fieldError); assertEquals(configId, jobFieldError.getId()); jobFieldError.setId(newConfigId); assertEquals(newConfigId, jobFieldError.getId()); } }
true
c90f8803ce5612d37e6d7b150ada0bfd12332b5d
Java
shiguangbl/JavaSE
/src/testShuZhu/XuanZePaiXu.java
TIS-620
1,013
3.109375
3
[]
no_license
package testShuZhu; class Date{ int year,month,day; Date(int y,int m,int d){ year = y; month = m; day = d; } Date(){ } public int Compare(Date d){ return year>d.year?1:year<d.year?-1 :month>d.month?1:d.month<month?-1 :day>d.day?1:-1; } public String toString(){ return "Year:Month:Day -- " + year + "-" + month + "-" + day; } } public class XuanZePaiXu { public static void main(String[] args) { Date[]date = new Date[5]; date[0] = new Date(2012,12,20); date[1] = new Date(2013,1,20); date[2] = new Date(2016,11,20); date[3] = new Date(2022,12,22); date[4] = new Date(2010,12,10); Date temp = new Date(); int k; for(int i=0;i<date.length;i++){//ѡ k = i; for(int j=i+1;j<date.length;j++){ if(date[k].Compare(date[j])>0){ k = j; } } temp = date[i]; date[i] = date[k]; date[k] = temp; } for(int i=0;i<date.length;i++) System.out.println(date[i]); } }
true
83c712112a7679fe3e931fbd7f5eb55e4f4c7b6e
Java
rbranham/WisSportsWebScraper
/src/main/java/com/HBSS/models/Team.java
UTF-8
546
2.53125
3
[]
no_license
package com.HBSS.models; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Data class for tracking a team. * * <ul> * <li> id - unique id provided by database. Leave null when adding new team to database. * <li> teamName - the name of the team as listed on Wissports * <li> town - string for name of the town to help differentiate teams with the same name. * <ul> * @author Roger Branham */ @Getter @Setter @ToString public class Team { private Integer id; private String teamName; private String town; }
true
058c46b61f9919d31c035cadbf074f48f67950d5
Java
datcoind/VideoMaker-1
/app/src/main/java/com/cliffex/videomaker/videoeditor/introvd/template/module/p326ad/p334h/p335a/C7655a.java
UTF-8
1,184
2.03125
2
[]
no_license
package com.introvd.template.module.p326ad.p334h.p335a; /* renamed from: com.introvd.template.module.ad.h.a.a */ public class C7655a { private final String dNw; private final long dNx; private final int dNy; private final int dNz; public C7655a(String str, int i, int i2) { this(str, System.currentTimeMillis(), i, i2); } public C7655a(String str, long j, int i, int i2) { this.dNw = str; this.dNx = j; this.dNy = i; this.dNz = i2; } public String aAB() { return this.dNw; } public long aAC() { return this.dNx; } public int aAD() { return this.dNy; } public int aAE() { return this.dNz; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("EncourageResourceRecord{resId='"); sb.append(this.dNw); sb.append('\''); sb.append(", unlockTime="); sb.append(this.dNx); sb.append(", validDuration="); sb.append(this.dNy); sb.append(", encourageType="); sb.append(this.dNz); sb.append('}'); return sb.toString(); } }
true
41dea3383e10b327862994d5394c5a57b5bc3d34
Java
kr056/SoftUni
/Programming Basics March 2017/PBExam19March2017Evening/Bills.java
UTF-8
958
3.84375
4
[ "MIT" ]
permissive
package PBExam19March2017Evening; import java.util.Scanner; public class Bills { public static void main(String[] args) { Scanner console = new Scanner(System.in); int months = Integer.parseInt(console.nextLine()); double water = months * 20; double net = months * 15; double others = 0; double el = 0; for (int i = 0; i < months; i++) { double electricity = Double.parseDouble(console.nextLine()); el += electricity; others += (electricity + 20 + 15) * 1.2; } double average = (water + net + el + others) / months; System.out.printf("Electricity: %.2f lv%n", el); System.out.printf("Water: %.2f lv%n", water); System.out.printf("Internet: %.2f lv%n", net); System.out.printf("Other: %.2f lv%n", others); System.out.printf("Average: %.2f lv", average); } }
true
1c1dd3fc88b3f5b6ce6e0f5ae93b2194ff694a8f
Java
kinfkong/mytcuml
/mytcuml-src/src/java/tests/com/topcoder/umltool/deploy/actions/undoable/ChangeAsynchronousActionTest.java
UTF-8
4,065
2.328125
2
[]
no_license
/* * Copyright (C) 2007 TopCoder Inc., All Rights Reserved. */ package com.topcoder.umltool.deploy.actions.undoable; import junit.framework.TestCase; import com.topcoder.uml.actions.general.UndoableAbstractAction; import com.topcoder.uml.model.actions.messagingactions.CallOperationAction; import com.topcoder.uml.model.actions.messagingactions.CallOperationActionImpl; import com.topcoder.uml.model.commonbehavior.instances.Stimulus; import com.topcoder.uml.model.commonbehavior.instances.StimulusImpl; import com.topcoder.uml.model.commonbehavior.procedure.Procedure; import com.topcoder.uml.model.commonbehavior.procedure.ProcedureImpl; /** * <p> * Test the functionality of <code>ChangeAsynchronousActionTest</code> class. * </p> * @author ly, FireIce, ylouis * @version 1.0 */ public class ChangeAsynchronousActionTest extends TestCase { /** * Represents the ChangeAsynchronousAction instance used for tests. */ private ChangeAsynchronousAction testChangeAsynchronousAction; /** * Represents the stimulus model element to change the asynchronous. */ private Stimulus element; /** * Represents the old asynchronous of the model element before the action performed. */ private final boolean oldAsynchronous = true; /** * Represents the new asynchronous of the model element the action will performed. */ private final boolean newAsynchronous = false; /** * Set up the test environment. */ protected void setUp() { element = new StimulusImpl(); Procedure procedure = new ProcedureImpl(); CallOperationAction callOperationAction = new CallOperationActionImpl(); callOperationAction.setAsynchronous(oldAsynchronous); procedure.setAction(callOperationAction); element.setDispatchAction(procedure); testChangeAsynchronousAction = new ChangeAsynchronousAction(element, newAsynchronous); } /** * Accuracy test for the method <code>undoAction()</code>. The asynchronous value of the ModelElememt should be * set to oldAsynchronous; */ public void testUndoAction() { testChangeAsynchronousAction.undoAction(); assertEquals("ChangeAsynchronousAction undoAction incorrectly.", oldAsynchronous, ((CallOperationAction) element.getDispatchAction().getAction()).isAsynchronous()); } /** * Accuracy test for the method <code>redoAction()</code>. The asynchronous value of the ModelElememt should be * set to newAsynchronous; */ public void testRedoAction() { testChangeAsynchronousAction.redoAction(); assertEquals("ChangeAsynchronousAction redoAction incorrectly.", newAsynchronous, ((CallOperationAction) element.getDispatchAction().getAction()).isAsynchronous()); } /** * Accuracy test for the method <code>executeAction()</code>. The asynchronous value of the ModelElememt should * be set to newAsynchronous; */ public void testExecuteAction() { testChangeAsynchronousAction.executeAction(); assertEquals("ChangeAsynchronousAction executeAction incorrectly.", newAsynchronous, ((CallOperationAction) element.getDispatchAction().getAction()).isAsynchronous()); } /** * Test ChangeAsynchronousAction constructor. */ public void testChangeAsynchronousActionConstructor() { UndoableAbstractAction action = new ChangeAsynchronousAction(element, oldAsynchronous); assertNotNull("Create ChangeAsynchronousAction incorrectly.", action); } /** * Test ChangeAsynchronousAction constructor with null element. Should throw IllegalArgumentException. */ public void testChangeAsynchronousActionConstructorNullElement() { try { new ChangeAsynchronousAction(null, oldAsynchronous); fail("IllegalArgumentException should be thrown when the passed element is null."); } catch (IllegalArgumentException e) { // success } } }
true
881f15ac6360f14f2f7c0b39871a15f59f09a9d9
Java
tyzik89/NetCracker
/Java_Lab/src/test/java/ru/sukmanov/lab2/common/AbstractRepositoryTest.java
UTF-8
3,359
2.90625
3
[]
no_license
package ru.sukmanov.lab2.common; import org.joda.time.LocalDate; import org.junit.After; import org.junit.Before; import org.junit.Test; import ru.sukmanov.lab2.object.*; import ru.sukmanov.lab2.repositories.CarRepository; import ru.sukmanov.lab2.repositories.MyRepository; import ru.sukmanov.lab2.repositories.PersonRepository; import static org.junit.Assert.*; public class AbstractRepositoryTest { //private MyRepository<Person> repPerson = new MyRepository<Person>(); private PersonRepository repPerson = new PersonRepository(); private CarRepository repCar = new CarRepository(); private Person p1, p2, p3; private Car c1, c2 ,c3; @Before public void initRepository(){ p1 = new Person("Ivanov","Ivan", LocalDate.parse("1980-01-01")); p2 = new Person("Sidorov","Petr", LocalDate.parse("1990-12-05")); p3 = new Person("Petrov","Sidr", LocalDate.parse("2000-02-01")); c1 = new Car("A", "White", "o315go", LocalDate.parse("1980")); c2 = new Car("B", "Black", "0315oo", LocalDate.parse("1990")); c3 = new Car("C", "Red", "y749yy", LocalDate.parse("2000")); } @After public void releaseRepository(){ repPerson = null; repCar = null; p1 = null; p2 = null; p3 = null; c1 = null; c2 = null; c3 = null; } /** * <p>Unit-test add item</p> */ @Test public void addElem() { repPerson.addElem(p1); assertEquals(1, repPerson.size()); repPerson.addElem(p2); assertEquals(2, repPerson.size()); repPerson.addElem(p3); assertEquals(3, repPerson.size()); assertEquals(p1, repPerson.getElem(0)); assertEquals(p2, repPerson.getElem(1)); assertEquals(p3, repPerson.getElem(2)); } /** * <p>Unit-test delete item</p> */ @Test public void delElem() { repPerson.addElem(p1); repPerson.addElem(p2); repPerson.addElem(p3); repPerson.delElem(1); assertEquals(2, repPerson.size()); assertEquals(p1, repPerson.getElem(0)); assertEquals(p3, repPerson.getElem(1)); repPerson.delElem(0); repPerson.delElem(0); assertEquals(0, repPerson.size()); } /** * <p>Unit-test search item</p> */ @Test public void findElem() { repPerson.addElem(p1); repPerson.addElem(p2); repPerson.addElem(p3); //Person pf = repPerson.findElem(person -> {return person.getLastName().equals("Petrov");}); //assertEquals(p3, pf); } /** * <p>Unit-test getting item</p> */ @Test public void getElem() { repPerson.addElem(p1); repPerson.addElem(p2); assertEquals(p1, repPerson.getElem(0)); } /** * <p>Unit-test buble sort by type car</p> */ @Test public void bubleSorting() { repCar.addElem(c2); repCar.addElem(c3); repCar.addElem(c1); repCar.bubleSortByType(); assertEquals(c1, repCar.getElem(0)); } /** * <p>Unit-test quick sort by age car</p> */ @Test public void qsort() { repCar.addElem(c2); repCar.addElem(c3); repCar.addElem(c1); repCar.quickSortByAge(); assertEquals(c1, repCar.getElem(0)); } }
true
9d24cf2ad75e619920e4e6fcd0cd3b45f9a1f517
Java
sandeepjalu/SampleGS
/sample-java-1.5/TeamchatSDKSamples/src/com/teamchat/client/sdk/demo/SetXSLTDemo.java
UTF-8
4,229
2.828125
3
[]
no_license
package com.teamchat.client.sdk.demo; import com.teamchat.client.annotations.OnKeyword; import com.teamchat.client.sdk.Form; import com.teamchat.client.sdk.TeamchatAPI; import com.teamchat.client.sdk.chatlets.PrimaryChatlet; /** * This bot demonstrates how to set xslt to the chatlet. * @author somesh * */ public class SetXSLTDemo { public static final String bot = "bot@teamchat.com"; public static final String password = "botpwd"; public static void main (String... args){ TeamchatAPI api = TeamchatAPI.fromFile("config.json") .setEmail(bot) //change to your teamchat registered email id .setPassword(password) //change to your teamchat password .startReceivingEvents(new SetXSLTDemo());//Wait for other user to send message } /** * The method posts a primary chatlet with a specific xslt. * @param api */ @OnKeyword("create1") public void postChatletOfParticularXSLT(TeamchatAPI api){ PrimaryChatlet p = new PrimaryChatlet(); //Setting the XSLT for the chatlet. p.setXSLTForChatlet("primary-2.7.2-somesh1"); //Set the question for the chatlet p.setQuestion("Please enter your profile"); //alternatively HTML can also be set for question //p.setQuestionHtml("<b><font style=\"color:red\">Please enter your profile</font></b>"); //Create reply form for this primary chatlet and add fields to it Form f = api.objects().form(); //a text field to enter name f.addField(api.objects().input().name("name").label("Name:")); //a dropdown to select city f.addField(api.objects().select().name("city").label("City") .addOption("Delhi").addOption("Mumbai") .addOption("Kolkata").addOption("Chennai")); //finally add this Form to primary chatlet as replyscreen p.setReplyScreen(f); //Decide if replies will be visible to everyone in the room //Also, label can be changed p.showDetails(true); p.setDetailsLabel("Entries"); //Decide if commenting is enabled on this chatlet or not p.allowComments(true); //Can change reply button label p.setReplyLabel("Enter"); //Can assign an alias, if you want to handle replies on this chatlet //The method with @OnAlias annotation will be called, when anyone replies //to this chatlet. For example, look at method handleReply in this class //it has annotation @OnAlias("profile"), which we are setting below. p.alias("profile"); //finally post the chatlet in the current room api.performPostInCurrentRoom(p); } /** * The method posts a primary chatlet with a specific xslt. * @param api */ @OnKeyword("create2") public void postChatletOfParticularXSLT2(TeamchatAPI api){ PrimaryChatlet p = new PrimaryChatlet(); //Setting the XSLT for the chatlet. p.setXSLTForChatlet("primary-2.7.2-somesh2"); //Set the question for the chatlet p.setQuestion("Please enter your profile"); //alternatively HTML can also be set for question //p.setQuestionHtml("<b><font style=\"color:red\">Please enter your profile</font></b>"); //Create reply form for this primary chatlet and add fields to it Form f = api.objects().form(); //a text field to enter name f.addField(api.objects().input().name("name").label("Name:")); //a dropdown to select city f.addField(api.objects().select().name("city").label("City") .addOption("Delhi").addOption("Mumbai") .addOption("Kolkata").addOption("Chennai")); //finally add this Form to primary chatlet as replyscreen p.setReplyScreen(f); //Decide if replies will be visible to everyone in the room //Also, label can be changed p.showDetails(true); p.setDetailsLabel("Entries"); //Decide if commenting is enabled on this chatlet or not p.allowComments(true); //Can change reply button label p.setReplyLabel("Enter"); //Can assign an alias, if you want to handle replies on this chatlet //The method with @OnAlias annotation will be called, when anyone replies //to this chatlet. For example, look at method handleReply in this class //it has annotation @OnAlias("profile"), which we are setting below. p.alias("profile"); //finally post the chatlet in the current room api.performPostInCurrentRoom(p); } }
true
3322d0319324528c241723c36b2edefaedce4074
Java
zhukaifeng/Farmers
/Farmers/app/src/main/java/com/osiris/farmers/view/ChooseMarketActivity.java
UTF-8
4,941
2.015625
2
[]
no_license
package com.osiris.farmers.view; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import com.google.gson.JsonParser; import com.osiris.farmers.R; import com.osiris.farmers.base.BaseActivity; import com.osiris.farmers.event.BoothgEvent; import com.osiris.farmers.event.MarketEvent; import com.osiris.farmers.model.JiedaoMarket; import com.osiris.farmers.model.Market; import com.osiris.farmers.network.ApiParams; import com.osiris.farmers.network.ApiRequestTag; import com.osiris.farmers.network.GlobalParams; import com.osiris.farmers.network.NetRequest; import com.osiris.farmers.network.NetRequestResultListener; import com.osiris.farmers.utils.JsonUtils; import com.osiris.farmers.view.adapter.MarketNoAdapter; import com.osiris.farmers.view.adapter.MyItemClickListener; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.OnClick; import me.jessyan.autosize.utils.LogUtils; public class ChooseMarketActivity extends BaseActivity { @BindView(R.id.rv_data) RecyclerView rvData; private List<Market.MarketBean> marketList = new ArrayList<>(); private MarketNoAdapter typeAdapter = new MarketNoAdapter(marketList); private boolean isTask; @OnClick({R.id.rl_back}) void onClick(View v) { switch (v.getId()) { case R.id.rl_back: finish(); break; } } @Override public int getLayoutResId() { return R.layout.activity_choose_market; } @Override public void init() { isTask = getIntent().getBooleanExtra("istask",false); if (isTask){ String id = getIntent().getStringExtra("id"); if (!TextUtils.isEmpty(id)){ getMarketData1(id); }else { getMarketData(); } }else { getMarketData(); } rvData.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); rvData.setAdapter(typeAdapter); typeAdapter.setOnItemClick(new MyItemClickListener() { @Override public void onItemClick(View view, int position) { postEvent(new MarketEvent(marketList.get(position).getMarketnm(), marketList.get(position).getId())); finish(); } }); } private void getMarketData1(String id) { String url = ApiParams.API_HOST + "/app/getMarketByquid.action"; Map<String, String> paramMap = new HashMap<>(); paramMap.put("id", id); LogUtils.d("zkf id;llll:" + id); NetRequest.request(url, ApiRequestTag.DATA, paramMap, new NetRequestResultListener() { @Override public void requestSuccess(int tag, String successResult) { JiedaoMarket[] jiedaoMarkets = JsonUtils.fromJson(new JsonParser().parse(successResult).getAsJsonArray(), JiedaoMarket[].class); List<JiedaoMarket> jiedaoMarkets1 = Arrays.asList(jiedaoMarkets); for (JiedaoMarket jiedaoMarket : jiedaoMarkets1) { LogUtils.d("zkf market name:" + jiedaoMarket.getMarketnm()); Market.MarketBean marketBean = new Market.MarketBean(); marketBean.setId(jiedaoMarket.getId()); marketBean.setMarketnm(jiedaoMarket.getMarketnm()); marketList.add(marketBean); } typeAdapter.notifyDataSetChanged(); } @Override public void requestFailure(int tag, int code, String msg) { } }); } private void getMarketData() { String url = ApiParams.API_HOST + "/app/xzmarket.action"; Map<String, String> paramMap = new HashMap<>(); paramMap.put("id", String.valueOf(GlobalParams.id)); NetRequest.request(url, ApiRequestTag.DATA, paramMap, new NetRequestResultListener() { @Override public void requestSuccess(int tag, String successResult) { LogUtils.d("zkf market data:" + successResult); String temp = successResult.substring(1, successResult.length() - 1); if (!TextUtils.isEmpty(successResult)) { Market market = JsonUtils.fromJson(temp, Market.class); if (marketList.size() > 0) { marketList.clear(); } marketList.addAll(market.getMarket()); typeAdapter.notifyDataSetChanged(); } } @Override public void requestFailure(int tag, int code, String msg) { } }); } }
true
f8261190ecc637f4b4583c9eb4d6d7c7a4310815
Java
daheicode/BaoFen
/app/src/main/java/com/example/administrator/baofen/bean/MobileNoVO.java
UTF-8
470
1.96875
2
[]
no_license
package com.example.administrator.baofen.bean; public class MobileNoVO { private String resourceName; private String mobileNo; public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } }
true
e2e1b6fd6b59e2236a0b7297f66c9eb46a901819
Java
cleitonpqz/jungle-s-map
/app/controllers/MetodosQB.java
UTF-8
2,287
2.359375
2
[ "MIT" ]
permissive
package controllers; import java.util.*; import play.mvc.*; import play.data.*; import static play.data.Form.*; import play.*; import views.html.metodoQB.*; import play.libs.Json; import javax.persistence.PersistenceException; import models.*; public class MetodosQB extends Controller { public static Result GO_HOME = redirect(routes.MetodosQB.manter()); public static Result index() { return GO_HOME; } public static Result manter() { return ok( manter.render( MetodoQuantificacaoBiomassa.list("descricao","asc", "")) ); } public static Result novoEditar(Long id, int quemChama) { Form<MetodoQuantificacaoBiomassa> metodoQBForm; if(id==0){ metodoQBForm = form(MetodoQuantificacaoBiomassa.class); }else{ metodoQBForm = form(MetodoQuantificacaoBiomassa.class).fill(MetodoQuantificacaoBiomassa.find.byId(id)); } return ok( novoEditar.render(id, metodoQBForm, quemChama) ); } public static Result salvar(Long id, int quemChama) { Form<MetodoQuantificacaoBiomassa> metodoQBForm = form(MetodoQuantificacaoBiomassa.class).bindFromRequest(); if(metodoQBForm.hasErrors()) { return badRequest(novoEditar.render(id, metodoQBForm, quemChama)); } if(quemChama==2 && id!=0){ flash("success", "MetodoQB " + metodoQBForm.get().descricao + " foi editado com sucesso"); metodoQBForm.get().update(id); }else if(quemChama==0){ flash("success", "MetodoQB " + metodoQBForm.get().descricao + " foi incluido com sucesso"); metodoQBForm.get().save(); }else{ metodoQBForm.get().save(); } return ok(Json.toJson(metodoQBForm.get())); } public static Result deletar(Long id) { try{ MetodoQuantificacaoBiomassa.find.ref(id).delete(); flash("success", "Metodo de Quantificação de Biomassa excluido"); return GO_HOME; }catch(PersistenceException exception){ flash("error", "Exclusão não permitida. Existe Trabalho Científico vinculadas a este método"); return GO_HOME; } } }
true
16ac060e9fc37512e81b02655938d689fa427337
Java
fegu01/java-lab
/Lab 2/src/messer/ADSBAircraftIdentMessage.java
UTF-8
5,410
3.015625
3
[]
no_license
package messer; import senser.ADSBSentence; import java.util.*; /** * Created by Matthias on 12.04.2016. */ public class ADSBAircraftIdentMessage extends ADSBMessage implements iADSBAircraftIdentMessage { // Variablen private int emitterCategory; // field for emitter category private String aircraftID; // field for Aircraft ID private String aircraftIDParts[] = new String[8]; // contains 6 bit per row, representing a char of the Aircraft ID private String airCraftIdBinary = ""; // contains the binary representation of the Aircraft ID // Konstruktor public ADSBAircraftIdentMessage(ADSBSentence sentence, int type){ // Superconstructor // For df and ca: Parse the Hex Value to binary, split in 5 and 3 Bit, and parse as Int super(sentence.getIcao() , type , sentence.getDf() , sentence.getCa() , sentence.getPayload() , sentence.getTimestamp()); // Fill flieds of the AircraftID object // Fill emitter Category - just an Integer? emitterCategory = Integer.parseInt(sentence.getBinaryPayload().substring(5,7),2); // getting the aircaftID binary airCraftIdBinary = sentence.getBinaryPayload().substring(8,56); // sepparate the 8 Byte Aircraft ID splitAircraftID(airCraftIdBinary, aircraftIDParts); // parse the parts to byte, the Aircraft ID is returned as string aircraftID = parseAircraftID(aircraftIDParts); } private void splitAircraftID(String aircraftID, String aircraftIDParts[]){ for(int i = 0; i < 8; i++){ aircraftIDParts[i] = aircraftID.substring(0 + (i * 6), 6 + (i * 6)); } } private String parseAircraftID(String airCraftIdParts[]){ // Variablen StringBuilder result = new StringBuilder(""); // Result string will contain Aircraft ID Map<String,Character>charTable = new HashMap<String,Character>(); // Contains the ASCII Table // Fill the Table fillCharTable(charTable); // Parse binary to character for(int i = 0; i < 8; i++){ result.append(charTable.get(airCraftIdParts[i])); } return result.toString(); } private void fillCharTable(Map<String, Character>charTable){ charTable.put("000000" , '@'); charTable.put("000001" , 'A'); charTable.put("000010" , 'B'); charTable.put("000011" , 'C'); charTable.put("000100" , 'D'); charTable.put("000101" , 'E'); charTable.put("000110" , 'F'); charTable.put("000111" , 'G'); charTable.put("001000" , 'H'); charTable.put("001001" , 'I'); charTable.put("001010" , 'J'); charTable.put("001011" , 'K'); charTable.put("001100" , 'L'); charTable.put("001101" , 'M'); charTable.put("001110" , 'N'); charTable.put("001111" , 'O'); charTable.put("010000" , 'P'); charTable.put("010001" , 'Q'); charTable.put("010010" , 'R'); charTable.put("010011" , 'S'); charTable.put("010100" , 'T'); charTable.put("010101" , 'U'); charTable.put("010110" , 'V'); charTable.put("010111" , 'W'); charTable.put("011000" , 'X'); charTable.put("011001" , 'Y'); charTable.put("011010" , 'Z'); charTable.put("011011" , '['); charTable.put("011100" , '='); charTable.put("011101" , ']'); charTable.put("011110" , 'ˆ'); charTable.put("011111" , '_'); charTable.put("100000" , ' '); charTable.put("100001" , '!'); charTable.put("100010" , '̈'); charTable.put("100011" , '#'); charTable.put("100100" , '$'); charTable.put("100101" , '%'); charTable.put("100110" , '&'); charTable.put("100111" , '’'); charTable.put("101000" , '('); charTable.put("101001" , ')'); charTable.put("101010" , '*'); charTable.put("101011" , '+'); charTable.put("101100" , ','); charTable.put("101101" , '-'); charTable.put("101110" , '.'); charTable.put("101111" , '/'); charTable.put("110000" , '0'); charTable.put("110001" , '1'); charTable.put("110010" , '2'); charTable.put("110011" , '3'); charTable.put("110100" , '4'); charTable.put("110101" , '5'); charTable.put("110110" , '6'); charTable.put("110111" , '7'); charTable.put("111000" , '8'); charTable.put("111001" , '9'); charTable.put("111010" , ':'); charTable.put("111011" , ';'); charTable.put("111100" , '<'); charTable.put("111101" , '='); charTable.put("111110" , '>'); charTable.put("111111" , '?'); } @Override public String toString(){ return this.getIcao() + " Aircraft Identification and Category Message\n" +"Ident: " + this.getAircraftID() +"\n" +"Categ: " + this.getEmitterCatergory() + "\n\n"; } // Getter @Override public int getEmitterCatergory() { return emitterCategory; } @Override public String getAircraftID() { return aircraftID; } }
true
b9a933d2cc4048fbfeecf55a24c5082b056e556a
Java
coder-zt/WorkInfo
/app/src/main/java/com/working/base/ZTBaseListActivity.java
UTF-8
8,268
1.96875
2
[]
no_license
package com.working.base; import android.app.DatePickerDialog; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import com.working.R; import com.working.adapter.IndexPagerAdapter; import com.working.databinding.ActivityRepertoryInLayoutBinding; import com.working.other.MessageEvent; import com.working.utils.AppConfig; import com.working.utils.TimeUtil; import com.working.utils.ToastUtil; import com.working.utils.UserDataMan; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * 清单页面的基类 */ public abstract class ZTBaseListActivity extends BaseActivity { private static final String TAG = "BaseListActivity"; private ActivityRepertoryInLayoutBinding mBinding; protected ViewPager mVpFragmentContainer; protected ListFragment mCommittedFragment; protected ListFragment mUnCommitFragment; protected int mActivityCode; private boolean mIsSearch; private String mStartTime; private String mEndTime; private EditText mEtSearchInput; private long end,start; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getIntentData(); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_repertory_in_layout); mBinding.setActivity(this); mBinding.setTitle(getActivityTitle()); mBinding.setIsCreate(getIsCreate()); initView(); initListener(); } protected abstract Boolean getIsCreate(); private void getIntentData() { mActivityCode = getIntent().getIntExtra("data", -1); if (mActivityCode == -1) { ToastUtil.showMessage("参数错误!"); finish(); } } /** * 该Activity的顶部标题 * * @return */ protected abstract String getActivityTitle(); private void initView() { mVpFragmentContainer = (ViewPager) findViewById(R.id.viewpager); List<Fragment> fragments = new ArrayList<>(); UserDataMan instance = UserDataMan.getInstance(); if (instance.checkSecondApprovalGrant() || instance.checkFirstApprovalGrant()) { mBinding.setIsApproval(true); mVpFragmentContainer.setCurrentItem(0); } mUnCommitFragment = getListFragment(false); if (mUnCommitFragment != null) { fragments.add(mUnCommitFragment); }else{ mBinding.bottomNavigationView.setVisibility(View.GONE); } mCommittedFragment = getListFragment(true); fragments.add(mCommittedFragment); //控制搜索栏的显示 if(mActivityCode == AppConfig.ACTIVITY_MATERIAL) { mBinding.llSearch.setVisibility(View.GONE); } mVpFragmentContainer.setAdapter(new IndexPagerAdapter(fragments, getSupportFragmentManager())); mEtSearchInput = findViewById(R.id.et_search); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent messageEvent) { if (messageEvent.getMessage().equals(MessageEvent.upload_file_success)) { mVpFragmentContainer.setCurrentItem(1); } } /** * 子类提供Fragment * * @param iusCommit * @return */ protected abstract ListFragment getListFragment(boolean iusCommit); private void initListener() { mVpFragmentContainer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mBinding.setIsCommit(position == 1); } @Override public void onPageScrollStateChanged(int state) { } }); mEtSearchInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d(TAG, "onTextChanged: " +s.toString()); searchWithFragments(s.toString()); } @Override public void afterTextChanged(Editable s) { Log.d(TAG, "afterTextChanged: "+s.toString()); } }); } protected void searchWithFragments(String info) { if (mCommittedFragment != null) { mCommittedFragment.search(info); } if (mUnCommitFragment != null) { mUnCommitFragment.search(info); } } protected void filterWithFragments(String startTime, String endTime) { if (mCommittedFragment != null) { mCommittedFragment.filter(startTime, endTime); } if (mUnCommitFragment != null) { mUnCommitFragment.filter(startTime, endTime); } } @Override protected void onResume() { super.onResume(); } @Override public void onBack() { if(!mIsSearch){ super.onBack(); }else{ mBinding.setIsSearch(false); mEtSearchInput.setText(""); mIsSearch = false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && mIsSearch){ onBack(); return true; } return super.onKeyDown(keyCode, event); } /** * 搜索功能 */ public void onSearch() { mIsSearch = true; mBinding.setIsSearch(true); mEtSearchInput.setText(""); } public void onSelectTime(boolean isEnd) { //获取日历的一个对象 Calendar calendar = Calendar.getInstance(); //获取年月日时分的信息 int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { if (isEnd) { end = TimeUtil.getTimeInMills(year, month,dayOfMonth); mEndTime = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth); mBinding.endTime.setText(mEndTime); if (mStartTime != null) { if (start > end){ ToastUtil.showMessage("开始时间不得大于结束时间"); return; } filterWithFragments(mStartTime, mEndTime); } } else { start = TimeUtil.getTimeInMills(year, month,dayOfMonth); mStartTime = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth); mBinding.startTime.setText(mStartTime); if (mEndTime != null) { if (start > end){ ToastUtil.showMessage("开始时间不得大于结束时间"); return; } filterWithFragments(mStartTime, mEndTime); } } } }, year, month, day).show(); } /** * 设置当前ViewPager中的Item * * @param position */ public void onSelectItem(int position) { mVpFragmentContainer.setCurrentItem(position); } //相关控件的可见性设置 public abstract void create(); }
true
f6f81b91e09b39158dfa4efa2e6afc80e73b471a
Java
JorgeCosta87/Engenharia_Informatica
/PA/FX4_EX3/src/telefonica/Cartao.java
UTF-8
2,099
2.9375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package telefonica; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * * @author Administrator */ public abstract class Cartao implements Comparable<Cartao>, Serializable{ protected List<Chamada> chamadas = new ArrayList<Chamada>(); private int numero; private double saldo; static private List<String> tipos = new ArrayList<String>(); static{ tipos.add("PoucoTempo"); tipos.add("Tagarela"); } static public List<String> getTipos(){ return tipos; } static public void setTipos(List<String> t){ tipos = t; } static public void addTipo(String tipo){ tipos.add(tipo); } public Cartao(int n, double s) { numero = n; saldo = s; } public int compareTo(Cartao o) { return numero - o.getNumero(); } public void setSaldo(double saldo) { this.saldo = saldo; } public int getNumero() { return numero; } public double getSaldo() { return saldo; } public abstract boolean registaChamada(int numero, int s); public void efectuaCarregamento(double quantia) { if( quantia > 0 ) saldo += quantia; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof Cartao) { return false; } final Cartao other = (Cartao) obj; if (this.numero != other.numero) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 19 * hash + this.numero; return hash; } @Override public String toString() { return " numero: " + numero + " saldo: " + saldo + "\n"; } public String facturaDetalhada() { return " numero: " + numero + " saldo: " + saldo + "\n chamadas:\n" + chamadas + "\n"; } }
true
0b9df8dbc994c545b4da00ccee306f95898f8895
Java
xieqixiang/mobileproject
/psr/src/com/athudong/psr/adapter/FragmentAdap.java
GB18030
2,258
2.09375
2
[]
no_license
package com.athudong.psr.adapter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import com.actionbarsherlock.app.SherlockFragment; import com.athudong.psr.R; import com.athudong.psr.activity.ParkingListAct; import com.athudong.psr.activity.ParkingSerachAct; import com.athudong.psr.activity.ParkingSpaceListAct; import com.athudong.psr.base.C; /** * ÿFragmentʾͿÿviewĵ¼ */ public class FragmentAdap extends SherlockFragment implements OnClickListener{ public static final String ARG_OBJECT = "object"; private LinearLayout llParkingSearch; private LinearLayout llHistoryLook; private LinearLayout llParkingMap; public android.view.View onCreateView(android.view.LayoutInflater inflater, android.view.ViewGroup container, android.os.Bundle savedInstanceState) { View rootView = null; rootView = inflater.inflate(R.layout.al_main_page1, container,false); llParkingSearch = (LinearLayout) rootView.findViewById(R.id.ai_main_parking_space_search); llHistoryLook = (LinearLayout) rootView.findViewById(R.id.ai_ps_ll_history_look); llParkingMap = (LinearLayout) rootView.findViewById(R.id.ai_ps_ll_parking_map); llHistoryLook.setOnClickListener(this); llParkingMap.setOnClickListener(this); llParkingSearch.setOnClickListener(this); return rootView; } @Override public void onClick(View v) { switch(v.getId()){ case R.id.ai_main_parking_space_search: overLayout(ParkingSerachAct.class,C.flag.locationSearch); break; case R.id.ai_ps_ll_history_look: overLayout(ParkingListAct.class,C.flag.historyInfo); break; case R.id.ai_ps_ll_parking_map: overLayout(ParkingSpaceListAct.class,C.flag.nowInfo); break; } }; private void overLayout(Class<?> class1,int flag){ Activity activity = getActivity(); Intent intent = new Intent(activity,class1); Bundle bundle = new Bundle(); bundle.putInt("flag", flag); intent.putExtra("bundle",bundle); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); activity.startActivity(intent); } }
true
ea1f32104ccfa3d7de74aed77b231ea38aa47c48
Java
vinhtknguyen/rdf-contextualizer
/rdf-contextualizer/src/main/java/org/knoesis/rdf/sp/converter/ContextConverterFactory.java
UTF-8
1,547
2.34375
2
[]
no_license
package org.knoesis.rdf.sp.converter; import org.knoesis.rdf.sp.utils.Constants; public class ContextConverterFactory { public static ContextualRepresentationConverter createConverter(String rep, String _uuidInitStr, long _uuidInitNum){ ContextualRepresentationConverter con; switch (rep.toUpperCase()){ case Constants.NANO_REP: con = new NanoPub2SP(_uuidInitNum, _uuidInitStr); break; case Constants.NG_REP: con = new NamedGraph2SP(_uuidInitNum, _uuidInitStr); break; case Constants.REI_REP: con = new Reification2SP(_uuidInitNum, _uuidInitStr); break; case Constants.TRIPLE_REP: con = new Triple2SP(_uuidInitNum, _uuidInitStr); break; case Constants.NONE_REP: con = new ContextualRepresentationConverter(_uuidInitNum, _uuidInitStr); break; default: con = new ContextualRepresentationConverter(_uuidInitNum, _uuidInitStr); break; } return con; } public static ContextualRepresentationConverter createConverter(String rep){ ContextualRepresentationConverter con; switch (rep.toUpperCase()){ case Constants.NANO_REP: con = new NanoPub2SP(); break; case Constants.NG_REP: con = new NamedGraph2SP(); break; case Constants.REI_REP: con = new Reification2SP(); break; case Constants.TRIPLE_REP: con = new Triple2SP(); break; case Constants.NONE_REP: con = new ContextualRepresentationConverter(); break; default: con = new ContextualRepresentationConverter(); break; } return con; } }
true
ce75b0e464f6d90b46ab009b531a02ad54c6374e
Java
ha271923/MyBasicAppComponents
/app/src/main/java/sample/hawk/com/mybasicappcomponents/designpattern/singleton/Singleton_sync1.java
UTF-8
1,240
3.59375
4
[]
no_license
package sample.hawk.com.mybasicappcomponents.designpattern.singleton; /** * Singleton class 的實作適用於單執行緒的程式,在多執行緒的程式下,以上的寫法在多個執行緒的競爭資源下,將仍有可能產生兩個以上的實例, * 例如下面的情況: * Thread1: if(instance == null) // true * Thread2: if(instance == null) // true * * Thread1: instance = new Singleton(); // 產生一個實例 * Thread2: instance = new Singleton(); // 又產生一個實例 * * Thread1: return instance; // 回傳一個實例 * Thread2: return instance; // 又回傳一個實例 * * ANS: 在多執行緒的環境下,為了避免資源同時競爭而導致如上產生多個實例的情況,所以加上同步(synchronized)機制: */ public class Singleton_sync1 extends NoSingleton{ private static Singleton_sync1 mInstance; //透用一個靜態變數記錄實體 private Singleton_sync1() { // private keyword is MUST. } synchronized public static Singleton_sync1 getInstance() { // 同步機制會造成相當的效能低落 if (mInstance == null) mInstance = new Singleton_sync1(); return mInstance; } }
true
1e54f19d54d376fb20dc3b3c42e5a7c896c32076
Java
yhuiyang/my-test-apps
/AndroidProjects/GNHelper/src/com/yhlab/guessnumberhelper/lite/GNApp.java
UTF-8
1,854
2.109375
2
[]
no_license
package com.yhlab.guessnumberhelper.lite; import android.app.Application; import android.content.SharedPreferences; import android.graphics.Rect; import android.preference.PreferenceManager; import com.yhlab.guessnumberhelper.guess.ChooserFactory; import com.yhlab.guessnumberhelper.guess.Game; import com.yhlab.guessnumberhelper.guess.IGuessChooser; import com.yhlab.guessnumberhelper.guess.ScoredChooser; public class GNApp extends Application { @SuppressWarnings("unused") private static final String TAG = "App"; public ChooserFactory factory; public Game game; public int nexGuess; /* position of view used by the help activity */ public Rect rectRestartGame = null; public Rect rectAddResult = null; public Rect rectAppArea = null; public Rect rectGuessNumber = null; public Rect rectGuessResult = null; @Override public void onCreate() { super.onCreate(); /* setup preference default values */ PreferenceManager.setDefaultValues(this, R.xml.preferences, false); } public void InitGame(int digitCount, String method) { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this); /* retrieve game parameters if not specific */ if (digitCount == -1) { String d = sp.getString(SettingsActivity.KEY_DIGIT_COUNT, null); digitCount = Integer.parseInt(d); } if (method == null) { method = sp.getString(SettingsActivity.KEY_GUESS_METHOD, null); } factory = ChooserFactory.getInstance(); IGuessChooser chooser = factory.createChooser(method, null); if (chooser instanceof ScoredChooser) { ((ScoredChooser) chooser).setTimeout(5000); } game = new Game(digitCount, 10, chooser); } }
true
b08e9f5b45f1b518044b24432fec92e7023a29d2
Java
muthu1512/Recycler
/app/src/main/java/com/example/recycler/MainActivity.java
UTF-8
1,645
2.375
2
[]
no_license
package com.example.recycler; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static RecyclerView rc; private static RecyclerView.Adapter ada; private RecyclerView.LayoutManager rlm; private static ArrayList<constr> ac; static View.OnClickListener tst; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tst = new Myon(this); rc = findViewById(R.id.rec1); rc.setHasFixedSize(true); rlm = new LinearLayoutManager(this); rc.setLayoutManager(rlm); ac = new ArrayList<constr>(); String a[] = {"cupcake", "Donut", "Eclair"}; Integer ad[] = {R.drawable.icon, R.drawable.icon, R.drawable.icon}; for (int i = 0; i < a.length; i++) { ac.add(new constr(a[i], ad[i])); } ada = new adapter(ac); rc.setAdapter(ada); } private static class Myon implements View.OnClickListener { private final Context context; private Myon(Context context) { this.context = context; } @Override public void onClick(View v) { Toast.makeText(context, "Hi", Toast.LENGTH_SHORT).show(); } } }
true
b0ba93a4a4da15f9eeec7fde1ca4322d29536fb6
Java
GeMoschen/SmartLauncher
/src/main/java/de/gemo/smartlauncher/launcher/listener/GetPacksListener.java
UTF-8
4,071
2.34375
2
[]
no_license
package de.gemo.smartlauncher.launcher.listener; import java.util.List; import javax.swing.JOptionPane; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import de.gemo.smartlauncher.launcher.units.Pack; import de.gemo.smartlauncher.launcher.units.PackVersion; import de.gemo.smartlauncher.universal.frames.StatusFrame; import de.gemo.smartlauncher.universal.internet.ByteAction; import de.gemo.smartlauncher.universal.internet.GETResponse; import de.gemo.smartlauncher.universal.internet.HTTPAction; import de.gemo.smartlauncher.universal.internet.HTTPListener; import de.gemo.smartlauncher.universal.internet.Worker; import de.gemo.smartlauncher.universal.units.Logger; import de.gemo.smartlauncher.universal.units.ThreadHolder; import de.gemo.smartlauncher.universal.units.VARS; public class GetPacksListener extends HTTPListener { public void onStart(HTTPAction action) { Logger.info("getting packs..."); StatusFrame.INSTANCE.setText("getting packs..."); } public void onFinish(HTTPAction action) { try { GETResponse response = (GETResponse) this.getWorker().getResponse(); JsonObject object = JsonObject.readFrom(response.getResponse().toString()); JsonArray json = object.get("packs").asArray(); List<JsonValue> singlePacks = json.values(); for (JsonValue singlePack : singlePacks) { try { JsonObject thisPack = singlePack.asObject(); String packName = thisPack.get("name").asString(); if (Pack.loadedPacks.containsKey(packName)) { Logger.warning("Pack with name '" + packName + "' already exists! Ignoring this one..."); continue; } String recommended = thisPack.get("recommended_version").asString(); Pack pack = new Pack(packName); // add recommended version... pack.addVersion(new PackVersion(recommended + (" - recommended"))); JsonValue versionObject = thisPack.get("versions"); if (versionObject != null) { JsonArray versionArray = versionObject.asArray(); for (int index = 0; index < versionArray.size(); index++) { JsonValue value = versionArray.get(index); try { pack.addVersion(new PackVersion(value.asString())); } catch (Exception e2) { // ignore this version.... e2.printStackTrace(); } } } ThreadHolder.appendWorker(new Worker(new ByteAction(VARS.URL.PACKSERVER + "packs/" + pack.getPackName() + "/" + pack.getPackName() + ".png"), new GetPackIconListener(pack))); Pack.loadedPacks.put(packName, pack); Logger.fine("loaded pack '" + pack.getPackName() + "' with " + pack.getVersions().size() + " versions..."); } catch (Exception e) { // ignore pack... e.printStackTrace(); } } Logger.fine("Packs fetched..."); // get icons... ThreadHolder.startThread(); } catch (Exception e) { e.printStackTrace(); this.onError(action); return; } } @Override public void onError(HTTPAction action) { JOptionPane.showMessageDialog(null, "Could not fetch available packs...\nExiting...", "Error", JOptionPane.ERROR_MESSAGE); System.exit(0); } @Override public void onProgress(int maximumLength, int currentLength) { // do nothing... } }
true
caf8809f8486b0814d711964db63e9783ca22491
Java
MrKangWen/ZRApplication
/app/src/main/java/com/zhaorou/zrapplication/home/IHomeFragmentView.java
UTF-8
679
1.523438
2
[]
no_license
package com.zhaorou.zrapplication.home; import com.zhaorou.zrapplication.base.IBaseMvpView; import com.zhaorou.zrapplication.home.model.ClassListModel; import com.zhaorou.zrapplication.home.model.FriendPopDetailModel; import com.zhaorou.zrapplication.home.model.GoodsListModel; import java.util.List; public interface IHomeFragmentView extends IBaseMvpView { void onFetchedClassList(List<ClassListModel.DataBean.ListBean> list); void onFetchDtkGoodsList(List<GoodsListModel.DataBean.ListBean> list); void onLoadMore(boolean loadMore); void onGetFriendPopDetail(FriendPopDetailModel.DataBean.EntityBean entityBean); void onGetTaowords(String tkl); }
true
63c07502e67f2e2a8f0863825f09c1812ceb9ac0
Java
tsongpon/sentinel
/src/test/java/no/api/sentinel/CompaniesApiVersion2Test.java
UTF-8
3,553
2.09375
2
[]
no_license
package no.api.sentinel; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.Response; import no.api.sentinel.enumuration.Service; import org.apache.http.HttpStatus; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; import static com.jayway.restassured.RestAssured.get; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.hamcrest.Matchers.equalTo; /** * */ public class CompaniesApiVersion2Test { private static final Logger LOGGER = LoggerFactory.getLogger(CompaniesApiVersion2Test.class); private static final String VERSION1 = "v2"; private static final String SEPARATOR = "/"; private static final String FRONTIER_API_KEY = "bearer 9a76cd49-7ef3-481a-a854-f6721c9c0730"; @Test public void testSaveCompanyWithNoAuthentication() throws Exception { URL url = Resources.getResource("company/company.json"); String newCompanyAsJson = Resources.toString(url, Charsets.UTF_8); Response response = given().body(newCompanyAsJson).contentType(ContentType.JSON).when(). post(Service.FRONTIER.serviceAddress() + SEPARATOR + VERSION1 + SEPARATOR + "companies"); response.then().statusCode(HttpStatus.SC_UNAUTHORIZED); } @Test public void testCompanyAPI() throws Exception { URL url = Resources.getResource("company/company.json"); String newCompanyAsJson = Resources.toString(url, Charsets.UTF_8); Response response = given().body(newCompanyAsJson).contentType(ContentType.JSON).when(). header("Authorization", FRONTIER_API_KEY). post(Service.FRONTIER.serviceAddress() + SEPARATOR + VERSION1 + SEPARATOR + "companies"); response.then().statusCode(HttpStatus.SC_CREATED); String newCompanyLocation = response.getHeader("Location"); Assert.assertNotNull(newCompanyLocation); String newCompanyId = newCompanyLocation.split("/")[7]; get(newCompanyLocation).then().statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON) .assertThat().contentType(ContentType.JSON) .body(matchesJsonSchemaInClasspath("company/company_jsonschema.json")) .body("title", equalTo("Dnb NOR Eiendom Asker")) .body("fields.size", equalTo(8)); Response responseFromGet = get(newCompanyLocation); String newAdAsJson = responseFromGet.asString(); // test update ad String modifiedAd = newAdAsJson.replace("Dnb NOR Eiendom Asker", "new title"); Response putResponse = given().body(modifiedAd).contentType(ContentType.JSON).when(). header("Authorization", FRONTIER_API_KEY). put(Service.FRONTIER.serviceAddress() + SEPARATOR + VERSION1 + SEPARATOR + "companies" + SEPARATOR + newCompanyId); putResponse.then().statusCode(HttpStatus.SC_OK); //another get to verify put request get(newCompanyLocation).then().statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON) .assertThat().contentType(ContentType.JSON) .body(matchesJsonSchemaInClasspath("company/company_jsonschema.json")) .body("title", equalTo("new title")) .body("fields.size", equalTo(8)); } }
true
59194d69208fa3807eb235b345cc73b4b22a196d
Java
YangChengTeam/51answer
/app/src/main/java/com/yc/ac/index/ui/widget/SelectGradeViewAdapter.java
UTF-8
632
2.03125
2
[]
no_license
package com.yc.ac.index.ui.widget; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.yc.ac.R; import java.util.List; import androidx.annotation.Nullable; /** * Created by wanglin on 2018/4/18 13:55. */ public class SelectGradeViewAdapter extends BaseQuickAdapter<String, BaseViewHolder> { public SelectGradeViewAdapter(@Nullable List<String> data) { super(R.layout.select_grade_view_item, data); } @Override protected void convert(BaseViewHolder helper, String item) { helper.setText(R.id.tv_grade_item, item); } }
true
f4875594484c6ceae72288d6fba6a88133d629be
Java
Eikinel/Ready-Steady-THINK-
/core/src/com/readysteadythink/frames/FlashNumbers.java
UTF-8
10,930
2.140625
2
[]
no_license
package com.readysteadythink.frames; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.TimeUtils; import com.readysteadythink.Global; import com.readysteadythink.ui.BaseUIElement; import com.readysteadythink.ui.IUIElement; import com.readysteadythink.ui.TextUtils; import com.readysteadythink.ui.UIElementManager; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Random; public class FlashNumbers extends BaseFrame { private IFrame next = null; //UI Elements private UIElementManager manager = new UIElementManager(); private IUIElement toMenu; //Game variables private long gameClock = TimeUtils.millis(); private int SQUARE_MIN = 4; private int MAX_SQUARE_PER_LINE = 4; private int MAX_SQUARE_PER_COLUMN = 5; private int squareNumbers = SQUARE_MIN; private boolean win = false; private boolean flash = true; private boolean wait = false; private long startFlash; private long startWait; private float flashDuration; private float waitDuration = 1000f; private boolean check = false; private int lastClicked; //Sprites private Sprite O = new Sprite(new Texture("FlashNumbers/O.png")); private Sprite X = new Sprite(new Texture("FlashNumbers/X.png")); private Sprite buttonToMenu = new Sprite(new Texture("Shared/to_menu.png")); private boolean blink = false; private float blinkEnd = waitDuration / 2.5f; private float blinkInterval = blinkEnd / 5.f; //Text private String title = "Flash Numbers"; private Vector2 titlePos; private GlyphLayout layout; TextUtils textUtils = new TextUtils(); //Shapes private ShapeRenderer square = new ShapeRenderer(); private float squareSize = screenw / 8.f; private float borderWidth = screenw / 12.f; private List<Integer> squareIndexes = new ArrayList<Integer>(); private List<Vector2> squarePos = new ArrayList<Vector2>(); private List<Boolean> squareFlipped = new ArrayList<Boolean>(); private Vector2 min, max, spaceWidth; //Boundaries for squares //Sound private Sound success = Gdx.audio.newSound(Gdx.files.internal("FlashNumbers/success.mp3")); private Sound fail = Gdx.audio.newSound(Gdx.files.internal("FlashNumbers/fail.mp3")); public FlashNumbers() { X.setScale(squareSize / X.getWidth()); O.setScale((screenw / O.getWidth()) * 0.75f); buttonToMenu.setScale((screenw / buttonToMenu.getWidth()) * 0.1f); square.setColor(Color.BLACK); layout = new GlyphLayout(textUtils.getFontLarge(), title); titlePos = new Vector2( screenw / 2 - layout.width / 2, screenh - layout.height - screenh * 0.05f); O.setPosition( screenw / 2.f - O.getWidth() / 2.f, screenh / 2.f - O.getHeight() / 2.f - (screenh - titlePos.y) / 2.f ); min = new Vector2(screenw * 0.1f, screenh * 0.15f); max = new Vector2( screenw * 0.9f - squareSize, titlePos.y - layout.height - squareSize - screenh * 0.15f); spaceWidth = new Vector2( (max.x - min.x - squareSize * (MAX_SQUARE_PER_LINE - 1)) / (MAX_SQUARE_PER_LINE - 1), (max.y - min.y - squareSize * (MAX_SQUARE_PER_COLUMN - 1)) / (MAX_SQUARE_PER_COLUMN - 1)); toMenu = new BaseUIElement(Global.TO_MENU, buttonToMenu, screenw - (buttonToMenu.getWidth() * buttonToMenu.getScaleX()) - screenw * 0.02f, screenh - (buttonToMenu.getHeight() * buttonToMenu.getScaleY()) - screenh * 0.01f); manager.add(toMenu); initSquares(); } @Override public void init() { super.init(); } public IFrame update(float dt) { if (next != null) return next; if (wait) { long timeSinceWait = TimeUtils.timeSinceMillis(startWait); if (timeSinceWait >= waitDuration) { wait = false; restart(); } else if (timeSinceWait < blinkEnd) { if (timeSinceWait % (blinkInterval * 2) < blinkInterval) blink = false; else blink = true; } else blink = false; } if (flash && TimeUtils.timeSinceMillis(startFlash) >= flashDuration) { Gdx.app.log("Debug", "Stop flash at time " + Long.toString(TimeUtils.timeSinceMillis(gameClock))); flipAll(false); flash = false; } if (check) { check = false; int nbTrue = 0; boolean previous = false; for (int i = squareFlipped.size() - 1; i >= 0; i--) { if (squareFlipped.get(i)) nbTrue++; if (nbTrue == squareFlipped.size()) { win = true; success.play(); initWait(); break; } if (previous && !squareFlipped.get(i)) { win = false; X.setPosition( squarePos.get(lastClicked).x - (X.getWidth() * X.getScaleX()) / 1.25f, squarePos.get(lastClicked).y - (X.getHeight() * X.getScaleY()) / 1.25f); fail.play(); initWait(); break; } previous = squareFlipped.get(i); } } return this; } public void draw() { super.draw(); Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); for (int i = 0; i < squareIndexes.size(); i++) { if (squareFlipped.get(i)) { Gdx.gl.glLineWidth(borderWidth); square.begin(ShapeType.Line); } else { square.begin(ShapeType.Filled); } square.rect(squarePos.get(i).x, squarePos.get(i).y, squareSize, squareSize); square.end(); } long timeElapsedSecond = TimeUtils.timeSinceMillis(gameClock) / 1000; batch.begin(); manager.draw(batch, viewport); textUtils.getFontLarge().draw(batch, title, titlePos.x, titlePos.y); textUtils.getFontTiny().draw(batch, "Timer: " + Long.toString(timeElapsedSecond) + " second" + (timeElapsedSecond >= 2 ? "s" : ""), screenw * 0.02f, screenh * 0.98f); for (int i = 0; i < squareIndexes.size(); i++) { layout.setText(textUtils.getFontSmall(), Integer.toString(squareIndexes.get(i))); textUtils.getFontSmall().draw(batch, Integer.toString(squareIndexes.get(i)), squarePos.get(i).x + squareSize / 2 - layout.width / 2, squarePos.get(i).y + squareSize - layout.height / 2); } if (wait) { if (!win) X.draw(batch); else if (win && !blink) O.draw(batch); } batch.end(); } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (!flash && !wait) { Vector3 camPos = camera.unproject(new Vector3(screenX, screenY, 0)); String hit = manager.firstHit(camPos.x, camPos.y); ListIterator<Vector2> it = squarePos.listIterator(); int i = 0; if (hit != null) { Gdx.app.log("Log", hit); if (hit == toMenu.getName()) next = new MenuMain(); } while (it.hasNext()) { Vector2 pos = it.next(); if (camPos.x >= pos.x && camPos.x <= pos.x + squareSize && camPos.y >= pos.y && camPos.y <= pos.y + squareSize) { Gdx.app.log("Debug", "Touched square n°" + squareIndexes.get(i)); lastClicked = i; squareFlipped.set(i, true); check = true; return true; } i++; } } return false; } @Override public void dispose() { textUtils.dispose(); square.dispose(); O.getTexture().dispose(); X.getTexture().dispose(); } public void restart() { Gdx.app.log("Debug", "Game is " + (win ? "won" : "lost")); if (win) squareNumbers++; else if (!win && squareNumbers > SQUARE_MIN) squareNumbers--; squareIndexes.clear(); squarePos.clear(); squareFlipped.clear(); initSquares(); } public void initWait() { flipAll(true); blink = false; wait = true; startWait = TimeUtils.millis(); } public void initSquares() { Random rand = new Random(); List<Vector2> takenCases = new ArrayList<Vector2>(); flash = true; flashDuration = 1000.f + 200.f * (squareNumbers - SQUARE_MIN); startFlash = TimeUtils.millis(); for(int i = 1; i <= squareNumbers; i++) { Vector2 randCase = new Vector2(rand.nextInt(MAX_SQUARE_PER_LINE), rand.nextInt(MAX_SQUARE_PER_COLUMN)); for (int j = 0; j < takenCases.size(); j++) { if (randCase.equals(takenCases.get(j))) { Gdx.app.log("Debug", "Same position encountered, redefinition"); randCase = new Vector2(rand.nextInt(MAX_SQUARE_PER_LINE), rand.nextInt(MAX_SQUARE_PER_COLUMN)); j = -1; } } takenCases.add(randCase); squareIndexes.add(i); squarePos.add(new Vector2( min.x + randCase.x * squareSize + randCase.x * spaceWidth.x, max.y - randCase.y * squareSize - randCase.y * spaceWidth.y)); squareFlipped.add(true); } } public void flipAll(boolean flip) { for (int i = 0; i < squareFlipped.size(); i++) squareFlipped.set(i, flip); } }
true
9fe5f57c25b753b82f72a08a02561e9b1f579960
Java
OpenBEL/openbel-framework
/org.openbel.framework.ws/src/main/java/org/openbel/framework/ws/utils/InvalidIdException.java
UTF-8
2,571
2.40625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2013 OpenBEL Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openbel.framework.ws.utils; import static java.lang.String.format; import org.openbel.framework.api.KamElement; /** * {@link InvalidIdException} represents an invalid id for a * {@link KamElement}. * * <p> * This exception is useful when decoding and encoding ids and the id format * is invalid. * </p> * * @author Anthony Bargnesi {@code <abargnesi@selventa.com>} */ public class InvalidIdException extends Exception { private static final long serialVersionUID = -8513252613595602912L; /** * The message format string when id is invalid - {@value} */ private static final String INVALID_MSG_FMT = "Invalid id '%s'"; /** * The message for null ids - {@value} */ private static final String NULL_MESSAGE = "Null id is invalid"; /** * Construct the exception with a default message indicating the id was * <tt>null</tt>. The message used is * {@link InvalidIdException#NULL_MESSAGE null msg}. */ public InvalidIdException() { super(buildMessage(null)); } /** * Construct the exception with the <tt>id</tt> value that failed to * decode. * * <p> * The exception's message if constructed by * {@link InvalidIdException#buildMessage(String)} using the * {@link InvalidIdException#INVALID_MSG_FMT invalid id message format}. * </p> * * @param id, {@link String} the id */ public InvalidIdException(String id) { super(buildMessage(id)); } /** * Build the exception's message using the <tt>id</tt> value. * * @param id, {@link String} the id * @return the exception's message */ private static String buildMessage(final String id) { if (id == null) { return NULL_MESSAGE; } return format(INVALID_MSG_FMT, id); } /** * {@inheritDoc} */ @Override public String toString() { return getMessage(); } }
true
bd97d5789a7a1c4962df0eeff3dd8114100b92a0
Java
maxdeny/test
/AndroidFrame/src/com/mdx/mobile/service/MService.java
UTF-8
1,636
2.296875
2
[]
no_license
package com.mdx.mobile.service; import com.mdx.mobile.commons.threadpool.PRunable; import com.mdx.mobile.commons.threadpool.ThreadPool; import com.mdx.mobile.commons.threadpool.ThreadPool.OnThreadEmpty; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; public abstract class MService extends Service { public static MService SERVICE = null; public ThreadPool threadpool=new ThreadPool(); @Override public void onCreate() { super.onCreate(); threadpool.setOnThreadEmpty(new OnThreadEmpty() { @Override public void onThreadEmpty() { SERVICE.stopSelf(); } }); SERVICE = this; create(); } public synchronized void stopServer() { if (SERVICE != null) { if(threadpool.getRuning().size()+threadpool.getWatrun().size()>0){ threadpool.intermitAll(); } } } public synchronized static void start(Context context,Class<?> clas) { if (SERVICE == null) { Intent intent = new Intent(context,clas); intent.setFlags(BIND_AUTO_CREATE); context.startService(intent); } } public synchronized static void stop() { if (SERVICE != null) { SERVICE.stopServer(); } } @Override public void onDestroy() { super.onDestroy(); SERVICE = null; } protected void execute(PRunable runable){ if(SERVICE!=null){ threadpool.execute(runable); } } protected abstract void create(); public void setPoolSize(int size){ this.threadpool.setMaxThreadSize(size); } @Override public IBinder onBind(Intent intent) { return null; } }
true
2e0912781866ee96899562f49e50a6e1425dd28a
Java
paul-gege/Differential-Evolution
/Differential Evolution/src/two/Individual2D.java
UTF-8
816
3.625
4
[]
no_license
package two; //2 dimensional individual public class Individual2D { //genes to help determine fitness value private double gene1; private double gene2; //fitness value to determine how well individual is "built", there are better words to define but.. private double fitness_value; //constructor methods public Individual2D(double value1, double value2){ this.gene1 = value1; this.gene2 = value2; } //setting fitness value public void Set_Fitness(double fitness) { this.fitness_value = fitness; } //getting genes which are encapsulated public double get_gene1() { return gene1; } public double get_gene2() { return gene2; } //getting fitness as well which is encapsulated. public double get_fitness() { return fitness_value; } }
true
d723483d175fe9b3a5d445c4361fb6edded22451
Java
lvoegtlin/image_filter_methods_DivaServices
/src/ch/unifr/imageFilters/Main.java
UTF-8
8,762
3.015625
3
[ "Apache-2.0" ]
permissive
package ch.unifr.imageFilters; import com.jhlabs.image.*; import org.apache.commons.cli.*; import org.apache.commons.io.FilenameUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; /** * @author Lars Voegtlin * <p> * A CLI interface for the JH Lab filter classes. */ public class Main { static String filterName; static String fileFormat; static String[] filterArguments; static File outputFile; static BufferedImage outputImage; static BufferedImage inputImage; public static void main(String[] args) { Options ops = new Options(); //chose the filter you want to use ops.addOption(Option.builder("f") .longOpt("chose-filter") .numberOfArgs(1) .desc("The filter you want to use. ") //TODO list of filters .type(String.class) .required() .build()); ops.addOption(Option.builder("i") .longOpt("image") .numberOfArgs(1) .desc("The source image") .type(String.class) .required() .build()); ops.addOption(Option.builder("o") .longOpt("output-path") .numberOfArgs(1) .desc("The path to the output folder") .type(String.class) .required() .build()); //any number of parameters that the filter needs ops.addOption(Option.builder("a") .longOpt("arguments") .numberOfArgs(Option.UNLIMITED_VALUES) .desc("A list of arguments for the chosen filter") .required(false) .build()); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(ops, args); String inputImageName = cmd.getOptionValue('i'); filterName = cmd.getOptionValue('f').toLowerCase(); filterArguments = cmd.getOptionValues('a'); if (filterArguments == null){ filterArguments = new String[]{}; } inputImage = getImageByPath(cmd.getOptionValue('i')); fileFormat = FilenameUtils.getExtension(inputImageName); outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType()); String outputPath = cmd.getOptionValue('o'); String fileName = FilenameUtils.getName(inputImageName); outputFile = new File(outputPath + "/" + filterName + "_" + fileName); //executeClassWithArguments(); executeFilter(); } catch (ParseException | IOException e) { System.err.println("Could not parse the CLI options!"); e.printStackTrace(); System.exit(1); } System.out.println("Filter successfully applied!"); } private static BufferedImage getImageByPath(String path) throws IOException { return ImageIO.read(new File(path)); } private static void executeFilter() { switch (filterName) { case "gaussian": GaussianFilter gaussian = null; if (filterArguments.length == 1) { gaussian = new GaussianFilter(Float.parseFloat(filterArguments[0])); } else if (filterArguments.length == 0) { gaussian = new GaussianFilter(); } else { System.out.println("gaussian takes no or one argument!"); System.exit(1); } try { ImageIO.write(gaussian.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "threshold": ThresholdFilter threshold = null; if (filterArguments.length == 1) { threshold = new ThresholdFilter(Integer.parseInt(filterArguments[0])); } else if (filterArguments.length == 0) { threshold = new ThresholdFilter(); } else { System.out.println("threshold takes no or one argument!"); System.exit(1); } try { ImageIO.write(threshold.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "blur": BlurFilter blur = null; if (filterArguments.length == 0) { blur = new BlurFilter(); } else { System.out.println("Blur takes no argument!"); System.exit(1); } try { ImageIO.write(blur.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "contrast": ContrastFilter contrast = null; if (filterArguments.length == 0) { contrast = new ContrastFilter(); } else { System.out.println("Contrast takes no argument!"); System.exit(1); } try { ImageIO.write(contrast.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "exposure": ExposureFilter exposure = null; if (filterArguments.length == 0) { exposure = new ExposureFilter(); } else { System.out.println("exposure takes no argument!"); System.exit(1); } try { ImageIO.write(exposure.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "grayscale": GrayscaleFilter grayscale = null; if (filterArguments.length == 0) { grayscale = new GrayscaleFilter(); } else { System.out.println("grayscale takes no argument!"); System.exit(1); } try { ImageIO.write(grayscale.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; /***************** * EDGE DETECTION ****************/ case "edge": EdgeFilter edge = null; if (filterArguments.length == 0) { edge = new EdgeFilter(); } else { System.out.println("Edge takes no argument!"); System.exit(1); } try { ImageIO.write(edge.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "dog": DoGFilter dog = null; if (filterArguments.length == 0) { dog = new DoGFilter(); } else { System.out.println("DoG takes no argument!"); System.exit(1); } try { ImageIO.write(dog.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; case "laplace": LaplaceFilter laplace = null; if (filterArguments.length == 0) { laplace = new LaplaceFilter(); } else { System.out.println("LaPlace takes no argument!"); System.exit(1); } try { ImageIO.write(laplace.filter(inputImage, outputImage), fileFormat, outputFile); } catch (IOException e) { e.printStackTrace(); } break; } } }
true
7ca5b4637222bb9eeebfd01dc8b2b1097295fbf5
Java
LzDocker/NetWorkDetial
/app/src/main/java/com/dcoker/networkdetial/Myapplication.java
UTF-8
394
1.976563
2
[]
no_license
package com.dcoker.networkdetial; import android.app.Application; /** * Created by Mr.Zhang on 2017/6/27. */ public class Myapplication extends Application { private static Myapplication myinstance; @Override public void onCreate() { super.onCreate(); myinstance=this; } public static Myapplication getInstance(){ return myinstance; } }
true
16bc77d2016fc6fc7a9ad1c0c8649bebc36c4c5a
Java
zhangjianbinJAVA/MobileSafe
/app/src/main/java/mobilesafe/itheima/com/mobilesafe/NumberAddressActivity.java
UTF-8
2,935
2.640625
3
[]
no_license
package mobilesafe.itheima.com.mobilesafe; import android.app.Activity; import android.os.Bundle; import android.os.Vibrator; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import mobilesafe.itheima.com.mobilesafe.db.NumberAddressQueryUtils; /** * 号码归属地查询 */ public class NumberAddressActivity extends Activity { private EditText ed_phone; private TextView tv_showResult; /** * 系统自带的震动效果 */ private Vibrator vibrator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_number_address); ed_phone = (EditText) findViewById(R.id.ed_phone); tv_showResult = (TextView) findViewById(R.id.tv_showResult); //文本输入后自动查询 ed_phone.addTextChangedListener(new TextWatcher() { /** * 当文本发生变化之前回调 */ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } /** * 当文本发生变化的时候回调 */ @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s != null && s.length() >= 3) { //查询数据库,并且显示结果 String address = NumberAddressQueryUtils.queryNumber(s.toString()); tv_showResult.setText("结果:"+address); } } /** * 当文本发生变化之后回调 */ @Override public void afterTextChanged(Editable s) { } }); } /** * 查询号码归属地 * * @param view */ public void numberAddressQuery(View view) { String phoneNumber = ed_phone.getText().toString().trim(); if (TextUtils.isEmpty(phoneNumber)) { Toast.makeText(this, "号码为空", Toast.LENGTH_SHORT).show(); //实例化震动服务 vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(2000);//震动的时间 long[] pattern = {200,200,200,200};//停,震动 vibrator.vibrate(pattern,-1);// 0:循环震动, -1:不重复 1:从pattern的索引1开始震动 } else { //去数据库中查询 电话号码查询归属地 //第一种:联网查询; //第二种:把数据库 放在本地; String address = NumberAddressQueryUtils.queryNumber(phoneNumber); tv_showResult.setText("结果:"+address); } } }
true
4ce6c8d78d5804cf151131f4781b955269d1257e
Java
chamber-wong/JavaRelearn
/day7/src/demo/Demo4.java
GB18030
1,761
4.34375
4
[]
no_license
package demo; /* * ڼ̳ʹù췽 * * * * 1.һֻһĹ췽,ֻʹô,ʹ޲ε.ʹ,ֶ޲εĹ췽 * 2.ֻдĹ췽,Ĺ췽оͱڵһֶøĹ췽(super()) * 3.Ǵ췽ʱ,Լдsuper(),ϵͳԶ * ԭ:ҲҪгʼ,ԱԼĹ췽гʼ,Աsuper(),ÿ췽жĬһsuper() * * ΪʲôҪsuperڷĵһ? * :Ĺ췽пõ,ʹ֮ǰȽгʼ,޷ʹ. * * ֮:ڼ̳ϵ,Ϊõİ취ǽ޲ι췽вι췽д. */ public class Demo4 { public static void main(String[] args) { Dog dog = new Dog(); dog.play(); dog.setName(""); } } class Animal{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Animal() { // TODO Auto-generated constructor stub } public Animal(String name) { this.name = name; } } class Dog extends Animal{ public Dog() { //super();//Ĭϵõĸ޲εĹ췽 super("ë");//ֶøвεĹ췽 } public Dog(String name){ super(name);//ڵһ //дԼĴ,Ҫõ,Աȳʼʹ. } public void play(){ System.out.println("play"); } }
true
06bf2b8cbfe42c9c356205dc7bb93f29353fee43
Java
satishrana01/projectdiary
/src/org/projectdiaries/dao/ProjectDAO.java
UTF-8
3,813
2.609375
3
[]
no_license
package org.projectdiaries.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class ProjectDAO { Connection conn = null; DateFormat dfdate = new SimpleDateFormat("MM/dd/yyyy"); DateFormat dftime = new SimpleDateFormat("HH:mm:ss"); public ProjectDAO(Connection con) { if(null == con) throw new RuntimeException("The Connection is null"); else conn = con; } public ResultSet getTaskStatus(String projectName) { ResultSet rs = null; String sql = "Select * from project_details where project_name = '" + projectName + "' order by last_modified_time desc LIMIT 1"; try { PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql); rs = pst.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public void insertProjectRow(String pName, String bRate) { String sql = "Insert into project_details (project_name, start_time, end_time, date, rate, wages, status, last_modified_time) values (?, ?, ?, ?, ?, ?, ?, datetime())"; try { PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql); pst.setString (1, pName); pst.setString (2, dftime.format(Calendar.getInstance().getTime())); pst.setString (3, null); pst.setString (4, dfdate.format(Calendar.getInstance().getTime())); pst.setString (5, bRate); pst.setString (6, "0"); pst.setString (7, "In Progress"); pst.execute(); } catch (SQLException e) { e.printStackTrace(); } } public ResultSet fetchSelectedProjectRows(String projectName) { ResultSet rs = null; String sql = "Select * from project_details where project_name = '" + projectName + "' order by last_modified_time desc"; try { PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql); rs = pst.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public void updateProjectRow(String pName) throws ParseException { ResultSet rs = null; int SNo = 0; Date st_time = null; Date end_time = null; String rate = null; double wages = 0; String sqlfind = "Select * from project_details order by last_modified_time desc LIMIT 1"; try { PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sqlfind); rs = pst.executeQuery(); if(rs.next()) { SNo = (Integer) rs.getInt(1); st_time = dftime.parse(rs.getString("start_time")); rate = (String) rs.getString("rate"); } end_time = dftime.parse(dftime.format(Calendar.getInstance().getTime())); long diff = end_time.getTime() - st_time.getTime(); long diffHours = diff / (60 * 1000) % 24; wages = (Integer.parseInt(rate)/60) * diffHours; String sqlupdate = "Update project_details set end_time = ?, wages = ?, status = ?, last_modified_time = datetime() where SNo = '" + SNo + "'"; PreparedStatement pstnext = (PreparedStatement) conn.prepareStatement(sqlupdate); pstnext.setString(1, dftime.format(Calendar.getInstance().getTime())); pstnext.setString(2, String.valueOf(wages)); pstnext.setString(3, "Completed"); pstnext.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public ResultSet fetchCompletedProjectRows(String projectName) { ResultSet rs = null; String sql = "Select * from project_details where project_name = '" + projectName + "' and status = 'Completed' order by last_modified_time desc"; try { PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql); rs = pst.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } }
true
8e39090bc48ba3299414c00258f85ecc2e9ad6da
Java
timoshimmo/SpacioCRMApp
/app/src/main/java/com/android/spaciocrm/util/dialogs/CountryDialogFragment.java
UTF-8
1,088
1.945313
2
[]
no_license
package com.android.spaciocrm.util.dialogs; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.android.spaciocrm.R; public class CountryDialogFragment extends DialogFragment { Button btnCtryCancel, btnCtryOk; Dialog d; public CountryDialogFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onStart() { super.onStart(); d = getDialog(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.country_dialog_layout, container, false); return rootView; } }
true
31130fffb69e9f20ec9f877e7d9250d4a4f6cba3
Java
JackSatellite/AndroidOperator
/src/main/java/com/hjx/util/phone/InputCode.java
UTF-8
1,676
2.671875
3
[]
no_license
package com.hjx.util.phone; /** * 输入的关键字 */ public class InputCode { /** * 基本类型 */ public interface Number { String Num0 = " 7 ";//按键'0' String Num1 = " 8 ";//按键'1' String Num2 = " 9 ";//按键'2' String Num3 = " 10 ";//按键'3' String Num4 = " 11 ";//按键'4' String Num5 = " 12 ";//按键'5' String Num6 = " 13 ";//按键'6' String Num7 = " 14 ";//按键'7' String Num8 = " 15 ";//按键'8' String Num9 = " 16 ";//按键'9' } /** * 字母 */ public interface LETTER { String A = " 29 ";//按键'A' String B = " 30 ";//按键'B' String C = " 31 ";//按键'C' String D = " 32 ";//按键'D' String E = " 33 ";//按键'E' String F = " 34 ";//按键'F' String G = " 35 ";//按键'G' String H = " 36 ";//按键'H' String I = " 37 ";//按键'I' String J = " 38 ";//按键'J' String K = " 39 ";//按键'K' String L = " 40 ";//按键'L' String M = " 41 ";//按键'M' String N = " 42 ";//按键'N' String O = " 43 ";//按键'O' String P = " 44 ";//按键'P' String Q = " 45 ";//按键'Q' String R = " 46 ";//按键'R' String S = " 47 ";//按键'S' String T = " 48 ";//按键'T' String U = " 49 ";//按键'U' String V = " 50 ";//按键'V' String W = " 51 ";//按键'W' String X = " 52 ";//按键'X' String Y = " 53 ";//按键'Y' String Z = " 54 ";//按键'Z' } }
true
7e3dac3fc62138357096d3f948fed8a4005a8a1e
Java
Czurch/RoundTableJava
/src/com/czurch/rtl/mechanics/Items/Weapon.java
UTF-8
575
2.734375
3
[]
no_license
package com.czurch.rtl.mechanics.Items; import com.czurch.rtl.mechanics.coreMath; public class Weapon extends Item{ public enum weaponType{ two_handed, one_handed, ranged, shield } public String name; protected weaponType type; protected int minDmg, maxDmg; public Weapon(String nom, weaponType typ, int min, int max, int val){ this.name = nom; this.type = typ; this.minDmg = min; this.maxDmg = max; this.value = val; } public int active() { return coreMath.randomNumberBetween(minDmg, maxDmg); } public void passive() { } }
true
72f604871abf80b1166ff2c1c2666fc2f7943204
Java
wanyinsheng/leetcode
/src/main/java/leet_202301/DistinctPrimeFactors.java
UTF-8
707
3.375
3
[]
no_license
package leet_202301; import java.util.HashSet; /** * 2521. 数组乘积中的不同质因数数目 * * @Author wanys * @Date 2023/1/8 09:22 * @Version 1.0 **/ public class DistinctPrimeFactors { public int distinctPrimeFactors(int[] nums) { HashSet<Integer> set = new HashSet<>();//需要去重 for (int x : nums) { for (int i = 2; i * i <= x; i++) {//质因数 if (x % i == 0) { set.add(i); while (x % i == 0) { x /= i; } } } if (x > 1) { set.add(x); } } return set.size(); } }
true
ed8def35fd1754021869f743b5c830efe442c5c1
Java
ZoranLi/wechat_reversing
/com/tencent/mm/boot/svg/a/a/adl.java
UTF-8
4,470
1.78125
2
[]
no_license
package com.tencent.mm.boot.svg.a.a; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; import com.tencent.smtt.sdk.WebView; public final class adl extends c { private final int height = 63; private final int width = 63; protected final int b(int i, Object... objArr) { switch (i) { case 0: return 63; case 1: return 63; case 2: Canvas canvas = (Canvas) objArr[0]; Looper looper = (Looper) objArr[1]; Matrix d = c.d(looper); float[] c = c.c(looper); Paint g = c.g(looper); g.setFlags(385); g.setStyle(Style.FILL); Paint g2 = c.g(looper); g2.setFlags(385); g2.setStyle(Style.STROKE); g.setColor(WebView.NIGHT_MODE_COLOR); g2.setStrokeWidth(1.0f); g2.setStrokeCap(Cap.BUTT); g2.setStrokeJoin(Join.MITER); g2.setStrokeMiter(4.0f); g2.setPathEffect(null); c.a(g2, looper).setStrokeWidth(1.0f); Paint a = c.a(g, looper); a.setColor(-15028967); canvas.save(); c = c.a(c, 1.0f, 0.0f, 6.0f, 0.0f, 1.0f, 3.0f); d.reset(); d.setValues(c); canvas.concat(d); canvas.save(); c = c.a(c, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 18.0f); d.reset(); d.setValues(c); canvas.concat(d); canvas.save(); Paint a2 = c.a(a, looper); Path h = c.h(looper); h.moveTo(5.0f, 5.0f); h.lineTo(5.0f, 34.0f); h.lineTo(34.0f, 34.0f); h.lineTo(34.0f, 5.0f); h.lineTo(5.0f, 5.0f); h.close(); h.moveTo(0.0f, 1.5049495f); h.cubicTo(0.0f, 0.67378885f, 0.676918f, 0.0f, 1.5049495f, 0.0f); h.lineTo(37.495052f, 0.0f); h.cubicTo(38.32621f, 0.0f, 39.0f, 0.676918f, 39.0f, 1.5049495f); h.lineTo(39.0f, 37.495052f); h.cubicTo(39.0f, 38.32621f, 38.323082f, 39.0f, 37.495052f, 39.0f); h.lineTo(1.5049495f, 39.0f); h.cubicTo(0.67378885f, 39.0f, 0.0f, 38.323082f, 0.0f, 37.495052f); h.lineTo(0.0f, 1.5049495f); h.close(); WeChatSVGRenderC2Java.setFillType(h, 1); canvas.drawPath(h, a2); canvas.restore(); canvas.restore(); canvas.save(); a2 = c.a(a, looper); h = c.h(looper); h.moveTo(52.925938f, 23.0f); h.cubicTo(52.974922f, 22.49169f, 53.0f, 21.976135f, 53.0f, 21.454546f); h.cubicTo(53.0f, 12.919235f, 46.28427f, 6.0f, 38.0f, 6.0f); h.cubicTo(35.866688f, 6.0f, 33.837387f, 6.4588375f, 32.0f, 7.285953f); h.lineTo(32.0f, 10.252686f); h.cubicTo(33.60105f, 9.50638f, 35.378433f, 9.090909f, 37.25f, 9.090909f); h.cubicTo(44.29163f, 9.090909f, 50.0f, 14.9722595f, 50.0f, 22.227272f); h.cubicTo(50.0f, 22.486673f, 49.992702f, 22.744318f, 49.978306f, 23.0f); h.lineTo(52.925938f, 23.0f); h.close(); WeChatSVGRenderC2Java.setFillType(h, 2); canvas.drawPath(h, a2); canvas.restore(); canvas.save(); Paint a3 = c.a(a, looper); Path h2 = c.h(looper); h2.moveTo(35.0f, 0.0f); h2.lineTo(26.0f, 7.4431515f); h2.lineTo(34.865273f, 15.0f); h2.close(); WeChatSVGRenderC2Java.setFillType(h2, 1); WeChatSVGRenderC2Java.setFillType(h2, 2); canvas.drawPath(h2, a3); canvas.restore(); canvas.restore(); c.f(looper); break; } return 0; } }
true
82006afb2cece13a0e17cd8083465bafab02760f
Java
liuyucheng11/Spring-SpringMVC-MP
/src/main/java/com/studentAdmin/domain/VOs/MessageVO.java
UTF-8
623
2.15625
2
[]
no_license
package com.studentAdmin.domain.VOs; import com.studentAdmin.domain.Message; /** * @author: liu.yucheng * @Date: 2019-4-28 12:22 * @version: 1.0 */ public class MessageVO extends Message { //发送人名 private String sendName; //接收人名 private String receiveName; public String getSendName() { return sendName; } public void setSendName(String sendName) { this.sendName = sendName; } public String getReceiveName() { return receiveName; } public void setReceiveName(String receiveName) { this.receiveName = receiveName; } }
true
85e54417d1c1c46963cc6fb195e9d8294b885ae5
Java
landschootl/coo-letters
/test/letter/content/TextContentTest.java
UTF-8
523
2.328125
2
[]
no_license
package letter.content; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; public class TextContentTest extends ContentTest<String, TextContent>{ @Before public void setUp() throws Exception { value = "bla bla"; content = new TextContent(value); } @After public void tearDown() throws Exception { } @Override public void testToString() { // TODO Auto-generated method stub assertEquals("whose content is a text content (bla bla)", content.toString()); } }
true
532262e6a913bc2c5ef98a62514b5ab094d56b0f
Java
conglinhrocket13/Rocket13
/Java Core/Candidate (Bài Ôn Tập)/src/com/vti/backend/businesslayer/CandidateService.java
UTF-8
1,279
2.125
2
[]
no_license
package com.vti.backend.businesslayer; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import com.vti.backend.datalayer.CandidateRepository; import com.vti.entity.ExperienceCandidate; import com.vti.entity.FresherCandidate; import com.vti.ultis.ScannerUltis; public class CandidateService implements ICandidateService { private CandidateRepository repository; public CandidateService() throws FileNotFoundException, IOException { repository = new CandidateRepository(); } @Override public boolean Login(String email, String password) throws ClassNotFoundException, SQLException { return repository.Login(email, password); } @Override public boolean createExperience(ExperienceCandidate Exp) throws ClassNotFoundException, SQLException { return repository.createExperience(Exp); } @Override public boolean createFresher(FresherCandidate Fresh) throws SQLException, ClassNotFoundException { // TODO Auto-generated method stub return repository.createFresher(Fresh); } @Override public Boolean isEmailExists(String email) throws SQLException, ClassNotFoundException { Boolean check = repository.isEmailExists(email); if(check) { return true; }else { return false; } } }
true
47414975ece77fad17a94de03186c50e9199e76e
Java
GWsoftware786/islamiclibrary
/app/src/main/java/com/gwsoftware/alahazratkakalam/fragments/DownloadedBooks.java
UTF-8
2,467
2.09375
2
[]
no_license
package com.gwsoftware.alahazratkakalam.fragments; import android.os.AsyncTask; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gwsoftware.alahazratkakalam.R; import com.gwsoftware.alahazratkakalam.adapter.CollectionsListAdapter; import com.gwsoftware.alahazratkakalam.asyncktask.GetData; import com.gwsoftware.alahazratkakalam.interfaces.GetLocalData; import com.gwsoftware.alahazratkakalam.models.CollectionModel; import java.util.List; public class DownloadedBooks extends Fragment { RecyclerView collectionRecyclerView; CollectionsListAdapter collectionsListAdapter; TextView noDownloadsFound; //Overriden method onCreateView @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //Returning the layout file after inflating //Change R.layout.tab1 in you classes View view = inflater.inflate(R.layout.downloaded_books, container, false); collectionRecyclerView = view.findViewById(R.id.collectionRecyclerView); noDownloadsFound = view.findViewById(R.id.no_downloads_found); initializeRecyclerView(); getCollectionsList(); return view; } private void initializeRecyclerView() { LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getContext()); collectionRecyclerView.setLayoutManager(gridLayoutManager); } private void getCollectionsList() { new GetData(getContext(), new GetLocalData() { @Override public void getData(List<CollectionModel> tasks) { if (tasks != null && tasks.size() > 0) { noDownloadsFound.setVisibility(View.GONE); collectionRecyclerView.setVisibility(View.VISIBLE); collectionsListAdapter = new CollectionsListAdapter(getContext(), tasks); collectionRecyclerView.setAdapter(collectionsListAdapter); } else { noDownloadsFound.setVisibility(View.VISIBLE); collectionRecyclerView.setVisibility(View.GONE); } } }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }
true
a77edf207b24b4448fdd41e703f5af8ca0f15f09
Java
SandeepDevrari/android_code
/O_C_R/app/src/main/java/devrari/sandeep/ocrapp/recycler_adapters/RecyclerAdapter.java
UTF-8
4,229
2.234375
2
[]
no_license
package devrari.sandeep.ocrapp.recycler_adapters; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.text.TextBlock; import com.google.android.gms.vision.text.TextRecognizer; import java.io.IOException; import java.util.List; import devrari.sandeep.ocrapp.R; import devrari.sandeep.ocrapp.pojo_classes.GetndSet; /** * Created by user on 10/4/18. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.AdapterHolder> { private Context context; private List<GetndSet>lists; public RecyclerAdapter(Context context, List<GetndSet> lists) { this.context = context; this.lists = lists; } @Override public AdapterHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new AdapterHolder(LayoutInflater.from(context).inflate(R.layout.layout_card_view_ocr,parent,false)); } @Override public void onBindViewHolder(AdapterHolder holder, final int position) { final Uri thisImageURI=(lists.get(position)).getPathUri(); Glide.with(context).load(thisImageURI).into(holder.imageView); if(!holder.isClickableImage){ View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View v) { //StringBuilder builder=readerImage(thisImageURI); //Log.w("image clicked",""+builder); } }; holder.imageView.setOnClickListener(listener); // holder.isClickableImage=true; // setViewImageListner(holder.imageView,position); } } private void setViewImageListner(ImageView imageView,final int pos){ View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View v) { StringBuilder builder=readerImage((lists.get(pos).getPathUri())); Log.w("image clicked",""+builder); } }; imageView.setOnClickListener(listener); } @Override public int getItemCount() { return lists.size(); } public class AdapterHolder extends RecyclerView.ViewHolder { ImageView imageView; boolean isClickableImage=false; public AdapterHolder(View itemView) { super(itemView); imageView=itemView.findViewById(R.id.cardImage); //imageView.setOnClickListener(clickListener); } } public StringBuilder readerImage(Uri uri){ Log.w("File URI ",""+uri); Bitmap bitmapImage= null; try { bitmapImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(),uri); } catch (IOException e) { e.printStackTrace(); } StringBuilder stringBuilder=new StringBuilder(); if(bitmapImage!=null){ TextRecognizer textRecognizer=new TextRecognizer.Builder(context).build(); if(!textRecognizer.isOperational()){ Log.w("TextRecognizer","text recognizwer is not operational!!"); } Frame frame=new Frame.Builder().setBitmap(bitmapImage).build(); SparseArray<TextBlock>textBlockSparseArray=textRecognizer.detect(frame); for(int i=0;i<textBlockSparseArray.size();i++){ TextBlock textBlock=textBlockSparseArray.get(textBlockSparseArray.keyAt(i)); List<? extends com.google.android.gms.vision.text.Text> listText=textBlock.getComponents(); for(com.google.android.gms.vision.text.Text text:listText){ stringBuilder.append(text.getValue()); //textView.setText(textView.getText().toString()+"\n"+text.getValue()); } } } return stringBuilder; } }
true
224c3deaf4c4d1405fef0f38a1e2b40bc5bbdd72
Java
yelmatisowjanya/OSU
/OS_Phase1/src/ERROR_HANDLER.java
UTF-8
5,532
2.625
3
[]
no_license
import java.io.BufferedWriter; import java.io.FileWriter; /* Description: The error_handler subsystem handles the errors with custom exceptions by throwing a string message to the Exception class.It handles both warnings and errors. In case of warnings the program continue's execution and In case of errors it calls the dump and written to handle the termination.The static variable message used to print the Description of error or warning outputfile.txt file; */ public class ERROR_HANDLER extends Exception { public ERROR_HANDLER(int errornumber,PROCESSMANAGER PCB) { SCHEDULER.blockElements.clear(); SCHEDULER.DataElements.clear(); SCHEDULER.blockElements1.clear(); SCHEDULER.Outputelements.clear(); int pid=0; if (errornumber == 101) { errorcaseswrite("File not found exception",101); AvoidErrorJobs(); } if (errornumber == 104) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("Address out of range",104); MEMORY.memory("DUMP", 0, "0",PCB); } if (errornumber == 105) { errorcaseswrite("Illegal Input",105); AvoidErrorJobs(); } if (errornumber == 106) { errorcaseswrite("Invalid Loader Format Character",106); AvoidErrorJobs(); } if (errornumber == 107) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("Overlow",107); MEMORY.memory("DUMP", 0, "0",PCB); LOADER.readeachJob(); } if (errornumber == 108) { errorcaseswrite("More than one of the three bits is set",108); MEMORY.memory("DUMP", 0, "0",PCB); LOADER.readeachJob(); } if (errornumber == 109) { errorcaseswrite("The input accepts only 3 digit Hex Number",109); AvoidErrorJobs(); } if (errornumber == 110) { errorcaseswrite("The input has to be in Hex format",110); AvoidErrorJobs(); } if (errornumber == 111) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("invalid op-code",111); MEMORY.memory("DUMP", 0, "0",PCB); } if (errornumber == 112) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("Wrong combinations of actions",112); MEMORY.memory("DUMP", 0, "0",PCB); LOADER.readeachJob(); } if (errornumber == 140) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("Suspected Infinite Loop",140); MEMORY.memory("DUMP", 0, "0",PCB); LOADER.readeachJob(); } if (errornumber == 113) { errorcaseswrite("Unrecognizable Character Encountered while Loading",113); AvoidErrorJobs(); } if (errornumber == 114) { errorcaseswrite("Bad input file format: Extra characters detected.",114); AvoidErrorJobs(); } if (errornumber == 122) { errorcaseswrite("Warning : Bad Trace Flag.",122); } if (errornumber == 131) { errorcaseswrite("Missing The ** END record",131); AvoidErrorJobs(); } if (errornumber == 130) { errorcaseswrite("Missing The ** DATA record",130); AvoidErrorJobs(); } if (errornumber == 132) { errorcaseswrite("Missing The ** JOB record",132); AvoidErrorJobs(); } if (errornumber == 133) { errorcaseswrite("Missing Data for Job",133); AvoidErrorJobs(); } if (errornumber == 134) { errorcaseswrite("Missing Job",134); AvoidErrorJobs(); } if (errornumber == 135) { errorcaseswrite("NULL JOB",135); AvoidErrorJobs(); } if (errornumber == 141) { errorcaseswrite("Illegal Input",141); AvoidErrorJobs(); } if (errornumber == 142) { errorcaseswrite("Program too Long",142); AvoidErrorJobs(); } if (errornumber == 143) { errorcaseswrite("Missing/Unrecognizable Trace Bit",143); AvoidErrorJobs(); } if (errornumber == 150) { SCHEDULER.ReadyQueue.remove(0); errorcaseswrite("Insufficient Output Space",150); MEMORY.memory("DUMP", 0, "0",PCB); LOADER.readeachJob(); } } public void errorcaseswrite(String msg,int id) { try{ SYSTEM.writeProgressFile= new FileWriter("ProgressFile", true); SYSTEM.writeProgressFile.write("Error Message"+msg); SYSTEM.writeProgressFile.write(System.lineSeparator()); SYSTEM.writeProgressFile.write("ErrorID"+id); SYSTEM.writeProgressFile.write(System.lineSeparator()); SYSTEM.writeProgressFile.write("Bad Trace Flag"+msg); int count=0; if(id==104) { SYSTEM.writeProgressFile.write("Unrecognizable Character Encountered"); SYSTEM.writeProgressFile.write(System.lineSeparator()); count++; } if(id==104 && count==1) { SYSTEM.writeProgressFile.write(""); count++; } SYSTEM.writeProgressFile.close(); } catch(Exception e) { } } public static void AvoidErrorJobs() { LOADER.jobid=LOADER.jobid+1; try { String sCurrentLine; int k=0; SYSTEM.br.reset(); while ((sCurrentLine = SYSTEM.br.readLine())!=null) { if(sCurrentLine.isEmpty()) { LOADER.PCBCheckFlag="true"; LOADER.initialline=0; LOADER.count=0; LOADER.DataLinesCount=0; LOADER.LoaderLinesCount=0; LOADER.initialline=0; LOADER.count=0; LOADER.StoreLines.clear(); LOADER.FilePointer=0; LOADER.readeachJob(); } k=k+1; } } catch(Exception e) { } } }
true
12f9fc854d1d2a2ba98d60bddd761dcf2a1bf89b
Java
feinoah/xueqiao-trade
/trade_hosting_apps/trade_hosting_position_fee/server/src/main/java/xueqiao/trade/hosting/position/fee/msgbus/handler/IMessageHandler.java
UTF-8
238
1.757813
2
[]
no_license
package xueqiao.trade.hosting.position.fee.msgbus.handler; import org.soldier.framework.message_bus.api.IMessageConsumer; public interface IMessageHandler<E> { void onInit(); IMessageConsumer.ConsumeResult onHandle(E event); }
true
4207b7238a5be2de93f184d47c9bf719832620ce
Java
vcote331/Tp2
/P1.java
UTF-8
3,422
2.859375
3
[]
no_license
import java.util.concurrent.TimeoutException; import com.rabbitmq.client.*; import java.io.IOException; import java.util.*; import java.awt.*; import java.io.*; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; public class P1 { public static void main(String[] argv) throws Exception { String EXCHANGE_NAME = "echangeur_topic02"; String NOM_FILE_DATTENTE = "file_d_attente02"; String cleDeLiaison = "log.message" ; // cle de liaison/routage du message String nomUtilisateur = "guest"; // par defaut String motDePasse = "guest"; // par defaut int numeroPort = 5672; // par defaut String virtualHostName = "/"; // par defaut String hostName = "localhost"; //String hostName = "192.168.183.129"; boolean durable = true; boolean passive = true; // a true, on suppose que l'echangeur existe // deja boolean autoDelete = false; // ne pas supprimer l'echangeur lorsqu'aucun // client n'est connecte boolean exclusive = false; // se connecter au broker RabbitMQ ConnectionFactory factory = new ConnectionFactory(); // indiquer les parametres de la connexion factory.setUsername(nomUtilisateur); factory.setPassword(motDePasse); factory.setPort(numeroPort); factory.setVirtualHost(virtualHostName); factory.setHost(hostName); // autre alternative pour specifier les parametres de la connexion // factory.setUri("amqp://nomUtilisateur:motDePasse@hostName:numeroPort/virtualHostName"); // creer une nouvelle connexion Connection connexion; try { connexion = factory.newConnection(); // ouvrir un canal de communication avec le Broker pour l'envoi et la reception de messages Channel canalDeCommunication = connexion.createChannel(); // declarer un echangeur de type topic canalDeCommunication.exchangeDeclare(EXCHANGE_NAME, "topic", passive, durable, autoDelete, null); canalDeCommunication.queueDeclare(NOM_FILE_DATTENTE , durable, exclusive, autoDelete, null); canalDeCommunication.queueBind(NOM_FILE_DATTENTE, EXCHANGE_NAME, cleDeLiaison); canalDeCommunication.basicQos(1); // message a envoyer String message = "Salut tout le monde!"; for (int i = 0; i < argv.length; i++){ // envoyer le message //argv[i].getBytes("UTF-8"); a la place de messag.getbyte if (argv[i].equals("-t") && argv.length > i+1){ canalDeCommunication.basicPublish("", NOM_FILE_DATTENTE, null, argv[i + 1].getBytes("UTF-8")); System.out.println(" - Le texte :'" + argv[i + 1].toString() + "' est envoye avec succes!"); } else if (argv[i].equals("-i") && argv.length > i+1){ canalDeCommunication.basicPublish("", "file_d_attente03", null, argv[i + 1].getBytes("UTF-8")); System.out.println(" - Limage à été envoye avec succes!"); } } // fermer le canal canalDeCommunication.close(); // fermer la connexion connexion.close(); } catch (TimeoutException e) { e.printStackTrace(); } } }
true
bc739799c6802266c90d040eac103758ba2dc2b5
Java
sapei/schedoscope
/schedoscope-export/src/main/java/org/schedoscope/export/kafka/avro/HCatToAvroRecordConverter.java
UTF-8
8,212
2.328125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2016 Otto (GmbH & Co KG) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.schedoscope.export.kafka.avro; import com.fasterxml.jackson.databind.JsonNode; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.hive.hcatalog.data.HCatRecord; import org.schedoscope.export.utils.HCatRecordJsonSerializer; import org.schedoscope.export.utils.HCatUtils; import java.io.IOException; import java.util.*; /** * This class converts an HCatRecord to an AvroRecord. It uses the Avro schema * to recursively construct the record, requesting the fields from the JsonNode * as needed. */ public class HCatToAvroRecordConverter { private HCatRecordJsonSerializer serializer; private Set<String> anonFields; private String salt; /** * Create a new record converter instance, pass in a json serializer and a * list with field names to anonymize. * * @param serializer A Json serializer * @param anonFields A list with fields to anonymize * @param salt An optional salt to use when anonymizing fields */ public HCatToAvroRecordConverter(HCatRecordJsonSerializer serializer, Set<String> anonFields, String salt) { this.serializer = serializer; this.anonFields = anonFields; this.salt = salt; } /** * Create a new record converter instance, pass in a json serializer. * * @param serializer A Json serializer. */ public HCatToAvroRecordConverter(HCatRecordJsonSerializer serializer) { this.serializer = serializer; this.anonFields = new HashSet<String>(0); this.salt = ""; } /** * This function converts an HCatRecord to an Avro GenericRecord. * * @param hcatRecord The HCatRecord * @param avroSchema The Avro Schema * @return Returns an Avro GenericRecord * @throws IOException Is thrown if an error occurs */ public GenericRecord convert(HCatRecord hcatRecord, Schema avroSchema) throws IOException { JsonNode json = serializer.getRecordAsJson(hcatRecord); GenericRecord avroRecord = convertRecord(json, avroSchema); return avroRecord; } private GenericRecord convertRecord(JsonNode json, Schema schema) throws IOException { GenericRecordBuilder builder = new GenericRecordBuilder(schema); List<Field> fields = schema.getFields(); if (!json.isNull()) { for (Field f : fields) { for (Schema s : f.schema().getTypes()) { if (s.getType().equals(Schema.Type.STRING)) { builder.set(f.name(), HCatUtils.getHashValueIfInList( f.name(), json.get(f.name()).asText(), anonFields, salt)); } else if (s.getType().equals(Schema.Type.INT)) { builder.set(f.name(), json.get(f.name()).asInt()); } else if (s.getType().equals(Schema.Type.LONG)) { builder.set(f.name(), json.get(f.name()).asLong()); } else if (s.getType().equals(Schema.Type.BOOLEAN)) { builder.set(f.name(), json.get(f.name()).asBoolean()); } else if (s.getType().equals(Schema.Type.DOUBLE)) { builder.set(f.name(), json.get(f.name()).asDouble()); } else if (s.getType().equals(Schema.Type.FLOAT)) { builder.set(f.name(), json.get(f.name()).asDouble()); } else if (s.getType().equals(Schema.Type.RECORD)) { builder.set(f.name(), convertRecord(json.get(f.name()), s)); } else if (s.getType().equals(Schema.Type.ARRAY)) { builder.set(f.name(), convertArray(json.get(f.name()), s)); } else if (s.getType().equals(Schema.Type.MAP)) { builder.set(f.name(), convertMap(json.get(f.name()), s)); } } } } return builder.build(); } private Map<String, Object> convertMap(JsonNode json, Schema schema) throws IOException { Map<String, Object> res = new HashMap<>(); Iterator<Map.Entry<String, JsonNode>> it = json.fields(); while (it.hasNext()) { Map.Entry<String, JsonNode> n = it.next(); if (!n.getValue().isNull()) { for (Schema s : schema.getValueType().getTypes()) { if (s.getType().equals(Schema.Type.STRING)) { res.put(n.getKey(), n.getValue().asText()); } else if (s.getType().equals(Schema.Type.INT)) { res.put(n.getKey(), n.getValue().asInt()); } else if (s.getType().equals(Schema.Type.LONG)) { res.put(n.getKey(), n.getValue().asLong()); } else if (s.getType().equals(Schema.Type.BOOLEAN)) { res.put(n.getKey(), n.getValue().asBoolean()); } else if (s.getType().equals(Schema.Type.DOUBLE)) { res.put(n.getKey(), n.getValue().asDouble()); } else if (s.getType().equals(Schema.Type.FLOAT)) { res.put(n.getKey(), n.getValue().asDouble()); } else if (s.getType().equals(Schema.Type.RECORD)) { res.put(n.getKey(), convertRecord(n.getValue(), s)); } else if (s.getType().equals(Schema.Type.ARRAY)) { res.put(n.getKey(), convertArray(n.getValue(), s)); } else if (s.getType().equals(Schema.Type.MAP)) { res.put(n.getKey(), convertMap(n.getValue(), s)); } } } } return res; } private List<Object> convertArray(JsonNode json, Schema schema) throws IOException { List<Object> res = new ArrayList<>(); Iterator<JsonNode> it = json.elements(); while (it.hasNext()) { JsonNode n = it.next(); if (!n.isNull()) { for (Schema s : schema.getElementType().getTypes()) { if (s.getType().equals(Schema.Type.STRING)) { res.add(n.asText()); } else if (s.getType().equals(Schema.Type.INT)) { res.add(n.asInt()); } else if (s.getType().equals(Schema.Type.LONG)) { res.add(n.asLong()); } else if (s.getType().equals(Schema.Type.BOOLEAN)) { res.add(n.asBoolean()); } else if (s.getType().equals(Schema.Type.DOUBLE)) { res.add(n.asDouble()); } else if (s.getType().equals(Schema.Type.FLOAT)) { res.add(n.asDouble()); } else if (s.getType().equals(Schema.Type.RECORD)) { res.add(convertRecord(n, s)); } else if (s.getType().equals(Schema.Type.ARRAY)) { res.addAll(convertArray(n, s)); } else if (s.getType().equals(Schema.Type.MAP)) { res.add(convertMap(n, s)); } } } } return res; } }
true
27f38f68374e014dba8ea934c5e82adc99d916eb
Java
Akshansh986/Suzik
/suzik/src/main/java/com/blackMonster/suzik/musicstore/infoFromOtherPlayers/ExceptionUnknownBroadcast.java
UTF-8
377
1.96875
2
[]
no_license
package com.blackMonster.suzik.musicstore.infoFromOtherPlayers; import static com.blackMonster.suzik.util.LogUtils.LOGE; public class ExceptionUnknownBroadcast extends Exception { /** * */ private static final long serialVersionUID = 1L; @Override public void printStackTrace() { LOGE("UnknownBroadcast", "UnknownBroadcast"); super.printStackTrace(); } }
true
560a4a253bd4de5d0aa8508b783d5cb6e14c53b9
Java
nobun-com/tgc-server
/src/main/java/com/go2/classes/data/repository/jpa/AdminJpaRepository.java
UTF-8
302
1.859375
2
[]
no_license
package com.go2.classes.data.repository.jpa; import org.springframework.data.repository.PagingAndSortingRepository; import com.go2.classes.models.jpa.AdminEntity; public interface AdminJpaRepository extends PagingAndSortingRepository<AdminEntity, Long> { AdminEntity findByEmail(String email); }
true
db37c52ec077f666cce71c335a42a3833843415f
Java
lpyx/wxgit
/src/main/java/com/hbase/HBaseTest.java
UTF-8
2,272
2.546875
3
[]
no_license
package com.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.List; public class HBaseTest { static Configuration conf= HBaseConfiguration.create(); { conf.set("hbase.zookeeper.quorum","master"); //hbase 服务地址 conf.set("hbase.zookeeper.property.clientPort","2181"); //端口号 } public static void main(String[] args) { testGet(); } static void testGet(){ Table htable = null; try{ Connection conn = ConnectionFactory.createConnection(conf); TableName tableName = TableName.valueOf("testtable"); htable = conn.getTable(tableName); Get get = new Get("row1".getBytes()); get.addFamily("fam1".getBytes()); // get.addColumn(Bytes.toBytes("fam1")) Result result = htable.get(get); System.out.println(result); }catch (Exception ex){ ex.printStackTrace(); }finally { try{ htable.close(); }catch (Exception e){ e.printStackTrace(); } } } static void testPut(){ Table htable = null; try { Connection conn = ConnectionFactory.createConnection(conf); TableName tableName = TableName.valueOf("testtable"); htable = conn.getTable(tableName); Put put = new Put("row1".getBytes()); // put.addColumn("fam1".getBytes(),"column1".getBytes(),"value1".getBytes()); // put.addColumn("fam1".getBytes(),"column2".getBytes(),"value2".getBytes()); List<Cell> cells = put.get("fam1".getBytes(),"column1".getBytes()); htable.put(put); System.out.println("添加成功"); } catch (IOException e) { e.printStackTrace(); }finally { try { htable.close(); } catch (IOException e) { e.printStackTrace(); } } } }
true
57b2d93e5a83bfed15d4968f358ab6d79bb136b5
Java
mohamedjavith/java-student-result
/WebContent/examresult.java
UTF-8
1,505
2.390625
2
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; 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 ajaxprojectdbconnection.connectiondb; /** * Servlet implementation class examresult */ @WebServlet("/examresult") public class examresult extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { Connection con = connectiondb.initializeDatabase(); PreparedStatement st = con.prepareStatement("select * from results where sid=?"); st.setInt(1, Integer.valueOf(request.getParameter("sid"))); ResultSet rs = st.executeQuery(); out.println("<tr><td><b>Subject Code</b><td><b>Mark</b><td><b>Result</b></td></tr>"); while(rs.next()) { String subjectcode = rs.getString("subjectcode"); int mark = rs.getInt("mark"); String result = rs.getString("result"); out.println("<tr><td>"+subjectcode+"<td>"+mark+"<td>"+result+"</td></tr>"); } } catch (Exception e) { e.printStackTrace(); } } }
true
5e9b757769425e4ebb71a6370ef0c1e444c51fb0
Java
nysenate/BillBuzz
/src/main/java/gov/nysenate/billbuzz/disqus/DisqusCursor.java
UTF-8
1,287
2.296875
2
[]
no_license
package gov.nysenate.billbuzz.disqus; public class DisqusCursor { private String prev; private String next; private boolean hasNext; private boolean hasPrev; private Integer total; private String id; private boolean more; public DisqusCursor() {} public boolean hasMore() { return more; } public void setMore(boolean more) { this.more = more; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public boolean getHasPrev() { return hasPrev; } public void setHasPrev(boolean hasPrev) { this.hasPrev = hasPrev; } public boolean getHasNext() { return hasNext; } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } public String getNext() { return next; } public void setNext(String next) { this.next = next; } public String getPrev() { return prev; } public void setPrev(String prev) { this.prev = prev; } }
true
ef989c449458e27ec8d37297333e05019177f203
Java
Doanquyptit/Java_springboot_vnhealthservicemogo
/src/main/java/demo/service/ServiceFactory.java
UTF-8
1,413
2.296875
2
[]
no_license
package demo.service; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ServiceFactory implements ApplicationContextAware { private static ApplicationContext applicationContext; private static HoSoBenhAnReponsitory ho_so_banh_anService; private static BenhNhanService benhNhanService; private static CoSoKhamBenhReponsitory co_so_kham_benhService; @Override public void setApplicationContext(ApplicationContext applicationContext) { ServiceFactory.applicationContext = applicationContext; } public static HoSoBenhAnReponsitory getHo_so_banh_anModel(){ if(ho_so_banh_anService ==null){ ho_so_banh_anService = applicationContext.getBean(HoSoBenhAnReponsitory.class); } return ho_so_banh_anService; } public static BenhNhanService getBenhNhanService(){ if(benhNhanService ==null){ benhNhanService = applicationContext.getBean(BenhNhanService.class); } return benhNhanService; } public static CoSoKhamBenhReponsitory getCo_so_kham_benhService(){ if(co_so_kham_benhService == null){ co_so_kham_benhService = applicationContext.getBean(CoSoKhamBenhReponsitory.class); } return co_so_kham_benhService; } }
true
a51ee416878f3f4c5b6a9d9b38af709cdf59cb07
Java
bellmit/yuanhan-framework
/saas-core/src/main/java/com/zhjs/saas/core/web/BootServletInitializer.java
UTF-8
897
1.875
2
[]
no_license
package com.zhjs.saas.core.web; import javax.servlet.ServletContext; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.web.context.WebApplicationContext; import com.zhjs.saas.core.event.ApplicationBootedEvent; import com.zhjs.saas.core.event.EventDispatcher; import com.zhjs.saas.core.util.ApplicationContextUtil; /** * * @author: Jackie Wang * @since: 2017-10-16 * @modified: 2017-10-16 * @version: */ public abstract class BootServletInitializer extends SpringBootServletInitializer { protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { WebApplicationContext application = super.createRootApplicationContext(servletContext); ApplicationContextUtil.setApplicationContext(application); EventDispatcher.dispatchEvent(new ApplicationBootedEvent(application)); return application; } }
true
0058bc93914f880b93f77f69d3c600868d215356
Java
zhhangao/mapApp
/mapApp/src/main/java/com/example/demo/UserMapper.java
UTF-8
2,470
2.1875
2
[]
no_license
package com.example.demo; import java.util.List; public interface UserMapper { int insertUser(User user); int deleteUser(Integer id); User selectUser(Integer id); int updateUser(User user); List<User> selectAll(); //记录我的位置的操作 int insertMyTargetPosition(myPosition mP); //查看位置表里有多少条数据 int selectCountOfPos(); //查询相同的天里位置的信息 List<Day> selectTheDay(); List<myPosition>selectThePositionLine(String Day); List<myPosition>selectTheAllPositionRecord(); List<myPosition>selectTheOnePositionRecord(Integer UserID,Integer ConcreteID); //查看有多少条轨迹记录信息 int selectCountOfMyTraceID(); //插入我所记录的轨迹的每一时刻的经纬度信息 int insertMyPerTimeTrace(myPerTrace mP); //查看其中一条路径的信息 List<myPerTrace>selectTheConcreteTrace(Integer TraceID); //取得每一条路径的第一个时间采样点的信息 List<myPerTrace>selectTheFirstTimeTrace(); //判断管理用户的登录信息 ManageUser searchManageUserInfo(String UserName,String UserPassword); //删除所记录的位置信息 int deleteMyPosition(Integer RecordID); //更改主键信息 int updateRecordID(); //删除轨迹点的操作 int deleteMyTrace(Integer TraceID); //更改TraceID的操作 int updateTraceID(Integer TraceID); //实现多用户的操作 int selectIfExitTheOpenID(String OpenID); int selectTheUserID(String OpenID); int selectTheCountOfUser(); //查找单用户的位置记录信息 List<myPosition>selectForUserPositionRecord(Integer UserID); //查看一个用户下它有多少条轨迹 int selectTheCountOfOneUserPosition(Integer UserID); //更改RecordForUserID int updateRecordForUserID(Integer ConcreteID); //查找该条信息的ConcreteID int selectTheConcreteID(Integer UserID,Integer RecordID); //给管理者写的查询某一具体路径的方法 List<myPosition>selectTheForManagerConcretePos(Integer RecordID); //插入聊天信息 int insertMyChatContent(chatContent content); //返回聊天记录数量 int selectTheCountOfChat(); //返回聊天列表信息 List<chatContent>selectTheChatContent(); //删除消息列表里的消息 int deleteTheChatMessage(Integer RecordID); //更改主键信息 int updateChatMessageRecordID(); }
true
781c2438f58b23fe845623e3c6489ec72cce5a08
Java
JDwu1120/iot_cloud
/api_gateway/src/main/java/com/iot/nero/api_gateway/core/core/ApiGatewayHandler.java
UTF-8
14,170
1.554688
2
[ "MIT" ]
permissive
package com.iot.nero.api_gateway.core.core; import com.alibaba.dubbo.common.json.ParseException; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.iot.nero.api_gateway.common.Debug; import com.iot.nero.api_gateway.common.IOUtils; import com.iot.nero.api_gateway.common.NetUtil; import com.iot.nero.api_gateway.common.UtilJson; import com.iot.nero.api_gateway.core.CONSTANT; import com.iot.nero.api_gateway.core.doc.ApiDoc; import com.iot.nero.api_gateway.core.exceptions.*; import com.iot.nero.api_gateway.core.firewall.entity.Admin; import com.iot.nero.api_gateway.core.firewall.AdminAuth; import com.iot.nero.api_gateway.core.firewall.IpTables; import com.iot.nero.api_gateway.core.log.entity.ApiLog; import com.iot.nero.api_gateway.core.log.entity.Log; import com.iot.nero.api_gateway.core.mock.Entity.ApiMock; import com.iot.nero.api_gateway.core.mock.Mock; import com.iot.nero.api_gateway.core.trafficmanage.DataTrafficManage; import com.iot.nero.utils.spring.PropertyPlaceholder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import sun.security.util.Length; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Author neroyang * Email nerosoft@outlook.com * Date 2017/8/25 * Time 下午12:41 */ public class ApiGatewayHandler implements InitializingBean, ApplicationContextAware { private static final Logger logger = LoggerFactory.getLogger(ApiGatewayHandler.class); private static final String METHOD = "method"; private static final String PARAMS = "params"; private static final String SYS_PARAMS = "sysParams"; private static String TRAFFIC_OPEN = PropertyPlaceholder.getProperty("trafficManager.isOpen").toString(); private static String TRAFFIC_AVG = PropertyPlaceholder.getProperty("trafficManager.avgFlow").toString(); private static String TRAFFIC_MAX = PropertyPlaceholder.getProperty("trafficManager.maxPool").toString(); private static String MOCK_OPEN = PropertyPlaceholder.getProperty("mock.isOpen").toString(); private static String IP_TABLE_OPEN = PropertyPlaceholder.getProperty("ipTable.isOpen").toString(); public static void setIpTableOpen(String ipTableOpen) { IP_TABLE_OPEN = ipTableOpen; } public static void setTrafficOpen(String trafficOpen) { TRAFFIC_OPEN = trafficOpen; } public static void setTrafficAvg(String trafficAvg) { TRAFFIC_AVG = trafficAvg; } public static void setTrafficMax(String trafficMax) { TRAFFIC_MAX = trafficMax; } public static void setMockOpen(String mockOpen) { MOCK_OPEN = mockOpen; } public static String getIpTableOpen() { return IP_TABLE_OPEN; } public static String getTrafficOpen() { return TRAFFIC_OPEN; } public static String getTrafficAvg() { return TRAFFIC_AVG; } public static String getTrafficMax() { return TRAFFIC_MAX; } public static String getMockOpen() { return MOCK_OPEN; } private ApiDoc apiDoc; private IpTables ipTables; private AdminAuth adminAuth; ApiStore apiStore; final ParameterNameDiscoverer parameterNameDiscoverer; DataTrafficManage tokenBucket; public ApiGatewayHandler() { parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); tokenBucket = DataTrafficManage.newBuilder().avgFlowRate(Integer.valueOf(TRAFFIC_AVG)).maxFlowRate(Integer.valueOf(TRAFFIC_MAX)).build(); apiDoc = new ApiDoc(); ipTables = new IpTables(); adminAuth = new AdminAuth(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { apiStore = new ApiStore(applicationContext, parameterNameDiscoverer); } public void afterPropertiesSet() throws Exception { apiStore.loadApiFromSpringBeans(); } public void handle(HttpServletRequest request, HttpServletResponse response) { Gson gson = new Gson(); Date date = new Date(); String method = request.getParameter(METHOD); String params = request.getParameter(PARAMS); String sysParams = request.getParameter(SYS_PARAMS); Object result; ApiStore.ApiRunnable apiRunnable = null; try { if ("yes".equals(TRAFFIC_OPEN)) { boolean tokens = tokenBucket.getTokens("a".getBytes()); if (!tokens) { throw new FlowOverException(CONSTANT.FLOW_OVER); } } logger.info(gson.toJson(new Log(0001, new ApiLog(NetUtil.getRealIP(request), method, params, sysParams, request.getRequestURL().toString()), date.getTime()))); if ("yes".equals(IP_TABLE_OPEN)) { ipTables.filter(request, response); } paramsValdate(request); if ("sys".equals(method.subSequence(0, 3))) { sysParamsValid(request); adminAuth.auth(sysParams); if ("sys.doc".equals(method)) { result = apiDoc.getApis(apiStore.findApiRunnables()); } else { apiRunnable = sysParamsValdate(request); Object[] args = buildParams(apiRunnable, params, request, response); result = apiRunnable.run(args); } } else { apiRunnable = sysParamsValdate(request); if ("yes".equals(MOCK_OPEN)) { Mock mock = new Mock(); result = mock.run(apiRunnable); } else { Object[] args = buildParams(apiRunnable, params, request, response); result = apiRunnable.run(args); } } } catch (ApiException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (IllegalAccessException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (InvocationTargetException e) { response.setStatus(500); result = handleErr(e.getTargetException()); } catch (AuthFailedException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (IOException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (IPNotAccessException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (MockApiNotFoundException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (JsonSyntaxException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (FlowOverException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } catch (InstantiationException e) { response.setStatus(500); result = handleErr(e.fillInStackTrace()); } returnResult(result, response); } private void sysParamsValid(HttpServletRequest request) throws ApiException { String sysParams = request.getParameter(SYS_PARAMS); if (sysParams == null || "".equals(sysParams)) { throw new ApiException("调用失败,参数 " + SYS_PARAMS + " 为空"); } } private Object handleErr(Throwable e) { String code = ""; String message = ""; if (e instanceof ApiException) { code = "0001"; message = e.getMessage(); } else if (e instanceof FlowOverException) { code = "0002"; message = e.getMessage(); e.printStackTrace(); } else if (e instanceof IPNotAccessException) { code = "0003"; message = e.getMessage(); e.printStackTrace(); } else { code = "0004"; message = e.getMessage(); e.printStackTrace(); } Map<String, Object> result = new HashMap<String, Object>(); result.put("error", code); result.put("msg", message); //ByteArrayOutputStream out = new ByteArrayOutputStream(); //PrintStream stream = new PrintStream(out); //e.printStackTrace(stream); //result.put("track", e.getStackTrace()); return result; } private void paramsValdate(HttpServletRequest request) throws ApiException { String apiName = request.getParameter(METHOD); String json = request.getParameter(PARAMS); if (apiName == null || "".equals(apiName)) { throw new ApiException("调用失败,参数 'method' 为空"); } else if (json == null || "".equals(json)) { throw new ApiException("调用失败," + "参数 'params' 为空"); } } private ApiStore.ApiRunnable sysParamsValdate(HttpServletRequest request) throws ApiException { String apiName = request.getParameter(METHOD); ApiStore.ApiRunnable apiRunnable; paramsValdate(request); if ((apiRunnable = apiStore.findApiRunnable(apiName)) == null) { throw new ApiException("调用失败:指定API不存在,API:" + apiName); } return apiRunnable; } private Object[] buildParams(ApiStore.ApiRunnable apiRunnable, String params, HttpServletRequest request, HttpServletResponse response) throws ApiException { Map<String, Object> map = null; try { map = UtilJson.toMap(params); } catch (IllegalArgumentException e) { throw new ApiException("调用失败:JSON字符串格式化失败,请检查params参数"); } catch (ParseException e) { throw new ApiException("调用失败:JSON字符串toMap失败,请检查params参数"); } logger.error("________________MAP : " + map.toString()); if (map == null) { map = new HashMap<String, Object>(); } Method method = apiRunnable.getTargetMethod(); List<String> paramsNames = Arrays.asList(parameterNameDiscoverer.getParameterNames(method)); logger.error("_______________NAMES : " + paramsNames.toString()); Class<?>[] paramType = method.getParameterTypes(); for (Map.Entry<String, Object> m : map.entrySet()) { if (!paramsNames.contains(m.getKey())) { throw new ApiException("调用失败,接口 '" + apiRunnable.getApiName() + "' 对应方法 '" + method.getName() + "' 不存在 '" + m.getKey() + "' 参数"); } } Object[] args = new Object[paramType.length]; for (int i = 0; i < paramType.length; i++) { if (paramType[i].isAssignableFrom(HttpServletRequest.class)) { args[i] = request; } else if (map.containsKey(paramsNames.get(i))) { try { args[i] = convertJsonToBean(map.get(paramsNames.get(i)), paramType[i]); } catch (Exception e) { throw new ApiException("调用失败:指定参数格式错误或值错误 '" + paramsNames.get(i) + "' :" + e.getMessage()); } } else { args[i] = null; } } logger.error("__________ARGS : " + args.toString()); return args; } private <T> Object convertJsonToBean(Object val, Class<?> targetClass) { Object result = null; if (val == null) { return null; } else if (Integer.class.equals(targetClass)) { result = Integer.parseInt(val.toString()); } else if (Long.class.equals(targetClass)) { result = Long.parseLong(val.toString()); } else if (Date.class.equals(targetClass)) { if (val.toString().matches("[0-9]+")) { result = new Date(Long.parseLong(val.toString())); } else { throw new IllegalArgumentException("日期必须是长整型的时间戳"); } } else if (String.class.equals(targetClass)) { if (val instanceof String) { result = val; } else { throw new IllegalArgumentException("转换目标类型为字符串"); } } else { result = UtilJson.convertValue(val, targetClass); } return result; } private void returnResult(Object result, HttpServletResponse response) { try { UtilJson.JSON_MAPPER.configure( SerializationFeature.WRITE_NULL_MAP_VALUES, true); Map<String, Object> returnResult = new HashMap<String, Object>(); returnResult.put("code", 1000); returnResult.put("data", result); String json = UtilJson.writeValueAsString(returnResult); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html/json;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); if (json != null) { response.getWriter().write(json); } } catch (IOException e) { throw new RuntimeException(e); } } }
true
cd5a9d6b2ddd26bf1d1eb1688dafcf79ae45bfd5
Java
SabreOSS/yare
/yare-core/src/main/java/com/sabre/oss/yare/core/reference/ChainedTypeExtractor.java
UTF-8
4,782
2.421875
2
[ "MIT", "Apache-2.0" ]
permissive
/* * MIT License * * Copyright 2018 Sabre GLBL Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.sabre.oss.yare.core.reference; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ChainedTypeExtractor { private static final ConcurrentMap<Type, ConcurrentMap<String, Type>> typeCache = new ConcurrentHashMap<>(); public Type findPathType(Type type, String path) { String[] pathParts = path.split("\\.", -1); Type currentType = type; Iterator<String> iterator = Arrays.asList(pathParts).iterator(); while (iterator.hasNext()) { String pathPart = iterator.next(); Type finalCurrentType = currentType; currentType = typeCache .computeIfAbsent(currentType, k -> new ConcurrentHashMap<>()) .computeIfAbsent(pathPart, s -> computeTypeFromProperty(finalCurrentType, s)); if (iterator.hasNext() && isCollection(currentType)) { return List.class; } } return currentType; } private Type computeTypeFromProperty(Type type, String pathPart) { return computeTypeOfReference(unwrapCollectionType(type), pathPart.replace("[*]", "")); } private Type unwrapCollectionType(Type type) { return isCollection(type) ? getTypeOfElementInList(type) : type; } private boolean isCollection(Type type) { return type instanceof ParameterizedType && Collection.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType()); } private Type getTypeOfElementInList(Type listType) { return ((ParameterizedType) listType).getActualTypeArguments()[0]; } private Type computeTypeOfReference(Type type, String pathPart) { Optional<Type> map = extractMapType(type); if (map.isPresent()) { return map.get(); } Optional<Type> field = extractFieldType((Class<?>) type, pathPart); if (field.isPresent()) { return field.get(); } Optional<Type> method = extractMethodType((Class<?>) type, pathPart); if (method.isPresent()) { return method.get(); } throw new InvalidPathException(); } private Optional<Type> extractMapType(Type type) { return Optional.of(type) .map(Class.class::cast) .filter(Map.class::isAssignableFrom) .map(Class::getGenericSuperclass) .filter(ParameterizedType.class::isInstance) .map(ParameterizedType.class::cast) .map(p -> p.getActualTypeArguments()[1]); } private Optional<Type> extractFieldType(Class<?> type, String fieldName) { return Arrays.stream(type.getFields()) .filter(f -> Modifier.isPublic(f.getModifiers())) .filter(f -> f.getName().equals(fieldName)) .map(Field::getGenericType) .findFirst(); } private Optional<Type> extractMethodType(Class<?> type, String fieldName) { return Arrays.stream(type.getMethods()) .filter(m -> m.getParameterCount() == 0) .filter(m -> (m.getName().equals("get" + capitalize(fieldName)) || m.getName().equals("is" + capitalize(fieldName)))) .map(Method::getGenericReturnType) .findFirst(); } private String capitalize(String fieldName) { return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } public static class InvalidPathException extends RuntimeException { } }
true
5728f7506b5b58f4f60ad89c75f9d1f72ae54e1c
Java
davidmoranoperez/eadmin-1
/src/test/java/es/fpdual/eadmin/eadmin/modelo/DocumentoTest.java
UTF-8
871
2.390625
2
[]
no_license
package es.fpdual.eadmin.eadmin.modelo; import static org.junit.Assert.assertTrue; import java.util.Date; import org.junit.Before; import org.junit.Test; public class DocumentoTest { private static final Date FECHA_CREACION = new Date(); private static final Date FECHA_ULTIMA_MOFICACION = new Date(); private static final String NOMBRE_DOCUMENTO = "nombre"; private static final Boolean DOCUMENTO_PUBLICO = true; private static final Integer CODIGO_DOCUMENTO = 1; private Documento doc1; @Before public void inicializarCadaTest() { doc1 = new Documento(CODIGO_DOCUMENTO, NOMBRE_DOCUMENTO, FECHA_CREACION,FECHA_ULTIMA_MOFICACION, DOCUMENTO_PUBLICO, EstadoDocumento.ACTIVO); } @Test public void comprobarGetter() { assertTrue(doc1.getPublico().equals(DOCUMENTO_PUBLICO)); assertTrue(doc1.getEstado().equals(EstadoDocumento.ACTIVO)); } }
true
4194d364903abd3092d625d8ce931c8670aa0c83
Java
abcd71974248/GZMQ
/mqxxgl/src/main/java/com/hotsun/mqxxgl/busi/service/BusiRetrofitHelper.java
UTF-8
3,568
2.09375
2
[]
no_license
package com.hotsun.mqxxgl.busi.service; import android.content.Context; import android.content.SharedPreferences; import com.hotsun.mqxxgl.R; import com.hotsun.mqxxgl.busi.model.ConditionText; import com.hotsun.mqxxgl.busi.model.FwLdxx; import com.hotsun.mqxxgl.busi.model.ResponseResults; import com.hotsun.mqxxgl.busi.model.sysbeans.TSysUsers; import com.hotsun.mqxxgl.busi.util.UIHelper; import com.hotsun.mqxxgl.gis.service.LiveNetworkMonitor; import com.hotsun.mqxxgl.gis.service.NetworkMonitor; import com.hotsun.mqxxgl.gis.util.ToastUtil; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.Response; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by li on 2017/5/5. * 初始化 Retrofit */ public class BusiRetrofitHelper { private Context mContext; private static NetworkMonitor networkMonitor; private static BusiRetrofitHelper instance = null; protected Retrofit mRetrofit = null; public static BusiRetrofitHelper getInstance(Context context){ if(instance == null){ instance = new BusiRetrofitHelper(context); networkMonitor=new LiveNetworkMonitor(context); } return instance; } protected BusiRetrofitHelper(Context ctx){ this.mContext = ctx; init(); } private void init(){ resetApp(); } private void resetApp() { SharedPreferences autoPreferences = mContext.getSharedPreferences("ipsetinfo", mContext.MODE_PRIVATE); String ip=autoPreferences.getString("ip",""); String port=autoPreferences.getString("port",""); String baseUrl="http://"+ip+":"+port+"/"; OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); // 看这里 !!! 我们添加了一个网络监听拦截器 /*okHttpClientBuilder.addInterceptor(chain -> { boolean connected = networkMonitor.isConnected(); if (networkMonitor.isConnected()) { return chain.proceed(chain.request()); } else { throw new NoNetworkException(); } });*/ okHttpClientBuilder.addNetworkInterceptor(new MyNetworkInterceptor()); okHttpClientBuilder.connectTimeout(5, TimeUnit.SECONDS); mRetrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClientBuilder.build()) .addConverterFactory( GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } // public Call<ResponseResults> getServer(String route){ // PostRoute postRoute=mRetrofit.create(PostRoute.class); // RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route); // Call<ResponseResults> call=postRoute.postFlyRoute(body); // return null; // } private class MyNetworkInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { if (networkMonitor.isConnected()) { return chain.proceed(chain.request()); } else { ToastUtil.setToast(mContext,"无网络连接,请检查网络"); } return null; } } }
true
93ff97f230542eb2dce609176396984ecb54fd11
Java
orlando26/jira-fake-ws
/src/main/java/com/jirafake/api/dto/ProjectDTO.java
UTF-8
800
2.546875
3
[]
no_license
package com.jirafake.api.dto; import com.jirafake.api.entity.Project; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ProjectDTO { private Integer id; private String name; private String description; @Builder public ProjectDTO(Integer id, String name, String description) { this.id = id; this.name = name; this.description = description; } public ProjectDTO(Project project) { this.id = project.getId(); this.name = project.getName(); this.description = project.getDescription(); } public Project toEntity() { return Project.builder() .id(id) .name(name) .description(description) .build(); } }
true
b025ecadd8a485bc8a797790d58324fb5f8a93b1
Java
LFengYe/WorkProject_v3.3
/DLPort/src/main/java/com/DLPort/myactivity/HuoInquireActivity.java
UTF-8
9,081
1.921875
2
[]
no_license
package com.DLPort.myactivity; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.DLPort.R; import com.DLPort.app.Constant; import com.DLPort.myadapter.huoInquireAdapter; import com.DLPort.mydata.HuoInquire; import com.DLPort.mytool.GlobalParams; import com.DLPort.mytool.MyHandler; import com.DLPort.mytool.MyThread; import com.DLPort.mytool.MyToast; import com.DLPort.myview.TitleView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/5/15. */ public class HuoInquireActivity extends BaseActivity { private String OrderId; private static final String TAG="HuoInquireActivity"; private List<HuoInquire> mlist = new ArrayList<HuoInquire>(); private TextView[] textViews; private ListView listView; private huoInquireAdapter adapter; private TextView delete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.huo_order_xiangqing); initTitle(); init(); } private MyHandler handler =new MyHandler(this) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { try { JSONObject jsonUser = new JSONObject((String) msg.obj); Log.d(TAG, "Login的响应" + jsonUser.toString()); int status = jsonUser.getInt("Status"); Log.i(TAG, "状态" + status); if (0 == status) { String data = jsonUser.getString("Data"); if (data.equals("[]")) { MyToast.makeText(HuoInquireActivity.this, "目前订单没被抢"); } else { display(data); } } else if (1 == status || -1 == status) { MyToast.makeText(HuoInquireActivity.this, "获取失败"); } } catch (JSONException e) { Log.d(TAG, "异常——————————————————————————————"); e.printStackTrace(); } } else { Log.i(TAG, "IO异常"); MyToast.makeText(HuoInquireActivity.this, "服务器连接异常"); } } }; private MyHandler handler1 =new MyHandler(this) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==1){ try { JSONObject jsonUser = null; jsonUser = new JSONObject((String) msg.obj); Log.d(TAG, jsonUser.toString()); int status = jsonUser.getInt("Status"); Log.d(TAG, jsonUser.getInt("Status") + jsonUser.getString("Message")); MyToast.makeText(HuoInquireActivity.this, jsonUser.getString("Message")); } catch (JSONException e) { e.printStackTrace(); } }else { MyToast.makeText(HuoInquireActivity.this, msg.what + " 服务器异常"); } } }; private void initTitle() { TitleView titleView = (TitleView) findViewById(R.id.xiangqing_title); titleView.setLeftViewVisible(true); titleView.setMiddleTextVisible(true); titleView.setRightTextVisible(true); titleView.setWineText(R.string.my_order); titleView.setRightText("刷新"); titleView.setMiddleText(R.string.order_par); View view =findViewById(R.id.title_back); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); titleView.setRightTextListenter(new View.OnClickListener() { @Override public void onClick(View v) { refreshData(); } }); } private void init() { textViews = new TextView[3]; textViews[0]= (TextView) findViewById(R.id.huo_Price); textViews[1] = (TextView) findViewById(R.id.huo_Remain); textViews[2] = (TextView) findViewById(R.id.huo_ChargeType); listView = (ListView) findViewById(R.id.huo_list); adapter = new huoInquireAdapter(this,R.layout.huo_details,mlist); listView.setAdapter(adapter); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); OrderId = bundle.getString("ID"); textViews[0].setText(bundle.getString("Price")); textViews[1].setText(bundle.getString("Amount")); if(bundle.getInt("ChargeType")==0){ textViews[2].setText("平台结算"); }else { textViews[2].setText("自行结算"); } delete = (TextView) findViewById(R.id.delete); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (GlobalParams.isNetworkAvailable(HuoInquireActivity.this)) { JSONObject json = new JSONObject(); try { json.put("Id", OrderId); new MyThread(Constant.URL_CargoOwnerPostRemove, handler1, json,HuoInquireActivity.this).start(); } catch (JSONException e) { e.printStackTrace(); } } else { MyToast.makeText(HuoInquireActivity.this, "请把数据补充完整!!"); } } }); getdata(); } public void refreshData() { mlist.clear(); adapter.notifyDataSetChanged(); getdata(); } public void getdata() { if (GlobalParams.isNetworkAvailable(HuoInquireActivity.this)) { JSONObject json = new JSONObject(); try { json.put("Cargoid", OrderId); Log.d(TAG, json.toString()); new MyThread(Constant.URL_GetOrderDetails, handler, json,HuoInquireActivity.this).start(); } catch (JSONException e) { e.printStackTrace(); } }else { Toast.makeText(HuoInquireActivity.this, "亲,请连接网络!!!", Toast.LENGTH_SHORT) .show(); } } private void display(String data){ try { JSONArray jsonArray = new JSONArray(data); Log.d(TAG, jsonArray.toString()); for (int i= 0 ;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String Principal =jsonObject.getString("Principal"); String CarNo = jsonObject.getString("CarNo"); String SuitCaseNo = jsonObject.getString("SuitCaseNo"); String Tel = jsonObject.getString("Tel"); String ChargeStatus="'"; String OrderStatus =""; int chargeStatusValue = jsonObject.getInt("ChargeStatus"); int orderStatusValue = jsonObject.getInt("OrderStatus"); switch (orderStatusValue) { case 0: OrderStatus = "进行中"; break; case 1: OrderStatus = "已完成"; break; case 2: OrderStatus = "申请取消"; break; case 3: OrderStatus = "已取消"; break; case 4: OrderStatus = "拒绝取消"; break; case 5: OrderStatus = "同意取消"; } switch (chargeStatusValue){ case 0: ChargeStatus="未结算"; break; case 1: ChargeStatus="已结算"; } String OrderId = jsonObject.getString("OrderId"); String PresentNumber = jsonObject.getString("PresentNumber"); String PutBoxID = jsonObject.getString("PutBoxID"); mlist.add(new HuoInquire(Principal,CarNo,SuitCaseNo,Tel,OrderStatus,ChargeStatus, OrderId, orderStatusValue, chargeStatusValue,PutBoxID,PresentNumber)); } } catch (JSONException e) { e.printStackTrace(); } adapter.notifyDataSetChanged(); } }
true
0d55e1b7d29c35a991c7c7eb82de1ab2dde4d3ca
Java
Aalvinkumar6001/bootprojectmanager
/src/main/java/com/iiht/finalbootapp/service/ProjectService.java
UTF-8
272
1.9375
2
[]
no_license
package com.iiht.finalbootapp.service; import java.util.List; import com.iiht.finalbootapp.model.Project; public interface ProjectService { public Project addProject(Project project); public List<Project> getProject(); public void deleteProject(Project project); }
true
1df9b495d4b59eacd744427318f4ce95c6476f17
Java
jajir/microcol
/microcol-game/src/main/java/org/microcol/model/unit/CanMount.java
UTF-8
862
2.234375
2
[]
no_license
package org.microcol.model.unit; import java.util.List; import java.util.function.Function; import org.microcol.model.AbstractUnit; import org.microcol.model.Model; import org.microcol.model.Place; import org.microcol.model.Player; import org.microcol.model.Unit; import com.google.common.collect.ImmutableList; public abstract class CanMount extends AbstractUnit { public CanMount(final Model model, final Integer id, final Function<Unit, Place> placeBuilder, final Player owner, final int actionPoints, final UnitAction unitAction) { super(model, id, placeBuilder, owner, actionPoints, unitAction); } @Override public boolean isShip() { return false; } protected List<UnitActionType> getSupportedActions() { return ImmutableList.of(UnitActionType.plowField, UnitActionType.noAction); } }
true
a250e937cc5004ad522b459897b340fa05a01920
Java
PhilipAnderson/flip
/software/java/server/src/main/java/flip/server/controllers/trialconfig/SingleResponseConfigController.java
UTF-8
3,189
1.960938
2
[]
no_license
package flip.server.controllers.trialconfig; import flip.common.entities.trial.config.TrialConfig; import flip.common.entities.trial.config.SingleResponseConfig; import flip.common.entities.trial.Delay; import javax.validation.Valid; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.PathVariable; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.stereotype.Controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; interface SingleResponseConfigRepository extends CrudRepository<SingleResponseConfig, Long> {} @Controller @RequestMapping("/config/single-response") public class SingleResponseConfigController { @Autowired TrialConfigRepository repository; @Autowired SingleResponseConfigRepository singleResponseConfigRepository; @GetMapping("/create") public String showCreateForm(SingleResponseConfig singleResponseConfig, Model model) { model.addAttribute("singleResponseConfig", singleResponseConfig); model.addAttribute("updating", false); return "config/forms/single-response"; } @GetMapping("/update/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { SingleResponseConfig config = singleResponseConfigRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Invalid Config Id: " + id)); model.addAttribute("singleResponseConfig", config); model.addAttribute("updating", true); return "config/forms/single-response"; } @PostMapping("/create") public String createConfig( @Valid SingleResponseConfig singleResponseConfig, BindingResult result, Model model) { if (result.hasErrors()) { model.addAttribute("updating", false); return "config/forms/single-response"; } repository.save(singleResponseConfig); return "redirect:/config"; } @PostMapping("/update/{id}") public String updateConfig( @PathVariable("id") long id, @Valid SingleResponseConfig singleResponseConfig, BindingResult result, Model model) { if (result.hasErrors()) { model.addAttribute("updating", true); return "config/forms/single-response"; } repository.save(singleResponseConfig); return "redirect:/config"; } }
true
52568a2adcfb7bcee8bd31840252f4658d885431
Java
painquin/Endgame
/src/minecraft_server/net/minecraft/src/TeleportHelper.java
UTF-8
1,511
2.15625
2
[]
no_license
package net.minecraft.src; import net.minecraft.server.MinecraftServer; import cpw.mods.fml.server.FMLServerHandler; public class TeleportHelper { public void dimensionalTeleportPlayer(EntityPlayer ent, int dim, double x, double y, double z) { EntityPlayerMP player = (EntityPlayerMP)ent; int currentDimension = player.dimension; MinecraftServer mcserver = FMLServerHandler.instance().getServer(); if (currentDimension != dim) { player.dimension = dim; WorldServer wOld = mcserver.getWorldManager(currentDimension); WorldServer wNew = mcserver.getWorldManager(dim); player.playerNetServerHandler.sendPacket( new Packet9Respawn(dim, (byte)player.worldObj.difficultySetting, wNew.getWorldInfo().getTerrainType(), wNew.getHeight(), player.itemInWorldManager.getGameType()) ); wOld.removePlayer(player); player.isDead = false; mcserver.configManager.joinNewPlayerManager(player); player.setLocationAndAngles(x, y, z, player.rotationYaw, player.rotationPitch); player.setWorld(wNew); player.itemInWorldManager.setWorld(wNew); mcserver.configManager.updateTimeAndWeather(player, wNew); mcserver.configManager.func_30008_g(player); // ? FMLServerHandler.instance().announceDimensionChange(player); } else { player.setLocationAndAngles(x, y, z, player.rotationYaw, player.rotationPitch); } player.playerNetServerHandler.teleportTo(player.posX, player.posY, player.posZ, player.rotationYaw, player.rotationPitch); } }
true
51329a675bee9ea52ddba4c409839d4c70947efa
Java
guancio/vectorpen
/src-ui/com/vectorpen/util/AwtWrapper.java
UTF-8
348
2.296875
2
[]
no_license
package com.vectorpen.ui.util; import com.vectorpen.core.util.Color; public class AwtWrapper { public static java.awt.Color convertColor(Color c) { return new java.awt.Color(c.getRed(), c.getGreen(), c.getBlue()); } public static Color importColor(java.awt.Color c) { return new Color(c.getRed(), c.getGreen(), c.getBlue()); } }
true
75691ba1636b949447f5725bf53c8f1d196d20a3
Java
lradomski/SageAkka
/src/main/java/com/tr/analytics/sage/akka/data/StartCalcSingleRic.java
UTF-8
1,619
2.546875
3
[]
no_license
package com.tr.analytics.sage.akka.data; import com.tr.analytics.sage.akka.data.serializers.SageSerializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class StartCalcSingleRic extends StartCalc implements SageSerializable { private final String ric; public StartCalcSingleRic(String calcName, String instanceName, int id, String ric) { this(calcName, instanceName, id, false, ric); } public StartCalcSingleRic(String calcName, String instanceName, int id, boolean isSnapshot, String ric) { super(calcName, instanceName, id, isSnapshot); this.ric = ric; } public StartCalcSingleRic(ObjectInputStream ois) throws IOException { super(ois); this.ric = ois.readUTF(); } @Override public void serialize(ObjectOutputStream oos) throws IOException { super.serialize(oos); oos.writeUTF(getRic()); } public String getRic() { return ric; } @Override public String toStringCore() { return super.toStringCore() + "/" + ric + ""; } public static StartCalcSingleRic fromFor(StartCalcMultiRic multiRic, int id, String ric) { return new StartCalcSingleRic(multiRic.getCalcName(), multiRic.getInstanceName(), id, ric); } @Override public boolean equals(Object obj) { if (obj instanceof StartCalcSingleRic) { StartCalcSingleRic other = (StartCalcSingleRic)obj; return this.ric.equals(other.ric) && super.equals(obj); } else return false; } }
true
16133240958fc254059251b382d2b34b2afc58f7
Java
ddt-jissyusei1/meikai_java_2017_02_shida
/jissyu/src/ensyuu15/En15_8_ArgsCalendar.java
UTF-8
5,370
3.453125
3
[]
no_license
package ensyuu15; /* * コマンドライン引数で指定された月のカレンダーを表示するプログラムを作成せよ。 * コマンドラインから年のみが与えられた場合は、その年の1月から12月までのカレンダーを表示して、 * 年と月が与えられた場合は、その月のカレンダーを表示して、 * 年も月も与えられたなかったら、現在の月のカレンダーを表示すること。 * *追加仕様:年、月以外にも引数が入力された場合(引数三つ以上ある)、許容数以上であることを通知し、 * 処理を実行せずプログラムを終了することとする。 *追加日 :2018/07/18 メンター・卜部決定 * */ public class En15_8_ArgsCalendar { //プログラムの説明文のための定数 private static final String PROGRAM_EXPLANATION_STRING = "コマンドライン引数で指定された月のカレンダーを表示します。" + "\n年のみが与えられたら1月~12月まで表示します。\n年と月が与えられたらその月のカレンダーを表示します。" + "\nどちらも与えられなかったら現在の月のカレンダーを表示します。\n"; //コマンドライン引数の年の値を表示する文のための定数 private static final String SHOW_ARGUMENTS_VALUE_STRING = "args[%d]:%s\n"; //コマンドライン引数の数が許容数以上であることを告げる通知文のための定数 private static final String ARGUMENTS_NUMBER_ERROR_MESSAGE = "\nコマンドライン引数の数が許容数以上です。" + "年のみまたは年と月を入れなおしてください。"; //コマンドライン引数の数が0(現在月カレンダー表示)の条件分岐のための定数 private static final int CURRENT_CALENDAR_CASE_NUMBER = 0; //コマンドライン引数の数が1(指定年カレンダー表示)の条件分岐のための定数 private static final int SPECIFIED_YEAR_CALENDAR_CASE_NUMBER = 1; //コマンドライン引数の数が2(指定年月カレンダー表示)の条件分岐のための定数 private static final int SPECIFIED_YEARMONTH_CALENDAR_CASE_NUMBER = 2; public static void main(String[] args) { //プログラムの説明文を表示するための出力 System.out.println(PROGRAM_EXPLANATION_STRING); int showArgsValueCounter = 0; //コマンドライン引数の値を表示するループのためのカウンタ変数 int argsLength = args.length; //引数の数によって処理を分けるための引数の配列の長さの取得 //コマンドライン引数の値を表示するための拡張for文 for(String argsValue : args){ //コマンドライン引数の値を表示するための出力 System.out.printf(SHOW_ARGUMENTS_VALUE_STRING, showArgsValueCounter, argsValue); //次の引数の値を表示するためのカウンタの加算 showArgsValueCounter++; } //カレンダーを表示するためのインスタンスの宣言 En15_8_AbsCalendar calendars = null; //配列の要素数によってい処理を分けるための条件分岐 switch(argsLength){ //要素数が0の場合に実行する処理のための条件分岐 case CURRENT_CALENDAR_CASE_NUMBER://現在月のカレンダーを表示するための参照先インスタンスを生成 calendars = new En15_8_CurrentMonthCalendar(); //次の分岐に処理が移らないようにするためのブロック抜け文 break; //要素数が1の場合に実行する処理のための条件分岐 case SPECIFIED_YEAR_CALENDAR_CASE_NUMBER://指定年の年間カレンダーを表示するための参照先インスタンスの宣言 calendars = new En15_8_YearCalendar(args[0]); //次の分岐に処理が移らないようにするためのブロック抜け文 break; //要素数が2の場合に実行する処理のための条件分岐 case SPECIFIED_YEARMONTH_CALENDAR_CASE_NUMBER://指定年月のカレンダーを表示するための参照先インスタンスの宣言 calendars = new En15_8_YearMonthCalendar(args[0],args[1]); //次の分岐に処理が移らないようにするためのブロック抜け文 break; //上記条件以外の時に実行する処理のためのデフォルト分岐 default: //コマンドライン引数が上限数以上であることを通知するための文の表示 System.out.println(ARGUMENTS_NUMBER_ERROR_MESSAGE); //例外発生を防ぐためのプログラム終了コード return; } //コマンドライン引数の数に応じたカレンダーを表示するためのカレンダー表示メソッドの呼び出し calendars.showCalendar(); } }
true
e4e1fc820a79548f823a7bfb1e2fc86944027593
Java
SzymonB97/Programming2-SDA
/src/test/java/core/multithreading/runnableTraining/HanselAndGretelTest.java
UTF-8
676
3
3
[]
no_license
package core.multithreading.runnableTraining; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.PrintStream; public class HanselAndGretelTest { @Test void shouldDoTasks() throws InterruptedException { //ustawiamy naszego mock'a jako symulację klasy PrintStream PrintStream mock = Mockito.mock(PrintStream.class); //ustawiamy metodę wywołania teksu na naszego mock'a System.setOut(mock); //uruchamiamy main naszej klasy HanselAndGretel.main(null); //sprawdzamy czy nasz mock wypisał dany tekst Mockito.verify(mock).println("Jaś skończył się ubierać"); } }
true
09add208856eef66fac6960f251fffc0a0027156
Java
louismarie/budgetview
/budgetview/bv_desktop/src/main/java/com/budgetview/session/states/Persistence.java
UTF-8
2,115
1.773438
2
[]
no_license
package com.budgetview.session.states; import com.budgetview.client.exceptions.IdentificationFailed; import com.budgetview.persistence.prevayler.AccountDataManager; import org.globsframework.model.Glob; import org.globsframework.model.GlobList; import org.globsframework.utils.serialization.SerializedInput; import org.globsframework.utils.serialization.SerializedOutput; import java.util.List; public interface Persistence { UserInfo createUser(String name, boolean autoLog, boolean isRegisteredUser, byte[] encryptedPassword, byte[] linkInfo, byte[] encryptedLinkInfo); void getData(SerializedOutput output, Integer userId); void updateData(SerializedInput input, SerializedOutput output, Integer userId); void connect(SerializedOutput output, long version); Glob identify(String name, byte[] encryptedPassword); Integer confirmUser(String b64LinkInfo) throws IdentificationFailed; void register(byte[] mail, byte[] signature, String activationCode); void delete(String name, byte[] encryptedLinkInfo, Integer userId); Glob getUser(String name); Glob getHiddenUser(byte[] encryptedLinkInfo); void close(); void close(Integer userId); void takeSnapshot(Integer userId); boolean restore(SerializedInput input, Integer userId); GlobList getLocalUsers(); Integer renameUser(String newName, String name, boolean autoLog, byte[] password, byte[] previousLinkInfo, byte[] previousEncryptedLinkInfo, byte[] linkInfo, byte[] encryptedLinkInfo, Integer previousUserId, SerializedInput input); void setDownloadedVersion(long version); void setLang(String lang); List<AccountDataManager.SnapshotInfo> getSnapshotInfos(Integer userId); void getSnapshotData(String fileName, SerializedOutput output, Integer userId); boolean hasChanged(Integer userId); class UserInfo { final public Integer userId; final public boolean isRegistered; public UserInfo(Integer userId, boolean registered) { this.userId = userId; isRegistered = registered; } } }
true