blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fb9c201a5b9f11c349c08826011a00ab204e2159 | 13,297,218,818,811 | 88ceea4a18aee964e1866bf10e8322a60950549e | /darma/app/co/darma/configs/DataConfig.java | 2d36f1909947d738e726a59a0f35ba0febf2fd98 | [] | no_license | suevip/smart-device | https://github.com/suevip/smart-device | 03e1860f626becbce46840ef39fd082707b82113 | 1e78bda66c8e3893bbf08799aa0b0a6236160aa1 | refs/heads/master | 2017-05-11T05:26:53.968000 | 2017-02-10T14:10:30 | 2017-02-10T14:10:30 | 82,620,589 | 0 | 1 | null | true | 2017-02-21T01:16:35 | 2017-02-21T01:16:35 | 2017-02-10T14:13:26 | 2017-02-10T14:12:19 | 996 | 0 | 0 | 0 | null | null | null | package co.darma.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import play.Play;
@Configuration
public class DataConfig {
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName(Play.application().configuration().getString("database.driver"));
// dataSource.setUrl(Play.application().configuration().getString("database.url"));
// dataSource.setUsername(Play.application().configuration().getString("database.user"));
// dataSource.setPassword(Play.application().configuration().getString("database.password"));
return dataSource;
}
} | UTF-8 | Java | 859 | java | DataConfig.java | Java | [] | null | [] | package co.darma.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import play.Play;
@Configuration
public class DataConfig {
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
// dataSource.setDriverClassName(Play.application().configuration().getString("database.driver"));
// dataSource.setUrl(Play.application().configuration().getString("database.url"));
// dataSource.setUsername(Play.application().configuration().getString("database.user"));
// dataSource.setPassword(Play.application().configuration().getString("database.password"));
return dataSource;
}
} | 859 | 0.756694 | 0.756694 | 24 | 34.833332 | 35.979931 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 7 |
0bb26183e700b50bc149878c5ac568d03a97e36f | 21,079,699,503,549 | 5cfaeebdc7c50ca23ee368fa372d48ed1452dfeb | /xd-cache/src/main/java/com/xiaodou/common/cache/local/LocalCache.java | a89555a8c290c9282ce2e54e404783623bbd3163 | [] | no_license | zdhuangelephant/xd_pro | https://github.com/zdhuangelephant/xd_pro | c8c8ff6dfcfb55aead733884909527389e2c8283 | 5611b036968edfff0b0b4f04f0c36968333b2c3b | refs/heads/master | 2022-12-23T16:57:28.306000 | 2019-12-05T06:05:43 | 2019-12-05T06:05:43 | 226,020,526 | 0 | 2 | null | false | 2022-12-16T02:23:20 | 2019-12-05T05:06:27 | 2019-12-05T06:09:36 | 2022-12-16T02:23:19 | 383,586 | 0 | 2 | 66 | JavaScript | false | false | package com.xiaodou.common.cache.local;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* 本地缓存-放在应用服务器内存中的缓存(注意集群环境中不要出现脏数据)
* 1.2.0后不建议使用该类,请使用DynamicLocalCache与StaticLocalCache
* @author zhaodan
* @version 1.0
* @date 2014-3-4
*/
@Deprecated
public class LocalCache {
private static Map<String, Object> localCacheListMap = Maps.newHashMap();
public static void reBuildLocalKeyMap(Object localMap, String localCacheKey) {
Object currentBuildObjMap = null;
if (localCacheListMap.containsKey(localCacheKey)) {
currentBuildObjMap = localCacheListMap.get(localCacheKey);
synchronized (currentBuildObjMap) {
localCacheListMap.put(localCacheKey, localMap);
}
}
}
public Map<String, Object> getLocalMapByCacheKey(String localCacheKey) {
if (localCacheListMap.containsKey(localCacheKey)) {
localCacheListMap.get(localCacheKey);
}
return null;
}
public void putLocalCacheKeyToMap(Object localMap, String localCacheKey) {
if (!localCacheListMap.containsKey(localCacheKey))
localCacheListMap.put(localCacheKey, localMap);
}
public static Map<String, Object> getLocalCacheMap() {
return localCacheListMap;
}
}
| UTF-8 | Java | 1,344 | java | LocalCache.java | Java | [
{
"context": ",请使用DynamicLocalCache与StaticLocalCache\r\n * @author zhaodan\r\n * @version 1.0\r\n * @date 2014-3-4\r\n */\r\n@Deprec",
"end": 226,
"score": 0.999627947807312,
"start": 219,
"tag": "USERNAME",
"value": "zhaodan"
}
] | null | [] | package com.xiaodou.common.cache.local;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* 本地缓存-放在应用服务器内存中的缓存(注意集群环境中不要出现脏数据)
* 1.2.0后不建议使用该类,请使用DynamicLocalCache与StaticLocalCache
* @author zhaodan
* @version 1.0
* @date 2014-3-4
*/
@Deprecated
public class LocalCache {
private static Map<String, Object> localCacheListMap = Maps.newHashMap();
public static void reBuildLocalKeyMap(Object localMap, String localCacheKey) {
Object currentBuildObjMap = null;
if (localCacheListMap.containsKey(localCacheKey)) {
currentBuildObjMap = localCacheListMap.get(localCacheKey);
synchronized (currentBuildObjMap) {
localCacheListMap.put(localCacheKey, localMap);
}
}
}
public Map<String, Object> getLocalMapByCacheKey(String localCacheKey) {
if (localCacheListMap.containsKey(localCacheKey)) {
localCacheListMap.get(localCacheKey);
}
return null;
}
public void putLocalCacheKeyToMap(Object localMap, String localCacheKey) {
if (!localCacheListMap.containsKey(localCacheKey))
localCacheListMap.put(localCacheKey, localMap);
}
public static Map<String, Object> getLocalCacheMap() {
return localCacheListMap;
}
}
| 1,344 | 0.718601 | 0.709857 | 42 | 27.952381 | 25.782009 | 80 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false | 8 |
bd5f08892177f7486aff2c44c6e0580c9ca4aecb | 12,386,685,720,712 | be5e1076427d942be2542d0a5eb0f963a24422df | /classes/com/upsight/android/googleadvertisingid/internal/GoogleAdvertisingProviderModule.java | b7a214bcf5f10b912ef3962b7b2379be9f47f0a9 | [] | no_license | makertech81/pokemongo-decompiledcode-android | https://github.com/makertech81/pokemongo-decompiledcode-android | 628a57f1605dc651434f3d00344d714023f36eb0 | df2d83d432804d25b0db9387d4a785f8da7353e4 | refs/heads/master | 2020-03-03T04:29:40.692000 | 2016-08-05T19:01:26 | 2016-08-05T19:01:26 | 65,024,502 | 15 | 7 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.upsight.android.googleadvertisingid.internal;
import com.upsight.android.UpsightContext;
import com.upsight.android.logger.UpsightLogger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
@Module
public final class GoogleAdvertisingProviderModule
{
private final UpsightContext mUpsight;
public GoogleAdvertisingProviderModule(UpsightContext paramUpsightContext)
{
this.mUpsight = paramUpsightContext;
}
@Provides
@Singleton
public GooglePlayAdvertisingProvider provideGooglePlayAdvertisingProvider()
{
UpsightLogger localUpsightLogger = this.mUpsight.getLogger();
return new GooglePlayAdvertisingProvider(this.mUpsight, localUpsightLogger);
}
@Provides
@Singleton
UpsightContext provideUpsightContext()
{
return this.mUpsight;
}
}
/* Location: /Users/tjledwith/Downloads/dex2jar-0.0.9.8/classes_dex2jar.jar!/com/upsight/android/googleadvertisingid/internal/GoogleAdvertisingProviderModule.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,075 | java | GoogleAdvertisingProviderModule.java | Java | [
{
"context": "Upsight;\n }\n}\n\n\n/* Location: /Users/tjledwith/Downloads/dex2jar-0.0.9.8/classes_dex2jar.jar!/co",
"end": 870,
"score": 0.9996528625488281,
"start": 861,
"tag": "USERNAME",
"value": "tjledwith"
}
] | null | [] | package com.upsight.android.googleadvertisingid.internal;
import com.upsight.android.UpsightContext;
import com.upsight.android.logger.UpsightLogger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
@Module
public final class GoogleAdvertisingProviderModule
{
private final UpsightContext mUpsight;
public GoogleAdvertisingProviderModule(UpsightContext paramUpsightContext)
{
this.mUpsight = paramUpsightContext;
}
@Provides
@Singleton
public GooglePlayAdvertisingProvider provideGooglePlayAdvertisingProvider()
{
UpsightLogger localUpsightLogger = this.mUpsight.getLogger();
return new GooglePlayAdvertisingProvider(this.mUpsight, localUpsightLogger);
}
@Provides
@Singleton
UpsightContext provideUpsightContext()
{
return this.mUpsight;
}
}
/* Location: /Users/tjledwith/Downloads/dex2jar-0.0.9.8/classes_dex2jar.jar!/com/upsight/android/googleadvertisingid/internal/GoogleAdvertisingProviderModule.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 1,075 | 0.779535 | 0.767442 | 39 | 26.589743 | 34.200554 | 176 | false | false | 0 | 0 | 0 | 0 | 81 | 0.075349 | 0.307692 | false | false | 8 |
f8a6573fc2425a6d81fdfa2f23dd9fab77a18d91 | 18,975,165,561,034 | a1f54c4fc08b70dfcde20dd3dc2e0b544850ceb9 | /Vasilev_samouchitel/src/Ch_8/AbstractDemo.java | 5ae0dc931c9b252e166ab130c5bda4488e83ff2c | [] | no_license | smith1984/java_src_tutorial | https://github.com/smith1984/java_src_tutorial | 175d4f69e443084f82c48ab7457dcacfae3dfb23 | 50fd98e37d675f597074a6e53a9ef34824d5fcd4 | refs/heads/master | 2020-04-09T03:38:38.848000 | 2018-12-01T21:57:20 | 2018-12-01T21:57:20 | 159,990,788 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Ch_8;
// Абстрактный класс:
abstract class Base3{
// Текстовое поле:
String operation;
// Конструктор:
Base3(String str){
operation=str;}
// Абстрактный метод:
abstract int F(int n);
// Обычный метод (с вызовом абстрактного):
void show(int n){
System.out.println("Операция: "+operation);
System.out.println("Аргумент: "+n);
System.out.println("Значение: "+F(n));}
}
// Подкласс абстрактного суперкласса:
class BaseA extends Base3{
// Конструктор подкласса:
BaseA(){
// Вызов конструктора (абстрактного) суперкласса:
super("факториал");}
// Переопределение абстрактного метода:
int F(int n){
if(n==1) return 1;
else return n*F(n-1);}
}
// Еще один подкласс абстрактного суперкласса:
class BaseB extends Base3{
// Вызов конструктора (абстрактного) суперкласса:
BaseB(){
// Вызов конструктора (абстрактного) суперкласса:
super("двойной факториал");}
// Переопределение абстрактного метода:
int F(int n){
if(n==1||n==2) return n;
else return n*F(n-2);}
}
public class AbstractDemo {
public static void main(String[] args){
// Создание объекта первого подкласса:
BaseA A=new BaseA();
// Создание объекта второго подкласса:
BaseB B=new BaseB();
// Вызов метода из первого подкласса:
A.show(5);
// Вызов метода из второго подкласса:
B.show(5);}
}
| UTF-8 | Java | 2,009 | java | AbstractDemo.java | Java | [] | null | [] | package Ch_8;
// Абстрактный класс:
abstract class Base3{
// Текстовое поле:
String operation;
// Конструктор:
Base3(String str){
operation=str;}
// Абстрактный метод:
abstract int F(int n);
// Обычный метод (с вызовом абстрактного):
void show(int n){
System.out.println("Операция: "+operation);
System.out.println("Аргумент: "+n);
System.out.println("Значение: "+F(n));}
}
// Подкласс абстрактного суперкласса:
class BaseA extends Base3{
// Конструктор подкласса:
BaseA(){
// Вызов конструктора (абстрактного) суперкласса:
super("факториал");}
// Переопределение абстрактного метода:
int F(int n){
if(n==1) return 1;
else return n*F(n-1);}
}
// Еще один подкласс абстрактного суперкласса:
class BaseB extends Base3{
// Вызов конструктора (абстрактного) суперкласса:
BaseB(){
// Вызов конструктора (абстрактного) суперкласса:
super("двойной факториал");}
// Переопределение абстрактного метода:
int F(int n){
if(n==1||n==2) return n;
else return n*F(n-2);}
}
public class AbstractDemo {
public static void main(String[] args){
// Создание объекта первого подкласса:
BaseA A=new BaseA();
// Создание объекта второго подкласса:
BaseB B=new BaseB();
// Вызов метода из первого подкласса:
A.show(5);
// Вызов метода из второго подкласса:
B.show(5);}
}
| 2,009 | 0.618822 | 0.61002 | 49 | 28.142857 | 13.51643 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387755 | false | false | 8 |
2cc8b44c079a24c0e9e72f1afcf298115022efb0 | 33,603,824,162,908 | 8e438e2a9289f327af602b46b66d1e31d0ccfc00 | /src/logica/ControladorPaciente.java | aa34c73c9814c76d70453268fd8bfec4191847b9 | [] | no_license | kcastellano/Hera-Server | https://github.com/kcastellano/Hera-Server | cbea8ac2314d5981cf7cb80147c166cfa7b9e54a | e86adbe71e99f85734e265d941a4b796c5262e5a | refs/heads/master | 2021-01-21T13:48:47.731000 | 2011-08-06T02:14:37 | 2011-08-06T02:14:37 | 2,111,718 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
import configuracion.ConexionFactory;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import persistencia.DaoPaciente;
import dominio.Paciente;
/**
*
* @author ecomobile
*/
public class ControladorPaciente {
public List<Paciente> obtenerTodosPacientes() throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
List<Paciente> Pacientes = PacienteDao.obtenerTodosPacientes();
sesion.close();
return Pacientes;
}
public Paciente obtenerPacientePorId(int id) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
Paciente Paciente = PacienteDao.obtenerPacientePorId(id);
sesion.close();
return Paciente;
}
public Paciente crearPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
PacienteDao.crearPaciente(paciente);
sesion.commit();
sesion.close();
return paciente;
}
public Paciente actualizarPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
PacienteDao.actualizarPaciente(paciente);
sesion.commit();
sesion.close();
return paciente;
}
public int eliminarPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
int resultado = PacienteDao.eliminarPaciente(paciente);
sesion.commit();
sesion.close();
return resultado;
}
}
| UTF-8 | Java | 2,078 | java | ControladorPaciente.java | Java | [
{
"context": "iente;\nimport dominio.Paciente;\n\n/**\n *\n * @author ecomobile\n */\npublic class ControladorPaciente {\n\n publi",
"end": 311,
"score": 0.9991662502288818,
"start": 302,
"tag": "USERNAME",
"value": "ecomobile"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
import configuracion.ConexionFactory;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import persistencia.DaoPaciente;
import dominio.Paciente;
/**
*
* @author ecomobile
*/
public class ControladorPaciente {
public List<Paciente> obtenerTodosPacientes() throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
List<Paciente> Pacientes = PacienteDao.obtenerTodosPacientes();
sesion.close();
return Pacientes;
}
public Paciente obtenerPacientePorId(int id) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
Paciente Paciente = PacienteDao.obtenerPacientePorId(id);
sesion.close();
return Paciente;
}
public Paciente crearPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
PacienteDao.crearPaciente(paciente);
sesion.commit();
sesion.close();
return paciente;
}
public Paciente actualizarPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
PacienteDao.actualizarPaciente(paciente);
sesion.commit();
sesion.close();
return paciente;
}
public int eliminarPaciente(Paciente paciente) throws Exception {
SqlSession sesion = ConexionFactory.getSession().openSession();
DaoPaciente PacienteDao = sesion.getMapper(DaoPaciente.class);
int resultado = PacienteDao.eliminarPaciente(paciente);
sesion.commit();
sesion.close();
return resultado;
}
}
| 2,078 | 0.701636 | 0.701636 | 63 | 31.984127 | 27.14657 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 8 |
d84377f2cc2c59b7f9b42fa08776abb33e1f2fb1 | 22,144,851,407,027 | 47b77d915d77353e2b5c309437cd5be59e17a81f | /src/emidetail/database/utils/LinksFunctions.java | 3f5ea33a2e45c598dde974666910c1a015a9a33f | [] | no_license | DVAmod/emiCabLink | https://github.com/DVAmod/emiCabLink | 2133109b7bdcc4cd24dcaf1d966f3434c1e00970 | cf49cabb41bbb117ec39b45c40aa625667ba1d60 | refs/heads/master | 2020-03-25T04:14:58.867000 | 2018-09-21T09:33:53 | 2018-09-21T09:33:53 | 143,385,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 emidetail.database.utils;
import emidetail.database.beans.LinkStands;
import emidetail.database.beans.LinkTrays;
import emidetail.database.beans.Metis;
import emidetail.database.beans.Trays;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
/**
*
* @author DVAmod
*/
public class LinksFunctions {
public static List<LinkTrays> getLinkedMetis(int standType, Trays tray, boolean ishard, int cover){
List<LinkTrays> links = null;
int type = 0;
String hard = "!=1";
int construction = 0;
construction = tray.getConstructionId();
type = tray.getType();
if (ishard) {
hard = "=1";
}
Session s = null;
try{
s = Hibernate.getSession();
s.beginTransaction();
String query = "from LinkTrays where "+
" cover_type=" + cover +
" and isFixed!=1"+
" and trays_type LIKE ('%"+type+"%')"+
" and construction_id="+construction+
" and profil_id="+standType;
query += " and isHard"+hard;
links = s.createQuery(query).list();
s.getTransaction().commit();
s.flush();
System.out.println("Commit tran linked");
} catch (Exception e) {
System.err.println("Error db all by linked metis");
//s.getTransaction().rollback();
} finally {
Hibernate.closeSession(s);
}
return links;
}
public static List<LinkTrays> getLinkedTrays(int standType,Trays tray, boolean ishard, int cover) {
List<LinkTrays> links = new ArrayList<LinkTrays>();
Session s = null;
String hard = "!=1";
int type = 0;
type = tray.getType();
if (ishard) {
hard = "=1";
}
try{
s = Hibernate.getSession();
s.beginTransaction();
System.err.println("a1");
String queryStr = "from LinkTrays where "+
" cover_type=" + cover +
" and trays_type LIKE ('%"+type+"%')"+
" and isFixed=1"+
" and profil_id="+standType;
queryStr += " and isHard"+hard ;
System.err.println("Query: "+queryStr);
links = s.createQuery(queryStr).list();
System.err.println("a2");
s.getTransaction().commit();
s.flush();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(LinksFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
System.err.println("a3");
}catch(HibernateException e){
System.err.println("Error db all by linked functions");
s.getTransaction().rollback();
}finally{
Hibernate.closeSession(s);
}
return links;
}
public static List<LinkStands> getLikedMetis(String standType, String profilType) {
List<LinkStands> links = new ArrayList<LinkStands>();
Session s = null;
try{
s = Hibernate.getSession();
s.beginTransaction();
links = s.createQuery("from LinkStands ls where "+
" ls.standIds LIKE ('%"+standType+"%') "+
" and ls.profilIds LIKE ('%"+profilType+"%')").list();
s.getTransaction().commit();
}catch(HibernateException e){
System.err.println("Error db all by linked");
s.getTransaction().rollback();
}finally{
Hibernate.closeSession(s);
}
return links;
}
}
| UTF-8 | Java | 4,612 | java | LinksFunctions.java | Java | [
{
"context": "port org.hibernate.Session;\r\n\r\n/**\r\n *\r\n * @author DVAmod\r\n */\r\npublic class LinksFunctions {\r\n \r\n \r\n",
"end": 619,
"score": 0.9996501803398132,
"start": 613,
"tag": "USERNAME",
"value": "DVAmod"
}
] | null | [] | /*
* 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 emidetail.database.utils;
import emidetail.database.beans.LinkStands;
import emidetail.database.beans.LinkTrays;
import emidetail.database.beans.Metis;
import emidetail.database.beans.Trays;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
/**
*
* @author DVAmod
*/
public class LinksFunctions {
public static List<LinkTrays> getLinkedMetis(int standType, Trays tray, boolean ishard, int cover){
List<LinkTrays> links = null;
int type = 0;
String hard = "!=1";
int construction = 0;
construction = tray.getConstructionId();
type = tray.getType();
if (ishard) {
hard = "=1";
}
Session s = null;
try{
s = Hibernate.getSession();
s.beginTransaction();
String query = "from LinkTrays where "+
" cover_type=" + cover +
" and isFixed!=1"+
" and trays_type LIKE ('%"+type+"%')"+
" and construction_id="+construction+
" and profil_id="+standType;
query += " and isHard"+hard;
links = s.createQuery(query).list();
s.getTransaction().commit();
s.flush();
System.out.println("Commit tran linked");
} catch (Exception e) {
System.err.println("Error db all by linked metis");
//s.getTransaction().rollback();
} finally {
Hibernate.closeSession(s);
}
return links;
}
public static List<LinkTrays> getLinkedTrays(int standType,Trays tray, boolean ishard, int cover) {
List<LinkTrays> links = new ArrayList<LinkTrays>();
Session s = null;
String hard = "!=1";
int type = 0;
type = tray.getType();
if (ishard) {
hard = "=1";
}
try{
s = Hibernate.getSession();
s.beginTransaction();
System.err.println("a1");
String queryStr = "from LinkTrays where "+
" cover_type=" + cover +
" and trays_type LIKE ('%"+type+"%')"+
" and isFixed=1"+
" and profil_id="+standType;
queryStr += " and isHard"+hard ;
System.err.println("Query: "+queryStr);
links = s.createQuery(queryStr).list();
System.err.println("a2");
s.getTransaction().commit();
s.flush();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(LinksFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
System.err.println("a3");
}catch(HibernateException e){
System.err.println("Error db all by linked functions");
s.getTransaction().rollback();
}finally{
Hibernate.closeSession(s);
}
return links;
}
public static List<LinkStands> getLikedMetis(String standType, String profilType) {
List<LinkStands> links = new ArrayList<LinkStands>();
Session s = null;
try{
s = Hibernate.getSession();
s.beginTransaction();
links = s.createQuery("from LinkStands ls where "+
" ls.standIds LIKE ('%"+standType+"%') "+
" and ls.profilIds LIKE ('%"+profilType+"%')").list();
s.getTransaction().commit();
}catch(HibernateException e){
System.err.println("Error db all by linked");
s.getTransaction().rollback();
}finally{
Hibernate.closeSession(s);
}
return links;
}
}
| 4,612 | 0.47745 | 0.474198 | 157 | 27.375795 | 21.780729 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484076 | false | false | 8 |
b28941e804fa25c6168850920eee3696a4a0372a | 6,201,932,814,982 | 2772a37ce35f824e93a9d0940a434c2b829188ae | /faith-blog-java/src/main/java/cn/yanstu/blog/service/impl/LinkServiceImpl.java | b22bfef67aefe334043d0a292fdc0f86cf326b9e | [] | no_license | Xinjiann/faith-blog | https://github.com/Xinjiann/faith-blog | 21bafe0ac40c6cef48205ecaa247c918837695b7 | f8d5d937adec13d0a071c0696ee834dc41648c18 | refs/heads/master | 2023-01-15T22:28:00.142000 | 2020-11-28T06:09:21 | 2020-11-28T06:09:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.yanstu.blog.service.impl;
import cn.yanstu.blog.entity.Link;
import cn.yanstu.blog.mapper.LinkMapper;
import cn.yanstu.blog.service.LinkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author yanstu
* @since 2020-11-21
*/
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {
}
| UTF-8 | Java | 462 | java | LinkServiceImpl.java | Java | [
{
"context": "rvice;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author yanstu\n * @since 2020-11-21\n */\n@Service\npublic class Li",
"end": 322,
"score": 0.9996693730354309,
"start": 316,
"tag": "USERNAME",
"value": "yanstu"
}
] | null | [] | package cn.yanstu.blog.service.impl;
import cn.yanstu.blog.entity.Link;
import cn.yanstu.blog.mapper.LinkMapper;
import cn.yanstu.blog.service.LinkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author yanstu
* @since 2020-11-21
*/
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {
}
| 462 | 0.765487 | 0.747788 | 20 | 21.6 | 24.812094 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 8 |
56c484e3a78eef0e17219b9efea6344032b34488 | 6,201,932,813,229 | ed5b03c7cf8a8d6e9e98cda8f46be30b3bedc8bc | /src/huard/iws/servlet/ObjectQuery.java | 7f2a64775c00e0b725445883819bfb6cd5375302 | [] | no_license | yairzo/websites | https://github.com/yairzo/websites | ef3c7d5c13a0615d49a2ee0ae777d2373c9fd963 | cd3c4604e0bf601dde626b7d9ab8a58c66e9c465 | refs/heads/master | 2021-01-13T01:49:13.210000 | 2014-11-13T10:12:18 | 2014-11-13T10:12:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package huard.iws.servlet;
import huard.iws.bean.CallForProposalBean;
import huard.iws.bean.PersonBean;
import huard.iws.model.CallForProposal;
import huard.iws.model.Fund;
import huard.iws.service.CallForProposalService;
import huard.iws.service.FundService;
import huard.iws.service.HujiAuthorizationService;
import huard.iws.service.PersonService;
import huard.iws.service.TextualPageService;
import huard.iws.util.ApplicationContextProvider;
import huard.iws.util.UserPersonUtils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
public class ObjectQuery extends HttpServlet{
//private static final Logger logger = Logger.getLogger(SelectBoxFiller.class);
private ApplicationContext context = ApplicationContextProvider.getContext();
private PersonService personService;
private HujiAuthorizationService hujiAuthorizationService;
private FundService fundService;
private TextualPageService textualPageService;
private CallForProposalService callForProposalService;
final static long serialVersionUID = 0;
public void init(){
Object obj = context.getBean("personService");
personService = (PersonService)obj;
Object obj2 = context.getBean("hujiAuthorizationService");
hujiAuthorizationService = (HujiAuthorizationService)obj2;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type;
if ( (type = request.getParameter("type"))==null ) return;
String aId;
int id = 0;
if ( ( aId = request.getParameter("id")) == null) return;
if ( !(request.getParameter("id")).matches("^(?!^0)\\d{1,9}$")) return;
id = Integer.parseInt(aId);
if (id == 0) return;
init();
PersonBean userPersonBean = UserPersonUtils.getUserAsPersonBean(request, personService, hujiAuthorizationService);
if (type.equals("callForProposalToPost")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
String postMessage="";
postMessage=callForProposalBean.toPostMessage();
out.print(postMessage);
out.flush();
out.close();
}
if (type.equals("callForProposalToPostNew")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
String postMessage="";
postMessage=callForProposalBean.toPostMessageNew();
out.print(postMessage);
out.flush();
out.close();
}
if (type.equals("callForProposalTitle")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.print(callForProposalBean.getTitle() + " - " + callForProposalBean.getId());
out.flush();
out.close();
}
if (type.equals("callForProposalUrlTitle")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.print(callForProposalBean.getUrlTitle());
out.flush();
out.close();
}
if (type.equals("fundDesk")){
Object obj = context.getBean("fundService");
fundService = (FundService)obj;
Fund fund = fundService.getFund(id);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(fund.getDeskId());
out.flush();
out.close();
}
if (type.equals("textualPageCheckUrlTitle")){
Object obj = context.getBean("textualPageService");
textualPageService = (TextualPageService)obj;
int count = textualPageService.countTextualPagesByUrlTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(count);
out.flush();
out.close();
}
if (type.equals("textualPageCheckTitle")){
Object obj = context.getBean("textualPageService");
textualPageService = (TextualPageService)obj;
int count = textualPageService.countTextualPagesByTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(count);
out.flush();
out.close();
}
if (type.equals("callForProposalCheckTitle")){
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
int count = callForProposalService.countCallForProposalsByTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
if(count>0)
out.print(count);
out.flush();
out.close();
}
if (type.equals("callForProposalCheckUrlTitle")){
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
int count = callForProposalService.countCallForProposalsByUrlTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
if(count>0)
out.print(count);
out.flush();
out.close();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("=========servlet dopost....");
doGet(req,res);
}
}
| UTF-8 | Java | 8,228 | java | ObjectQuery.java | Java | [] | null | [] | package huard.iws.servlet;
import huard.iws.bean.CallForProposalBean;
import huard.iws.bean.PersonBean;
import huard.iws.model.CallForProposal;
import huard.iws.model.Fund;
import huard.iws.service.CallForProposalService;
import huard.iws.service.FundService;
import huard.iws.service.HujiAuthorizationService;
import huard.iws.service.PersonService;
import huard.iws.service.TextualPageService;
import huard.iws.util.ApplicationContextProvider;
import huard.iws.util.UserPersonUtils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
public class ObjectQuery extends HttpServlet{
//private static final Logger logger = Logger.getLogger(SelectBoxFiller.class);
private ApplicationContext context = ApplicationContextProvider.getContext();
private PersonService personService;
private HujiAuthorizationService hujiAuthorizationService;
private FundService fundService;
private TextualPageService textualPageService;
private CallForProposalService callForProposalService;
final static long serialVersionUID = 0;
public void init(){
Object obj = context.getBean("personService");
personService = (PersonService)obj;
Object obj2 = context.getBean("hujiAuthorizationService");
hujiAuthorizationService = (HujiAuthorizationService)obj2;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type;
if ( (type = request.getParameter("type"))==null ) return;
String aId;
int id = 0;
if ( ( aId = request.getParameter("id")) == null) return;
if ( !(request.getParameter("id")).matches("^(?!^0)\\d{1,9}$")) return;
id = Integer.parseInt(aId);
if (id == 0) return;
init();
PersonBean userPersonBean = UserPersonUtils.getUserAsPersonBean(request, personService, hujiAuthorizationService);
if (type.equals("callForProposalToPost")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
String postMessage="";
postMessage=callForProposalBean.toPostMessage();
out.print(postMessage);
out.flush();
out.close();
}
if (type.equals("callForProposalToPostNew")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
String postMessage="";
postMessage=callForProposalBean.toPostMessageNew();
out.print(postMessage);
out.flush();
out.close();
}
if (type.equals("callForProposalTitle")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.print(callForProposalBean.getTitle() + " - " + callForProposalBean.getId());
out.flush();
out.close();
}
if (type.equals("callForProposalUrlTitle")){
if (! userPersonBean.isAuthorized("POST", "ADMIN") && ! userPersonBean.isAuthorized("POST", "CREATOR"))
return ;
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
CallForProposal callForProposal = callForProposalService.getCallForProposal(id);
//if no such callForProposal - user entered wrong number
if (callForProposal.getId()==0)
return;
CallForProposalBean callForProposalBean = new CallForProposalBean(callForProposal, true);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.print(callForProposalBean.getUrlTitle());
out.flush();
out.close();
}
if (type.equals("fundDesk")){
Object obj = context.getBean("fundService");
fundService = (FundService)obj;
Fund fund = fundService.getFund(id);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(fund.getDeskId());
out.flush();
out.close();
}
if (type.equals("textualPageCheckUrlTitle")){
Object obj = context.getBean("textualPageService");
textualPageService = (TextualPageService)obj;
int count = textualPageService.countTextualPagesByUrlTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(count);
out.flush();
out.close();
}
if (type.equals("textualPageCheckTitle")){
Object obj = context.getBean("textualPageService");
textualPageService = (TextualPageService)obj;
int count = textualPageService.countTextualPagesByTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
out.print(count);
out.flush();
out.close();
}
if (type.equals("callForProposalCheckTitle")){
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
int count = callForProposalService.countCallForProposalsByTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
if(count>0)
out.print(count);
out.flush();
out.close();
}
if (type.equals("callForProposalCheckUrlTitle")){
Object obj = context.getBean("callForProposalService");
callForProposalService = (CallForProposalService)obj;
int count = callForProposalService.countCallForProposalsByUrlTitle(id,request.getParameter("title"));
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = response.getOutputStream();
if(count>0)
out.print(count);
out.flush();
out.close();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("=========servlet dopost....");
doGet(req,res);
}
}
| 8,228 | 0.753889 | 0.751094 | 214 | 37.448597 | 27.136633 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.046729 | false | false | 8 |
9ec52089663d3d6ada0218a2956f4544ce44150e | 14,791,867,411,999 | 299f5fd4f42bce6cdddee7fea4ae8c59b496122b | /simulator/src/main/java/com/cxstudio/trading/SequentialHistoricalTradeRetriever.java | b272ee929f85bf66d3e71e9e32d908eaee34c2d0 | [] | no_license | cxstudio-com/market-simulator | https://github.com/cxstudio-com/market-simulator | 37b98cbf05ade09a68cff930d6073d10be66a9f4 | 949f7a9d9343ad383b793b9b90f675b7d1ad13c0 | refs/heads/master | 2016-09-03T01:43:10.218000 | 2015-02-21T09:55:46 | 2015-02-21T09:55:46 | 26,846,539 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cxstudio.trading;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cxstudio.trading.dao.TradeDao;
import com.cxstudio.trading.model.DataFilter;
import com.cxstudio.trading.model.Symbol;
import com.cxstudio.trading.model.Trade;
import com.cxstudio.trading.model.TradeSpacing;
/**
* TODO: caching logic is still flawed. Refetching should happen when half the cache is reached not when the end
*
* @author mikecao
*
*/
public class SequentialHistoricalTradeRetriever implements TradeRetriever {
static Logger log = LoggerFactory.getLogger(SequentialHistoricalTradeRetriever.class);
private final TradeDao tradeDao;
private final Symbol symbol;
private final int bufferSize;
private LinkedList<Trade> tradeBuffer = new LinkedList<Trade>();
private DataFilter filter;
private TradeSpacing tradeSpacing;
private ListIterator<Trade> iterator;
public SequentialHistoricalTradeRetriever(TradeDao tradeDao, Symbol symbol, TradeSpacing tradeSpacing,
int bufferSize) {
this.tradeDao = tradeDao;
this.symbol = symbol;
this.tradeSpacing = tradeSpacing;
filter = new DataFilter();
filter.setInterval(tradeSpacing.getSeconds());
filter.setLimit(bufferSize);
this.bufferSize = bufferSize;
}
public Trade retrieve(Date dateTime) {
boolean freshFetch = false;
if (tradeBuffer.size() <= 0) { // initial fetch
log.trace("Buffer size 0. Fetch from source for {}", dateTime);
// get n number (n=bufferSize) of trades, centered at given dateTime with n/2 number of trades
// at before and after the giving date.
filter.setStartTime(dateTime);
filter.setLimit(bufferSize / 2);
List<Trade> trades = tradeDao.getMiddleBufferedTrades(symbol, filter);
log.trace("{} trades fetched from source.", (trades == null ? "null" : trades.size()));
if (trades != null && trades.size() > 0) {
log.trace("First one from the fetched data {}", trades.get(0));
tradeBuffer.addAll(trades);
iterator = tradeBuffer.listIterator();
freshFetch = true;
} else {
return null;
}
}
// the caching policy:
// advance idx pointer until cached trade matches the given time.
while (iterator.hasNext()) {
Trade trade = iterator.next();
int compare = compareDate(trade, dateTime, tradeSpacing);
if (compare == 0) {
log.trace("Returning trade {}, statck {}", trade, Thread.currentThread().getStackTrace());
return trade;
} else if (compare > 0) {
if (freshFetch) { // on a fresh fetch, this should not happen unless given date is not in the DB
return null;
}
log.trace("tradeBuffer.get(currentIndex) {} > dateTime {}. move to next", trade, dateTime);
if (compareDate(tradeBuffer.get(0), dateTime, tradeSpacing) <= 0) {
// if the first one in buffer is earlier than the given date start from begining and iterate it
// again
log.debug("The first one in the buffer {} <= given time {}. Iterate from first again",
tradeBuffer.get(0), dateTime);
iterator = tradeBuffer.listIterator(0);
freshFetch = true;
continue;
} else {
// if we starts from index=0, we should never reach trade date > given dateTime, re-fetch
log.debug("The first one in the buffer {} > given time {}. Clear cache and refetch.",
tradeBuffer.get(0), dateTime);
tradeBuffer.clear();
}
return retrieve(dateTime);
} else { // else compare < 0, trade date < given dateTime, then proceed to next trade
log.trace("move to next trade in buffer. tradeBuffer.get(currentIndex) {} < dateTime {}.", trade,
dateTime);
}
}
// if index meets the end, fetch another n number of trades
filter.setStartTime(dateTime);
filter.setLimit(bufferSize / 2);
List<Trade> trades = tradeDao.getTrades(symbol, filter);
log.info("{} trades RE-fetched from the source.", (trades == null ? "null" : trades.size()));
if (trades != null && trades.size() > 0) {
log.trace("First one from the RE-fetched data {}", trades.get(0));
if (compareDate(trades.get(0), dateTime, tradeSpacing) != 0) {
for (Trade trade : trades) {
tradeBuffer.remove();
tradeBuffer.add(trade);
}
iterator = tradeBuffer.listIterator();
} else { // if the first one from the refetch isn't what we expected, re-initialize the cache
tradeBuffer.clear();
}
return retrieve(dateTime);
} else {
return null;
}
}
public List<Trade> lastNumOfTrades(Date startTime, int numOfTrades) {
if (numOfTrades > bufferSize / 2) {
throw new IllegalArgumentException("Requested last " + numOfTrades + " exceeds half of the cached size "
+ bufferSize / 2);
}
if (iterator.hasPrevious()) {
iterator.previous(); // rewind one step before calling retrieve
}
if (retrieve(startTime) == null) {
return null; // no data for given time
} else {
int currentIndex = iterator.nextIndex() - 1;
return tradeBuffer.subList(currentIndex - numOfTrades > 0 ? currentIndex - numOfTrades : 0, currentIndex);
}
}
private Date getStartingDate(Date time, long tradeSpacing, int stepsAway) {
return new Date(time.getTime() + tradeSpacing * stepsAway / 2);
}
private int compareDate(Trade trade, Date time, TradeSpacing tradeSpacing) {
Date toTime = new Date(time.getTime() + tradeSpacing.getMilliseconds());
Date tradeTime = trade.getDateTime();
int compareValue = 0;
if (!tradeTime.before(time) && tradeTime.before(toTime)) {
return 0;
} else if (tradeTime.before(time)) {
compareValue = -1;
} else if (tradeTime.after(toTime)) {
compareValue = 1;
}
return compareValue;
}
}
| UTF-8 | Java | 6,726 | java | SequentialHistoricalTradeRetriever.java | Java | [
{
"context": "e cache is reached not when the end\n * \n * @author mikecao\n *\n */\npublic class SequentialHistoricalTradeRetr",
"end": 555,
"score": 0.9995848536491394,
"start": 548,
"tag": "USERNAME",
"value": "mikecao"
}
] | null | [] | package com.cxstudio.trading;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cxstudio.trading.dao.TradeDao;
import com.cxstudio.trading.model.DataFilter;
import com.cxstudio.trading.model.Symbol;
import com.cxstudio.trading.model.Trade;
import com.cxstudio.trading.model.TradeSpacing;
/**
* TODO: caching logic is still flawed. Refetching should happen when half the cache is reached not when the end
*
* @author mikecao
*
*/
public class SequentialHistoricalTradeRetriever implements TradeRetriever {
static Logger log = LoggerFactory.getLogger(SequentialHistoricalTradeRetriever.class);
private final TradeDao tradeDao;
private final Symbol symbol;
private final int bufferSize;
private LinkedList<Trade> tradeBuffer = new LinkedList<Trade>();
private DataFilter filter;
private TradeSpacing tradeSpacing;
private ListIterator<Trade> iterator;
public SequentialHistoricalTradeRetriever(TradeDao tradeDao, Symbol symbol, TradeSpacing tradeSpacing,
int bufferSize) {
this.tradeDao = tradeDao;
this.symbol = symbol;
this.tradeSpacing = tradeSpacing;
filter = new DataFilter();
filter.setInterval(tradeSpacing.getSeconds());
filter.setLimit(bufferSize);
this.bufferSize = bufferSize;
}
public Trade retrieve(Date dateTime) {
boolean freshFetch = false;
if (tradeBuffer.size() <= 0) { // initial fetch
log.trace("Buffer size 0. Fetch from source for {}", dateTime);
// get n number (n=bufferSize) of trades, centered at given dateTime with n/2 number of trades
// at before and after the giving date.
filter.setStartTime(dateTime);
filter.setLimit(bufferSize / 2);
List<Trade> trades = tradeDao.getMiddleBufferedTrades(symbol, filter);
log.trace("{} trades fetched from source.", (trades == null ? "null" : trades.size()));
if (trades != null && trades.size() > 0) {
log.trace("First one from the fetched data {}", trades.get(0));
tradeBuffer.addAll(trades);
iterator = tradeBuffer.listIterator();
freshFetch = true;
} else {
return null;
}
}
// the caching policy:
// advance idx pointer until cached trade matches the given time.
while (iterator.hasNext()) {
Trade trade = iterator.next();
int compare = compareDate(trade, dateTime, tradeSpacing);
if (compare == 0) {
log.trace("Returning trade {}, statck {}", trade, Thread.currentThread().getStackTrace());
return trade;
} else if (compare > 0) {
if (freshFetch) { // on a fresh fetch, this should not happen unless given date is not in the DB
return null;
}
log.trace("tradeBuffer.get(currentIndex) {} > dateTime {}. move to next", trade, dateTime);
if (compareDate(tradeBuffer.get(0), dateTime, tradeSpacing) <= 0) {
// if the first one in buffer is earlier than the given date start from begining and iterate it
// again
log.debug("The first one in the buffer {} <= given time {}. Iterate from first again",
tradeBuffer.get(0), dateTime);
iterator = tradeBuffer.listIterator(0);
freshFetch = true;
continue;
} else {
// if we starts from index=0, we should never reach trade date > given dateTime, re-fetch
log.debug("The first one in the buffer {} > given time {}. Clear cache and refetch.",
tradeBuffer.get(0), dateTime);
tradeBuffer.clear();
}
return retrieve(dateTime);
} else { // else compare < 0, trade date < given dateTime, then proceed to next trade
log.trace("move to next trade in buffer. tradeBuffer.get(currentIndex) {} < dateTime {}.", trade,
dateTime);
}
}
// if index meets the end, fetch another n number of trades
filter.setStartTime(dateTime);
filter.setLimit(bufferSize / 2);
List<Trade> trades = tradeDao.getTrades(symbol, filter);
log.info("{} trades RE-fetched from the source.", (trades == null ? "null" : trades.size()));
if (trades != null && trades.size() > 0) {
log.trace("First one from the RE-fetched data {}", trades.get(0));
if (compareDate(trades.get(0), dateTime, tradeSpacing) != 0) {
for (Trade trade : trades) {
tradeBuffer.remove();
tradeBuffer.add(trade);
}
iterator = tradeBuffer.listIterator();
} else { // if the first one from the refetch isn't what we expected, re-initialize the cache
tradeBuffer.clear();
}
return retrieve(dateTime);
} else {
return null;
}
}
public List<Trade> lastNumOfTrades(Date startTime, int numOfTrades) {
if (numOfTrades > bufferSize / 2) {
throw new IllegalArgumentException("Requested last " + numOfTrades + " exceeds half of the cached size "
+ bufferSize / 2);
}
if (iterator.hasPrevious()) {
iterator.previous(); // rewind one step before calling retrieve
}
if (retrieve(startTime) == null) {
return null; // no data for given time
} else {
int currentIndex = iterator.nextIndex() - 1;
return tradeBuffer.subList(currentIndex - numOfTrades > 0 ? currentIndex - numOfTrades : 0, currentIndex);
}
}
private Date getStartingDate(Date time, long tradeSpacing, int stepsAway) {
return new Date(time.getTime() + tradeSpacing * stepsAway / 2);
}
private int compareDate(Trade trade, Date time, TradeSpacing tradeSpacing) {
Date toTime = new Date(time.getTime() + tradeSpacing.getMilliseconds());
Date tradeTime = trade.getDateTime();
int compareValue = 0;
if (!tradeTime.before(time) && tradeTime.before(toTime)) {
return 0;
} else if (tradeTime.before(time)) {
compareValue = -1;
} else if (tradeTime.after(toTime)) {
compareValue = 1;
}
return compareValue;
}
}
| 6,726 | 0.589949 | 0.585192 | 155 | 42.393547 | 31.808804 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.754839 | false | false | 8 |
221f904a5835a50409b3fb5553b7f844c1d72d88 | 10,213,432,268,804 | 723e06240416852c65ab5595238ec68840d4cc94 | /src/main/java/org/upgrad/controllers/QuestionController.java | a7c96fdcdd8bd268f147e2a9eae621c16d43d845 | [
"MIT"
] | permissive | Akshar9015/spring-api | https://github.com/Akshar9015/spring-api | c58a59a90d0027b0115ae27af91cf0c0e876b8e6 | 9d10d78118fc81c2894dd90159f6b3811c74c468 | refs/heads/master | 2020-03-22T12:50:07.883000 | 2018-07-22T09:25:12 | 2018-07-22T09:25:12 | 140,065,370 | 0 | 0 | MIT | true | 2018-07-22T06:08:56 | 2018-07-07T08:08:54 | 2018-07-07T08:08:57 | 2018-07-21T23:17:48 | 80 | 0 | 0 | 1 | Java | false | null | package org.upgrad.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.upgrad.models.Question;
import org.upgrad.models.User;
import org.upgrad.services.QuestionService;
import org.upgrad.services.UserService;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Set;
@RestController
public class QuestionController {
@Autowired
private QuestionService questionService;
/**
* @param categoryId Set of category Ids to which question belongs
* @param question content of the question
* @param session HTTP session object
* @return returns the appropriate JSON response
*/
@PostMapping("/api/question")
public ResponseEntity<?> createQuestion(@RequestParam("categoryId") Set<Integer> categoryId, @RequestParam("question") String question, HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
questionService.addQuestion(question, user.getId(),categoryId);
return new ResponseEntity<>("Question is added.", HttpStatus.OK);
}
}
/**
* @param categoryId category id for which questions are to be retrieved
* @param session HTTP session
* @return returns all questions based on categoryId
*/
@GetMapping("/api/question/all/{categoryId}")
public ResponseEntity<?> getAllQuestionsByCategory(@PathVariable("categoryId") int categoryId, HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
return new ResponseEntity<>(questionService.getAllQuestionsByCategory(categoryId), HttpStatus.OK);
}
}
/**
* @param session HTTP session
* @return returns all questions for the logged in user
*/
@GetMapping("/api/question/all")
public ResponseEntity<?> getAllQuestionsByUser(HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
return new ResponseEntity<>(questionService.getAllQuestionsByUser(user.getId()), HttpStatus.OK);
}
}
/**
* @param questionId the path variable 'questionId' of data type Integer which has to be deleted.
* @param session HTTP session
* @return returns appropriate JSON response
*/
@DeleteMapping("/api/question/{questionId}")
public ResponseEntity<?> deleteQuestion(@PathVariable("questionId") int questionId,HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
int userId = questionService.findUserIdfromQuestion(questionId);
if(userId == user.getId() || user.getRole().equalsIgnoreCase("admin")) {
questionService.deleteQuestion(questionId);
return new ResponseEntity<>("Question and it'sId " + questionId + " deleted.", HttpStatus.OK);
}
else {
return new ResponseEntity<>("You can't delete this question!", HttpStatus.FORBIDDEN);
}
}
}
}
| UTF-8 | Java | 3,793 | java | QuestionController.java | Java | [] | null | [] | package org.upgrad.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.upgrad.models.Question;
import org.upgrad.models.User;
import org.upgrad.services.QuestionService;
import org.upgrad.services.UserService;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Set;
@RestController
public class QuestionController {
@Autowired
private QuestionService questionService;
/**
* @param categoryId Set of category Ids to which question belongs
* @param question content of the question
* @param session HTTP session object
* @return returns the appropriate JSON response
*/
@PostMapping("/api/question")
public ResponseEntity<?> createQuestion(@RequestParam("categoryId") Set<Integer> categoryId, @RequestParam("question") String question, HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
questionService.addQuestion(question, user.getId(),categoryId);
return new ResponseEntity<>("Question is added.", HttpStatus.OK);
}
}
/**
* @param categoryId category id for which questions are to be retrieved
* @param session HTTP session
* @return returns all questions based on categoryId
*/
@GetMapping("/api/question/all/{categoryId}")
public ResponseEntity<?> getAllQuestionsByCategory(@PathVariable("categoryId") int categoryId, HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
return new ResponseEntity<>(questionService.getAllQuestionsByCategory(categoryId), HttpStatus.OK);
}
}
/**
* @param session HTTP session
* @return returns all questions for the logged in user
*/
@GetMapping("/api/question/all")
public ResponseEntity<?> getAllQuestionsByUser(HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
return new ResponseEntity<>(questionService.getAllQuestionsByUser(user.getId()), HttpStatus.OK);
}
}
/**
* @param questionId the path variable 'questionId' of data type Integer which has to be deleted.
* @param session HTTP session
* @return returns appropriate JSON response
*/
@DeleteMapping("/api/question/{questionId}")
public ResponseEntity<?> deleteQuestion(@PathVariable("questionId") int questionId,HttpSession session) {
if (session.getAttribute("currUser")==null) {
return new ResponseEntity<>("Please Login",HttpStatus.UNAUTHORIZED);
}
else {
User user = (User) session.getAttribute("currUser");
int userId = questionService.findUserIdfromQuestion(questionId);
if(userId == user.getId() || user.getRole().equalsIgnoreCase("admin")) {
questionService.deleteQuestion(questionId);
return new ResponseEntity<>("Question and it'sId " + questionId + " deleted.", HttpStatus.OK);
}
else {
return new ResponseEntity<>("You can't delete this question!", HttpStatus.FORBIDDEN);
}
}
}
}
| 3,793 | 0.669127 | 0.669127 | 99 | 37.313129 | 34.821522 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464646 | false | false | 8 |
69eba6314c9064d1b48261ca8ec1b3995ddd66fd | 30,459,908,103,775 | bd4c54391aa43dd451408479dca6a20789acad1f | /src/main/java/com/example/jenkins_test/controller.java | dde66c38fb05f312edc17890a5dfe307068d3329 | [] | no_license | mekvn123/jenkins-test-demo | https://github.com/mekvn123/jenkins-test-demo | 413afbc50a311afea0aa5c8f7529f315d7ccfee9 | 43ed852cf9af225ffe7970b0f2c06663b46b04d7 | refs/heads/master | 2023-08-30T07:54:44.245000 | 2021-11-02T02:07:32 | 2021-11-02T02:07:32 | 423,373,159 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jenkins_test;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class controller {
@GetMapping("/hello")
public void getHello() {
System.out.println("this is a test hello Api.");
}
}
| UTF-8 | Java | 320 | java | controller.java | Java | [] | null | [] | package com.example.jenkins_test;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class controller {
@GetMapping("/hello")
public void getHello() {
System.out.println("this is a test hello Api.");
}
}
| 320 | 0.740625 | 0.740625 | 12 | 25.666666 | 22.008837 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 8 |
8e1ab7abccd68ad4caefd82bbeecd5bc42657278 | 8,710,193,711,685 | ae5c07fafa192f177f3edc395cd2aa2452163e5a | /Factorial.java | ff531ea636009f0cdec54edec6afa9355583395a | [] | no_license | anushapeddigar/Program-Structures-and-Algorithms-INFO6205 | https://github.com/anushapeddigar/Program-Structures-and-Algorithms-INFO6205 | e41291505a7e1acbc444c84093dc7bf879709984 | 291ddcf6c9ce0a4b596aeb4eba9f9b41a99eae38 | refs/heads/main | 2023-04-22T23:08:00.408000 | 2021-05-12T20:15:19 | 2021-05-12T20:15:19 | 366,839,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Anusha Peddigari
* 001023769
*/
package Test;
/**
*
* @author 16175
*/
public class Factorial {
public static int getFactorial(int n)
{
return ( n==0 || n==2 || n==1) ? n : n * getFactorial(n - 1);
}
public static void main(String[] args) {
int n = 5;
System.out.println("Factorial of "+n+" is :" + getFactorial(n));
}
}
| UTF-8 | Java | 378 | java | Factorial.java | Java | [
{
"context": "/*\r\n * Anusha Peddigari\r\n * 001023769\r\n */\r\npackage Test;\r\n\r\n/**\r\n *\r\n * ",
"end": 23,
"score": 0.9998826384544373,
"start": 7,
"tag": "NAME",
"value": "Anusha Peddigari"
},
{
"context": "023769\r\n */\r\npackage Test;\r\n\r\n/**\r\n *\r\n * @author 1617... | null | [] | /*
* <NAME>
* 001023769
*/
package Test;
/**
*
* @author 16175
*/
public class Factorial {
public static int getFactorial(int n)
{
return ( n==0 || n==2 || n==1) ? n : n * getFactorial(n - 1);
}
public static void main(String[] args) {
int n = 5;
System.out.println("Factorial of "+n+" is :" + getFactorial(n));
}
}
| 368 | 0.537037 | 0.486772 | 25 | 13.12 | 19.161043 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 8 |
9565bacb8f8b35ca48b3f61f862f74fb712e9a57 | 2,173,253,501,938 | c4c3c07aae0ed47399bf46c3847548530f3d238f | /src/main/java/com/chinesedreamer/rating/rating/repository/RatingScoreViewRepository.java | 73c65671532bab87a28ddde43077305d5899fa7b | [] | no_license | Sos10086tsj/rating | https://github.com/Sos10086tsj/rating | 99fa1d5c4b8706d56b9a8f209fe4041927d108cd | 41ff928af2375f5df2db51818fe1de284d5aa0b4 | refs/heads/master | 2021-01-18T21:56:56.845000 | 2017-01-04T07:47:58 | 2017-01-04T07:47:58 | 37,579,003 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chinesedreamer.rating.rating.repository;
import java.util.List;
import com.chinesedreamer.rating.base.jpa.repository.BaseRepository;
import com.chinesedreamer.rating.rating.model.RatingScoreView;
/**
* Description:
* @author Paris
* @date Jul 2, 20159:47:02 AM
* @version beta
*/
public interface RatingScoreViewRepository extends BaseRepository<RatingScoreView, Long>{
public List<RatingScoreView> findByTmplId(Long tmplId);
public List<RatingScoreView> findByTmplIdAndScorer(Long tmplId, Long scorer);
public List<RatingScoreView> findByTmplIdIn(List<Long> tmplIds);
}
| UTF-8 | Java | 595 | java | RatingScoreViewRepository.java | Java | [
{
"context": ".RatingScoreView;\n\n/**\n * Description: \n * @author Paris\n * @date Jul 2, 20159:47:02 AM\n * @version beta\n ",
"end": 248,
"score": 0.9970370531082153,
"start": 243,
"tag": "NAME",
"value": "Paris"
}
] | null | [] | package com.chinesedreamer.rating.rating.repository;
import java.util.List;
import com.chinesedreamer.rating.base.jpa.repository.BaseRepository;
import com.chinesedreamer.rating.rating.model.RatingScoreView;
/**
* Description:
* @author Paris
* @date Jul 2, 20159:47:02 AM
* @version beta
*/
public interface RatingScoreViewRepository extends BaseRepository<RatingScoreView, Long>{
public List<RatingScoreView> findByTmplId(Long tmplId);
public List<RatingScoreView> findByTmplIdAndScorer(Long tmplId, Long scorer);
public List<RatingScoreView> findByTmplIdIn(List<Long> tmplIds);
}
| 595 | 0.803361 | 0.786555 | 18 | 32.055557 | 30.011984 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 8 |
7c42492b6c6efcd161a0e3e696a2664ec34303ff | 21,294,447,902,409 | 6ed31f045fd77eebceea0ff4969507383509d018 | /src/properties/ApplicationStrings.java | 272d32b41bacdf1c054f6e42a50b2c72f3cce8b7 | [] | no_license | willamys/CitiesseExec | https://github.com/willamys/CitiesseExec | a35eaa6b5761fabfc91453152a78cb6c778a7e60 | 14659cfd056cd0a0b89b3604739d43fe9e3be88f | refs/heads/master | 2020-05-27T04:10:08.073000 | 2012-05-22T14:15:46 | 2012-05-22T14:15:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package properties;
public enum ApplicationStrings {
GMSEXECUTIONTEST_ERROR_MESSAGE_INSERT_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_UPDATE_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_DELETE_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_LIST_ALL_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_LIST_EXECUTIONTEST,
GMSRESULT_ERROR_MESSAGE_INSERT_RESULT,
GMSRESULT_ERROR_MESSAGE_UPDATE_RESULT,
GMSRESULT_ERROR_MESSAGE_DELETE_RESULT,
GMSRESULT_ERROR_MESSAGE_LIST_ALL_RESULT,
GMSRESULT_ERROR_MESSAGE_LIST_RESULT,
GMSTESTCASE_ERROR_MESSAGE_INSERT_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_UPDATE_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_DELETE_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_LIST_ALL_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_LIST_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_INSERT_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_UPDATE_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_DELETE_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_LIST_ALL_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_LIST_TESTCASE
}
| UTF-8 | Java | 1,000 | java | ApplicationStrings.java | Java | [] | null | [] | package properties;
public enum ApplicationStrings {
GMSEXECUTIONTEST_ERROR_MESSAGE_INSERT_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_UPDATE_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_DELETE_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_LIST_ALL_EXECUTIONTEST,
GMSEXECUTIONTEST_ERROR_MESSAGE_LIST_EXECUTIONTEST,
GMSRESULT_ERROR_MESSAGE_INSERT_RESULT,
GMSRESULT_ERROR_MESSAGE_UPDATE_RESULT,
GMSRESULT_ERROR_MESSAGE_DELETE_RESULT,
GMSRESULT_ERROR_MESSAGE_LIST_ALL_RESULT,
GMSRESULT_ERROR_MESSAGE_LIST_RESULT,
GMSTESTCASE_ERROR_MESSAGE_INSERT_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_UPDATE_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_DELETE_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_LIST_ALL_TESTCASE,
GMSTESTCASE_ERROR_MESSAGE_LIST_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_INSERT_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_UPDATE_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_DELETE_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_LIST_ALL_TESTCASE,
GMSWORKFLOW_ERROR_MESSAGE_LIST_TESTCASE
}
| 1,000 | 0.811 | 0.811 | 28 | 33.714287 | 18.568132 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.535714 | false | false | 8 |
0a288e272bb5f1849e43d8c1497ccc97ea9e64f1 | 10,642,929,029,967 | 4ceb6fb7b15866aa1a078414931aad95301256f3 | /src/main/java/com/vishal/application/services/LogReadingService.java | e3f52f40b4f184f8add509e8deafe198463cc19f | [] | no_license | Vishal-Joshi/project-log-tracer | https://github.com/Vishal-Joshi/project-log-tracer | 822c965c010ac60d4d061f550e8028323519b04c | 54f517251a8850a524bf56ca7bf5f4c973ca371d | refs/heads/master | 2021-01-20T13:03:14.783000 | 2017-05-15T07:46:04 | 2017-05-15T07:46:04 | 90,439,921 | 0 | 0 | null | false | 2017-05-10T15:50:21 | 2017-05-06T05:34:48 | 2017-05-08T05:07:51 | 2017-05-10T15:50:21 | 19,299 | 0 | 0 | 0 | Groovy | null | null | package com.vishal.application.services;
import com.vishal.application.TraceObjectFactory;
import com.vishal.application.entity.Span;
import com.vishal.application.entity.Trace;
import com.vishal.application.exception.InternalServerError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vishal.joshi on 5/10/17.
*/
@Service
@Slf4j
public class LogReadingService {
private FileReadingService fileReadingService;
private SpanOrganisationService spanOrganisationService;
private TraceOrderingService traceOrderingService;
private TraceObjectFactory traceObjectFactory;
@Autowired
public LogReadingService(FileReadingService fileReadingService,
SpanOrganisationService spanOrganisationService,
TraceOrderingService traceOrderingService,
TraceObjectFactory traceObjectFactory) {
this.fileReadingService = fileReadingService;
this.spanOrganisationService = spanOrganisationService;
this.traceOrderingService = traceOrderingService;
this.traceObjectFactory = traceObjectFactory;
}
public List<Trace> buildTraceAndSpan(String logFileName) {
try {
List<Trace> resultantTraceList = new ArrayList<>();
fileReadingService.readFile(logFileName).entrySet()
.forEach(traceIdAndLogLineInfoListEntrySet -> {
Span root = spanOrganisationService.organiseRootSpanAndItsChildren(traceIdAndLogLineInfoListEntrySet.getValue());
resultantTraceList.add(traceObjectFactory.createTraceObject(traceIdAndLogLineInfoListEntrySet.getKey(), root));
});
return traceOrderingService.orderByStartDateOfRootSpan(resultantTraceList);
} catch (IOException ioException) {
log.error("Exception while reading log file with name:{}", logFileName, ioException);
throw new InternalServerError(String.format("Exception while reading log file with name:%s", logFileName), ioException);
}
}
}
| UTF-8 | Java | 2,274 | java | LogReadingService.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by vishal.joshi on 5/10/17.\n */\n@Service\n@Slf4j\npublic class LogR",
"end": 495,
"score": 0.952980101108551,
"start": 483,
"tag": "USERNAME",
"value": "vishal.joshi"
}
] | null | [] | package com.vishal.application.services;
import com.vishal.application.TraceObjectFactory;
import com.vishal.application.entity.Span;
import com.vishal.application.entity.Trace;
import com.vishal.application.exception.InternalServerError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by vishal.joshi on 5/10/17.
*/
@Service
@Slf4j
public class LogReadingService {
private FileReadingService fileReadingService;
private SpanOrganisationService spanOrganisationService;
private TraceOrderingService traceOrderingService;
private TraceObjectFactory traceObjectFactory;
@Autowired
public LogReadingService(FileReadingService fileReadingService,
SpanOrganisationService spanOrganisationService,
TraceOrderingService traceOrderingService,
TraceObjectFactory traceObjectFactory) {
this.fileReadingService = fileReadingService;
this.spanOrganisationService = spanOrganisationService;
this.traceOrderingService = traceOrderingService;
this.traceObjectFactory = traceObjectFactory;
}
public List<Trace> buildTraceAndSpan(String logFileName) {
try {
List<Trace> resultantTraceList = new ArrayList<>();
fileReadingService.readFile(logFileName).entrySet()
.forEach(traceIdAndLogLineInfoListEntrySet -> {
Span root = spanOrganisationService.organiseRootSpanAndItsChildren(traceIdAndLogLineInfoListEntrySet.getValue());
resultantTraceList.add(traceObjectFactory.createTraceObject(traceIdAndLogLineInfoListEntrySet.getKey(), root));
});
return traceOrderingService.orderByStartDateOfRootSpan(resultantTraceList);
} catch (IOException ioException) {
log.error("Exception while reading log file with name:{}", logFileName, ioException);
throw new InternalServerError(String.format("Exception while reading log file with name:%s", logFileName), ioException);
}
}
}
| 2,274 | 0.725154 | 0.721636 | 53 | 41.905659 | 34.975067 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641509 | false | false | 8 |
c35c5e514fe78a4708b83eaded8744a45ad70249 | 4,638,564,698,041 | c29117922fcfae3516095d76143bdf86c1e0b758 | /Pangeo/src/pangeo/main/world/SpritesheetType.java | 0e4fe66f98b0174f2047aa3cfd0e6e2c91338ca6 | [] | no_license | rangerofthewest/pangeo-code-java | https://github.com/rangerofthewest/pangeo-code-java | b3b5dabfb0dc6f6c4135dab686691420d931c438 | d3a92eb9bf2b5e7fbe1f8699e7286da01567c528 | refs/heads/master | 2019-05-16T09:57:58.033000 | 2016-07-04T21:33:43 | 2016-07-04T21:36:22 | 27,643,445 | 1 | 1 | null | false | 2016-04-24T15:40:24 | 2014-12-06T17:59:49 | 2016-02-11T23:12:11 | 2016-04-24T15:40:23 | 621,349 | 1 | 0 | 20 | HTML | null | null | package pangeo.main.world;
public enum SpritesheetType {
Normal,
Torch,
Vegetation
}
| UTF-8 | Java | 89 | java | SpritesheetType.java | Java | [] | null | [] | package pangeo.main.world;
public enum SpritesheetType {
Normal,
Torch,
Vegetation
}
| 89 | 0.764045 | 0.764045 | 7 | 11.714286 | 10.633025 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 8 |
4ae1d4737c745c56667e17f0111a87674d0ae00c | 22,643,067,632,672 | eafa53d6815402a23645b33eb5798a499129d34b | /app/src/main/java/tech/ceece/opencircle/SignUp.java | d1305ebbb7be62cfa5c13bb4b26a293dd4d496d1 | [] | no_license | yashjain27/Open-Circle-Android-App | https://github.com/yashjain27/Open-Circle-Android-App | e77394af8fc863148f94f96c8387e0d83af1b85d | 5456af4f6af512a63656f8aef792a015acd23eda | refs/heads/master | 2021-06-18T08:10:10.407000 | 2017-07-02T21:21:27 | 2017-07-02T21:21:27 | 91,845,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tech.ceece.opencircle;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.IntentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.InputMismatchException;
public class SignUp extends AppCompatActivity {
//Data field
private EditText editText;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_signup);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void onSignUp(View v){
editText = (EditText) findViewById(R.id.editText);
final String userName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText2);
final String firstName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText3);
final String lastName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText4);
final String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText5);
final String phoneNumber = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText6);
String password = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText9);
String rePassword = editText.getText().toString();
try {
final Password pass = new Password(password);
if(!password.equals(rePassword))
throw new InputMismatchException();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
addToDataBase(userName, firstName + " " + lastName, email, phoneNumber, pass);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignUp.this, "Invalid email. Please use a valid email.", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IllegalPasswordException e) {
Toast.makeText(this, "Password must be 6 characters long, one lower case, one upper case, one digit, and one\n" +
" * special character (~!@#$%^&*()_+)" + e.toString(), Toast.LENGTH_SHORT).show();
} catch (InputMismatchException e) {
Toast.makeText(this, "Passwords don't match! Try again!", Toast.LENGTH_SHORT).show();
}
}
public void addToDataBase(String userName, String fullName, String email, String phoneNumber, Password pass){
try {
//Create account and try adding to the DataBase
Account account = new Account(userName, fullName, email, phoneNumber);
Toast.makeText(this, "Congratulations! You have successfully signed up!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, UserActivity.class);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mDatabase.child(user.getUid()).setValue(account);
startActivity(intent);
finish();
} catch (InputMismatchException e) {
Toast.makeText(this, "Passwords don't match! Try again!", Toast.LENGTH_SHORT).show();
}
}
}
| UTF-8 | Java | 4,427 | java | SignUp.java | Java | [
{
"context": " addToDataBase(userName, firstName + \" \" + lastName, email, phoneNumber, pass);\n ",
"end": 2698,
"score": 0.998792290687561,
"start": 2689,
"tag": "NAME",
"value": "firstName"
},
{
"context": " addToDataBase(userName, firstName + ... | null | [] | package tech.ceece.opencircle;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.IntentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.InputMismatchException;
public class SignUp extends AppCompatActivity {
//Data field
private EditText editText;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_signup);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void onSignUp(View v){
editText = (EditText) findViewById(R.id.editText);
final String userName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText2);
final String firstName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText3);
final String lastName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText4);
final String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText5);
final String phoneNumber = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText6);
String password = editText.getText().toString();
editText = (EditText) findViewById(R.id.editText9);
String rePassword = editText.getText().toString();
try {
final Password pass = new Password(password);
if(!password.equals(rePassword))
throw new InputMismatchException();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
addToDataBase(userName, firstName + " " + lastName, email, phoneNumber, pass);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignUp.this, "Invalid email. Please use a valid email.", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IllegalPasswordException e) {
Toast.makeText(this, "Password must be 6 characters long, one lower case, one upper case, one digit, and one\n" +
" * special character (~!@#$%^&*()_+)" + e.toString(), Toast.LENGTH_SHORT).show();
} catch (InputMismatchException e) {
Toast.makeText(this, "Passwords don't match! Try again!", Toast.LENGTH_SHORT).show();
}
}
public void addToDataBase(String userName, String fullName, String email, String phoneNumber, Password pass){
try {
//Create account and try adding to the DataBase
Account account = new Account(userName, fullName, email, phoneNumber);
Toast.makeText(this, "Congratulations! You have successfully signed up!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, UserActivity.class);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mDatabase.child(user.getUid()).setValue(account);
startActivity(intent);
finish();
} catch (InputMismatchException e) {
Toast.makeText(this, "Passwords don't match! Try again!", Toast.LENGTH_SHORT).show();
}
}
}
| 4,427 | 0.64197 | 0.639937 | 92 | 47.119564 | 30.924467 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923913 | false | false | 8 |
7c7b66c0ad596111a8be8d42e350401dce2c4d93 | 867,583,432,531 | da86ab22b62aa65e8f61b77fc0a76bbe4a951bab | /Probability & Sampling/380.InsertDeleteGetRandom.java | 92b6741aa0e7a3e2d2d631a2669e1528b53fe4d0 | [] | no_license | rainite/algorithm-exercise-notebook | https://github.com/rainite/algorithm-exercise-notebook | 4e5a128441a2df9af708285e12089b15d052b803 | 798489505cdf9579e98b33915eb0f91b076e1f3b | refs/heads/master | 2022-06-30T00:59:00.199000 | 2022-05-17T06:57:33 | 2022-05-17T06:57:33 | 203,053,866 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
思路: 主要用hashset 记录 val 的index, arraylist记录val;
insert:
arraylist加尾巴
map记录index
delete
思路为吧delete的元素照出来,用array尾部的元素替换, 如果本来就是最后一个元素, 直接删
1. get index of val
2. 记录array最后一个值temp
3. set (index,temp) [交换]
4. 删除array中最后一个元素
5. 删除map中这个元素val
6. 更新map记录新的index of temp
getRandom
直接公式取就好
*/
class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> res;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
res = new ArrayList<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
map.put(val, res.size());
res.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
int index = map.get(val);
if (index < res.size() - 1) {
int temp = res.get(res.size() - 1);
res.set(index, temp);
map.put(temp, index);
}
map.remove(val);
res.remove(res.size() - 1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int) (Math.random() * res.size());
return res.get(random);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/ | UTF-8 | Java | 1,760 | java | 380.InsertDeleteGetRandom.java | Java | [] | null | [] | /**
思路: 主要用hashset 记录 val 的index, arraylist记录val;
insert:
arraylist加尾巴
map记录index
delete
思路为吧delete的元素照出来,用array尾部的元素替换, 如果本来就是最后一个元素, 直接删
1. get index of val
2. 记录array最后一个值temp
3. set (index,temp) [交换]
4. 删除array中最后一个元素
5. 删除map中这个元素val
6. 更新map记录新的index of temp
getRandom
直接公式取就好
*/
class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> res;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
res = new ArrayList<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
map.put(val, res.size());
res.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
int index = map.get(val);
if (index < res.size() - 1) {
int temp = res.get(res.size() - 1);
res.set(index, temp);
map.put(temp, index);
}
map.remove(val);
res.remove(res.size() - 1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int) (Math.random() * res.size());
return res.get(random);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/ | 1,760 | 0.644836 | 0.63728 | 66 | 23.075758 | 20.634855 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false | 8 |
c327103165832a135c8160b42de36806f14302c1 | 35,029,753,288,386 | 858d66873ab6e459e82a8f090f29ad366dcf8f2b | /EAM2.0/tsrdp/src/main/java/com/tiansu/eam/modules/sys/dao/EamDictDao.java | e994fdcc1fa0ec9bb61443f525ab97df3de8a008 | [
"Apache-2.0"
] | permissive | duanfuju/EAM2.0 | https://github.com/duanfuju/EAM2.0 | 286c2b5c0165190eb4184835af6ece0564e7b4c5 | 18d6c7561af1659039f5ec2259506d7c6d0c2ec1 | refs/heads/master | 2020-03-16T17:25:44.244000 | 2018-05-10T01:29:45 | 2018-05-10T01:29:45 | 132,831,854 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tiansu.eam.modules.sys.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.tiansu.eam.modules.sys.entity.Dict;
import java.util.List;
import java.util.Map;
/**
* Created by wujh on 2017/7/26.
* 字典DAO接口
*/
@MyBatisDao
public interface EamDictDao extends CrudDao<Dict> {
public List<String> findTypeList(Dict dict);
/**
* 根据主键Id获取设备类别信息
* @param id
* @return
*/
public Map<String,Object> getEdit(String id);
/**
* 根据实体对象删除符合条件记录
* @param dict
* @return
*/
public int delete(Dict dict);
public List<Dict> getByCode(String typeCode);
}
| UTF-8 | Java | 768 | java | EamDictDao.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by wujh on 2017/7/26.\n * 字典DAO接口\n */\n@MyBatisDao\npublic i",
"end": 283,
"score": 0.9995874762535095,
"start": 279,
"tag": "USERNAME",
"value": "wujh"
}
] | null | [] | package com.tiansu.eam.modules.sys.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.tiansu.eam.modules.sys.entity.Dict;
import java.util.List;
import java.util.Map;
/**
* Created by wujh on 2017/7/26.
* 字典DAO接口
*/
@MyBatisDao
public interface EamDictDao extends CrudDao<Dict> {
public List<String> findTypeList(Dict dict);
/**
* 根据主键Id获取设备类别信息
* @param id
* @return
*/
public Map<String,Object> getEdit(String id);
/**
* 根据实体对象删除符合条件记录
* @param dict
* @return
*/
public int delete(Dict dict);
public List<Dict> getByCode(String typeCode);
}
| 768 | 0.683616 | 0.673729 | 34 | 19.82353 | 19.626619 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323529 | false | false | 8 |
b196babbb5281b5818ed402e6c12a226b3c23c8f | 36,060,545,442,215 | 1e9b897571b91413dca6e2b9d7bdd649bc94b12d | /src/main/java/com/mikayelovich/part1/cheesr/model/Cart.java | cb5df40042a69af841bfbe643d94f13597d843ee | [] | no_license | ArmanMikayelovich/wicket-example | https://github.com/ArmanMikayelovich/wicket-example | 1d15071b6a32e46582264e5936c90cbe13e79c99 | be0f8d41a52f7dadcb0e14d5c1e62a546692bafe | refs/heads/master | 2023-01-23T22:10:22.477000 | 2020-12-04T14:32:16 | 2020-12-04T14:32:16 | 317,312,425 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mikayelovich.part1.cheesr.model;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Data
public class Cart implements Serializable {
private List<Cheese> cheeses = new ArrayList<>();
private Address billingAddress = new Address();
public Double getTotal() {
double total = 0;
for (Cheese cheese : cheeses) {
total += cheese.getPrice();
}
return total;
}
}
| UTF-8 | Java | 487 | java | Cart.java | Java | [] | null | [] | package com.mikayelovich.part1.cheesr.model;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Data
public class Cart implements Serializable {
private List<Cheese> cheeses = new ArrayList<>();
private Address billingAddress = new Address();
public Double getTotal() {
double total = 0;
for (Cheese cheese : cheeses) {
total += cheese.getPrice();
}
return total;
}
}
| 487 | 0.652977 | 0.648871 | 26 | 17.73077 | 18.101334 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 8 |
35398700a4de11359e71dc60ab0537d537c784fe | 37,417,755,087,939 | 4cba327066a1495355509c9f14bc195c98741e8a | /Module02/src/package_07/Io_07.java | 94fdb17959baa4d707e20e6f1ec8e1a6f45b3669 | [] | no_license | lai864/Project01 | https://github.com/lai864/Project01 | ba08218d5d65ed27ccd432196d218aea68568459 | 266e4e83de558b5f24ca03f83d23fcbbfd69b98e | refs/heads/master | 2023-09-03T07:46:46.531000 | 2021-11-04T02:29:41 | 2021-11-04T02:29:41 | 424,447,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package package_07;
import java.util.Properties;
import java.util.Set;
/*特殊操作流
* Properties作为Map集合的使用*/
/*Properties作为集合的特有方法
* setProperty(String key, String value): 设置集合的键和值,都是String类型,调用方法 put Hashtable。
* String getProperty(String key):使用此属性列表中指定的键搜索属性
* stringPropertyNames() :在这个属性列表中返回一组不可修改的键集,其中键和它的对应值是字符串
*/
public class Io_07 {
public static void main(String[] args) {
Properties prop = new Properties();//使用Object类
prop.put("a0001","巨魔叔叔");
prop.put("a0002","混世魔王");
prop.put("a0003","王祖贤");
Set<Object> keySet = prop.keySet();
for (Object key:keySet) {
Object value = prop.get(key);
System.out.println(key + "," + value);
}
System.out.println("...................");
/*Properties作为集合的特有方法
* setProperty(String key, String value):
* 设置集合的键和值,都是String类型,调用方法 put Hashtable。*/
prop.setProperty("a0004","b站小霸王");
prop.setProperty("a0005","b站叔叔");
prop.setProperty("a0006","法外狂徒");
// String getProperty(String key):使用此属性列表中指定的键搜索属性
System.out.println(prop.getProperty("a0004"));
//stringPropertyNames() :在这个属性列表中返回一组不可修改的键集,其中键和它的对应值是字符串
Set<String> propertyNames = prop.stringPropertyNames();
for (String keys:propertyNames){
String values = prop.getProperty(keys);
System.out.println(keys+","+values);
}
}
}
| UTF-8 | Java | 1,864 | java | Io_07.java | Java | [] | null | [] | package package_07;
import java.util.Properties;
import java.util.Set;
/*特殊操作流
* Properties作为Map集合的使用*/
/*Properties作为集合的特有方法
* setProperty(String key, String value): 设置集合的键和值,都是String类型,调用方法 put Hashtable。
* String getProperty(String key):使用此属性列表中指定的键搜索属性
* stringPropertyNames() :在这个属性列表中返回一组不可修改的键集,其中键和它的对应值是字符串
*/
public class Io_07 {
public static void main(String[] args) {
Properties prop = new Properties();//使用Object类
prop.put("a0001","巨魔叔叔");
prop.put("a0002","混世魔王");
prop.put("a0003","王祖贤");
Set<Object> keySet = prop.keySet();
for (Object key:keySet) {
Object value = prop.get(key);
System.out.println(key + "," + value);
}
System.out.println("...................");
/*Properties作为集合的特有方法
* setProperty(String key, String value):
* 设置集合的键和值,都是String类型,调用方法 put Hashtable。*/
prop.setProperty("a0004","b站小霸王");
prop.setProperty("a0005","b站叔叔");
prop.setProperty("a0006","法外狂徒");
// String getProperty(String key):使用此属性列表中指定的键搜索属性
System.out.println(prop.getProperty("a0004"));
//stringPropertyNames() :在这个属性列表中返回一组不可修改的键集,其中键和它的对应值是字符串
Set<String> propertyNames = prop.stringPropertyNames();
for (String keys:propertyNames){
String values = prop.getProperty(keys);
System.out.println(keys+","+values);
}
}
}
| 1,864 | 0.610661 | 0.589069 | 49 | 29.244898 | 23.285742 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 8 |
8ce47b7629cd770c2f178160de760bf9aa61d01e | 35,596,688,968,447 | 827b3976c4bb363fbee1f196877ac2eb40630936 | /src/com/snakybo/sengine/model/Model.java | f74ecd6400fd6a62e03e16c27c9cb040372edad5 | [
"MIT"
] | permissive | dreamsxin/SEngine2 | https://github.com/dreamsxin/SEngine2 | 0a7fd7ba8a9e5e5db059af93cf1300a10ca4a24b | 1394b3fabf4f27a3f9eda68566ea47ac4a97affc | refs/heads/master | 2016-12-31T05:43:42.591000 | 2016-04-07T22:11:33 | 2016-04-07T22:11:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // The MIT License(MIT)
//
// Copyright(c) 2016 Kevin Krol
//
// 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.snakybo.sengine.model;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector2f;
import org.joml.Vector3f;
/**
* @author Snakybo
* @since 1.0
*/
public final class Model
{
private List<Vector3f> vertices;
private List<Vector2f> texCoords;
private List<Vector3f> normals;
private List<Vector3f> tangents;
private List<Integer> indices;
/**
* Create a new model
*/
public Model()
{
vertices = new ArrayList<Vector3f>();
texCoords = new ArrayList<Vector2f>();
normals = new ArrayList<Vector3f>();
tangents = new ArrayList<Vector3f>();
indices = new ArrayList<Integer>();
}
/**
* Attempt to calculate the normals of a model automatically
*/
public final void generateNormals()
{
for(int i = 0; i < indices.size(); i += 3)
{
int i0 = indices.get(i);
int i1 = indices.get(i + 1);
int i2 = indices.get(i + 2);
Vector3f v1 = new Vector3f();
vertices.get(i1).sub(vertices.get(i0), v1);
Vector3f v2 = new Vector3f();
vertices.get(i2).sub(vertices.get(i0), v2);
Vector3f normal = new Vector3f();
v1.cross(v2, normal).normalize();
normals.get(i0).add(normal);
normals.get(i1).add(normal);
normals.get(i2).add(normal);
}
for(int i = 0; i < normals.size(); i++)
{
normals.get(i).normalize();
}
}
/**
* Attempt to calculate the tangents of a model automatically
*/
public final void generateTangents()
{
for(int i = 0; i < indices.size(); i += 3)
{
int i0 = indices.get(i);
int i1 = indices.get(i + 1);
int i2 = indices.get(i + 2);
Vector3f edge1 = new Vector3f();
vertices.get(i1).sub(vertices.get(i0), edge1);
Vector3f edge2 = new Vector3f();
vertices.get(i2).sub(vertices.get(i0), edge2);
float deltaU1 = texCoords.get(i1).x - texCoords.get(i0).x;
float deltaV1 = texCoords.get(i1).y - texCoords.get(i0).y;
float deltaU2 = texCoords.get(i2).x - texCoords.get(i0).x;
float deltaV2 = texCoords.get(i2).y - texCoords.get(i0).y;
float dividend = deltaU1 * deltaV2 - deltaU2 * deltaV1;
float f = dividend == 0 ? 0 : 1 / dividend;
Vector3f tangent = new Vector3f();
tangent.x = f * (deltaV2 * edge1.x - deltaV1 * edge2.x);
tangent.y = f * (deltaV2 * edge1.y - deltaV1 * edge2.y);
tangent.z = f * (deltaV2 * edge1.z - deltaV1 * edge2.z);
tangents.get(i0).add(tangent);
tangents.get(i1).add(tangent);
tangents.get(i2).add(tangent);
}
for(int i = 0; i < tangents.size(); i++)
{
tangents.get(i).normalize();
}
}
/**
* Add a vertex to the model
* @param vertex - The vertex to add
*/
public final void addVertex(Vector3f vertex)
{
vertices.add(vertex);
}
/**
* Add a texture coordinate to the model
* @param texCoord - The texture coordinate to add
*/
public final void addTexCoord(Vector2f texCoord)
{
texCoords.add(texCoord);
}
/**
* Add a normal to the model
* @param normal - The model to add
*/
public final void addNormal(Vector3f normal)
{
normals.add(normal);
}
/**
* Add a tangent to the model
* @param tangent - The tangent to add
*/
public final void addTangent(Vector3f tangent)
{
tangents.add(tangent);
}
/**
* Add a single index to the model
* @param index - The index to add
*/
public final void addIndex(int index)
{
indices.add(index);
}
/**
* Add a face, or 3 indices to the model
* @param i0 - The first index
* @param i1 - The second index
* @param i2 - The third index
*/
public final void addFace(int i0, int i1, int i2)
{
addIndex(i0);
addIndex(i1);
addIndex(i2);
}
/**
* @return The vertices of the model
*/
public final List<Vector3f> getVertices()
{
return vertices;
}
/**
* @return The texture coordinates of the model
*/
public final List<Vector2f> getTexCoords()
{
return texCoords;
}
/**
* @return The normals of the model
*/
public final List<Vector3f> getNormals()
{
return normals;
}
/**
* @return The tangents of the model
*/
public final List<Vector3f> getTangents()
{
return tangents;
}
/**
* @return The indices of the model
*/
public final List<Integer> getIndices()
{
return indices;
}
/**
* @return The number of indices the model contains
*/
public final int getNumIndices()
{
return indices.size();
}
/**
* @return The number of triangles, or faces the model contains
*/
public final int getNumTriangles()
{
return indices.size() / 3;
}
}
| UTF-8 | Java | 5,609 | java | Model.java | Java | [
{
"context": "// The MIT License(MIT)\n//\n// Copyright(c) 2016 Kevin Krol\n//\n// Permission is hereby granted, free of charg",
"end": 58,
"score": 0.9998598098754883,
"start": 48,
"tag": "NAME",
"value": "Kevin Krol"
},
{
"context": "ector2f;\nimport org.joml.Vector3f;\n\n/**\n * @... | null | [] | // The MIT License(MIT)
//
// Copyright(c) 2016 <NAME>
//
// 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.snakybo.sengine.model;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector2f;
import org.joml.Vector3f;
/**
* @author Snakybo
* @since 1.0
*/
public final class Model
{
private List<Vector3f> vertices;
private List<Vector2f> texCoords;
private List<Vector3f> normals;
private List<Vector3f> tangents;
private List<Integer> indices;
/**
* Create a new model
*/
public Model()
{
vertices = new ArrayList<Vector3f>();
texCoords = new ArrayList<Vector2f>();
normals = new ArrayList<Vector3f>();
tangents = new ArrayList<Vector3f>();
indices = new ArrayList<Integer>();
}
/**
* Attempt to calculate the normals of a model automatically
*/
public final void generateNormals()
{
for(int i = 0; i < indices.size(); i += 3)
{
int i0 = indices.get(i);
int i1 = indices.get(i + 1);
int i2 = indices.get(i + 2);
Vector3f v1 = new Vector3f();
vertices.get(i1).sub(vertices.get(i0), v1);
Vector3f v2 = new Vector3f();
vertices.get(i2).sub(vertices.get(i0), v2);
Vector3f normal = new Vector3f();
v1.cross(v2, normal).normalize();
normals.get(i0).add(normal);
normals.get(i1).add(normal);
normals.get(i2).add(normal);
}
for(int i = 0; i < normals.size(); i++)
{
normals.get(i).normalize();
}
}
/**
* Attempt to calculate the tangents of a model automatically
*/
public final void generateTangents()
{
for(int i = 0; i < indices.size(); i += 3)
{
int i0 = indices.get(i);
int i1 = indices.get(i + 1);
int i2 = indices.get(i + 2);
Vector3f edge1 = new Vector3f();
vertices.get(i1).sub(vertices.get(i0), edge1);
Vector3f edge2 = new Vector3f();
vertices.get(i2).sub(vertices.get(i0), edge2);
float deltaU1 = texCoords.get(i1).x - texCoords.get(i0).x;
float deltaV1 = texCoords.get(i1).y - texCoords.get(i0).y;
float deltaU2 = texCoords.get(i2).x - texCoords.get(i0).x;
float deltaV2 = texCoords.get(i2).y - texCoords.get(i0).y;
float dividend = deltaU1 * deltaV2 - deltaU2 * deltaV1;
float f = dividend == 0 ? 0 : 1 / dividend;
Vector3f tangent = new Vector3f();
tangent.x = f * (deltaV2 * edge1.x - deltaV1 * edge2.x);
tangent.y = f * (deltaV2 * edge1.y - deltaV1 * edge2.y);
tangent.z = f * (deltaV2 * edge1.z - deltaV1 * edge2.z);
tangents.get(i0).add(tangent);
tangents.get(i1).add(tangent);
tangents.get(i2).add(tangent);
}
for(int i = 0; i < tangents.size(); i++)
{
tangents.get(i).normalize();
}
}
/**
* Add a vertex to the model
* @param vertex - The vertex to add
*/
public final void addVertex(Vector3f vertex)
{
vertices.add(vertex);
}
/**
* Add a texture coordinate to the model
* @param texCoord - The texture coordinate to add
*/
public final void addTexCoord(Vector2f texCoord)
{
texCoords.add(texCoord);
}
/**
* Add a normal to the model
* @param normal - The model to add
*/
public final void addNormal(Vector3f normal)
{
normals.add(normal);
}
/**
* Add a tangent to the model
* @param tangent - The tangent to add
*/
public final void addTangent(Vector3f tangent)
{
tangents.add(tangent);
}
/**
* Add a single index to the model
* @param index - The index to add
*/
public final void addIndex(int index)
{
indices.add(index);
}
/**
* Add a face, or 3 indices to the model
* @param i0 - The first index
* @param i1 - The second index
* @param i2 - The third index
*/
public final void addFace(int i0, int i1, int i2)
{
addIndex(i0);
addIndex(i1);
addIndex(i2);
}
/**
* @return The vertices of the model
*/
public final List<Vector3f> getVertices()
{
return vertices;
}
/**
* @return The texture coordinates of the model
*/
public final List<Vector2f> getTexCoords()
{
return texCoords;
}
/**
* @return The normals of the model
*/
public final List<Vector3f> getNormals()
{
return normals;
}
/**
* @return The tangents of the model
*/
public final List<Vector3f> getTangents()
{
return tangents;
}
/**
* @return The indices of the model
*/
public final List<Integer> getIndices()
{
return indices;
}
/**
* @return The number of indices the model contains
*/
public final int getNumIndices()
{
return indices.size();
}
/**
* @return The number of triangles, or faces the model contains
*/
public final int getNumTriangles()
{
return indices.size() / 3;
}
}
| 5,605 | 0.66215 | 0.641113 | 240 | 22.370832 | 22.405914 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.725 | false | false | 8 |
7003b394519cb94a26e18e7b863485d06d9dd983 | 7,584,912,300,343 | 97429fe36b8abd0c2030c91302210ca36dde4400 | /NeomindFornecedores/src/main/java/br/com/neomind/EM/EntidadeManager.java | 4163d5dfdfc7fd1cc3a22ca07279e0ebc79bd17f | [] | no_license | rafacendron2009/CadastroFornecedores | https://github.com/rafacendron2009/CadastroFornecedores | c0d34bdc2a3ea82a18109ee0e18b86e960dbddc7 | 91f90b3a26e92fe05a40010ed4823a69b5e51790 | refs/heads/master | 2022-06-23T14:00:35.503000 | 2020-02-02T22:19:54 | 2020-02-02T22:19:54 | 237,843,613 | 0 | 0 | null | false | 2022-02-10T01:18:00 | 2020-02-02T22:02:14 | 2020-02-02T22:20:29 | 2022-02-10T01:18:00 | 146 | 0 | 0 | 2 | JavaScript | false | false | package br.com.neomind.EM;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntidadeManager {
private EntityManagerFactory factory = Persistence.createEntityManagerFactory("fornecedores");
private EntityManager retorno = factory.createEntityManager();
public EntityManager getEntityManager(){
return retorno;
}
}
| UTF-8 | Java | 416 | java | EntidadeManager.java | Java | [] | null | [] | package br.com.neomind.EM;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntidadeManager {
private EntityManagerFactory factory = Persistence.createEntityManagerFactory("fornecedores");
private EntityManager retorno = factory.createEntityManager();
public EntityManager getEntityManager(){
return retorno;
}
}
| 416 | 0.819712 | 0.819712 | 16 | 25 | 26.872383 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 8 |
4daf538a014b7061e94f883d13fc72df74e00daa | 16,475,494,606,964 | af685aee30e35721f60859344b171eec54f76fa9 | /src/main/java/com/leetcode/category/offer/_09/ImplementAQueueWithTwoStacks.java | bb42761270ed37f45fedbede49bf0e958907b686 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | kirving0815/awesome-leetcode | https://github.com/kirving0815/awesome-leetcode | 5cfbeb989f9bb5ee0d24cf0b0c0866d3cc490fcf | 596348d000249c55dd1823672a559c92fd2aed9e | refs/heads/master | 2021-06-27T08:57:32.137000 | 2020-01-03T03:00:37 | 2020-01-03T03:00:37 | 143,891,775 | 0 | 0 | null | false | 2020-10-13T16:59:36 | 2018-08-07T15:17:23 | 2020-01-03T03:00:49 | 2020-10-13T16:59:35 | 90 | 0 | 0 | 1 | Java | false | false | package com.leetcode.category.offer._09;
import com.leetcode.category.common.util.ToolUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
/**
* 两个栈实现队列
*
* @author ZhouXu
* @version v1.0 2018-08-24
*/
public class ImplementAQueueWithTwoStacks {
private Stack<Integer> inStack = new Stack<>();
private Stack<Integer> outStack = new Stack<>();
public void push(int node) {
inStack.push(node);
}
public int pop() throws Exception {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
if (outStack.isEmpty()) {
throw new Exception("Queue is empty.");
}
return outStack.pop();
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
ImplementAQueueWithTwoStacks temp = new ImplementAQueueWithTwoStacks();
int[] arrIn = ToolUtil.stringToIntegerArray(line);
for (int i = 0; i < arrIn.length; i++) {
temp.push(arrIn[i]);
}
for (int i = 0; i < arrIn.length; i++) {
System.out.print(temp.pop() + " ");
}
}
}
}
| UTF-8 | Java | 1,407 | java | ImplementAQueueWithTwoStacks.java | Java | [
{
"context": "ort java.util.Stack;\n\n/**\n * 两个栈实现队列\n *\n * @author ZhouXu\n * @version v1.0 2018-08-24\n */\npublic class Impl",
"end": 219,
"score": 0.9992675185203552,
"start": 213,
"tag": "NAME",
"value": "ZhouXu"
}
] | null | [] | package com.leetcode.category.offer._09;
import com.leetcode.category.common.util.ToolUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
/**
* 两个栈实现队列
*
* @author ZhouXu
* @version v1.0 2018-08-24
*/
public class ImplementAQueueWithTwoStacks {
private Stack<Integer> inStack = new Stack<>();
private Stack<Integer> outStack = new Stack<>();
public void push(int node) {
inStack.push(node);
}
public int pop() throws Exception {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
if (outStack.isEmpty()) {
throw new Exception("Queue is empty.");
}
return outStack.pop();
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
ImplementAQueueWithTwoStacks temp = new ImplementAQueueWithTwoStacks();
int[] arrIn = ToolUtil.stringToIntegerArray(line);
for (int i = 0; i < arrIn.length; i++) {
temp.push(arrIn[i]);
}
for (int i = 0; i < arrIn.length; i++) {
System.out.print(temp.pop() + " ");
}
}
}
}
| 1,407 | 0.572864 | 0.562814 | 50 | 26.860001 | 22.525551 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.42 | false | false | 8 |
af576031c8b4aaf10a031905f9394090c7f99b48 | 30,090,540,943,137 | cc7c06ac7229fec368b274a8f49afab6e67728c3 | /core/src/main/java/com/newbee/demo/core/init/ContainerInitService.java | 6931ba7a2618d34b9b596b183c7db8e06d770207 | [] | no_license | Interesting-yum/demo-1 | https://github.com/Interesting-yum/demo-1 | 6193c76714b92e90edab925305e69d541b5135c4 | 89dc51b2fbee48963a3c6079340f1bb761966b7a | refs/heads/master | 2022-04-11T11:22:34.480000 | 2020-03-31T08:08:37 | 2020-03-31T08:08:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.newbee.demo.core.init;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author dingjiasheng@sinoiov.com
* @date 2019/10/20 22:06
* @description spring事件
*/
@Slf4j
@Component
public class ContainerInitService implements ApplicationListener<ApplicationStartedEvent> {
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
log.info("容器初始化完毕");
}
}
| UTF-8 | Java | 594 | java | ContainerInitService.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author dingjiasheng@sinoiov.com\n * @date 2019/10/20 22:06\n * @description spring事",
"end": 286,
"score": 0.9999128580093384,
"start": 262,
"tag": "EMAIL",
"value": "dingjiasheng@sinoiov.com"
}
] | null | [] | package com.newbee.demo.core.init;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author <EMAIL>
* @date 2019/10/20 22:06
* @description spring事件
*/
@Slf4j
@Component
public class ContainerInitService implements ApplicationListener<ApplicationStartedEvent> {
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
log.info("容器初始化完毕");
}
}
| 577 | 0.798611 | 0.772569 | 20 | 27.799999 | 28.207445 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 8 |
e3b678ea60e0e5cb6be636846298af9272697d76 | 31,069,793,454,043 | cf1338317856568ade29af63761b61ff876f1fc6 | /ex5/src/oop/ex5/filescript/filters/FilterFactory.java | 52c995240514c9f9511995932966f37db1d11aea | [] | no_license | shahamran/oop-2015 | https://github.com/shahamran/oop-2015 | 0439cff3b4c26d8eb6184815bfe55b456cd527cd | 953d6b1f22f43c5bfdbe9bcafa4794416fb07a16 | refs/heads/master | 2020-12-24T14:00:50.843000 | 2015-06-07T18:01:07 | 2015-06-07T18:01:07 | 31,860,472 | 0 | 0 | null | false | 2015-06-07T16:39:29 | 2015-03-08T18:30:58 | 2015-05-19T10:56:29 | 2015-06-07T16:39:28 | 1,296 | 0 | 0 | 0 | HTML | null | null | package oop.ex5.filescript.filters;
/**
* This class is in charge of creating new filter objects according to given values.
* @author ransha
*/
public class FilterFactory {
private static final String GREATER = "greater_than", SMALLER = "smaller_than", BETWEEN = "between",
FILE = "file", CONTAINS = "contains", PREFIX = "prefix", SUFFIX = "suffix",
WRITABLE = "writable", EXECUTABLE = "executable", HIDDEN = "hidden",
NOT = "NOT", ALL = "all";
private static final int FIRST_VAL = 1, SECOND_VAL = 2;
public static Filter createFilter(String[] values) throws FilterException {
if (values.length == 0)
return null;
Filter outFilter = null;
// The filter name should always be the first argument.
String filterName = values[0];
int expectedArgsLength;
// Switch statement uses an equivilent to s.equals() method and not reference comparison.
switch (filterName) {
case GREATER:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new GreaterThanFilter(Double.parseDouble(values[FIRST_VAL]));
break;
case SMALLER:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new SmallerThanFilter(Double.parseDouble(values[FIRST_VAL]));
break;
case BETWEEN:
expectedArgsLength = Filter.TWO_VALUES_FILTER_LENGTH;
double first = Double.parseDouble(values[FIRST_VAL]),
second = Double.parseDouble(values[SECOND_VAL]);
outFilter = new BetweenFilter(first,second);
break;
case FILE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new FileFilter(values[FIRST_VAL]);
break;
case CONTAINS:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new ContainsFilter(values[FIRST_VAL]);
break;
case PREFIX:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new PrefixFilter(values[FIRST_VAL]);
break;
case SUFFIX:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new SuffixFilter(values[FIRST_VAL]);
break;
case WRITABLE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new WritableFilter(values[FIRST_VAL]);
break;
case EXECUTABLE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new ExecutableFilter(values[FIRST_VAL]);
break;
case HIDDEN:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new HiddenFilter(values[FIRST_VAL]);
break;
case ALL:
expectedArgsLength = Filter.NO_VALUES_FILTER_LENGTH;
outFilter = new AllFilter();
break;
default:
// If other filter name was given, throw an exception.
throw new BadFilterNameException(filterName);
}
if (!isLegalValues(expectedArgsLength, values))
throw new BadFilterValueException();
if (isNegFilter(expectedArgsLength, values))
outFilter = new NegFilter(outFilter);
return outFilter;
}
/**
* @param expectedNumberOfValues The expected number of arguments.
* @param args The string args that were given.
* @return True if the right number of values was given, false otherwise.
*/
private static boolean isLegalValues(int expectedNumberOfValues, String[] args) {
return (args.length == expectedNumberOfValues ||
isNegFilter(expectedNumberOfValues,args));
}
/**
* @param expectedNumberOfValues The expected number of arguments.
* @param args The string args that were given.
* @return True if exactly one more argument was given, and the argument is "NOT"
*/
private static boolean isNegFilter(int expectedNumberOfValues, String[] args) {
return (args.length == expectedNumberOfValues + 1) &&
(args[expectedNumberOfValues].equals(NOT));
}
}
| UTF-8 | Java | 3,650 | java | FilterFactory.java | Java | [
{
"context": "lter objects according to given values.\n * @author ransha\n */\npublic class FilterFactory {\n\tprivate static ",
"end": 143,
"score": 0.9941909909248352,
"start": 137,
"tag": "USERNAME",
"value": "ransha"
}
] | null | [] | package oop.ex5.filescript.filters;
/**
* This class is in charge of creating new filter objects according to given values.
* @author ransha
*/
public class FilterFactory {
private static final String GREATER = "greater_than", SMALLER = "smaller_than", BETWEEN = "between",
FILE = "file", CONTAINS = "contains", PREFIX = "prefix", SUFFIX = "suffix",
WRITABLE = "writable", EXECUTABLE = "executable", HIDDEN = "hidden",
NOT = "NOT", ALL = "all";
private static final int FIRST_VAL = 1, SECOND_VAL = 2;
public static Filter createFilter(String[] values) throws FilterException {
if (values.length == 0)
return null;
Filter outFilter = null;
// The filter name should always be the first argument.
String filterName = values[0];
int expectedArgsLength;
// Switch statement uses an equivilent to s.equals() method and not reference comparison.
switch (filterName) {
case GREATER:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new GreaterThanFilter(Double.parseDouble(values[FIRST_VAL]));
break;
case SMALLER:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new SmallerThanFilter(Double.parseDouble(values[FIRST_VAL]));
break;
case BETWEEN:
expectedArgsLength = Filter.TWO_VALUES_FILTER_LENGTH;
double first = Double.parseDouble(values[FIRST_VAL]),
second = Double.parseDouble(values[SECOND_VAL]);
outFilter = new BetweenFilter(first,second);
break;
case FILE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new FileFilter(values[FIRST_VAL]);
break;
case CONTAINS:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new ContainsFilter(values[FIRST_VAL]);
break;
case PREFIX:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new PrefixFilter(values[FIRST_VAL]);
break;
case SUFFIX:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new SuffixFilter(values[FIRST_VAL]);
break;
case WRITABLE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new WritableFilter(values[FIRST_VAL]);
break;
case EXECUTABLE:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new ExecutableFilter(values[FIRST_VAL]);
break;
case HIDDEN:
expectedArgsLength = Filter.ONE_VALUE_FILTER_LENGTH;
outFilter = new HiddenFilter(values[FIRST_VAL]);
break;
case ALL:
expectedArgsLength = Filter.NO_VALUES_FILTER_LENGTH;
outFilter = new AllFilter();
break;
default:
// If other filter name was given, throw an exception.
throw new BadFilterNameException(filterName);
}
if (!isLegalValues(expectedArgsLength, values))
throw new BadFilterValueException();
if (isNegFilter(expectedArgsLength, values))
outFilter = new NegFilter(outFilter);
return outFilter;
}
/**
* @param expectedNumberOfValues The expected number of arguments.
* @param args The string args that were given.
* @return True if the right number of values was given, false otherwise.
*/
private static boolean isLegalValues(int expectedNumberOfValues, String[] args) {
return (args.length == expectedNumberOfValues ||
isNegFilter(expectedNumberOfValues,args));
}
/**
* @param expectedNumberOfValues The expected number of arguments.
* @param args The string args that were given.
* @return True if exactly one more argument was given, and the argument is "NOT"
*/
private static boolean isNegFilter(int expectedNumberOfValues, String[] args) {
return (args.length == expectedNumberOfValues + 1) &&
(args[expectedNumberOfValues].equals(NOT));
}
}
| 3,650 | 0.723562 | 0.721918 | 102 | 34.784313 | 26.752911 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.941176 | false | false | 8 |
0a566f455cfa01bb6cf7da7ee3c31386e9662f20 | 25,245,817,789,579 | 6c0ddb9dcfe3f716e6e9265b5c33c44709e8d6d1 | /src/main/java/com/dbs/sdwt/constant/ErrorCode.java | 45c4b368ac2227b62d97089d5e2ad5e0446c99f0 | [] | no_license | soansgla/stdw | https://github.com/soansgla/stdw | a15ac0cdc0a62789c5aeb6508fedab51f93fa9ce | 38ce776b81b6be1b500d656f3231f0aef2d60dd2 | refs/heads/master | 2018-11-27T22:14:47.943000 | 2016-07-13T07:07:08 | 2016-07-13T07:07:08 | 63,222,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dbs.sdwt.constant;
public enum ErrorCode {
FAIL_CREATE_COUNTERPARTY_TMP(101), FAIL_UPDATE_COUNTERPARTY_TMP(102);
private Integer value;
ErrorCode(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| UTF-8 | Java | 323 | java | ErrorCode.java | Java | [] | null | [] | package com.dbs.sdwt.constant;
public enum ErrorCode {
FAIL_CREATE_COUNTERPARTY_TMP(101), FAIL_UPDATE_COUNTERPARTY_TMP(102);
private Integer value;
ErrorCode(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| 323 | 0.712074 | 0.693498 | 20 | 15.15 | 17.810881 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.05 | false | false | 8 |
11977a38c3426862c81a0be65f72512a217a8c4c | 32,306,744,029,478 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /platform/platform-impl/src/com/intellij/ui/AbstractExpandableItemsHandler.java | a4ecc42f687466947f870591afb485c36f323728 | [
"Apache-2.0"
] | permissive | JetBrains/intellij-community | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.MovablePopup;
import com.intellij.ui.popup.list.SelectablePanel;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.Alarm;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.MouseEventAdapter;
import com.intellij.util.ui.MouseEventHandler;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.ScreenReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class AbstractExpandableItemsHandler<KeyType, ComponentType extends JComponent> implements ExpandableItemsHandler<KeyType> {
protected final ComponentType myComponent;
private final Alarm myUpdateAlarm = new Alarm();
private final CellRendererPane myRendererPane = new CellRendererPane();
private final JComponent myTipComponent = new JComponent() {
@Override
protected void paintComponent(Graphics g) {
Insets insets = getInsets();
Graphics2D g2d = (Graphics2D)g.create();
double scale = JBUIScale.sysScale((Graphics2D)g);
double devTop = insets.top * scale;
// A workaround for IDEA-183253. If insets.top is *.5 in device space, then move up the image by one device pixel.
if (devTop + 0.5 == Math.floor(devTop + 0.5)) {
double devPix = 1 / scale;
g2d.translate(0, -devPix);
}
try {
if (transparentPopup) {
g2d.setComposite(AlphaComposite.Src);
}
UIUtil.drawImage(g2d, myImage, insets.left, insets.top, null);
}
finally {
g2d.dispose();
}
}
};
private boolean myEnabled = Registry.is("ide.expansion.hints.enabled");
private final MovablePopup myPopup;
private KeyType myKey;
private Rectangle myKeyItemBounds;
private BufferedImage myImage;
private int borderArc = 0;
private boolean transparentPopup;
public static void setRelativeBounds(@NotNull Component parent, @NotNull Rectangle bounds,
@NotNull Component child, @NotNull Container validationParent) {
validationParent.add(parent);
parent.setBounds(bounds);
parent.validate();
child.setLocation(SwingUtilities.convertPoint(child, 0, 0, parent));
validationParent.remove(parent);
}
protected AbstractExpandableItemsHandler(final @NotNull ComponentType component) {
myComponent = component;
myComponent.add(myRendererPane);
myComponent.validate();
myPopup = new MovablePopup(myComponent, myTipComponent);
MouseEventHandler dispatcher = new MouseEventHandler() {
@Override
protected void handle(MouseEvent event) {
MouseEventAdapter.redispatch(event, myComponent);
}
@Override
public void mouseEntered(MouseEvent event) {
}
@Override
public void mouseExited(MouseEvent event) {
// don't hide the hint if mouse exited to owner component
if (myComponent.getMousePosition() == null) {
hideHint();
}
}
};
myTipComponent.addMouseListener(dispatcher);
myTipComponent.addMouseMotionListener(dispatcher);
myTipComponent.addMouseWheelListener(dispatcher);
MouseEventHandler handler = new MouseEventHandler() {
@Override
protected void handle(MouseEvent event) {
handleMouseEvent(event, MouseEvent.MOUSE_MOVED != event.getID());
}
@Override
public void mouseClicked(MouseEvent event) {
}
@Override
public void mouseExited(MouseEvent event) {
// don't hide the hint if mouse exited to it
if (Registry.is("ide.hide.expandable.tooltip.owner.mouse.exit") || myTipComponent.getMousePosition() == null) {
hideHint();
}
}
};
myComponent.addMouseListener(handler);
myComponent.addMouseMotionListener(handler);
myComponent.addFocusListener(
new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
onFocusLost();
}
@Override
public void focusGained(FocusEvent e) {
updateCurrentSelection();
}
}
);
myComponent.addComponentListener(
new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
hideHint();
}
@Override
public void componentMoved(ComponentEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
@Override
public void componentResized(ComponentEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
}
);
myComponent.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
@Override
public void ancestorMoved(HierarchyEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
@Override
public void ancestorResized(HierarchyEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
});
myComponent.addHierarchyListener(
new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
hideHint();
}
}
);
}
protected void onFocusLost() {
hideHint();
}
@Override
public void setEnabled(boolean enabled) {
myEnabled = enabled;
if (!isEnabled()) hideHint();
}
@Override
public boolean isEnabled() {
return myEnabled;
}
protected void setBorderArc(int borderArc) {
this.borderArc = borderArc;
}
@Override
public @NotNull Collection<KeyType> getExpandedItems() {
return myKey == null ? Collections.emptyList() : Collections.singleton(myKey);
}
private void updateCurrentSelectionOnMoveOrResize() {
if (ClientProperty.isTrue(myComponent, IGNORE_ITEM_SELECTION)) {
hideHint();
}
else {
updateCurrentSelection();
}
}
protected void updateCurrentSelection() {
handleSelectionChange(myKey, true);
}
protected void handleMouseEvent(MouseEvent e, boolean forceUpdate) {
if (ClientProperty.isTrue(myComponent, IGNORE_MOUSE_HOVER)) return;
KeyType selected = getCellKeyForPoint(e.getPoint());
if (forceUpdate || !Comparing.equal(myKey, selected)) {
handleSelectionChange(selected, true);
}
// Temporary workaround
if (e.getClickCount() == 2) {
hideHint();
}
}
protected void handleSelectionChange(KeyType selected) {
handleSelectionChange(ClientProperty.isTrue(myComponent, IGNORE_ITEM_SELECTION) ? myKey : selected, false);
}
protected void handleSelectionChange(final KeyType selected, final boolean processIfUnfocused) {
if (!EventQueue.isDispatchThread()) {
return;
}
myUpdateAlarm.cancelAllRequests();
if (selected == null || !isHandleSelectionEnabled(selected, processIfUnfocused)) {
hideHint();
return;
}
if (!selected.equals(myKey)) {
hideHint();
}
myUpdateAlarm.addRequest(() -> doHandleSelectionChange(selected, processIfUnfocused), 10);
}
private boolean isHandleSelectionEnabled(@NotNull KeyType selected, boolean processIfUnfocused) {
return isEnabled() &&
!ScreenReader.isActive() &&
myComponent.isEnabled() &&
myComponent.isShowing() &&
myComponent.getVisibleRect().intersects(getVisibleRect(selected)) &&
(processIfUnfocused || myComponent.isFocusOwner());
}
private void doHandleSelectionChange(@NotNull KeyType selected, boolean processIfUnfocused) {
if (!isHandleSelectionEnabled(selected, processIfUnfocused)) {
hideHint();
return;
}
myKey = selected;
Point location = createToolTipImage(myKey);
if (location == null) {
hideHint();
}
else {
Rectangle bounds = new Rectangle(location, myTipComponent.getPreferredSize());
myPopup.setTransparent(transparentPopup);
myPopup.setBounds(bounds);
myPopup.onAncestorFocusLost(() -> onFocusLost());
myPopup.setVisible(noIntersections(bounds));
repaintKeyItem();
}
}
protected boolean isPopup() {
Window window = SwingUtilities.getWindowAncestor(myComponent);
return UIUtil.isSimpleWindow(window) && !isHintsAllowed(window);
}
private static boolean isHintsAllowed(Window window) {
if (window instanceof RootPaneContainer) {
final JRootPane pane = ((RootPaneContainer)window).getRootPane();
if (pane != null) {
return Boolean.TRUE.equals(pane.getClientProperty(AbstractPopup.SHOW_HINTS));
}
}
return false;
}
private static boolean isFocused(Window window) {
return window != null && (window.isFocused() || isFocused(window.getOwner()));
}
private boolean noIntersections(Rectangle bounds) {
Window owner = SwingUtilities.getWindowAncestor(myComponent);
Window popup = SwingUtilities.getWindowAncestor(myTipComponent);
Window focus = WindowManagerEx.getInstanceEx().getMostRecentFocusedWindow();
if (focus == owner.getOwner()) {
focus = null; // do not check intersection with parent
}
boolean focused = SystemInfo.isWindows || isFocused(owner);
for (Window other : owner.getOwnedWindows()) {
if (!focused) {
focused = other.isFocused();
}
if (popup != other && other.isVisible() && bounds.x + 10 >= other.getX() && bounds.intersects(other.getBounds())) {
return false;
}
if (focus == other) {
focus = null; // already checked
}
}
return focused && (focus == owner || focus == null || !owner.getBounds().intersects(focus.getBounds()));
}
private void hideHint() {
myUpdateAlarm.cancelAllRequests();
if (myPopup.isVisible()) {
myPopup.setVisible(false);
repaintKeyItem();
}
myKey = null;
}
public boolean isShowing() {
return myPopup.isVisible();
}
private void repaintKeyItem() {
if (myKeyItemBounds != null) {
myComponent.repaint(myKeyItemBounds);
}
}
private static SelectablePanel findSelectablePanel(@NotNull JComponent renderer) {
Component result = renderer;
while (result instanceof ExpandedItemRendererComponentWrapper) {
result = ExpandedItemRendererComponentWrapper.unwrap(result);
}
if (result instanceof GroupedElementsRenderer.MyComponent myComponent) {
result = myComponent.getRenderer().getItemComponent();
}
return result instanceof SelectablePanel selectablePanel ? selectablePanel : null;
}
private @Nullable Point createToolTipImage(@NotNull KeyType key) {
ClientProperty.put(myComponent, EXPANDED_RENDERER, true);
Pair<Component, Rectangle> rendererAndBounds = getCellRendererAndBounds(key);
ClientProperty.put(myComponent, EXPANDED_RENDERER, null);
if (rendererAndBounds == null) return null;
JComponent renderer = ObjectUtils.tryCast(rendererAndBounds.first, JComponent.class);
if (renderer == null) return null;
if (ClientProperty.isTrue(renderer, RENDERER_DISABLED)) return null;
myKeyItemBounds = rendererAndBounds.second;
if (ClientProperty.isTrue(renderer, USE_RENDERER_BOUNDS)) {
myKeyItemBounds.translate(renderer.getX(), renderer.getY());
myKeyItemBounds.setSize(renderer.getSize());
}
SelectablePanel selectablePanel = findSelectablePanel(renderer);
int arc = selectablePanel == null ? borderArc : selectablePanel.getSelectionArc();
transparentPopup = arc > 0;
Rectangle cellBounds = myKeyItemBounds;
Rectangle visibleRect = getVisibleRect(key);
if (cellBounds.y < visibleRect.y) return null;
int cellMaxY = cellBounds.y + cellBounds.height;
int visMaxY = visibleRect.y + visibleRect.height;
if (cellMaxY > visMaxY) return null;
int cellMaxX = cellBounds.x + cellBounds.width;
int visMaxX = visibleRect.x + visibleRect.width;
Point location = new Point(visMaxX, cellBounds.y);
SwingUtilities.convertPointToScreen(location, myComponent);
Rectangle screen = ScreenUtil.getScreenRectangle(location);
// exclude case when myComponent touches screen boundary with its right edge, and popup would be displayed on adjacent screen
if (location.x == screen.x) return null;
int borderSize = isPaintBorder() ? 1 : 0;
int width = Math.min(screen.width + screen.x - location.x - borderSize, cellMaxX - visMaxX);
int height = cellBounds.height;
if (width <= 0 || height <= 0) return null;
Graphics2D g;
if (arc > 0) {
width += borderSize;
height += borderSize * 2;
int clippedY = 0;
int clippedHeight = height;
if (selectablePanel != null) {
width -= selectablePanel.getSelectionInsets().right;
if (width <= 0) {
return null;
}
renderer.setBounds(cellBounds);
Rectangle rect = calcRectInParent(selectablePanel, renderer);
clippedY = rect.y;
clippedHeight = rect.height + borderSize * 2;
}
myImage = UIUtil.createImage(myComponent, width, height, BufferedImage.TYPE_INT_ARGB);
g = myImage.createGraphics();
//noinspection GraphicsSetClipInspection
g.setClip(new RoundRectangle2D.Float(-arc, clippedY, width + arc, clippedHeight, arc, arc));
if (borderSize > 0) {
location.y -= borderSize;
g.setColor(getBorderColor());
g.fillRect(0, 0, width, height);
//noinspection GraphicsSetClipInspection
g.setClip(new RoundRectangle2D.Float(-arc, clippedY + borderSize, width + arc - borderSize, clippedHeight - borderSize * 2, arc, arc));
}
doFillBackground(height, width, g);
g.translate(cellBounds.x - visMaxX, borderSize);
doPaintTooltipImage(renderer, cellBounds, g, key);
myTipComponent.setBorder(null);
}
else {
myImage = UIUtil.createImage(myComponent, width, height, BufferedImage.TYPE_INT_RGB);
g = myImage.createGraphics();
//noinspection GraphicsSetClipInspection
g.setClip(null);
doFillBackground(height, width, g);
if (borderSize > 0) {
CustomLineBorder border = new CustomLineBorder(getBorderColor(), borderSize, 0, borderSize, borderSize);
location.y -= borderSize;
width += borderSize;
height += borderSize * 2;
myTipComponent.setBorder(border);
} else {
myTipComponent.setBorder(null);
}
g.translate(cellBounds.x - visMaxX, 0);
doPaintTooltipImage(renderer, cellBounds, g, key);
}
g.dispose();
myRendererPane.remove(renderer);
myTipComponent.setPreferredSize(new Dimension(width, height));
return location;
}
protected boolean isPaintBorder() {
return true;
}
protected Color getBorderColor() {
return JBColor.border();
}
protected void doFillBackground(int height, int width, Graphics2D g) {
g.setColor(myComponent.getBackground());
g.fillRect(0, 0, width, height);
}
protected void doPaintTooltipImage(Component rComponent, Rectangle cellBounds, Graphics2D g, KeyType key) {
myRendererPane.paintComponent(g, rComponent, myComponent, 0, 0, cellBounds.width, cellBounds.height, true);
}
protected Rectangle getVisibleRect(KeyType key) {
return myComponent.getVisibleRect();
}
protected abstract @Nullable Pair<Component, Rectangle> getCellRendererAndBounds(KeyType key);
protected abstract KeyType getCellKeyForPoint(Point point);
private static @NotNull Rectangle calcRectInParent(@NotNull Container child, @NotNull JComponent parent) {
List<Container> chain = new ArrayList<>();
Container container = child;
while (container != parent) {
chain.add(container);
container = container.getParent();
if (container == null) {
throw new IllegalArgumentException("Source is not part of " + parent);
}
}
Rectangle result = new Rectangle();
parent.doLayout();
for (int i = chain.size() - 1; i >= 0; i--) {
Container c = chain.get(i);
c.doLayout();
result.x += c.getX();
result.y += c.getY();
}
result.setSize(child.getSize());
return result;
}
}
| UTF-8 | Java | 16,726 | java | AbstractExpandableItemsHandler.java | Java | [] | null | [] | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.MovablePopup;
import com.intellij.ui.popup.list.SelectablePanel;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.Alarm;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.MouseEventAdapter;
import com.intellij.util.ui.MouseEventHandler;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.ScreenReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class AbstractExpandableItemsHandler<KeyType, ComponentType extends JComponent> implements ExpandableItemsHandler<KeyType> {
protected final ComponentType myComponent;
private final Alarm myUpdateAlarm = new Alarm();
private final CellRendererPane myRendererPane = new CellRendererPane();
private final JComponent myTipComponent = new JComponent() {
@Override
protected void paintComponent(Graphics g) {
Insets insets = getInsets();
Graphics2D g2d = (Graphics2D)g.create();
double scale = JBUIScale.sysScale((Graphics2D)g);
double devTop = insets.top * scale;
// A workaround for IDEA-183253. If insets.top is *.5 in device space, then move up the image by one device pixel.
if (devTop + 0.5 == Math.floor(devTop + 0.5)) {
double devPix = 1 / scale;
g2d.translate(0, -devPix);
}
try {
if (transparentPopup) {
g2d.setComposite(AlphaComposite.Src);
}
UIUtil.drawImage(g2d, myImage, insets.left, insets.top, null);
}
finally {
g2d.dispose();
}
}
};
private boolean myEnabled = Registry.is("ide.expansion.hints.enabled");
private final MovablePopup myPopup;
private KeyType myKey;
private Rectangle myKeyItemBounds;
private BufferedImage myImage;
private int borderArc = 0;
private boolean transparentPopup;
public static void setRelativeBounds(@NotNull Component parent, @NotNull Rectangle bounds,
@NotNull Component child, @NotNull Container validationParent) {
validationParent.add(parent);
parent.setBounds(bounds);
parent.validate();
child.setLocation(SwingUtilities.convertPoint(child, 0, 0, parent));
validationParent.remove(parent);
}
protected AbstractExpandableItemsHandler(final @NotNull ComponentType component) {
myComponent = component;
myComponent.add(myRendererPane);
myComponent.validate();
myPopup = new MovablePopup(myComponent, myTipComponent);
MouseEventHandler dispatcher = new MouseEventHandler() {
@Override
protected void handle(MouseEvent event) {
MouseEventAdapter.redispatch(event, myComponent);
}
@Override
public void mouseEntered(MouseEvent event) {
}
@Override
public void mouseExited(MouseEvent event) {
// don't hide the hint if mouse exited to owner component
if (myComponent.getMousePosition() == null) {
hideHint();
}
}
};
myTipComponent.addMouseListener(dispatcher);
myTipComponent.addMouseMotionListener(dispatcher);
myTipComponent.addMouseWheelListener(dispatcher);
MouseEventHandler handler = new MouseEventHandler() {
@Override
protected void handle(MouseEvent event) {
handleMouseEvent(event, MouseEvent.MOUSE_MOVED != event.getID());
}
@Override
public void mouseClicked(MouseEvent event) {
}
@Override
public void mouseExited(MouseEvent event) {
// don't hide the hint if mouse exited to it
if (Registry.is("ide.hide.expandable.tooltip.owner.mouse.exit") || myTipComponent.getMousePosition() == null) {
hideHint();
}
}
};
myComponent.addMouseListener(handler);
myComponent.addMouseMotionListener(handler);
myComponent.addFocusListener(
new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
onFocusLost();
}
@Override
public void focusGained(FocusEvent e) {
updateCurrentSelection();
}
}
);
myComponent.addComponentListener(
new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
hideHint();
}
@Override
public void componentMoved(ComponentEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
@Override
public void componentResized(ComponentEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
}
);
myComponent.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
@Override
public void ancestorMoved(HierarchyEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
@Override
public void ancestorResized(HierarchyEvent e) {
updateCurrentSelectionOnMoveOrResize();
}
});
myComponent.addHierarchyListener(
new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
hideHint();
}
}
);
}
protected void onFocusLost() {
hideHint();
}
@Override
public void setEnabled(boolean enabled) {
myEnabled = enabled;
if (!isEnabled()) hideHint();
}
@Override
public boolean isEnabled() {
return myEnabled;
}
protected void setBorderArc(int borderArc) {
this.borderArc = borderArc;
}
@Override
public @NotNull Collection<KeyType> getExpandedItems() {
return myKey == null ? Collections.emptyList() : Collections.singleton(myKey);
}
private void updateCurrentSelectionOnMoveOrResize() {
if (ClientProperty.isTrue(myComponent, IGNORE_ITEM_SELECTION)) {
hideHint();
}
else {
updateCurrentSelection();
}
}
protected void updateCurrentSelection() {
handleSelectionChange(myKey, true);
}
protected void handleMouseEvent(MouseEvent e, boolean forceUpdate) {
if (ClientProperty.isTrue(myComponent, IGNORE_MOUSE_HOVER)) return;
KeyType selected = getCellKeyForPoint(e.getPoint());
if (forceUpdate || !Comparing.equal(myKey, selected)) {
handleSelectionChange(selected, true);
}
// Temporary workaround
if (e.getClickCount() == 2) {
hideHint();
}
}
protected void handleSelectionChange(KeyType selected) {
handleSelectionChange(ClientProperty.isTrue(myComponent, IGNORE_ITEM_SELECTION) ? myKey : selected, false);
}
protected void handleSelectionChange(final KeyType selected, final boolean processIfUnfocused) {
if (!EventQueue.isDispatchThread()) {
return;
}
myUpdateAlarm.cancelAllRequests();
if (selected == null || !isHandleSelectionEnabled(selected, processIfUnfocused)) {
hideHint();
return;
}
if (!selected.equals(myKey)) {
hideHint();
}
myUpdateAlarm.addRequest(() -> doHandleSelectionChange(selected, processIfUnfocused), 10);
}
private boolean isHandleSelectionEnabled(@NotNull KeyType selected, boolean processIfUnfocused) {
return isEnabled() &&
!ScreenReader.isActive() &&
myComponent.isEnabled() &&
myComponent.isShowing() &&
myComponent.getVisibleRect().intersects(getVisibleRect(selected)) &&
(processIfUnfocused || myComponent.isFocusOwner());
}
private void doHandleSelectionChange(@NotNull KeyType selected, boolean processIfUnfocused) {
if (!isHandleSelectionEnabled(selected, processIfUnfocused)) {
hideHint();
return;
}
myKey = selected;
Point location = createToolTipImage(myKey);
if (location == null) {
hideHint();
}
else {
Rectangle bounds = new Rectangle(location, myTipComponent.getPreferredSize());
myPopup.setTransparent(transparentPopup);
myPopup.setBounds(bounds);
myPopup.onAncestorFocusLost(() -> onFocusLost());
myPopup.setVisible(noIntersections(bounds));
repaintKeyItem();
}
}
protected boolean isPopup() {
Window window = SwingUtilities.getWindowAncestor(myComponent);
return UIUtil.isSimpleWindow(window) && !isHintsAllowed(window);
}
private static boolean isHintsAllowed(Window window) {
if (window instanceof RootPaneContainer) {
final JRootPane pane = ((RootPaneContainer)window).getRootPane();
if (pane != null) {
return Boolean.TRUE.equals(pane.getClientProperty(AbstractPopup.SHOW_HINTS));
}
}
return false;
}
private static boolean isFocused(Window window) {
return window != null && (window.isFocused() || isFocused(window.getOwner()));
}
private boolean noIntersections(Rectangle bounds) {
Window owner = SwingUtilities.getWindowAncestor(myComponent);
Window popup = SwingUtilities.getWindowAncestor(myTipComponent);
Window focus = WindowManagerEx.getInstanceEx().getMostRecentFocusedWindow();
if (focus == owner.getOwner()) {
focus = null; // do not check intersection with parent
}
boolean focused = SystemInfo.isWindows || isFocused(owner);
for (Window other : owner.getOwnedWindows()) {
if (!focused) {
focused = other.isFocused();
}
if (popup != other && other.isVisible() && bounds.x + 10 >= other.getX() && bounds.intersects(other.getBounds())) {
return false;
}
if (focus == other) {
focus = null; // already checked
}
}
return focused && (focus == owner || focus == null || !owner.getBounds().intersects(focus.getBounds()));
}
private void hideHint() {
myUpdateAlarm.cancelAllRequests();
if (myPopup.isVisible()) {
myPopup.setVisible(false);
repaintKeyItem();
}
myKey = null;
}
public boolean isShowing() {
return myPopup.isVisible();
}
private void repaintKeyItem() {
if (myKeyItemBounds != null) {
myComponent.repaint(myKeyItemBounds);
}
}
private static SelectablePanel findSelectablePanel(@NotNull JComponent renderer) {
Component result = renderer;
while (result instanceof ExpandedItemRendererComponentWrapper) {
result = ExpandedItemRendererComponentWrapper.unwrap(result);
}
if (result instanceof GroupedElementsRenderer.MyComponent myComponent) {
result = myComponent.getRenderer().getItemComponent();
}
return result instanceof SelectablePanel selectablePanel ? selectablePanel : null;
}
private @Nullable Point createToolTipImage(@NotNull KeyType key) {
ClientProperty.put(myComponent, EXPANDED_RENDERER, true);
Pair<Component, Rectangle> rendererAndBounds = getCellRendererAndBounds(key);
ClientProperty.put(myComponent, EXPANDED_RENDERER, null);
if (rendererAndBounds == null) return null;
JComponent renderer = ObjectUtils.tryCast(rendererAndBounds.first, JComponent.class);
if (renderer == null) return null;
if (ClientProperty.isTrue(renderer, RENDERER_DISABLED)) return null;
myKeyItemBounds = rendererAndBounds.second;
if (ClientProperty.isTrue(renderer, USE_RENDERER_BOUNDS)) {
myKeyItemBounds.translate(renderer.getX(), renderer.getY());
myKeyItemBounds.setSize(renderer.getSize());
}
SelectablePanel selectablePanel = findSelectablePanel(renderer);
int arc = selectablePanel == null ? borderArc : selectablePanel.getSelectionArc();
transparentPopup = arc > 0;
Rectangle cellBounds = myKeyItemBounds;
Rectangle visibleRect = getVisibleRect(key);
if (cellBounds.y < visibleRect.y) return null;
int cellMaxY = cellBounds.y + cellBounds.height;
int visMaxY = visibleRect.y + visibleRect.height;
if (cellMaxY > visMaxY) return null;
int cellMaxX = cellBounds.x + cellBounds.width;
int visMaxX = visibleRect.x + visibleRect.width;
Point location = new Point(visMaxX, cellBounds.y);
SwingUtilities.convertPointToScreen(location, myComponent);
Rectangle screen = ScreenUtil.getScreenRectangle(location);
// exclude case when myComponent touches screen boundary with its right edge, and popup would be displayed on adjacent screen
if (location.x == screen.x) return null;
int borderSize = isPaintBorder() ? 1 : 0;
int width = Math.min(screen.width + screen.x - location.x - borderSize, cellMaxX - visMaxX);
int height = cellBounds.height;
if (width <= 0 || height <= 0) return null;
Graphics2D g;
if (arc > 0) {
width += borderSize;
height += borderSize * 2;
int clippedY = 0;
int clippedHeight = height;
if (selectablePanel != null) {
width -= selectablePanel.getSelectionInsets().right;
if (width <= 0) {
return null;
}
renderer.setBounds(cellBounds);
Rectangle rect = calcRectInParent(selectablePanel, renderer);
clippedY = rect.y;
clippedHeight = rect.height + borderSize * 2;
}
myImage = UIUtil.createImage(myComponent, width, height, BufferedImage.TYPE_INT_ARGB);
g = myImage.createGraphics();
//noinspection GraphicsSetClipInspection
g.setClip(new RoundRectangle2D.Float(-arc, clippedY, width + arc, clippedHeight, arc, arc));
if (borderSize > 0) {
location.y -= borderSize;
g.setColor(getBorderColor());
g.fillRect(0, 0, width, height);
//noinspection GraphicsSetClipInspection
g.setClip(new RoundRectangle2D.Float(-arc, clippedY + borderSize, width + arc - borderSize, clippedHeight - borderSize * 2, arc, arc));
}
doFillBackground(height, width, g);
g.translate(cellBounds.x - visMaxX, borderSize);
doPaintTooltipImage(renderer, cellBounds, g, key);
myTipComponent.setBorder(null);
}
else {
myImage = UIUtil.createImage(myComponent, width, height, BufferedImage.TYPE_INT_RGB);
g = myImage.createGraphics();
//noinspection GraphicsSetClipInspection
g.setClip(null);
doFillBackground(height, width, g);
if (borderSize > 0) {
CustomLineBorder border = new CustomLineBorder(getBorderColor(), borderSize, 0, borderSize, borderSize);
location.y -= borderSize;
width += borderSize;
height += borderSize * 2;
myTipComponent.setBorder(border);
} else {
myTipComponent.setBorder(null);
}
g.translate(cellBounds.x - visMaxX, 0);
doPaintTooltipImage(renderer, cellBounds, g, key);
}
g.dispose();
myRendererPane.remove(renderer);
myTipComponent.setPreferredSize(new Dimension(width, height));
return location;
}
protected boolean isPaintBorder() {
return true;
}
protected Color getBorderColor() {
return JBColor.border();
}
protected void doFillBackground(int height, int width, Graphics2D g) {
g.setColor(myComponent.getBackground());
g.fillRect(0, 0, width, height);
}
protected void doPaintTooltipImage(Component rComponent, Rectangle cellBounds, Graphics2D g, KeyType key) {
myRendererPane.paintComponent(g, rComponent, myComponent, 0, 0, cellBounds.width, cellBounds.height, true);
}
protected Rectangle getVisibleRect(KeyType key) {
return myComponent.getVisibleRect();
}
protected abstract @Nullable Pair<Component, Rectangle> getCellRendererAndBounds(KeyType key);
protected abstract KeyType getCellKeyForPoint(Point point);
private static @NotNull Rectangle calcRectInParent(@NotNull Container child, @NotNull JComponent parent) {
List<Container> chain = new ArrayList<>();
Container container = child;
while (container != parent) {
chain.add(container);
container = container.getParent();
if (container == null) {
throw new IllegalArgumentException("Source is not part of " + parent);
}
}
Rectangle result = new Rectangle();
parent.doLayout();
for (int i = chain.size() - 1; i >= 0; i--) {
Container c = chain.get(i);
c.doLayout();
result.x += c.getX();
result.y += c.getY();
}
result.setSize(child.getSize());
return result;
}
}
| 16,726 | 0.684144 | 0.680019 | 511 | 31.731897 | 28.699274 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.67319 | false | false | 8 |
0648de21e873f746ff46123d7ba1c2a37219d71e | 5,471,788,368,193 | 46d211a1cd8204ab0f84cd513f2befe4e4b57ff0 | /Tax-ejb/src/java/model1/Paytype.java | 9d94ba6172082c8992d787507dfa57964f314c90 | [] | no_license | Sedwin/tax | https://github.com/Sedwin/tax | ed2404c45942e6db4f61d4840de9306bf9a20b0b | 3b34ba1bddf6ffd4fe5ddfed3e1df73abc8152cb | refs/heads/master | 2017-09-28T08:28:34.011000 | 2016-06-21T22:08:48 | 2016-06-21T22:08:48 | 61,655,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 model1;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
/**
*
* @author Del
*/
@Entity
@Table(name = "paytype")
@NamedQueries({
@NamedQuery(name = "Paytype.findAll", query = "SELECT p FROM Paytype p"),
@NamedQuery(name = "Paytype.findByIdpaytype", query = "SELECT p FROM Paytype p WHERE p.idpaytype = :idpaytype"),
@NamedQuery(name = "Paytype.findByPaytypeName", query = "SELECT p FROM Paytype p WHERE p.paytypeName = :paytypeName")})
public class Paytype implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idpaytype")
private Integer idpaytype;
@Size(max = 45)
@Column(name = "paytype_name")
private String paytypeName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idpaytype")
private List<Payment> paymentList;
public Integer getIdpaytype() {
return idpaytype;
}
public void setIdpaytype(Integer idpaytype) {
this.idpaytype = idpaytype;
}
public String getPaytypeName() {
return paytypeName;
}
public void setPaytypeName(String paytypeName) {
this.paytypeName = paytypeName;
}
public List<Payment> getPaymentList() {
return paymentList;
}
public void setPaymentList(List<Payment> paymentList) {
this.paymentList = paymentList;
}
@Override
public int hashCode(){
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.idpaytype);
return hash;
}
@Override
public boolean equals(Object obj){
if (this == obj){
return true;
}
if (obj == null){
return false;
}
if (getClass() != obj.getClass()){
return false;
}
final Paytype other = (Paytype) obj;
return Objects.equals(this.idpaytype, other.idpaytype);
}
} | UTF-8 | Java | 2,616 | java | Paytype.java | Java | [
{
"context": "ax.validation.constraints.Size;\n\n/**\n *\n * @author Del\n */\n@Entity\n@Table(name = \"paytype\")\n@NamedQuerie",
"end": 735,
"score": 0.8642919063568115,
"start": 732,
"tag": "NAME",
"value": "Del"
}
] | null | [] | /*
* 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 model1;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
/**
*
* @author Del
*/
@Entity
@Table(name = "paytype")
@NamedQueries({
@NamedQuery(name = "Paytype.findAll", query = "SELECT p FROM Paytype p"),
@NamedQuery(name = "Paytype.findByIdpaytype", query = "SELECT p FROM Paytype p WHERE p.idpaytype = :idpaytype"),
@NamedQuery(name = "Paytype.findByPaytypeName", query = "SELECT p FROM Paytype p WHERE p.paytypeName = :paytypeName")})
public class Paytype implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idpaytype")
private Integer idpaytype;
@Size(max = 45)
@Column(name = "paytype_name")
private String paytypeName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idpaytype")
private List<Payment> paymentList;
public Integer getIdpaytype() {
return idpaytype;
}
public void setIdpaytype(Integer idpaytype) {
this.idpaytype = idpaytype;
}
public String getPaytypeName() {
return paytypeName;
}
public void setPaytypeName(String paytypeName) {
this.paytypeName = paytypeName;
}
public List<Payment> getPaymentList() {
return paymentList;
}
public void setPaymentList(List<Payment> paymentList) {
this.paymentList = paymentList;
}
@Override
public int hashCode(){
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.idpaytype);
return hash;
}
@Override
public boolean equals(Object obj){
if (this == obj){
return true;
}
if (obj == null){
return false;
}
if (getClass() != obj.getClass()){
return false;
}
final Paytype other = (Paytype) obj;
return Objects.equals(this.idpaytype, other.idpaytype);
}
} | 2,616 | 0.673165 | 0.670489 | 96 | 26.260416 | 23.633154 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 8 |
5ffeb1a52cd04c30ff91b60b3ff17e00bf12cfe6 | 32,246,614,502,110 | 187eecf66fbafd7d1acf1ff395d6aae7f7457039 | /app/src/main/java/com/example/administrator/hzsb_office_master/MainActivity.java | 731c21006b7488e7498ca43ea0e1cb72904bb00c | [] | no_license | appzhf/Hzsb_office_master | https://github.com/appzhf/Hzsb_office_master | b32ecc1b83001fc45bdea13433a5800aed9d71e6 | 0b90ef92b69b5dcc2cdc133bf84f2e3a700b6470 | refs/heads/master | 2021-01-20T07:20:45.735000 | 2017-05-02T04:55:13 | 2017-05-02T04:55:13 | 89,993,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.hzsb_office_master;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import com.example.administrator.hzsb_office_master.base.AppBaseActivity;
import com.example.administrator.hzsb_office_master.fragmet.ChartFragment;
import com.example.administrator.hzsb_office_master.fragmet.MainFragment;
import com.example.administrator.hzsb_office_master.fragmet.MenuFragment;
import com.example.administrator.hzsb_office_master.fragmet.TimelineFragment;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import com.tbruyelle.rxpermissions.RxPermissions;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import rx.functions.Action1;
/**
* @author liujiancheng
* 第一个界面
*/
public class MainActivity extends AppBaseActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@BindView(R.id.myCoordinator)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.viewPager)
ViewPager mViewPager;
private BottomBar mBottomBar;
private List<Fragment> mFragmentList;
private RxPermissions mRxPermissions;
public static void start(Activity activity) {
activity.startActivity(new Intent(activity, MainActivity.class));
}
@Override
public void initView(Bundle savedInstanceState) {
super.initView(savedInstanceState);
Log.i(TAG, "initView");
setTitle(R.string.app_name);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
mRxPermissions = new RxPermissions(MainActivity.this);
mRxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
if (!aBoolean) {
Log.i(TAG, "request permission");
initPre();
}
}
});
}
initdata();
mBottomBar = BottomBar.attachShy(mCoordinatorLayout, mViewPager, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() {
@Override
public void onMenuTabSelected(@IdRes int menuItemId) {
switch (menuItemId) {
case R.id.bb_menu_recents:
mViewPager.setCurrentItem(0);
break;
case R.id.bb_menu_favorites:
mViewPager.setCurrentItem(1);
break;
case R.id.bb_menu_nearby:
mViewPager.setCurrentItem(2);
break;
case R.id.bb_menu_friends:
mViewPager.setCurrentItem(3);
break;
}
}
@Override
public void onMenuTabReSelected(@IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0, ContextCompat.getColor(this, R.color.color_recents));
mBottomBar.mapColorForTab(1, ContextCompat.getColor(this, R.color.color_favorites));
mBottomBar.mapColorForTab(2, ContextCompat.getColor(this, R.color.color_nearby));
mBottomBar.mapColorForTab(3, ContextCompat.getColor(this, R.color.color_friends));
}
/**
* 第一次加载程序时初始化
*/
@Override
public void initFirst() {
super.initFirst();
//初始化greenDao
}
@Override
public void initPre() {
super.initPre();
}
@Override
public void initdata() {
mFragmentList = new ArrayList<>();
mFragmentList.add(MainFragment.getInstance());
mFragmentList.add(MenuFragment.getInstance());
mFragmentList.add(ChartFragment.getInstance());
mFragmentList.add(TimelineFragment.getInstance());
mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
});
/*
mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
});
*/
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mBottomBar.selectTabAtPosition(position, true);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
super.initdata();
}
@Override
public int getLayoutResId() {
return R.layout.activity_main;
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
mBottomBar.onSaveInstanceState(outState);
}
}
| UTF-8 | Java | 6,212 | java | MainActivity.java | Java | [
{
"context": "View;\nimport rx.functions.Action1;\n\n/**\n * @author liujiancheng\n * 第一个界面\n */\npublic class MainActivity ex",
"end": 1250,
"score": 0.998849093914032,
"start": 1238,
"tag": "USERNAME",
"value": "liujiancheng"
}
] | null | [] | package com.example.administrator.hzsb_office_master;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import com.example.administrator.hzsb_office_master.base.AppBaseActivity;
import com.example.administrator.hzsb_office_master.fragmet.ChartFragment;
import com.example.administrator.hzsb_office_master.fragmet.MainFragment;
import com.example.administrator.hzsb_office_master.fragmet.MenuFragment;
import com.example.administrator.hzsb_office_master.fragmet.TimelineFragment;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import com.tbruyelle.rxpermissions.RxPermissions;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import rx.functions.Action1;
/**
* @author liujiancheng
* 第一个界面
*/
public class MainActivity extends AppBaseActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@BindView(R.id.myCoordinator)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.viewPager)
ViewPager mViewPager;
private BottomBar mBottomBar;
private List<Fragment> mFragmentList;
private RxPermissions mRxPermissions;
public static void start(Activity activity) {
activity.startActivity(new Intent(activity, MainActivity.class));
}
@Override
public void initView(Bundle savedInstanceState) {
super.initView(savedInstanceState);
Log.i(TAG, "initView");
setTitle(R.string.app_name);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
mRxPermissions = new RxPermissions(MainActivity.this);
mRxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
if (!aBoolean) {
Log.i(TAG, "request permission");
initPre();
}
}
});
}
initdata();
mBottomBar = BottomBar.attachShy(mCoordinatorLayout, mViewPager, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() {
@Override
public void onMenuTabSelected(@IdRes int menuItemId) {
switch (menuItemId) {
case R.id.bb_menu_recents:
mViewPager.setCurrentItem(0);
break;
case R.id.bb_menu_favorites:
mViewPager.setCurrentItem(1);
break;
case R.id.bb_menu_nearby:
mViewPager.setCurrentItem(2);
break;
case R.id.bb_menu_friends:
mViewPager.setCurrentItem(3);
break;
}
}
@Override
public void onMenuTabReSelected(@IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0, ContextCompat.getColor(this, R.color.color_recents));
mBottomBar.mapColorForTab(1, ContextCompat.getColor(this, R.color.color_favorites));
mBottomBar.mapColorForTab(2, ContextCompat.getColor(this, R.color.color_nearby));
mBottomBar.mapColorForTab(3, ContextCompat.getColor(this, R.color.color_friends));
}
/**
* 第一次加载程序时初始化
*/
@Override
public void initFirst() {
super.initFirst();
//初始化greenDao
}
@Override
public void initPre() {
super.initPre();
}
@Override
public void initdata() {
mFragmentList = new ArrayList<>();
mFragmentList.add(MainFragment.getInstance());
mFragmentList.add(MenuFragment.getInstance());
mFragmentList.add(ChartFragment.getInstance());
mFragmentList.add(TimelineFragment.getInstance());
mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
});
/*
mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
});
*/
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mBottomBar.selectTabAtPosition(position, true);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
super.initdata();
}
@Override
public int getLayoutResId() {
return R.layout.activity_main;
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
mBottomBar.onSaveInstanceState(outState);
}
}
| 6,212 | 0.622935 | 0.620505 | 178 | 33.685394 | 25.638847 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.539326 | false | false | 8 |
e017e3e0fd55c4debf5ff4fc40e59a74f5b7cd7f | 5,884,105,217,036 | 9e867bd583874e72a821ca39bc70b92762942c03 | /app/src/main/java/com/example/financial_savings/fragments/trans_fast/Trans_Fast_Fragment.java | 3e874dcbc3c7b886d84f8a334bfda07d457995a0 | [] | no_license | nguyentranthyan/Financial_Savingsbudget | https://github.com/nguyentranthyan/Financial_Savingsbudget | 15a19969675570cd887e019c3614f14d79b72a1c | 524845778c06ff578c51c2e8a36a5b3371a48f40 | refs/heads/master | 2022-11-12T22:39:17.818000 | 2020-06-25T04:02:04 | 2020-06-25T04:02:04 | 274,426,414 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.financial_savings.fragments.trans_fast;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.financial_savings.R;
import com.example.financial_savings.controllers.chooses.ChooseWalletActivity;
import com.example.financial_savings.entities.DanhMuc;
import com.example.financial_savings.entities.SoGiaoDich;
import com.example.financial_savings.entities.ViCaNhan;
import com.example.financial_savings.helper.DBHelper;
import com.example.financial_savings.interfaces.IMappingView;
import com.example.financial_savings.modules.displays.TransactionFastDisplayModule;
import com.example.financial_savings.modules.formats.FormatMoneyModule;
import com.example.financial_savings.modules.refreshs.SwipeRefreshModule;
import com.example.financial_savings.modules.transactions.TransactionFastModule;
import com.example.financial_savings.modules.wallets.MoneyWalletModule;
import com.example.financial_savings.sessions.Session;
import java.util.ArrayList;
public class Trans_Fast_Fragment extends Fragment implements IMappingView {
private ImageButton buttonIconWallet, buttonIconDown, buttonIconFilter;
private TextView textViewNameWallet, textViewMoneyWallet;
private ListView listView;
private View root;
private DBHelper dbHelper;
private Session session;
private static final String WALLET_TOTAL = "total";
private static final String DOANHTHU = "doanhthu";
private static final String KHOANCHI = "khoanchi";
private String[] FILTER_ARRAY;
private ArrayList<SoGiaoDich> soGiaoDichs;
private SwipeRefreshLayout swipeRefresh;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.transaction_fast, container, false);
init();
if(getUserVisibleHint()) loadData();
loadData();
eventChooseWallet();
eventFilter();
eventRefresh();
return root;
}
private void eventRefresh() {
Runnable runnable = new Runnable() {
@Override
public void run() {
loadData();
}
};
SwipeRefreshModule.eventRefresh(swipeRefresh, runnable);
}
private void eventFilter() {
buttonIconFilter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getActivity());
dialog.setTitle(getResources().getString(R.string.filter_dialog));
dialog.setContentView(R.layout.transaction_filter_dialog);
ListView listViewFilter = dialog.findViewById(R.id.listViewFilter_filter_dialog);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, FILTER_ARRAY);
listViewFilter.setAdapter(adapter);
listViewFilter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
handlingFilter(position);
dialog.dismiss();
}
});
}
});
}
private void handlingFilter(int position) {
ArrayList<SoGiaoDich> list = new ArrayList<>();
for (int i = 0; i < soGiaoDichs.size(); i++) {
String idCate = soGiaoDichs.get(i).getMaDanhMuc();
DanhMuc danhMuc = dbHelper.getByID_DanhMuc(idCate);
if(position == 1 && danhMuc.getLoaiDanhMuc().equals(DOANHTHU)) {
list.add(soGiaoDichs.get(i));
}
else if(position == 2 && danhMuc.getLoaiDanhMuc().equals(KHOANCHI)) {
list.add(soGiaoDichs.get(i));
}
else if(position == 0) {
list.add(soGiaoDichs.get(i));
}
}
TransactionFastDisplayModule.showListViewHomeFast_Transaction(TransactionFastModule.getSoGiaoDichesStatus(list),
getActivity(), listView, dbHelper);
}
private void eventChooseWallet() {
buttonIconWallet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ChooseWalletActivity.class);
intent.putExtra("name", WALLET_TOTAL);
startActivity(intent);
}
});
buttonIconDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ChooseWalletActivity.class);
intent.putExtra("name", WALLET_TOTAL);
startActivity(intent);
}
});
}
@SuppressLint("SetTextI18n")
private void loadData() {
String idWallet = session.getIDWallet();
if(idWallet.equals(WALLET_TOTAL) || idWallet == null || idWallet.isEmpty()) {
soGiaoDichs = dbHelper.getAll_SoGiaoDich();
getListWalletTotal();
}
else {
soGiaoDichs = dbHelper.getByWallet_SoGiaoDich(idWallet);
getListIDWallet(idWallet);
}
TransactionFastDisplayModule.showListViewHomeFast_Transaction(TransactionFastModule.getSoGiaoDichesStatus(soGiaoDichs),
getActivity(), listView, dbHelper);
}
@SuppressLint("SetTextI18n")
private void getListWalletTotal() {
ArrayList<ViCaNhan> wallets = dbHelper.getAll_ViCaNhan();
double totalWallet = MoneyWalletModule.getMoneyWallet(wallets);
textViewNameWallet.setText(getResources().getString(R.string.all_wallet));
textViewMoneyWallet.setText(FormatMoneyModule.formatAmount(totalWallet) + " VND");
buttonIconWallet.setBackgroundResource(R.drawable.ic_language_black_24dp);
}
@SuppressLint("SetTextI18n")
private void getListIDWallet(String idWallet) {
ViCaNhan viCaNhan = dbHelper.getByID_ViCaNhan(idWallet);
textViewNameWallet.setText(viCaNhan.getTenVi());
textViewMoneyWallet.setText(FormatMoneyModule.formatAmount(viCaNhan.getSoTien()) + " VND");
buttonIconWallet.setBackgroundResource(R.drawable.ic_account_balance_wallet_black_24dp);
}
@Override
public void onResume() {
super.onResume();
loadData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && isResumed()) {
loadData();
}
}
@Override
public void init() {
buttonIconWallet = root.findViewById(R.id.buttonIconWallet_transaction_fast);
buttonIconDown = root.findViewById(R.id.buttonIconDown_transaction_fast);
buttonIconFilter = root.findViewById(R.id.buttonIconFilter_transaction_fast);
textViewNameWallet = root.findViewById(R.id.textViewNameWallet_transaction_fast);
textViewMoneyWallet = root.findViewById(R.id.textViewMoneyWallet_transaction_fast);
swipeRefresh = root.findViewById(R.id.swipeRefresh_transaction_fast);
listView = root.findViewById(R.id.listView_transaction_fast);
dbHelper = new DBHelper(root.getContext());
session = new Session(root.getContext());
session.clear();
FILTER_ARRAY = getResources().getStringArray(R.array.filter_array);
}
} | UTF-8 | Java | 8,307 | java | Trans_Fast_Fragment.java | Java | [] | null | [] | package com.example.financial_savings.fragments.trans_fast;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.financial_savings.R;
import com.example.financial_savings.controllers.chooses.ChooseWalletActivity;
import com.example.financial_savings.entities.DanhMuc;
import com.example.financial_savings.entities.SoGiaoDich;
import com.example.financial_savings.entities.ViCaNhan;
import com.example.financial_savings.helper.DBHelper;
import com.example.financial_savings.interfaces.IMappingView;
import com.example.financial_savings.modules.displays.TransactionFastDisplayModule;
import com.example.financial_savings.modules.formats.FormatMoneyModule;
import com.example.financial_savings.modules.refreshs.SwipeRefreshModule;
import com.example.financial_savings.modules.transactions.TransactionFastModule;
import com.example.financial_savings.modules.wallets.MoneyWalletModule;
import com.example.financial_savings.sessions.Session;
import java.util.ArrayList;
public class Trans_Fast_Fragment extends Fragment implements IMappingView {
private ImageButton buttonIconWallet, buttonIconDown, buttonIconFilter;
private TextView textViewNameWallet, textViewMoneyWallet;
private ListView listView;
private View root;
private DBHelper dbHelper;
private Session session;
private static final String WALLET_TOTAL = "total";
private static final String DOANHTHU = "doanhthu";
private static final String KHOANCHI = "khoanchi";
private String[] FILTER_ARRAY;
private ArrayList<SoGiaoDich> soGiaoDichs;
private SwipeRefreshLayout swipeRefresh;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.transaction_fast, container, false);
init();
if(getUserVisibleHint()) loadData();
loadData();
eventChooseWallet();
eventFilter();
eventRefresh();
return root;
}
private void eventRefresh() {
Runnable runnable = new Runnable() {
@Override
public void run() {
loadData();
}
};
SwipeRefreshModule.eventRefresh(swipeRefresh, runnable);
}
private void eventFilter() {
buttonIconFilter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getActivity());
dialog.setTitle(getResources().getString(R.string.filter_dialog));
dialog.setContentView(R.layout.transaction_filter_dialog);
ListView listViewFilter = dialog.findViewById(R.id.listViewFilter_filter_dialog);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, FILTER_ARRAY);
listViewFilter.setAdapter(adapter);
listViewFilter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
handlingFilter(position);
dialog.dismiss();
}
});
}
});
}
private void handlingFilter(int position) {
ArrayList<SoGiaoDich> list = new ArrayList<>();
for (int i = 0; i < soGiaoDichs.size(); i++) {
String idCate = soGiaoDichs.get(i).getMaDanhMuc();
DanhMuc danhMuc = dbHelper.getByID_DanhMuc(idCate);
if(position == 1 && danhMuc.getLoaiDanhMuc().equals(DOANHTHU)) {
list.add(soGiaoDichs.get(i));
}
else if(position == 2 && danhMuc.getLoaiDanhMuc().equals(KHOANCHI)) {
list.add(soGiaoDichs.get(i));
}
else if(position == 0) {
list.add(soGiaoDichs.get(i));
}
}
TransactionFastDisplayModule.showListViewHomeFast_Transaction(TransactionFastModule.getSoGiaoDichesStatus(list),
getActivity(), listView, dbHelper);
}
private void eventChooseWallet() {
buttonIconWallet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ChooseWalletActivity.class);
intent.putExtra("name", WALLET_TOTAL);
startActivity(intent);
}
});
buttonIconDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ChooseWalletActivity.class);
intent.putExtra("name", WALLET_TOTAL);
startActivity(intent);
}
});
}
@SuppressLint("SetTextI18n")
private void loadData() {
String idWallet = session.getIDWallet();
if(idWallet.equals(WALLET_TOTAL) || idWallet == null || idWallet.isEmpty()) {
soGiaoDichs = dbHelper.getAll_SoGiaoDich();
getListWalletTotal();
}
else {
soGiaoDichs = dbHelper.getByWallet_SoGiaoDich(idWallet);
getListIDWallet(idWallet);
}
TransactionFastDisplayModule.showListViewHomeFast_Transaction(TransactionFastModule.getSoGiaoDichesStatus(soGiaoDichs),
getActivity(), listView, dbHelper);
}
@SuppressLint("SetTextI18n")
private void getListWalletTotal() {
ArrayList<ViCaNhan> wallets = dbHelper.getAll_ViCaNhan();
double totalWallet = MoneyWalletModule.getMoneyWallet(wallets);
textViewNameWallet.setText(getResources().getString(R.string.all_wallet));
textViewMoneyWallet.setText(FormatMoneyModule.formatAmount(totalWallet) + " VND");
buttonIconWallet.setBackgroundResource(R.drawable.ic_language_black_24dp);
}
@SuppressLint("SetTextI18n")
private void getListIDWallet(String idWallet) {
ViCaNhan viCaNhan = dbHelper.getByID_ViCaNhan(idWallet);
textViewNameWallet.setText(viCaNhan.getTenVi());
textViewMoneyWallet.setText(FormatMoneyModule.formatAmount(viCaNhan.getSoTien()) + " VND");
buttonIconWallet.setBackgroundResource(R.drawable.ic_account_balance_wallet_black_24dp);
}
@Override
public void onResume() {
super.onResume();
loadData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && isResumed()) {
loadData();
}
}
@Override
public void init() {
buttonIconWallet = root.findViewById(R.id.buttonIconWallet_transaction_fast);
buttonIconDown = root.findViewById(R.id.buttonIconDown_transaction_fast);
buttonIconFilter = root.findViewById(R.id.buttonIconFilter_transaction_fast);
textViewNameWallet = root.findViewById(R.id.textViewNameWallet_transaction_fast);
textViewMoneyWallet = root.findViewById(R.id.textViewMoneyWallet_transaction_fast);
swipeRefresh = root.findViewById(R.id.swipeRefresh_transaction_fast);
listView = root.findViewById(R.id.listView_transaction_fast);
dbHelper = new DBHelper(root.getContext());
session = new Session(root.getContext());
session.clear();
FILTER_ARRAY = getResources().getStringArray(R.array.filter_array);
}
} | 8,307 | 0.674973 | 0.673167 | 198 | 40.959595 | 29.547571 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 8 |
408d45237ee8bdac20bd26e704b53644865c4b74 | 16,956,530,943,334 | 799671cce0d01cd0552c274c87be3cc48fdb41ed | /app/src/main/java/com/just/first/chapter02/RecoveryActivity.java | 4b61206a97362a4427963ff6c6389f2b4c8ab37d | [] | no_license | JustDo23/FirstLineCode | https://github.com/JustDo23/FirstLineCode | 0b22787d6b26b164a0fbc3ff4855e3c375219ac9 | 5d0552142561bf2fbd57b62af3a8c2ebbd253c5f | refs/heads/master | 2021-01-20T09:20:17.043000 | 2018-05-22T09:39:27 | 2018-05-22T09:39:27 | 90,239,244 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.just.first.chapter02;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.just.first.R;
import com.just.first.base.BaseActivity;
import com.just.first.utils.LogUtils;
/**
* 2.4.5 活动被回收了怎么办
*
* @author JustDo23
* @since 2017年05月07日
*/
public class RecoveryActivity extends BaseActivity implements View.OnClickListener {
private EditText et_email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recovery);
LogUtils.e(simpleName + " ---> " + "onCreate()");
findViewById(R.id.bt_go).setOnClickListener(this);
et_email = (EditText) findViewById(R.id.et_email);
if (savedInstanceState != null) {
String tempData = savedInstanceState.getString("data_key");
LogUtils.e(simpleName + " ---> " + "tempData = " + tempData);
}
}
@Override
protected void onStart() {
super.onStart();
LogUtils.e(simpleName + " ---> " + "onStart()");
}
@Override
protected void onResume() {
super.onResume();
LogUtils.e(simpleName + " ---> " + "onResume()");
}
@Override
protected void onPause() {
super.onPause();
LogUtils.e(simpleName + " ---> " + "onPause()");
}
@Override
protected void onStop() {
super.onStop();
LogUtils.e(simpleName + " ---> " + "onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
LogUtils.e(simpleName + " ---> " + "onDestroy()");
}
@Override
protected void onRestart() {
super.onRestart();
LogUtils.e(simpleName + " ---> " + "onRestart()");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_go:
startActivity(new Intent(this, IntentActivity.class));
break;
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
LogUtils.e(simpleName + " ---> " + "onSaveInstanceState()");
String tempData = "Something you just typed";
outState.putString("data_key", tempData);
}
}
| UTF-8 | Java | 2,157 | java | RecoveryActivity.java | Java | [
{
"context": "ls.LogUtils;\n\n/**\n * 2.4.5 活动被回收了怎么办\n *\n * @author JustDo23\n * @since 2017年05月07日\n */\npublic class RecoveryAc",
"end": 301,
"score": 0.9994011521339417,
"start": 293,
"tag": "USERNAME",
"value": "JustDo23"
}
] | null | [] | package com.just.first.chapter02;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.just.first.R;
import com.just.first.base.BaseActivity;
import com.just.first.utils.LogUtils;
/**
* 2.4.5 活动被回收了怎么办
*
* @author JustDo23
* @since 2017年05月07日
*/
public class RecoveryActivity extends BaseActivity implements View.OnClickListener {
private EditText et_email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recovery);
LogUtils.e(simpleName + " ---> " + "onCreate()");
findViewById(R.id.bt_go).setOnClickListener(this);
et_email = (EditText) findViewById(R.id.et_email);
if (savedInstanceState != null) {
String tempData = savedInstanceState.getString("data_key");
LogUtils.e(simpleName + " ---> " + "tempData = " + tempData);
}
}
@Override
protected void onStart() {
super.onStart();
LogUtils.e(simpleName + " ---> " + "onStart()");
}
@Override
protected void onResume() {
super.onResume();
LogUtils.e(simpleName + " ---> " + "onResume()");
}
@Override
protected void onPause() {
super.onPause();
LogUtils.e(simpleName + " ---> " + "onPause()");
}
@Override
protected void onStop() {
super.onStop();
LogUtils.e(simpleName + " ---> " + "onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
LogUtils.e(simpleName + " ---> " + "onDestroy()");
}
@Override
protected void onRestart() {
super.onRestart();
LogUtils.e(simpleName + " ---> " + "onRestart()");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_go:
startActivity(new Intent(this, IntentActivity.class));
break;
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
LogUtils.e(simpleName + " ---> " + "onSaveInstanceState()");
String tempData = "Something you just typed";
outState.putString("data_key", tempData);
}
}
| 2,157 | 0.646038 | 0.639006 | 88 | 23.238636 | 21.010275 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 8 |
d7ae412954f3e5a2d77181b03ab90e55db09833a | 23,218,593,234,399 | f306cda2ae09b6c0bd39e5ee5dd0bb0c964d76c1 | /web-base-user/src/main/java/com/web/base/user/controller/ExceptionController.java | 1a2f1c03ca96eebe6bb319b2007f7873f6578903 | [] | no_license | dhhua/web-base | https://github.com/dhhua/web-base | 938d6fa96d0745b5f4f9426c56f68d1e3a2f8816 | 9f73bb699ccfeccb37c3c198860d2eee4ffc0354 | refs/heads/master | 2023-06-21T23:04:31.315000 | 2020-05-18T15:12:43 | 2020-05-18T15:12:43 | 260,923,928 | 0 | 0 | null | false | 2023-06-14T22:30:00 | 2020-05-03T13:19:42 | 2020-05-18T15:13:17 | 2023-06-14T22:30:00 | 34 | 0 | 0 | 2 | Java | false | false | package com.web.base.user.controller;
import com.web.base.common.base.BusinessException;
import com.web.base.common.web.WebResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
/**
* @author donghonghua
* @date 2018/8/24
*/
@RestControllerAdvice
public class ExceptionController {
private final Logger logger = LoggerFactory.getLogger(ExceptionController.class);
@ExceptionHandler(BusinessException.class)
public WebResponse<?> catchException(BusinessException e) {
logger.info(e.getMessage());
return WebResponse.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<WebResponse<?>> httpException(HttpClientErrorException e) {
logger.info(e.getMessage());
WebResponse<?> response = WebResponse.fail(e.getStatusCode().value(), e.getMessage());
return ResponseEntity.status(e.getStatusCode().value()).body(response);
}
@ExceptionHandler(RuntimeException.class)
public WebResponse<?> runtimeException(RuntimeException e) {
logger.info(e.getMessage());
return WebResponse.fail(-1, e.getMessage());
}
}
| UTF-8 | Java | 1,419 | java | ExceptionController.java | Java | [
{
"context": "b.client.HttpClientErrorException;\n\n/**\n * @author donghonghua\n * @date 2018/8/24\n */\n@RestControllerAdvice\npubl",
"end": 464,
"score": 0.9992241263389587,
"start": 453,
"tag": "USERNAME",
"value": "donghonghua"
}
] | null | [] | package com.web.base.user.controller;
import com.web.base.common.base.BusinessException;
import com.web.base.common.web.WebResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
/**
* @author donghonghua
* @date 2018/8/24
*/
@RestControllerAdvice
public class ExceptionController {
private final Logger logger = LoggerFactory.getLogger(ExceptionController.class);
@ExceptionHandler(BusinessException.class)
public WebResponse<?> catchException(BusinessException e) {
logger.info(e.getMessage());
return WebResponse.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<WebResponse<?>> httpException(HttpClientErrorException e) {
logger.info(e.getMessage());
WebResponse<?> response = WebResponse.fail(e.getStatusCode().value(), e.getMessage());
return ResponseEntity.status(e.getStatusCode().value()).body(response);
}
@ExceptionHandler(RuntimeException.class)
public WebResponse<?> runtimeException(RuntimeException e) {
logger.info(e.getMessage());
return WebResponse.fail(-1, e.getMessage());
}
}
| 1,419 | 0.751938 | 0.744891 | 40 | 34.474998 | 28.26923 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
369fd92a9cbd730db920b5dcdfbf99876ec77c9b | 1,529,008,402,715 | 101a966196d8c250e9ab974c267303ff53350b64 | /src/leetCodeTest/四数相加2.java | fc81499a82f49159815847564ba33ae63520aa67 | [] | no_license | meiszl/LeetCodetest | https://github.com/meiszl/LeetCodetest | d59b424f3dc5468ecd8326fe50d61181401b29bc | 07b73544b1bdd371f5a327b9c386dab0c856a910 | refs/heads/master | 2023-04-13T03:46:53.009000 | 2023-04-10T15:22:23 | 2023-04-10T15:22:23 | 248,486,362 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetCodeTest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class 四数相加2 {
public static void main(String[] args) {
int[] A,B,C,D;
A = new int[]{1,2};
B = new int[]{-2,-1};
C = new int[]{-1,2};
D = new int[]{0,2};
int i = fourSumCount(A, B, C, D);
System.out.println("i = " + i);
}
public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int i,j,res = 0;
Map<Integer,Integer> map = new HashMap();
for (i=0;i<A.length;i++){
for (j=0;j<B.length;j++){
if (map.containsKey(A[i] + B[j]))
map.put(A[i] + B[j],map.get(A[i] + B[j]) + 1);
else
map.put(A[i] + B[j],1);
}
}
for (i=0;i<C.length;i++){
for (j=0;j<D.length;j++){
int sum = -(C[i] + D[j]);
if (map.containsKey(sum))
res += map.get(sum);
}
}
return res;
}
}
| UTF-8 | Java | 1,072 | java | 四数相加2.java | Java | [] | null | [] | package leetCodeTest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class 四数相加2 {
public static void main(String[] args) {
int[] A,B,C,D;
A = new int[]{1,2};
B = new int[]{-2,-1};
C = new int[]{-1,2};
D = new int[]{0,2};
int i = fourSumCount(A, B, C, D);
System.out.println("i = " + i);
}
public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int i,j,res = 0;
Map<Integer,Integer> map = new HashMap();
for (i=0;i<A.length;i++){
for (j=0;j<B.length;j++){
if (map.containsKey(A[i] + B[j]))
map.put(A[i] + B[j],map.get(A[i] + B[j]) + 1);
else
map.put(A[i] + B[j],1);
}
}
for (i=0;i<C.length;i++){
for (j=0;j<D.length;j++){
int sum = -(C[i] + D[j]);
if (map.containsKey(sum))
res += map.get(sum);
}
}
return res;
}
}
| 1,072 | 0.421053 | 0.406015 | 37 | 27.756756 | 16.956869 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.189189 | false | false | 8 |
fcc69303a180735ec7b834349dd675d80468541d | 6,176,163,025,076 | 995f73d30450a6dce6bc7145d89344b4ad6e0622 | /Mate20-9.0/src/main/java/com/android/server/gesture/anim/ScaleImageView.java | 053ff999a9e87cea0ef426d69bff0a8632c9d694 | [] | no_license | morningblu/HWFramework | https://github.com/morningblu/HWFramework | 0ceb02cbe42585d0169d9b6c4964a41b436039f5 | 672bb34094b8780806a10ba9b1d21036fd808b8e | refs/heads/master | 2023-07-29T05:26:14.603000 | 2021-09-03T05:23:34 | 2021-09-03T05:23:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.server.gesture.anim;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.TimeInterpolator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.SurfaceControl;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.PathInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import com.android.server.gesture.GestureNavConst;
import com.android.server.wm.PhaseInterpolator;
import java.util.Arrays;
import java.util.List;
public class ScaleImageView extends ImageView {
public static final int ANIM_TYPE_RECOVER = 1;
public static final int ANIM_TYPE_TRANSLATE = 0;
private static final int ERROR_ID = -1;
private static final float FOLLOW_TRANSLATE_RATIO = 0.1f;
private static final int LANDSCAPE_FINAL_WIDTH = 316;
private static final String LEFT = "left";
private static final float MAX_SCALE_DISTANCE = 500.0f;
private static final float MAX_SCALE_RATIO = 0.7f;
private static final int NAVIGATIONBAR_LAYER = 231000;
private static final int PICTURE_ROUND = 2;
private static final int PORTRAIT_FINAL_WIDTH = 328;
private static final long RECOVER_ANIMATION_DURATION = 100;
private static final String RIGHT = "right";
private static final float SCALE = 0.75f;
private static final float SCALE_X_PIVOT = 0.5f;
private static final float SCALE_Y_PIVOT = 0.625f;
private static final int STATE_LEFT = 1;
private static final int STATE_MIDDLE = 0;
private static final int STATE_RIGHT = 2;
private static final String TAG = "GestureScale";
private static final long TRANSLATE_ANIMATION_DURATION = 300;
private static final int TYPE_LANDSCAPE = 1;
private static final int TYPE_PORTRAIT = 0;
private TimeInterpolator[] mAlphaInterpolators = {this.mConstantInterpolator, new PathInterpolator(0.4f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.6f, 1.0f), this.mConstantInterpolator};
private ActivityManager mAm;
/* access modifiers changed from: private */
public TranslateAnimationListener mAnimationListener;
private TimeInterpolator mConstantInterpolator = new TimeInterpolator() {
public float getInterpolation(float input) {
return 1.0f;
}
};
private Context mContext;
private boolean mFollowStart;
private float mFollowStartX;
private float mFollowStartY;
private float mHeight;
private int mScreenOrientation;
private TimeInterpolator[] mSizeBigInterpolators = {new PathInterpolator(0.44f, 0.43f, 0.7f, 0.75f), new PathInterpolator(0.13f, 0.79f, 0.3f, 1.0f)};
private TimeInterpolator[] mSizeSmallInterpolators = {new PathInterpolator(0.41f, 0.38f, 0.7f, 0.71f), new PathInterpolator(0.16f, 0.64f, 0.33f, 1.0f)};
private float mWidth;
public interface TranslateAnimationListener {
void onAnimationEnd(int i);
}
public ScaleImageView(Context context) {
super(context);
init(context);
}
public ScaleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ScaleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
Log.d(TAG, "init");
this.mFollowStart = false;
this.mContext = context;
this.mAm = (ActivityManager) context.getSystemService(ActivityManager.class);
initWms();
}
private void initWms() {
}
/* access modifiers changed from: protected */
public void onSizeChanged(int w, int h, int oldW, int oldH) {
this.mWidth = (float) w;
this.mHeight = (float) h;
Log.d(TAG, "view width is " + this.mWidth + ", height is " + this.mHeight);
float pivotX = this.mWidth * 0.5f;
float pivotY = this.mHeight * SCALE_Y_PIVOT;
setPivotX(pivotX);
setPivotY(pivotY);
Log.d(TAG, "view pivotX is " + pivotX + ", pivotY is " + pivotY);
}
private static int dp2px(Context context, int dp) {
if (context != null && dp > 0) {
return (int) TypedValue.applyDimension(1, (float) dp, context.getResources().getDisplayMetrics());
}
Log.e(TAG, "dp2px parameters error.");
return 0;
}
/* access modifiers changed from: protected */
public void onConfigurationChanged(Configuration newConfig) {
if (newConfig.orientation == 1) {
this.mScreenOrientation = 0;
} else {
this.mScreenOrientation = 1;
}
Log.d(TAG, "mScreenOrientation " + this.mScreenOrientation);
}
public void setFollowPosition(float x, float y) {
if (!this.mFollowStart) {
this.mFollowStartX = x;
this.mFollowStartY = y;
this.mFollowStart = true;
return;
}
doScale(this.mFollowStartY < y ? GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO : this.mFollowStartY - y);
doTranslate(x - this.mFollowStartX, this.mFollowStartY - y, 0.1f);
}
private void doScale(float y) {
float scale;
if (y >= MAX_SCALE_DISTANCE) {
scale = 0.7f;
} else {
scale = 1.0f - (0.3f * (y / MAX_SCALE_DISTANCE));
}
setScaleX(scale);
setScaleY(scale);
}
private void doTranslate(float x, float y, float transRatio) {
float moveX = x * transRatio;
float moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO;
if (y > MAX_SCALE_DISTANCE) {
moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO - ((y - MAX_SCALE_DISTANCE) * transRatio);
} else if (y < GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO) {
moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO + ((-y) * transRatio);
}
setX(moveX);
setY(moveY);
}
public void refreshContent() {
Log.d(TAG, "refreshContent");
long oldT = System.currentTimeMillis();
setBackgroundColor(-7829368);
refreshBySurfaceControl();
setVisibility(0);
long newT = System.currentTimeMillis();
Log.d(TAG, "refresh content cost time " + (newT - oldT));
}
private static Bitmap addRoundOnBitmap(Bitmap source, float round) {
Bitmap bitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
Rect rect = new Rect(0, 0, source.getWidth(), source.getHeight());
RectF rectf = new RectF(rect);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectf, round, round, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, rect, rect, paint);
return bitmap;
}
private void refreshContentByActivityManager() {
Log.d(TAG, "refreshContentByActivityManager");
int topTaskId = getTopTaskId();
if (topTaskId == -1) {
Log.e(TAG, "error top task id");
return;
}
Bitmap snapshot = getTaskSnapshot(topTaskId);
if (snapshot == null) {
Log.w(TAG, "task snapshot is null, try to get task thumbnail");
snapshot = getTaskThumbnail(topTaskId);
}
if (snapshot != null) {
Log.d(TAG, "set snapshot bitmap into ImageView");
setScaleType(ImageView.ScaleType.FIT_CENTER);
setImageBitmap(addRoundOnBitmap(snapshot, (float) dp2px(this.mContext, 2)));
} else {
Log.d(TAG, "no snapshot, use color.");
setBackgroundColor(-7829368);
}
}
private int getTopTaskId() {
List<ActivityManager.RunningTaskInfo> tasks = this.mAm.getRunningTasks(1);
if (tasks == null || tasks.isEmpty()) {
Log.d(TAG, "tasks count is 0");
return -1;
}
Log.d(TAG, "tasks count is " + tasks.size());
return tasks.get(0).id;
}
private Bitmap getTaskSnapshot(int topTaskId) {
Log.d(TAG, "getTaskSnapshot with top task id " + topTaskId);
try {
ActivityManager.TaskSnapshot taskSnapshot = ActivityManager.getService().getTaskSnapshot(topTaskId, false);
if (taskSnapshot == null) {
Log.e(TAG, "error, taskSnapshot is null");
return null;
}
Bitmap snapshot = Bitmap.createHardwareBitmap(taskSnapshot.getSnapshot());
if (snapshot == null) {
Log.e(TAG, "error, snapshot is null");
}
return snapshot;
} catch (RemoteException e) {
Log.e(TAG, "RemoteException");
return null;
}
}
private Bitmap getTaskThumbnail(int topTaskId) {
Log.d(TAG, "getTaskThumbnail with top task id " + topTaskId);
return null;
}
private void refreshBySurfaceControl() {
Log.d(TAG, "refreshBySurfaceControl");
setScaleType(ImageView.ScaleType.MATRIX);
Matrix matrix = new Matrix();
matrix.setTranslate(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, (float) getStatusBarHeight(this.mContext));
setImageMatrix(matrix);
Bitmap bitmap = screenShotBitmap(this.mContext, 0, Integer.MAX_VALUE);
if (bitmap == null) {
setBackgroundColor(-7829368);
return;
}
setScaleType(ImageView.ScaleType.FIT_CENTER);
setImageBitmap(addRoundOnBitmap(bitmap, (float) dp2px(this.mContext, 2)));
}
public static Bitmap screenShotBitmap(Context ctx, int minLayer, int maxLayer) {
return screenShotBitmap(ctx, 1.0f);
}
public static Bitmap screenShotBitmap(Context ctx, float scale) {
Bitmap bitmap;
DisplayMetrics displayMetrics = new DisplayMetrics();
DisplayMetrics displayMetricsBody = new DisplayMetrics();
Display display = ((WindowManager) ctx.getSystemService("window")).getDefaultDisplay();
display.getMetrics(displayMetricsBody);
display.getRealMetrics(displayMetrics);
Log.d(TAG, "Display getMetrics w:" + displayMetricsBody.widthPixels + ", h:" + displayMetricsBody.heightPixels);
Log.d(TAG, "Display getRealMetrics w:" + displayMetrics.widthPixels + ", h:" + displayMetrics.heightPixels);
int[] dims = {(((int) (((float) displayMetrics.widthPixels) * scale)) / 2) * 2, (((int) (((float) displayMetrics.heightPixels) * scale)) / 2) * 2};
int[] dimsBody = {(((int) (((float) displayMetricsBody.widthPixels) * scale)) / 2) * 2, (((int) (((float) displayMetricsBody.heightPixels) * scale)) / 2) * 2};
Log.d(TAG, "mFingerViewParams, dims[0] =" + dims[0] + ", dims[1] =" + dims[1]);
Log.d(TAG, "mFingerViewParams, dimsBody[0] =" + dimsBody[0] + ", dimsBody[1] =" + dimsBody[1]);
if (isLazyMode(ctx)) {
Rect screenshotRect = getScreenshotRect(ctx);
} else {
new Rect();
}
Rect screenRect = new Rect(0, getStatusBarHeight(ctx), dimsBody[0], dimsBody[1]);
int rotation = display.getRotation();
if (rotation == 0 || 2 == rotation) {
Log.d(TAG, "SurfaceControl.screenshot_ext_hw with rotation " + rotation);
bitmap = SurfaceControl.screenshot_ext_hw(screenRect, dimsBody[0], dimsBody[1], 0, NAVIGATIONBAR_LAYER, false, converseRotation(rotation));
} else {
bitmap = rotationScreenBitmap(screenRect, rotation, dimsBody, 0, NAVIGATIONBAR_LAYER);
}
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, dimsBody[0], dimsBody[1]);
if (bitmap2 == null) {
Log.e(TAG, "screenShotBitmap error bitmap is null");
return null;
}
bitmap2.prepareToDraw();
return bitmap2;
}
private static int getStatusBarHeight(Context context) {
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return context.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
private static int converseRotation(int rotation) {
switch (rotation) {
case 1:
return 3;
case 2:
return 2;
case 3:
return 1;
default:
return 0;
}
}
private static float convertRotationToDegrees(int rotation) {
switch (rotation) {
case 1:
return 270.0f;
case 2:
return 180.0f;
case 3:
return 90.0f;
default:
return GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO;
}
}
private static Bitmap rotationScreenBitmap(Rect rect, int rotation, int[] srcDims, int minLayer, int maxLayer) {
StringBuilder sb = new StringBuilder();
sb.append("rotationScreenBitmap with rotation ");
sb.append(rotation);
sb.append(", srcDims ");
sb.append(Arrays.toString(srcDims));
sb.append(", layer ");
int i = minLayer;
sb.append(i);
sb.append(",");
int i2 = maxLayer;
sb.append(i2);
Log.d(TAG, sb.toString());
float degrees = convertRotationToDegrees(rotation);
float[] dims = {(float) srcDims[0], (float) srcDims[1]};
Matrix metrics = new Matrix();
metrics.reset();
metrics.preRotate(-degrees);
metrics.mapPoints(dims);
dims[0] = Math.abs(dims[0]);
dims[1] = Math.abs(dims[1]);
Bitmap bitmap = SurfaceControl.screenshot(rect, (int) dims[0], (int) dims[1], i, i2, false, 0);
Bitmap ss = Bitmap.createBitmap(srcDims[0], srcDims[1], Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(ss);
c.translate(((float) srcDims[0]) * 0.5f, ((float) srcDims[1]) * 0.5f);
c.rotate(degrees);
c.translate((-dims[0]) * 0.5f, (-dims[1]) * 0.5f);
c.drawBitmap(bitmap, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, null);
bitmap.recycle();
return ss;
}
private static int getLazyState(Context context) {
String str = Settings.Global.getString(context.getContentResolver(), "single_hand_mode");
if (str == null || "".equals(str)) {
return 0;
}
if (str.contains(LEFT)) {
return 1;
}
if (str.contains(RIGHT)) {
return 2;
}
return 0;
}
private static boolean isLazyMode(Context context) {
return getLazyState(context) != 0;
}
private static Rect getScreenshotRect(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService("window");
if (windowManager == null) {
return new Rect();
}
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getRealMetrics(displayMetrics);
Rect sourceCrop = null;
int state = getLazyState(context);
if (1 == state) {
sourceCrop = new Rect(0, (int) (((float) displayMetrics.heightPixels) * 0.25f), (int) (((float) displayMetrics.widthPixels) * 0.75f), displayMetrics.heightPixels);
} else if (2 == state) {
sourceCrop = new Rect((int) (((float) displayMetrics.widthPixels) * 0.25f), (int) (((float) displayMetrics.heightPixels) * 0.25f), displayMetrics.widthPixels, displayMetrics.heightPixels);
}
return sourceCrop;
}
public void playTranslateAnimation(int topDistance) {
int finalWidth;
this.mFollowStart = false;
float oldX = getX();
float oldY = getY();
float oldScaleX = getScaleX();
float oldScaleY = getScaleY();
if (this.mScreenOrientation == 0) {
finalWidth = dp2px(this.mContext, PORTRAIT_FINAL_WIDTH);
} else {
finalWidth = dp2px(this.mContext, LANDSCAPE_FINAL_WIDTH);
}
float newScale = ((float) finalWidth) / this.mWidth;
float newY = ((float) topDistance) - ((this.mHeight - (this.mHeight * newScale)) / 2.0f);
PropertyValuesHolder xProperty = PropertyValuesHolder.ofFloat("x", new float[]{oldX, 0.0f});
PropertyValuesHolder yProperty = PropertyValuesHolder.ofFloat("y", new float[]{oldY, newY});
PropertyValuesHolder xScaleProperty = PropertyValuesHolder.ofFloat("scaleX", new float[]{oldScaleX, newScale});
float f = oldX;
PropertyValuesHolder yScaleProperty = PropertyValuesHolder.ofFloat("scaleY", new float[]{oldScaleY, newScale});
ObjectAnimator transAnimator = ObjectAnimator.ofPropertyValuesHolder(this, new PropertyValuesHolder[]{xProperty, yProperty, xScaleProperty, yScaleProperty, PropertyValuesHolder.ofFloat("alpha", new float[]{1.0f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO})});
transAnimator.setInterpolator(AnimationUtils.loadInterpolator(this.mContext, 17563661));
PropertyValuesHolder propertyValuesHolder = yScaleProperty;
float f2 = oldY;
transAnimator.setDuration(TRANSLATE_ANIMATION_DURATION);
transAnimator.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
Log.d(ScaleImageView.TAG, "onAnimationEnd translate");
ScaleImageView.this.setVisibility(8);
ScaleImageView.this.setScaleX(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setScaleY(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setX(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setY(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setAlpha(1.0f);
if (ScaleImageView.this.mAnimationListener != null) {
ScaleImageView.this.mAnimationListener.onAnimationEnd(0);
}
}
});
transAnimator.start();
}
public void playRecoverAnimation() {
this.mFollowStart = false;
float oldX = getX();
float oldY = getY();
float oldScaleX = getScaleX();
float oldScaleY = getScaleY();
ObjectAnimator recover = ObjectAnimator.ofPropertyValuesHolder(this, new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("x", new float[]{oldX, 0.0f}), PropertyValuesHolder.ofFloat("y", new float[]{oldY, 0.0f}), PropertyValuesHolder.ofFloat("scaleX", new float[]{oldScaleX, 1.0f}), PropertyValuesHolder.ofFloat("scaleY", new float[]{oldScaleY, 1.0f})});
recover.setInterpolator(AnimationUtils.loadInterpolator(this.mContext, 17563661));
recover.setDuration(RECOVER_ANIMATION_DURATION);
recover.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
Log.d(ScaleImageView.TAG, "onAnimationEnd recover");
ScaleImageView.this.setVisibility(8);
if (ScaleImageView.this.mAnimationListener != null) {
ScaleImageView.this.mAnimationListener.onAnimationEnd(1);
}
}
});
recover.start();
}
public void playGestureToLauncherIconAnimation(boolean isIconView) {
}
private float[] calculateScalePivot(float px, float py, float fromWidth, float fromHeight, float toWidth, float toHeight, int[] fromLocInWindow) {
float scaleX = toWidth / fromWidth;
float scaleY = toHeight / fromHeight;
return new float[]{((px - (toWidth / 2.0f)) - (((float) fromLocInWindow[0]) * scaleX)) / (1.0f - scaleX), ((py - (toHeight / 2.0f)) - (((float) fromLocInWindow[1]) * scaleY)) / (1.0f - scaleY)};
}
private Animation createGestureToLauncherIconAnimation(float targetPx, float targetPy, int iconWidth, int iconHeight, float fromAlpha, float toAlpha) {
TimeInterpolator[] sizeXInterpolators;
TimeInterpolator[] sizeYInterpolators;
PhaseInterpolator contentAnimSet = new AnimationSet(false);
long duration = SystemProperties.getLong("to_launcher_dur", 350);
AlphaAnimation contentAlphaAnim = new AlphaAnimation(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f);
contentAlphaAnim.setDuration(duration);
float[] alphaInValues = {GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.16f, 0.32f, 1.0f};
float[] contentAlphaOutValues = {fromAlpha, fromAlpha, toAlpha, toAlpha};
PhaseInterpolator contentAlphaInterpolator = new PhaseInterpolator(alphaInValues, contentAlphaOutValues, this.mAlphaInterpolators);
contentAlphaAnim.setInterpolator(contentAlphaInterpolator);
WindowManager wm = (WindowManager) this.mContext.getSystemService("window");
int windowWidth = wm.getDefaultDisplay().getWidth();
int windowHeight = wm.getDefaultDisplay().getHeight();
int viewHeight = (int) (((float) getMeasuredHeight()) * getScaleY());
int viewWidth = (int) (((float) getMeasuredWidth()) * getScaleX());
int[] viewLocInWindow = new int[2];
getLocationInWindow(viewLocInWindow);
int windowWidth2 = windowWidth;
StringBuilder sb = new StringBuilder();
WindowManager windowManager = wm;
sb.append("[viewWidth, viewHeight, viewLocX, viewLocY] = [");
sb.append(viewWidth);
sb.append(", ");
sb.append(viewHeight);
sb.append(", ");
PhaseInterpolator phaseInterpolator = contentAlphaInterpolator;
sb.append(viewLocInWindow[0]);
sb.append(", ");
sb.append(viewLocInWindow[1]);
sb.append("]");
Log.d(TAG, sb.toString());
float fromWidth = (float) viewWidth;
float fromHeight = (float) viewHeight;
float toWidth = (float) iconWidth;
PhaseInterpolator contentAnimSet2 = contentAnimSet;
float toHeight = (float) iconHeight;
float scaleToX = toWidth / fromWidth;
float scaleToY = toHeight / fromHeight;
boolean isHorizontal = viewWidth > viewHeight;
float middleYRatio = 0.44f;
float middleXRatio = isHorizontal ? 0.54f : 0.44f;
if (!isHorizontal) {
middleYRatio = 0.54f;
}
float middleY = 1.0f - (((fromHeight - toHeight) * middleYRatio) / fromHeight);
int windowWidth3 = windowWidth2;
float[] fArr = contentAlphaOutValues;
int windowHeight2 = windowHeight;
int viewHeight2 = viewHeight;
float f = fromWidth;
float[] fArr2 = alphaInValues;
float[] pivot = calculateScalePivot(targetPx, targetPy, fromWidth, fromHeight, toWidth, toHeight, viewLocInWindow);
float pivotX = pivot[0];
float pivotY = pivot[1];
float[] scaleInValues = {GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.16f, 1.0f};
float[] scaleOutValuesX = {1.0f, 1.0f - (((fromWidth - toWidth) * middleXRatio) / fromWidth), scaleToX};
float[] scaleOutValuesY = {1.0f, middleY, scaleToY};
if (isHorizontal) {
sizeXInterpolators = this.mSizeBigInterpolators;
} else {
sizeXInterpolators = this.mSizeSmallInterpolators;
}
if (isHorizontal) {
sizeYInterpolators = this.mSizeSmallInterpolators;
} else {
sizeYInterpolators = this.mSizeBigInterpolators;
}
PhaseInterpolator interpolatorX = new PhaseInterpolator(scaleInValues, scaleOutValuesX, sizeXInterpolators);
float[] fArr3 = pivot;
PhaseInterpolator interpolatorY = new PhaseInterpolator(scaleInValues, scaleOutValuesY, sizeYInterpolators);
float f2 = pivotX;
float f3 = pivotY;
ScaleAnimation contentScaleAnimX = new ScaleAnimation(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f, 1.0f, 1.0f, f2, f3);
float[] fArr4 = scaleOutValuesY;
ScaleAnimation contentScaleAnimX2 = contentScaleAnimX;
contentScaleAnimX2.setDuration(duration);
contentScaleAnimX2.setInterpolator(interpolatorX);
ScaleAnimation contentScaleAnimY = new ScaleAnimation(1.0f, 1.0f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f, f2, f3);
float f4 = pivotX;
ScaleAnimation contentScaleAnimY2 = contentScaleAnimY;
contentScaleAnimY2.setDuration(duration);
contentScaleAnimY2.setInterpolator(interpolatorY);
PhaseInterpolator phaseInterpolator2 = interpolatorY;
PhaseInterpolator interpolatorY2 = contentAnimSet2;
interpolatorY2.addAnimation(contentAlphaAnim);
interpolatorY2.addAnimation(contentScaleAnimX2);
interpolatorY2.addAnimation(contentScaleAnimY2);
ScaleAnimation scaleAnimation = contentScaleAnimX2;
ScaleAnimation scaleAnimation2 = contentScaleAnimY2;
float f5 = pivotY;
int windowWidth4 = windowWidth3;
interpolatorY2.initialize(viewWidth, viewHeight2, windowWidth4, windowHeight2);
int i = windowWidth4;
interpolatorY2.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
ScaleImageView.this.setVisibility(8);
}
public void onAnimationRepeat(Animation animation) {
}
});
return interpolatorY2;
}
public void setAnimationListener(TranslateAnimationListener listener) {
this.mAnimationListener = listener;
}
}
| UTF-8 | Java | 26,748 | java | ScaleImageView.java | Java | [] | null | [] | package com.android.server.gesture.anim;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.TimeInterpolator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.SurfaceControl;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.PathInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import com.android.server.gesture.GestureNavConst;
import com.android.server.wm.PhaseInterpolator;
import java.util.Arrays;
import java.util.List;
public class ScaleImageView extends ImageView {
public static final int ANIM_TYPE_RECOVER = 1;
public static final int ANIM_TYPE_TRANSLATE = 0;
private static final int ERROR_ID = -1;
private static final float FOLLOW_TRANSLATE_RATIO = 0.1f;
private static final int LANDSCAPE_FINAL_WIDTH = 316;
private static final String LEFT = "left";
private static final float MAX_SCALE_DISTANCE = 500.0f;
private static final float MAX_SCALE_RATIO = 0.7f;
private static final int NAVIGATIONBAR_LAYER = 231000;
private static final int PICTURE_ROUND = 2;
private static final int PORTRAIT_FINAL_WIDTH = 328;
private static final long RECOVER_ANIMATION_DURATION = 100;
private static final String RIGHT = "right";
private static final float SCALE = 0.75f;
private static final float SCALE_X_PIVOT = 0.5f;
private static final float SCALE_Y_PIVOT = 0.625f;
private static final int STATE_LEFT = 1;
private static final int STATE_MIDDLE = 0;
private static final int STATE_RIGHT = 2;
private static final String TAG = "GestureScale";
private static final long TRANSLATE_ANIMATION_DURATION = 300;
private static final int TYPE_LANDSCAPE = 1;
private static final int TYPE_PORTRAIT = 0;
private TimeInterpolator[] mAlphaInterpolators = {this.mConstantInterpolator, new PathInterpolator(0.4f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.6f, 1.0f), this.mConstantInterpolator};
private ActivityManager mAm;
/* access modifiers changed from: private */
public TranslateAnimationListener mAnimationListener;
private TimeInterpolator mConstantInterpolator = new TimeInterpolator() {
public float getInterpolation(float input) {
return 1.0f;
}
};
private Context mContext;
private boolean mFollowStart;
private float mFollowStartX;
private float mFollowStartY;
private float mHeight;
private int mScreenOrientation;
private TimeInterpolator[] mSizeBigInterpolators = {new PathInterpolator(0.44f, 0.43f, 0.7f, 0.75f), new PathInterpolator(0.13f, 0.79f, 0.3f, 1.0f)};
private TimeInterpolator[] mSizeSmallInterpolators = {new PathInterpolator(0.41f, 0.38f, 0.7f, 0.71f), new PathInterpolator(0.16f, 0.64f, 0.33f, 1.0f)};
private float mWidth;
public interface TranslateAnimationListener {
void onAnimationEnd(int i);
}
public ScaleImageView(Context context) {
super(context);
init(context);
}
public ScaleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ScaleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
Log.d(TAG, "init");
this.mFollowStart = false;
this.mContext = context;
this.mAm = (ActivityManager) context.getSystemService(ActivityManager.class);
initWms();
}
private void initWms() {
}
/* access modifiers changed from: protected */
public void onSizeChanged(int w, int h, int oldW, int oldH) {
this.mWidth = (float) w;
this.mHeight = (float) h;
Log.d(TAG, "view width is " + this.mWidth + ", height is " + this.mHeight);
float pivotX = this.mWidth * 0.5f;
float pivotY = this.mHeight * SCALE_Y_PIVOT;
setPivotX(pivotX);
setPivotY(pivotY);
Log.d(TAG, "view pivotX is " + pivotX + ", pivotY is " + pivotY);
}
private static int dp2px(Context context, int dp) {
if (context != null && dp > 0) {
return (int) TypedValue.applyDimension(1, (float) dp, context.getResources().getDisplayMetrics());
}
Log.e(TAG, "dp2px parameters error.");
return 0;
}
/* access modifiers changed from: protected */
public void onConfigurationChanged(Configuration newConfig) {
if (newConfig.orientation == 1) {
this.mScreenOrientation = 0;
} else {
this.mScreenOrientation = 1;
}
Log.d(TAG, "mScreenOrientation " + this.mScreenOrientation);
}
public void setFollowPosition(float x, float y) {
if (!this.mFollowStart) {
this.mFollowStartX = x;
this.mFollowStartY = y;
this.mFollowStart = true;
return;
}
doScale(this.mFollowStartY < y ? GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO : this.mFollowStartY - y);
doTranslate(x - this.mFollowStartX, this.mFollowStartY - y, 0.1f);
}
private void doScale(float y) {
float scale;
if (y >= MAX_SCALE_DISTANCE) {
scale = 0.7f;
} else {
scale = 1.0f - (0.3f * (y / MAX_SCALE_DISTANCE));
}
setScaleX(scale);
setScaleY(scale);
}
private void doTranslate(float x, float y, float transRatio) {
float moveX = x * transRatio;
float moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO;
if (y > MAX_SCALE_DISTANCE) {
moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO - ((y - MAX_SCALE_DISTANCE) * transRatio);
} else if (y < GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO) {
moveY = GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO + ((-y) * transRatio);
}
setX(moveX);
setY(moveY);
}
public void refreshContent() {
Log.d(TAG, "refreshContent");
long oldT = System.currentTimeMillis();
setBackgroundColor(-7829368);
refreshBySurfaceControl();
setVisibility(0);
long newT = System.currentTimeMillis();
Log.d(TAG, "refresh content cost time " + (newT - oldT));
}
private static Bitmap addRoundOnBitmap(Bitmap source, float round) {
Bitmap bitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
Rect rect = new Rect(0, 0, source.getWidth(), source.getHeight());
RectF rectf = new RectF(rect);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectf, round, round, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, rect, rect, paint);
return bitmap;
}
private void refreshContentByActivityManager() {
Log.d(TAG, "refreshContentByActivityManager");
int topTaskId = getTopTaskId();
if (topTaskId == -1) {
Log.e(TAG, "error top task id");
return;
}
Bitmap snapshot = getTaskSnapshot(topTaskId);
if (snapshot == null) {
Log.w(TAG, "task snapshot is null, try to get task thumbnail");
snapshot = getTaskThumbnail(topTaskId);
}
if (snapshot != null) {
Log.d(TAG, "set snapshot bitmap into ImageView");
setScaleType(ImageView.ScaleType.FIT_CENTER);
setImageBitmap(addRoundOnBitmap(snapshot, (float) dp2px(this.mContext, 2)));
} else {
Log.d(TAG, "no snapshot, use color.");
setBackgroundColor(-7829368);
}
}
private int getTopTaskId() {
List<ActivityManager.RunningTaskInfo> tasks = this.mAm.getRunningTasks(1);
if (tasks == null || tasks.isEmpty()) {
Log.d(TAG, "tasks count is 0");
return -1;
}
Log.d(TAG, "tasks count is " + tasks.size());
return tasks.get(0).id;
}
private Bitmap getTaskSnapshot(int topTaskId) {
Log.d(TAG, "getTaskSnapshot with top task id " + topTaskId);
try {
ActivityManager.TaskSnapshot taskSnapshot = ActivityManager.getService().getTaskSnapshot(topTaskId, false);
if (taskSnapshot == null) {
Log.e(TAG, "error, taskSnapshot is null");
return null;
}
Bitmap snapshot = Bitmap.createHardwareBitmap(taskSnapshot.getSnapshot());
if (snapshot == null) {
Log.e(TAG, "error, snapshot is null");
}
return snapshot;
} catch (RemoteException e) {
Log.e(TAG, "RemoteException");
return null;
}
}
private Bitmap getTaskThumbnail(int topTaskId) {
Log.d(TAG, "getTaskThumbnail with top task id " + topTaskId);
return null;
}
private void refreshBySurfaceControl() {
Log.d(TAG, "refreshBySurfaceControl");
setScaleType(ImageView.ScaleType.MATRIX);
Matrix matrix = new Matrix();
matrix.setTranslate(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, (float) getStatusBarHeight(this.mContext));
setImageMatrix(matrix);
Bitmap bitmap = screenShotBitmap(this.mContext, 0, Integer.MAX_VALUE);
if (bitmap == null) {
setBackgroundColor(-7829368);
return;
}
setScaleType(ImageView.ScaleType.FIT_CENTER);
setImageBitmap(addRoundOnBitmap(bitmap, (float) dp2px(this.mContext, 2)));
}
public static Bitmap screenShotBitmap(Context ctx, int minLayer, int maxLayer) {
return screenShotBitmap(ctx, 1.0f);
}
public static Bitmap screenShotBitmap(Context ctx, float scale) {
Bitmap bitmap;
DisplayMetrics displayMetrics = new DisplayMetrics();
DisplayMetrics displayMetricsBody = new DisplayMetrics();
Display display = ((WindowManager) ctx.getSystemService("window")).getDefaultDisplay();
display.getMetrics(displayMetricsBody);
display.getRealMetrics(displayMetrics);
Log.d(TAG, "Display getMetrics w:" + displayMetricsBody.widthPixels + ", h:" + displayMetricsBody.heightPixels);
Log.d(TAG, "Display getRealMetrics w:" + displayMetrics.widthPixels + ", h:" + displayMetrics.heightPixels);
int[] dims = {(((int) (((float) displayMetrics.widthPixels) * scale)) / 2) * 2, (((int) (((float) displayMetrics.heightPixels) * scale)) / 2) * 2};
int[] dimsBody = {(((int) (((float) displayMetricsBody.widthPixels) * scale)) / 2) * 2, (((int) (((float) displayMetricsBody.heightPixels) * scale)) / 2) * 2};
Log.d(TAG, "mFingerViewParams, dims[0] =" + dims[0] + ", dims[1] =" + dims[1]);
Log.d(TAG, "mFingerViewParams, dimsBody[0] =" + dimsBody[0] + ", dimsBody[1] =" + dimsBody[1]);
if (isLazyMode(ctx)) {
Rect screenshotRect = getScreenshotRect(ctx);
} else {
new Rect();
}
Rect screenRect = new Rect(0, getStatusBarHeight(ctx), dimsBody[0], dimsBody[1]);
int rotation = display.getRotation();
if (rotation == 0 || 2 == rotation) {
Log.d(TAG, "SurfaceControl.screenshot_ext_hw with rotation " + rotation);
bitmap = SurfaceControl.screenshot_ext_hw(screenRect, dimsBody[0], dimsBody[1], 0, NAVIGATIONBAR_LAYER, false, converseRotation(rotation));
} else {
bitmap = rotationScreenBitmap(screenRect, rotation, dimsBody, 0, NAVIGATIONBAR_LAYER);
}
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, dimsBody[0], dimsBody[1]);
if (bitmap2 == null) {
Log.e(TAG, "screenShotBitmap error bitmap is null");
return null;
}
bitmap2.prepareToDraw();
return bitmap2;
}
private static int getStatusBarHeight(Context context) {
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return context.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
private static int converseRotation(int rotation) {
switch (rotation) {
case 1:
return 3;
case 2:
return 2;
case 3:
return 1;
default:
return 0;
}
}
private static float convertRotationToDegrees(int rotation) {
switch (rotation) {
case 1:
return 270.0f;
case 2:
return 180.0f;
case 3:
return 90.0f;
default:
return GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO;
}
}
private static Bitmap rotationScreenBitmap(Rect rect, int rotation, int[] srcDims, int minLayer, int maxLayer) {
StringBuilder sb = new StringBuilder();
sb.append("rotationScreenBitmap with rotation ");
sb.append(rotation);
sb.append(", srcDims ");
sb.append(Arrays.toString(srcDims));
sb.append(", layer ");
int i = minLayer;
sb.append(i);
sb.append(",");
int i2 = maxLayer;
sb.append(i2);
Log.d(TAG, sb.toString());
float degrees = convertRotationToDegrees(rotation);
float[] dims = {(float) srcDims[0], (float) srcDims[1]};
Matrix metrics = new Matrix();
metrics.reset();
metrics.preRotate(-degrees);
metrics.mapPoints(dims);
dims[0] = Math.abs(dims[0]);
dims[1] = Math.abs(dims[1]);
Bitmap bitmap = SurfaceControl.screenshot(rect, (int) dims[0], (int) dims[1], i, i2, false, 0);
Bitmap ss = Bitmap.createBitmap(srcDims[0], srcDims[1], Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(ss);
c.translate(((float) srcDims[0]) * 0.5f, ((float) srcDims[1]) * 0.5f);
c.rotate(degrees);
c.translate((-dims[0]) * 0.5f, (-dims[1]) * 0.5f);
c.drawBitmap(bitmap, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, null);
bitmap.recycle();
return ss;
}
private static int getLazyState(Context context) {
String str = Settings.Global.getString(context.getContentResolver(), "single_hand_mode");
if (str == null || "".equals(str)) {
return 0;
}
if (str.contains(LEFT)) {
return 1;
}
if (str.contains(RIGHT)) {
return 2;
}
return 0;
}
private static boolean isLazyMode(Context context) {
return getLazyState(context) != 0;
}
private static Rect getScreenshotRect(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService("window");
if (windowManager == null) {
return new Rect();
}
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getRealMetrics(displayMetrics);
Rect sourceCrop = null;
int state = getLazyState(context);
if (1 == state) {
sourceCrop = new Rect(0, (int) (((float) displayMetrics.heightPixels) * 0.25f), (int) (((float) displayMetrics.widthPixels) * 0.75f), displayMetrics.heightPixels);
} else if (2 == state) {
sourceCrop = new Rect((int) (((float) displayMetrics.widthPixels) * 0.25f), (int) (((float) displayMetrics.heightPixels) * 0.25f), displayMetrics.widthPixels, displayMetrics.heightPixels);
}
return sourceCrop;
}
public void playTranslateAnimation(int topDistance) {
int finalWidth;
this.mFollowStart = false;
float oldX = getX();
float oldY = getY();
float oldScaleX = getScaleX();
float oldScaleY = getScaleY();
if (this.mScreenOrientation == 0) {
finalWidth = dp2px(this.mContext, PORTRAIT_FINAL_WIDTH);
} else {
finalWidth = dp2px(this.mContext, LANDSCAPE_FINAL_WIDTH);
}
float newScale = ((float) finalWidth) / this.mWidth;
float newY = ((float) topDistance) - ((this.mHeight - (this.mHeight * newScale)) / 2.0f);
PropertyValuesHolder xProperty = PropertyValuesHolder.ofFloat("x", new float[]{oldX, 0.0f});
PropertyValuesHolder yProperty = PropertyValuesHolder.ofFloat("y", new float[]{oldY, newY});
PropertyValuesHolder xScaleProperty = PropertyValuesHolder.ofFloat("scaleX", new float[]{oldScaleX, newScale});
float f = oldX;
PropertyValuesHolder yScaleProperty = PropertyValuesHolder.ofFloat("scaleY", new float[]{oldScaleY, newScale});
ObjectAnimator transAnimator = ObjectAnimator.ofPropertyValuesHolder(this, new PropertyValuesHolder[]{xProperty, yProperty, xScaleProperty, yScaleProperty, PropertyValuesHolder.ofFloat("alpha", new float[]{1.0f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO})});
transAnimator.setInterpolator(AnimationUtils.loadInterpolator(this.mContext, 17563661));
PropertyValuesHolder propertyValuesHolder = yScaleProperty;
float f2 = oldY;
transAnimator.setDuration(TRANSLATE_ANIMATION_DURATION);
transAnimator.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
Log.d(ScaleImageView.TAG, "onAnimationEnd translate");
ScaleImageView.this.setVisibility(8);
ScaleImageView.this.setScaleX(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setScaleY(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setX(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setY(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO);
ScaleImageView.this.setAlpha(1.0f);
if (ScaleImageView.this.mAnimationListener != null) {
ScaleImageView.this.mAnimationListener.onAnimationEnd(0);
}
}
});
transAnimator.start();
}
public void playRecoverAnimation() {
this.mFollowStart = false;
float oldX = getX();
float oldY = getY();
float oldScaleX = getScaleX();
float oldScaleY = getScaleY();
ObjectAnimator recover = ObjectAnimator.ofPropertyValuesHolder(this, new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("x", new float[]{oldX, 0.0f}), PropertyValuesHolder.ofFloat("y", new float[]{oldY, 0.0f}), PropertyValuesHolder.ofFloat("scaleX", new float[]{oldScaleX, 1.0f}), PropertyValuesHolder.ofFloat("scaleY", new float[]{oldScaleY, 1.0f})});
recover.setInterpolator(AnimationUtils.loadInterpolator(this.mContext, 17563661));
recover.setDuration(RECOVER_ANIMATION_DURATION);
recover.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
Log.d(ScaleImageView.TAG, "onAnimationEnd recover");
ScaleImageView.this.setVisibility(8);
if (ScaleImageView.this.mAnimationListener != null) {
ScaleImageView.this.mAnimationListener.onAnimationEnd(1);
}
}
});
recover.start();
}
public void playGestureToLauncherIconAnimation(boolean isIconView) {
}
private float[] calculateScalePivot(float px, float py, float fromWidth, float fromHeight, float toWidth, float toHeight, int[] fromLocInWindow) {
float scaleX = toWidth / fromWidth;
float scaleY = toHeight / fromHeight;
return new float[]{((px - (toWidth / 2.0f)) - (((float) fromLocInWindow[0]) * scaleX)) / (1.0f - scaleX), ((py - (toHeight / 2.0f)) - (((float) fromLocInWindow[1]) * scaleY)) / (1.0f - scaleY)};
}
private Animation createGestureToLauncherIconAnimation(float targetPx, float targetPy, int iconWidth, int iconHeight, float fromAlpha, float toAlpha) {
TimeInterpolator[] sizeXInterpolators;
TimeInterpolator[] sizeYInterpolators;
PhaseInterpolator contentAnimSet = new AnimationSet(false);
long duration = SystemProperties.getLong("to_launcher_dur", 350);
AlphaAnimation contentAlphaAnim = new AlphaAnimation(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f);
contentAlphaAnim.setDuration(duration);
float[] alphaInValues = {GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.16f, 0.32f, 1.0f};
float[] contentAlphaOutValues = {fromAlpha, fromAlpha, toAlpha, toAlpha};
PhaseInterpolator contentAlphaInterpolator = new PhaseInterpolator(alphaInValues, contentAlphaOutValues, this.mAlphaInterpolators);
contentAlphaAnim.setInterpolator(contentAlphaInterpolator);
WindowManager wm = (WindowManager) this.mContext.getSystemService("window");
int windowWidth = wm.getDefaultDisplay().getWidth();
int windowHeight = wm.getDefaultDisplay().getHeight();
int viewHeight = (int) (((float) getMeasuredHeight()) * getScaleY());
int viewWidth = (int) (((float) getMeasuredWidth()) * getScaleX());
int[] viewLocInWindow = new int[2];
getLocationInWindow(viewLocInWindow);
int windowWidth2 = windowWidth;
StringBuilder sb = new StringBuilder();
WindowManager windowManager = wm;
sb.append("[viewWidth, viewHeight, viewLocX, viewLocY] = [");
sb.append(viewWidth);
sb.append(", ");
sb.append(viewHeight);
sb.append(", ");
PhaseInterpolator phaseInterpolator = contentAlphaInterpolator;
sb.append(viewLocInWindow[0]);
sb.append(", ");
sb.append(viewLocInWindow[1]);
sb.append("]");
Log.d(TAG, sb.toString());
float fromWidth = (float) viewWidth;
float fromHeight = (float) viewHeight;
float toWidth = (float) iconWidth;
PhaseInterpolator contentAnimSet2 = contentAnimSet;
float toHeight = (float) iconHeight;
float scaleToX = toWidth / fromWidth;
float scaleToY = toHeight / fromHeight;
boolean isHorizontal = viewWidth > viewHeight;
float middleYRatio = 0.44f;
float middleXRatio = isHorizontal ? 0.54f : 0.44f;
if (!isHorizontal) {
middleYRatio = 0.54f;
}
float middleY = 1.0f - (((fromHeight - toHeight) * middleYRatio) / fromHeight);
int windowWidth3 = windowWidth2;
float[] fArr = contentAlphaOutValues;
int windowHeight2 = windowHeight;
int viewHeight2 = viewHeight;
float f = fromWidth;
float[] fArr2 = alphaInValues;
float[] pivot = calculateScalePivot(targetPx, targetPy, fromWidth, fromHeight, toWidth, toHeight, viewLocInWindow);
float pivotX = pivot[0];
float pivotY = pivot[1];
float[] scaleInValues = {GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 0.16f, 1.0f};
float[] scaleOutValuesX = {1.0f, 1.0f - (((fromWidth - toWidth) * middleXRatio) / fromWidth), scaleToX};
float[] scaleOutValuesY = {1.0f, middleY, scaleToY};
if (isHorizontal) {
sizeXInterpolators = this.mSizeBigInterpolators;
} else {
sizeXInterpolators = this.mSizeSmallInterpolators;
}
if (isHorizontal) {
sizeYInterpolators = this.mSizeSmallInterpolators;
} else {
sizeYInterpolators = this.mSizeBigInterpolators;
}
PhaseInterpolator interpolatorX = new PhaseInterpolator(scaleInValues, scaleOutValuesX, sizeXInterpolators);
float[] fArr3 = pivot;
PhaseInterpolator interpolatorY = new PhaseInterpolator(scaleInValues, scaleOutValuesY, sizeYInterpolators);
float f2 = pivotX;
float f3 = pivotY;
ScaleAnimation contentScaleAnimX = new ScaleAnimation(GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f, 1.0f, 1.0f, f2, f3);
float[] fArr4 = scaleOutValuesY;
ScaleAnimation contentScaleAnimX2 = contentScaleAnimX;
contentScaleAnimX2.setDuration(duration);
contentScaleAnimX2.setInterpolator(interpolatorX);
ScaleAnimation contentScaleAnimY = new ScaleAnimation(1.0f, 1.0f, GestureNavConst.BOTTOM_WINDOW_SINGLE_HAND_RATIO, 1.0f, f2, f3);
float f4 = pivotX;
ScaleAnimation contentScaleAnimY2 = contentScaleAnimY;
contentScaleAnimY2.setDuration(duration);
contentScaleAnimY2.setInterpolator(interpolatorY);
PhaseInterpolator phaseInterpolator2 = interpolatorY;
PhaseInterpolator interpolatorY2 = contentAnimSet2;
interpolatorY2.addAnimation(contentAlphaAnim);
interpolatorY2.addAnimation(contentScaleAnimX2);
interpolatorY2.addAnimation(contentScaleAnimY2);
ScaleAnimation scaleAnimation = contentScaleAnimX2;
ScaleAnimation scaleAnimation2 = contentScaleAnimY2;
float f5 = pivotY;
int windowWidth4 = windowWidth3;
interpolatorY2.initialize(viewWidth, viewHeight2, windowWidth4, windowHeight2);
int i = windowWidth4;
interpolatorY2.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
ScaleImageView.this.setVisibility(8);
}
public void onAnimationRepeat(Animation animation) {
}
});
return interpolatorY2;
}
public void setAnimationListener(TranslateAnimationListener listener) {
this.mAnimationListener = listener;
}
}
| 26,748 | 0.64831 | 0.632907 | 596 | 43.879196 | 36.874794 | 365 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.07047 | false | false | 8 |
6be658e1f2220899c5a30a01f2f8da6833468d8b | 16,535,624,133,646 | d905e45cd9bd581c692068336ecaf38b99914bd7 | /app/markets/MarketPeopleRole.java | 91bb59b1801ef2cd204dc51014643294f64642d1 | [] | no_license | teraluis/MSRM | https://github.com/teraluis/MSRM | 5add6c34d4027f334cba20b272bbf9e609adcd28 | f78964fc0dcfaa2c0da94c2302699225d59b448c | refs/heads/master | 2023-03-21T11:22:47.339000 | 2021-03-11T15:02:56 | 2021-03-11T15:02:56 | 346,739,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package markets;
public enum MarketPeopleRole {
KEY("Contact principal"),
ACCOUNTING("Contact comptable"),
BILLING("Contact facturation"),
PURCHASER("Donneur d'ordre / Apporteur d'affaire"),
REPORT("Contact envoi de rapport");
private final String value;
MarketPeopleRole(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
| UTF-8 | Java | 429 | java | MarketPeopleRole.java | Java | [] | null | [] | package markets;
public enum MarketPeopleRole {
KEY("Contact principal"),
ACCOUNTING("Contact comptable"),
BILLING("Contact facturation"),
PURCHASER("Donneur d'ordre / Apporteur d'affaire"),
REPORT("Contact envoi de rapport");
private final String value;
MarketPeopleRole(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
| 429 | 0.65035 | 0.65035 | 20 | 20.450001 | 16.197145 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 8 |
cf7dc2badf8dfd758e7940db602e3ec8b1049615 | 2,190,433,348,742 | 6cd756bf890b53b748d41d14d6c460349a898c99 | /designer_base/src/com/fr/design/data/datapane/RefreshLabel.java | a02b4d6a6881fdbb033c67dd7474f8e8b0d59683 | [] | no_license | jiangzhenjian/FineReport | https://github.com/jiangzhenjian/FineReport | 4208b347f3b7fe839fec97cc0cb67bd33d761ba8 | ca34e419b4f117684ecbfafdd6a1178cc94ce5c6 | refs/heads/master | 2021-01-07T20:53:20.460000 | 2017-01-22T03:25:11 | 2017-01-22T03:25:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fr.design.data.datapane;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.fr.base.BaseUtils;
import com.fr.design.gui.ibutton.UIButton;
import com.fr.general.Inter;
public class RefreshLabel extends UIButton {
private Refreshable refreshable;
public RefreshLabel(Refreshable refreshable) {
super(BaseUtils.readIcon("/com/fr/design/images/control/refresh.png"));
this.refreshable = refreshable;
this.setToolTipText(Inter.getLocText("Refresh_Database"));
this.setCursor(new Cursor(Cursor.HAND_CURSOR));
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RefreshLabel.this.refreshable.refresh();
}
});
this.setPreferredSize(new Dimension(24, 20));
}
public static interface Refreshable {
public void refresh();
}
} | UTF-8 | Java | 911 | java | RefreshLabel.java | Java | [] | null | [] | package com.fr.design.data.datapane;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.fr.base.BaseUtils;
import com.fr.design.gui.ibutton.UIButton;
import com.fr.general.Inter;
public class RefreshLabel extends UIButton {
private Refreshable refreshable;
public RefreshLabel(Refreshable refreshable) {
super(BaseUtils.readIcon("/com/fr/design/images/control/refresh.png"));
this.refreshable = refreshable;
this.setToolTipText(Inter.getLocText("Refresh_Database"));
this.setCursor(new Cursor(Cursor.HAND_CURSOR));
this.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RefreshLabel.this.refreshable.refresh();
}
});
this.setPreferredSize(new Dimension(24, 20));
}
public static interface Refreshable {
public void refresh();
}
} | 911 | 0.758507 | 0.754116 | 37 | 23.648649 | 20.905472 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.621622 | false | false | 8 |
9fafc3be7c036f0fe4f55ef22ef4655e7c77b32f | 31,104,153,174,849 | 973bfd658a482489e721042eed12a3e9dd747c36 | /InterpreterWithLL/src/stackMachine/StackMachine.java | ad126061dc161e9861803772b2c000879990cecc | [] | no_license | JesusWasHomeless/UselessInterpriter | https://github.com/JesusWasHomeless/UselessInterpriter | 74199d29b719d2e4827645be4734e484309e2a79 | 62f37f90449535b7d3de2f0ece51f5691a4d5356 | refs/heads/master | 2020-05-17T16:47:29.184000 | 2019-05-24T20:02:51 | 2019-05-24T20:02:51 | 179,815,797 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stackMachine;
import KustarniyLinkedList.KLL;
import KHS.KustarniyHashSet;
import lexer.Token;
import java.util.*;
import lexer.LexGrammar;
public class StackMachine{
private int pos=0;
private ArrayList<Data> data = new ArrayList<>();
private ArrayList<String> poliz = new ArrayList<>();
private ArrayList<KLL> list = new ArrayList<>();
ArrayList<KustarniyHashSet> hash = new ArrayList<>();
public void initialization( LinkedList<Token> tokens) //Инициализация переменных
{
int i;
if (tokens.get(0).type.equals(LexGrammar.VAR)) {
if (!containment(tokens.get(0).value)) {
Data variable = new Data(tokens.get(0).value, 0);
data.add(variable);
}
}//если containment выдал false, то добавляем в таблицу переменных новую, по умолчанию равную 0
for (i = 1; i < tokens.size(); i++)
if (tokens.get(i).getLex() == LexGrammar.VAR) {//Если токен типа VAR, т.е. переменная
if (!containment(tokens.get(i).value))
if (!tokens.get(i-2).value.equals("LIST")&
!tokens.get(i-2).value.equals("ADD")&
!tokens.get(i-2).value.equals("REMOVE")&
!tokens.get(i-2).value.equals("SIZE")&
!tokens.get(i-2).value.equals("ELEMENT")&
!tokens.get(i-2).value.equals("SUPERREMOVE")&
!tokens.get(i-2).value.equals("HASHSET")&
!tokens.get(i-2).value.equals("HASHADD")&
!tokens.get(i-2).value.equals("HASHREMOVE")&
!tokens.get(i-2).value.equals("HASHCONTAINS")&
!tokens.get(i-2).value.equals("HASHSIZE")){
Data variable = new Data(tokens.get(i).value, 0);
data.add(variable);//Добавляем в лист со значением 0 как начальная инициализация
}
}
System.out.println("INITIALIZE");
for (Data aData : data) System.out.println(aData.name + " = " + aData.value);//вывод переменных, задействованных в программе
System.out.println("END OF INITIALIZE");
System.out.println("\n");
}
private boolean containment(String dataName) {//Если на входе имеется переменная, уже записанная в таблице переменных, то тру, иначе ложь
for (Data aData : data) {
if (aData.name.equals(dataName)) {
return (true);
}
}
return (false);
}
public void interpreter( LinkedList<Token> poliz1) { // Интерпретатор
for (Token aPoliz1 : poliz1) { //Добавление в лист интерпретатора элементов из полиза
this.poliz.add(aPoliz1.value);
}
CheckAndInterpretation();//Вызов метода, проверяющего, что обычное выражение, а что цикл, а затем выполняющего работу интерпретации кода, вызывая методы для выражения и для циклов.
System.out.println("\n");
System.out.println("RESULT");
for (Data aData : data) System.out.println(aData.name + " = " + aData.value); // вывод результата после интерпретации
System.out.println("END OF RESULT");
}
private void CheckAndInterpretation() {
while (pos < poliz.size()-1) {
char[] chars = poliz.get(pos).toCharArray();
// if (pos!=poliz.size()&pos+1<poliz.size()-1)
// pos++;
//else if (poliz.get(pos + 1).equals("ADD"))
// interpAdd();
// else if (poliz.get(pos + 1).equals("REMOVE"))
// interpRemove();
// else if ((poliz.get(pos + 1).equals("SIZE")))
// interpSize();
// else if (poliz.get(pos + 1).equals("ELEMEMT"))
// interpElement();
if (Character.isDigit(chars[0])&poliz.get(pos+1).equals("!"))
return; // если конец цикла и мы встречаем ссылку с безусловным переходом "!"
else if (poliz.get(pos + 1).equals("LIST"))
interpList();
else if (poliz.get(pos + 1).equals("SIZE"))
interpSize();
else if (poliz.get(pos + 1).equals("REMOVE"))
interpRemove();
else if (poliz.get(pos + 1).equals("HASHSET"))
interpHash();
else if (poliz.get(pos + 1).equals("HASHSIZE"))
interpHashSize();
else if (poliz.get(pos + 2).equals("HASHREMOVE"))
interpHashRemove();
else if (poliz.get(pos + 2).equals("ADD"))
interpAdd();
else if (poliz.get(pos + 2).equals("ELEMENT"))
interpElement();
else if (poliz.get(pos + 2).equals("SUPERREMOVE"))
interpSuperRemove();
else if (poliz.get(pos + 2).equals("HASHADD"))
interpHashAdd();
else if (poliz.get(pos + 2).equals("HASHCONTAINS"))
interpHashContain();
else if (Character.isLetter(chars[0])&(poliz.size()>pos+1)&(poliz.get(pos+2).equals(">")|
poliz.get(pos+2).equals("<") |
poliz.get(pos+2).equals("==")|
poliz.get(pos+2).equals(">=")|
poliz.get(pos+2).equals("<=")|
poliz.get(pos+2).equals("<>")))//Если натыкаемся на цикл, а именно на булевское выражение, присущее циклу
Cycle();
else if (Character.isLetter(chars[0]))
UsualStmt(); // если обычное выражение
else return; // иначе идите нафиг, улепётываем из этого метода
}
}
public boolean existHash (String name)
{
for(int t=0;t<hash.size();t++)
if (hash.get(t).name.equals(name))
return true;
return false;
}
public void interpHashSize(){
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
System.out.println("Size of hash " + hash.get(s).name + " is " + hash.get(s).size());
// System.out.println(a.getElement(0));
}
else System.out.println("This HashSet named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
public void interpHash ()
{
if (!existHash(poliz.get(pos)))
{
KustarniyHashSet a = new KustarniyHashSet(poliz.get(pos));
a.name = poliz.get(pos);
hash.add(a);
System.out.println("You have created new HashSet named " + a.name);
}
else System.out.println("This HashSet " + poliz.get(pos)+ " is already exists");
pos+=2;
}
public void interpHashAdd ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
hash.get(s).AddHash(Integer.parseInt(poliz.get(pos + 1)));
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos+1)))
hash.get(s).AddHash(data.get(h).value);
}
else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
public void interpHashRemove ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos))) {
for (int s = 0; s < hash.size(); s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
hash.get(s).Hashremove(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("The element " + Integer.parseInt(poliz.get(pos + 1)) + " has been removed from HashSet " + hash.get(s).name);
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++) {
if (data.get(h).name.equals(poliz.get(pos + 1)))
hash.get(s).Hashremove(data.get(h).value);
System.out.println("The element " + data.get(h).name + " = " + data.get(h).value + " has been removed from HashSet " + hash.get(s).name);
}
}
else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
public void interpHashContain ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
System.out.println("This Element says that existing of "+poliz.get(pos + 1)+" in set is "+ hash.get(s).contains(Integer.parseInt(poliz.get(pos + 1))));
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1)))
System.out.println("This element says that existing of "+data.get(h).name+ " = " + data.get(h).value + " in set is "+ hash.get(h).contains(data.get(h).value));
} else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
private boolean existingList(String a)//Чек на существование ранее объявленного листа
{
for (KLL aList : list)
if (aList.name.equals(a))
return true;
return false;
}
private void interpList() {//Создание листа
if (!existingList(poliz.get(pos)))
{
KLL a = new KLL();
a.name = poliz.get(pos);
list.add(a);
System.out.println("You have created new LinkedList named " + a.name);
}
else System.out.println("This list named " + poliz.get(pos) + " is already exists!");
pos+=2;
}
private void interpAdd()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {
list.get(s).add(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("New element " + Integer.parseInt(poliz.get(pos + 1)) + " has been added in list " + poliz.get(pos) + "!");
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1))) {
list.get(s).add(data.get(h).value);
System.out.println("New element " + data.get(s).name + " which equals " + data.get(h).value + " has been added in list " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void interpSuperRemove()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {
list.get(s).removeElement(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("The element " + Integer.parseInt(poliz.get(pos + 1)) + " has been deleted from list " + poliz.get(pos) + "!");
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1))) {
list.get(s).removeElement(data.get(h).value);
System.out.println("The element " + data.get(s).name + " which equals " + data.get(h).value + " has been deleted from list " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void interpRemove() {
if (existingList(poliz.get(pos))) {
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name)) {
list.get(s).remove();
System.out.println("You have removed last node from your Linked List " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
private void interpSize() {
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
System.out.println("Size of list " + list.get(s).name + " is " + list.get(s).getSize());
// System.out.println(a.getElement(0));
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
private void interpElement()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {//если число на вход
if(list.get(s).check(Integer.parseInt(poliz.get(pos + 1)))){
System.out.println("List " + list.get(s).name + " contains Element " + list.get(s).getElement(Integer.parseInt(poliz.get(pos + 1))) + " on position " + Character.valueOf(chars[0]));}
else System.out.println("There's no any element on position " + Integer.parseInt(poliz.get(pos+1))+ " in list " + list.get(s).name);
}
else if (Character.isLetter(chars[0]))//если переменная, содержашая число
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1)))
if(list.get(s).check(Integer.parseInt(poliz.get(pos + 1)))){
System.out.println("List " + list.get(h).name + " contains Element " + list.get(h).getElement(data.get(h).value)+ " on position " + Character.valueOf(chars[0]));}
else System.out.println("There's no any element on position " + Integer.parseInt(poliz.get(pos+1))+ " in list " + list.get(s).name);
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void UsualStmt()
{
Stack<String> stack = new Stack<>();
// переменные с которыми будут происходить вычисления
int a;
int b;
stack.push(poliz.get(pos)); // самая первая переменная, которая будет присваивать значение выражения
pos++;//идём дальше по листу
while (!poliz.get(pos).equals("=")) // пока не равно, выполняем
{
char[] chars = poliz.get(pos).toCharArray(); // та же песня, что и в методе выше
// if(poliz.get(inter).equals())
if (Character.isLetter(chars[0])) { // если это переменная а не число, то ищем её значение в памяти (из метода инициализация) и заносим в стек
for (Data aData : data)
if (aData.name.equals(poliz.get(pos)))//чекаем в таблице переменных
stack.push(Integer.toString(aData.value));
pos++;
} else if (Character.isDigit(chars[0])) { // иначе, если это просто число, то заносим в стек
stack.push(poliz.get(pos));
pos++;
// иначе если это знак операции, то
} else if (poliz.get(pos).equals("+")|
poliz.get(pos).equals("-")|
poliz.get(pos).equals("/")|
poliz.get(pos).equals("*"))
{
b = Integer.parseInt(stack.pop()); // из стека вытаскиваем 2 переменные предыдущие и выполняем соответствующую операцию и заносим обратно в стек
a = Integer.parseInt(stack.pop());
switch (poliz.get(pos)) {
case "+":
stack.push(Integer.toString(a + b));
break;
case "-":
stack.push(Integer.toString(a - b));
break;
case "*":
stack.push(Integer.toString(a * b));
break;
case "/":
stack.push(Integer.toString(a / b));
break;
}
pos++;
}
} if (poliz.get(pos).equals("=")) // теперь если всё же равно
{
b = Integer.parseInt(stack.pop()); // берём значение получившегося выражения из стека
String word =stack.pop(); // также имя внесённой переменной в стек в самом начале
for (Data aData : data)
if (aData.name.equals(word))// ищем переменную в нашей памяти
{
aData.value = b; // и присваеваем значение выражения переменной
}
if (poliz.size()-1>pos) pos++;
}
}
private void Cycle()
{
int m = 0;
int n = 0;
for (Data aData : data)
if (aData.name.equals(poliz.get(pos))) {
m = aData.value;
} else if (aData.name.equals(poliz.get(pos + 1)))
n = aData.value;
char[] chars1 = poliz.get(pos).toCharArray();
if (Character.isDigit(chars1[0]))
m = Integer.parseInt(poliz.get(pos));
char[] chars2 = poliz.get(pos+1).toCharArray();
if (Character.isDigit(chars2[0]))
n = Integer.parseInt(poliz.get(pos+1));
pos+=2;
// и понеслась. переход происходит по лжи, поэтому если больше не выполняется, то присваеваем ссылку нашему pos
switch (poliz.get(pos)) {
case ">":
if (m <= n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<":
if (m >= n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "==":
if (m != n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<>":
if (m == n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<=":
if (m > n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case ">=":
if (m < n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
}
pos++;
if (!poliz.get(pos).equals("!F")) // чек ошибки перехода по лжи
System.out.println("Error in cycle!");
pos++;
//пока не дошли до конца и пока не равно БП, то выполняем метод CheckAndInterpretation
while ((poliz.size()-1>pos))
if (!poliz.get(pos+1).equals("!"))
CheckAndInterpretation();
else break;
if (poliz.size()-1>pos)
pos = Integer.parseInt(poliz.get(pos)); // присвоение ссылки перед безусловным переходом то есть перед !
}
} | WINDOWS-1251 | Java | 22,379 | java | StackMachine.java | Java | [] | null | [] | package stackMachine;
import KustarniyLinkedList.KLL;
import KHS.KustarniyHashSet;
import lexer.Token;
import java.util.*;
import lexer.LexGrammar;
public class StackMachine{
private int pos=0;
private ArrayList<Data> data = new ArrayList<>();
private ArrayList<String> poliz = new ArrayList<>();
private ArrayList<KLL> list = new ArrayList<>();
ArrayList<KustarniyHashSet> hash = new ArrayList<>();
public void initialization( LinkedList<Token> tokens) //Инициализация переменных
{
int i;
if (tokens.get(0).type.equals(LexGrammar.VAR)) {
if (!containment(tokens.get(0).value)) {
Data variable = new Data(tokens.get(0).value, 0);
data.add(variable);
}
}//если containment выдал false, то добавляем в таблицу переменных новую, по умолчанию равную 0
for (i = 1; i < tokens.size(); i++)
if (tokens.get(i).getLex() == LexGrammar.VAR) {//Если токен типа VAR, т.е. переменная
if (!containment(tokens.get(i).value))
if (!tokens.get(i-2).value.equals("LIST")&
!tokens.get(i-2).value.equals("ADD")&
!tokens.get(i-2).value.equals("REMOVE")&
!tokens.get(i-2).value.equals("SIZE")&
!tokens.get(i-2).value.equals("ELEMENT")&
!tokens.get(i-2).value.equals("SUPERREMOVE")&
!tokens.get(i-2).value.equals("HASHSET")&
!tokens.get(i-2).value.equals("HASHADD")&
!tokens.get(i-2).value.equals("HASHREMOVE")&
!tokens.get(i-2).value.equals("HASHCONTAINS")&
!tokens.get(i-2).value.equals("HASHSIZE")){
Data variable = new Data(tokens.get(i).value, 0);
data.add(variable);//Добавляем в лист со значением 0 как начальная инициализация
}
}
System.out.println("INITIALIZE");
for (Data aData : data) System.out.println(aData.name + " = " + aData.value);//вывод переменных, задействованных в программе
System.out.println("END OF INITIALIZE");
System.out.println("\n");
}
private boolean containment(String dataName) {//Если на входе имеется переменная, уже записанная в таблице переменных, то тру, иначе ложь
for (Data aData : data) {
if (aData.name.equals(dataName)) {
return (true);
}
}
return (false);
}
public void interpreter( LinkedList<Token> poliz1) { // Интерпретатор
for (Token aPoliz1 : poliz1) { //Добавление в лист интерпретатора элементов из полиза
this.poliz.add(aPoliz1.value);
}
CheckAndInterpretation();//Вызов метода, проверяющего, что обычное выражение, а что цикл, а затем выполняющего работу интерпретации кода, вызывая методы для выражения и для циклов.
System.out.println("\n");
System.out.println("RESULT");
for (Data aData : data) System.out.println(aData.name + " = " + aData.value); // вывод результата после интерпретации
System.out.println("END OF RESULT");
}
private void CheckAndInterpretation() {
while (pos < poliz.size()-1) {
char[] chars = poliz.get(pos).toCharArray();
// if (pos!=poliz.size()&pos+1<poliz.size()-1)
// pos++;
//else if (poliz.get(pos + 1).equals("ADD"))
// interpAdd();
// else if (poliz.get(pos + 1).equals("REMOVE"))
// interpRemove();
// else if ((poliz.get(pos + 1).equals("SIZE")))
// interpSize();
// else if (poliz.get(pos + 1).equals("ELEMEMT"))
// interpElement();
if (Character.isDigit(chars[0])&poliz.get(pos+1).equals("!"))
return; // если конец цикла и мы встречаем ссылку с безусловным переходом "!"
else if (poliz.get(pos + 1).equals("LIST"))
interpList();
else if (poliz.get(pos + 1).equals("SIZE"))
interpSize();
else if (poliz.get(pos + 1).equals("REMOVE"))
interpRemove();
else if (poliz.get(pos + 1).equals("HASHSET"))
interpHash();
else if (poliz.get(pos + 1).equals("HASHSIZE"))
interpHashSize();
else if (poliz.get(pos + 2).equals("HASHREMOVE"))
interpHashRemove();
else if (poliz.get(pos + 2).equals("ADD"))
interpAdd();
else if (poliz.get(pos + 2).equals("ELEMENT"))
interpElement();
else if (poliz.get(pos + 2).equals("SUPERREMOVE"))
interpSuperRemove();
else if (poliz.get(pos + 2).equals("HASHADD"))
interpHashAdd();
else if (poliz.get(pos + 2).equals("HASHCONTAINS"))
interpHashContain();
else if (Character.isLetter(chars[0])&(poliz.size()>pos+1)&(poliz.get(pos+2).equals(">")|
poliz.get(pos+2).equals("<") |
poliz.get(pos+2).equals("==")|
poliz.get(pos+2).equals(">=")|
poliz.get(pos+2).equals("<=")|
poliz.get(pos+2).equals("<>")))//Если натыкаемся на цикл, а именно на булевское выражение, присущее циклу
Cycle();
else if (Character.isLetter(chars[0]))
UsualStmt(); // если обычное выражение
else return; // иначе идите нафиг, улепётываем из этого метода
}
}
public boolean existHash (String name)
{
for(int t=0;t<hash.size();t++)
if (hash.get(t).name.equals(name))
return true;
return false;
}
public void interpHashSize(){
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
System.out.println("Size of hash " + hash.get(s).name + " is " + hash.get(s).size());
// System.out.println(a.getElement(0));
}
else System.out.println("This HashSet named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
public void interpHash ()
{
if (!existHash(poliz.get(pos)))
{
KustarniyHashSet a = new KustarniyHashSet(poliz.get(pos));
a.name = poliz.get(pos);
hash.add(a);
System.out.println("You have created new HashSet named " + a.name);
}
else System.out.println("This HashSet " + poliz.get(pos)+ " is already exists");
pos+=2;
}
public void interpHashAdd ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
hash.get(s).AddHash(Integer.parseInt(poliz.get(pos + 1)));
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos+1)))
hash.get(s).AddHash(data.get(h).value);
}
else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
public void interpHashRemove ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos))) {
for (int s = 0; s < hash.size(); s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
hash.get(s).Hashremove(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("The element " + Integer.parseInt(poliz.get(pos + 1)) + " has been removed from HashSet " + hash.get(s).name);
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++) {
if (data.get(h).name.equals(poliz.get(pos + 1)))
hash.get(s).Hashremove(data.get(h).value);
System.out.println("The element " + data.get(h).name + " = " + data.get(h).value + " has been removed from HashSet " + hash.get(s).name);
}
}
else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
public void interpHashContain ()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existHash(poliz.get(pos)))
{
for (int s=0;s<hash.size();s++)
if (poliz.get(pos).equals(hash.get(s).name))
if (Character.isDigit(chars[0])) {
System.out.println("This Element says that existing of "+poliz.get(pos + 1)+" in set is "+ hash.get(s).contains(Integer.parseInt(poliz.get(pos + 1))));
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1)))
System.out.println("This element says that existing of "+data.get(h).name+ " = " + data.get(h).value + " in set is "+ hash.get(h).contains(data.get(h).value));
} else System.out.println("This HashSet " + poliz.get(pos)+ " isn't exist");
pos+=3;
}
private boolean existingList(String a)//Чек на существование ранее объявленного листа
{
for (KLL aList : list)
if (aList.name.equals(a))
return true;
return false;
}
private void interpList() {//Создание листа
if (!existingList(poliz.get(pos)))
{
KLL a = new KLL();
a.name = poliz.get(pos);
list.add(a);
System.out.println("You have created new LinkedList named " + a.name);
}
else System.out.println("This list named " + poliz.get(pos) + " is already exists!");
pos+=2;
}
private void interpAdd()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {
list.get(s).add(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("New element " + Integer.parseInt(poliz.get(pos + 1)) + " has been added in list " + poliz.get(pos) + "!");
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1))) {
list.get(s).add(data.get(h).value);
System.out.println("New element " + data.get(s).name + " which equals " + data.get(h).value + " has been added in list " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void interpSuperRemove()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {
list.get(s).removeElement(Integer.parseInt(poliz.get(pos + 1)));
System.out.println("The element " + Integer.parseInt(poliz.get(pos + 1)) + " has been deleted from list " + poliz.get(pos) + "!");
} else if (Character.isLetter(chars[0]))
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1))) {
list.get(s).removeElement(data.get(h).value);
System.out.println("The element " + data.get(s).name + " which equals " + data.get(h).value + " has been deleted from list " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void interpRemove() {
if (existingList(poliz.get(pos))) {
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name)) {
list.get(s).remove();
System.out.println("You have removed last node from your Linked List " + poliz.get(pos) + "!");
}
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
private void interpSize() {
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
System.out.println("Size of list " + list.get(s).name + " is " + list.get(s).getSize());
// System.out.println(a.getElement(0));
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=2;
}
private void interpElement()
{
char[] chars = poliz.get(pos+1).toCharArray();
if (existingList(poliz.get(pos)))
{
for (int s=0;s<list.size();s++)
if (poliz.get(pos).equals(list.get(s).name))
if (Character.isDigit(chars[0])) {//если число на вход
if(list.get(s).check(Integer.parseInt(poliz.get(pos + 1)))){
System.out.println("List " + list.get(s).name + " contains Element " + list.get(s).getElement(Integer.parseInt(poliz.get(pos + 1))) + " on position " + Character.valueOf(chars[0]));}
else System.out.println("There's no any element on position " + Integer.parseInt(poliz.get(pos+1))+ " in list " + list.get(s).name);
}
else if (Character.isLetter(chars[0]))//если переменная, содержашая число
for (int h = 0; h < data.size(); h++)
if (data.get(h).name.equals(poliz.get(pos + 1)))
if(list.get(s).check(Integer.parseInt(poliz.get(pos + 1)))){
System.out.println("List " + list.get(h).name + " contains Element " + list.get(h).getElement(data.get(h).value)+ " on position " + Character.valueOf(chars[0]));}
else System.out.println("There's no any element on position " + Integer.parseInt(poliz.get(pos+1))+ " in list " + list.get(s).name);
}
else System.out.println("This list named " + poliz.get(pos) + " doesn't exist");
pos+=3;
}
private void UsualStmt()
{
Stack<String> stack = new Stack<>();
// переменные с которыми будут происходить вычисления
int a;
int b;
stack.push(poliz.get(pos)); // самая первая переменная, которая будет присваивать значение выражения
pos++;//идём дальше по листу
while (!poliz.get(pos).equals("=")) // пока не равно, выполняем
{
char[] chars = poliz.get(pos).toCharArray(); // та же песня, что и в методе выше
// if(poliz.get(inter).equals())
if (Character.isLetter(chars[0])) { // если это переменная а не число, то ищем её значение в памяти (из метода инициализация) и заносим в стек
for (Data aData : data)
if (aData.name.equals(poliz.get(pos)))//чекаем в таблице переменных
stack.push(Integer.toString(aData.value));
pos++;
} else if (Character.isDigit(chars[0])) { // иначе, если это просто число, то заносим в стек
stack.push(poliz.get(pos));
pos++;
// иначе если это знак операции, то
} else if (poliz.get(pos).equals("+")|
poliz.get(pos).equals("-")|
poliz.get(pos).equals("/")|
poliz.get(pos).equals("*"))
{
b = Integer.parseInt(stack.pop()); // из стека вытаскиваем 2 переменные предыдущие и выполняем соответствующую операцию и заносим обратно в стек
a = Integer.parseInt(stack.pop());
switch (poliz.get(pos)) {
case "+":
stack.push(Integer.toString(a + b));
break;
case "-":
stack.push(Integer.toString(a - b));
break;
case "*":
stack.push(Integer.toString(a * b));
break;
case "/":
stack.push(Integer.toString(a / b));
break;
}
pos++;
}
} if (poliz.get(pos).equals("=")) // теперь если всё же равно
{
b = Integer.parseInt(stack.pop()); // берём значение получившегося выражения из стека
String word =stack.pop(); // также имя внесённой переменной в стек в самом начале
for (Data aData : data)
if (aData.name.equals(word))// ищем переменную в нашей памяти
{
aData.value = b; // и присваеваем значение выражения переменной
}
if (poliz.size()-1>pos) pos++;
}
}
private void Cycle()
{
int m = 0;
int n = 0;
for (Data aData : data)
if (aData.name.equals(poliz.get(pos))) {
m = aData.value;
} else if (aData.name.equals(poliz.get(pos + 1)))
n = aData.value;
char[] chars1 = poliz.get(pos).toCharArray();
if (Character.isDigit(chars1[0]))
m = Integer.parseInt(poliz.get(pos));
char[] chars2 = poliz.get(pos+1).toCharArray();
if (Character.isDigit(chars2[0]))
n = Integer.parseInt(poliz.get(pos+1));
pos+=2;
// и понеслась. переход происходит по лжи, поэтому если больше не выполняется, то присваеваем ссылку нашему pos
switch (poliz.get(pos)) {
case ">":
if (m <= n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<":
if (m >= n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "==":
if (m != n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<>":
if (m == n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case "<=":
if (m > n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
case ">=":
if (m < n) {
pos = Integer.parseInt(poliz.get(pos + 1));
return;
} else pos++;
break;
}
pos++;
if (!poliz.get(pos).equals("!F")) // чек ошибки перехода по лжи
System.out.println("Error in cycle!");
pos++;
//пока не дошли до конца и пока не равно БП, то выполняем метод CheckAndInterpretation
while ((poliz.size()-1>pos))
if (!poliz.get(pos+1).equals("!"))
CheckAndInterpretation();
else break;
if (poliz.size()-1>pos)
pos = Integer.parseInt(poliz.get(pos)); // присвоение ссылки перед безусловным переходом то есть перед !
}
} | 22,379 | 0.485971 | 0.478908 | 467 | 42.573875 | 37.208488 | 206 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533191 | false | false | 8 |
67488d2a273e6d807d9a4a26dd687a8031439951 | 33,328,946,247,962 | ba55c648584faae5842f95db43966b3668fec691 | /cachecloud-open-web/src/main/java/com/sohu/cache/alert/impl/BaseAlertService.java | f5e7c8b225fa172fc04c880058aefafa052c4f28 | [
"Apache-2.0"
] | permissive | iLove9ou/cachecloud | https://github.com/iLove9ou/cachecloud | 61a3146ee4ece3b5b193cf649e518cd22c6bcf80 | 0c93ac75c67df7e8124439ad49de6022d1485217 | refs/heads/master | 2020-03-20T23:45:54.470000 | 2018-06-21T03:35:22 | 2018-06-21T03:35:22 | 137,861,672 | 1 | 1 | Apache-2.0 | true | 2018-06-19T08:21:11 | 2018-06-19T08:21:11 | 2018-06-19T06:52:28 | 2017-09-27T09:41:38 | 18,042 | 0 | 0 | 0 | null | false | null | package com.sohu.cache.alert.impl;
import com.sohu.cache.web.component.EmailComponent;
import com.sohu.cache.web.component.MobileAlertComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 报警基类
* @author leifu
* @Date 2014年12月16日
* @Time 下午4:15:11
*/
public class BaseAlertService {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 邮箱报警
*/
protected EmailComponent emailComponent;
/**
* 手机短信报警
*/
protected MobileAlertComponent mobileAlertComponent;
public void setEmailComponent(EmailComponent emailComponent) {
this.emailComponent = emailComponent;
}
public void setMobileAlertComponent(MobileAlertComponent mobileAlertComponent) {
this.mobileAlertComponent = mobileAlertComponent;
}
}
| UTF-8 | Java | 895 | java | BaseAlertService.java | Java | [
{
"context": "g.slf4j.LoggerFactory;\r\n\r\n/**\r\n * 报警基类\r\n * @author leifu\r\n * @Date 2014年12月16日\r\n * @Time 下午4:15:11\r\n */\r\np",
"end": 241,
"score": 0.9995085000991821,
"start": 236,
"tag": "USERNAME",
"value": "leifu"
}
] | null | [] | package com.sohu.cache.alert.impl;
import com.sohu.cache.web.component.EmailComponent;
import com.sohu.cache.web.component.MobileAlertComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 报警基类
* @author leifu
* @Date 2014年12月16日
* @Time 下午4:15:11
*/
public class BaseAlertService {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 邮箱报警
*/
protected EmailComponent emailComponent;
/**
* 手机短信报警
*/
protected MobileAlertComponent mobileAlertComponent;
public void setEmailComponent(EmailComponent emailComponent) {
this.emailComponent = emailComponent;
}
public void setMobileAlertComponent(MobileAlertComponent mobileAlertComponent) {
this.mobileAlertComponent = mobileAlertComponent;
}
}
| 895 | 0.696616 | 0.679113 | 35 | 22.485714 | 24.540779 | 84 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 8 |
02de5e2b7f5805856b7168f836b7fb7a32bb9acf | 33,328,946,246,116 | 8499edb4d8636f42de73cfd9788d18504e5fee39 | /InteractionMiddleware/src/main/java/com/coll/restcontroller/ForumRestController.java | 4c26fa9fb62404c67d3fa0c6151315ab87ced87e | [] | no_license | ManaliSant/Project-2- | https://github.com/ManaliSant/Project-2- | cd6fcbee12b687b72b0f1e81ff82c8f2f56fc51e | bec48790043a29d3f728390bbb3daf4ff68aeba8 | refs/heads/master | 2020-04-01T03:45:16.748000 | 2018-12-19T11:06:46 | 2018-12-19T11:06:46 | 152,835,167 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coll.restcontroller;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.coll.dao.ForumDao;
import com.coll.models.Forum;
@RestController
public class ForumRestController {
@Autowired
ForumDao forumDao;
@GetMapping("/showAllForums")
public ResponseEntity<List<Forum>> showAllForums() {
List<Forum> listForums = forumDao.listForums();
if (listForums.size() > 0)
return new ResponseEntity<List<Forum>>(listForums, HttpStatus.OK);
else
return new ResponseEntity<List<Forum>>(listForums, HttpStatus.INTERNAL_SERVER_ERROR);
}
@PostMapping("/addForum")
public ResponseEntity<String> addForum(@RequestBody Forum forum) {
forum.setCreatedate(new Date());
forum.setUsername("Mana");
forum.setStatus("NA");
if (forumDao.addForum(forum))
return new ResponseEntity<String>("Forum Added", HttpStatus.OK);
else
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/approveForum/{forumid}")
public ResponseEntity<String> approveForum(@PathVariable("forumid") int forumid) {
Forum forum = (Forum) forumDao.getForum(forumid);
if (forumDao.approveForum(forum)) {
return new ResponseEntity<String>("Approved", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/rejectForum/{forumid}")
public ResponseEntity<String> rejectForum(@PathVariable("forumid") int forumid) {
Forum forum = (Forum) forumDao.getForum(forumid);
if (forumDao.rejectForum(forum)) {
return new ResponseEntity<String>("Reject", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| UTF-8 | Java | 2,163 | java | ForumRestController.java | Java | [
{
"context": "m.setCreatedate(new Date());\n\t\tforum.setUsername(\"Mana\");\n\t\tforum.setStatus(\"NA\");\n\n\t\tif (forumDao.addFo",
"end": 1177,
"score": 0.9996858835220337,
"start": 1173,
"tag": "USERNAME",
"value": "Mana"
}
] | null | [] | package com.coll.restcontroller;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.coll.dao.ForumDao;
import com.coll.models.Forum;
@RestController
public class ForumRestController {
@Autowired
ForumDao forumDao;
@GetMapping("/showAllForums")
public ResponseEntity<List<Forum>> showAllForums() {
List<Forum> listForums = forumDao.listForums();
if (listForums.size() > 0)
return new ResponseEntity<List<Forum>>(listForums, HttpStatus.OK);
else
return new ResponseEntity<List<Forum>>(listForums, HttpStatus.INTERNAL_SERVER_ERROR);
}
@PostMapping("/addForum")
public ResponseEntity<String> addForum(@RequestBody Forum forum) {
forum.setCreatedate(new Date());
forum.setUsername("Mana");
forum.setStatus("NA");
if (forumDao.addForum(forum))
return new ResponseEntity<String>("Forum Added", HttpStatus.OK);
else
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/approveForum/{forumid}")
public ResponseEntity<String> approveForum(@PathVariable("forumid") int forumid) {
Forum forum = (Forum) forumDao.getForum(forumid);
if (forumDao.approveForum(forum)) {
return new ResponseEntity<String>("Approved", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/rejectForum/{forumid}")
public ResponseEntity<String> rejectForum(@PathVariable("forumid") int forumid) {
Forum forum = (Forum) forumDao.getForum(forumid);
if (forumDao.rejectForum(forum)) {
return new ResponseEntity<String>("Reject", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Failure", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 2,163 | 0.766528 | 0.766066 | 70 | 29.9 | 27.780338 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.514286 | false | false | 8 |
607fcc396932f4941d8ccbf554e1ea586045119e | 29,652,454,252,349 | 68cb263b24a484ab115c07f2f01173677515b332 | /src/test/java/io/katharsis/resource/ResourceFieldNameTransformerTest.java | 1e71d5e02e756b3dbf7d71c094e9b4c5883ca815 | [
"Apache-2.0"
] | permissive | RentTheRunway/katharsis-core | https://github.com/RentTheRunway/katharsis-core | af8fd60e853303c2e77e3ba5a9641c345b60d40e | ff298c18f412d94d724b70f7a6949dca064dc704 | refs/heads/development | 2021-01-24T17:06:07.882000 | 2015-07-12T22:30:22 | 2015-07-12T22:30:22 | 39,638,626 | 1 | 0 | null | true | 2015-07-24T14:30:40 | 2015-07-24T14:30:40 | 2015-07-22T11:46:56 | 2015-07-12T22:32:13 | 977 | 0 | 0 | 0 | null | null | null | package io.katharsis.resource;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
public class ResourceFieldNameTransformerTest {
private ResourceFieldNameTransformer sut;
@Before
public void setUp() throws Exception {
sut = new ResourceFieldNameTransformer();
}
@Test
public void onFieldWithoutJsonPropertyShouldReturnBaseName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("field");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("field");
}
@Test
public void onFieldWithJsonPropertyShouldReturnCustomName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("fieldWithJsonProperty");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("customName");
}
@Test
public void onFieldWithDefaultJsonPropertyShouldReturnBaseName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("fieldWithDefaultJsonProperty");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("fieldWithDefaultJsonProperty");
}
public static class TestClass {
private String field;
@JsonProperty("customName")
private String fieldWithJsonProperty;
@JsonProperty
private String fieldWithDefaultJsonProperty;
}
}
| UTF-8 | Java | 1,651 | java | ResourceFieldNameTransformerTest.java | Java | [] | null | [] | package io.katharsis.resource;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
public class ResourceFieldNameTransformerTest {
private ResourceFieldNameTransformer sut;
@Before
public void setUp() throws Exception {
sut = new ResourceFieldNameTransformer();
}
@Test
public void onFieldWithoutJsonPropertyShouldReturnBaseName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("field");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("field");
}
@Test
public void onFieldWithJsonPropertyShouldReturnCustomName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("fieldWithJsonProperty");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("customName");
}
@Test
public void onFieldWithDefaultJsonPropertyShouldReturnBaseName() throws Exception {
// GIVEN
Field field = TestClass.class.getDeclaredField("fieldWithDefaultJsonProperty");
// WHEN
String name = sut.getName(field);
// THEN
assertThat(name).isEqualTo("fieldWithDefaultJsonProperty");
}
public static class TestClass {
private String field;
@JsonProperty("customName")
private String fieldWithJsonProperty;
@JsonProperty
private String fieldWithDefaultJsonProperty;
}
}
| 1,651 | 0.677165 | 0.677165 | 66 | 24.015152 | 25.672466 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.30303 | false | false | 8 |
185701e6cac326c400bfc18d9299b060e6862f8e | 14,697,378,148,280 | d0b0db24670c6a963bc47c47707f405fb3c6f6ad | /svn/hnkb/source/01.trunk/hnkb/portal-web/src/main/java/com/ai/aso/hnkb/user/service/impl/UserServiceImpl.java | 65ae98d220159e4a5488bd0b4207540a3c319b25 | [] | no_license | Lynwood01/asiainfoCode | https://github.com/Lynwood01/asiainfoCode | 3daebf58873dd6a9fd9b29d44bb1899fd7885132 | 93c319428afaf837a96ac79b267118dd9d757eec | refs/heads/master | 2019-03-20T22:38:46.902000 | 2018-09-02T08:09:44 | 2018-09-02T08:09:44 | 124,053,464 | 0 | 10 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ai.aso.hnkb.user.service.impl;
import com.ai.aso.hnkb.login.component.AcctRoleComp;
import com.ai.aso.hnkb.login.component.RegionComp;
import com.ai.aso.hnkb.login.db.model.AcctRole;
import com.ai.aso.hnkb.login.db.model.LoginAcct;
import com.ai.aso.hnkb.login.db.model.LoginName;
import com.ai.aso.hnkb.login.service.LoginNameService;
import com.ai.aso.hnkb.utils.StringUtil;
import com.ai.aso.hnkb.login.constants.LoginConstants;
import com.ai.aso.hnkb.login.db.dao.RegionMapper;
import com.ai.aso.hnkb.user.db.dao.UserMapper;
import com.ai.aso.hnkb.user.db.model.User;
import com.ai.aso.hnkb.user.db.model.UserExample;
import com.ai.aso.hnkb.login.exception.LoginExInfoEnum;
import com.ai.aso.hnkb.login.exception.LoginValidException;
import com.ai.aso.hnkb.login.service.LoginAcctService;
import com.ai.aso.hnkb.user.service.UserService;
import com.ai.aso.hnkb.sequence.SequenceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* Created by wuqiang6 on 2016/9/20.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private SequenceFactory sequenceFactory;
@Autowired
private RegionMapper regionMapper;
@Autowired
private LoginAcctService loginAcctService;
@Autowired
private LoginNameService loginNameService;
@Autowired
private AcctRoleComp acctRoleComp;
@Autowired
private RegionComp regionComp;
@Override
public User findUserByAcctId(String accId) {
assert StringUtil.isNotEmpty(accId);
UserExample example = new UserExample();
example.createCriteria().andAcctIdEqualTo(accId);
List<User> users = userMapper.selectByExample(example);
return users.get(0);
}
@Override
public void addUser(User user){
regionComp.checkRegion(user.getRegionId());
//4. 新增user表
User newUser = new User();
newUser.setAcctId(user.getAcctId());
newUser.setCreateDate(new Date());
newUser.setEmail(user.getEmail());
newUser.setMobile(user.getMobile());
newUser.setModiDate(new Date());
newUser.setRegionId(user.getRegionId());
newUser.setState(LoginConstants.USER_STATE_DEFAULT);
newUser.setUserId(sequenceFactory.next(LoginConstants.SEQUENCENAME_USER));
newUser.setUserName(user.getUserName());
userMapper.insertSelective(newUser);
}
@Override
public void updateUser(User user) {
regionComp.checkRegion(user.getRegionId());
//4. 新增user表
User newUser = new User();
newUser.setEmail(user.getEmail());
newUser.setMobile(user.getMobile());
newUser.setModiDate(new Date());
newUser.setUserId(user.getUserId());
newUser.setState(user.getState());
newUser.setUserName(user.getUserName());
newUser.setPhone(user.getPhone());
newUser.setRegionId(user.getRegionId());
userMapper.updateByPrimaryKeySelective(newUser);
}
}
| UTF-8 | Java | 2,974 | java | UserServiceImpl.java | Java | [
{
"context": "il.Date;\nimport java.util.List;\n\n/**\n * Created by wuqiang6 on 2016/9/20.\n */\n@Service\npublic class UserServi",
"end": 1088,
"score": 0.9996739625930786,
"start": 1080,
"tag": "USERNAME",
"value": "wuqiang6"
},
{
"context": "stants.SEQUENCENAME_USER));\n\t\tnewUs... | null | [] | package com.ai.aso.hnkb.user.service.impl;
import com.ai.aso.hnkb.login.component.AcctRoleComp;
import com.ai.aso.hnkb.login.component.RegionComp;
import com.ai.aso.hnkb.login.db.model.AcctRole;
import com.ai.aso.hnkb.login.db.model.LoginAcct;
import com.ai.aso.hnkb.login.db.model.LoginName;
import com.ai.aso.hnkb.login.service.LoginNameService;
import com.ai.aso.hnkb.utils.StringUtil;
import com.ai.aso.hnkb.login.constants.LoginConstants;
import com.ai.aso.hnkb.login.db.dao.RegionMapper;
import com.ai.aso.hnkb.user.db.dao.UserMapper;
import com.ai.aso.hnkb.user.db.model.User;
import com.ai.aso.hnkb.user.db.model.UserExample;
import com.ai.aso.hnkb.login.exception.LoginExInfoEnum;
import com.ai.aso.hnkb.login.exception.LoginValidException;
import com.ai.aso.hnkb.login.service.LoginAcctService;
import com.ai.aso.hnkb.user.service.UserService;
import com.ai.aso.hnkb.sequence.SequenceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* Created by wuqiang6 on 2016/9/20.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private SequenceFactory sequenceFactory;
@Autowired
private RegionMapper regionMapper;
@Autowired
private LoginAcctService loginAcctService;
@Autowired
private LoginNameService loginNameService;
@Autowired
private AcctRoleComp acctRoleComp;
@Autowired
private RegionComp regionComp;
@Override
public User findUserByAcctId(String accId) {
assert StringUtil.isNotEmpty(accId);
UserExample example = new UserExample();
example.createCriteria().andAcctIdEqualTo(accId);
List<User> users = userMapper.selectByExample(example);
return users.get(0);
}
@Override
public void addUser(User user){
regionComp.checkRegion(user.getRegionId());
//4. 新增user表
User newUser = new User();
newUser.setAcctId(user.getAcctId());
newUser.setCreateDate(new Date());
newUser.setEmail(user.getEmail());
newUser.setMobile(user.getMobile());
newUser.setModiDate(new Date());
newUser.setRegionId(user.getRegionId());
newUser.setState(LoginConstants.USER_STATE_DEFAULT);
newUser.setUserId(sequenceFactory.next(LoginConstants.SEQUENCENAME_USER));
newUser.setUserName(user.getUserName());
userMapper.insertSelective(newUser);
}
@Override
public void updateUser(User user) {
regionComp.checkRegion(user.getRegionId());
//4. 新增user表
User newUser = new User();
newUser.setEmail(user.getEmail());
newUser.setMobile(user.getMobile());
newUser.setModiDate(new Date());
newUser.setUserId(user.getUserId());
newUser.setState(user.getState());
newUser.setUserName(user.getUserName());
newUser.setPhone(user.getPhone());
newUser.setRegionId(user.getRegionId());
userMapper.updateByPrimaryKeySelective(newUser);
}
}
| 2,974 | 0.764348 | 0.760635 | 90 | 31.911112 | 19.227669 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.288889 | false | false | 8 |
43f415ed066ac2f3cc8bc2fe4faa312b6ac26b37 | 29,583,734,773,082 | 83d60ab4cc07c73a0a336741f86e44edbf3a772d | /src/functionalTests/java/uk/gov/hmcts/reform/finrem/functional/util/FunctionalTestUtils.java | 54caceb0c413808ecf4d7b7ee0c6a24b6363d869 | [
"MIT"
] | permissive | hmcts/finrem-case-orchestration-service | https://github.com/hmcts/finrem-case-orchestration-service | 61fcff79e87a50d05896a935bfa9048dcdc08ca4 | f9ef4c75eff89c6b980694bd209f6ed90fa5c8f8 | refs/heads/master | 2023-08-16T19:43:24.231000 | 2023-08-15T10:23:55 | 2023-08-15T10:23:55 | 144,502,110 | 5 | 2 | MIT | false | 2023-09-13T08:36:29 | 2018-08-12T21:29:09 | 2023-09-01T08:35:34 | 2023-09-13T08:36:28 | 13,107 | 3 | 2 | 25 | Java | false | false | package uk.gov.hmcts.reform.finrem.functional.util;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.serenitybdd.rest.SerenityRest;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.ResourceUtils;
import uk.gov.hmcts.reform.authorisation.generators.ServiceAuthTokenGenerator;
import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest;
import uk.gov.hmcts.reform.finrem.functional.TestContextConfiguration;
import uk.gov.hmcts.reform.finrem.functional.idam.IdamUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static uk.gov.hmcts.reform.finrem.caseorchestration.OrchestrationConstants.AUTHORIZATION_HEADER;
import static uk.gov.hmcts.reform.finrem.caseorchestration.OrchestrationConstants.SERVICE_AUTHORISATION_HEADER;
@ContextConfiguration(classes = TestContextConfiguration.class)
@Component
@Slf4j
@RequiredArgsConstructor
public class FunctionalTestUtils {
private final ServiceAuthTokenGenerator tokenGenerator;
private final IdamUtils idamUtils;
@Value("${user.id.url}")
private String userId;
@Value("${idam.username}")
private String idamUserName;
@Value("${idam.userpassword}")
private String idamUserPassword;
public String getJsonFromFile(String fileName, String directory) {
try {
File file = ResourceUtils.getFile(this.getClass().getResource(directory + fileName));
return new String(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Headers getHeadersWithUserId() {
return Headers.headers(
new Header(SERVICE_AUTHORISATION_HEADER, tokenGenerator.generate()),
new Header("user-roles", "caseworker-divorce"),
new Header("user-id", userId));
}
public Headers getHeaders() {
return Headers.headers(
new Header(AUTHORIZATION_HEADER, "Bearer "
+ idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword)),
new Header("Content-Type", ContentType.JSON.toString()));
}
public String getS2SToken(String callerMicroservice) {
return idamUtils.generateServiceTokenWithValidMicroservice(callerMicroservice);
}
public Headers getHeader() {
return Headers.headers(
new Header(AUTHORIZATION_HEADER, "Bearer "
+ idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword)));
}
public String getAuthToken() {
return "Bearer " + idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword);
}
public String downloadPdfAndParseToString(String documentUrl) {
Response document = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeadersWithUserId())
.when().get(documentUrl).andReturn();
return parsePdfToString(document.getBody().asInputStream());
}
public String parsePdfToString(InputStream inputStream) {
PDFParser parser;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
PDFTextStripper pdfStripper;
String parsedText;
try {
parser = new PDFParser(new RandomAccessBufferedFileInputStream(inputStream));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
} catch (Throwable t) {
t.printStackTrace();
try {
if (cosDoc != null) {
cosDoc.close();
}
if (pdDoc != null) {
pdDoc.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
throw new Error(t);
}
return parsedText;
}
public void validatePostSuccess(String url, String filename, String journeyType) {
int statusCode = getResponse(url, filename, journeyType).getStatusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
public JsonPath getResponseData(String url, String jsonBody, String dataPath) {
Response response = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(jsonBody)
.when().post(url)
.andReturn();
assertEquals(HttpStatus.OK, HttpStatus.valueOf(response.getStatusCode()));
JsonPath jsonPath = response.jsonPath().setRoot(dataPath);
return jsonPath;
}
public JsonPath getResponseData(String url, String filename, String journeyType, String dataPath) {
Response response = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(getJsonFromFile(filename, journeyType))
.when().post(url)
.andReturn();
assertEquals(HttpStatus.OK, HttpStatus.valueOf(response.getStatusCode()));
JsonPath jsonPath = response.jsonPath().setRoot(dataPath);
return jsonPath;
}
public Response getResponseData(String url, CallbackRequest callbackRequest) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(callbackRequest)
.when().post(url)
.andReturn();
}
public Response getResponse(String url, String filename, String journeyType) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(getJsonFromFile(filename, journeyType))
.when().post(url).andReturn();
}
public int getStatusCode(String url, String jsonFileName, String journeyType) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeaders())
.body(getJsonFromFile(jsonFileName, journeyType))
.when().post(url).getStatusCode();
}
}
| UTF-8 | Java | 6,985 | java | FunctionalTestUtils.java | Java | [] | null | [] | package uk.gov.hmcts.reform.finrem.functional.util;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.serenitybdd.rest.SerenityRest;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.ResourceUtils;
import uk.gov.hmcts.reform.authorisation.generators.ServiceAuthTokenGenerator;
import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest;
import uk.gov.hmcts.reform.finrem.functional.TestContextConfiguration;
import uk.gov.hmcts.reform.finrem.functional.idam.IdamUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static uk.gov.hmcts.reform.finrem.caseorchestration.OrchestrationConstants.AUTHORIZATION_HEADER;
import static uk.gov.hmcts.reform.finrem.caseorchestration.OrchestrationConstants.SERVICE_AUTHORISATION_HEADER;
@ContextConfiguration(classes = TestContextConfiguration.class)
@Component
@Slf4j
@RequiredArgsConstructor
public class FunctionalTestUtils {
private final ServiceAuthTokenGenerator tokenGenerator;
private final IdamUtils idamUtils;
@Value("${user.id.url}")
private String userId;
@Value("${idam.username}")
private String idamUserName;
@Value("${idam.userpassword}")
private String idamUserPassword;
public String getJsonFromFile(String fileName, String directory) {
try {
File file = ResourceUtils.getFile(this.getClass().getResource(directory + fileName));
return new String(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Headers getHeadersWithUserId() {
return Headers.headers(
new Header(SERVICE_AUTHORISATION_HEADER, tokenGenerator.generate()),
new Header("user-roles", "caseworker-divorce"),
new Header("user-id", userId));
}
public Headers getHeaders() {
return Headers.headers(
new Header(AUTHORIZATION_HEADER, "Bearer "
+ idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword)),
new Header("Content-Type", ContentType.JSON.toString()));
}
public String getS2SToken(String callerMicroservice) {
return idamUtils.generateServiceTokenWithValidMicroservice(callerMicroservice);
}
public Headers getHeader() {
return Headers.headers(
new Header(AUTHORIZATION_HEADER, "Bearer "
+ idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword)));
}
public String getAuthToken() {
return "Bearer " + idamUtils.generateUserTokenWithNoRoles(idamUserName, idamUserPassword);
}
public String downloadPdfAndParseToString(String documentUrl) {
Response document = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeadersWithUserId())
.when().get(documentUrl).andReturn();
return parsePdfToString(document.getBody().asInputStream());
}
public String parsePdfToString(InputStream inputStream) {
PDFParser parser;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
PDFTextStripper pdfStripper;
String parsedText;
try {
parser = new PDFParser(new RandomAccessBufferedFileInputStream(inputStream));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
} catch (Throwable t) {
t.printStackTrace();
try {
if (cosDoc != null) {
cosDoc.close();
}
if (pdDoc != null) {
pdDoc.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
throw new Error(t);
}
return parsedText;
}
public void validatePostSuccess(String url, String filename, String journeyType) {
int statusCode = getResponse(url, filename, journeyType).getStatusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
public JsonPath getResponseData(String url, String jsonBody, String dataPath) {
Response response = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(jsonBody)
.when().post(url)
.andReturn();
assertEquals(HttpStatus.OK, HttpStatus.valueOf(response.getStatusCode()));
JsonPath jsonPath = response.jsonPath().setRoot(dataPath);
return jsonPath;
}
public JsonPath getResponseData(String url, String filename, String journeyType, String dataPath) {
Response response = SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(getJsonFromFile(filename, journeyType))
.when().post(url)
.andReturn();
assertEquals(HttpStatus.OK, HttpStatus.valueOf(response.getStatusCode()));
JsonPath jsonPath = response.jsonPath().setRoot(dataPath);
return jsonPath;
}
public Response getResponseData(String url, CallbackRequest callbackRequest) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(callbackRequest)
.when().post(url)
.andReturn();
}
public Response getResponse(String url, String filename, String journeyType) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeader())
.contentType("application/json")
.body(getJsonFromFile(filename, journeyType))
.when().post(url).andReturn();
}
public int getStatusCode(String url, String jsonFileName, String journeyType) {
return SerenityRest.given()
.relaxedHTTPSValidation()
.headers(getHeaders())
.body(getJsonFromFile(jsonFileName, journeyType))
.when().post(url).getStatusCode();
}
}
| 6,985 | 0.670294 | 0.669434 | 195 | 34.820515 | 26.466497 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558974 | false | false | 8 |
a9fedf77ea321c4137f244d06ad01b5fb5552350 | 29,583,734,774,892 | 3976e90fae9284531168f2769a4288baa81e00ba | /src/com/asiacom/mqtt/MqttActivity.java | 71c03a103fa87fc4676bbc92221213bb80c284b9 | [] | no_license | djun100/MQDemo | https://github.com/djun100/MQDemo | 02ba4975fe89c68774705d158a26a683d3160e30 | 9357aa9aacdc9da9d6e70d44fd0576cda680cae6 | refs/heads/master | 2021-01-21T07:39:07.881000 | 2014-01-06T09:58:04 | 2014-01-06T09:58:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiacom.mqtt;
import com.asiacom.mq.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MqttActivity extends Activity implements MqttPublish,OnClickListener{
private static final String TAG = "MqttActivity";
private EditText editText;
private Button uploadBtn;
private String uploadContent = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqtt);
editText = (EditText)findViewById(R.id.content_et);
uploadBtn = (Button)findViewById(R.id.upload_btn);
uploadBtn.setOnClickListener(this);
}
@Override
public void publishSuccessfull(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishFailed(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishing(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishWaiting(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.upload_btn:
uploadContent = editText.getText().toString();
Log.d(TAG, "内容:" + uploadContent+"----"+uploadContent.length());
if(!"".equals(uploadContent.trim())&& uploadContent != null&&uploadContent.length()>0){
StringBuilder payload = new StringBuilder();// 上传参数
String topic = Constants.UPLOAD_LOCATION_MQTT;
payload.append("{");
payload.append("\"content\": ").append(uploadContent);
payload.append("}");
Log.d(TAG, "上传的参数:" + payload.toString());
//利用MQTT上传,此处上传服务器地址为空,所以会报错
ServiceMqtt.getInstance().publish(topic, payload.toString(), false, 0,
20, this, uploadContent);
}else{
Toast.makeText(this, "请输入要上传的内容", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
| UTF-8 | Java | 2,283 | java | MqttActivity.java | Java | [] | null | [] | package com.asiacom.mqtt;
import com.asiacom.mq.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MqttActivity extends Activity implements MqttPublish,OnClickListener{
private static final String TAG = "MqttActivity";
private EditText editText;
private Button uploadBtn;
private String uploadContent = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqtt);
editText = (EditText)findViewById(R.id.content_et);
uploadBtn = (Button)findViewById(R.id.upload_btn);
uploadBtn.setOnClickListener(this);
}
@Override
public void publishSuccessfull(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishFailed(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishing(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void publishWaiting(Object extra) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.upload_btn:
uploadContent = editText.getText().toString();
Log.d(TAG, "内容:" + uploadContent+"----"+uploadContent.length());
if(!"".equals(uploadContent.trim())&& uploadContent != null&&uploadContent.length()>0){
StringBuilder payload = new StringBuilder();// 上传参数
String topic = Constants.UPLOAD_LOCATION_MQTT;
payload.append("{");
payload.append("\"content\": ").append(uploadContent);
payload.append("}");
Log.d(TAG, "上传的参数:" + payload.toString());
//利用MQTT上传,此处上传服务器地址为空,所以会报错
ServiceMqtt.getInstance().publish(topic, payload.toString(), false, 0,
20, this, uploadContent);
}else{
Toast.makeText(this, "请输入要上传的内容", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
| 2,283 | 0.689749 | 0.687927 | 84 | 24.130953 | 21.994469 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.988095 | false | false | 8 |
96c4520dea2bea5f4717e799c480b855da9e9506 | 5,205,500,426,180 | 0fcc6d08898e899fb19376831d9829050606cb17 | /src/main/java/uriSchemeHandler/CouldNotOpenUriSchemeHandler.java | 8918af1cf0819a5add402febb8f448f1046d7ef2 | [] | no_license | beothorn/URISchemeHandler | https://github.com/beothorn/URISchemeHandler | 1d521beece19eafddbea70aee0bb03774a047abf | 40195a5469e5400eb33198e00270515030ad23d9 | refs/heads/master | 2021-06-01T22:18:17.111000 | 2019-01-26T22:58:57 | 2019-01-26T22:58:57 | 4,160,057 | 15 | 5 | null | false | 2018-12-02T15:01:13 | 2012-04-27T16:11:41 | 2018-08-19T12:59:00 | 2018-12-02T15:01:13 | 42 | 15 | 5 | 4 | Java | false | null | package uriSchemeHandler;
import java.io.IOException;
@SuppressWarnings("serial")
public class CouldNotOpenUriSchemeHandler extends Exception {
public CouldNotOpenUriSchemeHandler(final IOException e, final String uri) {
super("Could not open Uri scheme handler for "+uri,e);
}
}
| UTF-8 | Java | 288 | java | CouldNotOpenUriSchemeHandler.java | Java | [] | null | [] | package uriSchemeHandler;
import java.io.IOException;
@SuppressWarnings("serial")
public class CouldNotOpenUriSchemeHandler extends Exception {
public CouldNotOpenUriSchemeHandler(final IOException e, final String uri) {
super("Could not open Uri scheme handler for "+uri,e);
}
}
| 288 | 0.791667 | 0.791667 | 12 | 23 | 26.655207 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 8 |
f3f66a22de927f0b3a04c3f022c0402cee9a801b | 5,909,875,004,263 | 50816d6dea22b53d73f58139adff5119ba7c937e | /main/java/slash/commands/Regiester.java | 71b67860a3ce9a86944b65ce9fb900147ad639ed | [] | no_license | MarinusLeeuwerik/Slash | https://github.com/MarinusLeeuwerik/Slash | 89a0b8665363e2db28e31b77777467f8f137edad | d679a5cdb0d053fc3aa86f8979e28edd838141b9 | refs/heads/master | 2020-12-11T09:22:43.770000 | 2014-11-11T06:55:37 | 2014-11-11T06:55:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package slash.commands;
import slash.chats.templates.Tooltip;
import slash.commands.templates.Command;
import slash.elements.Player;
import slash.tools.McColor;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.IChatComponent;
public class Regiester extends Command
{
@Override
public String getName()
{
return "register";
}
@Override
public String getUsage(ICommandSender sender)
{
return " [password] [re-enter password] register your character to this server.";
}
@Override
public void processPlayer(Player sender, String[] args)
{
if(args.length == 2)
{
if(args[0].equals(args[1]))
{
sender.profile.load();
if(sender.profile.password == null)
{
sender.profile.password = args[0];
sender.profile.save();
sender.sendChatMessage(McColor.green + "Welcome to minecraft, " + sender.name + ".");
Login.loginPlayer(sender.entityPlayerMP);
}
else
{
sender.sendChatMessage(McColor.darkRed + "This user name have already been registered!");
}
}
else
{
sender.sendChatMessage(McColor.darkRed + "two passwords aren't matching :(");
}
}
else
{
sender.sendChatMessage(McColor.darkRed + "Argument mismatch.");
}
}
@Override
public void processConsole(ICommandSender console, String[] args)
{
}
@Override
public IChatComponent getFancyUsage()
{
return new Tooltip("How to change password","to change someone's password,\nSimply go to their pofile.txt file,\nand remove the line with password.");
}
}
| UTF-8 | Java | 1,546 | java | Regiester.java | Java | [] | null | [] | package slash.commands;
import slash.chats.templates.Tooltip;
import slash.commands.templates.Command;
import slash.elements.Player;
import slash.tools.McColor;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.IChatComponent;
public class Regiester extends Command
{
@Override
public String getName()
{
return "register";
}
@Override
public String getUsage(ICommandSender sender)
{
return " [password] [re-enter password] register your character to this server.";
}
@Override
public void processPlayer(Player sender, String[] args)
{
if(args.length == 2)
{
if(args[0].equals(args[1]))
{
sender.profile.load();
if(sender.profile.password == null)
{
sender.profile.password = args[0];
sender.profile.save();
sender.sendChatMessage(McColor.green + "Welcome to minecraft, " + sender.name + ".");
Login.loginPlayer(sender.entityPlayerMP);
}
else
{
sender.sendChatMessage(McColor.darkRed + "This user name have already been registered!");
}
}
else
{
sender.sendChatMessage(McColor.darkRed + "two passwords aren't matching :(");
}
}
else
{
sender.sendChatMessage(McColor.darkRed + "Argument mismatch.");
}
}
@Override
public void processConsole(ICommandSender console, String[] args)
{
}
@Override
public IChatComponent getFancyUsage()
{
return new Tooltip("How to change password","to change someone's password,\nSimply go to their pofile.txt file,\nand remove the line with password.");
}
}
| 1,546 | 0.69793 | 0.695343 | 70 | 21.085714 | 28.726166 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.157143 | false | false | 8 |
b0909237806c6c26dca97c319210523d055c9d41 | 9,079,560,872,847 | 664641af3131cb2ef0d62545ccfac3882107b2d9 | /src/main/java/com/example/entity/Malfunction.java | c1a771d2772e2e933813af593ef1c6062246302d | [] | no_license | BeDemon/demon | https://github.com/BeDemon/demon | e767591cc1335d14c2c38974ff578fb925458879 | f6a01a450894a187bad613f15bfc84a9520e4e70 | refs/heads/master | 2020-04-26T17:24:16.857000 | 2019-03-06T06:34:56 | 2019-03-06T06:34:56 | 173,711,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.entity;
import java.util.List;
public class Malfunction {
private Integer malfunction_id;
private Integer element_id;
private String malfunction_description;
private String malfunction_influences;
private List<Reason> reason_list;
private List<Solution> solution_list;
public Malfunction() {
}
public Malfunction(Integer malfunction_id, Integer element_id, String malfunction_description, String malfunction_influences, List<Reason> reason_list, List<Solution> solution_list) {
this.malfunction_id = malfunction_id;
this.element_id = element_id;
this.malfunction_description = malfunction_description;
this.malfunction_influences = malfunction_influences;
this.reason_list = reason_list;
this.solution_list = solution_list;
}
public Integer getMalfunction_id() {
return malfunction_id;
}
public void setMalfunction_id(Integer malfunction_id) {
this.malfunction_id = malfunction_id;
}
public Integer getElement_id() {
return element_id;
}
public void setElement_id(Integer element_id) {
this.element_id = element_id;
}
public String getMalfunction_description() {
return malfunction_description;
}
public void setMalfunction_description(String malfunction_description) {
this.malfunction_description = malfunction_description;
}
public String getMalfunction_influences() {
return malfunction_influences;
}
public void setMalfunction_influences(String malfunction_influences) {
this.malfunction_influences = malfunction_influences;
}
public List<Reason> getReason_list() {
return reason_list;
}
public void setReason_list(List<Reason> reason_list) {
this.reason_list = reason_list;
}
public List<Solution> getSolution_list() {
return solution_list;
}
public void setSolution_list(List<Solution> solution_list) {
this.solution_list = solution_list;
}
}
| UTF-8 | Java | 2,067 | java | Malfunction.java | Java | [] | null | [] | package com.example.entity;
import java.util.List;
public class Malfunction {
private Integer malfunction_id;
private Integer element_id;
private String malfunction_description;
private String malfunction_influences;
private List<Reason> reason_list;
private List<Solution> solution_list;
public Malfunction() {
}
public Malfunction(Integer malfunction_id, Integer element_id, String malfunction_description, String malfunction_influences, List<Reason> reason_list, List<Solution> solution_list) {
this.malfunction_id = malfunction_id;
this.element_id = element_id;
this.malfunction_description = malfunction_description;
this.malfunction_influences = malfunction_influences;
this.reason_list = reason_list;
this.solution_list = solution_list;
}
public Integer getMalfunction_id() {
return malfunction_id;
}
public void setMalfunction_id(Integer malfunction_id) {
this.malfunction_id = malfunction_id;
}
public Integer getElement_id() {
return element_id;
}
public void setElement_id(Integer element_id) {
this.element_id = element_id;
}
public String getMalfunction_description() {
return malfunction_description;
}
public void setMalfunction_description(String malfunction_description) {
this.malfunction_description = malfunction_description;
}
public String getMalfunction_influences() {
return malfunction_influences;
}
public void setMalfunction_influences(String malfunction_influences) {
this.malfunction_influences = malfunction_influences;
}
public List<Reason> getReason_list() {
return reason_list;
}
public void setReason_list(List<Reason> reason_list) {
this.reason_list = reason_list;
}
public List<Solution> getSolution_list() {
return solution_list;
}
public void setSolution_list(List<Solution> solution_list) {
this.solution_list = solution_list;
}
}
| 2,067 | 0.685535 | 0.685535 | 73 | 27.315069 | 29.463177 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424658 | false | false | 8 |
dd670284356302fd399a8a7567f431a031d5af67 | 10,333,691,332,492 | 1be68535be3d15bf1b63760c04145aa9cd937ef8 | /app/src/main/java/com/example/mathmurder/tablehitch/OrderActivity.java | 5ab228126c60eee1754e10e6aaab450cca6fff13 | [] | no_license | cmFodWx5YWRhdjEyMTA5/TableHitchNew | https://github.com/cmFodWx5YWRhdjEyMTA5/TableHitchNew | e8599251f57f0ca1ce4abdb77f22a9d92b0426be | 0fcb2360c8c4e25bd6f2cd90e60f3a6a3a59fcc8 | refs/heads/master | 2020-03-30T05:01:02.903000 | 2018-09-19T01:46:52 | 2018-09-19T01:46:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mathmurder.tablehitch;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class OrderActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private TextView orderReview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
orderReview = (TextView) findViewById(R.id.orderReview);
String toShow = "";
int price = 0;
int i = 1;
for (String order : FoodItemActivity.selectedItems){
// String[] toSplit = order.split("\t\t\t\t");
//
//
// String splitNum = toSplit[1];
// splitNum = splitNum.replaceAll("\\D","");
// int eachPrice = Integer.parseInt(splitNum);
// Log.i("price", "a: "+ eachPrice);
// sprice += eachPrice;
toShow += i+". " + order +"\n";
i++;
}
orderReview.setText(toShow);
TextView total = findViewById(R.id.textView5);
total.setText("$4");
// after payment is done, clear the array again!
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
Intent intent = new Intent(OrderActivity.this, MainActivity.class);
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.profileNav) {
// Handle the camera action
} else if (id == R.id.seatNav) {
} else if (id == R.id.foodNav) {
} else if (id == R.id.payNav) {
} else if (id == R.id.rewardNav) {
} else if (id == R.id.historyNav) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| UTF-8 | Java | 4,144 | java | OrderActivity.java | Java | [
{
"context": "package com.example.mathmurder.tablehitch;\n\nimport android.content.Intent;\nimpor",
"end": 30,
"score": 0.9830588698387146,
"start": 20,
"tag": "USERNAME",
"value": "mathmurder"
}
] | null | [] | package com.example.mathmurder.tablehitch;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class OrderActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private TextView orderReview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
orderReview = (TextView) findViewById(R.id.orderReview);
String toShow = "";
int price = 0;
int i = 1;
for (String order : FoodItemActivity.selectedItems){
// String[] toSplit = order.split("\t\t\t\t");
//
//
// String splitNum = toSplit[1];
// splitNum = splitNum.replaceAll("\\D","");
// int eachPrice = Integer.parseInt(splitNum);
// Log.i("price", "a: "+ eachPrice);
// sprice += eachPrice;
toShow += i+". " + order +"\n";
i++;
}
orderReview.setText(toShow);
TextView total = findViewById(R.id.textView5);
total.setText("$4");
// after payment is done, clear the array again!
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
Intent intent = new Intent(OrderActivity.this, MainActivity.class);
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.profileNav) {
// Handle the camera action
} else if (id == R.id.seatNav) {
} else if (id == R.id.foodNav) {
} else if (id == R.id.payNav) {
} else if (id == R.id.rewardNav) {
} else if (id == R.id.historyNav) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| 4,144 | 0.65082 | 0.648407 | 133 | 30.157894 | 25.35043 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511278 | false | false | 8 |
42c082c0caba6025358f4d0046eae693e4767499 | 4,415,226,413,705 | 54aa783fb975722a6a2a192471d37981205eb3f5 | /programs/ThredingInJava/src/thread1/ImplemetRunable.java | f321e805ff2c856f2d3f229ce28cbdd82be32b5e | [] | no_license | chetan988/java | https://github.com/chetan988/java | 562bcacf78d0c2c58f735c8251a519746912c67e | f5ad8b4034eaafd2327966b397e8dcd0fed7a8b9 | refs/heads/master | 2016-09-06T02:46:22.604000 | 2015-09-02T18:11:30 | 2015-09-02T18:11:30 | 41,818,216 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package thread1;
class Useranable implements Runnable {
private String threadname;
public Useranable(String name) {
threadname = name;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("running thread "+ threadname +" : "+ i );
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ImplemetRunable {
public static void main(String[] args) {
Thread t1 = new Thread(new Useranable("thread1"));
t1.start();
Thread t2 = new Thread(new Useranable("thread2"));
t2.start();
}
}
| UTF-8 | Java | 594 | java | ImplemetRunable.java | Java | [] | null | [] | package thread1;
class Useranable implements Runnable {
private String threadname;
public Useranable(String name) {
threadname = name;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("running thread "+ threadname +" : "+ i );
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ImplemetRunable {
public static void main(String[] args) {
Thread t1 = new Thread(new Useranable("thread1"));
t1.start();
Thread t2 = new Thread(new Useranable("thread2"));
t2.start();
}
}
| 594 | 0.649832 | 0.627946 | 33 | 17 | 17.805346 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 8 |
0f89322138f1fe4d3560b783459b5e341e3f4aee | 23,038,204,577,124 | 9bc741d96f7bf29a348d9d013abbc881b82f6047 | /src/test/java/util/JsonConverterTest.java | c0dddc50893dd4a416ed0f4fb97851d78fbb3466 | [] | no_license | vcpjr/semantic-bi | https://github.com/vcpjr/semantic-bi | 723cc3492c1a12e1eae30a8d328f203dce256da2 | 4a08165631e34f3830879d443c249ce6529321f4 | refs/heads/master | 2021-09-26T23:42:40.383000 | 2018-11-04T17:09:56 | 2018-11-04T17:09:56 | 71,284,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import org.junit.Assert;
import org.junit.Test;
import pojo.Tweet;
import pojo.dbpediaspotlight.Annotation;
import pojo.dbpediaspotlight.AnnotationResource;
import java.time.LocalDateTime;
import java.util.*;
public class JsonConverterTest {
final double OFFSET = 0.001;
boolean hasEquals(AnnotationResource lhs, AnnotationResource rhs) {
return lhs.getURI().equals(rhs.getURI())
&& lhs.getSupport() == rhs.getSupport()
&& lhs.getTypes().equals(rhs.getTypes())
&& lhs.getSurfaceForm().equals(rhs.getSurfaceForm())
&& lhs.getOffset() == rhs.getOffset()
&& Math.abs(lhs.getSimilarityScore() - rhs.getSimilarityScore()) < OFFSET
&& Math.abs(lhs.getPercentageOfSecondRank() - rhs.getPercentageOfSecondRank()) < OFFSET;
}
boolean hasEquals(Annotation lhs, Annotation rhs) {
List<AnnotationResource> lRes = lhs.getResources();
List<AnnotationResource> rRes = rhs.getResources();
lRes.sort(Comparator.comparing(AnnotationResource::getURI));
rRes.sort(Comparator.comparing(AnnotationResource::getURI));
if (lRes.size() != rRes.size()) {
return false;
}
for (int i = 0; i < lhs.getResourcesSize(); ++i) {
if (!hasEquals(lRes.get(i), rRes.get(i))) {
return false;
}
}
return lhs.getText().equals(rhs.getText())
&& Math.abs(lhs.getConfidence() - rhs.getConfidence()) <= OFFSET
&& lhs.getSupport() == rhs.getSupport()
&& lhs.getTypes().equals(rhs.getTypes())
&& lhs.getSparql().equals(rhs.getSparql())
&& lhs.getPolicy().equals(rhs.getPolicy());
}
boolean hasEquals(Tweet lhs, Tweet rhs) {
return lhs.getId().equals(rhs.getId())
&& lhs.getUserId().equals(rhs.getUserId())
&& lhs.getText().equals(rhs.getText())
&& lhs.getCreationDate().equals(rhs.getCreationDate())
&& lhs.isRetweet() == rhs.isRetweet();
}
@Test
public void testConvertJsonToAnnotation() {
final String json = "{" +
" '@text':'A textbook'," +
" '@confidence':'0.05'," +
" '@support':'0'," +
" '@types':''," +
" '@sparql':''," +
" '@policy':'whitelist'," +
" 'Resources':[" +
" {" +
" '@URI':'http://dbpedia.org/resource/Business'," +
" '@support':'1943'," +
" '@types':'DBpedia:Organisation,DBpedia:Company'," +
" '@surfaceForm':'A Business'," +
" '@offset':'0'," +
" '@similarityScore':'0.0'," +
" '@percentageOfSecondRank':'4.0'" +
" }" +
" ]" +
"}";
Annotation ann = new Annotation(
"A textbook", 0.05f, 0, "", "", "whitelist",
Collections.singletonList(new AnnotationResource("http://dbpedia.org/resource/Business", 1943,
new HashSet<>(Arrays.asList("DBpedia:Organisation", "DBpedia:Company")),
"A Business", 0, 0, 4
))
);
Assert.assertTrue(hasEquals(JsonConverter.toAnnotation(json), ann));
}
@Test
public void testConvertJsonToTweet() {
//TODO normalizar os dados do JSON vindos do mongo
// final String json = "{" +
// " '_id':'{\"$oid\":\"5999d40444d5bb0420b429c2\"}," +
// " '\"id\":{\"$numberLong\":\"899336510713016320\"}," +
// " \"userid\":{\"$numberLong\":\"633419436\"}," +
// " \"createdat\":{\"$date\":\"2017-08-20T00:00:00.000Z\"}," +
// " \"text\":\"Kkkkkk sim https://t.co/xeuLCcENLE\", " +
// " \"isretweet\":false" +
// "}";
final String json = "{" +
" 'id':'1'," +
" 'userid':'1'," +
" 'text':'text ....'," +
" 'createdat':'2017-08-20T00:00:00.000Z'," +
" 'isretweet':'false'" +
"}";
Calendar calendario =
new Calendar.Builder()
.setDate(2017, Calendar.AUGUST, 20)
.setTimeOfDay(0, 0, 0)
.build();
Date creationDate = calendario.getTime();
Tweet t = new Tweet(1L, 1L, "text ....", creationDate, false);
Assert.assertTrue(hasEquals(JsonConverter.toTweet(json), t));
}
} | UTF-8 | Java | 4,565 | java | JsonConverterTest.java | Java | [] | null | [] | package util;
import org.junit.Assert;
import org.junit.Test;
import pojo.Tweet;
import pojo.dbpediaspotlight.Annotation;
import pojo.dbpediaspotlight.AnnotationResource;
import java.time.LocalDateTime;
import java.util.*;
public class JsonConverterTest {
final double OFFSET = 0.001;
boolean hasEquals(AnnotationResource lhs, AnnotationResource rhs) {
return lhs.getURI().equals(rhs.getURI())
&& lhs.getSupport() == rhs.getSupport()
&& lhs.getTypes().equals(rhs.getTypes())
&& lhs.getSurfaceForm().equals(rhs.getSurfaceForm())
&& lhs.getOffset() == rhs.getOffset()
&& Math.abs(lhs.getSimilarityScore() - rhs.getSimilarityScore()) < OFFSET
&& Math.abs(lhs.getPercentageOfSecondRank() - rhs.getPercentageOfSecondRank()) < OFFSET;
}
boolean hasEquals(Annotation lhs, Annotation rhs) {
List<AnnotationResource> lRes = lhs.getResources();
List<AnnotationResource> rRes = rhs.getResources();
lRes.sort(Comparator.comparing(AnnotationResource::getURI));
rRes.sort(Comparator.comparing(AnnotationResource::getURI));
if (lRes.size() != rRes.size()) {
return false;
}
for (int i = 0; i < lhs.getResourcesSize(); ++i) {
if (!hasEquals(lRes.get(i), rRes.get(i))) {
return false;
}
}
return lhs.getText().equals(rhs.getText())
&& Math.abs(lhs.getConfidence() - rhs.getConfidence()) <= OFFSET
&& lhs.getSupport() == rhs.getSupport()
&& lhs.getTypes().equals(rhs.getTypes())
&& lhs.getSparql().equals(rhs.getSparql())
&& lhs.getPolicy().equals(rhs.getPolicy());
}
boolean hasEquals(Tweet lhs, Tweet rhs) {
return lhs.getId().equals(rhs.getId())
&& lhs.getUserId().equals(rhs.getUserId())
&& lhs.getText().equals(rhs.getText())
&& lhs.getCreationDate().equals(rhs.getCreationDate())
&& lhs.isRetweet() == rhs.isRetweet();
}
@Test
public void testConvertJsonToAnnotation() {
final String json = "{" +
" '@text':'A textbook'," +
" '@confidence':'0.05'," +
" '@support':'0'," +
" '@types':''," +
" '@sparql':''," +
" '@policy':'whitelist'," +
" 'Resources':[" +
" {" +
" '@URI':'http://dbpedia.org/resource/Business'," +
" '@support':'1943'," +
" '@types':'DBpedia:Organisation,DBpedia:Company'," +
" '@surfaceForm':'A Business'," +
" '@offset':'0'," +
" '@similarityScore':'0.0'," +
" '@percentageOfSecondRank':'4.0'" +
" }" +
" ]" +
"}";
Annotation ann = new Annotation(
"A textbook", 0.05f, 0, "", "", "whitelist",
Collections.singletonList(new AnnotationResource("http://dbpedia.org/resource/Business", 1943,
new HashSet<>(Arrays.asList("DBpedia:Organisation", "DBpedia:Company")),
"A Business", 0, 0, 4
))
);
Assert.assertTrue(hasEquals(JsonConverter.toAnnotation(json), ann));
}
@Test
public void testConvertJsonToTweet() {
//TODO normalizar os dados do JSON vindos do mongo
// final String json = "{" +
// " '_id':'{\"$oid\":\"5999d40444d5bb0420b429c2\"}," +
// " '\"id\":{\"$numberLong\":\"899336510713016320\"}," +
// " \"userid\":{\"$numberLong\":\"633419436\"}," +
// " \"createdat\":{\"$date\":\"2017-08-20T00:00:00.000Z\"}," +
// " \"text\":\"Kkkkkk sim https://t.co/xeuLCcENLE\", " +
// " \"isretweet\":false" +
// "}";
final String json = "{" +
" 'id':'1'," +
" 'userid':'1'," +
" 'text':'text ....'," +
" 'createdat':'2017-08-20T00:00:00.000Z'," +
" 'isretweet':'false'" +
"}";
Calendar calendario =
new Calendar.Builder()
.setDate(2017, Calendar.AUGUST, 20)
.setTimeOfDay(0, 0, 0)
.build();
Date creationDate = calendario.getTime();
Tweet t = new Tweet(1L, 1L, "text ....", creationDate, false);
Assert.assertTrue(hasEquals(JsonConverter.toTweet(json), t));
}
} | 4,565 | 0.507777 | 0.481271 | 121 | 36.735538 | 25.055235 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719008 | false | false | 8 |
7b49398e59a7d63a655c6cf1a835d9d292b70a41 | 6,734,508,744,484 | 98e3bc6ba8134e1a5806044f864c4c4f362b12a8 | /javac/LH.java | 76163668fa5e59745d03c81cc20bfadfd4a32abc | [] | no_license | ndeloof/bench | https://github.com/ndeloof/bench | a00cb733d9ebde87dd6a0955c636aa5c39f08ddf | d646a4386dbf195c9a9e49a826105a8612a13967 | refs/heads/master | 2016-09-06T21:26:14.669000 | 2013-01-30T10:32:51 | 2013-01-30T10:32:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class LH {
public int foo(int bar) {
return bar + 11 + 7;
}
}
| UTF-8 | Java | 83 | java | LH.java | Java | [] | null | [] |
public class LH {
public int foo(int bar) {
return bar + 11 + 7;
}
}
| 83 | 0.518072 | 0.481928 | 7 | 10.428572 | 11.286618 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 8 |
efaaa270572d8dba5d2e6e8e48322fe4b05d4840 | 11,450,382,865,426 | f5a8ea7142fce5d293b04c56ab1a885b16eecb84 | /Algorithms/Greedy/src/JimAndTheOrders.java | 3db0cd48200d6c58c34e2908301ffebcfdc27e35 | [] | no_license | lakmad0/Hackerrank | https://github.com/lakmad0/Hackerrank | 226047e9bd690fa589c81e0088fcb9d166cf54b0 | edb5ee719784f1e16279e0ed4998f8b2db5cf65f | refs/heads/master | 2021-01-19T04:46:41.984000 | 2016-07-20T17:03:46 | 2016-07-20T17:03:46 | 62,484,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
import java.util.TreeSet;
/**
* Created by lakshitha on 7/14/16.
*/
public class JimAndTheOrders {
public static void main(String[] args) {
TreeSet <Order> treeSet = new TreeSet<Order>();
StringBuilder stringBuilder = new StringBuilder();
Scanner s1 = new Scanner(System.in);
int orders = s1.nextInt();
for (int i = 0; i < orders; i++){
treeSet.add(new Order(i+1,s1.nextInt()+s1.nextInt()));
}
for (Order o : treeSet)
stringBuilder.append(o.orderId + " ");
System.out.println(stringBuilder.toString().trim());
}
}
class Order implements Comparable<Order>{
int orderId;
int finishedTime;
public Order(int orderId, int finishedTime) {
this.orderId = orderId;
this.finishedTime = finishedTime;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", finishedTime=" + finishedTime +
'}';
}
@Override
public int compareTo(Order o) {
if (this.finishedTime < o.finishedTime)
return -1;
return 1;
}
}
| UTF-8 | Java | 1,199 | java | JimAndTheOrders.java | Java | [
{
"context": "nner;\nimport java.util.TreeSet;\n\n/**\n * Created by lakshitha on 7/14/16.\n */\npublic class JimAndTheOrders {\n\n ",
"end": 80,
"score": 0.9981589317321777,
"start": 71,
"tag": "USERNAME",
"value": "lakshitha"
}
] | null | [] | import java.util.Scanner;
import java.util.TreeSet;
/**
* Created by lakshitha on 7/14/16.
*/
public class JimAndTheOrders {
public static void main(String[] args) {
TreeSet <Order> treeSet = new TreeSet<Order>();
StringBuilder stringBuilder = new StringBuilder();
Scanner s1 = new Scanner(System.in);
int orders = s1.nextInt();
for (int i = 0; i < orders; i++){
treeSet.add(new Order(i+1,s1.nextInt()+s1.nextInt()));
}
for (Order o : treeSet)
stringBuilder.append(o.orderId + " ");
System.out.println(stringBuilder.toString().trim());
}
}
class Order implements Comparable<Order>{
int orderId;
int finishedTime;
public Order(int orderId, int finishedTime) {
this.orderId = orderId;
this.finishedTime = finishedTime;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", finishedTime=" + finishedTime +
'}';
}
@Override
public int compareTo(Order o) {
if (this.finishedTime < o.finishedTime)
return -1;
return 1;
}
}
| 1,199 | 0.565471 | 0.554629 | 53 | 21.622641 | 20.030378 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396226 | false | false | 8 |
f26a7f9d7696346c327ba2f30bafdf816b4c5a36 | 5,514,738,053,881 | 464891ec6946c6acc7ebbb10c97131f09f4eb053 | /app/src/main/java/com/sin/cainiao/Utils/View/BackHandledFragment.java | 798c063c2b3adf192d05d0d0264b94035f8fd055 | [] | no_license | SinLucifer/CaiNiao | https://github.com/SinLucifer/CaiNiao | 476060b9759f1ee6531ecc28798c5aeabf18c0c4 | a54c3e12ea9349f6db20fa65b0688317f2811a3a | refs/heads/master | 2020-04-17T16:59:08.220000 | 2017-02-23T14:07:53 | 2017-02-23T14:07:53 | 67,760,322 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sin.cainiao.utils.View;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public abstract class BackHandledFragment extends Fragment {
protected BackHandledInterface mBackHandledInterface;
public abstract boolean onBackPressed();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!(getActivity() instanceof BackHandledInterface)){
throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
}else{
this.mBackHandledInterface = (BackHandledInterface)getActivity();
}
}
@Override
public void onStart() {
super.onStart();
mBackHandledInterface.setSelectedFragment(this);
}
@Override
public void onDetach() {
super.onDetach();
mBackHandledInterface = null;
}
}
| UTF-8 | Java | 954 | java | BackHandledFragment.java | Java | [] | null | [] | package com.sin.cainiao.utils.View;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public abstract class BackHandledFragment extends Fragment {
protected BackHandledInterface mBackHandledInterface;
public abstract boolean onBackPressed();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!(getActivity() instanceof BackHandledInterface)){
throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
}else{
this.mBackHandledInterface = (BackHandledInterface)getActivity();
}
}
@Override
public void onStart() {
super.onStart();
mBackHandledInterface.setSelectedFragment(this);
}
@Override
public void onDetach() {
super.onDetach();
mBackHandledInterface = null;
}
}
| 954 | 0.701258 | 0.70021 | 35 | 26.257143 | 25.540268 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371429 | false | false | 8 |
20177db388bb84f5d216502f24008f4abe9730ee | 31,894,427,187,972 | ce94827779be7eb78966a9ced976f34494bce0bb | /app/src/main/java/com/venus/android/view/register/PhoneVerificationCodeView.java | de8b115f949cffaf3c7c2c0395c30257ce2fc991 | [] | no_license | levuon/Venus-android | https://github.com/levuon/Venus-android | deea4c847baf3fd9a4f8bd7307028323d3afd128 | c5cd95d26639dd896944a0034c5c263590835196 | refs/heads/master | 2021-01-19T21:01:53.606000 | 2017-04-18T07:21:03 | 2017-04-18T07:21:03 | 88,594,326 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.venus.android.view.register;
import com.venus.android.view.FormView;
public interface PhoneVerificationCodeView extends FormView {
void navigateToMainActivity();
void goLoginActivity();
void clearPassWordText();
void focusConfirmPasswordEdit();
void onSetCodeToEdit(String str);
void onTvCountDownEnabled(boolean z);
void setCountDownText(String str);
}
| UTF-8 | Java | 403 | java | PhoneVerificationCodeView.java | Java | [] | null | [] | package com.venus.android.view.register;
import com.venus.android.view.FormView;
public interface PhoneVerificationCodeView extends FormView {
void navigateToMainActivity();
void goLoginActivity();
void clearPassWordText();
void focusConfirmPasswordEdit();
void onSetCodeToEdit(String str);
void onTvCountDownEnabled(boolean z);
void setCountDownText(String str);
}
| 403 | 0.756824 | 0.756824 | 20 | 19.15 | 20.030664 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 8 |
3f2651733d0b7083b5d8d261b5b09c86a68401d9 | 12,945,031,468,829 | 390df9d587eab83b1a8a16abb973fe8709022c8d | /app/src/main/java/com/example/iryna/daggerexample/MainActivity.java | 92bdf52f0e87e721a887fe250b79f1e9ec02a60e | [] | no_license | Luckygirlllll/MVPexample | https://github.com/Luckygirlllll/MVPexample | 97a677067e98f938487ae29a575dd74e9626b149 | beff4a8bafce4f67c383948f52e1997d0b5c5210 | refs/heads/master | 2021-06-01T02:26:36.592000 | 2016-08-17T14:48:14 | 2016-08-17T14:48:14 | 65,915,742 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.iryna.daggerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.iryna.daggerexample.DI.MainActivityModule;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements MainView {
@BindView(R.id.btGet)
Button btGet;
@BindView(R.id.btSet)
Button btnSet;
@BindView(R.id.etInsertText)
EditText etInsertText;
@BindView(R.id.tvShowText)
TextView tvShowTextt;
@Inject
MainPresenter mMainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
App.getInstance(this).getAppComponent().plus(new MainActivityModule(this)).inject(this);
}
@OnClick(R.id.btGet)
public void getText(){
mMainPresenter.getData();
}
@OnClick(R.id.btSet)
public void setText(){
mMainPresenter.addDate(etInsertText.getText().toString());
}
@Override
public void done() {
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
etInsertText.setText("");
}
@Override
public void showData(String data) {
tvShowTextt.setText(data);
}
}
| UTF-8 | Java | 1,516 | java | MainActivity.java | Java | [] | null | [] | package com.example.iryna.daggerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.iryna.daggerexample.DI.MainActivityModule;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements MainView {
@BindView(R.id.btGet)
Button btGet;
@BindView(R.id.btSet)
Button btnSet;
@BindView(R.id.etInsertText)
EditText etInsertText;
@BindView(R.id.tvShowText)
TextView tvShowTextt;
@Inject
MainPresenter mMainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
App.getInstance(this).getAppComponent().plus(new MainActivityModule(this)).inject(this);
}
@OnClick(R.id.btGet)
public void getText(){
mMainPresenter.getData();
}
@OnClick(R.id.btSet)
public void setText(){
mMainPresenter.addDate(etInsertText.getText().toString());
}
@Override
public void done() {
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
etInsertText.setText("");
}
@Override
public void showData(String data) {
tvShowTextt.setText(data);
}
}
| 1,516 | 0.708443 | 0.707784 | 61 | 23.852459 | 20.92362 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false | 8 |
90f16148b8c21ea83716c6735a35d745cdef3216 | 28,698,971,512,419 | fc5479147896931d3e931ef83d62c6f0aa2a53ea | /mooc-2013-OOProgrammingWithJava-PART2/week8-week8_16.SkiJumping/src/JumperList.java | 0b648a43d39bc79f6654fb59dd4942ced91d02f5 | [] | no_license | stchunduru/moocfi-Java-Programming-Part-2 | https://github.com/stchunduru/moocfi-Java-Programming-Part-2 | 5840348ac20216bd72c5675f81e50000fe77ac03 | f01c8302e6b383b9b08b0a0663977b6fae3d6baa | refs/heads/master | 2022-11-06T13:56:44.658000 | 2020-06-25T14:55:50 | 2020-06-25T14:55:50 | 274,936,519 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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.
*/
/**
*
* @author Cruzer
*/
import java.util.*;
public class JumperList {
private List<Jumper> list;
private int roundcount;
public JumperList(){
this.list = new ArrayList<Jumper>();
roundcount = 1;
}
//Adds jumper
public void add(String name){
this.list.add(new Jumper(name));
}
//Calls jump method on all jumpers. Orders list by ascending for jump order;
public void jump(){
for(Jumper x : this.list){
x.jump();
}
Collections.sort(this.list, Collections.reverseOrder());
}
public void roundIncrement(){
this.roundcount += 1;
}
//Returns round number
public int roundCount(){
return this.roundcount;
}
// Prints jumpers round stats
public void printJumpstats(){
for(Jumper x : this.list){
System.out.println(" " + x.getName());
System.out.println(" length: " + x.getJump());
System.out.println(" judge votes: " + x.getJudgeScores());
}
}
//Prints jumpers in order of total points.
public void printJumpers(){
int x = 1;
for(Jumper jumpman : this.list){
System.out.println(" " + x + ". " + this.list.get((x-1)));
x += 1;
}
}
//Used for final results. Orders list by points descending
public void printWinners(){
Collections.sort(list);
for(int x = 0; x < this.list.size(); x++){
System.out.println((x+1) + " " + this.list.get(x));
System.out.println(" " + this.list.get(x).jumpLengths());
}
}
}
| UTF-8 | Java | 1,878 | java | JumperList.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author Cruzer\n */\nimport java.util.*;\npublic class JumperList {",
"end": 210,
"score": 0.9746528267860413,
"start": 204,
"tag": "NAME",
"value": "Cruzer"
}
] | null | [] | /*
* 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.
*/
/**
*
* @author Cruzer
*/
import java.util.*;
public class JumperList {
private List<Jumper> list;
private int roundcount;
public JumperList(){
this.list = new ArrayList<Jumper>();
roundcount = 1;
}
//Adds jumper
public void add(String name){
this.list.add(new Jumper(name));
}
//Calls jump method on all jumpers. Orders list by ascending for jump order;
public void jump(){
for(Jumper x : this.list){
x.jump();
}
Collections.sort(this.list, Collections.reverseOrder());
}
public void roundIncrement(){
this.roundcount += 1;
}
//Returns round number
public int roundCount(){
return this.roundcount;
}
// Prints jumpers round stats
public void printJumpstats(){
for(Jumper x : this.list){
System.out.println(" " + x.getName());
System.out.println(" length: " + x.getJump());
System.out.println(" judge votes: " + x.getJudgeScores());
}
}
//Prints jumpers in order of total points.
public void printJumpers(){
int x = 1;
for(Jumper jumpman : this.list){
System.out.println(" " + x + ". " + this.list.get((x-1)));
x += 1;
}
}
//Used for final results. Orders list by points descending
public void printWinners(){
Collections.sort(list);
for(int x = 0; x < this.list.size(); x++){
System.out.println((x+1) + " " + this.list.get(x));
System.out.println(" " + this.list.get(x).jumpLengths());
}
}
}
| 1,878 | 0.547923 | 0.544196 | 70 | 25.828571 | 22.861053 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371429 | false | false | 8 |
65ccd84f00840d82425093b58719bee99e9077f7 | 9,990,093,974,866 | 2244c59575643d0763e9599f8dcc138a0633b718 | /myHessel/src/admin/ArrayOfPrimitives.java | 883e10c149ff86b0d8980d19e37959e9995b3feb | [] | no_license | Hazzle/Javatraining | https://github.com/Hazzle/Javatraining | a8cee2827af5490da32a0fa8d43ea5063a1c058d | 1e3b69dc2270fe1a1e45df0f275e2b02bc548f44 | refs/heads/master | 2016-08-07T17:26:54.211000 | 2014-10-03T14:19:20 | 2014-10-03T14:19:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package admin;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayOfPrimitives {
public static void main(String[] args) {
// Write code here, to create and use an array of primitives.
int numElements = 0;
int numPositive = 0;
Scanner myScanner = new Scanner(System.in);
System.out.println("How many elements would you like in your array?");
numElements = myScanner.nextInt();
double[] myArray = new double[numElements];
for (int i = 0; i < myArray.length; i++) {
System.out.println("Voer nummer " + (i+1) + " van de " + numElements + " + in:");
myArray[i] = myScanner.nextDouble();
if (myArray[i] > 0 ) {
numPositive++;
}
}
System.out.println(Arrays.toString(myArray));
System.out.println("Het aantal positieve nummers is " + numPositive);
}
} | UTF-8 | Java | 819 | java | ArrayOfPrimitives.java | Java | [] | null | [] | package admin;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayOfPrimitives {
public static void main(String[] args) {
// Write code here, to create and use an array of primitives.
int numElements = 0;
int numPositive = 0;
Scanner myScanner = new Scanner(System.in);
System.out.println("How many elements would you like in your array?");
numElements = myScanner.nextInt();
double[] myArray = new double[numElements];
for (int i = 0; i < myArray.length; i++) {
System.out.println("Voer nummer " + (i+1) + " van de " + numElements + " + in:");
myArray[i] = myScanner.nextDouble();
if (myArray[i] > 0 ) {
numPositive++;
}
}
System.out.println(Arrays.toString(myArray));
System.out.println("Het aantal positieve nummers is " + numPositive);
}
} | 819 | 0.664225 | 0.65812 | 41 | 19 | 23.946077 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.390244 | false | false | 8 |
c3956924e75bf8cbf0cb0d3a758569d3a7f64f9e | 19,516,331,448,554 | be7fe678d3d695f18380e0b08a5946706998ec43 | /ServiceLayer/src/br/ifes/les/dominio/entidade/Aliquota.java | a34cd1d8a07c2a339da6a573a60367477e3214bb | [] | no_license | diegopasti/faculdade.les.padraologicanegocio.servicelayer | https://github.com/diegopasti/faculdade.les.padraologicanegocio.servicelayer | 95e4809db3cbf7b2ae24b48093cc991c95664710 | cf597bcf2f22f0197abe36ea4945805db65b27f2 | refs/heads/master | 2016-09-05T22:41:50.827000 | 2015-07-05T21:10:23 | 2015-07-05T21:10:23 | 38,580,094 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.ifes.les.dominio.entidade;
public interface Aliquota {
public Double calcularValor(Double v);
}
| UTF-8 | Java | 119 | java | Aliquota.java | Java | [] | null | [] | package br.ifes.les.dominio.entidade;
public interface Aliquota {
public Double calcularValor(Double v);
}
| 119 | 0.722689 | 0.722689 | 7 | 15 | 17.096365 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 8 |
29633e394d60141c9aa8fb03556a7e6eaf089e4e | 15,642,270,944,727 | c6d93152ab18b0e282960b8ff224a52c88efb747 | /huntkey/code/sceo-commons-service/sceo-common-service-provider/src/main/java/com/huntkey/rx/sceo/common/service/provider/controller/EmailLogController.java | ec4d21b6f24bb302a27741458b317a8178a1e51a | [] | no_license | BAT6188/company-database | https://github.com/BAT6188/company-database | adfe5d8b87b66cd51efd0355e131de164b69d3f9 | 40d0342345cadc51ca2555840e32339ca0c83f51 | refs/heads/master | 2023-05-23T22:18:22.702000 | 2018-12-25T00:58:15 | 2018-12-25T00:58:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huntkey.rx.sceo.common.service.provider.controller;
import com.huntkey.rx.commons.utils.rest.Result;
import com.huntkey.rx.sceo.common.service.common.model.to.SimpleEmailTO;
import com.huntkey.rx.sceo.common.service.provider.service.EmailLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by zhaomj on 2017/4/28.
*/
@RestController
@RequestMapping("/email")
public class EmailLogController {
@Autowired
private EmailLogService emailLogService;
@RequestMapping(method = RequestMethod.POST)
public Result sendSmsPost(@RequestBody SimpleEmailTO to){
return emailLogService.sendSimpleEmail(to);
}
}
| UTF-8 | Java | 924 | java | EmailLogController.java | Java | [
{
"context": "bind.annotation.RestController;\n\n/**\n * Created by zhaomj on 2017/4/28.\n */\n@RestController\n@RequestMapping",
"end": 599,
"score": 0.9996387362480164,
"start": 593,
"tag": "USERNAME",
"value": "zhaomj"
}
] | null | [] | package com.huntkey.rx.sceo.common.service.provider.controller;
import com.huntkey.rx.commons.utils.rest.Result;
import com.huntkey.rx.sceo.common.service.common.model.to.SimpleEmailTO;
import com.huntkey.rx.sceo.common.service.provider.service.EmailLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by zhaomj on 2017/4/28.
*/
@RestController
@RequestMapping("/email")
public class EmailLogController {
@Autowired
private EmailLogService emailLogService;
@RequestMapping(method = RequestMethod.POST)
public Result sendSmsPost(@RequestBody SimpleEmailTO to){
return emailLogService.sendSimpleEmail(to);
}
}
| 924 | 0.808442 | 0.800866 | 26 | 34.53846 | 26.602821 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 8 |
9e3f23c725995433972d589d906cb9d2c9907bb1 | 28,192,165,340,352 | e642e6c97c0b5ef6b9e0c5f2c8302383e925ffc3 | /app/src/main/java/com/enipro/presentation/viewholders/FeedCommentViewHolder.java | 35878d9df97897fce46f22f4ffa97fa4e585bb23 | [] | no_license | afrikgenius/enipro-mobile | https://github.com/afrikgenius/enipro-mobile | 6cf9514139e0612331733e84876f9f2b9ed40257 | 81a9bff1f593b5b53bcf765e15862bb5d00bdd7d | refs/heads/master | 2022-02-19T22:10:51.540000 | 2018-09-15T23:48:42 | 2018-09-15T23:48:42 | 206,146,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.enipro.presentation.viewholders;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.enipro.R;
import com.enipro.data.remote.model.FeedComment;
import com.enipro.databinding.CommentItemBinding;
public class FeedCommentViewHolder extends RecyclerView.ViewHolder {
private Context context;
private CommentItemBinding binding;
public FeedCommentViewHolder(Context context, CommentItemBinding binding) {
super(binding.getRoot());
this.context = context;
this.binding = binding;
}
public void bind(FeedComment comment) {
binding.setComment(comment);
// If there is a comment image, load it otherwise remove view
if (comment.getComment_image() == null)
((ViewGroup) binding.commentImage.getParent()).removeView(binding.commentImage);
else {
binding.commentImage.setVisibility(View.VISIBLE);
Glide.with(context)
.load(comment.getComment_image())
.apply(new RequestOptions().placeholder(R.drawable.bg_image))
.apply(new RequestOptions().centerCrop())
.apply(new RequestOptions().fitCenter())
.apply(new RequestOptions().transform(new RoundedCorners(10)))
.into(binding.commentImage);
}
}
}
| UTF-8 | Java | 1,587 | java | FeedCommentViewHolder.java | Java | [] | null | [] | package com.enipro.presentation.viewholders;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.enipro.R;
import com.enipro.data.remote.model.FeedComment;
import com.enipro.databinding.CommentItemBinding;
public class FeedCommentViewHolder extends RecyclerView.ViewHolder {
private Context context;
private CommentItemBinding binding;
public FeedCommentViewHolder(Context context, CommentItemBinding binding) {
super(binding.getRoot());
this.context = context;
this.binding = binding;
}
public void bind(FeedComment comment) {
binding.setComment(comment);
// If there is a comment image, load it otherwise remove view
if (comment.getComment_image() == null)
((ViewGroup) binding.commentImage.getParent()).removeView(binding.commentImage);
else {
binding.commentImage.setVisibility(View.VISIBLE);
Glide.with(context)
.load(comment.getComment_image())
.apply(new RequestOptions().placeholder(R.drawable.bg_image))
.apply(new RequestOptions().centerCrop())
.apply(new RequestOptions().fitCenter())
.apply(new RequestOptions().transform(new RoundedCorners(10)))
.into(binding.commentImage);
}
}
}
| 1,587 | 0.68305 | 0.681159 | 44 | 35.06818 | 26.237896 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
9a8282b9d9f4aa373b2ac82c82f66c1e64859d0f | 32,298,154,068,749 | f1fe2f477110e35fe051151b3fb885a6c7e95555 | /src/medium/_413/Solution.java | d0980f60f4e7e3dafd1d5f01ac67176dc66c88a7 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jsyjst/LeetCode | https://github.com/jsyjst/LeetCode | c0170bad7c51e38c652ffcc13ec72b591e0c363f | 396a1584333eb4c8874898e312bfeb4482c1182b | refs/heads/master | 2022-09-05T09:26:24.074000 | 2022-08-07T11:18:43 | 2022-08-07T11:18:43 | 183,161,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package medium._413;
/**
* <pre>
* author : 残渊
* time : 2019/10/12
* desc : 数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。
* 如果满足以下条件,则称子数组(P, Q)为等差数组:元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。
* 函数要返回数组 A 中所有为等差数组的子数组个数。
* </pre>
*/
public class Solution {
/**
* A = [1, 2, 3, 4]
* 返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
*/
public int numberOfArithmeticSlices(int[] A) {
int n = A.length;
if(n<3) return 0;
int[] dp = new int[n];
int res = 0;
for (int i = 2; i<n ; i++) {
if(A[i]+A[i-2]==2*A[i-1]){
dp[i] = dp[i-1]+1;
res+=dp[i];
}
}
return res;
}
//公式法,更优
public int numberOfArithmeticSlicesBetter(int[] A) {
int n = A.length;
if(n<3) return 0;
int count = 0;
int res = 0;
for (int i = 2; i<n ; i++) {
if(A[i]+A[i-2]==2*A[i-1]){
count++;
}else {
res+=count*(count+1)/2;
count = 0;
}
}
return res+count*(count+1)/2;
}
}
| UTF-8 | Java | 1,434 | java | Solution.java | Java | [
{
"context": "package medium._413;\n\n/**\n * <pre>\n * author : 残渊\n * time : 2019/10/12\n * desc : 数组 A 包",
"end": 53,
"score": 0.999665379524231,
"start": 51,
"tag": "NAME",
"value": "残渊"
}
] | null | [] | package medium._413;
/**
* <pre>
* author : 残渊
* time : 2019/10/12
* desc : 数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。
* 如果满足以下条件,则称子数组(P, Q)为等差数组:元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。
* 函数要返回数组 A 中所有为等差数组的子数组个数。
* </pre>
*/
public class Solution {
/**
* A = [1, 2, 3, 4]
* 返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
*/
public int numberOfArithmeticSlices(int[] A) {
int n = A.length;
if(n<3) return 0;
int[] dp = new int[n];
int res = 0;
for (int i = 2; i<n ; i++) {
if(A[i]+A[i-2]==2*A[i-1]){
dp[i] = dp[i-1]+1;
res+=dp[i];
}
}
return res;
}
//公式法,更优
public int numberOfArithmeticSlicesBetter(int[] A) {
int n = A.length;
if(n<3) return 0;
int count = 0;
int res = 0;
for (int i = 2; i<n ; i++) {
if(A[i]+A[i-2]==2*A[i-1]){
count++;
}else {
res+=count*(count+1)/2;
count = 0;
}
}
return res+count*(count+1)/2;
}
}
| 1,434 | 0.401985 | 0.358147 | 48 | 24.1875 | 19.793365 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 8 |
41da532ff2425d1a9699bcd2ec2e72891f164263 | 11,605,001,662,724 | b67aa2482f65ae299fc63b1e69b8e0ca34d26afc | /src/main/java/io/github/moulberry/notenoughupdates/questing/requirements/RequirementLocation.java | 0e995f34732fc6f90c75155099ad65a13dd86eae | [
"LicenseRef-scancode-proprietary-license"
] | permissive | Tuwuppy/NotEnoughUpdates | https://github.com/Tuwuppy/NotEnoughUpdates | 74aa5a9f9f805688c03ca34a54cc6e92630a777f | e93b6f7bceddad33d21cc3a48f7778b45bf4d820 | refs/heads/master | 2022-12-30T17:29:56.306000 | 2020-10-23T20:15:37 | 2020-10-23T20:15:37 | 306,479,526 | 0 | 0 | MIT | true | 2020-10-23T00:29:51 | 2020-10-22T23:15:07 | 2020-10-22T23:15:09 | 2020-10-23T00:29:50 | 293,211 | 0 | 0 | 0 | null | false | false | package io.github.moulberry.notenoughupdates.questing.requirements;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
public class RequirementLocation extends Requirement {
private int x;
private int y;
private int z;
private float radius;
public RequirementLocation(int x, int y, int z, float radius, Requirement... preconditions) {
super(preconditions);
this.x = x;
this.y = y;
this.z = z;
this.radius = radius;
}
@Override
public void updateRequirement() {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
completed = player.getDistance(x, y, z) < radius;
}
}
| UTF-8 | Java | 707 | java | RequirementLocation.java | Java | [
{
"context": "package io.github.moulberry.notenoughupdates.questing.requirements;\n\nimport n",
"end": 27,
"score": 0.9979529976844788,
"start": 18,
"tag": "USERNAME",
"value": "moulberry"
}
] | null | [] | package io.github.moulberry.notenoughupdates.questing.requirements;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
public class RequirementLocation extends Requirement {
private int x;
private int y;
private int z;
private float radius;
public RequirementLocation(int x, int y, int z, float radius, Requirement... preconditions) {
super(preconditions);
this.x = x;
this.y = y;
this.z = z;
this.radius = radius;
}
@Override
public void updateRequirement() {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
completed = player.getDistance(x, y, z) < radius;
}
}
| 707 | 0.673267 | 0.673267 | 26 | 26.192308 | 24.922987 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 8 |
ebd4fab1a9126f241ffb2d3b3611c51200171b0d | 19,318,762,935,109 | 55889712a9adf03489f4b6402a48c1a854d70321 | /ignite_easyticket_client_v1.0/src/com/ignite/mm/ticketing/application/MyErrorHandler.java | b29a62da4de3d0f565d522c0e7ddee1164c898c4 | [] | no_license | ignitemyanmar/POSAndroid | https://github.com/ignitemyanmar/POSAndroid | 7b346b5a62a00d0db576cc739776ea80dd876a8f | 9614177e73fe019d42afc283ed23877fccf8ab75 | refs/heads/master | 2021-05-01T09:30:56.967000 | 2015-06-08T04:30:23 | 2015-06-08T04:30:23 | 27,748,660 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ignite.mm.ticketing.application;
import android.util.Log;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;
import retrofit.client.Response;
class MyErrorHandler implements ErrorHandler {
public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null) {
Log.d("Retrofix","Reponse Status"+ r.getStatus() +" , Reason: "+r.getReason());
}
return cause;
}
} | UTF-8 | Java | 445 | java | MyErrorHandler.java | Java | [] | null | [] | package com.ignite.mm.ticketing.application;
import android.util.Log;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;
import retrofit.client.Response;
class MyErrorHandler implements ErrorHandler {
public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null) {
Log.d("Retrofix","Reponse Status"+ r.getStatus() +" , Reason: "+r.getReason());
}
return cause;
}
} | 445 | 0.714607 | 0.714607 | 17 | 25.235294 | 22.683317 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.117647 | false | false | 8 |
ad46e2af10a5a077975fffc573a84c36db4f49e6 | 17,901,423,692,870 | 5a1872c1f19b978deb97d7ad30ac6f8a565bb2aa | /src/br/com/AD7/silasladislau/Arq.java | 940d7757b34b72cf48f1cbfab833839df0ff6cea | [] | no_license | splhead/ES | https://github.com/splhead/ES | 39a3611f4d44778f71394dab80c3a3bfef3c48f6 | 2abd6850d209a2fd78934c7a8a399571a84aac22 | refs/heads/master | 2020-05-17T02:07:18.941000 | 2014-08-08T12:41:58 | 2014-08-08T12:41:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.AD7.silasladislau;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.util.Log;
public class Arq {
Context c;
boolean existeArmazenamentoExterno = false;
boolean escreveArmazenamentoExterno = false;
private BroadcastReceiver mExternalStorageReceiver;
private File caminho;
private URL url;
// baixa um arquivo
public String download(String endereco)
{
try
{
url = new URL(endereco);
//if(usarArmazenamentoExterno())
//{
// caminho = new File(Environment.getExternalStorageDirectory().toString() + "/data/" + c.getPackageName()+ "/imagens/" +
// endereco.substring(endereco.lastIndexOf('/')+1));
//}
//else
//{
caminho = new File(c.getFilesDir() + "/imagens/" + endereco.substring(endereco.lastIndexOf('/')+1));
//}
long inicio = System.currentTimeMillis();
Log.d("Download","começando o download");
Log.d("Download","url: " + endereco);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int atual = 0;
while ((atual = bis.read()) != -1)
{
baf.append((byte) atual);
}
FileOutputStream fos = new FileOutputStream(caminho);
fos.write(baf.toByteArray());
fos.close();
Log.d("DownloadIndice","Download concluído em: " +
((System.currentTimeMillis() - inicio) / 1000) + " segundo(s)");
return null;
}//fim try
catch (IOException ioe)
{
Log.d("DownloadIndice", "Erro " + ioe );
System.exit(1);
}//fim catch
return null;
}//fim do método download
void atualizarEstadoArmazenamentoExterno() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status)) {
existeArmazenamentoExterno =
escreveArmazenamentoExterno = true;
} else if
(Environment.MEDIA_MOUNTED_READ_ONLY.equals
(status)) {
existeArmazenamentoExterno = true;
escreveArmazenamentoExterno = false;
} else {
existeArmazenamentoExterno =
escreveArmazenamentoExterno = false;
}
}
@SuppressWarnings("unused")
private boolean usarArmazenamentoExterno()
{
return existeArmazenamentoExterno && escreveArmazenamentoExterno;
}
void comecarAssistirArmazenamentoExterno() {
mExternalStorageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("test", "Storage: " + intent.getData());
atualizarEstadoArmazenamentoExterno();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
c.registerReceiver(mExternalStorageReceiver, filter);
atualizarEstadoArmazenamentoExterno();
}
void pararAssistirArmazenamentoExterno() {
c.unregisterReceiver(mExternalStorageReceiver);
}
} | UTF-8 | Java | 3,540 | java | Arq.java | Java | [] | null | [] | package br.com.AD7.silasladislau;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.util.Log;
public class Arq {
Context c;
boolean existeArmazenamentoExterno = false;
boolean escreveArmazenamentoExterno = false;
private BroadcastReceiver mExternalStorageReceiver;
private File caminho;
private URL url;
// baixa um arquivo
public String download(String endereco)
{
try
{
url = new URL(endereco);
//if(usarArmazenamentoExterno())
//{
// caminho = new File(Environment.getExternalStorageDirectory().toString() + "/data/" + c.getPackageName()+ "/imagens/" +
// endereco.substring(endereco.lastIndexOf('/')+1));
//}
//else
//{
caminho = new File(c.getFilesDir() + "/imagens/" + endereco.substring(endereco.lastIndexOf('/')+1));
//}
long inicio = System.currentTimeMillis();
Log.d("Download","começando o download");
Log.d("Download","url: " + endereco);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int atual = 0;
while ((atual = bis.read()) != -1)
{
baf.append((byte) atual);
}
FileOutputStream fos = new FileOutputStream(caminho);
fos.write(baf.toByteArray());
fos.close();
Log.d("DownloadIndice","Download concluído em: " +
((System.currentTimeMillis() - inicio) / 1000) + " segundo(s)");
return null;
}//fim try
catch (IOException ioe)
{
Log.d("DownloadIndice", "Erro " + ioe );
System.exit(1);
}//fim catch
return null;
}//fim do método download
void atualizarEstadoArmazenamentoExterno() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status)) {
existeArmazenamentoExterno =
escreveArmazenamentoExterno = true;
} else if
(Environment.MEDIA_MOUNTED_READ_ONLY.equals
(status)) {
existeArmazenamentoExterno = true;
escreveArmazenamentoExterno = false;
} else {
existeArmazenamentoExterno =
escreveArmazenamentoExterno = false;
}
}
@SuppressWarnings("unused")
private boolean usarArmazenamentoExterno()
{
return existeArmazenamentoExterno && escreveArmazenamentoExterno;
}
void comecarAssistirArmazenamentoExterno() {
mExternalStorageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("test", "Storage: " + intent.getData());
atualizarEstadoArmazenamentoExterno();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
c.registerReceiver(mExternalStorageReceiver, filter);
atualizarEstadoArmazenamentoExterno();
}
void pararAssistirArmazenamentoExterno() {
c.unregisterReceiver(mExternalStorageReceiver);
}
} | 3,540 | 0.664405 | 0.661012 | 114 | 30.035088 | 22.606445 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.842105 | false | false | 8 |
ba72103bb9ac06cc77f63e5b6333a153677251ec | 3,126,736,255,975 | 7dbdb9fa46488f45b36947a31e179cb4879ae17e | /toy-framework-myrpc/rpc/src/main/java/com/clpsz/myrpc/invoke/proxy/ImplPool.java | cc20ee2973ab29d026a492e3ca4660d7670a0355 | [] | no_license | clpsz/toys | https://github.com/clpsz/toys | 2fdad93b0c435ae9899c81cad98b151c5f016be4 | 354eeb4f64be8ac51556b389ea4bd0fcc77d0de2 | refs/heads/master | 2021-01-19T20:55:08.272000 | 2020-06-17T08:16:44 | 2020-06-17T08:16:44 | 88,576,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.clpsz.myrpc.invoke.proxy;
import com.clpsz.myrpc.invoke.sample.impl.FindGirlFriendServiceImpl;
import com.clpsz.myrpc.invoke.sample.impl.SampleAddServiceImpl;
import com.clpsz.myrpc.invoke.sample.impl.SampleSayHelloServiceImpl;
import java.util.HashMap;
import java.util.Map;
/**
* Created by peter.zuo on 2017/4/18.
*/
public class ImplPool {
private Map<String, Object> implMap = new HashMap<>();
private static ImplPool INSTANCE = new ImplPool();
static {
//TODO: 改成用SampleAddService.class作为key
INSTANCE.add("com.clpsz.myrpc.invoke.sample.SampleAddService", new SampleAddServiceImpl());
INSTANCE.add("com.clpsz.myrpc.invoke.sample.SampleSayHelloService", new SampleSayHelloServiceImpl());
INSTANCE.add("com.clpsz.myrpc.invoke.sample.FindGirlFriendService", new FindGirlFriendServiceImpl());
}
private ImplPool() {}
public void add(String interfaze, Object impl) {
implMap.put(interfaze, impl);
}
public Object getImpl(String interfaze) {
if (interfaze == null) {
throw new NullPointerException("接口名为空");
}
if (!implMap.containsKey(interfaze)) {
throw new IllegalArgumentException("该接口无对应的实现类: " + interfaze);
}
return implMap.get(interfaze);
}
public static ImplPool getInstance() {
return INSTANCE;
}
}
| UTF-8 | Java | 1,474 | java | ImplPool.java | Java | [
{
"context": "hMap;\r\nimport java.util.Map;\r\n\r\n/**\r\n * Created by peter.zuo on 2017/4/18.\r\n */\r\npublic class ImplPool {\r\n ",
"end": 330,
"score": 0.9983820915222168,
"start": 321,
"tag": "USERNAME",
"value": "peter.zuo"
}
] | null | [] | package com.clpsz.myrpc.invoke.proxy;
import com.clpsz.myrpc.invoke.sample.impl.FindGirlFriendServiceImpl;
import com.clpsz.myrpc.invoke.sample.impl.SampleAddServiceImpl;
import com.clpsz.myrpc.invoke.sample.impl.SampleSayHelloServiceImpl;
import java.util.HashMap;
import java.util.Map;
/**
* Created by peter.zuo on 2017/4/18.
*/
public class ImplPool {
private Map<String, Object> implMap = new HashMap<>();
private static ImplPool INSTANCE = new ImplPool();
static {
//TODO: 改成用SampleAddService.class作为key
INSTANCE.add("com.clpsz.myrpc.invoke.sample.SampleAddService", new SampleAddServiceImpl());
INSTANCE.add("com.clpsz.myrpc.invoke.sample.SampleSayHelloService", new SampleSayHelloServiceImpl());
INSTANCE.add("com.clpsz.myrpc.invoke.sample.FindGirlFriendService", new FindGirlFriendServiceImpl());
}
private ImplPool() {}
public void add(String interfaze, Object impl) {
implMap.put(interfaze, impl);
}
public Object getImpl(String interfaze) {
if (interfaze == null) {
throw new NullPointerException("接口名为空");
}
if (!implMap.containsKey(interfaze)) {
throw new IllegalArgumentException("该接口无对应的实现类: " + interfaze);
}
return implMap.get(interfaze);
}
public static ImplPool getInstance() {
return INSTANCE;
}
}
| 1,474 | 0.669456 | 0.664575 | 46 | 29.173914 | 30.488276 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 8 |
894dd97098b674b01561084ef94a90ed53d5b71d | 28,887,950,045,103 | 37a654c7e1baca800e175c40c5189af29b757d66 | /enployeemanage/src/com/bjsxt/job/service/impl/TPositionServiceImpl.java | 651360b6bdefeed11c18a02f0545964d78ca116d | [] | no_license | chenpengyu119/ServletDemo | https://github.com/chenpengyu119/ServletDemo | 0ed669ab523df34451e1bc6c2fc61f37bebc774f | 27f4cac7e0a0bbdc2bde8d547e30747331dfa9ea | refs/heads/master | 2020-08-29T21:06:54.647000 | 2019-10-29T01:01:14 | 2019-10-29T01:01:14 | 218,174,694 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bjsxt.job.service.impl;
import com.bjsxt.job.dao.impl.TPositionDaoImpl;
import com.bjsxt.job.service.TPositionService;
import java.sql.Date;
/**
* @author pengyu
*/
public class TPositionServiceImpl implements TPositionService {
@Override
public int publish(String pname, double minsal, double maxsal, Date releasedate, String cname) {
return new TPositionDaoImpl().add(pname, minsal, maxsal, releasedate, cname);
}
@Override
public int del(String pname) {
return new TPositionDaoImpl().del(pname);
}
}
| UTF-8 | Java | 563 | java | TPositionServiceImpl.java | Java | [
{
"context": "ionService;\n\nimport java.sql.Date;\n\n/**\n * @author pengyu\n */\npublic class TPositionServiceImpl implements ",
"end": 177,
"score": 0.9986498355865479,
"start": 171,
"tag": "USERNAME",
"value": "pengyu"
}
] | null | [] | package com.bjsxt.job.service.impl;
import com.bjsxt.job.dao.impl.TPositionDaoImpl;
import com.bjsxt.job.service.TPositionService;
import java.sql.Date;
/**
* @author pengyu
*/
public class TPositionServiceImpl implements TPositionService {
@Override
public int publish(String pname, double minsal, double maxsal, Date releasedate, String cname) {
return new TPositionDaoImpl().add(pname, minsal, maxsal, releasedate, cname);
}
@Override
public int del(String pname) {
return new TPositionDaoImpl().del(pname);
}
}
| 563 | 0.719361 | 0.719361 | 23 | 23.47826 | 28.559427 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false | 8 |
1fb3ac973f2c4c31b332a906c834aa95e180fa57 | 5,162,550,709,074 | 58ed54d66cbd4d32e45819c72d00e33f4376ca23 | /src/ee/raidoseene/releaseplanner/gui/FixedDependencyDialog.java | bce4b38ccf3717c35c9e9ee0d21f6960a13d3560 | [] | no_license | raidoseene/Release-Planner | https://github.com/raidoseene/Release-Planner | 02a5ebf5d492f375c1feb7c131d00d7969965ecc | 40a872c1f64d92e8acde2bca4b2c21c761ccb825 | refs/heads/master | 2021-01-21T12:47:42.303000 | 2016-04-03T15:51:02 | 2016-04-03T15:51:02 | 30,310,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 ee.raidoseene.releaseplanner.gui;
import ee.raidoseene.releaseplanner.backend.ProjectManager;
import ee.raidoseene.releaseplanner.datamodel.Feature;
import ee.raidoseene.releaseplanner.datamodel.Dependencies;
import ee.raidoseene.releaseplanner.datamodel.Release;
import ee.raidoseene.releaseplanner.datamodel.Releases;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
*
* @author Raido Seene
*/
public class FixedDependencyDialog extends JDialog {
private final Feature feature;
private final JComboBox release;
private boolean state = false;
private int type;
private FixedDependencyDialog(Feature f, int type) {
this.type = type;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Dimension size = new Dimension(400, 200);
this.setLocation((screen.width - size.width) >> 1, (screen.height - size.height) >> 1);
this.setSize(size);
this.setResizable(false);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setTitle("Select Release");
this.setModal(true);
JPanel cont = new JPanel(new BorderLayout(10, 10));
cont.setBorder(new EmptyBorder(10, 10, 10, 10));
this.setContentPane(cont);
this.feature = f;
Container c = new Container();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
Releases releases = ProjectManager.getCurrentProject().getReleases();
int count = releases.getReleaseCount();
this.release = new JComboBox();
for (int i = 0; i < count; i++) {
this.release.addItem(releases.getRelease(i).getName());
}
c.add(this.release);
c.add(new JLabel("Release"));
cont.add(BorderLayout.PAGE_START, c);
c = new Container();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
cont.add(BorderLayout.PAGE_END, c);
JButton btn = new JButton("OK");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Releases rels = ProjectManager.getCurrentProject().getReleases();
Release rel = rels.getRelease(FixedDependencyDialog.this.release.getSelectedIndex());
Dependencies ids = ProjectManager.getCurrentProject().getDependencies();
ids.addReleaseDependency(FixedDependencyDialog.this.feature, rel, FixedDependencyDialog.this.type, false, false);
FixedDependencyDialog.this.state = true;
FixedDependencyDialog.this.dispose();
} catch (Exception ex) {
FixedDependencyDialog.this.dispose();
Messenger.showError(ex, null);
}
}
});
c.add(btn);
btn = new JButton("Cancel");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
FixedDependencyDialog.this.dispose();
} catch (Throwable t) {
t.printStackTrace();
}
}
});
c.add(btn);
}
public static boolean showFixedDependencyDialog(Feature f, int type) {
FixedDependencyDialog dialog = new FixedDependencyDialog(f, type);
dialog.setVisible(true);
return dialog.state;
}
}
| UTF-8 | Java | 4,022 | java | FixedDependencyDialog.java | Java | [
{
"context": "javax.swing.border.EmptyBorder;\n\n/**\n *\n * @author Raido Seene\n */\npublic class FixedDependencyDialog extends JD",
"end": 933,
"score": 0.9998656511306763,
"start": 922,
"tag": "NAME",
"value": "Raido Seene"
}
] | null | [] | /*
* 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 ee.raidoseene.releaseplanner.gui;
import ee.raidoseene.releaseplanner.backend.ProjectManager;
import ee.raidoseene.releaseplanner.datamodel.Feature;
import ee.raidoseene.releaseplanner.datamodel.Dependencies;
import ee.raidoseene.releaseplanner.datamodel.Release;
import ee.raidoseene.releaseplanner.datamodel.Releases;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
*
* @author <NAME>
*/
public class FixedDependencyDialog extends JDialog {
private final Feature feature;
private final JComboBox release;
private boolean state = false;
private int type;
private FixedDependencyDialog(Feature f, int type) {
this.type = type;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Dimension size = new Dimension(400, 200);
this.setLocation((screen.width - size.width) >> 1, (screen.height - size.height) >> 1);
this.setSize(size);
this.setResizable(false);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setTitle("Select Release");
this.setModal(true);
JPanel cont = new JPanel(new BorderLayout(10, 10));
cont.setBorder(new EmptyBorder(10, 10, 10, 10));
this.setContentPane(cont);
this.feature = f;
Container c = new Container();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
Releases releases = ProjectManager.getCurrentProject().getReleases();
int count = releases.getReleaseCount();
this.release = new JComboBox();
for (int i = 0; i < count; i++) {
this.release.addItem(releases.getRelease(i).getName());
}
c.add(this.release);
c.add(new JLabel("Release"));
cont.add(BorderLayout.PAGE_START, c);
c = new Container();
c.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
cont.add(BorderLayout.PAGE_END, c);
JButton btn = new JButton("OK");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Releases rels = ProjectManager.getCurrentProject().getReleases();
Release rel = rels.getRelease(FixedDependencyDialog.this.release.getSelectedIndex());
Dependencies ids = ProjectManager.getCurrentProject().getDependencies();
ids.addReleaseDependency(FixedDependencyDialog.this.feature, rel, FixedDependencyDialog.this.type, false, false);
FixedDependencyDialog.this.state = true;
FixedDependencyDialog.this.dispose();
} catch (Exception ex) {
FixedDependencyDialog.this.dispose();
Messenger.showError(ex, null);
}
}
});
c.add(btn);
btn = new JButton("Cancel");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
FixedDependencyDialog.this.dispose();
} catch (Throwable t) {
t.printStackTrace();
}
}
});
c.add(btn);
}
public static boolean showFixedDependencyDialog(Feature f, int type) {
FixedDependencyDialog dialog = new FixedDependencyDialog(f, type);
dialog.setVisible(true);
return dialog.state;
}
}
| 4,017 | 0.639483 | 0.633267 | 114 | 34.280701 | 26.116308 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807018 | false | false | 8 |
1f0b74b18e12affe2dda419c33e12c70457e9539 | 13,907,104,110,109 | 08662ed79a0486de8b73cc5042caeefef3f31fd5 | /Skeleton/src/settings/VideoSettings.java | cdb10195e545923cf3276fb999fb33318f6367c6 | [] | no_license | gyulaimark97/Skeleton | https://github.com/gyulaimark97/Skeleton | 28099f64939dc26647935493f3cd694efb7a8506 | 7bcebab1bd97916914febbc046476340154bce88 | refs/heads/master | 2020-04-09T18:52:00.981000 | 2018-12-09T11:45:51 | 2018-12-09T11:45:51 | 160,525,904 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package settings;
public class VideoSettings {
private Resolution screenResolution;
private int lightingQuality;
private int colorDepth;
private int details;
public Resolution getScreenResolution() {
return null;
}
public void setScreenResolution(Resolution screenResolution) {
}
public int getLightingQuality() {
return 0;
}
public void setLightingQuality(int lightingQuality) {
}
public int getColorDepth() {
return 0;
}
public void setColorDepth(int colorDepth) {
}
public int getDetails() {
return 0;
}
public void setDetails(int details) {
}
}
| UTF-8 | Java | 636 | java | VideoSettings.java | Java | [] | null | [] | package settings;
public class VideoSettings {
private Resolution screenResolution;
private int lightingQuality;
private int colorDepth;
private int details;
public Resolution getScreenResolution() {
return null;
}
public void setScreenResolution(Resolution screenResolution) {
}
public int getLightingQuality() {
return 0;
}
public void setLightingQuality(int lightingQuality) {
}
public int getColorDepth() {
return 0;
}
public void setColorDepth(int colorDepth) {
}
public int getDetails() {
return 0;
}
public void setDetails(int details) {
}
}
| 636 | 0.683962 | 0.679245 | 37 | 15.189189 | 17.303082 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false | 8 |
000c3c525fd364c66a2654a4ea1e563b21a06735 | 24,970,939,865,330 | 96d1336c0086a2acc53ed41eca5604d66962d13a | /src/com/interview/codechef/ccdsap_2/leetcode/sql/easy/ProjectEmployeeI.java | 73b10f39b309aed9f8079ba2834e0ba0bb533ea4 | [
"Apache-2.0"
] | permissive | prdp89/interview | https://github.com/prdp89/interview | 990e052d6bba5d2555a7b549d5bb5a12a92121ef | 04424ec1f13b0d1555382090d35c394b99a3a24b | refs/heads/master | 2022-12-27T16:44:41.690000 | 2020-09-30T13:21:44 | 2020-09-30T13:21:44 | 109,804,931 | 1 | 1 | null | true | 2017-11-07T08:05:26 | 2017-11-07T08:05:25 | 2017-11-07T06:18:28 | 2017-11-04T12:29:55 | 1,190 | 0 | 0 | 0 | null | false | null | package com.interview.codechef.ccdsap_2.leetcode.sql.easy;
public class ProjectEmployeeI {
/*
Table: Employee
Write an SQL query that reports the average experience years
of all the employees for each project, rounded to 2 digits.
The query result format is in the following example:
Project table:
+-------------+-------------+
| project_id | employee_id |
+-------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 4 |
+-------------+-------------+
Employee table:
+-------------+--------+------------------+
| employee_id | name | experience_years |
+-------------+--------+------------------+
| 1 | Khaled | 3 |
| 2 | Ali | 2 |
| 3 | John | 1 |
| 4 | Doe | 2 |
+-------------+--------+------------------+
Result table:
+-------------+---------------+
| project_id | average_years |
+-------------+---------------+
| 1 | 2.00 |
| 2 | 2.50 |
+-------------+---------------+
The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00
and for the second project is (3 + 2) / 2 = 2.50
*/
/*
# https://code.dennyzhang.com/project-employees-i
select project_id, round(avg(experience_years), 2) as average_years
from Project
inner join Employee
on Project.employee_id = Employee.employee_id
group by project_id
*/
}
| UTF-8 | Java | 1,824 | java | ProjectEmployeeI.java | Java | [
{
"context": "------+------------------+\n | 1 | Khaled | 3 |\n | 2 | Ali ",
"end": 897,
"score": 0.9996840357780457,
"start": 891,
"tag": "NAME",
"value": "Khaled"
},
{
"context": "haled | 3 |\n | 2 | A... | null | [] | package com.interview.codechef.ccdsap_2.leetcode.sql.easy;
public class ProjectEmployeeI {
/*
Table: Employee
Write an SQL query that reports the average experience years
of all the employees for each project, rounded to 2 digits.
The query result format is in the following example:
Project table:
+-------------+-------------+
| project_id | employee_id |
+-------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 4 |
+-------------+-------------+
Employee table:
+-------------+--------+------------------+
| employee_id | name | experience_years |
+-------------+--------+------------------+
| 1 | Khaled | 3 |
| 2 | Ali | 2 |
| 3 | John | 1 |
| 4 | Doe | 2 |
+-------------+--------+------------------+
Result table:
+-------------+---------------+
| project_id | average_years |
+-------------+---------------+
| 1 | 2.00 |
| 2 | 2.50 |
+-------------+---------------+
The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00
and for the second project is (3 + 2) / 2 = 2.50
*/
/*
# https://code.dennyzhang.com/project-employees-i
select project_id, round(avg(experience_years), 2) as average_years
from Project
inner join Employee
on Project.employee_id = Employee.employee_id
group by project_id
*/
}
| 1,824 | 0.346491 | 0.323465 | 58 | 30.448277 | 23.044315 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.87931 | false | false | 8 |
da032b6db577f6f12cbff445f1f149521dd12d01 | 24,970,939,869,381 | 7b733d7be68f0fa4df79359b57e814f5253fc72d | /system/services/src/com/percussion/services/security/data/PSCatalogerConfigurations.java | 9f917c9dc2a849aaa6fab13ce831467452e10ae9 | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"OFL-1.1",
"LGPL-2.0-or-later"
] | permissive | percussion/percussioncms | https://github.com/percussion/percussioncms | 318ac0ef62dce12eb96acf65fc658775d15d95ad | c8527de53c626097d589dc28dba4a4b5d6e4dd2b | refs/heads/development | 2023-08-31T14:34:09.593000 | 2023-08-31T14:04:23 | 2023-08-31T14:04:23 | 331,373,975 | 18 | 6 | Apache-2.0 | false | 2023-09-14T21:29:25 | 2021-01-20T17:03:38 | 2023-09-14T01:11:27 | 2023-09-14T21:29:24 | 174,353 | 10 | 5 | 60 | Java | false | false | /*
* Copyright 1999-2023 Percussion Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.percussion.services.security.data;
import com.percussion.services.security.IPSRoleMgr;
import com.percussion.services.security.data.PSCatalogerConfig.ConfigTypes;
import com.percussion.services.security.impl.PSRoleMgr;
import com.percussion.security.IPSRoleCataloger;
import com.percussion.security.IPSSubjectCataloger;
import com.percussion.utils.servlet.PSServletUtils;
import com.percussion.utils.spring.IPSBeanConfig;
import com.percussion.utils.spring.PSSpringBeanUtils;
import com.percussion.utils.spring.PSSpringConfiguration;
import com.percussion.utils.xml.PSInvalidXmlException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Manages persistence for the subject and role cataloger configurations,
* provides wiring of runtime instances with the {@link PSRoleMgr}
*/
public class PSCatalogerConfigurations implements IPSBeanConfig
{
/**
* Constant for the name of this class's bean configuration
*/
private static final String BEAN_NAME = "sys_catalogers";
/**
* Constant for the role catalogers property name
*/
private static final String ROLE_CATALOGERS = "roleCatalogers";
/**
* Constant for the subject catalogers property name
*/
private static final String SUBJECT_CATALOGERS = "subjectCatalogers";
/**
* Constant for the role mgr property name
*/
private static final String ROLE_MGR = "roleMgr";
/**
* Gets all defined cataloger configurations from the specified file.
*
* @param configFile The file to read from, may not be <code>null</code>.
*
* @return A list of cataloger configurations, never <code>null</code>, may
* be empty.
*
* @throws SAXException If the spring config file is malformed.
* @throws IOException If there is an error loading the spring config file.
* @throws PSInvalidXmlException If the spring config xml is invalid.
*/
public static List<PSCatalogerConfig> getCatalogerConfigs(File configFile)
throws PSInvalidXmlException, IOException, SAXException
{
if (configFile == null)
throw new IllegalArgumentException("configFile may not be null");
PSSpringConfiguration springConfig = new PSSpringConfiguration(
configFile);
PSCatalogerConfigurations configs =
(PSCatalogerConfigurations) springConfig.getBean(BEAN_NAME);
return configs.m_catalogerConfigs;
}
/**
* Saves the list of cataloger configurations in the specified file,
* replacing any that are currently defined.
*
* @param configs The configurations to save, may be empty, never
* <code>null</code>.
* @param configFile The file to save to, may not be <code>null</code>.
*
* @throws SAXException If the spring config file is malformed.
* @throws IOException If there is an error loading the spring config file.
* @throws PSInvalidXmlException If the spring config xml is invalid.
*/
public static void saveCatalogerConfigs(List<PSCatalogerConfig> configs,
File configFile)
throws PSInvalidXmlException, IOException, SAXException
{
if (configs == null)
throw new IllegalArgumentException("configs may not be null");
if (configFile == null)
throw new IllegalArgumentException("configFile may not be null");
PSCatalogerConfigurations mgr = new PSCatalogerConfigurations();
mgr.m_catalogerConfigs.addAll(configs);
PSSpringConfiguration springConfig = new PSSpringConfiguration(
configFile);
springConfig.setBean(mgr);
springConfig.save();
}
// see IPSBeanConfig interface
public Element toXml(Document doc)
{
if (doc == null)
throw new IllegalArgumentException("doc may not be null");
Element root = PSSpringBeanUtils.createBeanRootElement(
this, doc);
PSSpringBeanUtils.addBeanRef(root, ROLE_MGR,
PSServletUtils.ROLE_MGR_BEAN_NAME);
List<PSCatalogerConfig> subConfigs = new ArrayList<>();
List<PSCatalogerConfig> roleConfigs = new ArrayList<>();
for (PSCatalogerConfig config : m_catalogerConfigs)
{
if (config.getConfigType().equals(ConfigTypes.SUBJECT))
subConfigs.add(config);
else
roleConfigs.add(config);
}
PSSpringBeanUtils.addBeanProperty(root, SUBJECT_CATALOGERS, subConfigs);
PSSpringBeanUtils.addBeanProperty(root, ROLE_CATALOGERS, roleConfigs);
return root;
}
// see IPSBeanConfig interface
public void fromXml(Element source) throws PSInvalidXmlException
{
if (source == null)
throw new IllegalArgumentException("source may not be null");
PSSpringBeanUtils.validateBeanRootElement(getBeanName(), getClassName(),
source);
m_catalogerConfigs.clear();
// the first prop is the role mgr, ignore it
Element propEl = PSSpringBeanUtils.getNextPropertyElement(source, null,
ROLE_MGR);
propEl = PSSpringBeanUtils.getNextPropertyElement(source, propEl,
SUBJECT_CATALOGERS);
m_catalogerConfigs.addAll(getCatalogerList(propEl, ConfigTypes.SUBJECT));
propEl = PSSpringBeanUtils.getNextPropertyElement(source, propEl,
ROLE_CATALOGERS);
m_catalogerConfigs.addAll(getCatalogerList(propEl, ConfigTypes.ROLE));
}
/**
* Walks the list elements of the supplied property value and creates a
* cataloger config for each one found.
*
* @param source The current property element, assumed not <code>null</code>
* and to have a list as a value.
* @param type The type of configs to create, assumed not <code>null</code>.
*
* @return The list of configs, never <code>null</code>, may be empty.
*
* @throws PSInvalidXmlException If the supplied element does not represent
* a list of beans that can be represented by a {@link PSCatalogerConfig}.
*/
private Collection<PSCatalogerConfig> getCatalogerList(
Element source, ConfigTypes type) throws PSInvalidXmlException
{
List<PSCatalogerConfig> configs = new ArrayList<>();
Element catEl = PSSpringBeanUtils.getNextPropertyListElement(source,
null);
while (catEl != null)
{
configs.add(new PSCatalogerConfig(catEl, type));
catEl = PSSpringBeanUtils.getNextPropertyListElement(source,
catEl);
}
return configs;
}
// See IPSBeanConfig interface
public String getBeanName()
{
return BEAN_NAME;
}
// See IPSBeanConfig interface
public String getClassName()
{
return this.getClass().getName();
}
/**
* The the role manager to use.
*
* @param roleMgr The role manager, may not be <code>null</code>.
*/
public void setRoleMgr(IPSRoleMgr roleMgr)
{
if (roleMgr == null)
throw new IllegalArgumentException("roleMgr may not be null");
m_roleMgr = roleMgr;
}
/**
* Sets the list of subject catalogers to use.
* {@link #setRoleMgr(IPSRoleMgr)} must have been previously called.
*
* @param catalogers The list, never <code>null</code>, may be empty.
*
* @throws IllegalStateException if {@link #setRoleMgr(IPSRoleMgr)} has not
* been called.
*/
public void setSubjectCatalogers(List<IPSSubjectCataloger> catalogers)
{
if (catalogers == null)
throw new IllegalArgumentException("catalogers may not be null");
if (m_roleMgr == null)
throw new IllegalStateException("setRoleMgr() has not been called");
m_roleMgr.setSubjectCatalogers(catalogers);
}
/**
* Sets the list of role catalogers to use. {@link #setRoleMgr(IPSRoleMgr)}
* must have been previously called.
*
* @param catalogers The list, never <code>null</code>, may be empty.
*
* @throws IllegalStateException if {@link #setRoleMgr(IPSRoleMgr)} has not
* been called.
*/
public void setRoleCatalogers(List<IPSRoleCataloger> catalogers)
{
if (catalogers == null)
throw new IllegalArgumentException("catalogers may not be null");
if (m_roleMgr == null)
throw new IllegalStateException("setRoleMgr() has not been called");
m_roleMgr.setRoleCatalogers(catalogers);
}
/**
* The role manager to use, usually set by Spring dependency injection,
* <code>null</code> only until first call to
* {@link #setRoleMgr(IPSRoleMgr)}, never modified after that.
*/
private IPSRoleMgr m_roleMgr;
/**
* Collection of cataloger configs, set by
* {@link #saveCatalogerConfigs(List, File)} so they are available when
* {@link #toXml(Document)} is called, also set by {@link #fromXml(Element)}
* as a result of calling {@link #getCatalogerConfigs(File)}.
*/
private List<PSCatalogerConfig> m_catalogerConfigs =
new ArrayList<>();
}
| UTF-8 | Java | 9,870 | java | PSCatalogerConfigurations.java | Java | [] | null | [] | /*
* Copyright 1999-2023 Percussion Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.percussion.services.security.data;
import com.percussion.services.security.IPSRoleMgr;
import com.percussion.services.security.data.PSCatalogerConfig.ConfigTypes;
import com.percussion.services.security.impl.PSRoleMgr;
import com.percussion.security.IPSRoleCataloger;
import com.percussion.security.IPSSubjectCataloger;
import com.percussion.utils.servlet.PSServletUtils;
import com.percussion.utils.spring.IPSBeanConfig;
import com.percussion.utils.spring.PSSpringBeanUtils;
import com.percussion.utils.spring.PSSpringConfiguration;
import com.percussion.utils.xml.PSInvalidXmlException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Manages persistence for the subject and role cataloger configurations,
* provides wiring of runtime instances with the {@link PSRoleMgr}
*/
public class PSCatalogerConfigurations implements IPSBeanConfig
{
/**
* Constant for the name of this class's bean configuration
*/
private static final String BEAN_NAME = "sys_catalogers";
/**
* Constant for the role catalogers property name
*/
private static final String ROLE_CATALOGERS = "roleCatalogers";
/**
* Constant for the subject catalogers property name
*/
private static final String SUBJECT_CATALOGERS = "subjectCatalogers";
/**
* Constant for the role mgr property name
*/
private static final String ROLE_MGR = "roleMgr";
/**
* Gets all defined cataloger configurations from the specified file.
*
* @param configFile The file to read from, may not be <code>null</code>.
*
* @return A list of cataloger configurations, never <code>null</code>, may
* be empty.
*
* @throws SAXException If the spring config file is malformed.
* @throws IOException If there is an error loading the spring config file.
* @throws PSInvalidXmlException If the spring config xml is invalid.
*/
public static List<PSCatalogerConfig> getCatalogerConfigs(File configFile)
throws PSInvalidXmlException, IOException, SAXException
{
if (configFile == null)
throw new IllegalArgumentException("configFile may not be null");
PSSpringConfiguration springConfig = new PSSpringConfiguration(
configFile);
PSCatalogerConfigurations configs =
(PSCatalogerConfigurations) springConfig.getBean(BEAN_NAME);
return configs.m_catalogerConfigs;
}
/**
* Saves the list of cataloger configurations in the specified file,
* replacing any that are currently defined.
*
* @param configs The configurations to save, may be empty, never
* <code>null</code>.
* @param configFile The file to save to, may not be <code>null</code>.
*
* @throws SAXException If the spring config file is malformed.
* @throws IOException If there is an error loading the spring config file.
* @throws PSInvalidXmlException If the spring config xml is invalid.
*/
public static void saveCatalogerConfigs(List<PSCatalogerConfig> configs,
File configFile)
throws PSInvalidXmlException, IOException, SAXException
{
if (configs == null)
throw new IllegalArgumentException("configs may not be null");
if (configFile == null)
throw new IllegalArgumentException("configFile may not be null");
PSCatalogerConfigurations mgr = new PSCatalogerConfigurations();
mgr.m_catalogerConfigs.addAll(configs);
PSSpringConfiguration springConfig = new PSSpringConfiguration(
configFile);
springConfig.setBean(mgr);
springConfig.save();
}
// see IPSBeanConfig interface
public Element toXml(Document doc)
{
if (doc == null)
throw new IllegalArgumentException("doc may not be null");
Element root = PSSpringBeanUtils.createBeanRootElement(
this, doc);
PSSpringBeanUtils.addBeanRef(root, ROLE_MGR,
PSServletUtils.ROLE_MGR_BEAN_NAME);
List<PSCatalogerConfig> subConfigs = new ArrayList<>();
List<PSCatalogerConfig> roleConfigs = new ArrayList<>();
for (PSCatalogerConfig config : m_catalogerConfigs)
{
if (config.getConfigType().equals(ConfigTypes.SUBJECT))
subConfigs.add(config);
else
roleConfigs.add(config);
}
PSSpringBeanUtils.addBeanProperty(root, SUBJECT_CATALOGERS, subConfigs);
PSSpringBeanUtils.addBeanProperty(root, ROLE_CATALOGERS, roleConfigs);
return root;
}
// see IPSBeanConfig interface
public void fromXml(Element source) throws PSInvalidXmlException
{
if (source == null)
throw new IllegalArgumentException("source may not be null");
PSSpringBeanUtils.validateBeanRootElement(getBeanName(), getClassName(),
source);
m_catalogerConfigs.clear();
// the first prop is the role mgr, ignore it
Element propEl = PSSpringBeanUtils.getNextPropertyElement(source, null,
ROLE_MGR);
propEl = PSSpringBeanUtils.getNextPropertyElement(source, propEl,
SUBJECT_CATALOGERS);
m_catalogerConfigs.addAll(getCatalogerList(propEl, ConfigTypes.SUBJECT));
propEl = PSSpringBeanUtils.getNextPropertyElement(source, propEl,
ROLE_CATALOGERS);
m_catalogerConfigs.addAll(getCatalogerList(propEl, ConfigTypes.ROLE));
}
/**
* Walks the list elements of the supplied property value and creates a
* cataloger config for each one found.
*
* @param source The current property element, assumed not <code>null</code>
* and to have a list as a value.
* @param type The type of configs to create, assumed not <code>null</code>.
*
* @return The list of configs, never <code>null</code>, may be empty.
*
* @throws PSInvalidXmlException If the supplied element does not represent
* a list of beans that can be represented by a {@link PSCatalogerConfig}.
*/
private Collection<PSCatalogerConfig> getCatalogerList(
Element source, ConfigTypes type) throws PSInvalidXmlException
{
List<PSCatalogerConfig> configs = new ArrayList<>();
Element catEl = PSSpringBeanUtils.getNextPropertyListElement(source,
null);
while (catEl != null)
{
configs.add(new PSCatalogerConfig(catEl, type));
catEl = PSSpringBeanUtils.getNextPropertyListElement(source,
catEl);
}
return configs;
}
// See IPSBeanConfig interface
public String getBeanName()
{
return BEAN_NAME;
}
// See IPSBeanConfig interface
public String getClassName()
{
return this.getClass().getName();
}
/**
* The the role manager to use.
*
* @param roleMgr The role manager, may not be <code>null</code>.
*/
public void setRoleMgr(IPSRoleMgr roleMgr)
{
if (roleMgr == null)
throw new IllegalArgumentException("roleMgr may not be null");
m_roleMgr = roleMgr;
}
/**
* Sets the list of subject catalogers to use.
* {@link #setRoleMgr(IPSRoleMgr)} must have been previously called.
*
* @param catalogers The list, never <code>null</code>, may be empty.
*
* @throws IllegalStateException if {@link #setRoleMgr(IPSRoleMgr)} has not
* been called.
*/
public void setSubjectCatalogers(List<IPSSubjectCataloger> catalogers)
{
if (catalogers == null)
throw new IllegalArgumentException("catalogers may not be null");
if (m_roleMgr == null)
throw new IllegalStateException("setRoleMgr() has not been called");
m_roleMgr.setSubjectCatalogers(catalogers);
}
/**
* Sets the list of role catalogers to use. {@link #setRoleMgr(IPSRoleMgr)}
* must have been previously called.
*
* @param catalogers The list, never <code>null</code>, may be empty.
*
* @throws IllegalStateException if {@link #setRoleMgr(IPSRoleMgr)} has not
* been called.
*/
public void setRoleCatalogers(List<IPSRoleCataloger> catalogers)
{
if (catalogers == null)
throw new IllegalArgumentException("catalogers may not be null");
if (m_roleMgr == null)
throw new IllegalStateException("setRoleMgr() has not been called");
m_roleMgr.setRoleCatalogers(catalogers);
}
/**
* The role manager to use, usually set by Spring dependency injection,
* <code>null</code> only until first call to
* {@link #setRoleMgr(IPSRoleMgr)}, never modified after that.
*/
private IPSRoleMgr m_roleMgr;
/**
* Collection of cataloger configs, set by
* {@link #saveCatalogerConfigs(List, File)} so they are available when
* {@link #toXml(Document)} is called, also set by {@link #fromXml(Element)}
* as a result of calling {@link #getCatalogerConfigs(File)}.
*/
private List<PSCatalogerConfig> m_catalogerConfigs =
new ArrayList<>();
}
| 9,870 | 0.680851 | 0.679433 | 287 | 33.386761 | 28.222366 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43554 | false | false | 8 |
2540d159224e14b7476ca167630b0df0ec1739bc | 18,210,661,345,179 | 7f73612fdc6ecd3f81887b9db62e9a73a58c0b60 | /src/main/java/com/github/saleco/interview/calendar/api/user/mapper/UserMapper.java | 44d954884e06ba8cfde648ca3ac09f5ae864a140 | [] | no_license | saleco/interview-calendar-api | https://github.com/saleco/interview-calendar-api | 7affb1e3d6a0ae2c87d07db2ec6414b2370b5a6d | e51daaed6d19db2d691362f4c6f1d4c560b369d5 | refs/heads/master | 2023-04-11T02:04:46.844000 | 2021-04-25T18:40:57 | 2021-04-25T18:40:57 | 360,240,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.saleco.interview.calendar.api.user.mapper;
import com.github.saleco.interview.calendar.api.mapper.DateMapper;
import com.github.saleco.interview.calendar.api.user.dto.UserDto;
import com.github.saleco.interview.calendar.api.user.model.User;
import org.mapstruct.Mapper;
@Mapper(uses = DateMapper.class)
public interface UserMapper {
UserDto modelToDto(User user);
User dtoToModel(UserDto userDto);
}
| UTF-8 | Java | 430 | java | UserMapper.java | Java | [] | null | [] | package com.github.saleco.interview.calendar.api.user.mapper;
import com.github.saleco.interview.calendar.api.mapper.DateMapper;
import com.github.saleco.interview.calendar.api.user.dto.UserDto;
import com.github.saleco.interview.calendar.api.user.model.User;
import org.mapstruct.Mapper;
@Mapper(uses = DateMapper.class)
public interface UserMapper {
UserDto modelToDto(User user);
User dtoToModel(UserDto userDto);
}
| 430 | 0.802326 | 0.802326 | 13 | 32.076923 | 25.110407 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 8 |
d09b6f83f336b3594eeb245e2f661f23a5594be6 | 9,397,388,457,592 | 6d45067b449283cf6dde828e9793461b496bdeaf | /plugins/de.ovgu.featureide.core.mpl/src/de/ovgu/featureide/core/mpl/job/AChainJob.java | b2fb7a0c9e05588722f0b84f05b919072ea8e109 | [] | no_license | sanschul/FeatureIDE | https://github.com/sanschul/FeatureIDE | bdc2c411cfa49bd1264127317519e797de0f40da | 40404a3ff37936f331fb63468eb21d7fd8be87d6 | refs/heads/master | 2020-12-03T09:26:02.657000 | 2015-01-09T18:26:31 | 2015-01-09T18:26:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* FeatureIDE - A Framework for Feature-Oriented Software Development
* Copyright (C) 2005-2013 FeatureIDE team, University of Magdeburg, Germany
*
* This file is part of FeatureIDE.
*
* FeatureIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FeatureIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FeatureIDE. If not, see <http://www.gnu.org/licenses/>.
*
* See http://www.fosd.de/featureide/ for further information.
*/
package de.ovgu.featureide.core.mpl.job;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import de.ovgu.featureide.core.mpl.MPLPlugin;
import de.ovgu.featureide.core.mpl.job.util.AJobArguments;
import de.ovgu.featureide.core.mpl.job.util.IChainJob;
import de.ovgu.featureide.fm.core.job.IJob.JobStatus;
/**
* An abstract eclipse job, which starts another job when the work is done.
*
* @author Sebastian Krieter
*/
abstract class AChainJob<T extends AJobArguments> extends Job implements IChainJob {
private class InnerThread extends Thread {
private volatile Thread thread = this;
public InnerThread() {
super("Thread-" + AChainJob.this.getName());
final int prio = AChainJob.this.getPriority();
if (prio == SHORT || prio == INTERACTIVE) {
this.setPriority(Thread.MAX_PRIORITY);
} else if (prio == LONG) {
this.setPriority(Thread.NORM_PRIORITY);
} else {
this.setPriority(Thread.MIN_PRIORITY);
}
}
@Override
public void run() {
JobStatus status = JobStatus.FAILED;
try {
status = AChainJob.this.work() ? JobStatus.OK : JobStatus.FAILED;
} catch (Exception e) {
MPLPlugin.getDefault().logError(e);
} finally {
synchronized (AChainJob.this.status) {
AChainJob.this.status = status;
}
finalWork();
; }
}
}
private boolean ignorePreviousJobFail = true;
private int cancelingTimeout = 5000;
private InnerThread innerThread = null;
private JobStatus status = JobStatus.FAILED;
private Object sequenceObject = null;
protected IProject project = null;
protected final T arguments;
protected AChainJob(String name, T arguments) {
this(name, Job.SHORT, arguments);
}
protected AChainJob(String name, int priority, T arguments) {
super(name);
setPriority(priority);
this.arguments = arguments;
}
@SuppressWarnings("deprecation")
@Override
public IStatus run(IProgressMonitor monitor) {
synchronized (status) {
// in case job was started and cancelled at the same time
if (status == JobStatus.FAILED) {
finished();
return Status.CANCEL_STATUS;
}
innerThread = new InnerThread();
innerThread.start();
}
try {
innerThread.join();
finished();
return Status.OK_STATUS;
} catch (InterruptedException e) {
MPLPlugin.getDefault().logError(e);
innerThread.stop();
synchronized (status) {
status = JobStatus.FAILED;
}
finished();
return Status.CANCEL_STATUS;
}
}
private void finished() {
System.out.println();
synchronized (sequenceObject) {
if (sequenceObject != null) {
JobManager.startNextJob(sequenceObject);
sequenceObject = null;
}
}
}
/**
* Check whether the user has sent a cancel request for this job.
*
* @return {@code true} if the job should be canceled
*/
protected final boolean checkCancel() {
return Thread.currentThread() == innerThread.thread;
}
/**
* In this method all the work of the job is done.
* </br></br>
* Implementing jobs should continuously call {@link #checkCancel()} and respond to a canceling request.
*
* @return {@code true} if no error occurred during the process
*/
protected abstract boolean work();
/**
* This method is called after {@link #work()} is finished regardless whether it succeeded or not.
* The default method is empty.
*/
protected void finalWork() {}
@Override
public void canceling() {
synchronized (status) {
if (innerThread == null) {
status = JobStatus.FAILED;
return;
}
}
innerThread.thread = null;
new Thread(new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
Thread.sleep(cancelingTimeout);
} catch (InterruptedException e) {
MPLPlugin.getDefault().logError(e);
}
if (innerThread.isAlive()) {
innerThread.stop();
}
}
}).start();
}
@Override
public final int getCancelingTimeout() {
return cancelingTimeout;
}
@Override
public final IProject getProject() {
return project;
}
@Override
public JobStatus getStatus() {
return status;
}
@Override
public final boolean ignoresPreviousJobFail() {
return ignorePreviousJobFail;
}
@Override
public final void setIgnorePreviousJobFail(boolean ignorePreviousJobFail) {
this.ignorePreviousJobFail = ignorePreviousJobFail;
}
@Override
public final void setCancelingTimeout(int cancelingTimeout) {
this.cancelingTimeout = cancelingTimeout;
}
@Override
public final void setProject(IProject interfaceProject) {
this.project = interfaceProject;
setName(getName() + " - " + interfaceProject.getName());
}
void setSequenceObject(Object sequenceObject) {
this.sequenceObject = sequenceObject;
}
Object getSequenceObject() {
return sequenceObject;
}
}
| UTF-8 | Java | 5,865 | java | AChainJob.java | Java | [
{
"context": " another job when the work is done.\n * \n * @author Sebastian Krieter\n */\nabstract class AChainJob<T extends AJobArgume",
"end": 1511,
"score": 0.999884307384491,
"start": 1494,
"tag": "NAME",
"value": "Sebastian Krieter"
}
] | null | [] | /* FeatureIDE - A Framework for Feature-Oriented Software Development
* Copyright (C) 2005-2013 FeatureIDE team, University of Magdeburg, Germany
*
* This file is part of FeatureIDE.
*
* FeatureIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FeatureIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FeatureIDE. If not, see <http://www.gnu.org/licenses/>.
*
* See http://www.fosd.de/featureide/ for further information.
*/
package de.ovgu.featureide.core.mpl.job;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import de.ovgu.featureide.core.mpl.MPLPlugin;
import de.ovgu.featureide.core.mpl.job.util.AJobArguments;
import de.ovgu.featureide.core.mpl.job.util.IChainJob;
import de.ovgu.featureide.fm.core.job.IJob.JobStatus;
/**
* An abstract eclipse job, which starts another job when the work is done.
*
* @author <NAME>
*/
abstract class AChainJob<T extends AJobArguments> extends Job implements IChainJob {
private class InnerThread extends Thread {
private volatile Thread thread = this;
public InnerThread() {
super("Thread-" + AChainJob.this.getName());
final int prio = AChainJob.this.getPriority();
if (prio == SHORT || prio == INTERACTIVE) {
this.setPriority(Thread.MAX_PRIORITY);
} else if (prio == LONG) {
this.setPriority(Thread.NORM_PRIORITY);
} else {
this.setPriority(Thread.MIN_PRIORITY);
}
}
@Override
public void run() {
JobStatus status = JobStatus.FAILED;
try {
status = AChainJob.this.work() ? JobStatus.OK : JobStatus.FAILED;
} catch (Exception e) {
MPLPlugin.getDefault().logError(e);
} finally {
synchronized (AChainJob.this.status) {
AChainJob.this.status = status;
}
finalWork();
; }
}
}
private boolean ignorePreviousJobFail = true;
private int cancelingTimeout = 5000;
private InnerThread innerThread = null;
private JobStatus status = JobStatus.FAILED;
private Object sequenceObject = null;
protected IProject project = null;
protected final T arguments;
protected AChainJob(String name, T arguments) {
this(name, Job.SHORT, arguments);
}
protected AChainJob(String name, int priority, T arguments) {
super(name);
setPriority(priority);
this.arguments = arguments;
}
@SuppressWarnings("deprecation")
@Override
public IStatus run(IProgressMonitor monitor) {
synchronized (status) {
// in case job was started and cancelled at the same time
if (status == JobStatus.FAILED) {
finished();
return Status.CANCEL_STATUS;
}
innerThread = new InnerThread();
innerThread.start();
}
try {
innerThread.join();
finished();
return Status.OK_STATUS;
} catch (InterruptedException e) {
MPLPlugin.getDefault().logError(e);
innerThread.stop();
synchronized (status) {
status = JobStatus.FAILED;
}
finished();
return Status.CANCEL_STATUS;
}
}
private void finished() {
System.out.println();
synchronized (sequenceObject) {
if (sequenceObject != null) {
JobManager.startNextJob(sequenceObject);
sequenceObject = null;
}
}
}
/**
* Check whether the user has sent a cancel request for this job.
*
* @return {@code true} if the job should be canceled
*/
protected final boolean checkCancel() {
return Thread.currentThread() == innerThread.thread;
}
/**
* In this method all the work of the job is done.
* </br></br>
* Implementing jobs should continuously call {@link #checkCancel()} and respond to a canceling request.
*
* @return {@code true} if no error occurred during the process
*/
protected abstract boolean work();
/**
* This method is called after {@link #work()} is finished regardless whether it succeeded or not.
* The default method is empty.
*/
protected void finalWork() {}
@Override
public void canceling() {
synchronized (status) {
if (innerThread == null) {
status = JobStatus.FAILED;
return;
}
}
innerThread.thread = null;
new Thread(new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
Thread.sleep(cancelingTimeout);
} catch (InterruptedException e) {
MPLPlugin.getDefault().logError(e);
}
if (innerThread.isAlive()) {
innerThread.stop();
}
}
}).start();
}
@Override
public final int getCancelingTimeout() {
return cancelingTimeout;
}
@Override
public final IProject getProject() {
return project;
}
@Override
public JobStatus getStatus() {
return status;
}
@Override
public final boolean ignoresPreviousJobFail() {
return ignorePreviousJobFail;
}
@Override
public final void setIgnorePreviousJobFail(boolean ignorePreviousJobFail) {
this.ignorePreviousJobFail = ignorePreviousJobFail;
}
@Override
public final void setCancelingTimeout(int cancelingTimeout) {
this.cancelingTimeout = cancelingTimeout;
}
@Override
public final void setProject(IProject interfaceProject) {
this.project = interfaceProject;
setName(getName() + " - " + interfaceProject.getName());
}
void setSequenceObject(Object sequenceObject) {
this.sequenceObject = sequenceObject;
}
Object getSequenceObject() {
return sequenceObject;
}
}
| 5,854 | 0.707076 | 0.704859 | 225 | 25.066668 | 23.095936 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.982222 | false | false | 8 |
5a0037a025138297a32a0035b602c08925cfec56 | 30,331,059,061,525 | 9d6ecc2e9cfe1f4ec32d75d2db9a86551747cfee | /VerticalLine.java | dd8109c5891ff514938f4484bf3af9362c1a2a6c | [] | no_license | sfbahr/IntersectingLines | https://github.com/sfbahr/IntersectingLines | dfafc0b68ed2e279440a9e2a059fbd86cdb79c91 | d33dcbd960be81f2d3009855e06ab4fdb5efdb7b | refs/heads/master | 2021-01-17T20:05:14.057000 | 2015-12-10T00:34:38 | 2015-12-10T00:34:38 | 47,432,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author Anuj
*
*/
public class VerticalLine extends Line {
public VerticalLine(Point start, Point end, Boolean vertical) {
super(start, end, vertical);
}
public VerticalLine(Line line) {
super(line.getLesser(), line.getGreater(), true);
}
@Override
public int compareTo(Line o) {
if (this.getLesser().getX() == o.getLesser().getX()) {
return 0;
}
else if (this.getLesser().getX() > o.getLesser().getX()) {
return 1;
}
return -1;
}
public int getX() {
return this.getLesser().getX();
}
}
| UTF-8 | Java | 533 | java | VerticalLine.java | Java | [
{
"context": "/**\n * @author Anuj\n *\n */\npublic class VerticalLine extends Line {\n\n",
"end": 19,
"score": 0.8920038938522339,
"start": 15,
"tag": "NAME",
"value": "Anuj"
}
] | null | [] | /**
* @author Anuj
*
*/
public class VerticalLine extends Line {
public VerticalLine(Point start, Point end, Boolean vertical) {
super(start, end, vertical);
}
public VerticalLine(Line line) {
super(line.getLesser(), line.getGreater(), true);
}
@Override
public int compareTo(Line o) {
if (this.getLesser().getX() == o.getLesser().getX()) {
return 0;
}
else if (this.getLesser().getX() > o.getLesser().getX()) {
return 1;
}
return -1;
}
public int getX() {
return this.getLesser().getX();
}
}
| 533 | 0.630394 | 0.624765 | 29 | 17.379311 | 19.938551 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.551724 | false | false | 8 |
fbcbcc26af5e03d1ad8fc76cd4dfde28700309de | 25,005,299,607,205 | 86854f4afbe2cb408b0dc80c5284b9a4618c7637 | /src/main/java/com/example/moveydiscovery/repository/SavingRepository.java | 91fb6ded33ae50b4efc2f616a1fb5d17ff177b6c | [] | no_license | KySo4oK/movey-notifications | https://github.com/KySo4oK/movey-notifications | 9fd651f20db4eaa8f0e5845fb7a5ced98bbd0ba4 | e43c3fd40f2810ff139f54078b4b7918ceca9ba3 | refs/heads/master | 2023-05-13T15:40:47.340000 | 2021-06-04T16:35:45 | 2021-06-04T16:35:45 | 349,357,287 | 0 | 0 | null | false | 2021-05-02T16:00:39 | 2021-03-19T08:50:15 | 2021-05-02T15:36:12 | 2021-05-02T16:00:39 | 20 | 0 | 0 | 0 | Java | false | false | package com.example.moveydiscovery.repository;
import com.example.moveydiscovery.entity.Saving;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface SavingRepository extends JpaRepository<Saving, Long> {
List<Saving> findAllByUserId(String userId);
}
| UTF-8 | Java | 307 | java | SavingRepository.java | Java | [] | null | [] | package com.example.moveydiscovery.repository;
import com.example.moveydiscovery.entity.Saving;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface SavingRepository extends JpaRepository<Saving, Long> {
List<Saving> findAllByUserId(String userId);
}
| 307 | 0.824104 | 0.824104 | 10 | 29.700001 | 26.739672 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 8 |
69cb4bc220ab05e58bc68a2ecece5d7d170a64fb | 3,891,240,374,812 | a5f4cb08fbaa0d192d439729c5fb21e9f094f2a3 | /src/main/java/sayTheSpire/speech/TolkHandler.java | c24a23727da3944550241ffc8c3714561486a441 | [] | no_license | yncat/say-the-spire | https://github.com/yncat/say-the-spire | 7830be5ee91b512a7c0b7414c3f6f99221e1a295 | e0851aa0e764ad9220cd29f1b339c1c8ffe54e98 | refs/heads/master | 2023-07-18T16:45:00.811000 | 2020-09-26T05:38:40 | 2020-09-26T05:38:40 | 298,933,815 | 0 | 0 | null | true | 2020-09-27T02:04:10 | 2020-09-27T02:04:09 | 2020-09-26T10:42:07 | 2020-09-26T05:38:47 | 98 | 0 | 0 | 0 | null | false | false | package sayTheSpire.speech;
import com.davykager.tolk.Tolk;
public class TolkHandler extends SpeechHandler {
public Boolean detect() {
return System.getProperty("os.name").startsWith("Windows");
}
public void disposeResources() {
// do nothing
}
public Boolean loadResources() {
return true; // do nothing
}
public Boolean load() {
Tolk.load();
return true;
}
public Boolean output(String text, Boolean interrupt) {
Tolk.output(text, interrupt);
return true;
}
public Boolean silence() {
Tolk.silence();
return true;
}
public Boolean speak(String text, Boolean interrupt) {
Tolk.speak(text, interrupt);
return true;
}
public void unload() {
Tolk.unload();
}
}
| UTF-8 | Java | 750 | java | TolkHandler.java | Java | [] | null | [] | package sayTheSpire.speech;
import com.davykager.tolk.Tolk;
public class TolkHandler extends SpeechHandler {
public Boolean detect() {
return System.getProperty("os.name").startsWith("Windows");
}
public void disposeResources() {
// do nothing
}
public Boolean loadResources() {
return true; // do nothing
}
public Boolean load() {
Tolk.load();
return true;
}
public Boolean output(String text, Boolean interrupt) {
Tolk.output(text, interrupt);
return true;
}
public Boolean silence() {
Tolk.silence();
return true;
}
public Boolean speak(String text, Boolean interrupt) {
Tolk.speak(text, interrupt);
return true;
}
public void unload() {
Tolk.unload();
}
}
| 750 | 0.657333 | 0.657333 | 42 | 16.857143 | 17.443203 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404762 | false | false | 8 |
7f2ca632bc574e27a04d6b105b2022c6a4ff4092 | 4,552,665,349,539 | 7ce47d1d6e2865ba8e683910bff09ce8d0de4ee3 | /src/WorksheetProperties.java | 07c2890c2b8351f20b5628819398c3bf0b601b38 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | RvanVeenendaal/Spreadsheet-Complexity-Analyser | https://github.com/RvanVeenendaal/Spreadsheet-Complexity-Analyser | c51598f1697b94da69ea4088683a9418e7c284d0 | 4910538edafff7a540faf8d09e78074555ef732a | refs/heads/master | 2022-12-21T22:21:24.729000 | 2022-12-13T10:10:34 | 2022-12-13T10:10:34 | 130,328,493 | 14 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class WorksheetProperties {
public String sSheetName = "";
public int iPivotTables = 0;
public int iTables = 0;
public int iShapes = 0;
public int iCharts = 0;
public int iRowsUsed = 0;
public int iPhysicallyUsedRows = 0;
public int iCellsUsed = 0;
public int iPhysicallyUsedCells = 0;
public int iFormulas = 0;
public int iDates = 0;
public int iHyperlinks = 0;
public int iCellComments = 0;
public String getsSheetName() {
return sSheetName;
}
public void setsSheetName(String sSheetName) {
this.sSheetName = sSheetName;
}
public int getiPivotTables() {
return iPivotTables;
}
public void setiPivotTables(int iPivotTables) {
this.iPivotTables = iPivotTables;
}
public int getiTables() {
return iTables;
}
public void setiTables(int iTables) {
this.iTables = iTables;
}
public int getiShapes() {
return iShapes;
}
public void setiShapes(int iShapes) {
this.iShapes = iShapes;
}
public int getiCharts() {
return iCharts;
}
public void setiCharts(int iCharts) {
this.iCharts = iCharts;
}
public int getiRowsUsed() {
return iRowsUsed;
}
public void setiRowsUsed(int iRowsUsed) {
this.iRowsUsed = iRowsUsed;
}
public int getiPhysicallyUsedRows() {
return iPhysicallyUsedRows;
}
public void setiPhysicallyUsedRows(int iPhysicallyUsedRows) {
this.iPhysicallyUsedRows = iPhysicallyUsedRows;
}
public int getiCellsUsed() {
return iCellsUsed;
}
public void setiCellsUsed(int iCellsUsed) {
this.iCellsUsed = iCellsUsed;
}
public int getiPhysicallyUsedCells() {
return iPhysicallyUsedCells;
}
public void setiPhysicallyUsedCells(int iPhysicallyUsedCells) {
this.iPhysicallyUsedCells = iPhysicallyUsedCells;
}
public int getiFormulas() {
return iFormulas;
}
public void setiFormulas(int iFormulas) {
this.iFormulas = iFormulas;
}
public int getiDates() {
return iDates;
}
public void setiDates(int iDates) {
this.iDates = iDates;
}
public int getiHyperlinks() {
return iHyperlinks;
}
public void setiHyperlinks(int iHyperlinks) {
this.iHyperlinks = iHyperlinks;
}
public int getiCellComments() {
return iCellComments;
}
public void setiCellComments(int iCellComments) {
this.iCellComments = iCellComments;
}
}
| UTF-8 | Java | 2,320 | java | WorksheetProperties.java | Java | [] | null | [] | public class WorksheetProperties {
public String sSheetName = "";
public int iPivotTables = 0;
public int iTables = 0;
public int iShapes = 0;
public int iCharts = 0;
public int iRowsUsed = 0;
public int iPhysicallyUsedRows = 0;
public int iCellsUsed = 0;
public int iPhysicallyUsedCells = 0;
public int iFormulas = 0;
public int iDates = 0;
public int iHyperlinks = 0;
public int iCellComments = 0;
public String getsSheetName() {
return sSheetName;
}
public void setsSheetName(String sSheetName) {
this.sSheetName = sSheetName;
}
public int getiPivotTables() {
return iPivotTables;
}
public void setiPivotTables(int iPivotTables) {
this.iPivotTables = iPivotTables;
}
public int getiTables() {
return iTables;
}
public void setiTables(int iTables) {
this.iTables = iTables;
}
public int getiShapes() {
return iShapes;
}
public void setiShapes(int iShapes) {
this.iShapes = iShapes;
}
public int getiCharts() {
return iCharts;
}
public void setiCharts(int iCharts) {
this.iCharts = iCharts;
}
public int getiRowsUsed() {
return iRowsUsed;
}
public void setiRowsUsed(int iRowsUsed) {
this.iRowsUsed = iRowsUsed;
}
public int getiPhysicallyUsedRows() {
return iPhysicallyUsedRows;
}
public void setiPhysicallyUsedRows(int iPhysicallyUsedRows) {
this.iPhysicallyUsedRows = iPhysicallyUsedRows;
}
public int getiCellsUsed() {
return iCellsUsed;
}
public void setiCellsUsed(int iCellsUsed) {
this.iCellsUsed = iCellsUsed;
}
public int getiPhysicallyUsedCells() {
return iPhysicallyUsedCells;
}
public void setiPhysicallyUsedCells(int iPhysicallyUsedCells) {
this.iPhysicallyUsedCells = iPhysicallyUsedCells;
}
public int getiFormulas() {
return iFormulas;
}
public void setiFormulas(int iFormulas) {
this.iFormulas = iFormulas;
}
public int getiDates() {
return iDates;
}
public void setiDates(int iDates) {
this.iDates = iDates;
}
public int getiHyperlinks() {
return iHyperlinks;
}
public void setiHyperlinks(int iHyperlinks) {
this.iHyperlinks = iHyperlinks;
}
public int getiCellComments() {
return iCellComments;
}
public void setiCellComments(int iCellComments) {
this.iCellComments = iCellComments;
}
}
| 2,320 | 0.707759 | 0.702586 | 94 | 22.680851 | 16.009447 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.670213 | false | false | 8 |
42248792de652503a9c74f9f0d9f140cb8842e46 | 28,656,021,800,126 | 961fd8cff3dc19f946a00fd73587d66aa8896166 | /src/main/java/ohjelmisto/dao/VastausRowMapper.java | 83cb249afb6b18b906dd2d9529b1d60437d94a19 | [] | no_license | laihanen/Oprojekti | https://github.com/laihanen/Oprojekti | 875624b16464fbd802974c5052e74d60a42c2e03 | 06b4c0cf1979ffd7cf622e2024590cc6de3468e8 | refs/heads/master | 2021-01-20T07:32:34.557000 | 2017-05-17T13:54:54 | 2017-05-17T13:54:54 | 90,012,266 | 0 | 0 | null | false | 2017-05-05T07:40:14 | 2017-05-02T08:58:29 | 2017-05-03T10:06:36 | 2017-05-05T07:34:20 | 8,983 | 0 | 0 | 1 | CSS | null | null | package ohjelmisto.dao;
import ohjelmisto.bean.Vastaus;
import ohjelmisto.bean.VastausImpl;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by bferr on 12/05/2017.
*/
public class VastausRowMapper implements RowMapper<Vastaus> {
public Vastaus mapRow(ResultSet rs, int rowNum) throws SQLException{
Vastaus v = new VastausImpl();
v.setId(rs.getInt("id"));
v.setAvointekstivastaus(rs.getString("avointekstivastaus"));
return v;
}
} | UTF-8 | Java | 549 | java | VastausRowMapper.java | Java | [
{
"context": ";\nimport java.sql.SQLException;\n\n/**\n * Created by bferr on 12/05/2017.\n */\npublic class VastausRowMapper ",
"end": 225,
"score": 0.9995483160018921,
"start": 220,
"tag": "USERNAME",
"value": "bferr"
}
] | null | [] | package ohjelmisto.dao;
import ohjelmisto.bean.Vastaus;
import ohjelmisto.bean.VastausImpl;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by bferr on 12/05/2017.
*/
public class VastausRowMapper implements RowMapper<Vastaus> {
public Vastaus mapRow(ResultSet rs, int rowNum) throws SQLException{
Vastaus v = new VastausImpl();
v.setId(rs.getInt("id"));
v.setAvointekstivastaus(rs.getString("avointekstivastaus"));
return v;
}
} | 549 | 0.721311 | 0.70674 | 24 | 21.916666 | 22.788734 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 8 |
c7a387ec9d6268944e24099334aef1c73c154696 | 1,760,936,599,773 | c43c8158179c982606c142565fe10cdbe051e9f3 | /src/kr/ac/kookmin/cs/bigdata/kkp/word2vecDriver.java | 629928d5650a4b3a5b9e3f2e4b5ff3fdf120b000 | [] | no_license | kmucs-web-client-2017-01/kmucs-bigdata-project-bus-team | https://github.com/kmucs-web-client-2017-01/kmucs-bigdata-project-bus-team | a4089b846ad2629ef0503cb014759e8ca01eae19 | 433ef729a934a6adc9f3566a38e10201f48b03c8 | refs/heads/master | 2021-03-19T10:52:13.941000 | 2017-06-05T14:50:21 | 2017-06-05T14:50:21 | 91,996,078 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.ac.kookmin.cs.bigdata.kkp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.json.*; // * 를 활용한 모든 라이브러리 포함은 위험
import com.google.gson.Gson;
import kr.ac.kookmin.cs.bigdata.kkp.vec.Word2VEC;
public class word2vecDriver extends Configured implements Tool {
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(args));
Configuration config = new Configuration();
config.set("filePath", args[0]);
int res = ToolRunner.run(config, new word2vecDriver(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
System.out.println(Arrays.toString(args));
Job step1Job = Job.getInstance(getConf());
step1Job.setJarByClass(word2vecDriver.class);
step1Job.setOutputKeyClass(Text.class);
step1Job.setOutputValueClass(FloatWritable.class);
step1Job.setMapperClass(step1Map.class);
step1Job.setReducerClass(step1Reduce.class);
step1Job.setInputFormatClass(TextInputFormat.class);
step1Job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(step1Job, new Path(args[1]));
FileOutputFormat.setOutputPath(step1Job, new Path(args[2]));
step1Job.waitForCompletion(true);
Job step2Job = Job.getInstance(getConf());
step2Job.setJarByClass(word2vecDriver.class);
step2Job.setOutputKeyClass(Text.class);
step2Job.setOutputValueClass(FloatWritable.class);
step2Job.setMapperClass(step2Map.class);
step2Job.setReducerClass(step2Reduce.class);
step2Job.setInputFormatClass(TextInputFormat.class);
step2Job.setOutputFormatClass(TextOutputFormat.class);
// FileInputFormat.addInputPath(step2Job, new Path("hdfs://master:9000" + args[2]));
FileInputFormat.addInputPath(step2Job, new Path(args[2]+ "/part-r-00000"));
FileOutputFormat.setOutputPath(step2Job, new Path(args[3]));
step2Job.waitForCompletion(true);
Job step3Job = Job.getInstance(getConf());
step3Job.setJarByClass(word2vecDriver.class);
step3Job.setOutputKeyClass(Text.class);
step3Job.setOutputValueClass(Text.class);
step3Job.setMapperClass(step3Map.class);
step3Job.setReducerClass(step3Reduce.class);
step3Job.setInputFormatClass(TextInputFormat.class);
step3Job.setOutputFormatClass(TextOutputFormat.class);
// FileInputFormat.addInputPath(step3Job, new Path("hdfs://master:9000" + args[3]));
FileInputFormat.addInputPath(step3Job, new Path(args[3]+ "/part-r-00000"));
FileOutputFormat.setOutputPath(step3Job, new Path(args[4]));
step3Job.waitForCompletion(true);
return 0;
}
/*
* STEP 1
* Get Mapreduce Key(topAsin + topWord + overallAsin),
* Value(topWord's max similarity in overallAsin's all word)
*/
public static class step1Map extends Mapper<LongWritable, Text, Text, FloatWritable> {
Configuration conf;
String filePath;
Word2VEC word2vec = new Word2VEC();
public void setup(Context context) {
conf = context.getConfiguration();
filePath = conf.get("filePath");
try {
word2vec.loadGoogleModel(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split(" ");
String[] topElem = element[0].split("\t");
String[] overallElem = element[1].split("\t");
String topAsin = topElem[0], topWord = topElem[1],
overallAsin = overallElem[0], overallWord = overallElem[1];
Text newKey = new Text(topAsin + " " + topWord + " " + overallAsin);
float similarity = word2vec.wordSimilarity(topWord, overallWord);
context.write(newKey, new FloatWritable(similarity));
}
}
public static class step1Reduce extends
Reducer<Text, FloatWritable, Text, FloatWritable> {
@Override
public void reduce(Text key, Iterable<FloatWritable> values,
Context context) throws IOException, InterruptedException {
float topSimilarity = -1;
for (FloatWritable val : values) {
float temp = val.get();
topSimilarity = (temp > topSimilarity) ? temp : topSimilarity;
}
context.write(key, new FloatWritable(topSimilarity));
}
}
/*
* STEP 2
* Get Mapreduce Key(topAsin overallAsin),
* Value(topAsin's average similarity with overallAsin)
*/
public static class step2Map extends Mapper<LongWritable, Text, Text, FloatWritable> {
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split("\t");
String[] keyElem = element[0].split(" ");
float maxSimilarity = Float.parseFloat(element[1]);
String topAsin = keyElem[0], topWord = keyElem[1], overallAsin = keyElem[2];
Text newKey = new Text(topAsin + " " + overallAsin);
context.write(newKey, new FloatWritable(maxSimilarity));
}
}
public static class step2Reduce extends
Reducer<Text, FloatWritable, Text, FloatWritable> {
@Override
public void reduce(Text key, Iterable<FloatWritable> values,
Context context) throws IOException, InterruptedException {
float sumSimilarity = 0, count = 0, averageSimilarity = 0;
for (FloatWritable val : values) {
sumSimilarity += val.get();
count++;
}
averageSimilarity = sumSimilarity / count;
context.write(key, new FloatWritable(averageSimilarity));
}
}
/*
* STEP 3
* Get Mapreduce Key(topAsin),
* Value(TOP 10 in topAsin's similar overallAsin )
*/
public static class step3Map extends Mapper<LongWritable, Text, Text, Text> {
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split("\t");
String[] keyElem = element[0].split(" ");
String averageSimilarity = element[1];
String topAsin = keyElem[0], overallAsin = keyElem[1];
Text newKey = new Text(topAsin);
context.write(newKey, new Text(overallAsin + " " + averageSimilarity));
}
}
public static class step3Reduce extends
Reducer<Text, Text, Text, Text> {
@Override
public void reduce(Text key, Iterable<Text> values,
Context context) throws IOException, InterruptedException {
PriorityQueue<SimilarObject> priorityQueue = new PriorityQueue<SimilarObject>();
for (Text val : values) {
String[] element = val.toString().split(" ");
String overallAsin = element[0];
float averageSimilarity = Float.parseFloat(element[1]);;
SimilarObject SimTempObj = new SimilarObject(overallAsin, averageSimilarity);
priorityQueue.offer(SimTempObj);
if(priorityQueue.size() > 10) {
priorityQueue.poll();
}
}
PriorityQueue<SimilarObject> reversedPriorityQueue = new PriorityQueue<SimilarObject>(priorityQueue.size(), Collections.reverseOrder());
reversedPriorityQueue.addAll(priorityQueue);
int i = 1;
while(!reversedPriorityQueue.isEmpty()) {
SimilarObject SimTempObj = reversedPriorityQueue.poll();
context.write(key, new Text(SimTempObj.toString() + " (" + i + ")"));
i++;
}
}
}
}
| UTF-8 | Java | 8,327 | java | word2vecDriver.java | Java | [] | null | [] | package kr.ac.kookmin.cs.bigdata.kkp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.json.*; // * 를 활용한 모든 라이브러리 포함은 위험
import com.google.gson.Gson;
import kr.ac.kookmin.cs.bigdata.kkp.vec.Word2VEC;
public class word2vecDriver extends Configured implements Tool {
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(args));
Configuration config = new Configuration();
config.set("filePath", args[0]);
int res = ToolRunner.run(config, new word2vecDriver(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
System.out.println(Arrays.toString(args));
Job step1Job = Job.getInstance(getConf());
step1Job.setJarByClass(word2vecDriver.class);
step1Job.setOutputKeyClass(Text.class);
step1Job.setOutputValueClass(FloatWritable.class);
step1Job.setMapperClass(step1Map.class);
step1Job.setReducerClass(step1Reduce.class);
step1Job.setInputFormatClass(TextInputFormat.class);
step1Job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(step1Job, new Path(args[1]));
FileOutputFormat.setOutputPath(step1Job, new Path(args[2]));
step1Job.waitForCompletion(true);
Job step2Job = Job.getInstance(getConf());
step2Job.setJarByClass(word2vecDriver.class);
step2Job.setOutputKeyClass(Text.class);
step2Job.setOutputValueClass(FloatWritable.class);
step2Job.setMapperClass(step2Map.class);
step2Job.setReducerClass(step2Reduce.class);
step2Job.setInputFormatClass(TextInputFormat.class);
step2Job.setOutputFormatClass(TextOutputFormat.class);
// FileInputFormat.addInputPath(step2Job, new Path("hdfs://master:9000" + args[2]));
FileInputFormat.addInputPath(step2Job, new Path(args[2]+ "/part-r-00000"));
FileOutputFormat.setOutputPath(step2Job, new Path(args[3]));
step2Job.waitForCompletion(true);
Job step3Job = Job.getInstance(getConf());
step3Job.setJarByClass(word2vecDriver.class);
step3Job.setOutputKeyClass(Text.class);
step3Job.setOutputValueClass(Text.class);
step3Job.setMapperClass(step3Map.class);
step3Job.setReducerClass(step3Reduce.class);
step3Job.setInputFormatClass(TextInputFormat.class);
step3Job.setOutputFormatClass(TextOutputFormat.class);
// FileInputFormat.addInputPath(step3Job, new Path("hdfs://master:9000" + args[3]));
FileInputFormat.addInputPath(step3Job, new Path(args[3]+ "/part-r-00000"));
FileOutputFormat.setOutputPath(step3Job, new Path(args[4]));
step3Job.waitForCompletion(true);
return 0;
}
/*
* STEP 1
* Get Mapreduce Key(topAsin + topWord + overallAsin),
* Value(topWord's max similarity in overallAsin's all word)
*/
public static class step1Map extends Mapper<LongWritable, Text, Text, FloatWritable> {
Configuration conf;
String filePath;
Word2VEC word2vec = new Word2VEC();
public void setup(Context context) {
conf = context.getConfiguration();
filePath = conf.get("filePath");
try {
word2vec.loadGoogleModel(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split(" ");
String[] topElem = element[0].split("\t");
String[] overallElem = element[1].split("\t");
String topAsin = topElem[0], topWord = topElem[1],
overallAsin = overallElem[0], overallWord = overallElem[1];
Text newKey = new Text(topAsin + " " + topWord + " " + overallAsin);
float similarity = word2vec.wordSimilarity(topWord, overallWord);
context.write(newKey, new FloatWritable(similarity));
}
}
public static class step1Reduce extends
Reducer<Text, FloatWritable, Text, FloatWritable> {
@Override
public void reduce(Text key, Iterable<FloatWritable> values,
Context context) throws IOException, InterruptedException {
float topSimilarity = -1;
for (FloatWritable val : values) {
float temp = val.get();
topSimilarity = (temp > topSimilarity) ? temp : topSimilarity;
}
context.write(key, new FloatWritable(topSimilarity));
}
}
/*
* STEP 2
* Get Mapreduce Key(topAsin overallAsin),
* Value(topAsin's average similarity with overallAsin)
*/
public static class step2Map extends Mapper<LongWritable, Text, Text, FloatWritable> {
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split("\t");
String[] keyElem = element[0].split(" ");
float maxSimilarity = Float.parseFloat(element[1]);
String topAsin = keyElem[0], topWord = keyElem[1], overallAsin = keyElem[2];
Text newKey = new Text(topAsin + " " + overallAsin);
context.write(newKey, new FloatWritable(maxSimilarity));
}
}
public static class step2Reduce extends
Reducer<Text, FloatWritable, Text, FloatWritable> {
@Override
public void reduce(Text key, Iterable<FloatWritable> values,
Context context) throws IOException, InterruptedException {
float sumSimilarity = 0, count = 0, averageSimilarity = 0;
for (FloatWritable val : values) {
sumSimilarity += val.get();
count++;
}
averageSimilarity = sumSimilarity / count;
context.write(key, new FloatWritable(averageSimilarity));
}
}
/*
* STEP 3
* Get Mapreduce Key(topAsin),
* Value(TOP 10 in topAsin's similar overallAsin )
*/
public static class step3Map extends Mapper<LongWritable, Text, Text, Text> {
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] element = line.split("\t");
String[] keyElem = element[0].split(" ");
String averageSimilarity = element[1];
String topAsin = keyElem[0], overallAsin = keyElem[1];
Text newKey = new Text(topAsin);
context.write(newKey, new Text(overallAsin + " " + averageSimilarity));
}
}
public static class step3Reduce extends
Reducer<Text, Text, Text, Text> {
@Override
public void reduce(Text key, Iterable<Text> values,
Context context) throws IOException, InterruptedException {
PriorityQueue<SimilarObject> priorityQueue = new PriorityQueue<SimilarObject>();
for (Text val : values) {
String[] element = val.toString().split(" ");
String overallAsin = element[0];
float averageSimilarity = Float.parseFloat(element[1]);;
SimilarObject SimTempObj = new SimilarObject(overallAsin, averageSimilarity);
priorityQueue.offer(SimTempObj);
if(priorityQueue.size() > 10) {
priorityQueue.poll();
}
}
PriorityQueue<SimilarObject> reversedPriorityQueue = new PriorityQueue<SimilarObject>(priorityQueue.size(), Collections.reverseOrder());
reversedPriorityQueue.addAll(priorityQueue);
int i = 1;
while(!reversedPriorityQueue.isEmpty()) {
SimilarObject SimTempObj = reversedPriorityQueue.poll();
context.write(key, new Text(SimTempObj.toString() + " (" + i + ")"));
i++;
}
}
}
}
| 8,327 | 0.728873 | 0.715009 | 269 | 29.836432 | 27.13102 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.475837 | false | false | 8 |
0a5d6ec176203bf0ec2d71134d37b4a2862f814f | 2,095,944,045,274 | 789c4aee41029133423f07cacd284105a7cc57dc | /src/main/java/com/system/service/impl/ScheduleServiceImpl.java | a9e3e3b7a88598110c9ad8f0285dd40218dbb057 | [] | no_license | Kingking1994/91system | https://github.com/Kingking1994/91system | bcb44fe01fa4a2e805b39e7a9a6dabc5ed163c0e | addd3f6d62b01b06dd88ff29c7bf9640ffc3467b | refs/heads/master | 2020-12-24T18:51:41.429000 | 2016-05-29T11:40:06 | 2016-05-29T11:40:06 | 56,694,980 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.system.service.impl;
import com.system.dao.ScheduleDao;
import com.system.entity.Schedule;
import com.system.service.ScheduleService;
import com.system.util.BeanUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by king on 2016/4/26.
*/
@Service("scheduleService")
public class ScheduleServiceImpl implements ScheduleService {
private static final Logger LOGGER = Logger.getLogger(ScheduleServiceImpl.class);
@Autowired
private ScheduleDao scheduleDao;
public Schedule load(int id) {
LOGGER.info("load id = "+ id);
if(id == 0){
return null;
}else{
return scheduleDao.load(id);
}
}
public Schedule get(int id) {
LOGGER.info("get id = "+ id);
if(id == 0){
return null;
}else{
return scheduleDao.get(id);
}
}
public List<Schedule> findAll() {
LOGGER.info("findAll");
return scheduleDao.findAll();
}
public void persist(Schedule entity) {
LOGGER.info("persist entity = " + entity);
if(BeanUtil.nonNull(entity)){
scheduleDao.persist(entity);
}
}
public int save(Schedule entity) {
LOGGER.info("save entity = " + entity);
if(BeanUtil.nonNull(entity)){
return scheduleDao.save(entity);
}else{
return 0;
}
}
public void saveOrUpdate(Schedule entity) {
LOGGER.info("saveOrUpdate entity = " + entity);
if(BeanUtil.nonNull(entity)){
scheduleDao.saveOrUpdate(entity);
}
}
public void delete(int id) {
LOGGER.info("delete id = " + id);
if(id != 0){
scheduleDao.delete(id);
}
}
public void flush() {
LOGGER.info("flush");
scheduleDao.flush();
}
}
| UTF-8 | Java | 1,978 | java | ScheduleServiceImpl.java | Java | [
{
"context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by king on 2016/4/26.\n */\n@Service(\"scheduleService\")\npub",
"end": 369,
"score": 0.997721791267395,
"start": 365,
"tag": "USERNAME",
"value": "king"
}
] | null | [] | package com.system.service.impl;
import com.system.dao.ScheduleDao;
import com.system.entity.Schedule;
import com.system.service.ScheduleService;
import com.system.util.BeanUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by king on 2016/4/26.
*/
@Service("scheduleService")
public class ScheduleServiceImpl implements ScheduleService {
private static final Logger LOGGER = Logger.getLogger(ScheduleServiceImpl.class);
@Autowired
private ScheduleDao scheduleDao;
public Schedule load(int id) {
LOGGER.info("load id = "+ id);
if(id == 0){
return null;
}else{
return scheduleDao.load(id);
}
}
public Schedule get(int id) {
LOGGER.info("get id = "+ id);
if(id == 0){
return null;
}else{
return scheduleDao.get(id);
}
}
public List<Schedule> findAll() {
LOGGER.info("findAll");
return scheduleDao.findAll();
}
public void persist(Schedule entity) {
LOGGER.info("persist entity = " + entity);
if(BeanUtil.nonNull(entity)){
scheduleDao.persist(entity);
}
}
public int save(Schedule entity) {
LOGGER.info("save entity = " + entity);
if(BeanUtil.nonNull(entity)){
return scheduleDao.save(entity);
}else{
return 0;
}
}
public void saveOrUpdate(Schedule entity) {
LOGGER.info("saveOrUpdate entity = " + entity);
if(BeanUtil.nonNull(entity)){
scheduleDao.saveOrUpdate(entity);
}
}
public void delete(int id) {
LOGGER.info("delete id = " + id);
if(id != 0){
scheduleDao.delete(id);
}
}
public void flush() {
LOGGER.info("flush");
scheduleDao.flush();
}
}
| 1,978 | 0.595551 | 0.589484 | 81 | 23.419754 | 18.677156 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false | 8 |
e620701323822e6acef2f0d36aa61bfa33d68643 | 26,439,818,683,008 | d45db2a105b86b8b584a0b7539800cea14251417 | /src/main/java/org/sirenia/test/util/PropertiesUtil.java | 3731fba8debb83be4599cf1e8828d24f77b2ab6d | [] | no_license | zhoujiaping/sirenia-test | https://github.com/zhoujiaping/sirenia-test | eeecc7a1f206ad0b3d0e6051538f8b60cb616d5a | dc3d9ba6ebbb49324c828aebeae410a4de6ca98a | refs/heads/master | 2020-04-22T16:05:16.026000 | 2019-05-04T01:32:54 | 2019-05-04T01:32:54 | 170,497,092 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sirenia.test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* https://www.hellojava.com/a/158.html
*
*/
public class PropertiesUtil {
public static Properties loadProperties(File file){
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"))) {
Properties prop = new Properties();
prop.load(reader);
return prop;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| UTF-8 | Java | 569 | java | PropertiesUtil.java | Java | [] | null | [] | package org.sirenia.test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* https://www.hellojava.com/a/158.html
*
*/
public class PropertiesUtil {
public static Properties loadProperties(File file){
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"))) {
Properties prop = new Properties();
prop.load(reader);
return prop;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 569 | 0.739895 | 0.732865 | 22 | 24.863636 | 23.587931 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.409091 | false | false | 8 |
128f24fb04fea635c49a7f2734dd6187fee3a52e | 2,095,944,050,135 | 1aa1a384277f871e2d870f9d15d5c5ce2ff21e10 | /src/main/java/com/ydhl/outsourcing/ts/finance/common/utils/EaringsUtil.java | 7d562242fe9652357f1c8e1aa6bdc249f14364b1 | [] | no_license | yangyisong/bikong | https://github.com/yangyisong/bikong | 4c95bb93e01408f68b7f0d9faac81d004f2d31db | e78b1ed32f0521b7667b890237e5d4f8c28b0720 | refs/heads/master | 2020-04-11T02:30:09.156000 | 2018-12-12T08:02:21 | 2018-12-12T08:02:31 | 161,446,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ydhl.outsourcing.ts.finance.common.utils;
import java.math.BigDecimal;
/**
* @author Martins
* @create 2018/1/26 10:41.
* @description
*/
public class EaringsUtil {
//保留两位小数
private static final Integer SCALE = 2;
/**
* 计算每日收益
*
* @param amount 合同金额
* @param earingRatio 年收益比
* @return 每日收益
*/
public static BigDecimal getEverydayEarning(BigDecimal amount, BigDecimal earingRatio) {
/*BigDecimal dayEarning = amount.multiply(earingRatio).divide(new BigDecimal(360), SCALE, BigDecimal.ROUND_HALF_UP);*/
BigDecimal dayEarning = amount.multiply(earingRatio.divide(new BigDecimal(100), 10 , BigDecimal.ROUND_HALF_UP)).divide(new BigDecimal(360), 10, BigDecimal.ROUND_HALF_UP);
return dayEarning;
}
}
| UTF-8 | Java | 838 | java | EaringsUtil.java | Java | [
{
"context": "ils;\n\nimport java.math.BigDecimal;\n\n/**\n * @author Martins\n * @create 2018/1/26 10:41.\n * @description\n */\np",
"end": 107,
"score": 0.9954768419265747,
"start": 100,
"tag": "NAME",
"value": "Martins"
}
] | null | [] | package com.ydhl.outsourcing.ts.finance.common.utils;
import java.math.BigDecimal;
/**
* @author Martins
* @create 2018/1/26 10:41.
* @description
*/
public class EaringsUtil {
//保留两位小数
private static final Integer SCALE = 2;
/**
* 计算每日收益
*
* @param amount 合同金额
* @param earingRatio 年收益比
* @return 每日收益
*/
public static BigDecimal getEverydayEarning(BigDecimal amount, BigDecimal earingRatio) {
/*BigDecimal dayEarning = amount.multiply(earingRatio).divide(new BigDecimal(360), SCALE, BigDecimal.ROUND_HALF_UP);*/
BigDecimal dayEarning = amount.multiply(earingRatio.divide(new BigDecimal(100), 10 , BigDecimal.ROUND_HALF_UP)).divide(new BigDecimal(360), 10, BigDecimal.ROUND_HALF_UP);
return dayEarning;
}
}
| 838 | 0.68481 | 0.653165 | 27 | 28.25926 | 40.784523 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 8 |
94220310724aa1384afd975f1286d492d11c9b7e | 6,296,422,068,200 | a36236e5f1931682f866e351a9c73b72e2310d4c | /src/main/java/com/spotify/spire/arbiter/TaskBrokerConfiguration.java | 71afe0e4b04149046d82f9edc024dc00df7a700e | [
"Apache-2.0"
] | permissive | pombredanne/spire-server | https://github.com/pombredanne/spire-server | e9ede8767b742097a8d215b9644f742ee8793bb4 | c0abe19ef898e2341d959cc918595ca36a29a7b1 | refs/heads/master | 2017-11-15T00:29:19.374000 | 2013-12-20T15:23:47 | 2013-12-20T15:23:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spotify.spire.arbiter;
import java.net.URI;
import com.spotify.spire.master.util.RabbitMqConnectionConfiguration;
import com.spotify.spire.proto.Spire;
import lombok.Data;
/**
* See spire-arbiter.conf for more information about these settings.
**/
@Data
public class TaskBrokerConfiguration implements RabbitMqConnectionConfiguration {
private int heartbeatInterval;
private String queueNameTemplate;
private URI rabbitMqUri;
}
| UTF-8 | Java | 447 | java | TaskBrokerConfiguration.java | Java | [] | null | [] | package com.spotify.spire.arbiter;
import java.net.URI;
import com.spotify.spire.master.util.RabbitMqConnectionConfiguration;
import com.spotify.spire.proto.Spire;
import lombok.Data;
/**
* See spire-arbiter.conf for more information about these settings.
**/
@Data
public class TaskBrokerConfiguration implements RabbitMqConnectionConfiguration {
private int heartbeatInterval;
private String queueNameTemplate;
private URI rabbitMqUri;
}
| 447 | 0.818792 | 0.818792 | 17 | 25.294117 | 25.60047 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 8 |
3397f5eeb0032d6ba1fa4bd105775d6a22e4c0c1 | 20,126,216,759,298 | ba7ac7e433af4cfccd65458d77921167c2f59b8c | /chatroom/src/main/java/org/springboot/chatroom/service/impl/MailServiceImpl.java | ea74706961c12350573a63b7818fe649472e0b63 | [] | no_license | paidaxing-puls/chatroom | https://github.com/paidaxing-puls/chatroom | f640e713144d677721883dfce462664820e068fc | d0ab71109b3f934cce03d87f65112ad6d72eaa95 | refs/heads/main | 2023-01-30T21:37:27.014000 | 2020-12-11T02:13:44 | 2020-12-11T02:13:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.springboot.chatroom.service.impl;
import org.springboot.chatroom.service.MailService;
import org.springboot.chatroom.utils.MailUtil;
import org.springboot.chatroom.vo.MailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class MailServiceImpl implements MailService {
@Autowired
MailUtil mailUtil;
@Override
public boolean sendMail(MailVo mailVo) {
if(mailUtil.sendMail(mailVo) != null){
return true;
}else{
return false;
}
}
@Override
public void receiveMail(MailVo mailVo) {
}
@Override
public boolean deleteMail(String id) {
return false;
}
@Override
public boolean saveMail(MailVo mailVo) {
return false;
}
@Override
public boolean sendMailAtSpecifiedTime(MailVo mailVo, Date date) {
return false;
}
}
| UTF-8 | Java | 1,018 | java | MailServiceImpl.java | Java | [] | null | [] | package org.springboot.chatroom.service.impl;
import org.springboot.chatroom.service.MailService;
import org.springboot.chatroom.utils.MailUtil;
import org.springboot.chatroom.vo.MailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class MailServiceImpl implements MailService {
@Autowired
MailUtil mailUtil;
@Override
public boolean sendMail(MailVo mailVo) {
if(mailUtil.sendMail(mailVo) != null){
return true;
}else{
return false;
}
}
@Override
public void receiveMail(MailVo mailVo) {
}
@Override
public boolean deleteMail(String id) {
return false;
}
@Override
public boolean saveMail(MailVo mailVo) {
return false;
}
@Override
public boolean sendMailAtSpecifiedTime(MailVo mailVo, Date date) {
return false;
}
}
| 1,018 | 0.652259 | 0.652259 | 46 | 20.130434 | 19.857765 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 8 |
0e05081bd7ee4c4fdc0b30ecebb5b76b7a049846 | 20,624,432,965,063 | 0b59cd6298cd4e12334b7fc3d56078a7667e3c56 | /android/app/src/main/java/come/manager/direct/hackuniversity/CloseListFragment.java | 67ff9832fa29ef552737e3b66808916c25e41939 | [] | no_license | kanzeparov/hackuniversity | https://github.com/kanzeparov/hackuniversity | 91022df5f513a995c8dd511a5469773cae1efc90 | 7ff3ccf243e3a36567957a6ac46db9780103fa5e | refs/heads/master | 2020-05-01T04:12:57.169000 | 2019-03-24T08:59:28 | 2019-03-24T08:59:28 | 177,267,640 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package come.manager.direct.hackuniversity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CloseListFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private WebView webView;
private static final String ARG_PARAM2 = "param2";
private RecyclerView rvNumbers;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CloseListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
String [] numbers = {"Oergregrene", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
rvNumbers = (RecyclerView) view.findViewById(R.id.rv_numbers);
rvNumbers.setLayoutManager(new LinearLayoutManager(getActivity()));
rvNumbers.setAdapter(new RecyclerViewAdapter(numbers));
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
String listData[];
public RecyclerViewAdapter(String data[]){
this.listData = data;
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
RecyclerViewAdapter.ViewHolder vh = new RecyclerViewAdapter.ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
holder.tvNumber.setText(listData[position]);
}
@Override
public int getItemCount() {
return listData.length;
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvNumber;
public ViewHolder(View v) {
super(v);
// tvNumber = (TextView) v.findViewById(R.id.tv_number);
}
}
}
}
| UTF-8 | Java | 5,142 | java | CloseListFragment.java | Java | [
{
"context": " container, false);\n String [] numbers = {\"Oergregrene\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\",",
"end": 2555,
"score": 0.9938181638717651,
"start": 2544,
"tag": "NAME",
"value": "Oergregrene"
}
] | null | [] | package come.manager.direct.hackuniversity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CloseListFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private WebView webView;
private static final String ARG_PARAM2 = "param2";
private RecyclerView rvNumbers;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CloseListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list, container, false);
String [] numbers = {"Oergregrene", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
rvNumbers = (RecyclerView) view.findViewById(R.id.rv_numbers);
rvNumbers.setLayoutManager(new LinearLayoutManager(getActivity()));
rvNumbers.setAdapter(new RecyclerViewAdapter(numbers));
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
String listData[];
public RecyclerViewAdapter(String data[]){
this.listData = data;
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
RecyclerViewAdapter.ViewHolder vh = new RecyclerViewAdapter.ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
holder.tvNumber.setText(listData[position]);
}
@Override
public int getItemCount() {
return listData.length;
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvNumber;
public ViewHolder(View v) {
super(v);
// tvNumber = (TextView) v.findViewById(R.id.tv_number);
}
}
}
}
| 5,142 | 0.668222 | 0.66375 | 149 | 33.510067 | 26.836971 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483221 | false | false | 8 |
831f1fc3f4aa5730182c6af5373175cc6fedba1c | 27,762,668,613,185 | 41b3cb388090f2ad8b56db8b1915e59362177794 | /dome-module-1/src/com/duyi/MianTest.java | 73f2089537a46df97d6d7066d59f3654bc64e615 | [] | no_license | pu0513/Git-Dome | https://github.com/pu0513/Git-Dome | f4203e9b5c5fae4d07b592354bf902f8c00e2fd4 | a76b737af641792d3fcdb6bb9c0cef07aa6745ac | refs/heads/master | 2023-03-13T05:03:05.183000 | 2021-02-27T15:11:05 | 2021-02-27T15:11:05 | 342,870,756 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duyi;
/**
* @Auther: php
* @Date: 2021/2/27 - 02 - 27 - 22:14
* @Description: com.duyi
* @version: 1.0
*/
public class MianTest {
public static void main(String[] args) {
System.out.println("hello git");
System.out.println("git change");
}
}
| UTF-8 | Java | 285 | java | MianTest.java | Java | [
{
"context": "package com.duyi;\n\n/**\n * @Auther: php\n * @Date: 2021/2/27 - 02 - 27 - 22:14\n * @Descrip",
"end": 38,
"score": 0.9989520311355591,
"start": 35,
"tag": "USERNAME",
"value": "php"
}
] | null | [] | package com.duyi;
/**
* @Auther: php
* @Date: 2021/2/27 - 02 - 27 - 22:14
* @Description: com.duyi
* @version: 1.0
*/
public class MianTest {
public static void main(String[] args) {
System.out.println("hello git");
System.out.println("git change");
}
}
| 285 | 0.585965 | 0.526316 | 15 | 18 | 15.692885 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
8a310139cf614041ab0be79435126b3b7b6887ef | 27,762,668,613,308 | a2b28b6bbc055e8b2d4d06185443322789f809cf | /src/test/java/nio/path/TestAttribute.java | 0a72f7501e8f2ede3e593673860adcfa36552d7b | [] | no_license | mygithubzh123/BasicPractising | https://github.com/mygithubzh123/BasicPractising | c3a64f427b3ebb26481dd0690822f131b2ac67d3 | 35c3bf1a5b79b464c4fd126e900a38bc812e0b36 | refs/heads/master | 2022-06-26T20:20:43.437000 | 2020-09-05T12:30:57 | 2020-09-05T12:30:57 | 162,976,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* (用一句话描述该文件做什么)
* @Filename TestAttribute.java
* @Package nio.path
* @author neo
* @since 2018年4月3日 下午7:10:10
* @Version V1.0
*/
package nio.path;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
/**
* (这里用一句话描述这个类的作用)
* TestAttribute
* @author neo
* @since 2018年4月3日 下午7:10:10
*/
public class TestAttribute {
Path p = Paths.get("C:\\Users\\neo\\Desktop\\abc");
@Test
public void test() throws IOException{
Files.createFile(p, new FileAttribute<String>() {
@Override
public String name() {
return "length";
}
@Override
public String value() {
return "123";
}
});
}
@Test
public void test1()throws Exception{
BasicFileAttributes bfa = Files.readAttributes(p, BasicFileAttributes.class);
System.out.println(bfa.creationTime());
BasicFileAttributeView bfav = Files.getFileAttributeView(p, BasicFileAttributeView.class);
System.out.println(bfav);
}
}
| UTF-8 | Java | 1,299 | java | TestAttribute.java | Java | [
{
"context": "TestAttribute.java\r\n* @Package nio.path\r\n* @author neo\r\n* @since 2018年4月3日 下午7:10:10\r\n* @Version V1.0\r\n*",
"end": 91,
"score": 0.6448214054107666,
"start": 88,
"tag": "USERNAME",
"value": "neo"
},
{
"context": " (这里用一句话描述这个类的作用)\r\n * TestAttribute\r\n * @a... | null | [] | /**
* (用一句话描述该文件做什么)
* @Filename TestAttribute.java
* @Package nio.path
* @author neo
* @since 2018年4月3日 下午7:10:10
* @Version V1.0
*/
package nio.path;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
/**
* (这里用一句话描述这个类的作用)
* TestAttribute
* @author neo
* @since 2018年4月3日 下午7:10:10
*/
public class TestAttribute {
Path p = Paths.get("C:\\Users\\neo\\Desktop\\abc");
@Test
public void test() throws IOException{
Files.createFile(p, new FileAttribute<String>() {
@Override
public String name() {
return "length";
}
@Override
public String value() {
return "123";
}
});
}
@Test
public void test1()throws Exception{
BasicFileAttributes bfa = Files.readAttributes(p, BasicFileAttributes.class);
System.out.println(bfa.creationTime());
BasicFileAttributeView bfav = Files.getFileAttributeView(p, BasicFileAttributeView.class);
System.out.println(bfav);
}
}
| 1,299 | 0.683782 | 0.660962 | 55 | 20.309092 | 20.142107 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.254545 | false | false | 8 |
83e493ed86d530437bcb2749268e8bdd0da93f70 | 27,762,668,613,202 | 5750fd38e50050918b016b521c00d6b1b65f2ace | /app/src/main/java/com/sergiomse/encuentralo/model/Thing.java | f919d29f2ad866deddca9cd3235b7ab15ff84233 | [] | no_license | smillase/Encuentralo | https://github.com/smillase/Encuentralo | c4cc33eb1c3bb28f0335796069a413ed928045cd | f6779cd7d2f17fe00416ddeacecb49936bf84a40 | refs/heads/master | 2021-01-10T03:34:31.466000 | 2015-10-25T20:27:53 | 2015-10-25T20:27:53 | 43,002,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sergiomse.encuentralo.model;
import java.util.Date;
/**
* Created by sergiomse@gmail.com on 24/09/2015.
*/
public class Thing {
private long id;
private String imagePath;
private String tags;
private String location;
private Date modifDate;
public Thing() {
}
public Thing(long id, String imagePath, String tags, String location, Date modifDate) {
this.id = id;
this.imagePath = imagePath;
this.tags = tags;
this.location = location;
this.modifDate = modifDate;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getModifDate() {
return modifDate;
}
public void setModifDate(Date modifDate) {
this.modifDate = modifDate;
}
}
| UTF-8 | Java | 1,341 | java | Thing.java | Java | [
{
"context": "l;\r\n\r\nimport java.util.Date;\r\n\r\n/**\r\n * Created by sergiomse@gmail.com on 24/09/2015.\r\n */\r\npublic class Thing {\r\n\r\n ",
"end": 108,
"score": 0.9999250173568726,
"start": 89,
"tag": "EMAIL",
"value": "sergiomse@gmail.com"
}
] | null | [] | package com.sergiomse.encuentralo.model;
import java.util.Date;
/**
* Created by <EMAIL> on 24/09/2015.
*/
public class Thing {
private long id;
private String imagePath;
private String tags;
private String location;
private Date modifDate;
public Thing() {
}
public Thing(long id, String imagePath, String tags, String location, Date modifDate) {
this.id = id;
this.imagePath = imagePath;
this.tags = tags;
this.location = location;
this.modifDate = modifDate;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getModifDate() {
return modifDate;
}
public void setModifDate(Date modifDate) {
this.modifDate = modifDate;
}
}
| 1,329 | 0.571216 | 0.56525 | 66 | 18.318182 | 17.611256 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393939 | false | false | 8 |
6095f5e479171e0e2856036f02cf98357eadd938 | 2,130,303,786,781 | e1d0fd6f65cca1c0257f7327efba37a12c8eadb5 | /src/main/java/com/nathan/beans/package-info.java | 81a7705949fe41a07520ed69310f34a9a02df540 | [] | no_license | NathanPelli/webtest | https://github.com/NathanPelli/webtest | 881f5402427f772bad594c825f801f8814b06923 | 295ffad814241355dd9e57980db11e49280e0666 | refs/heads/master | 2021-05-05T17:57:58.510000 | 2017-12-07T03:39:23 | 2017-12-07T03:39:23 | 103,512,936 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
/**@author Nathan
* 2017年9月14日 下午2:29:08
*/
package com.nathan.beans; | UTF-8 | Java | 93 | java | package-info.java | Java | [
{
"context": "/**\n * \n */\n/**@author Nathan\n * 2017年9月14日 下午2:29:08\n */\npackage com.nathan.be",
"end": 29,
"score": 0.9982943534851074,
"start": 23,
"tag": "NAME",
"value": "Nathan"
}
] | null | [] | /**
*
*/
/**@author Nathan
* 2017年9月14日 下午2:29:08
*/
package com.nathan.beans; | 93 | 0.60241 | 0.457831 | 7 | 11 | 9.50188 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 8 |
4a67da7f1cf868bd5801b14373de804e30df7d9e | 455,266,587,802 | cc5ed8da10aa3c2537bc1bc118a06747545b1108 | /Tutorial2/src/Main.java | ec2ad98cee466bf60370870fcc870ad42706c7b7 | [] | no_license | Arinjbj/startjava | https://github.com/Arinjbj/startjava | 1bc6a326c8dcc67647a5d1339b8093645ee17d3f | dcf7ffc9fd2bd0744fdc0345f40553ae036b6549 | refs/heads/master | 2022-11-30T21:33:04.931000 | 2020-08-13T13:52:52 | 2020-08-13T13:52:52 | 279,297,329 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Main {
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
int c = (int)1.5;
System.out.println(c);
double d = 0.6;
int e = (int) (d + 0.5);
System.out.println(e);
}
}
| UTF-8 | Java | 444 | java | Main.java | Java | [] | null | [] |
public class Main {
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
int c = (int)1.5;
System.out.println(c);
double d = 0.6;
int e = (int) (d + 0.5);
System.out.println(e);
}
}
| 444 | 0.488739 | 0.470721 | 23 | 18.26087 | 16.686932 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 8 |
3523a790ca3e59e34266e620f493b79650f7067f | 8,667,244,046,129 | 18991d28d41dcab1301c243d6813af412681f6c8 | /java/aop/src/main/java/io/aos/aop/aspectj/auth/AspectJAuthModule.java | 564874f1c499861769cbf90f45f857846f7ee799 | [
"Apache-2.0"
] | permissive | XClouded/t4f-core | https://github.com/XClouded/t4f-core | 3eecdc91df3bf55c23d1a11a8039429345eca452 | 73b89abe758007a8fc42f378aeab3402760a0fa9 | refs/heads/master | 2020-12-24T16:15:42.610000 | 2014-11-03T09:37:22 | 2014-11-03T09:37:22 | 26,402,580 | 0 | 1 | null | false | 2016-03-09T23:11:46 | 2014-11-09T17:07:33 | 2015-01-24T14:08:55 | 2016-03-09T23:11:46 | 56,540 | 0 | 1 | 1 | null | null | null | package io.aos.aop.aspectj.auth;
import static org.aspectj.lang.Aspects.aspectOf;
import io.aos.aop.aspectj.auth.aspect.ProfileVerificationAspect;
import io.aos.aop.aspectj.auth.auth.UserProfileChecker;
import io.aos.aop.aspectj.auth.auth.UserProfileCheckerImpl;
import io.aos.aop.aspectj.auth.contact.ContactManager;
import io.aos.aop.aspectj.auth.contact.ContactManagerImpl;
import com.google.inject.AbstractModule;
public class AspectJAuthModule extends AbstractModule {
@Override
protected void configure() {
bind(ContactManager.class).to(ContactManagerImpl.class).asEagerSingleton();
bind(UserProfileChecker.class).to(UserProfileCheckerImpl.class).asEagerSingleton();
requestInjection(aspectOf(ProfileVerificationAspect.class));
}
}
| UTF-8 | Java | 779 | java | AspectJAuthModule.java | Java | [] | null | [] | package io.aos.aop.aspectj.auth;
import static org.aspectj.lang.Aspects.aspectOf;
import io.aos.aop.aspectj.auth.aspect.ProfileVerificationAspect;
import io.aos.aop.aspectj.auth.auth.UserProfileChecker;
import io.aos.aop.aspectj.auth.auth.UserProfileCheckerImpl;
import io.aos.aop.aspectj.auth.contact.ContactManager;
import io.aos.aop.aspectj.auth.contact.ContactManagerImpl;
import com.google.inject.AbstractModule;
public class AspectJAuthModule extends AbstractModule {
@Override
protected void configure() {
bind(ContactManager.class).to(ContactManagerImpl.class).asEagerSingleton();
bind(UserProfileChecker.class).to(UserProfileCheckerImpl.class).asEagerSingleton();
requestInjection(aspectOf(ProfileVerificationAspect.class));
}
}
| 779 | 0.797176 | 0.797176 | 21 | 36.095238 | 29.671061 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 8 |
f97561f7604360291892dccd3699d6b5a0dfe810 | 25,993,142,115,912 | 9e736247941800694340edb8a7ffe0a2da0f14b3 | /service-datapack/src/main/java/com/dataint/service/datapack/dao/IDiseasesDao.java | b04bf303bd7c6fcac2716602a81c73e10a37c582 | [] | no_license | cgb-jsqlparser/Customers | https://github.com/cgb-jsqlparser/Customers | 20deef64d2bab6e69383c23273d72f48cf7a5d13 | 613d36413e1839d47f711d127747f8a1d6b06ac8 | refs/heads/master | 2023-07-22T05:10:28.500000 | 2020-09-09T09:36:20 | 2020-09-09T09:36:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dataint.service.datapack.dao;
import com.dataint.service.datapack.dao.entity.Diseases;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IDiseasesDao extends JpaRepository<Diseases, Integer>, JpaSpecificationExecutor<Diseases> {
Diseases findByNameCn(String nameCn);
List<Diseases> findByNameCnLike(String nameCn);
Diseases findByNameCnOrNameEn(String nameCn, String nameEn);
}
| UTF-8 | Java | 595 | java | IDiseasesDao.java | Java | [] | null | [] | package com.dataint.service.datapack.dao;
import com.dataint.service.datapack.dao.entity.Diseases;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IDiseasesDao extends JpaRepository<Diseases, Integer>, JpaSpecificationExecutor<Diseases> {
Diseases findByNameCn(String nameCn);
List<Diseases> findByNameCnLike(String nameCn);
Diseases findByNameCnOrNameEn(String nameCn, String nameEn);
}
| 595 | 0.826891 | 0.826891 | 18 | 32.055557 | 31.863375 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 8 |
8d9dbe6eccbabeb79984fcdd0ddbc45c1167eda7 | 25,769,819,565 | 06049bed4970b40b9d6ffe3d3d89d6263b468601 | /md-stepper-addon/src/main/java/org/vaadin/addons/md_stepper/iterator/MoveToListener.java | 80c980d88312f900e06b5050738f047a45a39c19 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | jpvelsamy/md-stepper | https://github.com/jpvelsamy/md-stepper | aec00a47370fd8144c2568bba527ba6c3db92688 | 6e30af58faf183e65eb0c4098a58b03eb2bfd642 | refs/heads/master | 2021-05-17T12:39:54.860000 | 2020-07-06T09:11:45 | 2020-07-06T09:11:45 | 250,781,363 | 0 | 0 | Apache-2.0 | true | 2020-03-28T11:49:16 | 2020-03-28T11:49:15 | 2019-10-04T12:37:04 | 2017-08-11T12:19:15 | 135 | 0 | 0 | 0 | null | false | false | package org.vaadin.addons.md_stepper.iterator;
import java.util.Iterator;
/**
* Listener that is triggered whenever an iterator moves.
*
* @param <E>
* The type of the elements of the iterator
*/
@FunctionalInterface
public interface MoveToListener<E> extends PositionableIterationListener {
/**
* Triggered when the iterator is moved.
*
* @param event
* Event that contains information about the move
*/
void onMoveTo(MoveToEvent<E> event);
/**
* An event fired when an iterator moves.
*
* @param <E>
* The type of the element of the iterator
*/
class MoveToEvent<E> extends PositionableIterationEvent<E> {
/**
* Construct a new iteration event.
*
* @param source
* The iterator that causes the event
* @param previous
* The current element <b>before</b> the iteration
* @param current
* The current element <b>after</b> the iteration
*/
public MoveToEvent(Iterator<E> source, E previous, E current) {
super(source, previous, current);
}
}
}
| UTF-8 | Java | 1,080 | java | MoveToListener.java | Java | [] | null | [] | package org.vaadin.addons.md_stepper.iterator;
import java.util.Iterator;
/**
* Listener that is triggered whenever an iterator moves.
*
* @param <E>
* The type of the elements of the iterator
*/
@FunctionalInterface
public interface MoveToListener<E> extends PositionableIterationListener {
/**
* Triggered when the iterator is moved.
*
* @param event
* Event that contains information about the move
*/
void onMoveTo(MoveToEvent<E> event);
/**
* An event fired when an iterator moves.
*
* @param <E>
* The type of the element of the iterator
*/
class MoveToEvent<E> extends PositionableIterationEvent<E> {
/**
* Construct a new iteration event.
*
* @param source
* The iterator that causes the event
* @param previous
* The current element <b>before</b> the iteration
* @param current
* The current element <b>after</b> the iteration
*/
public MoveToEvent(Iterator<E> source, E previous, E current) {
super(source, previous, current);
}
}
}
| 1,080 | 0.649074 | 0.649074 | 44 | 23.545454 | 22.594704 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 8 |
79e3acb5dcb94f88cc7aa20cd4637646c2f8430c | 33,543,694,646,251 | 54f8a30a9284c740a1b0a05075348e273fb78d78 | /Utils/SHDL2VHDL/src/org/jcb/shdl/shdlc/java/S_CMD11_SHDL.java | c1f921e378dc8c08c59258cfe3f4b21591eaceaa | [] | no_license | Kiddinglife/CRAPS-Kernel | https://github.com/Kiddinglife/CRAPS-Kernel | deca4033dc4fcc420a50cb0c432cd2085bf693f9 | 92b4d348f4b0eca1f7ebb4c57b42c49475c8d0b0 | refs/heads/master | 2021-05-05T18:17:44.215000 | 2015-03-13T01:44:37 | 2015-03-13T01:44:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jcb.shdl.shdlc.java;
import mg.egg.eggc.libjava.lex.*;
import mg.egg.eggc.libjava.*;
class S_CMD11_SHDL {
S_CMD11_SHDL(LEX_SHDL att_scanner) {
this.att_scanner = att_scanner;
}
SHDLCombinatorialSetting att_hcombinSetting;
SHDLSignal att_hsignal;
SHDLSequentialSetting att_seqSetting;
SHDLModule att_hmodule;
LEX_SHDL att_scanner;
SHDLSequentialModifier glob_seqModifier;
private void regle30() throws EGGException {
//declaration
T_ident_SHDL x_1 = new T_ident_SHDL(att_scanner ) ;
S_SIGNAL__SHDL x_4 = new S_SIGNAL__SHDL(att_scanner) ;
//appel
x_1.analyser() ;
att_scanner.accepter_sucre(LEX_SHDL.token_aff ) ;
action_trans_30(x_1, x_4);
x_4.analyser() ;
action_set_30(x_1, x_4);
att_scanner.accepter_sucre(LEX_SHDL.token_pv ) ;
}
private void action_set_30(T_ident_SHDL x_1, S_SIGNAL__SHDL x_4) throws EGGException {
// locales
// instructions
glob_seqModifier.setSignalOccurence(x_4.att_signalOccurence);
}
private void action_trans_30(T_ident_SHDL x_1, S_SIGNAL__SHDL x_4) throws EGGException {
// locales
// instructions
glob_seqModifier= new SHDLSequentialModifier(this.att_scanner.getBeginLine(), this.att_hmodule);
glob_seqModifier.setSignal(this.att_hsignal);
glob_seqModifier.setModifier(x_1.att_txt);
this.att_hmodule.addSeqModifier(glob_seqModifier);
if (x_1.att_txt.equalsIgnoreCase("clk")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("rst")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("set")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("ena")){
x_4.att_hmodule=this.att_hmodule;
}
else {
{ String as[]={
""+x_1.att_txt, ""+x_1.att_txt}
;att_scanner._interrompre(att_scanner.messages.P_02,as);
}
}
this.att_seqSetting=null;
}
public void analyser () throws EGGException { regle30 () ;
}
}
| UTF-8 | Java | 1,906 | java | S_CMD11_SHDL.java | Java | [] | null | [] | package org.jcb.shdl.shdlc.java;
import mg.egg.eggc.libjava.lex.*;
import mg.egg.eggc.libjava.*;
class S_CMD11_SHDL {
S_CMD11_SHDL(LEX_SHDL att_scanner) {
this.att_scanner = att_scanner;
}
SHDLCombinatorialSetting att_hcombinSetting;
SHDLSignal att_hsignal;
SHDLSequentialSetting att_seqSetting;
SHDLModule att_hmodule;
LEX_SHDL att_scanner;
SHDLSequentialModifier glob_seqModifier;
private void regle30() throws EGGException {
//declaration
T_ident_SHDL x_1 = new T_ident_SHDL(att_scanner ) ;
S_SIGNAL__SHDL x_4 = new S_SIGNAL__SHDL(att_scanner) ;
//appel
x_1.analyser() ;
att_scanner.accepter_sucre(LEX_SHDL.token_aff ) ;
action_trans_30(x_1, x_4);
x_4.analyser() ;
action_set_30(x_1, x_4);
att_scanner.accepter_sucre(LEX_SHDL.token_pv ) ;
}
private void action_set_30(T_ident_SHDL x_1, S_SIGNAL__SHDL x_4) throws EGGException {
// locales
// instructions
glob_seqModifier.setSignalOccurence(x_4.att_signalOccurence);
}
private void action_trans_30(T_ident_SHDL x_1, S_SIGNAL__SHDL x_4) throws EGGException {
// locales
// instructions
glob_seqModifier= new SHDLSequentialModifier(this.att_scanner.getBeginLine(), this.att_hmodule);
glob_seqModifier.setSignal(this.att_hsignal);
glob_seqModifier.setModifier(x_1.att_txt);
this.att_hmodule.addSeqModifier(glob_seqModifier);
if (x_1.att_txt.equalsIgnoreCase("clk")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("rst")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("set")){
x_4.att_hmodule=this.att_hmodule;
}
else if (x_1.att_txt.equalsIgnoreCase("ena")){
x_4.att_hmodule=this.att_hmodule;
}
else {
{ String as[]={
""+x_1.att_txt, ""+x_1.att_txt}
;att_scanner._interrompre(att_scanner.messages.P_02,as);
}
}
this.att_seqSetting=null;
}
public void analyser () throws EGGException { regle30 () ;
}
}
| 1,906 | 0.705666 | 0.683631 | 61 | 30.229507 | 23.063984 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622951 | false | false | 8 |
aaba317c9cfd5a0bf679c6244a5d8e1e9d3e66c4 | 1,898,375,547,810 | 5d6e69f650be0c72231971fb7e0f745269836885 | /src/com/javaguru/lessons/lesson9/homework/UniqueWordCounterTest.java | 86b752cfebb57500ccde17dadcd054a84e480065 | [] | no_license | KarinaKuznecova/HomeWorkFromCourses | https://github.com/KarinaKuznecova/HomeWorkFromCourses | eb82c9f5fe444c8b31f6eb6e172748a7430a22ab | 9ddb15d35172d6d8ed0c67e7e15521f8833b4688 | refs/heads/master | 2020-04-22T20:41:47.055000 | 2019-04-17T07:13:03 | 2019-04-17T07:13:03 | 170,649,375 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javaguru.lessons.lesson9.homework;
class UniqueWordCounterTest {
public static void main(String[] args) {
UniqueWordCounterTest testRunner = new UniqueWordCounterTest();
testRunner.shouldAddUniqueWord();
testRunner.shouldAddDuplicate();
testRunner.shouldNotAddEmptyString();
testRunner.shouldNotAddNull();
testRunner.shouldReturnMostPopular();
}
private void shouldAddUniqueWord() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount() + 1;
String testLine = "Java";
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldAddUniqueWord");
}
private void shouldAddDuplicate() {
UniqueWordCounter victim = new UniqueWordCounter();
System.out.println("Should add duplicate and increase counter:");
String testLine = "Java";
victim.AddWord(testLine);
victim.AddWord("Java");
victim.printToConsole();
System.out.println("* * *");
}
private void shouldNotAddEmptyString() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount();
String testLine = "";
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldNotAddEmptyString");
}
private void shouldNotAddNull() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount();
String testLine = null;
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldNotAddNull");
}
private void shouldReturnMostPopular() {
UniqueWordCounter victim = new UniqueWordCounter();
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Tea");
victim.AddWord("Tea");
String expected = "Coffee";
String actual = victim.getMostPopularWord();
victim.printToConsole();
System.out.println("Most popular word: " + victim.getMostPopularWord());
check(expected, actual, "shouldReturnMostPopular");
}
private void check(int expected, int actual, String testName) {
if (actual == expected) {
System.out.println(testName + " has passed");
} else {
System.out.println(testName + " has failed");
System.out.println("Expected: " + expected + ", Actual: " + actual);
}
System.out.println("* * *");
}
private void check(String expected, String actual, String testName) {
if (actual.equals(expected)) {
System.out.println(testName + " has passed");
} else {
System.out.println(testName + " has failed");
System.out.println("Expected: " + expected + ", Actual: " + actual);
}
System.out.println("* * *");
}
}
| UTF-8 | Java | 3,227 | java | UniqueWordCounterTest.java | Java | [] | null | [] | package com.javaguru.lessons.lesson9.homework;
class UniqueWordCounterTest {
public static void main(String[] args) {
UniqueWordCounterTest testRunner = new UniqueWordCounterTest();
testRunner.shouldAddUniqueWord();
testRunner.shouldAddDuplicate();
testRunner.shouldNotAddEmptyString();
testRunner.shouldNotAddNull();
testRunner.shouldReturnMostPopular();
}
private void shouldAddUniqueWord() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount() + 1;
String testLine = "Java";
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldAddUniqueWord");
}
private void shouldAddDuplicate() {
UniqueWordCounter victim = new UniqueWordCounter();
System.out.println("Should add duplicate and increase counter:");
String testLine = "Java";
victim.AddWord(testLine);
victim.AddWord("Java");
victim.printToConsole();
System.out.println("* * *");
}
private void shouldNotAddEmptyString() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount();
String testLine = "";
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldNotAddEmptyString");
}
private void shouldNotAddNull() {
UniqueWordCounter victim = new UniqueWordCounter();
int expected = victim.getUniqueWordCount();
String testLine = null;
victim.AddWord(testLine);
int actual = victim.getUniqueWordCount();
victim.printToConsole();
check(expected, actual, "shouldNotAddNull");
}
private void shouldReturnMostPopular() {
UniqueWordCounter victim = new UniqueWordCounter();
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Coffee");
victim.AddWord("Tea");
victim.AddWord("Tea");
String expected = "Coffee";
String actual = victim.getMostPopularWord();
victim.printToConsole();
System.out.println("Most popular word: " + victim.getMostPopularWord());
check(expected, actual, "shouldReturnMostPopular");
}
private void check(int expected, int actual, String testName) {
if (actual == expected) {
System.out.println(testName + " has passed");
} else {
System.out.println(testName + " has failed");
System.out.println("Expected: " + expected + ", Actual: " + actual);
}
System.out.println("* * *");
}
private void check(String expected, String actual, String testName) {
if (actual.equals(expected)) {
System.out.println(testName + " has passed");
} else {
System.out.println(testName + " has failed");
System.out.println("Expected: " + expected + ", Actual: " + actual);
}
System.out.println("* * *");
}
}
| 3,227 | 0.62287 | 0.62225 | 88 | 35.670456 | 21.547369 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795455 | false | false | 8 |
96c7311f9e144e31f0b17465481bd060d22076e2 | 17,652,315,626,748 | 29a3f493baf96c0a1303b6786ef703c70f9f97b7 | /src/main/java/com/chooshine/ems/sys/service/AuthorityService.java | 1f39e1edc5ee25d0b11998ca5cccce3dd847f8bf | [
"Apache-2.0"
] | permissive | chooshine/ems | https://github.com/chooshine/ems | 0f744843f1b21998cf38d5052f26b0d7f983e386 | da0290ac4aedeac40e4397cea17977137f22dcbc | refs/heads/master | 2016-06-15T09:45:18.074000 | 2016-03-20T02:57:04 | 2016-03-20T02:57:04 | 42,250,313 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chooshine.ems.sys.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import com.chooshine.ems.mybatis.auto.entity.SysUser;
import com.chooshine.ems.mybatis.manual.entity.Authority;
import com.chooshine.ems.wechat.entity.TemplateMessage;
import com.chooshine.ems.wechat.service.MessageProcessFactory;
@Service
public class AuthorityService {
@Autowired
private SystemService service;
// private AuthorityDao authorityDao;
// @Autowired
// private SysUserMapper dao;
/**
* 查找所有权限
* @return 返回权限列表
*/
public List<Authority> findAllAuthorities() {
return service.findAllAuthorities();
}
public Map<String, Object> regist(String phone, String password) {
Md5PasswordEncoder encoder = new Md5PasswordEncoder();
encoder.setEncodeHashAsBase64(true);
Map<String, Object> result = new HashMap<>();
// Map<String, Object> user = new HashMap<>();
// user.put("phone", phone);
// user.put("password", encoder.encodePassword(password, ""));
// List<SysUser> temp = dao.selectByExample(example);
if (service.phoneHasRegist(phone)) {
result.put("SUCCESS", false);
result.put("msg", "该手机号已被注册.");
return result;
}
SysUser user = new SysUser();
user.setPhoneNo(phone);
user.setPassword(encoder.encodePassword(password, ""));
user.setStatus(0);
// dao.insertSelective(user);
if (service.insertSysUser(user)) {
result.put("SUCCESS", true);
MessageProcessFactory.fetchTemplateMessage(TemplateMessage.createUserJoinTemplatMessage(phone));
} else
result.put("SUCCESS", false);
//result.put("msg", "成功");
return result;
}
}
| UTF-8 | Java | 2,085 | java | AuthorityService.java | Java | [] | null | [] | package com.chooshine.ems.sys.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import com.chooshine.ems.mybatis.auto.entity.SysUser;
import com.chooshine.ems.mybatis.manual.entity.Authority;
import com.chooshine.ems.wechat.entity.TemplateMessage;
import com.chooshine.ems.wechat.service.MessageProcessFactory;
@Service
public class AuthorityService {
@Autowired
private SystemService service;
// private AuthorityDao authorityDao;
// @Autowired
// private SysUserMapper dao;
/**
* 查找所有权限
* @return 返回权限列表
*/
public List<Authority> findAllAuthorities() {
return service.findAllAuthorities();
}
public Map<String, Object> regist(String phone, String password) {
Md5PasswordEncoder encoder = new Md5PasswordEncoder();
encoder.setEncodeHashAsBase64(true);
Map<String, Object> result = new HashMap<>();
// Map<String, Object> user = new HashMap<>();
// user.put("phone", phone);
// user.put("password", encoder.encodePassword(password, ""));
// List<SysUser> temp = dao.selectByExample(example);
if (service.phoneHasRegist(phone)) {
result.put("SUCCESS", false);
result.put("msg", "该手机号已被注册.");
return result;
}
SysUser user = new SysUser();
user.setPhoneNo(phone);
user.setPassword(encoder.encodePassword(password, ""));
user.setStatus(0);
// dao.insertSelective(user);
if (service.insertSysUser(user)) {
result.put("SUCCESS", true);
MessageProcessFactory.fetchTemplateMessage(TemplateMessage.createUserJoinTemplatMessage(phone));
} else
result.put("SUCCESS", false);
//result.put("msg", "成功");
return result;
}
}
| 2,085 | 0.66144 | 0.658501 | 62 | 31.919355 | 24.907116 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.919355 | false | false | 8 |
84c84b4c2a6c0ac5002a4e142515b2e85f6f9873 | 30,975,304,170,005 | 3ba65c9553e012cf2f7a45faab10f5f9c3df18cd | /src/main/java/com/kosinskyi/ecom/registry/mapping/base/crud/ReadMapper.java | c96752127464250a73d825aee8a1ed7a36611133 | [] | no_license | skosinskiy/ecom-registry | https://github.com/skosinskiy/ecom-registry | b59118a9f963fd0c21c83f10779461ddfc0484dc | c86d1d94ac31f18958db18df0ad2e55dc65eb7ba | refs/heads/master | 2023-01-21T01:51:45.590000 | 2020-07-07T08:21:18 | 2020-07-07T08:21:18 | 194,379,962 | 0 | 0 | null | false | 2023-01-11T03:30:22 | 2019-06-29T07:57:08 | 2020-07-07T08:21:23 | 2023-01-11T03:30:22 | 7,927 | 0 | 0 | 6 | Java | false | false | package com.kosinskyi.ecom.registry.mapping.base.crud;
import com.kosinskyi.ecom.registry.entity.base.BaseEntity;
import com.kosinskyi.ecom.registry.mapping.base.BaseMapper;
import com.kosinskyi.ecom.registry.service.crud.ReadService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.stream.Collectors;
public interface ReadMapper<E extends BaseEntity> extends BaseMapper {
ReadService<E> readServiceSupplier();
default <O> O findById(Long id, Class<O> responseClass) {
return mapEntityToResponseDto(readServiceSupplier().findById(id), responseClass);
}
default <O> List<O> findAll(Class<O> responseClass) {
return readServiceSupplier()
.findAll()
.stream()
.map(e -> mapEntityToResponseDto(e, responseClass))
.collect(Collectors.toList());
}
default <O> Page<O> findAll(Pageable pageable, Class<O> responseClass) {
return readServiceSupplier().findAll(pageable).map(e -> mapEntityToResponseDto(e, responseClass));
}
}
| UTF-8 | Java | 1,070 | java | ReadMapper.java | Java | [] | null | [] | package com.kosinskyi.ecom.registry.mapping.base.crud;
import com.kosinskyi.ecom.registry.entity.base.BaseEntity;
import com.kosinskyi.ecom.registry.mapping.base.BaseMapper;
import com.kosinskyi.ecom.registry.service.crud.ReadService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.stream.Collectors;
public interface ReadMapper<E extends BaseEntity> extends BaseMapper {
ReadService<E> readServiceSupplier();
default <O> O findById(Long id, Class<O> responseClass) {
return mapEntityToResponseDto(readServiceSupplier().findById(id), responseClass);
}
default <O> List<O> findAll(Class<O> responseClass) {
return readServiceSupplier()
.findAll()
.stream()
.map(e -> mapEntityToResponseDto(e, responseClass))
.collect(Collectors.toList());
}
default <O> Page<O> findAll(Pageable pageable, Class<O> responseClass) {
return readServiceSupplier().findAll(pageable).map(e -> mapEntityToResponseDto(e, responseClass));
}
}
| 1,070 | 0.752336 | 0.752336 | 32 | 32.4375 | 29.718405 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 8 |
de671bef7bed52be9d568f4be726406f94c09422 | 13,443,247,669,307 | a15966c5bb8ca6af05a7bcd642b3d6bf7944b988 | /app/src/main/java/com/xue/siu/module/base/activity/BaseBlankActivity.java | 9e910542191336fbe4e6c58b7365b8462ee63b86 | [] | no_license | xue5455/SIU | https://github.com/xue5455/SIU | c4d3788f54c95395267e7a23b10ec848bfdd2d2c | 592d4eb420546eb421f65d88ef4fbfb988e9fcf5 | refs/heads/master | 2021-01-21T12:59:10.461000 | 2016-04-24T07:41:14 | 2016-04-24T07:41:14 | 49,245,493 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xue.siu.module.base.activity;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.view.ViewGroup;
import com.xue.siu.R;
import com.xue.siu.module.base.presenter.BasePresenter;
/**
* Created by XUE on 2015/12/9.
*/
public abstract class BaseBlankActivity<T extends BasePresenter> extends BaseActivity<T> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blank);
initContentView();
}
private void initContentView() {
mRootView = findView(R.id.root_view);
mContentView = findView(R.id.content_view);
}
/**
* Inflate a content view for the activity.
*
* @param resId ID for an XML layout resource as the content view
*/
public void setRealContentView(@LayoutRes int resId) {
getLayoutInflater().inflate(resId, mContentView);
}
}
| UTF-8 | Java | 963 | java | BaseBlankActivity.java | Java | [
{
"context": "e.base.presenter.BasePresenter;\n\n/**\n * Created by XUE on 2015/12/9.\n */\npublic abstract class BaseBlank",
"end": 246,
"score": 0.9995192289352417,
"start": 243,
"tag": "USERNAME",
"value": "XUE"
}
] | null | [] | package com.xue.siu.module.base.activity;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.view.ViewGroup;
import com.xue.siu.R;
import com.xue.siu.module.base.presenter.BasePresenter;
/**
* Created by XUE on 2015/12/9.
*/
public abstract class BaseBlankActivity<T extends BasePresenter> extends BaseActivity<T> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blank);
initContentView();
}
private void initContentView() {
mRootView = findView(R.id.root_view);
mContentView = findView(R.id.content_view);
}
/**
* Inflate a content view for the activity.
*
* @param resId ID for an XML layout resource as the content view
*/
public void setRealContentView(@LayoutRes int resId) {
getLayoutInflater().inflate(resId, mContentView);
}
}
| 963 | 0.696781 | 0.689512 | 34 | 27.32353 | 24.400724 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false | 8 |
409b73c729b2d8f0dfe869f3d66aca13e9f92520 | 6,949,257,109,040 | 4e1537a13cb2ba7658eec5acc3afedf09956e4ca | /Client/src/com/team66/main/me/UserFeedback.java | 66b71afc5174196e45a811527c13c2cc01474edb | [] | no_license | gouyuwang/AndroidBlog | https://github.com/gouyuwang/AndroidBlog | 312222582b6acda0afcc144140b2fb84fd255fdf | d1c11e4b2ec27ced21e58bb050a46e9aea269c96 | refs/heads/master | 2019-05-15T01:48:35.043000 | 2016-05-31T08:27:11 | 2016-05-31T08:27:11 | 60,067,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.team66.main.me;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import com.team66.common.GobackOnclickListener;
import com.team66.main.R;
/**
* 我的 - 用户反馈
* @author fvvl
*
*/
public class UserFeedback extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggestions);
((Button) findViewById(R.id.btn_goback))
.setOnClickListener(new GobackOnclickListener(UserFeedback.this));
}
}
| GB18030 | Java | 559 | java | UserFeedback.java | Java | [
{
"context": "rt com.team66.main.R;\n\n/**\n * 我的 - 用户反馈\n * @author fvvl\n *\n */\npublic class UserFeedback extends Activity",
"end": 222,
"score": 0.9996020793914795,
"start": 218,
"tag": "USERNAME",
"value": "fvvl"
}
] | null | [] | package com.team66.main.me;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import com.team66.common.GobackOnclickListener;
import com.team66.main.R;
/**
* 我的 - 用户反馈
* @author fvvl
*
*/
public class UserFeedback extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggestions);
((Button) findViewById(R.id.btn_goback))
.setOnClickListener(new GobackOnclickListener(UserFeedback.this));
}
}
| 559 | 0.767824 | 0.756856 | 24 | 21.791666 | 20.406248 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.916667 | false | false | 8 |
2d74682c87b75faa499fa9c9427bebf160701f45 | 14,826,227,130,695 | 53a13ac0757f96a6b75159334a47f7b6f39678bb | /FrequencyOfElements.java | 05a843b9662bdb3c167d09329367b9fc4a884f7c | [] | no_license | the0riginals/Java-Practicals | https://github.com/the0riginals/Java-Practicals | b79b4cb2d5efaeb3d886ac90265a452a8242cd5a | 5e119b9b685118b77e2c4e38928dc9486e997eb1 | refs/heads/master | 2020-08-28T22:55:46.690000 | 2019-11-04T16:21:49 | 2019-11-04T16:21:49 | 217,845,502 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
class FrequencyOfElements{
public static void main(String args[]){
int n, i, j, count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements");
n = sc.nextInt();
int a[] = new int[n] ;
int frequency[] = new int[n] ;
System.out.println("Enter elements");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
}
for(i=0; i<n; i++){
count = 1;
for(j=i+1;j<n;j++){
if(a[i] == a[j]){
count += 1;
frequency[j] = -1;
}
if(frequency[i]!=-1){
frequency[i] = count;
}
}
}
for(i=0;i<n;i++){
if(frequency[i]!=-1){
System.out.println("Frequency of " + a[i] + " is " + frequency[i]);
}
}
}
} | UTF-8 | Java | 1,012 | java | FrequencyOfElements.java | Java | [] | null | [] | import java.util.Scanner;
class FrequencyOfElements{
public static void main(String args[]){
int n, i, j, count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements");
n = sc.nextInt();
int a[] = new int[n] ;
int frequency[] = new int[n] ;
System.out.println("Enter elements");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
}
for(i=0; i<n; i++){
count = 1;
for(j=i+1;j<n;j++){
if(a[i] == a[j]){
count += 1;
frequency[j] = -1;
}
if(frequency[i]!=-1){
frequency[i] = count;
}
}
}
for(i=0;i<n;i++){
if(frequency[i]!=-1){
System.out.println("Frequency of " + a[i] + " is " + frequency[i]);
}
}
}
} | 1,012 | 0.370553 | 0.360672 | 36 | 26.166666 | 16.699135 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694444 | false | false | 8 |
4b4dd1e86ec750361c5051330853fae5e23ff6aa | 20,504,173,904,248 | 5006f590347244b554a285bdc10d8d782b15c660 | /app/src/main/java/com/example/z/thelastrow_client_gamedeal/ActivityMeListViewJump.java | 12f16182172ea235d33744390bf5de8495923fcc | [] | no_license | DGUT-Asiasoft-2013/TheLastRow_Client_GameDeal | https://github.com/DGUT-Asiasoft-2013/TheLastRow_Client_GameDeal | 93b63b1292ec7691cb7c1d77c8c8cf6db0ec495f | 7020afcb398e75e59881a37cf5769e7fe47b5e00 | refs/heads/master | 2021-01-20T04:02:22.948000 | 2017-01-12T01:08:06 | 2017-01-12T01:08:06 | 76,822,279 | 1 | 1 | null | false | 2016-12-20T01:54:01 | 2016-12-19T02:47:34 | 2016-12-19T12:03:45 | 2016-12-20T01:54:01 | 2,002 | 0 | 1 | 0 | Java | null | null | package com.example.z.thelastrow_client_gamedeal;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.z.thelastrow_client_gamedeal.fragment.api.entity.User;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyCollectionFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyIndentFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyMessageFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyMoneyRecordFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.widget.ActionBarFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.widget.ToastAndDialog;
/**
* Created by Z on 2016/12/23.
*/
public class ActivityMeListViewJump extends Activity {
User user;
ActionBarFragment actionBarFragment;
MyIndentFragment myIndentFragment=new MyIndentFragment();
MyCollectionFragment myCollectionFragment=new MyCollectionFragment();
MyMoneyRecordFragment myMoneyRecordFragment=new MyMoneyRecordFragment();
MyMessageFragment myMessageFragment=new MyMessageFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_me_listview_jump);
user= (User) getIntent().getSerializableExtra("user");
actionBarFragment=(ActionBarFragment)getFragmentManager().findFragmentById(R.id.me_listview_jump_frag_action_bar);
}
@Override
protected void onResume() {
super.onResume();
changeFragment();
}
private void changeFragment() {
String title=getIntent().getStringExtra("listViewItem");
Fragment newFrag = null;
actionBarFragment.setTitle(title);
switch (title){
default: break;
case "我的订单": newFrag=myIndentFragment; break;
case "我的收藏": newFrag=myCollectionFragment; break;
case "消费记录": newFrag=myMoneyRecordFragment; break;
case "我的消息": newFrag=myMessageFragment; break;
}
if (newFrag!=null){
Intent intent=new Intent(this,newFrag.getClass());
intent.putExtra("user",user);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.me_listview_jump_contain,newFrag)
.commit();
}
}
| UTF-8 | Java | 2,496 | java | ActivityMeListViewJump.java | Java | [] | null | [] | package com.example.z.thelastrow_client_gamedeal;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.z.thelastrow_client_gamedeal.fragment.api.entity.User;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyCollectionFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyIndentFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyMessageFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.page.MyMoneyRecordFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.widget.ActionBarFragment;
import com.example.z.thelastrow_client_gamedeal.fragment.widget.ToastAndDialog;
/**
* Created by Z on 2016/12/23.
*/
public class ActivityMeListViewJump extends Activity {
User user;
ActionBarFragment actionBarFragment;
MyIndentFragment myIndentFragment=new MyIndentFragment();
MyCollectionFragment myCollectionFragment=new MyCollectionFragment();
MyMoneyRecordFragment myMoneyRecordFragment=new MyMoneyRecordFragment();
MyMessageFragment myMessageFragment=new MyMessageFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_me_listview_jump);
user= (User) getIntent().getSerializableExtra("user");
actionBarFragment=(ActionBarFragment)getFragmentManager().findFragmentById(R.id.me_listview_jump_frag_action_bar);
}
@Override
protected void onResume() {
super.onResume();
changeFragment();
}
private void changeFragment() {
String title=getIntent().getStringExtra("listViewItem");
Fragment newFrag = null;
actionBarFragment.setTitle(title);
switch (title){
default: break;
case "我的订单": newFrag=myIndentFragment; break;
case "我的收藏": newFrag=myCollectionFragment; break;
case "消费记录": newFrag=myMoneyRecordFragment; break;
case "我的消息": newFrag=myMessageFragment; break;
}
if (newFrag!=null){
Intent intent=new Intent(this,newFrag.getClass());
intent.putExtra("user",user);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.me_listview_jump_contain,newFrag)
.commit();
}
}
| 2,496 | 0.719562 | 0.716315 | 64 | 37.5 | 28.759781 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671875 | false | false | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.