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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cc2700f7da8414b1635c1565d8bdf59217f12e5f | 10,307,921,570,187 | 162b7a29274304ae34ffbd7aff1e0a1882713149 | /taotao-manager/taotao-manager-dao/src/main/java/com/taotao/mapper/TbOrderItemMapper.java | cbc0d8922657d510945b47f2a48eb103c4bb1f7f | [] | no_license | pangwawa/taotao-file | https://github.com/pangwawa/taotao-file | 1192e4ae067ead69fe658ee0ac110aa9966b46ed | 0a2b41f6cb5e4ddf100b5a1e13760f77cf98282a | refs/heads/master | 2020-04-17T22:00:10.433000 | 2019-01-22T10:34:37 | 2019-01-22T10:34:37 | 166,975,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taotao.mapper;
import com.taotao.pojo.TbOrderItem;
import java.util.List;
public interface TbOrderItemMapper {
int insert(TbOrderItem record);
List<TbOrderItem> selectAll();
} | UTF-8 | Java | 199 | java | TbOrderItemMapper.java | Java | [] | null | [] | package com.taotao.mapper;
import com.taotao.pojo.TbOrderItem;
import java.util.List;
public interface TbOrderItemMapper {
int insert(TbOrderItem record);
List<TbOrderItem> selectAll();
} | 199 | 0.763819 | 0.763819 | 11 | 17.181818 | 15.998967 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 10 |
302a0271572213a610327424d723ed45cca8260d | 3,289,944,962,469 | 5271d6a411be64831ecd0c0e13210f688e181972 | /app/src/main/java/com/example/more/di/module/ViewModelModule.java | e67adfecb68d13537d0036da069464271583dba5 | [] | no_license | AshishMK/More | https://github.com/AshishMK/More | a60fcb295ffbf3813fc933f88aaf410553bff6aa | e62550b960d4b66fabf17e195374f0eb949dffda | refs/heads/master | 2021-07-05T14:12:50.286000 | 2020-12-14T05:55:25 | 2020-12-14T05:55:25 | 214,552,062 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.more.di.module;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.example.more.di.ViewModelKey;
import com.example.more.factory.ViewModelFactory;
import com.example.more.viewmodel.ContentListViewModel;
import com.example.more.viewmodel.DMActivityViewModel;
import com.example.more.viewmodel.ImageFirebaseViewModel;
import com.example.more.viewmodel.NotificationListViewModel;
import com.example.more.viewmodel.SearchListViewModel;
import com.example.more.viewmodel.WhatsappStatusViewModel;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
/*
* Module to inject specified list of ViewModule
*/
@Module
public abstract class ViewModelModule {
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
/*
* This method basically says
* inject this object into a Map using the @IntoMap annotation,
* with the ContentListViewModel.class as key,
* and a Provider that will build a ContentListViewModel
* object.
*
* */
@Binds
@IntoMap
@ViewModelKey(ContentListViewModel.class)
protected abstract ViewModel movieListViewModel(ContentListViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(DMActivityViewModel.class)
protected abstract ViewModel dmActivityViewModel(DMActivityViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(SearchListViewModel.class)
protected abstract ViewModel searchListViewModel(SearchListViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(WhatsappStatusViewModel.class)
protected abstract ViewModel statusViewModel(WhatsappStatusViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(ImageFirebaseViewModel.class)
protected abstract ViewModel imageListViewModel(ImageFirebaseViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(NotificationListViewModel.class)
protected abstract ViewModel notificationListViewModel(NotificationListViewModel contentListViewModel);
} | UTF-8 | Java | 2,126 | java | ViewModelModule.java | Java | [] | null | [] | package com.example.more.di.module;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.example.more.di.ViewModelKey;
import com.example.more.factory.ViewModelFactory;
import com.example.more.viewmodel.ContentListViewModel;
import com.example.more.viewmodel.DMActivityViewModel;
import com.example.more.viewmodel.ImageFirebaseViewModel;
import com.example.more.viewmodel.NotificationListViewModel;
import com.example.more.viewmodel.SearchListViewModel;
import com.example.more.viewmodel.WhatsappStatusViewModel;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
/*
* Module to inject specified list of ViewModule
*/
@Module
public abstract class ViewModelModule {
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
/*
* This method basically says
* inject this object into a Map using the @IntoMap annotation,
* with the ContentListViewModel.class as key,
* and a Provider that will build a ContentListViewModel
* object.
*
* */
@Binds
@IntoMap
@ViewModelKey(ContentListViewModel.class)
protected abstract ViewModel movieListViewModel(ContentListViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(DMActivityViewModel.class)
protected abstract ViewModel dmActivityViewModel(DMActivityViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(SearchListViewModel.class)
protected abstract ViewModel searchListViewModel(SearchListViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(WhatsappStatusViewModel.class)
protected abstract ViewModel statusViewModel(WhatsappStatusViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(ImageFirebaseViewModel.class)
protected abstract ViewModel imageListViewModel(ImageFirebaseViewModel contentListViewModel);
@Binds
@IntoMap
@ViewModelKey(NotificationListViewModel.class)
protected abstract ViewModel notificationListViewModel(NotificationListViewModel contentListViewModel);
} | 2,126 | 0.793509 | 0.793509 | 71 | 28.957747 | 30.27314 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323944 | false | false | 10 |
603c0f81ee4d28c1ea17e16df9a930c664ffaf39 | 6,734,508,739,260 | b90c80f838a9806df38c853bb17873c17e52c2e2 | /Heranças e Polimorfismo/src/herancas/testeGerente.java | d522cf95a31c57a66f71e6300a0ec864f0ead1a1 | [] | no_license | JulioLongo/Java | https://github.com/JulioLongo/Java | 07cb9e2db56edd5c5e32c288367e15fdee1a774d | e6a6b98af20ac4850843ea990841c2ae85da078e | refs/heads/master | 2020-07-07T17:29:42.649000 | 2019-09-09T13:34:13 | 2019-09-09T13:34:13 | 203,422,182 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package herancas;
public class testeGerente {
public static void main(String[] args) {
Gerente jubs = new Gerente();
//Insire variaveis de funcionario
jubs.setNome("Julio");
jubs.setSalario(500);
System.out.println(jubs.getNome());
jubs.setSenha(123);
boolean autenticou = jubs.autentica(123);
System.out.println(autenticou);
//teste bonificação
System.out.println(jubs.getBonificacao());
}
}
| ISO-8859-1 | Java | 427 | java | testeGerente.java | Java | [
{
"context": "//Insire variaveis de funcionario\n\t\tjubs.setNome(\"Julio\");\n\t\tjubs.setSalario(500);\n\t\tSystem.out.println(j",
"end": 181,
"score": 0.9997249245643616,
"start": 176,
"tag": "NAME",
"value": "Julio"
},
{
"context": "m.out.println(jubs.getNome());\n\t\t\n\t\tjubs.... | null | [] | package herancas;
public class testeGerente {
public static void main(String[] args) {
Gerente jubs = new Gerente();
//Insire variaveis de funcionario
jubs.setNome("Julio");
jubs.setSalario(500);
System.out.println(jubs.getNome());
jubs.setSenha(123);
boolean autenticou = jubs.autentica(123);
System.out.println(autenticou);
//teste bonificação
System.out.println(jubs.getBonificacao());
}
}
| 427 | 0.708235 | 0.687059 | 19 | 21.368422 | 15.314976 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.947368 | false | false | 10 |
3153630b196ced41c4fac5189350c2e83916949a | 27,839,978,074,952 | 4e29948cad42137ced755c98a6cc065d6f95af81 | /src/main/java/com/turing/spider/fanxing/KeyValue.java | 8a080af3f448dd73a3f8c50c18c7406d0d503be1 | [] | no_license | chenbinTR/turing-apider | https://github.com/chenbinTR/turing-apider | ff238903620574808d81cff9fd22b9b1e057b83a | 05d541a16e17fc6cbf44421f51f5552b839f0774 | refs/heads/master | 2020-03-26T16:14:54.221000 | 2020-03-25T09:17:04 | 2020-03-25T09:17:04 | 145,089,748 | 0 | 0 | null | false | 2020-05-13T05:42:41 | 2018-08-17T07:51:04 | 2020-05-13T05:42:23 | 2020-05-13T05:42:40 | 3,937 | 0 | 0 | 1 | Java | false | false | package com.turing.spider.fanxing;
import java.util.Map;
/**
* @author ChenOT
* @date 2019-05-23
* @see
* @since
*/
public class KeyValue<K,V> {
private K k;
private V v;
public void put(K k, V v){
this.k = k;
this.v = v;
}
public V getV(K k){
return this.v;
}
public static void main(String[] args) {
KeyValue<String, String> keyValue = new KeyValue<>();
keyValue.put("1", "2");
}
}
| UTF-8 | Java | 466 | java | KeyValue.java | Java | [
{
"context": "er.fanxing;\n\nimport java.util.Map;\n\n/**\n * @author ChenOT\n * @date 2019-05-23\n * @see\n * @since\n */\npublic ",
"end": 80,
"score": 0.9966861605644226,
"start": 74,
"tag": "USERNAME",
"value": "ChenOT"
}
] | null | [] | package com.turing.spider.fanxing;
import java.util.Map;
/**
* @author ChenOT
* @date 2019-05-23
* @see
* @since
*/
public class KeyValue<K,V> {
private K k;
private V v;
public void put(K k, V v){
this.k = k;
this.v = v;
}
public V getV(K k){
return this.v;
}
public static void main(String[] args) {
KeyValue<String, String> keyValue = new KeyValue<>();
keyValue.put("1", "2");
}
}
| 466 | 0.540773 | 0.519313 | 28 | 15.642858 | 14.842541 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false | 10 |
768a6cfa4e5cc790e698d34f8c50524010542fb1 | 283,467,877,476 | 5df4ee432fe688336e5d0d5ce4c4fbda769b6650 | /src/main/java/com/as2secure/MimepartHelper.java | b830a4da9589759004748113c301cc004f726041 | [
"MIT"
] | permissive | igwtech/as2secure-java | https://github.com/igwtech/as2secure-java | d27a49a9c0eb17acc0fea1ec6eb928bd7c083d97 | fea91a9009289ac0cdff84aeb1ef827adb536d56 | refs/heads/master | 2022-02-25T21:40:58.800000 | 2019-09-17T20:14:23 | 2019-09-17T20:14:23 | 208,940,883 | 0 | 0 | MIT | true | 2019-09-17T02:25:54 | 2019-09-17T02:25:53 | 2018-07-17T13:23:35 | 2014-06-04T16:00:59 | 128 | 0 | 0 | 0 | null | false | false | package com.as2secure;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class MimepartHelper
{
public static MimeMultipart getMultipartFromFile(File file) throws FileNotFoundException, MessagingException, IOException { return getMultipartFromFile(new FileInputStream(file)); }
public static MimeMultipart getMultipartFromFile(String filename) throws MessagingException, IOException { return getMultipartFromFile(new FileInputStream(filename)); }
public static MimeMultipart getMultipartFromFile(FileInputStream fileInputStream) throws MessagingException, IOException {
Properties localProperties = System.getProperties();
Session localSession = Session.getDefaultInstance(localProperties, null);
MimeMessage message = new MimeMessage(localSession, fileInputStream);
ByteArrayOutputStream mem = new ByteArrayOutputStream();
message.writeTo(mem);
mem.flush();
mem.close();
return new MimeMultipart(new ByteArrayDataSource(mem.toByteArray(), message.getContentType()));
}
}
| UTF-8 | Java | 1,404 | java | MimepartHelper.java | Java | [] | null | [] | package com.as2secure;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class MimepartHelper
{
public static MimeMultipart getMultipartFromFile(File file) throws FileNotFoundException, MessagingException, IOException { return getMultipartFromFile(new FileInputStream(file)); }
public static MimeMultipart getMultipartFromFile(String filename) throws MessagingException, IOException { return getMultipartFromFile(new FileInputStream(filename)); }
public static MimeMultipart getMultipartFromFile(FileInputStream fileInputStream) throws MessagingException, IOException {
Properties localProperties = System.getProperties();
Session localSession = Session.getDefaultInstance(localProperties, null);
MimeMessage message = new MimeMessage(localSession, fileInputStream);
ByteArrayOutputStream mem = new ByteArrayOutputStream();
message.writeTo(mem);
mem.flush();
mem.close();
return new MimeMultipart(new ByteArrayDataSource(mem.toByteArray(), message.getContentType()));
}
}
| 1,404 | 0.7849 | 0.784188 | 37 | 36.918919 | 44.384911 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.783784 | false | false | 10 |
c3c5be1f1b05d7d149fca826f09a46c4fd1da719 | 20,366,734,977,704 | 7a70adfa9b1458833a5289549381ff051d657d45 | /app/src/main/java/mgr/mobmove/plik/Plik.java | c2f1540b2808935e21f875b26b93b961cd9bcfb1 | [] | no_license | liwiusz/MobMove | https://github.com/liwiusz/MobMove | 3db451062808f8ef4529831ce9e97b8e1160206e | 2f6fc6ba29102538775f9d019f3da352001a9610 | refs/heads/master | 2020-05-21T03:27:09.398000 | 2016-12-22T16:28:59 | 2016-12-22T16:28:59 | 52,968,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mgr.mobmove.plik;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Plik {
public static void save(String filename, ArrayList<Dane> d,String rodzajAktywnosci,String dystans,String cel,String uwagi)
{
String s;
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename+".txt");
// file = new File("/sdcard/"+ filename+".txt");
outputStream = new FileOutputStream(file);
outputStream.write("Rodzaj aktywnosci \t".getBytes());
outputStream.write(rodzajAktywnosci.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Dystans \t".getBytes());
outputStream.write(dystans.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Cel \t".getBytes());
outputStream.write(cel.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Uwagi \t".getBytes());
outputStream.write(uwagi.getBytes());
outputStream.write("\n".getBytes());
outputStream.write("czas".getBytes());
outputStream.write("\t\t".getBytes());
outputStream.write("accelerometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Gravity".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Gyroscope".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("GyroscopeU".getBytes());
outputStream.write("\t\t\t\t\t\t\t".getBytes());
outputStream.write("LinearAccelometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Magnetic".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Macierz obrotu dla accelerometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Macierz obrotu dla LinearAccelometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Orientation".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Rotation".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Mapa".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Krok".getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Dystans".getBytes());
outputStream.write("\n".getBytes());
for (int i=0;i<d.size();i++)
{
outputStream.write(d.get(i).getCzas().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getXa().getBytes());
outputStream.write(d.get(i).getYa().getBytes());
outputStream.write(d.get(i).getZa().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGravityX().getBytes());
outputStream.write(d.get(i).getGravityY().getBytes());
outputStream.write(d.get(i).getGravityZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGyroscopeX().getBytes());
outputStream.write(d.get(i).getGyroscopeY().getBytes());
outputStream.write(d.get(i).getGyroscopeZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGyroscopeUXa().getBytes());
outputStream.write(d.get(i).getGyroscopeUYa().getBytes());
outputStream.write(d.get(i).getGyroscopeUZa().getBytes());
outputStream.write(d.get(i).getGyroscopeUXb().getBytes());
outputStream.write(d.get(i).getGyroscopeUYb().getBytes());
outputStream.write(d.get(i).getGyroscopeUZb().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getLinearAccelometerX().getBytes());
outputStream.write(d.get(i).getLinearAccelometerY().getBytes());
outputStream.write(d.get(i).getLinearAccelometerZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getMagneticX().getBytes());
outputStream.write(d.get(i).getMagneticY().getBytes());
outputStream.write(d.get(i).getMagneticZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getMacierzObrotu().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getOrientationX().getBytes());
outputStream.write(d.get(i).getOrientationY().getBytes());
outputStream.write(d.get(i).getOrientationZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getRotationX().getBytes());
outputStream.write(d.get(i).getRotationY().getBytes());
outputStream.write(d.get(i).getRotationZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getSpeed().getBytes());
outputStream.write(d.get(i).getxMap().getBytes());
outputStream.write(d.get(i).getyMap().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getKrok().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getDystans().getBytes());
outputStream.write("\t".getBytes());
outputStream.write("\n".getBytes());
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 6,328 | java | Plik.java | Java | [] | null | [] | package mgr.mobmove.plik;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Plik {
public static void save(String filename, ArrayList<Dane> d,String rodzajAktywnosci,String dystans,String cel,String uwagi)
{
String s;
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename+".txt");
// file = new File("/sdcard/"+ filename+".txt");
outputStream = new FileOutputStream(file);
outputStream.write("Rodzaj aktywnosci \t".getBytes());
outputStream.write(rodzajAktywnosci.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Dystans \t".getBytes());
outputStream.write(dystans.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Cel \t".getBytes());
outputStream.write(cel.getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Uwagi \t".getBytes());
outputStream.write(uwagi.getBytes());
outputStream.write("\n".getBytes());
outputStream.write("czas".getBytes());
outputStream.write("\t\t".getBytes());
outputStream.write("accelerometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Gravity".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Gyroscope".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("GyroscopeU".getBytes());
outputStream.write("\t\t\t\t\t\t\t".getBytes());
outputStream.write("LinearAccelometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Magnetic".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Macierz obrotu dla accelerometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Macierz obrotu dla LinearAccelometer".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Orientation".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Rotation".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Mapa".getBytes());
outputStream.write("\t\t\t\t".getBytes());
outputStream.write("Krok".getBytes());
outputStream.write("\t".getBytes());
outputStream.write("Dystans".getBytes());
outputStream.write("\n".getBytes());
for (int i=0;i<d.size();i++)
{
outputStream.write(d.get(i).getCzas().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getXa().getBytes());
outputStream.write(d.get(i).getYa().getBytes());
outputStream.write(d.get(i).getZa().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGravityX().getBytes());
outputStream.write(d.get(i).getGravityY().getBytes());
outputStream.write(d.get(i).getGravityZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGyroscopeX().getBytes());
outputStream.write(d.get(i).getGyroscopeY().getBytes());
outputStream.write(d.get(i).getGyroscopeZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getGyroscopeUXa().getBytes());
outputStream.write(d.get(i).getGyroscopeUYa().getBytes());
outputStream.write(d.get(i).getGyroscopeUZa().getBytes());
outputStream.write(d.get(i).getGyroscopeUXb().getBytes());
outputStream.write(d.get(i).getGyroscopeUYb().getBytes());
outputStream.write(d.get(i).getGyroscopeUZb().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getLinearAccelometerX().getBytes());
outputStream.write(d.get(i).getLinearAccelometerY().getBytes());
outputStream.write(d.get(i).getLinearAccelometerZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getMagneticX().getBytes());
outputStream.write(d.get(i).getMagneticY().getBytes());
outputStream.write(d.get(i).getMagneticZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getMacierzObrotu().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getOrientationX().getBytes());
outputStream.write(d.get(i).getOrientationY().getBytes());
outputStream.write(d.get(i).getOrientationZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getRotationX().getBytes());
outputStream.write(d.get(i).getRotationY().getBytes());
outputStream.write(d.get(i).getRotationZ().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getSpeed().getBytes());
outputStream.write(d.get(i).getxMap().getBytes());
outputStream.write(d.get(i).getyMap().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getKrok().getBytes());
outputStream.write("\t".getBytes());
outputStream.write(d.get(i).getDystans().getBytes());
outputStream.write("\t".getBytes());
outputStream.write("\n".getBytes());
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 6,328 | 0.573957 | 0.573799 | 155 | 39.825806 | 29.858408 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716129 | false | false | 10 |
297473b163f5e0ead131ee7edf3b38257b3db783 | 24,386,824,318,379 | fea4a382bd17ac1aaa82a5c8ec0e3a78c33b7270 | /app/src/main/java/com/ntn/testhometiki/HomeActivity.java | 621caa061fe4cefe5bd7242033c36993d3b30a59 | [] | no_license | trungnghi4/Tiki-Home-Test | https://github.com/trungnghi4/Tiki-Home-Test | f93a5bdd8904ea6d46fde168bb7c564069938a41 | 4dd844e45fe8f25bde88a91150c942ac8d0d688c | refs/heads/master | 2022-11-20T07:10:25.451000 | 2020-07-18T03:22:58 | 2020-07-18T03:22:58 | 280,428,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ntn.testhometiki;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.ntn.testhometiki.adapter.CategoryAdapter;
import com.ntn.testhometiki.adapter.KeyWordAdapter;
import com.ntn.testhometiki.adapter.ServiceAdapter;
import com.ntn.testhometiki.adapter.TikiDealAdapter;
import com.ntn.testhometiki.model.TikiDeal;
import com.ntn.testhometiki.model.TikiService;
import com.ntn.testhometiki.presenter.HomeActivityPresenter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HomeActivity extends AppCompatActivity implements HomeActivityPresenter.HomeActivityView {
@BindView(R.id.recycler_view_category)
RecyclerView recyclerViewCategory;
@BindView(R.id.recycler_view_service)
RecyclerView recyclerViewService;
@BindView(R.id.recycler_view_hot_key_word)
RecyclerView recyclerViewHotKeyWord;
@BindView(R.id.recycler_view_deal)
RecyclerView recyclerViewDeal;
@BindView(R.id.btn_register)
Button btnRegister;
@BindView(R.id.btn_login)
Button btnLogin;
CategoryAdapter categoryAdapter;
ServiceAdapter serviceAdapter;
KeyWordAdapter keyWordAdapter;
TikiDealAdapter dealAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
// Set layout
recyclerViewCategory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewService.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewHotKeyWord.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewDeal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
// View category
categoryAdapter = new CategoryAdapter(this, null);
recyclerViewCategory.setAdapter(categoryAdapter);
// View service
serviceAdapter = new ServiceAdapter(this, null);
recyclerViewService.setAdapter(serviceAdapter);
// View hot key word
keyWordAdapter = new KeyWordAdapter(this, null);
recyclerViewHotKeyWord.setAdapter(keyWordAdapter);
// View deal
dealAdapter = new TikiDealAdapter(this, null);
recyclerViewDeal.setAdapter(dealAdapter);
HomeActivityPresenter homeActivityPresenter = new HomeActivityPresenter(this);
homeActivityPresenter.initData();
if(isNetworkAvailable()){
homeActivityPresenter.initDataKeyWord();
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getResources().getString(R.string.error_internet_no_connection))
.setPositiveButton("OK", (dialogInterface, i) -> dialogInterface.cancel())
.setCancelable(false);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
@Override
public void handleCategoryAdapter(List<String> data) {
categoryAdapter.updateDataCategory(data);
}
@Override
public void handleServiceAdapter(List<TikiService> data) {
serviceAdapter.updateDataService(data);
}
@Override
public void handleKeyWordAdapter(List<String> data) {
keyWordAdapter.updateDataKeyWord(data);
}
@Override
public void handleTikiDealAdapter(List<TikiDeal> data) {
dealAdapter.updateDataDeal(data);
}
@Override
public void handeMessageErrorAPI(int message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getResources().getString(message))
.setPositiveButton("OK", (dialogInterface, i) -> dialogInterface.cancel())
.setCancelable(false);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
protected boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
| UTF-8 | Java | 4,654 | java | HomeActivity.java | Java | [] | null | [] | package com.ntn.testhometiki;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.ntn.testhometiki.adapter.CategoryAdapter;
import com.ntn.testhometiki.adapter.KeyWordAdapter;
import com.ntn.testhometiki.adapter.ServiceAdapter;
import com.ntn.testhometiki.adapter.TikiDealAdapter;
import com.ntn.testhometiki.model.TikiDeal;
import com.ntn.testhometiki.model.TikiService;
import com.ntn.testhometiki.presenter.HomeActivityPresenter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HomeActivity extends AppCompatActivity implements HomeActivityPresenter.HomeActivityView {
@BindView(R.id.recycler_view_category)
RecyclerView recyclerViewCategory;
@BindView(R.id.recycler_view_service)
RecyclerView recyclerViewService;
@BindView(R.id.recycler_view_hot_key_word)
RecyclerView recyclerViewHotKeyWord;
@BindView(R.id.recycler_view_deal)
RecyclerView recyclerViewDeal;
@BindView(R.id.btn_register)
Button btnRegister;
@BindView(R.id.btn_login)
Button btnLogin;
CategoryAdapter categoryAdapter;
ServiceAdapter serviceAdapter;
KeyWordAdapter keyWordAdapter;
TikiDealAdapter dealAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
// Set layout
recyclerViewCategory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewService.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewHotKeyWord.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerViewDeal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
// View category
categoryAdapter = new CategoryAdapter(this, null);
recyclerViewCategory.setAdapter(categoryAdapter);
// View service
serviceAdapter = new ServiceAdapter(this, null);
recyclerViewService.setAdapter(serviceAdapter);
// View hot key word
keyWordAdapter = new KeyWordAdapter(this, null);
recyclerViewHotKeyWord.setAdapter(keyWordAdapter);
// View deal
dealAdapter = new TikiDealAdapter(this, null);
recyclerViewDeal.setAdapter(dealAdapter);
HomeActivityPresenter homeActivityPresenter = new HomeActivityPresenter(this);
homeActivityPresenter.initData();
if(isNetworkAvailable()){
homeActivityPresenter.initDataKeyWord();
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getResources().getString(R.string.error_internet_no_connection))
.setPositiveButton("OK", (dialogInterface, i) -> dialogInterface.cancel())
.setCancelable(false);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
@Override
public void handleCategoryAdapter(List<String> data) {
categoryAdapter.updateDataCategory(data);
}
@Override
public void handleServiceAdapter(List<TikiService> data) {
serviceAdapter.updateDataService(data);
}
@Override
public void handleKeyWordAdapter(List<String> data) {
keyWordAdapter.updateDataKeyWord(data);
}
@Override
public void handleTikiDealAdapter(List<TikiDeal> data) {
dealAdapter.updateDataDeal(data);
}
@Override
public void handeMessageErrorAPI(int message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getResources().getString(message))
.setPositiveButton("OK", (dialogInterface, i) -> dialogInterface.cancel())
.setCancelable(false);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
protected boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
| 4,654 | 0.735926 | 0.735926 | 123 | 36.829269 | 30.931791 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.626016 | false | false | 10 |
75cd0607d1e506c270e3cb68ac44b28fbaa378ec | 36,867,999,284,967 | b210695c3a85efaf7aa7aad8fbe66abae45a4ecf | /src/main/java/com/beha/dto/GradeLessonDTO.java | 87e42c0b03b15ccade86a6ea9a556f84c891aaf4 | [] | no_license | gatess/beha-school-shop | https://github.com/gatess/beha-school-shop | 5ad5c1fbef8c42074ce5b34b32b5f32043997c42 | 11fbbe0cf68ff9fb57ea439a4e12b5bdf2ddfd0f | refs/heads/master | 2023-07-12T02:01:22.140000 | 2021-08-12T16:03:48 | 2021-08-12T16:03:48 | 395,058,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beha.dto;
import lombok.Data;
@Data
public class GradeLessonDTO {
private String gradeName;
private String lessonName;
private long gradeId;
private long lessonId;
private String teacherName;
private long teacherId;
}
| UTF-8 | Java | 239 | java | GradeLessonDTO.java | Java | [] | null | [] | package com.beha.dto;
import lombok.Data;
@Data
public class GradeLessonDTO {
private String gradeName;
private String lessonName;
private long gradeId;
private long lessonId;
private String teacherName;
private long teacherId;
}
| 239 | 0.786611 | 0.786611 | 14 | 16.071428 | 11.435935 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
bba02aa919f1720818adffbd97b880d9ec317e9d | 6,287,832,180,625 | 94032301c970fc36cc0ad8f15a42c8b01bab7e8a | /src/main/java/com/codeyasam/testcasemanagement/repository/BatchUploadRepository.java | 3978cbfc745e639d120b6aa6b2f8950db54d68a3 | [] | no_license | codeyasam/TMS-POC | https://github.com/codeyasam/TMS-POC | 85ef66d538f52e8a0a1d0317207436bff7e2b453 | e3560aa4cb116ee1efd2faecb159f7a258d28068 | refs/heads/master | 2020-04-01T23:56:52.091000 | 2018-10-14T16:53:30 | 2018-10-14T16:53:30 | 153,780,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codeyasam.testcasemanagement.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.codeyasam.testcasemanagement.domain.BatchUpload;
public interface BatchUploadRepository extends PagingAndSortingRepository<BatchUpload, Long> {
}
| UTF-8 | Java | 285 | java | BatchUploadRepository.java | Java | [] | null | [] | package com.codeyasam.testcasemanagement.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.codeyasam.testcasemanagement.domain.BatchUpload;
public interface BatchUploadRepository extends PagingAndSortingRepository<BatchUpload, Long> {
}
| 285 | 0.870175 | 0.870175 | 9 | 30.666666 | 35.680683 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
edcbaa1569808ef05aa6e193db60fc4cef67d0ff | 39,341,900,447,815 | 11541990f394df21e94669e15c573125943fe975 | /src/main/java/rpc/http2/consumer/HttpConsumer.java | 1c9e056799c7e6c80821070a128d704fbcac1049 | [] | no_license | lucifer7/soa-demo | https://github.com/lucifer7/soa-demo | 520078186aa351f96c031c7a7bb6221964bbf99a | 056aa9df770373d0a0c241eb12bc118e5c8d0e32 | refs/heads/master | 2021-01-20T20:15:17.669000 | 2016-07-07T14:01:49 | 2016-07-07T14:01:49 | 61,297,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rpc.http2.consumer;
import lombok.extern.log4j.Log4j;
import rpc.http2.protocol.Encode;
import rpc.http2.protocol.ProtocolUtil;
import rpc.http2.protocol.Request;
import rpc.http2.protocol.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import static util.ProjectConstants.HOST_ADDRESS;
import static util.ProjectConstants.HTTP_PORT;
/**
* Created by lucifer on 2016-7-3.
*/
@Log4j
public class HttpConsumer {
public void consume(String command) throws IOException {
log.info("Consumer executes on command: " + command);
// 1. 初始化请求
Request request = new Request(Encode.UTF_8.getValue(), command, command.length());
Socket client = new Socket(HOST_ADDRESS, HTTP_PORT);
// 2. 发送请求
OutputStream output = client.getOutputStream();
ProtocolUtil.writeRequest(output, request);
// 3. 处理响应数据
InputStream input = client.getInputStream();
Response response = ProtocolUtil.readResponse(input);
// 4. 读取响应内容
log.info(response.getResponse());
}
}
| UTF-8 | Java | 1,171 | java | HttpConsumer.java | Java | [
{
"context": "til.ProjectConstants.HTTP_PORT;\n\n/**\n * Created by lucifer on 2016-7-3.\n */\n@Log4j\npublic class HttpConsumer",
"end": 442,
"score": 0.9996082782745361,
"start": 435,
"tag": "USERNAME",
"value": "lucifer"
}
] | null | [] | package rpc.http2.consumer;
import lombok.extern.log4j.Log4j;
import rpc.http2.protocol.Encode;
import rpc.http2.protocol.ProtocolUtil;
import rpc.http2.protocol.Request;
import rpc.http2.protocol.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import static util.ProjectConstants.HOST_ADDRESS;
import static util.ProjectConstants.HTTP_PORT;
/**
* Created by lucifer on 2016-7-3.
*/
@Log4j
public class HttpConsumer {
public void consume(String command) throws IOException {
log.info("Consumer executes on command: " + command);
// 1. 初始化请求
Request request = new Request(Encode.UTF_8.getValue(), command, command.length());
Socket client = new Socket(HOST_ADDRESS, HTTP_PORT);
// 2. 发送请求
OutputStream output = client.getOutputStream();
ProtocolUtil.writeRequest(output, request);
// 3. 处理响应数据
InputStream input = client.getInputStream();
Response response = ProtocolUtil.readResponse(input);
// 4. 读取响应内容
log.info(response.getResponse());
}
}
| 1,171 | 0.701506 | 0.684677 | 41 | 26.536585 | 22.861298 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585366 | false | false | 3 |
be560a96aad92a13d8ea6bc254067df631566abd | 38,654,705,675,922 | fdd8c892c396f62a5ea3884a72e8058cdd5a33b3 | /web/src/main/java/com/github/freeacs/web/app/page/window/WindowData.java | 7cdca14dbbfe85a343c1f104a5bc140ab4f4378e | [
"MIT"
] | permissive | yrong/freeacs | https://github.com/yrong/freeacs | 8e408dffd62be25163a36b877d7f5f6f5a7eb58a | a8458c2b319c7680afd39998481a659f60edac7a | refs/heads/master | 2020-06-24T22:29:15.296000 | 2019-07-29T03:52:41 | 2019-07-29T03:52:41 | 199,109,973 | 1 | 0 | MIT | true | 2019-07-27T03:23:27 | 2019-07-27T03:23:27 | 2019-07-17T20:37:21 | 2019-06-15T20:25:50 | 17,239 | 0 | 0 | 0 | null | false | false | package com.github.freeacs.web.app.page.window;
import com.github.freeacs.web.app.input.Input;
import com.github.freeacs.web.app.input.InputData;
import java.util.Map;
/** The Class WindowData. */
public class WindowData extends InputData {
/** The download. */
private Input download = Input.getStringInput("download");
/** The regular. */
private Input regular = Input.getStringInput("regular");
/** The frequency. */
private Input frequency = Input.getStringInput("frequency");
/** The page. */
private Input page = Input.getStringInput("page");
/**
* Sets the download.
*
* @param download the new download
*/
public void setDownload(Input download) {
this.download = download;
}
/**
* Gets the download.
*
* @return the download
*/
public Input getDownload() {
return download;
}
/**
* Sets the regular.
*
* @param regular the new regular
*/
public void setRegular(Input regular) {
this.regular = regular;
}
/**
* Gets the regular.
*
* @return the regular
*/
public Input getRegular() {
return regular;
}
/**
* Sets the frequency.
*
* @param frequency the new frequency
*/
public void setFrequency(Input frequency) {
this.frequency = frequency;
}
/**
* Gets the frequency.
*
* @return the frequency
*/
public Input getFrequency() {
return frequency;
}
/**
* Sets the page.
*
* @param page the new page
*/
public void setPage(Input page) {
this.page = page;
}
/**
* Gets the page.
*
* @return the page
*/
public Input getPage() {
return page;
}
@Override
public void bindForm(Map<String, Object> root) {}
@Override
public boolean validateForm() {
return false;
}
}
| UTF-8 | Java | 1,790 | java | WindowData.java | Java | [] | null | [] | package com.github.freeacs.web.app.page.window;
import com.github.freeacs.web.app.input.Input;
import com.github.freeacs.web.app.input.InputData;
import java.util.Map;
/** The Class WindowData. */
public class WindowData extends InputData {
/** The download. */
private Input download = Input.getStringInput("download");
/** The regular. */
private Input regular = Input.getStringInput("regular");
/** The frequency. */
private Input frequency = Input.getStringInput("frequency");
/** The page. */
private Input page = Input.getStringInput("page");
/**
* Sets the download.
*
* @param download the new download
*/
public void setDownload(Input download) {
this.download = download;
}
/**
* Gets the download.
*
* @return the download
*/
public Input getDownload() {
return download;
}
/**
* Sets the regular.
*
* @param regular the new regular
*/
public void setRegular(Input regular) {
this.regular = regular;
}
/**
* Gets the regular.
*
* @return the regular
*/
public Input getRegular() {
return regular;
}
/**
* Sets the frequency.
*
* @param frequency the new frequency
*/
public void setFrequency(Input frequency) {
this.frequency = frequency;
}
/**
* Gets the frequency.
*
* @return the frequency
*/
public Input getFrequency() {
return frequency;
}
/**
* Sets the page.
*
* @param page the new page
*/
public void setPage(Input page) {
this.page = page;
}
/**
* Gets the page.
*
* @return the page
*/
public Input getPage() {
return page;
}
@Override
public void bindForm(Map<String, Object> root) {}
@Override
public boolean validateForm() {
return false;
}
}
| 1,790 | 0.621229 | 0.621229 | 100 | 16.9 | 16.498787 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.18 | false | false | 3 |
41ca07f1b0c8803659ff6189868fa700c22b0b21 | 24,515,673,360,930 | 3a8f56b4cd8dbef8d7466006045218f299fd3c7a | /maven/jakarta-slide-kernel/src/main/java/org/apache/slide/extractor/SimpleXmlExtractor.java | e0c2a192d2244c40ad7ed73b8cd298353d668534 | [
"Apache-2.0"
] | permissive | integrated/jakarta-slide-server | https://github.com/integrated/jakarta-slide-server | cc308e5d1e0227f4175ded571db88785243991ab | d8ca711048cc6fe559f7b06a9ae0d64f6ecb574f | refs/heads/master | 2020-03-02T18:14:15.476000 | 2013-02-08T14:33:14 | 2013-02-08T14:33:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* $Header: /var/chroot/cvs/cvs/factsheetDesigner/extern/jakarta-slide-server-src-2.1-iPlus Edit/src/share/org/apache/slide/extractor/SimpleXmlExtractor.java,v 1.2 2006-01-22 22:49:05 peter-cvs Exp $
* $Revision: 1.2 $
* $Date: 2006-01-22 22:49:05 $
*
* ====================================================================
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.slide.extractor;
import org.apache.slide.common.PropertyName;
import org.apache.slide.util.conf.Configurable;
import org.apache.slide.util.conf.Configuration;
import org.apache.slide.util.conf.ConfigurationException;
import org.apache.slide.util.CustomSAXBuilder;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* The SimpleXmlExtractor class
*
*/
public class SimpleXmlExtractor extends AbstractPropertyExtractor implements Configurable {
protected List instructions = new ArrayList();
public SimpleXmlExtractor(String uri, String contentType, String namespace) {
super(uri, contentType, namespace);
}
public Map extract(InputStream content) throws ExtractorException {
Map properties = new HashMap();
try {
SAXBuilder saxBuilder = CustomSAXBuilder.newInstance();
Document document = saxBuilder.build(content);
for (Iterator i = instructions.iterator(); i.hasNext();) {
Instruction instruction = (Instruction) i.next();
XPath xPath = instruction.getxPath();
List nodeList = xPath.selectNodes(document);
Object propertyValue = filter(nodeList, instruction);
if (propertyValue != null) {
properties.put(instruction.getPropertyName(), propertyValue);
}
}
} catch (IOException e) {
throw new ExtractorException("Exception while retrieving content");
} catch (JDOMException e) {
throw new ExtractorException("Exception while parsing content. XML document must be wellformed.");
}
return properties;
}
public void configure(Configuration configuration) throws ConfigurationException {
Enumeration instructions = configuration.getConfigurations("instruction");
while (instructions.hasMoreElements()) {
Configuration instruction = (Configuration) instructions.nextElement();
addInstruction(createInstruction(instruction));
}
}
/**
* Allow subclasses to apply filtering to property values before they are written.
* Returning null signals that the extractor ignors this value.
*
* @param text the Node List identified by the xpath instruction.
* @return the property value to be set, <code>null</codee> if to be ignored.
*/
protected Object filter(List nodeList, Instruction instruction) throws ExtractorException {
if (nodeList.size() > 0) {
if (nodeList.get(0) instanceof Text) {
return ((Text) nodeList.get(0)).getText();
} else if (nodeList.get(0) instanceof Attribute) {
return ((Attribute) nodeList.get(0)).getValue();
} else if (nodeList.get(0) instanceof String) {
return nodeList.get(0);
}
}
return null;
}
protected void addInstruction(Instruction instruction) {
instructions.add(instruction);
}
protected Instruction createInstruction(Configuration instruction) throws ConfigurationException {
try {
String property = instruction.getAttribute("property");
String namespace = instruction.getAttribute("namespace", "DAV:");
XPath xPath = XPath.newInstance(instruction.getAttribute("xpath"));
return new Instruction(xPath, new PropertyName(property, namespace));
} catch (JDOMException e) {
throw new ConfigurationException("Could not create xPath from given attribute", instruction);
}
}
protected static class Instruction {
private XPath xPath;
private PropertyName propertyName;
public Instruction(XPath xPath, PropertyName property) {
this.xPath = xPath;
this.propertyName = property;
}
public XPath getxPath() {
return xPath;
}
public PropertyName getPropertyName() {
return propertyName;
}
}
}
| UTF-8 | Java | 5,198 | java | SimpleXmlExtractor.java | Java | [
{
"context": "XmlExtractor.java,v 1.2 2006-01-22 22:49:05 peter-cvs Exp $\n * $Revision: 1.2 $\n * $Date: 2006-01-22 2",
"end": 195,
"score": 0.6346368789672852,
"start": 193,
"tag": "USERNAME",
"value": "cv"
}
] | null | [] | /*
* $Header: /var/chroot/cvs/cvs/factsheetDesigner/extern/jakarta-slide-server-src-2.1-iPlus Edit/src/share/org/apache/slide/extractor/SimpleXmlExtractor.java,v 1.2 2006-01-22 22:49:05 peter-cvs Exp $
* $Revision: 1.2 $
* $Date: 2006-01-22 22:49:05 $
*
* ====================================================================
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.slide.extractor;
import org.apache.slide.common.PropertyName;
import org.apache.slide.util.conf.Configurable;
import org.apache.slide.util.conf.Configuration;
import org.apache.slide.util.conf.ConfigurationException;
import org.apache.slide.util.CustomSAXBuilder;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* The SimpleXmlExtractor class
*
*/
public class SimpleXmlExtractor extends AbstractPropertyExtractor implements Configurable {
protected List instructions = new ArrayList();
public SimpleXmlExtractor(String uri, String contentType, String namespace) {
super(uri, contentType, namespace);
}
public Map extract(InputStream content) throws ExtractorException {
Map properties = new HashMap();
try {
SAXBuilder saxBuilder = CustomSAXBuilder.newInstance();
Document document = saxBuilder.build(content);
for (Iterator i = instructions.iterator(); i.hasNext();) {
Instruction instruction = (Instruction) i.next();
XPath xPath = instruction.getxPath();
List nodeList = xPath.selectNodes(document);
Object propertyValue = filter(nodeList, instruction);
if (propertyValue != null) {
properties.put(instruction.getPropertyName(), propertyValue);
}
}
} catch (IOException e) {
throw new ExtractorException("Exception while retrieving content");
} catch (JDOMException e) {
throw new ExtractorException("Exception while parsing content. XML document must be wellformed.");
}
return properties;
}
public void configure(Configuration configuration) throws ConfigurationException {
Enumeration instructions = configuration.getConfigurations("instruction");
while (instructions.hasMoreElements()) {
Configuration instruction = (Configuration) instructions.nextElement();
addInstruction(createInstruction(instruction));
}
}
/**
* Allow subclasses to apply filtering to property values before they are written.
* Returning null signals that the extractor ignors this value.
*
* @param text the Node List identified by the xpath instruction.
* @return the property value to be set, <code>null</codee> if to be ignored.
*/
protected Object filter(List nodeList, Instruction instruction) throws ExtractorException {
if (nodeList.size() > 0) {
if (nodeList.get(0) instanceof Text) {
return ((Text) nodeList.get(0)).getText();
} else if (nodeList.get(0) instanceof Attribute) {
return ((Attribute) nodeList.get(0)).getValue();
} else if (nodeList.get(0) instanceof String) {
return nodeList.get(0);
}
}
return null;
}
protected void addInstruction(Instruction instruction) {
instructions.add(instruction);
}
protected Instruction createInstruction(Configuration instruction) throws ConfigurationException {
try {
String property = instruction.getAttribute("property");
String namespace = instruction.getAttribute("namespace", "DAV:");
XPath xPath = XPath.newInstance(instruction.getAttribute("xpath"));
return new Instruction(xPath, new PropertyName(property, namespace));
} catch (JDOMException e) {
throw new ConfigurationException("Could not create xPath from given attribute", instruction);
}
}
protected static class Instruction {
private XPath xPath;
private PropertyName propertyName;
public Instruction(XPath xPath, PropertyName property) {
this.xPath = xPath;
this.propertyName = property;
}
public XPath getxPath() {
return xPath;
}
public PropertyName getPropertyName() {
return propertyName;
}
}
}
| 5,198 | 0.659484 | 0.650058 | 137 | 36.941605 | 32.852196 | 199 | false | false | 0 | 0 | 0 | 0 | 69 | 0.013274 | 0.49635 | false | false | 3 |
968ba9366565eb1334d268122fe475459214fd0b | 7,739,531,116,623 | bb88d398f7ff89365e4c16656c1fc6b376e11cd0 | /xsl-autoconfig-mvc/src/main/java/com/openxsl/config/filedata/export/service/ImportService.java | 74ca69008e66478ab8b41dfc07a4436bf42f03a1 | [] | no_license | shlxiong/autoconfig | https://github.com/shlxiong/autoconfig | e93a88e1acb8a2190359a4d6dad225cb943ebdce | c1302c6733b870d61f0d21a8c8bb310d3614265e | refs/heads/master | 2022-12-23T13:57:00.854000 | 2022-06-22T13:41:37 | 2022-06-22T13:41:37 | 247,972,058 | 2 | 0 | null | false | 2022-12-16T10:03:38 | 2020-03-17T13:07:58 | 2022-05-15T05:07:10 | 2022-12-16T10:03:36 | 1,880 | 2 | 0 | 21 | Java | false | false | package com.openxsl.config.filedata.export.service;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;
import com.openxsl.base.framework.service.BaseEntity;
import com.openxsl.base.utils.StringUtils;
import com.openxsl.config.dal.ExcelUtils;
import com.openxsl.config.filedata.export.dao.ImportConfigDao;
import com.openxsl.config.filedata.export.dao.ImportLogDao;
import com.openxsl.config.filedata.export.dao.ImportMappingDao;
import com.openxsl.config.filedata.export.entity.ImportConfig;
import com.openxsl.config.filedata.export.entity.ImportLog;
import com.openxsl.config.filedata.export.entity.ImportMapping;
@ConditionalOnClass(JdbcTemplate.class)
@Service
public class ImportService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private ImportMappingDao mappingDao;
@Autowired
private ImportConfigDao configDao;
@Autowired
private ImportLogDao importDao;
public void importFile(ImportLog importLog) {
importLog.setImportTime(new Date());
String importName = importLog.getImportName();
String scenicCode = importLog.getScenicCode();
ImportConfig importConfig = configDao.getImportConfig(importName, scenicCode);
String tableName = importConfig.getTableName();
boolean skipFirst = importConfig.isFirstCaption();
List<ImportMapping> mappings = mappingDao.getMappings(importName, scenicCode);
String sql = this.getSql(tableName, mappings);
int succs = 0, fails = 0;
try {
for (Map<String,?> rowData : ExcelUtils.readFile(importLog.getSourceFile(), skipFirst)) {
Object[] args = new Object[mappings.size()];
int i = 0;
for (ImportMapping mapping : mappings) {
args[i++] = this.getValue(rowData, mapping);
}
if (this.executeInsert(sql, args) > 0) {
succs ++;
} else {
fails ++;
importLog.setFailRecord((String)rowData.get("A")); //第一列为Key
}
}
importLog.setSuccessNum(succs);
importLog.setFailNum(fails);
importLog.setTotalNum(succs+fails);
importDao.insert(importLog);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据表名生成初始的Mapping
* @param tableName
* @throws SQLException
*/
public Collection<ImportMapping> generateMappings(String tableName) {
Map<String,ImportMapping> columnMap = new LinkedHashMap<String,ImportMapping>();
String sql = new StringBuilder("SELECT * FROM ").append(tableName)
.append(" WHERE 1<>1").toString();
try {
ResultSet rs = jdbcTemplate.getDataSource().getConnection()
.prepareStatement(sql).executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i=2,cnt=rsmd.getColumnCount(); i<=cnt; i++) { //1:Id,从第二个开始
ImportMapping mapping = new ImportMapping();
mapping.setColumnName(rsmd.getColumnName(i));
mapping.setDataType(rsmd.getColumnClassName(i)); //JdbcUtils.getTypeName(rsmd.getColumnType(i));
mapping.setMaxLen(rsmd.getPrecision(i));
columnMap.put(mapping.getColumnName(), mapping);
}
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.CREATE_BY_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.CREATE_TIME_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.MODIFY_BY_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.MODIFY_TIME_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.DELETED_FIELD, "_"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return columnMap.values();
}
/**
* 通过名称获取Mapping
* @param name
*/
public List<ImportMapping> getMappings(String name, String scenicCode){
return mappingDao.getMappings(name, scenicCode);
}
public ImportConfig getImportConfig(String name, String scenicCode) {
return configDao.getImportConfig(name, scenicCode);
}
/**
* 保存文件-表的映射关系
* @param name
*/
public void saveMappings(String importName, ImportMapping[] importMappings, String scenicCode) {
if (importMappings==null || importMappings.length < 1) {
return;
}
//删除原来的
mappingDao.deleteByConfigName(importName, scenicCode);
for (ImportMapping mapping : importMappings) {
if (mapping.getConfigName() == null) {
mapping.setConfigName(importName);
}
mappingDao.insert(mapping);
}
}
// @see ImportConfigService
// public void saveImportConfig(ImportConfig config) {
// int cnt = configDao.update(config);
// if (cnt < 1) {
// configDao.insert(config);
// }
// }
private String getSql(String tableName, List<ImportMapping> mappings) {
StringBuilder buffer = new StringBuilder("INSERT INTO ").append(tableName);
StringBuilder fieldBuf = new StringBuilder("(");
StringBuilder valueBuf = new StringBuilder(") VALUES (");
for (ImportMapping mapping : mappings) {
fieldBuf.append(mapping.getColumnName()).append(", ");
valueBuf.append("?, ");
}
String createBy = StringUtils.camelToSplitJoin(BaseEntity.CREATE_TIME_FIELD, "_");
String modifyBy = StringUtils.camelToSplitJoin(BaseEntity.MODIFY_TIME_FIELD, "_");
fieldBuf.append(createBy).append(", ").append(modifyBy);
valueBuf.append("now(), now())");
buffer.append(fieldBuf).append(valueBuf);
// .append(valueBuf.substring(0, valueBuf.length()-2)).append(')');
return buffer.toString();
}
private Object getValue(Map<String,?> rowData, ImportMapping mapping) {
Object value = rowData.get(mapping.getExcelColumnNo());
String reference = mapping.getReference(); //table.column1 on column2
if (!StringUtils.isEmpty(reference)) {
String[] temps = reference.split("\\.|( on )");
String sql = String.format("SELECT %s FROM %s WHERE %s = ?", temps[1],temps[0],temps[2]);
Map<String,Object> map = jdbcTemplate.queryForMap(sql, value);
String name2 = temps[1].toUpperCase();
value = map.getOrDefault(temps[1], map.getOrDefault(name2, value));
}
return value;
}
private int executeInsert(String sql, Object[] args) {
try {
return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() {
@Override
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
int i = 0;
for (Object arg : args) {
ps.setObject(++i, arg);
}
return ps.executeUpdate();
}
});
} catch (Exception e) {
logger.error("", e);
return 0;
}
}
// private int batchInsert(String sql, List<ImportMapping> mappings) {
// int batchSize = 100;
// int dataSize = 0;
// List<Object[]> batchArgs = new ArrayList<Object[]>(batchSize);
// for (Map<String,?> rowData : ExcelUtils.readFile(importLog.getSourceFile(), 0)) {
// Object[] args = null;
// for (ImportMapping mapping : mappings) {
// Object value = rowData.get(mapping.getExcelColumnNo());
// String reference = mapping.getReference();
// if (StringUtils.isEmpty(reference)) {
//
// }
// }
// batchArgs.add(args);
// if (batchSize == batchArgs.size() || dataSize == batchArgs.size()) {
// int[] rows = jdbcTemplate.batchUpdate(sql, batchArgs);
// batchArgs.clear();
// }
// }
// }
}
| UTF-8 | Java | 7,757 | java | ImportService.java | Java | [] | null | [] | package com.openxsl.config.filedata.export.service;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;
import com.openxsl.base.framework.service.BaseEntity;
import com.openxsl.base.utils.StringUtils;
import com.openxsl.config.dal.ExcelUtils;
import com.openxsl.config.filedata.export.dao.ImportConfigDao;
import com.openxsl.config.filedata.export.dao.ImportLogDao;
import com.openxsl.config.filedata.export.dao.ImportMappingDao;
import com.openxsl.config.filedata.export.entity.ImportConfig;
import com.openxsl.config.filedata.export.entity.ImportLog;
import com.openxsl.config.filedata.export.entity.ImportMapping;
@ConditionalOnClass(JdbcTemplate.class)
@Service
public class ImportService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private ImportMappingDao mappingDao;
@Autowired
private ImportConfigDao configDao;
@Autowired
private ImportLogDao importDao;
public void importFile(ImportLog importLog) {
importLog.setImportTime(new Date());
String importName = importLog.getImportName();
String scenicCode = importLog.getScenicCode();
ImportConfig importConfig = configDao.getImportConfig(importName, scenicCode);
String tableName = importConfig.getTableName();
boolean skipFirst = importConfig.isFirstCaption();
List<ImportMapping> mappings = mappingDao.getMappings(importName, scenicCode);
String sql = this.getSql(tableName, mappings);
int succs = 0, fails = 0;
try {
for (Map<String,?> rowData : ExcelUtils.readFile(importLog.getSourceFile(), skipFirst)) {
Object[] args = new Object[mappings.size()];
int i = 0;
for (ImportMapping mapping : mappings) {
args[i++] = this.getValue(rowData, mapping);
}
if (this.executeInsert(sql, args) > 0) {
succs ++;
} else {
fails ++;
importLog.setFailRecord((String)rowData.get("A")); //第一列为Key
}
}
importLog.setSuccessNum(succs);
importLog.setFailNum(fails);
importLog.setTotalNum(succs+fails);
importDao.insert(importLog);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据表名生成初始的Mapping
* @param tableName
* @throws SQLException
*/
public Collection<ImportMapping> generateMappings(String tableName) {
Map<String,ImportMapping> columnMap = new LinkedHashMap<String,ImportMapping>();
String sql = new StringBuilder("SELECT * FROM ").append(tableName)
.append(" WHERE 1<>1").toString();
try {
ResultSet rs = jdbcTemplate.getDataSource().getConnection()
.prepareStatement(sql).executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i=2,cnt=rsmd.getColumnCount(); i<=cnt; i++) { //1:Id,从第二个开始
ImportMapping mapping = new ImportMapping();
mapping.setColumnName(rsmd.getColumnName(i));
mapping.setDataType(rsmd.getColumnClassName(i)); //JdbcUtils.getTypeName(rsmd.getColumnType(i));
mapping.setMaxLen(rsmd.getPrecision(i));
columnMap.put(mapping.getColumnName(), mapping);
}
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.CREATE_BY_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.CREATE_TIME_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.MODIFY_BY_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.MODIFY_TIME_FIELD, "_"));
columnMap.remove(StringUtils.camelToSplitJoin(BaseEntity.DELETED_FIELD, "_"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return columnMap.values();
}
/**
* 通过名称获取Mapping
* @param name
*/
public List<ImportMapping> getMappings(String name, String scenicCode){
return mappingDao.getMappings(name, scenicCode);
}
public ImportConfig getImportConfig(String name, String scenicCode) {
return configDao.getImportConfig(name, scenicCode);
}
/**
* 保存文件-表的映射关系
* @param name
*/
public void saveMappings(String importName, ImportMapping[] importMappings, String scenicCode) {
if (importMappings==null || importMappings.length < 1) {
return;
}
//删除原来的
mappingDao.deleteByConfigName(importName, scenicCode);
for (ImportMapping mapping : importMappings) {
if (mapping.getConfigName() == null) {
mapping.setConfigName(importName);
}
mappingDao.insert(mapping);
}
}
// @see ImportConfigService
// public void saveImportConfig(ImportConfig config) {
// int cnt = configDao.update(config);
// if (cnt < 1) {
// configDao.insert(config);
// }
// }
private String getSql(String tableName, List<ImportMapping> mappings) {
StringBuilder buffer = new StringBuilder("INSERT INTO ").append(tableName);
StringBuilder fieldBuf = new StringBuilder("(");
StringBuilder valueBuf = new StringBuilder(") VALUES (");
for (ImportMapping mapping : mappings) {
fieldBuf.append(mapping.getColumnName()).append(", ");
valueBuf.append("?, ");
}
String createBy = StringUtils.camelToSplitJoin(BaseEntity.CREATE_TIME_FIELD, "_");
String modifyBy = StringUtils.camelToSplitJoin(BaseEntity.MODIFY_TIME_FIELD, "_");
fieldBuf.append(createBy).append(", ").append(modifyBy);
valueBuf.append("now(), now())");
buffer.append(fieldBuf).append(valueBuf);
// .append(valueBuf.substring(0, valueBuf.length()-2)).append(')');
return buffer.toString();
}
private Object getValue(Map<String,?> rowData, ImportMapping mapping) {
Object value = rowData.get(mapping.getExcelColumnNo());
String reference = mapping.getReference(); //table.column1 on column2
if (!StringUtils.isEmpty(reference)) {
String[] temps = reference.split("\\.|( on )");
String sql = String.format("SELECT %s FROM %s WHERE %s = ?", temps[1],temps[0],temps[2]);
Map<String,Object> map = jdbcTemplate.queryForMap(sql, value);
String name2 = temps[1].toUpperCase();
value = map.getOrDefault(temps[1], map.getOrDefault(name2, value));
}
return value;
}
private int executeInsert(String sql, Object[] args) {
try {
return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() {
@Override
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
int i = 0;
for (Object arg : args) {
ps.setObject(++i, arg);
}
return ps.executeUpdate();
}
});
} catch (Exception e) {
logger.error("", e);
return 0;
}
}
// private int batchInsert(String sql, List<ImportMapping> mappings) {
// int batchSize = 100;
// int dataSize = 0;
// List<Object[]> batchArgs = new ArrayList<Object[]>(batchSize);
// for (Map<String,?> rowData : ExcelUtils.readFile(importLog.getSourceFile(), 0)) {
// Object[] args = null;
// for (ImportMapping mapping : mappings) {
// Object value = rowData.get(mapping.getExcelColumnNo());
// String reference = mapping.getReference();
// if (StringUtils.isEmpty(reference)) {
//
// }
// }
// batchArgs.add(args);
// if (batchSize == batchArgs.size() || dataSize == batchArgs.size()) {
// int[] rows = jdbcTemplate.batchUpdate(sql, batchArgs);
// batchArgs.clear();
// }
// }
// }
}
| 7,757 | 0.724691 | 0.720782 | 213 | 35.032864 | 26.77701 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.807512 | false | false | 3 |
0d201fbb5a71c1cf4d8ac15fee118ccff100ba48 | 32,427,003,119,492 | 1c3312b0dc82553276847631c99913e70e55e5ea | /src/main/java/it/tooly/fxtooly/tab/connector/Connector.java | 2acc610767b6a2a47365611c645cba4bf2651cc0 | [] | no_license | ruudk12/FXTooly | https://github.com/ruudk12/FXTooly | 9ec4e0db34bc2bfbcc1f5ab540a04a49726aa185 | 7b9953873c54f547880dfd5870d860febf0c8e06 | refs/heads/master | 2021-01-23T11:21:28.306000 | 2017-06-21T08:20:05 | 2017-06-21T08:20:05 | 93,134,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.tooly.fxtooly.tab.connector;
import it.tooly.fxtooly.ToolyPane;
public class Connector extends ToolyPane {
public Connector() {
super();
}
}
| UTF-8 | Java | 167 | java | Connector.java | Java | [] | null | [] | package it.tooly.fxtooly.tab.connector;
import it.tooly.fxtooly.ToolyPane;
public class Connector extends ToolyPane {
public Connector() {
super();
}
}
| 167 | 0.706587 | 0.706587 | 9 | 16.555555 | 16.733938 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 3 |
8af522c7015508cef42d5936b370efe74df02eed | 463,856,489,391 | 8d17eed31463934283696945ce5c8d2e17478608 | /app/src/main/java/com/kuaimeizhuang/fashionmix/bean/UserPageBean.java | ca12f334f386f8578354e407a6ff5e3a9b2d8742 | [] | no_license | shiguangxiang/dome | https://github.com/shiguangxiang/dome | 6a780c646472c50f55fe1a8473e2dc4810cd4595 | 44b6987dbb75b99b03879973742dbf2e4920af3c | refs/heads/master | 2021-06-17T16:38:58.402000 | 2017-06-08T04:25:25 | 2017-06-08T04:25:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kuaimeizhuang.fashionmix.bean;
import com.kuaimeizhuang.fashionmix.bean.base.BaseBean;
import java.util.List;
/**
* <p>用户个人主页</p>
* Created on 17/6/3.
*
* @author Shi GuangXiang.
*/
public class UserPageBean extends BaseBean {
private int per_page;
private boolean has_page;
private List<Post> Posts;
public int getPer_page() {
return per_page;
}
public void setPer_page(int per_page) {
this.per_page = per_page;
}
public boolean isHas_page() {
return has_page;
}
public void setHas_page(boolean has_page) {
this.has_page = has_page;
}
public List<Post> getPosts() {
return Posts;
}
public void setPosts(List<Post> posts) {
Posts = posts;
}
} | UTF-8 | Java | 790 | java | UserPageBean.java | Java | [
{
"context": " <p>用户个人主页</p>\n * Created on 17/6/3.\n *\n * @author Shi GuangXiang.\n */\n\npublic class UserPageBean extends BaseBean ",
"end": 196,
"score": 0.999797523021698,
"start": 182,
"tag": "NAME",
"value": "Shi GuangXiang"
}
] | null | [] | package com.kuaimeizhuang.fashionmix.bean;
import com.kuaimeizhuang.fashionmix.bean.base.BaseBean;
import java.util.List;
/**
* <p>用户个人主页</p>
* Created on 17/6/3.
*
* @author <NAME>.
*/
public class UserPageBean extends BaseBean {
private int per_page;
private boolean has_page;
private List<Post> Posts;
public int getPer_page() {
return per_page;
}
public void setPer_page(int per_page) {
this.per_page = per_page;
}
public boolean isHas_page() {
return has_page;
}
public void setHas_page(boolean has_page) {
this.has_page = has_page;
}
public List<Post> getPosts() {
return Posts;
}
public void setPosts(List<Post> posts) {
Posts = posts;
}
} | 782 | 0.616967 | 0.611825 | 43 | 17.11628 | 16.606541 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27907 | false | false | 3 |
35184ab643f147a7fac4e4be3e2b324ff842f5a5 | 463,856,487,847 | 94f9172c894c3d578ab9321c2c6f6dfcaa64182b | /src/by/dbarkova/runner/MainApp4.java | 03f612ad3569813d5ab092511ba95879704fef74 | [] | no_license | daryabarkova/Lesson9 | https://github.com/daryabarkova/Lesson9 | 393cab89fe232e3de6b773020fb1f513765bb089 | 126cb42c736c40a9e2b88e42f0921cb7f986e9d9 | refs/heads/master | 2021-05-12T15:07:32.523000 | 2018-01-10T15:31:40 | 2018-01-10T15:31:40 | 116,975,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.dbarkova.runner;
import java.util.Arrays;
public class MainApp4 {
public static void main(String[] args) {
// гл. 7, вар. А, задание 9
// Определить, сколько раз повторяется в тексте каждое слово, которое встречается в нем.. (используя String)
String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet.";
System.out.println(s);
String s1 = s.replace('.', ' ');
String s2 = s1.replace(',', ' ');
System.out.println(s2);
String[] words = s2.split(" ");
Arrays.sort(words);
for(String word : words) {
System.out.println("word is " + word);
String[] wordsUnique = new String[10];
int c = 0;
for(int i = 0; i < words.length; i++) {
if(i == words.length - 1) {
wordsUnique[c] = words[i];
}else if(!words[i].equals(" ") && !words[i].equals(words[i + 1])) {
wordsUnique[c] = words[i];
c = c + 1;
}
}
for(String wordUnique : wordsUnique) {
System.out.println("Unique word is: " + wordUnique);
}
}
}
}
| WINDOWS-1251 | Java | 1,262 | java | MainApp4.java | Java | [
{
"context": "\n\r\n\tpublic static void main(String[] args) {\r\n\t\t// гл. 7, вар. А, задание 9\r\n\t\t// Определить, сколько ",
"end": 135,
"score": 0.7592867612838745,
"start": 134,
"tag": "NAME",
"value": "г"
},
{
"context": "lic static void main(String[] args) {\r\n\t\t// гл. 7... | null | [] | package by.dbarkova.runner;
import java.util.Arrays;
public class MainApp4 {
public static void main(String[] args) {
// гл. 7, <NAME>, задание 9
// Определить, сколько раз повторяется в тексте каждое слово, которое встречается в нем.. (используя String)
String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet.";
System.out.println(s);
String s1 = s.replace('.', ' ');
String s2 = s1.replace(',', ' ');
System.out.println(s2);
String[] words = s2.split(" ");
Arrays.sort(words);
for(String word : words) {
System.out.println("word is " + word);
String[] wordsUnique = new String[10];
int c = 0;
for(int i = 0; i < words.length; i++) {
if(i == words.length - 1) {
wordsUnique[c] = words[i];
}else if(!words[i].equals(" ") && !words[i].equals(words[i + 1])) {
wordsUnique[c] = words[i];
c = c + 1;
}
}
for(String wordUnique : wordsUnique) {
System.out.println("Unique word is: " + wordUnique);
}
}
}
}
| 1,258 | 0.576561 | 0.56373 | 46 | 23.413044 | 29.678404 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.804348 | false | false | 3 |
b6ff299385a451f0b6cf724923ee2615d7a1b157 | 21,964,462,774,152 | 73238bea4a755981f8ab4016038aae76093fd305 | /src/main/java/com/job/user/review/service/impl/ReviewUserServiceImpl.java | 734ad413f8552e07a705c3d53e154ee484ca060c | [] | no_license | nhi2020/job | https://github.com/nhi2020/job | 15adc5e09b90cdf70c8d266e1a7b0f3bbf1a036a | 9c5d411d924d56d7c9e4ca75107e931fbf89d490 | refs/heads/master | 2023-01-03T10:01:43.307000 | 2020-10-27T02:53:49 | 2020-10-27T02:53:49 | 299,147,647 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.job.user.review.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.job.user.biz.service.BizUserVO;
import com.job.user.review.service.ReviewUserService;
import com.job.user.review.service.ReviewUserVO;
@Service("reviewUserService")
public class ReviewUserServiceImpl implements ReviewUserService {
@Resource(name="reviewUserDAO")
private ReviewUserDAO reviewUserDAO;
/*리뷰리스트*/
public ReviewUserVO reviewBizInfo(ReviewUserVO reviewUserVO) {
ReviewUserVO reviewBizInfo = reviewUserDAO.reviewBizInfo(reviewUserVO);
return reviewBizInfo;
}
/*-기업리뷰*/
@Override
public List<ReviewUserVO> reviewSelectList1(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl");
return reviewUserDAO.reviewSelectList1(reviewUserVO);
}
@Override
public int total1(String bsmno) {
System.out.println("ReviewUserServiceImpl total1");
return reviewUserDAO.total1(bsmno);
}
/*-기업연봉*/
@Override
public List<ReviewUserVO> reviewSelectList2(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl" + reviewUserVO.getSal());
return reviewUserDAO.reviewSelectList2(reviewUserVO);
}
@Override
public int total2(String bsmno) {
return reviewUserDAO.total2(bsmno);
}
/*-면접후기*/
@Override
public List<ReviewUserVO> reviewSelectList3(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl");
return reviewUserDAO.reviewSelectList3(reviewUserVO);
}
@Override
public int total3(String bsmno) {
return reviewUserDAO.total3(bsmno);
}
@Override
public int reviewSalChk(ReviewUserVO reviewUserVO) {
return reviewUserDAO.reviewSalChk(reviewUserVO);
}
@Override
public int salChkUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.salChkUpdate(reviewUserVO);
}
/*글작성*/
@Override
public int Write(ReviewUserVO reviewUserVO) {
return reviewUserDAO.Write(reviewUserVO);
}
@Override
public int mWrite(ReviewUserVO reviewUserVO) {
return reviewUserDAO.mWrite(reviewUserVO);
}
@Override
public int sWrite(ReviewUserVO reviewUserVO) {
return reviewUserDAO.sWrite(reviewUserVO);
}
/*리뷰상세보기*/
@Override
public ReviewUserVO reviewDetailForm(int rnum) {
return reviewUserDAO.reviewDetailForm(rnum);
}
@Override
public ReviewUserVO mreviewDetailForm(int rnum) {
return reviewUserDAO.mreviewDetailForm(rnum);
}
@Override
public ReviewUserVO salDetailForm(int rnum) {
return reviewUserDAO.salDetailForm(rnum);
}
/*리뷰 수정*/
@Override
public int reviewUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.Update(reviewUserVO);
}
@Override
public int salUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.sUpdate(reviewUserVO);
}
@Override
public int mreviewUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.mUpdate(reviewUserVO);
}
/*리뷰 삭제*/
@Override
public int Delete(int rnum) {
return reviewUserDAO.Delete(rnum);
}
}
| UTF-8 | Java | 3,117 | java | ReviewUserServiceImpl.java | Java | [] | null | [] | package com.job.user.review.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.job.user.biz.service.BizUserVO;
import com.job.user.review.service.ReviewUserService;
import com.job.user.review.service.ReviewUserVO;
@Service("reviewUserService")
public class ReviewUserServiceImpl implements ReviewUserService {
@Resource(name="reviewUserDAO")
private ReviewUserDAO reviewUserDAO;
/*리뷰리스트*/
public ReviewUserVO reviewBizInfo(ReviewUserVO reviewUserVO) {
ReviewUserVO reviewBizInfo = reviewUserDAO.reviewBizInfo(reviewUserVO);
return reviewBizInfo;
}
/*-기업리뷰*/
@Override
public List<ReviewUserVO> reviewSelectList1(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl");
return reviewUserDAO.reviewSelectList1(reviewUserVO);
}
@Override
public int total1(String bsmno) {
System.out.println("ReviewUserServiceImpl total1");
return reviewUserDAO.total1(bsmno);
}
/*-기업연봉*/
@Override
public List<ReviewUserVO> reviewSelectList2(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl" + reviewUserVO.getSal());
return reviewUserDAO.reviewSelectList2(reviewUserVO);
}
@Override
public int total2(String bsmno) {
return reviewUserDAO.total2(bsmno);
}
/*-면접후기*/
@Override
public List<ReviewUserVO> reviewSelectList3(ReviewUserVO reviewUserVO) {
System.out.println("StartServiceImpl");
return reviewUserDAO.reviewSelectList3(reviewUserVO);
}
@Override
public int total3(String bsmno) {
return reviewUserDAO.total3(bsmno);
}
@Override
public int reviewSalChk(ReviewUserVO reviewUserVO) {
return reviewUserDAO.reviewSalChk(reviewUserVO);
}
@Override
public int salChkUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.salChkUpdate(reviewUserVO);
}
/*글작성*/
@Override
public int Write(ReviewUserVO reviewUserVO) {
return reviewUserDAO.Write(reviewUserVO);
}
@Override
public int mWrite(ReviewUserVO reviewUserVO) {
return reviewUserDAO.mWrite(reviewUserVO);
}
@Override
public int sWrite(ReviewUserVO reviewUserVO) {
return reviewUserDAO.sWrite(reviewUserVO);
}
/*리뷰상세보기*/
@Override
public ReviewUserVO reviewDetailForm(int rnum) {
return reviewUserDAO.reviewDetailForm(rnum);
}
@Override
public ReviewUserVO mreviewDetailForm(int rnum) {
return reviewUserDAO.mreviewDetailForm(rnum);
}
@Override
public ReviewUserVO salDetailForm(int rnum) {
return reviewUserDAO.salDetailForm(rnum);
}
/*리뷰 수정*/
@Override
public int reviewUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.Update(reviewUserVO);
}
@Override
public int salUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.sUpdate(reviewUserVO);
}
@Override
public int mreviewUpdate(ReviewUserVO reviewUserVO) {
return reviewUserDAO.mUpdate(reviewUserVO);
}
/*리뷰 삭제*/
@Override
public int Delete(int rnum) {
return reviewUserDAO.Delete(rnum);
}
}
| 3,117 | 0.75205 | 0.747786 | 112 | 25.223215 | 22.458576 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 3 |
21cea243885c12c9dddf943b47cb58ce5c7d675a | 18,382,460,051,147 | 378983b57bf0d39a3a009697c999f5fc79d11061 | /src/main/java/com/ymourino/ad04/utils/CommandPrompt.java | 9292ccc81667e3b3e5400ab12d6a8afd8c5e8f34 | [] | no_license | yago1982/AD04 | https://github.com/yago1982/AD04 | b27cd03bf4c3d9ffd628d27a4bf3e0170cebec91 | 53fd0ac8b3598060729e972c3d093a9aa32cbdba | refs/heads/master | 2022-06-27T02:26:09.476000 | 2020-02-09T20:59:27 | 2020-02-09T20:59:27 | 239,373,501 | 0 | 0 | null | false | 2022-05-20T21:24:27 | 2020-02-09T21:00:10 | 2020-02-09T21:01:12 | 2022-05-20T21:24:27 | 27 | 0 | 0 | 3 | Java | false | false | /*
* NOTA IMPORTANTE: las clases del paquete com.ymourino.ad04.utils son parte de un proyecto personal todavía en desarrollo.
* Hay código que se deriva del diseño previo realizado para dicho proyecto, pero que todavía no tiene una utilidad real
* en este momento.
*/
package com.ymourino.ad04.utils;
import java.util.LinkedHashMap;
/**
* <p>Clase encargada de interactuar con el usuario mediante una línea de comandos muy básica.</p>
*/
public class CommandPrompt {
private LinkedHashMap<String, Command> commands;
private boolean customHelp;
private boolean customQuit;
private String prompt;
/**
* <p>Constructor de la clase. Es privado porque esta clase utiliza <b>method chaining</b> para trabajar.</p></p>
*/
private CommandPrompt() {
commands = new LinkedHashMap<>();
customHelp = false;
customQuit = false;
prompt = null;
/*commands.put("quit",
Command.withName("quit").withDescription("Finaliza el programa").withMethod(() -> System.exit(0)));*/
}
/**
* <p>Constructor de la clase. Recibe los comandos que podrá ejecutar el programa y los almacena.</p>
*
* @param commands Un número indeterminado de objetos de la clase Command que serán los comandos que el usuario
* podrá ejecutar mediante órdenes en la línea de comandos.
* @return Objeto de la clase CommandPrompt.
* @throws IllegalArgumentException Se produce una excepción si se intentan almacenar dos comandos con el mismo nombre.
*/
public static CommandPrompt withCommands(Command... commands)
throws IllegalArgumentException {
CommandPrompt commandPrompt = new CommandPrompt();
for (Command command : commands) {
if (!commandPrompt.commands.containsKey(command.name())) {
commandPrompt.commands.put(command.name(), command);
} else {
if (!commandPrompt.customHelp && command.name().equals("help")) {
commandPrompt.commands.replace(command.name(), command);
commandPrompt.customHelp = true;
} else if (!commandPrompt.customQuit && command.name().equals("quit")) {
commandPrompt.commands.replace(command.name(), command);
commandPrompt.customQuit = true;
} else {
throw new IllegalArgumentException(
"El comando '" + command.name() + "' ya existe.");
}
}
}
return commandPrompt;
}
/**
* <p>Ejecuta un comando previamente introducido por el usuario en el teclado.</p>
*
* @param userInput Comando a ejecutar junto con cualesquiera parámetros adicionales.
* @throws IllegalArgumentException Se produce una excepción si el comando que se ha introducido no es correcto.
*/
private void executeCommand(String[] userInput)
throws IllegalArgumentException {
String command = userInput[0];
if (commands.containsKey(command)) {
commands.get(command).execute(userInput);
} else {
throw new IllegalArgumentException(
"Comando '" + command + "' no reconocido.");
}
}
/**
* <p>Solicita un comando al usuario y usa el método <b>executeCommand</b> para ejecutarlo.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @param messageForErrors Mensaje a mostrar en caso de error en la introducción del comando.
* @throws IllegalArgumentException Si la ejecución del comando produce alguna excepción.
*/
private void executeCommandFromUser(String prompt,
String messageForErrors)
throws IllegalArgumentException {
executeCommand(getCommandFromUser(prompt, messageForErrors));
}
/**
* <p>Lee la entrada del usuario, la separa según los espacios existentes, y comprueba el comando que se
* quiere ejecutar. Si el comando no existe se muestra un error, y en caso contrario se devuelve la
* matriz con el comando y sus parámetros.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @param messageForErrors Mensaje a mostrar en caso de error en la introducción de datos.
* @return Matriz con el comando y sus parámetros.
*/
private String[] getCommandFromUser(String prompt, String messageForErrors) {
do {
String[] userInput = KeyboardReader.readString(prompt, messageForErrors, true)
.split(" ");
String command = userInput[0];
if (commands.containsKey(command)) {
return userInput;
} else {
System.out.println("Comando '" + command + "' no reconocido.");
}
} while (true);
}
/**
* <p>Entra en un bucle infinito que pide constantemente comandos al usuario y los va ejecutando. El programa solo
* terminará si alguno de dichos comandos provoca la salida.</p>
*/
public void run() {
while (true) {
System.out.println();
System.out.println();
System.out.println("MENU");
System.out.println("====");
System.out.println();
for (String k : commands.keySet()) {
System.out.println(commands.get(k).name() + ".\t" + commands.get(k).description());
if (commands.get(k).hasSeparator()) {
System.out.println();
}
}
System.out.println();
executeCommandFromUser(this.prompt, "ERROR");
}
}
/**
* <p>Establece la cadena que se mostrará al usuario como prompt.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @return Se devuelve a sí mismo, implementando el patrón de diseño "method chaining".
*/
public CommandPrompt withPrompt(String prompt) {
this.prompt = prompt;
return this;
}
}
| UTF-8 | Java | 6,129 | java | CommandPrompt.java | Java | [] | null | [] | /*
* NOTA IMPORTANTE: las clases del paquete com.ymourino.ad04.utils son parte de un proyecto personal todavía en desarrollo.
* Hay código que se deriva del diseño previo realizado para dicho proyecto, pero que todavía no tiene una utilidad real
* en este momento.
*/
package com.ymourino.ad04.utils;
import java.util.LinkedHashMap;
/**
* <p>Clase encargada de interactuar con el usuario mediante una línea de comandos muy básica.</p>
*/
public class CommandPrompt {
private LinkedHashMap<String, Command> commands;
private boolean customHelp;
private boolean customQuit;
private String prompt;
/**
* <p>Constructor de la clase. Es privado porque esta clase utiliza <b>method chaining</b> para trabajar.</p></p>
*/
private CommandPrompt() {
commands = new LinkedHashMap<>();
customHelp = false;
customQuit = false;
prompt = null;
/*commands.put("quit",
Command.withName("quit").withDescription("Finaliza el programa").withMethod(() -> System.exit(0)));*/
}
/**
* <p>Constructor de la clase. Recibe los comandos que podrá ejecutar el programa y los almacena.</p>
*
* @param commands Un número indeterminado de objetos de la clase Command que serán los comandos que el usuario
* podrá ejecutar mediante órdenes en la línea de comandos.
* @return Objeto de la clase CommandPrompt.
* @throws IllegalArgumentException Se produce una excepción si se intentan almacenar dos comandos con el mismo nombre.
*/
public static CommandPrompt withCommands(Command... commands)
throws IllegalArgumentException {
CommandPrompt commandPrompt = new CommandPrompt();
for (Command command : commands) {
if (!commandPrompt.commands.containsKey(command.name())) {
commandPrompt.commands.put(command.name(), command);
} else {
if (!commandPrompt.customHelp && command.name().equals("help")) {
commandPrompt.commands.replace(command.name(), command);
commandPrompt.customHelp = true;
} else if (!commandPrompt.customQuit && command.name().equals("quit")) {
commandPrompt.commands.replace(command.name(), command);
commandPrompt.customQuit = true;
} else {
throw new IllegalArgumentException(
"El comando '" + command.name() + "' ya existe.");
}
}
}
return commandPrompt;
}
/**
* <p>Ejecuta un comando previamente introducido por el usuario en el teclado.</p>
*
* @param userInput Comando a ejecutar junto con cualesquiera parámetros adicionales.
* @throws IllegalArgumentException Se produce una excepción si el comando que se ha introducido no es correcto.
*/
private void executeCommand(String[] userInput)
throws IllegalArgumentException {
String command = userInput[0];
if (commands.containsKey(command)) {
commands.get(command).execute(userInput);
} else {
throw new IllegalArgumentException(
"Comando '" + command + "' no reconocido.");
}
}
/**
* <p>Solicita un comando al usuario y usa el método <b>executeCommand</b> para ejecutarlo.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @param messageForErrors Mensaje a mostrar en caso de error en la introducción del comando.
* @throws IllegalArgumentException Si la ejecución del comando produce alguna excepción.
*/
private void executeCommandFromUser(String prompt,
String messageForErrors)
throws IllegalArgumentException {
executeCommand(getCommandFromUser(prompt, messageForErrors));
}
/**
* <p>Lee la entrada del usuario, la separa según los espacios existentes, y comprueba el comando que se
* quiere ejecutar. Si el comando no existe se muestra un error, y en caso contrario se devuelve la
* matriz con el comando y sus parámetros.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @param messageForErrors Mensaje a mostrar en caso de error en la introducción de datos.
* @return Matriz con el comando y sus parámetros.
*/
private String[] getCommandFromUser(String prompt, String messageForErrors) {
do {
String[] userInput = KeyboardReader.readString(prompt, messageForErrors, true)
.split(" ");
String command = userInput[0];
if (commands.containsKey(command)) {
return userInput;
} else {
System.out.println("Comando '" + command + "' no reconocido.");
}
} while (true);
}
/**
* <p>Entra en un bucle infinito que pide constantemente comandos al usuario y los va ejecutando. El programa solo
* terminará si alguno de dichos comandos provoca la salida.</p>
*/
public void run() {
while (true) {
System.out.println();
System.out.println();
System.out.println("MENU");
System.out.println("====");
System.out.println();
for (String k : commands.keySet()) {
System.out.println(commands.get(k).name() + ".\t" + commands.get(k).description());
if (commands.get(k).hasSeparator()) {
System.out.println();
}
}
System.out.println();
executeCommandFromUser(this.prompt, "ERROR");
}
}
/**
* <p>Establece la cadena que se mostrará al usuario como prompt.</p>
*
* @param prompt Cadena a mostrar al usuario como prompt.
* @return Se devuelve a sí mismo, implementando el patrón de diseño "method chaining".
*/
public CommandPrompt withPrompt(String prompt) {
this.prompt = prompt;
return this;
}
}
| 6,129 | 0.614489 | 0.613342 | 150 | 39.673332 | 35.179256 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false | 3 |
4e2c3e4676c380ab92830e252717035fa8e2ce0a | 20,624,432,980,119 | 156480098917a674af10ec790d4069bd6ce6d4f2 | /src/com/design/patterns/gof/behavioural/strategy/DummyInventoryManager.java | a6427417dc5250d2f4eb0b95e8688dfb2c45b3e5 | [
"MIT"
] | permissive | kanaparthikiran/TakeOff | https://github.com/kanaparthikiran/TakeOff | 5cbdc1fda16897316e208aef2bf0f45f10162b7a | 35850511d73bbe8509e867b901831fced2703e01 | refs/heads/master | 2021-01-20T22:15:29.780000 | 2019-10-22T00:46:09 | 2019-10-22T00:46:09 | 60,874,908 | 1 | 0 | null | false | 2018-09-29T18:48:28 | 2016-06-10T20:26:19 | 2018-08-16T07:04:19 | 2018-09-29T18:48:28 | 18,730 | 1 | 0 | 0 | Java | false | null | /**
*
*/
package com.design.patterns.gof.behavioural.strategy;
/**
* @author kkanaparthi
*
*/
public class DummyInventoryManager implements InventoryManager {
/**
*
*/
public DummyInventoryManager() {
}
}
| UTF-8 | Java | 228 | java | DummyInventoryManager.java | Java | [
{
"context": "patterns.gof.behavioural.strategy;\n\n/**\n * @author kkanaparthi\n *\n */\npublic class DummyInventoryManager impleme",
"end": 93,
"score": 0.9972138404846191,
"start": 82,
"tag": "USERNAME",
"value": "kkanaparthi"
}
] | null | [] | /**
*
*/
package com.design.patterns.gof.behavioural.strategy;
/**
* @author kkanaparthi
*
*/
public class DummyInventoryManager implements InventoryManager {
/**
*
*/
public DummyInventoryManager() {
}
}
| 228 | 0.649123 | 0.649123 | 21 | 9.857142 | 17.650808 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 3 |
9a3d546101fd0281178156ea6403edbe5b226882 | 29,712,583,775,369 | 2d65a59bcee55237d8e122d77f3632dbb690310e | /app/src/main/java/net/kisslogo/holdyou/ui/activity/info/DataActivity.java | d866f705783f0a796d1f021cd865cf1bb8a08517 | [] | no_license | yz1309/holdyou | https://github.com/yz1309/holdyou | 71671b8853748b527e131dc481a37869dbb9296b | 8c105929495be4dbcbdff634f282a0547313f8f1 | refs/heads/master | 2021-05-06T11:56:34.247000 | 2019-07-03T09:30:34 | 2019-07-03T09:30:34 | 113,005,944 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.kisslogo.holdyou.ui.activity.info;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.opengl.GLSurfaceView;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.awesome.android.sdk.publish.Scloth;
import com.awesome.android.sdk.publish.enumbean.LayerErrorCode;
import com.awesome.android.sdk.publish.enumbean.ViewSize;
import com.awesome.android.sdk.publish.listener.IAwSclothListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import net.kisslogo.holdyou.MyApplication;
import net.kisslogo.holdyou.R;
import net.kisslogo.holdyou.adapter.DataListAdapter;
import net.kisslogo.holdyou.bean.DataListBean;
import net.kisslogo.holdyou.bean.SysAppAds;
import net.kisslogo.holdyou.common.DataConfig;
import net.kisslogo.holdyou.common.KeyConfig;
import net.kisslogo.holdyou.common.UIHelper;
import net.kisslogo.holdyou.ui.activity.base.BaseActivity;
import net.kisslogo.holdyou.ui.view.TitleView;
import net.kisslogo.holdyou.utils.CPUUtils;
import net.kisslogo.holdyou.utils.CameraUtil;
import net.kisslogo.holdyou.utils.GetEquipInfo;
import net.kisslogo.holdyou.utils.HomeGridDataUtils;
import net.kisslogo.holdyou.utils.PublicMethod;
import net.kisslogo.holdyou.utils.SDUtils;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.slantech.yzlibrary.interfaces.OnGetDataLinstener;
import top.slantech.yzlibrary.utils.SettingUtils;
import top.slantech.yzlibrary.utils.ULog;
/**
* 基础信息模块
* Created by slantech on 2017/12/05 10:35
*/
public class DataActivity extends BaseActivity {
@BindView(R.id.title_view)
TitleView titleView;
@BindView(R.id.rv_list)
RecyclerView rvList;
@BindView(R.id.refreshLayout)
SmartRefreshLayout refreshLayout;
DataListAdapter mAdapter;
private int mTypes;
private String mTitles;
Scloth scloth;
public static void actionStart(Activity context, int types) {
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("types", types);
context.startActivity(intent);
context.
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.include_list);
ButterKnife.bind(this);
mTypes = getIntent().getIntExtra("types", HomeGridDataUtils.Home_Type_Basic);
switch (mTypes) {
case HomeGridDataUtils.Home_Type_Basic:
mTitles = getString(R.string.basic);
break;
case HomeGridDataUtils.Home_Type_Cpu:
mTitles = getString(R.string.cpu);
break;
case HomeGridDataUtils.Home_Type_Storage:
mTitles = getString(R.string.storage);
break;
case HomeGridDataUtils.Home_Type_Gpu:
mTitles = getString(R.string.gpu);
break;
case HomeGridDataUtils.Home_Type_Battery:
mTitles = getString(R.string.battery);
break;
case HomeGridDataUtils.Home_Type_Net:
mTitles = getString(R.string.net2);
break;
case HomeGridDataUtils.Home_Type_Carmera:
mTitles = getString(R.string.carmera);
break;
case HomeGridDataUtils.Home_Type_Chuanganqi:
mTitles = getString(R.string.chuanganqi);
break;
default:
mTitles = getString(R.string.basic);
break;
}
titleView.setTopTitle(mTitles);
initAdapter();
initSwipe();
SysAppAds sysAppAds = UIHelper.checkIsShowAds(this, KeyConfig.Ads_Is_Show_Server_Banner,
-1);
if (sysAppAds.getIsOpen() == 0 && UIHelper.checkIsShowBannerAds(this)) {
new Handler(new Handler.Callback() {
// 处理接收到消息的方法
@Override
public boolean handleMessage(Message msg) {
initBannerAds();
return false;
}
}).sendEmptyMessageDelayed(0, 2000);
//表示延时2秒执行任务
}
}
@OnClick({R.id.ll_iv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_iv_right:
if (mAdapter != null && mAdapter.getData() != null && mAdapter.getData()
.size() > 0) {
MyApplication.showSaveStr(this, mTitles, mAdapter);
}
break;
}
}
private void initAdapter() {
mAdapter = new DataListAdapter(R.layout.item_data);
rvList.setLayoutManager(new LinearLayoutManager(this));
rvList.setAdapter(mAdapter);
}
private void initSwipe() {
refreshLayout.autoRefresh();
refreshLayout.setEnableLoadmore(false);
refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
@Override
public void onRefresh(final com.scwang.smartrefresh.layout.api.RefreshLayout
refreshlayout) {
initData();
}
@Override
public void onLoadmore(final com.scwang.smartrefresh.layout.api.RefreshLayout
refreshlayout) {
}
});
}
private void initData() {
switch (mTypes) {
case HomeGridDataUtils.Home_Type_Basic:
getBasicData();
break;
case HomeGridDataUtils.Home_Type_Cpu:
getCpuData();
break;
case HomeGridDataUtils.Home_Type_Storage:
getStorageData();
break;
case HomeGridDataUtils.Home_Type_Gpu:
getGpuData();
break;
case HomeGridDataUtils.Home_Type_Battery:
getBatteryData();
break;
case HomeGridDataUtils.Home_Type_Net:
getNetData();
break;
case HomeGridDataUtils.Home_Type_Carmera:
getCarmeraData();
break;
case HomeGridDataUtils.Home_Type_Chuanganqi:
getChuanGanQiData();
break;
}
}
private void getBasicData() {
try {
DataListBean pinpaiBean = new DataListBean(getString(R.string.basic_pinpai), "");
DataListBean modelBean = new DataListBean(getString(R.string.basic_model), "");
DataListBean osVersionBean = new DataListBean(getString(R.string.basic_osversion), "");
DataListBean gujianVersionBean = new DataListBean(getString(R.string
.basic_gujianversion), "");
DataListBean coreVersionBean = new DataListBean(getString(R.string.basic_coreversion)
, "");
DataListBean imeiBean = new DataListBean(getString(R.string.basic_imei), "");
DataListBean rootBean = new DataListBean(getString(R.string.basic_root), "");
String[] versions = GetEquipInfo.getVersion();
if (versions.length == 5) {
pinpaiBean.setVal(versions[4]);
modelBean.setVal(versions[2]);
osVersionBean.setVal(versions[1]);
gujianVersionBean.setVal(versions[3]);
coreVersionBean.setVal(versions[0]);
}
imeiBean.setVal(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId());
List<DataListBean> list = new ArrayList<>();
list.add(pinpaiBean);
list.add(modelBean);
list.add(osVersionBean);
list.add(gujianVersionBean);
list.add(coreVersionBean);
list.add(imeiBean);
list.add(rootBean);
mAdapter.setNewData(list);
checkRoot();
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void checkRoot() {
SettingUtils.isRootSystem2(new OnGetDataLinstener() {
@Override
public void onBack(Boolean isRoot) {
Message msg = new Message();
msg.what = 1;
msg.obj = isRoot;
mHandler.sendMessage(msg);
}
});
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Boolean isRoot = (Boolean) msg.obj;
int index = getBean(getString(R.string.basic_root), mAdapter.getData());
if (index > -1) {
DataListBean bean = mAdapter.getItem(index);
if (isRoot) {
bean.setVal(getString(R.string.basic_root_yes));
} else {
bean.setVal(getString(R.string.basic_root_no));
}
mAdapter.setData(index, bean);
}
}
}
};
private void getCpuData() {
try {
DataListBean cpuTypeBean = new DataListBean(getString(R.string.cpu_type), "");
DataListBean cpuYingJianBean = new DataListBean(getString(R.string.cpu_yingjian), "");
DataListBean cpuNumBean = new DataListBean(getString(R.string.cpu_num), "");
DataListBean cpuMaxZhuPinBean = new DataListBean(getString(R.string
.cpu_max_cpuzhupin), "");
DataListBean cpuMinZhuPinBean = new DataListBean(getString(R.string
.cpu_min_cpuzhupin), "");
DataListBean cpuYunSuanBean = new DataListBean(getString(R.string.cpu_yunsuan), "");
DataListBean cpuZhiLingJiBean = new DataListBean(getString(R.string.cpu_zhilingji), "");
String[] cpuinfo = CPUUtils.getCpuInfo();
if (cpuinfo.length == 4) {
cpuTypeBean.setVal(cpuinfo[0]);
cpuYingJianBean.setVal(cpuinfo[3]);
cpuYunSuanBean.setVal(cpuinfo[1]);
cpuZhiLingJiBean.setVal(cpuinfo[2]);
}
cpuNumBean.setVal(Integer.toString(CPUUtils.getNumCores()) + "核");
int maxCpuFreq = PublicMethod.stringConvertInt(CPUUtils.getMaxCpuFreq(), 1);
maxCpuFreq = maxCpuFreq / 1000;
cpuMaxZhuPinBean.setVal(Integer.toString(maxCpuFreq) + "Mhz");
int minCpuFreq = PublicMethod.stringConvertInt(CPUUtils.getMinCpuFreq(), 1);
minCpuFreq = minCpuFreq / 1000;
cpuMinZhuPinBean.setVal(Integer.toString(minCpuFreq) + "Mhz");
List<DataListBean> list = new ArrayList<>();
list.add(cpuTypeBean);
list.add(cpuYingJianBean);
list.add(cpuNumBean);
list.add(cpuMaxZhuPinBean);
list.add(cpuMinZhuPinBean);
list.add(cpuYunSuanBean);
list.add(cpuZhiLingJiBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getStorageData() {
try {
DataListBean storageRamBean = new DataListBean(getString(R.string.storage_ram), "");
DataListBean storageRomBean = new DataListBean(getString(R.string.storage_rom), "");
DataListBean storageSDBean = new DataListBean(getString(R.string.storage_sd), "");
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
long totalMemory = PublicMethod.stringConvertLong(SDUtils.getTotalRAMMemory(), 1);
storageRamBean.setVal("(" + PublicMethod.formatSize(mi.availMem) +
"/" + PublicMethod.formatSize(totalMemory * 1024) + ")");
long[] rom = SDUtils.getRomMemroy();
if (rom.length == 2) {
storageRomBean.setVal("(" + PublicMethod.formatSize((Long) rom[1]) + ")/("
+ PublicMethod.formatSize((Long) rom[0]) + ")");
}
long[] sd = SDUtils.getSDCardMemory();
if (PublicMethod.judageSDIsExist()) {
storageSDBean.setVal("(" + PublicMethod.formatSize((Long) sd[1])
+ ")/(" + PublicMethod.formatSize((Long) sd[0]) + ")");
} else {
storageSDBean.setVal("SD卡不存在");
}
List<DataListBean> list = new ArrayList<>();
list.add(storageRamBean);
list.add(storageRomBean);
list.add(storageSDBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getGpuData() {
try {
DataListBean gpuXianKaBean = new DataListBean(getString(R.string.gpu_xianka),
mRanderer);
DataListBean gpuGongYingShangBean = new DataListBean(getString(R.string
.gpu_gongyingshang), mGongYingshang);
DataListBean gpuFenBianLvBean = new DataListBean(getString(R.string.gpu_fenbianlv), "");
DataListBean gpuScreenXiangSuMiDuBean = new DataListBean(getString(R.string
.gpu_screenxiangsumidu), "");
DataListBean gpuVersionBean = new DataListBean(getString(R.string.gpu_version),
mGPUVersion);
DataListBean gpuPinLuBean = new DataListBean(getString(R.string.gpu_pinlu), "");
DataListBean gpuCaiZhiBean = new DataListBean(getString(R.string.gpu_caizhi), "");
DataListBean gpuChuMoBean = new DataListBean(getString(R.string.gpu_chumo), "");
String[] screen = GetEquipInfo.getDisplayMetrics(this);
if (screen.length == 4) {
gpuFenBianLvBean.setVal(screen[0] + "*" + screen[1]);
gpuScreenXiangSuMiDuBean.setVal(screen[3] + "dpi");
}
gpuXianKaBean.setVal("");
gpuChuMoBean.setVal(GetEquipInfo.isSupportMultiTouch(this) ? getString(R.string
.chuanganqi_zhichi) : getString(R.string.chuanganqi_not_zhichi));
List<DataListBean> list = new ArrayList<>();
list.add(gpuXianKaBean);
list.add(gpuGongYingShangBean);
list.add(gpuFenBianLvBean);
list.add(gpuScreenXiangSuMiDuBean);
list.add(gpuVersionBean);
list.add(gpuPinLuBean);
list.add(gpuCaiZhiBean);
list.add(gpuChuMoBean);
mAdapter.setNewData(list);
mGlSurfaceView = new GLSurfaceView(this);
mGlSurfaceView.setRenderer(mGlRenderer);
llRoot.addView(mGlSurfaceView);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private String mRanderer, mGPUVersion, mGongYingshang;
private GLSurfaceView mGlSurfaceView;
private GLSurfaceView.Renderer mGlRenderer = new GLSurfaceView.Renderer() {
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
mRanderer = gl.glGetString(GL10.GL_RENDERER);
mGPUVersion = gl.glGetString(GL10.GL_VERSION);
mGongYingshang = gl.glGetString(GL10.GL_VENDOR);
ULog.e("gpu=" + mRanderer + "," + mGPUVersion + "," + mGongYingshang);
runOnUiThread(new Runnable() {
@Override
public void run() {
int indexGpuXianKa = getBean(getString(R.string.gpu_xianka), mAdapter.getData
());
if (indexGpuXianKa > -1) {
DataListBean gpuXianKa = mAdapter.getItem(indexGpuXianKa);
gpuXianKa.setVal(mRanderer);
mAdapter.setData(indexGpuXianKa, gpuXianKa);
}
int indexGpuVersion = getBean(getString(R.string.gpu_version), mAdapter
.getData());
if (indexGpuVersion > -1) {
DataListBean gpuVersion = mAdapter.getItem(indexGpuVersion);
gpuVersion.setVal(mGPUVersion);
mAdapter.setData(indexGpuVersion, gpuVersion);
}
int indexGpuGongYingShang = getBean(getString(R.string.gpu_gongyingshang),
mAdapter.getData());
if (indexGpuGongYingShang > -1) {
DataListBean gpuGongYingShang = mAdapter.getItem(indexGpuGongYingShang);
gpuGongYingShang.setVal(mGongYingshang);
mAdapter.setData(indexGpuGongYingShang, gpuGongYingShang);
}
llRoot.removeView(mGlSurfaceView);
}
});
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
@Override
public void onDrawFrame(GL10 gl) {
}
};
private void getBatteryData() {
try {
DataListBean batterNumBean = new DataListBean(getString(R.string.battery_num), "");
DataListBean batterDianLiangBean = new DataListBean(getString(R.string
.battery_dianliang), "");
DataListBean batterWenDuBean = new DataListBean(getString(R.string.battery_wendu), "");
DataListBean batterTypeBean = new DataListBean(getString(R.string.battery_type), "");
DataListBean batterStateBean = new DataListBean(getString(R.string.battery_state), "");
DataListBean batterTimeBean = new DataListBean(getString(R.string.battery_time), "");
batterNumBean.setVal(Double.toString(GetEquipInfo.getBatteryCapacity(this)) + "mAh");
List<DataListBean> list = new ArrayList<>();
list.add(batterNumBean);
list.add(batterDianLiangBean);
list.add(batterWenDuBean);
list.add(batterTypeBean);
list.add(batterStateBean);
list.add(batterTimeBean);
mAdapter.setNewData(list);
batteryReceiver = new BatteryReceiver();
IntentFilter batteryFilter = new IntentFilter();
batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
this.registerReceiver(batteryReceiver, batteryFilter);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
/*通过监听获取电池信息*/
private BatteryReceiver batteryReceiver;
class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
/* 电池状态
BatteryManager.BATTERY_STATUS_CHARGING:充电状态。
BatteryManager.BATTERY_STATUS_DISCHARGING:放电状态。
BatteryManager.BATTERY_STATUS_NOT_CHARGING:未充满。
BatteryManager.BATTERY_STATUS_FULL:充满电。
BatteryManager.BATTERY_STATUS_UNKNOWN:未知状态。*/
//ULog.e("status-"+arg1.getIntExtra("status",0));
int health = arg1.getIntExtra("health", 0);
int level = arg1.getIntExtra("level", 0);
int temperature = arg1.getIntExtra("temperature", 0);
String tech = arg1.getStringExtra("technology");
float fl = ((float) temperature) / 10;
int indexDianLiang = getBean(getString(R.string.battery_dianliang), mAdapter.getData());
if (indexDianLiang > -1) {
DataListBean dianliang = mAdapter.getItem(indexDianLiang);
dianliang.setVal(level + "%");
mAdapter.setData(indexDianLiang, dianliang);
}
String state;
if (level == BatteryManager.BATTERY_HEALTH_DEAD)
state = getString(R.string.battery_state_dead);
else if (level == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE)
state = getString(R.string.battery_state_over_voltage);
else if (level == BatteryManager.BATTERY_HEALTH_OVERHEAT)
state = getString(R.string.battery_state_overheat);
else if (level == BatteryManager.BATTERY_HEALTH_UNKNOWN)
state = getString(R.string.battery_state_unknown);
else
state = getString(R.string.battery_state_good);
int indexState = getBean(getString(R.string.battery_state), mAdapter.getData());
if (indexState > -1) {
DataListBean stateBean = mAdapter.getItem(indexState);
stateBean.setVal(state);
mAdapter.setData(indexState, stateBean);
}
int indexWenDu = getBean(getString(R.string.battery_wendu), mAdapter.getData());
if (indexWenDu > -1) {
DataListBean wendu = mAdapter.getItem(indexWenDu);
wendu.setVal(String.valueOf(fl) + " C");
mAdapter.setData(indexWenDu, wendu);
}
int indexType = getBean(getString(R.string.battery_type), mAdapter.getData());
if (indexType > -1) {
DataListBean typeBean = mAdapter.getItem(indexType);
typeBean.setVal(String.valueOf(fl) + " C");
mAdapter.setData(indexType, typeBean);
}
}
}
private void getNetData() {
try {
DataListBean netWifiBean = new DataListBean(getString(R.string.net_wifi), "");
DataListBean netIPBean = new DataListBean(getString(R.string.net_ip), "");
DataListBean netMacBean = new DataListBean(getString(R.string.net_mac), "");
DataListBean netBlueTeetchBean = new DataListBean(getString(R.string.net_blueteetch),
"");
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
if (!wifiManager.isWifiEnabled()) {
netWifiBean.setVal(getString(R.string.net_wifi_not_open));
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (info.getMacAddress() != null)
netMacBean.setVal(info.getMacAddress());
if (bluetoothAdapter == null) {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_not_use));
}
// 若蓝牙没打开
if (bluetoothAdapter.isEnabled()) {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_open) + " " +
bluetoothAdapter.getName());
} else {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_not_open));
}
List<DataListBean> list = new ArrayList<>();
list.add(netWifiBean);
list.add(netIPBean);
list.add(netMacBean);
list.add(netBlueTeetchBean);
mAdapter.setNewData(list);
wifiConnectReceiver = new WifiConnectReceiver();
IntentFilter wififilter = new IntentFilter();
wififilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(wifiConnectReceiver, wififilter);
blutteetchReceiver = new BlutteetchReceiver();
IntentFilter bluefilter = new IntentFilter();
bluefilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(blutteetchReceiver, bluefilter);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private BroadcastReceiver wifiConnectReceiver;
private WifiManager wifiManager;
private BroadcastReceiver blutteetchReceiver;
private BluetoothAdapter bluetoothAdapter; //本地蓝牙适配器
class WifiConnectReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager manager = (ConnectivityManager) getSystemService
(CONNECTIVITY_SERVICE);
NetworkInfo notewokInfo = manager.getActiveNetworkInfo();
String netWifi = getString(R.string.net_wifi_not_open);
//tvNetIp.setText("");
if (notewokInfo != null) {
String tempSSID = wifiManager.getConnectionInfo().getSSID().replace("\"", "");
if (tempSSID.trim().length() > 0 && !tempSSID.equals("<unknown ssid>")) {
netWifi = getString(R.string.net_wifi_connect) + " " + tempSSID;
int indexNetWifi = getBean(getString(R.string.net_wifi), mAdapter.getData
());
if (indexNetWifi > -1) {
DataListBean netWifiBean = mAdapter.getItem(indexNetWifi);
netWifiBean.setVal(netWifi);
mAdapter.setData(indexNetWifi, netWifiBean);
}
int indexNetIP = getBean(getString(R.string.net_ip), mAdapter.getData());
if (indexNetIP > -1) {
DataListBean netIPBean = mAdapter.getItem(indexNetIP);
netIPBean.setVal(MyApplication.getHostIP());
mAdapter.setData(indexNetIP, netIPBean);
}
}
}
}
}
}
class BlutteetchReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
switch (blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
break;
case BluetoothAdapter.STATE_ON:
updateBlueTeetchState();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
break;
case BluetoothAdapter.STATE_OFF:
updateBlueTeetchState();
break;
}
break;
}
}
}
private void updateBlueTeetchState() {
int indexBlueTeetch = getBean(getString(R.string.net_blueteetch), mAdapter.getData());
if (indexBlueTeetch > -1) {
DataListBean blueTeetchBean = mAdapter.getItem(indexBlueTeetch);
// 若蓝牙没打开
if (bluetoothAdapter.isEnabled()) {
blueTeetchBean.setVal(getString(R.string.net_blueteetch_open) + " " +
bluetoothAdapter.getName());
} else {
blueTeetchBean.setVal(getString(R.string.net_blueteetch_not_open));
}
mAdapter.setData(indexBlueTeetch, blueTeetchBean);
}
}
private void getCarmeraData() {
try {
DataListBean carmeraHeadBean = new DataListBean(getString(R.string
.carmera_showcamerahead), "");
DataListBean carmeraBackBean = new DataListBean(getString(R.string
.carmera_showcameraback), "");
DataListBean videoBean = new DataListBean(getString(R.string.carmera_video), "");
carmeraHeadBean.setVal(CameraUtil.getCameraPixels(CameraUtil.HasFrontCamera()));
carmeraBackBean.setVal(CameraUtil.getCameraPixels(CameraUtil.HasBackCamera()));
Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
// samsung 最大值为第一个
if (supportedPreviewSizes.size() > 1) {
int one = supportedPreviewSizes.get(0).height;
int two = supportedPreviewSizes.get(1).height;
if (one < two) {
videoBean.setVal(supportedPreviewSizes.get(supportedPreviewSizes.size() - 1)
.height + "p");
} else {
videoBean.setVal(one + "p");
}
}
List<DataListBean> list = new ArrayList<>();
list.add(carmeraHeadBean);
list.add(carmeraBackBean);
list.add(videoBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getChuanGanQiData() {
try {
DataListBean cgqTuoLuoYiBean = new DataListBean(getString(R.string
.chuanganqi_tuoluoyi), getString(R.string.chuanganqi_zhichi));
DataListBean cgqGuanXianBean = new DataListBean(getString(R.string
.chuanganqi_guangxian), getString(R.string.chuanganqi_zhichi));
DataListBean cgqJiaSuBean = new DataListBean(getString(R.string.chuanganqi_jiasu),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqCiChangBean = new DataListBean(getString(R.string.chuanganqi_cichang)
, getString(R.string.chuanganqi_zhichi));
DataListBean cgqYaLiBean = new DataListBean(getString(R.string.chuanganqi_yali),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqJuLiBean = new DataListBean(getString(R.string.chuanganqi_juli),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqWenDuBean = new DataListBean(getString(R.string.chuanganqi_wendu),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqXianXingBean = new DataListBean(getString(R.string
.chuanganqi_xianxing), getString(R.string.chuanganqi_zhichi));
DataListBean cgqXuanZhuanBean = new DataListBean(getString(R.string
.chuanganqi_xuanzhuan), getString(R.string.chuanganqi_zhichi));
DataListBean cgqZhongLiBean = new DataListBean(getString(R.string.chuanganqi_zhongli)
, getString(R.string.chuanganqi_zhichi));
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor tuoluoyi = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (tuoluoyi == null)
cgqTuoLuoYiBean.setVal("不支持");
Sensor guangxian = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (guangxian == null)
cgqGuanXianBean.setVal("不支持");
Sensor jiasu = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (jiasu == null)
cgqJiaSuBean.setVal("不支持");
Sensor cichang = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (cichang == null)
cgqCiChangBean.setVal("不支持");
Sensor yali = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (yali == null)
cgqYaLiBean.setVal("不支持");
Sensor juli = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (juli == null)
cgqJuLiBean.setVal("不支持");
Sensor wendu = sensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
if (wendu == null)
cgqWenDuBean.setVal("不支持");
Sensor xianxing = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
if (xianxing == null)
cgqXianXingBean.setVal("不支持");
Sensor xuanzhuan = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (xuanzhuan == null)
cgqXuanZhuanBean.setVal("不支持");
Sensor zhongli = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
if (zhongli == null)
cgqZhongLiBean.setVal("不支持");
List<DataListBean> list = new ArrayList<>();
list.add(cgqTuoLuoYiBean);
list.add(cgqGuanXianBean);
list.add(cgqJiaSuBean);
list.add(cgqCiChangBean);
list.add(cgqYaLiBean);
list.add(cgqJuLiBean);
list.add(cgqWenDuBean);
list.add(cgqXianXingBean);
list.add(cgqXuanZhuanBean);
list.add(cgqZhongLiBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private SensorManager sensorManager;
public static int getBean(String title, List<DataListBean> list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getTitle().equals(title))
return i;
}
return -1;
}
private void initBannerAds() {
if (isForegroud()) {
//初始化横幅监听对象
IAwSclothListener iAwSclothListener = new IAwSclothListener() {
@Override
public void onSclothPreparedFailed(LayerErrorCode errorCode) {
//广告加载失败
ULog.e("AdBana " + "on banner prepared failed " + errorCode);
flAds.setVisibility(View.GONE);
}
@Override
public void onSclothPrepared() {
//广告预加载成功
ULog.e("AdBana " + "on banner prepared");
flAds.setVisibility(View.VISIBLE);
}
@Override
public void onSclothExposure() {
//广告展示成功回调
ULog.e("AdBana " + "on banner exposure");
}
@Override
public void onSclothClosed() {
//广告被用户关闭回调
ULog.e("AdBana " + "on banner close ");
flAds.setVisibility(View.GONE);
}
@Override
public void onSclothClicked() {
//广告被点击回调
ULog.e("AdBana " + "on banner clicked ");
}
};
scloth = new Scloth(this, DataConfig.AdBana_App_ID, DataConfig.AdBana_Banner_AdID);
//设置横幅容器并设置大小
scloth.setSclothContainer(flAds, ViewSize.SCLOTH_SIZE_728X90);
//给广告位设置监听
scloth.setSclothEventListener(iAwSclothListener);
//开始请求广告
scloth.requestAwScloth();
}
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onResume() {
if (scloth != null) {
//scloth.resumeScloth();
scloth.onResume();
}
super.onResume();
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onPause() {
if (scloth != null) {
//scloth.dismissScloth();
scloth.onPause();
}
super.onPause();
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onDestroy() {
if (scloth != null) {
scloth.onDestroy();
}
if (batteryReceiver != null)
unregisterReceiver(batteryReceiver);
if (wifiConnectReceiver != null)
unregisterReceiver(wifiConnectReceiver);
if (blutteetchReceiver != null)
unregisterReceiver(blutteetchReceiver);
super.onDestroy();
}
@BindView(R.id.fl_ads)
FrameLayout flAds;
@BindView(R.id.ll_root)
LinearLayout llRoot;
}
| UTF-8 | Java | 37,929 | java | DataActivity.java | Java | [
{
"context": "yzlibrary.utils.ULog;\n\n/**\n * 基础信息模块\n * Created by slantech on 2017/12/05 10:35\n */\n\npublic class DataActivit",
"end": 2481,
"score": 0.9984549880027771,
"start": 2473,
"tag": "USERNAME",
"value": "slantech"
}
] | null | [] | package net.kisslogo.holdyou.ui.activity.info;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.opengl.GLSurfaceView;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.awesome.android.sdk.publish.Scloth;
import com.awesome.android.sdk.publish.enumbean.LayerErrorCode;
import com.awesome.android.sdk.publish.enumbean.ViewSize;
import com.awesome.android.sdk.publish.listener.IAwSclothListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import net.kisslogo.holdyou.MyApplication;
import net.kisslogo.holdyou.R;
import net.kisslogo.holdyou.adapter.DataListAdapter;
import net.kisslogo.holdyou.bean.DataListBean;
import net.kisslogo.holdyou.bean.SysAppAds;
import net.kisslogo.holdyou.common.DataConfig;
import net.kisslogo.holdyou.common.KeyConfig;
import net.kisslogo.holdyou.common.UIHelper;
import net.kisslogo.holdyou.ui.activity.base.BaseActivity;
import net.kisslogo.holdyou.ui.view.TitleView;
import net.kisslogo.holdyou.utils.CPUUtils;
import net.kisslogo.holdyou.utils.CameraUtil;
import net.kisslogo.holdyou.utils.GetEquipInfo;
import net.kisslogo.holdyou.utils.HomeGridDataUtils;
import net.kisslogo.holdyou.utils.PublicMethod;
import net.kisslogo.holdyou.utils.SDUtils;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.slantech.yzlibrary.interfaces.OnGetDataLinstener;
import top.slantech.yzlibrary.utils.SettingUtils;
import top.slantech.yzlibrary.utils.ULog;
/**
* 基础信息模块
* Created by slantech on 2017/12/05 10:35
*/
public class DataActivity extends BaseActivity {
@BindView(R.id.title_view)
TitleView titleView;
@BindView(R.id.rv_list)
RecyclerView rvList;
@BindView(R.id.refreshLayout)
SmartRefreshLayout refreshLayout;
DataListAdapter mAdapter;
private int mTypes;
private String mTitles;
Scloth scloth;
public static void actionStart(Activity context, int types) {
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("types", types);
context.startActivity(intent);
context.
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.include_list);
ButterKnife.bind(this);
mTypes = getIntent().getIntExtra("types", HomeGridDataUtils.Home_Type_Basic);
switch (mTypes) {
case HomeGridDataUtils.Home_Type_Basic:
mTitles = getString(R.string.basic);
break;
case HomeGridDataUtils.Home_Type_Cpu:
mTitles = getString(R.string.cpu);
break;
case HomeGridDataUtils.Home_Type_Storage:
mTitles = getString(R.string.storage);
break;
case HomeGridDataUtils.Home_Type_Gpu:
mTitles = getString(R.string.gpu);
break;
case HomeGridDataUtils.Home_Type_Battery:
mTitles = getString(R.string.battery);
break;
case HomeGridDataUtils.Home_Type_Net:
mTitles = getString(R.string.net2);
break;
case HomeGridDataUtils.Home_Type_Carmera:
mTitles = getString(R.string.carmera);
break;
case HomeGridDataUtils.Home_Type_Chuanganqi:
mTitles = getString(R.string.chuanganqi);
break;
default:
mTitles = getString(R.string.basic);
break;
}
titleView.setTopTitle(mTitles);
initAdapter();
initSwipe();
SysAppAds sysAppAds = UIHelper.checkIsShowAds(this, KeyConfig.Ads_Is_Show_Server_Banner,
-1);
if (sysAppAds.getIsOpen() == 0 && UIHelper.checkIsShowBannerAds(this)) {
new Handler(new Handler.Callback() {
// 处理接收到消息的方法
@Override
public boolean handleMessage(Message msg) {
initBannerAds();
return false;
}
}).sendEmptyMessageDelayed(0, 2000);
//表示延时2秒执行任务
}
}
@OnClick({R.id.ll_iv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_iv_right:
if (mAdapter != null && mAdapter.getData() != null && mAdapter.getData()
.size() > 0) {
MyApplication.showSaveStr(this, mTitles, mAdapter);
}
break;
}
}
private void initAdapter() {
mAdapter = new DataListAdapter(R.layout.item_data);
rvList.setLayoutManager(new LinearLayoutManager(this));
rvList.setAdapter(mAdapter);
}
private void initSwipe() {
refreshLayout.autoRefresh();
refreshLayout.setEnableLoadmore(false);
refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
@Override
public void onRefresh(final com.scwang.smartrefresh.layout.api.RefreshLayout
refreshlayout) {
initData();
}
@Override
public void onLoadmore(final com.scwang.smartrefresh.layout.api.RefreshLayout
refreshlayout) {
}
});
}
private void initData() {
switch (mTypes) {
case HomeGridDataUtils.Home_Type_Basic:
getBasicData();
break;
case HomeGridDataUtils.Home_Type_Cpu:
getCpuData();
break;
case HomeGridDataUtils.Home_Type_Storage:
getStorageData();
break;
case HomeGridDataUtils.Home_Type_Gpu:
getGpuData();
break;
case HomeGridDataUtils.Home_Type_Battery:
getBatteryData();
break;
case HomeGridDataUtils.Home_Type_Net:
getNetData();
break;
case HomeGridDataUtils.Home_Type_Carmera:
getCarmeraData();
break;
case HomeGridDataUtils.Home_Type_Chuanganqi:
getChuanGanQiData();
break;
}
}
private void getBasicData() {
try {
DataListBean pinpaiBean = new DataListBean(getString(R.string.basic_pinpai), "");
DataListBean modelBean = new DataListBean(getString(R.string.basic_model), "");
DataListBean osVersionBean = new DataListBean(getString(R.string.basic_osversion), "");
DataListBean gujianVersionBean = new DataListBean(getString(R.string
.basic_gujianversion), "");
DataListBean coreVersionBean = new DataListBean(getString(R.string.basic_coreversion)
, "");
DataListBean imeiBean = new DataListBean(getString(R.string.basic_imei), "");
DataListBean rootBean = new DataListBean(getString(R.string.basic_root), "");
String[] versions = GetEquipInfo.getVersion();
if (versions.length == 5) {
pinpaiBean.setVal(versions[4]);
modelBean.setVal(versions[2]);
osVersionBean.setVal(versions[1]);
gujianVersionBean.setVal(versions[3]);
coreVersionBean.setVal(versions[0]);
}
imeiBean.setVal(((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId());
List<DataListBean> list = new ArrayList<>();
list.add(pinpaiBean);
list.add(modelBean);
list.add(osVersionBean);
list.add(gujianVersionBean);
list.add(coreVersionBean);
list.add(imeiBean);
list.add(rootBean);
mAdapter.setNewData(list);
checkRoot();
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void checkRoot() {
SettingUtils.isRootSystem2(new OnGetDataLinstener() {
@Override
public void onBack(Boolean isRoot) {
Message msg = new Message();
msg.what = 1;
msg.obj = isRoot;
mHandler.sendMessage(msg);
}
});
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Boolean isRoot = (Boolean) msg.obj;
int index = getBean(getString(R.string.basic_root), mAdapter.getData());
if (index > -1) {
DataListBean bean = mAdapter.getItem(index);
if (isRoot) {
bean.setVal(getString(R.string.basic_root_yes));
} else {
bean.setVal(getString(R.string.basic_root_no));
}
mAdapter.setData(index, bean);
}
}
}
};
private void getCpuData() {
try {
DataListBean cpuTypeBean = new DataListBean(getString(R.string.cpu_type), "");
DataListBean cpuYingJianBean = new DataListBean(getString(R.string.cpu_yingjian), "");
DataListBean cpuNumBean = new DataListBean(getString(R.string.cpu_num), "");
DataListBean cpuMaxZhuPinBean = new DataListBean(getString(R.string
.cpu_max_cpuzhupin), "");
DataListBean cpuMinZhuPinBean = new DataListBean(getString(R.string
.cpu_min_cpuzhupin), "");
DataListBean cpuYunSuanBean = new DataListBean(getString(R.string.cpu_yunsuan), "");
DataListBean cpuZhiLingJiBean = new DataListBean(getString(R.string.cpu_zhilingji), "");
String[] cpuinfo = CPUUtils.getCpuInfo();
if (cpuinfo.length == 4) {
cpuTypeBean.setVal(cpuinfo[0]);
cpuYingJianBean.setVal(cpuinfo[3]);
cpuYunSuanBean.setVal(cpuinfo[1]);
cpuZhiLingJiBean.setVal(cpuinfo[2]);
}
cpuNumBean.setVal(Integer.toString(CPUUtils.getNumCores()) + "核");
int maxCpuFreq = PublicMethod.stringConvertInt(CPUUtils.getMaxCpuFreq(), 1);
maxCpuFreq = maxCpuFreq / 1000;
cpuMaxZhuPinBean.setVal(Integer.toString(maxCpuFreq) + "Mhz");
int minCpuFreq = PublicMethod.stringConvertInt(CPUUtils.getMinCpuFreq(), 1);
minCpuFreq = minCpuFreq / 1000;
cpuMinZhuPinBean.setVal(Integer.toString(minCpuFreq) + "Mhz");
List<DataListBean> list = new ArrayList<>();
list.add(cpuTypeBean);
list.add(cpuYingJianBean);
list.add(cpuNumBean);
list.add(cpuMaxZhuPinBean);
list.add(cpuMinZhuPinBean);
list.add(cpuYunSuanBean);
list.add(cpuZhiLingJiBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getStorageData() {
try {
DataListBean storageRamBean = new DataListBean(getString(R.string.storage_ram), "");
DataListBean storageRomBean = new DataListBean(getString(R.string.storage_rom), "");
DataListBean storageSDBean = new DataListBean(getString(R.string.storage_sd), "");
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
long totalMemory = PublicMethod.stringConvertLong(SDUtils.getTotalRAMMemory(), 1);
storageRamBean.setVal("(" + PublicMethod.formatSize(mi.availMem) +
"/" + PublicMethod.formatSize(totalMemory * 1024) + ")");
long[] rom = SDUtils.getRomMemroy();
if (rom.length == 2) {
storageRomBean.setVal("(" + PublicMethod.formatSize((Long) rom[1]) + ")/("
+ PublicMethod.formatSize((Long) rom[0]) + ")");
}
long[] sd = SDUtils.getSDCardMemory();
if (PublicMethod.judageSDIsExist()) {
storageSDBean.setVal("(" + PublicMethod.formatSize((Long) sd[1])
+ ")/(" + PublicMethod.formatSize((Long) sd[0]) + ")");
} else {
storageSDBean.setVal("SD卡不存在");
}
List<DataListBean> list = new ArrayList<>();
list.add(storageRamBean);
list.add(storageRomBean);
list.add(storageSDBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getGpuData() {
try {
DataListBean gpuXianKaBean = new DataListBean(getString(R.string.gpu_xianka),
mRanderer);
DataListBean gpuGongYingShangBean = new DataListBean(getString(R.string
.gpu_gongyingshang), mGongYingshang);
DataListBean gpuFenBianLvBean = new DataListBean(getString(R.string.gpu_fenbianlv), "");
DataListBean gpuScreenXiangSuMiDuBean = new DataListBean(getString(R.string
.gpu_screenxiangsumidu), "");
DataListBean gpuVersionBean = new DataListBean(getString(R.string.gpu_version),
mGPUVersion);
DataListBean gpuPinLuBean = new DataListBean(getString(R.string.gpu_pinlu), "");
DataListBean gpuCaiZhiBean = new DataListBean(getString(R.string.gpu_caizhi), "");
DataListBean gpuChuMoBean = new DataListBean(getString(R.string.gpu_chumo), "");
String[] screen = GetEquipInfo.getDisplayMetrics(this);
if (screen.length == 4) {
gpuFenBianLvBean.setVal(screen[0] + "*" + screen[1]);
gpuScreenXiangSuMiDuBean.setVal(screen[3] + "dpi");
}
gpuXianKaBean.setVal("");
gpuChuMoBean.setVal(GetEquipInfo.isSupportMultiTouch(this) ? getString(R.string
.chuanganqi_zhichi) : getString(R.string.chuanganqi_not_zhichi));
List<DataListBean> list = new ArrayList<>();
list.add(gpuXianKaBean);
list.add(gpuGongYingShangBean);
list.add(gpuFenBianLvBean);
list.add(gpuScreenXiangSuMiDuBean);
list.add(gpuVersionBean);
list.add(gpuPinLuBean);
list.add(gpuCaiZhiBean);
list.add(gpuChuMoBean);
mAdapter.setNewData(list);
mGlSurfaceView = new GLSurfaceView(this);
mGlSurfaceView.setRenderer(mGlRenderer);
llRoot.addView(mGlSurfaceView);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private String mRanderer, mGPUVersion, mGongYingshang;
private GLSurfaceView mGlSurfaceView;
private GLSurfaceView.Renderer mGlRenderer = new GLSurfaceView.Renderer() {
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
mRanderer = gl.glGetString(GL10.GL_RENDERER);
mGPUVersion = gl.glGetString(GL10.GL_VERSION);
mGongYingshang = gl.glGetString(GL10.GL_VENDOR);
ULog.e("gpu=" + mRanderer + "," + mGPUVersion + "," + mGongYingshang);
runOnUiThread(new Runnable() {
@Override
public void run() {
int indexGpuXianKa = getBean(getString(R.string.gpu_xianka), mAdapter.getData
());
if (indexGpuXianKa > -1) {
DataListBean gpuXianKa = mAdapter.getItem(indexGpuXianKa);
gpuXianKa.setVal(mRanderer);
mAdapter.setData(indexGpuXianKa, gpuXianKa);
}
int indexGpuVersion = getBean(getString(R.string.gpu_version), mAdapter
.getData());
if (indexGpuVersion > -1) {
DataListBean gpuVersion = mAdapter.getItem(indexGpuVersion);
gpuVersion.setVal(mGPUVersion);
mAdapter.setData(indexGpuVersion, gpuVersion);
}
int indexGpuGongYingShang = getBean(getString(R.string.gpu_gongyingshang),
mAdapter.getData());
if (indexGpuGongYingShang > -1) {
DataListBean gpuGongYingShang = mAdapter.getItem(indexGpuGongYingShang);
gpuGongYingShang.setVal(mGongYingshang);
mAdapter.setData(indexGpuGongYingShang, gpuGongYingShang);
}
llRoot.removeView(mGlSurfaceView);
}
});
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
@Override
public void onDrawFrame(GL10 gl) {
}
};
private void getBatteryData() {
try {
DataListBean batterNumBean = new DataListBean(getString(R.string.battery_num), "");
DataListBean batterDianLiangBean = new DataListBean(getString(R.string
.battery_dianliang), "");
DataListBean batterWenDuBean = new DataListBean(getString(R.string.battery_wendu), "");
DataListBean batterTypeBean = new DataListBean(getString(R.string.battery_type), "");
DataListBean batterStateBean = new DataListBean(getString(R.string.battery_state), "");
DataListBean batterTimeBean = new DataListBean(getString(R.string.battery_time), "");
batterNumBean.setVal(Double.toString(GetEquipInfo.getBatteryCapacity(this)) + "mAh");
List<DataListBean> list = new ArrayList<>();
list.add(batterNumBean);
list.add(batterDianLiangBean);
list.add(batterWenDuBean);
list.add(batterTypeBean);
list.add(batterStateBean);
list.add(batterTimeBean);
mAdapter.setNewData(list);
batteryReceiver = new BatteryReceiver();
IntentFilter batteryFilter = new IntentFilter();
batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
this.registerReceiver(batteryReceiver, batteryFilter);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
/*通过监听获取电池信息*/
private BatteryReceiver batteryReceiver;
class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
/* 电池状态
BatteryManager.BATTERY_STATUS_CHARGING:充电状态。
BatteryManager.BATTERY_STATUS_DISCHARGING:放电状态。
BatteryManager.BATTERY_STATUS_NOT_CHARGING:未充满。
BatteryManager.BATTERY_STATUS_FULL:充满电。
BatteryManager.BATTERY_STATUS_UNKNOWN:未知状态。*/
//ULog.e("status-"+arg1.getIntExtra("status",0));
int health = arg1.getIntExtra("health", 0);
int level = arg1.getIntExtra("level", 0);
int temperature = arg1.getIntExtra("temperature", 0);
String tech = arg1.getStringExtra("technology");
float fl = ((float) temperature) / 10;
int indexDianLiang = getBean(getString(R.string.battery_dianliang), mAdapter.getData());
if (indexDianLiang > -1) {
DataListBean dianliang = mAdapter.getItem(indexDianLiang);
dianliang.setVal(level + "%");
mAdapter.setData(indexDianLiang, dianliang);
}
String state;
if (level == BatteryManager.BATTERY_HEALTH_DEAD)
state = getString(R.string.battery_state_dead);
else if (level == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE)
state = getString(R.string.battery_state_over_voltage);
else if (level == BatteryManager.BATTERY_HEALTH_OVERHEAT)
state = getString(R.string.battery_state_overheat);
else if (level == BatteryManager.BATTERY_HEALTH_UNKNOWN)
state = getString(R.string.battery_state_unknown);
else
state = getString(R.string.battery_state_good);
int indexState = getBean(getString(R.string.battery_state), mAdapter.getData());
if (indexState > -1) {
DataListBean stateBean = mAdapter.getItem(indexState);
stateBean.setVal(state);
mAdapter.setData(indexState, stateBean);
}
int indexWenDu = getBean(getString(R.string.battery_wendu), mAdapter.getData());
if (indexWenDu > -1) {
DataListBean wendu = mAdapter.getItem(indexWenDu);
wendu.setVal(String.valueOf(fl) + " C");
mAdapter.setData(indexWenDu, wendu);
}
int indexType = getBean(getString(R.string.battery_type), mAdapter.getData());
if (indexType > -1) {
DataListBean typeBean = mAdapter.getItem(indexType);
typeBean.setVal(String.valueOf(fl) + " C");
mAdapter.setData(indexType, typeBean);
}
}
}
private void getNetData() {
try {
DataListBean netWifiBean = new DataListBean(getString(R.string.net_wifi), "");
DataListBean netIPBean = new DataListBean(getString(R.string.net_ip), "");
DataListBean netMacBean = new DataListBean(getString(R.string.net_mac), "");
DataListBean netBlueTeetchBean = new DataListBean(getString(R.string.net_blueteetch),
"");
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
if (!wifiManager.isWifiEnabled()) {
netWifiBean.setVal(getString(R.string.net_wifi_not_open));
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (info.getMacAddress() != null)
netMacBean.setVal(info.getMacAddress());
if (bluetoothAdapter == null) {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_not_use));
}
// 若蓝牙没打开
if (bluetoothAdapter.isEnabled()) {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_open) + " " +
bluetoothAdapter.getName());
} else {
netBlueTeetchBean.setVal(getString(R.string.net_blueteetch_not_open));
}
List<DataListBean> list = new ArrayList<>();
list.add(netWifiBean);
list.add(netIPBean);
list.add(netMacBean);
list.add(netBlueTeetchBean);
mAdapter.setNewData(list);
wifiConnectReceiver = new WifiConnectReceiver();
IntentFilter wififilter = new IntentFilter();
wififilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(wifiConnectReceiver, wififilter);
blutteetchReceiver = new BlutteetchReceiver();
IntentFilter bluefilter = new IntentFilter();
bluefilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(blutteetchReceiver, bluefilter);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private BroadcastReceiver wifiConnectReceiver;
private WifiManager wifiManager;
private BroadcastReceiver blutteetchReceiver;
private BluetoothAdapter bluetoothAdapter; //本地蓝牙适配器
class WifiConnectReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager manager = (ConnectivityManager) getSystemService
(CONNECTIVITY_SERVICE);
NetworkInfo notewokInfo = manager.getActiveNetworkInfo();
String netWifi = getString(R.string.net_wifi_not_open);
//tvNetIp.setText("");
if (notewokInfo != null) {
String tempSSID = wifiManager.getConnectionInfo().getSSID().replace("\"", "");
if (tempSSID.trim().length() > 0 && !tempSSID.equals("<unknown ssid>")) {
netWifi = getString(R.string.net_wifi_connect) + " " + tempSSID;
int indexNetWifi = getBean(getString(R.string.net_wifi), mAdapter.getData
());
if (indexNetWifi > -1) {
DataListBean netWifiBean = mAdapter.getItem(indexNetWifi);
netWifiBean.setVal(netWifi);
mAdapter.setData(indexNetWifi, netWifiBean);
}
int indexNetIP = getBean(getString(R.string.net_ip), mAdapter.getData());
if (indexNetIP > -1) {
DataListBean netIPBean = mAdapter.getItem(indexNetIP);
netIPBean.setVal(MyApplication.getHostIP());
mAdapter.setData(indexNetIP, netIPBean);
}
}
}
}
}
}
class BlutteetchReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
switch (blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
break;
case BluetoothAdapter.STATE_ON:
updateBlueTeetchState();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
break;
case BluetoothAdapter.STATE_OFF:
updateBlueTeetchState();
break;
}
break;
}
}
}
private void updateBlueTeetchState() {
int indexBlueTeetch = getBean(getString(R.string.net_blueteetch), mAdapter.getData());
if (indexBlueTeetch > -1) {
DataListBean blueTeetchBean = mAdapter.getItem(indexBlueTeetch);
// 若蓝牙没打开
if (bluetoothAdapter.isEnabled()) {
blueTeetchBean.setVal(getString(R.string.net_blueteetch_open) + " " +
bluetoothAdapter.getName());
} else {
blueTeetchBean.setVal(getString(R.string.net_blueteetch_not_open));
}
mAdapter.setData(indexBlueTeetch, blueTeetchBean);
}
}
private void getCarmeraData() {
try {
DataListBean carmeraHeadBean = new DataListBean(getString(R.string
.carmera_showcamerahead), "");
DataListBean carmeraBackBean = new DataListBean(getString(R.string
.carmera_showcameraback), "");
DataListBean videoBean = new DataListBean(getString(R.string.carmera_video), "");
carmeraHeadBean.setVal(CameraUtil.getCameraPixels(CameraUtil.HasFrontCamera()));
carmeraBackBean.setVal(CameraUtil.getCameraPixels(CameraUtil.HasBackCamera()));
Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
// samsung 最大值为第一个
if (supportedPreviewSizes.size() > 1) {
int one = supportedPreviewSizes.get(0).height;
int two = supportedPreviewSizes.get(1).height;
if (one < two) {
videoBean.setVal(supportedPreviewSizes.get(supportedPreviewSizes.size() - 1)
.height + "p");
} else {
videoBean.setVal(one + "p");
}
}
List<DataListBean> list = new ArrayList<>();
list.add(carmeraHeadBean);
list.add(carmeraBackBean);
list.add(videoBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private void getChuanGanQiData() {
try {
DataListBean cgqTuoLuoYiBean = new DataListBean(getString(R.string
.chuanganqi_tuoluoyi), getString(R.string.chuanganqi_zhichi));
DataListBean cgqGuanXianBean = new DataListBean(getString(R.string
.chuanganqi_guangxian), getString(R.string.chuanganqi_zhichi));
DataListBean cgqJiaSuBean = new DataListBean(getString(R.string.chuanganqi_jiasu),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqCiChangBean = new DataListBean(getString(R.string.chuanganqi_cichang)
, getString(R.string.chuanganqi_zhichi));
DataListBean cgqYaLiBean = new DataListBean(getString(R.string.chuanganqi_yali),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqJuLiBean = new DataListBean(getString(R.string.chuanganqi_juli),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqWenDuBean = new DataListBean(getString(R.string.chuanganqi_wendu),
getString(R.string.chuanganqi_zhichi));
DataListBean cgqXianXingBean = new DataListBean(getString(R.string
.chuanganqi_xianxing), getString(R.string.chuanganqi_zhichi));
DataListBean cgqXuanZhuanBean = new DataListBean(getString(R.string
.chuanganqi_xuanzhuan), getString(R.string.chuanganqi_zhichi));
DataListBean cgqZhongLiBean = new DataListBean(getString(R.string.chuanganqi_zhongli)
, getString(R.string.chuanganqi_zhichi));
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor tuoluoyi = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (tuoluoyi == null)
cgqTuoLuoYiBean.setVal("不支持");
Sensor guangxian = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (guangxian == null)
cgqGuanXianBean.setVal("不支持");
Sensor jiasu = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (jiasu == null)
cgqJiaSuBean.setVal("不支持");
Sensor cichang = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (cichang == null)
cgqCiChangBean.setVal("不支持");
Sensor yali = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (yali == null)
cgqYaLiBean.setVal("不支持");
Sensor juli = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (juli == null)
cgqJuLiBean.setVal("不支持");
Sensor wendu = sensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
if (wendu == null)
cgqWenDuBean.setVal("不支持");
Sensor xianxing = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
if (xianxing == null)
cgqXianXingBean.setVal("不支持");
Sensor xuanzhuan = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (xuanzhuan == null)
cgqXuanZhuanBean.setVal("不支持");
Sensor zhongli = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
if (zhongli == null)
cgqZhongLiBean.setVal("不支持");
List<DataListBean> list = new ArrayList<>();
list.add(cgqTuoLuoYiBean);
list.add(cgqGuanXianBean);
list.add(cgqJiaSuBean);
list.add(cgqCiChangBean);
list.add(cgqYaLiBean);
list.add(cgqJuLiBean);
list.add(cgqWenDuBean);
list.add(cgqXianXingBean);
list.add(cgqXuanZhuanBean);
list.add(cgqZhongLiBean);
mAdapter.setNewData(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
refreshLayout.finishRefresh(500);
}
}
private SensorManager sensorManager;
public static int getBean(String title, List<DataListBean> list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getTitle().equals(title))
return i;
}
return -1;
}
private void initBannerAds() {
if (isForegroud()) {
//初始化横幅监听对象
IAwSclothListener iAwSclothListener = new IAwSclothListener() {
@Override
public void onSclothPreparedFailed(LayerErrorCode errorCode) {
//广告加载失败
ULog.e("AdBana " + "on banner prepared failed " + errorCode);
flAds.setVisibility(View.GONE);
}
@Override
public void onSclothPrepared() {
//广告预加载成功
ULog.e("AdBana " + "on banner prepared");
flAds.setVisibility(View.VISIBLE);
}
@Override
public void onSclothExposure() {
//广告展示成功回调
ULog.e("AdBana " + "on banner exposure");
}
@Override
public void onSclothClosed() {
//广告被用户关闭回调
ULog.e("AdBana " + "on banner close ");
flAds.setVisibility(View.GONE);
}
@Override
public void onSclothClicked() {
//广告被点击回调
ULog.e("AdBana " + "on banner clicked ");
}
};
scloth = new Scloth(this, DataConfig.AdBana_App_ID, DataConfig.AdBana_Banner_AdID);
//设置横幅容器并设置大小
scloth.setSclothContainer(flAds, ViewSize.SCLOTH_SIZE_728X90);
//给广告位设置监听
scloth.setSclothEventListener(iAwSclothListener);
//开始请求广告
scloth.requestAwScloth();
}
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onResume() {
if (scloth != null) {
//scloth.resumeScloth();
scloth.onResume();
}
super.onResume();
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onPause() {
if (scloth != null) {
//scloth.dismissScloth();
scloth.onPause();
}
super.onPause();
}
/**
* 为sdk添加生命周期(必须添加加 不添加会影响展示)(non-Javadoc)
*/
@Override
protected void onDestroy() {
if (scloth != null) {
scloth.onDestroy();
}
if (batteryReceiver != null)
unregisterReceiver(batteryReceiver);
if (wifiConnectReceiver != null)
unregisterReceiver(wifiConnectReceiver);
if (blutteetchReceiver != null)
unregisterReceiver(blutteetchReceiver);
super.onDestroy();
}
@BindView(R.id.fl_ads)
FrameLayout flAds;
@BindView(R.id.ll_root)
LinearLayout llRoot;
}
| 37,929 | 0.580975 | 0.577307 | 922 | 39.510845 | 27.360302 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62039 | false | false | 3 |
75df27b838465d62a89865ca90be0e61ad40a7af | 31,336,081,412,629 | c4477ea91b3b42b9c6ab3a01f4ccc9b92120fe82 | /parkingLot/parkingLot.java | 104c49faf4da7766de673fe7065c464357713b90 | [] | no_license | matannagar/Algorithmics_1 | https://github.com/matannagar/Algorithmics_1 | 6be41624d098705f46fddf9b88ea1238ebaf3164 | d7c8ed2807f7ba15227d676968d231ab2eb83e55 | refs/heads/master | 2023-03-04T22:58:16.116000 | 2021-02-17T20:34:58 | 2021-02-17T20:34:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package parkingLot;
import parkingLot.Node;
import parkingLot.LinkedListCycle;
public class parkingLot {
public static void main(String[] args) {
LinkedListCycle parking = new LinkedListCycle();
int nLetters = 23, size = 13;
char v = 'v', w = 'w';
for (int i = 0; i < size; i++) {
char c = (char) ('a' + (int) (Math.random() * nLetters));
parking.add(c);
}
System.out.println(parking.toString());
System.out.println(parking.getSize());
System.out.println("num of cars with 1 pointer:" + countCars(parking, v, w));
System.out.println("num of cars with 2 pointer:" + parkingPointers(parking));
}
public static int countCars(LinkedListCycle parking, char v, char w) {
parking.getHead().setData(v); // we'll mark the first car with V
Node t = parking.getHead().getNext(); // move the pointer one car to the left
boolean flag = true;
int count = 1; // count number of steps (counted the head car)
while (flag) {
if (t.getData() == v) { //if we encounter a car marked with V
t.setData(w); //well mark it W
int i = count;
while (i > 0) {
t = t.getPrev(); //and go back count steps
i--;
}
if (t.getData() == w) // we'll check if this was the only V marked car
flag = false; // if so, we are done and can return count;
else { //if not, we need to mark more cars with W
count = 1;
t = parking.getHead().getNext(); //start walking again
}
} else { //if this car is not marked with V or W, keep stepping forward
t = t.getNext();
count++;
}
}
return count;
}
//using two pointers is O(n) complexity
public static int parkingPointers(LinkedListCycle parking) {
int result = 1; // counter
Node forward = parking.getHead().getNext(); // set the pointer to a car next to the first car
Node head = parking.getHead(); // well loop through the cycle
while (forward != head) {
forward = forward.getNext();
result++; // counter ++
}
return result;
}
}
| UTF-8 | Java | 2,374 | java | parkingLot.java | Java | [] | null | [] | package parkingLot;
import parkingLot.Node;
import parkingLot.LinkedListCycle;
public class parkingLot {
public static void main(String[] args) {
LinkedListCycle parking = new LinkedListCycle();
int nLetters = 23, size = 13;
char v = 'v', w = 'w';
for (int i = 0; i < size; i++) {
char c = (char) ('a' + (int) (Math.random() * nLetters));
parking.add(c);
}
System.out.println(parking.toString());
System.out.println(parking.getSize());
System.out.println("num of cars with 1 pointer:" + countCars(parking, v, w));
System.out.println("num of cars with 2 pointer:" + parkingPointers(parking));
}
public static int countCars(LinkedListCycle parking, char v, char w) {
parking.getHead().setData(v); // we'll mark the first car with V
Node t = parking.getHead().getNext(); // move the pointer one car to the left
boolean flag = true;
int count = 1; // count number of steps (counted the head car)
while (flag) {
if (t.getData() == v) { //if we encounter a car marked with V
t.setData(w); //well mark it W
int i = count;
while (i > 0) {
t = t.getPrev(); //and go back count steps
i--;
}
if (t.getData() == w) // we'll check if this was the only V marked car
flag = false; // if so, we are done and can return count;
else { //if not, we need to mark more cars with W
count = 1;
t = parking.getHead().getNext(); //start walking again
}
} else { //if this car is not marked with V or W, keep stepping forward
t = t.getNext();
count++;
}
}
return count;
}
//using two pointers is O(n) complexity
public static int parkingPointers(LinkedListCycle parking) {
int result = 1; // counter
Node forward = parking.getHead().getNext(); // set the pointer to a car next to the first car
Node head = parking.getHead(); // well loop through the cycle
while (forward != head) {
forward = forward.getNext();
result++; // counter ++
}
return result;
}
}
| 2,374 | 0.53075 | 0.526116 | 63 | 36.619049 | 28.047255 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.698413 | false | false | 3 |
690521f516217d84f9ada5152599f84a66cfa53a | 26,955,214,779,588 | 63d2323c7a61565a90a7b9bf66810ee6d3c858f0 | /nix-explorer/src/main/java/nixexplorer/widgets/dnd/FolderViewBaseTransferHandler.java | c7d49d4fc294f45c1c7f8aa44dffb51cc9923a31 | [] | no_license | jayd2446/nix-explorer | https://github.com/jayd2446/nix-explorer | a608c3b05554ba5f709767f16e67f5c0fa0ff268 | f29da4c609bd1a46ddc81dfe4f769a6485554c9c | refs/heads/master | 2020-11-24T10:13:48.001000 | 2019-10-22T06:55:20 | 2019-10-22T06:55:20 | 228,102,346 | 1 | 0 | null | true | 2019-12-14T23:17:58 | 2019-12-14T23:17:58 | 2019-10-22T14:24:31 | 2019-11-13T09:23:07 | 4,319 | 0 | 0 | 0 | null | false | false | package nixexplorer.widgets.dnd;
import javax.swing.TransferHandler;
import nixexplorer.widgets.folderview.FolderViewWidget;
public class FolderViewBaseTransferHandler extends TransferHandler {
protected FolderViewWidget folderView;
public FolderViewWidget getWidget() {
return folderView;
}
public void setWidget(FolderViewWidget widget) {
this.folderView = widget;
}
}
| UTF-8 | Java | 385 | java | FolderViewBaseTransferHandler.java | Java | [] | null | [] | package nixexplorer.widgets.dnd;
import javax.swing.TransferHandler;
import nixexplorer.widgets.folderview.FolderViewWidget;
public class FolderViewBaseTransferHandler extends TransferHandler {
protected FolderViewWidget folderView;
public FolderViewWidget getWidget() {
return folderView;
}
public void setWidget(FolderViewWidget widget) {
this.folderView = widget;
}
}
| 385 | 0.815584 | 0.815584 | 17 | 21.647058 | 22.276184 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.882353 | false | false | 3 |
18f7d7358ba3533845639ede0fc5ac83e5e6df9e | 9,251,359,588,935 | 9a732c4032960dac75635da5336efb53c11776e0 | /demo-distributed/src/main/java/com/wanggh/demo/distrbuted/rpc/EchoServiceImpl.java | 5e484ddc800a949ed5f07636099e10c0a8fbafee | [] | no_license | wgh1118/demo | https://github.com/wgh1118/demo | d0b650e40919e0c24e054b71e71b77d03219e4e9 | 90b18c00884f3d41c08ddbf219fd009cca97ddfd | refs/heads/master | 2020-07-29T07:39:55.744000 | 2019-09-20T06:41:36 | 2019-09-20T06:41:36 | 209,718,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wanggh.demo.distrbuted.rpc;
public class EchoServiceImpl implements EchoService {
@Override
public String echo(String s) {
return s;
}
}
| UTF-8 | Java | 170 | java | EchoServiceImpl.java | Java | [] | null | [] | package com.wanggh.demo.distrbuted.rpc;
public class EchoServiceImpl implements EchoService {
@Override
public String echo(String s) {
return s;
}
}
| 170 | 0.694118 | 0.694118 | 8 | 20.25 | 18.335417 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
cb354308a0f14cade61fa9608feaab2731347093 | 2,199,023,292,114 | b48967d5c9898bd9819c499dc63e5cf16f418d6e | /DSLCommon/source/dk/tdc/iht/util/factory/ObjectFactory.java | 4b9a38e71f20b47da85f30083c1a1faaa8e6d158 | [] | no_license | ayanch/DSLMON | https://github.com/ayanch/DSLMON | f245f7db16aa433792b7ff1351c5cb2ab71a0da5 | 039fd1188cea25d8bf1c885bc6671c8e10461004 | refs/heads/master | 2016-09-06T17:52:49.572000 | 2015-09-07T23:12:09 | 2015-09-07T23:12:09 | 42,077,295 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*** FILE "ObjectFactory.java" ************************************************/
/******************************************************************************/
/** **/
/** TDC Network Automation Tools - DSL Monitor. **/
/** **/
/******************************************************************************/
/*
* $Log: ObjectFactory.java,v $
* Revision 1.2 2006/11/22 12:59:01 momor
* Object factories now timer capeable
* Modified logger instantiation.
*
* Revision 1.1 2006/09/13 11:54:42 momor
* Common functionality for all main factories.
* Modified provider-implementations.
* Work in progress on test-providers.
*/
package dk.tdc.iht.util.factory;
import java.io.*;
/*** ObjectFactory: ***********************************************************/
/**
* ObjectFactory for creating object instances.
*
* @author <a href="mailto:Morten.Mortensen@yelstream.org"
* >Morten Sabroe Mortensen</a>
* @version $Id: ObjectFactory.java,v 1.2 2006/11/22 12:59:01 momor Exp $
*/
public interface ObjectFactory<E>
{
/**
* Creates a new object instance.
* <br/>
* The type of the instance is the default type according to
* the actual system configuration.
* @return Created instance.
* @throws IOException Thrown in case of I/O error.
*/
E createObject()
throws
IOException;
/**
* Creates a new object instance.
* <br/>
* The type of the instance is determined by the type-name specified.
* @param name Alias for the type of instance requested.
* @return Created instance.
* @throws IllegalArgumentException Thrown in case of an invalid type-name.
* @throws IOException Thrown in case of I/O error.
*/
E createObject(String name)
throws
IllegalArgumentException,
IOException;
/**
* Gets the default object instance.
* @return Default instance.
* @throws IOException
*/
E getObject()
throws
IOException;
/**
* Disposes internal state.
*/
void dispose();
}
/******** "ObjectFactory.java" ************************************************/
| UTF-8 | Java | 2,336 | java | ObjectFactory.java | Java | [
{
"context": "ry.java,v $\r\n * Revision 1.2 2006/11/22 12:59:01 momor\r\n * Object factories now timer capeable\r\n * Modif",
"end": 576,
"score": 0.9796110987663269,
"start": 571,
"tag": "USERNAME",
"value": "momor"
},
{
"context": "iation.\r\n *\r\n * Revision 1.1 2006/09/13 11... | null | [] | /*** FILE "ObjectFactory.java" ************************************************/
/******************************************************************************/
/** **/
/** TDC Network Automation Tools - DSL Monitor. **/
/** **/
/******************************************************************************/
/*
* $Log: ObjectFactory.java,v $
* Revision 1.2 2006/11/22 12:59:01 momor
* Object factories now timer capeable
* Modified logger instantiation.
*
* Revision 1.1 2006/09/13 11:54:42 momor
* Common functionality for all main factories.
* Modified provider-implementations.
* Work in progress on test-providers.
*/
package dk.tdc.iht.util.factory;
import java.io.*;
/*** ObjectFactory: ***********************************************************/
/**
* ObjectFactory for creating object instances.
*
* @author <a href="mailto:<EMAIL>"
* ><NAME></a>
* @version $Id: ObjectFactory.java,v 1.2 2006/11/22 12:59:01 momor Exp $
*/
public interface ObjectFactory<E>
{
/**
* Creates a new object instance.
* <br/>
* The type of the instance is the default type according to
* the actual system configuration.
* @return Created instance.
* @throws IOException Thrown in case of I/O error.
*/
E createObject()
throws
IOException;
/**
* Creates a new object instance.
* <br/>
* The type of the instance is determined by the type-name specified.
* @param name Alias for the type of instance requested.
* @return Created instance.
* @throws IllegalArgumentException Thrown in case of an invalid type-name.
* @throws IOException Thrown in case of I/O error.
*/
E createObject(String name)
throws
IllegalArgumentException,
IOException;
/**
* Gets the default object instance.
* @return Default instance.
* @throws IOException
*/
E getObject()
throws
IOException;
/**
* Disposes internal state.
*/
void dispose();
}
/******** "ObjectFactory.java" ************************************************/
| 2,296 | 0.5 | 0.479452 | 77 | 28.337662 | 26.466156 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.116883 | false | false | 3 |
4410cf44f0bcb96c816fc57b54c4e1e44d2cbcbf | 27,178,553,069,346 | 6a6df438cbc657cac728b5b50c68611080a9c696 | /ticketing-infrastructure/src/main/java/be/dewolf/App.java | 05fe765106a254bb3bb6a81318a9848b893a4981 | [] | no_license | yannisdewolf/ticketing | https://github.com/yannisdewolf/ticketing | 63cce0944ad4f274779f8ae5e96ee84d1a6fecc8 | bc3fb4d24070da3caf7ae7eda72f4256172f15ea | refs/heads/master | 2023-01-09T12:32:21.358000 | 2019-12-21T12:53:24 | 2019-12-21T12:53:24 | 222,228,993 | 0 | 0 | null | false | 2023-01-01T14:39:13 | 2019-11-17T10:09:13 | 2019-12-21T12:53:37 | 2023-01-01T14:39:10 | 2,204 | 0 | 0 | 11 | Java | false | false | package be.dewolf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Hello world!
*/
@SpringBootApplication
@Controller
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@GetMapping("/")
public ModelAndView home() {
return new ModelAndView("redirect:/ticket/agenda");
}
}
| UTF-8 | Java | 604 | java | App.java | Java | [] | null | [] | package be.dewolf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Hello world!
*/
@SpringBootApplication
@Controller
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@GetMapping("/")
public ModelAndView home() {
return new ModelAndView("redirect:/ticket/agenda");
}
}
| 604 | 0.75 | 0.75 | 24 | 24.166666 | 22.521595 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
110c97efc0878e8c80dbc43dc94345c0e653fcf6 | 27,178,553,068,400 | 211e0162004b03455839879773c909a4d4868a2f | /pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/bestpractices/missingoverride/HierarchyWithSeveralBridges.java | 08e1f1fd93235137da6d21b91c91352e02b759d4 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | pmd/pmd | https://github.com/pmd/pmd | 460ca96dfcc5d25b5b3e78fc8731593dc6ddf8d3 | 512d6cbb8d198119a588b84c238ed78d75abda0c | refs/heads/master | 2023-09-04T05:58:54.224000 | 2023-08-31T14:20:57 | 2023-08-31T14:20:57 | 4,992,906 | 4,409 | 1,671 | NOASSERTION | false | 2023-09-14T08:13:05 | 2012-07-11T18:03:00 | 2023-09-13T12:22:00 | 2023-09-12T11:10:15 | 440,287 | 4,402 | 1,446 | 659 | Java | false | false | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.bestpractices.missingoverride;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
public abstract class HierarchyWithSeveralBridges<T extends Node> {
abstract void foo(T node);
public abstract static class SubclassOne<T extends JavaNode> extends HierarchyWithSeveralBridges<T> {
@Override
abstract void foo(T node);
}
public abstract static class SubclassTwo<T extends TypeNode> extends SubclassOne<T> {
@Override
void foo(T node) {
}
}
public static class Concrete extends SubclassTwo<ASTPrimitiveType> {
// bridges: foo(AbstractJavaTypeNode), foo(JavaNode), foo(Node)
@Override
void foo(ASTPrimitiveType node) {
}
}
}
| UTF-8 | Java | 1,016 | java | HierarchyWithSeveralBridges.java | Java | [] | null | [] | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.bestpractices.missingoverride;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.TypeNode;
public abstract class HierarchyWithSeveralBridges<T extends Node> {
abstract void foo(T node);
public abstract static class SubclassOne<T extends JavaNode> extends HierarchyWithSeveralBridges<T> {
@Override
abstract void foo(T node);
}
public abstract static class SubclassTwo<T extends TypeNode> extends SubclassOne<T> {
@Override
void foo(T node) {
}
}
public static class Concrete extends SubclassTwo<ASTPrimitiveType> {
// bridges: foo(AbstractJavaTypeNode), foo(JavaNode), foo(Node)
@Override
void foo(ASTPrimitiveType node) {
}
}
}
| 1,016 | 0.707677 | 0.707677 | 39 | 25.051283 | 30.523592 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25641 | false | false | 3 |
892a5e888bbcf1045d86068cc870dfe66153ed74 | 20,203,526,223,226 | 9147f91753425f65ddba5597290af179bba1c043 | /baixian_service/src/main/java/com/yztc/hkl/service/VipUserService.java | 033ec4e56acfb13f148c23dd48c7affd51347e22 | [] | no_license | 978569208/baixian | https://github.com/978569208/baixian | 480d6aea594a60e2628702eb2151d1a460e0ed54 | c61521b4b011ec94b4068471828597eec62ac92a | refs/heads/master | 2021-08-24T00:25:00.656000 | 2017-12-07T07:43:11 | 2017-12-07T07:47:57 | 113,418,940 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yztc.hkl.service;
import java.util.List;
import com.yztc.hkl.pojo.VipUser;
public interface VipUserService {
VipUser islogin(VipUser vipUser);
}
| UTF-8 | Java | 174 | java | VipUserService.java | Java | [] | null | [] | package com.yztc.hkl.service;
import java.util.List;
import com.yztc.hkl.pojo.VipUser;
public interface VipUserService {
VipUser islogin(VipUser vipUser);
}
| 174 | 0.724138 | 0.724138 | 11 | 13.818182 | 15.254318 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
9e172b6279619c4e39cb3c03e31a9fd57e3b86bd | 23,759,759,122,326 | 1f8d00560262a84b5312f9fef89fbaa41a917fef | /src/test/java/com/sc/cd/optional/OptionalDemo.java | 76c25816e58524b4f4e42f837afe7e7e1bd86fec | [] | no_license | junxchen/jdk8demo | https://github.com/junxchen/jdk8demo | db29e0c904bb8be3049d87a6f74f90521d49acbd | 7814d8927d43e5c916d857a3162dd44516b9e4e8 | refs/heads/master | 2022-06-22T05:06:31.402000 | 2021-09-10T13:13:01 | 2021-09-10T13:13:01 | 186,758,740 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sc.cd.optional;
import java.util.Optional;
import org.junit.Test;
import com.sc.cd.specification.optional.model.UserDO;
/**
* 描述:
* OptionalDemo
*
* @author junxi.chen
* @create 2018-11-30 18:03
*/
public class OptionalDemo {
@Test
public void whenCreateEmptyOptional_thenNull() {
Optional<UserDO> emptyOpt = Optional.empty();
emptyOpt.get();
}
@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
//Optional<UserDO> opt = Optional.of(user);
}
}
| UTF-8 | Java | 582 | java | OptionalDemo.java | Java | [
{
"context": ".UserDO;\n\n/**\n * 描述:\n * OptionalDemo\n *\n * @author junxi.chen\n * @create 2018-11-30 18:03\n */\n\npublic ",
"end": 178,
"score": 0.9117993712425232,
"start": 177,
"tag": "NAME",
"value": "j"
},
{
"context": "serDO;\n\n/**\n * 描述:\n * OptionalDemo\n *\n * @author ... | null | [] | package com.sc.cd.optional;
import java.util.Optional;
import org.junit.Test;
import com.sc.cd.specification.optional.model.UserDO;
/**
* 描述:
* OptionalDemo
*
* @author junxi.chen
* @create 2018-11-30 18:03
*/
public class OptionalDemo {
@Test
public void whenCreateEmptyOptional_thenNull() {
Optional<UserDO> emptyOpt = Optional.empty();
emptyOpt.get();
}
@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
//Optional<UserDO> opt = Optional.of(user);
}
}
| 582 | 0.683391 | 0.66263 | 29 | 18.931034 | 20.733 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 3 |
3555a692bcb9fb5e0ba66fae6bfab0d1d198aae5 | 2,576,980,438,468 | 5821b61ebf73d8ccc58147e0b3e94b3ca1e04041 | /app-web/src/main/java/ru/koleslena/shop/orm/dao/impl/UserRoleDaoImpl.java | 725014676ea3b29220704f71d3c43841420339c2 | [] | no_license | talkvip/shop | https://github.com/talkvip/shop | 94972ef624868c5ca4d11c64b0b8c04a921168d3 | a8cabf4fdacb91c3e5caf2d6b4562c4dcb7fd6d0 | refs/heads/master | 2016-09-11T11:53:47.123000 | 2013-12-18T08:00:59 | 2013-12-18T08:00:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.koleslena.shop.orm.dao.impl;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.koleslena.shop.exception.ShopException;
import ru.koleslena.shop.orm.dao.BaseDao;
import ru.koleslena.shop.orm.dao.UserRoleDao;
import ru.koleslena.shop.orm.dto.Role;
import ru.koleslena.shop.orm.dto.User;
/**
* @author koleslena
*
*/
@Repository
public class UserRoleDaoImpl implements UserRoleDao {
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
@Inject
private BaseDao baseDao;
@Autowired
private SessionFactory sessionFactory;
/**
* Вспомогательный метод для получения текущей сессии
*
* @return
*/
protected Session session() {
return sessionFactory.getCurrentSession();
}
@Override
@Transactional(readOnly=true)
public User authUser(String login, String security) {
return (User) session().createQuery("FROM User as u WHERE u.name like :name AND u.password like :pass ")
.setParameter("name", login)
.setParameter("pass", security).uniqueResult();
}
@Override
public void createUser(String login, String security) throws ShopException {
Role userRole = getRoleBySpringName(Role.STRING_USER_ROLE_NAME);
if(userRole == null)
throw new ShopException("Не правильно настроены роли. Не найдена роль user.");
User user = new User();
user.setName(login);
user.setPassword(security);
user.setRole(userRole);
baseDao.persist(user);
return;
}
@Override
@Transactional(readOnly=true)
public Role getRoleBySpringName(String name) {
return (Role) session().createQuery("FROM Role as r WHERE r.springName like :name")
.setParameter("name", name).uniqueResult();
}
}
| UTF-8 | Java | 2,081 | java | UserRoleDaoImpl.java | Java | [
{
"context": "rt ru.koleslena.shop.orm.dto.User;\n\n/**\n * @author koleslena\n *\n */\n@Repository\npublic class UserRoleDaoImpl i",
"end": 614,
"score": 0.9996775388717651,
"start": 605,
"tag": "USERNAME",
"value": "koleslena"
},
{
"context": "User();\n\t\tuser.setName(login);\n\t\... | null | [] | package ru.koleslena.shop.orm.dao.impl;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.koleslena.shop.exception.ShopException;
import ru.koleslena.shop.orm.dao.BaseDao;
import ru.koleslena.shop.orm.dao.UserRoleDao;
import ru.koleslena.shop.orm.dto.Role;
import ru.koleslena.shop.orm.dto.User;
/**
* @author koleslena
*
*/
@Repository
public class UserRoleDaoImpl implements UserRoleDao {
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
@Inject
private BaseDao baseDao;
@Autowired
private SessionFactory sessionFactory;
/**
* Вспомогательный метод для получения текущей сессии
*
* @return
*/
protected Session session() {
return sessionFactory.getCurrentSession();
}
@Override
@Transactional(readOnly=true)
public User authUser(String login, String security) {
return (User) session().createQuery("FROM User as u WHERE u.name like :name AND u.password like :pass ")
.setParameter("name", login)
.setParameter("pass", security).uniqueResult();
}
@Override
public void createUser(String login, String security) throws ShopException {
Role userRole = getRoleBySpringName(Role.STRING_USER_ROLE_NAME);
if(userRole == null)
throw new ShopException("Не правильно настроены роли. Не найдена роль user.");
User user = new User();
user.setName(login);
user.setPassword(<PASSWORD>);
user.setRole(userRole);
baseDao.persist(user);
return;
}
@Override
@Transactional(readOnly=true)
public Role getRoleBySpringName(String name) {
return (Role) session().createQuery("FROM Role as r WHERE r.springName like :name")
.setParameter("name", name).uniqueResult();
}
}
| 2,083 | 0.745373 | 0.744372 | 75 | 25.653334 | 25.159487 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.306667 | false | false | 3 |
754a4d2832018fa61b2a7d75a10834762ed34376 | 23,063,974,438,578 | 0af0741ed8b8e7f241ab07f072875855b5461e05 | /src/java/org/probosque/model/json/TotalJson.java | 7488e8bef9bd053c111e3d63d7010e1fec92dbd8 | [] | no_license | PROBOSQUE2017/ServiceBosque | https://github.com/PROBOSQUE2017/ServiceBosque | 5106435ab4bc7977e00c5c9e0d10686255d1bd49 | 42d55c0cbc1759a9c684ec56870ae9b6415cf22d | refs/heads/master | 2021-05-15T17:57:58.795000 | 2018-02-26T21:59:42 | 2018-02-26T21:59:42 | 107,585,734 | 0 | 1 | null | false | 2018-02-26T21:59:43 | 2017-10-19T18:51:12 | 2017-10-19T18:57:13 | 2018-02-26T21:59:43 | 4,467 | 0 | 1 | 0 | Java | false | null | package org.probosque.model.json;
import org.probosque.dto.TotalDTO;
public class TotalJson {
private TotalDTO totals;
public TotalDTO getTotals() {
return totals;
}
public void setTotals(TotalDTO totals) {
this.totals = totals;
}
}
| UTF-8 | Java | 277 | java | TotalJson.java | Java | [] | null | [] | package org.probosque.model.json;
import org.probosque.dto.TotalDTO;
public class TotalJson {
private TotalDTO totals;
public TotalDTO getTotals() {
return totals;
}
public void setTotals(TotalDTO totals) {
this.totals = totals;
}
}
| 277 | 0.65704 | 0.65704 | 16 | 16.1875 | 15.146034 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 3 |
cedf3229003df8f1aacfae027d12789080f80a87 | 28,930,899,768,305 | fa4ccc1aaadfb4ab68807c86ac3d750aa435d0f5 | /QRTracker/app/src/main/java/daielchom/qrtracker/QRTrackerService.java | dea53f730bd8d577c8ac91af642f7ad3324d51ba | [] | no_license | DaielChom/QRTrackerApp | https://github.com/DaielChom/QRTrackerApp | f958167e50fdec4fb524518f73d069be66f8955a | 18779b9a0239ab82041cdbb54d3ad9f6037b8487 | refs/heads/master | 2020-12-02T17:49:46.408000 | 2017-07-24T20:42:03 | 2017-07-24T20:42:03 | 96,435,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package daielchom.qrtracker;
import android.util.Log;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
/**
* Created by daielchom on 7/07/17.
*/
public interface QRTrackerService {
@GET("funcionarios/{id_official}")
Call<official> getOfficialAPI(@Path("id_official") String id_official);
@GET("paquetes/list")
Call <paqueteList> getPackageList(@QueryMap Map<String, String> options);
@GET("paquetes/{id_paquete}")
Call <paquete> getPackage(@Path("id_paquete") String id_paquete);
@POST("monitoreos")
Call <Monitor> postMonitor(@Body Monitor monitor);
}
| UTF-8 | Java | 760 | java | QRTrackerService.java | Java | [
{
"context": "import retrofit2.http.QueryMap;\n\n/**\n * Created by daielchom on 7/07/17.\n */\n\npublic interface QRTrackerServic",
"end": 296,
"score": 0.9996063709259033,
"start": 287,
"tag": "USERNAME",
"value": "daielchom"
}
] | null | [] | package daielchom.qrtracker;
import android.util.Log;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
/**
* Created by daielchom on 7/07/17.
*/
public interface QRTrackerService {
@GET("funcionarios/{id_official}")
Call<official> getOfficialAPI(@Path("id_official") String id_official);
@GET("paquetes/list")
Call <paqueteList> getPackageList(@QueryMap Map<String, String> options);
@GET("paquetes/{id_paquete}")
Call <paquete> getPackage(@Path("id_paquete") String id_paquete);
@POST("monitoreos")
Call <Monitor> postMonitor(@Body Monitor monitor);
}
| 760 | 0.725 | 0.710526 | 34 | 21.352942 | 22.014544 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441176 | false | false | 3 |
5913911b6e0ca8aafa62b19cd6813f6603d596e8 | 18,193,481,474,059 | 9ccefbec72d441bb679ba0d197f369cde5c7852b | /HelloJava01/src/java01/Compare.java | 64db18bbd7a4cd7fa7a39d92789950ec39115e25 | [] | no_license | YWZFrances/Java_study | https://github.com/YWZFrances/Java_study | 8563bc5e377848c56d83a4492ae8db6f4d3492c8 | 99f4eb608157402f1903749030aa3fbf558b89fe | refs/heads/master | 2018-09-27T10:35:22.828000 | 2018-07-14T07:23:20 | 2018-07-14T07:23:20 | 114,589,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package java01;
public class Compare {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
int number1 = 4;
int number2 = 5;
// boolean number3 = 0;
boolean a = number1 > number2;
boolean b = number1 < number2;
System.out.println(a);
System.out.println(b);
}
}
| GB18030 | Java | 332 | java | Compare.java | Java | [] | null | [] | package java01;
public class Compare {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
int number1 = 4;
int number2 = 5;
// boolean number3 = 0;
boolean a = number1 > number2;
boolean b = number1 < number2;
System.out.println(a);
System.out.println(b);
}
}
| 332 | 0.630573 | 0.592357 | 19 | 15.526316 | 12.261915 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.526316 | false | false | 3 |
e35f346975781f1f89cdab5dd1d6f8b55b4ba06f | 17,282,948,462,814 | ec6087bfcfba20306748b2ff5cd559cb32b35ff6 | /uva/11340/Main.java | f7ca1106d13584a695a0a55a8c696db7fd2c5041 | [
"BSD-3-Clause"
] | permissive | lang010/acit | https://github.com/lang010/acit | 20bc1ea2956f83853551e398d86e3a14672e0aeb | 5c43d6400e55992e9cf059d2bdf05536b776f71b | refs/heads/master | 2021-01-20T09:45:24.832000 | 2020-12-16T04:05:10 | 2020-12-16T04:05:10 | 25,975,369 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2014 Liang Li <ll@lianglee.org>. All rights reserved.
*
* This program is a free software and released under the BSD license.
* https://github.com/lang010/acit
*
* Solutions for UVa Problem 11340
* UVa link: http://uva.onlinejudge.org/external/113/11340.html
*
* @Authur Liang Li <ll@lianglee.org>
* @Date Nov 27 21:38:41 2014
*/
import java.util.Scanner;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Main {
Scanner sc = new Scanner(System.in, "ISO-8859-1");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out, "ISO-8859-1"));
public Main() throws Exception {
}
public static void main(String[] args) throws Exception {
Main m = new Main();
m.run();
m.release();
}
void release() {
sc.close();
pw.close();
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
int sum = 0;
int n = 0;
int k,m;
Integer val = null;
void run() {
n = sc.nextInt();
for (int c = 0; c < n; c++) {
map.clear();
sum = 0;
k = sc.nextInt();
for (int i = 0; i < k; i++) {
map.put(sc.next().charAt(0), sc.nextInt());
}
m = sc.nextInt();
sc.nextLine();
for (int i = 0; i < m; i++) {
String s = sc.nextLine();
for (int j = 0; j < s.length(); j++) {
val = map.get(s.charAt(j));
if (val != null) {
sum += val;
}
}
}
pw.printf("%.2f$%n", sum/100.0);
}
}
}
| UTF-8 | Java | 1,731 | java | Main.java | Java | [
{
"context": "/*\n * Copyright (c) 2014 Liang Li <ll@lianglee.org>. All rights reserved.\n *\n * Th",
"end": 34,
"score": 0.9997455477714539,
"start": 26,
"tag": "NAME",
"value": "Liang Li"
},
{
"context": "/*\n * Copyright (c) 2014 Liang Li <ll@lianglee.org>. All rights reserved.... | null | [] | /*
* Copyright (c) 2014 <NAME> <<EMAIL>>. All rights reserved.
*
* This program is a free software and released under the BSD license.
* https://github.com/lang010/acit
*
* Solutions for UVa Problem 11340
* UVa link: http://uva.onlinejudge.org/external/113/11340.html
*
* @Authur <NAME> <<EMAIL>>
* @Date Nov 27 21:38:41 2014
*/
import java.util.Scanner;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Main {
Scanner sc = new Scanner(System.in, "ISO-8859-1");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out, "ISO-8859-1"));
public Main() throws Exception {
}
public static void main(String[] args) throws Exception {
Main m = new Main();
m.run();
m.release();
}
void release() {
sc.close();
pw.close();
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
int sum = 0;
int n = 0;
int k,m;
Integer val = null;
void run() {
n = sc.nextInt();
for (int c = 0; c < n; c++) {
map.clear();
sum = 0;
k = sc.nextInt();
for (int i = 0; i < k; i++) {
map.put(sc.next().charAt(0), sc.nextInt());
}
m = sc.nextInt();
sc.nextLine();
for (int i = 0; i < m; i++) {
String s = sc.nextLine();
for (int j = 0; j < s.length(); j++) {
val = map.get(s.charAt(j));
if (val != null) {
sum += val;
}
}
}
pw.printf("%.2f$%n", sum/100.0);
}
}
}
| 1,711 | 0.508377 | 0.476603 | 67 | 24.835821 | 20.92103 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716418 | false | false | 3 |
18c57e253a539d965def19880201a4a7c9cd36ef | 25,211,458,057,396 | 159c11b8c539e14262011432a3c3953180ca4c00 | /src/main/java/katas/ReverseOrRotateApp.java | d8fca12d5e6ebfb8dfba171c6be720907e2b1815 | [] | no_license | mmlaura19940/codewars-katas | https://github.com/mmlaura19940/codewars-katas | 6b4a4c3644b7448bd26df0c167728cbb69eebd04 | a336df7d1d658d257ab3e7162a22fbf91d5ba461 | refs/heads/master | 2020-06-24T02:23:35.571000 | 2019-07-25T13:20:31 | 2019-07-25T13:20:31 | 198,821,382 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package katas;
public class ReverseOrRotateApp {
public String reverseOrRotate(String str, int chunkSize) {
if (chunkSize == 0 || str.length() == 0 || chunkSize > str.length()) {
return "";
}
int start = 0;
final char[] charsOfPart = str.toCharArray();
boolean isContainNumber = false;
for (int i = 0; i < charsOfPart.length; i++) {
if (Character.isDigit(charsOfPart[i])) {
isContainNumber = true;
}
}
if (isContainNumber) {
final StringBuilder stringBuilder = new StringBuilder();
while (start <= str.length() - chunkSize) {
int cube = 0;
int sum = 0;
for (int i = start; i < start + chunkSize; i++) {
final int numericValue = Character.getNumericValue(charsOfPart[i]);
cube = (int) Math.pow((double) numericValue, 3);
sum += cube;
}
if (sum % 2 == 0) {
for (int j = start + chunkSize - 1; j >= start; j--) {
stringBuilder.append(charsOfPart[j]);
}
} else {
for (int j = start; j < start + chunkSize; j++) {
if (j != start) {
stringBuilder.append(charsOfPart[j]);
}
}
stringBuilder.append(charsOfPart[start]);
}
start = start + chunkSize;
}
return stringBuilder.toString().trim();
}
else {
return str;
}
}
}
| UTF-8 | Java | 1,313 | java | ReverseOrRotateApp.java | Java | [] | null | [] | package katas;
public class ReverseOrRotateApp {
public String reverseOrRotate(String str, int chunkSize) {
if (chunkSize == 0 || str.length() == 0 || chunkSize > str.length()) {
return "";
}
int start = 0;
final char[] charsOfPart = str.toCharArray();
boolean isContainNumber = false;
for (int i = 0; i < charsOfPart.length; i++) {
if (Character.isDigit(charsOfPart[i])) {
isContainNumber = true;
}
}
if (isContainNumber) {
final StringBuilder stringBuilder = new StringBuilder();
while (start <= str.length() - chunkSize) {
int cube = 0;
int sum = 0;
for (int i = start; i < start + chunkSize; i++) {
final int numericValue = Character.getNumericValue(charsOfPart[i]);
cube = (int) Math.pow((double) numericValue, 3);
sum += cube;
}
if (sum % 2 == 0) {
for (int j = start + chunkSize - 1; j >= start; j--) {
stringBuilder.append(charsOfPart[j]);
}
} else {
for (int j = start; j < start + chunkSize; j++) {
if (j != start) {
stringBuilder.append(charsOfPart[j]);
}
}
stringBuilder.append(charsOfPart[start]);
}
start = start + chunkSize;
}
return stringBuilder.toString().trim();
}
else {
return str;
}
}
}
| 1,313 | 0.569688 | 0.562072 | 50 | 24.26 | 21.758501 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.62 | false | false | 3 |
dea2a5d344233c18c084f3d4b3aaa7ee6641f495 | 23,510,651,035,307 | 637f2b415f5283e155f54218aa347013a373a4a9 | /src/HillDecipher.java | 8b0e94185b696d85535b30c51a823a1c6cbd3507 | [] | no_license | emillen/hill_cipher | https://github.com/emillen/hill_cipher | d28acbc096cbd516c402f15da115508c03a0f87c | 193550adb0e4f5e0b50e6939ed33d8815655c074 | refs/heads/master | 2021-01-01T05:22:07.482000 | 2016-04-19T09:41:38 | 2016-04-19T09:41:38 | 56,312,690 | 0 | 0 | null | false | 2016-04-15T11:48:15 | 2016-04-15T10:39:14 | 2016-04-15T11:38:54 | 2016-04-15T11:48:15 | 3 | 0 | 0 | 0 | Java | null | null | import org.jscience.mathematics.number.Real;
import org.jscience.mathematics.vector.DenseMatrix;
import org.jscience.mathematics.vector.DenseVector;
import java.io.File;
import java.io.PrintWriter;
/**
* A program used to decrypt a file using hill cipher algorithm
*
* @author Emil Lengman
* @author Simon Enerstrand
*/
public class HillDecipher {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: HillDecipher <fileContainingD> <fileContainingCipherText> <fileToSaveTo>");
return;
}
String DFile = args[0];
String CFile = args[1];
String saveFile = args[2];
DenseMatrix<Real> D;
if ((D = Util.getMatrixFromFile(DFile)) == null) {
System.out.println("File <" + DFile + "> does not exist, or does not contain a matrix");
}
if ((new File(saveFile).isFile())) {
if (!(Util.overwrite(saveFile)))
return;
}
DenseMatrix<Real> cipherMatrix;
if ((cipherMatrix = Util.getStringMatrixFromFile(CFile)) == null) {
System.out.println("The file does not exist, or does not contain a valid message");
}
writeToFile(saveFile, decipher(D, cipherMatrix).transpose());
}
private static DenseMatrix<Real> decipher(DenseMatrix<Real> K, DenseMatrix<Real> message) {
return Util.timesMod(K, message, Util.NUM_IN_ALPHBET);
}
/**
* Writes the matrix to a file
*
* @param fileName the file to write to
* @param matrix the encryption matrix
*/
private static void writeToFile(String fileName, DenseMatrix<Real> matrix) {
PrintWriter writer;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (Exception e) {
System.out.println("Something went terribly wrong");
return;
}
for (int i = 0; i < matrix.getNumberOfRows() - 1; i++) {
for (int j = 0; j < matrix.getNumberOfColumns(); j++) {
writer.write(matrix.get(i, j).intValue() + 65);
}
}
writeLastRow(writer, matrix);
writer.close();
}
/**
* Depads and writes the last row to the file.
*
* @param writer the PrintWriter
* @param matrix the matrix that we are writing
*/
private static void writeLastRow(PrintWriter writer, DenseMatrix<Real> matrix) {
DenseVector<Real> lastRow = matrix.getRow(matrix.getNumberOfRows() - 1);
int sameCount = countSame(lastRow);
int amountToWrite = lastRow.getDimension();
if (sameCount == lastRow.get(amountToWrite - 1).intValue())
amountToWrite -= sameCount;
for (int i = 0; i < amountToWrite; i++)
writer.write(lastRow.get(i).intValue() + 65);
}
/**
* Counts how many numbers that are the same and next to eachother starting from the last number in the vector
*
* @param row the vector
* @return the count
*/
private static int countSame(DenseVector<Real> row) {
int last = row.getDimension() - 1;
int value = row.get(last).intValue();
int count = 1;
for (int i = last - 1; i >= 0; i--) {
int iValue = row.get(i).intValue();
if (value == iValue)
count++;
else
break;
}
return count;
}
}
| UTF-8 | Java | 3,470 | java | HillDecipher.java | Java | [
{
"context": "t a file using hill cipher algorithm\n *\n * @author Emil Lengman\n * @author Simon Enerstrand\n */\npublic class Hill",
"end": 294,
"score": 0.9998515248298645,
"start": 282,
"tag": "NAME",
"value": "Emil Lengman"
},
{
"context": "er algorithm\n *\n * @author Emil Leng... | null | [] | import org.jscience.mathematics.number.Real;
import org.jscience.mathematics.vector.DenseMatrix;
import org.jscience.mathematics.vector.DenseVector;
import java.io.File;
import java.io.PrintWriter;
/**
* A program used to decrypt a file using hill cipher algorithm
*
* @author <NAME>
* @author <NAME>
*/
public class HillDecipher {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: HillDecipher <fileContainingD> <fileContainingCipherText> <fileToSaveTo>");
return;
}
String DFile = args[0];
String CFile = args[1];
String saveFile = args[2];
DenseMatrix<Real> D;
if ((D = Util.getMatrixFromFile(DFile)) == null) {
System.out.println("File <" + DFile + "> does not exist, or does not contain a matrix");
}
if ((new File(saveFile).isFile())) {
if (!(Util.overwrite(saveFile)))
return;
}
DenseMatrix<Real> cipherMatrix;
if ((cipherMatrix = Util.getStringMatrixFromFile(CFile)) == null) {
System.out.println("The file does not exist, or does not contain a valid message");
}
writeToFile(saveFile, decipher(D, cipherMatrix).transpose());
}
private static DenseMatrix<Real> decipher(DenseMatrix<Real> K, DenseMatrix<Real> message) {
return Util.timesMod(K, message, Util.NUM_IN_ALPHBET);
}
/**
* Writes the matrix to a file
*
* @param fileName the file to write to
* @param matrix the encryption matrix
*/
private static void writeToFile(String fileName, DenseMatrix<Real> matrix) {
PrintWriter writer;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (Exception e) {
System.out.println("Something went terribly wrong");
return;
}
for (int i = 0; i < matrix.getNumberOfRows() - 1; i++) {
for (int j = 0; j < matrix.getNumberOfColumns(); j++) {
writer.write(matrix.get(i, j).intValue() + 65);
}
}
writeLastRow(writer, matrix);
writer.close();
}
/**
* Depads and writes the last row to the file.
*
* @param writer the PrintWriter
* @param matrix the matrix that we are writing
*/
private static void writeLastRow(PrintWriter writer, DenseMatrix<Real> matrix) {
DenseVector<Real> lastRow = matrix.getRow(matrix.getNumberOfRows() - 1);
int sameCount = countSame(lastRow);
int amountToWrite = lastRow.getDimension();
if (sameCount == lastRow.get(amountToWrite - 1).intValue())
amountToWrite -= sameCount;
for (int i = 0; i < amountToWrite; i++)
writer.write(lastRow.get(i).intValue() + 65);
}
/**
* Counts how many numbers that are the same and next to eachother starting from the last number in the vector
*
* @param row the vector
* @return the count
*/
private static int countSame(DenseVector<Real> row) {
int last = row.getDimension() - 1;
int value = row.get(last).intValue();
int count = 1;
for (int i = last - 1; i >= 0; i--) {
int iValue = row.get(i).intValue();
if (value == iValue)
count++;
else
break;
}
return count;
}
}
| 3,454 | 0.581844 | 0.576369 | 122 | 27.442623 | 27.937592 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false | 3 |
da5f914eaf5d566ee54806d8287f225c926f6d56 | 28,372,553,981,805 | 0d64fabd30895bb0771ad47d7ba78f0d6bf0be88 | /src/main/java/org/yfr/spring/service/impl/GoogleMapServiceImpl.java | e1fad5cc489bd9a74ad7f983f1035acc89bacf59 | [] | no_license | Jian-Min-Huang/web-app-framework | https://github.com/Jian-Min-Huang/web-app-framework | 0d25b60505f8f5d5f04e8f6666dd573b9cf97b0d | 52a7e963b16704db417ed575470767780c9d0d1a | HEAD | 2018-01-08T04:22:56.269000 | 2016-02-21T05:42:28 | 2016-02-21T05:42:28 | 36,881,193 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.yfr.spring.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.yfr.spring.data.jpa.MapPolygonRepository;
import org.yfr.spring.data.jpa.MapPolylineRepository;
import org.yfr.spring.data.jpa.MarkerPositionRepository;
import org.yfr.spring.dto.MapPolygonPosition;
import org.yfr.spring.dto.MapPolylinePosition;
import org.yfr.spring.entity.MapPolygonEntity;
import org.yfr.spring.entity.MapPolylineEntity;
import org.yfr.spring.entity.MarkerPositionEntity;
import org.yfr.spring.service.GoogleMapService;
@Service("googleMapService")
public class GoogleMapServiceImpl implements GoogleMapService {
@Resource
private MapPolylineRepository mapPolylineRepository;
@Resource
private MapPolygonRepository mapPolygonRepository;
@Resource
private MarkerPositionRepository markerPositionRepository;
@Override
public List<MapPolylinePosition> queryMapPolylines() throws Exception {
List<MapPolylinePosition> rtnList = new ArrayList<MapPolylinePosition>();
List<MapPolylineEntity> mapPolylines = mapPolylineRepository.findAll();
for (MapPolylineEntity mapPolyline : mapPolylines) {
MapPolylinePosition mapPolylinePosition = new MapPolylinePosition();
mapPolylinePosition.setName(mapPolyline.getName());
mapPolylinePosition.setPaths(mapPolyline.getPaths());
mapPolylinePosition.setStrokeColor(mapPolyline.getStrokeColor());
mapPolylinePosition.setStrokeOpacity(mapPolyline.getStrokeOpacity());
mapPolylinePosition.setStrokeWeight(mapPolyline.getStrokeWeight());
List<MarkerPositionEntity> positions = new ArrayList<MarkerPositionEntity>();
String[] paths = mapPolyline.getPaths().split(",");
for (String path : paths) {
positions.add(markerPositionRepository.findOne(path));
}
mapPolylinePosition.setPositions(positions);
rtnList.add(mapPolylinePosition);
}
return rtnList;
}
@Override
public List<MapPolygonPosition> queryMapPolygons() throws Exception {
List<MapPolygonPosition> rtnList = new ArrayList<MapPolygonPosition>();
List<MapPolygonEntity> mapPolygons = mapPolygonRepository.findAll();
for (MapPolygonEntity mapPolygon : mapPolygons) {
MapPolygonPosition mapPolygonPosition = new MapPolygonPosition();
mapPolygonPosition.setName(mapPolygon.getName());
mapPolygonPosition.setPaths(mapPolygon.getPaths());
mapPolygonPosition.setStrokeColor(mapPolygon.getStrokeColor());
mapPolygonPosition.setStrokeOpacity(mapPolygon.getStrokeOpacity());
mapPolygonPosition.setStrokeWeight(mapPolygon.getStrokeWeight());
mapPolygonPosition.setFillColor(mapPolygon.getFillColor());
mapPolygonPosition.setFillOpacity(mapPolygon.getFillOpacity());
List<MarkerPositionEntity> positions = new ArrayList<MarkerPositionEntity>();
String[] paths = mapPolygon.getPaths().split(",");
for (String path : paths) {
positions.add(markerPositionRepository.findOne(path));
}
mapPolygonPosition.setPositions(positions);
rtnList.add(mapPolygonPosition);
}
return rtnList;
}
}
| UTF-8 | Java | 3,099 | java | GoogleMapServiceImpl.java | Java | [] | null | [] |
package org.yfr.spring.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.yfr.spring.data.jpa.MapPolygonRepository;
import org.yfr.spring.data.jpa.MapPolylineRepository;
import org.yfr.spring.data.jpa.MarkerPositionRepository;
import org.yfr.spring.dto.MapPolygonPosition;
import org.yfr.spring.dto.MapPolylinePosition;
import org.yfr.spring.entity.MapPolygonEntity;
import org.yfr.spring.entity.MapPolylineEntity;
import org.yfr.spring.entity.MarkerPositionEntity;
import org.yfr.spring.service.GoogleMapService;
@Service("googleMapService")
public class GoogleMapServiceImpl implements GoogleMapService {
@Resource
private MapPolylineRepository mapPolylineRepository;
@Resource
private MapPolygonRepository mapPolygonRepository;
@Resource
private MarkerPositionRepository markerPositionRepository;
@Override
public List<MapPolylinePosition> queryMapPolylines() throws Exception {
List<MapPolylinePosition> rtnList = new ArrayList<MapPolylinePosition>();
List<MapPolylineEntity> mapPolylines = mapPolylineRepository.findAll();
for (MapPolylineEntity mapPolyline : mapPolylines) {
MapPolylinePosition mapPolylinePosition = new MapPolylinePosition();
mapPolylinePosition.setName(mapPolyline.getName());
mapPolylinePosition.setPaths(mapPolyline.getPaths());
mapPolylinePosition.setStrokeColor(mapPolyline.getStrokeColor());
mapPolylinePosition.setStrokeOpacity(mapPolyline.getStrokeOpacity());
mapPolylinePosition.setStrokeWeight(mapPolyline.getStrokeWeight());
List<MarkerPositionEntity> positions = new ArrayList<MarkerPositionEntity>();
String[] paths = mapPolyline.getPaths().split(",");
for (String path : paths) {
positions.add(markerPositionRepository.findOne(path));
}
mapPolylinePosition.setPositions(positions);
rtnList.add(mapPolylinePosition);
}
return rtnList;
}
@Override
public List<MapPolygonPosition> queryMapPolygons() throws Exception {
List<MapPolygonPosition> rtnList = new ArrayList<MapPolygonPosition>();
List<MapPolygonEntity> mapPolygons = mapPolygonRepository.findAll();
for (MapPolygonEntity mapPolygon : mapPolygons) {
MapPolygonPosition mapPolygonPosition = new MapPolygonPosition();
mapPolygonPosition.setName(mapPolygon.getName());
mapPolygonPosition.setPaths(mapPolygon.getPaths());
mapPolygonPosition.setStrokeColor(mapPolygon.getStrokeColor());
mapPolygonPosition.setStrokeOpacity(mapPolygon.getStrokeOpacity());
mapPolygonPosition.setStrokeWeight(mapPolygon.getStrokeWeight());
mapPolygonPosition.setFillColor(mapPolygon.getFillColor());
mapPolygonPosition.setFillOpacity(mapPolygon.getFillOpacity());
List<MarkerPositionEntity> positions = new ArrayList<MarkerPositionEntity>();
String[] paths = mapPolygon.getPaths().split(",");
for (String path : paths) {
positions.add(markerPositionRepository.findOne(path));
}
mapPolygonPosition.setPositions(positions);
rtnList.add(mapPolygonPosition);
}
return rtnList;
}
}
| 3,099 | 0.801872 | 0.801872 | 85 | 35.44706 | 27.514063 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.058824 | false | false | 3 |
d87f72473a3a244cd95445a40b3bb47178fd2d3c | 4,406,636,507,390 | 25fe7d83f615ae581339b67c034cd31fa1426030 | /ComicReader/src/com/blogspot/applications4android/comicreader/comics/AGirlandHerFed.java | 0ec88cf5845c09f306f47732b249d6f7c59e60b6 | [
"Apache-2.0"
] | permissive | applications4android/ComicReader | https://github.com/applications4android/ComicReader | 87e2426925aa1cbab3d61e4b51ac193c1a3eeed7 | d553d25345851a9230811afc43fbba0f4fa64864 | refs/heads/master | 2021-07-05T09:49:11.702000 | 2020-08-23T03:23:52 | 2020-08-23T03:23:52 | 5,045,151 | 18 | 13 | NOASSERTION | false | 2020-04-10T06:18:44 | 2012-07-14T06:15:29 | 2018-12-13T07:55:41 | 2020-04-10T06:18:43 | 1,295 | 46 | 28 | 50 | HTML | false | false | package com.blogspot.applications4android.comicreader.comics;
import java.io.BufferedReader;
import java.io.IOException;
import com.blogspot.applications4android.comicreader.comictypes.RandomIndexedComic;
import com.blogspot.applications4android.comicreader.core.Strip;
import com.blogspot.applications4android.comicreader.exceptions.ComicLatestException;
public class AGirlandHerFed extends RandomIndexedComic {
@Override
protected String getFrontPageUrl() {
return "https://agirlandherfed.com/";
}
@Override
public String getComicWebPageUrl() {
return "https://agirlandherfed.com/";
}
@Override
protected int parseForLatestId(BufferedReader reader) throws IOException, ComicLatestException {
String str;
String final_str = null;
while((str = reader.readLine()) != null) {
int index1 = str.indexOf("img/strip/1-");
if (index1 != -1) {
final_str = str;
}
}
if(final_str == null) {
String msg = "Failed to get the latest id for "+this.getClass().getSimpleName();
ComicLatestException e = new ComicLatestException(msg);
throw e;
}
final_str = final_str.replaceAll(".*img/strip/1-","");
final_str = final_str.replaceAll(".jpg.*","");
int finalid = Integer.parseInt(final_str);
return finalid;
}
@Override
public String getStripUrlFromId(int num) {
return "https://agirlandherfed.com/1." + num + ".html";
}
@Override
protected int getIdFromStripUrl(String url) {
String temp = url.replaceAll("https.*/1.", "");
temp = temp.replaceAll(".html", "");
return Integer.parseInt(temp);
}
@Override
protected int parseForPrevId(String line, int def) {
if(line == null) {
return def;
}
return getIdFromStripUrl (line);
}
@Override
protected int parseForNextId(String line, int def) {
if(line == null) {
return def;
}
return getIdFromStripUrl (line);
}
@Override
protected boolean htmlNeeded() {
return true;
}
@Override
protected String parse(String url, BufferedReader reader, Strip strip)
throws IOException {
String str;
String final_str = null;
String final_title = null;
while ((str = reader.readLine()) != null) {
int index1 = str.indexOf("img/strip/1-");
if (index1 != -1) {
final_str = str;
final_title = str;
}
}
final_str = final_str.replaceAll(".*src=\"","");
final_str = final_str.replaceAll("\".*","");
final_title = final_title.replaceAll(".*img/strip/1-","");
final_title = final_title.replaceAll(".jpg.*","");
strip.setTitle("A Girl and Her Fed: 1."+final_title);
strip.setText("-NA-");
return "https://agirlandherfed.com/"+final_str;
}
@Override
protected int getNextStripId(BufferedReader br, String url) {
String str;
try {
while ((str = br.readLine()) != null) {
int i = str.indexOf("next.png");
if (i != -1) {
int i2 = str.lastIndexOf ("href=\"1.", i);
if (i2 != -1) {
i2 += 8;
int i3 = str.indexOf (".html", i2);
if (i3 != -1) {
return Integer.parseInt (str.substring (i2, i3));
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
protected int getPreviousStripId(BufferedReader br, String url) {
String str;
try {
while ((str = br.readLine()) != null) {
int i = str.indexOf("back.png");
if (i != -1) {
int i2 = str.lastIndexOf ("href=\"1.", i);
if (i2 != -1) {
i2 += 8;
int i3 = str.indexOf (".html", i2);
if (i3 != -1) {
return Integer.parseInt (str.substring (i2, i3));
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
protected String getRandUrl() {
// Not implemented.
return getStripUrlFromId (1);
}
}
| UTF-8 | Java | 4,185 | java | AGirlandHerFed.java | Java | [] | null | [] | package com.blogspot.applications4android.comicreader.comics;
import java.io.BufferedReader;
import java.io.IOException;
import com.blogspot.applications4android.comicreader.comictypes.RandomIndexedComic;
import com.blogspot.applications4android.comicreader.core.Strip;
import com.blogspot.applications4android.comicreader.exceptions.ComicLatestException;
public class AGirlandHerFed extends RandomIndexedComic {
@Override
protected String getFrontPageUrl() {
return "https://agirlandherfed.com/";
}
@Override
public String getComicWebPageUrl() {
return "https://agirlandherfed.com/";
}
@Override
protected int parseForLatestId(BufferedReader reader) throws IOException, ComicLatestException {
String str;
String final_str = null;
while((str = reader.readLine()) != null) {
int index1 = str.indexOf("img/strip/1-");
if (index1 != -1) {
final_str = str;
}
}
if(final_str == null) {
String msg = "Failed to get the latest id for "+this.getClass().getSimpleName();
ComicLatestException e = new ComicLatestException(msg);
throw e;
}
final_str = final_str.replaceAll(".*img/strip/1-","");
final_str = final_str.replaceAll(".jpg.*","");
int finalid = Integer.parseInt(final_str);
return finalid;
}
@Override
public String getStripUrlFromId(int num) {
return "https://agirlandherfed.com/1." + num + ".html";
}
@Override
protected int getIdFromStripUrl(String url) {
String temp = url.replaceAll("https.*/1.", "");
temp = temp.replaceAll(".html", "");
return Integer.parseInt(temp);
}
@Override
protected int parseForPrevId(String line, int def) {
if(line == null) {
return def;
}
return getIdFromStripUrl (line);
}
@Override
protected int parseForNextId(String line, int def) {
if(line == null) {
return def;
}
return getIdFromStripUrl (line);
}
@Override
protected boolean htmlNeeded() {
return true;
}
@Override
protected String parse(String url, BufferedReader reader, Strip strip)
throws IOException {
String str;
String final_str = null;
String final_title = null;
while ((str = reader.readLine()) != null) {
int index1 = str.indexOf("img/strip/1-");
if (index1 != -1) {
final_str = str;
final_title = str;
}
}
final_str = final_str.replaceAll(".*src=\"","");
final_str = final_str.replaceAll("\".*","");
final_title = final_title.replaceAll(".*img/strip/1-","");
final_title = final_title.replaceAll(".jpg.*","");
strip.setTitle("A Girl and Her Fed: 1."+final_title);
strip.setText("-NA-");
return "https://agirlandherfed.com/"+final_str;
}
@Override
protected int getNextStripId(BufferedReader br, String url) {
String str;
try {
while ((str = br.readLine()) != null) {
int i = str.indexOf("next.png");
if (i != -1) {
int i2 = str.lastIndexOf ("href=\"1.", i);
if (i2 != -1) {
i2 += 8;
int i3 = str.indexOf (".html", i2);
if (i3 != -1) {
return Integer.parseInt (str.substring (i2, i3));
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
protected int getPreviousStripId(BufferedReader br, String url) {
String str;
try {
while ((str = br.readLine()) != null) {
int i = str.indexOf("back.png");
if (i != -1) {
int i2 = str.lastIndexOf ("href=\"1.", i);
if (i2 != -1) {
i2 += 8;
int i3 = str.indexOf (".html", i2);
if (i3 != -1) {
return Integer.parseInt (str.substring (i2, i3));
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
protected String getRandUrl() {
// Not implemented.
return getStripUrlFromId (1);
}
}
| 4,185 | 0.567742 | 0.55675 | 152 | 26.532894 | 22.111237 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.473684 | false | false | 3 |
c911854d3e58f54b7ca4455ea2475151f0c50ccb | 7,894,149,939,291 | eb617b218686ed426f161e56b1a81532030cccc1 | /test/com/lge/stream/terminal/Main.java | 03b1992e670c33486c3d87a3e98691f9adc686ce | [] | no_license | yjstyle/ajava1911 | https://github.com/yjstyle/ajava1911 | 172c63d1a034789934e1abe5914ac7bdbfcccbaa | 79d1ee7e328cc27d0e6e316542575c59979c198e | refs/heads/master | 2020-09-20T17:18:47.018000 | 2019-11-27T08:13:26 | 2019-11-27T08:13:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lge.stream.terminal;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Random;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.Collector.Characteristics;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class Main {
//@Disabled
@Test
void testCollectorHelperPractice3() {
Stream<Integer> numbers = newIntegerStream();
newIntStream().average();
OptionalDouble od = numbers.collect(
Collector.of(() -> new long[2], (a, i) -> {
a[0] += i;
a[1]++;
}, (a1, a2) -> {
a1[0] += a2[0];
a1[1] += a2[1];
return a1;
}, (l) -> {
return l[1] == 0 ? OptionalDouble.empty()
: OptionalDouble.of(l[0] / l[1]);
}));
od.ifPresent(System.out::println);
/*
*
* (a, i)->{
a[0]+=i;
a[1]++;
}, (a1, a2)->{
a1[0]+=a2[0];
a1[1]+=a2[1];
return a1;
}, (l) -> l[1]==0? OptionalDouble.empty(): l[0]/l[1],
Characteristics.CONCURRENT))
*/
od.ifPresent(System.out::println);
}
@Disabled
@Test
void testCollectorHelperPractice2() {
// Memory Pool로 현재 시스템의 메모리사용량에 대해(getUsed)
// DoubleSummaryStatistics 을 구하세요
List<MemoryPoolMXBean> beans = ManagementFactory
.getMemoryPoolMXBeans();
DoubleSummaryStatistics dss = beans.stream()
.map((MemoryPoolMXBean bean) -> bean.getUsage())
.collect(Collectors.summarizingDouble(
(MemoryUsage t) -> t.getUsed()));
System.out.println(dss);
MemoryUsage usage = beans.get(0).getUsage();
long youngUsedMemory = usage.getUsed();
// {count=8, sum=34289560.000000, min=0.000000,
// average=4286195.000000, max=22020096.000000}
}
@Disabled
@Test
void testCollectorHelperPractice() {
class Customer {
String name;
int points;
Customer(String name, int points) {
this.name = name;
this.points = points;
}
int getPoints() {
return this.points;
}
String getName() {
return this.name;
}
}
List<Customer> customers = List.of(
new Customer("John P.", 15),
new Customer("Sarah M.", 200),
new Customer("Charles B.", 150),
new Customer("Mary T.", 1));
// John P.Sarah M.Charles B.Mary T.
// 366
String seq = customers.stream().map(c -> c.getName())
.collect(Collectors.joining());
System.out.println(seq);
Integer sum = customers.stream().map(c -> c.getPoints())
.reduce(0, (l, r) -> l + r);
}
@Disabled
@Test
void testCollectorHelper() {
List<Integer> lst = newIntegerStream().collect(
Collectors.toCollection(LinkedList<Integer>::new));
newIntegerStream().collect(Collectors.toUnmodifiableList());
Collections.unmodifiableList(
(newIntegerStream().collect(Collectors.toList())));
String str = newIntegerStream().map(String::valueOf)
.collect(Collectors.joining());
System.out.println(str);
DoubleSummaryStatistics s = newIntegerStream().collect(
Collectors.summarizingDouble(Integer::intValue));
System.out.println(s);
}
@Disabled
@Test
void testCollectOf() {
Stream<Integer> s = newIntegerStream();
ArrayList<Integer> lst = s.collect(newListColletor());
// ArrayList<Integer>::new,
// ArrayList::add, ArrayList::addAll
}
static Collector<Integer, ArrayList<Integer>, ArrayList<Integer>> newListColletor() {
return Collector.of(ArrayList<Integer>::new, ArrayList::add,
(l, r) -> {
l.addAll(r);
return l;
});
}
@Disabled
@Test
void testCollect2() {
// ctrl 1
List<Integer> lst = newIntegerStream().collect(
new Collector<Integer, List<Integer>, List<Integer>>() {
@Override
public Supplier<List<Integer>> supplier() {
return LinkedList<Integer>::new;
}
@Override
public BiConsumer<List<Integer>, Integer> accumulator() {
return (lst, t) -> lst.add(t);
}
@Override
public BinaryOperator<List<Integer>> combiner() {
return (l, r) -> {
l.addAll(r);
return l;
};
}
@Override
public Function<List<Integer>, List<Integer>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(
Characteristics.CONCURRENT,
Characteristics.UNORDERED,
Characteristics.IDENTITY_FINISH)
);
}
});
}
@Disabled
@Test
void testCollectPractice() {
// 다음 출력결과를 참고하여 스트림을 HashMap으로 변형하세요
Stream<Integer> numbers = newIntegerStream();
HashMap<Integer, String> map = numbers
.collect(HashMap<Integer, String>::new, (m, t) -> {
m.put(t, "my-value" + t);
}, (m, m2) -> {
m.putAll(m2);
});
System.out.println(map);
// {1:"my-value=1", 2:"my-value=2", 3:"my-value=3"}
List<Integer> lst = newIntegerStream()
.collect(Collectors.toList());
}
@Disabled
@Test
void testCollect() {
Stream<Integer> s = newIntegerStream();
ArrayList<Integer> lst = s.collect(ArrayList<Integer>::new,
ArrayList::add, ArrayList::addAll);
}
@Disabled
@Test
void testReducePractice2() {
// ctrl+ shift+o
List<MemoryPoolMXBean> beans = ManagementFactory
.getMemoryPoolMXBeans();
// Stream<MemoryUsage> m =
// beans.stream().map(bean->bean.getUsage());
long sum = beans.stream().map(bean -> bean.getUsage())
.map(usage -> usage.getUsed()).reduce(0L, Long::sum);
long sum2 = beans.stream().map(bean -> bean.getUsage())
.mapToLong(usage -> usage.getUsed()).sum();
long sum3 = beans.stream().map(MemoryPoolMXBean::getUsage)
.mapToLong(MemoryUsage::getUsed).sum();
// for (MemoryPoolMXBean bean : beans) {
// MemoryUsage usage = bean.getUsage();
// long youngUsedMemory = usage.getUsed();
// sum += youngUsedMemory;
// }
System.out.println(sum);
}
@Disabled
@Test
void testReducePractice() {
// IntStream numbers = newIntStream();
// int sum = numbers.sum();
// System.out.println(sum);
IntStream numbers = newIntStream();
Integer sum = numbers.reduce(0, Integer::sum);
System.out.println(sum);
}
@Disabled
@Test
void testReduce1() {
Stream<Integer> s2 = newIntegerStream();
// Optional<Integer> ret = s2.reduce(Integer::sum);
// Integer ret2 = s2.reduce(0, Integer::sum);
// Integer ret3 = s2.reduce(0, Integer::sum,
// (l, r) -> l + r);
Double ret4 = s2.parallel().reduce(0.0d, (d, i) -> {
System.out.println("a:" + d + "+" + i);
return d + i;
}, (d1, d2) -> {
System.out.println("c:" + d1 + "+" + d2);
return d1 + d2;
});
System.out.println(ret4);
}
OptionalDouble divide(double d) {
return d == 0 ? OptionalDouble.empty()
: OptionalDouble.of(1 / d);
}
@Disabled
@Test
void testTerminalPractice2() {
divide(4).ifPresent(System.out::println);
}
@Disabled
@Test
void testTerminalPractice() {
// ctrl + shift + o
// 다음 주어진 Stream 에서 >0.2인 평균을 구하고, 화면에 출력하세요.
// 단, 데이터가 존재하지 않는 경우 "None" 메시지를 화면에 출력하세요
Random r = new Random();
DoubleStream ds = DoubleStream.generate(r::nextDouble)
.limit(100);
ds.filter(d -> d > 0.2).average().ifPresentOrElse(
System.out::println,
() -> System.out.println("None"));
DoubleStream ds2 = DoubleStream.generate(r::nextDouble)
.limit(0);
ds2.filter(d -> d > 0.2).average().ifPresentOrElse(
System.out::println,
() -> System.out.println("None"));
// 다음 주어진 Stream<Integer> 에서 최대값을 구하세요
// 단, 그 결과 값이 > 23이라면 그 값에 *100을 하여 화면에 출력하세요
// Random r = new Random();
Stream<Integer> s = IntStream.generate(r::nextInt).limit(100)
.boxed();
Optional<Integer> ret2 = s.max(Comparator.naturalOrder());
ret2.filter(i -> i > 23).map(i -> i * 100)
.ifPresent(System.out::println);
}
@Disabled
@Test
void testTerminal2() {
OptionalInt r = newIntStream().findAny();
boolean b = newIntStream().allMatch(i -> i > 0);
}
@Disabled
@Test
void testOptional() {
Optional<Integer> min = newIntegerStream()
.min(Comparator.reverseOrder());
if (min.isPresent()) {
System.out.println(min.get());
}
min.ifPresent(System.out::println);
min.ifPresentOrElse(System.out::println, System.out::println);
min.filter(i -> i > 1).map(String::valueOf)
.ifPresent(System.out::println);
Optional<Integer> op2 = min
.or(() -> Optional.ofNullable(null));
Integer value2 = min.orElse(5);
Integer value = min.orElseGet(() -> 5);
min.orElseThrow(IllegalStateException::new);
}
@Disabled
@Test
void test() {
long cnt = newIntegerStream().count();
Optional<Integer> max = newIntegerStream()
.max(Comparator.naturalOrder());
Optional<Integer> min = newIntegerStream()
.min(Comparator.reverseOrder());
int sum = newIntStream().sum();
OptionalDouble avg = newIntStream().average();
OptionalInt max2 = newIntStream().max();
OptionalInt min2 = newIntStream().min();
}
// CTRL+1
// ctrl+shift+o
IntStream newIntStream() {
return IntStream.of(1, 2, 3);
};
Stream<Integer> newIntegerStream() {
return newIntStream().boxed();
};
}
| UHC | Java | 10,264 | java | Main.java | Java | [
{
"context": "Customer> customers = List.of(\r\n\t\t\t\tnew Customer(\"John P.\", 15),\r\n\t\t\t\tnew Customer(\"Sarah M.\", 200),\r\n\t\t\t\tnew",
"end": 2835,
"score": 0.9988696575164795,
"start": 2829,
"tag": "NAME",
"value": "John P"
},
{
"context": "\t\tnew Customer(\"John P.\",... | null | [] | package com.lge.stream.terminal;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Random;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.Collector.Characteristics;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class Main {
//@Disabled
@Test
void testCollectorHelperPractice3() {
Stream<Integer> numbers = newIntegerStream();
newIntStream().average();
OptionalDouble od = numbers.collect(
Collector.of(() -> new long[2], (a, i) -> {
a[0] += i;
a[1]++;
}, (a1, a2) -> {
a1[0] += a2[0];
a1[1] += a2[1];
return a1;
}, (l) -> {
return l[1] == 0 ? OptionalDouble.empty()
: OptionalDouble.of(l[0] / l[1]);
}));
od.ifPresent(System.out::println);
/*
*
* (a, i)->{
a[0]+=i;
a[1]++;
}, (a1, a2)->{
a1[0]+=a2[0];
a1[1]+=a2[1];
return a1;
}, (l) -> l[1]==0? OptionalDouble.empty(): l[0]/l[1],
Characteristics.CONCURRENT))
*/
od.ifPresent(System.out::println);
}
@Disabled
@Test
void testCollectorHelperPractice2() {
// Memory Pool로 현재 시스템의 메모리사용량에 대해(getUsed)
// DoubleSummaryStatistics 을 구하세요
List<MemoryPoolMXBean> beans = ManagementFactory
.getMemoryPoolMXBeans();
DoubleSummaryStatistics dss = beans.stream()
.map((MemoryPoolMXBean bean) -> bean.getUsage())
.collect(Collectors.summarizingDouble(
(MemoryUsage t) -> t.getUsed()));
System.out.println(dss);
MemoryUsage usage = beans.get(0).getUsage();
long youngUsedMemory = usage.getUsed();
// {count=8, sum=34289560.000000, min=0.000000,
// average=4286195.000000, max=22020096.000000}
}
@Disabled
@Test
void testCollectorHelperPractice() {
class Customer {
String name;
int points;
Customer(String name, int points) {
this.name = name;
this.points = points;
}
int getPoints() {
return this.points;
}
String getName() {
return this.name;
}
}
List<Customer> customers = List.of(
new Customer("<NAME>.", 15),
new Customer("<NAME>.", 200),
new Customer("<NAME>.", 150),
new Customer("<NAME>.", 1));
// <NAME>.<NAME>.<NAME>.<NAME>.
// 366
String seq = customers.stream().map(c -> c.getName())
.collect(Collectors.joining());
System.out.println(seq);
Integer sum = customers.stream().map(c -> c.getPoints())
.reduce(0, (l, r) -> l + r);
}
@Disabled
@Test
void testCollectorHelper() {
List<Integer> lst = newIntegerStream().collect(
Collectors.toCollection(LinkedList<Integer>::new));
newIntegerStream().collect(Collectors.toUnmodifiableList());
Collections.unmodifiableList(
(newIntegerStream().collect(Collectors.toList())));
String str = newIntegerStream().map(String::valueOf)
.collect(Collectors.joining());
System.out.println(str);
DoubleSummaryStatistics s = newIntegerStream().collect(
Collectors.summarizingDouble(Integer::intValue));
System.out.println(s);
}
@Disabled
@Test
void testCollectOf() {
Stream<Integer> s = newIntegerStream();
ArrayList<Integer> lst = s.collect(newListColletor());
// ArrayList<Integer>::new,
// ArrayList::add, ArrayList::addAll
}
static Collector<Integer, ArrayList<Integer>, ArrayList<Integer>> newListColletor() {
return Collector.of(ArrayList<Integer>::new, ArrayList::add,
(l, r) -> {
l.addAll(r);
return l;
});
}
@Disabled
@Test
void testCollect2() {
// ctrl 1
List<Integer> lst = newIntegerStream().collect(
new Collector<Integer, List<Integer>, List<Integer>>() {
@Override
public Supplier<List<Integer>> supplier() {
return LinkedList<Integer>::new;
}
@Override
public BiConsumer<List<Integer>, Integer> accumulator() {
return (lst, t) -> lst.add(t);
}
@Override
public BinaryOperator<List<Integer>> combiner() {
return (l, r) -> {
l.addAll(r);
return l;
};
}
@Override
public Function<List<Integer>, List<Integer>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(
Characteristics.CONCURRENT,
Characteristics.UNORDERED,
Characteristics.IDENTITY_FINISH)
);
}
});
}
@Disabled
@Test
void testCollectPractice() {
// 다음 출력결과를 참고하여 스트림을 HashMap으로 변형하세요
Stream<Integer> numbers = newIntegerStream();
HashMap<Integer, String> map = numbers
.collect(HashMap<Integer, String>::new, (m, t) -> {
m.put(t, "my-value" + t);
}, (m, m2) -> {
m.putAll(m2);
});
System.out.println(map);
// {1:"my-value=1", 2:"my-value=2", 3:"my-value=3"}
List<Integer> lst = newIntegerStream()
.collect(Collectors.toList());
}
@Disabled
@Test
void testCollect() {
Stream<Integer> s = newIntegerStream();
ArrayList<Integer> lst = s.collect(ArrayList<Integer>::new,
ArrayList::add, ArrayList::addAll);
}
@Disabled
@Test
void testReducePractice2() {
// ctrl+ shift+o
List<MemoryPoolMXBean> beans = ManagementFactory
.getMemoryPoolMXBeans();
// Stream<MemoryUsage> m =
// beans.stream().map(bean->bean.getUsage());
long sum = beans.stream().map(bean -> bean.getUsage())
.map(usage -> usage.getUsed()).reduce(0L, Long::sum);
long sum2 = beans.stream().map(bean -> bean.getUsage())
.mapToLong(usage -> usage.getUsed()).sum();
long sum3 = beans.stream().map(MemoryPoolMXBean::getUsage)
.mapToLong(MemoryUsage::getUsed).sum();
// for (MemoryPoolMXBean bean : beans) {
// MemoryUsage usage = bean.getUsage();
// long youngUsedMemory = usage.getUsed();
// sum += youngUsedMemory;
// }
System.out.println(sum);
}
@Disabled
@Test
void testReducePractice() {
// IntStream numbers = newIntStream();
// int sum = numbers.sum();
// System.out.println(sum);
IntStream numbers = newIntStream();
Integer sum = numbers.reduce(0, Integer::sum);
System.out.println(sum);
}
@Disabled
@Test
void testReduce1() {
Stream<Integer> s2 = newIntegerStream();
// Optional<Integer> ret = s2.reduce(Integer::sum);
// Integer ret2 = s2.reduce(0, Integer::sum);
// Integer ret3 = s2.reduce(0, Integer::sum,
// (l, r) -> l + r);
Double ret4 = s2.parallel().reduce(0.0d, (d, i) -> {
System.out.println("a:" + d + "+" + i);
return d + i;
}, (d1, d2) -> {
System.out.println("c:" + d1 + "+" + d2);
return d1 + d2;
});
System.out.println(ret4);
}
OptionalDouble divide(double d) {
return d == 0 ? OptionalDouble.empty()
: OptionalDouble.of(1 / d);
}
@Disabled
@Test
void testTerminalPractice2() {
divide(4).ifPresent(System.out::println);
}
@Disabled
@Test
void testTerminalPractice() {
// ctrl + shift + o
// 다음 주어진 Stream 에서 >0.2인 평균을 구하고, 화면에 출력하세요.
// 단, 데이터가 존재하지 않는 경우 "None" 메시지를 화면에 출력하세요
Random r = new Random();
DoubleStream ds = DoubleStream.generate(r::nextDouble)
.limit(100);
ds.filter(d -> d > 0.2).average().ifPresentOrElse(
System.out::println,
() -> System.out.println("None"));
DoubleStream ds2 = DoubleStream.generate(r::nextDouble)
.limit(0);
ds2.filter(d -> d > 0.2).average().ifPresentOrElse(
System.out::println,
() -> System.out.println("None"));
// 다음 주어진 Stream<Integer> 에서 최대값을 구하세요
// 단, 그 결과 값이 > 23이라면 그 값에 *100을 하여 화면에 출력하세요
// Random r = new Random();
Stream<Integer> s = IntStream.generate(r::nextInt).limit(100)
.boxed();
Optional<Integer> ret2 = s.max(Comparator.naturalOrder());
ret2.filter(i -> i > 23).map(i -> i * 100)
.ifPresent(System.out::println);
}
@Disabled
@Test
void testTerminal2() {
OptionalInt r = newIntStream().findAny();
boolean b = newIntStream().allMatch(i -> i > 0);
}
@Disabled
@Test
void testOptional() {
Optional<Integer> min = newIntegerStream()
.min(Comparator.reverseOrder());
if (min.isPresent()) {
System.out.println(min.get());
}
min.ifPresent(System.out::println);
min.ifPresentOrElse(System.out::println, System.out::println);
min.filter(i -> i > 1).map(String::valueOf)
.ifPresent(System.out::println);
Optional<Integer> op2 = min
.or(() -> Optional.ofNullable(null));
Integer value2 = min.orElse(5);
Integer value = min.orElseGet(() -> 5);
min.orElseThrow(IllegalStateException::new);
}
@Disabled
@Test
void test() {
long cnt = newIntegerStream().count();
Optional<Integer> max = newIntegerStream()
.max(Comparator.naturalOrder());
Optional<Integer> min = newIntegerStream()
.min(Comparator.reverseOrder());
int sum = newIntStream().sum();
OptionalDouble avg = newIntStream().average();
OptionalInt max2 = newIntStream().max();
OptionalInt min2 = newIntStream().min();
}
// CTRL+1
// ctrl+shift+o
IntStream newIntStream() {
return IntStream.of(1, 2, 3);
};
Stream<Integer> newIntegerStream() {
return newIntStream().boxed();
};
}
| 10,256 | 0.629596 | 0.611711 | 389 | 23.727507 | 18.975773 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.532134 | false | false | 3 |
39d56c646aa317d3428ca689a2a297a8e10887a1 | 29,162,827,940,911 | 4ef537b7f01e3435b16de10d28c25e52a7be505b | /src/main/java/net/teamcarbon/carboncards/utils/Config.java | e49b3d273639558d9614f1d3b2d47ff23ecf7e26 | [] | no_license | Team-Carbon/CarbonCards | https://github.com/Team-Carbon/CarbonCards | 36cc340bf73eeed910d2d5038ce3fe6fab3633b3 | e44abf8c192150e33df3f26a86469d03862ee260 | refs/heads/master | 2017-12-02T19:33:29.086000 | 2017-04-02T21:02:46 | 2017-04-02T21:02:46 | 85,488,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) Luther Langford
* This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
* http://creativecommons.org/licenses/by-nc/4.0/
*/
package net.teamcarbon.carboncards.utils;
import net.milkbowl.vault.item.Items;
import net.teamcarbon.carboncards.CarbonCards;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Config {
public enum ColorType {
DESCRIPTION("cards.description-color", 'e'),
COMMON_PRE("cards.rarity-colors.common", 'f'),
UNCOMMON_PRE("cards.rarity-colors.uncommon", 'a'),
RARE_PRE("cards.rarity-colors.rare", '9'),
LEGENDARY_PRE("cards.rarity-colors.legendary", '5'),
LIMITED_PRE("cards.rarity-colors.limited", '6');
private String p;
private char d;
ColorType(String path, char def) {
p = path;
d = def;
}
public String path() { return p; }
public char code() { return d; }
}
public static final Enchantment SHINY = Enchantment.ARROW_INFINITE,
DECK = Enchantment.BINDING_CURSE,
PACK = Enchantment.LUCK;
public static final int SHINY_LEVEL = 5,
DECK_LEVEL = 6,
PACK_LEVEL = 7,
BAR_SEGMENTS = 20, // Progress bar segments in series lists
LINES_PER_PAGE = 4; // Lines per page of series list
public static final char PROG_BAR_FULL = '\u28FF',
PROG_BAR_EMPTY = '\u2800',
BALLOT_TICKED = '\u2617',
BALLOT_EMPTY = '\u2616';
private static CarbonCards plugin;
private static File cardDataFile;
private static FileConfiguration cardData;
public Config(CarbonCards plugin) {
Config.plugin = plugin;
saveDefaultConfig();
reloadConfig();
cardDataFile = new File(Config.plugin.getDataFolder(), "cards.yml");
saveDefaultCards();
reloadCards();
reloadPacks();
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { public void run() { reloadDecks(); } }, 10L); // Run later to prevent issues with Vault perms
}
private static void saveDefaultConfig() { plugin.saveDefaultConfig(); }
private static void saveDefaultCards() {
if (!cardDataFile.exists()) { plugin.saveResource("cards.yml", false); }
}
private static ItemStack resolveItem(String item, Material defMat, Short defSub) {
String matName = item.contains(":") ? item.split(":")[0] : item;
short sub = item.contains(":") ? Short.valueOf(item.split(":")[1]) : defSub;
Material mat = Items.itemByName(matName).material;
if (mat == null) mat = defMat;
ItemStack is = new ItemStack(mat);
is.setDurability(sub);
return is;
}
public static void saveConfig() { plugin.saveConfig(); }
public static void saveCards() {
try {
cardData.save(cardDataFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void reloadConfig() {
plugin.reloadConfig();
}
public static void reloadCards() {
cardData = YamlConfiguration.loadConfiguration(cardDataFile);
Card.flushCards();
for (Card.Rarity r : Card.Rarity.values()) {
if (!cardData.contains(r.name().toLowerCase())) continue;
for (String card : cardData.getConfigurationSection(r.name().toLowerCase()).getKeys(false)) {
new Card(card, r);
}
}
}
public static void reloadDecks() {
Deck.flushDecks();
for (Player p : plugin.getServer().getOnlinePlayers()) { new Deck(plugin, p); }
}
public static void reloadPacks() {
Pack.flushPacks();
for (String packName : Config.conf().getConfigurationSection("packs.packs").getKeys(false)) {
try { new Pack(packName); } catch (IllegalStateException e) {
CarbonCards.errorPrint("Tried to load pack: " + packName + ", but it's already loaded.");
} catch (IllegalArgumentException e) {
CarbonCards.errorPrint("Tried to load pack: " + packName + ", but it couldn't be found in the config.");
}
}
}
public static void reloadAll() {
reloadConfig();
reloadCards();
reloadPacks();
}
public static FileConfiguration conf() { return plugin.getConfig(); }
public static FileConfiguration getCards() { return cardData; }
public static boolean isDebug() { return conf().getBoolean("general.debug-output", false); }
public static ItemStack getCardItem() {
ItemStack is = resolveItem(conf().getString("cards.item-material", "paper"), Material.PAPER, (short)0);
ItemMeta im = is.getItemMeta();
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getDeckItem() {
ItemStack is = resolveItem(conf().getString("decks.item-material", "book"), Material.BOOK, (short)0);
is.addUnsafeEnchantment(DECK, DECK_LEVEL);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.DECK_KEY + ChatColor.GOLD + "Deck Binder");
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&5Right-click to open your deck binder"));
lore.add(CarbonCards.trans("&7Cards are not bound to this book."));
lore.add(CarbonCards.trans("&7If you lose this book, craft another!"));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getPackItem() {
ItemStack is = resolveItem(conf().getString("packs.item-material", "enchanted_book"), Material.ENCHANTED_BOOK, (short)0);
is.addUnsafeEnchantment(PACK, PACK_LEVEL);
ItemMeta im = is.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&5Right-click to open this pack!"));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static boolean isShinyCardItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return itemMeta.hasEnchant(SHINY) && itemMeta.getEnchantLevel(SHINY) == SHINY_LEVEL;
}
public static boolean isCardItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& item.getItemMeta().getDisplayName().startsWith(CarbonCards.CARD_KEY)
&& getCardItem().getType() == item.getType() && getCardItem().getDurability() == item.getDurability();
}
public static boolean isDeckItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& itemMeta.getDisplayName().equals(getDeckItem().getItemMeta().getDisplayName())
&& getDeckItem().getType() == item.getType()
&& getDeckItem().getDurability() == item.getDurability()
&& itemMeta.hasEnchant(DECK) && itemMeta.getEnchantLevel(DECK) == DECK_LEVEL;
}
public static boolean isPackItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& getPackItem().getType() == item.getType()
&& item.getItemMeta().getDisplayName().startsWith(CarbonCards.PACK_KEY)
&& getPackItem().getDurability() == item.getDurability()
&& itemMeta.hasEnchant(PACK) && itemMeta.getEnchantLevel(PACK) == PACK_LEVEL;
}
public static ItemStack getPagePrevItem(int curPage) {
ItemStack is = resolveItem(
Config.conf().getString("decks.page-prev-item", "stained_glass_pane:5"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&5Page &d" + (curPage-1)));
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getPageNextItem(int curPage) {
ItemStack is = resolveItem(
Config.conf().getString("decks.page-next-item", "stained_glass_pane:1"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&5Page &d" + (curPage+1)));
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getSpacerItem(OfflinePlayer player) {
ItemStack is = resolveItem(
Config.conf().getString("decks.spacer-item", "stained_glass_pane:15"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&d" + player.getName() + "'s &5Deck"));
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&8" + player.getUniqueId().toString()));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ChatColor getColor(ColorType ct) {
String color = conf().getString(ct.path(), ct.code() + "");
return ChatColor.getByChar(color.charAt(0));
}
public static ChatColor getRarityColor(Card.Rarity r) {
switch (r) {
case COMMON: return getColor(ColorType.COMMON_PRE);
case UNCOMMON: return getColor(ColorType.UNCOMMON_PRE);
case RARE: return getColor(ColorType.RARE_PRE);
case LEGENDARY: return getColor(ColorType.LEGENDARY_PRE);
case LIMITED: return getColor(ColorType.LIMITED_PRE);
}
return null;
}
public static List<String> getAllSeries() {
List<String> series = new ArrayList<>();
if (conf().contains("series")) series.addAll(conf().getConfigurationSection("series").getKeys(false));
return series;
}
public static Card.Rarity getRankRarity(String rank) {
Card.Rarity rarity = Card.Rarity.COMMON;
for (String r : Config.conf().getConfigurationSection("general.player-card-rank-rarity").getKeys(false)) {
if (rank.equalsIgnoreCase(r)) {
try {
rarity = Card.Rarity.valueOf(Config.conf().getString("general.player-card-rank-rarity." + rank, "common").toUpperCase(Locale.ENGLISH));
} catch (Exception ignore) {}
}
}
return rarity;
}
public static void setSeriesRewardItems(String s, List<ItemStack> i) {
s = CarbonCards.stripAlt(s);
conf().set("series." + s + ".reward.items", i);
saveConfig();
}
public static Reward getSeriesReward(String s) {
s = correctSeriesName(s);
if (seriesHasReward(s)) {
String path = "series." + s + ".reward.";
double m = 0D;
List<ItemStack> i = new ArrayList<>();
if (conf().contains(path + "money")) { m = conf().getDouble(path + "money", 0D); }
if (conf().contains(path + "items") && conf().isList(path + "items")) {
Object itemsObj = conf().get(path + "items");
if (itemsObj instanceof List) {
List itemsList = (List) itemsObj;
for (Object o : itemsList) { if (o instanceof ItemStack) { i.add((ItemStack) o); } }
}
}
return new Reward(plugin, m, i);
}
return null;
}
public static boolean seriesHasReward(String s) {
s = correctSeriesName(s);
String path = "series." + s + ".reward.";
return conf().contains("series." + s + ".reward")
&& (conf().getDouble(path + "money") > 0D || conf().isList(path + "items"));
}
public static ChatColor seriesColor(String s) {
s = correctSeriesName(s);
if (conf().contains("series." + s)) {
String color = conf().getString("series." + s + ".color", "");
return ChatColor.getByChar(color.charAt(0));
}
return null;
}
public static String seriesTitle(String s) {
s = correctSeriesName(s);
if (conf().contains("series." + s)) { return conf().getString("series." + s + ".title", ""); }
return "";
}
public static String correctSeriesName(String s) {
s = CarbonCards.stripAlt(s).toLowerCase(Locale.ENGLISH);
if (!conf().contains("series." + s)) {
for (String key : conf().getConfigurationSection("series").getKeys(false)) {
if (key.equalsIgnoreCase(s)) { return key; }
}
}
return s;
}
}
| UTF-8 | Java | 11,940 | java | Config.java | Java | [
{
"context": "/*\n * Copyright (c) Luther Langford\n * This work is licensed under a Creative Commons",
"end": 35,
"score": 0.9998481869697571,
"start": 20,
"tag": "NAME",
"value": "Luther Langford"
}
] | null | [] | /*
* Copyright (c) <NAME>
* This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
* http://creativecommons.org/licenses/by-nc/4.0/
*/
package net.teamcarbon.carboncards.utils;
import net.milkbowl.vault.item.Items;
import net.teamcarbon.carboncards.CarbonCards;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class Config {
public enum ColorType {
DESCRIPTION("cards.description-color", 'e'),
COMMON_PRE("cards.rarity-colors.common", 'f'),
UNCOMMON_PRE("cards.rarity-colors.uncommon", 'a'),
RARE_PRE("cards.rarity-colors.rare", '9'),
LEGENDARY_PRE("cards.rarity-colors.legendary", '5'),
LIMITED_PRE("cards.rarity-colors.limited", '6');
private String p;
private char d;
ColorType(String path, char def) {
p = path;
d = def;
}
public String path() { return p; }
public char code() { return d; }
}
public static final Enchantment SHINY = Enchantment.ARROW_INFINITE,
DECK = Enchantment.BINDING_CURSE,
PACK = Enchantment.LUCK;
public static final int SHINY_LEVEL = 5,
DECK_LEVEL = 6,
PACK_LEVEL = 7,
BAR_SEGMENTS = 20, // Progress bar segments in series lists
LINES_PER_PAGE = 4; // Lines per page of series list
public static final char PROG_BAR_FULL = '\u28FF',
PROG_BAR_EMPTY = '\u2800',
BALLOT_TICKED = '\u2617',
BALLOT_EMPTY = '\u2616';
private static CarbonCards plugin;
private static File cardDataFile;
private static FileConfiguration cardData;
public Config(CarbonCards plugin) {
Config.plugin = plugin;
saveDefaultConfig();
reloadConfig();
cardDataFile = new File(Config.plugin.getDataFolder(), "cards.yml");
saveDefaultCards();
reloadCards();
reloadPacks();
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { public void run() { reloadDecks(); } }, 10L); // Run later to prevent issues with Vault perms
}
private static void saveDefaultConfig() { plugin.saveDefaultConfig(); }
private static void saveDefaultCards() {
if (!cardDataFile.exists()) { plugin.saveResource("cards.yml", false); }
}
private static ItemStack resolveItem(String item, Material defMat, Short defSub) {
String matName = item.contains(":") ? item.split(":")[0] : item;
short sub = item.contains(":") ? Short.valueOf(item.split(":")[1]) : defSub;
Material mat = Items.itemByName(matName).material;
if (mat == null) mat = defMat;
ItemStack is = new ItemStack(mat);
is.setDurability(sub);
return is;
}
public static void saveConfig() { plugin.saveConfig(); }
public static void saveCards() {
try {
cardData.save(cardDataFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void reloadConfig() {
plugin.reloadConfig();
}
public static void reloadCards() {
cardData = YamlConfiguration.loadConfiguration(cardDataFile);
Card.flushCards();
for (Card.Rarity r : Card.Rarity.values()) {
if (!cardData.contains(r.name().toLowerCase())) continue;
for (String card : cardData.getConfigurationSection(r.name().toLowerCase()).getKeys(false)) {
new Card(card, r);
}
}
}
public static void reloadDecks() {
Deck.flushDecks();
for (Player p : plugin.getServer().getOnlinePlayers()) { new Deck(plugin, p); }
}
public static void reloadPacks() {
Pack.flushPacks();
for (String packName : Config.conf().getConfigurationSection("packs.packs").getKeys(false)) {
try { new Pack(packName); } catch (IllegalStateException e) {
CarbonCards.errorPrint("Tried to load pack: " + packName + ", but it's already loaded.");
} catch (IllegalArgumentException e) {
CarbonCards.errorPrint("Tried to load pack: " + packName + ", but it couldn't be found in the config.");
}
}
}
public static void reloadAll() {
reloadConfig();
reloadCards();
reloadPacks();
}
public static FileConfiguration conf() { return plugin.getConfig(); }
public static FileConfiguration getCards() { return cardData; }
public static boolean isDebug() { return conf().getBoolean("general.debug-output", false); }
public static ItemStack getCardItem() {
ItemStack is = resolveItem(conf().getString("cards.item-material", "paper"), Material.PAPER, (short)0);
ItemMeta im = is.getItemMeta();
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getDeckItem() {
ItemStack is = resolveItem(conf().getString("decks.item-material", "book"), Material.BOOK, (short)0);
is.addUnsafeEnchantment(DECK, DECK_LEVEL);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.DECK_KEY + ChatColor.GOLD + "Deck Binder");
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&5Right-click to open your deck binder"));
lore.add(CarbonCards.trans("&7Cards are not bound to this book."));
lore.add(CarbonCards.trans("&7If you lose this book, craft another!"));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getPackItem() {
ItemStack is = resolveItem(conf().getString("packs.item-material", "enchanted_book"), Material.ENCHANTED_BOOK, (short)0);
is.addUnsafeEnchantment(PACK, PACK_LEVEL);
ItemMeta im = is.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&5Right-click to open this pack!"));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static boolean isShinyCardItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return itemMeta.hasEnchant(SHINY) && itemMeta.getEnchantLevel(SHINY) == SHINY_LEVEL;
}
public static boolean isCardItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& item.getItemMeta().getDisplayName().startsWith(CarbonCards.CARD_KEY)
&& getCardItem().getType() == item.getType() && getCardItem().getDurability() == item.getDurability();
}
public static boolean isDeckItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& itemMeta.getDisplayName().equals(getDeckItem().getItemMeta().getDisplayName())
&& getDeckItem().getType() == item.getType()
&& getDeckItem().getDurability() == item.getDurability()
&& itemMeta.hasEnchant(DECK) && itemMeta.getEnchantLevel(DECK) == DECK_LEVEL;
}
public static boolean isPackItem(ItemStack item) {
if (item == null) return false;
ItemMeta itemMeta = item.getItemMeta();
return !(itemMeta == null || itemMeta.getDisplayName() == null)
&& getPackItem().getType() == item.getType()
&& item.getItemMeta().getDisplayName().startsWith(CarbonCards.PACK_KEY)
&& getPackItem().getDurability() == item.getDurability()
&& itemMeta.hasEnchant(PACK) && itemMeta.getEnchantLevel(PACK) == PACK_LEVEL;
}
public static ItemStack getPagePrevItem(int curPage) {
ItemStack is = resolveItem(
Config.conf().getString("decks.page-prev-item", "stained_glass_pane:5"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&5Page &d" + (curPage-1)));
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getPageNextItem(int curPage) {
ItemStack is = resolveItem(
Config.conf().getString("decks.page-next-item", "stained_glass_pane:1"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&5Page &d" + (curPage+1)));
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ItemStack getSpacerItem(OfflinePlayer player) {
ItemStack is = resolveItem(
Config.conf().getString("decks.spacer-item", "stained_glass_pane:15"),
Material.STAINED_GLASS_PANE,
(short)0
);
ItemMeta im = is.getItemMeta();
im.setDisplayName(CarbonCards.trans("&d" + player.getName() + "'s &5Deck"));
List<String> lore = new ArrayList<>();
lore.add(CarbonCards.trans("&8" + player.getUniqueId().toString()));
im.setLore(lore);
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
is.setItemMeta(im);
return is;
}
public static ChatColor getColor(ColorType ct) {
String color = conf().getString(ct.path(), ct.code() + "");
return ChatColor.getByChar(color.charAt(0));
}
public static ChatColor getRarityColor(Card.Rarity r) {
switch (r) {
case COMMON: return getColor(ColorType.COMMON_PRE);
case UNCOMMON: return getColor(ColorType.UNCOMMON_PRE);
case RARE: return getColor(ColorType.RARE_PRE);
case LEGENDARY: return getColor(ColorType.LEGENDARY_PRE);
case LIMITED: return getColor(ColorType.LIMITED_PRE);
}
return null;
}
public static List<String> getAllSeries() {
List<String> series = new ArrayList<>();
if (conf().contains("series")) series.addAll(conf().getConfigurationSection("series").getKeys(false));
return series;
}
public static Card.Rarity getRankRarity(String rank) {
Card.Rarity rarity = Card.Rarity.COMMON;
for (String r : Config.conf().getConfigurationSection("general.player-card-rank-rarity").getKeys(false)) {
if (rank.equalsIgnoreCase(r)) {
try {
rarity = Card.Rarity.valueOf(Config.conf().getString("general.player-card-rank-rarity." + rank, "common").toUpperCase(Locale.ENGLISH));
} catch (Exception ignore) {}
}
}
return rarity;
}
public static void setSeriesRewardItems(String s, List<ItemStack> i) {
s = CarbonCards.stripAlt(s);
conf().set("series." + s + ".reward.items", i);
saveConfig();
}
public static Reward getSeriesReward(String s) {
s = correctSeriesName(s);
if (seriesHasReward(s)) {
String path = "series." + s + ".reward.";
double m = 0D;
List<ItemStack> i = new ArrayList<>();
if (conf().contains(path + "money")) { m = conf().getDouble(path + "money", 0D); }
if (conf().contains(path + "items") && conf().isList(path + "items")) {
Object itemsObj = conf().get(path + "items");
if (itemsObj instanceof List) {
List itemsList = (List) itemsObj;
for (Object o : itemsList) { if (o instanceof ItemStack) { i.add((ItemStack) o); } }
}
}
return new Reward(plugin, m, i);
}
return null;
}
public static boolean seriesHasReward(String s) {
s = correctSeriesName(s);
String path = "series." + s + ".reward.";
return conf().contains("series." + s + ".reward")
&& (conf().getDouble(path + "money") > 0D || conf().isList(path + "items"));
}
public static ChatColor seriesColor(String s) {
s = correctSeriesName(s);
if (conf().contains("series." + s)) {
String color = conf().getString("series." + s + ".color", "");
return ChatColor.getByChar(color.charAt(0));
}
return null;
}
public static String seriesTitle(String s) {
s = correctSeriesName(s);
if (conf().contains("series." + s)) { return conf().getString("series." + s + ".title", ""); }
return "";
}
public static String correctSeriesName(String s) {
s = CarbonCards.stripAlt(s).toLowerCase(Locale.ENGLISH);
if (!conf().contains("series." + s)) {
for (String key : conf().getConfigurationSection("series").getKeys(false)) {
if (key.equalsIgnoreCase(s)) { return key; }
}
}
return s;
}
}
| 11,931 | 0.696901 | 0.692211 | 351 | 33.017094 | 29.081177 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.373219 | false | false | 3 |
4a3f0ecf7116a775312709c2f6ce4895290ba767 | 14,422,500,207,428 | 8998141cf961012205f769cb86f058e5beece99e | /src/main/java/com/mpc/merchant/helper/ConnectionHelper.java | 651432dea29081dc7132658c98400996eb8e8f48 | [] | no_license | dans5200/merchant-management | https://github.com/dans5200/merchant-management | 6b4c52665584e8cda8ecd0b21e22439e8c0846e8 | f16ae8b91948d6bfb2c29610c6bc20cd8b1501c3 | refs/heads/master | 2020-12-05T21:15:29.449000 | 2020-01-21T04:08:12 | 2020-01-21T04:08:12 | 232,250,371 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mpc.merchant.helper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class ConnectionHelper {
private Connection connection = null;
private PropertiesHelper applicationProperties = new PropertiesHelper("application.properties");
private Logger log = LogManager.getLogger(getClass());
private String select = "*";
private String tableName = "";
private String where = "where ";
private List<Object> param = new ArrayList<>();
public ConnectionHelper() {
connection = setConnection();
}
public Connection setConnection(){
try {
Class.forName(applicationProperties.getPropertis("spring.datasource.driver-class-name"));
this.connection = DriverManager.getConnection(
applicationProperties.getPropertis("spring.datasource.url"),
applicationProperties.getPropertis("spring.datasource.username"),
applicationProperties.getPropertis("spring.datasource.password")
);
}catch (Exception e){
log.error(e);
}
return connection;
}
private ResultSet executeQuery(String sql){
ResultSet resultSet = null;
try {
Statement statement = (Statement) connection.createStatement();
resultSet = statement.executeQuery(sql);
} catch (Exception e) {
log.error(e);
}
return resultSet;
}
private ResultSet executeQuery(String sql, List<Object> params){
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
Integer i = 1;
for (Object param : params) {
preparedStatement.setObject(i, param);
i++;
}
resultSet = preparedStatement.executeQuery();
} catch (Exception e) {
log.error(e);
}
return resultSet;
}
private Integer executeUpdate(String sql){
Integer status = null;
try {
Statement statement = (Statement) connection.createStatement();
status = statement.executeUpdate(sql);
} catch (Exception e) {
log.error(e);
}
return status;
}
private Integer executeUpdate(String sql, List<Object> params){
Integer status = null;
try {
PreparedStatement statement = connection.prepareStatement(sql);
Integer i = 1;
for (Object param : params) {
statement.setObject(i, param);
i++;
}
status = statement.executeUpdate();
} catch (Exception e) {
log.error(e);
}
return status;
}
public Object save(Object object){
try{
param = new ArrayList<>();
StringHelper stringHelper = new StringHelper();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(object, Map.class);
String sql = "insert into "+ stringHelper.strConvertCU(object.getClass().getSimpleName());
String field = "(";
String values = " values(";
for (Map.Entry<String, Object> mapObj : map.entrySet()){
field += stringHelper.strConvertCU(mapObj.getKey())+",";
values += "?,";
if (mapObj.getValue() instanceof String) {
param.add(mapObj.getValue());
}else if (mapObj.getValue() instanceof Long){
param.add( new DateFormaterHelper().timestampToDB( new Timestamp((Long) mapObj.getValue()) ) );
}else{
param.add(mapObj.getValue());
}
}
field += ")";
values += ")";
field = field.replace(",)",")");
values = values.replace(",)",")");
sql = sql+field+values;
log.debug("Query: "+sql);
log.debug("Param: "+param);
this.executeUpdate(sql,param);
}catch (Exception e){
log.error(e);
}
return object;
}
public ConnectionHelper select(String select){
this.select = select;
return this;
}
public ConnectionHelper table(String tableName){
this.tableName = tableName;
return this;
}
public ConnectionHelper where(String field, Object value){
if (value instanceof String){
this.where += field+"=? and ";
}else{
this.where += field+"=? and ";
}
param.add(value);
return this;
}
public ConnectionHelper where(String field, String operator, Object value){
if (value instanceof String){
this.where += field+" "+operator+" ? and ";
}else{
this.where += field+" "+operator+" ? and ";
}
param.add(value);
return this;
}
public ConnectionHelper whereDateBetween(String date, Integer dateIncrease){
return this;
}
public ConnectionHelper findBy(Map<String, Object> findValue){
StringHelper stringHelper = new StringHelper();
param = new ArrayList<>();
try {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(findValue, Map.class);
where += "(";
for (Map.Entry<String, Object> mapObj : map.entrySet()){
where += stringHelper.strConvertCU(mapObj.getKey()) +" like ? or ";
param.add("%"+mapObj.getValue()+"%");
}
where += ")";
where = where.replace("or )",") and ");
}catch (Exception e){
log.error(e);
}
return this;
}
public ResultSet first(){
ResultSet resultSet = null;
String sql = "";
try{
if (where.equals("where ")){
sql = "select "+this.select+" from "+this.tableName+" limit 1";
}else{
sql = "select "+this.select+" from "+this.tableName+" "+this.where+"= limit 1";
// sql = this.select+this.where+"= limit 1";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet get(){
ResultSet resultSet = null;
String sql = "";
try{
if (where.equals("where ")){
// sql = this.select;
sql = "select "+this.select+" from "+this.tableName;
}else{
// sql = this.select+this.where+"=";
sql = "select "+this.select+" from "+this.tableName+" "+this.where+"=";
}
sql = sql.replace(" and =","");
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet paginate(String showPage){
ResultSet resultSet = null;
String sql = "";
try {
if (where.equals("where ")){
// sql = this.select+" limit "+showPage+" offset 0";
sql = "select "+this.select+" from "+ this.tableName+" limit "+showPage+" offset 0";
}else{
// sql = this.select+this.where+"="+" limit "+showPage+" offset 0";
sql = "select "+this.select+" from "+ this.tableName+" "+this.where+"= limit "+showPage+" offset 0";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet paginate(String showPage, String page){
ResultSet resultSet = null;
Integer offset = 0;
String sql = "";
try {
if (page.equals("1")){
offset = 0;
}else{
offset = (new Integer(showPage) * (new Integer(page) - 1) );
}
if (where.equals("where ")){
// sql = this.select+" limit "+showPage+" offset "+offset;
sql = "select "+this.select+" from "+ this.tableName+" limit "+showPage+" offset "+offset;
}else{
// sql = this.select+this.where+"="+" limit "+showPage+" offset "+offset;
sql = "select "+this.select+" from "+ this.tableName+" "+this.where+"= limit "+showPage+" offset "+offset;
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public Integer count(){
ResultSet resultSet = null;
String sql = "";
Integer count = 0;
try {
if (where.equals("where ")){
sql = "select count(*) as count from "+this.tableName+" ";
}else{
sql = "select count(*) as count from "+this.tableName+" "+this.where+"=";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
resultSet.next();
count = new Integer(resultSet.getString("count"));
}catch (Exception e){
log.error(e);
}
return count;
}
}
| UTF-8 | Java | 10,249 | java | ConnectionHelper.java | Java | [] | null | [] | package com.mpc.merchant.helper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class ConnectionHelper {
private Connection connection = null;
private PropertiesHelper applicationProperties = new PropertiesHelper("application.properties");
private Logger log = LogManager.getLogger(getClass());
private String select = "*";
private String tableName = "";
private String where = "where ";
private List<Object> param = new ArrayList<>();
public ConnectionHelper() {
connection = setConnection();
}
public Connection setConnection(){
try {
Class.forName(applicationProperties.getPropertis("spring.datasource.driver-class-name"));
this.connection = DriverManager.getConnection(
applicationProperties.getPropertis("spring.datasource.url"),
applicationProperties.getPropertis("spring.datasource.username"),
applicationProperties.getPropertis("spring.datasource.password")
);
}catch (Exception e){
log.error(e);
}
return connection;
}
private ResultSet executeQuery(String sql){
ResultSet resultSet = null;
try {
Statement statement = (Statement) connection.createStatement();
resultSet = statement.executeQuery(sql);
} catch (Exception e) {
log.error(e);
}
return resultSet;
}
private ResultSet executeQuery(String sql, List<Object> params){
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql);
Integer i = 1;
for (Object param : params) {
preparedStatement.setObject(i, param);
i++;
}
resultSet = preparedStatement.executeQuery();
} catch (Exception e) {
log.error(e);
}
return resultSet;
}
private Integer executeUpdate(String sql){
Integer status = null;
try {
Statement statement = (Statement) connection.createStatement();
status = statement.executeUpdate(sql);
} catch (Exception e) {
log.error(e);
}
return status;
}
private Integer executeUpdate(String sql, List<Object> params){
Integer status = null;
try {
PreparedStatement statement = connection.prepareStatement(sql);
Integer i = 1;
for (Object param : params) {
statement.setObject(i, param);
i++;
}
status = statement.executeUpdate();
} catch (Exception e) {
log.error(e);
}
return status;
}
public Object save(Object object){
try{
param = new ArrayList<>();
StringHelper stringHelper = new StringHelper();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(object, Map.class);
String sql = "insert into "+ stringHelper.strConvertCU(object.getClass().getSimpleName());
String field = "(";
String values = " values(";
for (Map.Entry<String, Object> mapObj : map.entrySet()){
field += stringHelper.strConvertCU(mapObj.getKey())+",";
values += "?,";
if (mapObj.getValue() instanceof String) {
param.add(mapObj.getValue());
}else if (mapObj.getValue() instanceof Long){
param.add( new DateFormaterHelper().timestampToDB( new Timestamp((Long) mapObj.getValue()) ) );
}else{
param.add(mapObj.getValue());
}
}
field += ")";
values += ")";
field = field.replace(",)",")");
values = values.replace(",)",")");
sql = sql+field+values;
log.debug("Query: "+sql);
log.debug("Param: "+param);
this.executeUpdate(sql,param);
}catch (Exception e){
log.error(e);
}
return object;
}
public ConnectionHelper select(String select){
this.select = select;
return this;
}
public ConnectionHelper table(String tableName){
this.tableName = tableName;
return this;
}
public ConnectionHelper where(String field, Object value){
if (value instanceof String){
this.where += field+"=? and ";
}else{
this.where += field+"=? and ";
}
param.add(value);
return this;
}
public ConnectionHelper where(String field, String operator, Object value){
if (value instanceof String){
this.where += field+" "+operator+" ? and ";
}else{
this.where += field+" "+operator+" ? and ";
}
param.add(value);
return this;
}
public ConnectionHelper whereDateBetween(String date, Integer dateIncrease){
return this;
}
public ConnectionHelper findBy(Map<String, Object> findValue){
StringHelper stringHelper = new StringHelper();
param = new ArrayList<>();
try {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(findValue, Map.class);
where += "(";
for (Map.Entry<String, Object> mapObj : map.entrySet()){
where += stringHelper.strConvertCU(mapObj.getKey()) +" like ? or ";
param.add("%"+mapObj.getValue()+"%");
}
where += ")";
where = where.replace("or )",") and ");
}catch (Exception e){
log.error(e);
}
return this;
}
public ResultSet first(){
ResultSet resultSet = null;
String sql = "";
try{
if (where.equals("where ")){
sql = "select "+this.select+" from "+this.tableName+" limit 1";
}else{
sql = "select "+this.select+" from "+this.tableName+" "+this.where+"= limit 1";
// sql = this.select+this.where+"= limit 1";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet get(){
ResultSet resultSet = null;
String sql = "";
try{
if (where.equals("where ")){
// sql = this.select;
sql = "select "+this.select+" from "+this.tableName;
}else{
// sql = this.select+this.where+"=";
sql = "select "+this.select+" from "+this.tableName+" "+this.where+"=";
}
sql = sql.replace(" and =","");
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet paginate(String showPage){
ResultSet resultSet = null;
String sql = "";
try {
if (where.equals("where ")){
// sql = this.select+" limit "+showPage+" offset 0";
sql = "select "+this.select+" from "+ this.tableName+" limit "+showPage+" offset 0";
}else{
// sql = this.select+this.where+"="+" limit "+showPage+" offset 0";
sql = "select "+this.select+" from "+ this.tableName+" "+this.where+"= limit "+showPage+" offset 0";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public ResultSet paginate(String showPage, String page){
ResultSet resultSet = null;
Integer offset = 0;
String sql = "";
try {
if (page.equals("1")){
offset = 0;
}else{
offset = (new Integer(showPage) * (new Integer(page) - 1) );
}
if (where.equals("where ")){
// sql = this.select+" limit "+showPage+" offset "+offset;
sql = "select "+this.select+" from "+ this.tableName+" limit "+showPage+" offset "+offset;
}else{
// sql = this.select+this.where+"="+" limit "+showPage+" offset "+offset;
sql = "select "+this.select+" from "+ this.tableName+" "+this.where+"= limit "+showPage+" offset "+offset;
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
}catch (Exception e){
log.error(e);
}
return resultSet;
}
public Integer count(){
ResultSet resultSet = null;
String sql = "";
Integer count = 0;
try {
if (where.equals("where ")){
sql = "select count(*) as count from "+this.tableName+" ";
}else{
sql = "select count(*) as count from "+this.tableName+" "+this.where+"=";
}
sql = sql.replace(" and =","");
log.debug("Query: "+sql);
log.debug("Param: "+param);
resultSet = this.executeQuery(sql, param);
resultSet.next();
count = new Integer(resultSet.getString("count"));
}catch (Exception e){
log.error(e);
}
return count;
}
}
| 10,249 | 0.523661 | 0.5221 | 326 | 30.43865 | 25.925108 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598159 | false | false | 3 |
b00fc1b2188befae99f77171f4f2561e4b05cdd3 | 29,377,576,374,868 | d8f892c655a2f1dd0b864db76c1e20c6ce3650f5 | /client/src/chat/client/ChatWindow.java | fbd5ea3c8b80ab4b4424ef2093633c74342a1e5c | [] | no_license | RomanYusko/Local | https://github.com/RomanYusko/Local | f30799a070d4bdbeb91642c67a5a1fc481810681 | f736f6c62f1a2b29971fdcd5ffa93bea8302b253 | refs/heads/master | 2022-11-17T06:10:31.488000 | 2020-07-13T12:28:55 | 2020-07-13T12:28:55 | 279,296,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chat.client;
import chat.network.TCPConnection;
import chat.network.TCPConnectionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class ChatWindow extends JFrame implements ActionListener, TCPConnectionListener {
public static final String TP_ADDR = "213.5.192.246";
public static final int PORT = 55657;
public static final int HEIGHT = 400;
public static final int WIDTH = 600;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChatWindow();
}
});
}
private final JTextArea log = new JTextArea();
private final JTextField nickname = new JTextField("roma");
private final JTextField input = new JTextField();
private TCPConnection connection;
private ChatWindow() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(WIDTH,HEIGHT);
setLocationRelativeTo(null);
setAlwaysOnTop(true);
log.setEditable(false);
log.setLineWrap(true);
add(log, BorderLayout.CENTER);
input.addActionListener(this);
add(input, BorderLayout.SOUTH);
add(nickname, BorderLayout.NORTH);
setVisible(true);
try {
connection = new TCPConnection(this, TP_ADDR,PORT);
} catch (IOException e) {
printMessage("Connection exception " + e);
}
}
@Override
public void actionPerformed(ActionEvent e) {
String message = input.getText();
if (message.equals("")) return;
input.setText(null);
connection.sentMessage(nickname.getText() + ": " + message);
}
@Override
public void onConnectionReady(TCPConnection tcpConnection) {
printMessage("Connection ready...");
}
@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
printMessage(value);
}
@Override
public void onDisconnect(TCPConnection tcpConnection) {
printMessage("Connection close...");
}
@Override
public void onException(TCPConnection tcpConnection, Exception e) {
printMessage("Connection exception " + e);
}
private synchronized void printMessage(String message) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
log.append(message + "\n");
log.setCaretPosition(log.getDocument().getLength());
}
});
}
}
| UTF-8 | Java | 2,666 | java | ChatWindow.java | Java | [
{
"context": "ener {\n\n public static final String TP_ADDR = \"213.5.192.246\";\n public static final int PORT = 55657;\n p",
"end": 389,
"score": 0.999770998954773,
"start": 376,
"tag": "IP_ADDRESS",
"value": "213.5.192.246"
},
{
"context": "ivate final JTextField nickname... | null | [] | package chat.client;
import chat.network.TCPConnection;
import chat.network.TCPConnectionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class ChatWindow extends JFrame implements ActionListener, TCPConnectionListener {
public static final String TP_ADDR = "192.168.3.11";
public static final int PORT = 55657;
public static final int HEIGHT = 400;
public static final int WIDTH = 600;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChatWindow();
}
});
}
private final JTextArea log = new JTextArea();
private final JTextField nickname = new JTextField("roma");
private final JTextField input = new JTextField();
private TCPConnection connection;
private ChatWindow() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(WIDTH,HEIGHT);
setLocationRelativeTo(null);
setAlwaysOnTop(true);
log.setEditable(false);
log.setLineWrap(true);
add(log, BorderLayout.CENTER);
input.addActionListener(this);
add(input, BorderLayout.SOUTH);
add(nickname, BorderLayout.NORTH);
setVisible(true);
try {
connection = new TCPConnection(this, TP_ADDR,PORT);
} catch (IOException e) {
printMessage("Connection exception " + e);
}
}
@Override
public void actionPerformed(ActionEvent e) {
String message = input.getText();
if (message.equals("")) return;
input.setText(null);
connection.sentMessage(nickname.getText() + ": " + message);
}
@Override
public void onConnectionReady(TCPConnection tcpConnection) {
printMessage("Connection ready...");
}
@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
printMessage(value);
}
@Override
public void onDisconnect(TCPConnection tcpConnection) {
printMessage("Connection close...");
}
@Override
public void onException(TCPConnection tcpConnection, Exception e) {
printMessage("Connection exception " + e);
}
private synchronized void printMessage(String message) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
log.append(message + "\n");
log.setCaretPosition(log.getDocument().getLength());
}
});
}
}
| 2,665 | 0.636909 | 0.629032 | 93 | 27.666666 | 22.462553 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 3 |
a264a3d590ac066cc8a0b9563c81aa6c9d5f85b0 | 29,377,576,374,587 | 3af0cc64f622c29e56e41a52f7004b3c3bab245f | /src/com/gmail/brunodiazmartin5/controlador/MainController.java | ad7603b9f2c2a45eac2c0323cd2a58fa72bdc149 | [] | no_license | brunodm99/tareaAED3 | https://github.com/brunodm99/tareaAED3 | 2a9832e5942f659089fca2bc70b22f5e06ab5d6e | 460c30b7e2bb1c7b74d188ba2589dd30b7c5ec08 | refs/heads/master | 2020-04-07T17:56:23.784000 | 2018-11-27T21:50:04 | 2018-11-27T21:50:04 | 158,590,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gmail.brunodiazmartin5.controlador;
import com.gmail.brunodiazmartin5.TareaAED3;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.stage.Stage;
/**
*
* @author bruno
*/
public class MainController implements Initializable{
@FXML
private MenuItem mniSalir;
@Override
public void initialize(URL location, ResourceBundle resources) {
mniSalir.setOnAction(d -> {
Platform.exit();
System.exit(0);
});
}
@FXML
private void infoConexion(ActionEvent event) {
FXMLLoader fxmlLoader = new FXMLLoader(TareaAED3.class.getResource("vista/InformacionConexionView.fxml"));
Stage s = new Stage();
try {
s.setScene(new Scene(fxmlLoader.load()));
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
s.sizeToScene();
s.getIcons().add(new Image(TareaAED3.class.getResourceAsStream("resources/icon.png")));
s.setResizable(false);
s.setTitle("Información acerca de la conexión");
s.show();
}
}
| UTF-8 | Java | 1,512 | java | MainController.java | Java | [
{
"context": "l.brunodiazmartin5.controlador;\n\nimport com.gmail.brunodiazmartin5.TareaAED3;\nimport java.io.IOException;\nimport jav",
"end": 82,
"score": 0.9185678958892822,
"start": 66,
"tag": "USERNAME",
"value": "brunodiazmartin5"
},
{
"context": "age;\nimport javafx.stage.Stag... | null | [] | package com.gmail.brunodiazmartin5.controlador;
import com.gmail.brunodiazmartin5.TareaAED3;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.stage.Stage;
/**
*
* @author bruno
*/
public class MainController implements Initializable{
@FXML
private MenuItem mniSalir;
@Override
public void initialize(URL location, ResourceBundle resources) {
mniSalir.setOnAction(d -> {
Platform.exit();
System.exit(0);
});
}
@FXML
private void infoConexion(ActionEvent event) {
FXMLLoader fxmlLoader = new FXMLLoader(TareaAED3.class.getResource("vista/InformacionConexionView.fxml"));
Stage s = new Stage();
try {
s.setScene(new Scene(fxmlLoader.load()));
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
s.sizeToScene();
s.getIcons().add(new Image(TareaAED3.class.getResourceAsStream("resources/icon.png")));
s.setResizable(false);
s.setTitle("Información acerca de la conexión");
s.show();
}
}
| 1,512 | 0.682781 | 0.678808 | 54 | 26.962963 | 24.351563 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 3 |
4d13aa3d810863c2cbaa49f98204a32eb54eab9b | 15,822,659,579,697 | 8c348a58d538360b6a59567338064e8983fcdd14 | /Java SPALAH/l6_HomeWork/src/l6_homework/L6_HomeWork.java | d834ff7d24643049361f2e9889ef2e6c9085f2b8 | [] | no_license | ClayPwr/save | https://github.com/ClayPwr/save | d0f46b5f62f13171a1aadbbd2cd0cd84e6e464db | 26993241fab4019bf41c2b8e9efc385d5d6f24bf | refs/heads/master | 2020-03-05T16:55:27.935000 | 2017-06-17T13:37:43 | 2017-06-17T13:37:43 | 93,514,505 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package l6_homework;
import java.util.ArrayList;
import java.util.Scanner;
public class L6_HomeWork {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Information> arrData = new ArrayList<>();
do{
System.out.println("");
System.out.println("");
System.out.println("Действие:");
System.out.println("1. Добавить элемент.");
System.out.println("2. Вывести весь список.");
System.out.println("3. Поиск.");
System.out.println("4. Удалить весь список.");
System.out.println("0. Выход");
int nType = scan.nextInt();
switch(nType){
case 1:
System.out.println("Тип");
System.err.println("1. Книга");
System.out.println("2. Газета");
nType = scan.nextInt();
Information item;
if (nType==1){
item = new Books();
} else {
item = new Newspaper();
}
item.inputData();
arrData.add(item);
break;
case 2:
for(Information information:arrData){
information.outputData();
if(information.getClass().equals(Books.class)){
}
}
break;
case 3:
scan.hasNextLine();
String strSearch = scan.nextLine();
for (Information information:arrData){
if(information.isValid(strSearch)){
information.outputData();
}
}
break;
case 4:
arrData.clear();
break;
case 0:
return;
default:
System.out.println("Выбрано не коректное значение. Повторите ввод");
}
}while(true);
}
}
| UTF-8 | Java | 2,366 | java | L6_HomeWork.java | Java | [] | null | [] |
package l6_homework;
import java.util.ArrayList;
import java.util.Scanner;
public class L6_HomeWork {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Information> arrData = new ArrayList<>();
do{
System.out.println("");
System.out.println("");
System.out.println("Действие:");
System.out.println("1. Добавить элемент.");
System.out.println("2. Вывести весь список.");
System.out.println("3. Поиск.");
System.out.println("4. Удалить весь список.");
System.out.println("0. Выход");
int nType = scan.nextInt();
switch(nType){
case 1:
System.out.println("Тип");
System.err.println("1. Книга");
System.out.println("2. Газета");
nType = scan.nextInt();
Information item;
if (nType==1){
item = new Books();
} else {
item = new Newspaper();
}
item.inputData();
arrData.add(item);
break;
case 2:
for(Information information:arrData){
information.outputData();
if(information.getClass().equals(Books.class)){
}
}
break;
case 3:
scan.hasNextLine();
String strSearch = scan.nextLine();
for (Information information:arrData){
if(information.isValid(strSearch)){
information.outputData();
}
}
break;
case 4:
arrData.clear();
break;
case 0:
return;
default:
System.out.println("Выбрано не коректное значение. Повторите ввод");
}
}while(true);
}
}
| 2,366 | 0.410508 | 0.403829 | 66 | 33.015152 | 18.332363 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530303 | false | false | 3 |
8bc7570608ba82fe2707a4670d11e6ff759b36c5 | 30,116,310,699,103 | f5000a784274018a4526ee26394428cc41ff1fec | /src/test/java/stepdefs/Hooks.java | 99bd8dcb41a94b9fe55d6f89bca973de42580165 | [] | no_license | EceEroglu/CucumberAppium | https://github.com/EceEroglu/CucumberAppium | 2c93e51edfffbee2d60176a35b7044bb0de31d2a | c8d4337a4ef70c2cc8485c42f3b7cfe7cfd7498b | refs/heads/master | 2022-12-30T09:35:52.392000 | 2020-06-22T11:29:01 | 2020-06-22T11:29:01 | 272,368,383 | 0 | 0 | null | false | 2020-10-13T22:48:14 | 2020-06-15T07:16:45 | 2020-06-22T11:29:04 | 2020-10-13T22:48:12 | 298,572 | 0 | 0 | 1 | Java | false | false | package stepdefs;
import io.cucumber.core.api.Scenario;
import io.cucumber.java.After;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import helper.AppiumController;
public class Hooks {
@After
public void afterScenario(Scenario scenario) throws Exception {
if (scenario.isFailed()) {
scenario.embed(((TakesScreenshot)AppiumController.instance.driver)
.getScreenshotAs(OutputType.BYTES), "image/png");
}
AppiumController.instance.stop();
}
} | UTF-8 | Java | 567 | java | Hooks.java | Java | [] | null | [] | package stepdefs;
import io.cucumber.core.api.Scenario;
import io.cucumber.java.After;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import helper.AppiumController;
public class Hooks {
@After
public void afterScenario(Scenario scenario) throws Exception {
if (scenario.isFailed()) {
scenario.embed(((TakesScreenshot)AppiumController.instance.driver)
.getScreenshotAs(OutputType.BYTES), "image/png");
}
AppiumController.instance.stop();
}
} | 567 | 0.68254 | 0.68254 | 23 | 23.695652 | 23.550934 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 3 |
344b7b3fb8cc6f50eb5c3db57f207e8335cb59d6 | 30,116,310,697,514 | f007cecfbcff3940904f275fe9318d3632b9fc81 | /Networks_lab/ex3a.java | d0436201cbfa0c43741d363d5503daac5cf1ad64 | [] | no_license | sundhar-velmurugan/CSE | https://github.com/sundhar-velmurugan/CSE | b23371a03114a748eb173b03303a4983fbf83189 | ba3a9d0834f8782a2c6df470daf566d1c729e8cd | refs/heads/master | 2022-01-28T05:09:28.863000 | 2019-06-01T01:34:24 | 2019-06-01T01:34:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.net.DatagramPacket;
public class ex3a{
public static void main(String []args) throws Exception{
DatagramSocket ds = new DatagramSocket();
InetAddress addr = InetAddress.getLocalHost();
//int i=0;
//while(i<15){
while(true){
//Thread.sleep(1000);
Date d = new Date();
byte[] s = d.toString().getBytes();
DatagramPacket dp = new DatagramPacket(s, s.length, addr, 2000);
ds.send(dp);
//i++;
}
}
} | UTF-8 | Java | 640 | java | ex3a.java | Java | [] | null | [] | import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.net.DatagramPacket;
public class ex3a{
public static void main(String []args) throws Exception{
DatagramSocket ds = new DatagramSocket();
InetAddress addr = InetAddress.getLocalHost();
//int i=0;
//while(i<15){
while(true){
//Thread.sleep(1000);
Date d = new Date();
byte[] s = d.toString().getBytes();
DatagramPacket dp = new DatagramPacket(s, s.length, addr, 2000);
ds.send(dp);
//i++;
}
}
} | 640 | 0.55625 | 0.5375 | 21 | 28.571428 | 19.13006 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.761905 | false | false | 3 |
672effd963a24323960f6c49d42fc7b7e9875f0b | 5,712,306,571,886 | acc80ca9232b251858558dca61aa302504975bec | /src/main/java/leetcode/Solution300.java | 1855ede21f54ebf540796eb15bf2cd1cb071ce99 | [] | no_license | shaoyihe/leetcode | https://github.com/shaoyihe/leetcode | 9348e575bcca5f6fc4627dbe1d22c3274d9b4403 | d109de0b1967cce517a6f5058ff5506bb2208c00 | refs/heads/master | 2021-11-24T14:02:51.274000 | 2019-02-10T06:36:17 | 2019-02-10T06:36:17 | 143,421,908 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
import leetcode.util.BaseTest;
import org.junit.Test;
import java.util.Arrays;
/**
* <pre>
* https://leetcode.com/problems/longest-increasing-subsequence/description/
* 300. Longest Increasing Subsequence
* </pre>
* on 2018/09/03.
*/
public class Solution300 extends BaseTest {
@Test
public void test() {
assertEquals(4, lengthOfLIS(arr(10, 9, 2, 5, 3, 7, 101, 18)));
}
@Test
public void test2() {
assertEquals(4, lengthOfLIS2(arr(10, 9, 2, 5, 3, 7, 101, 18)));
}
private final int NOT_CHOICE = -1;
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] cache = new int[nums.length];
Arrays.fill(cache, -1);
return lengthOfLIS(nums, 0, cache, NOT_CHOICE);
}
private int lengthOfLIS(int[] nums, int index, int[] cache, int lastChoice) {
if (index == nums.length) return 0;
//
int max = 0;
if (lastChoice == NOT_CHOICE || nums[index] > nums[lastChoice]) {
if (cache[index] == -1) {
cache[index] = 1 + lengthOfLIS(nums, index + 1, cache, index);
}
max = cache[index];
}
return Math.max(max, lengthOfLIS(nums, index + 1, cache, lastChoice));
}
public int lengthOfLIS2(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] cache = new int[nums.length];
int max = 1;
for (int i = 0; i < nums.length; ++i) {
int lessThanCurMaxVal = 0;
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i] && cache[j] > lessThanCurMaxVal) lessThanCurMaxVal = cache[j];
}
if ((cache[i] = lessThanCurMaxVal + 1) > max) max = cache[i];
}
return max;
}
}
| UTF-8 | Java | 1,828 | java | Solution300.java | Java | [] | null | [] | package leetcode;
import leetcode.util.BaseTest;
import org.junit.Test;
import java.util.Arrays;
/**
* <pre>
* https://leetcode.com/problems/longest-increasing-subsequence/description/
* 300. Longest Increasing Subsequence
* </pre>
* on 2018/09/03.
*/
public class Solution300 extends BaseTest {
@Test
public void test() {
assertEquals(4, lengthOfLIS(arr(10, 9, 2, 5, 3, 7, 101, 18)));
}
@Test
public void test2() {
assertEquals(4, lengthOfLIS2(arr(10, 9, 2, 5, 3, 7, 101, 18)));
}
private final int NOT_CHOICE = -1;
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] cache = new int[nums.length];
Arrays.fill(cache, -1);
return lengthOfLIS(nums, 0, cache, NOT_CHOICE);
}
private int lengthOfLIS(int[] nums, int index, int[] cache, int lastChoice) {
if (index == nums.length) return 0;
//
int max = 0;
if (lastChoice == NOT_CHOICE || nums[index] > nums[lastChoice]) {
if (cache[index] == -1) {
cache[index] = 1 + lengthOfLIS(nums, index + 1, cache, index);
}
max = cache[index];
}
return Math.max(max, lengthOfLIS(nums, index + 1, cache, lastChoice));
}
public int lengthOfLIS2(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] cache = new int[nums.length];
int max = 1;
for (int i = 0; i < nums.length; ++i) {
int lessThanCurMaxVal = 0;
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i] && cache[j] > lessThanCurMaxVal) lessThanCurMaxVal = cache[j];
}
if ((cache[i] = lessThanCurMaxVal + 1) > max) max = cache[i];
}
return max;
}
}
| 1,828 | 0.543764 | 0.510394 | 68 | 25.882353 | 26.289413 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.926471 | false | false | 3 |
b34254de042ca43b6a9664b2bfd0e153c16d8c78 | 10,642,929,014,247 | ca92ab4e6f712556750269a8df6d2b0e635d2c9e | /offer/src/main/java/com/bzdepot/offer/model/ClassGroup.java | 731aa0f9ca72daad81c96e9a2796a4e9280097fa | [] | no_license | a120862114/baizhu | https://github.com/a120862114/baizhu | c6b66d264e312dcc835297f0aa9fdb75be84e798 | 6dc334cc4326a82177fec44d061dd51d2630eeb0 | refs/heads/master | 2020-04-16T22:21:00.187000 | 2019-01-15T07:11:28 | 2019-01-15T07:11:28 | 165,964,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bzdepot.offer.model;
import javax.validation.constraints.NotNull;
import java.util.List;
public class ClassGroup {
private Long id;
@NotNull(message = "分组名不能为空!")
private String groupName;
private Byte status;
private Long createTime;
private Long updateTime;
@NotNull(message = "商家编号不能为空!")
private Long sellerId;
private List<Classfiy> classfiy;
public List<Classfiy> getClassfiy() {
return classfiy;
}
public void setClassfiy(List<Classfiy> classfiy) {
this.classfiy = classfiy;
}
public Long getSellerId() {
return sellerId;
}
public void setSellerId(Long sellerId) {
this.sellerId = sellerId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
} | UTF-8 | Java | 1,525 | java | ClassGroup.java | Java | [] | null | [] | package com.bzdepot.offer.model;
import javax.validation.constraints.NotNull;
import java.util.List;
public class ClassGroup {
private Long id;
@NotNull(message = "分组名不能为空!")
private String groupName;
private Byte status;
private Long createTime;
private Long updateTime;
@NotNull(message = "商家编号不能为空!")
private Long sellerId;
private List<Classfiy> classfiy;
public List<Classfiy> getClassfiy() {
return classfiy;
}
public void setClassfiy(List<Classfiy> classfiy) {
this.classfiy = classfiy;
}
public Long getSellerId() {
return sellerId;
}
public void setSellerId(Long sellerId) {
this.sellerId = sellerId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
} | 1,525 | 0.620067 | 0.620067 | 78 | 18.179487 | 17.211164 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 3 |
476fb5634b0b6a21b13ffb6a6fc6836375e4edd6 | 17,669,495,523,656 | 13a84cca5cee45ebc4c04ae8fe5a8d77cd7ca34e | /ojdbc/oracle/sql/CharacterSetFactory.java | 5d3ef7581316006d4e0a8f04b700b67e79442607 | [] | no_license | mccxj/tns | https://github.com/mccxj/tns | 3b3829579b3e7a731fd041b1881e4d4ad1eb2abe | 1b3eb609ee495e8564d0737c2a48f68446f07394 | refs/heads/master | 2020-03-30T16:41:07.391000 | 2018-10-03T14:47:10 | 2018-10-03T14:47:10 | 151,421,226 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package oracle.sql;
import java.io.PrintStream;
import java.sql.SQLException;
abstract class CharacterSetFactory
{
public static final short DEFAULT_CHARSET = -1;
public static final short ASCII_CHARSET = 1;
public static final short ISO_LATIN_1_CHARSET = 31;
public static final short UNICODE_1_CHARSET = 870;
public static final short UNICODE_2_CHARSET = 871;
public abstract CharacterSet make(int paramInt);
public static void main(String[] paramArrayOfString)
{
/* 80 */ CharacterSet localCharacterSet1 = CharacterSet.make(871);
/* 81 */ int[] arrayOfInt = { 1, 31, 870, 871 };
/* 86 */ for (int i = 0; i < arrayOfInt.length; i++)
{
/* 88 */ CharacterSet localCharacterSet2 = CharacterSet.make(arrayOfInt[i]);
/* 91 */ String str1 = "longlonglonglong";
/* 92 */ str1 = str1 + str1 + str1 + str1;
/* 93 */ str1 = str1 + str1 + str1 + str1;
/* 94 */ str1 = str1 + str1 + str1 + str1;
/* 95 */ str1 = str1 + str1 + str1 + str1;
/* 97 */ String[] arrayOfString = { "abc", "ab?c", "XYZ", str1 };
/* 102 */ for (int j = 0; j < arrayOfString.length; j++)
{
/* 104 */ String str2 = arrayOfString[j];
/* 105 */ String str3 = str2;
/* 107 */ if (str2.length() > 16)
{
/* 109 */ str3 = str3.substring(0, 16) + "...";
}
/* 112 */ System.out.println("testing " + localCharacterSet2 + " against <" + str3 + ">");
/* 114 */ int k = 1;
try
{
/* 118 */ byte[] arrayOfByte1 = localCharacterSet2.convertWithReplacement(str2);
/* 119 */ String str4 = localCharacterSet2.toStringWithReplacement(arrayOfByte1, 0, arrayOfByte1.length);
/* 122 */ arrayOfByte1 = localCharacterSet2.convert(str4);
/* 124 */ String str5 = localCharacterSet2.toString(arrayOfByte1, 0, arrayOfByte1.length);
/* 126 */ if (!str4.equals(str5))
{
/* 128 */ System.out.println(" FAILED roundTrip " + str5);
/* 130 */ k = 0;
}
Object localObject;
/* 133 */ if (localCharacterSet2.isLossyFrom(localCharacterSet1))
{
try
{
/* 137 */ byte[] arrayOfByte2 = localCharacterSet2.convert(str2);
/* 138 */ localObject = localCharacterSet2.toString(arrayOfByte2, 0, arrayOfByte2.length);
/* 140 */ if (!((String)localObject).equals(str5))
{
/* 142 */ System.out.println(" FAILED roundtrip, no throw");
}
}
catch (SQLException localSQLException) {}
}
else
{
/* 149 */ if (!str5.equals(str2))
{
/* 151 */ System.out.println(" FAILED roundTrip " + str5);
/* 153 */ k = 0;
}
/* 156 */ byte[] arrayOfByte3 = localCharacterSet1.convert(str2);
/* 157 */ localObject = localCharacterSet2.convert(localCharacterSet1, arrayOfByte3, 0, arrayOfByte3.length);
/* 159 */ String str6 = localCharacterSet2.toString((byte[])localObject, 0, localObject.length);
/* 163 */ if (!str6.equals(str2))
{
/* 165 */ System.out.println(" FAILED withoutReplacement " + str6);
/* 168 */ k = 0;
}
}
}
catch (Exception localException)
{
/* 174 */ System.out.println(" FAILED with Exception " + localException);
}
/* 177 */ if (k != 0)
{
/* 179 */ System.out.println(" PASSED " + (localCharacterSet2.isLossyFrom(localCharacterSet1) ? "LOSSY" : ""));
}
}
}
}
/* 187 */ private static final String _Copyright_2007_Oracle_All_Rights_Reserved_ = null;
public static final boolean TRACE = false;
}
/* Location: /home/caixj/下载/ojdbc6.jar!/oracle/sql/CharacterSetFactory.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 4,229 | java | CharacterSetFactory.java | Java | [] | null | [] | package oracle.sql;
import java.io.PrintStream;
import java.sql.SQLException;
abstract class CharacterSetFactory
{
public static final short DEFAULT_CHARSET = -1;
public static final short ASCII_CHARSET = 1;
public static final short ISO_LATIN_1_CHARSET = 31;
public static final short UNICODE_1_CHARSET = 870;
public static final short UNICODE_2_CHARSET = 871;
public abstract CharacterSet make(int paramInt);
public static void main(String[] paramArrayOfString)
{
/* 80 */ CharacterSet localCharacterSet1 = CharacterSet.make(871);
/* 81 */ int[] arrayOfInt = { 1, 31, 870, 871 };
/* 86 */ for (int i = 0; i < arrayOfInt.length; i++)
{
/* 88 */ CharacterSet localCharacterSet2 = CharacterSet.make(arrayOfInt[i]);
/* 91 */ String str1 = "longlonglonglong";
/* 92 */ str1 = str1 + str1 + str1 + str1;
/* 93 */ str1 = str1 + str1 + str1 + str1;
/* 94 */ str1 = str1 + str1 + str1 + str1;
/* 95 */ str1 = str1 + str1 + str1 + str1;
/* 97 */ String[] arrayOfString = { "abc", "ab?c", "XYZ", str1 };
/* 102 */ for (int j = 0; j < arrayOfString.length; j++)
{
/* 104 */ String str2 = arrayOfString[j];
/* 105 */ String str3 = str2;
/* 107 */ if (str2.length() > 16)
{
/* 109 */ str3 = str3.substring(0, 16) + "...";
}
/* 112 */ System.out.println("testing " + localCharacterSet2 + " against <" + str3 + ">");
/* 114 */ int k = 1;
try
{
/* 118 */ byte[] arrayOfByte1 = localCharacterSet2.convertWithReplacement(str2);
/* 119 */ String str4 = localCharacterSet2.toStringWithReplacement(arrayOfByte1, 0, arrayOfByte1.length);
/* 122 */ arrayOfByte1 = localCharacterSet2.convert(str4);
/* 124 */ String str5 = localCharacterSet2.toString(arrayOfByte1, 0, arrayOfByte1.length);
/* 126 */ if (!str4.equals(str5))
{
/* 128 */ System.out.println(" FAILED roundTrip " + str5);
/* 130 */ k = 0;
}
Object localObject;
/* 133 */ if (localCharacterSet2.isLossyFrom(localCharacterSet1))
{
try
{
/* 137 */ byte[] arrayOfByte2 = localCharacterSet2.convert(str2);
/* 138 */ localObject = localCharacterSet2.toString(arrayOfByte2, 0, arrayOfByte2.length);
/* 140 */ if (!((String)localObject).equals(str5))
{
/* 142 */ System.out.println(" FAILED roundtrip, no throw");
}
}
catch (SQLException localSQLException) {}
}
else
{
/* 149 */ if (!str5.equals(str2))
{
/* 151 */ System.out.println(" FAILED roundTrip " + str5);
/* 153 */ k = 0;
}
/* 156 */ byte[] arrayOfByte3 = localCharacterSet1.convert(str2);
/* 157 */ localObject = localCharacterSet2.convert(localCharacterSet1, arrayOfByte3, 0, arrayOfByte3.length);
/* 159 */ String str6 = localCharacterSet2.toString((byte[])localObject, 0, localObject.length);
/* 163 */ if (!str6.equals(str2))
{
/* 165 */ System.out.println(" FAILED withoutReplacement " + str6);
/* 168 */ k = 0;
}
}
}
catch (Exception localException)
{
/* 174 */ System.out.println(" FAILED with Exception " + localException);
}
/* 177 */ if (k != 0)
{
/* 179 */ System.out.println(" PASSED " + (localCharacterSet2.isLossyFrom(localCharacterSet1) ? "LOSSY" : ""));
}
}
}
}
/* 187 */ private static final String _Copyright_2007_Oracle_All_Rights_Reserved_ = null;
public static final boolean TRACE = false;
}
/* Location: /home/caixj/下载/ojdbc6.jar!/oracle/sql/CharacterSetFactory.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 4,229 | 0.520473 | 0.462485 | 116 | 35.431034 | 31.624746 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577586 | false | false | 3 |
69881bc1d42dbcce60a243a853b71417ab26e05b | 37,701,222,925,129 | af0e56aad72cdd329ed4625ea140db66a69fe4af | /src/java/com/vipin/microservice/comsservice/repsitory/UploadProfileRepository.java | fc771b1ea4b4e8da53ee1e96a70acc4f5f6349b0 | [] | no_license | kaushikji856/demo-project-docker | https://github.com/kaushikji856/demo-project-docker | 39068dc035b539641ab2b7a85cdac9911ef81674 | 78113c4ceecbe7df29b874f09aea895788499aee | refs/heads/master | 2020-06-05T17:15:29.566000 | 2019-09-10T07:51:05 | 2019-09-10T07:51:05 | 192,494,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.vipin.microservice.comsservice.repsitory;
import org.springframework.data.jpa.repository.JpaRepository;
import com.vipin.microservice.comsservice.model.UserMaster;
/**
* @author VI852115
*
*/
public interface UploadProfileRepository extends JpaRepository<UserMaster, Long>{
UserMaster findByUserId(Long userid);
}
| UTF-8 | Java | 366 | java | UploadProfileRepository.java | Java | [
{
"context": "e.comsservice.model.UserMaster;\r\n\r\n/**\r\n * @author VI852115\r\n *\r\n */\r\npublic interface UploadProfileRepositor",
"end": 224,
"score": 0.999620795249939,
"start": 216,
"tag": "USERNAME",
"value": "VI852115"
}
] | null | [] | /**
*
*/
package com.vipin.microservice.comsservice.repsitory;
import org.springframework.data.jpa.repository.JpaRepository;
import com.vipin.microservice.comsservice.model.UserMaster;
/**
* @author VI852115
*
*/
public interface UploadProfileRepository extends JpaRepository<UserMaster, Long>{
UserMaster findByUserId(Long userid);
}
| 366 | 0.740437 | 0.724044 | 18 | 18.333334 | 26.2234 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 3 |
279c984b918dcfba34eece38e39e6c6b8ce8032e | 9,981,504,061,899 | a66838d40c80ddd2b8b7a6a27e49ec460cfd2482 | /CCPjt/src/main/java/com/kh/jhj/persistence/IPeBoardDao.java | b379acbe88963db6f7bf5f76966080a255124b2c | [] | no_license | jijiya1/CC-Project | https://github.com/jijiya1/CC-Project | 6f9299d2b897f2f2908c650b74f13267e8ce8379 | ff4ce2cf0cec6a10d5cc1dd8cba25ce6366284d7 | refs/heads/master | 2022-12-24T02:57:27.020000 | 2019-07-16T07:44:24 | 2019-07-16T07:44:24 | 192,459,209 | 0 | 0 | null | false | 2022-12-16T06:03:58 | 2019-06-18T03:34:05 | 2019-07-16T07:47:01 | 2022-12-16T06:03:55 | 6,948 | 0 | 0 | 5 | JavaScript | false | false | package com.kh.jhj.persistence;
import java.util.List;
import com.kh.domain.DetailDataVo;
import com.kh.domain.PagingDto;
import com.kh.jhj.domain.PetitionVo;
public interface IPeBoardDao {
public List<PetitionVo> listAll(PagingDto pageDto, int a_no) throws Exception;
public int listCount(PagingDto pageDto, int a_no) throws Exception;
public List<PetitionVo> listMain(int a_no) throws Exception;
public PetitionVo petitionRead (String b_serialno) throws Exception;
public void petitionDel (String b_serialno) throws Exception;
public List<PetitionVo> listRunOut(PagingDto pageDto, int a_no) throws Exception;
public List<DetailDataVo> detailArea(int a_no) throws Exception;
public void write(PetitionVo peVo) throws Exception;
public void writeLink(String link) throws Exception;
public int runOutCount(PagingDto pageDto, int a_no) throws Exception;
public List<String> readLink(String b_serialno) throws Exception;
public void readCount(String b_serialno) throws Exception;
public PetitionVo confirm() throws Exception;
public List<PetitionVo> myList(String u_email) throws Exception;
}
| UTF-8 | Java | 1,134 | java | IPeBoardDao.java | Java | [] | null | [] | package com.kh.jhj.persistence;
import java.util.List;
import com.kh.domain.DetailDataVo;
import com.kh.domain.PagingDto;
import com.kh.jhj.domain.PetitionVo;
public interface IPeBoardDao {
public List<PetitionVo> listAll(PagingDto pageDto, int a_no) throws Exception;
public int listCount(PagingDto pageDto, int a_no) throws Exception;
public List<PetitionVo> listMain(int a_no) throws Exception;
public PetitionVo petitionRead (String b_serialno) throws Exception;
public void petitionDel (String b_serialno) throws Exception;
public List<PetitionVo> listRunOut(PagingDto pageDto, int a_no) throws Exception;
public List<DetailDataVo> detailArea(int a_no) throws Exception;
public void write(PetitionVo peVo) throws Exception;
public void writeLink(String link) throws Exception;
public int runOutCount(PagingDto pageDto, int a_no) throws Exception;
public List<String> readLink(String b_serialno) throws Exception;
public void readCount(String b_serialno) throws Exception;
public PetitionVo confirm() throws Exception;
public List<PetitionVo> myList(String u_email) throws Exception;
}
| 1,134 | 0.785714 | 0.785714 | 25 | 43.360001 | 26.528294 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.52 | false | false | 3 |
44f124b00a8549a10cf1fae9983d2a67259c9941 | 266,288,008,499 | 675967651c01269d3d41f8bdc54996d7f223d655 | /Git-tuto/src/org/homegit/MainClass.java | 4b346b33cead4dc3130fa113d68c496d404c9f69 | [] | no_license | dyddyddl09/Git-tuto | https://github.com/dyddyddl09/Git-tuto | 57dc4da9f1188867b97ebe7757b3a69df5d5490a | 457a5f2db64da4421bce5fc5f7c24d5108925528 | refs/heads/master | 2020-11-25T08:08:57.203000 | 2019-12-18T06:02:23 | 2019-12-18T06:02:23 | 228,568,610 | 0 | 1 | null | false | 2019-12-18T06:02:24 | 2019-12-17T08:25:36 | 2019-12-18T05:51:38 | 2019-12-18T06:02:24 | 19 | 0 | 1 | 0 | Java | false | false | package org.homegit;
public class MainClass {
public static void main(String[] args) {
System.out.println("작업자 용호 쏼라쏼라");
System.out.println("종료");
System.out.println("용호작업2");
System.out.println("문동주 시작");
System.out.println("문동주 작업");
System.out.println("용호작업3");
System.out.println("작업4");
System.out.println("실험적 브랜치 작업");
System.out.println("브랜치 작업2");
}
}
| UTF-8 | Java | 498 | java | MainClass.java | Java | [] | null | [] | package org.homegit;
public class MainClass {
public static void main(String[] args) {
System.out.println("작업자 용호 쏼라쏼라");
System.out.println("종료");
System.out.println("용호작업2");
System.out.println("문동주 시작");
System.out.println("문동주 작업");
System.out.println("용호작업3");
System.out.println("작업4");
System.out.println("실험적 브랜치 작업");
System.out.println("브랜치 작업2");
}
}
| 498 | 0.631707 | 0.621951 | 19 | 19.578947 | 14.80866 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.789474 | false | false | 3 |
e61d4bac6369bc2171d060efbc5a0af06c5afbd4 | 37,288,906,065,309 | 2574c3fc15eb504034f6a19437e1dbe90562f387 | /src/main/java/com/huobi/api/crossservice/crosstrade/CrossTradeAPIService.java | b73f1f9631b77e845076959bd51f79aafb961d3c | [] | no_license | mdvx/huobi_usdt_swap_Java | https://github.com/mdvx/huobi_usdt_swap_Java | 4a0a0e97876b205c2d6bf02b4b94618a334036e3 | fe2905e5eb941f5303ea968e1ea2262a4269eaf3 | refs/heads/master | 2023-07-13T18:18:02.630000 | 2021-08-23T05:49:38 | 2021-08-23T05:49:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huobi.api.crossservice.crosstrade;
import com.huobi.api.crossrequest.trade.*;
import com.huobi.api.crossresponse.trade.*;
import com.huobi.api.request.trade.*;
import com.huobi.api.response.trade.*;
public interface CrossTradeAPIService {
SwapCrossOrderResponse swapCrossOrderRequest(SwapCrossOrderRequest request);//合约下单(全仓模式)
SwapCrossBatchorderResponse swapCrossBatchorderRequest(SwapCrossBatchorderRequest request);//合约批量下单(全仓模式)
SwapCrossCancelResponse swapCrossCancelRequest(SwapCrossCancelRequest request);//撤销订单(全仓模式)
SwapCrossCancelallResponse swapCrossCancelallRequest(SwapCrossCancelallRequest request);//全部撤单(全仓模式)
SwapCrossOrderInfoResponse swapCrossOrderInfoRequest(SwapCrossOrderInfoRequest request);//获取合约订单信息(全仓模式)
SwapCrossOrderDetailResponse swapCrossOrderDetailRequest(SwapCrossOrderDetailRequest request);//获取订单明细信息(全仓模式)
SwapCrossOpenordersResponse swapCrossOpenordersRequest(SwapCrossOpenordersRequest request);//获取合约当前未成交委托(全仓模式)
SwapCrossHisordersResponse swapCrossHisordersRequest(SwapCrossHisordersRequest request);//获取合约历史委托(全仓模式)
SwapCrossMatchresultsResponse swapCrossMatchresultsRequest(SwapCrossMatchresultsRequest request);//获取历史成交记录(全仓模式)
SwapCrossLightningClosePositionResponse swapCrossLightningClosePositionRequest(SwapCrossLightningClosePositionRequest request);//闪电平仓下单(全仓模式)
SwapCrossTriggerOrderResponse swapCrossTriggerOrderResponse(SwapCrossTriggerOrderRequest request);//计划委托下单(全仓模式)
SwapCrossTriggerCancelResponse swapCrossTriggerCancelResponse(SwapCrossTriggerCancelRequest request);//计划委托撤单(全仓模式)
SwapCrossTriggerCancelallResponse swapCrossTriggerCancelallResponse(SwapCrossTriggerCancelallRequest request);//计划委托合部撤单(全仓模式)
SwapCrossTriggerOpenordersResponse swapCrossTriggerOpenordersResponse(SwapCrossTriggerOpenordersRequest request);//获取计划委托当前委托(全仓模式)
SwapCrossTriggerHisordersResponse swapCrossTriggerHisordersResponse(SwapCrossTriggerHisordersRequest request);//获取计划委托历史委托(全仓模式)
SwapCrossSwitchLeverRateResponse getSwapCrossSwitchLeverRate(String contractCode, Integer lever_rate);//切换杠杆(全仓模式)
SwapTpslOrderResponse swapCrossTpslOrderResponse(SwapTpslOrderRequest request);
SwapTpslCancelResponse swapCrossTpslCancelResponse(SwapTpslCancelRequest request);
SwapTpslCancelallResponse swapCrossTpslCancelallResponse(SwapTpslCancelallRequest request);
SwapTpslOpenordersResponse swapCrossTpslOpenordersResponse(SwapTpslOpenordersRequest request);
SwapTpslHisordersResponse swapCrossTpslHisordersResponse(SwapTpslHisordersRequset request);
SwapRelationTpslOrderResponse swapCrossRelationTpslOrderResponse(SwapRelationTpslOrderRequest request);
SwapHisordersExactResponse swapCrossHisordersResponse(SwapHisordersExactRequest request);
SwapMatchresultsExactResponse swapCrossMatchresultsResponse(SwapMatchresultsExactRequest request);
SwapTrackOrderResponse swapCrossTrackOrderResponse(SwapTrackOrderRequest request);
SwapTrackCancelResponse swapCrossTrackCancelResponse(SwapTrackCancelRequest request);
SwapTrackCancelallResponse swapCrossTrackCancelallResponse(SwapTrackCancelallRequest request);
SwapTrackOpenordersResponse swapCrossTrackOpenordersResponse(SwapTrackOpenordersRequest request);
SwapTrackHisordersResponse swapCrossTrackHisordersResponse(SwapTrackHisordersRequest request);
}
| UTF-8 | Java | 3,813 | java | CrossTradeAPIService.java | Java | [] | null | [] | package com.huobi.api.crossservice.crosstrade;
import com.huobi.api.crossrequest.trade.*;
import com.huobi.api.crossresponse.trade.*;
import com.huobi.api.request.trade.*;
import com.huobi.api.response.trade.*;
public interface CrossTradeAPIService {
SwapCrossOrderResponse swapCrossOrderRequest(SwapCrossOrderRequest request);//合约下单(全仓模式)
SwapCrossBatchorderResponse swapCrossBatchorderRequest(SwapCrossBatchorderRequest request);//合约批量下单(全仓模式)
SwapCrossCancelResponse swapCrossCancelRequest(SwapCrossCancelRequest request);//撤销订单(全仓模式)
SwapCrossCancelallResponse swapCrossCancelallRequest(SwapCrossCancelallRequest request);//全部撤单(全仓模式)
SwapCrossOrderInfoResponse swapCrossOrderInfoRequest(SwapCrossOrderInfoRequest request);//获取合约订单信息(全仓模式)
SwapCrossOrderDetailResponse swapCrossOrderDetailRequest(SwapCrossOrderDetailRequest request);//获取订单明细信息(全仓模式)
SwapCrossOpenordersResponse swapCrossOpenordersRequest(SwapCrossOpenordersRequest request);//获取合约当前未成交委托(全仓模式)
SwapCrossHisordersResponse swapCrossHisordersRequest(SwapCrossHisordersRequest request);//获取合约历史委托(全仓模式)
SwapCrossMatchresultsResponse swapCrossMatchresultsRequest(SwapCrossMatchresultsRequest request);//获取历史成交记录(全仓模式)
SwapCrossLightningClosePositionResponse swapCrossLightningClosePositionRequest(SwapCrossLightningClosePositionRequest request);//闪电平仓下单(全仓模式)
SwapCrossTriggerOrderResponse swapCrossTriggerOrderResponse(SwapCrossTriggerOrderRequest request);//计划委托下单(全仓模式)
SwapCrossTriggerCancelResponse swapCrossTriggerCancelResponse(SwapCrossTriggerCancelRequest request);//计划委托撤单(全仓模式)
SwapCrossTriggerCancelallResponse swapCrossTriggerCancelallResponse(SwapCrossTriggerCancelallRequest request);//计划委托合部撤单(全仓模式)
SwapCrossTriggerOpenordersResponse swapCrossTriggerOpenordersResponse(SwapCrossTriggerOpenordersRequest request);//获取计划委托当前委托(全仓模式)
SwapCrossTriggerHisordersResponse swapCrossTriggerHisordersResponse(SwapCrossTriggerHisordersRequest request);//获取计划委托历史委托(全仓模式)
SwapCrossSwitchLeverRateResponse getSwapCrossSwitchLeverRate(String contractCode, Integer lever_rate);//切换杠杆(全仓模式)
SwapTpslOrderResponse swapCrossTpslOrderResponse(SwapTpslOrderRequest request);
SwapTpslCancelResponse swapCrossTpslCancelResponse(SwapTpslCancelRequest request);
SwapTpslCancelallResponse swapCrossTpslCancelallResponse(SwapTpslCancelallRequest request);
SwapTpslOpenordersResponse swapCrossTpslOpenordersResponse(SwapTpslOpenordersRequest request);
SwapTpslHisordersResponse swapCrossTpslHisordersResponse(SwapTpslHisordersRequset request);
SwapRelationTpslOrderResponse swapCrossRelationTpslOrderResponse(SwapRelationTpslOrderRequest request);
SwapHisordersExactResponse swapCrossHisordersResponse(SwapHisordersExactRequest request);
SwapMatchresultsExactResponse swapCrossMatchresultsResponse(SwapMatchresultsExactRequest request);
SwapTrackOrderResponse swapCrossTrackOrderResponse(SwapTrackOrderRequest request);
SwapTrackCancelResponse swapCrossTrackCancelResponse(SwapTrackCancelRequest request);
SwapTrackCancelallResponse swapCrossTrackCancelallResponse(SwapTrackCancelallRequest request);
SwapTrackOpenordersResponse swapCrossTrackOpenordersResponse(SwapTrackOpenordersRequest request);
SwapTrackHisordersResponse swapCrossTrackHisordersResponse(SwapTrackHisordersRequest request);
}
| 3,813 | 0.871139 | 0.871139 | 66 | 50.5 | 51.819107 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530303 | false | false | 3 |
cec01279876ba95771065e797da08875ec8a3cf7 | 19,825,569,070,833 | 733fbea7303d22e9fb547b03525216bb0160ce0a | /app/src/main/java/com/ljubeboskovski/drmario/game/components/BodyComponent.java | eb79869ce562db89bd22c7046e29c83c30fd8712 | [] | no_license | LjubeBoskovski/android_opengles | https://github.com/LjubeBoskovski/android_opengles | c55665a4e6508712ac40db0b5425a325a535eab9 | be1f04a1f423485349f0ffa4c3e441395eca3ba2 | refs/heads/master | 2022-04-29T04:22:38.970000 | 2022-04-23T22:04:07 | 2022-04-23T22:04:07 | 246,099,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ljubeboskovski.drmario.game.components;
import com.ljubeboskovski.drmario.game.PlaygroundJBox2D;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
public class BodyComponent extends BaseComponent {
World b2World;
BodyDef bodyDef;
PolygonShape shape;
FixtureDef fixtureDef;
public BodyComponent(World b2World, Vec2 position, Object userData) {
this.b2World = b2World;
bodyDef = new BodyDef();
bodyDef.position = position;
bodyDef.angle = 0.0f;
bodyDef.linearVelocity = new Vec2(0.0f, 0.0f);
bodyDef.angularVelocity = 0.0f;
bodyDef.fixedRotation = false;
bodyDef.active = true;
bodyDef.bullet = false;
bodyDef.allowSleep = true;
bodyDef.gravityScale = 1.0f;
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = userData;
bodyDef.type = BodyType.DYNAMIC;
shape = new PolygonShape();
shape.setAsBox(0.5f, 0.5f);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.userData = null;
fixtureDef.friction = 0.35f;
fixtureDef.restitution = 0.05f;
fixtureDef.density = 0.75f;
fixtureDef.isSensor = false;
Body body = b2World.createBody(bodyDef);
body.createFixture(fixtureDef);
}
@Override
public void update(float dt) {
}
}
| UTF-8 | Java | 1,635 | java | BodyComponent.java | Java | [
{
"context": "package com.ljubeboskovski.drmario.game.components;\n\nimport com.ljubeboskovs",
"end": 26,
"score": 0.9260022044181824,
"start": 12,
"tag": "USERNAME",
"value": "ljubeboskovski"
},
{
"context": "ubeboskovski.drmario.game.components;\n\nimport com.ljubeboskovski.drmario... | null | [] | package com.ljubeboskovski.drmario.game.components;
import com.ljubeboskovski.drmario.game.PlaygroundJBox2D;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
public class BodyComponent extends BaseComponent {
World b2World;
BodyDef bodyDef;
PolygonShape shape;
FixtureDef fixtureDef;
public BodyComponent(World b2World, Vec2 position, Object userData) {
this.b2World = b2World;
bodyDef = new BodyDef();
bodyDef.position = position;
bodyDef.angle = 0.0f;
bodyDef.linearVelocity = new Vec2(0.0f, 0.0f);
bodyDef.angularVelocity = 0.0f;
bodyDef.fixedRotation = false;
bodyDef.active = true;
bodyDef.bullet = false;
bodyDef.allowSleep = true;
bodyDef.gravityScale = 1.0f;
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = userData;
bodyDef.type = BodyType.DYNAMIC;
shape = new PolygonShape();
shape.setAsBox(0.5f, 0.5f);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.userData = null;
fixtureDef.friction = 0.35f;
fixtureDef.restitution = 0.05f;
fixtureDef.density = 0.75f;
fixtureDef.isSensor = false;
Body body = b2World.createBody(bodyDef);
body.createFixture(fixtureDef);
}
@Override
public void update(float dt) {
}
}
| 1,635 | 0.667278 | 0.640979 | 58 | 27.189655 | 17.941916 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.741379 | false | false | 3 |
28641441bd49cabb901418a01c4efdbf0894fa1b | 36,266,703,864,221 | 1b827843eb5e26778a7baec52c46efe78ccd888c | /src/main/java/com/actions/prototype/dao/ActionDao.java | 1a8ea6443121072350f0ce85dff3eb98149b904c | [] | no_license | tomarto/prototype-rest | https://github.com/tomarto/prototype-rest | b952dd8a3f515e73eb28eb3fa4db04d5ba09dd85 | e7220be258502fa838d5853c7cec305f667559d6 | refs/heads/master | 2021-01-21T13:08:00.397000 | 2016-04-22T15:49:14 | 2016-04-22T15:49:14 | 43,894,005 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.actions.prototype.dao;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.actions.prototype.model.resource.action.Action;
import com.actions.prototype.model.resource.action.ActionListResponse;
import com.actions.prototype.request.action.ActionRequest;
/**
* <p>
* ActionDao interface.
* </p>
*
* @author Omar Ortiz.
*/
public interface ActionDao {
/**
* <p>
* Retrieves all the Action records from database.
* </p>
*
* @param request
* a {@link com.actions.prototype.request.action.ActionRequest} object.
*
* @return a {@link com.actions.prototype.model.resource.action.ActionListResponse} object.
*/
ActionListResponse findAll(ActionRequest request);
/**
* <p>
* Insert an Action record to database.
* </p>
*
* @param action
* a {@link com.actions.prototype.model.resource.action.Action} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean insert(Action action);
/**
* <p>
* Update an Action record from database.
* </p>
*
* @param action
* a {@link com.actions.prototype.model.resource.action.Action} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean update(Action action);
/**
* <p>
* Delete an Action record from database.
* </p>
*
* @param id
* a {@link java.lang.Integer} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean delete(Integer id);
/**
* @param name the name to set. For unit test purposes.
*/
void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate);
}
| UTF-8 | Java | 1,641 | java | ActionDao.java | Java | [
{
"context": "<p>\n * ActionDao interface.\n * </p>\n * \n * @author Omar Ortiz.\n */\npublic interface ActionDao {\n\t\n\t/**\n\t * <p>\n",
"end": 371,
"score": 0.9998553395271301,
"start": 361,
"tag": "NAME",
"value": "Omar Ortiz"
}
] | null | [] | package com.actions.prototype.dao;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.actions.prototype.model.resource.action.Action;
import com.actions.prototype.model.resource.action.ActionListResponse;
import com.actions.prototype.request.action.ActionRequest;
/**
* <p>
* ActionDao interface.
* </p>
*
* @author <NAME>.
*/
public interface ActionDao {
/**
* <p>
* Retrieves all the Action records from database.
* </p>
*
* @param request
* a {@link com.actions.prototype.request.action.ActionRequest} object.
*
* @return a {@link com.actions.prototype.model.resource.action.ActionListResponse} object.
*/
ActionListResponse findAll(ActionRequest request);
/**
* <p>
* Insert an Action record to database.
* </p>
*
* @param action
* a {@link com.actions.prototype.model.resource.action.Action} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean insert(Action action);
/**
* <p>
* Update an Action record from database.
* </p>
*
* @param action
* a {@link com.actions.prototype.model.resource.action.Action} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean update(Action action);
/**
* <p>
* Delete an Action record from database.
* </p>
*
* @param id
* a {@link java.lang.Integer} object.
*
* @return a {@link java.lang.Boolean} object.
*/
Boolean delete(Integer id);
/**
* @param name the name to set. For unit test purposes.
*/
void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate);
}
| 1,637 | 0.656307 | 0.656307 | 70 | 22.442858 | 25.490971 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 3 |
7a5aea10e3bf3f4af3958c872ed9dc2a73aa1aeb | 23,983,097,429,568 | ad1d31fa52e2bf51a4a09d4453b75a1a8e4f2246 | /Utilities/Color.java | 9dafb208d683cc369c2830c96f63bb992b1a6403 | [] | no_license | Shadowhnr/POO-trab3 | https://github.com/Shadowhnr/POO-trab3 | 099201578654c3cacc036ac32d41ffc6fca8429d | d32bcb159665d883220a7b1596242e250a9762d6 | refs/heads/master | 2021-01-23T22:10:36.014000 | 2014-12-14T21:16:55 | 2014-12-14T21:16:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Utilities;
//enumeracao que representara a cor dos times
public enum Color
{
//esses campos sao constantes, por isso o nome em maiusculo:
BLUE(0,0,255),
RED(255,0,0),
GREEN(0,255,0),
YELLOW(255,255,0),
WHITE(255,255,255),
BLACK(0,0,0);
//valores rgb para cores:
private int red;
private int green;
private int blue;
//construtor de enum's precisa ser private ou package-private:
Color(int red,int green,int blue)
{
this.red=red;
this.green=green;
this.blue=blue;
}
}
| UTF-8 | Java | 497 | java | Color.java | Java | [] | null | [] | package Utilities;
//enumeracao que representara a cor dos times
public enum Color
{
//esses campos sao constantes, por isso o nome em maiusculo:
BLUE(0,0,255),
RED(255,0,0),
GREEN(0,255,0),
YELLOW(255,255,0),
WHITE(255,255,255),
BLACK(0,0,0);
//valores rgb para cores:
private int red;
private int green;
private int blue;
//construtor de enum's precisa ser private ou package-private:
Color(int red,int green,int blue)
{
this.red=red;
this.green=green;
this.blue=blue;
}
}
| 497 | 0.704225 | 0.635815 | 23 | 20.565218 | 16.051077 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.130435 | false | false | 3 |
470f95eaad4f8a51ec36d759ac6985fb276c1383 | 14,422,500,226,066 | 2feda664019e45d01aed28adfe52e405b9fce431 | /src/com/leetcode_cn/easy/IncreasingDecreasingString.java | abe8dea37c5b588891172e3e025ac4dca1983745 | [] | no_license | Folgerjun/leetcode-cn | https://github.com/Folgerjun/leetcode-cn | 0b8c7c86cfbdbcb9b738c4e6ef67f7fe42bcb398 | bb46ac96417969d48000f7628e810893648cf9b4 | refs/heads/master | 2021-06-05T04:20:54.295000 | 2020-06-12T02:51:49 | 2020-06-12T02:51:49 | 142,521,732 | 11 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leetcode_cn.easy;
/********上升下降字符串******/
/**
* 给你一个字符串 s ,请你根据下面的算法重新构造字符串:
*
* 1.从 s 中选出 最小 的字符,将它 接在 结果字符串的后面。
* 2.从 s 剩余字符中选出 最小 的字符,且该字符比上一个添加的字符大,将它 接在 结果字符串后面。
* 3.重复步骤 2 ,直到你没法从 s 中选择字符。
* 4.从 s 中选出 最大 的字符,将它 接在 结果字符串的后面。
* 5.从 s 剩余字符中选出 最大 的字符,且该字符比上一个添加的字符小,将它 接在 结果字符串后面。
* 6.重复步骤 5 ,直到你没法从 s 中选择字符。
*
* 重复步骤 1 到 6 ,直到 s 中所有字符都已经被选过。
* 在任何一步中,如果最小或者最大字符不止一个 ,你可以选择其中任意一个,并将其添加到结果字符串。
*
* 请你返回将 s 中字符重新排序后的 结果字符串 。
*
*
* 示例 1:
*
* 输入:s = "aaaabbbbcccc"
* 输出:"abccbaabccba"
* 解释:第一轮的步骤 1,2,3 后,结果字符串为 result = "abc"
* 第一轮的步骤 4,5,6 后,结果字符串为 result = "abccba"
* 第一轮结束,现在 s = "aabbcc" ,我们再次回到步骤 1
* 第二轮的步骤 1,2,3 后,结果字符串为 result = "abccbaabc"
* 第二轮的步骤 4,5,6 后,结果字符串为 result = "abccbaabccba"
*
* 示例 2:
*
* 输入:s = "rat"
* 输出:"art"
* 解释:单词 "rat" 在上述算法重排序以后变成 "art"
* 示例 3:
*
* 输入:s = "leetcode"
* 输出:"cdelotee"
* 示例 4:
*
* 输入:s = "ggggggg"
* 输出:"ggggggg"
* 示例 5:
*
* 输入:s = "spo"
* 输出:"ops"
*
* 提示:
*
* 1 <= s.length <= 500
* s 只包含小写英文字母。
*
*/
public class IncreasingDecreasingString {
public static void main(String[] args) {
System.out.println(sortString("aaaabbbbcccc"));
}
public static String sortString(String s) {
if (s == null || s == "") return "";
int[] letterNums = new int[26];
char[] letters = s.toCharArray();
StringBuilder result = new StringBuilder();
// 遍历统计相同字符个数
for (char letter : letters) {
letterNums[letter - 'a']++;
}
while (hasNum(letterNums)) {
// 先从小到大
for (int i = 0; i < letterNums.length; i++) {
if (letterNums[i] > 0) {
result.append((char)(i + 'a'));
letterNums[i]--;
}
}
// 再从大到小
for (int i = letterNums.length - 1; i >= 0; i--) {
if (letterNums[i] > 0) {
result.append((char)(i + 'a'));
letterNums[i]--;
}
}
}
return result.toString();
}
/**
* 判断是否还有剩余的字符未被处理
* @param letterNums
* @return
*/
private static boolean hasNum(int[] letterNums) {
for (int letterNum : letterNums) {
if (letterNum > 0)
return true;
}
return false;
}
}
| UTF-8 | Java | 3,323 | java | IncreasingDecreasingString.java | Java | [] | null | [] | package com.leetcode_cn.easy;
/********上升下降字符串******/
/**
* 给你一个字符串 s ,请你根据下面的算法重新构造字符串:
*
* 1.从 s 中选出 最小 的字符,将它 接在 结果字符串的后面。
* 2.从 s 剩余字符中选出 最小 的字符,且该字符比上一个添加的字符大,将它 接在 结果字符串后面。
* 3.重复步骤 2 ,直到你没法从 s 中选择字符。
* 4.从 s 中选出 最大 的字符,将它 接在 结果字符串的后面。
* 5.从 s 剩余字符中选出 最大 的字符,且该字符比上一个添加的字符小,将它 接在 结果字符串后面。
* 6.重复步骤 5 ,直到你没法从 s 中选择字符。
*
* 重复步骤 1 到 6 ,直到 s 中所有字符都已经被选过。
* 在任何一步中,如果最小或者最大字符不止一个 ,你可以选择其中任意一个,并将其添加到结果字符串。
*
* 请你返回将 s 中字符重新排序后的 结果字符串 。
*
*
* 示例 1:
*
* 输入:s = "aaaabbbbcccc"
* 输出:"abccbaabccba"
* 解释:第一轮的步骤 1,2,3 后,结果字符串为 result = "abc"
* 第一轮的步骤 4,5,6 后,结果字符串为 result = "abccba"
* 第一轮结束,现在 s = "aabbcc" ,我们再次回到步骤 1
* 第二轮的步骤 1,2,3 后,结果字符串为 result = "abccbaabc"
* 第二轮的步骤 4,5,6 后,结果字符串为 result = "abccbaabccba"
*
* 示例 2:
*
* 输入:s = "rat"
* 输出:"art"
* 解释:单词 "rat" 在上述算法重排序以后变成 "art"
* 示例 3:
*
* 输入:s = "leetcode"
* 输出:"cdelotee"
* 示例 4:
*
* 输入:s = "ggggggg"
* 输出:"ggggggg"
* 示例 5:
*
* 输入:s = "spo"
* 输出:"ops"
*
* 提示:
*
* 1 <= s.length <= 500
* s 只包含小写英文字母。
*
*/
public class IncreasingDecreasingString {
public static void main(String[] args) {
System.out.println(sortString("aaaabbbbcccc"));
}
public static String sortString(String s) {
if (s == null || s == "") return "";
int[] letterNums = new int[26];
char[] letters = s.toCharArray();
StringBuilder result = new StringBuilder();
// 遍历统计相同字符个数
for (char letter : letters) {
letterNums[letter - 'a']++;
}
while (hasNum(letterNums)) {
// 先从小到大
for (int i = 0; i < letterNums.length; i++) {
if (letterNums[i] > 0) {
result.append((char)(i + 'a'));
letterNums[i]--;
}
}
// 再从大到小
for (int i = letterNums.length - 1; i >= 0; i--) {
if (letterNums[i] > 0) {
result.append((char)(i + 'a'));
letterNums[i]--;
}
}
}
return result.toString();
}
/**
* 判断是否还有剩余的字符未被处理
* @param letterNums
* @return
*/
private static boolean hasNum(int[] letterNums) {
for (int letterNum : letterNums) {
if (letterNum > 0)
return true;
}
return false;
}
}
| 3,323 | 0.509362 | 0.49234 | 101 | 22.267326 | 17.526157 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.19802 | false | false | 3 |
7f2afd63c90538e35412093e2651a135ccc042b1 | 9,053,791,123,816 | 206d15befecdfb67a93c61c935c2d5ae7f6a79e9 | /sina_microblog/src/mobile/android/demo/sina/microblog/BigPicture.java | 35867162168fa498f1732bb89a91ff4c4fb0feb5 | [] | no_license | MarkChege/micandroid | https://github.com/MarkChege/micandroid | 2e4d2884929548a814aa0a7715727c84dc4dcdab | 0b0a6dee39cf7e258b6f54e1103dcac8dbe1c419 | refs/heads/master | 2021-01-10T19:15:34.994000 | 2013-05-16T05:56:21 | 2013-05-16T05:56:21 | 34,704,029 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mobile.android.demo.sina.microblog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class BigPicture extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bigpicture);
ImageView ivBigPicture = (ImageView)findViewById(R.id.ivBigPicture);
ivBigPicture.setImageBitmap(MicroBlog.mBitmap);
}
}
| UTF-8 | Java | 485 | java | BigPicture.java | Java | [] | null | [] | package mobile.android.demo.sina.microblog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class BigPicture extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bigpicture);
ImageView ivBigPicture = (ImageView)findViewById(R.id.ivBigPicture);
ivBigPicture.setImageBitmap(MicroBlog.mBitmap);
}
}
| 485 | 0.742268 | 0.742268 | 24 | 18.208334 | 21.181713 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 3 |
b90a47d099e0f9afb9acc4e77f99414dee7cb99b | 1,245,540,553,492 | 5ca5a02ece72d3aec4c45e721dd1655f539fca52 | /lesson03/Example1.java | f2e5c19983ce639282469cf99b65f7b0633951a9 | [] | no_license | yjll1019/Algorithm_lesson | https://github.com/yjll1019/Algorithm_lesson | 611f168b8d09c15a47fa2323b0f566f66e394fe1 | 1f5a1c759631e82a9eec6454909689528d72c358 | refs/heads/master | 2021-04-03T02:49:56.290000 | 2018-06-19T15:44:56 | 2018-06-19T15:44:56 | 124,913,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lesson03;
//findMin2 selectionSort2 아직 이해 ㄴㄴㄴ!
import java.util.Arrays;
/*
* 작성일 : 2018년 03월 23일
* 내 용 : 선택정렬(selection sort) 구현
*/
public class Example1 {
static void swap(int[] a, int i, int j) {
//배열 a에서 a[i]와 a[j]의 값을 바꿔주는 메소드 swap
//O(1)
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int findMin(int[] a, int start) {
//배열 a[start]에서 부터 끝까지 원소 중 가장 작은 값의 위치(인덱스)를 리턴하는 메소드 findMin
//앞에서부터 시작해 최솟값을 찾아 앞에 위치시키는 방식
//O(n)
int min = start;
for(int i=start; i<a.length; ++i) {
if(a[min] > a[i])
min = i;
}
return min;
}
static int findMin2(int[] a, int start) {
//배열 a[start]에서부터 끝까지원소 중 가장 작은 값의 위치(인덱스)를 리턴하는 메소드 findMin2
//뒤에서부터 시작해 최댓값을 찾아 뒤에 위치시키는 방식
//O(n)
int max = a.length-1;
for(int i=a.length-1; i<=1; --i) {
if(a[max] < a[i])
max = i;
}
return max;
}
static void selectionSort(int[] a) {
//O(log n)
int min=0;
for(int i=0; i<a.length-1; ++i) { //어쩌피 마지막 인덱스부터 마지막 인덱스까지 비교하는게 의미가 없기 때문에 a.length-1임.
min = findMin(a, i); //i의 위치부터 a[i]보다 작은 중 제일 작은 값의 인덱스를 리턴, 없으면 그대로 i리턴
if(min!=i) swap(a, i, min); //min과 i가 다르면(그대로 i가 아닌 가장 작은 값이 리턴 되었다면) a[i]와 a[min]의 값을 바꾼다.
}
}
static void selectionSort2(int[] a) {
//O(log n)
int min=0;
for(int i=a.length-1; i<=1; ++i) { //어쩌피 마지막 인덱스부터 마지막 인덱스까지 비교하는게 의미가 없기 때문에 a.length-1임.
min = findMin2(a, i); //i의 위치부터 a[i]보다 작은 중 제일 작은 값의 인덱스를 리턴, 없으면 그대로 i리턴
if(min!=i) swap(a, i, min); //min과 i가 다르면(그대로 i가 아닌 가장 작은 값이 리턴 되었다면) a[i]와 a[min]의 값을 바꾼다.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("lesson03_Example1 : 이예지");
int [] a = {17, 14, 11, 19, 13, 15, 18, 12, 16, 20 };
selectionSort(a); //O(n)
System.out.println(Arrays.toString(a));
selectionSort2(a); //O(n)
System.out.println(Arrays.toString(a));
}
}
| UHC | Java | 2,534 | java | Example1.java | Java | [] | null | [] | package lesson03;
//findMin2 selectionSort2 아직 이해 ㄴㄴㄴ!
import java.util.Arrays;
/*
* 작성일 : 2018년 03월 23일
* 내 용 : 선택정렬(selection sort) 구현
*/
public class Example1 {
static void swap(int[] a, int i, int j) {
//배열 a에서 a[i]와 a[j]의 값을 바꿔주는 메소드 swap
//O(1)
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int findMin(int[] a, int start) {
//배열 a[start]에서 부터 끝까지 원소 중 가장 작은 값의 위치(인덱스)를 리턴하는 메소드 findMin
//앞에서부터 시작해 최솟값을 찾아 앞에 위치시키는 방식
//O(n)
int min = start;
for(int i=start; i<a.length; ++i) {
if(a[min] > a[i])
min = i;
}
return min;
}
static int findMin2(int[] a, int start) {
//배열 a[start]에서부터 끝까지원소 중 가장 작은 값의 위치(인덱스)를 리턴하는 메소드 findMin2
//뒤에서부터 시작해 최댓값을 찾아 뒤에 위치시키는 방식
//O(n)
int max = a.length-1;
for(int i=a.length-1; i<=1; --i) {
if(a[max] < a[i])
max = i;
}
return max;
}
static void selectionSort(int[] a) {
//O(log n)
int min=0;
for(int i=0; i<a.length-1; ++i) { //어쩌피 마지막 인덱스부터 마지막 인덱스까지 비교하는게 의미가 없기 때문에 a.length-1임.
min = findMin(a, i); //i의 위치부터 a[i]보다 작은 중 제일 작은 값의 인덱스를 리턴, 없으면 그대로 i리턴
if(min!=i) swap(a, i, min); //min과 i가 다르면(그대로 i가 아닌 가장 작은 값이 리턴 되었다면) a[i]와 a[min]의 값을 바꾼다.
}
}
static void selectionSort2(int[] a) {
//O(log n)
int min=0;
for(int i=a.length-1; i<=1; ++i) { //어쩌피 마지막 인덱스부터 마지막 인덱스까지 비교하는게 의미가 없기 때문에 a.length-1임.
min = findMin2(a, i); //i의 위치부터 a[i]보다 작은 중 제일 작은 값의 인덱스를 리턴, 없으면 그대로 i리턴
if(min!=i) swap(a, i, min); //min과 i가 다르면(그대로 i가 아닌 가장 작은 값이 리턴 되었다면) a[i]와 a[min]의 값을 바꾼다.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("lesson03_Example1 : 이예지");
int [] a = {17, 14, 11, 19, 13, 15, 18, 12, 16, 20 };
selectionSort(a); //O(n)
System.out.println(Arrays.toString(a));
selectionSort2(a); //O(n)
System.out.println(Arrays.toString(a));
}
}
| 2,534 | 0.591006 | 0.562634 | 76 | 23.578947 | 24.987503 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.276316 | false | false | 3 |
889295d41fdd17e245957edf48c4c9b331b02e2e | 901,943,174,248 | 5b31d51c77a49c897f664c58f5eeb798505b57aa | /JSS_Research/src/app/evolution/multitask/jump/FitnessProbabilityJump2.java | 722e4a7ea7f348437b8a9d185c75c738d8a26b24 | [] | no_license | johnskpark/jss-research | https://github.com/johnskpark/jss-research | 769653bad8f0178d41a2eef1cc82bfed59856505 | bfee314549f875e5b01a777252364cad5d4e3d40 | refs/heads/master | 2020-05-21T06:27:33.830000 | 2019-07-14T08:45:07 | 2019-07-14T08:45:07 | 185,933,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.evolution.multitask.jump;
import app.evolution.multitask.JasimaMultitaskIndividual;
import ec.EvolutionState;
import ec.util.Parameter;
public class FitnessProbabilityJump2 extends FitnessProbabilityJump {
private static final long serialVersionUID = 5953377944185011148L;
@Override
public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
}
@Override
public boolean jumpToNeighbour(final EvolutionState state,
final int subpopulation,
final int currentTask,
final int neighbourTask,
final JasimaMultitaskIndividual ind,
final int threadnum) {
// Calculate the probability from the fitness using min-max normalisation
// to bring the fitness value in between 0.0 and 1.0 first.
double taskFitness = ind.getTaskFitness(currentTask);
double minFitness = getBestIndsPerTask()[subpopulation][currentTask].getTaskFitness(currentTask);
double maxFitness = getWorstIndsPerTask()[subpopulation][currentTask].getTaskFitness(currentTask);
double prob = 1.0 - (taskFitness - minFitness) / (maxFitness - minFitness);
probabilityOutput(state, prob, taskFitness, maxFitness, minFitness);
return getRand().nextBoolean(prob);
}
}
| UTF-8 | Java | 1,214 | java | FitnessProbabilityJump2.java | Java | [] | null | [] | package app.evolution.multitask.jump;
import app.evolution.multitask.JasimaMultitaskIndividual;
import ec.EvolutionState;
import ec.util.Parameter;
public class FitnessProbabilityJump2 extends FitnessProbabilityJump {
private static final long serialVersionUID = 5953377944185011148L;
@Override
public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
}
@Override
public boolean jumpToNeighbour(final EvolutionState state,
final int subpopulation,
final int currentTask,
final int neighbourTask,
final JasimaMultitaskIndividual ind,
final int threadnum) {
// Calculate the probability from the fitness using min-max normalisation
// to bring the fitness value in between 0.0 and 1.0 first.
double taskFitness = ind.getTaskFitness(currentTask);
double minFitness = getBestIndsPerTask()[subpopulation][currentTask].getTaskFitness(currentTask);
double maxFitness = getWorstIndsPerTask()[subpopulation][currentTask].getTaskFitness(currentTask);
double prob = 1.0 - (taskFitness - minFitness) / (maxFitness - minFitness);
probabilityOutput(state, prob, taskFitness, maxFitness, minFitness);
return getRand().nextBoolean(prob);
}
}
| 1,214 | 0.788303 | 0.766886 | 36 | 32.722221 | 30.952124 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.75 | false | false | 3 |
a1e6112159f56fbe07f9eace1e2eeb9c5bc05055 | 29,351,806,505,627 | 255ff79057c0ff14d0b760fc2d6da1165f1806c8 | /01JavaStep01/第二阶段资料/二阶day3资料/案例/学员练习代码/myArgs/src/com/itheima_03/JumppingDemo.java | bd7c4e3abddb6574b45ebac87a283fe39625a020 | [] | no_license | wjphappy90/Resource | https://github.com/wjphappy90/Resource | 7f1f817d323db5adae06d26da17dfc09ee5f9d3a | 6574c8399f3cdfb6d6b39cd64dc9507e784a2549 | refs/heads/master | 2022-07-30T03:33:59.869000 | 2020-08-10T02:31:35 | 2020-08-10T02:31:35 | 285,701,650 | 2 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itheima_03;
/*
测试类
*/
public class JumppingDemo {
public static void main(String[] args) {
//创建操作类对象,并调用方法
}
}
| UTF-8 | Java | 178 | java | JumppingDemo.java | Java | [] | null | [] | package com.itheima_03;
/*
测试类
*/
public class JumppingDemo {
public static void main(String[] args) {
//创建操作类对象,并调用方法
}
}
| 178 | 0.59589 | 0.582192 | 11 | 12.272727 | 13.994096 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.090909 | false | false | 3 |
c9d7431cf464b4828c5a654bdb6db0685d26ea22 | 9,448,928,108,354 | 4e3a8e9e97aa5c0bfcb85a9164bea69ac2e1234d | /max holes/holes.java | baacd846fbbcd84fb4cc00398d0b7aa11c054899 | [] | no_license | saurav0705/java | https://github.com/saurav0705/java | f427eb9c5dfcf372ae68ecdfd6443017ee965ed5 | 019a8dd4e1d0a8a42bdb4e5bc9fa510de78f873a | refs/heads/master | 2021-07-06T14:04:50.647000 | 2019-03-16T09:39:36 | 2019-03-16T09:39:36 | 143,140,082 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class holes{
public static int maxholes(int arr[])
{
int max=0;
for(int i=0;i<5;i++)
{
if(arr[i]==8)
{max=2;
break;}
else if(arr[i]==4 ||arr[i]==6 ||arr[i]==9)
max=1;
}
return max;
}
public static void main(String[] args) {
int array[]= new int[5];
array[0]=1;
array[1]=1;
array[2]=1;
array[3]=4;
array[4]=1;
System.out.println("Max Holes:: "+maxholes(array));
}
} | UTF-8 | Java | 588 | java | holes.java | Java | [] | null | [] | class holes{
public static int maxholes(int arr[])
{
int max=0;
for(int i=0;i<5;i++)
{
if(arr[i]==8)
{max=2;
break;}
else if(arr[i]==4 ||arr[i]==6 ||arr[i]==9)
max=1;
}
return max;
}
public static void main(String[] args) {
int array[]= new int[5];
array[0]=1;
array[1]=1;
array[2]=1;
array[3]=4;
array[4]=1;
System.out.println("Max Holes:: "+maxholes(array));
}
} | 588 | 0.380952 | 0.346939 | 24 | 23.541666 | 14.988827 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
233543dc67279f8502f9a5c0f1e069de0226f992 | 9,448,928,105,324 | 5b9c37ecdd7978f2ce73d3945fda10f8e0c6a619 | /app/src/main/java/com/syrovama/fragmentstask/RandomService.java | 93da0804aadfd619fcd3bce1e2277902785f81f6 | [] | no_license | syrmaria/FragmentsTask | https://github.com/syrmaria/FragmentsTask | 74dd3bbadf4fa1dc6d93e75ee5133b44dd08b718 | 9157f6094df867afc0ee89847590aced1675dfe0 | refs/heads/master | 2020-04-08T20:34:09.296000 | 2018-11-29T19:13:07 | 2018-11-29T19:13:07 | 159,705,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.syrovama.fragmentstask;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import java.util.Random;
/*
Creates random number and sends it in broadcast
*/
public class RandomService extends JobIntentService {
private static final String TAG = "RandomService";
private static final int JOB_ID = 1000;
private Random random = new Random();
public static final String ACTION = "com.syrovama.fragmentstask.numberAction";
public static final String EXTRA_NUMBER = "NUMBER";
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, RandomService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Log.d(TAG, "Handle work");
int newNumber = random.nextInt();
Intent broadcastIntent = new Intent(ACTION);
broadcastIntent.putExtra(EXTRA_NUMBER, newNumber);
sendBroadcast(broadcastIntent);
}
public static Intent newIntent(Context c) {
return new Intent(c, RandomService.class);
}
}
| UTF-8 | Java | 1,179 | java | RandomService.java | Java | [] | null | [] | package com.syrovama.fragmentstask;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import java.util.Random;
/*
Creates random number and sends it in broadcast
*/
public class RandomService extends JobIntentService {
private static final String TAG = "RandomService";
private static final int JOB_ID = 1000;
private Random random = new Random();
public static final String ACTION = "com.syrovama.fragmentstask.numberAction";
public static final String EXTRA_NUMBER = "NUMBER";
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, RandomService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
Log.d(TAG, "Handle work");
int newNumber = random.nextInt();
Intent broadcastIntent = new Intent(ACTION);
broadcastIntent.putExtra(EXTRA_NUMBER, newNumber);
sendBroadcast(broadcastIntent);
}
public static Intent newIntent(Context c) {
return new Intent(c, RandomService.class);
}
}
| 1,179 | 0.722646 | 0.718405 | 37 | 30.864864 | 23.475304 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.702703 | false | false | 3 |
82b7581634b9efa53fc1771642eae57931b429f0 | 18,133,351,986,331 | 5740dcc3c57560c3498dc38530534f1cbb11d877 | /MultiShop2/src/main/java/com/poly/main/Validator/UserLoginValidator.java | f074cc765b627052caf5f960ad8862795a70c30d | [] | no_license | khoahoang555/MultiShop | https://github.com/khoahoang555/MultiShop | 405bfffe2598022b53c0e66a4bbad4f231e17c22 | 134246783179b77976db301c6ec90fb0080b79cd | refs/heads/master | 2023-06-12T14:08:03.798000 | 2021-07-07T03:02:12 | 2021-07-07T03:02:12 | 382,974,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.poly.main.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.poly.main.Dao.UserDao;
import com.poly.main.Entity.User;
import com.poly.main.Model.UserLogin;
import com.poly.main.Service.SessionService;
@Component
public class UserLoginValidator implements Validator {
@Autowired
private UserDao dao;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return clazz == UserLogin.class;
}
@Override
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
UserLogin entity = (UserLogin) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotBlank.userLogin.username");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotBlank.userLogin.password");
if (!errors.hasFieldErrors()) {
User user = dao.findByEmail(entity.getUsername());
if (user == null) {
errors.rejectValue("username", "NotFind.userLogin.username");
errors.rejectValue("password", "NotFind.userLogin.password");
}
else {
// passwordEncoder.matches(user.getPassword(), entity.getPassword())
// if(user.getPassword().equals(entity.getPassword()) == false) {
if(passwordEncoder.matches(entity.getPassword(), user.getPassword()) == false) {
errors.rejectValue("password", "NotFind.userLogin.password");
}
//errors.rejectValue("password", "NotFind.userLogin.password");
}
}
}
}
| UTF-8 | Java | 1,839 | java | UserLoginValidator.java | Java | [
{
"context": "ls.rejectIfEmptyOrWhitespace(errors, \"password\", \"NotBlank.userLogin.password\");\r\n\r\n\t\tif (!errors.hasFieldErrors()) {\r\n\t\t\tUser ",
"end": 1172,
"score": 0.9964799284934998,
"start": 1145,
"tag": "PASSWORD",
"value": "NotBlank.userLogin.password"
},
{
"cont... | null | [] | package com.poly.main.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.poly.main.Dao.UserDao;
import com.poly.main.Entity.User;
import com.poly.main.Model.UserLogin;
import com.poly.main.Service.SessionService;
@Component
public class UserLoginValidator implements Validator {
@Autowired
private UserDao dao;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return clazz == UserLogin.class;
}
@Override
public void validate(Object target, Errors errors) {
// TODO Auto-generated method stub
UserLogin entity = (UserLogin) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotBlank.userLogin.username");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "<PASSWORD>");
if (!errors.hasFieldErrors()) {
User user = dao.findByEmail(entity.getUsername());
if (user == null) {
errors.rejectValue("username", "NotFind.userLogin.username");
errors.rejectValue("password", "<PASSWORD>");
}
else {
// passwordEncoder.matches(user.getPassword(), entity.getPassword())
// if(user.getPassword().equals(entity.getPassword()) == false) {
if(passwordEncoder.matches(entity.getPassword(), user.getPassword()) == false) {
errors.rejectValue("password", "<PASSWORD>");
}
//errors.rejectValue("password", "<PASSWORD>");
}
}
}
}
| 1,774 | 0.737901 | 0.737901 | 54 | 32.055557 | 27.687687 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.981481 | false | false | 3 |
7c73f2c307dc304de0c1a5ebab766e8f6207d0e3 | 19,095,424,665,709 | 4b4ac5e703d73db511a26c28e9ef8e35d59b509b | /src/test/java/com/fishercoder/_1394Test.java | 81d5b06a9ce83663861a74a523a89d505a864d7a | [
"Apache-2.0"
] | permissive | fishercoder1534/Leetcode | https://github.com/fishercoder1534/Leetcode | b850a4db143a79337aebd7093c09077ff5c23f96 | 1c3a15d31c4a2ffdb3e5553aecce531be21c5c84 | refs/heads/master | 2023-09-03T01:53:48.011000 | 2023-06-11T17:55:37 | 2023-06-11T17:55:37 | 64,578,459 | 3,950 | 1,510 | Apache-2.0 | false | 2023-06-26T15:14:16 | 2016-07-31T05:28:15 | 2023-06-26T15:03:52 | 2023-06-26T15:14:15 | 8,914 | 3,580 | 1,243 | 17 | Java | false | false | package com.fishercoder;
import com.fishercoder.solutions._1394;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _1394Test {
private static _1394.Solution1 solution1;
@BeforeClass
public static void setup() {
solution1 = new _1394.Solution1();
}
@Test
public void test1() {
assertEquals(2, solution1.findLucky(new int[]{2, 2, 3, 4}));
}
@Test
public void test2() {
assertEquals(3, solution1.findLucky(new int[]{1, 2, 2, 3, 3, 3}));
}
@Test
public void test3() {
assertEquals(-1, solution1.findLucky(new int[]{2, 2, 2, 3, 3}));
}
@Test
public void test4() {
assertEquals(-1, solution1.findLucky(new int[]{5}));
}
} | UTF-8 | Java | 791 | java | _1394Test.java | Java | [] | null | [] | package com.fishercoder;
import com.fishercoder.solutions._1394;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _1394Test {
private static _1394.Solution1 solution1;
@BeforeClass
public static void setup() {
solution1 = new _1394.Solution1();
}
@Test
public void test1() {
assertEquals(2, solution1.findLucky(new int[]{2, 2, 3, 4}));
}
@Test
public void test2() {
assertEquals(3, solution1.findLucky(new int[]{1, 2, 2, 3, 3, 3}));
}
@Test
public void test3() {
assertEquals(-1, solution1.findLucky(new int[]{2, 2, 2, 3, 3}));
}
@Test
public void test4() {
assertEquals(-1, solution1.findLucky(new int[]{5}));
}
} | 791 | 0.614412 | 0.553729 | 39 | 19.307692 | 21.660734 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 3 |
d6cffa5b83e3c8bc03335385a032e84bdab4f02e | 21,028,159,931,481 | 6acb8980badaf5133dcf4013dba0fad5e1bae42f | /src/com/crt/openapi/modules/apiinterface/domain/entity/ApiUsers.java | a14cba937fb7facf7084664db2a1938079069da4 | [] | no_license | liubao19860416/generatorSqlmapCustom | https://github.com/liubao19860416/generatorSqlmapCustom | 8e2d85e5dd3e3254cf8be4893aa3a08d9d81b86d | 22353083e0d39d25a9be42f64d508e6dcdd0aecb | refs/heads/master | 2021-05-03T10:47:23.242000 | 2018-11-21T15:27:12 | 2018-11-21T15:27:12 | 69,371,438 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.crt.openapi.modules.apiinterface.domain.entity;
public class ApiUsers {
private Long id;
private String userNo;
private String userName;
private String password;
private String linkPhone;
private String emailAddress;
private String sort;
private String remark;
private String isAdmin;
private String isPublish;
private String isSubscribe;
private String delFlag;
private String creater;
private String createrDate;
private String update;
private String updateDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getLinkPhone() {
return linkPhone;
}
public void setLinkPhone(String linkPhone) {
this.linkPhone = linkPhone == null ? null : linkPhone.trim();
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress == null ? null : emailAddress.trim();
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort == null ? null : sort.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(String isAdmin) {
this.isAdmin = isAdmin == null ? null : isAdmin.trim();
}
public String getIsPublish() {
return isPublish;
}
public void setIsPublish(String isPublish) {
this.isPublish = isPublish == null ? null : isPublish.trim();
}
public String getIsSubscribe() {
return isSubscribe;
}
public void setIsSubscribe(String isSubscribe) {
this.isSubscribe = isSubscribe == null ? null : isSubscribe.trim();
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag == null ? null : delFlag.trim();
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater == null ? null : creater.trim();
}
public String getCreaterDate() {
return createrDate;
}
public void setCreaterDate(String createrDate) {
this.createrDate = createrDate == null ? null : createrDate.trim();
}
public String getUpdate() {
return update;
}
public void setUpdate(String update) {
this.update = update == null ? null : update.trim();
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate == null ? null : updateDate.trim();
}
} | UTF-8 | Java | 3,646 | java | ApiUsers.java | Java | [
{
"context": "\r\n private String userNo;\r\n\r\n private String userName;\r\n\r\n private String password;\r\n\r\n private S",
"end": 169,
"score": 0.9659810066223145,
"start": 161,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "\n public String getUserName()... | null | [] | package com.crt.openapi.modules.apiinterface.domain.entity;
public class ApiUsers {
private Long id;
private String userNo;
private String userName;
private String password;
private String linkPhone;
private String emailAddress;
private String sort;
private String remark;
private String isAdmin;
private String isPublish;
private String isSubscribe;
private String delFlag;
private String creater;
private String createrDate;
private String update;
private String updateDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getLinkPhone() {
return linkPhone;
}
public void setLinkPhone(String linkPhone) {
this.linkPhone = linkPhone == null ? null : linkPhone.trim();
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress == null ? null : emailAddress.trim();
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort == null ? null : sort.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(String isAdmin) {
this.isAdmin = isAdmin == null ? null : isAdmin.trim();
}
public String getIsPublish() {
return isPublish;
}
public void setIsPublish(String isPublish) {
this.isPublish = isPublish == null ? null : isPublish.trim();
}
public String getIsSubscribe() {
return isSubscribe;
}
public void setIsSubscribe(String isSubscribe) {
this.isSubscribe = isSubscribe == null ? null : isSubscribe.trim();
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag == null ? null : delFlag.trim();
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater == null ? null : creater.trim();
}
public String getCreaterDate() {
return createrDate;
}
public void setCreaterDate(String createrDate) {
this.createrDate = createrDate == null ? null : createrDate.trim();
}
public String getUpdate() {
return update;
}
public void setUpdate(String update) {
this.update = update == null ? null : update.trim();
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate == null ? null : updateDate.trim();
}
} | 3,646 | 0.586396 | 0.586396 | 163 | 20.380367 | 21.539295 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.300613 | false | false | 3 |
4a179d69918def9e52c47a5a236428ac5ecf4e57 | 21,028,159,928,822 | 91122f4487ec9ccc0c26dc4248338c43d8743626 | /Hibernate/Hibernatelove2code/src/main/java/com/love2code/hibernate/demo/entity/Student.java | 4d0658774299d173619d7683f6635abd0dd321ad | [] | no_license | RedSulfur/Java-EE-practice | https://github.com/RedSulfur/Java-EE-practice | f2804d91fc58ef2476dde592f37df6a3cad43746 | 6ac6bf2655d5f98c1bb5cca70140616c92a7ec3b | refs/heads/master | 2021-05-24T04:39:09.615000 | 2016-10-08T17:50:14 | 2016-10-08T17:50:14 | 53,417,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.love2code.hibernate.demo.entity;
import javax.persistence.*;
@Entity
@Table(name = "student")
public class Student {
/**
* This part maps the field to the database columns.
*
* @param id represents a primary key for our {@link Student} class
* that is related to an actual primary key {@code id} from
* the database
* Id annotation tells Hibernate, that this given field is a primary key
* and this field maps to a column in a database table, and that column name
* is id.
*/
@Id
/**
* tells hibernate how to perform generation, to use a given strategy for
* generating an id
*/
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
/**
* define non arg constructor
*/
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
| UTF-8 | Java | 2,066 | java | Student.java | Java | [] | null | [] | package com.love2code.hibernate.demo.entity;
import javax.persistence.*;
@Entity
@Table(name = "student")
public class Student {
/**
* This part maps the field to the database columns.
*
* @param id represents a primary key for our {@link Student} class
* that is related to an actual primary key {@code id} from
* the database
* Id annotation tells Hibernate, that this given field is a primary key
* and this field maps to a column in a database table, and that column name
* is id.
*/
@Id
/**
* tells hibernate how to perform generation, to use a given strategy for
* generating an id
*/
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
/**
* define non arg constructor
*/
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
| 2,066 | 0.564376 | 0.563892 | 90 | 21.955555 | 20.755674 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.288889 | false | false | 3 |
23096b7885470b4da6769ff2e269c9465855d660 | 7,619,272,021,202 | 7c3c1c28dd131118a3f8d6222c06806d13d623b9 | /src/thing/Seller.java | e72917e6f4eacc56e0ffe9c059fb775607bbacb9 | [] | no_license | Nanging/Design-Pattern | https://github.com/Nanging/Design-Pattern | b72e4bbb7d8adbf90559b5e9c7d17e791f2d2157 | 7cecf229a7438cb99f44e27cb572080232794241 | refs/heads/master | 2020-04-03T03:03:41.409000 | 2018-11-02T03:06:51 | 2018-11-02T03:06:51 | 154,975,454 | 1 | 0 | null | false | 2018-11-01T12:18:45 | 2018-10-27T14:47:51 | 2018-11-01T09:56:14 | 2018-11-01T12:18:45 | 976 | 0 | 0 | 0 | Java | false | null | package thing;
import construction.Sale;
public class Seller {
public void sellGoods(Goods goods) {
Sale.sale(goods);
}
}
| UTF-8 | Java | 128 | java | Seller.java | Java | [] | null | [] | package thing;
import construction.Sale;
public class Seller {
public void sellGoods(Goods goods) {
Sale.sale(goods);
}
}
| 128 | 0.726563 | 0.726563 | 9 | 13.222222 | 12.576678 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 3 |
08294a092880ace05f4260f56321320238bfd345 | 24,721,831,762,408 | accdf6d99cbc99b3da68b9449b5152e01cb3fd84 | /sunshine-redis/src/main/java/cn/sunshine/App.java | 3345d0f7bc9b468b2a982d8a9d536736879feb58 | [
"Apache-2.0"
] | permissive | wiesel07/sunshine | https://github.com/wiesel07/sunshine | 0c980c7715f3eeb4d2de9e6a4d63aa7528f79afd | a6fdded0cd46e13f02da6bc4194a406608ae5179 | refs/heads/master | 2022-06-27T23:55:11.506000 | 2019-06-20T12:03:12 | 2019-06-20T12:03:12 | 189,194,634 | 1 | 0 | Apache-2.0 | false | 2021-04-26T19:11:54 | 2019-05-29T09:31:51 | 2019-12-20T11:03:37 | 2021-04-26T19:11:54 | 3,947 | 1 | 0 | 1 | CSS | false | false | package cn.sunshine;
import java.util.Optional;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
String[] cacheNames = new String[] {"aa"};
Optional<String[]> aOptional = Optional.ofNullable(cacheNames);
if (aOptional.isPresent()) {
System.out.println(1);
}else {
System.out.println("test");
}
}
}
| UTF-8 | Java | 421 | java | App.java | Java | [] | null | [] | package cn.sunshine;
import java.util.Optional;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
String[] cacheNames = new String[] {"aa"};
Optional<String[]> aOptional = Optional.ofNullable(cacheNames);
if (aOptional.isPresent()) {
System.out.println(1);
}else {
System.out.println("test");
}
}
}
| 421 | 0.612827 | 0.610451 | 22 | 18.136364 | 18.621336 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false | 3 |
cd35050320f64005f584ecd4666624f695fbe2a2 | 23,957,327,624,492 | e3d9c0b15a9c6ac9aa0ae0c92ec06a228d0d5859 | /linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/service/impl/BmlProjectServiceImpl.java | 190085abe72fd2851aef6231d48d2471cb9d8930 | [
"Apache-2.0",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-unicode",
"LGPL-2.0-or-later",
"EPL-1.0",
"Classpath-exception-2.0",
"GPL-1.0-or-later",
"CC-BY-SA-3.0",
"CPL-1.0",
"LicenseRef-scancode-generic-cla",
"SAX-PD",
"EPL-2.0",
"LicenseRef-scancode-free-unknown",
"CC-PDDC",
... | permissive | tgh-621/Linkis | https://github.com/tgh-621/Linkis | 9e7d468b8abedffaf1723842f0f3f1ecf516bf1f | f27699aa6be01d7ee2ae3e544c8fefcef2830b0a | refs/heads/master | 2022-03-06T12:27:15.359000 | 2022-02-11T02:02:28 | 2022-02-11T02:02:28 | 289,199,303 | 1 | 0 | Apache-2.0 | true | 2021-09-03T01:01:33 | 2020-08-21T06:49:38 | 2021-08-09T07:09:34 | 2021-09-03T01:01:32 | 145,784 | 1 | 0 | 0 | Scala | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.linkis.bml.service.impl;
import org.apache.linkis.bml.Entity.BmlProject;
import org.apache.linkis.bml.dao.BmlProjectDao;
import org.apache.linkis.bml.service.BmlProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
@Service
public class BmlProjectServiceImpl implements BmlProjectService {
private static final Logger LOGGER = LoggerFactory.getLogger(BmlProjectServiceImpl.class);
public static final Integer DEFAULT_EDIT_PRIV = 7;
public static final Integer DEFAULT_ACCESS_PRIV = 5;
public static final Integer DEFAULT_ADMIN_PRIV = 8;
@Autowired private BmlProjectDao bmlProjectDao;
@Override
public int createBmlProject(
String projectName, String creator, List<String> editUsers, List<String> accessUsers) {
BmlProject bmlProject1 = bmlProjectDao.getBmlProject(projectName);
if (bmlProject1 != null) {
return bmlProject1.getId();
}
Date createTime = new Date(System.currentTimeMillis());
BmlProject bmlProject = new BmlProject();
bmlProject.setName(projectName);
bmlProject.setCreator(creator);
bmlProject.setCreateTime(createTime);
bmlProject.setDescription(creator + " 在bml创建的工程 ");
bmlProject.setEnabled(1);
bmlProject.setSystem("dss");
bmlProjectDao.createNewProject(bmlProject);
// 2 将用户和工程绑定
if (!editUsers.contains(creator)) {
editUsers.add(creator);
}
if (editUsers.size() > 0) {
setProjectEditPriv(bmlProject.getName(), editUsers);
}
if (accessUsers.size() > 0) {
setProjectAccessPriv(bmlProject.getName(), accessUsers);
}
return bmlProject.getId();
}
@Override
public boolean checkEditPriv(String projectName, String username) {
try {
Integer priv = bmlProjectDao.getPrivInProject(projectName, username);
return priv >= DEFAULT_EDIT_PRIV;
} catch (Exception e) {
return true;
}
}
@Override
public boolean checkAccessPriv(String projectName, String username) {
try {
Integer priv = bmlProjectDao.getPrivInProject(projectName, username);
return priv >= DEFAULT_ACCESS_PRIV;
} catch (Exception e) {
return true;
}
}
@Override
public void setProjectEditPriv(String projectName, List<String> editUsers) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
String creator = bmlProject.getCreator();
Date createTime = new Date(System.currentTimeMillis());
bmlProjectDao.setProjectPriv(
bmlProject.getId(), editUsers, DEFAULT_EDIT_PRIV, creator, createTime);
}
@Override
public void addProjectEditPriv(String projectName, List<String> editUsers) {}
@Override
public void deleteProjectEditPriv(String projectName, List<String> editUsers) {}
@Override
public void setProjectAccessPriv(String projectName, List<String> accessUsers) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
String creator = bmlProject.getCreator();
Date createTime = new Date(System.currentTimeMillis());
bmlProjectDao.setProjectPriv(
bmlProject.getId(), accessUsers, DEFAULT_ACCESS_PRIV, creator, createTime);
}
@Override
public void addProjectAccessPriv(String projectName, List<String> accessUsers) {}
@Override
public void deleteProjectAccessPriv(String projectName, List<String> accessUsers) {}
@Override
public String getProjectNameByResourceId(String resourceId) {
return bmlProjectDao.getProjectNameByResourceId(resourceId);
}
@Override
public void addProjectResource(String resourceId, String projectName) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
if (bmlProject != null) {
bmlProjectDao.addProjectResource(bmlProject.getId(), resourceId);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void attach(String projectName, String resourceId) {
Integer projectId = bmlProjectDao.getProjectIdByName(projectName);
Integer cnt = bmlProjectDao.checkIfExists(projectId, resourceId);
if (cnt > 0) {
return;
}
bmlProjectDao.attachResourceAndProject(projectId, resourceId);
}
@Override
public void updateProjectUsers(
String username, String projectName, List<String> editUsers, List<String> accessUsers) {
Integer projectId = bmlProjectDao.getProjectIdByName(projectName);
if (projectId == null) {
LOGGER.error("{} does not exist", projectName);
} else {
Date updateTime = new Date(System.currentTimeMillis());
bmlProjectDao.deleteAllPriv(projectId);
if (editUsers.size() > 0) {
bmlProjectDao.setProjectPriv(
projectId, editUsers, DEFAULT_EDIT_PRIV, username, updateTime);
}
if (accessUsers.size() > 0) {
bmlProjectDao.setProjectPriv(
projectId, accessUsers, DEFAULT_ACCESS_PRIV, username, updateTime);
}
}
}
}
| UTF-8 | Java | 6,378 | java | BmlProjectServiceImpl.java | Java | [] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.linkis.bml.service.impl;
import org.apache.linkis.bml.Entity.BmlProject;
import org.apache.linkis.bml.dao.BmlProjectDao;
import org.apache.linkis.bml.service.BmlProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
@Service
public class BmlProjectServiceImpl implements BmlProjectService {
private static final Logger LOGGER = LoggerFactory.getLogger(BmlProjectServiceImpl.class);
public static final Integer DEFAULT_EDIT_PRIV = 7;
public static final Integer DEFAULT_ACCESS_PRIV = 5;
public static final Integer DEFAULT_ADMIN_PRIV = 8;
@Autowired private BmlProjectDao bmlProjectDao;
@Override
public int createBmlProject(
String projectName, String creator, List<String> editUsers, List<String> accessUsers) {
BmlProject bmlProject1 = bmlProjectDao.getBmlProject(projectName);
if (bmlProject1 != null) {
return bmlProject1.getId();
}
Date createTime = new Date(System.currentTimeMillis());
BmlProject bmlProject = new BmlProject();
bmlProject.setName(projectName);
bmlProject.setCreator(creator);
bmlProject.setCreateTime(createTime);
bmlProject.setDescription(creator + " 在bml创建的工程 ");
bmlProject.setEnabled(1);
bmlProject.setSystem("dss");
bmlProjectDao.createNewProject(bmlProject);
// 2 将用户和工程绑定
if (!editUsers.contains(creator)) {
editUsers.add(creator);
}
if (editUsers.size() > 0) {
setProjectEditPriv(bmlProject.getName(), editUsers);
}
if (accessUsers.size() > 0) {
setProjectAccessPriv(bmlProject.getName(), accessUsers);
}
return bmlProject.getId();
}
@Override
public boolean checkEditPriv(String projectName, String username) {
try {
Integer priv = bmlProjectDao.getPrivInProject(projectName, username);
return priv >= DEFAULT_EDIT_PRIV;
} catch (Exception e) {
return true;
}
}
@Override
public boolean checkAccessPriv(String projectName, String username) {
try {
Integer priv = bmlProjectDao.getPrivInProject(projectName, username);
return priv >= DEFAULT_ACCESS_PRIV;
} catch (Exception e) {
return true;
}
}
@Override
public void setProjectEditPriv(String projectName, List<String> editUsers) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
String creator = bmlProject.getCreator();
Date createTime = new Date(System.currentTimeMillis());
bmlProjectDao.setProjectPriv(
bmlProject.getId(), editUsers, DEFAULT_EDIT_PRIV, creator, createTime);
}
@Override
public void addProjectEditPriv(String projectName, List<String> editUsers) {}
@Override
public void deleteProjectEditPriv(String projectName, List<String> editUsers) {}
@Override
public void setProjectAccessPriv(String projectName, List<String> accessUsers) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
String creator = bmlProject.getCreator();
Date createTime = new Date(System.currentTimeMillis());
bmlProjectDao.setProjectPriv(
bmlProject.getId(), accessUsers, DEFAULT_ACCESS_PRIV, creator, createTime);
}
@Override
public void addProjectAccessPriv(String projectName, List<String> accessUsers) {}
@Override
public void deleteProjectAccessPriv(String projectName, List<String> accessUsers) {}
@Override
public String getProjectNameByResourceId(String resourceId) {
return bmlProjectDao.getProjectNameByResourceId(resourceId);
}
@Override
public void addProjectResource(String resourceId, String projectName) {
BmlProject bmlProject = bmlProjectDao.getBmlProject(projectName);
if (bmlProject != null) {
bmlProjectDao.addProjectResource(bmlProject.getId(), resourceId);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void attach(String projectName, String resourceId) {
Integer projectId = bmlProjectDao.getProjectIdByName(projectName);
Integer cnt = bmlProjectDao.checkIfExists(projectId, resourceId);
if (cnt > 0) {
return;
}
bmlProjectDao.attachResourceAndProject(projectId, resourceId);
}
@Override
public void updateProjectUsers(
String username, String projectName, List<String> editUsers, List<String> accessUsers) {
Integer projectId = bmlProjectDao.getProjectIdByName(projectName);
if (projectId == null) {
LOGGER.error("{} does not exist", projectName);
} else {
Date updateTime = new Date(System.currentTimeMillis());
bmlProjectDao.deleteAllPriv(projectId);
if (editUsers.size() > 0) {
bmlProjectDao.setProjectPriv(
projectId, editUsers, DEFAULT_EDIT_PRIV, username, updateTime);
}
if (accessUsers.size() > 0) {
bmlProjectDao.setProjectPriv(
projectId, accessUsers, DEFAULT_ACCESS_PRIV, username, updateTime);
}
}
}
}
| 6,378 | 0.682362 | 0.67937 | 167 | 37.023952 | 29.425631 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.616766 | false | false | 3 |
7371e39f38d1affa3c0efc36873a21355817a22f | 33,036,888,450,528 | 2cad2c75ca7f6b0d9d7e6d23e3ff77a394be6737 | /src/main/java/ua/ali_x/telegrambot/service/statistic/StatisticJsonUkraineService.java | 14fa2925857afb6a9d069934bae10ece3404abe1 | [] | no_license | Ali-X/corona-ukraine | https://github.com/Ali-X/corona-ukraine | d009a8518648dd49f2d5000470cc581ab695dc97 | c8f8a16a6de9c11b3a578ce3164b1ceb082d9de5 | refs/heads/master | 2022-10-03T07:23:16.757000 | 2020-07-02T17:21:28 | 2020-07-02T17:21:28 | 250,853,500 | 0 | 0 | null | false | 2022-09-01T23:22:57 | 2020-03-28T17:25:05 | 2020-07-02T17:21:32 | 2022-09-01T23:22:55 | 53,923 | 0 | 0 | 1 | Java | false | false | package ua.ali_x.telegrambot.service.statistic;
import com.jayway.jsonpath.DocumentContext;
import net.minidev.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.ali_x.telegrambot.dao.MessageTemplateDao;
import ua.ali_x.telegrambot.model.Statistic;
import ua.ali_x.telegrambot.service.RequestService;
@Component
public class StatisticJsonUkraineService implements StatisticService, RequestService {
@Autowired
private MessageTemplateDao messageTemplateDao;
public String getStatisticsStr() {
return extractStatistic();
}
@Override
public Statistic getStatistics() {
return null;
}
private String extractStatistic() {
String message = messageTemplateDao.findFirstByCode("statistic_ukraine_d").getMessage();
String basePath = "$.data[?(@.name_en=='Украина')]";
String url = "http://coronavirus19.com.ua/ajax/world-stat";
DocumentContext responseJson = sendGET(url);
Integer allCases = (Integer) responseJson.read(basePath + ".total_cases", JSONArray.class).get(0);
Integer recovered = (Integer) responseJson.read(basePath + ".total_recovered", JSONArray.class).get(0);
Integer death = (Integer) responseJson.read(basePath + ".total_deaths", JSONArray.class).get(0);
return String.format(message, allCases, recovered, death);
}
} | UTF-8 | Java | 1,446 | java | StatisticJsonUkraineService.java | Java | [] | null | [] | package ua.ali_x.telegrambot.service.statistic;
import com.jayway.jsonpath.DocumentContext;
import net.minidev.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.ali_x.telegrambot.dao.MessageTemplateDao;
import ua.ali_x.telegrambot.model.Statistic;
import ua.ali_x.telegrambot.service.RequestService;
@Component
public class StatisticJsonUkraineService implements StatisticService, RequestService {
@Autowired
private MessageTemplateDao messageTemplateDao;
public String getStatisticsStr() {
return extractStatistic();
}
@Override
public Statistic getStatistics() {
return null;
}
private String extractStatistic() {
String message = messageTemplateDao.findFirstByCode("statistic_ukraine_d").getMessage();
String basePath = "$.data[?(@.name_en=='Украина')]";
String url = "http://coronavirus19.com.ua/ajax/world-stat";
DocumentContext responseJson = sendGET(url);
Integer allCases = (Integer) responseJson.read(basePath + ".total_cases", JSONArray.class).get(0);
Integer recovered = (Integer) responseJson.read(basePath + ".total_recovered", JSONArray.class).get(0);
Integer death = (Integer) responseJson.read(basePath + ".total_deaths", JSONArray.class).get(0);
return String.format(message, allCases, recovered, death);
}
} | 1,446 | 0.730368 | 0.726894 | 40 | 35 | 33.406586 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 3 |
83f637ff560d56804dcb896d3bafc75eefa9341a | 6,562,710,032,940 | 1487369f5adba5d0bac12609a1433c00eaa0275d | /src/jena_practice/Consulta4_SPARQL.java | 1a4dce6f299782e57105488f4a28f73a7091f379 | [] | no_license | Raejimenezca/Jena_library_practice-Java | https://github.com/Raejimenezca/Jena_library_practice-Java | e40117421139bf71f78d12446c405a6223e56178 | 21d913b2efbda5279db2f1498b233ce379d8badf | refs/heads/master | 2020-12-29T09:26:17.785000 | 2020-02-05T21:56:37 | 2020-02-05T21:56:37 | 238,555,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jena_practice;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.util.FileManager;
public class Consulta4_SPARQL {
public static void main(String[] args) {
// Carga la ontologia de data.ttl y la imprime
FileManager.get().addLocatorClassLoader(Consulta4_SPARQL.class.getClassLoader());
Model model = FileManager.get().loadModel("src/owl/data.ttl");
System.out.println("Input data: ");
model.write(System.out, "TURTLE");
// Lee la lista de archivos de consulta que inicien con "construct-"
// y que finalicen con ".sparql"
File path = new File("src/owl/queries");
File[] files = path.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("construct-") && name.endsWith(".sparql");
}
});
Arrays.sort(files);
// Se ejecuta cada uno de los archivos de consulta previamente identificados
for (File file : files) {
System.out.println("Executing " + file.getName() + " ...");
Query query = QueryFactory.read(file.getAbsolutePath());
QueryExecution qexec = QueryExecutionFactory.create(query, model);
try {
Model result = qexec.execConstruct();
model.add(result);
} finally {
qexec.close();
}
}
// Se imprime el resultado
System.out.println("Output data: ");
model.write(System.out, "TURTLE");
}
}
| UTF-8 | Java | 1,679 | java | Consulta4_SPARQL.java | Java | [] | null | [] | package jena_practice;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.util.FileManager;
public class Consulta4_SPARQL {
public static void main(String[] args) {
// Carga la ontologia de data.ttl y la imprime
FileManager.get().addLocatorClassLoader(Consulta4_SPARQL.class.getClassLoader());
Model model = FileManager.get().loadModel("src/owl/data.ttl");
System.out.println("Input data: ");
model.write(System.out, "TURTLE");
// Lee la lista de archivos de consulta que inicien con "construct-"
// y que finalicen con ".sparql"
File path = new File("src/owl/queries");
File[] files = path.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("construct-") && name.endsWith(".sparql");
}
});
Arrays.sort(files);
// Se ejecuta cada uno de los archivos de consulta previamente identificados
for (File file : files) {
System.out.println("Executing " + file.getName() + " ...");
Query query = QueryFactory.read(file.getAbsolutePath());
QueryExecution qexec = QueryExecutionFactory.create(query, model);
try {
Model result = qexec.execConstruct();
model.add(result);
} finally {
qexec.close();
}
}
// Se imprime el resultado
System.out.println("Output data: ");
model.write(System.out, "TURTLE");
}
}
| 1,679 | 0.68374 | 0.682549 | 54 | 29.092592 | 23.489374 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.259259 | false | false | 3 |
290fa06711c30faa58ed682e0a8a362edb2f17f0 | 2,095,944,041,203 | 1fa44acaceba7afeed321410160d0d7c9eb83062 | /src/design/zhaowd/action/mediator/ClassA.java | 6f81157eb694d6248fa210a38b508cd06f909562 | [] | no_license | shenwuwu/desigin | https://github.com/shenwuwu/desigin | 4e626c5998290a959020f750e46877d5dbe1aa4e | 3b396cd7c093bc8559592f12e7dc3f4c8077cb70 | refs/heads/master | 2020-04-13T19:04:46.238000 | 2018-12-28T09:33:07 | 2018-12-28T09:33:07 | 163,392,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package design.zhaowd.action.mediator;
public class ClassA extends ClassXX{
public void printB() {
media.printB();
};
public void print() {
};
}
| UTF-8 | Java | 166 | java | ClassA.java | Java | [] | null | [] | package design.zhaowd.action.mediator;
public class ClassA extends ClassXX{
public void printB() {
media.printB();
};
public void print() {
};
}
| 166 | 0.638554 | 0.638554 | 11 | 13.090909 | 14.067723 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
7bc563f4b7553ae9961746510be5902a72eb19c4 | 11,656,541,262,008 | 7abf9a1bce17409fed3ba3cf51fa49b0c3667ccb | /src/main/java/br/unicesumar/time05/consultapersonalizada/DadosParaConsultaSQL.java | e180f672fcf460fc0b2fc2a8677adcda9b1444ea | [] | no_license | renatoAlecrim/escolaDeTI-Time05 | https://github.com/renatoAlecrim/escolaDeTI-Time05 | cc2750111199b6270c583094728242d80257be1e | 16e033ce184b503540a276dde6da37dfe1c2c72b | refs/heads/master | 2021-01-10T05:05:42.627000 | 2015-12-06T12:44:27 | 2015-12-06T12:44:27 | 47,496,077 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.unicesumar.time05.consultapersonalizada;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DadosParaConsultaSQL {
String nomeTabela = "";
String idTabela = "";
String campoOrdenacaoPadrao = "";
List<CampoParaScriptSQL> campos;
public DadosParaConsultaSQL() {
campos = new ArrayList<>();
}
public String getIdTabela() {
return idTabela;
}
public void setIdTabela(String aIdTabela) {
this.idTabela = aIdTabela;
}
public void setNomeTabela(String aNomeTabela) {
this.nomeTabela = aNomeTabela;
}
public void setCampoOrdenacaoPadrao(String aCampoOrdenacaoPadrao) {
this.campoOrdenacaoPadrao = aCampoOrdenacaoPadrao;
}
public void addCampo(CampoParaScriptSQL aCampo) {
this.campos.add(aCampo);
}
public String getNomeTabela() {
return nomeTabela;
}
public List<CampoParaScriptSQL> getCampos() {
return Collections.unmodifiableList(campos);
}
public String getCampoOrdenacaoPadrao() {
return campoOrdenacaoPadrao;
}
}
| UTF-8 | Java | 1,143 | java | DadosParaConsultaSQL.java | Java | [] | null | [] | package br.unicesumar.time05.consultapersonalizada;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DadosParaConsultaSQL {
String nomeTabela = "";
String idTabela = "";
String campoOrdenacaoPadrao = "";
List<CampoParaScriptSQL> campos;
public DadosParaConsultaSQL() {
campos = new ArrayList<>();
}
public String getIdTabela() {
return idTabela;
}
public void setIdTabela(String aIdTabela) {
this.idTabela = aIdTabela;
}
public void setNomeTabela(String aNomeTabela) {
this.nomeTabela = aNomeTabela;
}
public void setCampoOrdenacaoPadrao(String aCampoOrdenacaoPadrao) {
this.campoOrdenacaoPadrao = aCampoOrdenacaoPadrao;
}
public void addCampo(CampoParaScriptSQL aCampo) {
this.campos.add(aCampo);
}
public String getNomeTabela() {
return nomeTabela;
}
public List<CampoParaScriptSQL> getCampos() {
return Collections.unmodifiableList(campos);
}
public String getCampoOrdenacaoPadrao() {
return campoOrdenacaoPadrao;
}
}
| 1,143 | 0.677165 | 0.675416 | 50 | 21.860001 | 20.168303 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34 | false | false | 3 |
ad5741e5be7fcb0fedd411f05c2f9d4c4ce07222 | 16,673,063,069,901 | 56bb94e12c01d0e9b03d68ee8b67b02b027e7f8b | /src/item44/Main.java | ed08a78dd5d4215338a22d498a0529f9dde9c23d | [] | no_license | Lokie89/effective-java | https://github.com/Lokie89/effective-java | 8065b41488432a5c26704925897afd79925944c8 | 3567a6d20d5edc87488cc011308d937d6b05bd63 | refs/heads/master | 2022-12-13T13:55:08.354000 | 2020-09-09T06:50:31 | 2020-09-09T06:50:31 | 275,691,828 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package item44;
public class Main {
public static void main(String[] args) {
LinkedHashMapUnderHundred map = new LinkedHashMapUnderHundred();
for (int i = 0; i < 200; i++) {
map.put("key" + i, "value" + i);
}
System.out.println(map.size());
}
}
| UTF-8 | Java | 298 | java | Main.java | Java | [] | null | [] | package item44;
public class Main {
public static void main(String[] args) {
LinkedHashMapUnderHundred map = new LinkedHashMapUnderHundred();
for (int i = 0; i < 200; i++) {
map.put("key" + i, "value" + i);
}
System.out.println(map.size());
}
}
| 298 | 0.557047 | 0.536913 | 11 | 26.09091 | 21.956381 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 3 |
6a2e6428aac0d5622d72161768aabbf218a63e4b | 31,645,319,080,451 | a882e44fe45fc973b2d5e4d7bc317efc9aa848a1 | /tdat1005/12 Arv&poly - dyrehage/src/dyrehage/Dyregruppe.java | a52de49e99610402c8324314c97fbad058ec89ca | [] | no_license | toberge/uni-exercises | https://github.com/toberge/uni-exercises | 68e56c0a58e9418bb6c18eadb72228a7d2544e4c | f10e106bbeda783549d4286595f63e81674535d0 | refs/heads/master | 2020-07-03T13:42:49.001000 | 2020-03-31T11:18:52 | 2020-03-31T11:18:52 | 201,922,773 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dyrehage;
/**
* Dyregrupper: Dyr vi forholder oss til i grupper, som for eksempel fiskestimer, insektsvermer og fugleflokker.
* Om hver gruppe lagrer vi gruppenavn og omtrentlig antall individer i gruppen.
* I tillegg har vi spesielt tilpassede klasser for hhv. fiskestimer
* (der vi lagrer gjennomsnittlig lengde for et voksent eksemplar av arten og om den kan dele akvarium med en annen dyregruppe)
* og fugleflokker (der vi lagrer gjennomsnittlig vekt for et voksent eksemplar av arten og om det er en type svømmefugl) som du ser i klassediagrammet.
*/
abstract class Dyregruppe extends Dyr {
private final String gruppenavn;
private int antIndivider;
public Dyregruppe(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse);
if (gruppenavn == null || gruppenavn.trim().equals("") || antIndivider < 0) {
throw new IllegalArgumentException("Ey, dem GRUPPEARGS BE WRONGK");
}
this.gruppenavn = gruppenavn;
this.antIndivider = antIndivider;
}
// metoden i Dyr er final, da kan ingen underklasser override den.
@Override
public String getNorskNavn() {
return "gruppe av " + super.getNorskNavn();
}
public String getGruppenavn() {
return gruppenavn;
}
public int getAntIndivider() {
return antIndivider;
}
public void setAntIndivider(int antIndivider) {
if (antIndivider > 0) {
this.antIndivider = antIndivider;
}
}
@Override
public String toString() {
return super.toString();
}
}
class Fiskestim extends Dyregruppe {
private final float gjennomsnittligLengde;
private final boolean kanDeleAkvarium;
public Fiskestim(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider,
float gjennomsnittligLengde, boolean kanDeleAkvarium) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse, gruppenavn, antIndivider);
if (gjennomsnittligLengde < 0.0f) throw new IllegalArgumentException("Negative length");
this.gjennomsnittligLengde = gjennomsnittligLengde;
this.kanDeleAkvarium = kanDeleAkvarium;
}
public float getGjennomsnittligLengde() {
return gjennomsnittligLengde;
}
public boolean kanDeleAkvarium() {
return kanDeleAkvarium;
}
}
class Fugleflokk extends Dyregruppe {
private final float gjennomsnittligVekt;
private final boolean kanSvømme;
public Fugleflokk(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider,
float gjennomsnittligVekt, boolean kanSvømme) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse, gruppenavn, antIndivider);
if (gjennomsnittligVekt < 0.0f) throw new IllegalArgumentException("Negative weight");
this.gjennomsnittligVekt = gjennomsnittligVekt;
this.kanSvømme = kanSvømme;
}
public float getGjennomsnittligVekt() {
return gjennomsnittligVekt;
}
public boolean kanSvømme() {
return kanSvømme;
}
} | UTF-8 | Java | 3,404 | java | Dyregruppe.java | Java | [] | null | [] | package dyrehage;
/**
* Dyregrupper: Dyr vi forholder oss til i grupper, som for eksempel fiskestimer, insektsvermer og fugleflokker.
* Om hver gruppe lagrer vi gruppenavn og omtrentlig antall individer i gruppen.
* I tillegg har vi spesielt tilpassede klasser for hhv. fiskestimer
* (der vi lagrer gjennomsnittlig lengde for et voksent eksemplar av arten og om den kan dele akvarium med en annen dyregruppe)
* og fugleflokker (der vi lagrer gjennomsnittlig vekt for et voksent eksemplar av arten og om det er en type svømmefugl) som du ser i klassediagrammet.
*/
abstract class Dyregruppe extends Dyr {
private final String gruppenavn;
private int antIndivider;
public Dyregruppe(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse);
if (gruppenavn == null || gruppenavn.trim().equals("") || antIndivider < 0) {
throw new IllegalArgumentException("Ey, dem GRUPPEARGS BE WRONGK");
}
this.gruppenavn = gruppenavn;
this.antIndivider = antIndivider;
}
// metoden i Dyr er final, da kan ingen underklasser override den.
@Override
public String getNorskNavn() {
return "gruppe av " + super.getNorskNavn();
}
public String getGruppenavn() {
return gruppenavn;
}
public int getAntIndivider() {
return antIndivider;
}
public void setAntIndivider(int antIndivider) {
if (antIndivider > 0) {
this.antIndivider = antIndivider;
}
}
@Override
public String toString() {
return super.toString();
}
}
class Fiskestim extends Dyregruppe {
private final float gjennomsnittligLengde;
private final boolean kanDeleAkvarium;
public Fiskestim(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider,
float gjennomsnittligLengde, boolean kanDeleAkvarium) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse, gruppenavn, antIndivider);
if (gjennomsnittligLengde < 0.0f) throw new IllegalArgumentException("Negative length");
this.gjennomsnittligLengde = gjennomsnittligLengde;
this.kanDeleAkvarium = kanDeleAkvarium;
}
public float getGjennomsnittligLengde() {
return gjennomsnittligLengde;
}
public boolean kanDeleAkvarium() {
return kanDeleAkvarium;
}
}
class Fugleflokk extends Dyregruppe {
private final float gjennomsnittligVekt;
private final boolean kanSvømme;
public Fugleflokk(String norskNavn, String latNavn, String latFamilie, int ankommetDato, String adresse,
String gruppenavn, int antIndivider,
float gjennomsnittligVekt, boolean kanSvømme) {
super(norskNavn, latNavn, latFamilie, ankommetDato, adresse, gruppenavn, antIndivider);
if (gjennomsnittligVekt < 0.0f) throw new IllegalArgumentException("Negative weight");
this.gjennomsnittligVekt = gjennomsnittligVekt;
this.kanSvømme = kanSvømme;
}
public float getGjennomsnittligVekt() {
return gjennomsnittligVekt;
}
public boolean kanSvømme() {
return kanSvømme;
}
} | 3,404 | 0.690315 | 0.688549 | 110 | 29.890909 | 34.562023 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672727 | false | false | 3 |
8c7b2b580a0b6c796f5f0f69633a3fe72ccc3995 | 32,487,132,680,277 | 80b5ae0beded749c6ca4f489fa860304899d8315 | /Tecnología de la Programación/Juegos usando MVC/2. Versión con interfaz gráfica/main/java/es/ucm/fdi/tp/view/PlayersInfoViewer.java | d4570142278cf200ed3d2545cd80a505d1363d2a | [] | no_license | Joncarre/Java-language | https://github.com/Joncarre/Java-language | ba3e686747e668e72294597b645e1851d9ac2644 | 8ffe5a67b0f1397e2259c53e29d61e5bd635e979 | refs/heads/master | 2023-09-01T19:52:39.060000 | 2023-08-24T19:10:31 | 2023-08-24T19:10:31 | 95,045,879 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.es.ucm.fdi.tp.view;
import java.awt.Color;
import java.util.List;
import javax.swing.JPanel;
import main.java.es.ucm.fdi.tp.base.model.GameAction;
import main.java.es.ucm.fdi.tp.base.model.GameState;
import main.java.es.ucm.fdi.tp.mvc.GameObserver;
public abstract class PlayersInfoViewer<S extends GameState<S, A>, A extends GameAction<S, A>> extends GUIView<S, A> {
private static final long serialVersionUID = 1L;
/**
* Modifica el contenido de PlayersInfoViewerComp
*/
public void setPlayersInfoViewer(PlayersInfoViewer<S, A> playersInfoViewer){
// Es vacío por defecto. Puede sobreescribirse en las subclases. //
}
/** Se usa para establecer el número de jugadores */
abstract public void setNumberOfPlayer(int n);
/** Devuelve el color asociado a un jugador */
abstract public Color getPlayerColor(int p);
/** Los observadores deben implementar esta interfaz */
public interface PlayersInfoObserver{
public void colorChanged(int p, Color color);
}
/** Declaramos una lista de observadores */
protected List<PlayersInfoObserver> observers;
/**
* Añadir observador a la lista
* @param o
*/
public void addObserver(PlayersInfoObserver o){
observers.add(o);
}
/**
* Notificar a los observadores
* @param p
* @param color
*/
protected void notifyObservers(int p, Color color){
for(PlayersInfoObserver o: observers)
o.colorChanged(p, color);
}
}
| UTF-8 | Java | 1,434 | java | PlayersInfoViewer.java | Java | [] | null | [] | package main.java.es.ucm.fdi.tp.view;
import java.awt.Color;
import java.util.List;
import javax.swing.JPanel;
import main.java.es.ucm.fdi.tp.base.model.GameAction;
import main.java.es.ucm.fdi.tp.base.model.GameState;
import main.java.es.ucm.fdi.tp.mvc.GameObserver;
public abstract class PlayersInfoViewer<S extends GameState<S, A>, A extends GameAction<S, A>> extends GUIView<S, A> {
private static final long serialVersionUID = 1L;
/**
* Modifica el contenido de PlayersInfoViewerComp
*/
public void setPlayersInfoViewer(PlayersInfoViewer<S, A> playersInfoViewer){
// Es vacío por defecto. Puede sobreescribirse en las subclases. //
}
/** Se usa para establecer el número de jugadores */
abstract public void setNumberOfPlayer(int n);
/** Devuelve el color asociado a un jugador */
abstract public Color getPlayerColor(int p);
/** Los observadores deben implementar esta interfaz */
public interface PlayersInfoObserver{
public void colorChanged(int p, Color color);
}
/** Declaramos una lista de observadores */
protected List<PlayersInfoObserver> observers;
/**
* Añadir observador a la lista
* @param o
*/
public void addObserver(PlayersInfoObserver o){
observers.add(o);
}
/**
* Notificar a los observadores
* @param p
* @param color
*/
protected void notifyObservers(int p, Color color){
for(PlayersInfoObserver o: observers)
o.colorChanged(p, color);
}
}
| 1,434 | 0.73515 | 0.734451 | 54 | 25.5 | 25.750046 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.240741 | false | false | 3 |
9afee891e73795d63922a1feca2d3a2e54ed2813 | 5,540,507,877,713 | bdc91cb482977d258a35855f23c459405008874c | /nn-ysb-service/src/main/java/com/n/ysb/service/business/core/ClientWithdrawService.java | 2fe67ca8b7c278702c214afb833145bc77d36184 | [] | no_license | mumu-shoucang/ysb | https://github.com/mumu-shoucang/ysb | 26138e7e7f135beccdfeb8a357e4fd44060a3f8b | 9cb6c6cbc9569cba50f2f0d7bb8355fa2e9d4f20 | refs/heads/master | 2020-04-25T01:55:59.937000 | 2019-02-25T03:13:44 | 2019-02-25T03:13:44 | 172,422,840 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.n.ysb.service.business.core;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.n.ysb.service.business.WithdrawStatus;
import com.n.ysb.service.business.core.YeepayBusService.YeeReturn;
import com.n.ysb.service.business.pars.QueryWithdrawPars;
import com.n.ysb.service.business.pars.WithdrawPars;
import com.n.ysb.service.business.pars.base.ReturnCode;
import com.n.ysb.service.business.pars.base.ReturnMap;
import com.n.ysb.service.merchant.mapper.NnMerchantMapper;
import com.n.ysb.service.merchant.po.NnMerchant;
import com.n.ysb.service.merchant.po.NnMerchantExample;
import com.n.ysb.service.merchant.vo.NnMerchantVo;
import com.n.ysb.service.order.po.NnOrder;
import com.n.ysb.service.thirdparty.vo.WithDrawVo;
import com.n.ysb.service.withdraw.mapper.NnYeecustomerWithdrawLogMapper;
import com.n.ysb.service.withdraw.mapper.NnYeecustomerWithdrawMapper;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdraw;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawExample;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawExample.Criteria;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawLog;
@Service
public class ClientWithdrawService {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private YeepayBusService yeepayBusService;
@Autowired
private IDGenerator IDGenerator;
@Autowired
private NnMerchantMapper merchantMapper;
@Autowired
private NnYeecustomerWithdrawLogMapper withdrawLogMapper;
@Autowired
private NnYeecustomerWithdrawMapper withdrawMapper;
public Map<String, Object> withdraw(WithdrawPars pars){
//创建订单
NnYeecustomerWithdraw buildOrder = buildOrder(pars);
boolean addSuc = addOrder(buildOrder);
if(!addSuc) {
return ReturnMap.fail();
}
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(),"结算订单接收成功");
NnMerchant merchant = getMerchant(pars.getMerchantMobile().toString());
NnMerchantVo merchantVo = new NnMerchantVo();
merchantVo.setYeeCustomerNumber(buildOrder.getYeeCustomerNumber());
WithDrawVo withDrawVo = new WithDrawVo();
withDrawVo.setWithDrawAmt(buildOrder.getWithdrawAmt());
withDrawVo.setExternalNo(buildOrder.getOrderNo());
YeeReturn yeeRet = yeepayBusService.withdraw(merchantVo, withDrawVo);
if(!yeeRet.isSuc()) {
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(), "调用易宝结算接口返回信息为:" + yeeRet.getDesc());
return ReturnMap.New(ReturnCode.bus_invalid.getCode(), yeeRet.getDesc());
}
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(),"成功调用易宝侧withdraw接口");
return ReturnMap.suc();
}
private boolean addOrder(NnYeecustomerWithdraw order) {
int c = withdrawMapper.insertSelective(order);
return c > 0 ? true : false;
}
private NnMerchant getMerchant(String merchantMobile){
NnMerchantExample condition = new NnMerchantExample();
com.n.ysb.service.merchant.po.NnMerchantExample.Criteria criteria = condition.createCriteria();
criteria.andLoginMobileEqualTo(merchantMobile);
List<NnMerchant> merchants = merchantMapper.selectByExample(condition);
return merchants != null && merchants.size() == 1 ? merchants.get(0) : null;
}
private NnYeecustomerWithdraw buildOrder(WithdrawPars pars) {
NnYeecustomerWithdraw po = new NnYeecustomerWithdraw();
po.setCreateDate(new Date());
po.setYeeCustomerNumber(pars.getYeeCustomerNumber());
po.setWithdrawAmt(pars.getWithdrawAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
po.setOrderNo(IDGenerator.buildWithdrawOrderNo());
po.setWithdrawStatus(WithdrawStatus.init.getCode());
return po;
}
private void withdrawLog(String orderNo, String withdrawStatus, String desc){
NnYeecustomerWithdrawLog log = new NnYeecustomerWithdrawLog();
log.setOrderNo(orderNo);
log.setOpTime(new Date());
log.setOpUser("system");
log.setWithdrawStatus(withdrawStatus);
log.setRemarks(desc);
withdrawLogMapper.insertSelective(log);
}
public Map<String, Object> queryWithdraw(QueryWithdrawPars pars, int pageNo, int limit) {
Page<NnYeecustomerWithdraw> startPage = PageHelper.startPage(pageNo, limit);
NnYeecustomerWithdrawExample example = new NnYeecustomerWithdrawExample();
Criteria criteria = example.createCriteria();
criteria.andYeeCustomerNumberEqualTo(pars.getYeeCustomerNumber());
example.setOrderByClause("CREATE_DATE desc");
List<NnYeecustomerWithdraw> WithdrawOrderList = withdrawMapper.selectByExample(example);
return ReturnMap.suc(startPage.getResult());
}
}
| UTF-8 | Java | 5,522 | java | ClientWithdrawService.java | Java | [
{
"context": "og.setOpTime(new Date());\r\n log.setOpUser(\"system\");\r\n log.setWithdrawStatus(withdrawStatus)",
"end": 4645,
"score": 0.5916500091552734,
"start": 4639,
"tag": "USERNAME",
"value": "system"
}
] | null | [] | package com.n.ysb.service.business.core;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.n.ysb.service.business.WithdrawStatus;
import com.n.ysb.service.business.core.YeepayBusService.YeeReturn;
import com.n.ysb.service.business.pars.QueryWithdrawPars;
import com.n.ysb.service.business.pars.WithdrawPars;
import com.n.ysb.service.business.pars.base.ReturnCode;
import com.n.ysb.service.business.pars.base.ReturnMap;
import com.n.ysb.service.merchant.mapper.NnMerchantMapper;
import com.n.ysb.service.merchant.po.NnMerchant;
import com.n.ysb.service.merchant.po.NnMerchantExample;
import com.n.ysb.service.merchant.vo.NnMerchantVo;
import com.n.ysb.service.order.po.NnOrder;
import com.n.ysb.service.thirdparty.vo.WithDrawVo;
import com.n.ysb.service.withdraw.mapper.NnYeecustomerWithdrawLogMapper;
import com.n.ysb.service.withdraw.mapper.NnYeecustomerWithdrawMapper;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdraw;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawExample;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawExample.Criteria;
import com.n.ysb.service.withdraw.po.NnYeecustomerWithdrawLog;
@Service
public class ClientWithdrawService {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private YeepayBusService yeepayBusService;
@Autowired
private IDGenerator IDGenerator;
@Autowired
private NnMerchantMapper merchantMapper;
@Autowired
private NnYeecustomerWithdrawLogMapper withdrawLogMapper;
@Autowired
private NnYeecustomerWithdrawMapper withdrawMapper;
public Map<String, Object> withdraw(WithdrawPars pars){
//创建订单
NnYeecustomerWithdraw buildOrder = buildOrder(pars);
boolean addSuc = addOrder(buildOrder);
if(!addSuc) {
return ReturnMap.fail();
}
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(),"结算订单接收成功");
NnMerchant merchant = getMerchant(pars.getMerchantMobile().toString());
NnMerchantVo merchantVo = new NnMerchantVo();
merchantVo.setYeeCustomerNumber(buildOrder.getYeeCustomerNumber());
WithDrawVo withDrawVo = new WithDrawVo();
withDrawVo.setWithDrawAmt(buildOrder.getWithdrawAmt());
withDrawVo.setExternalNo(buildOrder.getOrderNo());
YeeReturn yeeRet = yeepayBusService.withdraw(merchantVo, withDrawVo);
if(!yeeRet.isSuc()) {
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(), "调用易宝结算接口返回信息为:" + yeeRet.getDesc());
return ReturnMap.New(ReturnCode.bus_invalid.getCode(), yeeRet.getDesc());
}
withdrawLog(buildOrder.getOrderNo(),buildOrder.getWithdrawStatus(),"成功调用易宝侧withdraw接口");
return ReturnMap.suc();
}
private boolean addOrder(NnYeecustomerWithdraw order) {
int c = withdrawMapper.insertSelective(order);
return c > 0 ? true : false;
}
private NnMerchant getMerchant(String merchantMobile){
NnMerchantExample condition = new NnMerchantExample();
com.n.ysb.service.merchant.po.NnMerchantExample.Criteria criteria = condition.createCriteria();
criteria.andLoginMobileEqualTo(merchantMobile);
List<NnMerchant> merchants = merchantMapper.selectByExample(condition);
return merchants != null && merchants.size() == 1 ? merchants.get(0) : null;
}
private NnYeecustomerWithdraw buildOrder(WithdrawPars pars) {
NnYeecustomerWithdraw po = new NnYeecustomerWithdraw();
po.setCreateDate(new Date());
po.setYeeCustomerNumber(pars.getYeeCustomerNumber());
po.setWithdrawAmt(pars.getWithdrawAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
po.setOrderNo(IDGenerator.buildWithdrawOrderNo());
po.setWithdrawStatus(WithdrawStatus.init.getCode());
return po;
}
private void withdrawLog(String orderNo, String withdrawStatus, String desc){
NnYeecustomerWithdrawLog log = new NnYeecustomerWithdrawLog();
log.setOrderNo(orderNo);
log.setOpTime(new Date());
log.setOpUser("system");
log.setWithdrawStatus(withdrawStatus);
log.setRemarks(desc);
withdrawLogMapper.insertSelective(log);
}
public Map<String, Object> queryWithdraw(QueryWithdrawPars pars, int pageNo, int limit) {
Page<NnYeecustomerWithdraw> startPage = PageHelper.startPage(pageNo, limit);
NnYeecustomerWithdrawExample example = new NnYeecustomerWithdrawExample();
Criteria criteria = example.createCriteria();
criteria.andYeeCustomerNumberEqualTo(pars.getYeeCustomerNumber());
example.setOrderByClause("CREATE_DATE desc");
List<NnYeecustomerWithdraw> WithdrawOrderList = withdrawMapper.selectByExample(example);
return ReturnMap.suc(startPage.getResult());
}
}
| 5,522 | 0.701394 | 0.700293 | 136 | 38.088234 | 29.025717 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.691176 | false | false | 3 |
e420c589e8ce91d0b46f20c4e981fde4b3a993b4 | 22,119,081,625,379 | 2b294e7bb46de4b8dfd324a54e688dd23faa7fae | /src/java7sample/GenericsSample.java | cd756af91f21cebc64d69a68b0ecc3bd1139d4a3 | [] | no_license | tanaka-takayoshi/Java7Sample | https://github.com/tanaka-takayoshi/Java7Sample | 597cd898c6f789dfa54e51fa2976dee8a26210f1 | 92647fb690baa2660b8bebe69856845ccb705bb2 | refs/heads/master | 2021-01-01T06:32:57.518000 | 2011-08-11T08:02:15 | 2011-08-11T08:02:15 | 2,189,898 | 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 java7sample;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author TanakaTa
*/
public class GenericsSample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
}
public static void main2(String[] args) {
List<String> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Map<String, List<String>> listMap = new HashMap<>();
}
}
| UTF-8 | Java | 756 | java | GenericsSample.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n *\n * @author TanakaTa\n */\npublic class GenericsSample {\n \n public",
"end": 248,
"score": 0.9852290153503418,
"start": 240,
"tag": "NAME",
"value": "TanakaTa"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package java7sample;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author TanakaTa
*/
public class GenericsSample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
}
public static void main2(String[] args) {
List<String> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Map<String, List<String>> listMap = new HashMap<>();
}
}
| 756 | 0.634921 | 0.632275 | 29 | 25.068966 | 23.026119 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 3 |
b54d3cb4d57b6ee7a5ed221d5576b079a59c5220 | 30,210,799,998,560 | 82b60c434f764d702433e3b73e1be46a868e3dca | /Lesson_07/Lesson7.java | 0820d621fbe08e57f44b44be63fb1a5f6554538e | [] | no_license | reecealanboyd/LearningJava | https://github.com/reecealanboyd/LearningJava | 3b74441c10cbcea3fedc61495445195d50061b6b | 131edc6e3edf038c158099023e23f4e2fc268ff4 | refs/heads/master | 2021-01-24T17:49:44.419000 | 2016-03-29T04:33:34 | 2016-03-29T04:33:34 | 54,269,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Lesson7
{
public static void main(String args[])
{
Monster Frank = new Monster();
// The following line would cause an error at compile-time because
// attack is private and you can only access within the class.
// Because of this, we will have to use a getter from Monster.
//System.out.println(Frank.attack);
System.out.println(Frank.getAttack());
}
}
| UTF-8 | Java | 397 | java | Lesson7.java | Java | [] | null | [] | public class Lesson7
{
public static void main(String args[])
{
Monster Frank = new Monster();
// The following line would cause an error at compile-time because
// attack is private and you can only access within the class.
// Because of this, we will have to use a getter from Monster.
//System.out.println(Frank.attack);
System.out.println(Frank.getAttack());
}
}
| 397 | 0.690176 | 0.687657 | 12 | 32.083332 | 25.365522 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
77c4ef51785343835e0754477c2f54a0692ab749 | 14,285,061,261,477 | e48b80323e570d78df025c36082bfd0279ab6042 | /src/main/java/com/njust/bean/baseBean/Importance.java | 80e05b2b9e8dd2543330d993f608a3aa180440f4 | [] | no_license | QianMuTang/expertfinding | https://github.com/QianMuTang/expertfinding | 32942b31fe08f24e0cdcce670685369ab69b39db | 16d63b37f70bcd50df7117b7559404119ec72e9a | refs/heads/master | 2021-09-11T20:48:20.804000 | 2018-04-12T06:42:18 | 2018-04-12T06:42:18 | 110,107,759 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.njust.bean.baseBean;
import javax.persistence.*;
public class Importance {
@Id
@Column(name = "importance_id")
private Long importanceId;
@Column(name = "result_id")
private Long resultId;
@Column(name = "importance_score")
private Double importanceScore;
public Importance(Long importanceId, Long resultId, Double importanceScore) {
this.importanceId = importanceId;
this.resultId = resultId;
this.importanceScore = importanceScore;
}
public Importance() {
super();
}
/**
* @return importance_id
*/
public Long getImportanceId() {
return importanceId;
}
/**
* @param importanceId
*/
public void setImportanceId(Long importanceId) {
this.importanceId = importanceId;
}
/**
* @return result_id
*/
public Long getResultId() {
return resultId;
}
/**
* @param resultId
*/
public void setResultId(Long resultId) {
this.resultId = resultId;
}
/**
* @return importance_score
*/
public Double getImportanceScore() {
return importanceScore;
}
/**
* @param importanceScore
*/
public void setImportanceScore(Double importanceScore) {
this.importanceScore = importanceScore;
}
} | UTF-8 | Java | 1,412 | java | Importance.java | Java | [] | null | [] | package com.njust.bean.baseBean;
import javax.persistence.*;
public class Importance {
@Id
@Column(name = "importance_id")
private Long importanceId;
@Column(name = "result_id")
private Long resultId;
@Column(name = "importance_score")
private Double importanceScore;
public Importance(Long importanceId, Long resultId, Double importanceScore) {
this.importanceId = importanceId;
this.resultId = resultId;
this.importanceScore = importanceScore;
}
public Importance() {
super();
}
/**
* @return importance_id
*/
public Long getImportanceId() {
return importanceId;
}
/**
* @param importanceId
*/
public void setImportanceId(Long importanceId) {
this.importanceId = importanceId;
}
/**
* @return result_id
*/
public Long getResultId() {
return resultId;
}
/**
* @param resultId
*/
public void setResultId(Long resultId) {
this.resultId = resultId;
}
/**
* @return importance_score
*/
public Double getImportanceScore() {
return importanceScore;
}
/**
* @param importanceScore
*/
public void setImportanceScore(Double importanceScore) {
this.importanceScore = importanceScore;
}
} | 1,412 | 0.575071 | 0.575071 | 67 | 19.104477 | 17.814243 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.253731 | false | false | 3 |
30bb002bf95ccf698940235b7dd62e4744644c2d | 16,303,695,884,704 | b9b7627e839b49ca11f084b1778c8d512212dcee | /app/src/main/java/com/jacksonvillecomedy/broskj/jaxcomedy/Directions.java | a6be5133da350c3b7f572541f60ab39e91f611ec | [] | no_license | techibis/JaxComedy | https://github.com/techibis/JaxComedy | 84058af81a9e1dcefb6f291b48d91bd24da6f5f3 | 1cce5cf100a0a17b7956b6c1d3b9a9f08c6e7ae1 | refs/heads/master | 2021-01-16T17:57:05.957000 | 2015-02-18T01:29:53 | 2015-02-18T01:29:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jacksonvillecomedy.broskj.jaxcomedy;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;
/**
* Created by Kyle on 12/29/2014.
*
* NO LONGER BEING USED, REPLACED WITH MAP INTENT.
*/
public class Directions extends Activity {
int screenWidth, screenHeight;
final String addressURL = "https://www.google.com/maps/place/11000+Beach+Blvd,+Jacksonville,+FL+32246/";
@TargetApi(16)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directions);
System.out.println("directions created");
final int screenWidth = getIntent().getExtras().getInt("screenWidth");
final int screenHeight = getIntent().getExtras().getInt("screenHeight");
manageActionBar();
scaleBackground(screenWidth, screenHeight);
/*
creates a webview object and parses a URL string. Enables GPS location for directions.
*/
WebView webview = (WebView) findViewById(R.id.webview_directions);
try {
webview.setWebViewClient(new GeoWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setGeolocationEnabled(true);
webview.setWebChromeClient(new GeoWebChromeClient());
webview.loadUrl(addressURL);
} catch (Exception e) {
System.out.println("Exception called during webview process");
e.printStackTrace();
}
}//end onCreate
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
} //end onOptionsItemSelected
public class GeoWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}//end GeoWebViewClient
public class GeoWebChromeClient extends WebChromeClient {
@Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}//end GeoWebChromeClient
/*
creates ActionBar object, enables the home button, and resets title to ''
*/
public void manageActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Directions");
}//end manageActionBar
/*
scales background for performance
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void scaleBackground(int screenWidth, int screenHeight) {
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.rlDirections);
Bitmap bitmapBackground = BitmapFactory.decodeResource(getResources(), R.drawable.background);
Bitmap resizedBitmapBackground = Bitmap.createScaledBitmap(bitmapBackground, screenWidth, screenHeight, true);
myLayout.setBackground(new BitmapDrawable(getResources(), resizedBitmapBackground));
}//end scaleBackground
} | UTF-8 | Java | 4,342 | java | Directions.java | Java | [
{
"context": "w;\nimport android.widget.Toast;\n\n/**\n * Created by Kyle on 12/29/2014.\n *\n * NO LONGER BEING USED, REPLAC",
"end": 804,
"score": 0.9965524673461914,
"start": 800,
"tag": "NAME",
"value": "Kyle"
}
] | null | [] | package com.jacksonvillecomedy.broskj.jaxcomedy;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;
/**
* Created by Kyle on 12/29/2014.
*
* NO LONGER BEING USED, REPLACED WITH MAP INTENT.
*/
public class Directions extends Activity {
int screenWidth, screenHeight;
final String addressURL = "https://www.google.com/maps/place/11000+Beach+Blvd,+Jacksonville,+FL+32246/";
@TargetApi(16)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directions);
System.out.println("directions created");
final int screenWidth = getIntent().getExtras().getInt("screenWidth");
final int screenHeight = getIntent().getExtras().getInt("screenHeight");
manageActionBar();
scaleBackground(screenWidth, screenHeight);
/*
creates a webview object and parses a URL string. Enables GPS location for directions.
*/
WebView webview = (WebView) findViewById(R.id.webview_directions);
try {
webview.setWebViewClient(new GeoWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setGeolocationEnabled(true);
webview.setWebChromeClient(new GeoWebChromeClient());
webview.loadUrl(addressURL);
} catch (Exception e) {
System.out.println("Exception called during webview process");
e.printStackTrace();
}
}//end onCreate
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
} //end onOptionsItemSelected
public class GeoWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}//end GeoWebViewClient
public class GeoWebChromeClient extends WebChromeClient {
@Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}//end GeoWebChromeClient
/*
creates ActionBar object, enables the home button, and resets title to ''
*/
public void manageActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Directions");
}//end manageActionBar
/*
scales background for performance
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void scaleBackground(int screenWidth, int screenHeight) {
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.rlDirections);
Bitmap bitmapBackground = BitmapFactory.decodeResource(getResources(), R.drawable.background);
Bitmap resizedBitmapBackground = Bitmap.createScaledBitmap(bitmapBackground, screenWidth, screenHeight, true);
myLayout.setBackground(new BitmapDrawable(getResources(), resizedBitmapBackground));
}//end scaleBackground
} | 4,342 | 0.689083 | 0.684247 | 120 | 35.191666 | 27.212526 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
17c88864a498e27e928312fef5fac40131f475ec | 12,790,412,641,046 | 9e001af2a9261c9ccbdefade4a73c3b751ce369d | /naolf/src/com/cocosh/car/service/impl/OrderLogServiceImpl.java | b0771e98e7711ab9435fa45e57ba48e53391f46c | [] | no_license | admiralsoft/java_projects | https://github.com/admiralsoft/java_projects | 2ae0186abf75183dab58e28689cb2cb1169f812e | 68be434805641af6c401d47fe09bae4f434f76aa | refs/heads/master | 2023-03-15T13:12:23.137000 | 2017-11-29T08:11:26 | 2017-11-29T08:11:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cocosh.car.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cocosh.framework.util.StringUtil;
import com.cocosh.car.mapper.OrderLogMapper;
import com.cocosh.car.model.OrderLog;
import com.cocosh.car.service.OrderLogService;
@Transactional
@Service
public class OrderLogServiceImpl implements OrderLogService {
@Autowired
private OrderLogMapper mapper;
@Override
public boolean add(OrderLog po) {
po.setId(StringUtil.getUuid());
return mapper.add(po) > 0;
}
@Override
public List<OrderLog> query(String id) {
return mapper.query(id);
}
}
| UTF-8 | Java | 748 | java | OrderLogServiceImpl.java | Java | [] | null | [] | package com.cocosh.car.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cocosh.framework.util.StringUtil;
import com.cocosh.car.mapper.OrderLogMapper;
import com.cocosh.car.model.OrderLog;
import com.cocosh.car.service.OrderLogService;
@Transactional
@Service
public class OrderLogServiceImpl implements OrderLogService {
@Autowired
private OrderLogMapper mapper;
@Override
public boolean add(OrderLog po) {
po.setId(StringUtil.getUuid());
return mapper.add(po) > 0;
}
@Override
public List<OrderLog> query(String id) {
return mapper.query(id);
}
}
| 748 | 0.796247 | 0.794906 | 31 | 23.064516 | 20.817076 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903226 | false | false | 3 |
97c3f0cc92dcd2b1b7e50791703478c8a70b7c09 | 27,762,668,632,373 | bbcd1ca59601057feaca183ef534028853d9300e | /lwh-gl/gl-order/src/main/java/com/lwhtarena/glmall/order/vo/FareVo.java | 41e0213f7b03578f581f603827d1b4ed71c63681 | [] | no_license | hkkkkq/cloud | https://github.com/hkkkkq/cloud | 214f95e1c0a07af99339219119b7200ff6b8056f | ee21c997ed02ec69ff5b97c78851894c5c25301b | refs/heads/master | 2023-01-01T05:03:44.237000 | 2020-10-22T16:32:56 | 2020-10-22T16:32:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lwhtarena.glmall.order.vo;
import lombok.Data;
import java.math.BigDecimal;
/**
* @author liwh
* @Title: FareVo
* @Package com.lwhtarena.glmall.order.vo
* @Description:
* @Version 1.0.0
* @date 2020/9/9 16:16
*/
@Data
public class FareVo {
private MemberAddressVo address;
private BigDecimal fare;
}
| UTF-8 | Java | 333 | java | FareVo.java | Java | [
{
"context": "ata;\n\nimport java.math.BigDecimal;\n\n/**\n * @author liwh\n * @Title: FareVo\n * @Package com.lwhtarena.glmal",
"end": 110,
"score": 0.9996964931488037,
"start": 106,
"tag": "USERNAME",
"value": "liwh"
}
] | null | [] | package com.lwhtarena.glmall.order.vo;
import lombok.Data;
import java.math.BigDecimal;
/**
* @author liwh
* @Title: FareVo
* @Package com.lwhtarena.glmall.order.vo
* @Description:
* @Version 1.0.0
* @date 2020/9/9 16:16
*/
@Data
public class FareVo {
private MemberAddressVo address;
private BigDecimal fare;
}
| 333 | 0.693694 | 0.654655 | 21 | 14.809524 | 13.48233 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false | 3 |
3feccb246bf05b7d06046557642741a082c86775 | 20,779,051,807,812 | 6a499f351231259b093fb19f72c394f1b12826fd | /src/main/java/parkinglot/ParkingSpot/ParkingSpot.java | a22180a029aebfed0a78aeafa00510ffd93a382c | [] | no_license | sourabh13/ParkingLot | https://github.com/sourabh13/ParkingLot | 378afeb4316560544608263b8ca39f2ec1e41959 | 8429f75d8c74077149e341e582ac1affdbcfabd7 | refs/heads/master | 2022-04-05T15:47:38.505000 | 2020-02-23T09:47:54 | 2020-02-23T09:47:54 | 242,280,654 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package parkinglot.ParkingSpot;
import parkinglot.Enums.ParkingSpotType;
import parkinglot.Vehicles.Vehicle;
public abstract class ParkingSpot {
private final ParkingSpotType type;
private Integer number;
private Vehicle vehicle;
private Boolean isFree;
public ParkingSpot(ParkingSpotType type, Integer number) {
this.type = type;
this.number = number;
this.isFree = true;
this.vehicle = null;
}
public Integer getNumber() {
return this.number;
}
public Vehicle getVehicle() {
return this.vehicle;
}
public ParkingSpotType getType() {
return this.type;
}
public void assignVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
this.isFree = false;
}
public void removeVehicle() {
this.vehicle = null;
this.isFree = true;
}
}
| UTF-8 | Java | 886 | java | ParkingSpot.java | Java | [] | null | [] | package parkinglot.ParkingSpot;
import parkinglot.Enums.ParkingSpotType;
import parkinglot.Vehicles.Vehicle;
public abstract class ParkingSpot {
private final ParkingSpotType type;
private Integer number;
private Vehicle vehicle;
private Boolean isFree;
public ParkingSpot(ParkingSpotType type, Integer number) {
this.type = type;
this.number = number;
this.isFree = true;
this.vehicle = null;
}
public Integer getNumber() {
return this.number;
}
public Vehicle getVehicle() {
return this.vehicle;
}
public ParkingSpotType getType() {
return this.type;
}
public void assignVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
this.isFree = false;
}
public void removeVehicle() {
this.vehicle = null;
this.isFree = true;
}
}
| 886 | 0.637698 | 0.637698 | 44 | 19.136364 | 16.501503 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431818 | false | false | 3 |
2d515225670b0bff33ad04942c864e01f1433d2e | 7,653,631,764,486 | 2b83d9f2e44a945988cf780606c0a7c7be392128 | /grpc/betPawa/bet-server/src/main/java/ee/dsoccer/server/BalanceServiceImpl.java | bea50279e07ac2ee2e8061c74ba4464e2a948c8e | [] | no_license | dsoccer1980/spring-db | https://github.com/dsoccer1980/spring-db | 10da6bdcf4caaa78c19c55d07892111dd78ac2a8 | 34f32b8891191087ca84120e396f6b78e72ef816 | refs/heads/master | 2022-12-22T20:28:12.509000 | 2021-12-14T13:35:24 | 2021-12-14T13:35:24 | 218,032,414 | 0 | 0 | null | false | 2022-12-16T15:49:55 | 2019-10-28T11:35:32 | 2021-12-14T14:45:35 | 2022-12-16T15:49:52 | 290 | 0 | 0 | 37 | Java | false | false | package ee.dsoccer.server;
import ee.dsoccer.bet.BalanceServiceGrpc.BalanceServiceImplBase;
import ee.dsoccer.bet.Bet.Balance;
import ee.dsoccer.bet.Bet.User;
import ee.dsoccer.repository.BankRepository;
import io.grpc.stub.StreamObserver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BalanceServiceImpl extends BalanceServiceImplBase {
private final BankRepository repository;
public BalanceServiceImpl(BankRepository repository) {
this.repository = repository;
}
@Override
public void balance(User user, StreamObserver<Balance> responseObserver) {
try {
Balance balance = repository.getBalance(user);
responseObserver.onNext(balance);
responseObserver.onCompleted();
} catch (Exception e) {
responseObserver.onError(e);
}
}
}
| UTF-8 | Java | 875 | java | BalanceServiceImpl.java | Java | [] | null | [] | package ee.dsoccer.server;
import ee.dsoccer.bet.BalanceServiceGrpc.BalanceServiceImplBase;
import ee.dsoccer.bet.Bet.Balance;
import ee.dsoccer.bet.Bet.User;
import ee.dsoccer.repository.BankRepository;
import io.grpc.stub.StreamObserver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BalanceServiceImpl extends BalanceServiceImplBase {
private final BankRepository repository;
public BalanceServiceImpl(BankRepository repository) {
this.repository = repository;
}
@Override
public void balance(User user, StreamObserver<Balance> responseObserver) {
try {
Balance balance = repository.getBalance(user);
responseObserver.onNext(balance);
responseObserver.onCompleted();
} catch (Exception e) {
responseObserver.onError(e);
}
}
}
| 875 | 0.777143 | 0.777143 | 31 | 27.225807 | 23.371763 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false | 3 |
b7018a0fa497135684b69bd713bd29eb2b7728a7 | 5,712,306,521,357 | d555776cf5190abc9b1b1f1b96a54369d218966c | /src/main/java/Tst/CloudSqlServlet.java | 098589999d227d18d0d34bdfbfb9fda42c639d73 | [] | no_license | AndreyOOP/GoogleMySql | https://github.com/AndreyOOP/GoogleMySql | e4f4a0cc0f6ea38c0c9fe16369795c169740769b | b8d73cf2f5d6d0c4989911b972cf6799fcfa695f | refs/heads/master | 2020-05-25T19:53:20.216000 | 2016-10-03T17:15:24 | 2016-10-03T17:15:24 | 69,887,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Tst;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
public class CloudSqlServlet extends HttpServlet {
final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL," +
" timestamp DATETIME NOT NULL, PRIMARY KEY (visit_id) )";
final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC LIMIT 10";
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
String path = req.getRequestURI();
ignoreFavicon(path);
String userIp = storeIP( req.getRemoteAddr());
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
String url = chooseDriverGAEorLocalAndReturnURL();
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
conn.createStatement().executeUpdate(createTableSql);
statementCreateVisit.setString(1, userIp);
statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
statementCreateVisit.executeUpdate();
try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
out.print("Last 10 visits:\n");
while (rs.next()) {
String savedIp = rs.getString("user_ip");
String timeStamp = rs.getString("timestamp");
out.print("TimeN: " + timeStamp + " Addr: " + savedIp + "\n");
}
}
out.print( "Get From testuserauth table: " + dbAccess(conn));
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
}
private String storeIP(String userIp){
InetAddress address = null;
try {
address = InetAddress.getByName(userIp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (address instanceof Inet6Address) {
return userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
} else if (address instanceof Inet4Address) {
return userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
}
return "error";
}
private void ignoreFavicon(String path){
if (path.startsWith("/favicon.ico")) { // ignore the request for favicon.ico
return;
}
}
private String chooseDriverGAEorLocalAndReturnURL(){
if (System.getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {// Check the System properties to determine if we are running on appengine or not
try {
Class.forName("com.mysql.jdbc.GoogleDriver"); // Load the class that provides the new "jdbc:google:mysql://" prefix.
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return System.getProperty("ae-cloudsql.cloudsql-database-url");
} else {
return System.getProperty("ae-cloudsql.local-database-url"); // Set the url with the local MySQL database connection url when running locally
}
}
private String dbAccess(Connection connection){
try {
ResultSet resultSet = connection.prepareStatement("SELECT * FROM testuserauth").executeQuery();
resultSet.next();
return resultSet.getString("login");
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
}
| UTF-8 | Java | 4,337 | java | CloudSqlServlet.java | Java | [] | null | [] | package Tst;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
public class CloudSqlServlet extends HttpServlet {
final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL," +
" timestamp DATETIME NOT NULL, PRIMARY KEY (visit_id) )";
final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC LIMIT 10";
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
String path = req.getRequestURI();
ignoreFavicon(path);
String userIp = storeIP( req.getRemoteAddr());
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
String url = chooseDriverGAEorLocalAndReturnURL();
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
conn.createStatement().executeUpdate(createTableSql);
statementCreateVisit.setString(1, userIp);
statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
statementCreateVisit.executeUpdate();
try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
out.print("Last 10 visits:\n");
while (rs.next()) {
String savedIp = rs.getString("user_ip");
String timeStamp = rs.getString("timestamp");
out.print("TimeN: " + timeStamp + " Addr: " + savedIp + "\n");
}
}
out.print( "Get From testuserauth table: " + dbAccess(conn));
} catch (SQLException e) {
throw new ServletException("SQL error", e);
}
}
private String storeIP(String userIp){
InetAddress address = null;
try {
address = InetAddress.getByName(userIp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (address instanceof Inet6Address) {
return userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
} else if (address instanceof Inet4Address) {
return userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
}
return "error";
}
private void ignoreFavicon(String path){
if (path.startsWith("/favicon.ico")) { // ignore the request for favicon.ico
return;
}
}
private String chooseDriverGAEorLocalAndReturnURL(){
if (System.getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {// Check the System properties to determine if we are running on appengine or not
try {
Class.forName("com.mysql.jdbc.GoogleDriver"); // Load the class that provides the new "jdbc:google:mysql://" prefix.
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return System.getProperty("ae-cloudsql.cloudsql-database-url");
} else {
return System.getProperty("ae-cloudsql.local-database-url"); // Set the url with the local MySQL database connection url when running locally
}
}
private String dbAccess(Connection connection){
try {
ResultSet resultSet = connection.prepareStatement("SELECT * FROM testuserauth").executeQuery();
resultSet.next();
return resultSet.getString("login");
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
}
| 4,337 | 0.63454 | 0.630851 | 128 | 32.882813 | 36.557877 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.539063 | false | false | 10 |
da80f89ae458d56eca1c3f94709101ecef584da6 | 1,529,008,363,217 | 98790e1bf485ddba1baf5e060ec934823333a0bb | /src/sparrow/driver/Sender.java | e357b38d5ed0d827fb3ff6fda3c8c1f668e50e0e | [] | no_license | Juanjdurillo/sparrow | https://github.com/Juanjdurillo/sparrow | 8f508fececc7d96d84dacb9ecc227d6047fc4843 | 2090c79223f9df68124e6bb5ccd7c2646b1f75bd | refs/heads/master | 2021-05-04T04:20:28.561000 | 2018-02-05T20:30:48 | 2018-02-05T20:30:48 | 120,332,258 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* JMetalDriverSender.java
*
* @author Antonio J. Nebro
* @authr Juan J. Durillo
* @version 1.0
*/
package sparrow.driver;
import sparrow.util.SharedObjects;
import sparrow.util.Message;
import sparrow.util.Task;
import java.io.*;
import java.net.Socket;
import java.util.*;
import sparrow.applications.Monitor;
import sparrow.worker.WorkerId;
/**
* This class implementes the sender thread of the driver
*/
public class Sender extends Thread {
/**
* store all the diferents workers that have been
* participated in the computation
*/
SharedObjects sharedObjects_ ;
/**
* Constructor
*/
public Sender(SharedObjects sharedObjects) {
super();
sharedObjects_ = sharedObjects ;
} // Constructor
/**
* Sends a task to a worker
* @param task the task
* @param worker the worker
*/
public void send(Task task, WorkerId worker) throws Exception {
Socket socket;
ObjectOutputStream outStream;
ObjectInputStream inStream;
Message taskMessage, response;
socket = new Socket(worker.getIP(),worker.getPort());
outStream = new ObjectOutputStream(socket.getOutputStream()) ;
inStream = new ObjectInputStream(socket.getInputStream()) ;
System.out.println("SENDER: sending task " + task.getId()) ;
taskMessage = new Message(sharedObjects_.sessionId_,
Message.EXECUTE,
task);
outStream.writeObject(taskMessage) ;
response = (Message)inStream.readObject();
outStream.close();
inStream.close();
socket.close();
if (response.getType() != Message.EXECUTE_ACK) {
throw new SenderException();
}
} // send
/**
* Run method
* @throws
*/
public void run() {
// Endless loop
boolean finish ;
finish = false ;
while (!sharedObjects_.terminate_) {
WorkerId worker = null;
Task task = null;
try {
worker = sharedObjects_.idleWorkers_.get();
task = sharedObjects_.nonScheduledTask_.get();
if (worker == null) {
finish = true;
} else //// CAMBIOOOOOOOOOOOOOOOOOOOOOOOOOO
if (task == null) { // terminate
finish = true ;
} else {
synchronized(sharedObjects_) {
// Enviar el mensaje a un worker.
send(task,worker);
// Removes task and worker from the list
sharedObjects_.idleWorkers_.remove();
sharedObjects_.nonScheduledTask_.remove();
sharedObjects_.busyWorkers_.add(task.getId(),worker);
sharedObjects_.scheduledTask_.add(task.getId(),task);
}
}
} catch (Exception e) {
// The task can have been scheduled into the worker.
// It is possible that the worker are corrupt,
//then remove from the list and add at the end
if (worker != null) {
synchronized(sharedObjects_) {
sharedObjects_.idleWorkers_.remove();
sharedObjects_.allWorkers_.remove(worker);
List<WorkerId> toReset = new ArrayList<WorkerId>();
toReset.add(worker);
Monitor.reset(toReset);
// sharedObjects_.idleWorkers_.add(worker);
}
}
}
} // while
} // run
} // Sender
| UTF-8 | Java | 3,446 | java | Sender.java | Java | [
{
"context": "/**\r\n * JMetalDriverSender.java\r\n *\r\n * @author Antonio J. Nebro\r\n * @authr Juan J. Durillo\r\n * @version 1.0\r\n */\r",
"end": 64,
"score": 0.9998812675476074,
"start": 48,
"tag": "NAME",
"value": "Antonio J. Nebro"
},
{
"context": "r.java\r\n *\r\n * @author ... | null | [] | /**
* JMetalDriverSender.java
*
* @author <NAME>
* @authr <NAME>
* @version 1.0
*/
package sparrow.driver;
import sparrow.util.SharedObjects;
import sparrow.util.Message;
import sparrow.util.Task;
import java.io.*;
import java.net.Socket;
import java.util.*;
import sparrow.applications.Monitor;
import sparrow.worker.WorkerId;
/**
* This class implementes the sender thread of the driver
*/
public class Sender extends Thread {
/**
* store all the diferents workers that have been
* participated in the computation
*/
SharedObjects sharedObjects_ ;
/**
* Constructor
*/
public Sender(SharedObjects sharedObjects) {
super();
sharedObjects_ = sharedObjects ;
} // Constructor
/**
* Sends a task to a worker
* @param task the task
* @param worker the worker
*/
public void send(Task task, WorkerId worker) throws Exception {
Socket socket;
ObjectOutputStream outStream;
ObjectInputStream inStream;
Message taskMessage, response;
socket = new Socket(worker.getIP(),worker.getPort());
outStream = new ObjectOutputStream(socket.getOutputStream()) ;
inStream = new ObjectInputStream(socket.getInputStream()) ;
System.out.println("SENDER: sending task " + task.getId()) ;
taskMessage = new Message(sharedObjects_.sessionId_,
Message.EXECUTE,
task);
outStream.writeObject(taskMessage) ;
response = (Message)inStream.readObject();
outStream.close();
inStream.close();
socket.close();
if (response.getType() != Message.EXECUTE_ACK) {
throw new SenderException();
}
} // send
/**
* Run method
* @throws
*/
public void run() {
// Endless loop
boolean finish ;
finish = false ;
while (!sharedObjects_.terminate_) {
WorkerId worker = null;
Task task = null;
try {
worker = sharedObjects_.idleWorkers_.get();
task = sharedObjects_.nonScheduledTask_.get();
if (worker == null) {
finish = true;
} else //// CAMBIOOOOOOOOOOOOOOOOOOOOOOOOOO
if (task == null) { // terminate
finish = true ;
} else {
synchronized(sharedObjects_) {
// Enviar el mensaje a un worker.
send(task,worker);
// Removes task and worker from the list
sharedObjects_.idleWorkers_.remove();
sharedObjects_.nonScheduledTask_.remove();
sharedObjects_.busyWorkers_.add(task.getId(),worker);
sharedObjects_.scheduledTask_.add(task.getId(),task);
}
}
} catch (Exception e) {
// The task can have been scheduled into the worker.
// It is possible that the worker are corrupt,
//then remove from the list and add at the end
if (worker != null) {
synchronized(sharedObjects_) {
sharedObjects_.idleWorkers_.remove();
sharedObjects_.allWorkers_.remove(worker);
List<WorkerId> toReset = new ArrayList<WorkerId>();
toReset.add(worker);
Monitor.reset(toReset);
// sharedObjects_.idleWorkers_.add(worker);
}
}
}
} // while
} // run
} // Sender
| 3,427 | 0.580093 | 0.579512 | 121 | 26.47934 | 19.694401 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.966942 | false | false | 10 |
06f68e2dc5c1abfa8a0d7896b82fdd95be297eb0 | 17,248,588,666,295 | c7b809a1965e729690d79dc9b41705d926b559e8 | /dl-worker/dl-worker-api/src/main/java/com/ucar/datalink/worker/api/probe/TaskExceptionProbe.java | 7665ba261ae828016cee97cef4ff2feb6b9d5b51 | [
"CDDL-1.1",
"Apache-2.0",
"CDDL-1.0"
] | permissive | KangZhiDong/DataLink | https://github.com/KangZhiDong/DataLink | a32ad97a2af503f04e09d725e7b47a6d5eafa038 | 3bf8bfbf910f7830aa34c3918a98567ac2f67d17 | refs/heads/master | 2020-05-03T04:42:47.792000 | 2019-03-29T15:23:21 | 2019-03-29T15:23:21 | 178,429,752 | 4 | 2 | Apache-2.0 | true | 2019-03-29T15:21:03 | 2019-03-29T15:21:03 | 2019-03-28T14:02:04 | 2019-02-25T07:03:05 | 8,447 | 0 | 0 | 0 | null | false | null | package com.ucar.datalink.worker.api.probe;
import com.ucar.datalink.worker.api.probe.index.TaskExceptionProbeIndex;
/**
* Created by lubiao on 2018/3/14.
*/
public interface TaskExceptionProbe extends Probe{
void record(TaskExceptionProbeIndex index);
}
| UTF-8 | Java | 265 | java | TaskExceptionProbe.java | Java | [
{
"context": ".index.TaskExceptionProbeIndex;\n\n/**\n * Created by lubiao on 2018/3/14.\n */\npublic interface TaskExceptionP",
"end": 143,
"score": 0.9995453357696533,
"start": 137,
"tag": "USERNAME",
"value": "lubiao"
}
] | null | [] | package com.ucar.datalink.worker.api.probe;
import com.ucar.datalink.worker.api.probe.index.TaskExceptionProbeIndex;
/**
* Created by lubiao on 2018/3/14.
*/
public interface TaskExceptionProbe extends Probe{
void record(TaskExceptionProbeIndex index);
}
| 265 | 0.777358 | 0.750943 | 12 | 21.083334 | 25.137815 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 10 |
ff2860977ff7d3836a9a6c6e16a9ee1bda959616 | 27,195,732,923,465 | 8fe8bbf4565adea58a337f8493fa3cdbfbb85f8c | /src/main/java/fr/miage/projetagent/entity/Association.java | 5cc030967c775fb7506221ac83ae3a77de54eb6e | [
"Apache-2.0"
] | permissive | tillind/ProjetAgent | https://github.com/tillind/ProjetAgent | f697186f03406c5de5f2d03226675868e34d8413 | e7709fb22f7ed7c562752b335697b03d7fbd4b48 | refs/heads/master | 2021-09-05T15:46:26.293000 | 2018-01-29T11:37:16 | 2018-01-29T11:37:16 | 110,519,234 | 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 fr.miage.projetagent.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries({
@NamedQuery(name="Association.findAll",
query="SELECT a FROM Association a"),
})
public class Association implements Serializable {
@Id
private String nom;
@OneToOne
private Argent tresorerie;
@OneToMany (mappedBy = "association")
private Set<Vaccin> vaccins;
@OneToMany (mappedBy = "association")
private Set<Vol> vols;
@OneToMany (mappedBy = "association")
private Set<Envoi> envois;
@OneToOne
private Metrics metrics;
public Association() {
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Argent getTresorerie() {
return tresorerie;
}
public void setTresorerie(Argent tresorerie) {
this.tresorerie = tresorerie;
}
public Set<Vaccin> getVaccins() {
return vaccins;
}
public void setVaccins(Set<Vaccin> vaccins) {
this.vaccins = vaccins;
}
public Set<Vol> getVols() {
return vols;
}
public void setVols(Set<Vol> vols) {
this.vols = vols;
}
public Set<Envoi> getEnvois() {
return envois;
}
public void setEnvois(Set<Envoi> envois) {
this.envois = envois;
}
}
| UTF-8 | Java | 1,847 | java | Association.java | Java | [] | 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 fr.miage.projetagent.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries({
@NamedQuery(name="Association.findAll",
query="SELECT a FROM Association a"),
})
public class Association implements Serializable {
@Id
private String nom;
@OneToOne
private Argent tresorerie;
@OneToMany (mappedBy = "association")
private Set<Vaccin> vaccins;
@OneToMany (mappedBy = "association")
private Set<Vol> vols;
@OneToMany (mappedBy = "association")
private Set<Envoi> envois;
@OneToOne
private Metrics metrics;
public Association() {
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Argent getTresorerie() {
return tresorerie;
}
public void setTresorerie(Argent tresorerie) {
this.tresorerie = tresorerie;
}
public Set<Vaccin> getVaccins() {
return vaccins;
}
public void setVaccins(Set<Vaccin> vaccins) {
this.vaccins = vaccins;
}
public Set<Vol> getVols() {
return vols;
}
public void setVols(Set<Vol> vols) {
this.vols = vols;
}
public Set<Envoi> getEnvois() {
return envois;
}
public void setEnvois(Set<Envoi> envois) {
this.envois = envois;
}
}
| 1,847 | 0.628045 | 0.628045 | 80 | 21.0875 | 17.952154 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 10 |
1e2eddf0a7d7d69dac2d901ba184237f1fcd18da | 30,545,807,411,213 | 7aa7ce5fa9141a0df74cd675fffa10780413631b | /justtestlah-core/src/main/java/qa/justtestlah/aop/AopConfig.java | 1b30edfd24bed2893edc99cf997a9d74ed7a270a | [
"Apache-2.0"
] | permissive | hankbot/justtestlah | https://github.com/hankbot/justtestlah | aee04fbd911476491a54f8516b38eea15cec1778 | 96f91271b4eedd00724925866c4747544fb83718 | refs/heads/master | 2022-12-23T00:40:46.336000 | 2020-09-24T05:04:17 | 2020-09-24T05:05:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package qa.justtestlah.aop;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* AOP Logging Spring configuration. Enables entry-exit logging for all public methods in steps and
* page objects and all methods.
*/
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
// placeholder for steps and page object packages
private static final String POINTCUT_TEMPLATE = "execution(public * __package__..*.*(..))";
@Value("${pages.package}")
private String pagesPackage;
@Value("${steps.package}")
private String stepsPackage;
@Bean
public EntryExitLoggingAspect entryExitLoggingAspect() {
return new EntryExitLoggingAspect();
}
@Bean
public AspectJExpressionPointcutAdvisor stepsLoggingAdvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(POINTCUT_TEMPLATE.replaceFirst("__package__", stepsPackage));
advisor.setAdvice(entryExitLoggingAspect());
return advisor;
}
@Bean
public AspectJExpressionPointcutAdvisor pagesLoggingAdvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(POINTCUT_TEMPLATE.replaceFirst("__package__", pagesPackage));
advisor.setAdvice(entryExitLoggingAspect());
return advisor;
}
}
| UTF-8 | Java | 1,580 | java | AopConfig.java | Java | [] | null | [] | package qa.justtestlah.aop;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* AOP Logging Spring configuration. Enables entry-exit logging for all public methods in steps and
* page objects and all methods.
*/
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
// placeholder for steps and page object packages
private static final String POINTCUT_TEMPLATE = "execution(public * __package__..*.*(..))";
@Value("${pages.package}")
private String pagesPackage;
@Value("${steps.package}")
private String stepsPackage;
@Bean
public EntryExitLoggingAspect entryExitLoggingAspect() {
return new EntryExitLoggingAspect();
}
@Bean
public AspectJExpressionPointcutAdvisor stepsLoggingAdvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(POINTCUT_TEMPLATE.replaceFirst("__package__", stepsPackage));
advisor.setAdvice(entryExitLoggingAspect());
return advisor;
}
@Bean
public AspectJExpressionPointcutAdvisor pagesLoggingAdvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(POINTCUT_TEMPLATE.replaceFirst("__package__", pagesPackage));
advisor.setAdvice(entryExitLoggingAspect());
return advisor;
}
}
| 1,580 | 0.784177 | 0.784177 | 46 | 33.347828 | 31.17079 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 10 |
fd325a96f0b6811221aa4c75493e0aea7b9ea6de | 30,545,807,415,298 | 6cb531888a9642ab84f98c6beb2a05d40c1e2f75 | /TestTrouble3D/src/org/testtrouble3d/game/engine/GameEngine.java | 12d7c54085fb3b5540dd4e58a00df25b030381b4 | [] | no_license | itamarq0/TestTrouble3D | https://github.com/itamarq0/TestTrouble3D | 4dd3df281c8adb1b64424ff2bd3a4f77d5855b9a | 2ddef93836d67f98daff296a6aea1819621249e0 | refs/heads/master | 2020-09-15T12:17:51.589000 | 2017-07-07T14:16:23 | 2017-07-07T14:16:23 | 94,477,975 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.testtrouble3d.game.engine;
import org.testtrouble3d.game.engine.window.KeyboardInput;
import org.testtrouble3d.game.engine.window.MouseInput;
import org.testtrouble3d.game.engine.window.Window;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
public class GameEngine implements Runnable {
public GameEngine(String windowTitle, int width, int height, boolean vsSync, IGameLogic gameLogic) throws Exception {
//gameLoopThread = new Thread(this, "GAME_LOOP_THREAD");
this.window = new Window(windowTitle, width, height, vsSync);
this.gameLogic = gameLogic;
this.mouseInput = new MouseInput();
this.keyboardInput = new KeyboardInput();
}
public void start() {
//gameLoopThread.start();
run();
}
@Override
public void run() {
try {
init();
gameLoop();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
cleanup();
}
}
protected void gameLoop() {
window.show();
float lastTimeStamp = 0;
float currentTimeStamp =(float) glfwGetTime();
float interval = 0;
while (!window.shouldClose()) {
lastTimeStamp = currentTimeStamp;
currentTimeStamp = (float) glfwGetTime();
interval = currentTimeStamp - lastTimeStamp;
input();
update(interval);
render();
}
}
protected void render() {
gameLogic.render(window);
}
protected void init() throws Exception {
//WINDOW NEEDS TO BE THE FIRST ONE INITIALIZED!
window.init();
gameLogic.init();
mouseInput.init(window);
keyboardInput.init(window);
}
protected void cleanup(){
window.cleanup();
gameLogic.cleanup();
}
protected void input() {
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
mouseInput.input(window);
gameLogic.input(window, mouseInput, keyboardInput);
}
protected void update(float interval) {
gameLogic.update(interval, mouseInput, keyboardInput);
}
//private final Thread gameLoopThread;
private Window window;
private MouseInput mouseInput;
private KeyboardInput keyboardInput;
private IGameLogic gameLogic;
} | UTF-8 | Java | 2,364 | java | GameEngine.java | Java | [] | null | [] | package org.testtrouble3d.game.engine;
import org.testtrouble3d.game.engine.window.KeyboardInput;
import org.testtrouble3d.game.engine.window.MouseInput;
import org.testtrouble3d.game.engine.window.Window;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
public class GameEngine implements Runnable {
public GameEngine(String windowTitle, int width, int height, boolean vsSync, IGameLogic gameLogic) throws Exception {
//gameLoopThread = new Thread(this, "GAME_LOOP_THREAD");
this.window = new Window(windowTitle, width, height, vsSync);
this.gameLogic = gameLogic;
this.mouseInput = new MouseInput();
this.keyboardInput = new KeyboardInput();
}
public void start() {
//gameLoopThread.start();
run();
}
@Override
public void run() {
try {
init();
gameLoop();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
cleanup();
}
}
protected void gameLoop() {
window.show();
float lastTimeStamp = 0;
float currentTimeStamp =(float) glfwGetTime();
float interval = 0;
while (!window.shouldClose()) {
lastTimeStamp = currentTimeStamp;
currentTimeStamp = (float) glfwGetTime();
interval = currentTimeStamp - lastTimeStamp;
input();
update(interval);
render();
}
}
protected void render() {
gameLogic.render(window);
}
protected void init() throws Exception {
//WINDOW NEEDS TO BE THE FIRST ONE INITIALIZED!
window.init();
gameLogic.init();
mouseInput.init(window);
keyboardInput.init(window);
}
protected void cleanup(){
window.cleanup();
gameLogic.cleanup();
}
protected void input() {
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
mouseInput.input(window);
gameLogic.input(window, mouseInput, keyboardInput);
}
protected void update(float interval) {
gameLogic.update(interval, mouseInput, keyboardInput);
}
//private final Thread gameLoopThread;
private Window window;
private MouseInput mouseInput;
private KeyboardInput keyboardInput;
private IGameLogic gameLogic;
} | 2,364 | 0.721235 | 0.717851 | 98 | 23.132652 | 20.450357 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.867347 | false | false | 10 |
faf766034403238faa455217c8da3f45762b698f | 6,957,847,024,551 | 2e9a86693b665b879c59b14dfd63c2c92acbf08a | /webconverter/decomiledJars/rt/com/sun/org/apache/xml/internal/utils/BoolStack.java | f6daf42f820a62ecaf6f562114d5e6bb88f76839 | [] | no_license | shaikgsb/webproject-migration-code-java | https://github.com/shaikgsb/webproject-migration-code-java | 9e2271255077025111e7ea3f887af7d9368c6933 | 3b17211e497658c61435f6c0e118b699e7aa3ded | refs/heads/master | 2021-01-19T18:36:42.835000 | 2017-07-13T09:11:05 | 2017-07-13T09:11:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sun.org.apache.xml.internal.utils;
public final class BoolStack
implements Cloneable
{
private boolean[] m_values;
private int m_allocatedSize;
private int m_index;
public BoolStack()
{
this(32);
}
public BoolStack(int paramInt)
{
this.m_allocatedSize = paramInt;
this.m_values = new boolean[paramInt];
this.m_index = -1;
}
public final int size()
{
return this.m_index + 1;
}
public final void clear()
{
this.m_index = -1;
}
public final boolean push(boolean paramBoolean)
{
if (this.m_index == this.m_allocatedSize - 1) {
grow();
}
return this.m_values[(++this.m_index)] = paramBoolean;
}
public final boolean pop()
{
return this.m_values[(this.m_index--)];
}
public final boolean popAndTop()
{
this.m_index -= 1;
return this.m_index >= 0 ? this.m_values[this.m_index] : false;
}
public final void setTop(boolean paramBoolean)
{
this.m_values[this.m_index] = paramBoolean;
}
public final boolean peek()
{
return this.m_values[this.m_index];
}
public final boolean peekOrFalse()
{
return this.m_index > -1 ? this.m_values[this.m_index] : false;
}
public final boolean peekOrTrue()
{
return this.m_index > -1 ? this.m_values[this.m_index] : true;
}
public boolean isEmpty()
{
return this.m_index == -1;
}
private void grow()
{
this.m_allocatedSize *= 2;
boolean[] arrayOfBoolean = new boolean[this.m_allocatedSize];
System.arraycopy(this.m_values, 0, arrayOfBoolean, 0, this.m_index + 1);
this.m_values = arrayOfBoolean;
}
public Object clone()
throws CloneNotSupportedException
{
return super.clone();
}
}
| UTF-8 | Java | 1,752 | java | BoolStack.java | Java | [] | null | [] | package com.sun.org.apache.xml.internal.utils;
public final class BoolStack
implements Cloneable
{
private boolean[] m_values;
private int m_allocatedSize;
private int m_index;
public BoolStack()
{
this(32);
}
public BoolStack(int paramInt)
{
this.m_allocatedSize = paramInt;
this.m_values = new boolean[paramInt];
this.m_index = -1;
}
public final int size()
{
return this.m_index + 1;
}
public final void clear()
{
this.m_index = -1;
}
public final boolean push(boolean paramBoolean)
{
if (this.m_index == this.m_allocatedSize - 1) {
grow();
}
return this.m_values[(++this.m_index)] = paramBoolean;
}
public final boolean pop()
{
return this.m_values[(this.m_index--)];
}
public final boolean popAndTop()
{
this.m_index -= 1;
return this.m_index >= 0 ? this.m_values[this.m_index] : false;
}
public final void setTop(boolean paramBoolean)
{
this.m_values[this.m_index] = paramBoolean;
}
public final boolean peek()
{
return this.m_values[this.m_index];
}
public final boolean peekOrFalse()
{
return this.m_index > -1 ? this.m_values[this.m_index] : false;
}
public final boolean peekOrTrue()
{
return this.m_index > -1 ? this.m_values[this.m_index] : true;
}
public boolean isEmpty()
{
return this.m_index == -1;
}
private void grow()
{
this.m_allocatedSize *= 2;
boolean[] arrayOfBoolean = new boolean[this.m_allocatedSize];
System.arraycopy(this.m_values, 0, arrayOfBoolean, 0, this.m_index + 1);
this.m_values = arrayOfBoolean;
}
public Object clone()
throws CloneNotSupportedException
{
return super.clone();
}
}
| 1,752 | 0.623858 | 0.615297 | 89 | 18.685392 | 19.783432 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.325843 | false | false | 10 |
88c2394b2c0e980d6c2f43e97287c4d75d2758bc | 10,264,971,845,004 | 0f77c5ec508d6e8b558f726980067d1058e350d7 | /1_39_120042/com/ankamagames/wakfu/client/core/game/specifics/IceStatueDoubleCharacteristicsImpl.java | 56b1c213576dede91c15c9eb96c06fd4b83419e3 | [] | no_license | nightwolf93/Wakxy-Core-Decompiled | https://github.com/nightwolf93/Wakxy-Core-Decompiled | aa589ebb92197bf48e6576026648956f93b8bf7f | 2967f8f8fba89018f63b36e3978fc62908aa4d4d | refs/heads/master | 2016-09-05T11:07:45.145000 | 2014-12-30T16:21:30 | 2014-12-30T16:21:30 | 29,250,176 | 5 | 5 | null | true | 2015-01-14T15:17:02 | 2015-01-14T15:17:02 | 2015-01-14T15:16:54 | 2014-12-30T16:28:28 | 9,832 | 0 | 0 | 0 | null | null | null | package com.ankamagames.wakfu.client.core.game.specifics;
import com.ankamagames.wakfu.common.datas.*;
import com.ankamagames.wakfu.common.game.spell.*;
import com.ankamagames.wakfu.common.rawData.*;
import com.ankamagames.baseImpl.common.clientAndServer.game.inventory.*;
import com.ankamagames.wakfu.client.core.game.characterInfo.*;
import com.ankamagames.wakfu.client.core.game.characterInfo.monsters.*;
import com.ankamagames.wakfu.client.core.game.breed.*;
import com.ankamagames.framework.graphics.engine.Anm2.*;
import com.ankamagames.wakfu.common.datas.specific.*;
public final class IceStatueDoubleCharacteristicsImpl extends IceStatueDoubleCharacteristics
{
public IceStatueDoubleCharacteristicsImpl() {
super();
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance() {
return new IceStatueDoubleCharacteristicsImpl();
}
public IceStatueDoubleCharacteristicsImpl(final short id, final String name, final int hp, final short level, final BasicCharacterInfo model, final int doublePower, final SpellInventory<AbstractSpellLevel> spellInventory) {
super(id, name, hp, level, model, doublePower, spellInventory);
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance(final short id, final String name, final int hp, final short level, final BasicCharacterInfo model, final int doublePower, final SpellInventory<AbstractSpellLevel> spellInventory) {
return new IceStatueDoubleCharacteristicsImpl(id, name, hp, level, model, doublePower, spellInventory);
}
public IceStatueDoubleCharacteristicsImpl(final short maximumSpellInventorySize, final InventoryContentProvider<AbstractSpellLevel, RawSpellLevel> contentProvider, final InventoryContentChecker<AbstractSpellLevel> contentChecker, final boolean ordered, final boolean stackable, final boolean serializeQuantity) {
super(maximumSpellInventorySize, contentProvider, contentChecker, ordered, stackable, serializeQuantity);
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance(final short maximumSpellInventorySize, final InventoryContentProvider<AbstractSpellLevel, RawSpellLevel> contentProvider, final InventoryContentChecker<AbstractSpellLevel> contentChecker, final boolean ordered, final boolean stackable, final boolean serializeQuantity) {
return new IceStatueDoubleCharacteristicsImpl(maximumSpellInventorySize, contentProvider, contentChecker, ordered, stackable, serializeQuantity);
}
@Override
public void initializeSummoning(final BasicCharacterInfo summoning, final BasicCharacterInfo summoner) {
super.initializeSummoning(summoning, summoner);
final NonPlayerCharacter summon = (NonPlayerCharacter)summoning;
summon.setGfxId(this.getDoubleGfx());
summon.setForcedGfxId(this.getDoubleGfx());
final MonsterSpecialGfx customGfx = new MonsterSpecialGfx();
customGfx.addEquipement(new MonsterSpecialGfx.Equipment(BreedColorsManager.getInstance().getDressStyle(this.getTypeId(), this.getSex() == 0, this.m_clothIndex), AnmPartHelper.getParts("VETEMENTCUSTOM")));
summon.setSpecificSpecialGfx(customGfx);
summon.forceEquipmentAppearance(this.m_equipmentAppearance);
summon.refreshDisplayEquipment();
}
private int getDoubleGfx() {
int baseId = 1;
baseId *= 1000;
baseId += this.getTypeId() * 10 + this.m_sex;
baseId *= 100;
return ++baseId;
}
}
| UTF-8 | Java | 3,525 | java | IceStatueDoubleCharacteristicsImpl.java | Java | [] | null | [] | package com.ankamagames.wakfu.client.core.game.specifics;
import com.ankamagames.wakfu.common.datas.*;
import com.ankamagames.wakfu.common.game.spell.*;
import com.ankamagames.wakfu.common.rawData.*;
import com.ankamagames.baseImpl.common.clientAndServer.game.inventory.*;
import com.ankamagames.wakfu.client.core.game.characterInfo.*;
import com.ankamagames.wakfu.client.core.game.characterInfo.monsters.*;
import com.ankamagames.wakfu.client.core.game.breed.*;
import com.ankamagames.framework.graphics.engine.Anm2.*;
import com.ankamagames.wakfu.common.datas.specific.*;
public final class IceStatueDoubleCharacteristicsImpl extends IceStatueDoubleCharacteristics
{
public IceStatueDoubleCharacteristicsImpl() {
super();
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance() {
return new IceStatueDoubleCharacteristicsImpl();
}
public IceStatueDoubleCharacteristicsImpl(final short id, final String name, final int hp, final short level, final BasicCharacterInfo model, final int doublePower, final SpellInventory<AbstractSpellLevel> spellInventory) {
super(id, name, hp, level, model, doublePower, spellInventory);
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance(final short id, final String name, final int hp, final short level, final BasicCharacterInfo model, final int doublePower, final SpellInventory<AbstractSpellLevel> spellInventory) {
return new IceStatueDoubleCharacteristicsImpl(id, name, hp, level, model, doublePower, spellInventory);
}
public IceStatueDoubleCharacteristicsImpl(final short maximumSpellInventorySize, final InventoryContentProvider<AbstractSpellLevel, RawSpellLevel> contentProvider, final InventoryContentChecker<AbstractSpellLevel> contentChecker, final boolean ordered, final boolean stackable, final boolean serializeQuantity) {
super(maximumSpellInventorySize, contentProvider, contentChecker, ordered, stackable, serializeQuantity);
}
@Override
public IceStatueDoubleCharacteristicsImpl newInstance(final short maximumSpellInventorySize, final InventoryContentProvider<AbstractSpellLevel, RawSpellLevel> contentProvider, final InventoryContentChecker<AbstractSpellLevel> contentChecker, final boolean ordered, final boolean stackable, final boolean serializeQuantity) {
return new IceStatueDoubleCharacteristicsImpl(maximumSpellInventorySize, contentProvider, contentChecker, ordered, stackable, serializeQuantity);
}
@Override
public void initializeSummoning(final BasicCharacterInfo summoning, final BasicCharacterInfo summoner) {
super.initializeSummoning(summoning, summoner);
final NonPlayerCharacter summon = (NonPlayerCharacter)summoning;
summon.setGfxId(this.getDoubleGfx());
summon.setForcedGfxId(this.getDoubleGfx());
final MonsterSpecialGfx customGfx = new MonsterSpecialGfx();
customGfx.addEquipement(new MonsterSpecialGfx.Equipment(BreedColorsManager.getInstance().getDressStyle(this.getTypeId(), this.getSex() == 0, this.m_clothIndex), AnmPartHelper.getParts("VETEMENTCUSTOM")));
summon.setSpecificSpecialGfx(customGfx);
summon.forceEquipmentAppearance(this.m_equipmentAppearance);
summon.refreshDisplayEquipment();
}
private int getDoubleGfx() {
int baseId = 1;
baseId *= 1000;
baseId += this.getTypeId() * 10 + this.m_sex;
baseId *= 100;
return ++baseId;
}
}
| 3,525 | 0.774468 | 0.771064 | 62 | 55.854839 | 71.440445 | 328 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.306452 | false | false | 10 |
6b54a541958f5df388fdb992e2a2b36b28e153e7 | 18,124,762,024,615 | 6e808b10126ab4de90a88459c23705422472a4ec | /app/src/main/java/ir/jahanshahloo/evmis/UI/MainActivity.java | d8fbf6f1276ffdbee5ac122317913b58641b1598 | [] | no_license | a-jahanshahlo/evmis-android | https://github.com/a-jahanshahlo/evmis-android | 9abc3032991e7b1d4f63285af7247433437b7626 | a3d058c02902d467f4f06573bfc7b3a06565003a | refs/heads/master | 2021-03-27T15:22:30.469000 | 2017-11-10T16:21:49 | 2017-11-10T16:21:49 | 110,264,718 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ir.jahanshahloo.evmis.UI;
import android.content.Intent;
import android.os.Bundle;
import com.github.clans.fab.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionMenu;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import ir.jahanshahloo.evmis.R;
import ir.jahanshahloo.evmis.Util.App;
import ir.jahanshahloo.evmis.Util.AppUrls;
public class MainActivity extends AppCompatActivity implements HouseFragment.OnTouchListListener, HouseForRentFragment.OnTouchForRentListListener {
/**/
private FloatingActionButton fab_sales;
private FloatingActionButton fab_rent;
private FloatingActionMenu fab_menu_main;
Toolbar toolbar;
Picasso picasso;
private TabLayout tabLayout;
private ViewPager viewPager;
AccountHeader headerResult;
Drawer result;
IProfile activeProfile;
HouseForRentDialogFragment rentDialogFragment;
private Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab_menu_main=(FloatingActionMenu)findViewById(R.id.main_fab_menu);
fab_menu_main.setClosedOnTouchOutside(true);
fab_rent = (FloatingActionButton) findViewById(R.id.fab_rent);
fab_sales = (FloatingActionButton) findViewById(R.id.fab_sales);
rentDialogFragment = new HouseForRentDialogFragment();
/*
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (FAB_Status == false) {
//Display FAB menu
expandFAB();
FAB_Status = true;
} else {
//Close FAB menu
hideFAB();
FAB_Status = false;
}
}
});*/
picasso = ((App) getApplication()).getNetComponent().getPicasso();
//initialize tabLayout
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//initialize viewpager
viewPager = (ViewPager) findViewById(R.id.viewpager);
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Test");
// getSupportActionBar().setSubtitle("subtitle");
toolbar.setSubtitle("subtitle");
setUpDrawer();
/* if (AndroidUtility.isConnectToInternet(getBaseContext())) {
}
*/
setupViewPager(viewPager);
//link tabs with view pager
tabLayout.setupWithViewPager(viewPager);
setTabs();
fab_sales.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// i=new Intent(MainActivity.this,)
}
});
fab_rent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(MainActivity.this, NewHouseForRentActivity.class);
startActivity(i);
}
});
}
private void refreshProfileImage() {
if (headerResult != null) {
if (activeProfile != null) {
headerResult.updateProfile(activeProfile);
}
}
}
@Override
protected void onResume() {
super.onResume();
refreshProfileImage();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_search:
Toast.makeText(getBaseContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
break;
}
return true;
}
public void onFilterClick(MenuItem menuItem) {
rentDialogFragment.show(getFragmentManager(), "dasdsd");
}
public void setUpDrawer() {
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.backgroung_evmis_profile)
.addProfiles(
new ProfileDrawerItem()
.withName("علیرضا")
.withEmail("جهانشاهلو")
.withIcon(AppUrls.PROFILE_IMAGE)
.withSelectedColorRes(R.color.iconsTint_dark)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
activeProfile = headerResult.getActiveProfile();
result = new DrawerBuilder()
.withAccountHeader(headerResult)
.withActivity(this)
.withToolbar(toolbar)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.pref_mobile_number).withIcon(FontAwesome.Icon.faw_mobile).withIdentifier(1).withDescription("9307185332"),
new DividerDrawerItem(),
new SecondaryDrawerItem().withIdentifier(2).withName("تنظیمات").withIcon(FontAwesome.Icon.faw_gear).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
/* Intent i =new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, 1);*/
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
return false;
}
}),
new SecondaryDrawerItem().withIdentifier(3).withName("dddd"),
new SecondaryDrawerItem().withIdentifier(4).withName("wwwww")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D
return false;
}
})
.withDrawerGravity(Gravity.END)
.build();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
HouseFragment houseFragment = new HouseFragment();
HouseForRentFragment houseForRentFragment = new HouseForRentFragment();
// create three fragments for three tabs and set them
adapter.addFragment(houseForRentFragment, getResources().getString(R.string.House_Salse));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.House_Rent));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.service));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.consultant));
viewPager.setAdapter(adapter);
}
@Override
public void onTouch(View v, MotionEvent event) {
}
@Override
public void onTouchRentHouse(View v, MotionEvent event) {
Log.i("ali","List tuched");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setTabs() {
// add names and icons to tabs or can attach a custom layout
// can identify tabs attach with fragments using id
tabLayout.getTabAt(0).setText(getResources().getString(R.string.House_Salse));//.setIcon(R.drawable.first_tab_icon);
tabLayout.getTabAt(1).setText(getResources().getString(R.string.House_Rent));//.setIcon(R.drawable.first_tab_icon);
tabLayout.getTabAt(2).setText(getResources().getString(R.string.service));//.setIcon(R.drawable.second_tab_icon);
tabLayout.getTabAt(3).setText(getResources().getString(R.string.consultant));//.setIcon(R.drawable.third_tab_icon);
}
}
| UTF-8 | Java | 10,607 | java | MainActivity.java | Java | [
{
"context": "tent;\nimport android.os.Bundle;\nimport com.github.clans.fab.FloatingActionButton;\nimport android.support.",
"end": 116,
"score": 0.7177726030349731,
"start": 111,
"tag": "USERNAME",
"value": "clans"
},
{
"context": "Item()\n .withName(\... | null | [] | package ir.jahanshahloo.evmis.UI;
import android.content.Intent;
import android.os.Bundle;
import com.github.clans.fab.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionMenu;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import ir.jahanshahloo.evmis.R;
import ir.jahanshahloo.evmis.Util.App;
import ir.jahanshahloo.evmis.Util.AppUrls;
public class MainActivity extends AppCompatActivity implements HouseFragment.OnTouchListListener, HouseForRentFragment.OnTouchForRentListListener {
/**/
private FloatingActionButton fab_sales;
private FloatingActionButton fab_rent;
private FloatingActionMenu fab_menu_main;
Toolbar toolbar;
Picasso picasso;
private TabLayout tabLayout;
private ViewPager viewPager;
AccountHeader headerResult;
Drawer result;
IProfile activeProfile;
HouseForRentDialogFragment rentDialogFragment;
private Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab_menu_main=(FloatingActionMenu)findViewById(R.id.main_fab_menu);
fab_menu_main.setClosedOnTouchOutside(true);
fab_rent = (FloatingActionButton) findViewById(R.id.fab_rent);
fab_sales = (FloatingActionButton) findViewById(R.id.fab_sales);
rentDialogFragment = new HouseForRentDialogFragment();
/*
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (FAB_Status == false) {
//Display FAB menu
expandFAB();
FAB_Status = true;
} else {
//Close FAB menu
hideFAB();
FAB_Status = false;
}
}
});*/
picasso = ((App) getApplication()).getNetComponent().getPicasso();
//initialize tabLayout
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//initialize viewpager
viewPager = (ViewPager) findViewById(R.id.viewpager);
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Test");
// getSupportActionBar().setSubtitle("subtitle");
toolbar.setSubtitle("subtitle");
setUpDrawer();
/* if (AndroidUtility.isConnectToInternet(getBaseContext())) {
}
*/
setupViewPager(viewPager);
//link tabs with view pager
tabLayout.setupWithViewPager(viewPager);
setTabs();
fab_sales.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// i=new Intent(MainActivity.this,)
}
});
fab_rent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(MainActivity.this, NewHouseForRentActivity.class);
startActivity(i);
}
});
}
private void refreshProfileImage() {
if (headerResult != null) {
if (activeProfile != null) {
headerResult.updateProfile(activeProfile);
}
}
}
@Override
protected void onResume() {
super.onResume();
refreshProfileImage();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_search:
Toast.makeText(getBaseContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show();
break;
}
return true;
}
public void onFilterClick(MenuItem menuItem) {
rentDialogFragment.show(getFragmentManager(), "dasdsd");
}
public void setUpDrawer() {
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.backgroung_evmis_profile)
.addProfiles(
new ProfileDrawerItem()
.withName("علیرضا")
.withEmail("جهانشاهلو")
.withIcon(AppUrls.PROFILE_IMAGE)
.withSelectedColorRes(R.color.iconsTint_dark)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
activeProfile = headerResult.getActiveProfile();
result = new DrawerBuilder()
.withAccountHeader(headerResult)
.withActivity(this)
.withToolbar(toolbar)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.pref_mobile_number).withIcon(FontAwesome.Icon.faw_mobile).withIdentifier(1).withDescription("9307185332"),
new DividerDrawerItem(),
new SecondaryDrawerItem().withIdentifier(2).withName("تنظیمات").withIcon(FontAwesome.Icon.faw_gear).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
/* Intent i =new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, 1);*/
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
return false;
}
}),
new SecondaryDrawerItem().withIdentifier(3).withName("dddd"),
new SecondaryDrawerItem().withIdentifier(4).withName("wwwww")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D
return false;
}
})
.withDrawerGravity(Gravity.END)
.build();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
HouseFragment houseFragment = new HouseFragment();
HouseForRentFragment houseForRentFragment = new HouseForRentFragment();
// create three fragments for three tabs and set them
adapter.addFragment(houseForRentFragment, getResources().getString(R.string.House_Salse));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.House_Rent));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.service));
adapter.addFragment(new HouseFragment(), getResources().getString(R.string.consultant));
viewPager.setAdapter(adapter);
}
@Override
public void onTouch(View v, MotionEvent event) {
}
@Override
public void onTouchRentHouse(View v, MotionEvent event) {
Log.i("ali","List tuched");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setTabs() {
// add names and icons to tabs or can attach a custom layout
// can identify tabs attach with fragments using id
tabLayout.getTabAt(0).setText(getResources().getString(R.string.House_Salse));//.setIcon(R.drawable.first_tab_icon);
tabLayout.getTabAt(1).setText(getResources().getString(R.string.House_Rent));//.setIcon(R.drawable.first_tab_icon);
tabLayout.getTabAt(2).setText(getResources().getString(R.string.service));//.setIcon(R.drawable.second_tab_icon);
tabLayout.getTabAt(3).setText(getResources().getString(R.string.consultant));//.setIcon(R.drawable.third_tab_icon);
}
}
| 10,607 | 0.628153 | 0.625791 | 293 | 35.126282 | 31.30813 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515358 | false | false | 10 |
e398f367c24a06d42ecf5bb970941fcf4cd82d3a | 25,409,026,570,381 | 8f30ec284c29e02d8cacf2ef0b2b901d84fddb7a | /net.dougqh.jak.jvm.assembler/test-src/net/dougqh/jak/jvm/assembler/LocalsTest.java | 40f0e7967cc90a25eb6688b04df99c63467d340c | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | dougqh/JAK | https://github.com/dougqh/JAK | 8b7096766b36909262d03a3754ae71b1c8c67e03 | e10da7384cce6466530c12378ee782a1d8209b51 | refs/heads/master | 2021-01-01T16:19:39.434000 | 2013-04-04T04:01:42 | 2013-04-04T04:01:42 | 732,624 | 11 | 2 | null | false | 2013-04-04T04:01:27 | 2010-06-21T20:00:44 | 2013-04-04T04:01:26 | 2013-04-04T04:00:16 | 2,504 | null | 0 | 1 | Java | null | null | package net.dougqh.jak.jvm.assembler;
import java.lang.reflect.Type;
import net.dougqh.jak.types.Any;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.Test;
import static org.junit.Assert.*;
public final class LocalsTest {
@Test
public final void noDeclarations() {
DefaultLocals locals = new DefaultLocals();
locals.load( 0, int.class );
assertThat( locals.maxLocals(), is( 1 ) );
assertThat( locals.typeOf( 0, Any.class ), is( int.class ) );
locals.load( 1, long.class );
assertThat( locals.maxLocals(), is( 3 ) );
assertThat( locals.typeOf( 1, Any.class ), is( long.class ) );
locals.load( 3, String.class );
assertThat( locals.maxLocals(), is( 4 ) );
assertThat( locals.typeOf( 3, Any.class ), is( String.class ) );
}
@Test
public final void declareCategory1() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( int.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( int.class ) );
int secondSlot = locals.declare( float.class );
assertThat( secondSlot, is( 1 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( float.class );
assertThat( thirdSlot, is( 0 ) );
assertThat( locals.typeOf( thirdSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
}
@Test
public final void declareCategory2() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( long.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( long.class ) );
int secondSlot = locals.declare( double.class );
assertThat( secondSlot, is( 2 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( double.class ) );
assertThat( locals.maxLocals(), is( 4 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( long.class );
assertThat( thirdSlot, is( 0 ) );
assertThat( locals.typeOf( thirdSlot, Any.class ), is( long.class ) );
assertThat( locals.maxLocals(), is( 4 ) );
}
@Test
public final void declareMix() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( int.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( int.class ) );
int secondSlot = locals.declare( float.class );
assertThat( secondSlot, is( 1 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( long.class );
assertThat( thirdSlot, is( 2 ) );
locals.undeclare( secondSlot );
int fourthSlot = locals.declare( long.class );
assertThat( fourthSlot, is( 0 ) );
assertThat( locals.maxLocals(), is( 4 ) );
}
private static final Matcher< Integer > is( final int value ) {
return CoreMatchers.is( value );
}
private static final Matcher< Type > is( final Type value ) {
return CoreMatchers.is( value );
}
}
| UTF-8 | Java | 3,184 | java | LocalsTest.java | Java | [] | null | [] | package net.dougqh.jak.jvm.assembler;
import java.lang.reflect.Type;
import net.dougqh.jak.types.Any;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.Test;
import static org.junit.Assert.*;
public final class LocalsTest {
@Test
public final void noDeclarations() {
DefaultLocals locals = new DefaultLocals();
locals.load( 0, int.class );
assertThat( locals.maxLocals(), is( 1 ) );
assertThat( locals.typeOf( 0, Any.class ), is( int.class ) );
locals.load( 1, long.class );
assertThat( locals.maxLocals(), is( 3 ) );
assertThat( locals.typeOf( 1, Any.class ), is( long.class ) );
locals.load( 3, String.class );
assertThat( locals.maxLocals(), is( 4 ) );
assertThat( locals.typeOf( 3, Any.class ), is( String.class ) );
}
@Test
public final void declareCategory1() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( int.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( int.class ) );
int secondSlot = locals.declare( float.class );
assertThat( secondSlot, is( 1 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( float.class );
assertThat( thirdSlot, is( 0 ) );
assertThat( locals.typeOf( thirdSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
}
@Test
public final void declareCategory2() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( long.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( long.class ) );
int secondSlot = locals.declare( double.class );
assertThat( secondSlot, is( 2 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( double.class ) );
assertThat( locals.maxLocals(), is( 4 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( long.class );
assertThat( thirdSlot, is( 0 ) );
assertThat( locals.typeOf( thirdSlot, Any.class ), is( long.class ) );
assertThat( locals.maxLocals(), is( 4 ) );
}
@Test
public final void declareMix() {
DefaultLocals locals = new DefaultLocals();
int firstSlot = locals.declare( int.class );
assertThat( firstSlot, is( 0 ) );
assertThat( locals.typeOf( firstSlot, Any.class ), is( int.class ) );
int secondSlot = locals.declare( float.class );
assertThat( secondSlot, is( 1 ) );
assertThat( locals.typeOf( secondSlot, Any.class ), is( float.class ) );
assertThat( locals.maxLocals(), is( 2 ) );
locals.undeclare( firstSlot );
int thirdSlot = locals.declare( long.class );
assertThat( thirdSlot, is( 2 ) );
locals.undeclare( secondSlot );
int fourthSlot = locals.declare( long.class );
assertThat( fourthSlot, is( 0 ) );
assertThat( locals.maxLocals(), is( 4 ) );
}
private static final Matcher< Integer > is( final int value ) {
return CoreMatchers.is( value );
}
private static final Matcher< Type > is( final Type value ) {
return CoreMatchers.is( value );
}
}
| 3,184 | 0.669912 | 0.661432 | 111 | 27.684685 | 23.508091 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.423424 | false | false | 10 |
134c09c4e162fa0b910875ca8ab486ad0b8ee671 | 31,903,017,140,852 | 2e8150a1d9af03a4b5c7c23c9fcffd7c1291470d | /stub/src/jcrypt/Main.java | 4ff86cabc57c7dd6f864540d04f3204f83e2e0cd | [] | no_license | wille/jcrypt | https://github.com/wille/jcrypt | e879276ccc9a91f4ac148f673eb29a88fc46324b | df89a16a92a5ae8f6187392fd3c32a2cb4b84a78 | refs/heads/master | 2023-08-27T02:27:16.514000 | 2023-08-07T10:24:54 | 2023-08-07T10:24:54 | 10,582,038 | 13 | 11 | null | false | 2023-08-07T10:24:55 | 2013-06-09T10:59:46 | 2023-04-23T12:52:01 | 2023-08-07T10:24:54 | 131 | 43 | 22 | 3 | Java | false | false | package jcrypt;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.Key;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static final String ENCRYPTED_ARCHIVE = "/jar.dat";
public static void main(String[] args) throws Exception {
ZipFile zip = new ZipFile(Utils.getJarFile());
ZipEntry e = zip.getEntry("jar.dat");
byte[] extra = e.getExtra();
byte[] key = new byte[16];
System.arraycopy(extra, 0, key, 0, 16);
byte[] iv = new byte[16];
System.arraycopy(extra, 16, iv, 0, 16);
boolean cryptAll = extra[32] == 1;
byte[] bMainClass = new byte[extra.length - 33];
System.arraycopy(extra, 33, bMainClass, 0, extra.length - 33);
String mainClass = new String(bMainClass);
zip.close();
InputStream resource = Main.class.getResourceAsStream(ENCRYPTED_ARCHIVE);
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
Key sks = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(iv));
JarInputStream jarInputStream = new JarInputStream(new CipherInputStream(resource, cipher));
EncryptedClassLoader classLoader = new EncryptedClassLoader(Main.class.getClassLoader(), jarInputStream, cryptAll);
Class<?> classToLoad = classLoader.loadClass(mainClass);
Method method = classToLoad.getMethod("main", new Class[] { String[].class });
method.invoke(classToLoad.newInstance(), new Object[] { args });
jarInputStream.close();
}
}
| UTF-8 | Java | 1,683 | java | Main.java | Java | [] | null | [] | package jcrypt;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.Key;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static final String ENCRYPTED_ARCHIVE = "/jar.dat";
public static void main(String[] args) throws Exception {
ZipFile zip = new ZipFile(Utils.getJarFile());
ZipEntry e = zip.getEntry("jar.dat");
byte[] extra = e.getExtra();
byte[] key = new byte[16];
System.arraycopy(extra, 0, key, 0, 16);
byte[] iv = new byte[16];
System.arraycopy(extra, 16, iv, 0, 16);
boolean cryptAll = extra[32] == 1;
byte[] bMainClass = new byte[extra.length - 33];
System.arraycopy(extra, 33, bMainClass, 0, extra.length - 33);
String mainClass = new String(bMainClass);
zip.close();
InputStream resource = Main.class.getResourceAsStream(ENCRYPTED_ARCHIVE);
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
Key sks = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(iv));
JarInputStream jarInputStream = new JarInputStream(new CipherInputStream(resource, cipher));
EncryptedClassLoader classLoader = new EncryptedClassLoader(Main.class.getClassLoader(), jarInputStream, cryptAll);
Class<?> classToLoad = classLoader.loadClass(mainClass);
Method method = classToLoad.getMethod("main", new Class[] { String[].class });
method.invoke(classToLoad.newInstance(), new Object[] { args });
jarInputStream.close();
}
}
| 1,683 | 0.733214 | 0.719548 | 57 | 28.526316 | 27.697048 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.877193 | false | false | 10 |
c1e94ac8d1e98d6cd078aff7755517a40ce0391d | 5,806,795,829,543 | 887f03e31dbbea80be14646c47dfcf010cc15612 | /src/main/java/student_alexander_fateev/lesson10/FindByIdUIAction.java | 6607a706508f21a0b1b13ae839068d1012d6ee4b | [] | no_license | javagurulv/ok_ru_admin_group_2 | https://github.com/javagurulv/ok_ru_admin_group_2 | 8137113dedfd9b72e8fdbca21a9a4088887db612 | 9fdb8ac22648da3be9e96689042b30f379df22fd | refs/heads/master | 2023-08-19T13:07:13.124000 | 2021-10-31T13:03:34 | 2021-10-31T13:03:34 | 372,749,341 | 0 | 3 | null | false | 2021-06-02T08:01:45 | 2021-06-01T08:02:43 | 2021-06-02T07:22:05 | 2021-06-02T08:01:44 | 42,141 | 0 | 3 | 0 | Java | false | false | package student_alexander_fateev.lesson10;
import java.util.Optional;
import java.util.Scanner;
class FindByIdUIAction implements UIAction {
private BookDatabase bookDatabase;
public FindByIdUIAction(BookDatabase bookDatabase) {
this.bookDatabase = bookDatabase;
}
public void execute() {
Scanner scan = new Scanner(System.in);
System.out.print("Input book ID: ");
long id = scan.nextLong();
Optional<Book> bookOpt = bookDatabase.findById(id);
if (bookOpt.isPresent()) {
System.out.println("Author: " + bookOpt.get().getAuthor());
System.out.println("Title: " + bookOpt.get().getTitle());
}
else {
System.out.println("No book with such ID found");
}
}
}
| UTF-8 | Java | 788 | java | FindByIdUIAction.java | Java | [
{
"context": "package student_alexander_fateev.lesson10;\n\nimport java.util.Optional;\nimpo",
"end": 25,
"score": 0.6039487719535828,
"start": 20,
"tag": "NAME",
"value": "ander"
},
{
"context": "package student_alexander_fateev.lesson10;\n\nimport java.util.Optional;\nimport java",... | null | [] | package student_alexander_fateev.lesson10;
import java.util.Optional;
import java.util.Scanner;
class FindByIdUIAction implements UIAction {
private BookDatabase bookDatabase;
public FindByIdUIAction(BookDatabase bookDatabase) {
this.bookDatabase = bookDatabase;
}
public void execute() {
Scanner scan = new Scanner(System.in);
System.out.print("Input book ID: ");
long id = scan.nextLong();
Optional<Book> bookOpt = bookDatabase.findById(id);
if (bookOpt.isPresent()) {
System.out.println("Author: " + bookOpt.get().getAuthor());
System.out.println("Title: " + bookOpt.get().getTitle());
}
else {
System.out.println("No book with such ID found");
}
}
}
| 788 | 0.625634 | 0.623096 | 28 | 27.142857 | 23.252825 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
c6fa56a7511cad97dcdac77d8868346e555153b9 | 11,570,641,951,057 | 8ef841ae3e50dbe8d12e7f578cbc403be32d67f2 | /backend/src/main/java/br/com/garug/placeholder/placeholder/PlaceholderApplication.java | 3456b5585bae13bcd09464aa155febf59266dd20 | [
"MIT"
] | permissive | garug/placeholder | https://github.com/garug/placeholder | 1ff40c04a526969c51488886a8fc1e173e793a82 | a432f179b2d64d5c09045a753d5b3c4ceb3bd351 | refs/heads/master | 2023-03-02T09:38:10.476000 | 2022-11-29T12:09:15 | 2022-11-29T12:09:15 | 217,421,700 | 0 | 0 | null | false | 2023-03-01T06:47:42 | 2019-10-25T00:56:14 | 2022-11-29T12:09:21 | 2023-03-01T06:47:37 | 2,943 | 0 | 0 | 33 | TypeScript | false | false | package br.com.garug.placeholder.placeholder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PlaceholderApplication {
public static void main(String[] args) {
SpringApplication.run(PlaceholderApplication.class, args);
}
}
| UTF-8 | Java | 339 | java | PlaceholderApplication.java | Java | [] | null | [] | package br.com.garug.placeholder.placeholder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PlaceholderApplication {
public static void main(String[] args) {
SpringApplication.run(PlaceholderApplication.class, args);
}
}
| 339 | 0.828909 | 0.828909 | 13 | 25.076923 | 24.981413 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 10 |
c565cc7ad26948fff40db7fb4012a999349b9314 | 506,806,150,613 | 836e3f88f3297a884b413b8d268d582404be40a6 | /src/Square.java | a6a1505d58e784143f9ef367b82911252dd1271d | [] | no_license | AlexMef/Lesson2 | https://github.com/AlexMef/Lesson2 | cf9c34d1c05a0c77b0d922c888f7150a289cc472 | 7e9a1dd34f059f77e07b92cbcdab89e9cbfa8fb7 | refs/heads/master | 2020-03-24T21:36:39.358000 | 2018-07-31T16:48:51 | 2018-07-31T16:48:51 | 143,041,717 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Square implements Shape{
private int sideLength;
public Square(int sideLength) {
this.sideLength = sideLength;
}
public int getSideLength() {
return sideLength;
}
public void setSideLength(int sideLength) {
this.sideLength = sideLength;
}
@Override
public void draw() {
System.out.println("Нарисован квадрат");
}
@Override
public double getPerimeter() {
return sideLength*4;
}
@Override
public double getArea() {
return Math.pow(sideLength, 2);
}
}
| UTF-8 | Java | 596 | java | Square.java | Java | [] | null | [] | public class Square implements Shape{
private int sideLength;
public Square(int sideLength) {
this.sideLength = sideLength;
}
public int getSideLength() {
return sideLength;
}
public void setSideLength(int sideLength) {
this.sideLength = sideLength;
}
@Override
public void draw() {
System.out.println("Нарисован квадрат");
}
@Override
public double getPerimeter() {
return sideLength*4;
}
@Override
public double getArea() {
return Math.pow(sideLength, 2);
}
}
| 596 | 0.608621 | 0.605172 | 30 | 18.333334 | 16.048538 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 10 |
2a3c2fe06ce09d920141e76f427c5038e074b19b | 29,721,173,742,669 | ef982cb173fb11886824fea1c9d4a4aaff3e2648 | /JavaFinalEj1/src/com/company/GuardaRopa.java | c693a69557a3320519298d9f46b6e2891928d0c2 | [] | no_license | rngarcia94/Bootcamp | https://github.com/rngarcia94/Bootcamp | 261de838a40b0770a87c45e9544a43c3ba206688 | 5cced68bd7dd31b6b13653f464fef9ad18e598e8 | refs/heads/main | 2023-04-04T03:56:01.520000 | 2021-04-20T13:30:12 | 2021-04-20T13:30:12 | 349,463,368 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GuardaRopa {
private int contador;
Map<Integer,Prenda> dicc = new HashMap<Integer,Prenda>();
public Integer guardarPrendas(List<Prenda> listaDePrenda){
//int[] arr = new int[listaDePrenda.size()];
int salida = 0;
for(int i = 0; i<listaDePrenda.size(); i++){
dicc.put(i,listaDePrenda.get(i));
contador++;
salida = i;
}
return salida;
}
public void mostrarPrendas(){
dicc.forEach((key, value) -> System.out.println(key + ": " + value));
}
public List<Prenda> devolverPrendas(Integer numero){
List<Prenda> res = new ArrayList<Prenda>();
res.add( dicc.get(numero));
dicc.remove(1);
return res;
}
}
| UTF-8 | Java | 881 | java | GuardaRopa.java | Java | [] | null | [] | package com.company;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GuardaRopa {
private int contador;
Map<Integer,Prenda> dicc = new HashMap<Integer,Prenda>();
public Integer guardarPrendas(List<Prenda> listaDePrenda){
//int[] arr = new int[listaDePrenda.size()];
int salida = 0;
for(int i = 0; i<listaDePrenda.size(); i++){
dicc.put(i,listaDePrenda.get(i));
contador++;
salida = i;
}
return salida;
}
public void mostrarPrendas(){
dicc.forEach((key, value) -> System.out.println(key + ": " + value));
}
public List<Prenda> devolverPrendas(Integer numero){
List<Prenda> res = new ArrayList<Prenda>();
res.add( dicc.get(numero));
dicc.remove(1);
return res;
}
}
| 881 | 0.598184 | 0.594779 | 34 | 24.911764 | 20.951439 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.