blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
3de81ae48a114658ea5fec488f436edc3f8b9af3
Java
AlbornozMilton/EjercicioCine
/src/ClasesCine/Sala.java
UTF-8
485
2.484375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ClasesCine; /** * * @author Milton */ public class Sala { private int numero; private int capacidad; //ctor public void Sala(int unNro, int unaCapacidad) { this.numero = unNro; this.capacidad = unaCapacidad; } }
true
c96063a759438d0e8ef9156bb025db2ef0dd7723
Java
vijayakanth89/Memcached-Java-Client
/test/src/cacheTest/cacheClient.java
UTF-8
876
2.15625
2
[]
no_license
package cacheTest; import com.meetup.memcached.SockIOPool; import com.meetup.memcached.MemcachedClient; //import java.util.*; public class cacheClient { public static void main(String[] args) { String[] servers = {"marketsimplified.com:11211"}; SockIOPool pool = SockIOPool.getInstance("BetaCache"); pool.setServers( servers ); pool.setFailover( true ); pool.setInitConn( 10 ); pool.setMinConn( 5 ); pool.setMaxConn( 250 ); pool.setMaintSleep( 30 ); pool.setNagle( false ); pool.setSocketTO( 3000 ); pool.setAliveCheck( true ); pool.initialize(); MemcachedClient mcc = new MemcachedClient("BetaCache"); System.out.println("add status:"+mcc.add("1", "Original")); System.out.println("Get from Cache:"+mcc.get("1")); } }
true
74b86acf26201318f0a720d8ae7008d6229335a5
Java
1003021685/DiaoH-master
/app/src/main/java/com/arcgis/mymap/Alert_dialogActivity.java
UTF-8
15,895
1.742188
2
[ "Apache-2.0" ]
permissive
package com.arcgis.mymap; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.arcgis.mymap.contacts.ContactDB; import com.arcgis.mymap.contacts.MyDatabaseHelper; import com.arcgis.mymap.contacts.NewProject; import com.arcgis.mymap.utils.GetTable; import com.arcgis.mymap.utils.LogUtils; import com.arcgis.mymap.utils.PinyinAPI; import com.arcgis.mymap.utils.ToastNotRepeat; import org.w3c.dom.ls.LSInput; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Administrator on 2018/1/31. */ public class Alert_dialogActivity extends Activity { public long i=1; public Button bt1,bt2; public EditText et,et2,et3; public ImageButton search; public ImageView imag,imag2; public String ut,pt,mla,atotitle,pposition; public Boolean hasfocus=true; public int p=-1; public int ap; private MyDatabaseHelper dbHelper; private SQLiteDatabase db; public String totitle=null; public List<NewProject> projects=new ArrayList<>(); public Cursor utc,ptc; public int number=0; private GridView gridView; public String[] titles= ContactDB.getStrings(); public Integer[] imager=ContactDB.getInters(); public String[] codes=ContactDB.getCodes(); private Intent intent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alert_dialogview); intViews(); Clicklistener clicklistener=new Clicklistener(); bt1.setOnClickListener(clicklistener); bt2.setOnClickListener(clicklistener); search.setOnClickListener(clicklistener); final PictureAdapter pictureAdapter=new PictureAdapter(titles,imager); gridView.setAdapter(pictureAdapter); setdrawable(); if (number!=0){ setEt(); } gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { imag.setImageResource(imager[position]); p=position; totitle=titles[p]; } }); } public void setdrawable(){ ptc=db.query("Newpoints"+pposition,new String[]{"classification"},null,null,null,null,null); if (ptc.moveToLast()){ pt=ptc.getString(ptc.getColumnIndex("classification")); } ptc.close(); if (pt!=null){ int index=printArray(titles,pt); imag.setImageResource(imager[index]); } } //遍历数组 public static int printArray(String [] array,String value){ for (int i=0;i<array.length;i++){ if(array[i].equals(value)){ return i; } } return 0;//当if条件不成立时,默认返回一个负数值-1 } public Integer[] getInteger(){ return imager; } public String[] getStrings(){ return titles; } public void setEt(){ //utc=db.rawQuery("select * from Newpoints0 where name like'[!R]'",null); utc=db.query("Newpoints"+pposition,null,"name != ? and name != ? and name != ? and name != ? and name != ? and name != ? and name != ?", new String[]{"H","Z","J","P","T","R","FY"},null,null,null); if (utc.moveToLast()){ ut=utc.getString(utc.getColumnIndex("name")); } utc.close(); if (ut==null){ ut="a0"; } if (isContainNumber(ut)){ int x=getInt(ut); ut=ut.replace(String.valueOf(x),String.valueOf(x+1)); et.setText(ut); }else { ut=ut+"1"; et.setText(ut); } } /** * 截取字符串 * @param str * @return */ public int getInt(String str){ String regEx="[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); int num=Integer.parseInt(m.replaceAll("").trim()); return num; } /** * 判断字符串中是否包含数字 */ public static boolean isContainNumber(String company) { Pattern p = Pattern.compile("[0-9]"); Matcher m = p.matcher(company); if (m.find()) { return true; } return false; } //初始化控件 private void intViews() { search= (ImageButton) findViewById(R.id.search); gridView= (GridView) findViewById(R.id.gridView); et = (EditText) findViewById(R.id.etext1); et2 = (EditText) findViewById(R.id.etext2); et3 = (EditText) findViewById(R.id.etext3); bt1 = (Button) findViewById(R.id.cancel); bt2 = (Button) findViewById(R.id.comfron); imag= (ImageView) findViewById(R.id.ig); imag2= (ImageView) findViewById(R.id.ib); dbHelper=new MyDatabaseHelper(this,"pointsStore.db",null,5); db=dbHelper.getWritableDatabase(); //获取表位置 GetTable getTable=new GetTable(); pposition=getTable.getTableposition(Alert_dialogActivity.this,db,dbHelper,projects); Cursor c=db.rawQuery("select*from Newpoints"+pposition,null); number=c.getCount(); intent=getIntent(); et2.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean Focus) { if (Focus){ gridView.setVisibility(View.GONE); imag.setVisibility(View.GONE); imag2.setVisibility(View.VISIBLE); et3.setText(""); hasfocus=true; et.setFocusableInTouchMode(true); } } }); et3.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean Focus) { if (Focus){ et2.setText(""); hasfocus=false; gridView.setVisibility(View.VISIBLE); imag.setVisibility(View.VISIBLE); imag.setImageResource(R.mipmap.white); imag2.setVisibility(View.GONE); } } }); } //给控件添加监听 private class Clicklistener implements View.OnClickListener { @Override public void onClick(View v) { switch(v.getId()){ case R.id.search: String text=et3.getText().toString(); List<String> Slist=new ArrayList<>(); List<Integer> Ilist=new ArrayList<>(); if (text!=""){ for (int i=0;i<titles.length;i++){ String ss= PinyinAPI.getPinYinHeadChar(titles[i]); if (ss.contains(text)){ Slist.add(titles[i]); Ilist.add(imager[i]); } } final String[] titlesh = Slist.toArray(new String[Slist.size()]); final Integer[] imagerh = Ilist.toArray(new Integer[Ilist.size()]); PictureAdapter pictureAdapter=new PictureAdapter(titlesh,imagerh); gridView.setAdapter(pictureAdapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { imag.setImageResource(imagerh[position]); p=position; totitle=titlesh[p]; } }); }else { PictureAdapter pictureAdapter=new PictureAdapter(titles,imager); gridView.setAdapter(pictureAdapter); } break; case R.id.cancel: finish(); break; case R.id.comfron: if (number!=0){ Cursor cla=db.query("Newpoints"+pposition,new String[]{"la"},null,null,null,null,null); if (cla.moveToLast()){ mla=cla.getString(cla.getColumnIndex("la")); } cla.close(); }else { mla=""; } if (hasfocus){ String la=intent.getStringExtra("jingdu"); String ln=intent.getStringExtra("weidu"); String high=intent.getStringExtra("gaodu"); String time=intent.getStringExtra("shijian"); String text2=et2.getText().toString(); Bundle bundle =new Bundle(); bundle.putString("second",text2); bundle.putString("time",time); intent.putExtras(bundle); setResult(RESULT_OK,intent); if (mla.equals(la)){ ToastNotRepeat.show(Alert_dialogActivity.this,"请确认坐标点是否已添加!"); }else if (TextUtils.isEmpty(text2)){ ToastNotRepeat.show(Alert_dialogActivity.this,"请确认通用点类别!"); }else { ContentValues values=new ContentValues(); values.put("name",et.getText().toString()); values.put("la",la); values.put("ln",ln); values.put("high",high); values.put("time",time); values.put("code","null"); values.put("classification",text2); db.insert("Newpoints"+pposition,null,values); values.clear(); ToastNotRepeat.show(Alert_dialogActivity.this,"添加成功"); finish(); } }else { if (intent!=null){ String la=intent.getStringExtra("jingdu"); String ln=intent.getStringExtra("weidu"); String high=intent.getStringExtra("gaodu"); String time=intent.getStringExtra("shijian"); atotitle=intent.getStringExtra("xiabiao"); Bundle bundle =new Bundle(); if (totitle!=null){ bundle.putString("second",totitle); bundle.putString("time",time); intent.putExtras(bundle); setResult(RESULT_OK,intent); if (mla.equals(la)){ ToastNotRepeat.show(Alert_dialogActivity.this,"请确认坐标点是否已添加"); }else { for (int k=0;k<titles.length;k++){ if (titles[k].equals(totitle)){ ap=k; } } ContentValues values=new ContentValues(); values.put("name",et.getText().toString()); values.put("la",la); values.put("ln",ln); values.put("high",high); values.put("time",time); values.put("classification",totitle); values.put("code",codes[ap]); db.insert("Newpoints"+pposition,null,values); values.clear(); Intent i=new Intent("com.arcgis.broadcasttest"); sendBroadcast(i); ToastNotRepeat.show(Alert_dialogActivity.this,"添加成功"); finish(); } }else { ToastNotRepeat.show(Alert_dialogActivity.this,"请选择标记点!"); } } } break; } } } //gridView配置Adapter public class PictureAdapter extends BaseAdapter { private List<Pictrue> pictures=new ArrayList<Pictrue>(); public PictureAdapter(String[] titles,Integer[] images){ super(); for (int i=0;i<images.length;i++){ Pictrue picture=new Pictrue(titles[i],images[i]); pictures.add(picture); } } @Override public int getCount() { return pictures.size(); } @Override public Object getItem(int position) { return pictures.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView==null){ viewHolder=new ViewHolder(); // 获得容器 convertView= LayoutInflater.from(Alert_dialogActivity.this).inflate(R.layout.bitmapitem,null); // 初始化组件 viewHolder.image= (ImageView) convertView.findViewById(R.id.gtimage); viewHolder.title = (TextView) convertView.findViewById(R.id.tv); // 给converHolder附加一个对象 convertView.setTag(viewHolder); }else { // 取得converHolder附加的对象 viewHolder = (ViewHolder) convertView.getTag(); } // 给组件设置资源 Pictrue pictrue=pictures.get(position); viewHolder.image.setImageResource(pictrue.getImageId()); viewHolder.title.setText(pictrue.getTitled()); return convertView; } } class ViewHolder{ public TextView title; public ImageView image; } class Pictrue{ private String titled; private int imageId; public Pictrue(String title,Integer imageId){ this.imageId=imageId; this.titled = title; } public int getImageId() { return imageId; } public String getTitled() { return titled; } } }
true
f52134a72592a1521bf9c8e4957b5e743135dbda
Java
wuguangxue/hbase
/src/main/java/com/bboniao/asynchbase/GetReq.java
UTF-8
1,023
2.328125
2
[]
no_license
package com.bboniao.asynchbase; import java.util.Map; import java.util.NavigableSet; /** * Created by bboniao on 11/19/14. */ public class GetReq { private byte[] row; private boolean cacheBlocks; private int maxVersions = 1; private Map<byte[], NavigableSet<byte[]>> families; public GetReq(byte[] row) { this.row = row; } public boolean hasFamilies() { return families != null && !families.isEmpty(); } public Map<byte[], NavigableSet<byte[]>> getFamilyMap() { return families; } public int getMaxVersions() { return maxVersions; } public void setMaxVersions(int maxVersions) { this.maxVersions = maxVersions; } public boolean getCacheBlocks() { return cacheBlocks; } public void setCacheBlocks(boolean cacheBlocks) { this.cacheBlocks = cacheBlocks; } public byte[] getRow() { return row; } public void setRow(byte[] row) { this.row = row; } }
true
9945c48e4716d07f6949d29dc0d42fc4240e2a6e
Java
sjg2020/COMP2000_2020
/src/Actor.java
UTF-8
165
1.890625
2
[]
no_license
import java.awt.*; import java.util.ArrayList; public interface Actor { public void paint(Graphics g); ArrayList<Polygon> Jkss = new ArrayList<Polygon>(20); }
true
b07f1c4beb16923ad862578f396eae8d4591f6de
Java
davidnewcomb/cfgen4j
/src/main/java/uk/co/bigsoft/apps/cfgen4j/gen/files/CfGen4jExceptionGenerator.java
UTF-8
1,815
2.28125
2
[ "MIT" ]
permissive
package uk.co.bigsoft.apps.cfgen4j.gen.files; import java.io.IOException; import javax.lang.model.element.Modifier; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeSpec.Builder; import uk.co.bigsoft.apps.cfgen4j.gen.JavaFileFactory; import uk.co.bigsoft.apps.cfgen4j.gen.JavaFileHandler; import uk.co.bigsoft.apps.cfgen4j.gen.PoetFactory; public class CfGen4jExceptionGenerator implements CfGen4jFileGenerator { private JavaFileFactory javaFileFactory = new JavaFileFactory(); private PoetFactory poetFactory = new PoetFactory(); public CfGen4jExceptionGenerator() { } @Override public void save(JavaFileHandler fileHandler, String packageName, String folder) throws IOException { TypeSpec type = init(); JavaFile javaFile = javaFileFactory.create(packageName, type); fileHandler.write(javaFile, folder); } private TypeSpec init() { CodeBlock body = CodeBlock.builder() // .addStatement("super(x)") // .build(); MethodSpec constructor1 = poetFactory.constructor(body, ClassName.get(Throwable.class), "x"); MethodSpec constructor2 = poetFactory.constructor(body, ClassName.get(String.class), "x"); FieldSpec serialVersionUIDField = FieldSpec .builder(TypeName.LONG, "serialVersionUID", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("-1").build(); Builder klaus = TypeSpec.classBuilder("CfGen4jException") // .superclass(RuntimeException.class) // .addField(serialVersionUIDField) // .addMethod(constructor1) // .addMethod(constructor2); return klaus.build(); } }
true
e2310ae900aa8fa7e6e026f14b94da258c17b072
Java
Lizhny/coding2017
/group26/89460886/src/week05/source/constant/NameAndTypeInfo.java
UTF-8
1,103
2.75
3
[]
no_license
package jvm.constant; /** * @author jiaxun */ public class NameAndTypeInfo extends ConstantInfo { public int tag = ConstantInfo.NAME_AND_TYPE_INFO; private int index1; private int index2; public NameAndTypeInfo(ConstantPool pool) { super(pool); } public int getIndex1() { return index1; } public void setIndex1(int index1) { this.index1 = index1; } public int getIndex2() { return index2; } public void setIndex2(int index2) { this.index2 = index2; } public int getTag() { return tag; } public String getName() { ConstantPool pool = this.getConstantPool(); UTF8Info utf8Info1 = (UTF8Info) pool.getConstantInfo(index1); return utf8Info1.getBytes(); } public String getTypeInfo() { ConstantPool pool = this.getConstantPool(); UTF8Info utf8Info2 = (UTF8Info) pool.getConstantInfo(index2); return utf8Info2.getBytes(); } public String toString() { return "(" + getName() + "," + getTypeInfo() + ")"; } }
true
2df6beddf26db8c3d8c9ac5e6acd30c1b4d530ce
Java
BartekSmalec/squashapp
/src/main/java/io/squashapp/squashapp/resource/UserResource.java
UTF-8
3,426
2.453125
2
[]
no_license
package io.squashapp.squashapp.resource; import io.squashapp.squashapp.repository.UserRepository; import io.squashapp.squashapp.models.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.net.URISyntaxException; import java.security.Principal; import java.util.Optional; @CrossOrigin(origins = "http://localhost:4500", maxAge = 3600) @RestController @RequestMapping("/users") public class UserResource { @Autowired UserRepository userRepository; @Autowired PasswordEncoder passwordEncoder; Logger logger = LoggerFactory.getLogger(UserResource.class); @PostMapping("/register") public ResponseEntity<User> create(@RequestBody User user) { User createdUser; if (userRepository.findByUserName(user.getUserName()).isPresent()) { return ResponseEntity.badRequest().build(); } else { user.setPassword(passwordEncoder.encode(user.getPassword())); user.setActive(true); user.setRoles("ROLE_USER"); createdUser = userRepository.save(user); } if (createdUser == null) { return ResponseEntity.notFound().build(); } else { URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/getUsers/{id}") .buildAndExpand(createdUser.getId()) .toUri(); return ResponseEntity.created(uri) .body(createdUser); } } @GetMapping("/getUsers/{id}") public ResponseEntity<User> read(@PathVariable("id") String id) { Optional<User> foundUser = userRepository.findById(Long.valueOf(id)); if (!foundUser.isPresent()) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(foundUser.get()); } } @GetMapping("/getUsers") public ResponseEntity<Iterable<User>> read() { Optional<Iterable<User>> foundUsers = Optional.of(userRepository.findAll()); if (!foundUsers.isPresent()) { return ResponseEntity.notFound().build(); } else { return ResponseEntity.ok(foundUsers.get()); } } @PostMapping("/update") public ResponseEntity<User> update(@RequestBody User user) throws URISyntaxException { Optional<User> foundUser = userRepository.findById(Long.valueOf(user.getId())); if (!foundUser.isPresent()) { return ResponseEntity.notFound().build(); } else { User createdUser = userRepository.save(user); URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/getUsers/{id}") .buildAndExpand(createdUser.getId()) .toUri(); return ResponseEntity.created(uri) .body(createdUser); } } @GetMapping("/currentUser") public User getCurrentUser(Principal principal) { Optional<User> user = userRepository.findByUserName(principal.getName()); return user.get(); } }
true
2f57e07ab4dbe642d3af3b5992da4ebc5453d7da
Java
marekventur/myHome
/src/de/wi08e/myhome/nodeplugins/camerasimulator/JuliaGenerator.java
UTF-8
1,731
2.671875
3
[]
no_license
package de.wi08e.myhome.nodeplugins.camerasimulator; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.Random; public class JuliaGenerator { private double reC, imC; private Random random = new Random(); public int checkZo(double reZ_minus1,double imZ_minus1) { double reZ,imZ; int i; for (i=0;i<47;i++) { imZ=2*reZ_minus1*imZ_minus1+imC; reZ=reZ_minus1*reZ_minus1-imZ_minus1*imZ_minus1+reC; if (reZ*reZ+imZ*imZ>4) return i; reZ_minus1=reZ; imZ_minus1=imZ; } return i; } public Image generate() { BufferedImage result = new BufferedImage ( 300, 300, BufferedImage.TYPE_INT_RGB ); Graphics2D gp = result.createGraphics(); Color c = new Color(random.nextInt(200)+50,random.nextInt(200)+50,random.nextInt(200)+50); gp.setColor(c); gp.setBackground(c); gp.fillRect(0, 0, 300, 300); double reZo, imZo, zelle=0.0065; int x,y; Color colJulia = new Color(random.nextInt(200),random.nextInt(200),random.nextInt(200)); reC = -0.65175; imC = 0.41850; reC = -0.65175-random.nextFloat()*0.1; imC = 0.41850-random.nextFloat()*0.1; imZo=-0.96; for (y=0;y<300;y++) { reZo=-1.5; for (x=0;x<300;x++) { if (checkZo(reZo,imZo)==47) { gp.setColor(colJulia); gp.drawLine(x,y,x,y); } reZo=reZo+zelle; } imZo=imZo+zelle; } gp.dispose(); return result; } }
true
04d68eb67166e7fc00b369b09942805092e80135
Java
green-fox-academy/pingithefrosty
/week8/day2/heroku-todo/src/main/java/com/greenfoxacademy/sqlspringpractice/collections/Types.java
UTF-8
364
2.484375
2
[]
no_license
package com.greenfoxacademy.sqlspringpractice.collections; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class Types { private List<String> todoTypes; public Types() { todoTypes = Arrays.asList("Work", "Fun"); } public List<String> getTodoTypes() { return todoTypes; } }
true
32cb8198dcd25f480e5d13f98cb5c150e949db77
Java
knmsk/java-test-stock-quote-manager
/src/main/java/com/stock/stockquotemanager/repository/entity/Quote.java
UTF-8
637
2.421875
2
[]
no_license
package com.stock.stockquotemanager.repository.entity; import javax.persistence.Embeddable; import javax.persistence.Table; @Embeddable @Table(name="quotes") public class Quote { private String date; private String price; public Quote() { } public Quote(String date, String price) { this.date = date; this.price = price; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }
true
6c9611703dbd76447c7a8f1cad2ff039bc2b230a
Java
Li-amK/School-Chemie-App
/sources/androidx/lifecycle/Transformations.java
UTF-8
2,109
2.171875
2
[ "Unlicense" ]
permissive
package androidx.lifecycle; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.arch.core.util.Function; /* loaded from: classes.dex */ public class Transformations { private Transformations() { } @MainThread public static <X, Y> LiveData<Y> map(@NonNull LiveData<X> source, @NonNull final Function<X, Y> mapFunction) { final MediatorLiveData<Y> result = new MediatorLiveData<>(); result.addSource(source, new Observer<X>() { // from class: androidx.lifecycle.Transformations.1 @Override // androidx.lifecycle.Observer public void onChanged(@Nullable X x) { MediatorLiveData.this.setValue(mapFunction.apply(x)); } }); return result; } @MainThread public static <X, Y> LiveData<Y> switchMap(@NonNull LiveData<X> source, @NonNull final Function<X, LiveData<Y>> switchMapFunction) { final MediatorLiveData<Y> result = new MediatorLiveData<>(); result.addSource(source, new Observer<X>() { // from class: androidx.lifecycle.Transformations.2 LiveData<Y> mSource; @Override // androidx.lifecycle.Observer public void onChanged(@Nullable X x) { LiveData<Y> newLiveData = (LiveData) Function.this.apply(x); if (this.mSource != newLiveData) { if (this.mSource != null) { result.removeSource(this.mSource); } this.mSource = newLiveData; if (this.mSource != null) { result.addSource(this.mSource, new Observer<Y>() { // from class: androidx.lifecycle.Transformations.2.1 @Override // androidx.lifecycle.Observer public void onChanged(@Nullable Y y) { result.setValue(y); } }); } } } }); return result; } }
true
6dc90b46b51857945caad2f6edd22a29a618bebb
Java
me-dalii/municipalite-project
/src/main/java/org/fsb/municipalite/controllers/AutorisationPageController.java
UTF-8
15,636
2.15625
2
[]
no_license
package org.fsb.municipalite.controllers; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.DialogPane; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.fsb.municipalite.entities.Autorisation; import org.fsb.municipalite.services.impl.AutorisationServiceImpl; import java.net.URL; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; public class AutorisationPageController implements Initializable{ @FXML TextField searchBox; @FXML TableView<Autorisation> tableView; @FXML TableColumn<Autorisation, Long> Id; @FXML TableColumn<Autorisation, LocalDateTime> Date; @FXML TableColumn<Autorisation, Autorisation.Etat> Status; @FXML TableColumn<Autorisation, String> Name; @FXML TableColumn<Autorisation, String> Subject; @FXML TableColumn<Autorisation, Long> Cin; public ObservableList<Autorisation> data; private double xOffset = 0; private double yOffset = 0; @Override public void initialize(URL location, ResourceBundle resources) { tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); Id.setCellValueFactory(new PropertyValueFactory<Autorisation,Long>("id")); Date.setCellValueFactory(new PropertyValueFactory<Autorisation,LocalDateTime >("DateAutorisation")); Status.setCellValueFactory(new PropertyValueFactory<Autorisation,Autorisation.Etat>("etat")); Name.setCellValueFactory(new PropertyValueFactory<Autorisation,String>("nomCitoyen")); Cin.setCellValueFactory(new PropertyValueFactory<Autorisation,Long>("cin")); Subject.setCellValueFactory(new PropertyValueFactory<Autorisation, String>("sujet")); AutorisationServiceImpl autorisationService =new AutorisationServiceImpl(); List<Autorisation> list = autorisationService.selectAll(); data = FXCollections.observableArrayList(); for (Autorisation a : list) { data.addAll(a); } tableView.setItems(data); searchBox.textProperty().addListener((observable, oldValue, newValue) -> { ListenerSearch(newValue); }); tableView.setRowFactory( tv -> { TableRow<Autorisation> row = new TableRow<>(); row.setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (! row.isEmpty()) && event.getButton().equals(MouseButton.PRIMARY) ) { Autorisation rowData = row.getItem(); message(rowData); } if ((row.isEmpty()) && event.getButton().equals(MouseButton.PRIMARY) ) this.tableView.getSelectionModel().clearSelection(); }); return row ; }); } public void ListenerSearch(String n){ AutorisationServiceImpl autorisationService =new AutorisationServiceImpl(); data = FXCollections.observableArrayList(); List<Autorisation> list; if (!(n.equals(""))) { if (isNumeric(n)) { list = autorisationService.selectLike("id", n ); for (Autorisation p : list) { data.add(p); } } else { list =autorisationService.selectLike("nomCitoyen", "'" + n + "%'"); for (Autorisation p : list) { data.add(p); } } tableView.setItems(data); } else { list = autorisationService.selectAll(); for (Autorisation p : list) { data.add(p); } tableView.setItems(data); } } @FXML public void reload(ActionEvent event){ tableView.getItems().clear(); AutorisationServiceImpl autorisationService =new AutorisationServiceImpl(); List<Autorisation> list = autorisationService.selectAll(); data = FXCollections.observableArrayList(); for (Autorisation m : list) { data.add(m); } tableView.setItems(data); } public void onClickEventAdd(ActionEvent event) { try { FXMLLoader f = new FXMLLoader(); f.setLocation(getClass().getResource("/interfaces/AutorisationAddPage.fxml")); Pane autoDialogPane = f.load(); AutorisationDialogController edc = f.getController(); Dialog<ButtonType> d = new Dialog<>(); //this is just for adding an icon to the dialog pane Stage stage = (Stage) d.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("/assets/img/icon.png")); d.setDialogPane((DialogPane) autoDialogPane); d.setTitle("Add Authorization"); d.setResizable(false); d.initStyle(StageStyle.UNDECORATED); //these two are for moving the window with the mouse autoDialogPane.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { xOffset = event.getSceneX(); yOffset = event.getSceneY(); } }); autoDialogPane.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { d.setX(event.getScreenX() - xOffset); d.setY(event.getScreenY() - yOffset); } }); //name field listener edc.name.textProperty().addListener((observable, oldValue, newValue) -> { if(!isAlpha(newValue)) { edc.labName.setVisible(true); }else edc.labName.setVisible(false); }); //cin field listener edc.cin.textProperty().addListener((observable, oldValue, newValue) -> { if(isNumeric(newValue) && newValue.length() == 8 && !newValue.matches("00000000")) { edc.labCin.setVisible(false); }else edc.labCin.setVisible(true); }); edc.msg.textProperty().addListener((observable, oldValue, newValue) -> { edc.msgLength.setText(newValue.length()+"/3000"); if(newValue.length()>3000 || newValue.length() == 0) { edc.labMsg.setVisible(true); }else edc.labMsg.setVisible(false); }); //subject listener edc.subject.textProperty().addListener((observable, oldValue, newValue) -> { if(newValue.length() > 255) { edc.labSubject.setVisible(true); }else edc.labSubject.setVisible(false); }); d.getDialogPane().lookupButton(ButtonType.APPLY).getStyleClass().add("dialogButtons"); d.getDialogPane().lookupButton(ButtonType.CANCEL).getStyleClass().add("dialogButtons"); d.getDialogPane().lookupButton(ButtonType.APPLY).disableProperty().bind(Bindings.createBooleanBinding(() -> edc.name.getText().isEmpty() || edc.cin.getText().isEmpty() || edc.cin.getText().matches("00000000") || edc.cin.getText().length() != 8||!isNumeric(edc.cin.getText())|| edc.subject.getText().length() >255||edc.msg.getText().isEmpty()|| edc.msg.getText().length()>3000 || edc.subject.getText().isEmpty()|| !isAlpha(edc.name.getText()), edc.name.textProperty(),edc.cin.textProperty(),edc.subject.textProperty(), edc.msg.textProperty())); Optional<ButtonType> clickedButton = d.showAndWait(); //new Autorisation creation and addition if (clickedButton.get() == ButtonType.APPLY) { Autorisation a = new Autorisation(); a.setNomCitoyen(edc.name.getText()); a.setCin(Long.parseLong(edc.cin.getText())); a.setSujet(edc.subject.getText()); a.setMsg(edc.msg.getText()); if (edc.processed.isSelected()) { a.setEtat(Autorisation.Etat.processed); } if (edc.unprocessed.isSelected()) { a.setEtat(Autorisation.Etat.unprocessed); } AutorisationServiceImpl autorisationService = new AutorisationServiceImpl(); autorisationService.create(a); System.out.println("Authorization ADDED !"); reload(event); } } catch (Exception e) { e.printStackTrace(); } } @FXML public void UpdateAutorisation(ActionEvent event) { try { FXMLLoader f = new FXMLLoader(); f.setLocation(getClass().getResource("/interfaces/AutorisationAddPage.fxml")); Pane autorisationDialogPane = f.load(); AutorisationDialogController edc = f.getController(); if(tableView.getSelectionModel().getSelectedItem() != null) { AutorisationServiceImpl autorisationService = new AutorisationServiceImpl(); Autorisation c = tableView.getSelectionModel().getSelectedItem(); Autorisation test = autorisationService.getById(c.getId()); edc.setAutorisationDialogPane(test); Dialog<ButtonType> d = new Dialog<>(); Stage stage = (Stage) d.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("/assets/img/icon.png")); edc.titleLabel.setText("Update Authorization"); d.setDialogPane((DialogPane) autorisationDialogPane); d.setTitle("Update Authorization"); d.setResizable(false); d.initStyle(StageStyle.UNDECORATED); autorisationDialogPane.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { xOffset = event.getSceneX(); yOffset = event.getSceneY(); } }); autorisationDialogPane.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { d.setX(event.getScreenX() - xOffset); d.setY(event.getScreenY() - yOffset); } }); edc.name.textProperty().addListener((observable, oldValue, newValue) -> { if(!isAlpha(newValue)) { edc.labName.setVisible(true); }else edc.labName.setVisible(false); }); //cin field listener edc.cin.textProperty().addListener((observable, oldValue, newValue) -> { if(isNumeric(newValue) && newValue.length() == 8 && !newValue.matches("00000000")) { edc.labCin.setVisible(false); }else edc.labCin.setVisible(true); }); //subject listener edc.subject.textProperty().addListener((observable, oldValue, newValue) -> { if(!isAlpha(newValue)) { edc.labSubject.setVisible(true); }else edc.labSubject.setVisible(false); }); //message Listener edc.msg.textProperty().addListener((observable, oldValue, newValue) -> { edc.msgLength.setText(newValue.length()+"/3000"); if(newValue.length()>3000) { edc.labMsg.setVisible(true); }else edc.labMsg.setVisible(false); }); d.getDialogPane().lookupButton(ButtonType.APPLY).getStyleClass().add("dialogButtons"); d.getDialogPane().lookupButton(ButtonType.CANCEL).getStyleClass().add("dialogButtons"); //make name field first to be selected //apply button binder d.getDialogPane().lookupButton(ButtonType.APPLY).disableProperty().bind(Bindings.createBooleanBinding(() -> edc.name.getText().isEmpty() || edc.cin.getText().isEmpty()|| edc.cin.getText().length() != 8|| edc.cin.getText().matches("00000000") || !isNumeric(edc.cin.getText())|| edc.subject.getText().length() >255||edc.msg.getText().isEmpty()|| edc.msg.getText().length()>3000 || edc.subject.getText().isEmpty()|| !isAlpha(edc.name.getText()), edc.name.textProperty(),edc.cin.textProperty(),edc.subject.textProperty(), edc.msg.textProperty())); Optional<ButtonType> clickedButton = d.showAndWait(); if(clickedButton.get() == ButtonType.APPLY) { edc.getCurrentAutorisation(test); System.out.println(test); autorisationService.update(test); reload(event); } } }catch(Exception e) { e.printStackTrace(); } } public void onClickEventRemove(ActionEvent event) { if (tableView.getSelectionModel().getSelectedItem() != null) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("/assets/img/icon.png")); alert.setTitle("Delete Authorization ?"); alert.setHeaderText(null); alert.setContentText("Are you Sure You Want to Delete Selected Authorization(s) ?"); Optional <ButtonType> action = alert.showAndWait(); if(action.get() == ButtonType.OK) { ObservableList<Autorisation> selectedAutorisationList = tableView.getSelectionModel().getSelectedItems(); for(Autorisation c : selectedAutorisationList) { AutorisationServiceImpl cService = new AutorisationServiceImpl(); cService.remove(c.getId()); } reload(event); } } } public void message(Autorisation autorisation) { try { FXMLLoader f = new FXMLLoader(); f.setLocation(getClass().getResource("/interfaces/AutorisationMsg.fxml")); Pane AutorisationDialogPane = f.load(); AutorisationMsgController edc = f.getController(); AutorisationServiceImpl autorisationService = new AutorisationServiceImpl(); Autorisation auto = autorisationService.getById(autorisation.getId()); edc.title.setText(edc.title.getText()+" "+ auto.getId()); edc.setAutorisationMsgDialogPane(auto); Dialog<ButtonType> d = new Dialog<>(); Stage stage = (Stage) d.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("/assets/img/icon.png")); d.setDialogPane((DialogPane) AutorisationDialogPane); d.setTitle("Authorization"); d.initStyle(StageStyle.UNDECORATED); AutorisationDialogPane.setOnMousePressed(event -> { xOffset = event.getSceneX(); yOffset = event.getSceneY(); }); AutorisationDialogPane.setOnMouseDragged(event -> { d.setX(event.getScreenX() - xOffset); d.setY(event.getScreenY() - yOffset); }); d.getDialogPane().lookupButton(ButtonType.CLOSE).getStyleClass().add("dialogButtons"); d.showAndWait(); } catch (Exception e) { e.printStackTrace(); } } @FXML void selectAll(ActionEvent event) { this.tableView.getSelectionModel().selectAll(); } //the String contain just numbers public boolean isNumeric(String str) { try { Long.parseLong(str); return true; } catch(NumberFormatException e){ return false; } } //the string should contain just character for a to z and A to Z public boolean isAlpha(String name) { return name.matches("[a-zA-Z' ']+"); } //you can write a string with a alphabetic \n character and numbers public boolean isAlphaE(String name) { return name.matches("[a-zA-Z 0-9]+[a-zA-Z .',0-9\n' ']*"); } }
true
46a81e90f7dfb1ca8431bcb3214d73d4939660fe
Java
oweson/java--basic
/java/src/pig/daoyun/ArrayTest.java
UTF-8
430
2.609375
3
[]
no_license
package pig.daoyun; /** * the class is create by @Author:oweson * * @Date:2019/3/20 0020 8:48 */ public class ArrayTest { // 构造函数可以修饰符不同; ArrayTest() { } private ArrayTest(int a) { } public static void main(String[] args) { // 数组的局部或者成员变量都会初始化默认值; int[] arr = new int[10]; System.out.println(arr[0]); } }
true
aea4ccfdd3707b8421d1a8fc7fd6f7c8adcd49c3
Java
AyozeVera/MoneyCalc
/src/MoneyCalculator/model/Number.java
UTF-8
2,694
3.625
4
[]
no_license
package MoneyCalculator.model; public class Number { private long numerator; private long denominator; public Number(long numerator, long denominator) { this.numerator = numerator; this.denominator = denominator; reduce(); } public Number(Number number) { this(number.numerator, number.denominator); } public Number(long number) { this(number, 1); } public Number(int number) { this(number, 1); } public Number parseNumber(String string){ return new Number(Double.parseDouble(string)); } public Number(double number) { this.numerator = (long) number; this.denominator = 1; while (number != numerator) { number *= 10; denominator *= 10; numerator = (long) number; } } private int[] getPrimeNumbers() { return new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23}; } private boolean isDivisible(int number) { return ((numerator % number == 0) && (denominator % denominator == 0)); } private void reduce() { int[] primeNumbers = getPrimeNumbers(); for (int number : primeNumbers) { if (numerator < number) break; if (denominator < number) break; while (isDivisible(number)) { numerator /= number; denominator /= number; } } } public Number add(Number num) { Number number = new Number(num); this.reduce(); num.reduce(); if (denominator != num.denominator) { number.denominator = denominator * num.denominator; number.numerator = (numerator * num.denominator) + (num.numerator * denominator); number.reduce(); return number; } else { number.denominator = num.denominator; number.numerator = num.numerator + numerator; number.reduce(); return number; } } public Number multiply (Number num){ Number number = new Number(num.numerator*numerator, num.denominator*denominator); number.reduce(); return number; } @Override public boolean equals(Object object) { if (object == null) return false; if (!(object instanceof Number)) return false; return equals((Number) object); } private boolean equals(Number number) { return (number.numerator) == numerator; } @Override public String toString (){ return numerator + " / " + denominator; } }
true
90a90747c746a06e640b205339a24cbc97da1639
Java
hhu-propra2-2019/abschlussprojekt-big_f_for_auas
/src/main/java/mops/infrastructure/config/GroupSyncConfig.java
UTF-8
1,581
2.1875
2
[]
no_license
package mops.infrastructure.config; import lombok.NoArgsConstructor; import mops.domain.repositories.GroupRepository; import mops.infrastructure.groupsync.GroupSyncService; import mops.infrastructure.groupsync.GroupSyncValidator; import mops.infrastructure.groupsync.GroupSyncWebclient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableScheduling @NoArgsConstructor public class GroupSyncConfig { /** * Hier konfigurieren wir, dass der GroupSyncService nur erstellt wird, wenn das in der application.properties * eingestellt ist. * @param webclient Der Webclient, der die Anfrage an das SCS stellt * @param validator Die Komponente, die das von webclient zurückgegebene Dto validiert * @param groupRepository Das Repository, in das die Gruppen synchronisiert werden sollen * @return der Service, der die Gruppen synchronisiert. */ @Autowired @Bean @ConditionalOnProperty(value = "mops.gruppen2.sync.enabled", havingValue = "true") public GroupSyncService syncService(GroupSyncWebclient webclient, GroupSyncValidator validator, GroupRepository groupRepository) { return new GroupSyncService(webclient, validator, groupRepository); } }
true
095113b883bc3d5babb9f0e9d32e5ee7143f0653
Java
konglinghai123/his
/his-statistics/src/main/java/cn/honry/statistics/bi/outpatient/outpatientPassengers/vo/DimensionVO.java
UTF-8
2,401
2.328125
2
[]
no_license
package cn.honry.statistics.bi.outpatient.outpatientPassengers.vo; //门诊人次统计 VO public class DimensionVO { /**总人次**/ private Integer sumPeople; /**急诊人次**/ private Integer emerGencyPeople; /**普诊人次**/ private Integer ordinaryPeople; /**年度**/ private String years; /**科室**/ private String dept; /**地域**/ private String region; /**开始时间**/ private Integer start; /**结束时间**/ private Integer end; /**性别**/ private String sex; /**统计大类**/ private String codeName; /**比例**/ private String sumtotcosts; /**年龄**/ private String age; /**年龄单位**/ private String ageUnit; public String getSumtotcosts() { return sumtotcosts; } public void setSumtotcosts(String sumtotcosts) { this.sumtotcosts = sumtotcosts; } public String getCodeName() { return codeName; } public void setCodeName(String codeName) { this.codeName = codeName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getSumPeople() { return sumPeople; } public void setSumPeople(Integer sumPeople) { this.sumPeople = sumPeople; } public Integer getEmerGencyPeople() { return emerGencyPeople; } public void setEmerGencyPeople(Integer emerGencyPeople) { this.emerGencyPeople = emerGencyPeople; } public Integer getOrdinaryPeople() { return ordinaryPeople; } public void setOrdinaryPeople(Integer ordinaryPeople) { this.ordinaryPeople = ordinaryPeople; } public String getYears() { return years; } public void setYears(String years) { this.years = years; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Integer getStart() { return start; } public void setStart(Integer start) { this.start = start; } public Integer getEnd() { return end; } public void setEnd(Integer end) { this.end = end; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAgeUnit() { return ageUnit; } public void setAgeUnit(String ageUnit) { this.ageUnit = ageUnit; } }
true
efc5dea34d22e36782be2728380e5c7d44063ff3
Java
WXRain/GameCommunity
/src/main/java/com/rain/gameCommunity/entity/ShoppingCartEntity.java
UTF-8
1,918
2.3125
2
[]
no_license
package com.rain.gameCommunity.entity; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.stereotype.Repository; /** * * @author wangxinyu * */ @Repository public class ShoppingCartEntity implements Serializable { //购物车id private long id; //用户id private long userId; //购物车中的游戏 private String gameIds; //创建时间 private Date createTime; private String createTimeString; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public ShoppingCartEntity(long id, long userId, String gameIds, Date createTime, String createTimeString, SimpleDateFormat sdf) { super(); this.id = id; this.userId = userId; this.gameIds = gameIds; this.createTime = createTime; this.createTimeString = createTimeString; this.sdf = sdf; } public ShoppingCartEntity() { } @Override public String toString() { return "ShoppingCartEntity [id=" + id + ", userId=" + userId + ", gameIds=" + gameIds + ", createTime=" + createTime + ", createTimeString=" + createTimeString + ", sdf=" + sdf + "]"; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getGameIds() { return gameIds; } public void setGameIds(String gameIds) { this.gameIds = gameIds; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateTimeString() { return createTimeString; } public void setCreateTimeString(String createTimeString) { this.createTimeString = createTimeString; } public SimpleDateFormat getSdf() { return sdf; } public void setSdf(SimpleDateFormat sdf) { this.sdf = sdf; } }
true
6dfbc75d9d1866fd07bf39f0d28b5b917537d689
Java
snehalpande216/FromHome
/src/com/awtandevents/Label2.java
UTF-8
1,648
3.09375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.awtandevents; import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Admin */ public class Label2 { public static void main(String[] args) { Frame f2 = new Frame("Label With Action"); Button b = new Button("Find IP"); TextField tf = new TextField(30); Label l3 = new Label(); l3.setVisible(true); f2.add(tf); f2.add(l3); f2.add(b); f2.setLayout(new FlowLayout()); f2.setSize(500, 500); f2.setVisible(true); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String host = tf.getText(); String IP = java.net.InetAddress.getByName(host).getHostAddress(); l3.setText("IP of : " + host + " is : " + IP); } catch (UnknownHostException ex) { Logger.getLogger(Label2.class.getName()).log(Level.SEVERE, null, ex); } } }); } }
true
37e2c24ed6051b770be64bee8887a5132385e22c
Java
azanoviv02/HermesWeb
/src/main/java/com/hermes/core/domain/hauls/BasicHaul.java
UTF-8
281
1.773438
2
[]
no_license
package com.hermes.core.domain.hauls; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; /** * Created by ivan on 26.10.16. */ @Entity @DiscriminatorValue("BASIC_HAUL") public class BasicHaul extends AbstractHaul { public BasicHaul() { } }
true
0e4951863b80c92a3185dba26c838db054073677
Java
herve8913/Abuse_Reporting_System
/src/bean/Patient.java
UTF-8
12,938
2.203125
2
[]
no_license
package bean; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; public class Patient { private int id; private int status; private String patientName; private String patientMidname; private String patientLastName; private int iq; private Date birthdate; private String sex; private String telephone; private int maritalStatusId; private String maritalStatus; private int groupHomeId; private String groupHome; private String currentlyServedBy; private String clientGuardian; private int clientGuardianId; private int ethnicityId; private String ethnicity; private int currentlyServedById; private String logNumber; private Connection conn; public Patient(int id, int status, String patientName, String patientMidname, String patientLastName, int iq, Date birthdate, String sex, String telephone, int maritalStatusId, int groupHomeId, int currentlyServedById, Connection conn) { this.id=id; this.status = status; this.patientName = patientName; this.patientMidname = patientMidname; this.patientLastName = patientLastName; this.iq = iq; this.birthdate = birthdate; this.sex = sex; this.telephone = telephone; this.maritalStatusId = maritalStatusId; this.groupHomeId = groupHomeId; this.currentlyServedById = currentlyServedById; this.conn = conn; } public Patient(int id, String patientName, String patientMidname, String patientLastName, int iq, Date birthdate, String sex, String telephone, String maritalStatus, String groupHome, String currentlyServedBy, String clientGuardian, String ethnicity, String logNumber, Connection conn) { this.id = id; this.patientName = patientName; this.patientMidname = patientMidname; this.patientLastName = patientLastName; this.iq = iq; this.birthdate = birthdate; this.sex = sex; this.telephone = telephone; this.maritalStatus = maritalStatus; this.groupHome = groupHome; this.currentlyServedBy = currentlyServedBy; this.clientGuardian = clientGuardian; this.ethnicity = ethnicity; this.logNumber = logNumber; this.conn = conn; } public Patient(String patientName, String patientMidname, String patientLastName, String sex, int iq, Date birthdate, String telephone, int maritalStatusId, int groupHomeId, int currentlyServedById, int ethnicityId, int clientGuardianId, Connection conn){ this.patientName = patientName; this.patientMidname = patientMidname; this.patientLastName = patientLastName; this.sex = sex; this.iq = iq; this.birthdate = birthdate; this.telephone = telephone; this.maritalStatusId = maritalStatusId; this.groupHomeId = groupHomeId; this.currentlyServedById = currentlyServedById; this.ethnicityId = ethnicityId; this.clientGuardianId = clientGuardianId; this.conn = conn; } public Patient(String logNumber, String patientName, String patientMidname, String patientLastName, String sex, int iq, Date birthdate, String telephone, int maritalStatusId, int groupHomeId, int currentlyServedById, int ethnicityId, int clientGuardianId, Connection conn){ this.logNumber = logNumber; this.patientName = patientName; this.patientMidname = patientMidname; this.patientLastName = patientLastName; this.sex = sex; this.iq = iq; this.birthdate = birthdate; this.telephone = telephone; this.maritalStatusId = maritalStatusId; this.groupHomeId = groupHomeId; this.currentlyServedById = currentlyServedById; this.ethnicityId = ethnicityId; this.clientGuardianId = clientGuardianId; this.conn = conn; } public Patient(Connection conn, String logNumber){ this.conn = conn; this.logNumber = logNumber; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getIq() { return iq; } public void setIq(int iq) { this.iq = iq; } public String getMaritalStatus() { return maritalStatus; } public void setMaritalStatus(String maritalStatus) { this.maritalStatus = maritalStatus; } public int getGroupHomeId() { return groupHomeId; } public void setGroupHomeId(int groupHomeId) { this.groupHomeId = groupHomeId; } public String getGroupHome() { return groupHome; } public void setGroupHome(String groupHome) { this.groupHome = groupHome; } public String getCurrentlyServedBy() { return currentlyServedBy; } public void setCurrentlyServedBy(String currentlyServedBy) { this.currentlyServedBy = currentlyServedBy; } public String getClientGuardian() { return clientGuardian; } public void setClientGuardian(String clientGuardian) { this.clientGuardian = clientGuardian; } public int getEthnicityId() { return ethnicityId; } public void setEthnicityId(int ethnicityId) { this.ethnicityId = ethnicityId; } public String getEthnicity() { return ethnicity; } public void setEthnicity(String ethnicity) { this.ethnicity = ethnicity; } public String getLogNumber() { return logNumber; } public void setLogNumber(String logNumber) { this.logNumber = logNumber; } public void setId(int id) { this.id = id; } public void setPatientMidname(String patientMidname) { this.patientMidname = patientMidname; } public void setPatientLastName(String patientLastName) { this.patientLastName = patientLastName; } public Patient(int id, Connection conn){ this.id=id; this.conn=conn; } public int getId(){ return id; } public String getPatientName() { return patientName; } public String getPatientMidname() { return patientMidname; } public String getPatientLastName() { return patientLastName; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public int getMaritalStatusId() { return maritalStatusId; } public void setMaritalStatusId(int maritalStatusId) { this.maritalStatusId = maritalStatusId; } public void setPatientName(String patientName) { this.patientName = patientName; } public int getCurrentlyServedById(){ return currentlyServedById; } public void setCurrentlyServedById(int currentlyServedById){ this.currentlyServedById = currentlyServedById; } public int getClientGuardianId() { return clientGuardianId; } public void setClientGuardianId(int clientGuardianId) { this.clientGuardianId = clientGuardianId; } public static List<Patient> getAllPatient(Connection conn) { List<Patient> listOfAllPatient = new LinkedList<Patient>(); String sql = "SELECT * FROM patient"; try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); int status = rs.getInt("status"); String patientName = rs.getString("patient_name"); String patientMidname = rs.getString("patient_midname"); String patientLastName = rs.getString("patient_last_name"); int iq = rs.getInt("iq"); Date birthdate = rs.getDate("birthdate"); String sex = rs.getString("sex"); String telephone = rs.getString("telephone"); int maritalStatusId = rs.getInt("marital_status_id"); int groupHomeId = rs.getInt("group_home_id"); int currentlyServedById = rs.getInt("currently_served_by_id"); Patient patient = new Patient(id, status, patientName, patientMidname, patientLastName, iq, birthdate, sex, telephone, maritalStatusId, groupHomeId, currentlyServedById, conn); listOfAllPatient.add(patient); } rs.close(); stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listOfAllPatient; } public void setPatientInfo(int type){ String sql=null; if(type==1){ sql = "SELECT * FROM patient WHERE id = ?"; }else if(type==2){ sql = "SELECT * FROM patient WHERE patient_log_number = ?"; } try { PreparedStatement stmt = conn.prepareStatement(sql); if(type==1){ stmt.setInt(1, id); }else if (type==2){ stmt.setString(1, logNumber); } ResultSet rs = stmt.executeQuery(); if(rs.next()){ setPatientName(rs.getString("patient_name")); setPatientLastName(rs.getString("patient_last_name")); setPatientMidname(rs.getString("patient_midname")); setIq(rs.getInt("iq")); setGroupHomeId(rs.getInt("group_home_id")); setClientGuardianId(rs.getInt("client_guardian_id")); setEthnicityId(rs.getInt("ethnicity_id")); setSex(rs.getString("sex")); setTelephone(rs.getString("telephone")); setBirthdate(rs.getDate("birthdate")); setMaritalStatusId(rs.getInt("marital_status_id")); setCurrentlyServedById(rs.getInt("currently_served_by_id")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static List<Patient> getPatientPanelList(Connection conn){ List<Patient> listOfPatient = new LinkedList<>(); String sql = "SELECT * FROM view_patient WHERE patient_status=1 ORDER BY id"; try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("patient_name"); String midName = rs.getString("patient_midname"); String lastName = rs.getString("patient_last_name"); String logNumber = rs.getString("patient_log_number"); int iq = rs.getInt("iq"); Date birthdate = rs.getDate("birthdate"); String sex = rs.getString("sex"); String telephone = rs.getString("telephone"); String maritalStatus = rs.getString("marital_status"); String groupHome = rs.getString("address"); String currentlyServedBy = rs.getString("currently_served_by"); String clientGuardianName = rs.getString("user_name"); String clientGuardianLastName = rs.getString("user_last_name"); String clientGuardian = clientGuardianName+" "+clientGuardianLastName; String ethnicity = rs.getString("ethnicity"); Patient patient = new Patient(id, name, midName, lastName, iq, birthdate, sex, telephone, maritalStatus, groupHome, currentlyServedBy, clientGuardian, ethnicity, logNumber, conn ); listOfPatient.add(patient); } rs.close(); stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listOfPatient; } public void createPatient(){ String sql = "INSERT INTO patient(patient_name, patient_midname,patient_last_name, iq, birthdate, sex, telephone, marital_status_id, group_home_id, currently_served_by_id, client_guardian_id, ethnicity_id) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, patientName); stmt.setString(2, patientMidname); stmt.setString(3, patientLastName); stmt.setInt(4, iq); stmt.setDate(5, birthdate); stmt.setString(6, sex); stmt.setString(7, telephone); stmt.setInt(8, maritalStatusId); stmt.setInt(9, groupHomeId); stmt.setInt(10,currentlyServedById); stmt.setInt(11, clientGuardianId); stmt.setInt(12, ethnicityId); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void deletePatient(Connection conn, String logNumber){ String sql = "DELETE FROM patient WHERE patient_log_number = ?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, logNumber); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updatePatient(){ String sql = "UPDATE patient SET patient_name=?, patient_midname=?, patient_last_name=?, iq=?, birthdate=?, sex=?, telephone=?, marital_status_id=?, group_home_id=?, currently_served_by_id=?, client_guardian_id=?, ethnicity_id=? WHERE patient_log_number=?"; try { PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, patientName); stmt.setString(2, patientMidname); stmt.setString(3, patientLastName); stmt.setInt(4, iq); stmt.setDate(5, birthdate); stmt.setString(6, sex); stmt.setString(7, telephone); stmt.setInt(8, maritalStatusId); stmt.setInt(9, groupHomeId); stmt.setInt(10, currentlyServedById); stmt.setInt(11, clientGuardianId); stmt.setInt(12, ethnicityId); stmt.setString(13, logNumber); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
d8bcc67aa32f74861fb564937a0e31809011a69e
Java
OleksZamkovyi/PaymentProject
/src/test/java1/ozamkovyi/web/servlet/clientServlets/ClientPaymentMenuServletTest.java
UTF-8
12,198
2.125
2
[]
no_license
package ozamkovyi.web.servlet.clientServlets; import org.junit.Test; import ozamkovyi.db.bean.BankAccountBean; import ozamkovyi.db.bean.PaymentBean; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import static org.mockito.Mockito.*; import static org.mockito.Mockito.times; public class ClientPaymentMenuServletTest { @Test public void shouldRedirectToClientPaymentMenuNextPage() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("nextPage")).thenReturn("ok"); when(session.getAttribute("pageNumber")).thenReturn(1); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuPreviousPage() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("previousPage")).thenReturn("ok"); when(session.getAttribute("pageNumber")).thenReturn(2); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByNumber() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByNumber")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(1); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByNumber2() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByNumber")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(2); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByNumberNull() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByNumber")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByDate() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByDate")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(3); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByDate2() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByDate")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(4); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByDateNull() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByDate")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByAmount() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByAmount")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(5); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByAmount2() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByAmount")).thenReturn("ok"); when(session.getAttribute("sortType")).thenReturn(6); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientPaymentMenuSortByAmountNull() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("sortByAmount")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientPaymentMenu"); } @Test public void shouldRedirectToClientAccountMenu() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<PaymentBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("buttonMyAccount")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientAccountMenu"); } @Test public void shouldRedirectToClientCardMenu() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<BankAccountBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("buttonMyCard")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientCardMenu"); } @Test public void shouldRedirectToClientAddPayment() throws ServletException, IOException { ClientPaymentMenuServlet servlet = new ClientPaymentMenuServlet(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); ArrayList<BankAccountBean> listOfBankAccountForUnlock = new ArrayList<>(); when(request.getSession()).thenReturn(session); when(request.getParameter("add_payment")).thenReturn("ok"); when(session.getAttribute("listOfPayment")).thenReturn(listOfBankAccountForUnlock); servlet.doPost(request, response); verify(response, times(1)).sendRedirect("/clientAddPayment"); } }
true
7d4936325eacee603ec7bcfe5c21d310e95e0aee
Java
willp-bl/eidas-mirror
/EIDAS-SpecificCommunicationDefinition/src/main/java/eu/eidas/specificcommunication/protocol/util/SecurityUtils.java
UTF-8
3,919
2.171875
2
[]
no_license
/* * Copyright (c) 2019 by European Commission * * Licensed under the EUPL, Version 1.2 or - as soon they will be * approved by the European Commission - subsequent versions of the * EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/page/eupl-text-11-12 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the Licence for the specific language governing permissions and * limitations under the Licence */ package eu.eidas.specificcommunication.protocol.util; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.XMLReader; import javax.annotation.Nonnull; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import java.io.StringReader; /** * Util class with methods related to security. */ public final class SecurityUtils { private static final String LOAD_EXTERNAL_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; private static final String DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; private static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; private static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; /** * Creates a {@link SAXSource} with the security features turned on * for the input. * * @param input the string to be used to create the {@link SAXSource} instance * @return the secured {@link SAXSource} instance * @throws ParserConfigurationException if a parser cannot * be created which satisfies the requested configuration. * @throws SAXNotRecognizedException When the underlying XMLReader does * not recognize the property EXTERNAL_GENERAL_ENTITIES. */ @Nonnull public static final SAXSource createSecureSaxSource(String input) throws ParserConfigurationException, SAXException { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); // Ignore the external DTD completely // Note: this is for Xerces only: saxParserFactory.setFeature(LOAD_EXTERNAL_DTD, Boolean.FALSE); // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl saxParserFactory.setFeature(DISALLOW_DOCTYPE_DECL, Boolean.TRUE); // If you can't completely disable DTDs, then at least do the following: // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities saxParserFactory.setFeature(EXTERNAL_GENERAL_ENTITIES, Boolean.FALSE); // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities saxParserFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES, Boolean.FALSE); SAXParser saxParser = saxParserFactory.newSAXParser(); StringReader stringReader = new StringReader(input); InputSource inputSource = new InputSource(stringReader); XMLReader xmlReader = saxParser.getXMLReader(); SAXSource saxSource = new SAXSource(xmlReader, inputSource); return saxSource; } private SecurityUtils() { } }
true
06be567ebe1a38fe7d53648b4ea54147c801b4fa
Java
mpirnazarov/ERP
/src/main/java/com/lgcns/erp/tapps/viewModel/usermenu/JobexpViewModel.java
UTF-8
1,953
2.28125
2
[]
no_license
package com.lgcns.erp.tapps.viewModel.usermenu; import java.sql.Date; /** * Created by Dell on 25-Oct-16. */ public class JobexpViewModel { private String organization; private String position; private Date startDate; private Date endDate; private int contractType; private int id; public JobexpViewModel(String organization, String post, Date startDate, Date endDate, int contractType, int id) { this.organization = organization; this.position = post; this.startDate = startDate; this.endDate = endDate; this.contractType = contractType; this.id = id; } public JobexpViewModel() { } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getContractType() { return contractType; } public void setContractType(int contractType) { this.contractType = contractType; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "JobexpViewModel{" + "organization='" + organization + '\'' + ", position='" + position + '\'' + ", startDate=" + startDate + ", endDate=" + endDate + ", Contract type=" + contractType + '}'; } }
true
f83b50a632dd9a9bd3b4a52549b93383e634f2e9
Java
jonccooke/com.tere.tools.modelling
/src/main/java/com/tere/modelling/exeptions/TypeNotFoundException.java
UTF-8
222
1.945313
2
[ "Apache-2.0" ]
permissive
package com.tere.modelling.exeptions; import com.tere.TereException; public class TypeNotFoundException extends ModellingException { public TypeNotFoundException(String typeName) { super(typeName); } }
true
ce48d2a9302a2b1ac6159a7451711731546a7279
Java
DeveloperAdam/PFD
/app/src/main/java/com/techease/pfd/Fragments/Recipe.java
UTF-8
4,176
2.296875
2
[]
no_license
package com.techease.pfd.Fragments; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.techease.pfd.R; public class Recipe extends Fragment { TabLayout tabLayout; private FloatingActionButton fab; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_recipe, container, false); fab = (FloatingActionButton)view.findViewById(R.id.fab); final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPagerPecipe); tabLayout = (TabLayout) view.findViewById(R.id.tablayoutRecipe); LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); tabLayout.addTab(tabLayout.newTab().setText("ALL RECIPES")); tabLayout.addTab(tabLayout.newTab().setText("YOUR RECIPE")); viewPager.setAdapter(new PagerAdapter(((FragmentActivity)getActivity()).getSupportFragmentManager(), tabLayout.getTabCount())); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); reduceMarginsInTabs(tabLayout,20); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment=new CreateNewRecipeFragment(); getFragmentManager().beginTransaction().replace(R.id.container,fragment).addToBackStack("abc").commit(); } }); return view; } public static void reduceMarginsInTabs(TabLayout tabLayout, int marginOffset) { View tabStrip = tabLayout.getChildAt(0); if (tabStrip instanceof ViewGroup) { ViewGroup tabStripGroup = (ViewGroup) tabStrip; for (int i = 0; i < ((ViewGroup) tabStrip).getChildCount(); i++) { View tabView = tabStripGroup.getChildAt(i); if (tabView.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams) tabView.getLayoutParams()).leftMargin = marginOffset; ((ViewGroup.MarginLayoutParams) tabView.getLayoutParams()).rightMargin = marginOffset; } } tabLayout.requestLayout(); } } public static class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapter(android.support.v4.app.FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public android.support.v4.app.Fragment getItem(int position) { switch (position) { case 0: ListOfRecipesFragment frag=new ListOfRecipesFragment(); return frag; case 1: UserListOfRecipes frag2=new UserListOfRecipes(); return frag2; default: return null; } } @Override public int getCount() { return mNumOfTabs; } } }
true
543f56f4a379ab06c61712d4d513f52f250bcd9f
Java
CIoann/cuciTraceAnalyzers
/Data Analyser/src/DataStructures/Sce.java
UTF-8
2,806
2.734375
3
[]
no_license
package DataStructures; public class Sce { private String user; private String sce_gaze_id; private String sce_name; private String sce_type; private String how; private String total_length; private String start_line; private String end_line; private String start_col; private String end_col; private String depth; public Sce(String user, String sce_gaze_id, String sce_name, String sce_type, String how, String total_length, String start_line, String end_line, String start_col, String end_col, String depth) { super(); this.user = user; this.sce_gaze_id = sce_gaze_id; this.sce_name = sce_name; this.sce_type = sce_type; this.how = how; this.total_length = total_length; this.start_line = start_line; this.end_line = end_line; this.start_col = start_col; this.end_col = end_col; this.depth = depth; } public Sce(String user, String sce_gaze_id, String sce_name, String sce_type, String how) { super(); this.user = user; this.sce_gaze_id = sce_gaze_id; this.sce_name = sce_name; this.sce_type = sce_type; this.how = how; } public void print(){ System.out.println(sce_gaze_id + sce_name + sce_type + how + total_length + start_line + end_line +start_col + end_col + depth ); } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getSce_gaze_id() { return sce_gaze_id; } public void setSce_gaze_id(String sce_gaze_id) { this.sce_gaze_id = sce_gaze_id; } public String getSce_name() { return sce_name; } public void setSce_name(String sce_name) { this.sce_name = sce_name; } public String getSce_type() { return sce_type; } public void setSce_type(String sce_type) { this.sce_type = sce_type; } public String getHow() { return how; } public void setHow(String how) { this.how = how; } public String getTotal_length() { return total_length; } public void setTotal_length(String total_length) { this.total_length = total_length; } public String getStart_line() { return start_line; } public void setStart_line(String start_line) { this.start_line = start_line; } public String getEnd_line() { return end_line; } public void setEnd_line(String end_line) { this.end_line = end_line; } public String getStart_col() { return start_col; } public void setStart_col(String start_col) { this.start_col = start_col; } public String getEnd_col() { return end_col; } public void setEnd_col(String end_col) { this.end_col = end_col; } public String getDepth() { return depth; } public void setDepth(String depth) { this.depth = depth; } }
true
3cd8301ec4538950a6c86c05ab23997c9eeff8b4
Java
UltimateTM/DNDRipOff
/Main.java
UTF-8
4,988
3.28125
3
[]
no_license
import java.util.*; import java.lang.Thread; class Main { public static void main(String[] args) { Weapon w = new Weapon(); Potion p = new Potion(); Helper h = new Helper(); Item j = new Item(); Scanner scan = new Scanner(System.in); int input = 0; String sinput = ""; boolean isRunning = true; Player player = new Player(); Helper helper = new Helper(); Level level = new Level(); while(isRunning){ Hud.mainScreen(); input = h.errorCatch(); if(input == 1){ boolean gameTime = true, isntValid = true; while(isntValid){ Hud.createCharacter(); input = h.errorCatch(); if(input == 1 || input == 2 || input == 3) isntValid = false; else isntValid = true; } //character class is chosen if (input == 1){ player = new Barbarian(); } else if(input == 2){ player = new Rogue(); } else if(input == 3){ player = new Wizard(); } //displays stats before the start of the game player.displayStats(); scan.next(); sinput = scan.nextLine(); while(gameTime){ try { Hud.gameScreen(); input = h.errorCatch(); if(input == 1){ System.out.println("Game would start here"); level.scene1Part1(player); } else if(input == 2){ Hud.shop(player); input = h.errorCatch(); int money = player.money; if (input == 1 && player.money > 0) { Hud.clearScreen(); System.out.println("=============================="); Helper.slowPrint("Coin Balance : [" + money + "]"); System.out.println("==============================\n"); w.printWeaponArray(); Helper.slowPrint("\nPlease select an Item"); input = h.errorCatch(); player.money -= Weapon.shopWeaponItems.get(input).getCost(); if (player.money < 0) { player.money = money; Helper.slowPrint("LMAO smells like broke in here"); Thread.sleep(1500); } else { player.addToInventory(Weapon.shopWeaponItems.get(input)); Helper.slowPrint("You have bought " + Weapon.shopWeaponItems.get(input).getName()); Helper.slowPrint("Coin Balance : [" + player.money + "]"); Thread.sleep(1500); } } else if (input == 2 && player.money > 0) { Hud.clearScreen(); System.out.println("=============================="); Helper.slowPrint("Coin Balance : [" + money + "]"); System.out.println("==============================\n"); p.printPotionArray(); Helper.slowPrint("\nPlease select an Item"); input = h.errorCatch(); player.money -= Potion.shopPotionItems.get(input).getCost(); if (player.money < 0) { player.money = money; Helper.slowPrint("You cannot afford this item"); Thread.sleep(1500); } else { player.addToInventory(Potion.shopPotionItems.get(input)); Helper.slowPrint("You have bought " + Potion.shopPotionItems.get(input).getName()); Helper.slowPrint("Coin Balance : [" + player.money + "]"); Thread.sleep(1500); } } else { Hud.clearScreen(); // Helper.slowPrint("You have no money."); // scan.next(); // sinput = scan.nextLine(); } } else if(input == 3){ //accesses inventory player.printInventory(); Helper.slowPrint("Type Anything to Exit: "); scan.next(); sinput=scan.nextLine(); } else if(input == 4){ //goes back to mainscreen gameTime = false; System.out.println("L"); } } catch (InterruptedException E) { System.out.println("L"); } } } else if (input == 2) { System.exit(0); } } } }
true
4de4b3a23d3e8baf8253f2570cdf6a313e6a6e38
Java
dagike/Practica7Arbol
/src/numero/NumeroComplejo.java
UTF-8
757
3.046875
3
[]
no_license
package numero; public class NumeroComplejo extends Numero { private double parteImaginaria; public NumeroComplejo() { super(); parteImaginaria = 0.0; } public NumeroComplejo(double parteReal, double parteImaginaria) { super(parteReal); this.parteImaginaria = parteImaginaria; } public double getParteImaginaria() { return parteImaginaria; } public void setParteImaginaria(double parteImaginaria) { this.parteImaginaria = parteImaginaria; } public String toString() { return "(" + super.toString() + " + " + parteImaginaria + "i )"; } public boolean equals(Object nc){ if(parteImaginaria == ((NumeroComplejo)nc).parteImaginaria && parteReal == ((NumeroComplejo)nc).parteReal) return true; else return false; } }
true
26d16bd38e784a95c64a4dcc4845cb1442bda61a
Java
mesutsaritas/good-api
/src/main/java/com/goodapi/enums/PasswordHashUtil.java
UTF-8
2,076
3.046875
3
[]
no_license
package com.goodapi.enums; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import javax.xml.bind.DatatypeConverter; /** * A util class to encrypt and check password. * * @author tcmsaritas */ public enum PasswordHashUtil { INSTANCE; /** * Encrypt given passwort string with SHA-512 algorithm and salt. * * @param passwordToHash * @param salt * @return * @throws NoSuchAlgorithmException */ public String getSecurePassword(String passwordToHash, String salt) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(salt.getBytes()); byte[] bytes = md.digest(passwordToHash.getBytes()); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } String generatedPassword = sb.toString(); return generatedPassword; } /** * Return a random generated secret key to encrypt password. * * @return * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public String getSalt() throws NoSuchAlgorithmException, NoSuchProviderException { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN"); byte[] salt = new byte[16]; // Get a random salt sr.nextBytes(salt); return DatatypeConverter.printBase64Binary(salt); } /** * Encrypt the given password string and compare with encrypted password. * * @param passwordToHash * @param hashedPassword * @param salt * @return * @throws NoSuchAlgorithmException */ public boolean checkPassword(String passwordToHash, String hashedPassword, String salt) throws NoSuchAlgorithmException { return (hashedPassword != null && salt != null && getSecurePassword(passwordToHash, salt).equals(hashedPassword)); } }
true
c25c81db33f2f857536c4041f475e6810dbf6d08
Java
fmreina/ine5448-TopicosEspeciais-Testes
/codigo/SistemaBancario.Estoria/src/estoriatests/TesteDeposito.java
UTF-8
1,014
2.328125
2
[]
no_license
package estoriatests; import static org.junit.Assert.assertNotEquals; import org.junit.Before; import org.junit.Test; import br.ufsc.ine.leb.projetos.estoria.Fixture; import br.ufsc.ine.leb.projetos.estoria.FixtureSetup; import br.ufsc.ine.leb.sistemaBancario.Conta; import br.ufsc.ine.leb.sistemaBancario.Dinheiro; import br.ufsc.ine.leb.sistemaBancario.Entrada; import br.ufsc.ine.leb.sistemaBancario.Moeda; import br.ufsc.ine.leb.sistemaBancario.ValorMonetario; @FixtureSetup(TesteContaMaria.class) public class TesteDeposito { @Fixture private Conta contaMaria; @Fixture private ValorMonetario valorZero; private Dinheiro dezReais; private Entrada deposito; @Before public void configurar(){ dezReais = new Dinheiro(Moeda.BRL, 10, 0); deposito = new Entrada(contaMaria, dezReais); contaMaria.adicionarTransacao(deposito); } @Test public void testeDeposito(){ assertNotEquals(valorZero.obterQuantia().formatado(), contaMaria.calcularSaldo().obterQuantia().formatado()); } }
true
9ea636631b8cd5f7a575515f93e694575903298d
Java
nendraharyo/presensimahasiswa-sourcecode
/b/a/a/a/b/c/b$2.java
UTF-8
611
1.625
2
[]
no_license
package b.a.a.a.b.c; import b.a.a.a.c.a; import b.a.a.a.e.i; import java.io.IOException; class b$2 implements a { b$2(b paramb, i parami) {} public boolean a() { try { i locali = this.a; locali.b(); bool = true; } catch (IOException localIOException) { for (;;) { boolean bool = false; Object localObject = null; } } return bool; } } /* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\b\a\a\a\b\c\b$2.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
true
202fa281077b67ed88d22858e8f3c3a76cff1afa
Java
NevarDima/finalproject
/web/src/main/java/com/github/alexeysa83/finalproject/web/servlet/user/UpdatePasswordServlet.java
UTF-8
2,851
2.21875
2
[]
no_license
package com.github.alexeysa83.finalproject.web.servlet.user; import com.github.alexeysa83.finalproject.model.AuthUser; import com.github.alexeysa83.finalproject.service.validation.AuthValidationService; import com.github.alexeysa83.finalproject.service.auth.DefaultSecurityService; import com.github.alexeysa83.finalproject.service.auth.SecurityService; import com.github.alexeysa83.finalproject.web.servlet.auth.LoginServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.time.LocalDateTime; import static com.github.alexeysa83.finalproject.web.WebUtils.forwardToServletMessage; @WebServlet(name = "UpdatePasswordServlet", urlPatterns = {"/restricted/authuseruser/pass/update/password"}) public class UpdatePasswordServlet extends HttpServlet { private static final Logger log = LoggerFactory.getLogger(UpdatePasswordServlet.class); private SecurityService securityService = DefaultSecurityService.getInstance(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { final String passwordNew = req.getParameter("passwordNew"); final String passwordRepeat = req.getParameter("passwordRepeat"); String message = AuthValidationService.isPasswordValid(passwordNew, passwordRepeat); if (message != null) { forwardToServletMessage("/restricted/user/profile", message, req, resp); return; } final String passwordBefore = req.getParameter("passwordBefore"); final String authId = req.getParameter("authId"); final AuthUser user = securityService.getById(authId); final boolean isValid = AuthValidationService.isPasswordEqual(passwordBefore, user.getPassword()); if (!isValid) { message = "Invalid password"; log.info("Invalid password enter for user id: {} at: {}", authId, LocalDateTime.now()); forwardToServletMessage("/restricted/user/profile", message, req, resp); return; } final boolean isUpdated = securityService.update (new AuthUser(user.getId(), user.getLogin(), passwordNew, user.getRole(), user.isBlocked())); message = "Update succesfull"; if (!isUpdated) { message = "Update cancelled, please try again"; log.error("Failed to update password for user id: {} , at: {}", authId, LocalDateTime.now()); forwardToServletMessage("/restricted/user/profile", message, req, resp); } log.info("Updated password for user id: {}, at: {}", authId, LocalDateTime.now()); forwardToServletMessage("/auth/logout", message, req, resp); } }
true
a1072252e8e77af4ef5062bb36037e253e3666d6
Java
pillfill/pf-java-client
/src/main/java/com/apothesource/pillfill/datamodel/spl/Pkg.java
UTF-8
3,943
1.914063
2
[ "MIT" ]
permissive
/* * The MIT License * * Copyright 2015 Apothesource, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.apothesource.pillfill.datamodel.spl; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Pkg implements Serializable { private static final long serialVersionUID = -1L; private String quantity; private String ndc; private ArrayList<String> ndcs; private List<String> splLabelImage; private List<String> splPillImage; private String form; private List<String> upc; /** * public getter * * @returns java.lang.String */ public String getQuantity() { return this.quantity; } /** * public setter * * @param java.lang.String */ public void setQuantity(String quantity) { this.quantity = quantity; } /** * public getter * * @returns java.lang.String */ public String getNdc() { return this.ndc; } /** * public setter * * @param java.lang.String */ public void setNdc(String ndc) { this.ndc = ndc; } /** * public getter * * @returns java.util.List<java.lang.String> */ public List<String> getSplLabelImage() { if (splLabelImage == null) splLabelImage = new ArrayList<String>(); return this.splLabelImage; } /** * public setter * * @param java.util.List<java.lang.String> */ public void setSplLabelImage(List<String> splLabelImage) { this.splLabelImage = splLabelImage; } /** * public getter * * @returns java.util.List<java.lang.String> */ public List<String> getSplPillImage() { if (splPillImage == null) { splPillImage = new ArrayList<>(); } return this.splPillImage; } /** * public setter * * @param java.util.List<java.lang.String> */ public void setSplPillImage(List<String> splPillImage) { this.splPillImage = splPillImage; } /** * public getter * * @returns java.lang.String */ public String getForm() { return this.form; } /** * public setter * * @param java.lang.String */ public void setForm(String form) { this.form = form; } /** * public getter * * @returns java.util.List<java.lang.String> */ public List<String> getUpc() { return this.upc; } /** * public setter * * @param java.util.List<java.lang.String> */ public void setUpc(List<String> upc) { this.upc = upc; } public ArrayList<String> getNdcs() { if (ndcs == null) ndcs = new ArrayList<>(); return ndcs; } public void setNdcs(ArrayList<String> ndcs) { this.ndcs = ndcs; } }
true
0c4d740f7287b5dc9c184adb234f8f0c76f023cc
Java
heumjun/common
/src/java/stxship/dis/bom/bom/controller/BomController.java
UTF-8
3,225
2.03125
2
[]
no_license
package stxship.dis.bom.bom.controller; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import stxship.dis.bom.bom.service.BomService; import stxship.dis.common.command.CommandMap; import stxship.dis.common.constants.DisConstants; import stxship.dis.common.controller.CommonController; @Controller public class BomController extends CommonController { /** * Bom 서비스 */ @Resource(name = "bomService") private BomService bomService; /** * @메소드명 : linkSelectedMenu * @날짜 : 2015. 12. 10. * @작성자 : 이상빈 * @설명 : * * <pre> * 1.유저의 권한체크 * 2.Bom 페이지 이동 * </pre> * * @param commandMap * @return */ @RequestMapping(value = "bom.do") public ModelAndView linkSelectedMenu(CommandMap commandMap) { return getUserRoleAndLink(commandMap); } /** * @메소드명 : getGridListAction * @날짜 : 2015. 12. 10. * @작성자 : 이상빈 * @설명 : * * <pre> * Bom 리스트 취득 * </pre> * * @param commandMap * @return */ @RequestMapping(value = "bomList.do") public @ResponseBody Map<String, Object> getGridListAction(CommandMap commandMap) { // 공통 서비스에서 사용되어질 커스텀 서비스를 설정한다. // 각 서비스별로 별도 로직이 이루어진다. if(commandMap.get("p_item_code").equals("*")) { commandMap.put("p_item_code", ""); } return bomService.getGridList(commandMap); } /** * @메소드명 : bomExcelExport * @날짜 : 2015. 12. 10. * @작성자 : 이상빈 * @설명 : * * <pre> * Bom 리스트 엑셀 다운로드 * </pre> * * @param commandMap * @return */ @RequestMapping(value = "bomExcelExport.do") public View bomExcelExport(CommandMap commandMap, Map<String, Object> modelMap) throws Exception { return bomService.bomExcelExport(commandMap, modelMap); } /** * @메소드명 : popUpItem * @날짜 : 2017. 3. 4. * @작성자 : 조흠준 * @설명 : * * <pre> * 검색버튼을 선택하였을때 BOM 아이템 검색화면 이동 * </pre> * * @param commandMap * @return */ @RequestMapping(value = "popUpItem.do") public ModelAndView popUpItem(CommandMap commandMap) { ModelAndView mav = getUserRoleAndLink(commandMap); mav.setViewName(DisConstants.BOM + DisConstants.POPUP + commandMap.get(DisConstants.JSP_NAME)); return mav; } /** * @메소드명 : infoSearchItemAction * @날짜 : 2017. 3. 4. * @작성자 : 조흠준 * @설명 : * * <pre> * BOM 아이템 검색 * </pre> * * @param commandMap * @return * @throws UnsupportedEncodingException */ @RequestMapping(value = "popUpItemList.do") public @ResponseBody Map<String, Object> popUpItemList(CommandMap commandMap) throws Exception { return bomService.getGridList(commandMap); } }
true
64b66d43243a1103c5d431807dc54d796148dced
Java
whaooooot/MxS
/MxS/src/main/java/repository/StoreSessionRepository.java
UTF-8
1,940
2.34375
2
[]
no_license
package repository; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import model.StoreDTO; @Repository public class StoreSessionRepository extends AbstractRepository { private final String namespace = "repository.mapper.StoreMapper"; public List<StoreDTO> selectStore() { SqlSession sqlSession = this.getSqlSessionFactory().openSession(); String statement = namespace + ".selectStore"; List<StoreDTO> list = new ArrayList<StoreDTO>(); try { list = sqlSession.selectList(statement); System.out.println(list.size()); System.out.println(list); } catch(Exception e) { e.printStackTrace(); } return list; } /* public Integer insertComment(Comment comment) { SqlSession sqlSession = this.getSqlSessionFactory().openSession(); // Connection conn try { String statement = namespace + ".insertComment"; int result = sqlSession.insert(statement, comment); if (result > 0) { sqlSession.commit(); } return result; } finally { sqlSession.close(); } } public Integer updateComment(Comment comment) { SqlSession sqlSession = this.getSqlSessionFactory().openSession(); Integer result = sqlSession.update(namespace + ".updateComment", comment); if(result>0) { sqlSession.commit();//트랜젝션 관리가 가능함 }else { sqlSession.rollback(); } return result; } public Integer deleteComment(Long commentNo) { SqlSession sqlSession = this.getSqlSessionFactory().openSession(); Integer result = sqlSession.delete(namespace + ".deleteComment", commentNo); if(result>0) { sqlSession.commit();//트랜젝션 관리가 가능함 }else { sqlSession.rollback(); } return result; } */ }
true
d161e191a9fa37daa24adce7752d61672ef1240c
Java
bberzhou/JavaWeb
/book/src/com/bberzhou/dao/BookDao.java
UTF-8
1,950
2.84375
3
[]
no_license
package com.bberzhou.dao; import com.bberzhou.pojo.Book; import com.bberzhou.pojo.Page; import java.util.List; /** * @description: Book相关操作的接口 * @author: bberzhou@gmail.com * @date: 8/8/2021 * Create By Intellij IDEA */ public interface BookDao { /** * 根据书籍id来查询 * @param id 传入id号 * @return */ Book queryBookById(int id); Book queryBookByName(String bookName); /** * 更新书籍信息 * @param book 传入一个book对象 * @return */ int updateBook(Book book); /** * 根据id删除书籍 * @param id 传入要删除书籍的id * @return */ int deleteBookById(Integer id); /** * 添加图书信息 * @param book 传入一个book对象 * @return */ public int addBook(Book book); /** * 多本图书的查询 * @return 返回一个List集合 */ public List<Book> queryBooks(); /** * 用于分页操作中,查询数据库中总的记录数 * @return 返回总的记录数 */ public int queryForPageTotalCount(); /** * 用于分页查询, * @param begin 分页查询的起始索引值 * @param pageSize 分页查询中的每页大小 * @return 返回一个book的 list集合 */ public List<Book> queryForItems(int begin, Integer pageSize); /** * 查找价格区间内的所有数据 总数 * @param min 价格最小值 * @param max 价格最大值 * @return */ public int queryForPageSearchTotalCount(Integer min,Integer max); /** * 价格搜索时,按照每页的数量和起始值搜索 * @param begin 起始索引位置 * @param pageSize 每页数据大小 * @param min 价格最小值 * @param max 价格最大值 * @return */ public List<Book> queryForSearchItems(int begin, int pageSize, int min, int max); }
true
3116a0eb5485e4d9b1b5bf87cda00a7709f7419c
Java
Daniel-Roa-P/Mario_Data_Base
/src/java/Logica/YoshiAzul.java
UTF-8
352
2.40625
2
[]
no_license
package Logica; public class YoshiAzul extends Yoshi { @Override public void setImagen(){ this.imagen="https://raw.githubusercontent.com/DanielRoa20171020077/Mario/master/src/java/Imagenes/YoshiAzul.png"; } @Override public void setPoder(){ this.poder="Azul, sopla por su boca muchas burbujas"; } }
true
5182505826650fc3015262951f3e4b932bf974d5
Java
opengeospatial/geoapi
/geoapi/src/main/java/org/opengis/metadata/quality/DataQuality.java
UTF-8
3,918
2.046875
2
[ "Apache-2.0" ]
permissive
/* * GeoAPI - Java interfaces for OGC/ISO standards * Copyright © 2004-2023 Open Geospatial Consortium, Inc. * http://www.geoapi.org * * 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.opengis.metadata.quality; import java.util.Collection; import org.opengis.metadata.lineage.Lineage; import org.opengis.metadata.maintenance.Scope; import org.opengis.annotation.UML; import static org.opengis.annotation.Obligation.*; import static org.opengis.annotation.Specification.*; /** * Quality information for the data specified by a data quality scope. * * @author Martin Desruisseaux (IRD) * @author Alexis Gaillard (Geomatys) * @version 3.1 * @since 2.0 */ @UML(identifier="DQ_DataQuality", specification=ISO_19157) public interface DataQuality { /** * The specific data to which the data quality information applies. * The scope specifies the extent, spatial and/or temporal, and/or common characteristic(s) * that identify the data on which data quality is to be evaluated. * Examples: * <ul> * <li>a data set series;</li> * <li>a data set;</li> * <li>a subset of data defined by one or more of the following characteristics: * <ul> * <li>types of items (sets of feature types);</li> * <li>specific items (sets of feature instances);</li> * <li>geographic extent;</li> * <li>temporal extent.</li> * </ul> * </li> * </ul> * * @return the specific data to which the data quality information applies. */ @UML(identifier="scope", obligation=MANDATORY, specification=ISO_19157) Scope getScope(); /** * Quality information for the data specified by the scope. * The quality of a data set can be measured using a variety of methods; * a single data quality measure might be insufficient for fully evaluating * the quality of the data specified by the {@linkplain #getScope() scope}. * Therefore multiple data quality measures may be reported. * The data quality report should then include one instance of {@link Element} for each measure applied. * * @return quality information for the data specified by the scope. */ @UML(identifier="report", obligation=MANDATORY, specification=ISO_19157) Collection<? extends Element> getReports(); /** * Non-quantitative quality information about the lineage of the data specified by the scope. * * @return non-quantitative quality information about the lineage of the data specified, * or {@code null}. * * @deprecated Removed from ISO 19157:2013. */ @Deprecated @UML(identifier="lineage", obligation=CONDITIONAL, specification=ISO_19115, version=2003) default Lineage getLineage() { return null; } /** * Reference to an external standalone quality report. * Can be used for providing more details than reported as standard metadata. * * @return reference to an external standalone quality report, or {@code null} if none. * * @since 3.1 * * @todo Renamed in 19157:2022: {@code QualityEvaluationReport}. */ @UML(identifier="standaloneQualityReport", obligation=OPTIONAL, specification=ISO_19157) default StandaloneQualityReportInformation getStandaloneQualityReport() { return null; } }
true
9d388487ff0669f55c9086636ce510e21a691f31
Java
pawankumarsharm/UST-Global-16-SEP-19-PAWANKUMARSHARMA
/codes of ust/JPA Hibernate/assignment/src/main/java/com/ustglobal/assignment/UpdateQuery.java
UTF-8
780
2.359375
2
[]
no_license
package com.ustglobal.assignment; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.ustglobal.assignment.dto.Department; public class UpdateQuery { public static void main(String[] args) { EntityManager em=null; EntityTransaction t=null; try { EntityManagerFactory f = Persistence.createEntityManagerFactory("TestPersistence"); em = f.createEntityManager(); t = em.getTransaction(); t.begin(); Department d = em.find(Department.class, 90); d.setDname("Manager"); ; System.out.println("Record Updated"); t.commit(); } catch (Exception e) { e.printStackTrace(); t.rollback(); } em.close(); } }
true
dc08e81c2c3e28839be147994c85f62acb409754
Java
THYC/Actus
/src/main/java/net/teraoctet/actus/commands/portal/CommandPortalCreate.java
UTF-8
4,881
2.046875
2
[]
no_license
package net.teraoctet.actus.commands.portal; import java.util.function.Consumer; import static net.teraoctet.actus.Actus.plm; import static net.teraoctet.actus.Actus.ptm; import net.teraoctet.actus.plot.PlotSelection; import net.teraoctet.actus.portal.Portal; import net.teraoctet.actus.portal.PortalManager; import net.teraoctet.actus.utils.Data; import static net.teraoctet.actus.utils.MessageManager.MESSAGE; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.Location; import static net.teraoctet.actus.utils.MessageManager.NO_CONSOLE; import static net.teraoctet.actus.utils.MessageManager.NO_PERMISSIONS; import static net.teraoctet.actus.utils.MessageManager.NAME_ALREADY_USED; import static net.teraoctet.actus.utils.MessageManager.PROTECT_LOADED_PLOT; import static net.teraoctet.actus.utils.MessageManager.UNDEFINED_PLOT_ANGLES; import static net.teraoctet.actus.utils.MessageManager.USAGE; import org.spongepowered.api.command.source.ConsoleSource; import org.spongepowered.api.text.chat.ChatTypes; import org.spongepowered.api.world.World; public class CommandPortalCreate implements CommandExecutor { @Override public CommandResult execute(CommandSource src, CommandContext ctx) { if(src instanceof Player && src.hasPermission("actus.admin.portal")) { Player player = (Player) src; PlotSelection plotSelect = ptm.getPlotSel(player); if(!ctx.getOne("name").isPresent()) { player.sendMessage(USAGE("/portal create <name> : cr\351ation d'un portail au point d\351clar\351")); return CommandResult.empty(); } String name = ctx.<String> getOne("name").get(); if (plm.hasPortal(name) == false){ if(!plotSelect.getMinPos().isPresent() || !plotSelect.getMaxPos().isPresent()){ player.sendMessage(UNDEFINED_PLOT_ANGLES()); return CommandResult.empty(); } player.sendMessage(Text.builder("Clique ici pour confirmer la cr\351ation du portail").onClick(TextActions.executeCallback(callCreate(name))).color(TextColors.AQUA).build()); return CommandResult.success(); } else { player.sendMessage(NAME_ALREADY_USED()); } } else if (src instanceof ConsoleSource) { src.sendMessage(NO_CONSOLE()); } else { src.sendMessage(NO_PERMISSIONS()); } return CommandResult.empty(); } public Consumer<CommandSource> callCreate(String portalName) { return (CommandSource src) -> { Player player = (Player) src; PlotSelection plotSelect = ptm.getPlotSel(player); PortalManager plm = new PortalManager(); if(plm.hasPortal(portalName)){ player.sendMessage(MESSAGE("&bce portail existe d\351ja")); return; } Location[] c = {plotSelect.getMinPosLoc().get(), plotSelect.getMaxPosLoc().get()}; Location <World> world = c[0]; String worldName = world.getExtent().getName(); int x1 = c[0].getBlockX(); int y1 = c[0].getBlockY(); int z1 = c[0].getBlockZ(); int x2 = c[1].getBlockX(); int y2 = c[1].getBlockY(); int z2 = c[1].getBlockZ(); String message = "&c.. vers l''infini et au del\340 ..."; Portal portal = new Portal(portalName,0,worldName,x1,y1,z1,x2,y2,z2,message); portal.insert(); Data.commit(); Data.addPortal(portal); player.sendMessage(Text.builder().append(MESSAGE("Clique ici pour lire le message par d\351faut du portail")).onClick(TextActions.runCommand("/portal msg " + portalName )).color(TextColors.AQUA).build()); player.sendMessage(Text.builder().append(MESSAGE("Tape /portal msg <message> &bpour pour modifier le message par d\351faut")).onClick(TextActions.suggestCommand("/portal msg " + portalName + " 'remplace ce texte par ton message'")).color(TextColors.AQUA).build()); player.sendMessage(ChatTypes.ACTION_BAR,PROTECT_LOADED_PLOT(player,portalName)); }; } }
true
5056d266c7dbc270780812d1c0ddaf9688552c0a
Java
bigprincipalkk/sqlServie
/src/main/java/com.youngc.pipeline/model/UnitModel.java
UTF-8
618
1.695313
2
[]
no_license
package com.youngc.pipeline.model; import lombok.Data; import java.util.Date; @Data public class UnitModel { private Long unitId; private String unitCode; private String unitName; private String phoneOne; private String phoneTwo; private String contactOne; private String contactTwo; private String email; private String address; private String remark; private Long addPerson; private Date addTime; private Long lastPerson; private Date lastTime; private Long orgId; private String orgName; }
true
59d66bdc112f39fd4385dbd3b22c79beeae376fc
Java
gizmore/jpk
/src/org/gizmore/jpk/menu/file/JPKDiff.java
UTF-8
1,831
3.140625
3
[ "MIT" ]
permissive
package org.gizmore.jpk.menu.file; import java.io.File; import java.io.FileReader; import org.gizmore.jpk.JPKMethod; public final class JPKDiff implements JPKMethod { public String getName() { return "Diff"; } public int getMenuID() { return MENU_FILE; } public String getHelp() { return "Compare 2 binary files, (Very simple bytewise diff)"; } public int getMnemonic() { return 0; } public String getKeyStroke() { return ""; } public String execute(final String text) { final File[] files = JPKLoadFile.openFileDialog("Select Files", true); if (files == null) { return null; } if (files.length != 2) { return "Please select 2 files."; } return diff(files[0], files[1]); } private String diff(final File file1, final File file2) { try { final StringBuilder back = new StringBuilder(0xffff); final FileReader fr1 = new FileReader(file1); final FileReader fr2 = new FileReader(file2); long size = file1.length() > file2.length() ? file2.length() : file1.length(); back.append("Very simple bytewise diff\n"); back.append("Checking for differences in the following 2 files:\n"); back.append(String.format("File1: %s (%d bytes)\n", file1.getName(), file1.length())); back.append(String.format("File2: %s (%d bytes)\n", file2.getName(), file2.length())); back.append(String.format("Checking %d bytes... \n", size)); int a, b; for (long i = 0; i < size; i++) { a = fr1.read(); b = fr2.read(); if (a == b) { continue; } // back.append(String.format("%02x", a+b)); back.append(String.format("%08x: %02x %02x\n", i, a, b)); } return back.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } } }
true
45a548eb254f707763479c521ccf32b8615b9e94
Java
the-rahul/microservices
/Fare-Service/src/main/java/com/cts/flight/service/FareService.java
UTF-8
342
1.867188
2
[]
no_license
package com.cts.flight.service; import java.time.LocalDate; import com.cts.flight.entity.Fare; import com.cts.flight.entity.Flight; public interface FareService { Flight findByFlightNumberAndFlightDateAndOriginAndDestination(String flightNumber, LocalDate flightDate, String origin, String destination); Fare getFareById(int id); }
true
88068e3083469d82751170e17f4180cc6298f459
Java
lunax28/albumCreator
/src/main/java/AlbumCreatorController.java
UTF-8
15,609
2.453125
2
[]
no_license
import com.equilibriummusicgroup.albumCreator.model.Model; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import org.apache.commons.io.FilenameUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Scanner; import java.util.concurrent.ThreadLocalRandom; public class AlbumCreatorController { @FXML private Model model; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="upcTextArea" private TextArea upcTextArea; // Value injected by FXMLLoader @FXML // fx:id="chooseFolderButton" private Button chooseFolderButton; // Value injected by FXMLLoader @FXML // fx:id="folderPathTextField" private TextField folderPathTextField; // Value injected by FXMLLoader @FXML // fx:id="itmspCheckbox" private CheckBox itmspCheckbox; // Value injected by FXMLLoader @FXML // fx:id="songsNumberTextField" private TextField songsNumberTextField; // Value injected by FXMLLoader @FXML private File selectedDirectoryPath; @FXML private int songsPerAlbum; private int upcCount = 0; @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert upcTextArea != null : "fx:id=\"upcTextArea\" was not injected: check your FXML file 'albumCreatorHome.fxml'."; assert chooseFolderButton != null : "fx:id=\"chooseFolderButton\" was not injected: check your FXML file 'albumCreatorHome.fxml'."; assert folderPathTextField != null : "fx:id=\"folderPathTextField\" was not injected: check your FXML file 'albumCreatorHome.fxml'."; assert itmspCheckbox != null : "fx:id=\"itmspCheckbox\" was not injected: check your FXML file 'albumCreatorHome.fxml'."; assert songsNumberTextField != null : "fx:id=\"songsNumberTextField\" was not injected: check your FXML file 'albumCreatorHome.fxml'."; } public void setModel(Model model) { this.model = model; } /** * Entry point method */ @FXML void createAlbumButton(ActionEvent event) { //Check for correct entries if (this.upcTextArea.getText().isEmpty()) { displayWarningAlert("Insert a valid list of UPC first!"); return; } if (this.folderPathTextField.getText().isEmpty()) { displayWarningAlert("No folder selected!"); return; } //Ask for confirmation before proceeding ButtonType bt = displayConfirmationAlert("Before continuing, make sure you have:\n- Inserted your album covers\n- Placed your tracks inside a folder named Track"); if (bt == ButtonType.OK) { System.out.println("ButtonType.OK"); } else { System.out.println("CANCELLED"); return; } System.out.println("createFolders()"); createFolders(); System.out.println("sortTracks()"); try { sortTracks(); } catch (FileNotFoundException e) { e.printStackTrace(); displayExceptionDialog(e, e.getMessage()); return; } catch (Exception e) { e.printStackTrace(); displayExceptionDialog(e, e.getMessage()); return; } System.out.println("sortAlbumCovers()"); try { sortAlbumCovers(); } catch (IOException e) { e.printStackTrace(); displayExceptionDialog(e, "Failed to move an album cover!!"); return; } if (!itmspCheckbox.isSelected()) { createItmspPackage(); } } /** * Helper method to choose the root folder where the albums will be saved to */ @FXML void chooseFolder(ActionEvent event) { DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle("Select Folder"); String userDir = System.getProperty("user.home"); File defaultDirectory = new File(userDir + "/Desktop"); chooser.setInitialDirectory(defaultDirectory); this.selectedDirectoryPath = chooser.showDialog(new Stage()); if (selectedDirectoryPath != null) { this.folderPathTextField.setText(selectedDirectoryPath.getAbsolutePath().toString()); } } /** * Helper method to create new folders */ private void createFolders() { //For each UPC in the list create a folder Scanner scanner = new Scanner(this.upcTextArea.getText()); while (scanner.hasNextLine()) { String upc = scanner.nextLine(); //Check to make sure if the UPCs in the list are correctly formatted if (!upc.matches("[0-9]{13}")) { displayErrorMessage("UPC format error!"); return; } System.out.println("new folder: " + selectedDirectoryPath + "/" + upc); boolean success = (new File(selectedDirectoryPath + "/" + upc)).mkdirs(); if (!success) { displayErrorMessage("Error while creating a folder!"); return; } upcCount += 1; } } /** * Helper method to sort all the tracks in each folder */ private void sortTracks() throws Exception { //Store the number of songs per album into a global variable try { this.songsPerAlbum = Integer.parseInt(this.songsNumberTextField.getText()); } catch (NumberFormatException e) { throw new NumberFormatException("Enter a valid number!"); //displayExceptionDialog(e,"Enter a valid number!"); } //Keep track of tracks folder File tracksDir = new File(selectedDirectoryPath + "/tracks"); //if it doesn't exist, an error message is shown if (!tracksDir.exists()) { displayErrorMessage("tracks folder not created!!"); return; } //An array containing all the files inside the tracks folder File[] listOfTrackFiles = tracksDir.listFiles(); if (listOfTrackFiles.length <= 1) { throw new FileNotFoundException("No files in tracks folder!"); } int totalSongsPerAlbum = this.songsPerAlbum * this.upcCount; if (listOfTrackFiles.length <= totalSongsPerAlbum) { throw new Exception("Insufficient track files!!"); } //An array containing all the files and directories inside the root folder File[] listOfDir = selectedDirectoryPath.listFiles(); /*for (File f : listOfDir){ System.out.println("dir: " + f.getName()); }*/ //Create a list with an ordered list of ints up to the length of listOfTrackFiles List<Integer> indexList = new ArrayList<>(); for (int i = 0; i < listOfTrackFiles.length; i++) { indexList.add(i); } System.out.println("original indexList: " + indexList); //first file is _DS STORE!!!! for (int i = 0; i < listOfDir.length; i++) { //for each upc folder inside the root folder if (listOfDir[i].isDirectory() && listOfDir[i].getName().matches("[0-9]{13}")) { //Choose this.songsPerAlbum tracks to place inside listOfDir[i] folder for (int z = 0; z < this.songsPerAlbum; z++) { if (indexList.size() < 1) { return; } //Pick a random number between 0 and indexList's size int indexRandom = ThreadLocalRandom.current().nextInt(0, indexList.size()); System.out.println("indexRandom: " + indexRandom); //Get the element inside indexList corresponding to indexRandom index int indexRandFile = indexList.get(indexRandom); System.out.println("FILE NAME: " + listOfTrackFiles[indexRandFile]); //if the element of the listOfTrackFiles array on index: indexRandFile is file if (listOfTrackFiles[indexRandFile].isFile()) { //Move it to the listOfDir[i] folder System.out.println("MOVING TO: " + listOfDir[i].getAbsolutePath() + "/" + listOfTrackFiles[indexRandFile].getName()); try { Files.move(Paths.get(listOfTrackFiles[indexRandFile].getAbsolutePath()), Paths.get(listOfDir[i].getAbsolutePath() + "/" + listOfTrackFiles[indexRandFile].getName()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } System.out.println("File " + listOfTrackFiles[indexRandFile].getName()); } else if (listOfTrackFiles[indexRandFile].isDirectory()) { System.out.println("Directory " + listOfTrackFiles[indexRandFile].getName()); } //Remove the indexList element at index: indexRandom indexList.remove(indexRandom); System.out.println("indexList updated: " + indexList); } } } } /** * Helper method to place all the artwork inside their respective folder */ private void sortAlbumCovers() throws IOException { File[] listOfDir = selectedDirectoryPath.listFiles(); for (int i = 0; i < listOfDir.length - 1; i++) { System.out.println("listOfDir[i].getName(): " + listOfDir[i].getName()); //if listOfDir[i] is a jpeg String ext = FilenameUtils.getExtension(listOfDir[i].getName()); System.out.println("EXT: " + ext); if (ext.equals("jpg") || ext.equals("jpeg")) { if (!checkImageSize(listOfDir[i])) { displayErrorMessage("Check image size!!! Not 3000x3000"); return; } System.out.println("COVER FROM: " + listOfDir[i].getAbsolutePath()); System.out.println("COVER TO: " + selectedDirectoryPath + "/" + stripExtension(listOfDir[i].getName()).toString() + "/" + listOfDir[i].getName()); Files.move(Paths.get(listOfDir[i].getAbsolutePath()), Paths.get(selectedDirectoryPath + "/" + stripExtension(listOfDir[i].getName()).toString() + "/" + listOfDir[i].getName()), StandardCopyOption.REPLACE_EXISTING); } } } /** * Helper method to create iTunes Producer packages */ private void createItmspPackage() { File[] listOfDir = selectedDirectoryPath.listFiles(); for (int i = 0; i < listOfDir.length - 1; i++) { if (listOfDir[i].isDirectory()) { File itmspFile = new File(listOfDir[i].getAbsolutePath().concat(".itmsp")); listOfDir[i].renameTo(itmspFile); } } } /** * Helper method to check an image's size */ private boolean checkImageSize(File file) { double bytes = file.length(); System.out.println("File Size: " + String.format("%.2f", bytes / 1024) + "kb"); try { BufferedImage image = ImageIO.read(file); int width = image.getWidth(); int height = image.getHeight(); System.out.println("Width: " + width); System.out.println("Height: " + height); if (width + height < 6000) { return false; } } catch (Exception ex) { ex.printStackTrace(); } return true; } /** * Helper method to extract a file's extension */ private String stripExtension(String str) { // Handle null case specially. if (str == null) { return null; } // Get position of last '.'. int pos = str.lastIndexOf("."); // If there wasn't any '.' just return the string as is. if (pos == -1) { return str; } // Otherwise return the string, up to the dot. return str.substring(0, pos); } private void displayErrorMessage(String textMessage) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Warning!"); alert.setContentText(textMessage); alert.showAndWait(); return; } public void displayWarningAlert(String textMessage) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning!"); alert.setContentText(textMessage); alert.showAndWait(); return; } public ButtonType displayConfirmationAlert(String textMessage) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Wait!"); alert.setContentText(textMessage); alert.getResult(); alert.showAndWait(); return alert.getResult(); } private void displayExceptionDialog(Throwable ex, String exceptionMessage) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Exception Dialog"); alert.setHeaderText("Exception"); alert.setContentText(exceptionMessage); // Create expandable Exception. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); String exceptionText = sw.toString(); Label label = new Label("The exception stacktrace was:"); TextArea textArea = new TextArea(exceptionText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); GridPane expContent = new GridPane(); expContent.setMaxWidth(Double.MAX_VALUE); expContent.add(label, 0, 0); expContent.add(textArea, 0, 1); // Set expandable Exception into the dialog pane. alert.getDialogPane().setExpandableContent(expContent); alert.showAndWait(); } /** * This method displays the name and the version number of the program, * when the About item menu is clicked. */ @FXML public void aboutItemAction() { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Album Creator v1.0"); alert.setHeaderText("Album Creator v1.0\n"); alert.setContentText("1) Inserire una lista di UPC;\n" + "2) Selezionare una cartella vuota nel desktop dentro la quale saranno salvati gli album;\n" + "3) Inserire il numero di tracce per album;\n" + "4) Inserire le copertine;\n" + "5) Decidere se trasformare le cartelle in pacchetti di iTunes Producer con il relativo checkbox;\n" + "6) Procedere alla creazione dei file."); alert.showAndWait(); } }
true
ef1f9ef42cc4035d7663f2628a87d64e6cc383f1
Java
prashant2906/ePricer
/epricer-automation-master/epricer-automation-master/src/com/ibm/stax/Tests/RegressionBP/PCS_TC13_Request_VS_quote_and_distributor_approves.java
UTF-8
6,634
1.71875
2
[]
no_license
/** * @author Harsha Agarwal * */ package com.ibm.stax.Tests.RegressionBP; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.ibm.stax.BusinessLogic.Epricer_Application_CreateAQuote_BusinessLogic; import com.ibm.stax.BusinessLogic.Epricer_Application_Create_A_SBO_Quote_Incomplete_It_And_Accept_BusinessLogic; import com.ibm.stax.BusinessLogic.Epricer_Application_Duplicate_SBO_Quote_Accept_As_VS_BusinessLogic; import com.ibm.stax.BusinessLogic.Epricer_Application_UpdateAQuote_BusinessLogic; import com.ibm.stax.BusinessLogic.PCS.Epricer_Application_PCS_Login_BusinessLogic; import com.ibm.stax.BusinessLogic.PCS.Epricer_Application_PCS_NA_BusinessLogic; //import com.ibm.stax.BusinessLogic.PCS.*; import com.ibm.stax.InitialSetup.Driver_Setup; import com.ibm.stax.Reporting.Extent_Reporting; import com.ibm.stax.Utilities.ElementAction; public class PCS_TC13_Request_VS_quote_and_distributor_approves extends Driver_Setup { public WebDriver driver; ElementAction action = new ElementAction(); Epricer_Application_PCS_Login_BusinessLogic loginBusinessLogic = null; Epricer_Application_CreateAQuote_BusinessLogic createAQuoteBusinessLogic = null; Epricer_Application_UpdateAQuote_BusinessLogic updateAQuoteBusinessLogic = null; Epricer_Application_Create_A_SBO_Quote_Incomplete_It_And_Accept_BusinessLogic ePricerCreateASBOQuoteIncompleteItAndAcceptBusinessLogic= null; Epricer_Application_Create_A_SBO_Quote_Incomplete_It_And_Accept_BusinessLogic createAVSQuoteAndAcceptBusinessLogic=null; Epricer_Application_UpdateAQuote_BusinessLogic ePricerUpdateQuote = null; Epricer_Application_Duplicate_SBO_Quote_Accept_As_VS_BusinessLogic ePricerDuplicateSBOQuoteAcceptAsVSBusinessLogic=null; Epricer_Application_Duplicate_SBO_Quote_Accept_As_VS_BusinessLogic duplicateSBOQuote = null; Epricer_Application_PCS_NA_BusinessLogic PCSNABusinessLogic=null; @BeforeClass public void setUp() { System.out.println("PCS_TC13_Request_VS_quote_and_distributor_approves"); driver = getDriver(); } @Test @Parameters({"PCSURL","ENV"}) public void login_PCS(String PCSURL,String ENV) throws Throwable { try { loginBusinessLogic = new Epricer_Application_PCS_Login_BusinessLogic(driver, TC_ID,test); createAQuoteBusinessLogic = new Epricer_Application_CreateAQuote_BusinessLogic(driver, TC_ID,test); updateAQuoteBusinessLogic = new Epricer_Application_UpdateAQuote_BusinessLogic(driver, TC_ID,test); createAVSQuoteAndAcceptBusinessLogic=new Epricer_Application_Create_A_SBO_Quote_Incomplete_It_And_Accept_BusinessLogic(driver, TC_ID,test); ePricerCreateASBOQuoteIncompleteItAndAcceptBusinessLogic = new Epricer_Application_Create_A_SBO_Quote_Incomplete_It_And_Accept_BusinessLogic(driver, TC_ID,test); ePricerUpdateQuote = new Epricer_Application_UpdateAQuote_BusinessLogic(driver, TC_ID,test); ePricerDuplicateSBOQuoteAcceptAsVSBusinessLogic = new Epricer_Application_Duplicate_SBO_Quote_Accept_As_VS_BusinessLogic(driver, TC_ID,test); duplicateSBOQuote = new Epricer_Application_Duplicate_SBO_Quote_Accept_As_VS_BusinessLogic(driver, TC_ID,test); PCSNABusinessLogic = new Epricer_Application_PCS_NA_BusinessLogic(driver, TC_ID,test); //login into the screen loginBusinessLogic.epricerNavigatetoPCS(PCSURL); loginBusinessLogic.pcsloggin(); loginBusinessLogic.ibmIDPageData(ENV); Thread.sleep(10000); loginBusinessLogic.pcsENVSelect(ENV); // select group loginBusinessLogic.ePricerLoginscreen(); //create a quote and fill mandatory fields on overview page: createAQuoteBusinessLogic.createANewQuoteLinkClick(); createAQuoteBusinessLogic.overviewPolygonScreen(); createAQuoteBusinessLogic.countrybidtypeselectforEPricerOverviewScreen(); PCSNABusinessLogic.click_on_saveandcontinue(); //goto manage configuration screen and add product manually: createAQuoteBusinessLogic.manageConfigurationPolygonScreen(); createAQuoteBusinessLogic.addProductManuallyButtonClick(); createAQuoteBusinessLogic.dataForEPricerAddProductManuallyScreen(); //do collect pricing: createAQuoteBusinessLogic.collectPricingButtonClick(); createAQuoteBusinessLogic.pricingValueCheck(); //fill the registration details: createAQuoteBusinessLogic.registrationCustomerPolygon(); Thread.sleep(10000); PCSNABusinessLogic.pcs_RegistrationNumberScreen_VS(); //click on submit price request button: ePricerCreateASBOQuoteIncompleteItAndAcceptBusinessLogic.submitPriceRequestBtnClick(); PCSNABusinessLogic.quoteIdFetched(); PCSNABusinessLogic.fill_mandatory_fields_on_submitscreen(); PCSNABusinessLogic.click_on_submit_button(); //refresh the page and login with distributor profile: ePricerCreateASBOQuoteIncompleteItAndAcceptBusinessLogic.refreshPage(); loginBusinessLogic.epricerLogoScreen(); loginBusinessLogic.ePricerLoginWithDistributorProfile(); loginBusinessLogic.ePRICERMainScreen(); //Search the quote and accept value seller price: ePricerUpdateQuote.searchQuotesLinkClick(); ePricerUpdateQuote.searchCriteriaQuoteIdSelect(); PCSNABusinessLogic.searchQuoteButtonClicked(); Thread.sleep(30000); createAQuoteBusinessLogic.moveToDetailsPricing(); PCSNABusinessLogic.fill_BP_companyname(); action.waitForPageToLoad(driver); Thread.sleep(20000); createAQuoteBusinessLogic.acceptValueSellerOfferButtonClicked(); action.waitForPageToLoad(driver); //again login with SP2 profile: ePricerCreateASBOQuoteIncompleteItAndAcceptBusinessLogic.refreshPage(); loginBusinessLogic.ePricerLoginscreen(); loginBusinessLogic.ePRICERMainScreen(); //Search the quote and accept value seller price: ePricerUpdateQuote.searchQuotesLinkClick(); ePricerUpdateQuote.searchCriteriaQuoteIdSelect(); PCSNABusinessLogic.searchQuoteButtonClicked(); //verify addendum tab: //PCSNABusinessLogic.addendumTabClicked(); Extent_Reporting.Log_Pass("PCS_TC13_Request_VS_quote_and_distributor_approves Passed.", "PCS_TC13_Request_VS_quote_and_distributor_approves Passed.",test); System.out.println("completed"); } catch (Exception e) { Extent_Reporting.Log_Fail("PCS_TC13_Request_VS_quote_and_distributor_approves Failed.","PCS_TC13_Request_VS_quote_and_distributor_approves Failed.", driver,test); driver.quit(); e.printStackTrace(); throw new Exception("Failed"); } } @AfterTest public void tearDown() { driver.quit(); } }
true
68a194d81f5168939d7a678199112fc9d0aa3ec5
Java
OS-Revolution/OS-Revolution_Source
/src/ethos/phantasye/job/pay/impl/RandomPaymentModifier.java
UTF-8
477
2.40625
2
[]
no_license
package ethos.phantasye.job.pay.impl; import ethos.phantasye.job.pay.Payment; import ethos.phantasye.job.pay.PaymentDecorator; import java.util.Random; public class RandomPaymentModifier extends PaymentDecorator { private final int bound; public RandomPaymentModifier(Payment payment, int bound) { super(payment); this.bound = bound; } @Override public int make() { return super.make() + new Random().nextInt(bound); } }
true
f986436c5f1c00656e19e588fbf16e3832898dde
Java
kwonhyuksung/boardmvc
/src/com/kitri/board/controller/PictureUploadController.java
UTF-8
3,172
2.453125
2
[]
no_license
package com.kitri.board.controller; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import com.kitri.board.model.AlbumDto; import com.kitri.member.model.MemberDto; import com.kitri.util.*; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; @WebServlet("/uploadcontrol") public class PictureUploadController extends HttpServlet { private static final long serialVersionUID = 1L; private String realPath; private int maxPostSize; @Override // 한 번만 실행. public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); // /upload의 실제 경로를 얻어오고 싶어. 서버의 레알 경로 realPath = context.getRealPath("/upload"); // 5M setup maxPostSize = 5 * 1024 * 1024; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 오늘 날짜를 가진 문자열 생성 DateFormat df = new SimpleDateFormat("yyyyMMdd"); String today = df.format(new Date()); String saveDirectory = realPath + File.separator + today; File folder = new File(saveDirectory); if (!folder.exists()) { folder.mkdirs(); } MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, BoardConstance.CHARSET, new DateFileRenamePolicy()); // MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, BoardConstance.CHARSET, new DefaultFileRenamePolicy()); // 바로 위에서 이미지가 저장되었는데, 원본 사이즈의 이미지가 웹상에 모두 뿌려지면 웹이 너무 느리다. // thumnail 이미지를 만들어서 저장하는 것이 좋다. HttpSession session = request.getSession(); MemberDto memberDto = (MemberDto) session.getAttribute("userInfo"); String path = "/index.jsp"; if (memberDto != null) { AlbumDto albumDto = new AlbumDto(); albumDto.setId(memberDto.getId()); albumDto.setName(memberDto.getName()); albumDto.setEmail(memberDto.getEmailid() + "@" + memberDto.getEmaildomain()); albumDto.setSubject(multi.getParameter("subject")); albumDto.setContent(multi.getParameter("content")); albumDto.setBcode(Integer.parseInt(multi.getParameter("bcode"))); // System.out.println(multi.getParameter("subject")); albumDto.setSaveFolder(today); albumDto.setOrignPicture(multi.getOriginalFileName("picture")); albumDto.setSavePicture(multi.getFilesystemName("picture")); System.out.println(realPath); System.out.println("원본이미지이름 : " + albumDto.getOrignPicture() + "저장이미지이름 : " + albumDto.getSavePicture()); // int seq = ReboardServiceImpl.getReboardService().writeArticle(albumDto); // request.setAttribute("seq", seq); path = "/album/writeok.jsp"; } PageMove.forward(request, response, path); } }
true
e2d6de2d81744984ec16528030cadaccd876f03c
Java
harisstavrinos/cb4-Project1-Messaging
/menu/Choices.java
UTF-8
3,800
2.859375
3
[]
no_license
package menu; import java.util.Scanner; import java.util.concurrent.TimeUnit; import javax.swing.SwingUtilities; import database.DataBase; import extra.Flag; import window.EditText; import window.TextAreaGetContent; public class Choices { DataBase db=DataBase.getConnect(); public void choice1(String username) { String sndMsg[]=sendMessage(); String sender=username; String receiver=sndMsg[0]; String message=sndMsg[1]; db.sendMessage(sender,receiver, message); } public void choice2(String username){ db.viewMyMessages(username); } public void choice3(String username){ db.viewNewMessages(username); } public void choice4(String username){ db.viewAllMessages(); } public void choice5(String username) { /*System.out.println("Select one of the above choises:"); Scanner sc=new Scanner(System.in); super.setChoice(sc.nextInt());*/ int edtMes=this.edtMessage(); DataBase db=DataBase.getConnect(); String txtMessage=db.edtMessage(edtMes); EditText.text=txtMessage; Flag.setFlag(false); /////////////// JTextArea/////////////////////////////////// SwingUtilities.invokeLater(new Runnable() { public void run() { TextAreaGetContent.showFrame(); } }); System.out.println(Flag.getFlag()); System.out.println(Flag.getFlag()); /////////////////////////////////////////////////////////// while(Flag.getFlag().equals(false)){ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//waiting....; } db.edtMessage2(edtMes,EditText.getText()); System.out.println("test"); } public void choice6(String username) { //String usr,pass; DataBase db=DataBase.getConnect(); int delMes=this.deleteMessage(); db.deleteMessage(delMes); } public void choice7(String username) { String newU[]=createUser(); db.createUser(newU[0],newU[1],newU[2]); } public void choice8(String username) { //String usr,pass; String edtU[]=editUser(); db.editUser(edtU[0], edtU[1]); } public void choice9(String username) { //String usr,pass; String edtU[]=editUser(); db.editUser(edtU[0], edtU[1]); } //////////////////// public String sendMessage()[] { String sendMsg[]=new String[2]; Scanner sc=new Scanner(System.in); System.out.println("Who will be the receiver?:"); sendMsg[0]=sc.nextLine(); System.out.println("Write your message:"); sendMsg[1]=sc.nextLine(); return sendMsg; } public int edtMessage(){ int edtMes; Scanner sc=new Scanner(System.in); System.out.println("Give the ID of the message, which you want to edit:"); edtMes=sc.nextInt(); return edtMes; } public int deleteMessage(){ int delMes; Scanner sc=new Scanner(System.in); System.out.println("Give the ID of the message, which you want to delete:"); delMes=sc.nextInt(); return delMes; } public String createUser()[] { String newUser[]=new String[3]; Scanner sc=new Scanner(System.in); System.out.println("Give Username:"); newUser[0]=sc.nextLine(); System.out.println("Give Password:"); newUser[1]=sc.nextLine(); System.out.println("Give Privilege:"); newUser[2]=sc.nextLine(); return newUser; } public String delUser() { String delUser; Scanner sc=new Scanner(System.in); System.out.println("Give Username:"); delUser=sc.nextLine(); return delUser; } public String editUser()[] { String editUser[]=new String[2]; Scanner sc=new Scanner(System.in); System.out.println("Give Username:"); editUser[0]=sc.nextLine(); System.out.println("Give Privilege:"); editUser[1]=sc.nextLine(); return editUser; } }
true
e429a93b9ed0f971fe402349677ad2b218a20f5f
Java
peterhhh/DesignModelSummary
/app/src/main/java/observer_pattern/Observable.java
UTF-8
460
2.59375
3
[]
no_license
package observer_pattern; /** * @author dingbin * @date 2019/3/27 11:37 * 被观察者 */ public interface Observable { /** * 注入观察者 * @param observer */ void addObservers(Observer observer); /** * 移除 * @param observer */ void removeObservers(Observer observer); /** * 通知所有观察者更新数据 * @param objects */ void notifyDataSetChanged(String objects); }
true
23678630222bb5109a000d4fb41da0672122f877
Java
fznsakib/scotland-yard
/src/main/java/uk/ac/bris/cs/scotlandyard/ui/ai/Scoring.java
UTF-8
1,351
2.8125
3
[]
no_license
package uk.ac.bris.cs.scotlandyard.ui.ai; import uk.ac.bris.cs.scotlandyard.model.ScotlandYardPlayer; import uk.ac.bris.cs.scotlandyard.model.ScotlandYardView; import java.util.List; public abstract class Scoring { private int totalScore; private int destination; private DijkstraPath boardPath; private ScotlandYardView view; private List<GameTreePlayer> players; Scoring(ScotlandYardView view, int destination, List<GameTreePlayer> players) { this.totalScore = 0; this.destination = destination; this.view = view; this.boardPath = new DijkstraPath(destination, view); this.players = players; } // A scoring system to allow the AI to choose/prioritise the best moves available. The higher the score, the better // Sums up all the individual scores for a move that are generated according to some parameters (i.e. distance from // detectives, move eligibility of detectives to a certain location, contextual multipliers, etc) public abstract int totalScore(); // Provides a score for a move depending on how far away all the detectives are from a location. public abstract int distanceScore(); // Produces a score based on how likely it is a detective can reach a location by checking their tickets public abstract int ticketScore(); }
true
1d6e5b24d8026487f0544f72e8495370c1dc14df
Java
LambdaInnovation/HorrorFurniture
/cn/otfurniture/network/MsgInvsStateUpdate.java
UTF-8
1,026
2.296875
2
[]
no_license
/** * */ package cn.otfurniture.network; import cn.otfurniture.investigate.Investigator; import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; /** * 玩家调查状态(用于center放大镜)的更新 * @author WeAthFolD * */ public class MsgInvsStateUpdate implements IMessage { boolean canInvestigate; public MsgInvsStateUpdate(boolean b) { canInvestigate = b; } public MsgInvsStateUpdate() { } @Override public void fromBytes(ByteBuf buf) { canInvestigate = buf.readBoolean(); } @Override public void toBytes(ByteBuf buf) { buf.writeBoolean(canInvestigate); } public static class Handler implements IMessageHandler<MsgInvsStateUpdate, IMessage> { @Override public IMessage onMessage(MsgInvsStateUpdate msg, MessageContext ctx) { Investigator.INSTANCE.canInvestigate = msg.canInvestigate; return null; } } }
true
19f12a824b840804a7dd1a183f2b1136d2a3c464
Java
gayatrriiii/dsa-rep
/Basiccodes/Operators.java
UTF-8
1,130
4.3125
4
[]
no_license
import java.util.Scanner; public class Operators { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); double num1 = in.nextDouble(); System.out.print("Please enter another number: "); double num2 = in.nextDouble(); System.out.print("Please select any one operator from +, -, /, *: "); char operator = in.next().charAt(0); int result; if(operator == '+'){ result = (int) (num1 + num2); System.out.println("The addition of two numbers is: "+ result); } if(operator == '-'){ result = (int) (num1 - num2); System.out.println("The subtraction of two numbers is: "+result); } if(operator == '*') { result = (int) (num1 * num2); System.out.println("The multiplication of two numbers is: " + result); } if(operator == '/') { result = (int) (num1 / num2); System.out.println("The divison of two numbers is: " + result); } } }
true
68a67d99cf9dd86cd84b8c300b8a5e44b06dfb09
Java
joelnewcom/embeddedOracleKv
/src/main/resources/oracle-db/kv-18.1.19/src/oracle/kv/impl/admin/plan/task/VerifyBeforeMigrate.java
UTF-8
10,926
1.828125
2
[ "Apache-2.0", "Zlib", "MIT", "CC0-1.0", "FSFAP", "BSD-3-Clause" ]
permissive
/*- * Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package oracle.kv.impl.admin.plan.task; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.HashSet; import java.util.Set; import oracle.kv.KVVersion; import oracle.kv.impl.admin.Admin; import oracle.kv.impl.admin.TopologyCheck; import oracle.kv.impl.admin.TopologyCheck.JEHAInfo; import oracle.kv.impl.admin.TopologyCheck.OkayRemedy; import oracle.kv.impl.admin.TopologyCheck.Remedy; import oracle.kv.impl.admin.param.AdminParams; import oracle.kv.impl.admin.param.ArbNodeParams; import oracle.kv.impl.admin.param.Parameters; import oracle.kv.impl.admin.param.RepNodeParams; import oracle.kv.impl.admin.plan.AbstractPlan; import oracle.kv.impl.fault.OperationFaultException; import oracle.kv.impl.sna.StorageNodeAgentAPI; import oracle.kv.impl.topo.AdminId; import oracle.kv.impl.topo.ArbNodeId; import oracle.kv.impl.topo.RepNodeId; import oracle.kv.impl.topo.StorageNodeId; import oracle.kv.impl.topo.Topology; import oracle.kv.impl.util.VersionUtil; import oracle.kv.impl.util.registry.RegistryUtils; import com.sleepycat.persist.model.Persistent; /** * Do topology verification before a MigrateSNPlan. We hope to detect any * topology inconsistencies and prevent cascading topology errors. * * Also check the version of the new SN, to prevent the inadvertent downgrade * of a RN version. */ @Persistent public class VerifyBeforeMigrate extends SingleJobTask { private static final long serialVersionUID = 1L; private AbstractPlan plan; private StorageNodeId oldSN; private StorageNodeId newSN; /* For DPL */ VerifyBeforeMigrate() { } public VerifyBeforeMigrate(AbstractPlan plan, StorageNodeId oldSN, StorageNodeId newSN) { this.plan = plan; this.oldSN = oldSN; this.newSN = newSN; } @Override protected AbstractPlan getPlan() { return plan; } @Override public boolean continuePastError() { return false; } /** * Check that the rep groups for all the RNs that are involved in the move * have quorum. If they don't, the migrate will fail. */ @Override public State doWork() throws Exception { final Admin admin = plan.getAdmin(); final Parameters params = admin.getCurrentParameters(); final Topology topo = admin.getCurrentTopology(); /* * Check that the new SN is at a version compatible with that of the * Admin. Ideally we'd check the destination SN is a version that is * greater than or equal to the source SN, but the source SN is down * and unavailable. Instead, check that the destination SN is a version * that is >= the Admin version. If the Admin is at an older version * that the source SN, this check will be too lenient. If the Admin has * is at a newer version than the source SN, this will be too * stringent. Nevertheless, it's worthwhile making the attempt. If the * check is insufficient, the migrated RNs and Admins will not come up * on the new SN, so the user will see the issue, though at a less * convenient time. */ final RegistryUtils regUtils = new RegistryUtils(topo, admin.getLoginManager()); final String errorMsg = newSN + " cannot be contacted. Please ensure " + "that it is deployed and running before attempting to migrate " + "to this storage node: "; KVVersion newVersion = null; try { final StorageNodeAgentAPI newSNA = regUtils.getStorageNodeAgent(newSN); newVersion = newSNA.ping().getKVVersion(); } catch (RemoteException | NotBoundException e) { throw new OperationFaultException(errorMsg + e); } if (VersionUtil.compareMinorVersion(KVVersion.CURRENT_VERSION, newVersion) > 0) { throw new OperationFaultException ("Cannot migrate " + oldSN + " to " + newSN + " because " + newSN + " is at older version " + newVersion + ". Please upgrade " + newSN + " to a version that is equal or greater than " + KVVersion.CURRENT_VERSION); } /* * Find all the RNs that are purported to live on either the old * SN or the newSN. We need to check both old and new because the * migration might be re-executed, and the changes might already * have been partially carried out. */ final Set<RepNodeId> hostedRNs = new HashSet<>(); for (RepNodeParams rnp : params.getRepNodeParams()) { if (rnp.getStorageNodeId().equals(oldSN) || rnp.getStorageNodeId().equals(newSN)) { hostedRNs.add(rnp.getRepNodeId()); } } HealthCheck.create(plan.getAdmin(), toString(), hostedRNs).await(); /* * Make sure that the RNs involved are consistent in their topology, * config.xml, and JE HA addresses. However, we can only check the * new SN, because the old one may very well be down. If the migrate * has never executed, this RN will still be on the old SN and there * won't be anything to check on the new SN, but we will verify the * JEHA location. */ final TopologyCheck checker = new TopologyCheck(this.toString(), plan.getLogger(), topo, params); for (RepNodeId rnId : hostedRNs) { final Remedy remedy = checker.checkLocation(admin, newSN, rnId, false, /* calledByDeployNewRN */ true /* makeRNEnabled */, null /* oldSNId */, null /* storageDirectory */); /* TODO: Consider applying the remedy instead of failing. */ if (!remedy.isOkay()) { throw new OperationFaultException (rnId + " has inconsistent location metadata. Please " + "run plan repair-topology: " + remedy); } final JEHAInfo jeHAInfo = ((OkayRemedy) remedy).getJEHAInfo(); if (jeHAInfo != null) { final StorageNodeId currentHost = jeHAInfo.getSNId(); if (!currentHost.equals(oldSN) && !currentHost.equals(newSN)) { // TODO: Run tests to see if this situation occurs, and, // if so, try moving the check into checkRNLocation throw new OperationFaultException (rnId + " has inconsistent location metadata" + " and is living on " + currentHost + " rather than " + oldSN + " or " + newSN + "Please run plan repair-topology"); } } } final Set<ArbNodeId> hostedANs = new HashSet<>(); for (ArbNodeParams anp : params.getArbNodeParams()) { if (anp.getStorageNodeId().equals(oldSN) || anp.getStorageNodeId().equals(newSN)) { hostedANs.add(anp.getArbNodeId()); } } for (ArbNodeId anId : hostedANs) { final Remedy remedy = checker.checkLocation(admin, newSN, anId, false /* calledByDeployNewRN */, true /* makeRNEnabled */, null /* oldSNId */); if (!remedy.isOkay()) { throw new OperationFaultException (anId + " has inconsistent location metadata. Please " + "run plan repair-topology : " + remedy); } final JEHAInfo jeHAInfo = ((OkayRemedy) remedy).getJEHAInfo(); if (jeHAInfo != null) { final StorageNodeId currentHost = jeHAInfo.getSNId(); if (!currentHost.equals(oldSN) && !currentHost.equals(newSN)) { // TODO: Run tests to see if this situation occurs, and, // if so, try moving the check into checkRNLocation throw new OperationFaultException (anId + " has inconsistent location metadata" + " and is living on " + currentHost + " rather than " + oldSN + " or " + newSN + "Please run plan repair-topology"); } } } AdminId adminToCheck = null; for (AdminParams ap : params.getAdminParams()) { if (ap.getStorageNodeId().equals(oldSN) || ap.getStorageNodeId().equals(newSN)) { adminToCheck = ap.getAdminId(); } } if (adminToCheck != null) { final Remedy remedy = checker.checkAdminMove(admin, adminToCheck, oldSN, newSN); /* TODO: Consider applying the remedy instead of failing. */ if (!remedy.isOkay()) { throw new OperationFaultException( adminToCheck + " has inconsistent location metadata." + " Please run plan repair-topology: " + remedy); } final JEHAInfo jeHAInfo = ((OkayRemedy) remedy).getJEHAInfo(); if (jeHAInfo != null) { final StorageNodeId currentHost = jeHAInfo.getSNId(); if (!currentHost.equals(oldSN) && !currentHost.equals(newSN)) { // TODO: Run tests to see if this situation occurs, and, // if so, try moving the check into checkRNLocation throw new OperationFaultException (adminToCheck + " has inconsistent location metadata" + " and is living on " + currentHost + " rather than " + oldSN + " or " + newSN + "Please run plan repair-topology"); } } } return Task.State.SUCCEEDED; } }
true
f89d6e17437a568566d1923183c2b7a69c5fd3cf
Java
frwck/GemsJax-2.0
/GemsJaxClient/src/org/gemsjax/shared/communication/serialisation/instantiators/experiment/ExperimentGroupDTOInstantiator.java
UTF-8
395
1.914063
2
[]
no_license
package org.gemsjax.shared.communication.serialisation.instantiators.experiment; import org.gemsjax.shared.communication.message.experiment.ExperimentGroupDTO; import org.gemsjax.shared.communication.serialisation.ObjectInstantiator; public class ExperimentGroupDTOInstantiator implements ObjectInstantiator{ @Override public Object newInstance() { return new ExperimentGroupDTO(); } }
true
5c00ae3ea82f45e18847fc16ef706a74640a5f84
Java
dongguiyan/android
/book/Book/src/main/java/tgc/edu/mcy/security/User2.java
UTF-8
528
2.4375
2
[]
no_license
package tgc.edu.mcy.security; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; public class User2 extends User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public User2(String username, String password, String name, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); this.name = name; } }
true
1ba2b1e1e5384217036070061dfc0de9d9568b21
Java
lovejing0306/Junit4
/test/com/tju/junit/TriangleTest.java
UTF-8
1,474
2.71875
3
[]
no_license
package com.tju.junit; import static org.junit.Assert.*; import org.junit.Test; public class TriangleTest { Triangle c_t=new Triangle();; @Test public void testF_triangle_one() { assertEquals(0, c_t.f_triangle(1, 2, 3)); } @Test public void testF_triangle_one_01() { assertEquals(0, c_t.f_triangle(1, 3, 2)); } @Test public void testF_triangle_one_02() { assertEquals(0, c_t.f_triangle(2, 1, 3)); } @Test public void testF_triangle_one_03() { assertEquals(0, c_t.f_triangle(2, 3, 1)); } @Test public void testF_triangle_one_04() { assertEquals(0, c_t.f_triangle(3, 1, 2)); } @Test public void testF_triangle_one_05() { assertEquals(0, c_t.f_triangle(3, 2, 1)); } @Test public void testF_triangle_two() { assertEquals(1, c_t.f_triangle(3, 3, 3)); } @Test public void testF_triangle_three() { assertEquals(2, c_t.f_triangle(2, 3, 3)); } @Test public void testF_triangle_three_01() { assertEquals(2, c_t.f_triangle(2, 2, 3)); } @Test public void testF_triangle_three_02() { assertEquals(2, c_t.f_triangle(3, 2, 3)); } @Test public void testF_triangle_four() { assertEquals(3, c_t.f_triangle(3, 4, 5)); } @Test public void testF_triangle_four_01() { assertEquals(3, c_t.f_triangle(3, 5, 4)); } @Test public void testF_triangle_four_02() { assertEquals(3, c_t.f_triangle(4, 3, 5)); } @Test public void testF_triangle_four_03() { assertEquals(3, c_t.f_triangle(4, 5, 3)); } }
true
d8dfdd979a543e4e213a1f71b33cbede4d5fce1d
Java
williamhenry94/OOAD
/chapter10/Test16.java
UTF-8
659
2.40625
2
[]
no_license
package chapter10; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import org.junit.AfterClass; import org.junit.Test; public class Test16 { @Test public void test() { try { SubwayLoader loader = new SubwayLoader(); Subway objectville = loader.loadFromFile(new File("C:/william/workspace/Subway/src/chapter10/ObjectvilleSubway.txt")); loader.brokeStation("Infinite Circle"); Station station=objectville.getStation("Infinite Circle"); assertEquals(false, station.getStatus()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
40a493f543d00a23b9f9f2fd9233674d3c54859e
Java
yuzhicheng/ace
/src/main/java/com/yzc/dao/impl/PaintAuthorDaoImpl.java
UTF-8
7,461
2.1875
2
[]
no_license
package com.yzc.dao.impl; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import com.yzc.dao.PaintAuthorDao; import com.yzc.entity.PaintAuthor; import com.yzc.exception.repositoryException.EspStoreException; import com.yzc.repository.PaintAuthorRepository; import com.yzc.repository.index.AdaptQueryRequest; import com.yzc.repository.index.Hits; import com.yzc.repository.index.QueryResponse; import com.yzc.support.ErrorMessageMapper; import com.yzc.support.MessageException; import com.yzc.utils.CollectionUtils; import com.yzc.utils.ObjectUtils; import com.yzc.utils.ParamCheckUtil; import com.yzc.utils.StringUtils; import com.yzc.vos.ListViewModel; @Repository public class PaintAuthorDaoImpl implements PaintAuthorDao { private static final Logger LOG = LoggerFactory.getLogger(PaintAuthorDaoImpl.class); @Autowired private PaintAuthorRepository paintAuthorRepository; @Qualifier(value = "jdbcTemplate") @Autowired private JdbcTemplate defaultJdbcTemplate; @Override public PaintAuthor savePaintAuthor(PaintAuthor paintAuthor) { try { return paintAuthorRepository.add(paintAuthor); } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public PaintAuthor updatePaintAuthor(PaintAuthor paintAuthor) { try { return paintAuthorRepository.update(paintAuthor); } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public void deletePaintAuthor(String id) { try { paintAuthorRepository.del(id); } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public PaintAuthor getPaintAuthor(String id) { try { return paintAuthorRepository.get(id); } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public ListViewModel<PaintAuthor> queryPaintAuthorList(String authorName, String limit) { ListViewModel<PaintAuthor> returnValue = new ListViewModel<PaintAuthor>(); returnValue.setLimit(limit); try { AdaptQueryRequest<PaintAuthor> adaptQueryRequest = new AdaptQueryRequest<PaintAuthor>(); Integer result[] = ParamCheckUtil.checkLimit(limit); adaptQueryRequest.setOffset(result[0]); adaptQueryRequest.setLimit(result[1]); if (StringUtils.hasText(authorName)) { adaptQueryRequest.and("authorName", authorName); } QueryResponse<PaintAuthor> response = paintAuthorRepository.searchByExampleSupportLike(adaptQueryRequest); if (response != null) { Hits<PaintAuthor> hits = response.getHits(); if (hits != null) { returnValue.setTotal(hits.getTotal()); returnValue.setItems(hits.getDocs()); } } return returnValue; } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public List<PaintAuthor> batchGetPaintAuthor(List<String> ids) { try { List<PaintAuthor> uiList = paintAuthorRepository.getAll(ids); return uiList; } catch (EspStoreException e) { throw new MessageException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorMessageMapper.StoreSdkFail.getCode(), e.getLocalizedMessage()); } } @Override public List<String> getAuthorIdByNameAndNationality(String authorName, String nationality) { Map<String, Object> params = new HashMap<String, Object>(); String querySql = "select identifier as identifier from author where "; if (StringUtils.hasText(authorName)) { querySql += "author_name like :name"; params.put("name", "%" + authorName + "%"); } if (StringUtils.hasText(nationality)) { querySql += "nationality=:nat"; params.put("nat", nationality); } if (StringUtils.hasText(authorName) && StringUtils.hasText(nationality)) { querySql += "author_name like :name and nationality=:nat"; params.put("name", "%" + authorName + "%"); params.put("nat", nationality); } final List<String> userIdList = new ArrayList<String>(); NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(paintAuthorRepository.getJdbcTemple()); npjt.query(querySql, params, new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { userIdList.add(rs.getString("identifier")); return null; } }); return userIdList; } @Override public List<PaintAuthor> queryAuthorByNameAndNationality(String authorName, String nationality, String limit) { Integer result[] = ParamCheckUtil.checkLimit(limit); String sqlLimit = " LIMIT " + result[0] + "," + result[1]; final List<PaintAuthor> resultList = new ArrayList<PaintAuthor>(); String querySql = "SELECT a.identifier AS identifier,a.author_name AS author_name,a.birthdate as birthdate FROM author a WHERE a.author_name=:name and a.nationality=:nationality"+sqlLimit; Map<String, Object> params = new HashMap<String, Object>(); params.put("name", authorName); params.put("nationality", nationality); LOG.info("查询的SQL语句:" + querySql.toString()); LOG.info("查询的SQL参数:" + ObjectUtils.toJson(params)); NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(defaultJdbcTemplate); namedJdbcTemplate.query(querySql, params, new RowMapper<String>() { @Override public String mapRow(ResultSet rs, int rowNum) throws SQLException { PaintAuthor uim = new PaintAuthor(); uim.setIdentifier(rs.getString("identifier")); uim.setAuthorName(rs.getString("author_name")); uim.setBirthdate(rs.getString("birthdate")); resultList.add(uim); return null; } }); return resultList; } @Override public Long queryCountByNameAndNationality(String authorName, String nationality, String limit) { String querySql = "select count(*) as total FROM author a where a.author_name=:name and a.nationality=:nationality"; Map<String, Object> params = new HashMap<String, Object>(); params.put("name", authorName); params.put("nationality", nationality); LOG.info("查询的SQL语句:" + querySql.toString()); LOG.info("查询的SQL参数:" + ObjectUtils.toJson(params)); Query query = paintAuthorRepository.getEntityManager().createNativeQuery(querySql); if (CollectionUtils.isNotEmpty(params)) { for (String key : params.keySet()) { query.setParameter(key, params.get(key)); } } BigInteger c = (BigInteger) query.getSingleResult(); if (c != null) { return c.longValue(); } return 0L; } }
true
7bf18211c005f20c7a907c40c945bc7575d9a409
Java
moniad/Concurrency-Theory
/Lab7/src/server/MethodRequest.java
UTF-8
200
2.265625
2
[]
no_license
package server; public abstract class MethodRequest { public boolean guard() { // checks if synchronization conditions are fulfilled return false; } public void call() { } }
true
5285a150c52af4df6284f6cb9cc8f7624925d2f9
Java
xwzl/spring-security
/security-core/src/main/java/com/security/core/authorize/CoreAuthorizeConfigProvider.java
UTF-8
1,925
2.015625
2
[]
no_license
package com.security.core.authorize; import com.security.core.constant.SecurityConstants; import com.security.core.proterties.SecurityProperties; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.stereotype.Component; /** * 核心模块的授权配置提供器,安全模块涉及的url的授权配置在这里。 * * @author xuweizhi * @date 2019/06/20 0:11 */ @Component public class CoreAuthorizeConfigProvider implements AuthorizeConfigProvider { @Autowired private SecurityProperties securityProperties; @Override public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) { config.antMatchers( SecurityConstants.DEFAULT_UNAUTHENTICATION_URL, SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/*", SecurityConstants.STATIC_RESOURCES_URL, SecurityConstants.DEFAULT_SESSION_INVALID_URL, SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_OPENID, securityProperties.getBrowser().getLoginPage(), // 配置 qq 授权后的注册页面 securityProperties.getBrowser().getSignUrl(), securityProperties.getBrowser().getSignOutUrl() == null ? "404" : securityProperties.getBrowser().getSignOutUrl() ).permitAll(); if (StringUtils.isNotBlank(securityProperties.getBrowser().getSignOutUrl())) { config.antMatchers(securityProperties.getBrowser().getSignOutUrl()).permitAll(); } return false; } }
true
bc420fdecac3c975b4c246bfe3ca33c3a2a002d3
Java
Katsshura/Ze-Delivery-Challenge
/api/src/main/java/com/katsshura/zechallenge/api/viewModels/PartnerModel.java
UTF-8
640
1.648438
2
[]
no_license
package com.katsshura.zechallenge.api.viewModels; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class PartnerModel { @JsonProperty("id") private String id; @JsonProperty("tradingName") private String tradingName; @JsonProperty("ownerName") private String ownerName; @JsonProperty("document") private String document; @JsonProperty("coverageArea") private GeoInformationModel<List<List<List<double[]>>>> coverageArea; @JsonProperty("address") private GeoInformationModel<double[]> address; }
true
d08be325053746ff846212672c1c8e175ab08b3f
Java
greenstevester/flightAlert
/src/main/java/net/greensill/flightalert/repository/FlightSliceRepository.java
UTF-8
942
2.140625
2
[]
no_license
package net.greensill.flightalert.repository; import net.greensill.flightalert.domain.FlightSlice; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.Param; import java.util.List; /** * Spring Data JPA repository for the FlightSlice entity. */ public interface FlightSliceRepository extends JpaRepository<FlightSlice,Long> { @Query("select c FROM FlightSlice c where c.id=:id and c.userId =:userId") FlightSlice findOneByIdUserId( @Param("id") long id , @Param("userId") long userId ); @Query("select c FROM FlightSlice c where c.userId =:userId") List <FlightSlice> findAllByUserId( @Param("userId") long userId ); @Query("select c FROM FlightSlice c where c.userId =:userId") Page<FlightSlice> findAllByUserId( @Param("userId") long userId, Pageable pageable ); }
true
1995677cabd2cbcecc96d194ee3fadbfe28d9162
Java
rageappliedgame/AssetManager-Java
/src/java/eu/rageproject/asset/manager/IDataStorage.java
UTF-8
1,981
2.234375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 e-ucm, Universidad Complutense de Madrid * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * This project has received funding from the European Union’s Horizon * 2020 research and innovation programme under grant agreement No 644187. * 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 eu.rageproject.asset.manager; /** * Interface for data storage. * * @author Ivan Martinez-Ortiz */ public interface IDataStorage { /** * Deletes the given fileId. * * @param fileId The file identifier to delete. * * @return {@code true} if it succeeds, {@code false} otherwise. */ public boolean delete(final String fileId); /** * Checks if exits a file with <code>fileId</code> identifier. * * @param fileId The file identifier to check. * * @return {@code true} if exits, {@code false} otherwise. */ public boolean exists(final String fileId); /** * Get file identifiers stored in this storage. * * @return An array of fileIds. */ public String[] files(); /** * Loads content of the <code>fileId</code>. * * @param fileId file identifier to load. * * @return file contents or {@code null} if not exits. */ public String load(final String fileId); /** * Saves the given file. * * @param fileId file identifier to save. * @param fileData file content to save. */ public void save(final String fileId, final String fileData); }
true
28818e63b654194d5c5fcecd7657972d251a284b
Java
gmarchontes/Archore
/common/Commands.java
UTF-8
76,157
2.09375
2
[]
no_license
package common; //import game.GameServer; import game.GameThread; import game.GameServer.SaveThread; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.util.Map.Entry; import javax.swing.Timer; import common.World.ItemSet; import objects.Action; import objects.Carte; import objects.Compte; import objects.NPC_tmpl; import objects.Objet; import objects.Personnage; import objects.Carte.MountPark; import objects.HDV.HdvEntry; import objects.Metier.StatsMetier; import objects.Monstre.MobGroup; import objects.NPC_tmpl.NPC; import objects.NPC_tmpl.NPC_question; import objects.NPC_tmpl.NPC_reponse; import objects.Objet.ObjTemplate; public class Commands { Compte _compte; Personnage _perso; PrintWriter _out; // Sauvegarde private boolean _TimerStart = false; Timer _timer; private Timer createTimer(final int time) { ActionListener action = new ActionListener() { int Time = time; public void actionPerformed(ActionEvent event) { Time = Time - 1; if (Time == 1) { SocketManager.GAME_SEND_Im_PACKET_TO_ALL("115;" + Time + " minute"); } else { SocketManager.GAME_SEND_Im_PACKET_TO_ALL("115;" + Time + " minutes"); } if (Time <= 0) { for (Personnage perso : World.getOnlinePersos()) { perso.get_compte().getGameThread().kick(); } System.exit(0); } } }; // G�n�ration du repeat toutes les minutes. return new Timer(60000, action);// 60000 } public Commands(Personnage perso) { this._compte = perso.get_compte(); this._perso = perso; this._out = _compte.getGameThread().get_out(); } public void consoleCommand(String packet) { if (_compte.get_gmLvl() < 1) { _compte.getGameThread().closeSocket(); return; } String msg = packet.substring(2); String[] infos = msg.split(" "); if (infos.length == 0) return; String command = infos[0]; if (_compte.get_gmLvl() == 1) { commandGmOne(command, infos, msg); } else if (_compte.get_gmLvl() == 2) { commandGmTwo(command, infos, msg); } else if (_compte.get_gmLvl() == 3) { commandGmThree(command, infos, msg); } else if (_compte.get_gmLvl() >= 4) { commandGmFour(command, infos, msg); } } public void commandGmOne(String command, String[] infos, String msg) { if (_compte.get_gmLvl() < 1) { _compte.getGameThread().closeSocket(); return; } if (command.equalsIgnoreCase("INFOS")) { long uptime = System.currentTimeMillis() - Ancestra.gameServer.getStartTime(); int jour = (int) (uptime / (1000 * 3600 * 24)); uptime %= (1000 * 3600 * 24); int hour = (int) (uptime / (1000 * 3600)); uptime %= (1000 * 3600); int min = (int) (uptime / (1000 * 60)); uptime %= (1000 * 60); int sec = (int) (uptime / (1000)); String mess = "===========\n" + Ancestra.makeHeader() + "Uptime: " + jour + "j " + hour + "h " + min + "m " + sec + "s\n" + "Joueurs en lignes: " + Ancestra.gameServer.getPlayerNumber() + "\n" + "Record de connexion: " + Ancestra.gameServer.getMaxPlayer() + "\n" + "==========="; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("REFRESHMOBS")) { _perso.get_curCarte().refreshSpawns(); String mess = "Mob Spawn refreshed!"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("ITEM") || command.equalsIgnoreCase("!getitem")) { boolean isOffiCmd = command.equalsIgnoreCase("!getitem"); int tID = 0; try { tID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (tID == 0) { String mess = "Le template " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } int qua = 1; if (infos.length == 3)// Si une quantit� est sp�cifi�e { try { qua = Integer.parseInt(infos[2]); } catch (Exception e) { } ; } boolean useMax = false; if (infos.length == 4 && !isOffiCmd)// Si un jet est sp�cifi� { if (infos[3].equalsIgnoreCase("MAX")) useMax = true; } ObjTemplate t = World.getObjTemplate(tID); if (t == null) { String mess = "Le template " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } if (qua < 1) qua = 1; Objet obj = t.createNewItem(qua, useMax); if (_perso.addObjet(obj, true))// Si le joueur n'avait pas d'item // similaire World.addObjet(obj, true); String str = "Creation de l'item " + tID + " reussie"; if (useMax) str += " avec des stats maximums"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); SocketManager.GAME_SEND_Ow_PACKET(_perso); return; } else if (command.equalsIgnoreCase("MAPINFO")) { String mess = "==========\n" + "Liste des Npcs de la carte:"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); Carte map = _perso.get_curCarte(); for (Entry<Integer, NPC> entry : map.get_npcs().entrySet()) { mess = entry.getKey() + " " + entry.getValue().get_template().get_id() + " " + entry.getValue().get_cellID() + " " + entry.getValue().get_template().get_initQuestionID(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } mess = "Liste des groupes de monstres:"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); for (Entry<Integer, MobGroup> entry : map.getMobGroups().entrySet()) { mess = entry.getKey() + " " + entry.getValue().getCellID() + " " + entry.getValue().getAlignement() + " " + entry.getValue().getSize(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } mess = "=========="; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("WHO")) { String mess = "==========\n" + "Liste des joueurs en ligne:"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); int diff = Ancestra.gameServer.getClients().size() - 30; for (byte b = 0; b < 30; b++) { if (b == Ancestra.gameServer.getClients().size()) break; GameThread GT = Ancestra.gameServer.getClients().get(b); Personnage P = GT.getPerso(); if (P == null) continue; mess = P.get_name() + "(" + P.get_GUID() + ") "; switch (P.get_classe()) { case Constants.CLASS_FECA: mess += "Fec"; break; case Constants.CLASS_OSAMODAS: mess += "Osa"; break; case Constants.CLASS_ENUTROF: mess += "Enu"; break; case Constants.CLASS_SRAM: mess += "Sra"; break; case Constants.CLASS_XELOR: mess += "Xel"; break; case Constants.CLASS_ECAFLIP: mess += "Eca"; break; case Constants.CLASS_ENIRIPSA: mess += "Eni"; break; case Constants.CLASS_IOP: mess += "Iop"; break; case Constants.CLASS_CRA: mess += "Cra"; break; case Constants.CLASS_SADIDA: mess += "Sad"; break; case Constants.CLASS_SACRIEUR: mess += "Sac"; break; case Constants.CLASS_PANDAWA: mess += "Pan"; break; default: mess += "Unk"; } mess += " "; mess += (P.get_sexe() == 0 ? "M" : "F") + " "; mess += P.get_lvl() + " "; mess += P.get_curCarte().get_id() + "(" + P.get_curCarte().getX() + "/" + P.get_curCarte().getY() + ") "; mess += P.get_fight() == null ? "" : "Combat "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } if (diff > 0) { mess = "Et " + diff + " autres personnages"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } mess = "==========\n"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("SHOWFIGHTPOS")) { String mess = "Liste des StartCell [teamID][cellID]:"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); String places = _perso.get_curCarte().get_placesStr(); if (places.indexOf('|') == -1 || places.length() < 2) { mess = "Les places n'ont pas ete definies"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } String team0 = "", team1 = ""; String[] p = places.split("\\|"); try { team0 = p[0]; } catch (Exception e) { } ; try { team1 = p[1]; } catch (Exception e) { } ; mess = "Team 0:\n"; for (int a = 0; a <= team0.length() - 2; a += 2) { String code = team0.substring(a, a + 2); mess += CryptManager.cellCode_To_ID(code); } SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); mess = "Team 1:\n"; for (int a = 0; a <= team1.length() - 2; a += 2) { String code = team1.substring(a, a + 2); mess += CryptManager.cellCode_To_ID(code) + " , "; } SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("CREATEGUILD")) { Personnage perso = _perso; if (infos.length > 1) { perso = World.getPersoByName(infos[1]); } if (perso == null) { String mess = "Le personnage n'existe pas."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } if (!perso.isOnline()) { String mess = "Le personnage " + perso.get_name() + " n'etait pas connecte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } if (perso.get_guild() != null || perso.getGuildMember() != null) { String mess = "Le personnage " + perso.get_name() + " a deja une guilde"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } SocketManager.GAME_SEND_gn_PACKET(perso); String mess = perso.get_name() + ": Panneau de creation de guilde ouvert"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("TOOGLEAGGRO")) { Personnage perso = _perso; String name = null; try { name = infos[1]; } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null) { String mess = "Le personnage n'existe pas."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } perso.set_canAggro(!perso.canAggro()); String mess = perso.get_name(); if (perso.canAggro()) mess += " peut maintenant etre aggresser"; else mess += " ne peut plus etre agresser"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); if (!perso.isOnline()) { mess = "(Le personnage " + perso.get_name() + " n'etait pas connecte)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } } else if (command.equalsIgnoreCase("ANNOUNCE")) { infos = msg.split(" ", 2); SocketManager.GAME_SEND_MESSAGE_TO_ALL(infos[1], Ancestra.CONFIG_MOTD_COLOR); return; } else if (command.equalsIgnoreCase("MORPH")) { int morphID = -1; try { morphID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (morphID == -1) { String str = "MorphID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.set_gfxID(morphID); SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(target.get_curCarte(), target.get_GUID()); SocketManager.GAME_SEND_ADD_PLAYER_TO_MAP(target.get_curCarte(), target); String str = "Le joueur a ete transforme"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("DEMORPH")) { Personnage target = _perso; if (infos.length > 1)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[1]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } int morphID = target.get_classe() * 10 + target.get_sexe(); target.set_gfxID(morphID); SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(target.get_curCarte(), target.get_GUID()); SocketManager.GAME_SEND_ADD_PLAYER_TO_MAP(target.get_curCarte(), target); String str = "Le joueur a ete transforme"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("GONAME") || command.equalsIgnoreCase("JOIN")) { Personnage P = World.getPersoByName(infos[1]); if (P == null) { String str = "Le personnage n'existe pas"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } short mapID = P.get_curCarte().get_id(); int cellID = P.get_curCell().getID(); Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (target.get_fight() != null) { String str = "La cible est en combat"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.teleport(mapID, cellID); String str = "Le joueur a ete teleporte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("NAMEGO")) { Personnage target = World.getPersoByName(infos[1]); if (target == null) { String str = "Le personnage n'existe pas"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (target.get_fight() != null) { String str = "La cible est en combat"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage P = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { P = World.getPersoByName(infos[2]); if (P == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } if (P.isOnline()) { short mapID = P.get_curCarte().get_id(); int cellID = P.get_curCell().getID(); target.teleport(mapID, cellID); String str = "Le joueur a ete teleporte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else { String str = "Le joueur n'est pas en ligne"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } } else if (command.equalsIgnoreCase("NAMEANNOUNCE")) { infos = msg.split(" ", 2); String prefix = "[" + _perso.get_name() + "]"; SocketManager.GAME_SEND_MESSAGE_TO_ALL(prefix + infos[1], Ancestra.CONFIG_MOTD_COLOR); return; } else if (command.equalsIgnoreCase("TELEPORT")) { short mapID = -1; int cellID = -1; try { mapID = Short.parseShort(infos[1]); cellID = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (mapID == -1 || cellID == -1 || World.getCarte(mapID) == null) { String str = "MapID ou cellID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (World.getCarte(mapID).getCase(cellID) == null) { String str = "MapID ou cellID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 3)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[3]); if (target == null || target.get_fight() != null) { String str = "Le personnage n'a pas ete trouve ou est en combat"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.teleport(mapID, cellID); String str = "Le joueur a ete teleporte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("GOMAP")) { int mapX = 0; int mapY = 0; int cellID = 311; int contID = 0;// Par d�faut Amakna try { mapX = Integer.parseInt(infos[1]); mapY = Integer.parseInt(infos[2]); cellID = Integer.parseInt(infos[3]); contID = Integer.parseInt(infos[4]); } catch (Exception e) { } ; Carte map = World.getCarteByPosAndCont(mapX, mapY, contID); if (map == null) { String str = "Position ou continent invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (map.getCase(cellID) == null) { String str = "CellID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 5)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[5]); if (target == null || target.get_fight() != null) { String str = "Le personnage n'a pas ete trouve ou est en combat"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (target.get_fight() != null) { String str = "La cible est en combat"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.teleport(map.get_id(), cellID); String str = "Le joueur a ete teleporte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("MUTE")) { Personnage perso = _perso; String name = null; try { name = infos[1]; } catch (Exception e) { } ; int time = 0; try { time = Integer.parseInt(infos[2]); } catch (Exception e) { } ; String cause = null; try { cause = infos[3]; } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null || time < 0) { String mess = "Le personnage n'existe pas ou la dur&e est invalide."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } Personnage P = World.getPersoByName(infos[1]); SocketManager.GAME_SEND_MESSAGE_TO_ALL( "Le joueur <b>" + P.get_name() + "</b> vient d'être <b>muté</b> (<b>" + time + "</b> secondes) par <b>" + _perso.get_name() + "</b> pour " + cause + "", Ancestra.CONFIG_MOTD_COLOR); String mess = "Vous avez mute " + perso.get_name() + " pour " + time + " secondes"; if (perso.get_compte() == null) { mess = "(Le personnage " + perso.get_name() + " n'�tait pas connect�)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } perso.get_compte().mute(true, time); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); if (!perso.isOnline()) { mess = "(Le personnage " + perso.get_name() + " n'�tait pas connect�)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "1124;" + time); } return; } else if (command.equalsIgnoreCase("UNMUTE")) { Personnage perso = _perso; String name = null; try { name = infos[1]; } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null) { String mess = "Le personnage n'�xiste pas."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } perso.get_compte().mute(false, 0); String mess = "Vous avez unmute " + perso.get_name(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); if (!perso.isOnline()) { mess = "(Le personnage " + perso.get_name() + " n'�tait pas connect�)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } return; } else if (command.equalsIgnoreCase("SIZE")) { int size = -1; try { size = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (size == -1) { String str = "Taille invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.set_size(size); SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(target.get_curCarte(), target.get_GUID()); SocketManager.GAME_SEND_ADD_PLAYER_TO_MAP(target.get_curCarte(), target); String str = "La taille du joueur a �t� modifi�e"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("LEVEL")) { int count = 0; try { count = Integer.parseInt(infos[1]); if (count < 1) count = 1; if (count > World.getExpLevelSize()) count = World.getExpLevelSize(); Personnage perso = _perso; if (infos.length == 3)// Si le nom du perso est sp�cifi� { String name = infos[2]; perso = World.getPersoByName(name); if (perso == null) perso = _perso; } if (perso.get_lvl() < count) { while (perso.get_lvl() < count) { perso.levelUp(false, true); } if (perso.isOnline()) { SocketManager.GAME_SEND_SPELL_LIST(perso); SocketManager.GAME_SEND_NEW_LVL_PACKET(perso .get_compte().getGameThread().get_out(), perso.get_lvl()); SocketManager.GAME_SEND_STATS_PACKET(perso); } } String mess = "Vous avez fixer le niveau de " + perso.get_name() + " a " + count; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } catch (Exception e) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Valeur incorecte"); return; } ; return; } else if (command.equalsIgnoreCase("KAMAS")) { int count = 0; try { count = Integer.parseInt(infos[1]); } catch (Exception e) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Valeur incorecte"); return; } ; if (count == 0) return; Personnage perso = _perso; if (infos.length == 3)// Si le nom du perso est sp�cifi� { String name = infos[2]; perso = World.getPersoByName(name); if (perso == null) perso = _perso; } long curKamas = perso.get_kamas(); long newKamas = curKamas + count; if (newKamas < 0) newKamas = 0; if (newKamas > 1000000000) newKamas = 1000000000; perso.set_kamas(newKamas); if (perso.isOnline()) SocketManager.GAME_SEND_STATS_PACKET(perso); String mess = "Vous avez "; mess += (count < 0 ? "retirer" : "ajouter") + " "; mess += Math.abs(count) + " kamas a " + perso.get_name(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("SPELLPOINT")) { int pts = -1; try { pts = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (pts == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.addSpellPoint(pts); SocketManager.GAME_SEND_STATS_PACKET(target); String str = "Le nombre de point de sort a �t� modifi�e"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("LEARNSPELL")) { int spell = -1; try { spell = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (spell == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.learnSpell(spell, 1, true, true); String str = "Le sort a ete appris"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("SETALIGN")) { byte align = -1; try { align = Byte.parseByte(infos[1]); } catch (Exception e) { } ; if (align < Constants.ALIGNEMENT_NEUTRE || align > Constants.ALIGNEMENT_MERCENAIRE) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.modifAlignement(align); String str = "L'alignement du joueur a �t� modifi�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("HONOR")) { int honor = 0; try { honor = Integer.parseInt(infos[1]); } catch (Exception e) { } ; Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } String str = "Vous avez ajouter " + honor + " honneur a " + target.get_name(); if (target.get_align() == Constants.ALIGNEMENT_NEUTRE) { str = "Le joueur est neutre ..."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } target.addHonor(honor); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("CAPITAL")) { int pts = -1; try { pts = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (pts == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.addCapital(pts); SocketManager.GAME_SEND_STATS_PACKET(target); String str = "Le capital a �t� modifi�e"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("ITEMSET")) { int tID = 0; try { tID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; ItemSet IS = World.getItemSet(tID); if (tID == 0 || IS == null) { String mess = "La panoplie " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } boolean useMax = false; if (infos.length == 3) useMax = infos[2].equals("MAX");// Si un jet est sp�cifi� for (ObjTemplate t : IS.getItemTemplates()) { Objet obj = t.createNewItem(1, useMax); if (_perso.addObjet(obj, true))// Si le joueur n'avait pas // d'item similaire World.addObjet(obj, true); } String str = "Creation de la panoplie " + tID + " reussie"; if (useMax) str += " avec des stats maximums"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("DOACTION")) { // DOACTION NAME TYPE ARGS COND if (infos.length < 4) { String mess = "Nombre d'argument de la commande incorect !"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } int type = -100; String args = "", cond = ""; Personnage perso = _perso; try { perso = World.getPersoByName(infos[1]); if (perso == null) perso = _perso; type = Integer.parseInt(infos[2]); args = infos[3]; if (infos.length > 4) cond = infos[4]; } catch (Exception e) { String mess = "Arguments de la commande incorect !"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } (new Action(type, args, cond)).apply(perso, null, -1, -1); String mess = "Action effectuee !"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else { String mess = "Commande non reconnue"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } } public void commandGmTwo(String command, String[] infos, String msg) { if (_compte.get_gmLvl() < 2) { _compte.getGameThread().closeSocket(); return; } if (command.equalsIgnoreCase("MUTE")) { Personnage perso = _perso; String name = null; try { name = infos[1]; } catch (Exception e) { } ; int time = 0; try { time = Integer.parseInt(infos[2]); } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null || time < 0) { String mess = "Le personnage n'existe pas ou la duree est invalide."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } String mess = "Vous avez mute " + perso.get_name() + " pour " + time + " secondes"; if (perso.get_compte() == null) { mess = "(Le personnage " + perso.get_name() + " n'etait pas connecte)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } perso.get_compte().mute(true, time); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); if (!perso.isOnline()) { mess = "(Le personnage " + perso.get_name() + " n'etait pas connecte)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "1124;" + time); } return; } else if (command.equalsIgnoreCase("UNMUTE")) { Personnage perso = _perso; String name = null; try { name = infos[1]; } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null) { String mess = "Le personnage n'existe pas."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } perso.get_compte().mute(false, 0); String mess = "Vous avez unmute " + perso.get_name(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); if (!perso.isOnline()) { mess = "(Le personnage " + perso.get_name() + " n'etait pas connecte)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } } else if (command.equalsIgnoreCase("KICK")) { Personnage perso = _perso; String name = null; String razon = ""; try { name = infos[1]; } catch (Exception e) { } ; try { razon = msg .substring(infos[0].length() + infos[1].length() + 1); } catch (Exception e) { } ; perso = World.getPersoByName(name); if (perso == null) { String mess = "Le personnage n'�xiste pas."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } if (perso.isOnline()) { Personnage P = World.getPersoByName(infos[1]); if (razon != "") { String msj = "Vous viens d'�tre expuls� pour cette raison:\n" + razon + "\n\n" + _perso.get_name(); SocketManager.SEND_MESSAGE_DECO(P, 18, msj); } else { String msj = "Vous viens d'�tre expuls�.\n" + _perso.get_name(); SocketManager.SEND_MESSAGE_DECO(P, 18, msj); } SocketManager.GAME_SEND_MESSAGE_TO_ALL( "Le joueur <b>" + P.get_name() + "</b> vient d'�tre kick par <b>" + _perso.get_name() + "</b> pour " + razon + ".", Ancestra.CONFIG_MOTD_COLOR); P.get_compte().getGameThread().kick(); String mess = "Vous avez kick " + perso.get_name(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else { String mess = "Le personnage " + perso.get_name() + " n'est pas connect�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } return; } else if (command.equalsIgnoreCase("SPELLPOINT")) { int pts = -1; try { pts = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (pts == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.addSpellPoint(pts); SocketManager.GAME_SEND_STATS_PACKET(target); String str = "Le nombre de point de sort a ete modifiee"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("LEARNSPELL")) { int spell = -1; try { spell = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (spell == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.learnSpell(spell, 1, true, true); String str = "Le sort a ete appris"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("SETALIGN")) { byte align = -1; try { align = Byte.parseByte(infos[1]); } catch (Exception e) { } ; if (align < Constants.ALIGNEMENT_NEUTRE || align > Constants.ALIGNEMENT_MERCENAIRE) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.modifAlignement(align); String str = "L'alignement du joueur a ete modifie"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("SETREPONSES")) { if (infos.length < 3) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Il manque un/des arguments"); return; } int id = 0; try { id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; String reps = infos[2]; NPC_question Q = World.getNPCQuestion(id); String str = ""; if (id == 0 || Q == null) { str = "QuestionID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Q.setReponses(reps); boolean a = SQLManager.UPDATE_NPCREPONSES(id, reps); str = "Liste des reponses pour la question " + id + ": " + Q.getReponses(); if (a) str += "(sauvegarde dans la BDD)"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("SHOWREPONSES")) { int id = 0; try { id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; NPC_question Q = World.getNPCQuestion(id); String str = ""; if (id == 0 || Q == null) { str = "QuestionID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } str = "Liste des reponses pour la question " + id + ": " + Q.getReponses(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("HONOR")) { int honor = 0; try { honor = Integer.parseInt(infos[1]); } catch (Exception e) { } ; Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } String str = "Vous avez ajouter " + honor + " honneur a " + target.get_name(); if (target.get_align() == Constants.ALIGNEMENT_NEUTRE) { str = "Le joueur est neutre ..."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } target.addHonor(honor); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("ADDJOBXP")) { int job = -1; int xp = -1; try { job = Integer.parseInt(infos[1]); xp = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (job == -1 || xp < 0) { String str = "Valeurs invalides"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 3)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[3]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } StatsMetier SM = target.getMetierByID(job); if (SM == null) { String str = "Le joueur ne connais pas le metier demande"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } SM.addXp(target, xp); String str = "Le metier a ete experimenter"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("LEARNJOB")) { int job = -1; try { job = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (job == -1 || World.getMetier(job) == null) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.learnJob(World.getMetier(job)); String str = "Le metier a ete appris"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("CAPITAL")) { int pts = -1; try { pts = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (pts == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.addCapital(pts); SocketManager.GAME_SEND_STATS_PACKET(target); String str = "Le capital a ete modifiee"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } if (command.equalsIgnoreCase("SIZE")) { int size = -1; try { size = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (size == -1) { String str = "Taille invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.set_size(size); SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(target.get_curCarte(), target.get_GUID()); SocketManager.GAME_SEND_ADD_PLAYER_TO_MAP(target.get_curCarte(), target); String str = "La taille du joueur a ete modifiee"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("MORPH")) { int morphID = -1; try { morphID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (morphID == -1) { String str = "MorphID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.set_gfxID(morphID); SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(target.get_curCarte(), target.get_GUID()); SocketManager.GAME_SEND_ADD_PLAYER_TO_MAP(target.get_curCarte(), target); String str = "Le joueur a ete transforme"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } if (command.equalsIgnoreCase("MOVENPC")) { int id = 0; try { id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; NPC npc = _perso.get_curCarte().getNPC(id); if (id == 0 || npc == null) { String str = "Npc GUID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } int exC = npc.get_cellID(); // on l'efface de la map SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(_perso.get_curCarte(), id); // on change sa position/orientation npc.setCellID(_perso.get_curCell().getID()); npc.setOrientation((byte) _perso.get_orientation()); // on envoie la modif SocketManager.GAME_SEND_ADD_NPC_TO_MAP(_perso.get_curCarte(), npc); String str = "Le PNJ a ete deplace"; if (_perso.get_orientation() == 0 || _perso.get_orientation() == 2 || _perso.get_orientation() == 4 || _perso.get_orientation() == 6) str += " mais est devenu invisible (orientation diagonale invalide)."; if (SQLManager.DELETE_NPC_ON_MAP(_perso.get_curCarte().get_id(), exC) && SQLManager.ADD_NPC_ON_MAP( _perso.get_curCarte().get_id(), npc.get_template() .get_id(), _perso.get_curCell().getID(), _perso.get_orientation())) SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); else SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Erreur au moment de sauvegarder la position"); } else if (command.equalsIgnoreCase("ITEMSET")) { int tID = 0; String nom = null; try { if (infos.length > 3) nom = infos[3]; else if (infos.length > 1) tID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; ItemSet IS = World.getItemSet(tID); if (tID == 0 || IS == null) { String mess = "La panoplie " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } boolean useMax = false; if (infos.length > 2) useMax = infos[2].equals("MAX");// Si un jet est sp�cifi� Personnage perso = _perso; if (nom != null) try { perso = World.getPersoByName(nom); } catch (Exception e) { } for (ObjTemplate t : IS.getItemTemplates()) { Objet obj = t.createNewItem(1, useMax); if (perso != null) { if (perso.addObjet(obj, true))// Si le joueur n'avait pas // d'item similaire World.addObjet(obj, true); } else if (_perso.addObjet(obj, true))// Si le joueur n'avait // pas d'item similaire World.addObjet(obj, true); } String str = "Creation de la panoplie " + tID + " reussie"; if (useMax) str += " avec des stats maximums"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("LEVEL")) { int count = 0; try { count = Integer.parseInt(infos[1]); if (count < 1) count = 1; if (count > World.getExpLevelSize()) count = World.getExpLevelSize(); Personnage perso = _perso; if (infos.length == 3)// Si le nom du perso est sp�cifi� { String name = infos[2]; perso = World.getPersoByName(name); if (perso == null) perso = _perso; } if (perso.get_lvl() < count) { while (perso.get_lvl() < count) { perso.levelUp(false, true); } if (perso.isOnline()) { SocketManager.GAME_SEND_SPELL_LIST(perso); SocketManager.GAME_SEND_NEW_LVL_PACKET(perso .get_compte().getGameThread().get_out(), perso.get_lvl()); SocketManager.GAME_SEND_STATS_PACKET(perso); } } String mess = "Vous avez fixer le niveau de " + perso.get_name() + " a " + count; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } catch (Exception e) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Valeur incorecte"); return; } ; } else if (command.equalsIgnoreCase("PDVPER")) { int count = 0; try { count = Integer.parseInt(infos[1]); if (count < 0) count = 0; if (count > 100) count = 100; Personnage perso = _perso; if (infos.length == 3)// Si le nom du perso est sp�cifi� { String name = infos[2]; perso = World.getPersoByName(name); if (perso == null) perso = _perso; } int newPDV = perso.get_PDVMAX() * count / 100; perso.set_PDV(newPDV); if (perso.isOnline()) SocketManager.GAME_SEND_STATS_PACKET(perso); String mess = "Vous avez fixer le pourcentage de pdv de " + perso.get_name() + " a " + count; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } catch (Exception e) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Valeur incorecte"); return; } ; } else if (command.equalsIgnoreCase("KAMAS")) { int count = 0; try { count = Integer.parseInt(infos[1]); } catch (Exception e) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Valeur incorecte"); return; } ; if (count == 0) return; Personnage perso = _perso; if (infos.length == 3)// Si le nom du perso est sp�cifi� { String name = infos[2]; perso = World.getPersoByName(name); if (perso == null) perso = _perso; } long curKamas = perso.get_kamas(); long newKamas = curKamas + count; if (newKamas < 0) newKamas = 0; if (newKamas > 1000000000) newKamas = 1000000000; perso.set_kamas(newKamas); if (perso.isOnline()) SocketManager.GAME_SEND_STATS_PACKET(perso); String mess = "Vous avez "; mess += (count < 0 ? "retirer" : "ajouter") + " "; mess += Math.abs(count) + " kamas a " + perso.get_name(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else if (command.equalsIgnoreCase("ITEM") || command.equalsIgnoreCase("!getitem")) { boolean isOffiCmd = command.equalsIgnoreCase("!getitem"); if (_compte.get_gmLvl() < 2) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Vous n'avez pas le niveau MJ requis"); return; } int tID = 0; try { tID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (tID == 0) { String mess = "Le template " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } int qua = 1; if (infos.length == 3)// Si une quantit� est sp�cifi�e { try { qua = Integer.parseInt(infos[2]); } catch (Exception e) { } ; } boolean useMax = false; if (infos.length == 4 && !isOffiCmd)// Si un jet est sp�cifi� { if (infos[3].equalsIgnoreCase("MAX")) useMax = true; } ObjTemplate t = World.getObjTemplate(tID); if (t == null) { String mess = "Le template " + tID + " n'existe pas "; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } if (qua < 1) qua = 1; Objet obj = t.createNewItem(qua, useMax); if (_perso.addObjet(obj, true))// Si le joueur n'avait pas d'item // similaire World.addObjet(obj, true); String str = "Creation de l'item " + tID + " reussie"; if (useMax) str += " avec des stats maximums"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); SocketManager.GAME_SEND_Ow_PACKET(_perso); } else if (command.equalsIgnoreCase("SPAWN")) { String Mob = null; try { Mob = infos[1]; } catch (Exception e) { } ; if (Mob == null) return; _perso.get_curCarte().spawnGroupOnCommand( _perso.get_curCell().getID(), Mob); } else if (command.equalsIgnoreCase("TITLE")) { Personnage target = null; byte TitleID = 0; try { target = World.getPersoByName(infos[1]); TitleID = Byte.parseByte(infos[2]); } catch (Exception e) { } ; if (target == null) { String str = "Le personnage n'a pas ete trouve"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } target.set_title(TitleID); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Titre mis en place."); SQLManager.SAVE_PERSONNAGE(target, false); if (target.get_fight() == null) SocketManager.GAME_SEND_ALTER_GM_PACKET(target.get_curCarte(), target); } else { this.commandGmOne(command, infos, msg); } } public void commandGmThree(String command, String[] infos, String msg) { if (_compte.get_gmLvl() < 3) { _compte.getGameThread().closeSocket(); return; } if (command.equalsIgnoreCase("EXIT")) { System.exit(0); } else /* * if (command.equalsIgnoreCase("NEWTICALLFIGHTERSTURNS")) { * Ancestra._passerTours = new Thread(new GameServer.AllFightsTurns()); * Ancestra._passerTours.start(); * SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Ok."); } else */ if (command.equalsIgnoreCase("SAVE") && !Ancestra.isSaving) { Thread t = new Thread(new SaveThread()); t.start(); String mess = "Sauvegarde lancee!"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("GETCOORD")) { int cell = _perso.get_curCell().getID(); String mess = "[" + Pathfinding.getCellXCoord(_perso.get_curCarte(), cell) + "," + Pathfinding.getCellYCoord(_perso.get_curCarte(), cell) + "]"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("DELFIGHTPOS")) { int cell = -1; try { cell = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (cell < 0 || _perso.get_curCarte().getCase(cell) == null) { cell = _perso.get_curCell().getID(); } String places = _perso.get_curCarte().get_placesStr(); String[] p = places.split("\\|"); String newPlaces = ""; String team0 = "", team1 = ""; try { team0 = p[0]; } catch (Exception e) { } ; try { team1 = p[1]; } catch (Exception e) { } ; for (int a = 0; a <= team0.length() - 2; a += 2) { String c = p[0].substring(a, a + 2); if (cell == CryptManager.cellCode_To_ID(c)) continue; newPlaces += c; } newPlaces += "|"; for (int a = 0; a <= team1.length() - 2; a += 2) { String c = p[1].substring(a, a + 2); if (cell == CryptManager.cellCode_To_ID(c)) continue; newPlaces += c; } _perso.get_curCarte().setPlaces(newPlaces); if (!SQLManager.SAVE_MAP_DATA(_perso.get_curCarte())) return; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Les places ont ete modifiees (" + newPlaces + ")"); return; } else if (command.equalsIgnoreCase("BAN")) { Personnage P = World.getPersoByName(infos[1]); String cause = infos[2]; if (P == null) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Personnage non trouve"); return; } if (P.get_compte() == null) SQLManager.LOAD_ACCOUNT_BY_GUID(P.getAccID()); if (P.get_compte() == null) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Erreur"); return; } P.get_compte().setBanned(true); SQLManager.UPDATE_ACCOUNT_DATA(P.get_compte()); if (P.get_compte().getGameThread() != null) P.get_compte().getGameThread().kick(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Vous avez banni " + P.get_name()); SocketManager.GAME_SEND_MESSAGE_TO_ALL("Le joueur " + P.get_name() + " a �t� banni pour " + cause + "", Ancestra.CONFIG_MOTD_COLOR); return; } else if (command.equalsIgnoreCase("UNBAN")) { Personnage P = World.getPersoByName(infos[1]); if (P == null) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Personnage non trouve"); return; } if (P.get_compte() == null) SQLManager.LOAD_ACCOUNT_BY_GUID(P.getAccID()); if (P.get_compte() == null) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Erreur"); return; } P.get_compte().setBanned(false); SQLManager.UPDATE_ACCOUNT_DATA(P.get_compte()); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Vous avez debanni " + P.get_name()); return; } else if (command.equalsIgnoreCase("ADDFIGHTPOS")) { int team = -1; int cell = -1; try { team = Integer.parseInt(infos[1]); cell = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (team < 0 || team > 1) { String str = "Team ou cellID incorects"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (cell < 0 || _perso.get_curCarte().getCase(cell) == null || !_perso.get_curCarte().getCase(cell).isWalkable(true)) { cell = _perso.get_curCell().getID(); } String places = _perso.get_curCarte().get_placesStr(); String[] p = places.split("\\|"); boolean already = false; String team0 = "", team1 = ""; try { team0 = p[0]; } catch (Exception e) { } ; try { team1 = p[1]; } catch (Exception e) { } ; // Si case d�j� utilis�e System.out.println("0 => " + team0 + "\n1 =>" + team1 + "\nCell: " + CryptManager.cellID_To_Code(cell)); for (int a = 0; a <= team0.length() - 2; a += 2) if (cell == CryptManager.cellCode_To_ID(team0.substring(a, a + 2))) already = true; for (int a = 0; a <= team1.length() - 2; a += 2) if (cell == CryptManager.cellCode_To_ID(team1.substring(a, a + 2))) already = true; if (already) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "La case est deja dans la liste"); return; } if (team == 0) team0 += CryptManager.cellID_To_Code(cell); else if (team == 1) team1 += CryptManager.cellID_To_Code(cell); String newPlaces = team0 + "|" + team1; _perso.get_curCarte().setPlaces(newPlaces); if (!SQLManager.SAVE_MAP_DATA(_perso.get_curCarte())) return; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Les places ont ete modifiees (" + newPlaces + ")"); return; } else if (command.equalsIgnoreCase("SETMAXGROUP")) { infos = msg.split(" ", 4); byte id = -1; try { id = Byte.parseByte(infos[1]); } catch (Exception e) { } ; if (id == -1) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String mess = "Le nombre de groupe a ete fixe"; _perso.get_curCarte().setMaxGroup(id); boolean ok = SQLManager.SAVE_MAP_DATA(_perso.get_curCarte()); if (ok) mess += " et a ete sauvegarder a la BDD"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else if (command.equalsIgnoreCase("ADDREPONSEACTION")) { infos = msg.split(" ", 4); int id = -30; int repID = 0; String args = infos[3]; try { repID = Integer.parseInt(infos[1]); id = Integer.parseInt(infos[2]); } catch (Exception e) { } ; NPC_reponse rep = World.getNPCreponse(repID); if (id == -30 || rep == null) { String str = "Au moins une des valeur est invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String mess = "L'action a ete ajoute"; rep.addAction(new Action(id, args, "")); boolean ok = SQLManager.ADD_REPONSEACTION(repID, id, args); if (ok) mess += " et ajoute a la BDD"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else if (command.equalsIgnoreCase("SETINITQUESTION")) { infos = msg.split(" ", 4); int id = -30; int q = 0; try { q = Integer.parseInt(infos[2]); id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (id == -30) { String str = "NpcID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String mess = "L'action a ete ajoute"; NPC_tmpl npc = World.getNPCTemplate(id); npc.setInitQuestion(q); boolean ok = SQLManager.UPDATE_INITQUESTION(id, q); if (ok) mess += " et ajoute a la BDD"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); } else if (command.equalsIgnoreCase("ADDENDFIGHTACTION")) { infos = msg.split(" ", 4); int id = -30; int type = 0; String args = infos[3]; String cond = infos[4]; try { type = Integer.parseInt(infos[1]); id = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (id == -30) { String str = "Au moins une des valeur est invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String mess = "L'action a ete ajoute"; _perso.get_curCarte().addEndFightAction(type, new Action(id, args, cond)); boolean ok = SQLManager.ADD_ENDFIGHTACTION(_perso.get_curCarte() .get_id(), type, id, args, cond); if (ok) mess += " et ajoute a la BDD"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, mess); return; } else if (command.equalsIgnoreCase("SPAWNFIX")) { String groupData = infos[1]; _perso.get_curCarte().addStaticGroup(_perso.get_curCell().getID(), groupData); String str = "Le grouppe a ete fixe"; // Sauvegarde DB de la modif if (SQLManager.SAVE_NEW_FIXGROUP(_perso.get_curCarte().get_id(), _perso.get_curCell().getID(), groupData)) str += " et a ete sauvegarde dans la BDD"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("ADDNPC")) { int id = 0; try { id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (id == 0 || World.getNPCTemplate(id) == null) { String str = "NpcID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } NPC npc = _perso.get_curCarte().addNpc(id, _perso.get_curCell().getID(), _perso.get_orientation()); SocketManager.GAME_SEND_ADD_NPC_TO_MAP(_perso.get_curCarte(), npc); String str = "Le PNJ a ete ajoute"; if (_perso.get_orientation() == 0 || _perso.get_orientation() == 2 || _perso.get_orientation() == 4 || _perso.get_orientation() == 6) str += " mais est invisible (orientation diagonale invalide)."; if (SQLManager.ADD_NPC_ON_MAP(_perso.get_curCarte().get_id(), id, _perso.get_curCell().getID(), _perso.get_orientation())) SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); else SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Erreur au moment de sauvegarder la position"); } else if (command.equalsIgnoreCase("DELNPC")) { int id = 0; try { id = Integer.parseInt(infos[1]); } catch (Exception e) { } ; NPC npc = _perso.get_curCarte().getNPC(id); if (id == 0 || npc == null) { String str = "Npc GUID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } int exC = npc.get_cellID(); // on l'efface de la map SocketManager.GAME_SEND_ERASE_ON_MAP_TO_MAP(_perso.get_curCarte(), id); _perso.get_curCarte().removeNpcOrMobGroup(id); String str = "Le PNJ a ete supprime"; if (SQLManager.DELETE_NPC_ON_MAP(_perso.get_curCarte().get_id(), exC)) SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); else SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Erreur au moment de sauvegarder la position"); } else if (command.equalsIgnoreCase("DELTRIGGER")) { int cellID = -1; try { cellID = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (cellID == -1 || _perso.get_curCarte().getCase(cellID) == null) { String str = "CellID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } _perso.get_curCarte().getCase(cellID).clearOnCellAction(); boolean success = SQLManager.REMOVE_TRIGGER(_perso.get_curCarte() .get_id(), cellID); String str = ""; if (success) str = "Le trigger a ete retire"; else str = "Le trigger n'a pas ete retire"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("ADDTRIGGER")) { int actionID = -1; String args = "", cond = ""; try { actionID = Integer.parseInt(infos[1]); args = infos[2]; cond = infos[3]; } catch (Exception e) { } ; if (args.equals("") || actionID <= -3) { String str = "Valeur invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } _perso.get_curCell().addOnCellStopAction(actionID, args, cond); boolean success = SQLManager.SAVE_TRIGGER(_perso.get_curCarte() .get_id(), _perso.get_curCell().getID(), actionID, 1, args, cond); String str = ""; if (success) str = "Le trigger a ete ajoute"; else str = "Le trigger n'a pas ete ajoute"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("DELNPCITEM")) { if (_compte.get_gmLvl() < 3) return; int npcGUID = 0; int itmID = -1; try { npcGUID = Integer.parseInt(infos[1]); itmID = Integer.parseInt(infos[2]); } catch (Exception e) { } ; NPC_tmpl npc = _perso.get_curCarte().getNPC(npcGUID).get_template(); if (npcGUID == 0 || itmID == -1 || npc == null) { String str = "NpcGUID ou itmID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String str = ""; if (npc.delItemVendor(itmID)) str = "L'objet a ete retire"; else str = "L'objet n'a pas ete retire"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("ADDNPCITEM")) { if (_compte.get_gmLvl() < 3) return; int npcGUID = 0; int itmID = -1; try { npcGUID = Integer.parseInt(infos[1]); itmID = Integer.parseInt(infos[2]); } catch (Exception e) { } ; NPC_tmpl npc = _perso.get_curCarte().getNPC(npcGUID).get_template(); ObjTemplate item = World.getObjTemplate(itmID); if (npcGUID == 0 || itmID == -1 || npc == null || item == null) { String str = "NpcGUID ou itmID invalide"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } String str = ""; if (npc.addItemVendor(item)) str = "L'objet a ete rajoute"; else str = "L'objet n'a pas ete rajoute"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("ADDMOUNTPARK")) { int size = -1; int owner = -2; int price = -1; try { size = Integer.parseInt(infos[1]); owner = Integer.parseInt(infos[2]); price = Integer.parseInt(infos[3]); if (price > 20000000) price = 20000000; if (price < 0) price = 0; } catch (Exception e) { } ; if (size == -1 || owner == -2 || price == -1 || _perso.get_curCarte().getMountPark() != null) { String str = "Infos invalides ou map deja config."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } MountPark MP = new MountPark(owner, _perso.get_curCarte(), _perso .get_curCell().getID(), size, "", -1, price); _perso.get_curCarte().setMountPark(MP); SQLManager.SAVE_MOUNTPARK(MP); String str = "L'enclos a ete config. avec succes"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); } else if (command.equalsIgnoreCase("SHUTDOWN")) { int time = 30, OffOn = 0; try { OffOn = Integer.parseInt(infos[1]); time = Integer.parseInt(infos[2]); } catch (Exception e) { } ; if (OffOn == 1 && _TimerStart)// demande de d�marer le reboot { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Un shutdown est deja programmer."); } else if (OffOn == 1 && !_TimerStart) { _timer = createTimer(time); _timer.start(); _TimerStart = true; String timeMSG = "minutes"; if (time <= 1) { timeMSG = "minute"; } SocketManager.GAME_SEND_Im_PACKET_TO_ALL("115;" + time + " " + timeMSG); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Shutdown lance."); } else if (OffOn == 0 && _TimerStart) { _timer.stop(); _TimerStart = false; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Shutdown arrete."); } else if (OffOn == 0 && !_TimerStart) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Aucun shutdown n'est lance."); } } else { this.commandGmTwo(command, infos, msg); } } public void commandGmFour(String command, String[] infos, String msg) { if (_compte.get_gmLvl() < 4) { _compte.getGameThread().closeSocket(); return; } if (command.equalsIgnoreCase("MESSAGEPOPUP")) { infos = msg.split(" ", 2); SocketManager.GAME_SEND_PANEL_INFOS(infos[1]); return; } else if (command.equalsIgnoreCase("SETADMIN")) { int gmLvl = -100; try { gmLvl = Integer.parseInt(infos[1]); } catch (Exception e) { } ; if (gmLvl == -100) { String str = "Valeur incorrecte"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } Personnage target = _perso; if (infos.length > 2)// Si un nom de perso est sp�cifi� { target = World.getPersoByName(infos[2]); if (target == null) { String str = "Le personnage n'a pas �t� trouv�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } target.get_compte().setGmLvl(gmLvl); SQLManager.UPDATE_ACCOUNT_DATA(target.get_compte()); String str = "Le niveau GM du joueur a �t� modifi�"; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } else if (command.equalsIgnoreCase("LOCK")) { byte LockValue = 1;// Accessible try { LockValue = Byte.parseByte(infos[1]); } catch (Exception e) { } ; if (LockValue > 2) LockValue = 2; if (LockValue < 0) LockValue = 0; World.set_state((short) LockValue); if (LockValue == 1) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Serveur accessible."); } else if (LockValue == 0) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Serveur inaccessible."); } else if (LockValue == 2) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Serveur en sauvegarde."); } return; } else if (command.equalsIgnoreCase("UNBANIP")) { Personnage perso = null; try { perso = World.getPersoByName(infos[1]); } catch (Exception localException4) { } if (perso == null) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(this._out, "Le nom du personnage n'est pas bon"); return; } if (Constants.BAN_IP.contains(perso.get_compte().get_curIP())) { if (SQLManager.DELETE_BANIP(perso.get_compte().get_curIP())) { Constants.BAN_IP = ""; SQLManager.LOAD_BANIP(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(this._out, "L'IP a correctement �tait d�banni"); return; } } } else if (command.equalsIgnoreCase("BLOCK")) { byte GmAccess = 0; byte KickPlayer = 0; try { GmAccess = Byte.parseByte(infos[1]); KickPlayer = Byte.parseByte(infos[2]); } catch (Exception e) { } ; World.setGmAccess(GmAccess); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Serveur bloque au GmLevel : " + GmAccess); if (KickPlayer > 0) { for (Personnage z : World.getOnlinePersos()) { if (z.get_compte().get_gmLvl() < GmAccess) z.get_compte().getGameThread().closeSocket(); } SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Les joueurs de GmLevel inferieur a " + GmAccess + " ont ete kicks."); } return; } else if (command.equalsIgnoreCase("BANIP")) { Personnage P = null; try { P = World.getPersoByName(infos[1]); } catch (Exception e) { } ; if (P == null || !P.isOnline()) { String str = "Le personnage n'a pas ete trouve."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } if (!Constants.IPcompareToBanIP(P.get_compte().get_curIP())) { Constants.BAN_IP += "," + P.get_compte().get_curIP(); if (SQLManager.ADD_BANIP(P.get_compte().get_curIP())) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "L'IP a ete banni."); } if (P.isOnline()) { P.get_compte().getGameThread().kick(); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Le joueur a ete kick."); } } else { String str = "L'IP existe deja."; SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, str); return; } } else if (command.equalsIgnoreCase("FULLHDV")) { int numb = 1; try { numb = Integer.parseInt(infos[1]); } catch (Exception e) { } ; fullHdv(numb); return; }else if(command.equalsIgnoreCase("MUTEMAP")){ int tps = 7200; try { tps = Integer.parseInt(infos[1]); }catch(Exception e){}; for(Personnage p:_perso.get_curCarte().getPersos()) { if(p.get_GUID() != _perso.get_GUID()) // Si ce n'est pas le muteur p.get_compte().mute(true, tps); } SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out,"Map " + _perso.get_curCarte().get_id() + " mutté pour " + tps + " minutes"); }else if(command.equalsIgnoreCase("UNMUTEMAP")){ int tps = 0; for(Personnage p:_perso.get_curCarte().getPersos()) p.get_compte().mute(false, tps); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out,"Map " + _perso.get_curCarte().get_id() + "démuté"); } else { if (_compte.get_gmLvl() >= 4) this.commandGmThree(command, infos, msg); } } private void fullHdv(int ofEachTemplate) { SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "D�marrage du remplissage!"); Objet objet = null; HdvEntry entry = null; byte amount = 0; int hdv = 0; int lastSend = 0; long time1 = System.currentTimeMillis();// TIME for (ObjTemplate curTemp : World.getObjTemplates())// Boucler dans les // template { try { if (Ancestra.NOTINHDV.contains(curTemp.getID())) continue; for (int j = 0; j < ofEachTemplate; j++)// Ajouter plusieur fois // le template { if (curTemp.getType() == 85) break; objet = curTemp.createNewItem(1, false); hdv = getHdv(objet.getTemplate().getType()); if (hdv < 0) break; amount = (byte) Formulas.getRandomValue(1, 3); entry = new HdvEntry(calculPrice(objet, amount), amount, -1, objet); objet.setQuantity(entry.getAmount(true)); World.getHdv(hdv).addEntry(entry); World.addObjet(objet, false); } } catch (Exception e) { continue; } if ((System.currentTimeMillis() - time1) / 1000 != lastSend && (System.currentTimeMillis() - time1) / 1000 % 3 == 0) { lastSend = (int) ((System.currentTimeMillis() - time1) / 1000); SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, (System.currentTimeMillis() - time1) / 1000 + "sec Template: " + curTemp.getID()); } } SocketManager.GAME_SEND_CONSOLE_MESSAGE_PACKET(_out, "Remplissage fini en " + (System.currentTimeMillis() - time1) + "ms"); World.saveAll(null); SocketManager.GAME_SEND_MESSAGE_TO_ALL("HDV remplis!", Ancestra.CONFIG_MOTD_COLOR); } private int getHdv(int type) { int rand = Formulas.getRandomValue(1, 4); int map = -1; switch (type) { case 12: case 14: case 26: case 43: case 44: case 45: case 66: case 70: case 71: case 86: if (rand == 1) { map = 4271; } else if (rand == 2) { map = 4607; } else { map = 7516; } return map; case 1: case 9: if (rand == 1) { map = 4216; } else if (rand == 2) { map = 4622; } else { map = 7514; } return map; case 18: case 72: case 77: case 90: case 97: case 113: case 116: if (rand == 1) { map = 8759; } else { map = 8753; } return map; case 63: case 64: case 69: if (rand == 1) { map = 4287; } else if (rand == 2) { map = 4595; } else if (rand == 3) { map = 7515; } else { map = 7350; } return map; case 33: case 42: if (rand == 1) { map = 2221; } else if (rand == 2) { map = 4630; } else { map = 7510; } return map; case 84: case 93: case 112: case 114: if (rand == 1) { map = 4232; } else if (rand == 2) { map = 4627; } else { map = 12262; } return map; case 38: case 95: case 96: case 98: case 108: if (rand == 1) { map = 4178; } else if (rand == 2) { map = 5112; } else { map = 7289; } return map; case 10: case 11: if (rand == 1) { map = 4183; } else if (rand == 2) { map = 4562; } else { map = 7602; } return map; case 13: case 25: case 73: case 75: case 76: if (rand == 1) { map = 8760; } else { map = 8754; } return map; case 5: case 6: case 7: case 8: case 19: case 20: case 21: case 22: if (rand == 1) { map = 4098; } else if (rand == 2) { map = 5317; } else { map = 7511; } return map; case 39: case 40: case 50: case 51: case 88: if (rand == 1) { map = 4179; } else if (rand == 2) { map = 5311; } else { map = 7443; } return map; case 87: if (rand == 1) { map = 6159; } else { map = 6167; } return map; case 34: case 52: case 60: if (rand == 1) { map = 4299; } else if (rand == 2) { map = 4629; } else { map = 7397; } return map; case 41: case 49: case 62: if (rand == 1) { map = 4247; } else if (rand == 2) { map = 4615; } else if (rand == 3) { map = 7501; } else { map = 7348; } return map; case 15: case 35: case 36: case 46: case 47: case 48: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 65: case 68: case 103: case 104: case 105: case 106: case 107: case 109: case 110: case 111: if (rand == 1) { map = 4262; } else if (rand == 2) { map = 4646; } else { map = 7413; } return map; case 78: if (rand == 1) { map = 8757; } else { map = 8756; } return map; case 2: case 3: case 4: if (rand == 1) { map = 4174; } else if (rand == 2) { map = 4618; } else { map = 7512; } return map; case 16: case 17: case 81: if (rand == 1) { map = 4172; } else if (rand == 2) { map = 4588; } else { map = 7513; } return map; case 83: if (rand == 1) { map = 10129; } else { map = 8482; } return map; case 82: return 8039; default: return -1; } } private int calculPrice(Objet obj, int logAmount) { int amount = (byte) (Math.pow(10, (double) logAmount) / 10); int stats = 0; for (int curStat : obj.getStats().getMap().values()) { stats += curStat; } if (stats > 0) return (int) (((Math.cbrt(stats) * Math.pow(obj.getTemplate() .getLevel(), 2)) * 10 + Formulas.getRandomValue(1, obj .getTemplate().getLevel() * 100)) * amount); else return (int) ((Math.pow(obj.getTemplate().getLevel(), 2) * 10 + Formulas .getRandomValue(1, obj.getTemplate().getLevel() * 100)) * amount); } }
true
ef19db0be5eb69149458f6447aa5223a7818794b
Java
JurajKE/musicapp
/juraj-music-web/src/main/java/com/pacholsky/juraj/music/service/view/SongViewService.java
UTF-8
929
1.914063
2
[]
no_license
package com.pacholsky.juraj.music.service.view; import com.pacholsky.juraj.music.dto.PlaylistView; import com.pacholsky.juraj.music.dto.SongView; import com.pacholsky.juraj.music.entity.Song; import com.pacholsky.juraj.music.exception.ErrorCode; import com.pacholsky.juraj.music.exception.MusicException; import com.pacholsky.juraj.music.modelmapper.PlaylistModelMapper; import com.pacholsky.juraj.music.modelmapper.SongModelMapper; import com.pacholsky.juraj.music.repository.PlaylistRepository; import com.pacholsky.juraj.music.repository.SongRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Transactional @Service("songViewService") public class SongViewService extends AbstractViewService<Song, SongView>{ @Override public Class<SongView> getClassMethod() { return SongView.class; } }
true
dace42009da8f8a60e1acb14941d2fb3dfe56d0f
Java
fredericoeca/gestaodefluidos
/src/com/gf/model/dao/exception/RelatorioNuloException.java
ISO-8859-1
247
1.984375
2
[]
no_license
package com.gf.model.dao.exception; public class RelatorioNuloException extends Exception{ private static final long serialVersionUID = 1L; public RelatorioNuloException(){ super("Relatrio sem dados para esses parmetros!"); } }
true
edff9ff6dd0efa9088319e4c8225f673e3704a22
Java
shubha1994/CRAFTSVILLADEMO
/src/main/java/ObjectRepository/Quickveiwpopup.java
UTF-8
754
1.945313
2
[]
no_license
package main.java.ObjectRepository; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class Quickveiwpopup { private WebDriver driver; @FindBy(xpath="//div[@class='col-xs-12 col-sm-4 widgets-box']//img[@class='img-responsive' and @suits='']") private WebElement Product; @FindBy(xpath="//a[text='Quick View']") private WebElement Quickveiw; //Initializing all the elements public void Searchpage(WebDriver driver) { PageFactory.initElements(driver,this); } public void prdt() { Product.click(); } public void quickveiw() { Quickveiw.click(); } }
true
d840eb6eb73c4d5835353ec24b3392e983f4b3b2
Java
zlzlxm13/KH-Final-Project
/finalproject/src/main/java/controller/ChatWebSocketHandler.java
UTF-8
1,802
2.8125
3
[]
no_license
package controller; import java.util.ArrayList; import java.util.List; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; public class ChatWebSocketHandler extends TextWebSocketHandler { //접속한 클라이언트들의 정보를 저장할 컬렉션 객체 public static List<WebSocketSession> list=new ArrayList<WebSocketSession>(); public ChatWebSocketHandler() { } //클라이언트가 연결 되었을 때 호출되는 메소드 @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println(session.getId()+"연결 됨"); //리스트에 추가 list.add(session); }//end afterConnectionEstablished()//////////////// //클라이언트가 메세지를 보냈을 때 호출되는 메소드 @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { //전송된 메세지를 모든 클라이언트에게 전송 String msg=(String)message.getPayload(); for(WebSocketSession socket: list) { //메세지 생성 WebSocketMessage<String> sentMsg=new TextMessage(msg); // 각 세션에게 메세지를 전송 socket.sendMessage(sentMsg); } }//end handelMessage()////////////// //클라이언트와의 연결이 끊겼을 때 호출되는 메소드 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { //리스트에서 제거 System.out.println(session.getId()+"연결 종료 됨"); list.remove(session); } }//end class//////////////////////////
true
22ca273a644b11624c698f6eb650498d9e120ff8
Java
geely-shoping/geely-shopping-parent
/geely-service/src/main/java/com/geely/service/impl/CouponTbServiceImpl.java
UTF-8
1,699
1.945313
2
[]
no_license
package com.geely.service.impl; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import com.geely.entity.CouponTb; import com.geely.dao.CouponTbMapper; import com.geely.service.CouponTbService; @Service public class CouponTbServiceImpl implements CouponTbService{ @Resource private CouponTbMapper couponTbMapper; @Override public int deleteByPrimaryKey(Integer couponId) { return couponTbMapper.deleteByPrimaryKey(couponId); } @Override public int insert(CouponTb record) { return couponTbMapper.insert(record); } @Override public int insertSelective(CouponTb record) { return couponTbMapper.insertSelective(record); } @Override public CouponTb selectByPrimaryKey(Integer couponId) { return couponTbMapper.selectByPrimaryKey(couponId); } @Override public int updateByPrimaryKeySelective(CouponTb record) { return couponTbMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(CouponTb record) { return couponTbMapper.updateByPrimaryKey(record); } @Override public int updateBatch(List<CouponTb> list) { return couponTbMapper.updateBatch(list); } @Override public int batchInsert(List<CouponTb> list) { return couponTbMapper.batchInsert(list); } @Override public List<CouponTb> listCouponTbByPage(int pageNum, int pageSize) { return couponTbMapper.listCouponTb(pageNum, pageSize); } @Override public int batchDelete(List<Integer> couponIds) { return couponTbMapper.batchDelete(couponIds); } }
true
a6adf0e172f7f28697a1d5b0f38ec0f0ff105277
Java
consulo/consulo
/modules/base/util/util-collection/src/main/java/consulo/util/collection/WeakList.java
UTF-8
3,774
2.625
3
[ "Apache-2.0", "LicenseRef-scancode-jgraph" ]
permissive
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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 consulo.util.collection; import jakarta.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Implementation of the {@link List} interface which: * <ul> * <li>Stores elements using weak semantics (see {@link java.lang.ref.WeakReference})</li> * <li>Automatically reclaims storage for garbage collected elements</li> * <li>Is thread safe</li> * </ul> */ public class WeakList<T> extends UnsafeWeakList<T> { public WeakList() { this(new WeakReferenceArray<T>()); } // For testing only WeakList(@Nonnull WeakReferenceArray<T> array) { super(array); } @Override public T get(int index) { synchronized (myArray) { return super.get(index); } } @Override public boolean add(T element) { synchronized (myArray) { return super.add(element); } } @Override public boolean contains(Object o) { synchronized (myArray) { return super.contains(o); } } @Override public boolean addIfAbsent(T element) { synchronized (myArray) { return super.addIfAbsent(element); } } @Override public void add(int index, T element) { synchronized (myArray) { super.add(index, element); } } @Override public T set(int index, T element) { synchronized (myArray) { return super.set(index, element); } } @Override public int indexOf(Object o) { synchronized (myArray) { return super.indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (myArray) { return super.lastIndexOf(o); } } @Override public void clear() { synchronized (myArray) { super.clear(); } } @Override protected void removeRange(int fromIndex, int toIndex) { synchronized (myArray) { super.removeRange(fromIndex, toIndex); } } @Override public boolean remove(Object o) { synchronized (myArray) { return super.remove(o); } } @Override public T remove(int index) { synchronized (myArray) { return super.remove(index); } } @Override public boolean removeAll(Collection<?> c) { synchronized (myArray) { return super.removeAll(c); } } @Override @Nonnull public Iterator<T> iterator() { return new MySyncIterator(); } @Override public int size() { synchronized (myArray) { return myArray.size(); } } @Override public List<T> toStrongList() { synchronized (myArray) { List<T> result = new ArrayList<T>(myArray.size()); myArray.toStrongCollection(result); return result; } } public List<T> copyAndClear() { synchronized (myArray) { List<T> result = new ArrayList<T>(myArray.size()); myArray.toStrongCollection(result); clear(); return result; } } private class MySyncIterator extends MyIterator { @Override protected void findNext() { synchronized (myArray) { super.findNext(); } } @Override public void remove() { synchronized (myArray) { super.remove(); } } } }
true
817b0984f4f85fe83992065dc95f984c731c7887
Java
ruxeom/FMM-Web-Server
/src/fmmserver/MimeTypes.java
UTF-8
610
2.765625
3
[]
no_license
package fmmserver; import java.util.Hashtable; import java.util.Scanner; import java.io.*; public class MimeTypes { public Hashtable<String,String> getMimeHash() { Hashtable<String,String> table = new Hashtable<String,String>(); try { Scanner scanner = new Scanner(new FileInputStream("mimetable.txt")); while(scanner.hasNextLine()) { String[] line = scanner.nextLine().split("\t"); table.put(line[0], line[1]); } scanner.close(); } catch(Exception e) { System.out.println("Error while trying to load MIME types."); e.printStackTrace(); } return table; } }
true
f727fee5a4c5f1a95c65354cd8a1750708a68f0a
Java
jimcurry/premieraco
/src/main/java/com/lpasystems/premieraco/dao/UserDAO.java
UTF-8
1,848
2.28125
2
[]
no_license
package com.lpasystems.premieraco.dao; import java.util.List; import org.skife.jdbi.v2.HashPrefixStatementRewriter; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.customizers.OverrideStatementRewriterWith; import com.lpasystems.premieraco.mapper.UserInfoMapper; import com.lpasystems.premieraco.mapper.UserSettingsMapper; import com.lpasystems.premieraco.representations.UserInfo; import com.lpasystems.premieraco.representations.UserSetting; public interface UserDAO { /** * Returns the User Information for the passed in user name * * @param userName */ @Mapper(UserInfoMapper.class) // @formatter:off @OverrideStatementRewriterWith(HashPrefixStatementRewriter.class) @SqlQuery("SELECT pce_cst_nm " + ", apl_rl_cd " + ", pract_fltr_txt " + ", lvl_10_fltr_txt " + ", lvl_20_fltr_txt " + ", lvl_30_fltr_txt " + ", lvl_40_fltr_txt " + ", lvl_50_fltr_txt " + ", lvl_60_fltr_txt " + ", lvl_70_fltr_txt " + ", lvl_80_fltr_txt " + ", lvl_90_fltr_txt " + "FROM usr_info " + "where upper(usr_nm) = upper(#userName) " ) // @formatter:on\ UserInfo getUserInfo(@Bind("userName") String userName); /** * Returns the User Information for the passed in user name * * @param userName */ @Mapper(UserSettingsMapper.class) // @formatter:off @OverrideStatementRewriterWith(HashPrefixStatementRewriter.class) @SqlQuery("SELECT usr_setting_nm " + ", usr_setting_txt " + "FROM usr_settings " + "where upper(usr_nm) = upper(#userName) " ) // @formatter:on\ List<UserSetting> getUserSettings(@Bind("userName") String userName); }
true
1941f837f67f5834ca2995a7f61ca063557d6be3
Java
JungYOsup/java_standard
/20171023_XY_Calculation/src/min/edu/XY_Main.java
UTF-8
505
3.296875
3
[]
no_license
package min.edu; public class XY_Main { public static void main(String[] args) { // 값을 가지고 있는 객체를 생성 XY a = new XY(); a.x = 10.0; a.y = 20.0; XY b = new XY(); b.x = 5.0; b.y =10.0; XY rCal1 =XY_Calculation.Minus(a, b); System.out.printf("마이너스 결과는 ? x = %f , y = %f \n",rCal1.x , rCal1.y); XY rCal2 = XY_Calculation.plus(a, b); System.out.printf("플러스 결과는 ? x = %f , y = %f \n",rCal2.x , rCal2.y); } }
true
2bc27313bead103ee6a72f532b6340006f463fbd
Java
koma2412/Greenbook
/src/main/java/org/example/repositories/LocationRepository.java
UTF-8
343
1.976563
2
[]
no_license
package org.example.repositories; import org.example.entity.Location; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface LocationRepository extends CrudRepository<Location, Integer> { @Override List<Location> findAll(); }
true
1ff6508f1b5ed16396ebd71996e51869c0158520
Java
wangdg/projecteuler-java
/src/main/java/com/wangdg/projecteuler/level2/problem42/Problem42.java
UTF-8
1,658
3.421875
3
[]
no_license
package com.wangdg.projecteuler.level2.problem42; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * https://projecteuler.net/problem=42 */ public class Problem42 { protected static String LETTER_STR = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { Set<String> words = readWords(); int sum = 0; for (String word : words) { int val = getWordValue(word); if (isTriangleNumber(val)) { sum += 1; } } System.out.println("result = " + sum); } protected static boolean isTriangleNumber(int n) { int nn = n * 2; int limit = (int)Math.sqrt(nn) + 1; for (int i = 1; i <= limit; i++) { if (nn % i == 0 && (i + 1 == nn / i)) { return true; } } return false; } protected static int getWordValue(String str) { char[] chars = str.toCharArray(); int val = 0; for (char c : chars) { val += (LETTER_STR.indexOf(c) + 1); } return val; } protected static Set<String> readWords() { try { String str = IOUtils.toString(Problem42.class.getResourceAsStream("/problem42.txt"), "UTF-8"); String[] array = str.split(","); Set<String> words = new HashSet<>(); for (String word : array) { words.add(word.replace("\"", "").toLowerCase()); } return words; } catch (IOException e) { return null; } } }
true
3621937bdca2926733085ad708a433a0e9158811
Java
billa513/MFPE-Project
/Newhospitalmanagement/src/main/java/com/example/newhospitalmanagement/repository/EmployeeRepository.java
UTF-8
718
2
2
[]
no_license
package com.example.newhospitalmanagement.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.example.newhospitalmanagement.model.Employee; @Repository public interface EmployeeRepository extends JpaRepository<Employee,String>{ Optional<Employee> findById(String employeeId); @Query("from Employee where Role=:role") List<Employee> slectRecordByRole(@Param("role") String name); }
true
b6defec59ddb5f164a5370a096c28af4000e077c
Java
mamingrui8/mmrlearning
/basicknowledge/src/main/java/com/mmr/learn/theory/thinkinginjava/part21/DaemonFromFactory.java
UTF-8
2,595
3.875
4
[]
no_license
package com.mmr.learn.theory.thinkinginjava.part21; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * 通过ThreadFactory来初始化的Executors * @author Charles Wesley * @date 2019/11/27 23:47 */ public class DaemonFromFactory implements Runnable{ @Override public void run() { try { while(true){ TimeUnit.MILLISECONDS.sleep(100); System.out.println(Thread.currentThread() + " " + this); } }catch (InterruptedException e){ System.out.println("Thread interrupted"); } } public static void main(String[] args) throws Exception{ Thread.currentThread().setPriority(Thread.MIN_PRIORITY); ExecutorService es = Executors.newCachedThreadPool(new DaemonThreadFactory()); for(int i = 0; i < 10; i++){ es.execute(new DaemonFromFactory()); } System.out.println("All daemons started"); TimeUnit.MILLISECONDS.sleep(500); System.out.println(123); } /* Step1: main线程(非后台线程)输出"All daemons started",遇到sleep()命令进入休眠,休眠时间500ms Step2: 一个后台线程(可能是10个当中的任意一个)开始执行run()方法,当遇到sleep命令后,立刻通知调度器,让出CPU供其余的后台线程执行 如果把线程调度器切换线程的时间忽略不计,那么所有的后台线程都进入了休眠状态,休眠时间100ms Step3: 100ms结束后,每一个后台线程都会输出Thread.currentThread() + " " + this 语句。 Step4: 重复Step2和3总共4轮。当到第5轮,也就是所有的线程(包括main线程)全部度过了500ms后,main线程开始执行,并执行结束。 由于场上唯一的一个非后台线程结束运行,因此java进程将会被杀死,后台线程也会随之被杀死。 总计输出 1+ 10 * 4 + 1 = 42条语句 疑问: 500毫秒时,所有的线程都被唤醒并进入"可运行态"了,凭什么main线程(非后台线程/用户线程)先执行呢?难道说用户线程的优先级比守护线程的优先级高吗? 分析: 为了验证这个问题,我在DaemonThreadFactory中人为的把守护线程的优先级设置成了最高,在main中把main线程的优先级设置成最低,看看结果如何。 结果发现,守护线程仍然不会先于用户线程执行,所以和线程的优先级没什么关系。 */ }
true
830bb612ddfdc8a190d65f7d6e66ea1ab45ebf51
Java
JetBrains/intellij-community
/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenConfigImportingTest.java
UTF-8
5,598
1.671875
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing; import com.intellij.maven.testFramework.MavenDomTestCase; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import org.jetbrains.idea.maven.dom.references.MavenPsiElementWrapper; import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.MavenProject; import org.junit.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; public class MavenConfigImportingTest extends MavenDomTestCase { @Test public void testResolveJvmConfigProperty() throws IOException { createProjectSubFile(MavenConstants.JVM_CONFIG_RELATIVE_PATH, "-Dver=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version>"""); MavenProject mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("1", mavenProject.getMavenId().getVersion()); } @Test public void testResolveMavenConfigProperty() throws IOException { createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dver=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version>"""); MavenProject mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("1", mavenProject.getMavenId().getVersion()); } @Test public void testResolvePropertyPriority() throws IOException { createProjectSubFile(MavenConstants.JVM_CONFIG_RELATIVE_PATH, "-Dver=ignore"); createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dver=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version> <properties> <ver>ignore</ver></properties>"""); MavenProject mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("1", mavenProject.getMavenId().getVersion()); } @Test public void testResolveConfigPropertiesInModules() throws IOException { assumeVersionMoreThan("3.3.1"); createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dver=1 -DmoduleName=m1"); createModulePom("m1", """ <artifactId>${moduleName}</artifactId> <version>${ver}</version> <parent> <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version> </parent>"""); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version> <packaging>pom</packaging> <modules> <module>${moduleName}</module></modules>"""); MavenProject mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("1", mavenProject.getMavenId().getVersion()); MavenProject module = myProjectsManager.findProject(getModule(mn("project", "m1"))); assertNotNull(module); assertEquals("m1", module.getMavenId().getArtifactId()); assertEquals("1", module.getMavenId().getVersion()); } @Test public void testMavenConfigCompletion() throws Exception { createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dconfig.version=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1</version>"""); createProjectPom(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${config.<caret></version>"""); assertCompletionVariants(myProjectPom, "config.version"); } @Test public void testMavenConfigReferenceResolving() throws IOException { createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dconfig.version=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${config.version}</version>"""); PsiElement resolvedReference = getReference(myProjectPom, "config.version", 0).resolve(); assertNotNull(resolvedReference); assertInstanceOf(resolvedReference, MavenPsiElementWrapper.class); assertEquals("1", ((MavenPsiElementWrapper)resolvedReference).getName()); } @Test public void testReimportOnConfigChange() throws IOException { VirtualFile configFile = createProjectSubFile(MavenConstants.MAVEN_CONFIG_RELATIVE_PATH, "-Dver=1"); importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>${ver}</version>"""); MavenProject mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("1", mavenProject.getMavenId().getVersion()); WriteAction.runAndWait(() -> { byte[] content = "-Dver=2".getBytes(StandardCharsets.UTF_8); configFile.setBinaryContent(content, -1, configFile.getTimeStamp() + 1); }); configConfirmationForYesAnswer(); importProject(); mavenProject = myProjectsManager.findProject(getModule("project")); assertEquals("2", mavenProject.getMavenId().getVersion()); } }
true
54f27d2928a399145a32be05b165ddfe3519b0ed
Java
CodeChina888/testgit
/Release/update/20181204/src/com/hanweb/jmp/cms/dao/cols/ColDAO.java
UTF-8
34,549
2.25
2
[]
no_license
package com.hanweb.jmp.cms.dao.cols; import java.util.List; import com.hanweb.common.basedao.BaseJdbcDAO; import com.hanweb.common.basedao.LikeType; import com.hanweb.common.basedao.Query; import com.hanweb.common.basedao.UpdateSql; import com.hanweb.common.util.DateUtil; import com.hanweb.common.util.NumberUtil; import com.hanweb.jmp.cms.entity.cols.Col; import com.hanweb.jmp.constant.Tables; public class ColDAO extends BaseJdbcDAO<Integer, Col> { /** * 通过栏目ID、栏目名称及父栏目ID获得同名栏目名称的个数 * @param iid * 栏目ID * @param name * 栏目名称 * @param pid * 上级栏目ID * @param siteId * 网站id * @return 0 - 不存在<br/> * n - 存在n个 */ public int findNumOfSameName(Integer iid, String name, Integer pid, Integer siteId) { int num = 0; String sql = " SELECT COUNT(iid) FROM " + Tables.COL + " WHERE name=:name "; if (NumberUtil.getInt(iid) > 0) { sql += " AND iid NOT IN(:iid)"; } if (NumberUtil.getInt(siteId) > 0) { sql += " AND siteid=:siteId"; } if (pid != null) { sql += " AND pid = :pid"; } else { sql += " AND pid IS NULL"; } Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("name", name); query.addParameter("siteId", siteId); query.addParameter("pid", pid); num = this.queryForInteger(query); return num; } /** * 获得使用轻应用的栏目数 * @param ids * 轻应用ID串 如:1,2,3 * @return 0 - 不存在<br/> * n - 存在n个 */ public int findCountByAppid(List<Integer> ids) { String sql = "SELECT COUNT(iid) FROM " + Tables.COL + " WHERE lightappid IN (:ids)"; Query query = createQuery(sql); query.addParameter("ids", ids); int num = this.queryForInteger(query); return num; } /** * 获得子栏目数 * @param ids * 栏目ID串 如:1,2,3 * @return 0 - 不存在<br/> * n - 存在n个 */ public int findCountSubCol(List<Integer> ids) { String sql = "SELECT COUNT(iid) FROM " + Tables.COL + " WHERE pid IN (:ids)"; Query query = createQuery(sql); query.addParameter("ids", ids); int num = this.queryForInteger(query); return num; } /** * 获得信息数 * @param ids * 栏目ID串 如:1,2,3 * @param siteId * @return 0 - 不存在<br/> * n - 存在n个 */ public int findCountSubInfo(List<Integer> ids, Integer siteId) { String sql = "SELECT COUNT(iid) FROM " + Tables.INFO + " WHERE colid IN (:ids) AND isremove=0"; sql = sql.replace(Tables.INFO, "jmp_info" + siteId); Query query = createQuery(sql); query.addParameter("ids", ids); int num = this.queryForInteger(query); return num; } /** * 获得信息数 * @param ids * 栏目ID串 如:1,2,3 * @param siteId * @return 0 - 不存在<br/> * n - 存在n个 */ public int findCountRecycleInfo(List<Integer> ids, Integer siteId) { String sql = "SELECT COUNT(iid) FROM " + Tables.INFO + " WHERE colid IN (:ids) AND isremove=1"; sql = sql.replace(Tables.INFO, "jmp_info" + siteId); Query query = createQuery(sql); query.addParameter("ids", ids); int num = this.queryForInteger(query); return num; } /** * 更新附件路径 * @param col * 栏目对象 * @return true - 成功<br/> * false - 失败 */ public boolean updatePath(Col col) { UpdateSql sql = new UpdateSql(Tables.COL); sql.addString("iconpath", col.getIconPath()); sql.setWhere("iid = :iid"); sql.addWhereParamInt("iid", col.getIid()); return super.update(sql); } /** * 更新时间 * @param colid * 栏目id * @param startTime * 栏目开始时间 * @return true - 成功<br/> * false - 失败 */ public boolean updateTime(int colid, String startTime) { if (colid <= 0) { return false; } UpdateSql sql = new UpdateSql(Tables.COL); sql.addDate("starttime", DateUtil.stringtoDate(startTime, DateUtil.YYYY_MM_DD_HH_MM_SS)); sql.setWhere("iid = :iid"); sql.addWhereParamInt("iid", colid); return super.update(sql); } /** * 查询子栏目数量 * @param colid * 栏目id * @return 0 - 不存在<br/> * n - 存在n个 */ public int findSubCol(int colid) { int num = 0; String sql = " SELECT COUNT(iid) FROM " + Tables.COL; if (NumberUtil.getInt(colid) > 0) { sql += " WHERE pid =:colid"; } Query query = createQuery(sql); query.addParameter("colid", colid); num = this.queryForInteger(query); return num; } /** * 根据网站Id查询栏目数量 * @param siteId * 网站id * @return 栏目个数 */ public int findColCount(Integer siteId) { int num = 0; String sql = " SELECT COUNT(iid) FROM " + Tables.COL; if (NumberUtil.getInt(siteId) > 0) { sql += " WHERE siteid =:siteId"; } Query query = createQuery(sql); query.addParameter("siteId", siteId); num = this.queryForInteger(query); return num; } /** * 栏目启用停用 * @param ids * 栏目ID串 * @param enable * 是否有效<br/> * 1 - 有效<br/> * 0 - 无效 * @return true - 成功<br/> * false - 失败 */ public boolean updateEnable(List<Integer> ids, int enable) { UpdateSql sql = new UpdateSql(Tables.COL); sql.addInt("enable", enable); sql.setWhere("iid IN (:ids)"); sql.addWhereParamList("ids", ids); return super.update(sql); } /** * 通过ID获取栏目实体并获取isparent属性 用于频道的树调用 * @author denganming * @param iid * 栏目ID * @param type * 栏目类型 * @return 栏目实体 */ public Col findIsParentByIid(Integer iid, Integer type) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,type,orderid " + " FROM " + Tables.COL + " a WHERE a.iid=:iid"; if (NumberUtil.getInt(type) != 1) { sql += " AND type=:type"; } Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("type", type); return super.queryForEntity(query); } /** * 通过ID获取栏目实体并获取isparent属性 用于频道的树调用 * * @author denganming * @param iid * 栏目ID * @param types * 栏目类型串 * @return 栏目实体 */ public Col findIsParentByIid(Integer iid, String types) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,type,orderid " + " FROM " + Tables.COL + " a WHERE a.iid=:iid"; if (types.length() > 0) { sql += " AND type IN (:types)"; } Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("types", types); return super.queryForEntity(query); } /** * 通过ID获取栏目实体 * * @param iid * 栏目ID * @return 栏目实体 */ public Col findByIid(int iid) { String sql = this.getSql() + " WHERE a.iid=:iid"; Query query = createQuery(sql); query.addParameter("iid", iid); Col col = this.queryForEntity(query); return col; } /** * 通过栏目名称获取栏目 * @param name * 栏目名称 * @return 栏目实体集合 */ public List<Col> findByName(String name) { String sql = this.getSql() + " WHERE name=:name"; Query query = createQuery(sql); query.addParameter("name", name); List<Col> colList = queryForEntities(query); return colList; } /** * 通过栏目名称获取相似栏目 * @param name * 栏目名称 * @return 栏目实体集合 */ public List<Col> findSimilarByName(String name) { String sql = this.getSql() + " WHERE name LIKE:name"; Query query = createQuery(sql); query.addParameter("name", name, LikeType.LR); List<Col> colList = queryForEntities(query); return colList; } /** * 获取所有栏目 * @return 栏目实体列表 */ public List<Col> findAllCol() { String sql = getSql(); Query query = createQuery(sql); return super.queryForEntities(query); } /** * 通过栏目ID获得子栏目集合(树) * @param iid * 栏目父id * @param siteId * 网站id * @return 栏目集合 */ public List<Col> findChildColByIid(Integer iid, Integer siteId) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid,a.newlightappid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent," + " a.type,a.orderid,a.enable,a.createtime,a.coltype " + " FROM "+ Tables.COL + " a "; if (NumberUtil.getInt(iid) > 0) { sql += "WHERE a.pid=:iid"; } else { sql += "WHERE a.pid IS NULL"; } if (NumberUtil.getInt(siteId) > 0) { sql += " AND a.siteid=:siteId"; } sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("siteId", siteId); return super.queryForEntities(query); } /** * 查找所有类目 * @param iid * @param siteId * @return */ public List<Col> findColTreeByType(Integer iid, Integer siteId) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent," + " a.type,a.orderid,a.enable,a.createtime,a.coltype " + " FROM "+ Tables.COL + " a "; if (NumberUtil.getInt(iid) > 0) { sql += "WHERE a.pid=:iid"; } else { sql += "WHERE a.pid IS NULL"; } if (NumberUtil.getInt(siteId) > 0) { sql += " AND a.siteid=:siteId AND type=1"; } sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("siteId", siteId); return super.queryForEntities(query); } /** * 通过栏目ID获得子栏目集合(树) * @param iid * 栏目ID * @param siteId * @param typeIds * 栏目类型 * @return List<Map> 每个Map包含一个栏目实体 */ public List<Col> findChildColByIidAndType(Integer iid, Integer siteId, List<Integer> typeIds) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL+ " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,a.type,a.orderid" + " FROM "+ Tables.COL + " a "; sql += " WHERE a.type IN(:typeIds)"; if (NumberUtil.getInt(iid) > 0) { sql += "AND a.pid=:iid"; } sql += " AND a.siteId =:siteId"; sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("siteId", siteId); query.addParameter("typeIds", typeIds); return super.queryForEntities(query); } /** * 通过是否启用状态位查询栏目 * @param enable * 0 未启用 1 启用 * @param pageSize Integer * @param pageNo Integer * @return 栏目集合 */ public List<Col> findColByEnable(Integer pageSize, Integer pageNo, Integer enable) { String sql = " SELECT a.iid, a.name, a.type, a.pid,a.audittype,a.lastupdatetime, " + "a.infolisttype,a.infocontenttype,a.collisttype,a.siteid,a.synperiod,a.starttime," + "a.sourceurl,a.sourcetype,a.sourcename,a.sourcepwd,a.ditchid, " + "(SELECT taskid FROM " + Tables.COLRELATION + " WHERE colid = a.iid) taskid, " + "a.infonum " + " FROM " + Tables.COL + " a WHERE a.enable=:enable"; sql += " ORDER BY a.iid ASC"; Query query = createQuery(sql); query.addParameter("enable", enable); query.setPageNo(pageNo); query.setPageSize(pageSize); return super.queryForEntities(query); } /** * 查找数目 * @param enable Integer * @return int */ public int findEnableCount(Integer enable){ String sql = "SELECT COUNT(1) FROM " + Tables.COL + " WHERE enable=:enable"; Query query = createQuery(sql); query.addParameter("enable", enable); return this.queryForInteger(query); } /** * 查询某一状态的栏目 * @param enable * 启用状态位 * @param ids * 栏目id * @return 栏目集合 */ public List<Col> findColByEnable(Integer enable, List<Integer> ids) { String sql = " SELECT a.iid, a.name, a.type, a.pid,a.audittype, " + "a.infolisttype,a.infocontenttype,a.collisttype,a.siteid," + "a.synperiod,a.starttime," + "(SELECT taskid FROM " + Tables.COLRELATION + " WHERE colid = a.iid) taskid " + " FROM " + Tables.COL + " a WHERE a.enable=:enable"; sql += " AND a.iid IN(:ids)"; sql += " ORDER BY a.iid ASC"; Query query = createQuery(sql); query.addParameter("enable", enable); query.addParameter("ids", ids); return super.queryForEntities(query); } /** * 查询栏目,包括任务id * @param iid * 主键id * @return 栏目实体 */ public Col findTaskColByIid(int iid) { String sql = " SELECT a.iid, a.name, a.type, a.pid,a.audittype, " + " a.infolisttype,a.infocontenttype,a.collisttype,a.siteid," + " a.synperiod,a.starttime,a.sourceurl,a.sourcename,a.sourcepwd,a.sourcetype," + "(SELECT taskid FROM " + Tables.COLRELATION + " WHERE colid = a.iid) taskid " + " FROM " + Tables.COL + " a WHERE a.iid=:iid"; Query query = createQuery(sql); query.addParameter("iid", iid); return super.queryForEntity(query); } /** * 获得指定栏目ID串的栏目集合 * @param idsList * 栏目ID串 如:1,2,3 * @return 栏目集合 */ public List<Col> findByIds(List<Integer> idsList) { String sql = getSql(); sql += " WHERE iid IN (:idsList) ORDER BY orderid ASC"; Query query = createQuery(sql); query.addParameter("idsList", idsList); List<Col> colList = super.queryForEntities(query); return colList; } /** * 查询指定id串并且启用的栏目集合 * @param ids String * @param state boolean * @return List<Col> */ public List<Col> findByIdsAndState(String ids, boolean state) { String sql = getEntitySql() + " WHERE iid IN(:ids)"; if (state) { sql += " AND enable=1"; } Query query = createQuery(sql); query.addParameter("ids", ids); return super.queryForEntities(query); } /** * findBySiteIds:获得指定网站ID串下的所有栏目集合. * @param pageSize pageSize * @param pageNo pageNo * @param siteidList siteidList * @return 栏目集合 . */ public List<Col> findBySiteIds(Integer pageSize, Integer pageNo, List<Integer> siteidList) { String sql = getSql(); sql += " WHERE a.siteid IN (:siteidList) ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("siteidList", siteidList); query.setPageNo(pageNo); query.setPageSize(pageSize); List<Col> colList = super.queryForEntities(query); return colList; } /** * 通过网站id查找该网站下栏目数目 * @param siteidList * siteidList * @return 栏目数目 */ public int findColNumBySiteId(List<Integer> siteidList) { String sql = "SELECT COUNT(1) FROM " + Tables.COL + " WHERE siteid IN (:siteidList)"; Query query = this.createQuery(sql); query.addParameter("siteidList", siteidList); int num = this.queryForInteger(query); return num; } /** * 获得指定父栏目下的所有栏目集合 * @param pId * 父栏目 * @param siteId * 网站Id * @return 栏目集合 */ public List<Col> findByPidAndSiteId(Integer pId, Integer siteId) { String sql = getSql(); sql += " WHERE a.siteid =:siteId AND a.enable = 1"; if (NumberUtil.getInt(pId) > 0) { sql += " AND a.pid =:pId"; } else { sql += " AND a.pid IS NULL"; } sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("pId", pId); query.addParameter("siteId", siteId); List<Col> colList = super.queryForEntities(query); return colList; } /** * 获得离线下载栏目集合 * @param siteId * 网站Id * @return 栏目集合 */ public List<Col> findByofflineCol(Integer siteId) { String sql = getSql(); sql += " WHERE a.siteid =:siteId AND a.enable = 1 AND offlinenum>0"; sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("siteId", siteId); List<Col> colList = super.queryForEntities(query); return colList; } /** * 根据网站ID和栏目类型获取该网站下的栏目 * @param siteId * 网站id * @param type * 栏目类型 * @return List<Col> */ public List<Col> findBySiteIdAndType(Integer siteId, Integer type) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,type,orderid " + " FROM " + Tables.COL + " a " + " WHERE siteid=:siteid "; if (NumberUtil.getInt(type) != 1) { sql += " AND type=:type"; } sql += " ORDER BY orderid ASC"; Query query = createQuery(sql); query.addParameter("siteid", siteId); query.addParameter("type", type); List<Col> colList = super.queryForEntities(query); return colList; } /** * findBySiteIdAndType:根据网站ID和栏目类型获取该网站下的栏目. * @param pageSize pageSize * @param pageNo pageNo * @param siteId siteId * @return 设定参数 . */ public List<Col> findBySiteIdAndType(Integer pageSize, Integer pageNo, Integer siteId) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,type,orderid " + " FROM " + Tables.COL + " a " + " WHERE siteid=:siteid "; sql += " ORDER BY orderid ASC"; Query query = createQuery(sql); query.addParameter("siteid", siteId); query.setPageNo(pageNo); query.setPageSize(pageSize); List<Col> colList = super.queryForEntities(query); return colList; } /** * 查找栏目集合 * * @param enable * 启用状态 * @param start * 开始条数 * @param end * 结束条数 * @return 栏目集合 */ public List<Col> findByEnable(int enable, int start, int end) { String sql = "SELECT a.iid, a.name, a.type, a.pid,a.audittype, a.limittime, a.siteid FROM " + Tables.COL + " a WHERE a.enable=:enable"; Query query = createQuery(sql); query.addParameter("enable", enable); List<Col> colList = null; if (start > 0 || end > 0) { query.setStart(start); query.setEnd(end); } colList = super.queryForEntities(query); return colList; } /** * 取得表中相应字段最大的值 +1 (用于取得主键) * * @param tableName * 表名 * @param field * 字段名 * @return 最大值 */ public String getStrMaxKey(String tableName, String field) { try { /* 取得最大值 */ String sql = "SELECT MAX(orderid) FROM " + Tables.COL; Query query = createQuery(sql); int max = 0; max = this.queryForInteger(query); if (max + "" == null) { return "0"; } /* 最大值+1 */ max++; return max + ""; } catch (Exception e) { return "0"; } } /** * 当栏目下信息有变动时flag+1 * * @param ids * 栏目id集合 * @return true - 成功<br/> * false - 失败 */ public boolean updateFlag(List<Integer> ids) { String sql = "UPDATE " + Tables.COL + " SET flag=flag+1 WHERE iid IN (:ids)"; Query query = createQuery(sql); query.addParameter("ids", ids); int row = super.execute(query); return row > 0; } /** * 当栏目下信息有变动时flag+1 * * @param ids * 栏目id集合 * @return true - 成功<br/> * false - 失败 */ public boolean updateInfonum(List<Integer> ids, int infonum) { String sql = "UPDATE " + Tables.COL + " SET infonum=infonum+"+infonum+" WHERE iid IN (:ids)"; Query query = createQuery(sql); query.addParameter("ids", ids); int row = super.execute(query); return row > 0; } /** * 通用查询栏目的sql语句 * @return sql */ private String getSql() { String sql = "SELECT a.iid, a.name, a.userid,a.type, a.firstpicshow,a.pid," + "(SELECT name FROM " + Tables.COL + " WHERE iid = a.pid) pname," + "(SELECT name FROM " + Tables.COL + " WHERE iid = a.bannerid) bannername," + "(SELECT lightAppName FROM " + Tables.COL + " WHERE iid = a.iid) lightAppName," + "(SELECT url FROM " + Tables.LIGHTAPP + " WHERE iid = a.lightappid) lightAppUrl," + "(SELECT taskid FROM " + Tables.COLRELATION + " WHERE colid = a.iid) taskid," + "(SELECT taskname FROM " + Tables.COLRELATION + " WHERE colid = a.iid) taskname," + "a.audittype,a.limittime,a.infolisttype,a.infocontenttype,a.collisttype,a.domain," + "a.iconpath,a.enable,a.spec,a.hdtype,a.bgcolor," + "a.blogtype,a.nickname,a.acturl,a.siteid,a.orderid,a.bookorderid,a.flag," + "a.synperiod,a.starttime,a.isjsearch,a.isvisit,a.lastupdatetime,a.iscomment,a.createtime," + "a.offlinenum,a.listtype,a.collevel,a.commontype,a.bannerid,a.sorttype,a.imguuid," + "a.issearch, a.infonum,a.lightappid, a.showtype, a.sourceurl, " + "a.sourcename, a.sourcepwd, a.sourcetype, a.coltype, a.filterreg, a.ditchid, a.newlightappid, a.applayout " +" FROM "+ Tables.COL + " a"; return sql; } /** * 更新任务id的orderid * @param orderid * 排序id * @param iid * 任务id * @return true/false */ public boolean updateOrderIdById(Integer orderid, int iid) { UpdateSql sql = new UpdateSql(Tables.COL); sql.addInt("orderid", orderid); sql.setWhere("iid = :iid"); sql.addWhereParamInt("iid", iid); return this.update(sql); } /** * 更新任务id的subscribeorderid * @param subscribeorderid * 订阅排序id * @param iid * id * @return true/false */ public boolean updateSubscribeOrderIdById(Integer subscribeorderid, int iid) { UpdateSql sql = new UpdateSql(Tables.COL); sql.addInt("subscribeorderid", subscribeorderid); sql.setWhere("iid = :iid"); sql.addWhereParamInt("iid", iid); return this.update(sql); } /** * 获取网站下面最小的栏目id * * @param siteid * 网站id * @return 栏目id */ public int findMinId(int siteid) { int iid = 0; String sql = "SELECT MIN(iid) FROM " + Tables.COL + " WHERE siteid = :siteid"; Query query = createQuery(sql); query.addParameter("siteid", siteid); iid = this.queryForInteger(query); return iid; } /** * 通过网站id查找该网站下栏目数目 * * @param siteId * 网站id * @return 栏目数目 */ public int findColNumBySiteId(int siteId) { String sql = "SELECT COUNT(1) FROM " + Tables.COL + " WHERE siteid = :siteid"; Query query = this.createQuery(sql); query.addParameter("siteid", siteId); int num = this.queryForInteger(query); return num; } /** * 通过栏目id和导航id获取栏目 * @param channelId Integer * @param flagNew boolean * @return List<Col> */ public List<Col> complete(Integer channelId, boolean flagNew) { String sql = "SELECT b.iid,b.name,b.siteid,a.orderid,b.infolisttype,b.infocontenttype," + " b.collisttype,b.type,b.acturl,b.showtype,b.acttype,b.enable,b.visit,b.issearch " + " FROM "+ Tables.CHANNEL_COLUMN+ " a,"+ Tables.COL+ " b " + " WHERE a.colid=b.iid AND a.channelid=:channelid"; if (!flagNew) { sql += " AND b.type<>3 AND b.type<>4"; } sql += " ORDER BY a.i_orderid ASC"; Query query = createQuery(sql); query.addParameter("channelid", channelId); return this.queryForEntities(query); } /** * 修改启用状态 * @param col Col * @param enable Integer * @return boolean */ public boolean updateEnable(Col col, Integer enable) { UpdateSql updateSql = new UpdateSql(Tables.COL); updateSql.addInt("enable", col.getEnable()); String where = " siteid=:siteid AND type=:type AND enable=:enab "; updateSql.setWhere(where); updateSql.addWhereParamInt("siteid", col.getSiteId()); updateSql.addWhereParamInt("type", col.getType()); updateSql.addWhereParamInt("enab", enable); return super.update(updateSql); } /** * 修改栏目的首图路径 * @param colEn 栏目实体 * @return boolean */ public boolean updateFirstPath(Col colEn) { if(colEn==null || colEn.getIid()<=0){ return false; } UpdateSql sql = new UpdateSql(Tables.COL); sql.addString("infotitle", colEn.getInfoTitle()+""); sql.setWhere("iid=:iid"); sql.addWhereParamInt("iid", colEn.getIid()); return this.update(sql); } /** * 通过网站id查找该网站下栏目数目 * @param siteId * 网站id * @param type * 栏目类型 * @return 数目 */ public int findColNumBySiteId(int siteId , Integer type) { String sql = "SELECT COUNT(1) FROM " + Tables.COL + " WHERE siteid = :siteid"; if(NumberUtil.getInt(type)<=3){ sql = sql + " AND type = :type"; } Query query = this.createQuery(sql); query.addParameter("siteid", siteId); query.addParameter("type", NumberUtil.getInt(type)); int num = this.queryForInteger(query); return num; } /** * 通过网站id获取该网站下离线信息条数 * @param siteId int * @return List<Col> */ public List<Col> findAllOfflineBySiteId(int siteId){ String sql = getSql() + " WHERE a.siteid=:siteid AND a.offlinenum > 0"; Query query = this.createQuery(sql); query.addParameter("siteid", siteId); return queryForEntities(query); } /** * 通过网站id获取栏目 * @param siteId int * @return List<Col> */ public List<Col> findColBySiteId(int siteId){ String sql = getSql() + " WHERE a.siteid=:siteid"; Query query = this.createQuery(sql); query.addParameter("siteid", siteId); return queryForEntities(query); } /** * 获得频道下栏目list * @param chanid 频道id * @return List<Col> */ public List<Col> findColByChanId(int chanid){ String sql = getSql() + " , " + Tables.CHANNEL_COLUMN + " b WHERE a.iid=b.colid AND b.channelid=:chanid AND a.enable=1"; sql = sql.replace("a.orderid", "b.orderid"); Query query = this.createQuery(sql); query.addParameter("chanid", chanid); return queryForEntities(query); } /** * 获得该网站下所有支持订阅的栏目 * @param siteId 网站id * @return List<Col> */ public List<Col> findSubscribeColBySiteId(int siteId){ String sql = "SELECT a.iid, a.name, a.userid,a.type, a.firstpicshow,a.pid," + "(SELECT name FROM " + Tables.COL + " WHERE iid = a.pid) pname," + "(SELECT name FROM " + Tables.COL + " WHERE iid = a.bannerid) bannername," + "b.dimensionid AS bookdimensionid," + "a.audittype,a.limittime,a.infolisttype,a.infocontenttype,a.collisttype," + "a.iconpath,a.enable,a.spec,a.hdtype," + "a.blogtype,a.nickname,a.acturl,a.siteid,b.orderid,a.bookorderid,a.flag," + "a.synperiod,a.starttime,a.isjsearch,a.isvisit,a.showtype," + "a.offlinenum,a.listtype,a.collevel,a.commontype,a.bannerid,a.iscomment,a.issearch " + " FROM "+Tables.COL + " a, " + Tables.DIMENSIONREL + " b WHERE a.iid=b.attrid AND b.moduleid=2 AND b.siteid=:siteid AND a.enable=1"; Query query = this.createQuery(sql); query.addParameter("siteid", siteId); return this.queryForEntities(query); } public List<Col> findByPidAndSiteId(Integer pId, Integer siteId, Integer orderId) { String sql = getSql(); sql += " WHERE a.siteid =:siteId AND a.enable = 1"; if (NumberUtil.getInt(pId) > 0) { sql += " AND a.pid =:pId"; } else { sql += " AND a.pid IS NULL"; } if(orderId != null){ sql += " AND a.orderid > :orderId"; } sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("pId", pId); query.addParameter("orderId", orderId); query.addParameter("siteId", siteId); List<Col> colList = super.queryForEntities(query); return colList; } /** * 根据应用iid查找所有关联栏目 * @param iid * @param siteId * @return */ public List<Col> findByLightAppId(Integer iid,Integer siteId) { String sql = getSql(); sql += " WHERE a.siteid =:siteId "; if (NumberUtil.getInt(iid) > 0) { sql += " AND a.lightappid =:iid"; } Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("siteId", siteId); List<Col> colList = super.queryForEntities(query); return colList; } /** * 修改栏目中应用名 * @param iid * @param name * @return */ public boolean modifyLightAppName(Integer iid, String name) { String sql = "UPDATE " + Tables.COL + " SET lightappname=:name, name=:name" + " WHERE lightappid=:iid"; Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("name", name); int row = super.execute(query); return row > 0; } /** * 根据url查找是否存在栏目调用 * @param url * @return */ public int findCountByUrl(String url, int siteId) { String sql = "SELECT COUNT(*) FROM " + Tables.COL + " WHERE sourceurl=:url AND siteid=:siteId"; Query query = createQuery(sql); query.addParameter("url", url); query.addParameter("siteId", siteId); return this.queryForInteger(query); } /** * 根据type类型查找子栏目 * @param colId * @param siteId * @param type * @return */ public List<Col> findChildColByIidAndType(Integer colId, Integer siteId, int type) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL+ " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,a.type,a.orderid" + " FROM "+ Tables.COL + " a "; sql += " WHERE a.type =:type "; if (NumberUtil.getInt(colId) > 0) { sql += "AND a.pid=:iid"; } else { sql += "AND a.pid IS NULL"; } sql += " AND a.siteId =:siteId"; sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", colId); query.addParameter("siteId", siteId); query.addParameter("type", type); return super.queryForEntities(query); } /** * 查出非父栏目的其他信息列表类型栏目 * @param colId * @param siteId * @param type * @return */ public List<Col> findColByColIdAndType(int colId, Integer siteId, int type) { String sql = "SELECT a.iid, a.name, a.pid,a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL+ " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent,a.type,a.orderid" + " FROM "+ Tables.COL + " a "; sql += " WHERE a.type =:type "; if (NumberUtil.getInt(colId) > 0) { sql += "AND a.iid!=:iid"; } else { sql += "AND a.pid IS NOT NULL"; } sql += " AND a.siteId =:siteId"; sql += " ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", colId); query.addParameter("siteId", siteId); query.addParameter("type", type); return super.queryForEntities(query); } public boolean findCountByAppTypeName(String name){ String sql = "SELECT COUNT(*) FROM " + Tables.COL + " WHERE name=:name"; Query query = createQuery(sql); query.addParameter("name", name); return this.queryForInteger(query)>0; } /** * 根据类型获得iid */ public int findIidByAppTypeName(String name){ String sql = "SELECT iid FROM " + Tables.COL + " WHERE name=:name and pid is null"; Query query = createQuery(sql); query.addParameter("name", name); return this.queryForInteger(query); } public boolean findCountByPidAndKeyValue(int pid, String keyValue){ String sql = "SELECT COUNT(*) FROM " + Tables.COL + " WHERE pid=:pid AND keyvalue=:keyvalue"; Query query = createQuery(sql); query.addParameter("pid", pid); query.addParameter("keyvalue", keyValue); return this.queryForInteger(query)>0; } public boolean updateCol(String name,String keyValue) { UpdateSql sql = new UpdateSql(Tables.COL); sql.addString("name", name); sql.addString("lightappname", name); sql.setWhere("keyvalue = :keyvalue"); sql.addWhereParamString("keyvalue", keyValue); return super.update(sql); } /** * 通过keyValue删除栏目 */ public boolean deleteBykeyValue(String keyValue) { String sql = "DELETE FROM " + Tables.COL + " WHERE keyvalue=:keyvalue"; Query query = createQuery(sql); query.addParameter("keyvalue", keyValue); return this.delete(query); } /** * 根据渠道url查找栏目实体 * @param url * @param siteId * @return */ public List<Col> findBySourceUrl(String url, int siteId) { String sql = getEntitySql() + " WHERE sourceurl=:url AND siteid=:siteId"; Query query = createQuery(sql); query.addParameter("url", url); query.addParameter("siteId", siteId); return this.queryForEntities(query); } /** * 查询该权限下的子栏目 * @param iid * @param siteId * @param list * @return */ public List<Col> findChildColByIidAndList(int iid, int siteId, List<Integer> list) { String sql = "SELECT a.iid, a.name, a.pid, a.siteid, CASE WHEN EXISTS(SELECT 1 FROM " + Tables.COL + " b WHERE b.pid = a.iid) THEN 1 ELSE 0 END isparent," + " a.type,a.orderid,a.enable,a.createtime,a.coltype " + " FROM "+ Tables.COL + " a "; if (NumberUtil.getInt(iid) > 0) { sql += "WHERE a.pid=:iid"; } else { sql += "WHERE a.pid IS NULL"; } if (NumberUtil.getInt(siteId) > 0) { sql += " AND a.siteid=:siteId"; } sql += " AND a.iid IN (:list) ORDER BY a.orderid ASC"; Query query = createQuery(sql); query.addParameter("iid", iid); query.addParameter("list", list); query.addParameter("siteId", siteId); return super.queryForEntities(query); } }
true
7e34cada23a051feebf459c57c14249210196d25
Java
zxin-git/zjs-grape
/src/test/java/com/zxin/java/spring/utils/UnixTimeStampUtilsTest.java
UTF-8
382
2.1875
2
[]
no_license
package com.zxin.java.spring.utils; import org.junit.Test; public class UnixTimeStampUtilsTest { @Test public void timestamp() { System.out.println(UnixTimeStampUtils.timeSecond(1583379547L)); } @Test public void timeMill() { System.out.println(UnixTimeStampUtils.timeMill(1583379547567L)); } @Test public void time() { } }
true
aedffbd70667a7cdad44257a31d3e4d3f9bba061
Java
androidok/KTV
/ktv_portrait/src/main/java/com/beidousat/karaoke/ui/fragment/setting/FmSettingRoomInfo.java
UTF-8
10,327
1.671875
2
[]
no_license
package com.beidousat.karaoke.ui.fragment.setting; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.beidousat.karaoke.R; import com.beidousat.karaoke.ui.dialog.PromptDialogBig; import com.beidousat.karaoke.ui.dialog.PromptDialogSmall; import com.beidousat.karaoke.ui.fragment.BaseFragment; import com.beidousat.karaoke.util.FragmentUtil; import com.beidousat.karaoke.util.UIUtils; import com.bestarmedia.libcommon.data.DeviceInfoData; import com.bestarmedia.libcommon.data.NodeRoomInfo; import com.bestarmedia.libcommon.data.PrefData; import com.bestarmedia.libcommon.data.VodConfigData; import com.bestarmedia.libcommon.eventbus.BusEvent; import com.bestarmedia.libcommon.eventbus.EventBusId; import com.bestarmedia.libcommon.eventbus.EventBusUtil; import com.bestarmedia.libcommon.helper.LoginHelper; import com.bestarmedia.libcommon.http.BaseHttpRequest; import com.bestarmedia.libcommon.interf.CheckDeviceListener; import com.bestarmedia.libcommon.model.node.Author; import com.bestarmedia.libcommon.model.v4.DeviceType; import com.bestarmedia.libcommon.model.v4.NodeRoom; import com.bestarmedia.libcommon.model.v4.RoomDevice; import com.bestarmedia.libcommon.model.vod.login.DeviceInfo; import com.bestarmedia.libcommon.util.DeviceUtil; import com.bestarmedia.libwidget.recycler.HorizontalDividerItemDecoration; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import java.util.Objects; public class FmSettingRoomInfo extends BaseFragment implements View.OnClickListener, CheckDeviceListener { private View mRootView; private TextView tv_roomName, tv_roomCode, tv_ktvName, tv_ktvID; private RecyclerView recyclerView; private Adapter adapter; private LoginHelper loginHelper; @NonNull @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.setting_room_info, null); mRootView.findViewById(R.id.iv_back).setOnClickListener(this); mRootView.findViewById(R.id.setting_room_tv_updata_roomName).setOnClickListener(this); mRootView.findViewById(R.id.setting_room_tv_logout).setOnClickListener(this); tv_roomName = mRootView.findViewById(R.id.setting_room_tv_roomName); tv_roomCode = mRootView.findViewById(R.id.setting_room_tv_roomCode); tv_ktvName = mRootView.findViewById(R.id.setting_room_tv_ktvName); tv_ktvID = mRootView.findViewById(R.id.setting_room_tv_ktvCode); tv_ktvName.setText(VodConfigData.getInstance().getKtvName()); tv_ktvID.setText(VodConfigData.getInstance().getKtvNetCode()); recyclerView = mRootView.findViewById(R.id.room_setting_rv); adapter = new Adapter(getContext()); recyclerView.setAdapter(adapter); HorizontalDividerItemDecoration horDivider = new HorizontalDividerItemDecoration.Builder(getContext()) .color(Color.TRANSPARENT).size(25).build(); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.addItemDecoration(horDivider); loginHelper = LoginHelper.getInstance(getContext()); loginHelper.setCheckDeviceListener(this); loginHelper.getRoomInfo(VodConfigData.getInstance().getRoomCode()); EventBus.getDefault().register(this); return mRootView; } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.iv_back: EventBusUtil.postSticky(EventBusId.Id.BACK_FRAGMENT, ""); break; case R.id.setting_room_tv_logout: if (DeviceInfoData.getInstance().getNodeRoom() != null && DeviceInfoData.getInstance().getNodeRoom().roomDeviceList != null && DeviceInfoData.getInstance().getNodeRoom().roomDeviceList.size() > 0) { showLogoutDialog(); } else { Toast.makeText(getContext(), "没有绑定设备", Toast.LENGTH_SHORT).show(); } break; case R.id.setting_room_tv_updata_roomName: FragmentUtil.addFragment(new FmSettingRoomName(), false, true, true, true); break; } } private void showLogoutDialog() { PromptDialogBig promptDialogBig = new PromptDialogBig(getActivity()); promptDialogBig.setTitle(R.string.setting_room_logout_title); promptDialogBig.setMessage(R.string.setting_room_logout_content); promptDialogBig.setOkButton(true, "确定", v -> { if (!TextUtils.isEmpty(DeviceInfoData.getInstance().getLocalId())) { loginHelper.logout(DeviceInfoData.getInstance().getLocalId()); } else { Toast.makeText(getContext(), "房间信息不存在", Toast.LENGTH_SHORT).show(); } }); promptDialogBig.show(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(BusEvent busEvent) { switch (busEvent.id) { case EventBusId.Id.KTV_ROOM_CODE_CHANGED: tv_roomName.setText(NodeRoomInfo.getInstance().getRoomName()); break; case EventBusId.Id.KTV_ROOM_DEVCE_CHANGED: if (loginHelper != null) { loginHelper.getRoomInfo(VodConfigData.getInstance().getRoomCode()); } break; } } @Override public void onDeviceInfoSucced(DeviceInfo deviceInfo) { } @Override public void onDeviceInfoFail(String msg) { } @Override public void onRegister(boolean isSucced, String msg) { } @Override public void onGetJwt(String jwt) { } @Override public void onNodeRoom(NodeRoom nodeRoom) { DeviceInfoData.getInstance().setNodeRoom(nodeRoom); if (!TextUtils.isEmpty(nodeRoom.roomCode)) { tv_roomCode.setText(nodeRoom.roomCode); } if (!TextUtils.isEmpty(nodeRoom.ktvRoomCode)) { tv_roomName.setText(nodeRoom.ktvRoomCode); } if (nodeRoom.roomDeviceList != null && nodeRoom.roomDeviceList.size() > 0) { for (RoomDevice roomDevice : nodeRoom.roomDeviceList) { if (roomDevice.serialNo.equalsIgnoreCase(DeviceUtil.getCupSerial())) { DeviceInfoData.getInstance().setLocalId(roomDevice.id); } } adapter.setData(nodeRoom.roomDeviceList); adapter.notifyDataSetChanged(); } } @Override public void onLogout(boolean succed, String msg) { if (succed) { showDlgTips(); } } private void showDlgTips() { PrefData.setJWT(getContext(), ""); VodConfigData.getInstance().setJwtMessage(null); BaseHttpRequest.setToken(null); PromptDialogSmall promptDialogSmall = new PromptDialogSmall(getActivity()); promptDialogSmall.setTitle(R.string.setting_room_logout_succed_title); promptDialogSmall.setMessage(R.string.setting_room_logout_succed_content); promptDialogSmall.setOkButton(true, "重启", v -> { EventBusUtil.postSticky(EventBusId.PresentationId.MAIN_PLAYER_STOP, null); UIUtils.hideNavibar(getContext(), false); getActivity().finish(); android.os.Process.killProcess(android.os.Process.myPid());//获取PID System.exit(0);//直接结束程序 }); promptDialogSmall.show(); } @Override public void onDeviceType(List<DeviceType> deviceTypeList) { } @Override public void onAuthor(Author author) { } private class Adapter extends RecyclerView.Adapter<ViewHolder> { private LayoutInflater mInflater; private List<RoomDevice> roomDeviceList; private Adapter(Context context) { mInflater = LayoutInflater.from(context); } public void setData(List<RoomDevice> list_roomDevice) { this.roomDeviceList = list_roomDevice; } @Override public int getItemCount() { return roomDeviceList == null ? 0 : roomDeviceList.size(); } @Override @NonNull public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, final int i) { View view = mInflater.inflate(R.layout.setting_room_info_rvitem, viewGroup, false); final ViewHolder viewHolder = new ViewHolder(view); viewHolder.tv_device = view.findViewById(R.id.setting_room_item_tv_device); viewHolder.tv_device_info = view.findViewById(R.id.setting_room_item_tv_device_info); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) { RoomDevice roomDevice = roomDeviceList.get(i); if (roomDevice.serialNo.equalsIgnoreCase(DeviceUtil.getCupSerial())) { viewHolder.tv_device.setText("( 本机 ) " + roomDevice.name); } else { viewHolder.tv_device.setText(roomDevice.name); } viewHolder.tv_device_info.setText(roomDevice.ip); } } public static class ViewHolder extends RecyclerView.ViewHolder { private TextView tv_device, tv_device_info; public ViewHolder(View view) { super(view); } } }
true
623438477a2aad05ce21bbad651dc5f56c36b7ad
Java
Nilhcem/xebia-android-flaws
/03-coding-confessional/src/main/java/com/example/codingconfessional/models/Secret.java
UTF-8
632
2.28125
2
[]
no_license
package com.example.codingconfessional.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Secret { private String mAuthor; private String mContent; @JsonProperty("author") public String getAuthor() { return mAuthor; } public void setAuthor(String author) { mAuthor = author; } @JsonProperty("content") public String getContent() { return mContent; } public void setContent(String content) { mContent = content; } }
true
89d17abc1d162040d5167c2a120bfb1e633ace17
Java
sayederfanarefin/springboot-backend-hr-module
/src/main/java/com/sweetitech/hrm/controller/superadmin/SuperAdminLeaveController.java
UTF-8
2,375
2.15625
2
[]
no_license
package com.sweetitech.hrm.controller.superadmin; import com.sweetitech.hrm.common.Constants; import com.sweetitech.hrm.common.exception.EntityNotFoundException; import com.sweetitech.hrm.domain.LeaveStatus; import com.sweetitech.hrm.domain.dto.LeaveDTO; import com.sweetitech.hrm.domain.dto.LeaveResponseDTO; import com.sweetitech.hrm.service.implementation.LeaveServiceImpl; import com.sweetitech.hrm.service.mapping.LeaveCreateMapper; import com.sweetitech.hrm.service.mapping.LeaveResponseMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/super-admin/leaves") public class SuperAdminLeaveController { private LeaveServiceImpl leaveService; @Autowired private LeaveCreateMapper leaveCreateMapper; @Autowired private LeaveResponseMapper leaveResponseMapper; @Autowired public SuperAdminLeaveController(LeaveServiceImpl leaveService) { this.leaveService = leaveService; } // Update Leave @RequestMapping(value = "/{leaveId}", method = RequestMethod.PUT) public LeaveResponseDTO updateLeave(@PathVariable Long leaveId, @RequestBody LeaveDTO dto) throws Exception { if(leaveId == null) { throw new EntityNotFoundException("Null leave id found!"); } if (dto == null) { throw new EntityNotFoundException("No leave details found!"); } return leaveResponseMapper.map(leaveService.update(leaveId, leaveCreateMapper.map(dto))); } @RequestMapping(value = "/status/{leaveId}", method = RequestMethod.PUT) public LeaveResponseDTO updateStatus(@PathVariable Long leaveId, @RequestParam Long userId, @RequestParam String status, @RequestParam String reason) throws Exception { if(leaveId == null) { throw new EntityNotFoundException("Null leave id found!"); } if(userId == null) { throw new EntityNotFoundException("Null user id found!"); } LeaveStatus leaveStatus = leaveService.prepareStatus(status, userId, reason); return leaveResponseMapper.map(leaveService.updateStatus(leaveId, leaveStatus)); } }
true
0358557ae9e79660a12841bf7af222ff0e8e33ae
Java
wenyadi/Calculator
/Source Code/Calc/src/main/visual/VisualControl.java
UTF-8
3,509
2.796875
3
[]
no_license
package main.visual; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import main.audio.AudioPresentation; public class VisualControl implements ActionListener { JTextArea textArea = new JTextArea(); JTextField textField = new JTextField(); VisualAbstraction visualAbstraction = new VisualAbstraction(); AudioPresentation audioPresentation = new AudioPresentation(); public void textFieldProcess(final JTextArea textArea) { this.textArea = textArea; textArea.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub System.out.println("remove"); String input = textArea.getText(); System.out.println(input); } @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub System.out.println("insert"); String input = textArea.getText(); System.out.println(input); } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub System.out.println("changed"); String input = textArea.getText(); System.out.println(input); } }); } public void setTextField(JTextField input) { this.textField = input; } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); textArea.append(Integer.toString(number)); audioPresentation.Speak(Integer.toString(number)); } else if (command.equals("(")) { textArea.append("("); audioPresentation.Speak("Open parenthese"); } else if (command.equals(")")) { textArea.append(")"); audioPresentation.Speak("Close parenthese"); } else if (command.equals("+")) { textArea.append("+"); audioPresentation.Speak("plus"); } else if (command.equals("-")) { textArea.append("-"); audioPresentation.Speak("minus"); } else if (command.equals("*")) { textArea.append("*"); audioPresentation.Speak("multiply"); } else if (command.equals("^")) { textArea.append("^"); audioPresentation.Speak("power of"); } else if (command.equals("=")) { String result = null; if (!textArea.getText().contains("=")) { if (textArea.getText().trim().length() > 0) { result = visualAbstraction.eval(textArea.getText()); textArea.append("="); audioPresentation.Speak(textArea.getText()); textArea.append(result); audioPresentation.Speak(result.replaceAll("\\-", "negative").replaceAll("\\.0", "")); } textField.setText("$$ " + textArea.getText().replaceAll("\\^(\\-?\\d+)", "^ { $1 }") + " $$"); } } else if (command.equals("C")) { textArea.setText(""); } else if (command.equals("Del")) { System.out.println("Del"); audioPresentation.Speak("Delete"); try { textArea.setText(textArea.getText().substring(0, textArea.getText().length() - 1)); } catch (StringIndexOutOfBoundsException exception) { } } else if (command.equals("Quit")) { System.out.println("Quit"); System.exit(0); } else { System.err.println("No such button"); } } }
true
d8a7020b1c0ac29eb38ee3d4dc199ab636d1a0c8
Java
nayeemahmed24/eShop-Website
/Daraz/src/main/java/com/daraz/service/HomeSliderService.java
UTF-8
611
2.15625
2
[]
no_license
package com.daraz.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.daraz.obj.HomeSlider; import com.daraz.repo.HomeSliderRepo; @Service public class HomeSliderService { @Autowired private HomeSliderRepo homeSliderRepo; public List<HomeSlider> getAll(){ List<HomeSlider> all = new ArrayList<HomeSlider>(); homeSliderRepo.findAll().forEach(all::add);; return all; } public String deleteOne(String id) { homeSliderRepo.delete(id); return "Deleted"; } }
true
bb34fe77ecbf202fd10b5ebe933a12ddabf1d58a
Java
ignesious/MyDataStructures
/DataStructures/src/LinkedList/LinkedListTwo.java
UTF-8
10,573
3.234375
3
[]
no_license
package LinkedList; import java.util.ArrayList; public class LinkedListTwo { ListNode head; ListNode headTwo; ListNode slowPointPali; ListNode fastPointPali; ListNode reverseCheck; ListNode newHead; ListNode slowcut ; int reorderSwitch=1; ArrayList<Integer> storeNodeValue = new ArrayList<Integer>(); static LinkedListTwo demo; static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public void traversalList(ListNode n) { // ListNode n = head; while (n != null) { System.out.print(n.val + "------>"); n = n.next; } System.out.println("NULL"); } public String findelemRecursive(ListNode findElem, int key) { if (findElem == null) return "Not Found"; else if (key == findElem.val) return "Found the value " + key; else return findelemRecursive(findElem.next, key); } public ListNode reversUtil(ListNode curr, ListNode prev) { if (curr.next == null) { demo.reverseCheck = curr; curr.next = prev; return null; } else { ListNode next = curr.next; curr.next = prev; reversUtil(next, curr); } return null; } public ListNode reversUtilPali(ListNode curr, ListNode prev) { if (curr.next == null) { demo.head = curr; curr.next = prev; return null; } else { ListNode next = curr.next; curr.next = prev; reversUtil(next, curr); } return null; } public ListNode returnSlowFastPalindrome(ListNode curr) { slowPointPali = curr; slowcut = slowPointPali; fastPointPali = slowPointPali; while (fastPointPali != null && fastPointPali.next != null) { slowcut = slowPointPali; slowPointPali = slowPointPali.next; fastPointPali = fastPointPali.next.next; } slowcut.next = null; return slowPointPali; } // Floyd Cycle Detection Algorithm. public void detectLoop(ListNode slowPoint, ListNode fastPoint) { // ListNode slowPoint = demo.head; // ListNode fastPoint = demo.head; while (slowPoint != null && fastPoint != null && fastPoint.next != null) { slowPoint = slowPoint.next; fastPoint = fastPoint.next.next; if (slowPoint == fastPoint) { System.out.println("Cycle detected" + slowPoint.val); break; } } return; } public ListNode mergeSortedList(ListNode a, ListNode b) { ListNode result = null; if (a == null) return b; if (b == null) return a; if (a.val <= b.val) { result = a; result.next = mergeSortedList(a.next, b); } else { result = b; result.next = mergeSortedList(a, b.next); } return result; } public void isPalindrome(ListNode check) { boolean isEven = (this.findCount(check) % 2 == 0 ? true : false); boolean isPalindrome = true; ListNode tempNode; ListNode firstPoint, secondPoint; // System.out.println("Middle element is"+(this.returnSlowFastPalindrome(check)).val); this.returnSlowFastPalindrome(check); if (isEven) { // TODO for even block // Reverse the second half; this.reversUtilPali(demo.slowPointPali, null); firstPoint = demo.head; secondPoint = demo.reverseCheck; while (firstPoint != null && secondPoint != null) { if (firstPoint.val != secondPoint.val) { isPalindrome = false; break; } else { firstPoint = firstPoint.next; secondPoint = secondPoint.next; } } System.out.println("The palindrome result is " + isPalindrome); } else { // TODO for odd block tempNode = demo.slowPointPali; demo.slowPointPali = demo.slowPointPali.next; tempNode.next = null; this.reversUtilPali(demo.slowPointPali, null); firstPoint = demo.headTwo; secondPoint = demo.reverseCheck; while (firstPoint != null && secondPoint != null) { if (firstPoint.val != secondPoint.val) { isPalindrome = false; break; } else { firstPoint = firstPoint.next; secondPoint = secondPoint.next; } } System.out.println("The palindrome result is " + isPalindrome); } } public void removeDuplicates(ListNode dupli) { while (dupli != null && dupli.next != null) { if (dupli.val == dupli.next.val) { dupli.next = dupli.next.next; } else { dupli = dupli.next; } } } public void removeDuplicatesUnsorted(ListNode dupli) { while (dupli != null && dupli.next != null) { if ((dupli.val != dupli.next.val) && !(demo.storeNodeValue.contains(dupli.next.val))) { System.out.println("distint first value storing in array" + dupli.val); demo.storeNodeValue.add(dupli.val); dupli = dupli.next; } else { System.out.println("elem of array-->" + demo.storeNodeValue + "Duplicate element" + dupli.next.val); dupli.next = dupli.next.next; } } } public void rotateList(ListNode rotatelist, int k) { // Determine k should be mod of length k = k % demo.findCount(rotatelist); if(k!=0){ ListNode slowPoint, fastPoint; slowPoint = rotatelist; fastPoint = slowPoint; while (k != 0) { fastPoint = fastPoint.next; k--; } // Traverse till end of the list while (fastPoint.next != null) { slowPoint = slowPoint.next; fastPoint = fastPoint.next; } // System.out.println("fastpoint in this node" + fastPoint.val + "SlowPoint in " + slowPoint.val); demo.newHead = slowPoint.next; slowPoint.next = null; fastPoint.next = demo.head; } else { System.out.println("Nothing to modify"); } } /* * public void createIntersectionList(ListNode first, ListNode second) { * * while (first != null) { // System.out.print(n.val + "------>"); * demo.storeNodeValue.add(first.val); first = first.next; } while (second * != null) { // System.out.print(n.val + "------>"); if * (demo.storeNodeValue.contains(second.val)) { * * System.out.println("i will add this shit" + second.val); } * * second = second.next; } * * } * * Junk method hence commenting.....!!! */ public void createIntersectionList(ListNode first, ListNode second) { while (first != null && second != null) { if (first.val == second.val) { System.out.println("Intersecting hence will add" + first.val + "second val" + second.val); first = first.next; second = second.next; } else if (first.val < second.val) { first = first.next; } else second = second.next; } } public void reorderList(ListNode check) { boolean isEven = (this.findCount(check) % 2 == 0 ? true : false); ListNode p1, p2,preMiddle; this.returnSlowFastPalindrome(check); if (isEven) { // TODO for even block // Reverse the second half; this.reversUtil(demo.slowPointPali, null); p1 = demo.head; p2 = demo.reverseCheck; preMiddle=demo.slowcut; while(p1!=preMiddle){ preMiddle.next=p2.next; p2.next=p1.next; p1.next=p2; p1=p2.next; p2=preMiddle.next; } } } public int findCount(ListNode n) { // ListNode n = head; int listCount = 0; while (n != null) { // System.out.print(n.val+"------>"); n = n.next; listCount++; } return listCount; } public double traversalandGiveresultList(ListNode n,int lenght) { // ListNode n = head; double finalRes=0; while (n != null) { double calculate=0; //System.out.print(n.val + "------>"); calculate = n.val * Math.pow(10, --lenght); finalRes+=calculate; n = n.next; } return finalRes; } public ListNode createNewList(double finalListvalue) { ListNode finalListhead; String numWihoutDecimal = String.valueOf(finalListvalue).split("\\.")[0]; //System.out.println(numWihoutDecimal); //System.out.println(numWihoutDecimal.length()); char numWithoutDecimalChar[]=numWihoutDecimal.toCharArray(); /*for(char newvalue : numWithoutDecimalChar) { System.out.println(newvalue); }*/ finalListhead=this.createListRecursive(numWithoutDecimalChar, (numWithoutDecimalChar.length)-1, 0); return finalListhead; } public ListNode createListRecursive(char[] tocreate,int lenght,int piker) { ListNode newNode=null; if(lenght == 0) { //last node newNode=new ListNode(Integer.parseInt(tocreate[piker]+"")); return newNode; } else { newNode=new ListNode(Integer.parseInt(tocreate[piker]+"")); piker++; lenght--; newNode.next=this.createListRecursive(tocreate, lenght, piker); } return newNode; } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // int x=0; //int y=0; // System.out.println("Math.pow(" + x + "," + y + ")=" + Math.pow(x, y)); ListNode finalV=null; int firstListLength = this.findCount(l1); int secondListLength = this.findCount(l2); double firstListVal=this.traversalandGiveresultList(l1, firstListLength); double secondListVal=this.traversalandGiveresultList(l2, secondListLength); System.out.println("firstlistval" + firstListVal + "seconListValue"+ secondListVal); double finalListVal = firstListVal+secondListVal; System.out.println("FinalListVal"+finalListVal); finalV=this.createNewList(finalListVal); return finalV; } public static void main(String[] args) { // TODO Auto-generated method stub String list1="9"; String list2="1999999999"; demo = new LinkedListTwo(); demo.head = demo.createListRecursive(list1.toCharArray(), list1.length()-1, 0); demo.headTwo=demo.createListRecursive(list2.toCharArray(), list2.length()-1, 0); demo.traversalList(demo.head); demo.traversalList(demo.headTwo); // demo.traversalList(demo.head); // System.out.println("\n"); // demo.traversalList(demo.head); // demo.createIntersectionList(demo.head, demo.headTwo); //demo.rotateList(demo.head, 17); //System.out.println(" "); // demo.traversalList(demo.newHead); // demo.reorderList(demo.head); // System.out.println(" "); // demo.traversalList(demo.head); //System.out.println(" "); // demo.traversalList(demo.reverseCheck); // System.out.println(" "); demo.addTwoNumbers(demo.head, demo.headTwo); } }
true
49a3ff14650520a827aa48286a2f78fbca9c5a87
Java
DevNebula/android_packages_app_lgcamera
/src/main/java/com/lge/camera/managers/BarManager.java
UTF-8
12,632
2.140625
2
[]
no_license
package com.lge.camera.managers; import android.app.Activity; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import com.lge.camera.C0088R; import com.lge.camera.components.BarAction; import com.lge.camera.components.BarView; import com.lge.camera.components.BarView.BarManagerListener; import com.lge.camera.components.BeautyshotBar; import com.lge.camera.constants.CameraConstants; import com.lge.camera.constants.FunctionProperties; import com.lge.camera.settings.Setting; import com.lge.camera.util.CamLog; import com.lge.camera.util.HandlerRunnable; import com.lge.camera.util.Utils; public class BarManager extends ManagerInterfaceImpl implements BarAction { private static int[] sArrType = new int[]{1, 2, 4}; private SparseArray<BarView> mArrBar = new SparseArray(); public BarManager(ModuleInterface moduleInterface) { super(moduleInterface); } public void setBarListener(int type, BarManagerListener listener) { BarView currentBarView = getBar(type); if (currentBarView != null) { currentBarView.setBarListener(listener); } } public BarManagerListener getBarListener(int type) { BarView currentBarView = getBar(type); if (currentBarView != null) { return currentBarView.getBarListener(); } return null; } public void initBar(int types) { CamLog.m3d(CameraConstants.TAG, "[relighting]on type>" + types); if (this.mArrBar == null) { this.mArrBar = new SparseArray(); } for (int currentType : sArrType) { if ((currentType & types) == currentType) { BarView currentBarView = createBar(currentType); if (currentBarView != null) { this.mArrBar.put(currentType, currentBarView); currentBarView.startRotation(getOrientationDegree(), false); } } } } public BarView createBar(int type) { BeautyshotBar beautybar = (BeautyshotBar) this.mGet.findViewById(C0088R.id.beautyshot_bar); if (beautybar == null) { return null; } switch (type) { case 1: beautybar.setBarSettingKey(Setting.KEY_BEAUTYSHOT); beautybar.initBar(this, type); return beautybar; case 4: CamLog.m3d(CameraConstants.TAG, "[relighting] create TYPE_RELIGHTING_BAR"); beautybar.setBarSettingKey(Setting.KEY_RELIGHTING); beautybar.initBar(this, type); return beautybar; default: return beautybar; } } public void setEnable(int types, boolean enable) { BarView currentBarView = getBar(types); if (currentBarView != null) { currentBarView.initCursor(); currentBarView.setBarEnable(enable); } } public void setVisible(int types, boolean visible, boolean isSingleSet) { CamLog.m3d(CameraConstants.TAG, "types = " + types); int visibility = visible ? 0 : 4; int curDegree = getOrientationDegree(); BarView currentBarView; if (isSingleSet) { currentBarView = getBar(types); if (currentBarView != null && currentBarView.getVisibility() != visibility) { currentBarView.setVisibility(visibility); currentBarView.initCursor(); if (visible) { currentBarView.startRotation(curDegree, false); } } } else if (types == -2) { for (int current : sArrType) { currentBarView = getBar(current); if (currentBarView != null) { currentBarView.setVisibility(visibility); currentBarView.initCursor(); if (visible) { currentBarView.startRotation(curDegree, false); } } } } else { for (int current2 : sArrType) { if ((current2 & types) == current2) { currentBarView = getBar(current2); if (currentBarView != null) { currentBarView.setVisibility(visibility); currentBarView.initCursor(); if (visible) { currentBarView.startRotation(curDegree, false); } } } } } } public BarView getBar(int type) { return this.mArrBar == null ? null : (BarView) this.mArrBar.get(type); } public int getBarValue(int type) { BarView currentBarView = getBar(type); if (currentBarView != null) { return currentBarView.getCursorValue(); } return 0; } public void setBarMaxValue(int type, int maxValue) { BarView currentBarView = getBar(type); if (currentBarView != null) { currentBarView.setMaxValue(maxValue); } } public void destoryAllBar() { if (this.mArrBar != null) { for (int i = 0; i < this.mArrBar.size(); i++) { ((BarView) this.mArrBar.valueAt(i)).unbind(); } this.mArrBar.clear(); } } public void onPauseAfter() { setVisible(-2, false, false); super.onPauseAfter(); } public void onDestroy() { destoryAllBar(); this.mArrBar = null; super.onDestroy(); } public void removePostRunnable(Object object) { this.mGet.removePostRunnable(object); } public void updateAllBars(int types, int value) { int i = 0; int[] iArr; int length; BarView currentBarView; if (types == -2) { iArr = sArrType; length = iArr.length; while (i < length) { currentBarView = getBar(iArr[i]); if (currentBarView != null) { currentBarView.setBarValue(value); currentBarView.setCursor(value); } i++; } return; } iArr = sArrType; length = iArr.length; while (i < length) { int current = iArr[i]; if ((current & types) == current) { currentBarView = getBar(current); if (currentBarView != null) { currentBarView.setBarValue(value); currentBarView.setCursor(value); } } i++; } } public void rotateSettingBar(int types, int degree, boolean useAnim) { int i = 0; int[] iArr; int length; BarView currentBarView; if (types == -2) { iArr = sArrType; length = iArr.length; while (i < length) { currentBarView = getBar(iArr[i]); if (currentBarView != null && currentBarView.getVisibility() == 0) { currentBarView.startRotation(degree, useAnim); } i++; } return; } iArr = sArrType; length = iArr.length; while (i < length) { int current = iArr[i]; if ((current & types) == current) { currentBarView = getBar(current); if (currentBarView != null) { currentBarView.startRotation(degree, useAnim); } } i++; } } public void updateBar(int barType, int step) { BarView currentBarView = getBar(barType); if (currentBarView != null) { if (currentBarView.getVisibility() != 0) { currentBarView.setVisibility(0); currentBarView.startRotation(getOrientationDegree(), false); } currentBarView.updateBar(step, false, false, false); } } public void updateBarWithValue(int barType, int value) { BarView currentBarView = getBar(barType); if (currentBarView != null) { currentBarView.updateBarWithValue(value, false); } } public void updateExtraInfo(int barType, final String info) { final BarView currentBarView = getBar(barType); runOnUiThread(new HandlerRunnable(this) { public void handleRun() { if (currentBarView != null) { currentBarView.updateExtraInfo(info); } } }); } public boolean isBarVisible(int type) { BarView currentBarView = getBar(type); if (currentBarView != null) { return currentBarView.getVisibility() == 0; } else { return false; } } public void setBarRotateDegree(int type, int degree, boolean animation) { BarView currentBarView = getBar(type); if (currentBarView != null) { currentBarView.startRotation(degree, animation); } } public boolean onTouchEvent(MotionEvent event) { return false; } public boolean isPaused() { return this.mGet.isPaused(); } public View findViewById(int id) { return this.mGet.getActivity().findViewById(id); } public String getSettingValue(String key) { return this.mGet.getSettingValue(key); } public String getBarSettingValue(String key) { return getSettingValue(key); } public void runOnUiThread(Object action) { this.mGet.runOnUiThread(action); } public void postOnUiThread(Object action, long delay) { this.mGet.postOnUiThread(action, delay); } public boolean setBarSetting(String key, String value, boolean save) { int barType; if (Setting.KEY_BEAUTYSHOT.equals(key)) { barType = 1; } else if (Setting.KEY_RELIGHTING.equals(key)) { barType = 4; } else if ("zoom".equals(key)) { barType = 2; } else { barType = 0; } BarManagerListener listener = getBarListener(barType); if (listener == null) { return false; } return listener.setBarSetting(key, value, save); } public void resetBarDisappearTimer(int barType, int duration) { BarManagerListener listener = getBarListener(barType); if (listener != null) { listener.resetBarDisappearTimer(barType, duration); } } public void setRotateDegree(int degree, boolean animation) { rotateSettingBar(-2, degree, animation); } public Activity getActivity() { return this.mGet.getActivity(); } public void switchCamera() { if (this.mGet != null && !this.mGet.isCameraChanging() && !this.mGet.isAnimationShowing()) { if (FunctionProperties.isSupportedSwitchingAnimation()) { this.mGet.setGestureType(1); this.mGet.getCurPreviewBlurredBitmap(136, 240, 25, false); this.mGet.startCameraSwitchingAnimation(1); } this.mGet.handleSwitchCamera(); } } public void resumeShutterless() { this.mGet.resumeShutterless(); } public void pauseShutterless() { this.mGet.pauseShutterless(); } public boolean isBarTouching() { BarView currentBarView = getBar(1); if (currentBarView != null) { return currentBarView.isBarTouched(); } BarView currentBarView2 = getBar(4); if (currentBarView2 != null) { return currentBarView2.isBarTouched(); } return false; } public boolean isPreview4by3() { if (this.mGet == null) { return false; } String previewSize; if (this.mGet.getCameraState() == 6 || this.mGet.getCameraState() == 7) { previewSize = this.mGet.getCurrentSelectedVideoSize(); } else { previewSize = this.mGet.getCurrentSelectedPreviewSize(); } return Utils.calculate4by3Preview(previewSize); } public boolean isRearCamera() { if (this.mGet == null) { return false; } return this.mGet.isRearCamera(); } public String getShotMode() { if (this.mGet == null) { return "mode_normal"; } return this.mGet.getShotMode(); } }
true
b244c4997861692bbf10a4a517273f6d15075456
Java
danielzhe/kie-wb-common
/kie-wb-common-screens/kie-wb-common-data-modeller/kie-wb-common-data-modeller-client/src/main/java/org/kie/workbench/common/screens/datamodeller/client/util/DataObjectComparator.java
UTF-8
1,348
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.datamodeller.client.util; import java.util.Comparator; import org.kie.workbench.common.services.datamodeller.core.DataObject; public class DataObjectComparator implements Comparator <DataObject> { @Override public int compare(DataObject o1, DataObject o2) { if (o1 == null && o2 == null) return 0; if (o1 == null && o2 != null) return -1; if (o1 != null && o2 == null) return 1; String key1 = DataModelerUtils.getDataObjectUILabel(o1); String key2 = DataModelerUtils.getDataObjectUILabel(o2); if (key1 != null) return key1.compareTo(key2); if (key2 != null) return key2.compareTo(key1); return 0; } }
true
3d54cb5562854e4ab11f62027f553fb098773099
Java
gaurav21/structotest
/src/main/java/io/github/khangnt/downloader/EventDispatcher.java
UTF-8
4,514
2.578125
3
[]
no_license
package io.github.khangnt.downloader; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import io.github.khangnt.downloader.model.TaskReport; /** * Created by Khang NT on 6/3/17. * Email: khang.neon.1997@gmail.com */ class EventDispatcher implements EventListener { private final List<ListenerWrapper> mListenerList = new ArrayList<ListenerWrapper>(); public void registerListener(Executor executor, EventListener listener) { synchronized (mListenerList) { mListenerList.add(new ListenerWrapper(executor, listener)); } } public void unregisterListener(EventListener listener) { synchronized (mListenerList) { mListenerList.remove(listener); } } public void unregisterAllListener() { synchronized (mListenerList) { mListenerList.clear(); } } @Override public void onTaskAdded(final TaskReport taskReport) { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onTaskAdded(taskReport); } }); } } } @Override public void onTaskUpdated(final TaskReport taskReport) { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onTaskUpdated(taskReport); } }); } } } @Override public void onTaskCancelled(final TaskReport taskReport) { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onTaskCancelled(taskReport); } }); } } } @Override public void onTaskFinished(final TaskReport taskReport) { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onTaskFinished(taskReport); } }); } } } @Override public void onTaskFailed(final TaskReport taskReport) { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onTaskFailed(taskReport); } }); } } } @Override public void onResumed() { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onResumed(); } }); } } } @Override public void onPaused() { synchronized (mListenerList) { for (final ListenerWrapper listenerWrapper : mListenerList) { listenerWrapper.mExecutor.execute(new Runnable() { @Override public void run() { listenerWrapper.mListener.onPaused(); } }); } } } private class ListenerWrapper { private Executor mExecutor; private EventListener mListener; public ListenerWrapper(Executor mExecutor, EventListener mListener) { this.mExecutor = mExecutor; this.mListener = mListener; } @Override public boolean equals(Object o) { return mListener == o; } } }
true
d427ac54f8da4d7b521c55f7b435b8b95a258cb3
Java
JPB117/flexiPayImprovement
/src/main/java/com/icpak/rest/models/membership/ApplicationCategory.java
UTF-8
2,467
2.234375
2
[]
no_license
package com.icpak.rest.models.membership; import java.util.Date; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.icpak.rest.models.base.PO; import com.wordnik.swagger.annotations.ApiModel; import com.workpoint.icpak.shared.model.ApplicationCategoryDto; import com.workpoint.icpak.shared.model.ApplicationType; @ApiModel(description = "Application Category charges") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Entity @Table(name = "ApplicationCategory") public class ApplicationCategory extends PO { /** * */ private static final long serialVersionUID = 1L; @Enumerated(EnumType.STRING) private ApplicationType type; private String description; private double applicationAmount; private Double renewalAmount; private Date renewalDueDate; public ApplicationCategory() { } public ApplicationType getType() { return type; } public void setType(ApplicationType type) { this.type = type; } public double getApplicationAmount() { return applicationAmount; } public void setApplicationAmount(double applicationAmount) { this.applicationAmount = applicationAmount; } public Double getRenewalAmount() { return renewalAmount; } public void setRenewalAmount(Double renewalAmount) { this.renewalAmount = renewalAmount; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ApplicationCategoryDto toDto() { ApplicationCategoryDto category = new ApplicationCategoryDto(); category.setRefId(refId); category.setApplicationAmount(applicationAmount); category.setDescription(description); category.setRenewalAmount(renewalAmount); category.setType(type); return category; } public void copyFrom(ApplicationCategoryDto dto) { setType(dto.getType()); setDescription(dto.getDescription()); setApplicationAmount(dto.getApplicationAmount()); setRenewalAmount(dto.getRenewalAmount()); } public Date getRenewalDueDate() { return renewalDueDate; } public void setRenewalDueDate(Date renewalDueDate) { this.renewalDueDate = renewalDueDate; } }
true
694d02b95fceceeb721b4fd9a0d9df7d3a3a4cfd
Java
sedavSdk/XandOclient_v2.0
/core/src/com/mygdx/game/Player.java
UTF-8
2,685
2.265625
2
[]
no_license
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.freetype.FreeType; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import sun.font.TrueTypeFont; import sun.font.TrueTypeGlyphMapper; public class Player extends Actor { boolean updated = true, inv; String name; int i; Texture texture; Sprite sprite; BitmapFont font; ClickListener listener; LobbyScreen lobby; float y, ny, want_y; public Player(final String name, int i, Texture texture, final LobbyScreen lobby) { this.lobby = lobby; this.texture = texture; this.name = name; this.i = i; this.setZIndex(1); y = 520 - i * 30 + lobby.now_y - 550; ny = 0; font = MyFont.font; sprite = new Sprite(texture); sprite.setBounds(0, y, 300, 30); this.setBounds(0, y, 300, 30); listener = new ClickListener(){ @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { ny = y; want_y = y; inv = true; return super.touchDown(event, x, y, pointer, button); } @Override public void touchDragged(InputEvent event, float x, float y, int pointer) { inv = false; LobbyScreen.move(y - ny); } @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if(inv) lobby.bottomPanel.invite(name); super.touchUp(event, x, y, pointer, button); } }; this.addListener(listener); } public void move(){ i--; y += 30; ny += 30; sprite.setBounds(0, y, 300, 30); this.setBounds(0, y, 300, 30); } @Override public void draw(Batch batch, float parentAlpha) { sprite.draw(batch); font.draw(batch, name, 10, y + 23); } public void scroll(float y){ want_y = y; this.y += want_y; sprite.setBounds(0, this.y, 300, 30); this.setBounds(0, this.y, 300, 30); } @Override public void act(float delta) { super.act(delta); } }
true
83b25eb575dfc760bb097cacd8382cf56fedb19c
Java
nahuelsgk/ichnaea-pfc-nahuel
/amqp/src/test/java/edu/upc/ichnaea/amqp/xml/XmlBuildModelsRequestReaderTest.java
UTF-8
1,951
2.296875
2
[]
no_license
package edu.upc.ichnaea.amqp.xml; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.junit.Test; import org.xml.sax.SAXException; import edu.upc.ichnaea.amqp.IOUtils; import edu.upc.ichnaea.amqp.model.BuildModelsRequest; import edu.upc.ichnaea.amqp.model.Dataset; import edu.upc.ichnaea.amqp.model.DatasetColumn; public class XmlBuildModelsRequestReaderTest { @Test public void testXML() throws SAXException, IOException { String xml = "<request id=\"432\" type=\"build_models\"><dataset>\n"; xml += "<column name=\"test\"><value>1.5</value><value>2</value><value>3</value></column>\n"; xml += "<column name=\"test2\"><value>3</value><value>4</value></column>\n"; xml += "<column name=\"test3\"><value>5</value><value>6</value><value>7</value></column>\n"; xml += "</dataset></request>"; BuildModelsRequest message = new XmlBuildModelsRequestReader() .read(xml); Dataset dataset = message.getDataset(); Collection<String> names = dataset.columnNames(); assertTrue(names.contains("test")); assertEquals(3, names.size()); DatasetColumn column = dataset.get("test"); assertTrue(1.5 == column.get(0).floatValue()); column = dataset.get("test2"); assertEquals(2, column.size()); } @Test public void testBigXML() throws SAXException, IOException { InputStream in = getClass().getClassLoader().getResourceAsStream( "build_models_request.xml"); String xml = new String(IOUtils.read(in)); BuildModelsRequest message = new XmlBuildModelsRequestReader() .read(xml); assertEquals(104, message.getDataset().rows().size()); assertEquals(28, message.getDataset().columns().size()); assertEquals(21, message.getAging().keySet().size()); } }
true
165e988856dbc463e3324bfbad1cf14ce4cd2e47
Java
LancCJ/TrasAddForMultiple
/src/main/java/com/lsm/controller/TransactionController.java
UTF-8
2,722
2.34375
2
[]
no_license
package com.lsm.controller; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.lsm.service.ActionRecordService; import com.lsm.utils.R; @Controller @RequestMapping("/") public class TransactionController { private static final Logger LOGGER = LogManager.getLogger(TransactionController.class); @Autowired private ActionRecordService actionService; //第三方服务地址 @Value("${client.addr}") private String clientUrl; /* * 测试程序部署ok探针 */ @RequestMapping("/conn") @ResponseBody public R conn() { LOGGER.info("test ok"); int total = actionService.queryTotal(null); LOGGER.info(total); return R.ok("success"); } /** * 可以封装成工具类调用 */ public void sendTransactionData() { /* * 构建需要发送的json 数据,这里只是通过hashMap 伪造一个类似的,具体的看业务需求 */ Map<String, Object> map = new HashMap<>(); map.put("data1", "v1"); map.put("data2", "v1"); Gson gson = new Gson(); String json = gson.toJson(map); /* * 通过HttpClient调用第三方地址上报数据(这就是所谓的通讯),可以封装成工具类再调用 */ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(clientUrl); httpPost.setHeader("Content-type", "application/json; charset=utf-8"); StringEntity entity = new StringEntity(json, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); // 发送Json格式的数据请求 entity.setContentType("application/json"); httpPost.setEntity(entity); CloseableHttpResponse execute; try { execute = httpClient.execute(httpPost); HttpEntity resp = execute.getEntity(); String result = EntityUtils.toString(resp, "utf-8"); LOGGER.info(result); } catch (IOException e) { e.printStackTrace(); } } }
true
eb8b3f064b3928bae3b96fbad27ed39896da65fe
Java
a252937166/com.system.service
/src/com/crm/controller/HelloController.java
UTF-8
829
2.1875
2
[]
no_license
package com.crm.controller; import com.crm.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by 欧阳杜泞 on 2016/9/15. */ @Controller @RequestMapping("/hello.action") public class HelloController { @Autowired private HelloService helloService; @RequestMapping(value = "hello",method = RequestMethod.GET) public String hello(String username, Model model) { String name = helloService.hello(); model.addAttribute("username",name); return "hello"; } }
true
b6ac4886f283d7b4574697b4144b621dc5e999ba
Java
NTRsolutions/POSwithQRwithoutGPS
/app/src/main/java/com/example/pef/prathamopenschool/MultiPhotoSelectActivity.java
UTF-8
70,087
1.5625
2
[]
no_license
package com.example.pef.prathamopenschool; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Random; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; //import android.support.annotation.NonNull; public class MultiPhotoSelectActivity extends AppCompatActivity { //\public static TextToSp tts; public ImageAdapter imageAdapter; List<JSONArray> students; List<String> groupNames, assignedIds; StatusDBHelper statusDBHelper; StudentDBHelper studentDBHelper; GroupDBHelper groupDBHelper; TextView tv_title; private RadioGroup radioGroup; private RadioButton radioButton; private Button next; Utility utility; ArrayList<JSONObject> attendenceData; Context sessionContex; boolean timer; String newNodeList; ScoreDBHelper scoreDBHelper; PlayVideo playVideo; public static RelativeLayout myView; public static String deviceID = "DeviceID"; int aajKaSawalPlayed = 3; boolean doubleBackToExitPressedOnce = false; String checkQJson; TextView tv_msg, tv_msgBottom; boolean appName = false; StatusDBHelper s; public static DilogBoxForProcess dilog; private static final int REQUEST_FOR_STORAGE_PERMISSION = 123; static String programID, language; static String sessionId; public static Boolean grpSelectFlag; static String presentStudents[]; static String selectedGroupName; static String selectedGroupId; public static String selectedGroupsScore = ""; static CountDownTimer cd; static Long timeout = (long) 20000 * 60; static Long duration = timeout; static Boolean pauseFlg = false; String ageGrp = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.group_select); startService(new Intent(this, WebViewService.class)); Intent i = getIntent(); ageGrp = i.getStringExtra("ageGroup"); dilog = new DilogBoxForProcess(); grpSelectFlag = true; attendenceData = new ArrayList<>(); ActionBar actBar = getSupportActionBar(); statusDBHelper = new StatusDBHelper(this); studentDBHelper = new StudentDBHelper(this); groupDBHelper = new GroupDBHelper(this); utility = new Utility(); if (sessionId == null) sessionId = utility.GetUniqueID().toString(); sessionContex = this; playVideo = new PlayVideo(); MainActivity.sessionFlg = false; if (assessmentLogin.assessmentFlg) newNodeList = getIntent().getStringExtra("nodeList"); // Generate Unique Device ID deviceID = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID); } public static String getLanguage(Context c) { StatusDBHelper statdb; statdb = new StatusDBHelper(c); return statdb.getValue("TabLanguage"); } public void setSelectedStudents(String groupName) throws IOException { grpSelectFlag = false; //selectedGroupId = groupDBHelper.getGroupIdByName(selectedGroupName); students = new ArrayList<JSONArray>(); students.add(studentDBHelper.getStudentsList(selectedGroupId)); setContentView(R.layout.layout_multi_photo_select); populateImagesFromGallery(); } public void setLanguage() { String langString = null; try { File myJsonFile = new File(Environment.getExternalStorageDirectory() + "/.POSinternal/Json/Config.json"); FileInputStream stream = new FileInputStream(myJsonFile); String jsonStr = null; try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); jsonStr = Charset.defaultCharset().decode(bb).toString(); } catch (Exception e) { e.printStackTrace(); } finally { stream.close(); } JSONObject jsonObj = new JSONObject(jsonStr); langString = jsonObj.getString("programLanguage"); StatusDBHelper sdb; sdb = new StatusDBHelper(MultiPhotoSelectActivity.this); sdb.Update("TabLanguage", langString); BackupDatabase.backup(MultiPhotoSelectActivity.this); } catch (Exception e) { e.printStackTrace(); } } public void btnChoosePhotosClick(View v) throws JSONException { if (sessionId == null) sessionId = utility.GetUniqueID().toString(); selectedGroupsScore = ""; Attendance attendance = null; AttendanceDBHelper attendanceDBHelper = new AttendanceDBHelper(this); SessionDBHelper sessionDBHelper = new SessionDBHelper(this); Session s = new Session(); s.SessionID = MultiPhotoSelectActivity.sessionId; s.StartTime = new Utility().GetCurrentDateTime(false); s.EndTime = "NA"; sessionDBHelper.Add(s); // If no student present in RI if (programID.equals("2") && students.get(0).length() == 0) { presentStudents = new String[1]; presentStudents[0] = "RI"; try { attendance = new Attendance(); attendance.SessionID = sessionId; attendance.PresentStudentIds = "RI"; attendance.GroupID = selectedGroupId; if (!selectedGroupsScore.contains(attendance.GroupID)) { selectedGroupsScore += attendance.GroupID + ","; } attendanceDBHelper.Add(attendance); BackupDatabase.backup(this); /* -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- AAJ KA SAWAAL PLAYED ? -*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*- */ // Decide the next screen depending on aajKaSawalPlayed status // Get Current Date String currentDate = utility.GetCurrentDate(); // Get Currently Selected Group String currentlySelectedGroup = selectedGroupId; // Fetch records StatusDBHelper sdbh = new StatusDBHelper(sessionContex); List<String> AKSRecords = sdbh.getAKSRecordsOfSelectedGroup(currentlySelectedGroup); // Loop to get Aaj Ka Sawaal Played Status if (!AKSRecords.equals(null)) { if (AKSRecords.size() == 0) { // No Record Found aajKaSawalPlayed = 0; } for (int i = 0; i < AKSRecords.size(); i++) { if (AKSRecords.get(i).contains(currentDate)) { // If Record Found i.e Aaj Ka Sawaal Played aajKaSawalPlayed = 1; } else { // If Record NOT Found i.e Aaj Ka Sawaal Played aajKaSawalPlayed = 0; } } } /*// if Questions.json not present JSONArray queJsonArray = null; try { checkQJson = loadQueJSONFromAsset(); } catch (Exception e) { e.printStackTrace(); } if (checkQJson == null) { aajKaSawalPlayed = 3; } else { // if old que json then aksplayer = 3 if (!checkQJson.contains("nodelist")) aajKaSawalPlayed = 3; }*/ // Aaj Ka Sawaal Played if (aajKaSawalPlayed == 1) { Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "1"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } // Aaj Ka Sawaal NOT Played else if (aajKaSawalPlayed == 0) { // Update updateTrailerCountbyGroupID to 1 if played // StatusDBHelper updateTrailerCount = new StatusDBHelper(MultiPhotoSelectActivity.this); // updateTrailerCount.updateTrailerCountbyGroupID(1, selectedGroupId); // BackupDatabase.backup(MultiPhotoSelectActivity.this); Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "0"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } // if Questions.json not present else if (aajKaSawalPlayed == 3) { Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "3"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } /*Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) main.putExtra("nodeList", newNodeList.toString()); startActivity(main); finish();*/ } catch (Exception e) { e.printStackTrace(); } } // Atleast one student is present in group/ unit else { ArrayList<JSONObject> selectedItems = imageAdapter.getCheckedItems(); if (selectedItems.size() > 0) { presentStudents = new String[selectedItems.size()]; try { if (selectedItems != null && selectedItems.size() > 0) { for (int i = 0; i < selectedItems.size(); i++) { attendance = new Attendance(); attendance.SessionID = sessionId; attendance.PresentStudentIds = selectedItems.get(i).getString("stdId"); presentStudents[i] = selectedItems.get(i).getString("stdId"); attendance.GroupID = selectedItems.get(i).getString("grpId"); if (!selectedGroupsScore.contains(attendance.GroupID)) { selectedGroupsScore += attendance.GroupID + ","; } attendanceDBHelper.Add(attendance); } BackupDatabase.backup(this); } } catch (Exception e) { e.printStackTrace(); } /* -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- AAJ KA SAWAAL PLAYED ? -*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*- */ // Decide the next screen depending on aajKaSawalPlayed status // Get Current Date String currentDate = utility.GetCurrentDate(); // Get Currently Selected Group String currentlySelectedGroup = selectedGroupId; // Fetch records StatusDBHelper sdbh = new StatusDBHelper(sessionContex); List<String> AKSRecords = sdbh.getAKSRecordsOfSelectedGroup(currentlySelectedGroup); // Loop to get Aaj Ka Sawaal Played Status if (!AKSRecords.equals(null)) { if (AKSRecords.size() == 0) { // No Record Found aajKaSawalPlayed = 0; } for (int i = 0; i < AKSRecords.size(); i++) { if (AKSRecords.get(i).contains(currentDate)) { // If Record Found i.e Aaj Ka Sawaal Played aajKaSawalPlayed = 1; } else { // If Record NOT Found i.e Aaj Ka Sawaal Played aajKaSawalPlayed = 0; } } } /*// if Questions.json not present JSONArray queJsonArray = null; try { checkQJson = loadQueJSONFromAsset(); } catch (Exception e) { e.printStackTrace(); } if (checkQJson == null) { aajKaSawalPlayed = 3; } else { // if old que json then aksplayer = 3 if (!checkQJson.contains("nodelist")) aajKaSawalPlayed = 3; }*/ if (aajKaSawalPlayed == 1) { Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "1"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } else if (aajKaSawalPlayed == 0) { // Update updateTrailerCountbyGroupID to 1 if played // StatusDBHelper updateTrailerCount = new StatusDBHelper(MultiPhotoSelectActivity.this); // updateTrailerCount.updateTrailerCountbyGroupID(1, selectedGroupId); // BackupDatabase.backup(MultiPhotoSelectActivity.this); Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "0"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } // if Questions.json not present else if (aajKaSawalPlayed == 3) { Intent main = new Intent(MultiPhotoSelectActivity.this, MainActivity.class); if (assessmentLogin.assessmentFlg) { main.putExtra("nodeList", newNodeList.toString()); } MainActivity.sessionFlg = true; scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } main.putExtra("ageGrp", ageGrp); main.putExtra("aajKaSawalPlayed", "3"); main.putExtra("selectedGroupId", selectedGroupId); startActivity(main); finish(); } } else { Toast.makeText(this, "Please Select your Profile !!!", Toast.LENGTH_LONG).show(); } } } // Reading CRL Json From Internal Memory public String loadQueJSONFromAsset() { String queJsonStr = null; try { File queJsonSDCard = new File(splashScreenVideo.fpath + "AajKaSawaal/", "Questions.json"); FileInputStream stream = new FileInputStream(queJsonSDCard); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); queJsonStr = Charset.defaultCharset().decode(bb).toString(); } catch (Exception e) { e.printStackTrace(); } finally { stream.close(); } } catch (Exception e) { } return queJsonStr; } public void populateImagesFromGallery() throws IOException { if (!mayRequestGalleryImages()) { return; } ArrayList<JSONObject> imageUrls = loadPhotosFromNativeGallery(); initializeRecyclerView(imageUrls); } private boolean mayRequestGalleryImages() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (checkSelfPermission(READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { return true; } if (shouldShowRequestPermissionRationale(READ_EXTERNAL_STORAGE)) { //promptStoragePermission(); showPermissionRationaleSnackBar(); } else { requestPermissions(new String[]{READ_EXTERNAL_STORAGE}, REQUEST_FOR_STORAGE_PERMISSION); } return false; } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_FOR_STORAGE_PERMISSION: { if (grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { try { populateImagesFromGallery(); } catch (IOException e) { e.printStackTrace(); } } else { if (ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) { showPermissionRationaleSnackBar(); } else { Toast.makeText(this, "Go to settings and enable permission", Toast.LENGTH_LONG).show(); } } } break; } } } private ArrayList<JSONObject> loadPhotosFromNativeGallery() throws IOException { ArrayList<JSONObject> imageUrls = new ArrayList<JSONObject>(); JSONObject studentWithImgs; File folder = new File(Environment.getExternalStorageDirectory() + "/.POSinternal/StudentProfiles"); if (folder.exists()) { File photos[] = folder.listFiles(); String fileNameWithExtension = "";//default fileName try { for (int j = 0; j < students.size(); j++) {//noOfGroups for (int k = 0; k < students.get(j).length(); k++) {//noOfStudents int flag = 0; String stdid = students.get(j).getJSONObject(k).getString("studentId"); String stdName = students.get(j).getJSONObject(k).getString("studentName"); String grpId = students.get(j).getJSONObject(k).getString("groupId"); String gender = students.get(j).getJSONObject(k).getString("gender"); for (int i = 0; i < photos.length; i++) {//noOfImages fileNameWithExtension = photos[i].getName(); String filePath = photos[i].getAbsolutePath(); String[] fileName = fileNameWithExtension.split("\\."); if (fileName[0].equals(stdid)) { flag = 1; studentWithImgs = new JSONObject(); studentWithImgs.put("id", stdid); studentWithImgs.put("name", stdName); studentWithImgs.put("grpId", grpId); studentWithImgs.put("imgPath", filePath); imageUrls.add(studentWithImgs); break; } } if (flag == 0) { studentWithImgs = new JSONObject(); studentWithImgs.put("id", stdid); studentWithImgs.put("name", stdName); studentWithImgs.put("grpId", grpId); if ((gender.equals("M")) || (gender.equals("Male"))) studentWithImgs.put("imgPath", Environment.getExternalStorageDirectory() + "/.POSinternal/StudentProfiles/Boys/" + generateRandomNumber() + ".png"); else studentWithImgs.put("imgPath", Environment.getExternalStorageDirectory() + "/.POSinternal/StudentProfiles/Girls/" + generateRandomNumber() + ".png"); imageUrls.add(studentWithImgs); } } } } catch (JSONException e) { e.printStackTrace(); } return imageUrls; } else { return null; } } private String generateRandomNumber() { Random rand = new Random(); int n = rand.nextInt(3) + 1; return Integer.toString(n); } private void initializeRecyclerView(ArrayList<JSONObject> imageUrls) { imageAdapter = new ImageAdapter(this, imageUrls); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 8); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new ItemOffsetDecoration(this, R.dimen.item_offset2)); recyclerView.setAdapter(imageAdapter); } private void showPermissionRationaleSnackBar() { Snackbar.make(findViewById(R.id.btn_continue), getString(R.string.permission_rationale), Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() { @Override public void onClick(View view) { // Request the permission ActivityCompat.requestPermissions(MultiPhotoSelectActivity.this, new String[]{READ_EXTERNAL_STORAGE}, REQUEST_FOR_STORAGE_PERMISSION); } }).show(); } @Override public void onBackPressed() { if (grpSelectFlag) { super.onBackPressed(); } else { // finish(); // startActivity(getIntent()); setContentView(R.layout.group_select); onResume(); } } /*@Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); doubleBackToExitPressedOnce=false; } }, 2000); }*/ @Override protected void onResume() { super.onResume(); setContentView(R.layout.group_select); myView = (RelativeLayout) findViewById(R.id.my_layoutId); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); tv_title = (TextView) findViewById(R.id.tv_select); next = (Button) findViewById(R.id.goNext); grpSelectFlag = true; if (radioGroup.getChildCount() > 0) { radioGroup.removeAllViews(); } displayStudentsByAgeGroup(ageGrp); setLanguage(); // set Title according to program if (MultiPhotoSelectActivity.programID.equals("1")) setTitle("Pratham Digital - H Learning"); else if (MultiPhotoSelectActivity.programID.equals("2")) setTitle("Pratham Digital - Read India"); else if (MultiPhotoSelectActivity.programID.equals("3")) setTitle("Pratham Digital - Second Chance"); else if (MultiPhotoSelectActivity.programID.equals("10")) setTitle("Pratham Digital - Pratham Institute"); else if (MultiPhotoSelectActivity.programID.equals("8")) setTitle("Pratham Digital - ECE"); else if (MultiPhotoSelectActivity.programID.equals("13")) setTitle("Pratham Digital - Hamara Gaon"); else setTitle("Pratham Digital"); s = new StatusDBHelper(this); appName = s.initialDataAvailable("appName"); if (appName == false) { s = new StatusDBHelper(MultiPhotoSelectActivity.this); // app name if (MultiPhotoSelectActivity.programID.equals("1")) s.insertInitialData("appName", "Pratham Digital - H Learning"); else if (MultiPhotoSelectActivity.programID.equals("2")) s.insertInitialData("appName", "Pratham Digital - Read India"); else if (MultiPhotoSelectActivity.programID.equals("3")) s.insertInitialData("appName", "Pratham Digital - Second Chance"); else if (MultiPhotoSelectActivity.programID.equals("10")) s.insertInitialData("appName", "Pratham Digital - Pratham Institute"); else if (MultiPhotoSelectActivity.programID.equals("8")) s.insertInitialData("appName", "Pratham Digital - ECE"); else if (MultiPhotoSelectActivity.programID.equals("13")) s.insertInitialData("appName", "Pratham Digital - Hamara Gaon"); else s.insertInitialData("appName", "Pratham Digital"); } else { s = new StatusDBHelper(MultiPhotoSelectActivity.this); // app name if (MultiPhotoSelectActivity.programID.equals("1")) s.Update("appName", "Pratham Digital - H Learning"); else if (MultiPhotoSelectActivity.programID.equals("2")) s.Update("appName", "Pratham Digital - Read India"); else if (MultiPhotoSelectActivity.programID.equals("3")) s.Update("appName", "Pratham Digital - Second Chance"); else if (MultiPhotoSelectActivity.programID.equals("10")) s.Update("appName", "Pratham Digital - Pratham Institute"); else if (MultiPhotoSelectActivity.programID.equals("8")) s.Update("appName", "Pratham Digital - ECE"); else if (MultiPhotoSelectActivity.programID.equals("13")) s.Update("appName", "Pratham Digital - Hamara Gaon"); else s.Update("appName", "Pratham Digital"); } BackupDatabase.backup(MultiPhotoSelectActivity.this); // session duration = timeout; if (pauseFlg) { cd.cancel(); pauseFlg = false; } } private void displayStudentsByAgeGroup(String ageGrp) { if (ageGrp.equalsIgnoreCase("5")) { display3to6Students(); } else if (ageGrp.equalsIgnoreCase("8")) { display7to14Students(); } else if (ageGrp.equalsIgnoreCase("15")) { // display all Stds for PI display14to18Students(); } else if (ageGrp.equalsIgnoreCase("25")) { // display vocational stds for PI displayVocationalStudents(); } else { displayStudents(); } } public void displayStudents() { String assignedGroupIDs[]; students = new ArrayList<JSONArray>(); groupNames = new ArrayList<String>(); assignedIds = new ArrayList<String>(); try { programID = new Utility().getProgramId(); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { tv_title.setText("Select Groups"); } else if (programID.equals("2")) { tv_title.setText("Select Units"); } else tv_title.setText("Select Groups"); // if (programID.equals("1") || programID.equals("2") || programID.equals("3") || programID.equals("10")) { next = (Button) findViewById(R.id.goNext); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { next.setText("Select Groups"); } else if (programID.equals("2")) { next.setText("Select Units"); } else next.setText("Select Groups"); assignedGroupIDs = statusDBHelper.getGroupIDs(); if (!assignedGroupIDs[0].equals("")) { for (int i = 0; i < assignedGroupIDs.length; i++) { if (!assignedGroupIDs[i].equals("0")) { students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); assignedIds.add(assignedGroupIDs[i]); } } } next.setClickable(false); int groupCount = groupNames.size(); if (groupNames.isEmpty()) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else if (programID.equals("2")) { Toast.makeText(this, "Assign Units First", Toast.LENGTH_LONG).show(); } else Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else { next.setClickable(false); radioGroup.setPadding(0, 50, 0, 0); RadioButton rb; for (int i = 0; i < groupCount; i++) { rb = new RadioButton(this); RadioGroup.LayoutParams params = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(8, 0, 0, 0); rb.setLayoutParams(params); rb.setHeight(160); rb.setWidth(135); rb.setTextSize(16); // For HL if (MultiPhotoSelectActivity.programID.equals("1") || MultiPhotoSelectActivity.programID.equals("3") || MultiPhotoSelectActivity.programID.equals("10")) { rb.setBackgroundResource(R.drawable.groups); } else if (MultiPhotoSelectActivity.programID.equals("2")) { rb.setBackgroundResource(R.drawable.units); } else rb.setBackgroundResource(R.drawable.groups); rb.setPadding(0, 0, 2, 0); rb.setId(i); rb.setText(groupNames.get(i)); radioGroup.addView(rb); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // get selected radio button from radioGroup int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else if (programID.equals("2")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one unit", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else { // find the radiobutton by returned id radioButton = (RadioButton) findViewById(selectedId); radioButton.setBackgroundColor(getResources().getColor(R.color.selected)); selectedGroupId = assignedIds.get(selectedId); selectedGroupName = (String) radioButton.getText(); if (selectedGroupName.equals(null)) { Toast.makeText(MultiPhotoSelectActivity.this, "Assign Groups First", Toast.LENGTH_SHORT).show(); } else { setSelectedStudents(selectedGroupName); } } } catch (Exception e) { e.printStackTrace(); } } }); } /*} else { Toast.makeText(this, "Invalid Program Id", Toast.LENGTH_SHORT).show(); }*/ } catch (Exception e) { e.printStackTrace(); } } public void display3to6Students() { String assignedGroupIDs[]; students = new ArrayList<JSONArray>(); groupNames = new ArrayList<String>(); assignedIds = new ArrayList<String>(); try { programID = new Utility().getProgramId(); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { tv_title.setText("Select Groups"); } else if (programID.equals("2")) { tv_title.setText("Select Units"); } else tv_title.setText("Select Groups"); // if (programID.equals("1") || programID.equals("2") || programID.equals("3") || programID.equals("10")) { next = (Button) findViewById(R.id.goNext); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { next.setText("Select Groups"); } else if (programID.equals("2")) { next.setText("Select Units"); } else next.setText("Select Groups"); assignedGroupIDs = statusDBHelper.getGroupIDs(); if (!assignedGroupIDs[0].equals("")) { for (int i = 0; i < assignedGroupIDs.length; i++) { if (!assignedGroupIDs[i].equals("0")) { // check students age & add accordingly // Get Std count by group id StudentDBHelper stdDBHelper = new StudentDBHelper(this); List<Student> lstStudent = stdDBHelper.getStudentsByGroup(assignedGroupIDs[i]); int stdCount = 0; int wrongStdCount = 0; // get age of each std & then add grp if student age is less than 8 for (int j = 0; j < lstStudent.size(); j++) { int age = lstStudent.get(j).Age; if (age < 7) { stdCount++; } else { wrongStdCount++; } } // if all student age criteria satisfied if (stdCount == lstStudent.size()) { assignedIds.add(assignedGroupIDs[i]); students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); } // if all student age criteria not satisfied else if (wrongStdCount == lstStudent.size()) { } // few std fullfills criteria then add whole grp else if (stdCount > 0 && wrongStdCount > 0 && lstStudent.size() > 0) { students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); assignedIds.add(assignedGroupIDs[i]); } } } } next.setClickable(false); int groupCount = groupNames.size(); if (groupNames.isEmpty()) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else if (programID.equals("2")) { Toast.makeText(this, "Assign Units First", Toast.LENGTH_LONG).show(); } else Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else { next.setClickable(false); radioGroup.setPadding(0, 50, 0, 0); RadioButton rb; for (int i = 0; i < groupCount; i++) { rb = new RadioButton(this); RadioGroup.LayoutParams params = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(8, 0, 0, 0); rb.setLayoutParams(params); rb.setHeight(160); rb.setWidth(135); rb.setTextSize(16); // For HL if (MultiPhotoSelectActivity.programID.equals("1") || MultiPhotoSelectActivity.programID.equals("3") || MultiPhotoSelectActivity.programID.equals("10")) { rb.setBackgroundResource(R.drawable.groups); } else if (MultiPhotoSelectActivity.programID.equals("2")) { rb.setBackgroundResource(R.drawable.units); } else rb.setBackgroundResource(R.drawable.groups); rb.setPadding(0, 0, 2, 0); rb.setId(i); rb.setText(groupNames.get(i)); radioGroup.addView(rb); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // get selected radio button from radioGroup int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else if (programID.equals("2")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one unit", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else { // find the radiobutton by returned id radioButton = (RadioButton) findViewById(selectedId); radioButton.setBackgroundColor(getResources().getColor(R.color.selected)); selectedGroupId = assignedIds.get(selectedId); selectedGroupName = (String) radioButton.getText(); if (selectedGroupName.equals(null)) { Toast.makeText(MultiPhotoSelectActivity.this, "Assign Groups First", Toast.LENGTH_SHORT).show(); } else { setSelectedStudents(selectedGroupName); } } } catch (Exception e) { e.printStackTrace(); } } }); } /*} else { Toast.makeText(this, "Invalid Program Id", Toast.LENGTH_SHORT).show(); }*/ } catch (Exception e) { e.printStackTrace(); } } public void display7to14Students() { String assignedGroupIDs[]; students = new ArrayList<JSONArray>(); groupNames = new ArrayList<String>(); assignedIds = new ArrayList<String>(); try { programID = new Utility().getProgramId(); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { tv_title.setText("Select Groups"); } else if (programID.equals("2")) { tv_title.setText("Select Units"); } else tv_title.setText("Select Groups"); // if (programID.equals("1") || programID.equals("2") || programID.equals("3") || programID.equals("10")) { next = (Button) findViewById(R.id.goNext); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { next.setText("Select Groups"); } else if (programID.equals("2")) { next.setText("Select Units"); } else next.setText("Select Groups"); assignedGroupIDs = statusDBHelper.getGroupIDs(); if (!assignedGroupIDs[0].equals("")) { for (int i = 0; i < assignedGroupIDs.length; i++) { if (!assignedGroupIDs[i].equals("0")) { // check students age & add accordingly // Get Std count by group id StudentDBHelper stdDBHelper = new StudentDBHelper(this); List<Student> lstStudent = stdDBHelper.getStudentsByGroup(assignedGroupIDs[i]); int stdCount = 0; int wrongStdCount = 0; // get age of each std & then add grp if student age is less than 8 for (int j = 0; j < lstStudent.size(); j++) { int age = lstStudent.get(j).Age; if (age > 6 && age < 15) { stdCount++; } else { wrongStdCount++; } } // if all student age criteria satisfied if (stdCount == lstStudent.size()) { assignedIds.add(assignedGroupIDs[i]); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); } // if all student age criteria not satisfied else if (wrongStdCount == lstStudent.size()) { } // few std fullfills criteria then add whole grp else if (stdCount > 0 && wrongStdCount > 0 && lstStudent.size() > 0) { students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); assignedIds.add(assignedGroupIDs[i]); } } } } next.setClickable(false); int groupCount = groupNames.size(); if (groupNames.isEmpty()) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else if (programID.equals("2")) { Toast.makeText(this, "Assign Units First", Toast.LENGTH_LONG).show(); } else Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else { next.setClickable(false); radioGroup.setPadding(0, 50, 0, 0); RadioButton rb; for (int i = 0; i < groupCount; i++) { rb = new RadioButton(this); RadioGroup.LayoutParams params = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(8, 0, 0, 0); rb.setLayoutParams(params); rb.setHeight(160); rb.setWidth(135); rb.setTextSize(16); // For HL if (MultiPhotoSelectActivity.programID.equals("1") || MultiPhotoSelectActivity.programID.equals("3") || MultiPhotoSelectActivity.programID.equals("10")) { rb.setBackgroundResource(R.drawable.groups); } else if (MultiPhotoSelectActivity.programID.equals("2")) { rb.setBackgroundResource(R.drawable.units); } else rb.setBackgroundResource(R.drawable.groups); rb.setPadding(0, 0, 2, 0); rb.setId(i); rb.setText(groupNames.get(i)); radioGroup.addView(rb); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // get selected radio button from radioGroup int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else if (programID.equals("2")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one unit", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else { // find the radiobutton by returned id radioButton = (RadioButton) findViewById(selectedId); radioButton.setBackgroundColor(getResources().getColor(R.color.selected)); selectedGroupId = assignedIds.get(selectedId); selectedGroupName = (String) radioButton.getText(); if (selectedGroupName.equals(null)) { Toast.makeText(MultiPhotoSelectActivity.this, "Assign Groups First", Toast.LENGTH_SHORT).show(); } else { setSelectedStudents(selectedGroupName); } } } catch (Exception e) { e.printStackTrace(); } } }); } /*} else { Toast.makeText(this, "Invalid Program Id", Toast.LENGTH_SHORT).show(); }*/ } catch (Exception e) { e.printStackTrace(); } } public void display14to18Students() { String assignedGroupIDs[]; students = new ArrayList<JSONArray>(); groupNames = new ArrayList<String>(); assignedIds = new ArrayList<String>(); try { programID = new Utility().getProgramId(); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { tv_title.setText("Select Groups"); } else if (programID.equals("2")) { tv_title.setText("Select Units"); } else tv_title.setText("Select Groups"); // if (programID.equals("1") || programID.equals("2") || programID.equals("3") || programID.equals("10")) { next = (Button) findViewById(R.id.goNext); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { next.setText("Select Groups"); } else if (programID.equals("2")) { next.setText("Select Units"); } else next.setText("Select Groups"); assignedGroupIDs = statusDBHelper.getGroupIDs(); if (!assignedGroupIDs[0].equals("")) { for (int i = 0; i < assignedGroupIDs.length; i++) { if (!assignedGroupIDs[i].equals("0")) { // check students age & add accordingly // Get Std count by group id StudentDBHelper stdDBHelper = new StudentDBHelper(this); List<Student> lstStudent = stdDBHelper.getStudentsByGroup(assignedGroupIDs[i]); int stdCount = 0; int wrongStdCount = 0; // get age of each std & then add grp if student age is less than 8 for (int j = 0; j < lstStudent.size(); j++) { int age = lstStudent.get(j).Age; if (age > 13 && age < 19) { stdCount++; } else { wrongStdCount++; } } // if all student age criteria satisfied if (stdCount == lstStudent.size()) { assignedIds.add(assignedGroupIDs[i]); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); } // if all student age criteria not satisfied else if (wrongStdCount == lstStudent.size()) { } // few std fullfills criteria then add whole grp else if (stdCount > 0 && wrongStdCount > 0 && lstStudent.size() > 0) { students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); assignedIds.add(assignedGroupIDs[i]); } } } } next.setClickable(false); int groupCount = groupNames.size(); if (groupNames.isEmpty()) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else if (programID.equals("2")) { Toast.makeText(this, "Assign Units First", Toast.LENGTH_LONG).show(); } else Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else { next.setClickable(false); radioGroup.setPadding(0, 50, 0, 0); RadioButton rb; for (int i = 0; i < groupCount; i++) { rb = new RadioButton(this); RadioGroup.LayoutParams params = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(8, 0, 0, 0); rb.setLayoutParams(params); rb.setHeight(160); rb.setWidth(135); rb.setTextSize(16); // For HL if (MultiPhotoSelectActivity.programID.equals("1") || MultiPhotoSelectActivity.programID.equals("3") || MultiPhotoSelectActivity.programID.equals("10")) { rb.setBackgroundResource(R.drawable.groups); } else if (MultiPhotoSelectActivity.programID.equals("2")) { rb.setBackgroundResource(R.drawable.units); } else rb.setBackgroundResource(R.drawable.groups); rb.setPadding(0, 0, 2, 0); rb.setId(i); rb.setText(groupNames.get(i)); radioGroup.addView(rb); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // get selected radio button from radioGroup int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else if (programID.equals("2")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one unit", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else { // find the radiobutton by returned id radioButton = (RadioButton) findViewById(selectedId); radioButton.setBackgroundColor(getResources().getColor(R.color.selected)); selectedGroupId = assignedIds.get(selectedId); selectedGroupName = (String) radioButton.getText(); if (selectedGroupName.equals(null)) { Toast.makeText(MultiPhotoSelectActivity.this, "Assign Groups First", Toast.LENGTH_SHORT).show(); } else { setSelectedStudents(selectedGroupName); } } } catch (Exception e) { e.printStackTrace(); } } }); } /*} else { Toast.makeText(this, "Invalid Program Id", Toast.LENGTH_SHORT).show(); }*/ } catch (Exception e) { e.printStackTrace(); } } public void displayVocationalStudents() { String assignedGroupIDs[]; students = new ArrayList<JSONArray>(); groupNames = new ArrayList<String>(); assignedIds = new ArrayList<String>(); try { programID = new Utility().getProgramId(); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { tv_title.setText("Select Groups"); } else if (programID.equals("2")) { tv_title.setText("Select Units"); } else tv_title.setText("Select Groups"); // if (programID.equals("1") || programID.equals("2") || programID.equals("3") || programID.equals("10")) { next = (Button) findViewById(R.id.goNext); if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { next.setText("Select Groups"); } else if (programID.equals("2")) { next.setText("Select Units"); } else next.setText("Select Groups"); assignedGroupIDs = statusDBHelper.getGroupIDs(); if (!assignedGroupIDs[0].equals("")) { for (int i = 0; i < assignedGroupIDs.length; i++) { if (!assignedGroupIDs[i].equals("0")) { // check students age & add accordingly // Get Std count by group id StudentDBHelper stdDBHelper = new StudentDBHelper(this); List<Student> lstStudent = stdDBHelper.getStudentsByGroup(assignedGroupIDs[i]); int stdCount = 0; int wrongStdCount = 0; // get age of each std & then add grp if student age is less than 8 for (int j = 0; j < lstStudent.size(); j++) { int age = lstStudent.get(j).Age; if (age > 17 && age < 31) { stdCount++; } else { wrongStdCount++; } } // if all student age criteria satisfied if (stdCount == lstStudent.size()) { assignedIds.add(assignedGroupIDs[i]); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); } // if all student age criteria not satisfied else if (wrongStdCount == lstStudent.size()) { } // few std fullfills criteria then add whole grp else if (stdCount > 0 && wrongStdCount > 0 && lstStudent.size() > 0) { students.add(studentDBHelper.getStudentsList(assignedGroupIDs[i])); groupNames.add(groupDBHelper.getGroupById(assignedGroupIDs[i])); assignedIds.add(assignedGroupIDs[i]); } } } } next.setClickable(false); int groupCount = groupNames.size(); if (groupNames.isEmpty()) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else if (programID.equals("2")) { Toast.makeText(this, "Assign Units First", Toast.LENGTH_LONG).show(); } else Toast.makeText(this, "Assign Groups First", Toast.LENGTH_LONG).show(); } else { next.setClickable(false); radioGroup.setPadding(0, 50, 0, 0); RadioButton rb; for (int i = 0; i < groupCount; i++) { rb = new RadioButton(this); RadioGroup.LayoutParams params = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(8, 0, 0, 0); rb.setLayoutParams(params); rb.setHeight(160); rb.setWidth(135); rb.setTextSize(16); // For HL if (MultiPhotoSelectActivity.programID.equals("1") || MultiPhotoSelectActivity.programID.equals("3") || MultiPhotoSelectActivity.programID.equals("10")) { rb.setBackgroundResource(R.drawable.groups); } else if (MultiPhotoSelectActivity.programID.equals("2")) { rb.setBackgroundResource(R.drawable.units); } else rb.setBackgroundResource(R.drawable.groups); rb.setPadding(0, 0, 2, 0); rb.setId(i); rb.setText(groupNames.get(i)); radioGroup.addView(rb); } next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // get selected radio button from radioGroup int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { if (programID.equals("1") || programID.equals("3") || programID.equals("10")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else if (programID.equals("2")) { Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one unit", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MultiPhotoSelectActivity.this, "Select atleast one group", Toast.LENGTH_SHORT).show(); } else { // find the radiobutton by returned id radioButton = (RadioButton) findViewById(selectedId); radioButton.setBackgroundColor(getResources().getColor(R.color.selected)); selectedGroupId = assignedIds.get(selectedId); selectedGroupName = (String) radioButton.getText(); if (selectedGroupName.equals(null)) { Toast.makeText(MultiPhotoSelectActivity.this, "Assign Groups First", Toast.LENGTH_SHORT).show(); } else { setSelectedStudents(selectedGroupName); } } } catch (Exception e) { e.printStackTrace(); } } }); } /*} else { Toast.makeText(this, "Invalid Program Id", Toast.LENGTH_SHORT).show(); }*/ } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { Log.d("destroyed", "------------- Multi Photo --------------- in Destroy"); /* if (!CardAdapter.vidFlg) { scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } }*/ super.onDestroy(); } @Override protected void onPause() { super.onPause(); pauseFlg = true; cd = new CountDownTimer(duration, 1000) { //cd = new CountDownTimer(duration, 1000) { @Override public void onTick(long millisUntilFinished) { duration = millisUntilFinished; timer = true; } @Override public void onFinish() { timer = false; MainActivity.sessionFlg = true; if (!CardAdapter.vidFlg) { scoreDBHelper = new ScoreDBHelper(sessionContex); playVideo.calculateEndTime(scoreDBHelper); BackupDatabase.backup(sessionContex); try { finishAffinity(); } catch (Exception e) { e.printStackTrace(); } } } }.start(); } // // To Select only one radio button from Radio Group // public void oneRadioButtonClicked(View view) { // // // Is the button now checked? // boolean checked = ((RadioButton) view).isChecked(); // RadioGroup rg = (RadioGroup) findViewById(R.id.rg_options); // // switch (view.getId()) { // // // case R.id.rb_O1: { // rg.clearCheck(); // rg.check(view.getId()); // break; // } // // case R.id.rb_O2: { // rg.clearCheck(); // rg.check(view.getId()); // break; // } // // case R.id.rb_O3: { // rg.clearCheck(); // rg.check(view.getId()); // break; // } // // case R.id.rb_O4: { // rg.clearCheck(); // rg.check(view.getId()); // break; // } // // } // } }
true
777d732087442c4b9682119c668b55afe75b04ae
Java
mario1oreo/dungproxy
/client/src/main/java/com/virjar/dungproxy/client/ippool/config/DomainContext.java
UTF-8
3,902
2.171875
2
[]
no_license
package com.virjar.dungproxy.client.ippool.config; import com.google.common.base.Preconditions; import com.virjar.dungproxy.client.ippool.strategy.Offline; import com.virjar.dungproxy.client.ippool.strategy.ResourceFacade; import com.virjar.dungproxy.client.ippool.strategy.Scoring; /** * Created by virjar on 17/1/23. */ public class DomainContext { private DungProxyContext dungProxyContext; private ResourceFacade resourceFacade; private Scoring scoring; private Offline offline; private int coreSize; private double smartProxyQueueRatio; private long useInterval; private String domain; private int scoreFactory; /** * 不允许包外访问 */ DomainContext(String domain) { this.domain = domain; } public int getCoreSize() { return coreSize; } public DomainContext setCoreSize(int coreSize) { this.coreSize = coreSize; return this; } public DungProxyContext getDungProxyContext() { return dungProxyContext; } public DomainContext setDungProxyContext(DungProxyContext dungProxyContext) { this.dungProxyContext = dungProxyContext; return this; } public ResourceFacade getResourceFacade() { return resourceFacade; } public DomainContext setResourceFacade(ResourceFacade resourceFacade) { this.resourceFacade = resourceFacade; return this; } public double getSmartProxyQueueRatio() { return smartProxyQueueRatio; } public DomainContext setSmartProxyQueueRatio(double smartProxyQueueRatio) { this.smartProxyQueueRatio = smartProxyQueueRatio; return this; } public long getUseInterval() { return useInterval; } public DomainContext setUseInterval(long useInterval) { this.useInterval = useInterval; return this; } public String getDomain() { return domain; } public static DomainContext create(String domain) { Preconditions.checkNotNull(domain); return new DomainContext(domain); } public Offline getOffline() { return offline; } public DomainContext setOffline(Offline offline) { this.offline = offline; return this; } public Scoring getScoring() { return scoring; } public DomainContext setScoring(Scoring scoring) { this.scoring = scoring; return this; } public int getScoreFactory() { return scoreFactory; } public DomainContext setScoreFactory(int scoreFactory) { this.scoreFactory = scoreFactory; return this; } /** * 检查缺失配置项,如果有缺失,则添加默认策略 * * @param dungProxyContext 全局context,获取全局的配置信息 * @return DomainContext */ DomainContext extendWithDungProxyContext(DungProxyContext dungProxyContext) { this.dungProxyContext = dungProxyContext; if (coreSize <= 1) { coreSize = dungProxyContext.getDefaultCoreSize(); } if (smartProxyQueueRatio <= 0.1) { smartProxyQueueRatio = dungProxyContext.getDefaultSmartProxyQueueRatio(); } if (useInterval <= 1L) { useInterval = dungProxyContext.getDefaultUseInterval(); } if (resourceFacade == null) { resourceFacade = ObjectFactory.newInstance(dungProxyContext.getDefaultResourceFacade()); } if(scoring == null){ scoring = ObjectFactory.newInstance(dungProxyContext.getDefaultScoring()); } if(offline == null){ this.offline = ObjectFactory.newInstance(dungProxyContext.getDefaultOffliner()); } if(this.scoreFactory<=0){ this.scoreFactory = dungProxyContext.getDefaultScoreFactory(); } return this; } }
true
b4dfe9167cfbecd0cbec0f986334602a4b34ea95
Java
TinsPHP/tins-inference-engine
/test/ch/tsphp/tinsphp/inference_engine/test/integration/reference/ParameterDoubleDefinitionErrorTest.java
UTF-8
2,875
2.03125
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* * This file is part of the TinsPHP project published under the Apache License 2.0 * For the full copyright and license information, please have a look at LICENSE in the * root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License */ /* * This class is based on the class ParameterDoubleDefinitionErrorTest from the TSPHP project. * TSPHP is also published under the Apache License 2.0 * For more information see http://tsphp.ch/wiki/display/TSPHP/License */ package ch.tsphp.tinsphp.inference_engine.test.integration.reference; import ch.tsphp.tinsphp.common.issues.DefinitionIssueDto; import ch.tsphp.tinsphp.inference_engine.test.integration.testutils.reference.AReferenceDefinitionErrorTest; import org.antlr.runtime.RecognitionException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; import java.util.List; @RunWith(Parameterized.class) public class ParameterDoubleDefinitionErrorTest extends AReferenceDefinitionErrorTest { private static List<Object[]> collection; public ParameterDoubleDefinitionErrorTest(String testString, DefinitionIssueDto[] expectedLinesAndPositions) { super(testString, expectedLinesAndPositions); } @Test public void test() throws RecognitionException { runTest(); } @Parameterized.Parameters public static Collection<Object[]> testStrings() { collection = new ArrayList<>(); addVariations("function foo(", "){return ;}"); addVariations("namespace a; function foo(", "){return ;}"); addVariations("namespace a\\b\\z{ function foo(", "){return ;}}"); //TODO rstoll TINS-161 inference OOP // addVariations("class a{ function void foo(", "){return ;}}"); // addVariations("namespace a; class b{function void foo(", "){return ;}}"); // addVariations("namespace a\\b\\z{ class m{function void foo(", "){return ;}}}"); return collection; } public static void addVariations(String prefix, String appendix) { DefinitionIssueDto[] errorDto = new DefinitionIssueDto[]{new DefinitionIssueDto("$a", 2, 1, "$a", 3, 1)}; DefinitionIssueDto[] errorDtoTwo = new DefinitionIssueDto[]{ new DefinitionIssueDto("$a", 2, 1, "$a", 3, 1), new DefinitionIssueDto("$a", 2, 1, "$a", 4, 1) }; String[] types = new String[]{"array"}; for (String type : types) { collection.add(new Object[]{ prefix + type + "\n $a, \n $a" + appendix, errorDto }); collection.add(new Object[]{ prefix + type + "\n $a, \\Exception \n $a=1, \\ErrorException\n $a=3" + appendix, errorDtoTwo }); } } }
true
9c49f97d8e607be818154c7b68c36ea4d2d44dbe
Java
shabbirahussain/NEU-CS6200-InformationRetrieval
/HW5/src/com/ir/homework/hw5/evaluators/AbstractEvaluator.java
UTF-8
1,909
2.484375
2
[]
no_license
package com.ir.homework.hw5.evaluators; import java.text.DecimalFormat; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.ir.homework.hw5.models.ModelQrel; import com.ir.homework.hw5.models.ModelQres; public abstract class AbstractEvaluator implements Evaluator { protected static final DecimalFormat FORMATTER = new DecimalFormat("#0.0000"); protected Map<String, ModelQrel> qrel; protected Map<String, ModelQres> qres; protected String srcFile; protected Map<String, List<Result>> resultMap; class Result{ public Double prcisn, recall; public Boolean relevant; public Double numRel; } public void initialize(Map<String, ModelQrel> qrel, Map<String, ModelQres> qres, String srcFile){ this.qrel = qrel; this.qres = qres; this.srcFile = srcFile; resultMap = new HashMap<String, List<Result>>(); List<Result> tmpResultLst; Result tmpResult; // Calculate precision and recall for each query for(Entry<String, ModelQres> query: qres.entrySet()){ String qeryKey = query.getKey(); ModelQrel qrel1 = this.qrel.get(qeryKey); Double cntRel = 0.0; Double cntRet = 0.0; Integer totRel = qrel1.size(); for(Entry<String, Double> d: query.getValue()){ cntRet++; Integer relScore = (qrel1.getOrDefault(d.getKey(), 0.0)>0)? 1: 0; Integer docScore = 1;//(d.getValue() > 0.0)? 1: 0; //System.out.println(d); tmpResultLst = resultMap.getOrDefault(qeryKey, new LinkedList<Result>()); tmpResult = new Result(); if((tmpResult.relevant = (relScore == docScore))) cntRel ++; tmpResult.prcisn = cntRel/cntRet; tmpResult.recall = cntRel/totRel; tmpResult.numRel = ((Integer) qrel1.size()).doubleValue(); tmpResultLst.add(tmpResult); resultMap.put(qeryKey, tmpResultLst); } } } }
true
f02f890d02dfbfd5929e3ec6783fbaaf307053e7
Java
Walkerstar/patterns_learn
/patterns/src/com/bjsxt/prototype/Client1.java
GB18030
631
3.21875
3
[]
no_license
package com.bjsxt.prototype; import java.util.Date; /** * ԭģ(dz¡) * @author Administrator * */ public class Client1 { public static void main(String[] args) throws Exception { Date date=new Date(141646313164464L); Sheep s1=new Sheep("",date); System.out.println(s1); System.out.println(s1.getSname()); System.out.println(s1.getBirthday()); date.setTime(1645464681031L); System.out.println(s1.getBirthday()); Sheep s2=(Sheep) s1.clone(); s2.setSname(""); System.out.println(s2); System.out.println(s2.getSname()); System.out.println(s2.getBirthday()); } }
true