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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7f251707b79c6724c28f1d951927fc7d3a22bb55
|
Java
|
zhanghuawei123/shop_project
|
/shop_service_provider/shop_goods_service/src/test/java/com/qianfeng/shop_goods_service/ShopGoodsServiceApplicationTests.java
|
UTF-8
| 670
| 1.882813
| 2
|
[] |
no_license
|
package com.qianfeng.shop_goods_service;
import com.qianfeng.entity.Goods;
import com.qianfeng.service.GoodService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShopGoodsServiceApplicationTests {
@Autowired
private GoodService goodService;
@Test
public void contextLoads() {
List<Goods> goods = goodService.queryGoods();
System.out.println(goods);
}
}
| true
|
617a94820b5a19342e6bf5098273d93f9198c29c
|
Java
|
rfecher/geowave
|
/core/store/src/main/java/mil/nga/giat/geowave/core/store/base/Writer.java
|
UTF-8
| 543
| 2.203125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] |
permissive
|
package mil.nga.giat.geowave.core.store.base;
import java.io.Closeable;
/**
* This interface is returned by DataStoreOperations and useful for general
* purpose writing of entries. The default implementation of AccumuloOperations
* will wrap this interface with a BatchWriter but can be overridden for other
* mechanisms to write the data.
*/
public interface Writer<MutationType> extends
Closeable
{
public void write(
Iterable<MutationType> mutations );
public void write(
MutationType mutation );
public void flush();
}
| true
|
eadbede3c502ca6ad43f14cc2aa85e43f6cfdf67
|
Java
|
SimonDan/svl-app
|
/app/src/main/java/com/github/simondan/svl/app/PenaltyActivity.java
|
UTF-8
| 1,699
| 2.109375
| 2
|
[
"MIT"
] |
permissive
|
package com.github.simondan.svl.app;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.github.simondan.svl.app.server.IServer;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
public class PenaltyActivity extends AppCompatActivity
{
private static final String TAG = "xx SignInActivity";
private IServer server;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_penalty);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
server = IServer.getForCurrentActivity(this);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mainMenuStrafenAnlegen:
Log.d(TAG, "Strafen");
return true;
case R.id.mainMenuBenutzerVerwalten:
Log.d(TAG, "Benutzer");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| true
|
d1baec39ffa763414e58872fe0bef0735d3d6bef
|
Java
|
TimfuDeng/gtfree-bank
|
/suzhou/yuanqu/admin/src/main/java/cn/gtmap/landsale/admin/service/impl/CaPcsServiceImpl.java
|
UTF-8
| 6,044
| 2.15625
| 2
|
[] |
no_license
|
package cn.gtmap.landsale.admin.service.impl;
import cn.gtmap.egovplat.core.ex.AppException;
import cn.gtmap.egovplat.core.util.ArrayUtils;
import cn.gtmap.egovplat.core.util.Charsets;
import cn.gtmap.landsale.Constants;
import cn.gtmap.landsale.service.CaPcsService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.Collection;
import java.util.List;
/**
* @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
* @version 1.0, 2015/7/6
*/
public class CaPcsServiceImpl implements CaPcsService {
private static final String SL_PATH="sl.svr";
private static final String SG_PATH="sg.svr";
private static final String SPE_PATH="spe.svr";
private static final String SPD_PATH="spd.svr";
private static final String SMP1_PATH="smp1.svr";
private static final String SMP7_PATH="smp7.svr";
private HttpClient httpClient;
private String baseUrl;
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
* 获取可用的密钥ID
*
* @return
*/
@Override
public Collection<String> getAvailableKeyIds() throws Exception {
String keyIds = post(baseUrl+"/"+SL_PATH,null);
return StringUtils.isNotBlank(keyIds)?ArrayUtils.asList(StringUtils.split(keyIds,"\n")):null;
}
/**
* 获取密钥ID对应的数字证书
*
* @param keyId 密钥Id
* @return Base64编码的数字证书
*/
@Override
public String getCertificateByKeyId(String keyId) throws Exception {
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("id", keyId));
return post(baseUrl + "/" + SG_PATH, params);
}
/**
* 私钥加密
*
* @param keyId 密钥Id
* @param password 私钥保护的口令
* @param data BASE64编码的待加密数据(注意,私钥加密的明文最大长度不能超过私钥长度的2倍)
* @return
*/
@Override
public String encryptByPrivateKey(String keyId, String password, String data) throws Exception {
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("id", keyId));
params.add(new BasicNameValuePair("passwd", password));
params.add(new BasicNameValuePair("data", data));
return post(baseUrl + "/" + SPE_PATH, params);
}
/**
* 私钥解密
*
* @param keyId 密钥Id
* @param password 私钥保护的口令
* @param data BASE64编码待解密数据
* @return
*/
@Override
public String decryptByPrivateKey(String keyId, String password, String data) throws Exception {
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("id", keyId));
params.add(new BasicNameValuePair("passwd", password));
params.add(new BasicNameValuePair("data", data));
return post(baseUrl + "/" + SPD_PATH, params);
}
/**
* 创建PKCS1签名
*
* @param keyId 密钥Id
* @param password 私钥保护的口令
* @param data BASE64编码待签名数据
* @param algo 数字摘要算法
* @param dataType 原文数据类型
* @return
*/
@Override
public String signPKCS1(String keyId, String password, String data, String algo, Constants.CaOriginalDateType dataType) throws Exception {
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("id", keyId));
params.add(new BasicNameValuePair("passwd", password));
params.add(new BasicNameValuePair("data", data));
params.add(new BasicNameValuePair("algo", algo));
params.add(new BasicNameValuePair("datt", String.valueOf(dataType.ordinal())));
return post(baseUrl + "/" + SMP1_PATH, params);
}
/**
* 创建PKCS7签名
*
* @param keyId 密钥Id
* @param password 私钥保护的口令
* @param data BASE64编码待签名数据
* @return
*/
@Override
public String signPKCS7(String keyId, String password, String data) throws Exception {
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("id", keyId));
params.add(new BasicNameValuePair("passwd", password));
params.add(new BasicNameValuePair("data", data));
return post(baseUrl + "/" + SMP7_PATH, params);
}
private String post(String url,List params) throws Exception{
CloseableHttpClient closeableHttpClient = null;
CloseableHttpResponse response = null;
try{
closeableHttpClient = (CloseableHttpClient)httpClient;
HttpPost httPost = new HttpPost(url);
if(params!=null&&!params.isEmpty())
httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = closeableHttpClient.execute(httPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode==200) {
return EntityUtils.toString(response.getEntity(), Charsets.CHARSET_UTF8);
}else if(statusCode==400){
throw new AppException(4102);
}else if(statusCode==403){
throw new AppException(4103);
}else if(statusCode==404){
throw new AppException(4104);
}else if(StringUtils.startsWith(String.valueOf(statusCode),"5")){
throw new AppException(4101);
}
}finally {
if(response!=null)
response.close();
}
return null;
}
}
| true
|
1b852774d9cd44db5711c7c7c228fc1586d89b88
|
Java
|
mehmetersin/spor-simdi-bluetooth-turnike
|
/SporSimdiTurnike/src/com/kayi/sporsimdi/turnike/MainActivity.java
|
UTF-8
| 8,450
| 1.929688
| 2
|
[] |
no_license
|
package com.kayi.sporsimdi.turnike;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
public class MainActivity extends FragmentActivity {
public final static String TAG = "SporSimdiTurnike";
String receivedData = null;
private Button pwdLoginButton;
private TextView rfidTextView;
private UsbManager usbManager;
private UsbSerialDriver device;
private String rfidTicket;
private final ExecutorService mExecutor = Executors
.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {
@Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
@Override
public void onNewData(final byte[] data) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
MainActivity.this.updateReceivedData(data);
}
});
}
// new HttpAsyncTask()
// .execute("http://www.sporsimdi.com/mobile/turnstileRequest.jsf?request="
// + ticket);
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupChat();
// Get UsbManager from Android.
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
}
private void setupChat() {
// Initialize the array adapter for the conversation thread
rfidTextView = (TextView) findViewById(R.id.edit_text_out);
rfidTextView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String readRfid = rfidTextView.getText().toString();
if (readRfid.contains("\n")) {
rfidTicket = readRfid.replaceAll("\n", "");
final String message = "Q-QR-" + rfidTicket;
HttpAsyncTask task = new HttpAsyncTask();
task.execute("http://www.sporsimdi.com/mobile/turnstileRequest.jsf?request="
+ message);
rfidTicket = null;
rfidTextView.setText("");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Initialize the send button with a listener that for click events
pwdLoginButton = (Button) findViewById(R.id.button_send);
pwdLoginButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
final String message = view.getText().toString();
String requestMessage = "Q-PW-" + message;
HttpAsyncTask task = new HttpAsyncTask();
task.execute("http://www.sporsimdi.com/mobile/turnstileRequest.jsf?request="
+ requestMessage);
}
});
}
@Override
protected void onPause() {
super.onPause();
// check if the device is already closed
if (device != null) {
try {
device.close();
} catch (IOException e) {
// we couldn't close the device, but there's nothing we can do
// about it!
}
// remove the reference to the device
device = null;
}
}
@Override
protected void onResume() {
super.onResume();
// get a USB to Serial device object
device = UsbSerialProber.acquire(usbManager);
if (device == null) {
Toast.makeText(this, "ON resume cihaz bulumanadi",
Toast.LENGTH_SHORT).show();
} else {
try {
// open the device
device.open();
// set the communication speed
device.setBaudRate(9600); // make sure this matches your
// device's setting!
Toast.makeText(this, "ON resume cihaz baglandi",
Toast.LENGTH_SHORT).show();
} catch (IOException err) {
Log.e(TAG, "Error setting up USB device: " + err.getMessage(),
err);
try {
// something failed, so try closing the device
device.close();
} catch (IOException err2) {
// couldn't close, but there's nothing more to do!
}
device = null;
return;
}
}
onDeviceStateChange();
}
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (device != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(device, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
@Override
public void onDestroy() {
super.onDestroy();
}
// sends color data to a Serial device as {R, G, B, 0x0A}
public void sendToArduino(String color) {
byte[] dataToSend = color.getBytes();
Toast.makeText(this, "Yollanacak veri:" + color, Toast.LENGTH_SHORT)
.show();
// send the color to the serial device
if (device != null) {
try {
Toast.makeText(this,
"device null degil Yollanacak veri:" + color,
Toast.LENGTH_SHORT).show();
device.write(dataToSend, 500);
Toast.makeText(this, "Veri basarili yollandi",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e(TAG, "couldn't write color bytes to serial device");
}
} else {
Toast.makeText(this, "Bagli cihaz yok", Toast.LENGTH_SHORT).show();
}
}
private void updateReceivedData(byte[] data) {
String rec = new String(data);
if (rec.contains("\n")) {
if (receivedData == null) {
receivedData = rec;
} else {
receivedData = receivedData + rec;
}
receivedData = receivedData.replaceAll("\n", "");
Toast.makeText(this, "Veri tamamlandi " + receivedData,
Toast.LENGTH_SHORT).show();
HttpAsyncTask task = new HttpAsyncTask();
task.execute("http://www.sporsimdi.com/mobile/turnstileRequest.jsf?request="
+ receivedData);
receivedData = null;
} else {
if (receivedData == null) {
receivedData = rec;
} else {
receivedData = receivedData + rec;
}
Toast.makeText(
this,
"Veri parca geldi parca:" + rec + "Son hal:" + receivedData,
Toast.LENGTH_SHORT).show();
}
}
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// TODO send ardunio open port
String resultCode = result.substring(1, 2);
sendToArduino(resultCode);
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
}
| true
|
ffe6612351859444cd2854f4290b034cea89dc62
|
Java
|
fabiogmail/curso-git
|
/PortalOsx/WEB-INF/src/Portal/Service/VolumetriaService.java
|
ISO-8859-1
| 17,130
| 1.84375
| 2
|
[] |
no_license
|
package Portal.Service;
import java.util.ArrayList;
import java.util.Iterator;
import net.sf.jasperreports.engine.JasperPrint;
import org.hibernate.Session;
import src.br.com.visent.dbdeteccao.corba.CorbaException;
import src.br.com.visent.dbdeteccao.corba.CorbaUtil;
import src.br.com.visent.dbdeteccao.corba.Format;
import src.br.com.visent.dbdeteccao.dao.LogDAO;
import src.br.com.visent.dbdeteccao.dto.LogSys;
import src.br.com.visent.dbdeteccao.util.FiltrosLog;
import Portal.Dao.Hibernate.Conf.RelatoriosVolumetriaDAO;
import Portal.Dao.Util.HibernateUtil;
import Portal.Dto.Bilhetador;
import Portal.Dto.RecursoVolumetria;
import Portal.Dto.RelatorioVolumetria;
import Portal.Dto.RelatorioVolumetriaDomingo;
import Portal.Dto.RelatorioVolumetriaQuarta;
import Portal.Dto.RelatorioVolumetriaQuinta;
import Portal.Dto.RelatorioVolumetriaSabado;
import Portal.Dto.RelatorioVolumetriaSegunda;
import Portal.Dto.RelatorioVolumetriaSexta;
import Portal.Dto.RelatorioVolumetriaTerca;
import Portal.Jasper.RelatorioAcessoJasper;
import Portal.Operacoes.OpRelVolumetriaAjax;
import Portal.Utils.DBDeteccaoProperties;
public class VolumetriaService {
private RelatorioVolumetriaDomingo domingoDto;
private RelatorioVolumetriaSegunda segundaDto;
private RelatorioVolumetriaTerca tercaDto;
private RelatorioVolumetriaQuarta quartaDto;
private RelatorioVolumetriaQuinta quintaDto;
private RelatorioVolumetriaSexta sextaDto;
private RelatorioVolumetriaSabado sabadoDto;
private RelatoriosVolumetriaDAO relVolumetria;
private RelatorioVolumetria relatorioVolumetria;
public static final int RELATORIO = 0;
public static final int ALARME = 1;
private int tipo = -1;
/**
* DTO com os dados retornados pelo servidor a respeito dos alarmes
*/
private LogSys volumetriaAlarmeLog;
/**
* Objeto de comunicao com o servidor para obteno dos dados.
*/
private LogDAO relAlarmeDAO;
private Session session;
private Bilhetador bilhetador;
private ArrayList listaCompleta;
private RelatorioAcessoJasper relAcesso = new RelatorioAcessoJasper();
public VolumetriaService(Session session){
this.session = session;
setListaCompleta( new ArrayList());
setTipo(RELATORIO);
// setRelatorioVolumetria(new RelatorioVolumetria());
}
public VolumetriaService(){
setListaCompleta( new ArrayList());
inicializarCorba();
setTipo(ALARME);
}
public String getNomeBilhetador(String bilhetarores){
setRelVolumetria(new RelatoriosVolumetriaDAO(session));
listaCompleta = relVolumetria.getBilhetadores(bilhetarores);
StringBuffer nomeBilhetador = new StringBuffer();
for (Iterator iterator = listaCompleta.iterator(); iterator.hasNext();) {
Bilhetador bilhetador = (Bilhetador) iterator.next();
nomeBilhetador.append(bilhetador.getNome()+";");
}
nomeBilhetador.deleteCharAt(nomeBilhetador.lastIndexOf(";"));
return nomeBilhetador.toString();
}
public ArrayList getRecursoVolumetria(){
setRelVolumetria(new RelatoriosVolumetriaDAO(session));
ArrayList listaRecurso = relVolumetria.getRecursoVolumetria();
return listaRecurso;
}
public Boolean salvar(ArrayList listaOrdenada){
ArrayList listaVolumetria = listaOrdenada;
//Session session = HibernateUtil.getSessionFactory().openSession();
RelatoriosVolumetriaDAO dao = new RelatoriosVolumetriaDAO(session);
for (Iterator iterator = listaOrdenada.iterator(); iterator.hasNext();) {
RecursoVolumetria recurso = new RecursoVolumetria();
String recursoVol = (String) iterator.next();
String[]dados = recursoVol.split(";");
Bilhetador bil = dao.getBilhetador(dados[0]);
recurso.setBilhetador(bil);
recurso.setIdBilhetador(bil.getIdBilhetador());
recurso.setLimMinimo(0);
recurso.setLimMaximo(0);
if(dados.length>1 && !dados[1].equals("")){
recurso.setLimMaximo(Integer.parseInt(dados[1]));
}
if(dados.length>2 && !dados[2].equals("")){
recurso.setLimMinimo(Integer.parseInt(dados[2]));
}
dao.salvar(recurso);
}
return true;
}
public ArrayList getRelVolumetria (String bilhetadores){
setRelVolumetria(new RelatoriosVolumetriaDAO(session));
ArrayList dao = new ArrayList();
String queryBilhetadores = configuraWhere(bilhetadores);
dao = relVolumetria.getDomingo(queryBilhetadores);
criaObjetosVolumetria(dao,"domingo");
dao.clear();
dao = relVolumetria.getSegunda(queryBilhetadores);
criaObjetosVolumetria(dao,"segunda");
dao.clear();
dao = relVolumetria.getTerca(queryBilhetadores);
criaObjetosVolumetria(dao,"terca");
dao.clear();
dao = relVolumetria.getQuarta(queryBilhetadores);
criaObjetosVolumetria(dao,"quarta");
dao.clear();
dao = relVolumetria.getQuinta(queryBilhetadores);
criaObjetosVolumetria(dao,"quinta");
dao.clear();
dao = relVolumetria.getSexta(queryBilhetadores);
criaObjetosVolumetria(dao,"sexta");
dao.clear();
dao = relVolumetria.getSabado(queryBilhetadores);
criaObjetosVolumetria(dao,"sabado");
if(listaCompleta != null){
listaCompleta.trimToSize();
}
return listaCompleta;
}
public ArrayList getRelVolumetriaAlarme(String bilhetadores, String id) {
// TODO Auto-generated method stub
try {
relAlarmeDAO = new LogDAO();
FiltrosLog filtros = new FiltrosLog();//Filtros a serem passados ao servidor
filtros.setTipo("VOLUMETRIA");//retornando apenas os dados de volumetria
if(bilhetadores.length() > 0)
filtros.setRecurso(bilhetadores);
String formato[] = relAlarmeDAO.getFormato("SYS");
String dadosStr = relAlarmeDAO.buscarAlarmes(Integer.parseInt(id.substring(0, 7), 16),5,true,filtros.toString(),1);
String dados[] = new String[0];
if(!dadosStr.equals("")){
dados = dadosStr.split("\n");
}
Format format = new Format(formato,LogSys.class);
for (int i = 0; i < dados.length; i++) {
int fator = 2*(1-1);
LogSys log = (LogSys)format.formatar(dados[i]);
log.setID(fator+i);
listaCompleta.add(log);
}
if(listaCompleta != null){
listaCompleta.trimToSize();
}
return listaCompleta;
} catch (CorbaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
// return null;
}
private String configuraWhere(String bilhetadores) {
// TODO Auto-generated method stub
if(bilhetadores == null )
bilhetadores = "";
if(bilhetadores.length() < 1){
return "";
}
else{
String where = "where";
String []arrayBilhetadores = bilhetadores.split(";");
for (int i = 0; i < arrayBilhetadores.length; i++) {
if(i == 0)
where += " bil.nome = '"+ arrayBilhetadores[i]+"'";
else
where += " or bil.nome = '"+ arrayBilhetadores[i]+"'";
}
return where;
}
}
private void criaObjetosVolumetria(ArrayList listaVolumetria, String diaSemana){
Object []lista;
for (int i = 0; i < listaVolumetria.size(); i++) {
lista = (Object[]) listaVolumetria.get(i);
mesclaObjetosVolumetria(lista,diaSemana);
}
}
private void mesclaObjetosVolumetria(Object[] objetos, String diaSemana){
setRelatorioVolumetria(new RelatorioVolumetria());
if(diaSemana.equalsIgnoreCase("domingo")){
ArrayList listaSemana = new ArrayList();
setDomingoDto((RelatorioVolumetriaDomingo) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getDomingoDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getDomingoDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getDomingoDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getDomingoDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getDomingoDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getDomingoDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getDomingoDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("segunda")){
ArrayList listaSemana = new ArrayList();
setSegundaDto((RelatorioVolumetriaSegunda) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getSegundaDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getSegundaDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getSegundaDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getSegundaDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getSegundaDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getSegundaDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getSegundaDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("terca")){
ArrayList listaSemana = new ArrayList();
setTercaDto((RelatorioVolumetriaTerca) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getTercaDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getTercaDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getTercaDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getTercaDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getTercaDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getTercaDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getTercaDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("quarta")){
ArrayList listaSemana = new ArrayList();
setQuartaDto((RelatorioVolumetriaQuarta) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getQuartaDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getQuartaDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getQuartaDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getQuartaDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getQuartaDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getQuartaDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getQuartaDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("quinta")){
ArrayList listaSemana = new ArrayList();
setQuintaDto((RelatorioVolumetriaQuinta) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getQuintaDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getQuintaDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getQuintaDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getQuintaDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getQuintaDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getQuintaDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getQuintaDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("sexta")){
ArrayList listaSemana = new ArrayList();
setSextaDto((RelatorioVolumetriaSexta) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getSextaDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getSextaDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getSextaDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getSextaDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getSextaDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getSextaDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getSextaDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
if(diaSemana.equalsIgnoreCase("sabado")){
ArrayList listaSemana = new ArrayList();
setSabadoDto((RelatorioVolumetriaSabado) objetos[0]);
setBilhetador((Bilhetador) objetos[1]);
getRelatorioVolumetria().setBilhetador(getBilhetador().getNome());
getRelatorioVolumetria().setId(getSabadoDto().getId());
getRelatorioVolumetria().setDataUltimoProc(getSabadoDto().getDataUltimoProc());
getRelatorioVolumetria().setSemanaDois(getSabadoDto().getSemanaDois());
getRelatorioVolumetria().setSemanaTres(getSabadoDto().getSemanaTres());
getRelatorioVolumetria().setSemanaUm(getSabadoDto().getSemanaUm());
getRelatorioVolumetria().setSemanaQuatro(getSabadoDto().getSemanaQuatro());
getRelatorioVolumetria().setValorAtual(getSabadoDto().getValorAtual());
getRelatorioVolumetria().setDia(diaSemana);
listaCompleta.add(getRelatorioVolumetria());
}
setRelatorioVolumetria(null);
}
/**
* @param pg
* @param paramOrdem
* @param group indica qual relatrio ser executado. TRUE=relatorio FALSE=alarmes
* @param path
* @param bilhetadores
* @param opRelVolumetriaAjax
* @return
*/
public String getRelatorioAcesso(int pg, String paramOrdem, boolean group, String path, String bilhetadores, OpRelVolumetriaAjax opRelVolumetriaAjax){
//RelatorioAcessoAction action = new RelatorioAcessoAction();
ArrayList relatorio = new ArrayList();
if(group){
relatorio.addAll(getRelVolumetria(bilhetadores));
}
else{
try{
relatorio.addAll(getRelVolumetriaAlarme(bilhetadores, opRelVolumetriaAjax.getSessao().getId()));
}
catch (NullPointerException e) {
opRelVolumetriaAjax.setJasperPrint(new JasperPrint());
opRelVolumetriaAjax.setJasperPrintDownload(new JasperPrint());
return "Erro na comunicao com o servidor de alarmes.";
}
}
relatorio.trimToSize();
relAcesso.setDadosRelatorioAcesso(relatorio,group,path,opRelVolumetriaAjax);
return relAcesso.relatorioHTML(pg,opRelVolumetriaAjax);
}
public String getRelatorioPagina(int pg, OpRelVolumetriaAjax opRelVolumetriaAjax){
return relAcesso.relatorioHTML(pg,opRelVolumetriaAjax);
}
private void inicializarCorba() {
// TODO Auto-generated method stub
String host = DBDeteccaoProperties.getProperties("host");
String porta = DBDeteccaoProperties.getProperties("porta");
CorbaUtil util = new CorbaUtil(porta, host);
try {
util.init();
} catch (CorbaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public RelatorioVolumetriaDomingo getDomingoDto() {
return domingoDto;
}
public void setDomingoDto(RelatorioVolumetriaDomingo domingoDto) {
this.domingoDto = domingoDto;
}
public RelatorioVolumetriaSegunda getSegundaDto() {
return segundaDto;
}
public void setSegundaDto(RelatorioVolumetriaSegunda segundaDto) {
this.segundaDto = segundaDto;
}
public RelatorioVolumetriaTerca getTercaDto() {
return tercaDto;
}
public void setTercaDto(RelatorioVolumetriaTerca tercaDto) {
this.tercaDto = tercaDto;
}
public RelatorioVolumetriaQuarta getQuartaDto() {
return quartaDto;
}
public void setQuartaDto(RelatorioVolumetriaQuarta quartaDto) {
this.quartaDto = quartaDto;
}
public RelatorioVolumetriaQuinta getQuintaDto() {
return quintaDto;
}
public void setQuintaDto(RelatorioVolumetriaQuinta quintaDto) {
this.quintaDto = quintaDto;
}
public RelatorioVolumetriaSexta getSextaDto() {
return sextaDto;
}
public void setSextaDto(RelatorioVolumetriaSexta sextaDto) {
this.sextaDto = sextaDto;
}
public RelatorioVolumetriaSabado getSabadoDto() {
return sabadoDto;
}
public void setSabadoDto(RelatorioVolumetriaSabado sabadoDto) {
this.sabadoDto = sabadoDto;
}
public void setRelVolumetria(RelatoriosVolumetriaDAO relVolumetria) {
this.relVolumetria = relVolumetria;
}
public RelatorioVolumetria getRelatorioVolumetria() {
return relatorioVolumetria;
}
public void setRelatorioVolumetria(RelatorioVolumetria relatorioVolumetria) {
this.relatorioVolumetria = relatorioVolumetria;
}
public ArrayList getListaCompleta() {
return listaCompleta;
}
public void setListaCompleta(ArrayList listaCompleta) {
this.listaCompleta = listaCompleta;
}
public Bilhetador getBilhetador() {
return bilhetador;
}
public void setBilhetador(Bilhetador bilhetador) {
this.bilhetador = bilhetador;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
| true
|
4ed3c6626d92421be5f8b815d3126ee74a939ab6
|
Java
|
AmauriPereira/ProjetoServir
|
/src/br/com/servirjanuaria/amauri/domainModel/repositorios/PessoaRepositorio.java
|
UTF-8
| 518
| 1.914063
| 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 br.com.servirjanuaria.amauri.domainModel.repositorios;
import br.com.servirjanuaria.amauri.domainModel.Pessoa;
import java.util.List;
/**
*
* @author Amauri
*/
public interface PessoaRepositorio extends Repositorio<Pessoa>{
public List<Pessoa> buscarWhereDtype(String nome, String dtype);
}
| true
|
406daf8356be86f7e737e69d828304dfc7a7eab7
|
Java
|
TATJAVA-Uladzislau-Seuruk/TATJAVA01_2017_Task03_Uladzislau_Seuruk
|
/src/main/java/com/epam/oop/controller/command/impl/AddNews.java
|
UTF-8
| 1,087
| 2.640625
| 3
|
[] |
no_license
|
package com.epam.oop.controller.command.impl;
import com.epam.oop.controller.command.Command;
import com.epam.oop.service.exception.ServiceException;
import com.epam.oop.service.factory.ServiceFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Implements Command interface for add new news command.
*
* @author Uladzislau Seuruk.
*/
public class AddNews implements Command {
private static final Logger LOG = LogManager.getRootLogger();
/**
* Name of command.
*/
public static final String COMMAND_NAME = "ADD_NEWS";
/**
* @see Command#execute(String)
*/
@Override
public String execute(String params) {
String response;
try {
ServiceFactory factory = ServiceFactory.getInstance();
factory.getCatalogService().addNews(params);
response = "News was successfully added.";
} catch (ServiceException se) {
LOG.error(se.getMessage(), se);
response = "Error while news search.";
}
return response;
}
}
| true
|
23f21d18844c9fedae414af9ce811bdc76513542
|
Java
|
haywood2018/gulimall
|
/gulimall-product/src/main/java/com/wxx/gulimall/product/service/impl/SkuImagesServiceImpl.java
|
UTF-8
| 1,254
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.wxx.gulimall.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxx.common.utils.PageUtils;
import com.wxx.common.utils.Query;
import com.wxx.gulimall.product.dao.SkuImagesDao;
import com.wxx.gulimall.product.entity.SkuImagesEntity;
import com.wxx.gulimall.product.service.SkuImagesService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service("skuImagesService")
public class SkuImagesServiceImpl extends ServiceImpl<SkuImagesDao, SkuImagesEntity> implements SkuImagesService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SkuImagesEntity> page = this.page(
new Query<SkuImagesEntity>().getPage(params),
new QueryWrapper<SkuImagesEntity>()
);
return new PageUtils(page);
}
@Override
public List<SkuImagesEntity> getImagesBySkuId(Long skuId) {
QueryWrapper<SkuImagesEntity> wrapper = new QueryWrapper<>();
wrapper.eq("sku_id", skuId);
return this.baseMapper.selectList(wrapper);
}
}
| true
|
dd485f915c12412137bce020335e4cbc1da68c38
|
Java
|
hamidsid/MatchIT_Java_Labs
|
/Lab02/src/GuessingGameTest.java
|
UTF-8
| 2,609
| 3.671875
| 4
|
[] |
no_license
|
import java.util.Random;
import java.util.Scanner;
public class GuessingGameTest {
private static Random rand = new Random();
private static Scanner input = new Scanner(System.in);
private static boolean quit = false;
private static boolean win = false;
private static int target;
private static int tries;
private static int highNum = 0;
public static void main(String[] args) {
while (!quit) {
playGame();
}
}
private static void playGame() {
System.out.println("Hello and welcome to my number guessing game.");
System.out.println("Pick a highest possible number: ");
highNum = input.nextInt();
if (highNum > 100) {
System.out.println("This is a big number, it might take you a while to guess.");
System.out.println("Do you still want to continue?");
System.out.println("Type 0 for yes, type 1 for no.");
int choice = input.nextInt();
if(choice == 0) {
target = rand.nextInt(highNum);
guess(target);
}
else {
System.out.println("Pick a different number: ");
highNum = input.nextInt();
target = rand.nextInt(highNum);
guess(target);
}
} else {
System.out.println("Okay. Pick a number between 0 and " + highNum);
target = rand.nextInt(highNum);
guess(target);
}
}
private static void guess(int randNum) {
int guess = 0;
while(!win) {
guess = input.nextInt();
if (guess == randNum) {
win = true;
} else if (guess < randNum) {
System.out.println("Number is to low, try again");
} else if (guess > randNum) {
System.out.println("Number is to high, try again");
}
tries++;
}
playAgainMessage(guess);
}
private static void playAgainMessage(int correctNum) {
System.out.println("You win! The number was " + correctNum);
System.out.println("You got it in " + tries + " tries!");
System.out.println("Would you like to play again(y/n)?");
String play = input.next();
if (play.equalsIgnoreCase("y")) {
System.out.println("The game will restart.");
System.out.flush();
win = false;
playGame();
} else {
System.out.println("The game will quit.");
quit = true;
}
}
}
| true
|
51ca48d31846e4f88a34bd24d66917126c1aeb24
|
Java
|
ooglooFahad/Explore-114
|
/app/src/main/java/oogloo/com/explore114/TabsActivity.java
|
UTF-8
| 2,153
| 2.125
| 2
|
[] |
no_license
|
package oogloo.com.explore114;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.WindowManager;
public class TabsActivity extends AppCompatActivity {
static ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
int Numboftabs = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
setContentView(R.layout.activity_tabs);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.mylogoicon1);
SpannableString s = new SpannableString(" EXPLORE 114");
s.setSpan(new TypefaceSpan(this, "ALGER.TTF"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setTitle(s);
SpannableString surah = new SpannableString("SURAH");
surah.setSpan(new TypefaceSpan(this, "Bariol_Regular.otf"), 0, surah.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableString parah = new SpannableString("PARAH");
parah.setSpan(new TypefaceSpan(this, "Bariol_Regular.otf"), 0, parah.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
CharSequence Titles[] = {parah, surah};
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setSelectedIndicatorColors(R.color.tab_active);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
}
| true
|
4024b325658fb104749a2a86c5973f85f0547c70
|
Java
|
moutainhigh/firebats
|
/firebats-http/src/test/java/firebats/http/server/results/RedirectTest.java
|
UTF-8
| 2,964
| 2.25
| 2
|
[] |
no_license
|
package firebats.http.server.results;
import static org.junit.Assert.assertEquals;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Observable;
import th.api.common.Ws;
import th.api.common.Ws.WsRequest;
import firebats.http.server.Chain;
import firebats.http.server.Context;
import firebats.http.server.Ext;
import firebats.http.server.FireHttpServer;
import firebats.http.server.IRequestHandler;
import firebats.http.server.exts.route.RouteExt;
import firebats.http.server.results.redirect.RedirectResultAware;
import firebats.http.server.results.string.StringResultAware;
public class RedirectTest {
private static final String HTTP_LOCALHOST_25001 = "http://localhost:25001/";
FireHttpServer s = FireHttpServer.create(25001);
Ws ws = new Ws();
@Before
public void before() {
s.start();
}
@After
public void after() {
s.stop();
ws.close();
}
@Test
public void redirectProvider() {
class TestContext extends Context implements RedirectResultAware,StringResultAware{
protected TestContext(Context context) {
super(context);
}
}
class TestExt implements Ext<Context,TestContext>{
@Override
public Observable<?> call(Chain<Context, TestContext> chain,Context ctx) {
return chain.next(new TestContext(ctx));
}
}
s.chain()
.link(new TestExt())
.link(new RouteExt<TestContext>() {{
get("/hi", new IRequestHandler<TestContext>() {
@Override
public Object handle(TestContext ctx) {
System.out.println("getPath "+ctx.getRequest().getPath());
return ctx.string("hi:"+ctx.getRequest().getQueryString()).render();
}
});
get("/redirectToHi", new IRequestHandler<TestContext>() {
@Override
public Object handle(TestContext ctx) {
return ctx.redirect("http://localhost:25001/hi?a=b").render();
}
});
}});
assertEquals("hi:a=b", request().addPath("/redirectToHi").get().getString());
}
//redirect 原理就是设置300系列转向
@Test
public void rawRedirect() {
s.chain()
.link(new RouteExt<Context>() {{
get("/hi", new IRequestHandler<Context>() {
@Override
public Observable<?> handle(Context ctx) {
ctx.getResponse().writeString("hi");
return Observable.empty();
}
});
get("/redirectToHi", new IRequestHandler<Context>() {
@Override
public Observable<?> handle(Context ctx) {
ctx.getResponse().setStatus(HttpResponseStatus.SEE_OTHER);
ctx.getResponse().getHeaders().setHeader("Location","/hi");
ctx.getResponse().writeString("to hi");
return Observable.empty();
}
});
}});
assertEquals("hi", request().addPath("/redirectToHi").get().getString());
}
private WsRequest request() {
return ws.newRequest(HTTP_LOCALHOST_25001);
}
}
| true
|
a96dbf08cee5143527ba3d595a8f11a0e20bc75c
|
Java
|
akdiallo/BitMusic
|
/BitMusic/bitmusic/network/api/ApiException.java
|
UTF-8
| 403
| 1.742188
| 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 bitmusic.network.api;
import bitmusic.network.exception.EnumTypeException;
/**
*
* @author florian
*/
public interface ApiException {
public void throwException(EnumTypeException type, String msg);
}
| true
|
907eb5f7f3f65676ddede897bad924d5a2bb7a27
|
Java
|
rrojanat/demoToy
|
/src/test/java/workshop/toy/controller/CartControllerUnitTest.java
|
UTF-8
| 1,335
| 2.15625
| 2
|
[] |
no_license
|
package workshop.toy.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import workshop.toy.model.CartDetail;
import workshop.toy.model.CartDetailWithToy;
import workshop.toy.repo.CartDetailRepo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.MockitoAnnotations.initMocks;
@RunWith(MockitoJUnitRunner.class)
public class CartControllerUnitTest {
@Mock
private CartDetailRepo cartDetailRepo;
private CartController cartController;
@Before
public void setup() throws Exception{
initMocks(this);
cartController= new CartController(cartDetailRepo);
}
@Test
public void testCartDetailEmpty() throws Exception {
List<CartDetailWithToy> expected = new ArrayList<CartDetailWithToy>();
given(cartDetailRepo.findCartDetailByCartId(new BigDecimal(1)))
.willReturn(expected);
List<CartDetailWithToy> cartDetailList = cartController.getCartDetailByCartId(new BigDecimal(1));
assertEquals(expected.size(), cartDetailList.size());
}
}
| true
|
c0e776ae93e82e41bce18af98f5fec2a3850e775
|
Java
|
mobapp20g6/frivillig-app1
|
/project/app/src/main/java/no/ntnu/mobapp20g6/app1/data/repo/SharedNonCacheRepository.java
|
UTF-8
| 5,096
| 2.21875
| 2
|
[
"MIT"
] |
permissive
|
package no.ntnu.mobapp20g6.app1.data.repo;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.function.Consumer;
import no.ntnu.mobapp20g6.app1.data.Result;
import no.ntnu.mobapp20g6.app1.data.ds.GroupDataSource;
import no.ntnu.mobapp20g6.app1.data.ds.LocationDataSource;
import no.ntnu.mobapp20g6.app1.data.ds.PictureDataSource;
import no.ntnu.mobapp20g6.app1.data.model.Group;
import no.ntnu.mobapp20g6.app1.data.model.Task;
/**
* Requests information regarding Group and Location.
* Does not hold caches of this information.
* Is a singleton.
* @author maardal, TrymV
*/
public class SharedNonCacheRepository {
private static volatile SharedNonCacheRepository instance;
private final GroupDataSource groupDataSource;
private final LocationDataSource locationDataSource;
private final PictureDataSource pictureDataSource;
private SharedNonCacheRepository(GroupDataSource groupDataSource, LocationDataSource locationDataSource, PictureDataSource pictureDataSource) {
this.groupDataSource = groupDataSource;
this.locationDataSource = locationDataSource;
this.pictureDataSource = pictureDataSource;
}
public static SharedNonCacheRepository getInstance(GroupDataSource groupDataSource, LocationDataSource locationDataSource, PictureDataSource pictureDataSource) {
if (instance == null) {
instance = new SharedNonCacheRepository(groupDataSource, locationDataSource, pictureDataSource);
}
return instance;
}
public void createGroup(String token, String title, String description, Long orgId,
Consumer<Result<Group>> createGroupCallBack) {
groupDataSource.createGroup(token, title, description, orgId, (createGroupResult) -> {
createGroupCallBack.accept(createGroupResult);
});
}
public void updateGroup(String token, String title, String description, Long groupId,
Consumer<Result<Group>> updateGroupCallBack) {
groupDataSource.updateGroup(token, title, description, groupId, (updateGroupResult) -> {
updateGroupCallBack.accept(updateGroupResult);
});
}
public void addUserToGroup(String token, String userId, Long groupId,
Consumer<Result<Boolean>> addUserToGroupCallBack) {
groupDataSource.addUserToGroup(token, userId, groupId, (adduserToGroupResult) -> {
addUserToGroupCallBack.accept(adduserToGroupResult);
});
}
public void getAllGroupTasks(String token, Long groupId,
Consumer<Result<List<Task>>> getAllGroupTasksCallBack) {
groupDataSource.getAllGroupTasks(token, groupId, (getAllGroupTasksResult) -> {
getAllGroupTasksCallBack.accept(getAllGroupTasksResult);
});
}
public void isOwnerOfGroup(String token, Long groupId,
Consumer<Result<Boolean>> isOwnerOfGroupCallBack) {
groupDataSource.isOwnerOfGroup(token, groupId, (isOwnerOfGroupResult) -> {
isOwnerOfGroupCallBack.accept(isOwnerOfGroupResult);
});
}
public void addLocationToTask(String token, Long taskId,
Double latitude, Double longitude,
String streetAddr, String city, Long postal, String country,
Consumer<Result<Task>> addLocationToTaskCallBack) {
locationDataSource.addLocationToTask(token, taskId,
latitude, longitude,
streetAddr, city, postal, country,
(addLocationToTaskResult) -> {
addLocationToTaskCallBack.accept(addLocationToTaskResult);
});
}
public void addLocationToGroup(String token, Long groupId,
String latitude, String longitude,
String streetAddr, String city, Long postal, String country,
Consumer<Result<Group>> addLocationToGroupCallBack) {
locationDataSource.addLocationToGroup(token, groupId,
latitude, longitude,
streetAddr, city, postal, country,
(addLocationToGroupResult) -> {
addLocationToGroupCallBack.accept(addLocationToGroupResult);
});
}
public void setTaskImage(String token, Long taskId, String picturePath, Consumer<Result<Task>>setTaskImageCallback) {
pictureDataSource.setTaskImage(token, taskId, picturePath, setTaskImageCallback);
}
public void setGroupLogo(String token, Long groupId, String picturePath, Consumer<Result<Group>>setGroupLogoCallback) {
pictureDataSource.setGroupLogo(token, groupId, picturePath, setGroupLogoCallback);
}
public void getVoluntaryBrregOrg(String orgid, Consumer<Result<JsonObject>> getVoluntaryBrreggOrgCallBack) {
groupDataSource.getBrregOrg(orgid, brreggResult -> {
getVoluntaryBrreggOrgCallBack.accept(brreggResult);
});
}
}
| true
|
eb851c489b9735f671ee7bc1b64c1e45ec6e2189
|
Java
|
kingstiger/VoIP
|
/src/test/java/microphone_tests/EncryptorTest.java
|
UTF-8
| 2,015
| 2.671875
| 3
|
[] |
no_license
|
package microphone_tests;
import com.models.MicrophoneData;
import com.security_utils.DecryptorImpl;
import com.security_utils.EncryptorImpl;
import com.sound_utils.Microphone;
import org.junit.Assert;
import org.junit.Test;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.LineUnavailableException;
import java.net.DatagramPacket;
public class EncryptorTest {
@Test
public void encryptorTest() {
String key = "to jestjakistamklucz";
byte[] dataToEncrypt = "data to encrypt".getBytes();
MicrophoneData microphoneDataBeforeEncryption = new MicrophoneData(dataToEncrypt, dataToEncrypt.length);
MicrophoneData microphoneDataEncrypted = new EncryptorImpl(key)
.encrypt(microphoneDataBeforeEncryption);
DatagramPacket datagramPacketEncryptedMicData = new DatagramPacket(microphoneDataEncrypted.getData(),
microphoneDataBeforeEncryption.getNumBytesRead());
DatagramPacket decrypt = new DecryptorImpl(key).decrypt(datagramPacketEncryptedMicData);
Assert.assertNotEquals(microphoneDataBeforeEncryption.getData(), decrypt.getData());
Assert.assertEquals(new String(dataToEncrypt), new String(decrypt.getData()));
System.out.println(new String(decrypt.getData()));
}
@Test
public void micTest() throws
LineUnavailableException {
String key = "asdasdada";
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, true);
Microphone mic = new Microphone(format);
MicrophoneData microphoneData = mic.read();
DatagramPacket datagramPacket = new DatagramPacket(microphoneData.getData(), microphoneData.getNumBytesRead());
MicrophoneData encrypt = new EncryptorImpl(key).encrypt(microphoneData);
Assert.assertNotEquals(new String(encrypt.getData()), new String(datagramPacket.getData()));
}
}
| true
|
b6d0a91de44e5dda58db4cc708f7612c5fd18fc6
|
Java
|
Fernum/Cyton_CappStone
|
/GUI/cyton-robotic-arm-manipulation-project/src/robotinterface/client/RobotClient.java
|
UTF-8
| 6,800
| 3.09375
| 3
|
[] |
no_license
|
package robotinterface.client;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
* RobotClient Class. <p>
*
* @author Brian Bailey
*/
public class RobotClient {
private static final boolean VERBOSE = true;
private static final String ROBOT_ADDRESS = "localhost";
private static final int ROBOT_PORT = 2694;
private static final int MAX_SIZE = 1024;
private static final byte[] bytes = new byte[MAX_SIZE];
private static ByteBuffer buffer = ByteBuffer.wrap(bytes);
private static final byte[] rbytes = new byte[MAX_SIZE];
private static ByteBuffer rBuffer = ByteBuffer.wrap(rbytes);
private static boolean isRunning = false;
private static SocketAddress rAddress;
private static SocketChannel rChannel;
private static RobotHandler rHandler;
private static Thread runningTask;
/**
* RobotClient Default Constructor.
*/
public RobotClient() {
}
/**
* Start Client.
*/
public static void startClient() {
init();
isRunning = true;
}
/**
* Stop Client.
*/
public static void stopClient() {
close();
isRunning = false;
}
/**
* Initialize client to send data to server.
*/
private static void init() {
if (isRunning == true) {
return;
}
if (VERBOSE) {
System.out.println("[TCP Client Started]");
}
try {
rAddress = new InetSocketAddress(ROBOT_ADDRESS, ROBOT_PORT);
rChannel = SocketChannel.open();
rChannel.connect(rAddress);
} catch (UnknownHostException ex) {
System.err.println("IP address of " + ROBOT_ADDRESS
+ " could not be determined. Port: " + ROBOT_PORT);
} catch (IOException ex) {
System.err.println("Couldn't get I/O for the connection to: "
+ ROBOT_ADDRESS + ". Port: " + ROBOT_PORT);
System.err.println(ex.getMessage());
}
//EntryDAO.connect();
startListening();
}
/**
* Sends Message to Server containing Joint Array. <p>
*
* @param joints Array of joints angles.
* @return Return message from server.
*/
public static String sendMessage(double joints[]) {
buffer.clear();
if (rChannel == null) {
System.err.println("TCP Connection Not Established.");
return null;
}
try {
/* This Takes double array and make it a string, stringing [ and ] */
byte[] data = Arrays.toString(joints).replaceAll("[\\[\\]]", "").getBytes();
if (VERBOSE) {
System.out.println("Sending: \n " + new String(data)
+ "\nDestination: " + ROBOT_ADDRESS);
}
buffer.put(data).flip();
if (rChannel != null && rChannel.write((ByteBuffer) buffer) != -1) {
buffer.rewind();
if (VERBOSE) {
System.out.println("Transmitted: "
+ new String(buffer.array()).trim());
}
// TODO: Database Stuff
//if(!EntryDAO.addEntry(new Entry(new String(buffer.array()).trim()))) {
// System.err.println("Failed to insert Entry into database");
//}
}
} catch (IOException ex) {
System.err.println("Couldn't write buffer to connection: "
+ ROBOT_ADDRESS + ".");
}
return null;
}
/**
* Send Message to Server. <p>
*
* @param aString Message to Send to server.
* @return Return Message from Server.
*/
public static String sendMessage(String aString) {
buffer.clear();
try {
if (VERBOSE) {
System.out.println("Sending: \n" + aString
+ "\nDestination: " + ROBOT_ADDRESS);
}
String size = Integer.toString(aString.getBytes("UTF-8").length);
if (size.length() < 4) {
size = "0" + size;
}
aString = size + aString;
buffer.put(ByteBuffer.wrap(aString.getBytes())).flip();
if (rChannel != null && rChannel.write((ByteBuffer) buffer) != -1) {
buffer.rewind();
if (VERBOSE) {
System.out.println("Transmitted: "
+ new String(buffer.array()).trim());
}
// TODO: Database Stuff
//if(!EntryDAO.addEntry(new Entry(new String(buffer.array()).trim()))) {
// System.err.println("Failed to insert Entry into database");
//}
}
} catch (IOException ex) {
System.err.println("Couldn't write buffer to connection: " + ROBOT_ADDRESS + ".");
}
return null;
}
/**
* Start Listening for Server Messages.
*/
private static void startListening() {
isRunning = true;
if (VERBOSE) {
System.err.println("RobotClient.startListening()");
}
runningTask = new Thread(new Runnable() {
@Override
public void run() {
do {
if (Thread.currentThread().isInterrupted()) {
break;
}
if (rChannel != null) {
readMessage();
}
} while (isRunning);
}
});
runningTask.start();
}
/**
* Read Message from Server and fire Callback.
*/
private static void readMessage() {
try {
rBuffer.clear();
if (rChannel.read(rBuffer) > -1) {
if (VERBOSE) {
System.out.println("Receiving Data from: "
+ ROBOT_ADDRESS);
}
rBuffer.flip();
rHandler.gotMessage(new String(rBuffer.array()).trim());
}
} catch (IOException ex) {
}
}
/**
* Closes Socket Channel
*/
private static void close() {
if (isRunning == false) {
return;
}
if (VERBOSE) {
System.out.println("[TCP Client Stopped]");
}
try {
rChannel.close();
} catch (IOException ex) { /* TODO: Catch Exception */ }
}
/**
* Set RobotHandler for Client. <p>
*
* @param rHandler Client's RobotHandler.
*/
public static void setHandler(RobotHandler rHandler) {
RobotClient.rHandler = rHandler;
}
}
| true
|
94d6dc9a056cf37f657c9b850b9d5c754895eb1b
|
Java
|
slob-cow/java_performance_optimization
|
/decorator_seven/src/com/test/java/UpperCaseInputStream.java
|
UTF-8
| 1,365
| 3.21875
| 3
|
[] |
no_license
|
package com.test.java;
/**
* @program: java_performance_optimization
* @Author:chenxuebing
* @Date:2019-09-26 9:47
* @Description:(描述)
*/
/**
* java的Io流机制就使用了装饰模式
* InputStream: 接口类
* FileInputStream: StringBufferInputStream: ByteArrayInPutStream : 被装饰类
* FilterInputStream: 装饰类接口
* --: 具体装饰类
* BufferInputStream: DateInputStream: LineNumberInputStream
*
*/
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 实现一个将流中的小写字母转为大写字母的装饰者对象
*/
public class UpperCaseInputStream extends FilterInputStream {
protected UpperCaseInputStream(InputStream in) {
super(in);
}
@Override
//读取流,将流中的小写字母转为大写字母
public int read() throws IOException//单字符的读
{
int c=super.read();//这个super.read()就是调用上面super(in);的主题对象
return c==-1?c:Character.toUpperCase((char)(c));
}
@Override
public int read(byte[] b,int offset,int len) throws IOException//多字符的读
{
int result=super.read(b,offset,len);
for(int i=0;i<result;i++)
{
b[i]=(byte)Character.toUpperCase((char)(b[i]));
}
return result;
}
}
| true
|
ee438be00a00c01d9d3412a86d788b202cd11632
|
Java
|
rustamkremcheev/DETA_CACHE
|
/src/main/java/org/lyg/common/exceptions/DetaDBException.java
|
UTF-8
| 705
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.lyg.common.exceptions;
public class DetaDBException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errorId;
private String errorMessage;
public String getErrorId() {
return errorId;
}
public void setErrorId(String errorId) {
this.errorId = errorId;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DetaDBException() {
super();
}
public DetaDBException(String errorId, String errorMessage) {
super(errorMessage);
this.errorId = errorId;
this.errorMessage = errorMessage;
}
}
| true
|
c7720cb5f7f3f452d339f9a5610936249520018b
|
Java
|
sivareddy1/java-for-testers
|
/src/test/java/com/serenitydojo/HelloWorldWriterTest.java
|
UTF-8
| 968
| 3.28125
| 3
|
[] |
no_license
|
package com.serenitydojo;
import org.junit.Test;
public class HelloWorldWriterTest {
@Test
public void shouldWriteHelloWorldToConsole(){
HelloWorldWriter writer = new HelloWorldWriter();
writer.writeHelloWorldToConsole();
}
@Test
public void declaringNumericalVariables(){
int ageThisYear = 35; // or we can use Integer age = 35, Integer is a class in java and can use different default functions using Integer
int ageNextYear = ageThisYear+10;
long starsInTheGalaxy = 1000000000L;
double weight = 10.690;
System.out.println(ageNextYear);
}
@Test
public void workingWithStringVariables(){
String firstName = " Siva-Test ";
String replacedFirstName=firstName.replace("Test","Reddy");
System.out.println(firstName.toUpperCase());
System.out.println(firstName.trim());
System.out.println(replacedFirstName.toUpperCase());
}
}
| true
|
789cf76cefd0d4c86806a99a09b74f2c7b93cde8
|
Java
|
Lakshmanm/RBSK_NEW
|
/app/src/main/java/nunet/rbsk/model/Surgery.java
|
UTF-8
| 2,580
| 2.28125
| 2
|
[] |
no_license
|
//=============================================================================
// All rights reserved to Nunet Cube Software Solutions.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
//=============================================================================
package nunet.rbsk.model;
//*****************************************************************************
//* Name : SurgicalHistory.java
//* Type :
//* Description :
//* References :
//* Author : promodh.munjeti
//* Created Date : Jun 10, 2015
//*****************************************************************************
//* MODIFICATION LOG
//*****************************************************************************
//* Ver Date
//*
//*
//* Code Review LOG
//*****************************************************************************
//* Ver Date Code Review By Observations
//*****************************************************************************
public class Surgery {
int id;
String name;
String comments;
int screeningRound;
int screeningYear;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the comments
*/
public String getComments() {
return comments;
}
/**
* @param comments
* the comments to set
*/
public void setComments(String comments) {
this.comments = comments;
}
/**
* @return the screeningRound
*/
public int getScreeningRound() {
return screeningRound;
}
/**
* @param screeningRound
* the screeningRound to set
*/
public void setScreeningRound(int screeningRound) {
this.screeningRound = screeningRound;
}
/**
* @return the screeningYear
*/
public int getScreeningYear() {
return screeningYear;
}
/**
* @param screeningYear
* the screeningYear to set
*/
public void setScreeningYear(int screeningYear) {
this.screeningYear = screeningYear;
}
}
| true
|
80f67bcfb096c1d389c47ef31d2650f67758b330
|
Java
|
saketdchaudhari/fuelsolution
|
/src/com/fs/dao/UserDao.java
|
UTF-8
| 750
| 2.5625
| 3
|
[] |
no_license
|
package com.fs.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.fs.model.User;
public class UserDao extends PersistenceDao<User, Integer> implements IUserDao{
EntityManager entityManager;
public UserDao(EntityManager entityManager) {
super(User.class, entityManager);
this.entityManager = entityManager;
}
@Override
public User findUserBy(String loginId) {
User user = null;
Query query = getEntityManager().createQuery("from User usr where usr.loginId ='"+loginId+"'");
List<User> users = query.getResultList();
if(users.size() > 0) {
user = users.get(0);
}
return user;
}
public EntityManager getEntityManager() {
return this.entityManager;
}
}
| true
|
ccfc6219b47a9c8a0b5d939d6693623817bff468
|
Java
|
freestyler734/1Z0-809
|
/src/com/company/designPatternsAndPrinciples/patterns/factory/Pencil.java
|
UTF-8
| 381
| 2.71875
| 3
|
[] |
no_license
|
package com.company.designPatternsAndPrinciples.patterns.factory;
/**
* Один из возвращаемых фабрикой типов
*/
public class Pencil extends Item {
// делаем конструктор доступным только в этом пакете
Pencil(){}
@Override
void printName() {
System.out.println("Pencil");
}
}
| true
|
6e55c2e3abaae20a47536994ce6a630340949cf1
|
Java
|
GiovanniPoggi/Mastermind_and_Distributed_Puzzle
|
/es1/src/main/java/es1/util/SetupPlayer.java
|
UTF-8
| 510
| 3.40625
| 3
|
[] |
no_license
|
package es1.util;
/**
* Class That Set Up Player.
*/
public class SetupPlayer {
/**
* Field that represents the number of the Player.
*/
private final int number;
/**
* Constructor of the class.
* @param number of the player.
*/
public SetupPlayer(int number) {
this.number = number;
}
/**
* Method that return the Number of the Player.
* @return number of the player.
*/
public int getNumber() {
return number;
}
}
| true
|
87abb5f320eb861e252336e2e273026d2e10a429
|
Java
|
Amoghavarsha01/JavaConcepts
|
/src/com/java/TwoArraySpiral.java
|
UTF-8
| 1,346
| 3.765625
| 4
|
[] |
no_license
|
package com.java;
import java.util.Arrays;
public class TwoArraySpiral {
public static void main(String[] args) {
int[][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
//1. 1st row all the elements should be displayed (i = 0 )
//
/*for(int i=0; i < arr.length; i++) {
for(int j=0;j < arr[i].length;j++) {
if(i==0) {
System.out.println(arr[i][j]);
}
else {
if(i > 0 && i < (arr.length ) ){
System.out.println(arr[i][arr[i].length - 1]);
}
}
}
}*/
/*int a = 00;
int count = 0;
if(a==0) {
count++;
}
while(a != 0 ) {
System.out.println(a);
if(a%10 == 0) {
count++;
}
a=a/10;
}
System.out.println(count);*/
/*int[] arr1 = {1,2,3,4,5};
int numOfTriplets= 0;
for (int i = 0; i < arr1.length-2; i++)
{
for (int j = i+1; j < arr1.length-1; j++)
{
for (int k = j+1; k < arr1.length; k++)
{
// output the triplet arr[i], arr[j], arr[k]
System.out.println(arr1[i] + " " + arr1[j] + " " + arr1[k]);
++numOfTriplets;
}
}
}
System.out.println(numOfTriplets);*/
int[] arr2 = {2,10,3,4};
Arrays.sort(arr2);
int sum = 0 ;
for(int i = arr2[0] ; i <= arr2[arr2.length - 1]; i++) {
sum = sum + i;
}
System.out.println(sum);
}
}
| true
|
56dc2843cde20269ea3908f0384ecebfff854871
|
Java
|
theaisla/info216
|
/Thea sin kode/ProsjektINFO216/src/prosjekt/StudentSenteretSIB.java
|
UTF-8
| 12,295
| 2.15625
| 2
|
[] |
no_license
|
package prosjekt;
import java.io.FileOutputStream;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.rdf.model.InfModel;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.sparql.vocabulary.FOAF;
import org.apache.jena.vocabulary.VCARD;
public class StudentSenteretSIB {
public static void main(String[] args) {
Model basemodel = ModelFactory.createDefaultModel();
InfModel model = ModelFactory.createRDFSModel(basemodel);
// Forkortelser
// String dbpedia = "http://dbpedia.org/resource/";
String schema = "http://schema.org/";
String owl = "http://owl.org/";
// Properties
Property postalAddress = model.createProperty(schema + "PostalAddress");
Property telephone = model.createProperty(schema + "telephone");
Property email = model.createProperty(schema + "email");
// SIB
Resource SIB = model.createResource(owl + "SIB");
// Studentsenteret
Resource studentsenteret = model.createResource(owl + "studentsenteret");
// Relationship
SIB.addProperty(FOAF.knows, studentsenteret);
studentsenteret.addProperty(FOAF.knows, SIB);
// Contact info
studentsenteret.addProperty(postalAddress, "Parkveien1,5007Bergen,Norge");
studentsenteret.addProperty(telephone, "55545124");
studentsenteret.addProperty(email, "studentsenteret@sib.no");
//Åpningstider
Property openingHours = model.createProperty(schema + "openingHours");
Property mo = model.createProperty(schema + "Mandag");
Property tu = model.createProperty(schema + "Tirsdag");
Property we = model.createProperty(schema + "Onsdag");
Property th = model.createProperty(schema + "Torsdag");
Property fr = model.createProperty(schema + "Fredag");
Property sa = model.createProperty(schema + "Lordag");
Property su = model.createProperty(schema + "Sondag");
studentsenteret.addProperty(mo, "07:00-22:30");
studentsenteret.addProperty(tu, "07:00-22:30");
studentsenteret.addProperty(we, "07:00-22:30");
studentsenteret.addProperty(th, "07:00-22:30");
studentsenteret.addProperty(fr, "07:00-21:30");
studentsenteret.addProperty(sa, "09:00-18:00");
studentsenteret.addProperty(su, "10:00-20:00");
Resource[]ssListOfOpeningHours = {mo, tu, we, th, fr, sa, su};
Resource ssOpeningHours = model.createList(ssListOfOpeningHours);
studentsenteret.addProperty(openingHours, ssOpeningHours);
// Class type
Resource spinningtime = model.createResource(owl + "spinning");
Resource saltime = model.createResource(owl + "saltime");
Resource bassengtime = model.createResource(owl + "bassengtimer");
Resource rotime = model.createResource(owl + "rotime");
Property typeOfClass = model.createProperty(owl + "typeOfClass");
// Fasiliteter
Property harFasilitet = model.createProperty(owl + "harFasilitet");
Resource basseng = model.createResource(owl + "basseng");
Resource vekter = model.createResource(owl + "vekter");
Resource garderobe = model.createResource(owl + "garderobe");
Resource personligTrening = model.createResource(owl + "personligTrening");
studentsenteret.addProperty(harFasilitet, basseng)
.addLiteral(harFasilitet, vekter)
.addLiteral(harFasilitet, garderobe)
.addLiteral(harFasilitet, saltime)
.addLiteral(harFasilitet, bassengtime)
.addLiteral(harFasilitet, rotime)
.addLiteral(harFasilitet, personligTrening)
.addProperty(harFasilitet, spinningtime);
// Classes
Property workoutClass = model.createProperty(owl + "workoutClass");
//saltimer
Resource yoga = model.createResource(owl + "yoga"); yoga.addProperty(typeOfClass, saltime);
Resource pilates = model.createResource(owl + "pilates"); pilates.addProperty(typeOfClass, saltime);
Resource stepMoves = model.createResource(owl + "stepMoves"); stepMoves.addProperty(typeOfClass, saltime);
Resource stepIntervall = model.createResource(owl + "stepIntervall"); stepIntervall.addProperty(typeOfClass, saltime);
Resource tabata = model.createResource(owl + "tabata"); tabata.addProperty(typeOfClass, saltime);
Resource styrkeStang = model.createResource(owl + "styrkeMedStang"); styrkeStang.addProperty(typeOfClass, saltime);
Resource zumba = model.createResource(owl + "zumba"); zumba.addProperty(typeOfClass, saltime);
Resource basisballRaw = model.createResource(owl + "basisballRaw"); basisballRaw.addProperty(typeOfClass, saltime);
//spinning
Resource pulsTopp55 = model.createResource(owl + "pulstopp55"); pulsTopp55.addProperty(typeOfClass, spinningtime);
Resource intervall45 = model.createResource(owl + "intervall45"); intervall45.addProperty(typeOfClass, spinningtime);
Resource intervall55 = model.createResource(owl + "intervall55"); intervall55.addProperty(typeOfClass, spinningtime);
Resource intervall90 = model.createResource(owl + "intervall55"); intervall90.addProperty(typeOfClass, spinningtime);
Resource raceday75 = model.createResource(owl + "raceday75"); raceday75.addProperty(typeOfClass, spinningtime);
//basseng
Resource aquaIntervall = model.createResource(owl + "aquaIntervall"); aquaIntervall.addProperty(typeOfClass, bassengtime);
//spinning
Resource intervallPyramide = model.createResource(owl + "intervallPyramide"); intervallPyramide.addProperty(typeOfClass, rotime);
//liste
Resource[]listOfTrainingFormsStudentSenteret = {yoga, pilates, stepMoves, stepIntervall, tabata, styrkeStang, zumba, basisballRaw,
pulsTopp55, intervall45, intervall55, intervall90, raceday75};
Resource ssClasses = model.createList(listOfTrainingFormsStudentSenteret);
studentsenteret.addProperty(workoutClass, ssClasses);
// Tid / dag / varighet / instruktør
Property starttid = model.createProperty(owl + "start");
Property varighet = model.createProperty(owl + "varighet");
Property dag = model.createProperty(owl + "dag");
Property instrukor = model.createProperty(owl + "instruktor");
Property isClass = model.createProperty(owl + "isClass");
// Mandag
Resource yogaSSM = model.createResource(owl + "yogaSSM");
yogaSSM.addProperty(isClass, yoga).addProperty(starttid, "07:30").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "Randi");
intervallPyramide.addProperty(starttid, "08:430").addProperty(dag, mo).addProperty(varighet, "60 min").addProperty(instrukor, "Eivind");
pulsTopp55.addProperty(starttid, "16:15").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "Gina");
stepMoves.addProperty(starttid, "16:45").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "Heidi");
intervall45.addProperty(starttid, "18:00").addProperty(dag, mo).addProperty(varighet, "45 min").addProperty(instrukor, "Heidi");
tabata.addProperty(starttid, "18:00").addProperty(dag, mo).addProperty(varighet, "45 min").addProperty(instrukor, "Anna");
intervall55.addProperty(starttid, "19:00").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "Anna");
yoga.addProperty(starttid, "19:00").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "");
aquaIntervall.addProperty(starttid, "20:00").addProperty(dag, mo).addProperty(varighet, "45 min").addProperty(instrukor, "Gina");
styrkeStang.addProperty(starttid, "20:00").addProperty(dag, mo).addProperty(varighet, "55 min").addProperty(instrukor, "Astrid Maria");
// Tirsdag
zumba.addProperty(starttid, "17:00").addProperty(dag, tu).addProperty(varighet, "55 min").addProperty(instrukor, "Jazmin");
intervall90.addProperty(starttid, "17:30").addProperty(dag, tu).addProperty(varighet, "90 min").addProperty(instrukor, "Odin");
intervallPyramide.addProperty(starttid, "19:00").addProperty(dag, tu).addProperty(varighet, "60 min").addProperty(instrukor, "Jørgen");
tabata.addProperty(starttid, "19:10").addProperty(dag, tu).addProperty(varighet, "45 min").addProperty(instrukor, "Astrid Maria");
pulsTopp55.addProperty(starttid, "19:15").addProperty(dag, tu).addProperty(varighet, "55 min").addProperty(instrukor, "Emilie");
// Onsdag
aquaIntervall.addProperty(starttid, "15:00").addProperty(dag, we).addProperty(varighet, "45 min").addProperty(instrukor, "Gina");
intervallPyramide.addProperty(starttid, "17:00").addProperty(dag, we).addProperty(varighet, "60 min").addProperty(instrukor, "Eiving");
yoga.addProperty(starttid, "18:00").addProperty(dag, we).addProperty(varighet, "55 min").addProperty(instrukor, "Randi");
pulsTopp55.addProperty(starttid, "19:00").addProperty(dag, we).addProperty(varighet, "55 min").addProperty(instrukor, "Brynhild");
basisballRaw.addProperty(starttid, "19:10").addProperty(dag, we).addProperty(varighet, "45 min").addProperty(instrukor, "Veronika");
pilates.addProperty(starttid, "20:00").addProperty(dag, we).addProperty(varighet, "55 min").addProperty(instrukor, "Catrine");
// Torsdag
pulsTopp55.addProperty(starttid, "08:15").addProperty(dag, th).addProperty(varighet, "55 min").addProperty(instrukor, "Gina");
yoga.addProperty(starttid, "12:15").addProperty(dag, th).addProperty(varighet, "55 min").addProperty(instrukor, "Olga");
intervall55.addProperty(starttid, "16:15").addProperty(dag, th).addProperty(varighet, "55 min").addProperty(instrukor, "Espen");
pulsTopp55.addProperty(starttid, "17:30").addProperty(dag, th).addProperty(varighet, "55 min").addProperty(instrukor, "Trudi");
styrkeStang.addProperty(starttid, "18:15").addProperty(dag, th).addProperty(varighet, "55 min").addProperty(instrukor, "Tonje N");
intervallPyramide.addProperty(starttid, "19:00").addProperty(dag, th).addProperty(varighet, "60 min").addProperty(instrukor, "Amandus");
// Fredag
stepIntervall.addProperty(starttid, "16:00").addProperty(dag, fr).addProperty(varighet, "55 min").addProperty(instrukor, "Linn E");
raceday75.addProperty(starttid, "17:15").addProperty(dag, fr).addProperty(varighet, "75 min").addProperty(instrukor, "Linn E");
intervallPyramide.addProperty(starttid, "17:30").addProperty(dag, fr).addProperty(varighet, "60 min").addProperty(instrukor, "Jørgen");
// Lørdag
intervall55.addProperty(starttid, "13:00").addProperty(dag, sa).addProperty(varighet, "55 min").addProperty(instrukor, "Ann Kristin M");
// Søndag
pulsTopp55.addProperty(starttid, "17:00").addProperty(dag, su).addProperty(varighet, "55 min").addProperty(instrukor, "Linn E");
styrkeStang.addProperty(starttid, "18:15").addProperty(dag, su).addProperty(varighet, "55 min").addProperty(instrukor, "Linn E");
// Writing to file
try {
model.write(new FileOutputStream("StudentSenter.ttl"), "TURTLE");
} catch (Exception e) {
// TODO: handle exception
}
// Print
//model.write(System.out, "RDF/XML");
//model.close();
// SPARQL query
/* System.out.println("Query");
dumpQueryResult(
model,
String.format(
"prefix a: <http://owl.org/> "
+ "SELECT ?x ?p "
+ "WHERE { a:yoga ?x ?p}",
("StudentSenteret.ttl")));
}
private static void dumpQueryResult(final Model model, final String queryString) {
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results, query);
qe.close();
}*/
System.out.println("--------------TURTLE------------------");
model.write(System.out, "TURTLE");
/*System.out.println("--------------N-TRIPLE------------------");
model.write(System.out, "N-TRIPLE");
System.out.println("--------------N3------------------");
model.write(System.out, "N3");
System.out.println("--------------JSON-LD------------------");
model.write(System.out, "JSON-LD");
System.out.println("--------------RDF/XML------------------");
model.write(System.out, "RDF/XML");
*/
}}
| true
|
b5ba968edca208fd9f6f810a47d64658e5c47039
|
Java
|
WHAT-ROUGH-BEAST/RepositeManage
|
/src/util/CheckoutHelper.java
|
GB18030
| 2,373
| 2.703125
| 3
|
[] |
no_license
|
package util;
import java.util.*;
import javaBean.Order;
import javaBean.PickingTask;
import javaBean.Product;
import javaBean.ProductListContainer;
import javaBean.Reposite;;
interface CheckoutInterface
{
void addOrder(Order order);
void removeOrder(int id);
void checkout();
List<Order> getOrders();
}
public class CheckoutHelper implements CheckoutInterface
{
private List<Reposite> repos;
private List<Order> orders;
private static LinkedList<PickingTask> tasks = new LinkedList<>();
public CheckoutHelper(List<Reposite> repos)
{
orders = new ArrayList<>();
setReposites(repos);
}
// ǰеIJֿ
public void setReposites(List<Reposite> repos)
{
if (null == repos)
throw new RuntimeException();
this.repos = repos;
}
@Override
public void addOrder(Order order)
{
if (null == order || null == order.getBuyerName()
|| 0 == order.getProducts().size())
throw new RuntimeException("invalid order");
orders.add(order);
}
@Override
public void removeOrder(int id)
{
for (Order o : orders)
{
if (id == o.getId())
{
orders.remove(o);
return;
}
}
throw new RuntimeException("can't find order id: " + id);
}
public List<Order> getOrders()
{
return orders;
}
/**
* ֿи
*
*/
@Override
public void checkout()
{
// ²ֿ
ArrayList<Product> checkoutProducts = new ArrayList<>();
for (Order o : orders)
{
checkoutProducts.addAll(o.getProducts());
}
for (Product p : checkoutProducts)
{
for (Reposite r : repos)
{
Product product = r.search(p.getId());
if (product.getAmount() - p.getAmount() < 0)
throw new RuntimeException("治");
product.setAmount(product.getAmount() - p.getAmount());
// ݿ
Product.updateDBProduct(product);
}
}
// õtaskб
generateTask();
}
/*
* ԱordersתΪtasks
*/
private void generateTask()
{
TaskGenerator generator = (TaskGenerator) XMLUtil.getBean("TaskGeneratorconfig");
tasks.addAll(generator.generateTask(orders));
// database¼ʷ
orders.clear();
}
/*
* Աõÿε
*/
public PickingTask getTask()
{
if (tasks.isEmpty())
throw new RuntimeException("ûи");
return tasks.pop();
}
}
| true
|
c8d4e8bfac747d6a568a0fdcc5b90103399b52e8
|
Java
|
MR-116/com.masociete.projet_mobile-1_source_from_JADX
|
/sources/fr/pcsoft/wdjava/ui/utils/WDSablierImpl.java
|
UTF-8
| 3,364
| 2.140625
| 2
|
[] |
no_license
|
package fr.pcsoft.wdjava.ui.utils;
import android.app.Activity;
import fr.pcsoft.wdjava.core.application.WDProjet;
import fr.pcsoft.wdjava.core.utils.C0806j;
import fr.pcsoft.wdjava.core.utils.C0808l;
import fr.pcsoft.wdjava.p032m.C0938m;
import fr.pcsoft.wdjava.ui.activite.C0492a;
import fr.pcsoft.wdjava.ui.activite.C1056i;
import fr.pcsoft.wdjava.ui.activite.WDActivite;
import java.util.Stack;
public class WDSablierImpl implements C0857z {
/* renamed from: b */
private C1522x f4550b = null;
/* renamed from: c */
private int f4551c = 0;
/* renamed from: d */
private Stack<String> f4552d = new Stack();
/* renamed from: e */
private C0492a f4553e;
/* renamed from: f */
private Activity f4554f = null;
/* renamed from: g */
private int f4555g = 0;
public WDSablierImpl() {
Activity a = C1056i.m7562a();
if (a instanceof Activity) {
this.f4554f = a;
if (a instanceof WDActivite) {
this.f4553e = new C1506g(this);
((WDActivite) a).mo1766b().ajouterEcouteurActivite(this.f4553e);
}
}
}
/* renamed from: a */
public final boolean m10413a() {
return (this.f4555g & 1) == 0;
}
public void destroy() {
if (C0938m.m6815b()) {
if (this.f4553e != null && (this.f4554f instanceof WDActivite)) {
((WDActivite) this.f4554f).mo1766b().supprimerEcouteurActivite(this.f4553e);
this.f4553e = null;
}
this.f4554f = null;
if (this.f4552d != null) {
this.f4552d.clear();
}
if (this.f4550b != null) {
this.f4550b.dismiss();
this.f4550b = null;
}
}
}
public int getOptions() {
return this.f4555g;
}
public void hide() {
if (C0938m.m6815b() && isShown()) {
this.f4551c--;
this.f4552d.pop();
if (this.f4551c > 0) {
updateMessage(this.f4552d.isEmpty() ? "" : (String) this.f4552d.peek());
} else {
destroy();
}
}
}
public boolean isDestroyed() {
return this.f4554f == null;
}
public final boolean isShown() {
return this.f4550b != null && this.f4551c > 0;
}
public void show(String str) {
show(str, 0);
}
public void show(String str, int i) {
if (C0938m.m6815b()) {
this.f4555g |= i;
if (C0808l.m4053k(str)) {
str = WDProjet.getInstance().getTitreSuivant();
}
if (!isShown()) {
if (this.f4554f == null || this.f4554f.isFinishing()) {
destroy();
return;
} else {
this.f4550b = new C1522x(this.f4554f);
this.f4550b.show();
}
}
this.f4551c++;
this.f4552d.push(str);
updateMessage(str);
}
}
public void updateMessage(String str) {
if (C0938m.m6815b() && isShown()) {
this.f4550b.m10573a(str);
C1515p.m10542a(-50);
}
}
public void updateUI() {
if (C0938m.m6815b()) {
C0806j.m3953c();
}
}
}
| true
|
3ab0003d8fd5adc60340256013256bca197d3e50
|
Java
|
pproszowski/Java_University
|
/PhoneBook/Company.java
|
UTF-8
| 366
| 3.03125
| 3
|
[] |
no_license
|
public class Company extends Record{
String name;
String address;
Company(String _name, String _address, PhoneNumber _phoneNumber){
super(_phoneNumber);
name = _name;
address = _address;
}
@Override
String getDescription(){
return "Company: " + name + ", " + address + ", " + super.getPhoneNumber();
}
}
| true
|
91115d18d95de0b45bda690bafade4c1380ea784
|
Java
|
juandiazgit/Ceiba-ClinicaOdontologica
|
/java-arquitectura-hexagonal/microservicio/dominio/src/main/java/com/ceiba/clinicaodontologica/dominio/servicio/cita/ServicioObtenerCita.java
|
UTF-8
| 1,089
| 1.96875
| 2
|
[] |
no_license
|
package com.ceiba.clinicaodontologica.dominio.servicio.cita;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ceiba.clinicaodontologica.dominio.Cita;
import com.ceiba.clinicaodontologica.dominio.persistencia.entidad.CitaEntity;
import com.ceiba.clinicaodontologica.dominio.persistencia.repositorio.jpa.RepositorioCitaJPA;
import com.ceiba.clinicaodontologica.dominio.repositorio.RepositorioCita;
@Service
public class ServicioObtenerCita {
private final RepositorioCita repositorioCita;
private final RepositorioCitaJPA repositorioCitaJPA;
public ServicioObtenerCita(RepositorioCita repositorioCita, RepositorioCitaJPA repositorioCitaJPA) {
this.repositorioCita = repositorioCita;
this.repositorioCitaJPA = repositorioCitaJPA;
}
public Cita obtenerPorId(int codigoPaciente) {
return this.repositorioCita.obtenerPorId(codigoPaciente);
}
public List<CitaEntity> obtenerListaDeCitas(int codigoDoctor) {
return this.repositorioCitaJPA.obtenerCitasEntityPorCodigoDoctor(codigoDoctor);
}
}
| true
|
9e12ad25c1a3bb112634e22a7d6848627d6b1f8d
|
Java
|
rdzfv/subwayGame
|
/service/2DGame/src/main/java/com/xyy/subway/game2d/controller/VStationStoreController.java
|
UTF-8
| 11,412
| 2.109375
| 2
|
[] |
no_license
|
package com.xyy.subway.game2d.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xyy.subway.game2d.dto.ExpAndLevelDTO;
import com.xyy.subway.game2d.dto.VRouteStationDTO;
import com.xyy.subway.game2d.entity.*;
import com.xyy.subway.game2d.error.BusinessException;
import com.xyy.subway.game2d.error.EnumBusinessError;
import com.xyy.subway.game2d.response.CommonReturnType;
import com.xyy.subway.game2d.service.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* @author xyy
* @date 2020/1/28 12:17
* @description
*/
@Api(value="VStationStoreController",tags={"虚拟站点商店接口"})
@Controller("/vstationstore")
@RequestMapping("/vstationstore")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class VStationStoreController extends BaseController {
// 引入
@Autowired
private VStationStoreService vStationStoreService;
@Autowired
private VUserService vUserService;
@Autowired
private VStationService vStationService;
@Autowired
private VRouteService vRouteService;
@Autowired
private ToolService toolService;
/**
* @author xyy
* @date 2020/1/27 14:47
*/
@ApiOperation(value="通过id获取虚拟站点商店信息", tags={}, notes="")
@RequestMapping(value = "/getVStationStoreInfoById", method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name="id", value="虚拟站点商店id", dataType="int", paramType = "query", example="0")
})
@ResponseBody
public CommonReturnType getVStationStoreInfoById(@ApiParam(name="id", value = "虚拟站点商店id", required = true) int id) throws BusinessException {
VStationStore vStationStore = vStationStoreService.getVStationStoreInfoById(id);
if (vStationStore == null) throw new BusinessException(EnumBusinessError.VSTATIONSTORE_NOT_EXIST);
return CommonReturnType.create(vStationStore);
}
/**
* @author xyy
* @date 2020/1/27 14:55
*/
@ApiOperation(value="通过id获取虚拟站点商店类型信息", tags={}, notes="")
@RequestMapping(value = "/getVStationStoreTypeInfoById", method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name="id", value="虚拟站点商店类型id", dataType="int", paramType = "query", example="0")
})
@ResponseBody
public CommonReturnType getVStationStoreTypeInfoById(@ApiParam(name="id", value = "虚拟站点商店类型id", required = true) int id) throws BusinessException {
VStationStoreType vStationStoreType = vStationStoreService.getVStationStoreTypeInfoById(id);
if (vStationStoreType == null) throw new BusinessException(EnumBusinessError.VSTATIONSTORETYPE_NOT_EXIST);
return CommonReturnType.create(vStationStoreType);
}
/**
* @author xyy
* @date 2020/1/27 14:55
*/
@ApiOperation(value="获取全部虚拟站点商店类型信息", tags={}, notes="")
@RequestMapping(value = "/listAllVStationStoreTypeInfo", method = RequestMethod.GET)
@ResponseBody
public CommonReturnType listAllVStationStoreTypeInfo() throws BusinessException {
List<VStationStoreType> vStationStoreTypes = vStationStoreService.listAllVStationStoreTypeInfo();
return CommonReturnType.create(vStationStoreTypes);
}
/**
* @author xyy
* @date 2020/1/27 14:55
*/
@ApiOperation(value="建造一个店铺", tags={}, notes="商铺种类中:1表示甜品店,2表示快餐店,3表示服装店,4表示纪念品店")
@RequestMapping(value = "/postToBuildAStore", method = RequestMethod.POST)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam(name="id", value="用户id", dataType="int", paramType = "query", example=""),
@ApiImplicitParam(name="stationId", value="虚拟站点id", dataType="int", paramType = "query", example=""),
@ApiImplicitParam(name="storeType", value="商铺种类", dataType="int", paramType = "query", example=""),
@ApiImplicitParam(name="position", value="商铺位置", dataType="int", paramType = "query", example="")
})
public CommonReturnType postToBuildAStore(@ApiParam(name="id", value = "用户id", required = true) int id,
@ApiParam(name="stationId", value = "虚拟站点id", required = true) int stationId,
@ApiParam(name="storeType", value = "商铺种类", required = true) int storeType,
@ApiParam(name="position", value = "商铺位置", required = true) int position
) throws BusinessException {
// 通过商铺种类获取商铺种类详细信息
VStationStoreType vStationStoreType = vStationStoreService.getVStationStoreTypeInfoById(storeType);
String detail = vStationStoreType.getDetail();
JSONArray detailArray = JSONArray.parseArray(detail);
JSONObject detailObject = (JSONObject)detailArray.get(0);
int unlockedIn = (Integer)detailObject.get("unlockedIn");
int cost = (Integer)detailObject.get("cost");
float profit = Float.parseFloat(detailObject.get("profit").toString());
int maxProfit = (Integer)detailObject.get("maxProfit");
long upExp = Long.parseLong(detailObject.get("upExp").toString());
int unCrowdedness = (Integer)detailObject.get("unCrowdedness");
int safety = (Integer)detailObject.get("safety");
int tidy = (Integer)detailObject.get("tidy");
int worker = (Integer)detailObject.get("worker");
int visitor = (Integer)detailObject.get("visitor");
long building_time = Long.parseLong(detailObject.get("building_time").toString());
String picUrl = (String)detailObject.get("picUrl");
// 验证当前账户金钱是否充足
VUser vUser = vUserService.getVUserInfoById(id);
Long money = vUser.getMoney();
if (cost > money) {
throw new BusinessException(EnumBusinessError.USER_NOT_ENOUGH_MONEY);
}
// 验证当前账户小工是否充足
int availableWorkers = vUser.getAvailableWorkers();
if (availableWorkers < worker) {
throw new BusinessException(EnumBusinessError.USER_NOT_ENOUGH_WORKER);
}
// 获取当前地铁站信息
VStation vStation = vStationService.getVStationInfoById(stationId);
vStation.setSatisfaction(vStation.getSecurity() + safety);
vStation.setUncrowedness(vStation.getUncrowedness() + unCrowdedness);
vStation.setCleaness(vStation.getCleaness() + tidy);
vStation.setSatisfaction((vStation.getSecurity() + vStation.getUncrowedness() + vStation.getCleaness()) / 3);
vStation.setVisitorFlowrate(vStation.getVisitorFlowrate() + visitor);
// station信息写入数据库
vStationService.updateVStationInfo(vStation);
// store信息写入数据库
VStationStore vStationStore = new VStationStore();
vStationStore.setLevel(1);
vStationStore.setPosition(position);
vStationStore.setType(storeType);
vStationStore.setStatus(0);
vStationStore.setVstationId(stationId);
vStationStore.setRemainTime(building_time);
vStationStore.setUrl(picUrl);
vStationStoreService.postAStore(vStationStore);
// 根据userId获取全部地铁站信息
List<VRoute> vRoutes = vRouteService.getVRoutesInfoByUserId(id);
ArrayList<VRouteStationDTO> vRouteStationDTOS = new ArrayList<>();
if (vRoutes == null) {
return CommonReturnType.create(null);
}
for (int i = 0; i < vRoutes.size(); i ++) {
String stationsStr = vRoutes.get(i).getVstationIds();
int routeId = vRoutes.get(i).getId();
String routeName = vRoutes.get(i).getName();
String[] stationIds = stationsStr.split(",");
for (int j = 0; j < stationIds.length; j ++) {
VRouteStationDTO vRouteStationDTO = new VRouteStationDTO();
int stationIdId = Integer.parseInt(stationIds[j]);
VStation vStationInstance = vStationService.getVStationInfoById(stationIdId);
String stationName = vStationInstance.getName();
vRouteStationDTO.setUserId(id);
vRouteStationDTO.setRouteId(routeId);
vRouteStationDTO.setRouteName(routeName);
vRouteStationDTO.setRouteStationId(stationId);
vRouteStationDTO.setRouteStationName(stationName);
vRouteStationDTOS.add(vRouteStationDTO);
}
}
// 计算用户的总指数
int cleanSum = 0;
int safeSum = 0;
int uncrowdedSum = 0;
for (int i = 0; i < vRouteStationDTOS.size(); i ++) {
int aStationId = vRouteStationDTOS.get(i).getRouteStationId();
VStation vStationInstance = vStationService.getVStationInfoById(aStationId);
cleanSum = cleanSum + vStationInstance.getCleaness();
safeSum = safeSum + vStationInstance.getSecurity();
uncrowdedSum = uncrowdedSum + vStationInstance.getUncrowedness();
}
cleanSum = cleanSum / vRouteStationDTOS.size();
safeSum = safeSum / vRouteStationDTOS.size();
uncrowdedSum = uncrowdedSum / vRouteStationDTOS.size();
int satisfiyed = (cleanSum + safeSum + uncrowdedSum) / 3;
// 更新用户信息
vUser.setCleaness(cleanSum);
vUser.setSecurity(safeSum);
vUser.setUncrowedness(uncrowdedSum);
vUser.setSatisfactionDegree(satisfiyed);
vUser.setAvailableWorkers(vUser.getWorkers() - worker);
vUser.setExp(vUser.getExp() + upExp);
vUser.setMoney(vUser.getMoney() - cost);
vUser.setVisitorFlowrate(vUser.getVisitorFlowrate() + visitor);
// 判断是否升级了
int isUpLevel = 0;
ExpAndLevelDTO expAndLevelDTO = toolService.calculateExpAndLevel(vUser.getExp());
if (expAndLevelDTO.getLevel() != vUser.getLevel()) {
vUser.setLevel(expAndLevelDTO.getLevel());
isUpLevel = 1;
}
// 把更新后的用户信息写入数据库
vUserService.updateUserInfo(vUser);
// 构造返回对象
JSONObject object = new JSONObject();
object.put("newStore", vStationStore);
object.put("isUpLevel", isUpLevel);
object.put("newUser", vUser);
object.put("isSurprise", 0);
object.put("levelDetail", expAndLevelDTO);
object.put("storeTypeDetail", detailObject);
// 开始计时
int storeId = vStationStore.getId();
toolService.xyyTimer(building_time, storeId, worker, id, vStationStoreService); //创建线程任务时,直接将所需依赖注入的bean携带进子线程中
return CommonReturnType.create(object);
}
}
| true
|
c47a2461f74f6260f8a7ffb300004926bba6b6c5
|
Java
|
martaKlachko/EpamLessons
|
/lesson6/coffeePoint/src/Entity/Order.java
|
UTF-8
| 1,549
| 3.0625
| 3
|
[] |
no_license
|
package Entity;
import Entity.Customer;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
/**
* Created by User on 20.01.2018.
*/
public class Order {
private Customer customer;
private LocalDateTime time;
private Map<Product, Integer> products;
private double sum;
public Order(Customer customer, Map<Product, Integer> products) {
this.customer = customer;
this.time = LocalDateTime.now();
this.products = products;
double sum = 0;
for (Map.Entry entry : products.entrySet()) {
Product product = (Product) entry.getKey();
int quantity = (Integer) entry.getValue();
sum += product.getPrice() * quantity;
}
this.sum = sum;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public Map<Product, Integer> getProducts() {
return products;
}
public void setProducts(Map<Product, Integer> products) {
this.products = products;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public Order() {
}
public void add(Product product, int quantity) {
products.put(product, quantity);
sum += product.getPrice();
}
}
| true
|
3240729c446a42a0a2c9af808122f2a73a0ca8a0
|
Java
|
sfnelson/blog
|
/client/src/main/java/org/sfnelson/blog/server/service/TaskService.java
|
UTF-8
| 311
| 1.953125
| 2
|
[] |
no_license
|
package org.sfnelson.blog.server.service;
import java.util.List;
import org.sfnelson.blog.server.domain.Task;
/**
* Author: Stephen Nelson <stephen@sfnelson.org>
* Date: 31/10/11
*/
public interface TaskService {
List<Task> getCurrentTasks(int start, int limit);
void createTask(Task task);
void updateTask(Task task);
}
| true
|
15ac3a726fa81d12dfaf8c9b61cebb7c185e5102
|
Java
|
camel-man-ims/algorithm-collection
|
/src/문제집/프로그래머스/카카오기출/카카오2021/숫자_문자열과_영단어/Main.java
|
UTF-8
| 1,282
| 3.453125
| 3
|
[] |
no_license
|
package 문제집.프로그래머스.카카오기출.카카오2021.숫자_문자열과_영단어;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
sol.solution("2three45sixseven");
}
static class Solution{
static Map<String,Integer> map;
static String[] numbers = {"zero","one","two","three","four","five","six","seven","eight","nine"};
public int solution(String s){
map = new HashMap<>();
for(int i=0;i<10;i++){
map.put(numbers[i],i);
}
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for(int i=0;i<s.length();i++){
char current = s.charAt(i);
if(Character.isAlphabetic(current)){
temp.append(current);
if(map.containsKey(temp.toString())){
sb.append(map.get(temp.toString()));
temp.setLength(0);
}
}else{
sb.append(current);
}
}
return Integer.parseInt(sb.toString());
}
}
}
| true
|
979e2724ab9b41b192dc53de60a0e4c801854911
|
Java
|
jibopeng/cashloan-product-africa-web-app
|
/cashloan-cl/src/main/java/com/ajaya/cashloan/cl/mapper/UserMessagesMapper.java
|
UTF-8
| 4,834
| 2.21875
| 2
|
[] |
no_license
|
package com.ajaya.cashloan.cl.mapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.ajaya.cashloan.cl.domain.UserMessages;
import com.ajaya.cashloan.cl.model.UserMessagesModel;
import org.apache.ibatis.annotations.Param;
import com.ajaya.cashloan.core.common.mapper.BaseMapper;
import com.ajaya.cashloan.core.common.mapper.RDBatisDao;
/**
* 用户资料--联系人Dao
*
* @author yanzhqiiang
* @since 2020-02-27 11:54:57
*/
@RDBatisDao
public interface UserMessagesMapper extends BaseMapper<UserMessages, Long> {
/**
* 根据表名查询表数量
*
* @param tableName 表名称
* @return 返回表名数量
*/
int countTable(String tableName);
/**
* 创建表名称
*
* @param tableName 表名称
*/
void createTable(@Param("tableName") String tableName);
/**
* 删除该表中的数据
*
* @param tableName 表名称
* @param userId 用户id
*/
void deleteShardByUserId(@Param("tableName") String tableName, @Param("userId") Long userId);
/**
* (分表)新增
*
* @param tableName 表名
* @param userMessages 短信信息
* @return 更改数据库条数
*/
int saveShard(@Param("tableName") String tableName, @Param("item") UserMessages userMessages);
/**
* 根据参数(分表)查询
*
* @param tableName 表名
* @param params 参数
* @return
*/
List<UserMessages> listShardSelective(
@Param("tableName") String tableName,
@Param("params") Map<String, Object> params);
ArrayList<Long> findUserIdByuPhone(String phone);
/**
* 通过用户ID查询未绑定BorrowId的短信数据
*
* @param tableName
* @param userId
* @return
*/
List<UserMessages> findListNoBorrowidByUserid(@Param("tableName") String tableName, @Param("userId") Long userId);
/**
* 通过ID更新分表更新短信数据
*
* @param tableName
* @param userMessages
*/
void updateShard(@Param("tableName") String tableName, @Param("item") UserMessages userMessages);
/**
* 根据订单号分表查询用户短信原始数据
*
* @param tableName
* @param borrowId
* @return
*/
List<UserMessages> listShardByBorrowid(@Param("tableName") String tableName, @Param("borrowId") Long borrowId);
/**
* 分表查询,根据用户ID查询数据最近一次创建时间
*
* @param tableName
* @param userId
* @return
*/
Date findMaxCreatetimeByUserid(@Param("tableName") String tableName, @Param("userId") Long userId);
/**
* 分表查询,根据用户ID和最近一次创建时间查询数据
*
* @param tableName
* @param userId
* @param maxCreatetime
* @return
*/
List<UserMessages> findListByUseridAndCreatetime(@Param("tableName") String tableName, @Param("userId") Long userId, @Param("maxCreatetime") Date maxCreatetime);
/**
* top20短信记录
*
* @param tableName
* @param paramMap
* @return
*/
List<Map<String, Object>> listShardSelectiveTop20(@Param("tableName") String tableName, @Param("params") Map<String, Object> paramMap);
/**
* top20短信记录
*
* @param tableName
* @param paramMap
* @return
*/
List<Map<String, Object>> findListByUseridAndCreatetimeTop20(@Param("tableName") String tableName, @Param("userId") long userId, @Param("maxCreatetime") Date maxCreatetime);
/**
* top20短信记录
*
* @param tableName
* @param paramMap
* @return
*/
List<Map<String, Object>> listShardByBorrowidTop20(@Param("tableName") String tableNameMsg, @Param("borrowId") Long borrowId);
/**
* 通过ID批量更新分表更新短信数据
*
* @param tableName
* @param borrowId
* @param updateTime
* @param ids
*/
void updateByIdsShard(@Param("tableName") String tableName, @Param("borrowId") Long borrowId, @Param("updateTime") Date updateTime, @Param("ids") List<Long> ids);
/**
* 根据borrowId找找用户的messges原始 数据
*
* @param borrowId 订单id
* @param tableName 分表名称
* @return List<UserMessagesModel>
*/
List<UserMessagesModel> selectMessagesListByBorrowIdShard(@Param("borrowId") Long borrowId, @Param("tableName") String tableName);
Long selectDataMaxBorrowIdBefore(@Param("userId")Long userId, @Param("borrowId") Long borrowId, @Param("tableName") String tableName);
/**
* 获取短信
* @param tableName
* @param userId
* @return
*/
Long findMaxBorrowidByUserid(@Param("tableName")String tableNameMsg, @Param("userId")Long userId);
}
| true
|
9b90750067287bcbbe21e9ff418bb30c4e69dfbf
|
Java
|
Valzavator/SlidingPuzzle
|
/src/main/java/game/model/SettingsModel.java
|
UTF-8
| 3,830
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package game.model;
import game.enumeration.BoardType;
import game.enumeration.Difficulty;
import game.helpers.Player;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
@XmlRootElement(name = "settings")
public class SettingsModel extends Subject {
private static SettingsModel settingsModel;
private final static String FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/settings/settings.xml";
private SettingsModel() {
loadDefaultSettings();
}
public static SettingsModel getInstance() {
if (settingsModel == null)
if (!loadFromFile())
settingsModel = new SettingsModel();
return settingsModel;
}
private Difficulty difficulty;
private BoardType boardType;
private boolean highlightButtons;
private boolean multiSwitch;
private boolean hardmode;
private boolean playSounds;
private void loadDefaultSettings() {
difficulty = Difficulty.Easy;
boardType = BoardType.ImageBoard;
highlightButtons = true;
multiSwitch = false;
}
public Difficulty getDifficulty() {
return difficulty;
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
}
public BoardType getBoardType() {
return boardType;
}
public void setBoardType(BoardType boardType) {
this.boardType = boardType;
}
public boolean getHighlightButtons() {
return highlightButtons;
}
@XmlElement
public void setHighlightButtons(boolean highlightButtons) {
this.highlightButtons = highlightButtons;
}
public boolean getMultiSwitch() {
return multiSwitch;
}
@XmlElement
public void setMultiSwitch(boolean multiSwitch) {
this.multiSwitch = multiSwitch;
}
@XmlElement
public void setPlaySounds(boolean playSounds) {
this.playSounds = playSounds;
Player.setPlaySound(playSounds);
}
public boolean getPlaySounds() {
return playSounds;
}
@XmlElement
public void setHardmode(boolean hardmode) {
this.hardmode = hardmode;
}
public boolean getHardmode() {
return hardmode;
}
public void saveToFile() {
try {
FileWriter fileWriter = new FileWriter(
FILE_PATH,
false
);
JAXBContext jaxbContext = JAXBContext.newInstance(SettingsModel.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(this, fileWriter);
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
}
private static boolean loadFromFile() {
try {
File file = new File(FILE_PATH);
JAXBContext jaxbContext = JAXBContext.newInstance(SettingsModel.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
settingsModel = ((SettingsModel) jaxbUnmarshaller.unmarshal(file));
checkSettings();
return true;
} catch (JAXBException e) {
e.printStackTrace();
return false;
}
}
private static void checkSettings() {
if (settingsModel.boardType == null)
settingsModel.boardType = BoardType.TextBoard;
if (settingsModel.difficulty == null)
settingsModel.difficulty = Difficulty.Easy;
}
}
| true
|
09906c063f0834b8630f5fbd1a6dd031b6853c3d
|
Java
|
wonwoo/spring-social-daum
|
/src/main/java/org/springframework/social/daum/api/DaumBoardSearch.java
|
UTF-8
| 1,180
| 2.25
| 2
|
[] |
no_license
|
package org.springframework.social.daum.api;
public class DaumBoardSearch {
private String pubDate;
private String author;
private String title;
private String description;
private String link;
private String keyword;
private String comment;
public String getPubDate() {
return pubDate;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getLink() {
return link;
}
public String getKeyword() {
return keyword;
}
public String getComment() {
return comment;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DaumBoardSearch [pubDate=");
builder.append(pubDate);
builder.append(", author=");
builder.append(author);
builder.append(", title=");
builder.append(title);
builder.append(", description=");
builder.append(description);
builder.append(", link=");
builder.append(link);
builder.append(", keyword=");
builder.append(keyword);
builder.append(", comment=");
builder.append(comment);
builder.append("]");
return builder.toString();
}
}
| true
|
88338025082eb62cb3a19d7e1560fcc7da16e0d1
|
Java
|
adamtache/cell_society
|
/src/Model/HexagonCell.java
|
UTF-8
| 2,750
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
package src.Model;
public class HexagonCell extends Cell{
public HexagonCell(double centerX, double centerY, int state, double sideLength, Grid myGrid, String edgeType) {
super(centerX, centerY, state, sideLength, 6, myGrid, edgeType);
setHeight();
}
public HexagonCell(double sideLen, Grid grid, String edgeType) {
super(0,0,0,sideLen,6,grid,edgeType);
setHeight();
}
public double getWidth(){
return getSideLength() * Math.sqrt(2);
}
public void setHeight(){
super.setHeight(2*getInnerTriangleHeight() + getSideLength());
}
public double[] shiftByHorizontalRowGap(double[] newXPoints){
for(int x=0; x<newXPoints.length; x++){
newXPoints[x] += getOddRowHorizontalGap();
}
return newXPoints;
}
public double[] shiftByVerticalRowGap(double[] newYPoints, int col){
for(int x=0; x<newYPoints.length; x++){
newYPoints[x] += col*getOddRowVerticalGap();
}
return newYPoints;
}
public double getOddRowHorizontalGap(){
return Math.sqrt(2)/2*getSideLength();
}
public double getOddRowVerticalGap(){
return -1*getInnerTriangleHeight();
}
public double getInnerTriangleHeight(){
return Math.sqrt(2)/2*getSideLength();
}
public double XaddToNewRow(int row, int col) {
int mod = row%2;
double[] newXPoints = new double[6];
newXPoints[0] = getWidth()/2;
newXPoints[1] = getWidth();
newXPoints[2] = getWidth();
newXPoints[3] = getWidth()/2;
newXPoints[4] = 0;
newXPoints[5] = 0;
if(mod == 1)
newXPoints = shiftByHorizontalRowGap(newXPoints);
setXPoints(newXPoints);
return getAverageValue(newXPoints);
}
public double YaddToNewRow(int row, int col){
double[] newYPoints = new double[6];
newYPoints[0] = row*getHeight();
newYPoints[1] = row*getHeight() + getInnerTriangleHeight();
newYPoints[2] = row*getHeight() + getInnerTriangleHeight() + getSideLength();
newYPoints[3] = row*getHeight() + getInnerTriangleHeight()*2 + getSideLength();
newYPoints[4] = row*getHeight() + getInnerTriangleHeight() + getSideLength();
newYPoints[5] = row*getHeight() + getInnerTriangleHeight();
if(row!=0)
newYPoints = shiftByVerticalRowGap(newYPoints, row
);
setYPoints(newYPoints);
return getAverageValue(newYPoints);
}
public double XaddToExistingRow(int row, int col){
double[] newXPoints = new double[6];
double[] prevPoints = getGrid().getGridMap().get(row).get(col-1).getXPoints();
for(int x=0; x<prevPoints.length; x++){
newXPoints[x] = prevPoints[x] + getWidth();
}
setXPoints(newXPoints);
return getAverageValue(newXPoints);
}
public double YaddToExistingRow(int row, int col){
double[] prevPoints = getGrid().getGridMap().get(row).get(col-1).getYPoints();
setYPoints(prevPoints);
return getAverageValue(prevPoints);
}
}
| true
|
897cb235ce5ab0a4c8572c3f0dd02d52286afe6e
|
Java
|
zjwab118/games
|
/code/service/wm_code/src/main/java/com/wm/boot/proxy/vo/ClassVo.java
|
UTF-8
| 205
| 1.554688
| 2
|
[] |
no_license
|
package com.wm.boot.proxy.vo;
import lombok.Data;
/**
* @author wilson
* @title ClassVo
* @description 类信息
* @date 2021.02.06 08:11
*/
@Data
public class ClassVo {
private String url;
}
| true
|
1e7c13e9c0ea5fb342d7ef9733d78bed5c176a77
|
Java
|
ruicao93/oxp-protocol
|
/src/main/java/org/onosproject/oxp/protocol/OXPFactories.java
|
UTF-8
| 1,492
| 2.421875
| 2
|
[] |
no_license
|
package org.onosproject.oxp.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.oxp.exceptions.OXPParseError;
import org.onosproject.oxp.protocol.ver10.OXPFactoryVer10;
import org.onosproject.oxp.types.U8;
/**
* Created by cr on 16-4-9.
*/
public final class OXPFactories {
private static final GenericReader GENERIC_READER = new GenericReader();
private OXPFactories() {
}
public static OXPFactory getFactory(OXPVersion version) {
switch (version) {
case OXP_10:
return OXPFactoryVer10.INSTANCE;
default:
throw new IllegalArgumentException("Unknown version: " + version);
}
}
private static class GenericReader implements OXPMessageReader<OXPMessage> {
public OXPMessage readFrom(ChannelBuffer bb) throws OXPParseError {
if (!bb.readable()) {
return null;
}
short wireVersion = U8.f(bb.getByte(bb.readerIndex()));
OXPFactory factory;
switch (wireVersion) {
case 1:
factory = OXPFactoryVer10.INSTANCE;
break;
default:
throw new IllegalArgumentException("Unknown wire version: " + wireVersion);
}
return factory.getReader().readFrom(bb);
}
}
public static OXPMessageReader<OXPMessage> getGenericReader() {
return GENERIC_READER;
}
}
| true
|
f642784b951396b1f1b3e44e212d8711c344e442
|
Java
|
dangnghia2101/assignmentFinal
|
/app/src/main/java/com/example/myapplication/DAO/LoaiCarDAO.java
|
UTF-8
| 2,163
| 2.484375
| 2
|
[] |
no_license
|
package com.example.myapplication.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.myapplication.Database.Database;
import com.example.myapplication.Model.Car;
import com.example.myapplication.Model.LoaiCar;
import com.example.myapplication.Name.AppConstant;
import static com.example.myapplication.Name.AppConstant.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class LoaiCarDAO implements ILoaiCarDAO{
Database database;
SQLiteDatabase db;
public LoaiCarDAO(Context context) {
database = new Database(context);
db = database.getWritableDatabase();
}
@Override
public List<LoaiCar> get() {
List<LoaiCar> list = new ArrayList<>();
SQLiteDatabase db=database.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM "+ TABLE_LOAICAR +"",null);
while (cursor.moveToNext()){
String NameLoaiCar=cursor.getString(0);
String DetailLoaiCar=cursor.getString(1);
list.add(new LoaiCar(NameLoaiCar, DetailLoaiCar));
}
cursor.close();
return list;
}
@Override
public void insert(LoaiCar car) {
db = database.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_LOAICAR , car.getNameCar());
values.put(DETAIL_LOAICAR , car.getDetailCar());
db.insert(TABLE_LOAICAR, null,values);
}
@Override
public void update(LoaiCar car) {
db = database.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_LOAICAR , car.getNameCar());
values.put(DETAIL_LOAICAR, car.getDetailCar());
db.update(TABLE_LOAICAR, values, NAME_LOAICAR + " = ?", new String[]{car.getNameCar()});
}
@Override
public void delete(String Id_LoaiCar) {
db= database.getReadableDatabase();
String[] params = new String[]{Id_LoaiCar};
db.delete(TABLE_LOAICAR, ""+NAME_LOAICAR+" = ?", params);
}
}
| true
|
27d1800f3bc3c66439b93d914d46cbee59eacecb
|
Java
|
beiduofen2011/selfStu
|
/aqsStu/src/main/java/com/fen/dou/aqsStu/hashMapTest/TestUUid.java
|
UTF-8
| 1,016
| 3.015625
| 3
|
[] |
no_license
|
package com.fen.dou.aqsStu.hashMapTest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class TestUUid {
public static void main(String[] args) {
HashMap<Integer, Set<String>> map = new HashMap<Integer, Set<String>>();
for(int i=0;i<10000;i++){
UUID str = UUID.randomUUID();
int hash = str.toString().hashCode() ^ (str.toString().hashCode() >>> 16);
int index = hash & 15;
if(map.get(index) == null){
Set<String> strings = new HashSet<>();
strings.add(str.toString());
map.put(index,strings);
}else{
map.get(index).add(str.toString());
}
}
map.forEach((k,v)->{
if(v.size()>7){
System.out.println(k+","+v.size()+"|||");
for(String sr : v){
System.out.print(sr+" ,");
}
}
});
}
}
| true
|
bbbffb8a8f9edf39eb76e24b71a0a58576487a7c
|
Java
|
LinaMalinaMeow/Lab7
|
/common/src/main/java/object/VehicleDisplayerImpl.java
|
UTF-8
| 957
| 3.109375
| 3
|
[] |
no_license
|
package object;
import java.text.SimpleDateFormat;
public class VehicleDisplayerImpl implements VehicleDisplayer{
@Override
public String displayVehicle(Vehicle vehicle) {
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
return "\n\tID: " + vehicle.getId() +
"\n\tИмя: " + vehicle.getName() +
"\n\tКоординаты: (" + vehicle.getCoordinates().getX() + ", " + vehicle.getCoordinates().getY() +
")\n\tМощность двигателя: " + vehicle.getEnginePower() +
"\n\tКолёс: " + vehicle.getNumberOfWheels() +
"\n\tПроехано: " + vehicle.getDistanceTravelled() +
"\n\tТип топлива: " + vehicle.getFuelTypeString() +
"\n\tВремя создания: " + format.format(vehicle.getCreationDate()) +
"\n\tВладелец: " + vehicle.getUsername();
}
}
| true
|
91527d2f8a41e803e68d37b3afb7ef8578b7a2e8
|
Java
|
wuyamei95/excelload
|
/src/main/java/com/example/demo/pojo/bo/class_teacher.java
|
UTF-8
| 208
| 1.71875
| 2
|
[] |
no_license
|
package com.example.demo.pojo.bo;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class class_teacher {
@NotNull
int teacher_id;
@NotNull
String class_name;
}
| true
|
adf303774f68e7af4cc3b3a66ea705b11de5c820
|
Java
|
paragparalikar/thyng2
|
/parent/gateway-parent/gateway/src/main/java/com/thyng/gateway/service/BootstrapService.java
|
UTF-8
| 6,458
| 2.09375
| 2
|
[] |
no_license
|
package com.thyng.gateway.service;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import com.thyng.gateway.Constant;
import com.thyng.gateway.EventBus;
import com.thyng.gateway.client.EventPublisherClient;
import com.thyng.gateway.model.Context;
import com.thyng.gateway.provider.persistence.ConfigurationStore;
import com.thyng.gateway.provider.persistence.FilePersistenceProvider;
import com.thyng.gateway.provider.persistence.PersistenceProvider;
import com.thyng.gateway.service.health.HeartbeatService;
import com.thyng.gateway.service.health.StatusMonitoringService;
import com.thyng.model.RegistrationRequest;
import com.thyng.model.RegistrationResponse;
import com.thyng.model.dto.GatewayConfigurationDTO;
import com.thyng.netty.Client;
import com.thyng.netty.OioClient;
import com.thyng.util.Lambda;
import com.thyng.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BootstrapService extends CompositeService {
private Context context;
public BootstrapService() throws Exception {
initShutdownHook();
final PropertyLoader propertyLoader = new PropertyLoader();
propertyLoader.loadProperties();
context = buildContext();
add(new HeartbeatService(context));
add(new StatusMonitoringService(context));
add(new GatewayNettyServerService(context));
add(new MetricsDispatchService(context));
ServiceLoader.load(ServiceBuilder.class).forEach(builder -> add(builder.newInstance(context)));
}
@Override
public void stop() throws Exception {
super.stop();
stopExecutor();
}
private void stopExecutor(){
if(null != context){
try{
context.getExecutor().shutdown();
context.getExecutor().awaitTermination(3, TimeUnit.SECONDS);
}catch(Exception e){
log.error("Failed to stop executor gracefully", e);
}
}
}
private void initShutdownHook(){
final Thread thread = new Thread("Gateway-Shutdown-Hook") {
@Override
public void run() {
try {
BootstrapService.this.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Runtime.getRuntime().addShutdownHook(thread);
}
private Context buildContext() throws Exception{
final ThreadFactory threadFactory = runnable -> new Thread(runnable, "Gateway-executor-thread");
final ScheduledExecutorService executor = Executors.newScheduledThreadPool
(Runtime.getRuntime().availableProcessors(), threadFactory);
final EventBus eventBus = new EventBus(executor);
final PersistenceProvider persistenceProvider = new FilePersistenceProvider();
final Client rawClient = new OioClient(Integer.getInteger("thyng.server.port", 9090),
System.getProperty("thyng.server.host", "localhost"));
final Client client = new EventPublisherClient(rawClient, eventBus);
final GatewayConfigurationDTO details = getDetails(client, persistenceProvider.getConfigurationStore());
return Context.builder()
.eventBus(eventBus)
.executor(executor)
.details(details)
.client(client)
.persistenceProvider(persistenceProvider)
.build();
}
private GatewayConfigurationDTO getDetails(final Client client,
final ConfigurationStore configurationStore) throws Exception{
try{
return configurationStore.load().orElseGet(Lambda.uncheck(() -> {
log.info("Gateway details not available locally");
return configurationStore.save(fetch(client));
}));
}catch(Exception e){
log.error("Could not load details from persistence provider", e);
return configurationStore.save(fetch(client));
}
}
private GatewayConfigurationDTO fetch(final Client client) {
log.info("Fetching gateway details from Thyng server");
final RegistrationResponse response = client.execute(RegistrationRequest.builder()
.gatewayId(Long.getLong("thyng.gateway.id", null))
.host(System.getProperty("thyng.gateway.server.host", null))
.port(Integer.getInteger("thyng.gateway.server.port", null))
.build());
return response.getGatewayConfigurationDTO();
}
}
@Slf4j
class PropertyLoader{
void loadProperties() throws IOException {
final Properties properties = new Properties();
loadDefaultProperties(properties);
loadCustomProperties(properties);
loadSystemProperties(properties);
resolveSystemProperties(properties);
replaceSystemProperties(properties);
}
private void replaceSystemProperties(final Properties properties) {
System.getProperties().putAll(properties);
}
private void resolveSystemProperties(final Properties properties) {
final String prefix = "system:";
log.debug("Resolving properties with prefix \""+prefix+"\"");
properties.stringPropertyNames().forEach(key -> {
final String value = properties.getProperty(key);
if(StringUtil.hasText(value) && value.startsWith(prefix)) {
final String envKey = value.substring(prefix.length());
final String envValue = System.getProperty(envKey, System.getenv(envKey));
log.debug("Resolving " + key + " using " + envKey + " as " + envValue);
properties.put(key, envValue);
}
});
}
private void loadSystemProperties(final Properties properties){
log.debug("Loading properties - system");
properties.putAll(System.getProperties());
}
private void loadDefaultProperties(final Properties properties) throws IOException{
log.debug("Loading properties - default");
properties.put(Constant.KEY_STORAGE, System.getProperty("user.home")
+ File.separator + "thyng" + File.separator);
final String location = "/Thyng.properties";
try(final InputStream in = BootstrapService.class.getResourceAsStream(location)){
properties.load(in);
}
}
private void loadCustomProperties(final Properties properties) throws IOException{
log.debug("Loading properties - custom");
final String location = System.getProperty("thyng.gateway.configuration.path");
if(StringUtil.hasText(location)){
try(final InputStream in = BootstrapService.class.getResourceAsStream(location)){
properties.load(in);
log.info("Properties loaded from "+location);
}
}
}
}
| true
|
545681bafa552b2d8e50d6fed7b2911b1b2f35ca
|
Java
|
JasonHans316/My_Animal_Haven
|
/app/src/main/java/com/animalhaven/hansportable/myanimalhaven/DomainInterfaces/IUser.java
|
UTF-8
| 566
| 1.953125
| 2
|
[] |
no_license
|
package com.animalhaven.hansportable.myanimalhaven.DomainInterfaces;
import com.animalhaven.hansportable.myanimalhaven.Domain.Adoption;
import com.animalhaven.hansportable.myanimalhaven.Domain.Schedule;
import com.animalhaven.hansportable.myanimalhaven.Domain.Donation;
import java.util.List;
/**
* Created by Admin on 2016/04/03.
*/
public interface IUser {
Long getUserId();
String getName();
String getSurname();
String getIdNumber();
List<Donation> getDonations();
List<Schedule> getSchedules();
List<Adoption> getAdoptions();
}
| true
|
df777e4f177154d6d5402f85893b3af08c433ebc
|
Java
|
Neitsch/Networks-Assignment
|
/src/io/Console.java
|
UTF-8
| 422
| 2.828125
| 3
|
[] |
no_license
|
package io;
import java.util.ArrayList;
public class Console {
public enum LOGMODE {
GRAPH, PACKET
}
private static ArrayList<LOGMODE> logmodes;
static {
logmodes = new ArrayList<>();
}
public static void activate(LOGMODE e) {
logmodes.add(e);
}
public static void log(String message, LOGMODE e) {
if (logmodes.contains(e)) System.out.println("[" + System.currentTimeMillis() + "] " + message);
}
}
| true
|
98b326ee738f499a976c97bd6a009a3947e148b8
|
Java
|
wsicong/GraduationProject
|
/src/main/java/com/wsicong/enroll/service/impl/HobbyTypeServiceImpl.java
|
UTF-8
| 4,989
| 2.296875
| 2
|
[] |
no_license
|
package com.wsicong.enroll.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsicong.enroll.dto.HobbyTypeSearchDTO;
import com.wsicong.enroll.mapper.HobbyTypeMapper;
import com.wsicong.enroll.model.HobbyType;
import com.wsicong.enroll.model.User;
import com.wsicong.enroll.service.HobbyTypeService;
import com.wsicong.enroll.util.PageDataResult;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
public class HobbyTypeServiceImpl implements HobbyTypeService {
private static final Logger logger = LoggerFactory.getLogger(HobbyTypeServiceImpl.class);
@Autowired
private HobbyTypeMapper hobbyTypeMapper;
/**
* 分页查询兴趣分类列表
*
* @param page
* @param limit
* @return
*/
@Override
public PageDataResult list(int page, int limit, HobbyTypeSearchDTO hobbyTypeSearch) {
//时间处理
/*if (null != hobbyTypeSearch) {
if (StringUtils.isNotEmpty(hobbyTypeSearch.getInsertTimeStart()) && StringUtils.isEmpty(hobbyTypeSearch.getInsertTimeEnd())) {
hobbyTypeSearch.setInsertTimeEnd(DateUtil.format(new Date()));
} else if (StringUtils.isEmpty(hobbyTypeSearch.getInsertTimeStart()) && StringUtils.isNotEmpty(hobbyTypeSearch.getInsertTimeEnd())) {
hobbyTypeSearch.setInsertTimeStart(DateUtil.format(new Date()));
}
if (StringUtils.isNotEmpty(hobbyTypeSearch.getInsertTimeStart()) && StringUtils.isNotEmpty(hobbyTypeSearch.getInsertTimeEnd())) {
if (hobbyTypeSearch.getInsertTimeEnd().compareTo(hobbyTypeSearch.getInsertTimeStart()) < 0) {
String temp = hobbyTypeSearch.getInsertTimeStart();
hobbyTypeSearch.setInsertTimeStart(hobbyTypeSearch.getInsertTimeEnd());
hobbyTypeSearch.setInsertTimeEnd(temp);
}
}
}*/
PageDataResult result = new PageDataResult();
PageHelper.startPage(page, limit);
List<HobbyType> hobbyTypeList = hobbyTypeMapper.selectHobbyTypeList(hobbyTypeSearch);
//拿到分页查询后的数据
PageInfo<HobbyType> pageInfo = new PageInfo<>(hobbyTypeList);
// 设置获取到的总记录数total:
result.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
result.setList(hobbyTypeList);
return result;
}
/**
* 添加/更新兴趣
*
* @param hobbyType
* @return
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = {RuntimeException.class, Exception.class})
public String setHobbyType(HobbyType hobbyType) {
//获取当前用户
User existUser = (User) SecurityUtils.getSubject().getPrincipal();
//id为不为空时,说明为更新操作,否则为新增操作
if (null != hobbyType.getId()) {
hobbyType.setUpdateTime(new Date());
hobbyType.setUpdateBy(existUser.getId().toString());
hobbyTypeMapper.updateByPrimaryKeySelective(hobbyType);
} else {
HobbyType existHobbyType = this.hobbyTypeMapper.selectByHobbyTypeName(hobbyType.getHobbyTypeName());
System.out.println("+++++++++++++++++++++" + existHobbyType);
if (null != existHobbyType) {
return "该兴趣已存在,不能重复添加";
} else {
hobbyType.setCreateTime(new Date());
hobbyType.setCreateBy(existUser.getId().toString());
hobbyTypeMapper.insert(hobbyType);
}
}
return "ok";
}
/**
* 删除兴趣分类
*
* @param id
* @return
*/
@Override
public String delete(Integer id) {
return hobbyTypeMapper.deleteByPrimaryKey(id) == 1 ? "ok" : "删除失败,请您稍后再试";
}
/**
* 根据id查找兴趣分类
*
* @param id
* @return
*/
@Override
public HobbyType getHobbyType(Integer id) {
return hobbyTypeMapper.selectByPrimaryKey(id);
}
/**
* 设置是否启用兴趣分类
*
* @param id
* @param isEnable
* @return
*/
@Override
public String setEnable(Integer id, Integer isEnable) {
return hobbyTypeMapper.updateEnable(id, isEnable) == 1 ? "ok" : "操作失败,请您稍后再试";
}
@Override
public List<HobbyType> getHobbyTypes() {
return hobbyTypeMapper.selectHobbyTypes();
}
}
| true
|
77b4914f0136cedeb5848cf30ab5ebcf6a19c95d
|
Java
|
wucanwu/jskDynamicProxy
|
/src/test.java
|
UTF-8
| 254
| 2.375
| 2
|
[
"Apache-2.0"
] |
permissive
|
public class test {
public static void main(String[] args) {
MyNumImple myNum = new MyNumImple();
MyNum poxy = (MyNum) new MyNumPoxy().getInstance(myNum);
int a = (Integer)poxy.add(1,2);
System.out.println(a);
}
}
| true
|
bb3a5d93d45f3c5ad4e633d956da1ea9812762eb
|
Java
|
kostikum/time-overseer
|
/app/src/main/java/com/kostikum/timeoverseer/adapters/ProjectListAdapter.java
|
UTF-8
| 2,378
| 2.296875
| 2
|
[] |
no_license
|
package com.kostikum.timeoverseer.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.kostikum.timeoverseer.R;
import com.kostikum.timeoverseer.db.entity.Project;
import com.kostikum.timeoverseer.ui.ProjectCallback;
import java.util.List;
public class ProjectListAdapter extends RecyclerView.Adapter<ProjectListAdapter.ProjectViewHolder> {
private List<Project> projects;
private LayoutInflater inflater;
private ProjectCallback projectCallback;
public ProjectListAdapter(Context context, ProjectCallback callback) {
this.inflater = LayoutInflater.from(context);
this.projectCallback = callback;
}
@NonNull
@Override
public ProjectViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recyclerview_project_item, parent, false);
return new ProjectViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ProjectViewHolder holder, int position) {
final Project project = projects.get(position);
holder.frameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
projectCallback.onClick(project);
}
});
holder.nameTextView.setText(project.getName());
holder.colorTextView.setBackgroundResource(project.getColor());
}
@Override
public int getItemCount() {
return projects != null ? projects.size() : 0;
}
public void setProjectsList(List<Project> list) {
projects = list;
notifyDataSetChanged();
}
static class ProjectViewHolder extends RecyclerView.ViewHolder {
FrameLayout frameLayout;
TextView nameTextView;
TextView colorTextView;
ProjectViewHolder(@NonNull View itemView) {
super(itemView);
frameLayout = itemView.findViewById(R.id.rv_project_item_layout);
nameTextView = itemView.findViewById(R.id.project_name_textview);
colorTextView = itemView.findViewById(R.id.project_color_textview);
}
}
}
| true
|
256807c165feef65e8ecc51b65b046c5f69ed6e3
|
Java
|
Euchigere/simple-plagiarism-checker
|
/src/main/java/com/emmanuelc/plagiarismchecker/domain/dto/RespFile.java
|
UTF-8
| 318
| 1.96875
| 2
|
[] |
no_license
|
package com.emmanuelc.plagiarismchecker.domain.dto;
import com.emmanuelc.plagiarismchecker.domain.models.enumerations.MimeType;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RespFile {
private String name;
private String url;
private MimeType type;
private long size;
}
| true
|
ecbc2b90e31605b1153ca717917ae13692ce2a23
|
Java
|
AfoH328/131
|
/app/src/main/java/com/example/photofreecropofimage/MainActivity.java
|
UTF-8
| 642
| 2.09375
| 2
|
[] |
no_license
|
package com.example.photofreecropofimage;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
}
@Override
protected void onResume(){
super.onResume();
setContentView(new Someview(MainActivity.this));
}
private class Someview extends View {
public Someview(MainActivity mainActivity) {
super();
}
}
}
| true
|
a9de3d10253991a2c28734028f674c3bb352d47f
|
Java
|
vijayasri0805/Demoproject1
|
/src/test/java/com/upgrade/api/ApiTest.java
|
UTF-8
| 1,875
| 2.515625
| 3
|
[] |
no_license
|
package com.upgrade.api;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.testng.annotations.Test;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import junit.framework.Assert;
public class ApiTest {
static Response response = given().
when().
get("https://credapi.credify.tech/api/loanapp/v1/states").
then().extract().response();
static String json = response.getBody().asString();
static JsonPath jsonPath = new JsonPath(json);
static List<HashMap<String,Object>> ret = jsonPath.get("states");
//assertThat().
//body("states.label",hasSize(10));
@Test
public void check_Number_Of_states() {
List<String> jsonResponse = response.jsonPath().getList("states");
Assert.assertEquals(48, jsonResponse.size());
}
@Test
public void check_One_State_Has_min_Age_19()
{
//List<HashMap<String,Object>>ret = jsonPath.get("states");
List<Object> res = new ArrayList<Object>();
for (int i=0;i<ret.size();i++)
{
res.add(i, ret.get(i).get("minAge"));
}
//System.out.println(Collections.frequency(res, 19));
Assert.assertEquals(1, Collections.frequency(res, 19));
Assert.assertEquals("Alabama", ret.get(res.indexOf(19)).get("label"));
}
@Test
public void check_Georgia_is_only_state_with_min_Loan_amount_3005()
{
//List<HashMap<String,Object>>ret = jsonPath.get("states");
List<Object> res = new ArrayList<Object>();
for (int i=0;i<ret.size();i++)
{
res.add(i, ret.get(i).get("minLoanAmount").toString().trim());
}
Assert.assertEquals(1, Collections.frequency(res, "3005.0"));
Assert.assertEquals("Georgia", ret.get(res.indexOf("3005.0")).get("label"));
}
}
| true
|
e59db9fc56ba2d185a74f00c89b063a6ea19d998
|
Java
|
alldatacenter/alldata
|
/dts/inlong/inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/ServiceBaseTest.java
|
UTF-8
| 6,393
| 1.585938
| 2
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-compass",
"BSD-3-Clause"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.inlong.manager.service;
import org.apache.inlong.common.constant.MQType;
import org.apache.inlong.manager.common.enums.FieldType;
import org.apache.inlong.manager.common.enums.GroupStatus;
import org.apache.inlong.manager.pojo.group.InlongGroupInfo;
import org.apache.inlong.manager.pojo.group.none.InlongNoneMqInfo;
import org.apache.inlong.manager.pojo.group.pulsar.InlongPulsarInfo;
import org.apache.inlong.manager.pojo.stream.InlongStreamInfo;
import org.apache.inlong.manager.pojo.stream.InlongStreamRequest;
import org.apache.inlong.manager.pojo.stream.StreamField;
import org.apache.inlong.manager.pojo.user.LoginUserUtils;
import org.apache.inlong.manager.pojo.user.UserInfo;
import org.apache.inlong.manager.service.group.InlongGroupService;
import org.apache.inlong.manager.service.stream.InlongStreamService;
import org.apache.inlong.manager.test.BaseTest;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.List;
/**
* Test class for base test service.
*/
@SpringBootApplication
@SpringBootTest(classes = ServiceBaseTest.class)
public class ServiceBaseTest extends BaseTest {
public static final String GLOBAL_GROUP_ID = "global_group";
public static final String GLOBAL_STREAM_ID = "global_stream";
public static final String GLOBAL_OPERATOR = "admin";
public static final String PUBLIC_TENANT = "public";
public static final String GLOBAL_CLUSTER_NAME = "global_cluster";
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBaseTest.class);
@Autowired
protected InlongGroupService groupService;
@Autowired
protected InlongStreamService streamService;
@BeforeAll
public static void login() {
UserInfo userInfo = new UserInfo();
userInfo.setTenant(PUBLIC_TENANT);
userInfo.setName(GLOBAL_OPERATOR);
LoginUserUtils.setUserLoginInfo(userInfo);
}
@AfterAll
public static void logout() {
LoginUserUtils.removeUserLoginInfo();
}
@Test
public void test() {
LOGGER.info("The test class cannot be empty, otherwise 'No runnable methods exception' will be reported");
}
/**
* Create InlongGroup from the given specified InlongGroupId
*
* @return InlongGroupInfo after saving
*/
public InlongGroupInfo createInlongGroup(String inlongGroupId, String mqType) {
try {
streamService.logicDeleteAll(inlongGroupId, GLOBAL_OPERATOR);
groupService.delete(inlongGroupId, GLOBAL_OPERATOR);
} catch (Exception e) {
// ignore
}
InlongGroupInfo groupInfo;
if (MQType.PULSAR.equals(mqType) || MQType.TDMQ_PULSAR.equals(mqType)) {
groupInfo = new InlongPulsarInfo();
} else if (MQType.TUBEMQ.equals(mqType)) {
groupInfo = new InlongPulsarInfo();
} else {
groupInfo = new InlongNoneMqInfo();
}
groupInfo.setInlongGroupId(inlongGroupId);
groupInfo.setMqType(mqType);
groupInfo.setMqResource("test-queue");
groupInfo.setInCharges(GLOBAL_OPERATOR);
groupService.save(groupInfo.genRequest(), GLOBAL_OPERATOR);
InlongGroupInfo updateGroupInfo = groupService.get(inlongGroupId);
groupService.updateStatus(inlongGroupId, GroupStatus.TO_BE_APPROVAL.getCode(), GLOBAL_OPERATOR);
groupService.updateStatus(inlongGroupId, GroupStatus.APPROVE_PASSED.getCode(), GLOBAL_OPERATOR);
groupService.update(updateGroupInfo.genRequest(), GLOBAL_OPERATOR);
return groupInfo;
}
/**
* Create InlongStream from the given InlongGroupInfo and specified InlongStreamId
*
* @return InlongStreamInfo after saving
*/
public InlongStreamInfo createStreamInfo(InlongGroupInfo groupInfo, String inlongStreamId) {
String inlongGroupId = groupInfo.getInlongGroupId();
// delete first
try {
streamService.delete(inlongGroupId, inlongStreamId, GLOBAL_OPERATOR);
} catch (Exception e) {
// ignore
}
InlongStreamRequest request = new InlongStreamRequest();
request.setInlongGroupId(inlongGroupId);
request.setInlongStreamId(inlongStreamId);
request.setMqResource(inlongStreamId);
request.setDataSeparator(String.valueOf((int) '|'));
request.setDataEncoding("UTF-8");
request.setFieldList(createStreamFields(inlongGroupId, inlongStreamId));
streamService.save(request, GLOBAL_OPERATOR);
return streamService.get(request.getInlongGroupId(), request.getInlongStreamId());
}
/**
* Get StreamField list from the given groupId and streamId
*
* @return list of StreamField
*/
public List<StreamField> createStreamFields(String groupId, String streamId) {
final List<StreamField> streamFields = new ArrayList<>();
StreamField fieldInfo = new StreamField();
fieldInfo.setInlongGroupId(groupId);
fieldInfo.setInlongStreamId(streamId);
fieldInfo.setFieldName("id");
fieldInfo.setFieldType(FieldType.INT.toString());
fieldInfo.setFieldComment("idx");
streamFields.add(fieldInfo);
return streamFields;
}
}
| true
|
98d61ef8ef7fda684dc59d496c64dafed4d11ade
|
Java
|
wangmingle/iyoutianxia
|
/src/test/notes/NotesModel.java
|
UTF-8
| 1,327
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package test.notes;
public class NotesModel {
private Integer rownum;
private String id;
private String name;
private String context;
private String uid;
private String tags;
private Long createdate;
private Integer stype;
private Integer status;
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public NotesModel(){}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public Integer getRownum() {
return rownum;
}
public void setRownum(Integer rownum) {
this.rownum = rownum;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Long getCreatedate() {
return createdate;
}
public void setCreatedate(Long createdate) {
this.createdate = createdate;
}
public Integer getStype() {
return stype;
}
public void setStype(Integer stype) {
this.stype = stype;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
| true
|
62d2f87a0fb2b3ea57b606ab914c43aaf2b8189e
|
Java
|
raidcraft-archiv/rcskills
|
/src/main/java/de/raidcraft/skills/api/exceptions/CharacterException.java
|
UTF-8
| 260
| 2.09375
| 2
|
[] |
no_license
|
package de.raidcraft.skills.api.exceptions;
import de.raidcraft.api.RaidCraftException;
/**
* @author Silthus
*/
public class CharacterException extends RaidCraftException {
public CharacterException(String message) {
super(message);
}
}
| true
|
fcad8b61d5612e4ccd076b5d5ba01c4bacd8926e
|
Java
|
dumbledorebryant/leetcode
|
/leetcode/src/pass/Company/Amazon/OA/k_consistence.java
|
UTF-8
| 1,299
| 3.234375
| 3
|
[] |
no_license
|
package pass.Company.Amazon.OA;
import java.util.HashMap;
import java.util.Map;
public class k_consistence {
public int characterDelete(int[] array, int k) {
if (array == null || array.length == 0 || k > array.length) {
return -1;
}
HashMap<Integer, Integer> map = new HashMap<>();
int start = 0;
int maxCount = 0;
// sliding window
for (int end = 0; end < array.length; end++) {
int count = map.getOrDefault(array[end], 0) + 1;
maxCount = Math.max(maxCount, count);
map.put(array[end], count);
// in the sliding window, max consecutive integer
while (end - start + 1 - maxCount > k) {
int value = map.get(array[start]);
map.put(array[start], value - 1);
start++;
}
}
return maxCount;
}
public static void main(String[] args) throws Exception
{
int[] stocks1 = new int[] {1, -2, 1, 1, 3, 2, 1, -2}; //14
int[] stocks2 = new int[] {7, 5,7,7,1,1,7,7}; //14
int[] stocks3 = new int[] {1,1,2,1,2,1,3,4};
k_consistence kc = new k_consistence();
System.out.println(kc.characterDelete(stocks3, 3));
}
}
| true
|
62ff4cdb841edc42026f1b148d4551bf4318fd4a
|
Java
|
zhoujiaping/jsirenia
|
/src/main/java/org/jsirenia/groovy/GroovyScriptFileRunner.java
|
UTF-8
| 1,319
| 2.671875
| 3
|
[] |
no_license
|
package org.jsirenia.groovy;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.util.ResourceUtils;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
//https://blog.csdn.net/a906998248/article/details/46444967
public class GroovyScriptFileRunner {
private String filepath = "";//目录
private GroovyScriptEngine engine ;
public GroovyScriptFileRunner(String filepath){
try {
this.filepath = ResourceUtils.getFile(filepath).getAbsolutePath();
this.engine = new GroovyScriptEngine(this.filepath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Object run(String scriptName,Map<String,Object> variables){
//groovy代码文件名
Object res;
try {
res = engine.run(scriptName, new Binding(variables));
} catch (Exception e) {
throw new RuntimeException(e);
}
return res;
}
public String getFilepath() {
return filepath;
}
public static void main(String[] args) throws FileNotFoundException{
Map<String, Object> variables = new HashMap<>();
String filename = "classpath:./";
Object res = new GroovyScriptFileRunner(filename).run("groovy/Hello.groovy", variables);
System.out.println(res);
}
}
| true
|
4130b59164050d7c46583e8afb0a4fa93c8d6cde
|
Java
|
l-y-s/Bracketeer
|
/app/src/main/java/com/csci490/bracketeer/SwissRoundPairings.java
|
UTF-8
| 10,508
| 2.421875
| 2
|
[] |
no_license
|
package com.csci490.bracketeer;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SwissRoundPairings extends AppCompatActivity {
GameState currentGameState;
List<Player> currentPlayers;
List<List<Player>> seeds = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_round_pairings);
currentGameState = (GameState) getIntent().getExtras().getSerializable("gameState");
currentPlayers = currentGameState.getCurrentPlayers();
TextView round = findViewById(R.id.roundLabel);
String roundLabel = "Round " + currentGameState.getCurrentRound();
round.setText(roundLabel);
if(currentGameState.getCurrentRound() == 1 && !currentGameState.getLoaded()) {
Collections.shuffle(currentPlayers);
createInitalSeeds();
}
else {
createSeeds();
}
populateSeeds();
}
private void createInitalSeeds(){
int numPlayers = currentPlayers.size();
for(int i = 0; i < (numPlayers / 2); i++){
List<Player> pair = new ArrayList<>();
pair.add(currentPlayers.get(i));
pair.add(currentPlayers.get(numPlayers - 1 - i));
seeds.add(pair);
}
boolean presentFlag = false;
for(Player currentPlayer : currentPlayers){
for(List<Player> seed : seeds){
if(seed.contains(currentPlayer)) {
presentFlag = true;
break;
}
}
if(!presentFlag){
List<Player> pair = new ArrayList<>();
pair.add(currentPlayer);
seeds.add(pair);
}
presentFlag = false;
}
}
private void createSeeds(){
List<Player> playerQueue = new ArrayList<>();
playerQueue.addAll(currentPlayers);
while(playerQueue.size() != 0) {
List<Player> pair = new ArrayList<>();
if(playerQueue.size() == 1){
pair.add(playerQueue.get(0));
playerQueue.remove(0);
}
else {
Player first = playerQueue.get(0);
Player second = playerQueue.get(1);
for (int i = 2; i < playerQueue.size(); i++) {
if (playerQueue.get(i).getMatchPoints() > first.getMatchPoints()) {
second = first;
first = playerQueue.get(i);
} else if (playerQueue.get(i).getMatchPoints() > second.getMatchPoints()) {
second = playerQueue.get(i);
} else {
continue;
}
}
pair.add(first);
pair.add(second);
playerQueue.remove(first);
playerQueue.remove(second);
}
seeds.add(pair);
}
}
private void populateSeeds(){
LinearLayout leftParent = findViewById(R.id.leftLayout);
LinearLayout rightParent = findViewById(R.id.rightLayout);
leftParent.setGravity(Gravity.CENTER_VERTICAL);
rightParent.setGravity(Gravity.CENTER_VERTICAL);
for(List<Player> currentSeed : seeds){
LinearLayout leftSeedRow = new LinearLayout(getBaseContext());
LinearLayout rightSeedRow = new LinearLayout(getBaseContext());
leftSeedRow.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
rightSeedRow.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
leftSeedRow.setGravity(Gravity.CENTER_HORIZONTAL);
rightSeedRow.setGravity(Gravity.CENTER_HORIZONTAL);
leftSeedRow.setPadding(20, 20, 20, 20);
rightSeedRow.setPadding(20,20,20,20);
leftParent.addView(leftSeedRow);
rightParent.addView(rightSeedRow);
TextView leftPlayer = new TextView(getBaseContext());
TextView rightPlayer = new TextView(getBaseContext());
Typeface face = ResourcesCompat.getFont(this, R.font.aldrich);
leftPlayer.setTypeface(face);
rightPlayer.setTypeface(face);
leftPlayer.setText(currentSeed.get(0).getName());
leftPlayer.setGravity(Gravity.CENTER_HORIZONTAL);
CheckBox leftWinner = new CheckBox(getBaseContext());
leftWinner.setTag(currentSeed.get(0).getName());
leftSeedRow.addView(leftWinner);
leftSeedRow.addView(leftPlayer);
if(currentSeed.size() == 1){
rightPlayer.setText(R.string.bye);
rightPlayer.setGravity(Gravity.CENTER_HORIZONTAL);
leftWinner.setChecked(true);
rightSeedRow.addView(rightPlayer);
}
else {
rightPlayer.setText(currentSeed.get(1).getName());
rightPlayer.setGravity(Gravity.CENTER_HORIZONTAL);
CheckBox rightWinner = new CheckBox(getBaseContext());
rightWinner.setTag(currentSeed.get(1).getName());
rightSeedRow.addView(rightWinner);
rightSeedRow.addView(rightPlayer);
}
}
}
public void save(View view){
final EditText input = new EditText(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name for tournament:");
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentGameState.setName(input.getText().toString());
currentGameState.setSerialVersionUID(ObjectStreamClass.lookup(currentGameState.getClass()).getSerialVersionUID());
String filename = currentGameState.getName();
try {
File dirFile = new File(getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(dirFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(currentGameState);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void nextRound(View view){
int numPlayers = currentPlayers.size();
double totalRounds = Math.log(numPlayers) / Math.log(2);
totalRounds = Math.ceil(totalRounds);
LinearLayout layout = findViewById(R.id.leftLayout);
CheckBox box;
Intent intent = null;
for(List<Player> currentSeed : seeds){
if(currentSeed.size() == 1){
currentSeed.get(0).incrementMatchPoints(3);
currentSeed.get(0).addWinLoss(1);
currentSeed.get(0).addPreviousOpponent("Bye");
}
else {
box = layout.findViewWithTag(currentSeed.get(0).getName());
if (box.isChecked()) {
currentSeed.get(0).incrementMatchPoints(3);
currentSeed.get(0).addWinLoss(1);
currentSeed.get(1).addWinLoss(0);
} else {
currentSeed.get(1).incrementMatchPoints(3);
currentSeed.get(1).addWinLoss(1);
currentSeed.get(0).addWinLoss(0);
}
currentSeed.get(0).addPreviousOpponent(currentSeed.get(1).getName());
currentSeed.get(1).addPreviousOpponent(currentSeed.get(0).getName());
}
}
if(currentGameState.getCurrentRound() == totalRounds){
Player first = currentPlayers.get(0);
Player second = currentPlayers.get(1);
Player third = currentPlayers.get(2);
for(int i = 3; i < currentPlayers.size(); i++){
Player player = currentPlayers.get(i);
if(player.getMatchPoints() > first.getMatchPoints()){
third = second;
second = first;
first = player;
}
else if(player.getMatchPoints() > second.getMatchPoints()){
third = second;
second = player;
}
else if(player.getMatchPoints() > third.getMatchPoints()){
third = player;
}
else {
continue;
}
}
intent = new Intent(this, NonElimWinnerActivity.class);
intent.putExtra("first", first.getName());
intent.putExtra("second", second.getName());
intent.putExtra("third", third.getName());
}
else {
currentGameState.incrementRound();
Bundle bundle = new Bundle();
bundle.putSerializable("gameState", currentGameState);
intent = new Intent(this, SwissRoundPairings.class);
intent.putExtras(bundle);
}
startActivity(intent);
finish();
}
}
| true
|
1716c32145317fab6122370f94a898e4e072903f
|
Java
|
daweifly1/xgit-parts-pom
|
/gw-oauth/gw-oauth-api/src/main/java/cn/com/xgit/gw/enums/SystemEnum.java
|
UTF-8
| 484
| 2.421875
| 2
|
[] |
no_license
|
package cn.com.xgit.gw.enums;
public enum SystemEnum {
BASE(1, "基础平台"),
SHOP(2, "电商平台"),
STORAGE(3, "仓储平台");
private int code;
private String name;
SystemEnum(int code, String name) {
this.code = code;
this.name = name;
}
public long getLongCode() {
return code + 0L;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
| true
|
ed331cdf028de839515a5a8287ec8006fe340d7a
|
Java
|
devmngr/SDJ1-Java
|
/Rental System1/src/GUI/UnavailableVehiclePanel.java
|
UTF-8
| 2,036
| 2.578125
| 3
|
[] |
no_license
|
package GUI;
import Code.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class UnavailableVehiclePanel extends JPanel
{
private JLabel lblType, lblModel, lblStatus, lblBookingID, lblTimeLeft;
private JTextField txfSearch, txfType, txfModel, txfStatus, txfBookingID,
txfTimeLeft;
private JButton btnSearchID;
private JTextArea txaType, txaModel, txaStatus, txaBookingID, txaTimeLeft;
// buttons
public UnavailableVehiclePanel()
{
this.setLayout(null);
// Create Type label
lblType = new JLabel("Type");
lblType.setBounds(100, 60, 120, 25);
add(lblType);
// create Model label
lblModel = new JLabel("Model");
lblModel.setBounds(250, 60, 120, 25);
add(lblModel);
// status label
lblStatus = new JLabel("Status");
lblStatus.setBounds(400, 60, 120, 25);
add(lblStatus);
// Booking label
lblBookingID = new JLabel("BookingID");
lblBookingID.setBounds(550, 60, 120, 25);
add(lblBookingID);
lblTimeLeft = new JLabel("TimeLeft");
lblTimeLeft.setBounds(700, 60, 120, 25);
add(lblTimeLeft);
btnSearchID = new JButton("SearchID");
btnSearchID.setBounds(510, 20, 120, 25);
add(btnSearchID);
txfSearch = new JTextField();
txfSearch.setBounds(635, 20, 120, 25);
add(txfSearch);
// text fields for labels
txfType = new JTextField();
txfType.setBounds(50, 80, 120, 400);
add(txfType);
txfModel = new JTextField();
txfModel.setBounds(205, 80, 120, 400);
add(txfModel);
txfStatus = new JTextField();
txfStatus.setBounds(360, 80, 120, 400);
add(txfStatus);
txfBookingID = new JTextField();
txfBookingID.setBounds(520, 80, 120, 400);
add(txfBookingID);
txfTimeLeft = new JTextField();
txfTimeLeft.setBounds(680, 80, 120, 400);
add(txfTimeLeft);
}
}
| true
|
3ddbc0c9d8bbcb5710c870e86817a8a6414a8faa
|
Java
|
dannidanna/Algorithms-with-java
|
/Ejercicios/src/ejercicios/FillTheContainers11413.java
|
UTF-8
| 1,505
| 3.125
| 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 ejercicios;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* @author danni
*/
public class FillTheContainers11413 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int aux;
List<Integer> numeros;
numeros = new ArrayList<>();
List<Integer> capacidades;
capacidades = new ArrayList<>();
int capacidad=0;
int cont =0;
for(int j=0; j<n; j++){
aux = scan.nextInt();
numeros.add(aux);
}
int aux2 = n-m+1;
int aux3=m;
while(aux2>0){
for(int i=cont; aux3>0; i++){
capacidad = capacidad + numeros.get(i);
aux3--;
}
aux3 = m;
capacidades.add(capacidad);
cont++;
capacidad =0;
aux2--;
}
System.out.println(minimo(capacidades));
}
public static int minimo(List<Integer> capacidades){
int menor = capacidades.get(0);
for(int i=0; i<capacidades.size(); i++){
if(capacidades.get(i)< menor)
menor = capacidades.get(i);
}
return menor;
}
}
| true
|
1aafd19f0e58ccc67d8d274add156251da47d493
|
Java
|
eugeniopacceli/GetJedi
|
/GetJedi/app/src/main/java/edu/getjedi/frontend/mobile/state/ClientLoggedState.java
|
UTF-8
| 10,577
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package edu.getjedi.frontend.mobile.state;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import edu.getjedi.frontend.mobile.DialogDecorator;
import edu.getjedi.frontend.mobile.DialogType;
import edu.getjedi.frontend.mobile.StringTable;
import edu.getjedi.frontend.mobile.network.RequestType;
import edu.getjedi.schema.Client;
/**
* State of the application when a client is logged.
* Also a Google Map event handler, as the client user interacts with the map requesting services.
*/
public class ClientLoggedState implements AppState, GoogleMap.OnInfoWindowClickListener{
private Handler timer;
private String rayFilter;
private String priceFilter;
private GoogleMap map;
private AppContext context;
private JSONArray services;
private JSONArray users;
private ArrayList<Marker> markers;
private String choosenOne;
@Override
public void performAction(final AppContext context, Object action) {
if (action == null) { // Verifies if user is still logged, this is called when the application begins or is resumed
if (context.getUser() == null) {
context.setState(new BeginState());
} else {
init(context);
}
} else if (action instanceof GoogleMap){ // Received a working Google Map instance to be used.
initMap((GoogleMap) action);
} else if(action instanceof JSONArray){ // Receives the service offers nearby and professionals offering them.
parseResponses((JSONArray) action);
if(users != null && services != null){
updateMap(); // Updates the map
}
} else if(action instanceof String[]){ // User has changed service filter values.
rayFilter = ((String[])action)[0];
priceFilter = ((String[])action)[1];
} else if(action instanceof Boolean){ // User has prompted a service.
if(choosenOne != null){
sendJobRequest(context);
}
}
}
/**
* Dispatches a service request to the server, which will inform a professional of this user desire
* to be a client.
*/
private void sendJobRequest(AppContext context) {
String[] query = findProfessionalAndServiceByEmail(choosenOne);
HashMap<String,String> map = new HashMap<>();
map.put("clientId", context.getUser().getId());
map.put("professionalId", query[0]);
map.put("serviceId", query[1]);
map.put("startDate", "0");
map.put("endDate", "0");
map.put("jobStatus", "0");
map.put("clientRating", "5");
map.put("professionalRating", "5");
context.getScreen().getHttpHandler().makePOSTRequestForObject(new String[]{"createJob"}, map);
}
/**
* Verifies if the server sent the nearby services or nearby professionals, and stores them in memory,
* to be represented in the map for the user to navigate.
*/
private void parseResponses(JSONArray action) {
try {
if(action.length() > 0) {
JSONObject obj = action.getJSONObject(0);
if (obj.has("username")) {
users = action;
} else if (obj.has("professionalId")){
services = action;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Sets the map to send clicks to this class.
*/
private void initMap(GoogleMap action) {
map = action;
map.setOnInfoWindowClickListener(this);
}
/**
* Initializes this state.
* For every context.getUpdateInterval(), queries the server for services and professionals nearby.
* Changes the left menu content to show the options available for a Client.
*/
private void init(final AppContext context) {
context.getScreen().setMenuItems(new String[]{context.getUser().getFirstName() + " " + context.getUser().getLastName(), StringTable.CLIENT, " ", StringTable.FILTER_TITLE, StringTable.LOGOFF});
this.context = context;
timer = new Handler();
services = users = null;
priceFilter = rayFilter = null;
markers = new ArrayList<>();
timer.postDelayed(new Runnable() {
@Override
public void run() {
context.getScreen().getHttpHandler().makeRequestForArray(new String[]{"services"});
context.getScreen().getHttpHandler().makeRequestForArray(new String[]{"users"});
if (context.getState() instanceof ClientLoggedState) {
timer.postDelayed(this, context.getUpdateInterval());
}
}
}, context.getUpdateInterval());
}
/**
* Draws into the Google Map all the services makers, and populate them with service and professional information.
* Called for each map update.
*/
private void updateMap() {
cleanMarkers();
try {
for (int i = 0; i < services.length(); i++) {
JSONObject service = services.getJSONObject(i);
for (int j = 0; j < users.length(); j++) {
JSONObject user = users.getJSONObject(j);
if (service.getString("professionalId").equals(user.getString("_id")) && filterPrice(service.getInt("hourlyPrice"))
&& filterRay(user.getString("latitude"), user.getString("longitude"))){
drawMarkerOnMap(Double.parseDouble(user.getString("latitude")),
Double.parseDouble(user.getString("longitude")),
service.getString("category"),
service.getString("serviceName"),
service.getString("description"),
service.getString("hourlyPrice"),
user.getString("name"),
user.getString("lastName"),
user.getString("mail"));
break;
}
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
/**
* Applies the ray filter for updateMap(), returning true if the service passes the maximum ray requirement.
*/
private boolean filterRay(String latitude, String longitude) {
try {
double radius;
double x0 = context.getUser().getCoordinates().latitude;
double y0 = context.getUser().getCoordinates().longitude;
double x1 = Double.parseDouble(latitude);
double y1 = Double.parseDouble(longitude);
radius = Double.parseDouble(this.rayFilter);
//Ratio for earth surface - Harvarsine Formula
double deglen = 110.25;
double x = x1 - x0;
double y = (y1 - y0) * Math.cos(x0);
double distance = deglen * Math.sqrt(x*x + y*y);
return ( distance <= radius);
}catch (Exception e){
return true;
}
}
/**
* Applies the price filter for updateMap(), returning true if the service passes the maximum price requirement.
*/
private boolean filterPrice(int hourlyPrice) {
double priceFilter;
try {
priceFilter = Double.parseDouble(this.priceFilter);
}catch (Exception e){
priceFilter = Double.MAX_VALUE;
}
return hourlyPrice <= priceFilter;
}
/**
* Returns a String array with the professional id for a email into the position 0, and the service it offers into position 1
*/
private String[] findProfessionalAndServiceByEmail(String email){
String[] results = new String[2];
results[0] = "";
results[1] = "";
try {
for (int j = 0; j < users.length(); j++) {
JSONObject user = users.getJSONObject(j);
if (user.getString("mail").equals(email)) {
results[0] = user.getString("_id");
break;
}
}
for (int j = 0; j < services.length(); j++) {
JSONObject service = services.getJSONObject(j);
if (service.getString("professionalId").equals(results[0])) {
results[1] = service.getString("_id");
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
return results;
}
private void cleanMarkers(){
for(Marker e : markers){
e.remove();
}
}
/**
* Draws a marker on the map and builds it's description window.
*/
private void drawMarkerOnMap(double lat, double lng, String category, String name, String desc, String price, String username, String lastName, String email){
if(map != null) {
Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).
title(category + ": " + name).snippet(desc + "\nR$" + price + " (hora)\n" + username + " " + lastName + "\n" + email)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
markers.add(marker);
}
}
/**
* Handles user map clicks.
*/
@Override
public void onInfoWindowClick(Marker marker) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(),15)); // Move to clicked service marker
DialogDecorator dialogDecorator = new DialogDecorator();
String[] snippetLines = marker.getSnippet().split("\n");
choosenOne = snippetLines[snippetLines.length - 1];
if(choosenOne.length() > 2) {
// Prompts user for confirmation
dialogDecorator.getDialog(DialogType.CONFIRM_JOB, context.getScreen(), context.getScreen().getHttpHandler()).show();
}
}
}
| true
|
49b00be544c9215fd7e929822062a31041166683
|
Java
|
Pask423/keycloak-springboot
|
/base-integration/src/main/java/org/pcs/springboot/keycloak/controller/HelloController.java
|
UTF-8
| 537
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.pcs.springboot.keycloak.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public ResponseEntity<String> hello(Authentication authentication) {
final String body = "Hello " + authentication.getName();
return ResponseEntity.ok(body);
}
}
| true
|
acbd1255609ddfef71e708f9f939eb1c0d369d08
|
Java
|
niveksys/spring-mvc-rest
|
/src/test/java/com/niveksys/mvcrest/service/CustomerServiceImplTests.java
|
UTF-8
| 4,499
| 2.40625
| 2
|
[] |
no_license
|
package com.niveksys.mvcrest.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import com.niveksys.mvcrest.controller.CustomerController;
import com.niveksys.mvcrest.dto.CustomerDto;
import com.niveksys.mvcrest.mapper.CustomerMapper;
import com.niveksys.mvcrest.model.Customer;
import com.niveksys.mvcrest.repository.CustomerRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class CustomerServiceImplTests {
public static final Long ID1 = 1L;
public static final String FIRSTNAME1 = "Michale";
public static final String LASTNAME1 = "Weston";
public static final Long ID2 = 2L;
public static final String FIRSTNAME2 = "Sam";
public static final String LASTNAME2 = "Axe";
@Mock
CustomerRepository customerRepository;
CustomerService customerService;
@BeforeEach
public void setUp() throws Exception {
this.customerService = new CustomerServiceImpl(this.customerRepository, CustomerMapper.INSTANCE);
}
@Test
public void getAllCustomers() throws Exception {
// given
Customer customer1 = new Customer();
customer1.setId(ID1);
customer1.setFirstname(FIRSTNAME1);
customer1.setLastname(LASTNAME1);
Customer customer2 = new Customer();
customer2.setId(ID2);
customer2.setFirstname(FIRSTNAME2);
customer2.setLastname(LASTNAME2);
when(this.customerRepository.findAll()).thenReturn(Arrays.asList(customer1, customer2));
// when
List<CustomerDto> customerDtoList = this.customerService.getAllCustomers();
// then
assertEquals(2, customerDtoList.size());
}
@Test
public void getCustomerById() throws Exception {
// given
Customer customer = new Customer();
customer.setId(ID1);
customer.setFirstname(FIRSTNAME1);
customer.setLastname(FIRSTNAME2);
when(this.customerRepository.findById(anyLong())).thenReturn(Optional.ofNullable(customer));
// when
CustomerDto customerDto = this.customerService.getCustomerById(ID1);
// then
assertEquals(FIRSTNAME1, customerDto.getFirstname());
}
@Test
public void createCustomer() throws Exception {
// given
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstname(FIRSTNAME1);
customerDto.setLastname(LASTNAME1);
Customer savedCustomer = new Customer();
savedCustomer.setId(ID1);
savedCustomer.setFirstname(customerDto.getFirstname());
savedCustomer.setLastname(customerDto.getLastname());
when(this.customerRepository.save(any(Customer.class))).thenReturn(savedCustomer);
// when
CustomerDto savedDto = this.customerService.createCustomer(customerDto);
// then
assertEquals(customerDto.getFirstname(), savedDto.getFirstname());
assertEquals(CustomerController.BASE_URL + "/" + ID1, savedDto.getCustomerUrl());
}
@Test
public void updateCustomer() throws Exception {
// given
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstname(FIRSTNAME1);
Customer savedCustomer = new Customer();
savedCustomer.setFirstname(customerDto.getFirstname());
savedCustomer.setLastname(customerDto.getLastname());
savedCustomer.setId(1l);
when(this.customerRepository.save(any(Customer.class))).thenReturn(savedCustomer);
// when
CustomerDto savedDto = this.customerService.updateCustomer(ID1, customerDto);
// then
assertEquals(customerDto.getFirstname(), savedDto.getFirstname());
assertEquals(CustomerController.BASE_URL + "/" + ID1, savedDto.getCustomerUrl());
}
@Test
public void deleteCustomerById() throws Exception {
// when
this.customerService.deleteCustomer(ID1);
// then
verify(this.customerRepository, times(1)).deleteById(anyLong());
}
}
| true
|
c83de5d49dc83ffdb3516a27482ef6cb356daf07
|
Java
|
doha-youssef/Assignment2
|
/Address.java
|
UTF-8
| 380
| 2.859375
| 3
|
[] |
no_license
|
package test2;
public class Address
{
String streetNo;
String city;
String country;
public Address(String streetNo, String city, String country)
{
this.streetNo=streetNo;
this.city=city;
this.country=country;
}
public String getAddress()
{
return "Address: "+streetNo+" "+city+" "+country;
}
}
| true
|
3f7c30f4ad72f94ebea07199580a207d92bce546
|
Java
|
rrocharoberto/AgenciaDeViagens
|
/agencia/src/main/java/br/edu/univas/agencia/agencia/service/api/impl/HotelServiceImpl.java
|
UTF-8
| 1,271
| 2.34375
| 2
|
[] |
no_license
|
package br.edu.univas.agencia.agencia.service.api.impl;
import java.util.Collection;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import br.edu.univas.agencia.agencia.business.HotelBusiness;
import br.edu.univas.agencia.agencia.business.PackageBusiness;
import br.edu.univas.agencia.agencia.service.api.HotelService;
import br.edu.univas.agencia.exception.AgencyException;
import br.edu.univas.agencia.model.Hotel;
import br.edu.univas.agencia.model.HotelReserva;
import br.edu.univas.agencia.model.Pacote;
/**
* Implementation of services defined in {@link HotelService}.
* @author edilson
*
*/
@Path("/hotelAgency")
public class HotelServiceImpl implements HotelService {
PackageBusiness packageBusiness = new PackageBusiness();
HotelBusiness hotelBusiness = new HotelBusiness();
@GET
@Override
public Collection<Hotel> listHotels(@QueryParam("packageId") int packageId) throws AgencyException {
Pacote pacote = packageBusiness.retrievePackage(packageId);
return hotelBusiness.listHotels(pacote);
}
@POST
@Path("/reservation")
@Override
public void createHotelReservation(HotelReserva hotelReserva)
throws AgencyException {
hotelBusiness.createReservation(hotelReserva);
}
}
| true
|
1f836ba5f17a7005b6b1e1eb8d78289dd6ba68a2
|
Java
|
snoor19/Learning
|
/src/com/spero/learn/TestSample.java
|
UTF-8
| 1,636
| 2.65625
| 3
|
[] |
no_license
|
package com.spero.learn;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestSample {
public static void main(String[] args) {
/*
* byte[] timeZone = {-127,00}; String str = new String(timeZone);
* System.out.println("Str Data ::"+hexStringToByteArray("8100"));
*/
String account_details = "\"{\r\n" +
"\"bank_name\":\"Kotak\",\r\n" +
"\"user_name\":\"onmobile\",\r\n" +
"\"ifsc\":\"KKBK00000\",\r\n" +
"\"account_no\":\"123456\",\r\n" +
"\"account_type\":\"savings\"\r\n" +
"}\"";
Map<String, String> accountMap = null;
try {
account_details = account_details.substring(1,account_details.length()-1);
accountMap = new ObjectMapper().readValue(account_details, Map.class);
System.out.println("Data:"+accountMap);
} catch ( IOException e) {
System.out.println("In Exception::"+e);
}
String result = accountMap!=null?(accountMap.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue())
.collect(Collectors.joining("|"))):"";
System.out.println("Result::"+result);
String str = "/griff/getUserInfo.jsp?sessionid=$REF_ID$";
str = str.replace("$REF_ID$", "what");
System.out.println("Next::"+str);
}
public static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
}
| true
|
29bf4739710ac37988b17f89d1cf310e889170d6
|
Java
|
onurkaraduman/customer-service
|
/src/main/java/com/onrkrdmn/restapi/model/Response.java
|
UTF-8
| 699
| 2.3125
| 2
|
[] |
no_license
|
package com.onrkrdmn.restapi.model;
import com.onrkrdmn.restapi.dto.BaseDto;
import com.onrkrdmn.restapi.dto.MessageDto;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Custom response body
* In the future, some fields can be added according to needs
*
* @author Onur Karaduman
* @since 01.04.17
*/
@Getter
@Setter
public class Response<T extends BaseDto> extends ResponseEntity<T> {
public Response() {
super(HttpStatus.OK);
}
public Response(T body, HttpStatus status) {
super(body, status);
}
public Response(T body) {
super(body, HttpStatus.OK);
}
}
| true
|
82bbd3b8742caae1d35993b16818634ff5598ab9
|
Java
|
RalphMcDougall/grade-12-pat
|
/RalphMcDougallPAT2018/src/src/Tile/TileTypeHandler.java
|
UTF-8
| 3,061
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
/*
* 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 src.Tile;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import src.Utility.DBBridge;
import src.Main.GameHandler;
import src.Utility.GameLogger;
/**
* Loads all of the tile types and allows them to be retrieved at any time
*
* @author Ralph McDougall 26/4/2018
*/
public class TileTypeHandler {
// *****************************************************
// PRIVATE FIELDS
// *****************************************************
// The number of tile types
private static int numTileTypes;
// The array of all tile types in the game
private static TileType tileTypes[];
// *****************************************************
// PUBLIC METHODS
// *****************************************************
/**
* Load the tile types from the database
*
* @throws SQLException SQL couldn't load the tile types
*/
public static void load() throws SQLException
{
GameLogger.logInfo("Load tile types from database...");
// Get the database where all of the persistent data is stored
DBBridge db = GameHandler.getPersistentDB();
// Get the data from the tile table
ResultSet rs = db.query("SELECT TileID, TileName, SpriteSheetX, SpriteSheetY, Walkable "
+ "FROM tblTileTypes;");
ArrayList< ArrayList< String > > res = DBBridge.processResultSet(rs);
// The number of different tile types
numTileTypes = res.size();
// Initialise the array of tile types
tileTypes = new TileType[numTileTypes];
// Fill up the array with the tile types
for (int i = 0; i < numTileTypes; ++i)
{
rs.next();
int id = Integer.parseInt(res.get(i).get(0));
String name = res.get(i).get(1);
int spriteSheetX = Integer.parseInt(res.get(i).get(2));
int spriteSheetY = Integer.parseInt(res.get(i).get(3));
boolean canWalk = Boolean.parseBoolean(res.get(i).get(4));
tileTypes[i] = new TileType(id,
name,
spriteSheetX,
spriteSheetY,
canWalk );
}
GameLogger.logInfo("Tile types loaded successfully.");
}
/**
* Get the tile type that has a given ID
*
* @param id The ID of the tile type to find
* @return The TileType with the given ID
*/
public static TileType getTileType(int id)
{
if (id > numTileTypes || id <= 0)
{
// The ID of the tile type is higher than the number of tile types
GameLogger.logError("Unknown tile ID: " + id);
return null;
}
return tileTypes[id - 1];
}
}
| true
|
f4d92fec9fcb1afa8e17fd39f20ca7b00c5a1194
|
Java
|
thistestuser007/insurancebarcode
|
/src/java/PricecheckQuery/PricecheckLookup.java
|
UTF-8
| 2,345
| 2.6875
| 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 PricecheckQuery;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
*
* @author Denver
*/
public final class PricecheckLookup {
//-------------------
//2. Get price from pricecheck
public static String getPriceFromPriceCheck(String productName) {
String replaceTemp = productName.replaceAll(" ", "+");
return parseHTML(queryURL("http://www.pricecheck.co.za/search?search=" + replaceTemp));
}
private static String queryURL(String urlWithItem) {
try {
String inputLine;
StringBuilder response = new StringBuilder();
URL obj = new URL(urlWithItem);
int responseCode = 0;
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (MalformedURLException ex) {
Logger.getLogger(PricecheckLookup.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PricecheckLookup.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
private static String parseHTML(String returnedResult) {
Document doc = Jsoup.parse(returnedResult);
Elements list_items = doc.getElementsByClass("txt-price");
Elements list_items2 = doc.getElementsByClass("square-block wallpaper");
System.out.println("----" + list_items.get(0).text());
return list_items.get(0).text();
}
}
| true
|
ee00f3bf62e0425664c16cb777980d345a3d69ce
|
Java
|
catmaomao/android_sdk
|
/GameSDKDemo/gameSDK/src/main/java/com/heyijoy/gamesdk/operatorpay/CTResultActivity.java
|
UTF-8
| 1,606
| 2.015625
| 2
|
[] |
no_license
|
package com.heyijoy.gamesdk.operatorpay;
import com.zb.feecharge.FeeChargeManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
public class CTResultActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
FeeObserver feeObserver = OpPay.feeObserver;
String providerName = getIntent().getStringExtra("providerName");
//统一运营商支付方法调用
java.util.Map<String, Object> map=FeeChargeManager.getInstance().feeChargeOP(this,
MdoSmsService.class, providerName);
if(map.get("resultType")!=null){
//处理移动Mdo计费返回processId; 在feeObserver类中会处理移动mdo短信计费的结果,并且发送mdo计费成功的广播
Long processid = Long.parseLong((String) map.get("result"));
feeObserver.setProcessID("MDO", processid);
}
}
/**
* 计费支付返回接收方法
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//回调逻辑(注意电信计费:用户 必须在电信计费成功页面上点“返回”按钮 才行 )
int payresult=FeeChargeManager.getInstance().feeCharge_TC_return(requestCode,
resultCode, data);
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return super.onKeyDown(keyCode, event);
}
}
| true
|
26d096a580ea7e9b4c657cd87ff5e96eda1459bf
|
Java
|
jatanrathod/Idea-Plagiarism
|
/IPlagiarism/src/iplagiarism/GUI.java
|
UTF-8
| 4,974
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
package iplagiarism;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class GUI extends JFrame {
private final JTextField dirPath;
public static JTextArea processArea;
private final JButton checkButton;
private final JButton selectButton;
private final JPanel contentPanel;
private JPanel subPanel;
private final JLabel dirLabel;
private final JLabel processLabel;
private JScrollPane pane;
public static JProgressBar pbar;
public GUI() {
this.processLabel = new JLabel("Process : ");
this.dirLabel = new JLabel("Enter path of directory : ");
this.selectButton = new JButton("Select");
this.dirPath = new JTextField();
this.processArea = new JTextArea();
this.checkButton = new JButton("Check");
this.subPanel = new JPanel();
this.contentPanel = new JPanel();
this.pbar = new JProgressBar(0,100);
}
public void Display() {
setBounds(50, 50, 600, 200);
setMinimumSize(new Dimension(500, 300));
setMaximumSize(new Dimension(999, 200));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("JAM Plagiarism Checker");
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.PAGE_AXIS));
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setContentPane(contentPanel);
dirLabel.setPreferredSize(new Dimension(100, 20));
processLabel.setPreferredSize(new Dimension(150, 20));
dirPath.setPreferredSize(new Dimension(150, 5));
processArea.setPreferredSize(new Dimension(0, 1000));
processArea.setEditable(false);
pane = new JScrollPane (processArea);
pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pbar.setPreferredSize(new Dimension(150, 5));
pbar.setStringPainted(true);
subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));
subPanel.add(dirLabel);
contentPanel.add(subPanel);
subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));
subPanel.add(dirPath);
subPanel.add(Box.createRigidArea(new Dimension(5,0)));
subPanel.add(selectButton);
contentPanel.add(subPanel);
subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));
subPanel.add(processLabel);
contentPanel.add(subPanel);
subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));
subPanel.add(pane);
contentPanel.add(subPanel);
subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));
subPanel.add(pbar);
subPanel.add(Box.createRigidArea(new Dimension(5,0)));
subPanel.add(checkButton);
contentPanel.add(subPanel);
EventSb esb = new EventSb();
selectButton.addActionListener(esb);
EventCB ecb = new EventCB();
checkButton.addActionListener(ecb);
setVisible(true);
}
static String getDirectory() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("~"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile().getAbsolutePath();
}
return null;
}
class EventCB implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String path = dirPath.getText();
if (path.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please select Directory to proceed..");
} else {
(new checkPlagiarism(path)).execute();
}
}
}
class EventSb implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String s1 = GUI.getDirectory();
dirPath.setText(s1);
}
}
}
| true
|
152533c4ef9a62a99c73a70a6b336fd6278ca35d
|
Java
|
happyforever8/FBonsite
|
/******missing number in Arithmetic.java
|
UTF-8
| 1,388
| 3.546875
| 4
|
[] |
no_license
|
Given an array that represents elements of arithmetic progression in order. One element is missing in the progression, find the missing number.
Input: arr[] = {2, 4, 8, 10, 12, 14}
Output: 6
Input: arr[] = {1, 6, 11, 16, 21, 31};
Output: 26
class GFG
{
// A binary search function that
// returns the missing
// element in arithmetic
// progression
static int findMissingUtil(int arr[], int low,
int high, int diff)
{
// Find index of middle element
int mid;
while (low <= high)
{
// find index of middle element
mid = (low + high) / 2;
// if mid == (nth position of element in AP)-1
// the missing element will exist in right half
if ((arr[mid] - arr[0]) / diff == mid)
low = mid + 1;
else
// the missing element will exist in left half
high = mid - 1;
}
return arr[high] + diff;
}
static int findMissing(int arr[], int n)
{
int diff = (arr[n - 1] - arr[0]) / n;
// Binary search for the missing
// number using above calculated diff
return findMissingUtil(arr, 0, n - 1, diff);
}
// Driver Code
public static void main (String[] args)
{
int arr[] = {2, 4, 8, 10, 12, 14};
int n = arr.length;
System.out.println("The missing element is "+
findMissing(arr, n));
}
| true
|
072757610a94ed7d8128e0216b1720618da93fb1
|
Java
|
v1ckxy/radar-covid
|
/sources/p119o/p120a/C0926d1.java
|
UTF-8
| 1,496
| 1.53125
| 2
|
[] |
no_license
|
package p119o.p120a;
/* renamed from: o.a.d1 */
public class C0926d1 extends C0932f1 implements C0972r {
/* renamed from: f */
public final boolean f2526f;
public C0926d1(C0916a1 a1Var) {
boolean z = true;
super(true);
mo4248a(a1Var);
C0954m mVar = (C0954m) this._parentHandle;
if (!(mVar instanceof C0957n)) {
mVar = null;
}
C0957n nVar = (C0957n) mVar;
if (nVar != null) {
C0932f1 f1Var = (C0932f1) nVar.f2530h;
if (f1Var != null) {
while (true) {
if (!f1Var.mo4227e()) {
C0954m mVar2 = (C0954m) f1Var._parentHandle;
if (!(mVar2 instanceof C0957n)) {
mVar2 = null;
}
C0957n nVar2 = (C0957n) mVar2;
if (nVar2 == null) {
break;
}
f1Var = (C0932f1) nVar2.f2530h;
if (f1Var == null) {
break;
}
} else {
break;
}
}
}
}
z = false;
this.f2526f = z;
}
/* renamed from: e */
public boolean mo4227e() {
return this.f2526f;
}
/* renamed from: f */
public boolean mo4228f() {
return true;
}
}
| true
|
239d05e908f4bb73478b130ac16f80b66e82bfa5
|
Java
|
shashankg1991/eCatalogue
|
/app/src/main/java/com/e/spectra/presentation/view/BrandListener.java
|
UTF-8
| 246
| 1.648438
| 2
|
[] |
no_license
|
package com.e.spectra.presentation.view;
import android.content.Context;
import androidx.lifecycle.LiveData;
public interface BrandListener {
Context onStarted();
void onInsert(String response);
void onFailed(String message);
}
| true
|
4f2219e36b86e0916c9be7216bbceb236e0d8cf8
|
Java
|
nikks-tu/OME_NEW
|
/app/src/main/java/com/techuva/ome_new/api_interface/SendOTPDataInterface.java
|
UTF-8
| 491
| 1.898438
| 2
|
[] |
no_license
|
package com.techuva.ome_new.api_interface;
import com.google.gson.JsonElement;
import com.techuva.ome_new.app.Constants;
import com.techuva.ome_new.post_parameters.SendOTPPostParameters;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface SendOTPDataInterface {
@POST(Constants.SendOTP)
Call<JsonElement> getStringScalar(@Header("authUser") int headerValue, @Body SendOTPPostParameters postParameter);
}
| true
|
70c9472a6fa1e1a2bc3e22aecebc7c4352151bb3
|
Java
|
DavidYi/C_DataStructure
|
/DataStructures/tokens/LeftParenthesisToken.java
|
UTF-8
| 122
| 1.648438
| 2
|
[] |
no_license
|
package tokens;
/**
* Created by David on 2/10/2016.
*/
public class LeftParenthesisToken extends ParenthesisToken{
}
| true
|
029e5ce23ac01767acec3167b30695c6593b5fc9
|
Java
|
SantiagoSinatra/SantiagoSinatraAdicional
|
/MuseumApplicationTest/app/src/main/java/com/dhsantiagosinatra/museumapplication/view/AdapterPaints.java
|
UTF-8
| 4,066
| 2.28125
| 2
|
[] |
no_license
|
package com.dhsantiagosinatra.museumapplication.view;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.dhsantiagosinatra.museumapplication.R;
import com.dhsantiagosinatra.museumapplication.model.DAO.DAOFavoritosFromDatabase;
import com.dhsantiagosinatra.museumapplication.model.POJO.Paint;
import java.util.ArrayList;
import java.util.List;
public class AdapterPaints extends RecyclerView.Adapter<AdapterPaints.PaintViewHolder> {
private List<Paint>listaDePaints;
private ListenerAdapterPaints listener;
public AdapterPaints(ListenerAdapterPaints listenerAdapterPaints) {
this.listaDePaints = new ArrayList<>();
this.listener = listenerAdapterPaints;
setHasStableIds(true);
}
public void setPaints(List<Paint> paints){
this.listaDePaints = paints;
notifyDataSetChanged();
}
@NonNull
@Override
public PaintViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View viewDeLaCelda = inflater.inflate(R.layout.celda_paint, viewGroup, false);
PaintViewHolder paintViewHolder = new PaintViewHolder(viewDeLaCelda);
return paintViewHolder;
}
@Override
public void onBindViewHolder(@NonNull PaintViewHolder paintViewHolder, int i) {
Paint paint = listaDePaints.get(i);
paintViewHolder.bindPaint(paint);
}
@Override
public int getItemCount() {
if (listaDePaints != null){
return listaDePaints.size();
}else{
return 0;
}
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
//Interface que se comunica con la activity:
public interface ListenerAdapterPaints{
public void celdaPaintSeleccionada (Paint paint);
public void botonFavoritoSeleccionado (Paint paint);
}
//ViewHolder:
public class PaintViewHolder extends RecyclerView.ViewHolder{
private TextView textViewPaintCelda;
private ImageView imageViewPaintCelda;
private ImageButton botonFavoriteado;
public PaintViewHolder(@NonNull View itemView){
super(itemView);
imageViewPaintCelda = itemView.findViewById(R.id.imageview_paint_celda);
textViewPaintCelda = itemView.findViewById(R.id.textview_paint_celda);
botonFavoriteado = itemView.findViewById(R.id.boton_favoritear);
botonFavoriteado.setImageResource(R.drawable.favoriteado_icon);
imageViewPaintCelda.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Paint paint = listaDePaints.get(getAdapterPosition());
listener.celdaPaintSeleccionada(paint);
}
});
botonFavoriteado.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Paint paint = listaDePaints.get(getAdapterPosition());
listener.botonFavoritoSeleccionado(paint);
botonFavoriteado.setImageResource(R.drawable.favoriteado_icon);
}
});
}
//Juntar los componentes con la informacion:
public void bindPaint(Paint paint){
textViewPaintCelda.setText(paint.getName());
Glide.with(itemView.getContext()).load(paint.getDownloadUrl()).into(imageViewPaintCelda);
}
}
}
| true
|
110621fc56618455919869378c9726ee7dc6b451
|
Java
|
yfm049/oldcode
|
/BakSms/src/com/yfm/sms/NetWorkBroadcastReceiver.java
|
ISO-8859-1
| 615
| 1.882813
| 2
|
[] |
no_license
|
package com.yfm.sms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NetWorkBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Loginfo.write("BroadcastReceiver", "BroadcastReceiver");
SendMail sm=new SendMail(arg0);
Loginfo.write("BroadcastReceiver", "BroadcastReceiver״̬"+sm.getNetWorkState());
if(sm.getNetWorkState()&&!SendMail.isfasong){
SendMailThread smt=new SendMailThread(sm);
smt.start();
}
}
}
| true
|
c4794673051636ca22097de20cd89a2c0cf0549f
|
Java
|
yasyars/parking-app
|
/src/Model/TableModelGarage.java
|
UTF-8
| 2,003
| 3.078125
| 3
|
[] |
no_license
|
package Model;
import javax.swing.table.AbstractTableModel;
import java.util.List;
public class TableModelGarage extends AbstractTableModel {
List<Garage> listOfGarage;
public TableModelGarage(List<Garage> listOfGarage){
this.listOfGarage = listOfGarage;
}
@Override
public int getRowCount() {
return this.listOfGarage.size();
}
@Override
public int getColumnCount() {
return 8;
}
@Override
public String getColumnName(int column) {
switch (column){
case 0:
return "ID Garage";
case 1:
return "Nama Garage";
case 2:
return "Hari Operasional";
case 3:
return "Waktu Buka";
case 4:
return "Waktu Tutup";
case 5:
return "ID Area Garage";
case 6:
return "Tarif Motor";
case 7:
return "Tarif Mobil";
default:
return null;
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex){
case 0:
return listOfGarage.get(rowIndex).getId();
case 1:
return listOfGarage.get(rowIndex).getName();
case 2:
return listOfGarage.get(rowIndex).getOperationalTime().getDay();
case 3:
return listOfGarage.get(rowIndex).getOperationalTime().getOpenHour();
case 4:
return listOfGarage.get(rowIndex).getOperationalTime().getCloseHour();
case 5:
return listOfGarage.get(rowIndex).getArea();
case 6:
return String.valueOf(listOfGarage.get(rowIndex).getTarifMotor());
case 7:
return String.valueOf(listOfGarage.get(rowIndex).getTarifMobil());
default:
return null;
}
}
}
| true
|
947eefef59e3db1088213987113081bc5f1747b4
|
Java
|
isvilla88/Proyecto
|
/Platzigram/app/src/main/java/mx/com/platzigram/platzigram/Validación/ValidaciónDatos.java
|
UTF-8
| 4,609
| 2.328125
| 2
|
[] |
no_license
|
package mx.com.platzigram.platzigram.Validación;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.regex.Pattern;
import mx.com.platzigram.platzigram.R;
/**
* Created by Personal on 16/10/2016.
*/
public class ValidaciónDatos extends AppCompatActivity {
private TextInputLayout DexCorreo;
private TextInputLayout DexName;
private TextInputLayout DexUsuario;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro_veterinaria);
//Referencias Editex para limpiar los errores
EditText campoEmail = (EditText) findViewById(R.id.emailV);
EditText campoNombre = (EditText) findViewById(R.id.name);
EditText campoUsuario = (EditText) findViewById(R.id.usuario);
campoNombre.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
DexName.setError(null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
campoEmail.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
esCorreoValido(String.valueOf(s));
}
@Override
public void afterTextChanged(Editable s) {
}
});
//Referencias de Dex
DexCorreo = (TextInputLayout) findViewById(R.id.DexCorreo);
DexName = (TextInputLayout) findViewById(R.id.DexName);
DexUsuario = (TextInputLayout) findViewById(R.id.DexUsuario);
//Referencia Botón
Button botonAceptar = (Button) findViewById(R.id.joinUs_V);
botonAceptar.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
validarDatos();
}
});
}
private boolean validarNombre(String nombre){
Pattern patron = Pattern.compile("^[a-zA-Z ]+$");
return patron.matcher(nombre).matches() || nombre.length() > 30;
}
private boolean validarTelefono(String telefono){
return Patterns.PHONE.matcher(telefono).matches();
}
private boolean validarCorreo(String correo){
return Patterns.EMAIL_ADDRESS.matcher(correo).matches();
}
private boolean esCorreoValido(String correo){
if(!Patterns.EMAIL_ADDRESS.matcher(correo).matches()){
DexCorreo.setError("Correo electrónico invalido");
return false;
}else {
DexCorreo.setError(null);
}
return true;
}
private boolean esNombreValido(String nombre) {
Pattern patron = Pattern.compile("^[a-zA-Z ]+$");
if (!patron.matcher(nombre).matches() || nombre.length() > 30) {
DexName.setError("Nombre invalido");
return false;
} else {
DexName.setError(null);
}
return true;
}
private boolean esUsuarioValido(String usuario){
Pattern patron = Pattern.compile("^[a-zA-Z ]+$");
if(!patron.matcher(usuario).matches() || usuario.length() > 20 ){
DexUsuario.setError("Nombre de usuario invalido");
return false;
}else {
DexUsuario.setError(null);
}
return true;
}
private void validarDatos() {
String correo = DexCorreo.getEditText().getText().toString();
String nombre = DexName.getEditText().getText().toString();
String usuario = DexUsuario.getEditText().getText().toString();
boolean a = esCorreoValido(correo);
boolean b = esNombreValido(nombre);
boolean c = esUsuarioValido(usuario);
if(a && b && c ){
//Ok, se pasa a la siguiente acción
Toast.makeText(this,"Se guardo su registro", Toast.LENGTH_LONG).show();
}
}
}
| true
|
21189c04c82171f208be4ffd6cc4812d0135d6de
|
Java
|
chinastyle/GitHub
|
/AspExecService/src/com/aspire/android/test/task/entity/Task.java
|
UTF-8
| 8,860
| 2.21875
| 2
|
[] |
no_license
|
/**
* @(#) Task.java Created on 2012-4-26
*
* Copyright (c) 2012 Aspire. All Rights Reserved
*/
package com.aspire.android.test.task.entity;
import java.util.Date;
import com.aspire.android.common.entity.BaseEntity;
import com.aspire.android.test.Constants;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* The class <code>Task</code>
*
* @author linjunsui
* @version 1.0
*/
@DatabaseTable(tableName = Constants.TABLE_TASK)
public class Task extends BaseEntity {
/**
* Tabelname
*/
public static final String TABLENAME = Constants.TABLE_TASK;
/**
* Constants
*/
public static final int PRIORITY_LOW = 2;
public static final int PRIORITY_MEDIUM = 5;
public static final int PRIORITY_HIGH = 8;
public static final Character EXETYPE_BY_TIMES = '2';
public static final Character EXETYPE_BY_TIME = '1';
public static final Character ITERATION_TYPE_NONE = '0';
public static final Character ITERATION_TYPE_BY_DAY = '1';
public static final Character ITERATION_TYPE_BY_WEEK = '2';
public static final Character ITERATION_TYPE_BY_MONTH = '3';
/** 拨测任务ID **/
@DatabaseField(columnName = "ID", generatedId = true)
private long id;
/** 任务编号 **/
@DatabaseField(columnName = "TASKCODE")
private String taskCode;
/** 任务名称 **/
@DatabaseField(columnName = "TASKNAME")
private String taskName;
/** 任务描述 **/
@DatabaseField(columnName = "TASKDESC")
private String taskDesc;
/** 日志级别 **/
@DatabaseField(columnName = "LogLevel")
private String logLevel;
/** 抓包标识 **/
@DatabaseField(columnName = "NetCapture")
private String netCapture;
/** 任务类型 **/
@DatabaseField(columnName = "TASKTYPE")
private String taskType;
/** 优先级 **/
@DatabaseField(columnName = "PRIORITY")
private Integer priority;
/** 计划开始时间 **/
@DatabaseField(columnName = "STARTDATE", dataType=DataType.DATE)
private Date startDate;
/** 计划结束时间 **/
@DatabaseField(columnName = "ENDDATE", dataType=DataType.DATE)
private Date endDate;
/** 执行类型:1:按时执行2:按次执行 **/
@DatabaseField(columnName = "ExeType")
private String exeType;
/** 任务开始执行时间,格式:HH24MISS **/
@DatabaseField(columnName = "ExeBeginTime")
private String exeBeginTime;
/** 任务结束执行时间,格式:HH24MISS **/
@DatabaseField(columnName = "ExeEndTime")
private String exeEndTime;
/** 重复类型:0:不限,1:每天,2:每周,3:每月,执行类型为2时,默认为0 **/
@DatabaseField(columnName = "IterationType")
private String iterationType;
/** 循环次数,执行类型为1时,表示具体每次重复类型必须循环次数,执行类型为2时,表示总次数 **/
@DatabaseField(columnName = "IterationNum")
private Integer iterationNum;
/** 间隔时间,单位分钟,0:没间隔,非0表示具体的间隔分钟数 **/
@DatabaseField(columnName = "IntervalVal")
private Integer interval;
/** 更新时间 **/
@DatabaseField(columnName = "LASTUPDATEDATE", dataType=DataType.DATE)
private Date lastUpdateDate;
/**
* 状态: 1-有效 /0-无效
*/
@DatabaseField(columnName = "STATUS")
private int status;
/**
* 判断结果是否完成: 1-完成 /0-未完成
*/
@DatabaseField(columnName = "JUDGERESULT")
private int judgeResult;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the taskCode
*/
public String getTaskCode() {
return taskCode;
}
/**
* @param taskCode the taskCode to set
*/
public void setTaskCode(String taskCode) {
this.taskCode = taskCode;
}
/**
* @return the taskName
*/
public String getTaskName() {
return taskName;
}
/**
* @param taskName the taskName to set
*/
public void setTaskName(String taskName) {
this.taskName = taskName;
}
/**
* @return the taskDesc
*/
public String getTaskDesc() {
return taskDesc;
}
/**
* @param taskDesc the taskDesc to set
*/
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
/**
* @return the logLevel
*/
public String getLogLevel() {
return logLevel;
}
/**
* @param logLevel the logLevel to set
*/
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
/**
* @return the netCapture
*/
public String getNetCapture() {
return netCapture;
}
/**
* @param netCapture the netCapture to set
*/
public void setNetCapture(String netCapture) {
this.netCapture = netCapture;
}
/**
* @return the taskType
*/
public String getTaskType() {
return taskType;
}
/**
* @param taskType the taskType to set
*/
public void setTaskType(String taskType) {
this.taskType = taskType;
}
/**
* @return the priority
*/
public Integer getPriority() {
return priority;
}
/**
* @param priority the priority to set
*/
public void setPriority(Integer priority) {
this.priority = priority;
}
/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* @return the endDate
*/
public Date getEndDate() {
return endDate;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* @return the exeType
*/
public String getExeType() {
return exeType;
}
/**
* @param exeType the exeType to set
*/
public void setExeType(String exeType) {
this.exeType = exeType;
}
/**
* @return the exeBeginTime
*/
public String getExeBeginTime() {
return exeBeginTime;
}
/**
* @param exeBeginTime the exeBeginTime to set
*/
public void setExeBeginTime(String exeBeginTime) {
this.exeBeginTime = exeBeginTime;
}
/**
* @return the exeEndTime
*/
public String getExeEndTime() {
return exeEndTime;
}
/**
* @param exeEndTime the exeEndTime to set
*/
public void setExeEndTime(String exeEndTime) {
this.exeEndTime = exeEndTime;
}
/**
* @return the iterationType
*/
public String getIterationType() {
return iterationType;
}
/**
* @param iterationType the iterationType to set
*/
public void setIterationType(String iterationType) {
this.iterationType = iterationType;
}
/**
* @return the iterationNum
*/
public Integer getIterationNum() {
return iterationNum;
}
/**
* @param iterationNum the iterationNum to set
*/
public void setIterationNum(Integer iterationNum) {
this.iterationNum = iterationNum;
}
/**
* @return the interval
*/
public Integer getInterval() {
return interval;
}
/**
* @param interval the interval to set
*/
public void setInterval(Integer interval) {
this.interval = interval;
}
/**
* @return the lastUpdateDate
*/
public Date getLastUpdateDate() {
return lastUpdateDate;
}
/**
* @param lastUpdateDate the lastUpdateDate to set
*/
public void setLastUpdateDate(Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getJudgeResult() {
return judgeResult;
}
public void setJudgeResult(int judgeResult) {
this.judgeResult = judgeResult;
}
}
| true
|
f587ecdd81a7c9a8b13b0baccb4b41dbba9ba215
|
Java
|
Gemuesebau/GSEHEN
|
/eclipse-workspace/GSEHEN/src/main/java/de/hgu/gsehen/model/Messages.java
|
UTF-8
| 866
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package de.hgu.gsehen.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Messages {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String key;
private String localeId;
private String text;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getLocaleId() {
return localeId;
}
public void setLocaleId(String localeId) {
this.localeId = localeId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| true
|
92bebbfa7b98d7c3696d20b4dd05687fb435cf4e
|
Java
|
LiuYongxin1995/FlinkDemo
|
/src/main/java/FlinkWarnByKey.java
|
UTF-8
| 4,431
| 2.3125
| 2
|
[] |
no_license
|
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple11;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.*;
public class FlinkWarnByKey {
public static Logger logger2 = LoggerFactory.getLogger(FlinkWarnByKey.class);
public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static List<AlarmRule> ruleList = new ArrayList<AlarmRule>();
public static Date date1 = new Date();
public static boolean flag = false;
public static void main(String[] args) {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
Properties props = PropUtil.loadProperties("/config.properties");
Properties topicProp = PropUtil.loadProperties("/topic.properties");
String topicString = topicProp.getProperty("topic");
logger2.info("topic=" + topicString);
DataStreamSource<String> source = env.addSource(
new FlinkKafkaConsumer<String>(topicString, new SimpleStringSchema(), props));
source.setParallelism(3);
DataStream<Tuple11<String, String, String, String, String, String, String, String, String, String, String>> WarringMessage = source.map(new MapFunction<String, Tuple11<String, String, String, String, String, String, String, String, String, String, String>>() {
public Tuple11<String, String, String, String, String, String, String, String, String, String, String> map(String s) throws Exception {
if (!flag) {
ruleList = DBUtil.queryAlarmTable();
flag = true;
}
if (s != null && !"".equals(s)) {
String[] arrayString = StringUtils.splitByWholeSeparator(s, "(!@#$%)");
int length = arrayString.length;
Date date2 = new Date();
if (date2.getTime() - date1.getTime() > 1000 * 120) {
date1 = date2;
ruleList.addAll(DBUtil.queryAlarmTable());
}
if (length == 4) {
String message = arrayString[2];
String deviceIp = arrayString[0];
for (AlarmRule alarmRule : ruleList) {
String keyword = alarmRule.getKeyword();
if (message.indexOf(keyword) >= 0) {
String eventid = UUID.randomUUID().toString();
String eventtype = "LOG.APP";
String level = alarmRule.getLevel();
String content = alarmRule.getDescription();
Date date = new Date();
String time = format.format(date.getTime());
String processstatus = "0";
String eventstatus = "1";
String lasttime = time;
String eventtypeall = "LOG";
String isInsert = "0";
return new Tuple11<String, String, String, String, String, String, String, String, String, String, String>(eventid, eventtype
, level, content, time, deviceIp, processstatus, eventstatus, lasttime, eventtypeall, isInsert);
}
}
}
}
return new Tuple11<String, String, String, String, String, String, String, String, String, String, String>("", ""
, "", "", "", "", "", "", "", "", "1");
}
});
//WarringMessage.addSink(new MysqlSink());
try {
env.execute("data to mysql start");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
9d479ee9625cb49ce60ab0b2ce8b1928449110e8
|
Java
|
andreisavu/jclouds
|
/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionList.java
|
UTF-8
| 7,977
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.abiquo.domain.enterprise;
import static com.google.common.collect.Iterables.filter;
import java.util.List;
import org.jclouds.abiquo.AbiquoAsyncApi;
import org.jclouds.abiquo.AbiquoApi;
import org.jclouds.abiquo.domain.DomainWrapper;
import org.jclouds.abiquo.domain.infrastructure.Datacenter;
import org.jclouds.rest.RestContext;
import com.abiquo.am.model.TemplatesStateDto;
import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
/**
* Adds high level functionality to {@link TemplateDefinitionListDto}. A
* Template Definition List provides a way to organize multiple Template
* Definitions. A single Template Definition can be shared by many lists. Its
* compatible with ovfindex.xml format.
*
* @author Ignasi Barrera
* @author Francesc Montserrat
*/
public class TemplateDefinitionList extends DomainWrapper<TemplateDefinitionListDto> {
/** The enterprise where the list belongs. */
private Enterprise enterprise;
/**
* Constructor to be used only by the builder.
*/
protected TemplateDefinitionList(final RestContext<AbiquoApi, AbiquoAsyncApi> context,
final TemplateDefinitionListDto target) {
super(context, target);
}
// Domain operations
/**
* Delete the template definition list. Deleting the list doesn't delete the
* containing Template Definitions.
*
* @see API: <a href=
* "http://community.abiquo.com/display/ABI20/TemplateDefinitionListResource#TemplateDefinitionListResource-Deleteatemplatedefinitionlist"
* > http://community.abiquo.com/display/ABI20/
* TemplateDefinitionListResource#
* TemplateDefinitionListResource-Deleteatemplatedefinitionlist</a>
*/
public void delete() {
context.getApi().getEnterpriseApi().deleteTemplateDefinitionList(target);
target = null;
}
/**
* Create a template definition list. All the contained Template Definitions
* will also be created.
*
* @see API: <a href=
* "http://community.abiquo.com/display/ABI20/TemplateDefinitionListResource#TemplateDefinitionListResource-Createatemplatedefinitionlist"
* > http://community.abiquo.com/display/ABI20/
* TemplateDefinitionListResource#
* TemplateDefinitionListResource-Createatemplatedefinitionlistr</a>
*/
public void save() {
target = context.getApi().getEnterpriseApi().createTemplateDefinitionList(enterprise.unwrap(), target);
}
/**
* Update a template definition list with the data from this template
* definition list.
*
* @see API: <a href=
* "http://community.abiquo.com/display/ABI20/TemplateDefinitionListResource#TemplateDefinitionListResource-Modifyatemplatedefinitionlist"
* > http://community.abiquo.com/display/ABI20/
* TemplateDefinitionListResource#
* TemplateDefinitionListResource-Modifyatemplatedefinitionlist</a>
*/
public void update() {
target = context.getApi().getEnterpriseApi().updateTemplateDefinitionList(target);
}
// Children access
/**
* Retrieve the list of states of the templates in the template definition
* list in the repository of the given datacenter. Template Definition are
* available sources, but in order to create a Virtual Machine the Definition
* should be downloaded into the Datacenter Repository (NFS filesystem).
*
* @param The
* datacenter in which repository search.
* @see API: <a href=
* "http://community.abiquo.com/display/ABI20/TemplateDefinitionListResource#TemplateDefinitionListResource-Retrievealistofthestatusofalltemplatestatuslist"
* > http://community.abiquo.com/display/ABI20/
* TemplateDefinitionListResource# TemplateDefinitionListResource-
* Retrievealistofthestatusofalltemplatestatuslist</a>
*/
public List<TemplateState> listStatus(final Datacenter datacenter) {
TemplatesStateDto states = context.getApi().getEnterpriseApi()
.listTemplateListStatus(target, datacenter.unwrap());
return wrap(context, TemplateState.class, states.getCollection());
}
/**
* Retrieve a filtered list of states of the templates in the template
* definition list in the repository of the given datacenter. Template
* Definition are available sources, but in order to create a Virtual Machine
* the Definition should be downloaded into the Datacenter Repository (NFS
* filesystem).
*
* @param filter
* Filter to be applied to the list.
* @param The
* datacenter in which repository search.
* @see API: <a href=
* "http://community.abiquo.com/display/ABI20/TemplateDefinitionListResource#TemplateDefinitionListResource-Retrievealistofthestatusofalltemplatestatuslist"
* > http://community.abiquo.com/display/ABI20/
* TemplateDefinitionListResource# TemplateDefinitionListResource-
* Retrievealistofthestatusofalltemplatestatuslist</a>
*/
public List<TemplateState> listStatus(final Predicate<TemplateState> filter, final Datacenter datacenter) {
return Lists.newLinkedList(filter(listStatus(datacenter), filter));
}
// Builder
public static Builder builder(final RestContext<AbiquoApi, AbiquoAsyncApi> context, final Enterprise enterprise) {
return new Builder(context, enterprise);
}
public static class Builder {
private RestContext<AbiquoApi, AbiquoAsyncApi> context;
private Enterprise enterprise;
private String name;
private String url;
public Builder(final RestContext<AbiquoApi, AbiquoAsyncApi> context, final Enterprise enterprise) {
super();
this.context = context;
this.enterprise = enterprise;
}
public Builder name(final String name) {
this.name = name;
return this;
}
public Builder url(final String url) {
this.url = url;
return this;
}
public TemplateDefinitionList build() {
TemplateDefinitionListDto dto = new TemplateDefinitionListDto();
dto.setName(name);
dto.setUrl(url);
TemplateDefinitionList templateList = new TemplateDefinitionList(context, dto);
templateList.enterprise = enterprise;
return templateList;
}
public static Builder fromTemplateDefinitionList(final TemplateDefinitionList in) {
return TemplateDefinitionList.builder(in.context, in.enterprise).name(in.getName()).url(in.getUrl());
}
}
// Delegate methods
public Integer getId() {
return target.getId();
}
public String getName() {
return target.getName();
}
public String getUrl() {
return target.getUrl();
}
public void setName(final String name) {
target.setName(name);
}
public void setUrl(final String url) {
target.setUrl(url);
}
@Override
public String toString() {
return "TemplateDefinitionList [getId()=" + getId() + ", getName()=" + getName() + ", getUrl()=" + getUrl() + "]";
}
}
| true
|
21ed016ed1359dbf83be22db6ae04ba19cdab746
|
Java
|
Biblivre/Biblivre-4
|
/src/java/biblivre/administration/indexing/IndexingDTO.java
|
UTF-8
| 3,063
| 2.015625
| 2
|
[] |
no_license
|
/*******************************************************************************
* Este arquivo é parte do Biblivre4.
*
* Biblivre4 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Este programa é distribuído na esperança de que possa ser útil,
* mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
* MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
*
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto
* com este programa, Se não, veja em <http://www.gnu.org/licenses/>.
*
* @author Alberto Wagner <alberto@biblivre.org.br>
* @author Danniel Willian <danniel@biblivre.org.br>
******************************************************************************/
package biblivre.administration.indexing;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import org.apache.commons.lang3.StringUtils;
import biblivre.core.AbstractDTO;
public class IndexingDTO extends AbstractDTO {
private static final long serialVersionUID = 1L;
private Integer recordId;
private Integer indexingGroupId;
private StringBuilder phrase;
private HashMap<Integer, HashSet<String>> words;
private int ignoreCharsCount;
public IndexingDTO() {
this.words = new HashMap<Integer, HashSet<String>>();
this.phrase = new StringBuilder();
this.ignoreCharsCount = 0;
}
public Integer getRecordId() {
return this.recordId;
}
public void setRecordId(Integer recordId) {
this.recordId = recordId;
}
public Integer getIndexingGroupId() {
return this.indexingGroupId;
}
public void setIndexingGroupId(Integer indexingGroupId) {
this.indexingGroupId = indexingGroupId;
}
public int getIgnoreCharsCount() {
return this.ignoreCharsCount;
}
public void setIgnoreCharsCount(int ignoreCharsCount) {
this.ignoreCharsCount = ignoreCharsCount;
}
public String getPhrase() {
String phrase = this.phrase.toString();
if (StringUtils.isBlank(phrase)) {
return null;
}
return phrase.trim();
}
public int getPhraseLength() {
return this.phrase.length();
}
public void appendToPhrase(String phrase) {
if (phrase == null) {
return;
}
this.phrase.append(" ").append(phrase.trim());
}
public void addWord(String word, Integer datafieldId) {
if (StringUtils.isNotBlank(word)) {
if (!this.words.containsKey(datafieldId)) {
this.words.put(datafieldId, new HashSet<String>());
}
this.words.get(datafieldId).add(word);
}
}
public void addWords(String[] words, Integer datafieldId) {
if (!this.words.containsKey(datafieldId)) {
this.words.put(datafieldId, new HashSet<String>());
}
Collections.addAll(this.words.get(datafieldId), words);
}
public HashMap<Integer, HashSet<String>> getWords() {
return this.words;
}
public int getCount() {
return this.words.size();
}
}
| true
|
376e96182375be41ce761467c0ec95250cd37f94
|
Java
|
Fynoli/TurismoTierraMediaWeb
|
/src/controllers/TipoAtraccionActualizar.java
|
UTF-8
| 2,148
| 2.203125
| 2
|
[] |
no_license
|
package controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.TipoAtraccionDao;
import dao.UsuarioDao;
import models.TipoAtraccion;
import models.Usuario;
/**
* Servlet implementation class TipoAtraccionActualizar
*/
@WebServlet("/tipoatraccionactualizar")
public class TipoAtraccionActualizar extends HttpServlet {
private static final long serialVersionUID = 1L;
private TipoAtraccionDao aD;
private UsuarioDao uD;
TipoAtraccion tipoModificar = new TipoAtraccion();
/**
* @see HttpServlet#HttpServlet()
*/
public TipoAtraccionActualizar() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
aD = new TipoAtraccionDao();
uD = new UsuarioDao();
Usuario usuario = uD.getUno((Integer) request.getSession().getAttribute("usuarioId"));
if(usuario.getEsadmin()==1) {
tipoModificar = aD.getUno(Integer.parseInt(request.getParameter("id")));
request.setAttribute("tipo", tipoModificar);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/tipoatraccion_crear.jsp");
dispatcher.forward(request, response);
}else {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/no_permitido.jsp");
dispatcher.forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
aD = new TipoAtraccionDao();
Integer tId = tipoModificar.getId();
System.out.println("Flor" + tId);
String nombre = (String) request.getParameter("nombre");
tipoModificar.setNombre(nombre);
aD.update(tipoModificar);
RequestDispatcher dispatcher = request.getRequestDispatcher("tipoatraccionlist");
dispatcher.forward(request, response);
}
}
| true
|
005373edd5963b4f3cc9f0a7478708930845ed72
|
Java
|
Queatz/snappy
|
/village-follower/src/main/java/com/village/things/FollowerMine.java
|
UTF-8
| 1,665
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.village.things;
import com.google.common.collect.ImmutableMap;
import com.queatz.earth.EarthField;
import com.queatz.earth.EarthKind;
import com.queatz.earth.EarthStore;
import com.queatz.earth.EarthThing;
import com.queatz.snappy.as.EarthAs;
import com.queatz.snappy.as.EarthControl;
import com.queatz.snappy.plugins.FollowerMinePlugin;
import java.util.List;
/**
* Created by jacob on 5/14/16.
*/
public class FollowerMine extends EarthControl implements FollowerMinePlugin {
public FollowerMine(final EarthAs as) {
super(as);
}
@Override
public EarthThing getFollower(EarthThing person, EarthThing isFollowingPerson) {
List<EarthThing> result = use(EarthStore.class).query(
"x." + EarthField.KIND + " == @kind and " +
"x." + EarthField.SOURCE + " == @source_key and " +
"x." + EarthField.TARGET + " == @target_key",
ImmutableMap.<String, Object>of(
"kind", EarthKind.FOLLOWER_KIND,
"source_key", person.key().name(),
"target_key", isFollowingPerson.key().name()
), 1);
if (result.isEmpty()) {
return null;
} else {
return result.get(0);
}
}
@Override
public int countFollowers(EarthThing entity) {
return use(EarthStore.class).count(EarthKind.FOLLOWER_KIND, EarthField.TARGET, entity.key());
}
@Override
public int countFollowing(EarthThing entity) {
return use(EarthStore.class).count(EarthKind.FOLLOWER_KIND, EarthField.SOURCE, entity.key());
}
}
| true
|
8778b9d80d2d9189340281aea2f0a218e9fda23d
|
Java
|
qiuchili/ggnn_graph_classification
|
/program_data/JavaProgramData/98/2346.java
|
UTF-8
| 936
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
package <missing>;
public class GlobalMembers
{
public static int Main()
{
int n;
String tempVar = ConsoleInput.scanfRead();
if (tempVar != null)
{
n = Integer.parseInt(tempVar);
}
char[][] word = new char[n][20];
int i;
int sum = 0;
String tempVar2 = ConsoleInput.scanfRead();
if (tempVar2 != null)
{
word[0] = tempVar2.charAt(0);
}
sum += String.valueOf(word[0]).length() + 1;
for (i = 1;i < n;i++)
{
String tempVar3 = ConsoleInput.scanfRead();
if (tempVar3 != null)
{
word[i] = tempVar3.charAt(0);
}
sum += String.valueOf(word[i]).length();
if (sum > 80)
{
System.out.printf("%s\n",word[i - 1]);
sum = String.valueOf(word[i]).length() + 1;
}
else
{
System.out.printf("%s ",word[i - 1]);
sum += 1;
}
}
System.out.printf("%s",word[n - 1]);
}
}
| true
|
b4df5b96d70d14d3de89197f69fdb170f710f212
|
Java
|
xinil502/LearnJava
|
/src/netWorkProgram/UDPNetWork/UDP_3_Objcet_Server.java
|
UTF-8
| 1,560
| 3.28125
| 3
|
[] |
no_license
|
package netWorkProgram.UDPNetWork;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 服务端
*/
public class UDP_3_Objcet_Server {
public static void main(String[] args) throws Exception{
System.out.println("接收端启动中。");
// 1.使用DatagramSocket指定端口,创建接收端。
DatagramSocket server = new DatagramSocket(9999);
// 2.准备容器,封装成DatagramPacket包裹。
byte[] container = new byte[1024*60]; //最多60k
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
// 3.阻塞式接收包裹 receive(DatagramPacket p)。
server.receive(packet);
// 4.分析数据
byte[] datas = packet.getData();
int length = datas.length; //或者 int length = packet.getLength();
//顺序与写入时一致。
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
Person p = (Person) ois.readObject();
double a = ois.readDouble();
int b = ois.readInt();
String c = ois.readUTF();
char d = ois.readChar();
boolean e = ois.readBoolean();
System.out.println(p.name + " + " + p.age);
System.out.println(a + "--" + b + "--"+ c + "--" + d + "--" + e);
//5.释放资源
server.close();
ois.close();
}
}
| true
|
e1feefcabf3534e0db6535144cff37b752e3ee99
|
Java
|
dan323/raytracing
|
/imaging/src/test/java/com/dan/geometry/phong/texture/test/LightTest.java
|
UTF-8
| 1,517
| 2.5625
| 3
|
[] |
no_license
|
package com.dan.geometry.phong.texture.test;
import com.dan.geometry.objects.Sphere;
import com.dan.geometry.phong.light.Ambient;
import com.dan.geometry.phong.light.ParallelLight;
import com.dan.geometry.phong.light.PointLight;
import com.dan.geometry.phong.material.Color;
import com.dan.geometry.utils.Point;
import com.dan.geometry.utils.Vector;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LightTest {
private final static Point ORIGIN = new Point(0, 0, 0);
private final static Sphere SPHERE = new Sphere(ORIGIN, Math.sqrt(3));
private final static Point POINT_IN_SPHERE = new Point(1, 1, 1);
private final static Vector vector = new Vector(1, 1, 1);
@Test
public void lightPointTest() {
PointLight pointLight = new PointLight(ORIGIN, Color.RED, 3);
Vector vec = pointLight.getDirectionFromPoint(POINT_IN_SPHERE, SPHERE);
Assertions.assertEquals(vector.normalize().scale(-1), vec);
}
@Test
public void lightParallelTest() {
ParallelLight parallelLight = new ParallelLight(Color.ORANGE, vector, 3);
Vector vec = parallelLight.getDirectionFromPoint(POINT_IN_SPHERE, SPHERE);
Assertions.assertEquals(vector.normalize().scale(-1),vec);
}
@Test
public void ambientTest() {
Ambient ambient = new Ambient(Color.BLUE, 3);
Vector vec = ambient.getDirectionFromPoint(POINT_IN_SPHERE, SPHERE);
Assertions.assertEquals(vector.normalize(),vec);
}
}
| true
|
2aaaec850789e5f73b10d7cc89a45f0bf70b6bb3
|
Java
|
searleja/Family-History-Map-Server
|
/shared/src/Results/ClearResult.java
|
UTF-8
| 550
| 2.96875
| 3
|
[] |
no_license
|
package Results;
public class ClearResult {
private String message;
private boolean success;
/**
* Constructor for ClearResult. Stores the message to be output.
* @param message
*/
public ClearResult(String message) {
this.message=message;
success = false;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message=message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success=success;
}
}
| true
|
32917ae1c3de068aba0dc7e26588795fc2f30915
|
Java
|
ahmedshehab123/Spring-Mvc-Ticketing-and-Booking-App
|
/src/main/java/com/event/controller/FriendsController.java
|
UTF-8
| 2,723
| 2.109375
| 2
|
[] |
no_license
|
package com.event.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.event.model.Friends;
import com.event.model.Judges;
import com.event.model.User;
import com.event.services.FriendsServices;
import com.event.services.JudgeServices;
@Controller
public class FriendsController {
@Autowired
FriendsServices friendservices;
@Autowired
JudgeServices judgeServices;
@RequestMapping(value = "/saveFriends", method = RequestMethod.POST)
public String saveFreinds(@ModelAttribute("friends") Friends friends, @RequestParam String userID,
@RequestParam String friendEmail) {
friendservices.saveFreinds(friends);
return "redirect:dipalyFriends";
}
@RequestMapping(value = "/dipalyFriends", method = RequestMethod.GET)
public String dipalyFreinds(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("userlogin");
List<Friends> friends = friendservices.getfriends(user.getId());
request.setAttribute("friends", friends);
return "friends";
}
@RequestMapping(value="/deleteFriend", method=RequestMethod.POST)
public String deleteFriend(@RequestParam String friendID){
System.out.println("!!!!!"+friendID);
friendservices.deleteFriend(friendID);
return "redirect:dipalyFriends";
}
@RequestMapping(value="/clearlist", method=RequestMethod.POST)
public String clearList(HttpServletRequest request){
User user=(User)request.getSession().getAttribute("userlogin");
friendservices.clearList(user.getId());
return "redirect:dipalyFriends";
}
@RequestMapping(value = "/sendfriendinvitation", method = RequestMethod.POST)
public String sendFriendsInvitation(@ModelAttribute("judge") Judges judge, HttpServletRequest request,
@RequestParam String eventID) {
User user = (User) request.getSession().getAttribute("userlogin");
List<Friends> friends = friendservices.getfriends(user.getId());
request.setAttribute("friends", friends);
for (Friends temp : friends) {
String toAddress = temp.getFriendEmail();
List<Judges> checkinvitation = judgeServices.checkJudgeInvitation(eventID, toAddress);
if (checkinvitation.isEmpty()) {
judge = friendservices.inviteFriendsList(toAddress, user.getEmail(), eventID);
judgeServices.saveJudgeInfo(judge);
}
}
return "redirect:displayevents";
}
}
| true
|
1d1588e3746360f13d626a9c6ae3cd13e3649cfd
|
Java
|
whuang8/weekly-coding-challenge
|
/week1/Tests.java
|
UTF-8
| 922
| 2.953125
| 3
|
[] |
no_license
|
import junit.framework.*;
public class Tests extends TestCase {
protected Node n;
protected void setUp() {
n = new Node(1);
}
public void testInsert() {
Node head = n.insert(n, 2);
assertEquals(head.data, 2);
assertEquals(head.next.data, 1);
}
public void testFind() {
Node head = n.insert(n, 2);
Node result = n.find(head, 1);
assertEquals(result.data, 1);
}
public void testFindFailure() {
Node head = n.insert(n, 2);
Node result = n.find(head, 5);
assertEquals(result, null);
}
public void testRemove() {
Node head = n.insert(n, 2);
head = n.insert(head, 3);
Node result = n.remove(head, 2);
assertEquals(result.data, 2);
assertEquals(head.next.data, 1);
}
public void testRemoveFailure() {
Node head = n.insert(n, 2);
head = n.insert(head, 3);
Node result = n.remove(head, 5);
assertEquals(result, null);
}
}
| true
|
6e6b4beb92b04ea3488b273465f5e9c16a89d748
|
Java
|
campues/AGRICOLA
|
/src/java/ModeloDao/ArchivoDao.java
|
UTF-8
| 4,475
| 2.46875
| 2
|
[] |
no_license
|
package ModeloDao;
import Control.Variables;
import Modelo.Archivo;
import config.Conexion;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class ArchivoDao {
//INSTANCIAS DEL LOS OBJETOS
Variables global = new Variables();
private Conexion con;
private Connection connection;
public ArchivoDao() {
}
public ArchivoDao(String jdbcURL, String jdbcUsername, String jdbcPassword) throws SQLException {
System.out.println(jdbcURL);
con = new Conexion(jdbcURL, jdbcUsername, jdbcPassword);
}
// listar todos Agricultores
public List<Archivo> listarArchivo() throws SQLException {
List<Archivo> listarAr = new ArrayList<Archivo>();
String sql = "SELECT * FROM archivo";
con.conectar();
connection = con.getJdbcConnection();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery(sql);
while (res.next()) {
int pk = res.getInt("pk_archivo");
String nom = res.getString("nomArchivo");
String tip = res.getString("tipo");
String rut = res.getString("ruta");
String fk = res.getString("fk_agricultord");
Archivo archivo = new Archivo(pk, nom, tip, rut, fk);
listarAr.add(archivo);
}
con.desconectar();
return listarAr;
}
// listar ID
public List<Archivo> listarArchivoID() throws SQLException {
List<Archivo> listarArID = new ArrayList<Archivo>();
String sql = "SELECT * FROM archivo WHERE fk_agricultord='" + global.idAgricultor + "' ";
con.conectar();
connection = con.getJdbcConnection();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery(sql);
while (res.next()) {
int pk = res.getInt("pk_archivo");
String nom = res.getString("nomArchivo");
String tip = res.getString("tipo");
String rut = res.getString("ruta");
String fk = res.getString("fk_agricultord");
Archivo archivo = new Archivo(pk, nom, tip, rut, fk);
listarArID.add(archivo);
}
con.desconectar();
return listarArID;
}
// Insertar Empleado
public boolean insertarArchivo(Archivo ar) throws SQLException {
String sql = "INSERT INTO archivo (nomArchivo,tipo,ruta,fk_agricultord)VALUES(?,?,?,?)";
System.out.println(ar.getNomArchivo());
con.conectar();
connection = con.getJdbcConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, ar.getNomArchivo());
statement.setString(2, ar.getTipo());
statement.setString(3, ar.getRuta());
statement.setString(4, ar.getFk_agricultord());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
con.desconectar();
return rowInserted;
}
// Obtener por PK
public Archivo obtenerPorId(int pk) throws SQLException {
Archivo archivo = null;
String sql = "SELECT * FROM archivo WHERE pk_archivo= ? ";
con.conectar();
connection = con.getJdbcConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, pk);
ResultSet res = statement.executeQuery();
if (res.next()) {
archivo = new Archivo(
res.getInt("pk_archivo"),
res.getString("nomArchivo"),
res.getString("tipo"),
res.getString("ruta"),
res.getString("fk_agricultord")
);
}
res.close();
con.desconectar();
return archivo;
}
//eliminar
public boolean eliminarArchivo(Archivo a) throws SQLException {
boolean rowEliminar = false;
String sql = "DELETE FROM archivo WHERE pk_archivo=?";
con.conectar();
connection = con.getJdbcConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, a.getPk_archivo());
rowEliminar = statement.executeUpdate() > 0;
statement.close();
con.desconectar();
return rowEliminar;
}
}
| true
|
22ab8b2dc573afad29850361e4d49d4e1068e66b
|
Java
|
jonkjenn/hiofcommutingclient
|
/HIOFCommuting/src/no/hiof/hiofcommuting/register/LoginFragment.java
|
UTF-8
| 4,776
| 2.28125
| 2
|
[] |
no_license
|
package no.hiof.hiofcommuting.register;
import java.net.HttpCookie;
import no.hiof.hiofcommuting.R;
import no.hiof.hiofcommuting.objects.User;
import no.hiof.hiofommuting.database.HandleLogin;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends Fragment {
TextView response;
protected int attempts = 5;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_login, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button login = (Button) getView().findViewById(R.id.loginButton);
(getView().findViewById(R.id.login_editText_email)).requestFocus();
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Henter brukerinput
String email = ((EditText) getView().findViewById(
R.id.login_editText_email)).getText().toString();
if(!email.contains("@"))
{
email = email + "@hiof.no";
}
String password = ((EditText) getView().findViewById(
R.id.login_editText_passord)).getText().toString();
validateUserInput(email, password);
}
});
HttpCookie c = HandleLogin.getCookie(getActivity());
if (c != null) {
new ValidateUser().execute(new String[] { "", "" });
} else {
Bundle e = getActivity().getIntent().getExtras();
if (e != null && e.containsKey("email")) {
new ValidateUser().execute(new String[] { e.getString("email"),
e.getString("password") });
}
}
}
public void validateUserInput(String email, String password) {
// Forbereder toast-melding
CharSequence toastMessage = null;
// Sjekker om brukeren har fyllt inn data
if (!email.isEmpty() && !password.isEmpty()) {
// Sjekker om brukeren har prøvd å logge inn med feil passord for
// mange ganger
if (attempts > 0) {
String[] userInput = { email, password };
new ValidateUser().execute(userInput);
} else {
toastMessage = "Glemt passord?";
}
} else {
toastMessage = "Fyll inn brukernavn og passord";
}
// Skriver ut toast om noe gikk galt
if (toastMessage != null) {
Context context = getActivity().getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, toastMessage, duration).show();
}
}
/**
*
* @author Martin Validerer brukerinput opp mot database. Kjøres i AsyncTask
* da dette er en tyngre oppgave.
*/
public class ValidateUser extends AsyncTask<String[], Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(getActivity());
private String errorMessage;
private User userLoggedIn;
@Override
protected void onPreExecute() {
Dialog.setMessage("Logger inn...");
Dialog.show();
}
@Override
protected Boolean doInBackground(String[]... params) {
// System.out.println("Validating");
String[] userInput = params[0];
String email = userInput[0];
String password = userInput[1];
Boolean authenticated = HandleLogin.checkUnAndPw(email, password,
getActivity());
if (HandleLogin.cookie != null) {
HandleLogin.saveCookie(HandleLogin.cookie, getActivity());
HandleLogin.cookie = null;
}
if (authenticated) {
userLoggedIn = HandleLogin.getCurrentEmailUserLoggedIn(email,
getActivity());
return true;
} else {
HandleLogin.deleteCookie(getActivity());
errorMessage = "Feil brukernavn eller passord. " + (--attempts)
+ " forsøk igjen.";
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
// ValiderBrukerFerdig(result);
Dialog.dismiss();
if (result) {
Intent intent = new Intent(getActivity(),
no.hiof.hiofcommuting.tab.TabListenerActivity.class);
intent.putExtra("CURRENT_USER", userLoggedIn);
Bundle e = getActivity().getIntent().getExtras();
if (e != null && e.containsKey("sender_id")) {
intent.putExtra("sender_id", e.getString("sender_id"));
intent.putExtra("sender_firstname",
e.getString("sender_firstname"));
intent.putExtra("sender_surname",
e.getString("sender_surname"));
}
startActivity(intent);
getActivity().finish();
} else {
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT)
.show();
}
}
}
}
| true
|
4f9632a46a357b261917688c6261bedea20f2b49
|
Java
|
soulofandroid/MVPApp
|
/app/src/main/java/com/myapp/presenter/BasePresenter.java
|
UTF-8
| 356
| 2.625
| 3
|
[] |
no_license
|
package com.myapp.presenter;
import java.lang.ref.WeakReference;
/**
* 解决内存泄漏
* @param <T>
*/
public class BasePresenter<T> {
protected WeakReference<T> mViewRef;
//进行绑定
public void attachView(T view){
mViewRef=new WeakReference<>(view);
}
//解绑
public void detachView(){
mViewRef.clear();
}
}
| true
|
f72bfc0e06a11995309441293f236d1c5219f812
|
Java
|
DPurp4/ateam99-Social-Network
|
/Person.java
|
UTF-8
| 2,177
| 3.21875
| 3
|
[] |
no_license
|
// ALL STUDENTS COMPLETE THESE SECTIONS
// Title: Social Network Visualizer Program
// Files: Person.java
// Semester: Autumn 2019
//
// ATeam members: Devin DuBeau, LEC 002, ddubeau@wisc.edu, dubeau
// Mihir Arora, LEC 001, mrarora@wisc.edu, marora
// Xiaoyuan Liu, LEC 001, xliu798@wisc.edu, xiaoyuanl
// Yuehan Qin, LEC 001, yqin43@wisc.edu, yuehan
// Reid Chen, LEC 001, ychen878@wisc.edu, reid
//
//////////////////// STUDENTS WHO GET HELP FROM OTHER THAN THEIR PARTNER //////
// must fully acknowledge and credit those sources of help.
// Instructors and TAs do not have to be credited here,
// but tutors, roommates, relatives, strangers, etc do.
//
// Persons: Identify persons by name, relationship to you, and email.
// Describe in detail the the ideas and help they provided.
//
// Online sources: avoid web searches to solve your problems, but if you do
// search, be sure to include Web URLs and description of
// of any information you find.
//////////////////////////// 80 columns wide //////////////////////////////////
import java.util.HashSet;
import java.util.Set;
/**
* Filename: Person.java
* Project: a3
*
* Person implementation
*/
public class Person {
private Set<Person> neighbors = new HashSet<>();// all the neighbors of the person
private String name;// name of the Person
private boolean visited;// whether the person is visited
/*
* Constructor
*/
public Person(String name) {
this.name = name;
}
/**
* get all the neighbors of a person
*
* @return a set containing all the neighbors of the person
*/
public Set<Person> neighbors() {
return this.neighbors;
}
/**
* get the name of a person
*
* @return name of the person
*/
public String name() {
return this.name;
}
/**
* set whether the person is visited
*
* @param whether the person is visited
*/
public void setVisited(boolean visited) {
this.visited = visited;
}
/**
* get whether the person is visited
*
* @return whether the person is visited
*/
public boolean getVisited() {
return visited;
}
}
| true
|
6855070c7a583f20ec0c8c378a1824ff375bf9ab
|
Java
|
Sale1996/Legal-QA-Bot
|
/Pravna_semanticki_projekat/question-answer-legaldoc/src/main/java/com/pravnainformatikasemantickiweb/questionanswerlegaldoc/sparqlQuestion/exceptions/SparqlQuestionNotFoundException.java
|
UTF-8
| 314
| 2.03125
| 2
|
[] |
no_license
|
package com.pravnainformatikasemantickiweb.questionanswerlegaldoc.sparqlQuestion.exceptions;
public class SparqlQuestionNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public SparqlQuestionNotFoundException(String message) {
super(message);
}
}
| true
|