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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
04894299c43be239c63599037a1872009092c81a | Java | arapaka/algorithms-datastructures | /algorithms/src/main/java/Facebook/LongestWordInDictionary.java | UTF-8 | 6,105 | 3.328125 | 3 | [
"MIT"
] | permissive | package Facebook;
import java.util.*;
/**
* Created by archithrapaka on 5/1/17.
*/
public class LongestWordInDictionary {
public static String findLongestWord(String s, List<String> d) {
if (null == d || d.size() == 0 || null == s || s.length() == 0) {
return "";
}
int max = -1;
Collections.sort(d);
boolean exist = false;
for (int i = 0; i < d.size(); i++) {
String word = d.get(i);
if (charMatch(s, word)) {
if (max == -1) {
max = i;
exist = true;
}
if (word.length() > d.get(max).length()) {
max = i;
}
}
}
if (!exist) {
return "";
}
return d.get(max);
}
// if the substring is of same length , then lexicographical substring comes first
public static String findLongestWord2(String s, List<String> d) {
if (null == d || d.size() == 0 || null == s || s.length() == 0) {
return "";
}
String longest = "";
for (int i = 0; i < d.size(); i++) {
String word = d.get(i);
if (charMatch(s, word)) {
if (word.length() > longest.length()) {
longest = word;
} else if (word.length() == longest.length()) {
if (word.compareTo(longest) < 0) {
longest = word;
}
}
}
}
return longest;
}
public static boolean charMatch(String s, String b) {
int i = 0;
int j = 0;
while (i < s.length() && j < b.length()) {
if (s.charAt(i) == b.charAt(j)) {
i++;
j++;
} else {
i++;
}
}
return j == b.length() ? true : false;
}
static class Word {
String word;
int index;
public Word(String word, int index) {
this.word = word;
this.index = index;
}
}
public static String findLongestWord3(String s, List<String> d) {
if (null == d || d.size() == 0 || null == s || s.length() == 0) {
return "";
}
String longest = "";
Word longestWord = new Word(longest, -1);
for (int i = 0; i < d.size(); i++) {
String word = d.get(i);
if (charMatch2(s, word) >= 0) {
int index = charMatch2(s, word);
Word current = new Word(word, index);
if (current.word.length() > longestWord.word.length()) {
longestWord = current;
} else if (word.length() == longestWord.word.length()) {
if (current.index < longestWord.index) {
longestWord = current;
}
}
}
}
return longestWord.word;
}
public static String findLongestWord4(String s, Map<String, Boolean> parts) {
if (null == parts || null == s || s.isEmpty()) {
return "";
}
String longest = "";
Word longestWord = new Word(longest, -1);
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
String word = s.substring(i, j + 1);
if (parts.containsKey(word)) {
int index = i;
Word current = new Word(word, i);
if (current.word.length() > longestWord.word.length()) {
longestWord = current;
} else if (word.length() == longestWord.word.length()) {
if (current.index < longestWord.index) {
longestWord = current;
}
}
}
}
}
return longestWord.word;
}
public static int charMatch2(String s, String sub) {
return s.indexOf(sub);
}
public static String findIndexOfSubstr(String s, String substr) {
int index = s.indexOf(substr);
if (index == -1) {
return "";
}
StringBuilder sb = new StringBuilder("");
sb.append(s.substring(0, index));
sb.append("[");
sb.append(s.substring(index, index + substr.length()));
sb.append("]");
sb.append(s.substring(index + substr.length()));
return sb.toString();
}
public static void main(String[] args) {
//String s = "aewfafwafjlwajflwajflwafj";
//List<String> list = Arrays.asList(new String[]{"apple","ewaf","awefawfwaf","awef","awefe","ewafeffewafewf"});
//System.out.println(findLongestWord2(s,list));
String[] parts = new String[]{
"d",
"i"};
String[] words = new String[]{
"coccidiosis",
"gules"};
String[] answers = new String[words.length];
HashMap<String, Boolean> map = new HashMap<>();
for (String part : parts) {
map.put(part, true);
}
int i = 0;
for (String word : words) {
String longest = findLongestWord4(word, map);
if (longest.isEmpty()) {
longest = word;
} else {
longest = findIndexOfSubstr(word, longest);
}
answers[i] = longest;
i++;
}
for (String answer : answers) {
System.out.print(answer + " ");
}
//int inde = findIndexOfSubstr("Melon","Mel");
//System.out.print(findIndexOfSubstr("WaterMelon","Mel"));
//System.out.println(findLongestWord2("establish",Arrays.asList(parts)));
//System.out.println("coccidiosis".indexOf("i"));
//System.out.println("coccidiosis".indexOf("d"));
String a = "50";
String b = "20";
//System.out.print(-1.0/0);
//System.out.print(a & !b);
}
}
| true |
334031d1347bdbcef50352f536d63e527c67dc16 | Java | cuonglnhust/AppChatRMI | /ChatGUI/src/rmi/client/ClientDriver.java | UTF-8 | 691 | 2.5625 | 3 | [] | no_license | package rmi.client;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import rmi.server.IServer;
public class ClientDriver {
public static void main(String[] args) throws NotBoundException, MalformedURLException, RemoteException {
// create a GUI
ClientUI clientUI = new ClientUI();
clientUI.setVisible(true);
String chatServerURL = "rmi://localhost/RMIChatServer";
IServer chatServer = (IServer) Naming.lookup(chatServerURL);
// Note that chatServer is IServer
clientUI.setServerBase(chatServer);
ClientImp chatClient = new ClientImp(clientUI.getUserName(), chatServer, clientUI);
}
}
| true |
6c5ab925283308a35ab197f69b9a2735d6a97328 | Java | yulin010203/finance | /src/com/finance/ui/bean/GLCJL.java | UTF-8 | 2,493 | 2.75 | 3 | [] | no_license | package com.finance.ui.bean;
import com.finance.ui.GLDisplay;
import com.jogamp.opengl.GL2;
/**
* 成交量
*
* @author Chen Lin 2015-11-2
*/
public class GLCJL {
/**
* 主图画布
*/
private GLDisplay display;
/**
* 颜色(true:红,false:绿)
*/
private boolean red = true;
/**
* 成交量
*/
private int dealVol;
/**
* 持仓量
*/
private int vol;
/**
* 成交量坐标
*/
private float dealf;
/**
* 持仓量坐标
*/
private float volf;
/**
* 横轴坐标
*/
private float x1, x2, x3;
/**
* 简化画法
*/
private boolean simple;
/**
* @param display
* @param dealVol
* @param vol
*/
public GLCJL(GLDisplay display, int dealVol, int vol) {
this.display = display;
this.dealVol = dealVol;
this.vol = vol;
}
/**
* @param dealVol
* @param vol
*/
public void refresh(int dealVol, int vol) {
this.dealVol = dealVol;
this.vol = vol;
}
/**
* @param x
* @param span
* @param deal
* @param mid
* @param del
* @param red
*/
public void refresh(float x, float span, int deal, float mid, float del, boolean red) {
this.simple = display.getSpan() < 2.0;
this.x1 = x - span / 2.0f;
this.x2 = x;
this.x3 = x + span / 2.0f;
this.dealf = 1.9f * dealVol / deal - 1.0f;
this.volf = (vol - mid) / del * 1.80f;
this.red = red;
}
/**
* 屏幕刷新
*
* @param gl2
*/
public void refresh(GL2 gl2) {
if (simple) {
if (red) {
gl2.glColor3f(0.7f, 0, 0);
} else {
// gl2.glColor3f(0.0f, 1.0f, 0.0f);
gl2.glColor3f(0.0f, 1.0f, 1.0f);
}
gl2.glBegin(GL2.GL_LINES);
gl2.glVertex2f(x2, -1.0f);
gl2.glVertex2f(x2, dealf);
gl2.glEnd();
} else {
if (red) {
gl2.glColor3f(0.7f, 0, 0);
gl2.glBegin(GL2.GL_LINE_STRIP);
gl2.glVertex2f(x1, -1.0f);
gl2.glVertex2f(x1, dealf);
gl2.glVertex2f(x3, dealf);
gl2.glVertex2f(x3, -1.0f);
gl2.glEnd();
} else {
// gl2.glColor3f(0.0f, 1.0f, 0.0f);
gl2.glColor3f(0.0f, 1.0f, 1.0f);
gl2.glBegin(GL2.GL_POLYGON);
gl2.glVertex2f(x1, -1.0f);
gl2.glVertex2f(x1, dealf);
gl2.glVertex2f(x3, dealf);
gl2.glVertex2f(x3, -1.0f);
gl2.glEnd();
}
}
}
/**
* 获取 xxx
*
* @return xxx
*/
public int getDealVol() {
return dealVol;
}
/**
* 获取 xxx
*
* @return xxx
*/
public int getVol() {
return vol;
}
/**
* 获取持仓量坐标
*
* @return
*/
public float[] getVolf() {
float[] v = { x2, volf };
return v;
}
}
| true |
8dc04fb1383a0714fc13931797eb89e602d99370 | Java | phamtuanchip/activity-portlet | /src/main/java/exo/social/portlet/package-info.java | UTF-8 | 1,372 | 1.609375 | 2 | [] | no_license | @Application
@Portlet
@Bindings({
@Binding(value = ActivityManager.class, implementation = GateInMetaProvider.class),
@Binding(value = IdentityManager.class, implementation = GateInMetaProvider.class),
@Binding(value = Identity.class, implementation = IdentityProvider.class)
})
@Assets(
scripts = {
@Script(id = "jquery", src = "js/jquery-1.7.1.min.js"),
@Script(src = "js/less-1.2.2.min.js", depends = "jquery"),
@Script(src = "js/bootstrap.js", depends = "jquery"),
@Script(src = "js/bootstrap-collapse.js", depends = "jquery"),
@Script(src = "js/bootstrap-tooltip.js", depends = "jquery"),
@Script(src = "js/bootstrap-popover.js", depends = "jquery"),
@Script(src = "js/activity.js", depends = "juzu.ajax")
},
stylesheets = {
@Stylesheet(src = "css/gatein.less")
}
)
package exo.social.portlet;
import exo.social.portlet.providers.GateInMetaProvider;
import exo.social.portlet.providers.IdentityProvider;
import org.exoplatform.social.core.identity.model.Identity;
import org.exoplatform.social.core.manager.ActivityManager;
import org.exoplatform.social.core.manager.IdentityManager;
import juzu.Application;
import juzu.plugin.asset.Assets;
import juzu.plugin.asset.Script;
import juzu.plugin.asset.Stylesheet;
import juzu.plugin.binding.Binding;
import juzu.plugin.binding.Bindings;
import juzu.plugin.portlet.Portlet; | true |
e59af7db8622a0ad8c6777e69436a265363180de | Java | wantoinpress/AndroidManagementSystem_FirstProject | /Newproject/app/src/main/java/zdfwuy/newproject/data_safeguard/SerializableMap.java | UTF-8 | 482 | 1.953125 | 2 | [] | no_license | package zdfwuy.newproject.data_safeguard;
import com.alibaba.fastjson.JSONArray;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ASUS on 2021/5/9.
*/
public class SerializableMap implements Serializable {
private Map<String,JSONArray> map;
public Map<String, JSONArray> getMap() {
return map;
}
public void setMap(HashMap<String, JSONArray> map) {
this.map = map;
}
}
| true |
527f2c2f46df8f0064a848196448c60be12abe25 | Java | JonathanGWesterfield/HighSchoolJava | /Student Files/Lab09 - for loops/Lab09DB.java | UTF-8 | 1,533 | 3.828125 | 4 | [] | no_license | //Jonathan Westerfield
import java.util.Scanner;
public class Lab09DB
{
private char firstlet;
private char seclet;
public static void main(String[] args)
{
Lab09DB lab = new Lab09DB();
lab.input();
lab.output();
}
public void input()
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter the first character: ");
firstlet = reader.next().charAt(0);
System.out.print("Enter the second character: ");
seclet = reader.next().charAt(0);
}
public void output()
{
if(firstlet < seclet)
{
int count = 0;
System.out.println();
System.out.print("The Alphabet from " + firstlet +
" to " + seclet + ": ");
for(char c = firstlet ; c <= seclet ; c++)
{
System.out.print(c +" ");
count++;
}
System.out.println();
System.out.println("There are " + count + " characters from "
+ firstlet + " to " + seclet + ".");
System.out.println();
}
else
{
int count = 0;
System.out.println();
System.out.print("The Alphabet from " + firstlet +
" to " + seclet + ": ");
for(char c = firstlet ; c >= seclet ; c--)
{
System.out.print(c + " ");
count++;
}
System.out.println();
System.out.println("There are " + count + " characters from "
+ firstlet + " to " + seclet + ".");
System.out.println();
}
}
}
| true |
15e62dc2f07730158294e63b9e022c305d7f928b | Java | 859162000/et-eds-java | /eds/entity/src/main/java/com/edaisong/entity/domain/ClienterStatus.java | UTF-8 | 3,169 | 2.296875 | 2 | [] | no_license | package com.edaisong.entity.domain;
/**
* C端用户状态
* @author CaoHeYang
* @date 20150911
*/
public class ClienterStatus {
private int userid ;
private int status ;
private String phoneno ;
private Double amount ;
private Double AllowWithdrawPrice ;
private int IsBind ;
private int IsOnlyShowBussinessTask ;
private int DeliveryCompanyId ;
private String DeliveryCompanyName ;
private int IsDisplay ;
private int WorkStatus ;
private int IsReceivePush ;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public Double getAllowWithdrawPrice() {
return AllowWithdrawPrice;
}
public void setAllowWithdrawPrice(Double allowWithdrawPrice) {
AllowWithdrawPrice = allowWithdrawPrice;
}
/**
* 是否绑定了商户(0:否 1:是)
* @return
*/
public int getIsBind() {
return IsBind;
}
/**
* 是否绑定了商户(0:否 1:是)
* @param isBind
*/
public void setIsBind(int isBind) {
IsBind = isBind;
}
/**
* 是否只显示雇主任务
* @return
*/
public int getIsOnlyShowBussinessTask() {
return IsOnlyShowBussinessTask;
}
/**
* 是否只显示雇主任务
* @param isOnlyShowBussinessTask
*/
public void setIsOnlyShowBussinessTask(int isOnlyShowBussinessTask) {
IsOnlyShowBussinessTask = isOnlyShowBussinessTask;
}
/**
* 配送公司Id
* @return
*/
public int getDeliveryCompanyId() {
return DeliveryCompanyId;
}
/**
* 配送公司Id
* @param deliveryCompanyId
*/
public void setDeliveryCompanyId(int deliveryCompanyId) {
DeliveryCompanyId = deliveryCompanyId;
}
/**
* 配送公司名称
* @return
*/
public String getDeliveryCompanyName() {
return DeliveryCompanyName;
}
/**
* 配送公司名称
* @param deliveryCompanyName
*/
public void setDeliveryCompanyName(String deliveryCompanyName) {
DeliveryCompanyName = deliveryCompanyName;
}
/**
* 是否显示 金额 0隐藏 1 显示
* @return
*/
public int getIsDisplay() {
return IsDisplay;
}
/**
* 是否显示 金额 0隐藏 1 显示
* @param isDisplay
*/
public void setIsDisplay(int isDisplay) {
IsDisplay = isDisplay;
}
/**
* 超人状态 0上班 1下班 默认为0
* @return
*/
public int getWorkStatus() {
return WorkStatus;
}
/**
* 超人状态 0上班 1下班 默认为0
* @param workStatus
*/
public void setWorkStatus(int workStatus) {
WorkStatus = workStatus;
}
/**
* 骑士是否接受推送 1 接口 0 不接受 默认1
* @return
*/
public int getIsReceivePush() {
return IsReceivePush;
}
/**
* 骑士是否接受推送 1 接口 0 不接受 默认1
* @param isReceivePush
*/
public void setIsReceivePush(int isReceivePush) {
IsReceivePush = isReceivePush;
}
}
| true |
3f815f5a0471c3ad2ed1ae38542883e158864d49 | Java | Banisultan/Miten-mobile | /app/src/main/java/id/bnn/convey/Adapter/ViewPhotoAdapter.java | UTF-8 | 3,805 | 2.046875 | 2 | [] | no_license | package id.bnn.convey.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.gms.vision.text.Line;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import id.bnn.convey.Model.PositionPhotoModel;
import id.bnn.convey.Model.ViewPhotoModel;
import id.bnn.convey.R;
public class ViewPhotoAdapter extends RecyclerView.Adapter<ViewPhotoAdapter.Holder>{
Context context;
List<ViewPhotoModel> list;
PositionPhotoAdapter adapterphoto;
List<PositionPhotoModel> listphoto;
int POSITION;
SharedPreferences datainputsurveyin;
SharedPreferences.Editor datainputsurveyin_edit;
public ViewPhotoAdapter(
Context context,
List<ViewPhotoModel> list,
PositionPhotoAdapter adapterphoto,
List<PositionPhotoModel> listphoto,
int POSITION
){
this.context = context;
this.list = list;
this.adapterphoto = adapterphoto;
this.listphoto = listphoto;
this.POSITION = POSITION;
datainputsurveyin = context.getSharedPreferences("datainputsurveyin", Context.MODE_PRIVATE);
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(context).inflate(R.layout.list_foto_v2, parent, false);
return new Holder(itemview);
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
Glide.with(context).load(list.get(position).getImage_file()).into(holder.imageview);
holder.textcount.setText(String.valueOf(position+1));
holder.tombolhapus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!listphoto.get(POSITION).getList_photo().get(position).getId_foto().equals("null")){
saveremovedata(listphoto.get(POSITION).getList_photo().get(position).getId_foto());
}
listphoto.get(POSITION).getList_photo().remove(position);
adapterphoto.notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class Holder extends RecyclerView.ViewHolder {
ImageView imageview;
TextView textcount;
LinearLayout tombolhapus;
public Holder(View itemview){
super(itemview);
imageview = itemview.findViewById(R.id.image);
textcount = itemview.findViewById(R.id.textcount);
tombolhapus = itemview.findViewById(R.id.tombolhapus);
}
}
public void saveremovedata(String idfoto){
String data = datainputsurveyin.getString("datahapusfoto", "[]");
try{
JSONArray dataarray = new JSONArray(data);
JSONObject datajson = new JSONObject();
datajson.put("id_foto", idfoto);
dataarray.put(dataarray.length(), datajson);
datainputsurveyin_edit = context.getSharedPreferences("datainputsurveyin", Context.MODE_PRIVATE).edit();
datainputsurveyin_edit.putString("datahapusfoto", String.valueOf(dataarray));
datainputsurveyin_edit.apply();
}catch (Exception e){
}
}
}
| true |
c1f7919e0cb875963cca1950cb533ae882f4ad93 | Java | htsondk251/Spring-Security | /ch2/ch2-ex1/src/main/java/com/example/ch2ex1/controller/HomeController.java | UTF-8 | 312 | 1.96875 | 2 | [] | no_license | package com.example.ch2ex1.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class HomeController {
@GetMapping(value="/hello")
public String Hello() {
return "Hello!";
}
}
| true |
fb9484184e910de89e630d576ec9f9a26a290699 | Java | bhegmanns/adventofcode | /adventofcode2018/src/main/java/de/hegmanns/adventofcode2018/day12/DefaultPlantStrategy.java | UTF-8 | 1,148 | 2.984375 | 3 | [] | no_license | package de.hegmanns.adventofcode2018.day12;
public class DefaultPlantStrategy implements PlantStrategy{
private boolean from;
private boolean firstLeft;
private boolean secondLeft;
private boolean firstRight;
private boolean secondRight;
private boolean results;
public DefaultPlantStrategy(boolean secondLeft, boolean firstLeft, boolean from, boolean firstRight, boolean secondRight, boolean results) {
this.secondLeft = secondLeft;
this.firstLeft = firstLeft;
this.firstRight = firstRight;
this.secondRight = secondRight;
this.from = from;
this.results = results;
}
@Override
public boolean doMatch(boolean secondLeft, boolean firstLeft, boolean from, boolean firstRight,
boolean secondRight) {
return secondLeft==this.secondLeft && firstLeft==this.firstLeft && from==this.from && firstRight==this.firstRight && secondRight==this.secondRight;
}
@Override
public Boolean resultFrom(boolean secondLeft, boolean firstLeft, boolean from, boolean firstRight,
boolean secondRight) {
if (!doMatch(secondLeft, firstLeft, from, firstRight, secondRight)) {
return null;
}else {
return results;
}
}
}
| true |
2fbe9105b39afd4e005c8da5a97776ba4e0b039d | Java | viktorvano/FFNN | /src/FFNN/Neuron.java | UTF-8 | 5,392 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | package FFNN;
import java.util.ArrayList;
import static FFNN.Variables.*;
import static FFNN.FileManagement.*;
import static FFNN.GeneralFunctions.*;
public class Neuron {
public Neuron(int numOutputs, int myIndex)
{
m_outputWeights = new ArrayList<Connection>();
m_outputWeights.clear();
for (int c = 0; c < numOutputs; c++)
{
m_outputWeights.add(new Connection());
m_outputWeights.get(m_outputWeights.size()-1).weight = randomWeight();
}
m_myIndex = myIndex;
}
public void setOutputValue(float value) { m_outputValue = value; }
public float getOutputValue() { return m_outputValue; }
public void feedForward(Layer prevLayer)
{
float sum = 0.0f;
// Sum the previous layer's outputs (which are inputs)
// Include the bias node from the previous layer.
for (int n = 0; n < prevLayer.size(); n++)
{
sum += prevLayer.get(n).getOutputValue() * prevLayer.get(n).m_outputWeights.get(m_myIndex).weight;
}
m_outputValue = Neuron.transferFunction(sum);
}
public void calcOutputGradients(float targetValue)
{
float delta = targetValue - m_outputValue;
m_gradient = delta * transferFunctionDerivative(m_outputValue);
}
public void calcHiddenGradients(Layer nextLayer)
{
float dow = sumDOW(nextLayer);
m_gradient = dow * transferFunctionDerivative(m_outputValue);
}
public void updateInputWeights(Layer prevLayer)
{
// The weights to updated are in the Connection container
// in the neurons in the preceding layer
for (int n = 0; n < prevLayer.size(); n++)
{
Neuron neuron = prevLayer.get(n);
float oldDeltaWeight = neuron.m_outputWeights.get(m_myIndex).deltaWeight;
float newDeltaWeight =
// Individual input, magnified by the gradient and train rate:
eta // 0.0==slowlearner; 0.2==medium learner; 1.0==reckless learner
* neuron.getOutputValue()
* m_gradient
// Also add momentum = a fraction of the previous delta weight
+ alpha // 0.0==no momentum; 0.5==moderate momentum
* oldDeltaWeight;
neuron.m_outputWeights.get(m_myIndex).deltaWeight = newDeltaWeight;
neuron.m_outputWeights.get(m_myIndex).weight += newDeltaWeight;
}
}
public void saveInputWeights(Layer prevLayer)
{
// The weights to updated are in the Connection container
// in the neurons in the preceding layer
for (int n = 0; n < prevLayer.size(); n++)
{
Neuron neuron = prevLayer.get(n);
weights.set(neuronIndex, neuron.m_outputWeights.get(m_myIndex).weight);
neuronIndex++;
}
if (neuronIndex == weights.size())
{
//save weights from Weights[] to a file
String strWeights = new String();
for (int index = 0; index < weights.size(); index++)
{
strWeights += (formatFloatToString12(weights.get(index)) + "\n");
}
writeToFile("res\\weights.txt", strWeights);
}
}
public void loadInputWeights(Layer prevLayer)
{
// The weights to updated are in the Connection container
// in the neurons in the preceding layer
//load weights from a file to Weights[]
ArrayList<String> fileContent = new ArrayList<>(readOrCreateFile("res\\weights.txt"));
if(fileContent.size()==0 || fileContent==null)
{
System.out.println("Cannot open weights.txt");
System.exit(-10);
}
for (int index = 0; index < weights.size(); index++)
{
if(fileContent.get(index).length()!=0)
{
weights.set(index, Float.parseFloat(fileContent.get(index)));
}
}
for (int n = 0; n < prevLayer.size(); n++)
{
Neuron neuron = prevLayer.get(n);
neuron.m_outputWeights.get(m_myIndex).weight = weights.get(neuronIndex);
neuronIndex++;
}
}
private static float eta = velocity; // [0.0..1.0] overall network training rate
private static float alpha = momentum; // [0.0..n] multiplier of last weight change (momentum)
private float sumDOW(Layer nextLayer)
{
float sum = 0.0f;
// Sum our contributions of the errors at the nodes we feed
for (int n = 0; n < nextLayer.size() - 1; n++)
{
sum += m_outputWeights.get(n).weight * nextLayer.get(n).m_gradient;
}
return sum;
}
private static float transferFunction(float x)
{
// tanh - output range [-1.0..1.0]
return (float)Math.tanh(x);
}
private float transferFunctionDerivative(float x)
{
// tanh derivative
return (float) (1.0f - (float)Math.pow(Math.tanh(x), 2.0));// approximation return 1.0 - x*x;
}
private float randomWeight()
{
return (float)Math.random() - 0.5f;
}
private float m_outputValue;
private ArrayList<Connection> m_outputWeights;
private int m_myIndex;
private float m_gradient;
}
| true |
73fb998c23b35f6b9ec126845553d7cbbccb2ad5 | Java | jeftom/ImageTRM | /src/main/java/com/sunyard/insurance/socket/bean/MetadataBean.java | UTF-8 | 479 | 1.921875 | 2 | [
"MIT"
] | permissive | package com.sunyard.insurance.socket.bean;
import java.io.Serializable;
public class MetadataBean implements Serializable {
private static final long serialVersionUID = 8928911725561237220L;
private String CODE;
private String VALUE;
public String getCODE() {
return CODE;
}
public void setCODE(String cODE) {
CODE = cODE;
}
public String getVALUE() {
return VALUE;
}
public void setVALUE(String vALUE) {
VALUE = vALUE;
}
}
| true |
0423f658016d4b7d5b93255c0889d2ce11fe335b | Java | deliaZang/qli | /server/src/main/java/edu/zut/cs/qli/utils/FileParseUtil.java | UTF-8 | 1,483 | 2.640625 | 3 | [] | no_license | package edu.zut.cs.qli.utils;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import java.io.File;
import java.io.InputStream;
/**
* Created by shouhutsh on 15-5-24.
*/
/**
* 处理PPT文件
*/
public class FileParseUtil {
public static String getPPTContent(String s) throws Exception {
return getPPTContent(new java.io.FileInputStream(s));
}
public static String getPPTContent(File f) throws Exception {
return getPPTContent(new java.io.FileInputStream(f));
}
// FIXME 我假设 ppt 文档的结构有 title ,而且我假设为 Text 的第一个元素,此假设可能错误
public static String getPPTContent(InputStream is) throws Exception {
StringBuffer content = new StringBuffer("");
SlideShow ss = new SlideShow(new HSLFSlideShow(is));
Slide[] slides = ss.getSlides();
for (int i = 0; i < slides.length; i++) {
content.append("<h1>"+slides[i].getTitle()+"</h1><br/>");
TextRun[] t = slides[i].getTextRuns();
if(! slides[i].getTitle().equals(t[0].getText())){
content.append("<pre>"+t[0].getText()+"</pre><br/>");
}
for (int j = 1; j < t.length; j++) {
content.append("<pre>"+t[j].getText()+"</pre><br/>");
}
}
return content.toString();
}
}
| true |
b2a2cde21af1c02bf5e13b9ef2e8ec192a33bd5d | Java | Jimmy93315/TestGit | /src/HelloWorld.java | UTF-8 | 809 | 3.4375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 100; i < 1000; i++)
{
int baiwei = i/100;
int shiwei = (i%100)/10;
int gewei = (i%100)%10;
if(i == baiwei*baiwei*baiwei+shiwei*shiwei*shiwei+gewei*gewei*gewei)
{
arr.add(i);
}
}
int count = 0;
if(arr.size() != 0)
{
for(int i = 0 ; i< arr.size(); i++)
{
count = count+arr.get(i);
System.out.println("第"+(i+1)+"个水仙花数: "+arr.get(i).toString());
}
System.out.println("水仙花数总和为: "+count);
}
}
}
| true |
6173adb8f66d1ffe174f9dd1e6cc7a5270e7d4ce | Java | ChristianGalindo10/ProyectoFinalModelos | /src/estructurales/proxy/RealEspecificacion.java | UTF-8 | 913 | 2.625 | 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 estructurales.proxy;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
*
* @author Christian Galindo
*/
public class RealEspecificacion implements Especificacion {
@Override
public void dibuja(ImageIcon i) {
ImageIcon img = i;
Image escalada = img.getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT);
ImageIcon imgesc = new ImageIcon(escalada);
JOptionPane.showMessageDialog(null, null, "Previsualizacion",
JOptionPane.INFORMATION_MESSAGE,carga(imgesc));
}
@Override
public void click(ImageIcon i) {
}
public ImageIcon carga(ImageIcon i) {
ImageIcon icono = i;
return icono;
}
}
| true |
efe22f1d3ef0c2012c232c63f94b95763d1a7900 | Java | Haileyhm/Java_git | /Project0325/LecPrac2.java | UTF-8 | 225 | 2.65625 | 3 | [] | no_license |
public class LecPrac2 { //얘는 void main 용 클래스
public static void main(String[] args) {
LecPrac lecprac = new LecPrac();
lecprac.makeSum(1,100);
lecprac.makeSum(20,200);
lecprac.makeSum(30,300);
}
}
| true |
dbbe8506c888afe4ce71f58ea03bc3887d4b5127 | Java | min-juice/SpringWebProject | /SpringWebsiteProject/src/main/java/kr/co/domain/ReplyVO.java | UTF-8 | 1,057 | 2.078125 | 2 | [] | no_license | package kr.co.domain;
import java.util.Date;
public class ReplyVO {
/* gdsNum number not null,
memId varchar2(50) not null,
repNum number not null,
repCon varchar2(2000) not null,
repDate date default sysdate,
*/
private int gdsNum;
private String memId;
private int repNum;
private String repCon;
private Date repDate;
public ReplyVO() {
// TODO Auto-generated constructor stub
}
public int getGdsNum() {
return gdsNum;
}
public void setGdsNum(int gdsNum) {
this.gdsNum = gdsNum;
}
public String getMemId() {
return memId;
}
public void setMemId(String memId) {
this.memId = memId;
}
public int getRepNum() {
return repNum;
}
public void setRepNum(int repNum) {
this.repNum = repNum;
}
public String getRepCon() {
return repCon;
}
public void setRepCon(String repCon) {
this.repCon = repCon;
}
public Date getRepDate() {
return repDate;
}
public void setRepDate(Date repDate) {
this.repDate = repDate;
}
}
| true |
b128e64fb6b3ec088a83cb89543547a68e41a81b | Java | kwangkim/GeogebraiOS | /GeogebraiOS/javasources/org/geogebra/common/geogebra3D/euclidian3D/plots/DynamicMeshTriList2.java | UTF-8 | 2,136 | 2.671875 | 3 | [] | no_license | package org.geogebra.common.geogebra3D.euclidian3D.plots;
import org.geogebra.common.geogebra3D.euclidian3D.plots.java.nio.FloatBuffer;
/**
* A triangle list for dynamic meshes
*
* @author Andre Eriksson
*/
public interface DynamicMeshTriList2 {
/**
* @param e
* the element to add
*/
abstract public void add(DynamicMeshElement2 e);
/**
* @param e
* the element to add
* @param i
* triangle index (used for surfaces)
*/
abstract public void add(DynamicMeshElement2 e, int i);
/**
* @param e
* the element to remove
* @return true if the element was removed, otherwise false
*/
abstract public boolean remove(DynamicMeshElement2 e);
/**
* @param e
* the element to remove
* @param i
* triangle index (used for surfaces)
* @return true if the element was removed, otherwise false
*/
abstract public boolean remove(DynamicMeshElement2 e, int i);
/**
* @param t
* the element to attempt to hide
* @return true if the element was hidden, otherwise false
*/
abstract public boolean hide(DynamicMeshElement2 t);
/**
* @param t
* the element to attempt to show
* @return true if the element was shown, otherwise false
*/
abstract public boolean show(DynamicMeshElement2 t);
/**
* Reevaluates vertices, error, etc. for all elements in the list.
*
* @param currentVersion
* current mesh version
*/
public void recalculate(int currentVersion);
/**
* Reinserts an element into the list - used when an element is updated
*
* @param a
* element to reinsert
* @param version
* current version of the mesh
*/
abstract void reinsert(DynamicMeshElement2 a, int version);
/**
* @return the triangle buffer
*/
public abstract FloatBuffer getTriangleBuffer();
/**
* @return the float buffer
*/
public abstract FloatBuffer getNormalBuffer();
/**
* @return number of triangles in the list
*/
public abstract int getTriAmt();
/**
* @return number of chunks in the list
*/
public abstract int getChunkAmt();
}
| true |
62229b37822b0f3f37a5dbf2653ed8e6b4c74b1d | Java | mikaelsn/miniohtu | /src/main/java/ohtu/miniohtu/exceptions/NoShorthandException.java | UTF-8 | 311 | 1.859375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ohtu.miniohtu.exceptions;
/**
*
* @author olavilin
*/
public class NoShorthandException extends IllegalArgumentException {
public NoShorthandException(String s) {
super(s);
}
}
| true |
1b43b283de5601fc785f156078be4375b1f0675d | Java | lucas-china/OurBook | /app/src/main/java/br/ufpi/es/ourbook/visao/TelaCadastrar.java | UTF-8 | 1,963 | 2.1875 | 2 | [] | no_license | package br.ufpi.es.ourbook.visao;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import br.ufpi.es.ourbook.R;
import br.ufpi.es.ourbook.dados.Livro;
public class TelaCadastrar extends AppCompatActivity {
private EditText Titulo;
private EditText Autor;
private EditText Editora;
private EditText Genero;
private EditText Edicao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_cadastrar);
Titulo = (EditText)findViewById(R.id.etTitulo);
Autor = (EditText)findViewById(R.id.etAutor);
Editora = (EditText)findViewById(R.id.etEditora);
Genero = (EditText)findViewById(R.id.etGenero);
Edicao = (EditText)findViewById(R.id.etEdicao);
Titulo.requestFocus();
}
public void cadastarLivro(View view){
String tituloLivro = Titulo.getText().toString();
String autorLivro = Autor.getText().toString();;
String editoraLivro = Editora.getText().toString();;
String generoLivro = Genero.getText().toString();;
int edicaoLivro = Integer.parseInt(Edicao.getText().toString());
Livro novoLivro = new Livro(tituloLivro, autorLivro, generoLivro);
novoLivro.setEdicao(edicaoLivro);
novoLivro.setEditora(editoraLivro);
novoLivro.setDisponivel(true);
String msg = "Livro Adicionado com Sucesso";
Toast toast = Toast.makeText(this,msg,Toast.LENGTH_SHORT);
toast.show();
Titulo.setText("");
Autor.setText("");
Editora.setText("");
Genero.setText("");
Edicao.setText("");
Titulo.requestFocus();
}
public void cancelar(View view){
finish();
}
}
| true |
963e6b807ec146d3d3b61efe47472e9723efe39b | Java | Kartoffel-chen/Blog-PTA | /Data/PTA1017.java | UTF-8 | 265 | 2.53125 | 3 | [] | no_license | package cn.pat.kartoffel;
import java.util.Scanner;
public class PTA1017 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Integer num = new Integer("123456789050987654321");
System.out.println(num / 2);
}
}
| true |
775c156947cd4aafb280501ebdc49bd842a1aee6 | Java | bellmit/ears3 | /src/main/java/eu/eurofleets/ears3/domain/Navigation.java | UTF-8 | 2,175 | 2.3125 | 2 | [] | no_license | package eu.eurofleets.ears3.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import eu.eurofleets.ears3.utilities.DatagramOrder;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.xml.bind.annotation.XmlTransient;
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) //ignore all the getters
public class Navigation extends Acquisition {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@XmlTransient
private Long id;
@DatagramOrder(3)
private Double lon;
@DatagramOrder(4)
private Double lat;
@DatagramOrder(5)
private Double heading;
@DatagramOrder(6)
private Double sow;
@DatagramOrder(7)
private Double depth;
@DatagramOrder(8)
private Double cog;
@DatagramOrder(9)
private Double sog;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Double getLon() {
return this.lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return this.lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getDepth() {
if (this.depth != null && this.depth < 0) {
return this.depth * -1.0D;
} else {
return this.depth;
}
}
public void setDepth(Double depth) {
this.depth = depth;
}
public Double getCog() {
return this.cog;
}
public void setCog(Double cog) {
this.cog = cog;
}
public Double getSog() {
return this.sog;
}
public void setSog(Double sog) {
this.sog = sog;
}
public Double getHeading() {
return this.heading;
}
public void setHeading(Double heading) {
this.heading = heading;
}
public Double getSow() {
return this.sow;
}
public void setSow(Double sow) {
this.sow = sow;
}
}
| true |
b82bd4d6776a9a902fb32046b1c1942dea798d24 | Java | phillippat18/Pong-tTeamproject-cs3443 | /src/MVC/side/PlayerPanel.java | UTF-8 | 4,958 | 2.265625 | 2 | [] | no_license | package MVC.side;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import MVC.vbhitController;
import game.Controls;
import game.components.item.Item;
import game.core.Player;
public class PlayerPanel extends JPanel {
private BufferedImage bg;
private Player player;
private JLabel name;
private JLabel score, miss;
private JLabel ballimage;
private JButton statusbutton;
private vbhitController controller;
private int playernuber;
private Icon icon;
public PlayerPanel(Player player,vbhitController controller,int playernumber){
bg=null;
this.playernuber=playernumber;
this.controller=controller;
this.player=player;
this.setLayout(new BorderLayout());
this.setBackground(null);
this.setOpaque(false);
this.setFocusable(false);
JLabel label;
name = new JLabel(this.player.getName(),SwingConstants.CENTER);
name.setBackground(null);
name.setOpaque(false);
name.setForeground(Color.green);
name.setFont(Controls.MID_FONT_DEFAULT);
this.add(name,BorderLayout.NORTH);
JPanel centercontainer = new JPanel(new GridLayout(2,0));
centercontainer.setBackground(null);
centercontainer.setOpaque(false);
JPanel scorepanel = new JPanel();
scorepanel.setOpaque(false);
scorepanel.setBackground(null);
//scorepanel.setBorder(BorderFactory.createEtchedBorder(Color.DARK_GRAY, Color.green));
scorepanel.setLayout(new GridLayout(2,2));
//show score
label= new JLabel("Score:",SwingConstants.CENTER);
label.setForeground(Color.blue);
label.setBackground(null);
label.setOpaque(false);
scorepanel.add(label);
score= new JLabel(""+this.player.getScore().getScore(),SwingConstants.CENTER);
score.setForeground(Color.GREEN);
score.setBackground(null);
score.setOpaque(false);
score.setFont(Controls.LARGE_FONT_DEFAULT);
scorepanel.add(score);
//show miss
label= new JLabel("Miss:",SwingConstants.CENTER);
label.setForeground(Color.blue);
label.setBackground(null);
label.setOpaque(false);
scorepanel.add(label);
miss= new JLabel("" + this.player.getScore().getMiss(),SwingConstants.CENTER);
miss.setForeground(Color.red);
miss.setBackground(null);
miss.setOpaque(false);
miss.setFont(Controls.LARGE_FONT_DEFAULT);
scorepanel.add(miss);
centercontainer.add(scorepanel);
//jlabel
ballimage= new JLabel();
ballimage.setBackground(null);
ballimage.setOpaque(false);
centercontainer.add(ballimage);
this.add(centercontainer, BorderLayout.CENTER);
//playerstatus button
this.statusbutton = new JButton("Join");
this.statusbutton.setFont(Controls.LARGE_FONT_DEFAULT);
this.statusbutton.setBackground(null);
this.statusbutton.setForeground(Color.red);
this.setOpaque(false);
this.statusbutton.setContentAreaFilled(false);
this.statusbutton.addActionListener(this.controller);
this.statusbutton.setFocusable(false);
this.add(statusbutton,BorderLayout.SOUTH);
}
public void resetPanel(){
this.statusbutton.setEnabled(true);
this.statusbutton.setText("Join");
this.statusbutton.setForeground(Color.red);
}
public BufferedImage getBG() {
return bg;
}
public void setBG(BufferedImage background) {
this.bg = background;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public void update(){
score.setText(""+this.player.getScore().getScore());
miss.setText(""+this.player.getScore().getMiss());
}
public void setPlaystatus(){
this.statusbutton.setForeground(Color.green);
this.statusbutton.setText("Give Up");
this.player.setPlayerstatus(Controls.PLAYER_PLAY);
}
public void setGiveupStatus(){
this.statusbutton.setForeground(Color.gray);
this.statusbutton.setText("Give Up");
this.statusbutton.setEnabled(false);
this.player.setPlayerstatus(Controls.PLAYER_GIVE_UP);
}
public int getPlayerNumber(){
return this.playernuber;
}
@Override
protected void paintComponent(Graphics arg0) {
//arg0.drawImage(this.player.getBallimage().get(0), 0, 0,this.getWidth(),this.getHeight(), null);
if(this.ballimage.getIcon()==null){
ImageIcon icon = new ImageIcon(
player.getBallimage().get(0).getScaledInstance(this.ballimage.getHeight(),this.ballimage.getHeight(), FRAMEBITS));
ballimage.setIcon(icon);
ballimage.setHorizontalAlignment(SwingConstants.CENTER);
}
super.paintComponent(arg0);
}
}
| true |
06ce48f5d0031ec8bc65bd4a5bdbd512a4c14ad6 | Java | azyuzko/eclipsetransaq | /ru.eclipsetrader.transaq.core/src/ru/eclipsetrader/transaq/core/model/internal/Pit.java | UTF-8 | 1,449 | 2.21875 | 2 | [] | no_license | package ru.eclipsetrader.transaq.core.model.internal;
import ru.eclipsetrader.transaq.core.model.BoardType;
import ru.eclipsetrader.transaq.core.model.TQSymbol;
import ru.eclipsetrader.transaq.core.util.Utils;
public class Pit {
String secCode;
BoardType board;
Integer market;
int decimals;
double minStep;
int lotSize;
double point_cost;
TQSymbol symbol = null;
public TQSymbol getSymbol() {
if (symbol == null) {
symbol = new TQSymbol(board, secCode);
}
return symbol;
}
@Override
public String toString() {
return Utils.toString(this);
}
public String getSecCode() {
return secCode;
}
public void setSecCode(String secCode) {
this.secCode = secCode;
}
public BoardType getBoard() {
return board;
}
public void setBoard(BoardType board) {
this.board = board;
}
public Integer getMarket() {
return market;
}
public void setMarket(Integer market) {
this.market = market;
}
public int getDecimals() {
return decimals;
}
public void setDecimals(int decimals) {
this.decimals = decimals;
}
public double getMinStep() {
return minStep;
}
public void setMinStep(double minStep) {
this.minStep = minStep;
}
public int getLotSize() {
return lotSize;
}
public void setLotSize(int lotSize) {
this.lotSize = lotSize;
}
public double getPoint_cost() {
return point_cost;
}
public void setPoint_cost(double point_cost) {
this.point_cost = point_cost;
}
}
| true |
95be83027ce5f14d1681d80972f44412abbe0d7e | Java | grhbit/swing-minizoo | /src/minizoo/c/background/Ground.java | UTF-8 | 750 | 2.8125 | 3 | [] | no_license | package minizoo.c.background;
import minizoo.App;
import minizoo.c.Entity;
import minizoo.c.Sprite;
public class Ground extends Entity {
public Ground(String name) {
super(name);
Sprite sprTile = new Sprite("resources/kenney/grassMid.png");
sprTile.setPosition(0, App.ScreenHeight);
sprTile.setAnchor(0, 1);
int count = (int)Math.floor(App.ScreenWidth/sprTile.getContentSize().x);
this.addChild(sprTile);
for (int i=1; i<=count; ++i) {
sprTile = new Sprite("resources/kenney/grassMid.png");
sprTile.setPosition((float) sprTile.getContentSize().x * i, App.ScreenHeight);
sprTile.setAnchor(0, 1);
this.addChild(sprTile);
}
}
}
| true |
90d588f6b82cafe11a72b530897b684db11ee9f2 | Java | javazbwang/taotaoshop | /taotao-portal/src/main/java/com/taotao/portal/controller/IndexController.java | UTF-8 | 1,039 | 1.890625 | 2 | [] | no_license | package com.taotao.portal.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.portal.service.ContentService;
@Controller
public class IndexController {
@Autowired
private ContentService contentService;
@RequestMapping("/index")
public String index(Model model) {
String adJson = contentService.getContentList();
System.out.println(adJson+"**********");
model.addAttribute("ad1",adJson);
return "index";
}
@RequestMapping(value = "/httpclient/post",method = RequestMethod.POST)
@ResponseBody
public TaotaoResult testPost(String name,String password) {
String result= name+"***"+password;
System.out.println(result);
return TaotaoResult.ok(result);
}
}
| true |
b7e3ebee4bfdd13951a1d13fdd956c0551994884 | Java | oreon/lp | /.svn/pristine/b7/b7e3ebee4bfdd13951a1d13fdd956c0551994884.svn-base | UTF-8 | 384 | 2.109375 | 2 | [] | no_license | package lawpro.models.universe.response;
import common.models.ResponseModel;
import lawpro.models.universe.Firm;
import java.util.List;
public class FirmSearchResponse extends ResponseModel {
private List<Firm> firms;
public List<Firm> getFirms() {
return firms;
}
public void setFirms(List<Firm> value) {
firms = value;
}
}
| true |
a88842b30d186998defc5cc6fe24f3d4fb392000 | Java | the-blue-alliance/the-blue-alliance-android | /android/src/test/java/com/thebluealliance/androidclient/models/MatchTest.java | UTF-8 | 1,907 | 2.140625 | 2 | [
"MIT"
] | permissive | package com.thebluealliance.androidclient.models;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.thebluealliance.androidclient.datafeed.framework.ModelMaker;
import com.thebluealliance.api.model.IMatchAlliance;
import com.thebluealliance.api.model.IMatchAlliancesContainer;
import com.thebluealliance.api.model.IMatchVideo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
@RunWith(AndroidJUnit4.class)
public class MatchTest {
private Match mMatch;
private Match mCleanMatch;
@Before
public void readJsonData(){
mMatch = ModelMaker.getModel(Match.class, "2014cmp_f1m1");
mCleanMatch = new Match();
}
@Test
public void testMatchModel() {
assertNotNull(mMatch);
assertEquals(mMatch.getKey(), "2014cmp_f1m1");
assertEquals(mMatch.getMatchNumber().intValue(), 1);
assertEquals(mMatch.getSetNumber().intValue(), 1);
assertEquals(mMatch.getEventKey(), "2014cmp");
assertNotNull(mMatch.getTime());
assertEquals(mMatch.getTime().intValue(), 1398551880);
assertNotNull(mMatch.getVideos());
assertNotNull(mMatch.getAlliances());
List<IMatchVideo> videos = mMatch.getVideos();
assertEquals(videos.size(), 2);
IMatchVideo video1 = videos.get(0);
assertEquals(video1.getType(), "youtube");
assertEquals(video1.getKey(), "jdJutaggCMk");
IMatchAlliancesContainer alliances = mMatch.getAlliances();
IMatchAlliance blueAlliance = alliances.getBlue();
assertEquals(blueAlliance.getScore().intValue(), 361);
List<String> blueTeams = blueAlliance.getTeamKeys();
assertEquals(blueTeams.size(), 3);
assertEquals(blueTeams.get(0), "frc469");
}
}
| true |
20e74466910edf92a1d34e90df907c7a03a4b83e | Java | aofengen/Casino-Server | /src/main/java/controllers/PokerController.java | UTF-8 | 2,604 | 2.484375 | 2 | [] | no_license | package controllers;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import poker.video_poker.*;
import models.PokerStats;
import database.PokerDatabase;
@CrossOrigin(origins = "*")
@RestController
public class PokerController {
@GetMapping("/poker/shuffle")
public String shuffle() throws Exception {
Deck newDeck = new Deck();
newDeck.createDeck();
newDeck.shuffle();
String obj = newDeck.deckToJSON().toString();
return obj;
}
@GetMapping("/poker/leaderboard")
public String getLeaderboard() throws Exception {
JSONArray array = new JSONArray();
array = PokerDatabase.getTopTen();
return array.toString();
}
@GetMapping("/poker/stats/{id}")
public String getStats(@PathVariable(name = "id") int id) throws Exception {
try {
PokerDatabase.createVideoPokerStatsTable();
} catch (Exception e) {
System.out.println(e);
}
JSONObject obj = new JSONObject();
try {
obj = PokerDatabase.getStats(id);
} catch (Exception e) {
System.out.println(e);
}
return obj.toString();
}
@PostMapping("/poker/stats/{id}")
public String postStats(@PathVariable(name = "id") int id, @RequestBody PokerStats stats) throws Exception {
try {
PokerDatabase.createVideoPokerStatsTable();
} catch (Exception e) {
System.out.println(e);
}
JSONObject obj = new JSONObject();
try {
int handsWon = stats.getHandsWon();
int handsPlayed = stats.getHandsPlayed();
int highMoney = stats.getHighMoney();
int totalMoney = stats.getTotalMoney();
int royalFlush = stats.getRoyalFlush();
int straightFlush = stats.getStraightFlush();
int fourKind = stats.getFourKind();
int fullHouse = stats.getFullHouse();
int flush = stats.getFlush();
int straight = stats.getStraight();
int threeKind = stats.getThreeKind();
obj = PokerDatabase.updateStatsTable(id, handsWon, handsPlayed, highMoney, totalMoney, royalFlush, straightFlush, fourKind, fullHouse, flush, straight, threeKind);
} catch (Exception e) {
System.out.println(e);
}
return obj.toString();
// return obj;
}
}
| true |
deb5eb86f97eef28e8c8d961cbc60f50225bc1bd | Java | HeydarQa/Self_Practices | /src/Day11_NestedIF/Switch.java | UTF-8 | 724 | 3.1875 | 3 | [] | no_license | package Day11_NestedIF;
import javax.crypto.interfaces.PBEKey;
public class Switch {
public static void main(String[] args) {
int month=7;
String result="";
switch (month){
case 1:
case 3:
case 5:
case 10:
result=("31 days month");
break;
case 7:
case 9:
case 11:
case 12:
result=("30 days month");
break;
case 2:
result=("28 days month");
break;
default:
System.out.println("Invalid Number");
break;
}
System.out.println(result);
}
}
| true |
dff74cb8969d7f45e996f86d44efb0ba2b323f66 | Java | CBProgramming/internet-of-things | /IoTbottomNavigation/app/src/main/java/uk/ac/tees/t7099806/iotbottomnavigation/ui/GPS/GPSFragment.java | UTF-8 | 8,783 | 1.835938 | 2 | [] | no_license | package uk.ac.tees.t7099806.iotbottomnavigation.ui.GPS;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.util.ArrayList;
import java.util.List;
import uk.ac.tees.t7099806.iotbottomnavigation.PermissionUtils;
import uk.ac.tees.t7099806.iotbottomnavigation.R;
/**
* This demo shows how GMS Location can be used to check for changes to the users location. The
* "My Location" button uses GMS Location to set the blue dot representing the users location.
* Permission for {@link android.Manifest.permission#ACCESS_FINE_LOCATION} is requested at run
* time. If the permission has not been granted, the Activity is finished with an error message.
*/
public class GPSFragment extends Fragment implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
GoogleMap.OnMarkerClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
private ArrayList<LatLng> coords = new ArrayList<LatLng>();
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private Marker[] markers;
private String title, titleCheck;
private double lat, lng;
private GoogleMap mMap;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
String clientId;
MqttAndroidClient client;
private String USERNAME = "ferg";
private String PASSWORD = "pass";
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.google_map);
supportMapFragment.getMapAsync(this);
titleCheck = "";
clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(getContext(), "tcp://broker.hivemq.com:1883",
clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
subscribe();
// subscribe("/petprotector/camera_actuator", cameraOn);
// subscribe("/petprotector/feeder_actuator/feeding_times");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(getContext(), "Failure", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
return view;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// treasures here
mMap.setOnMarkerClickListener(this);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions( //Method of Fragment
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE
);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(getContext(), "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(getContext(), "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
else if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
}
}
else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
public boolean onMarkerClick(final Marker marker) {
title = marker.getTitle();
titleCheck = title;
return false;
}
private void subscribe()
{
try{
if(client.isConnected())
{
client.subscribe("/petprotector/gps/lat", 0);
client.subscribe("/petprotector/gps/lng", 0);
//add camera on data subsribe /petprotector/camera_actuator/data
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
if(topic.equals("/petprotector/gps/lat"))
{
String latS = message.toString();
lat = Double.parseDouble(latS);
System.out.println("lat= " + message.toString());
}
else if (topic.equals("/petprotector/gps/lng"))
{
String lngS = message.toString();
lng = Double.parseDouble(lngS);
System.out.println("lng= " + message.toString());
}
mMap.clear();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title("Dogs Location");
mMap.addMarker(markerOptions);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
}
} catch (Exception e){
Log.d("tag", "Error: " + e);
}
}
}
| true |
a3e0e393cd4145263c825ec4917a9599af602878 | Java | uk-gov-mirror/UKGovernmentBEIS.national-household-model-core-components | /core-projects/hom/src/main/java/uk/org/cse/nhm/hom/emf/technologies/package-info.java | UTF-8 | 2,340 | 2.59375 | 3 | [] | no_license | /**
* The technology model describes all the technologies present in a house. In order to accommodate convenient
* containment, removal and similar operations, this part of the system is modelled using EMF, the Eclipse
* Modelling Framework, an XMI-compatible modelling toolkit. The
* <a href="http://www.eclipse.org/modeling/emf/">EMF page</a> is a good place
* to start with an introduction to this system, but in summary:
* <ul>
* <li>The <code>technologies.ecore</code> file in <code>src/main/model/</code>
* defines the class structure, attributes, operations and containment hierarchy
* for all the technology elements</li>
* <li>The associated <code>technologies.genmodel</code> contains instructions
* for the EMF code generator, which turns the model description into java
* implementation code</li>
* </ul>
* <p>
* The code generator has an effective merging strategy which makes it safe to
* mix generated and non-generated code. When a generated method has been
* modified and should not be overwritten the "@generated false" attribute is
* set on the appropriate element.
* </p>
* <p>
* The technology model is composed of a few main parts, which store information
* about the technologies and their relationships; the most complex parts of
* these are the relationships between {@link uk.org.cse.nhm.hom.emf.technologies.IHeatSource},
* {@link uk.org.cse.nhm.hom.emf.technologies.ICentralHeatingSystem}, and
* {@link uk.org.cse.nhm.hom.emf.technologies.ICentralWaterSystem}.
* </p>
* <p>
* </p>
* <p>
* To interact with the energy calculator, some parts of the technology model
* implement the {@link uk.org.cse.nhm.hom.emf.technologies.IVisitorAccepter}
* interface. When the
* {@link uk.org.cse.nhm.hom.emf.technologies.ITechnologyModel} is asked to
* accept an
* {@link uk.org.cse.nhm.energycalculator.api.IEnergyCalculatorVisitor}, it
* will pass that visitor to all of its contained elements which also implement
* {@link uk.org.cse.nhm.energycalculator.api.IEnergyCalculatorVisitor}; they
* then have the opportunity to supply
* {@link uk.org.cse.nhm.energycalculator.api.IEnergyTransducer} or
* {@link uk.org.cse.nhm.energycalculator.api.IHeatingSystem} implementations
* into the energy calculation as they see fit.
* </p>
*/
package uk.org.cse.nhm.hom.emf.technologies;
| true |
259b74b170c374aec33128259bc4e5753d5fa60a | Java | nagioswork/xian | /xian-dao/src/main/java/info/xiancloud/dao/jdbc/sql/BatchInsertAction.java | UTF-8 | 3,048 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package info.xiancloud.dao.jdbc.sql;
import info.xiancloud.core.Unit;
import info.xiancloud.core.message.UnitResponse;
import info.xiancloud.core.util.LOG;
import info.xiancloud.core.util.Pair;
import info.xiancloud.core.util.Reflection;
import info.xiancloud.dao.jdbc.BasicSqlBuilder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* 批量插入记录
* 入参map = { "values" : [{},{},{}]}
*
* @author happyyangyuan
*/
public abstract class BatchInsertAction extends AbstractAction implements ISingleTableAction {
private Pair<String, Object[]> preparedSqlAndValues;
@Override
protected UnitResponse check(Unit daoUnit, Map map, Connection connection) {
if (getValues().size() >= 500) {
LOG.warn("批量插入的记录过多:" + getValues().size(), new Throwable("本异常的作用是警告开发者批量插入的长度过长,但是它不阻止过长的插入语句执行."));
}
return super.check(daoUnit, map, connection);
}
private List<Map> getValues() {
return Reflection.toType(map.get("values"), List.class);
}
/**
* 注意:批量插入不支持本db框架的pattern模式,原因是本action的入参并不是单纯的一个map,而是map列表,这些map内的key都是一样的
*/
@Override
protected String getPreparedSQL() throws SQLException {
if (preparedSql == null) {
preparedSqlAndValues = BasicSqlBuilder.buildBatchInsertPreparedSQL(table(), getCols(), getValues());
preparedSql = preparedSqlAndValues.fst;
}
return preparedSql;
}
@Override
protected Object[] getSqlParams() throws SQLException {
if (sqlParams == null) {
getPreparedSQL();
sqlParams = preparedSqlAndValues.snd;
}
return sqlParams;
}
@Override
protected String getSqlPattern() throws SQLException {
return sqlPattern(map, connection);
}
@Override
protected String sqlPattern(Map map, Connection connection) throws SQLException {
LOG.debug("这里只是为了兼容,返回preparedSQL替代之");
if (sqlPattern == null) {
sqlPattern = getPreparedSQL();
}
return sqlPattern;
}
@Override
protected Object executeSql(String preparedSql, Object[] sqlParams, Connection connection) throws SQLException {
LOG.debug("返回的是插入的条数");
List values = Reflection.toType(map.get("values"), List.class);
if (values == null || values.isEmpty()) {
LOG.warn("没什么可以插入的数据,什么也不做");
return 0;
}
return ISingleTableAction.dosql(preparedSql, sqlParams, connection);
}
private String[] cols;
public String[] getCols() throws SQLException {
if (cols == null || cols.length == 0) {
cols = ISingleTableAction.queryCols(table(), connection);
}
return cols;
}
}
| true |
7dd7a7c04f098136afdbac512043166b18f70053 | Java | liuqian1990/we-cmdb | /cmdb-core/src/main/java/com/webank/cmdb/dto/IntQueryOperateAggRequetDto.java | UTF-8 | 3,702 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package com.webank.cmdb.dto;
import java.util.LinkedList;
import java.util.List;
public class IntQueryOperateAggRequetDto {
private Integer queryId; // dont need for creation
private String operation;// create or update
private String queryName;
private String queryDesc;
private List<Criteria> criterias = new LinkedList<>();
public static class Criteria {
private String branchId;
// private int ciTypeId;
private String ciTypeName;
private List<CriteriaNode> routine = new LinkedList<>();
private CriteriaCiTypeAttr attribute;
public Criteria() {
}
public String getCiTypeName() {
return ciTypeName;
}
public void setCiTypeName(String ciTypeName) {
this.ciTypeName = ciTypeName;
}
public CriteriaCiTypeAttr getAttribute() {
return attribute;
}
public void setAttribute(CriteriaCiTypeAttr attribute) {
this.attribute = attribute;
}
public String getBranchId() {
return branchId;
}
public void setBranchId(String branchId) {
this.branchId = branchId;
}
public List<CriteriaNode> getRoutine() {
return routine;
}
public void setRoutine(List<CriteriaNode> routine) {
this.routine = routine;
}
}
public static class CriteriaNode {
private int ciTypeId;
private Relationship parentRs;
public CriteriaNode() {
}
public CriteriaNode(int ciTypeId) {
this(ciTypeId, null);
}
public CriteriaNode(int ciTypeId, Relationship parentRs) {
this.ciTypeId = ciTypeId;
this.parentRs = parentRs;
}
public Integer getCiTypeId() {
return ciTypeId;
}
public void setCiTypeId(int ciTypeId) {
this.ciTypeId = ciTypeId;
}
public Relationship getParentRs() {
return parentRs;
}
public void setParentRs(Relationship parentRs) {
this.parentRs = parentRs;
}
}
public static class CriteriaCiTypeAttr {
private Integer attrId;
private boolean isCondition;
private boolean isDisplayed;
public Integer getAttrId() {
return attrId;
}
public void setAttrId(Integer attrId) {
this.attrId = attrId;
}
public boolean isCondition() {
return isCondition;
}
public void setCondition(boolean isCondition) {
this.isCondition = isCondition;
}
public boolean isDisplayed() {
return isDisplayed;
}
public void setDisplayed(boolean isDisplayed) {
this.isDisplayed = isDisplayed;
}
}
public Integer getQueryId() {
return queryId;
}
public void setQueryId(Integer queryId) {
this.queryId = queryId;
}
public String getQueryName() {
return queryName;
}
public void setQueryName(String queryName) {
this.queryName = queryName;
}
public String getQueryDesc() {
return queryDesc;
}
public void setQueryDesc(String queryDesc) {
this.queryDesc = queryDesc;
}
public List<Criteria> getCriterias() {
return criterias;
}
public void setCriterias(List<Criteria> criterias) {
this.criterias = criterias;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
}
| true |
7137c5b091213bce8496dd6538799800b8254809 | Java | MieshkaDollie/restaurant | /src/main/java/com/restaurant/Repository/Implementation/LoginImplementation/RegisterNewUserImplementation.java | UTF-8 | 1,897 | 2.8125 | 3 | [] | no_license | package com.restaurant.Repository.Implementation.LoginImplementation;
import com.restaurant.Domain.Login.RegisterNewUser;
import com.restaurant.Repository.Login.RegisterNewUserRepository;
import java.util.*;
public class RegisterNewUserImplementation implements RegisterNewUserRepository {
private static RegisterNewUserImplementation registerNewUserImplementation = null;
private Map<String, RegisterNewUser> registerNewUserStringMap;
private RegisterNewUserImplementation(){
registerNewUserStringMap = new HashMap<>();
}
public static RegisterNewUserRepository getRepository(){
if ( registerNewUserImplementation == null){
registerNewUserImplementation = new RegisterNewUserImplementation();
}
return registerNewUserImplementation;
}
@Override
public Set<RegisterNewUser> getAll() {
Collection<RegisterNewUser> registerNewUsers = this.registerNewUserStringMap.values();
Set<RegisterNewUser> set = new HashSet<>();
set.addAll(registerNewUsers);
return set;
}
@Override
public RegisterNewUser create(RegisterNewUser registerNewUser) {
registerNewUserStringMap.put(registerNewUser.getName(), registerNewUser);
RegisterNewUser reg = registerNewUserStringMap.get(registerNewUser.getName());
return reg;
}
@Override
public RegisterNewUser read(String s) {
RegisterNewUser readNewUser = registerNewUserStringMap.get(s);
return null;
}
@Override
public RegisterNewUser update(RegisterNewUser registerNewUser) {
registerNewUserStringMap.put(registerNewUser.getName(), registerNewUser);
RegisterNewUser reg = registerNewUserStringMap.get(registerNewUser.getName());
return reg;
}
@Override
public void delete(String s) {
registerNewUserStringMap.remove(s);
}
}
| true |
cb6fe3aded1eda5b395e7d50f082d9a845e3d1f5 | Java | cozos/emrfs-hadoop | /com/amazon/ws/emr/hadoop/fs/shaded/org/apache/commons/math/optimization/linear/LinearConstraint.java | UTF-8 | 3,080 | 2.140625 | 2 | [] | no_license | package com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.optimization.linear;
import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.linear.ArrayRealVector;
import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.linear.MatrixUtils;
import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.linear.RealVector;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class LinearConstraint
implements Serializable
{
private static final long serialVersionUID = -764632794033034092L;
private final transient RealVector coefficients;
private final Relationship relationship;
private final double value;
public LinearConstraint(double[] coefficients, Relationship relationship, double value)
{
this(new ArrayRealVector(coefficients), relationship, value);
}
public LinearConstraint(RealVector coefficients, Relationship relationship, double value)
{
this.coefficients = coefficients;
this.relationship = relationship;
this.value = value;
}
public LinearConstraint(double[] lhsCoefficients, double lhsConstant, Relationship relationship, double[] rhsCoefficients, double rhsConstant)
{
double[] sub = new double[lhsCoefficients.length];
for (int i = 0; i < sub.length; i++) {
lhsCoefficients[i] -= rhsCoefficients[i];
}
coefficients = new ArrayRealVector(sub, false);
this.relationship = relationship;
value = (rhsConstant - lhsConstant);
}
public LinearConstraint(RealVector lhsCoefficients, double lhsConstant, Relationship relationship, RealVector rhsCoefficients, double rhsConstant)
{
coefficients = lhsCoefficients.subtract(rhsCoefficients);
this.relationship = relationship;
value = (rhsConstant - lhsConstant);
}
public RealVector getCoefficients()
{
return coefficients;
}
public Relationship getRelationship()
{
return relationship;
}
public double getValue()
{
return value;
}
public boolean equals(Object other)
{
if (this == other) {
return true;
}
if ((other instanceof LinearConstraint))
{
LinearConstraint rhs = (LinearConstraint)other;
return (relationship == relationship) && (value == value) && (coefficients.equals(coefficients));
}
return false;
}
public int hashCode()
{
return relationship.hashCode() ^ Double.valueOf(value).hashCode() ^ coefficients.hashCode();
}
private void writeObject(ObjectOutputStream oos)
throws IOException
{
oos.defaultWriteObject();
MatrixUtils.serializeRealVector(coefficients, oos);
}
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException
{
ois.defaultReadObject();
MatrixUtils.deserializeRealVector(this, "coefficients", ois);
}
}
/* Location:
* Qualified Name: com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.optimization.linear.LinearConstraint
* Java Class Version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ | true |
ead5096cf96bbb01c270ece8e832d4e3cd23fc8c | Java | berkagmp/BI_System | /src/main/java/com/keyora/app/dao/ProductDao.java | UTF-8 | 4,025 | 2.390625 | 2 | [] | no_license | package com.keyora.app.dao;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.keyora.app.entity.Brand;
import com.keyora.app.entity.Product;
@Repository
public class ProductDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
JdbcTemplate jdbcTemplate;
public Integer save(Product product) {
sessionFactory.getCurrentSession().save(product);
return product.getId();
}
public Product get(Integer id) {
return sessionFactory.getCurrentSession().get(Product.class, id);
}
public Integer getMaxId() {
String sql = "select max(id) from product";
Integer result = jdbcTemplate.queryForObject(sql, Integer.class);
return result;
}
public List<Product> list() {
Session session = sessionFactory.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
cq.select(root);
Query<Product> query = session.createQuery(cq);
return query.getResultList();
}
public List<Product> listByUseynAndBrandId(Boolean useyn, Integer brandId) {
Session session = sessionFactory.getCurrentSession();
StringBuilder str = new StringBuilder("from product p where 1=1 ");
if (useyn)
str.append(" and p.useyn = :useyn");
if (brandId > 0)
str.append(" and p.brandId = :brandId");
Query<Product> query = session.createQuery(str.toString(), Product.class);
if (useyn)
query.setParameter("useyn", useyn);
if (brandId > 0)
query.setParameter("brandId", brandId);
return query.getResultList();
}
public List<Product> listByBrand(Integer brandId) {
Session session = sessionFactory.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Metamodel m = session.getMetamodel();
EntityType<Product> Product_ = m.entity(Product.class);
Root<Product> root = cq.from(Product.class);
cq.where(cb.equal(root.get(Product_.getSingularAttribute("brandId")), brandId));
cq.select(root);
Query<Product> query = session.createQuery(cq);
return query.getResultList();
}
public Integer update(Integer id, Product product) {
/*
* session.byId(T).load(id) setter() session.flush()
*/
Session session = sessionFactory.getCurrentSession();
Product tempProduct = session.byId(Product.class).load(id);
tempProduct.setName(product.getName());
tempProduct.setUseyn(product.getUseyn());
tempProduct.setRaw(product.getRaw());
tempProduct.setKeyword(product.getKeyword());
// flush: Sync between session state and DB
session.flush();
return tempProduct.getId();
}
public void updateUseyn(Integer brandId, Brand brandDetail) {
Session session = sessionFactory.getCurrentSession();
String hql = "update product p set useyn = :useyn where p.brandId = :brandId";
Query query = session.createQuery(hql);
query.setParameter("useyn", brandDetail.getUseyn());
query.setParameter("brandId", brandId);
query.executeUpdate();
}
public void delete(Integer id) {
// session.delete(session.byId(T).load(id))
Session session = sessionFactory.getCurrentSession();
session.delete(session.byId(Product.class).load(id));
}
public int deleteByBrandId(Integer brandId) {
Session session = sessionFactory.getCurrentSession();
String hql = "delete product p where p.brandId = :brandId";
int deletedEntities = session.createQuery(hql).setParameter("brandId", brandId).executeUpdate();
return deletedEntities;
}
}
| true |
de4ef09f114d9bc1d2877f4305f667b3f2a3304d | Java | SergeyZinkovich/Task-Planner | /app/src/main/java/com/taskplanner/presenter/MainActivityPresenter.java | UTF-8 | 477 | 1.539063 | 2 | [] | no_license | package com.taskplanner.presenter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.arellomobile.mvp.InjectViewState;
import com.arellomobile.mvp.MvpPresenter;
import com.taskplanner.DBHelper;
import com.taskplanner.ui.MainActivity;
import com.taskplanner.ui.MainActivityView;
import java.text.SimpleDateFormat;
import java.util.Date;
@InjectViewState
public class MainActivityPresenter extends MvpPresenter<MainActivityView> {
}
| true |
a0c6a86956b28e78997b8b15c15f36df00fcc8b0 | Java | tiwiz/CorsoFOIT | /app/src/main/java/it/foit/corsofoit/BaseActivity.java | UTF-8 | 1,039 | 2.140625 | 2 | [] | no_license | package it.foit.corsofoit;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crash.FirebaseCrash;
public abstract class BaseActivity extends AppCompatActivity{
private FirebaseAnalytics analytics;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
analytics = FirebaseAnalytics.getInstance(this);
FirebaseCrash.report(new Exception("Non-fatal exception during " + getClass().getSimpleName() + " onCreate() method"));
}
@Override
protected void onResume() {
super.onResume();
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, getClass().getSimpleName());
analytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
FirebaseCrash.log("User saw Activity " + getClass().getSimpleName());
}
}
| true |
67f753fe0238df7a00b388151ba119d4581928da | Java | ditzjose/DataStructures | /src/com/collections/Queue.java | UTF-8 | 2,598 | 3.734375 | 4 | [] | no_license | package com.collections;
import static java.lang.System.*;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
class ConsumerProducer2 {
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
Random random = new Random();
void producer() throws InterruptedException {
while (true) {
Integer val = random.nextInt(1000);
out.println("Proder starting to produce: " + val);
queue.put(val);
out.println("Proder ended to produce: " + val);
Thread.sleep(500);
}
}
void consumer() throws InterruptedException {
while (true) {
Thread.sleep(3000);
Integer val = queue.take();
out.println("Consumer has consumed: " + val);
}
}
}
public class Queue {
public static void main(String... command) throws InterruptedException {
ConsumerProducer2 obj = new ConsumerProducer2();
Thread t1 = new Thread(()-> {
try {
obj.producer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
Thread t2 = new Thread(
()-> {
try {
obj.consumer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
t1.start();
t2.start();
//t1.join();
//t2.join();
}
}
// Queue are best used in Producer Consumer Problem
/*
Structure:
Collection
|
Queue
|
BlockedQueue
|
LinkedBlockingQueue ArrayBlockingQueue PriorityBlockingQueue
*/
/*
* Blocking Queue: Blocking Queue doesnt allow null values. ArrayBlockingQueue
* and LinkedBlockingQueue will give out throw new NullPointerException()
*
* BlockingQueu is Bounded and Unbounded: Bound will have a size Unbound has no
* size. Its size is set to MAX_SIZE
*
* Blocking Queue implemented by ArrayBlockingQueue, LinkedBlockingQueue,
* PriorityBlockingQueue and all are thread safe. They are mostly used in
* multi-threading environment to implement Producer Consumer pattern.
*/
/*
* ArrayBlockingQueue LinkedBlockingQueue Its performance is faster Slower than
* ArrayBlockingQueue
*
* It is bounded if not Node are dynamically created,hence memory wise Max_Size
* is used hence LinkedBlockingQueue is better to be used. lot of space in used
* in the memory, hence forms overhead
*/
// PriorityBlockingueue: Retrival of elements is some priority.It is unbounded
// and ordering is done
// based on some priority. | true |
5c3483057b8393fc810309d1b2bfddc80439f760 | Java | bmreddy1986/piggy-bank | /src/main/java/com/piggy/bank/controllers/GroupController.java | UTF-8 | 3,617 | 2.328125 | 2 | [] | no_license | package com.piggy.bank.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.piggy.bank.domain.interfaces.IGroupDomainService;
import com.piggy.bank.resource.models.Group;
import com.piggy.bank.resource.models.Member;
@Controller
public class GroupController {
@Autowired
private IGroupDomainService domainService;
@RequestMapping(value = "/group/{id}", method = RequestMethod.GET)
public ResponseEntity<Group> getGroupById(@PathVariable("id") String id) {
System.out.println("id: " + id);
Group group = domainService.getGroupById(id);
return ResponseEntity.ok().headers(getResponseHeader()).body(group);
}
@RequestMapping(value = "/group", method = RequestMethod.GET)
public ResponseEntity<List<Group>> searchtGroup(@RequestParam String organizerId) {
List<Group> groupList = domainService.searchGroup(organizerId);
return ResponseEntity.ok().headers(getResponseHeader()).body(groupList);
}
@RequestMapping(value = "/group", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Group> createGroup(@RequestBody Group group) {
group = domainService.createGroup(group);
return ResponseEntity.ok().headers(getResponseHeader()).body(group);
}
@RequestMapping(value = "/group/{id}/addMember", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Member> addMember(@RequestBody Member member, @PathVariable String id) {
member = domainService.addMember(id, member);
return ResponseEntity.ok().headers(getResponseHeader()).body(member);
}
@RequestMapping(value = "/member/{id}", method = RequestMethod.GET)
public ResponseEntity<Member> getMemberById(@PathVariable("id") String id) {
Member member = member = domainService.getMemberById(id);
return ResponseEntity.ok().headers(getResponseHeader()).body(member);
}
@RequestMapping(value = "/member", method = RequestMethod.GET)
public ResponseEntity<List<Member>> getMembersByGroupId(@RequestParam String groupId) {
List<Member> member = domainService.getMembersByGroupId(groupId);
return ResponseEntity.ok().headers(getResponseHeader()).body(member);
}
/*
* @RequestMapping(value = "/group/{id}", method = RequestMethod.DELETE,
* consumes = "application/json")
*
* @ResponseBody public String delete(@PathVariable("id") int id) { boolean
* isDeleted = false; HttpHeaders headers = new HttpHeaders();
* headers.add("Content-Type", "application/json"); headers.add("Responded",
* "GroupController");
*
* try { // Group emp = new Group(id); // isDeleted = GroupDao.delete(emp); }
* catch (Exception ex) { System.out.println("Group not found to delete" +
* ex.getMessage()); return "Error deleting the Group: " + ex.toString(); }
*
* if (isDeleted) { return "Group succesfully deleted!"; } return
* "Error! Group deleted!"; }
*/
public HttpHeaders getResponseHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
return headers;
}
}
| true |
b346423290709bd0d8eaa6a0ecb61493f2a85427 | Java | silverstarBb/Java | /src/com/java_0425/반복문1.java | UTF-8 | 5,012 | 3.765625 | 4 | [] | no_license | package com.java_0425;
public class 반복문1 {
/***
* for문: for (1, 2, 3) {실행문}
* 1) 초기화식: for문에서 사용할 변수 선언 및 초기값 정의
* 2) 조건식: if문과 동일하게 거짓을 찾기 위한 조건
* 3) 증감식: for문에서 사용할 변수를 변화를 주기 위한 식
***/
public void t1() {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
public void t2(int s) {
for (int i = 0; i < s; i++) {
System.out.println(i);
}
}
public void t3(int a, int b) {
System.out.println("t3 반복문 시작!");
for(; a < b; a++) {
System.out.println(a);
}
System.out.println("t3 반복문 종료!");
}
public void t4() {
for (int i = 0; i <= 5; i++) { // 0 ~ 4
if (i%2 == 0) {
System.out.print(i + " - ★짝수★");
} else {
System.out.print(i + " - ☆홀수☆");
}
System.out.println("");
}
}
public void t5() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j%2 == 0) {
System.out.print("★");
} else {
System.out.print("☆");
}
}
System.out.println();
}
}
// public void t6() {
// for (int i = 0; i <= 5; i++) {
// if (i%2 == 0) {
// //System.out.print("i = "+ i);
// for (int j = 0; j <= i; j++) {
// if (j%2 == 0) {
// System.out.print("★");
// } else {
// System.out.print("☆");
// }
// }
// } else {
// //System.out.print("i= "+i);
// for (int j = 0; j <= i; j++) {
// if (j%2 == 0) {
// System.out.print("☆");
// } else {
// System.out.print("★");
// }
// }
// }
// System.out.println("s");
// }
// }
public void t6() {
for (int i = 0; i <= 5; i++) {
for (int j = 0; j <= i; j++) {
if ((i-j)%2 == 0) {
System.out.print("★");
} else {
System.out.print("☆");
}
}
System.out.println("s");
}
}
public void t7() {
int k;
for (int i = 0; i < 9; i++) {
if (i <= 4) {
k = i;
} else {
k = 8 - i;
}
for (int j = 0; j <= k; j++) {
if ((j)%2 == 0) {
System.out.print("★");
} else {
System.out.print("☆");
}
}
System.out.println("");
}
}
// public void t7() {
// int t = 0;
// for (int i = 0; i < 9; i++) {
// if (i > 4) {
// t = t - 2;
// }
//
// for (int j = 0; j <= t; j++) {
// if (j%2 == 0) {
// System.out.print("★");
// } else {
// System.out.print("☆");
// }
// }
//
// t++;
// System.out.println("");
// }
// }
public void t8() {
int k;
for (int i = 0; i < 9; i++) {
if (i <= 4) {
k = i;
} else {
k = 8 - i;
}
for (int j = 0; j <= k; j++) {
if (((k-j))%2 == 0) {
System.out.print("★");
} else {
System.out.print("☆");
}
}
System.out.println("");
}
}
// public void t8() {
// int t = 0;
// for (int i = 0; i < 9; i++) {
// if (i > 4) {
// t = t - 2;
// }
//
// for (int j = 0; j <= t; j++) {
// if ((t-j)%2 == 0) {
// System.out.print("★");
// } else {
// System.out.print("☆");
// }
// }
//
// t++;
// System.out.println("");
// }
// }
public void t9() {
System.out.println("난이도: 1");
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
System.out.println(i+" * "+j+" = "+i*j);
}
System.out.println("");
}
}
public void t10() {
System.out.println("난이도: 2");
for (int i = 1; i <= 7; i+=3) { // 1 2 3; 4 5 6; 7 8 9
for (int j = 1; j <= 9; j++) {
for (int k = 0; k <= 2; k++) {
int x = i + k;
System.out.print(x+" * "+j+" = "+x*j+" ");
}
System.out.println("");
}
System.out.println("");
}
}
public void t11() {
System.out.println("난이도: 3");
for (int i = 1; i <= 3; i++) { //1 4 7; 2 5 8; 3 6 9 //
for (int j = 1; j <= 9; j++) {
for (int k = 0; k <= 6; k+=3) {
int x = i + k;
System.out.print(x+" * "+j+" = "+x*j+" ");
}
System.out.println("");
}
System.out.println("");
}
}
public void t12() {
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 10; j++) {
if (i%10 == 0) {
System.out.print("─");
}
if (i == 5) {
if (j == 0) {
System.out.print("├");
} else if (j == 5) {
System.out.print("*");
} else if (j == 10) {
System.out.print("┤");
} else {
System.out.print("─");
}
}
if (j%5 == 0) {
if (i%5 != 0) {
System.out.print("│");
}
}
if (i%5 != 0 && j%5 != 0) {
if (i == j) {
System.out.print("\\");
} else if (i + j == 10) {
System.out.print("/");
} else {
System.out.print(" ");
}
}
}
System.out.println("");
}
}
}
| true |
80d8b3ea6bd4dd3b16b56590afffb9f86e0b9765 | Java | Iofthenight/spring-boot-ionic-backend | /src/main/java/com/iofhtenight/cursomc/repositories/PagamentoRepository.java | UTF-8 | 306 | 1.59375 | 2 | [] | no_license | package com.iofhtenight.cursomc.repositories;
import org.springframework.stereotype.Repository;
import com.iofhtenight.cursomc.domain.Pagamento;
import org.springframework.data.jpa.repository.JpaRepository;
@Repository
public interface PagamentoRepository extends JpaRepository<Pagamento, Integer>{
}
| true |
99bfd5414d7664a50fc5800a0f2bcc756d988d19 | Java | HSKKOU/FCCPC | /app/src/main/java/jp/fccpc/taskmanager/SQLite/Model/Task.java | UTF-8 | 3,427 | 2.453125 | 2 | [] | no_license | package jp.fccpc.taskmanager.SQLite.Model;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import jp.fccpc.taskmanager.Server.ServerConnector;
/**
* Created by hskk1120551 on 2015/10/16.
*/
public class Task {
public static final String TAG = Task.class.getSimpleName();
private long id;
private String title;
private String content;
private long deadline;
private boolean completeFlag;
private long created_at;
private long updated_at;
private String[] KEYS = {"group", "title", "deadline", "detail"};
public Task(){}
public Task(String _title, String _content, long _deadline, boolean _completeFlag, long _created_at){
super();
this.title = _title;
this.content = _content;
this.deadline = _deadline;
this.completeFlag = _completeFlag;
this.created_at = _created_at;
}
public Task(long _id, String _title, String _content, long _deadline, boolean _completeFlag, long _created_at){
this(_title, _content, _deadline, _completeFlag, _created_at);
this.id = _id;
}
public Task(long _id, String _title, String _content, long _deadline, int _completeFlag, long _created_at){
this(_title, _content, _deadline, (_completeFlag != 0), _created_at);
this.id = _id;
}
// id
public long getId(){return this.id;}
// title
public String getTitle(){return this.title;}
public void setTitle(String title){this.title = title;}
// content
public String getContent(){return this.content;}
public void setContent(String content){this.content = content;}
// deadline
public long getDeadline(){return this.deadline;}
public void setDeadline(long dealine){this.deadline = dealine;}
// completFlag
public boolean getCompleteFlag(){return this.completeFlag;}
public void setCompleteFlag(int completeFlag){this.completeFlag = (completeFlag != 0);}
public void setCompleteFlag(boolean completeFlag){this.completeFlag = completeFlag;}
// created_at
public long getCreated_at(){return this.created_at;}
public void setCreated_at(long created_at){this.created_at = created_at;}
// updated_at
public long getUpdated_at(){return this.updated_at;}
public void setUpdated_at(long updated_at){this.updated_at = updated_at;}
public String toString(){
return this.getId() + ", "
+ this.getTitle() + ", "
+ this.getContent() + ", "
+ this.getDeadline() + ", "
+ this.getCompleteFlag() + ", "
+ this.getCreated_at() + "";
}
public String getQuery() throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
// private String[] KEYS = {"group", "title", "deadline", "detail"};
// TODO: replace dummy_group
String[] values = {"12345", this.getTitle(), this.getDeadline()+"", this.getContent()+""};
for(int i = 0; i < Math.min(values.length, KEYS.length); i++) {
if(i > 0) result.append("&");
result.append(URLEncoder.encode(KEYS[i], ServerConnector.CHAR_SET));
result.append("=");
result.append(URLEncoder.encode(values[i], ServerConnector.CHAR_SET));
}
Log.d(TAG, "getQuery: " + result.toString());
return result.toString();
}
} | true |
e03080a036f8ac807bbf890ee9099a6c1fd71e52 | Java | Mrleob/netofthings | /.apt_generated/cn/tranway/ui/RegisterActivity$$ViewInjector.java | UTF-8 | 1,183 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | // Generated code from Butter Knife. Do not modify!
package cn.tranway.ui;
import android.view.View;
import butterknife.ButterKnife.Finder;
public class RegisterActivity$$ViewInjector {
public static void inject(Finder finder, final cn.tranway.ui.RegisterActivity target, Object source) {
View view;
view = finder.findRequiredView(source, 2131165209, "field 'mUpassWord'");
target.mUpassWord = (android.widget.TextView) view;
view = finder.findRequiredView(source, 2131165207, "field 'mUphone'");
target.mUphone = (android.widget.TextView) view;
view = finder.findRequiredView(source, 2131165211, "field 'mUpassWordAgain'");
target.mUpassWordAgain = (android.widget.TextView) view;
view = finder.findRequiredView(source, 2131165212, "method 'register'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.register();
}
});
}
public static void reset(cn.tranway.ui.RegisterActivity target) {
target.mUpassWord = null;
target.mUphone = null;
target.mUpassWordAgain = null;
}
}
| true |
fd3d9c2742b0b2996fe27875fa63b8d66fd83f48 | Java | nnicha123/Java | /leetCode/LongPressedName.java | UTF-8 | 514 | 3.3125 | 3 | [] | no_license | public class LongPressedName {
public static void main(String[] z){
System.out.println(isLongPressedName("leelee","lleeelee"));
}
public static boolean isLongPressedName(String name, String typed) {
String newStr = "";
newStr += typed.charAt(0);
for(int i=0;i<typed.length()-1;i++){
if(typed.charAt(i) != typed.charAt(i+1)){
newStr += typed.charAt(i+1);
}
}
System.out.println(newStr);
if(newStr.equals(name)){return true;}
else{return false;}
}
}
| true |
09d123984c145070726eac9ca97f9dd4b85e604c | Java | Morphite/WaterAssessment | /src/main/java/com/leonov/diplome/controller/RegisterController.java | UTF-8 | 904 | 2.171875 | 2 | [] | no_license | package com.leonov.diplome.controller;
import com.leonov.diplome.model.User;
import com.leonov.diplome.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class RegisterController {
@Autowired
private UserService userService;
@GetMapping("/register")
public String getRegPage() {
return "register";
}
@PostMapping("/register")
public String regNewUser(User user, Model model) {
boolean success = userService.register(user, model);
if (success) {
return "redirect:/login";
} else {
return "register";
}
}
} | true |
8dce84c1a1e3be7aa71d74a74c41c672000a0148 | Java | GustavoMietlicki1993/Curso-basico-de-Java- | /UltraEmojiCombat/src/ultraemojicombat/UltraEmojiCombat.java | UTF-8 | 261 | 2.28125 | 2 | [] | no_license |
package ultraemojicombat;
public class UltraEmojiCombat {
public static void main(String[] args) {
Lutador l[] = new Lutador[6];
l[0] = new Lutador("Pretty boy", "França", 31, 11, 2,1, 1.75f, 68.9f);
l[0].apresentar();
}
}
| true |
eddbdcf847c82036a2bf19caca8744309fdf5399 | Java | xMansour/Java-Programming-Solving-Problems-with-Software | /Week 3/src/ColdestDay.java | UTF-8 | 10,332 | 3.28125 | 3 | [] | no_license | import edu.duke.DirectoryResource;
import edu.duke.FileResource;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.File;
public class ColdestDay {
public static void main(String[] args) {
ColdestDay coldestDay = new ColdestDay();
//coldestDay.testColdestHourInFile();
//coldestDay.testFileWithColdestTemperature();
//coldestDay.testLowestHumidityInFile();
//coldestDay.testLowestHumidityInManyFiles();
coldestDay.testAverageTemperatureInFile();
//coldestDay.testAverageTemperatureWithHighHumidityInFile();
}
//Write a method named coldestHourInFile that has one parameter,
//a CSVParser named parser. This method returns the CSVRecord with the coldest temperature
//in the file and thus all the information about the coldest temperature,
//such as the hour of the coldest temperature. You should also write a void
//method named testColdestHourInFile() to test this method and print out information
//about that coldest temperature, such as the time of its occurrence.
//NOTE: Sometimes there was not a valid reading at a specific hour,
//so the temperature field says -9999. You should ignore these bogus temperature
//values when calculating the lowest temperature.
public CSVRecord coldestHourInFile(CSVParser parser) {
CSVRecord coldestSoFar = null;
for (CSVRecord currentRecord : parser) {
if (Double.parseDouble(currentRecord.get("TemperatureF")) == -9999)
continue;
if (coldestSoFar == null) {
coldestSoFar = currentRecord;
} else {
double coldestTemp = Double.parseDouble(coldestSoFar.get("TemperatureF"));
double currentTemp = Double.parseDouble(currentRecord.get("TemperatureF"));
if (coldestTemp > currentTemp) {
coldestSoFar = currentRecord;
}
}
}
return coldestSoFar;
}
public void testColdestHourInFile() {
FileResource fileResource = new FileResource();
CSVParser parser = fileResource.getCSVParser();
CSVRecord coldestSoFar = coldestHourInFile(parser);
String coldestTemp = coldestSoFar.get("TemperatureF");
String time = coldestSoFar.get("TimeEDT");
String humidity = coldestSoFar.get("Humidity");
System.out.println("Coldest temp " + coldestTemp + " at " + time + " and the humidity was " + humidity);
}
//Write the method fileWithColdestTemperature that has no parameters.
//This method should return a string that is the name of the file from selected files
//that has the coldest temperature. You should also write a void method named
//testFileWithColdestTemperature() to test this method. Note that after determining the
//filename, you could call the method coldestHourInFile to determine the coldest temperature on that day.
public String fileWithColdestTemperature() {
String coldestFileName = "";
CSVRecord coldestSoFar = null;
DirectoryResource resource = new DirectoryResource();
for (File file : resource.selectedFiles()) {
FileResource fileResource = new FileResource(file);
CSVParser parser = fileResource.getCSVParser();
CSVRecord current = coldestHourInFile(parser);
if (coldestSoFar == null) {
coldestSoFar = current;
coldestFileName = file.getName();
} else {
double currentTemp = Double.parseDouble(current.get("TemperatureF"));
double coldestTemp = Double.parseDouble(coldestSoFar.get("TemperatureF"));
if (coldestTemp > currentTemp) {
coldestSoFar = current;
coldestFileName = file.getName();
}
}
}
return coldestFileName;
}
public void testFileWithColdestTemperature() {
String coldestFileName = fileWithColdestTemperature();
FileResource fileResource = new FileResource("datasets/2014/" + coldestFileName);
CSVParser parser = fileResource.getCSVParser();
CSVRecord coldestRecord = coldestHourInFile(parser);
String coldestTemp = coldestRecord.get("TemperatureF");
System.out.println("File: " + coldestFileName + " has the coldest temperature and it is: " + coldestTemp);
}
//Write a method named lowestHumidityInFile that has one parameter,
//a CSVParser named parser. This method returns the CSVRecord that has the lowest humidity.
//If there is a tie, then return the first such record that was found.
//Note that sometimes there is not a number in the Humidity column but instead
//there is the string “N/A”. This only happens very rarely.
//You should check to make sure the value you get is not “N/A” before converting it to a number.
//Also note that the header for the time is either TimeEST or TimeEDT,
//depending on the time of year. You will instead use the DateUTC field
//at the right end of the data file to get both the date and time of a temperature reading
//You should also write a void method named testLowestHumidityInFile() to test this method that starts with these lines:
public CSVRecord lowestHumidityInFile(CSVParser parser) {
CSVRecord lowestHumidityRecord = null;
for (CSVRecord currentRecord : parser) {
if (currentRecord.get("Humidity").equals("N/A"))
continue;
if (lowestHumidityRecord == null) {
lowestHumidityRecord = currentRecord;
} else {
double lowestHumidity = Double.parseDouble(lowestHumidityRecord.get("Humidity"));
double currentHumidity = Double.parseDouble(currentRecord.get("Humidity"));
if (lowestHumidity > currentHumidity) {
lowestHumidityRecord = currentRecord;
}
}
}
return lowestHumidityRecord;
}
public void testLowestHumidityInFile() {
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
CSVRecord csvRecord = lowestHumidityInFile(parser);
String lowestHumidity = csvRecord.get("Humidity");
String date = csvRecord.get("DateUTC");
System.out.println("Lowest humidity is: " + lowestHumidity + " at " + date);
}
//Write the method lowestHumidityInManyFiles that has no parameters.
//This method returns a CSVRecord that has the lowest humidity over all the files.
//If there is a tie, then return the first such record that was found.
//You should also write a void method named testLowestHumidityInManyFiles()
//to test this method and to print the lowest humidity AND the time the lowest humidity occurred.
public CSVRecord lowestHumidityInManyFiles() {
CSVRecord lowestSoFar = null;
DirectoryResource resource = new DirectoryResource();
for (File file : resource.selectedFiles()) {
FileResource fileResource = new FileResource(file);
CSVParser parser = fileResource.getCSVParser();
CSVRecord current = lowestHumidityInFile(parser);
if (lowestSoFar == null) {
lowestSoFar = current;
} else {
double currentHumidity = Double.parseDouble(current.get("Humidity"));
double lowestHumidity = Double.parseDouble(lowestSoFar.get("Humidity"));
if (lowestHumidity > currentHumidity) {
lowestSoFar = current;
}
}
}
return lowestSoFar;
}
public void testLowestHumidityInManyFiles() {
CSVRecord lowestHumidityRecord = lowestHumidityInManyFiles();
String lowestHumidity = lowestHumidityRecord.get("Humidity");
String date = lowestHumidityRecord.get("DateUTC");
System.out.println("lowest humidity: " + lowestHumidity + " at " + date);
}
//Write the method averageTemperatureInFile that has one parameter,
//a CSVParser named parser. This method returns a double that represents the average temperature in the file.
//You should also write a void method named testAverageTemperatureInFile() to test this method.
public double averageTemperatureInFile(CSVParser parser) {
double tempSum = 0.0;
int count = 0;
for (CSVRecord record : parser) {
double temp = Double.parseDouble(record.get("TemperatureF"));
tempSum += temp;
count++;
}
return tempSum / count;
}
public void testAverageTemperatureInFile() {
FileResource fileResource = new FileResource();
CSVParser parser = fileResource.getCSVParser();
System.out.println("Average temperature is: " + averageTemperatureInFile(parser));
}
//Write the method averageTemperatureWithHighHumidityInFile that has two parameters,
//a CSVParser named parser and an integer named value.
//This method returns a double that represents the average temperature
//of only those temperatures when the humidity was greater than or equal to value.
//You should also write a void method named testAverageTemperatureWithHighHumidityInFile() to test this method.
public double averageTemperatureWithHighHumidityInFile(CSVParser parser, int value) {
double tempSum = 0.0;
int count = 0;
for (CSVRecord record : parser) {
int currentHumidity = Integer.parseInt(record.get("Humidity"));
if (currentHumidity >= value) {
double temp = Double.parseDouble(record.get("TemperatureF"));
tempSum += temp;
count++;
}
}
return tempSum / count;
}
public void testAverageTemperatureWithHighHumidityInFile() {
FileResource fileResource = new FileResource();
CSVParser parser = fileResource.getCSVParser();
int lowestHumidity = 80;
double averageTemp = averageTemperatureWithHighHumidityInFile(parser, lowestHumidity);
System.out.println("Average temperature with humidity equal or greater to 80 is: " + averageTemp);
}
}
| true |
64e25c9d23a4e76108db1082ba5ad30777c2854c | Java | del1/sourcenext | /agent/src/main/java/com/mobiroo/n/sourcenextcorporation/agent/service/AgentDashClockService.java | UTF-8 | 2,075 | 1.960938 | 2 | [] | no_license | package com.mobiroo.n.sourcenextcorporation.agent.service;
import android.content.Context;
import android.content.Intent;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.mobiroo.n.sourcenextcorporation.agent.R;
import com.mobiroo.n.sourcenextcorporation.agent.activity.MainActivity;
import com.mobiroo.n.sourcenextcorporation.agent.item.Agent;
import com.mobiroo.n.sourcenextcorporation.agent.item.AgentFactory;
import com.mobiroo.n.sourcenextcorporation.agent.receiver.AgentStatusChangedReceiver;
import java.util.List;
public class AgentDashClockService extends DashClockExtension {
AgentStatusChangedReceiver mReceiver;
protected void onInitialize(boolean isReconnect) {
mReceiver = new AgentStatusChangedReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
AgentDashClockService.this.onUpdateData(0);
}
};
registerReceiver(mReceiver, AgentStatusChangedReceiver.getFilterAllActions());
}
@Override
protected void onUpdateData(int arg0) {
List<Agent> agents = AgentFactory.getActiveAgents(this);
String title = "";
String body = "";
String bodyConcat = "";
String status = Integer.toString(agents.size()) + getResources().getString(R.string.dashclock_status_trailer);
if(agents.size() > 0) {
title = Integer.toString(agents.size()) + getResources().getString(R.string.dashclock_title_end);
bodyConcat = getResources().getString(R.string.dashclock_status_expanded_start);
for(Agent agent : agents) {
body = bodyConcat;
body += agent.getName();
bodyConcat += ", ";
}
} else {
title = getResources().getString(R.string.dashclock_no_agents_running);
body = "";
}
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.ic_launcher_nob)
.status(status)
.expandedTitle(title)
.expandedBody(body)
.clickIntent(new Intent(this, MainActivity.class)));
}
}
| true |
e7665ba36be5303572468469a33e09f58c9f4f7b | Java | LeanderK/IzouTTSExtensionCollection | /src/main/java/leanderk/izou/tts/commonextensions/WelcomeExtension.java | UTF-8 | 4,036 | 2.34375 | 2 | [] | no_license | package leanderk.izou.tts.commonextensions;
import leanderk.izou.tts.outputextension.TTSData;
import leanderk.izou.tts.outputextension.TTSOutputExtension;
import org.intellimate.izou.events.EventModel;
import org.intellimate.izou.resource.ResourceModel;
import org.intellimate.izou.sdk.Context;
import org.intellimate.izou.sdk.events.CommonEvents;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Created by LeanderK on 14/11/14.
*/
public class WelcomeExtension extends TTSOutputExtension {
public static final String ID = WelcomeExtension.class.getCanonicalName();
private static final String PERSONAL_INFORMATION_ID = "leanderk.izou.personalinformation.InformationCG.ResourceInfo";
public static final String TTS_Greeting_MORNING = "greetingMorning";
public static final String TTS_Greeting_MIDDAY = "greetingMidday";
public static final String TTS_Greeting_Evening = "greetingEvening";
public static final String TTS_Greeting = "greeting";
public static final String TTS_Salutation = "salutation";
/**
* creates a new outputExtension with a new id
*/
public WelcomeExtension(Context context) {
super(ID, context);
addResourceIdToWishList(PERSONAL_INFORMATION_ID);
setPluginId("leanderk.izou.tts.outputplugin.TTSOutputPlugin");
}
@Override
public TTSData generateSentence(EventModel event) {
if (!event.containsDescriptor(CommonEvents.Response.FULL_RESPONSE_DESCRIPTOR) &&
!event.containsDescriptor(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR) &&
!event.containsDescriptor(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR))
return null;
List<ResourceModel> resources = event.getListResourceContainer().provideResource(PERSONAL_INFORMATION_ID);
StringBuilder words = new StringBuilder();
if(isMorning()) {
words.append(getWords(TTS_Greeting_MORNING, null));
} else if(isEvening()) {
words.append(getWords(TTS_Greeting_Evening, null));
} else {
words.append(getWords(TTS_Greeting, null));
}
if(resources.isEmpty()) {
words.append(".");
}
else {
try {
@SuppressWarnings("unchecked")
HashMap<String, String> information = (HashMap<String, String>) resources.get(0).getResource();
words.append(", ");
words.append(getWords(TTS_Salutation, information));
words.append("!");
} catch (ClassCastException e) {
words.append(".");
}
}
TTSData ttsData = TTSData.createTTSData(words.toString(), getLocale(), 0, ID);
return ttsData;
}
@Override
public boolean canGenerateForLanguage(String locale) {
//support for german and english
if(locale.equals(new Locale("de").getLanguage())) {
return true;
} else if (locale.equals(new Locale("en").getLanguage())) {
return true;
}
return false;
}
public boolean isMorning() {
Calendar upperLimit = Calendar.getInstance();
upperLimit.set(Calendar.HOUR_OF_DAY, 12);
upperLimit.set(Calendar.MINUTE, 00);
Calendar lowerLimit = Calendar.getInstance();
lowerLimit.set(Calendar.HOUR_OF_DAY, 04);
lowerLimit.set(Calendar.MINUTE,00);
Calendar now = Calendar.getInstance();
return now.before(upperLimit) && now.after(lowerLimit);
}
public boolean isEvening() {
Calendar upperLimit = Calendar.getInstance();
upperLimit.set(Calendar.HOUR_OF_DAY, 23);
upperLimit.set(Calendar.MINUTE, 55);
Calendar lowerLimit = Calendar.getInstance();
lowerLimit.set(Calendar.HOUR_OF_DAY, 18);
lowerLimit.set(Calendar.MINUTE,00);
Calendar now = Calendar.getInstance();
return now.before(upperLimit) && now.after(lowerLimit);
}
}
| true |
4bae39991c0e2ec17db11da1762ab8e8126b5314 | Java | kasper189/cluster | /src/it/polito/dp2/PJS/lab6/tests/HostImpl.java | UTF-8 | 1,197 | 2.734375 | 3 | [] | no_license | package it.polito.dp2.PJS.lab6.tests;
import it.polito.dp2.PJS.Host;
import it.polito.dp2.PJS.lab6.tests.gen.jaxb.THost;
import it.polito.dp2.PJS.lab6.tests.gen.jaxb.THostStatus;
import it.polito.dp2.PJS.lab6.tests.gen.jaxb.THostType;
public class HostImpl implements Host {
THost h;
/**
* @param h
*/
public HostImpl(THost h) {
this.h = h;
}
@Override
public int getLoad() {
return h.getLoad().intValue();
}
@Override
public String getName() {
return h.getName();
}
@Override
public int getPhysicalMemory() {
return h.getMemory().intValue();
}
@Override
public HostStatus getStatus() {
return convertStatus(h.getStatus());
}
private HostStatus convertStatus(THostStatus status) {
switch(status) {
case CLOSED : return HostStatus.CLOSED;
case OK : return HostStatus.OK;
case UNAVAIL : return HostStatus.UNAVAIL;
case UNLICENSED : return HostStatus.UNLICENSED;
}
return null;
}
@Override
public boolean isMaster() {
return (h.getType())==THostType.MASTER;
}
@Override
public boolean isServer() {
return (h.getType())==THostType.SERVER || (h.getType()) ==THostType.MASTER;
}
public String getURI() {
return h.getUri();
}
}
| true |
21a9adc5c996bc3945dc762e12e18b2655706c44 | Java | mjapon/smartfact | /src/smf/gui/clientes/ClientesFrame.java | UTF-8 | 23,221 | 2.203125 | 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 smf.gui.clientes;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import smf.controller.ClientesJpaController;
import smf.entity.Clientes;
import smf.gui.BaseFrame;
import smf.gui.SmartFactMain;
import smf.gui.facte.FacturaVentaFrame;
import smf.util.EstadoAPP;
import smf.util.FechasUtil;
import smf.util.datamodels.ClientesDM;
import smf.util.datamodels.DefGSVCol;
import smf.util.datamodels.JTableColumn;
/**
*
* @author mjapon
*/
public class ClientesFrame extends BaseFrame {
private ClientesDM clientesDM;
private ClientesJpaController controller;
private List<JTableColumn> columns;
private Integer tipo;
/**
* Creates new form ClientesFrame
*/
public ClientesFrame(Integer tipo) {
this.tipo = tipo;
initComponents();
controller = new ClientesJpaController(em);
initColumn();
clientesDM = new ClientesDM(columns, controller, tipo);
jTableMain.setModel(clientesDM);
jTableMain.getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int col = jTableMain.columnAtPoint(e.getPoint());
try{
for (int i=0; i<clientesDM.getColumnCount();i++){
jTableMain.getColumnModel().getColumn(i).setHeaderValue( clientesDM.getColumnName(i) );
}
clientesDM.switchSortColumn(col);
}
catch(Throwable ex){
showMsgError(ex);
}
}
});
jTableMain.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
btnHistServ.setEnabled( jTableMain.getSelectedRows().length>0 );
btnFacturar.setEnabled( jTableMain.getSelectedRows().length>0 );
}
}
});
String titulo = "";
switch(tipo){
case 1: {titulo="LISTA DE CLIENTES"; break;}
case 2: {titulo="LISTA DE PROVEEDORES"; break;}
default:{titulo="";break;}
}
jLabelTit.setText(titulo);
}
private void initColumn(){
columns = new ArrayList<>();
columns.add(new JTableColumn<Clientes>(
0,
"Ci/Ruc",
"cliCi",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliCi();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
String newCi = String.valueOf(value).trim().toUpperCase();
if (newCi.length()>0){
if (!row.getCliCi().equalsIgnoreCase(newCi)){
if ( controller.findByCi(newCi)!= null){
showMsg("Ya existe un referente con el numero de ci/ruc ingresado, no se puede actualizar");
}
else{
row.setCliCi(String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
}
}
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(new JTableColumn<Clientes>(
1,
"Nombres",
"cliNombres",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliNombres();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
row.setCliNombres(String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(new JTableColumn<Clientes>(
2,
"Apellidos",
"cliApellidos",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliApellidos();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
row.setCliApellidos(String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(new JTableColumn<Clientes>(
3,
"Dirección",
"cliDir",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliDir();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
row.setCliDir( String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(new JTableColumn<Clientes>(
4,
"Teléfono",
"cliTelf",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliTelf();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
row.setCliTelf(String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(new JTableColumn<Clientes>(
5,
"Email",
"cliEmail",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliEmail();
}
@Override
public boolean isCellEditable(Clientes row) {
return true;
}
@Override
public void setValueAt(Clientes row, int rowIndex, Object value) {
try{
row.setCliEmail(String.valueOf(value).trim().toUpperCase() );
controller.edit(row);
SmartFactMain.showSystemTrayMsg("Los cambios han sido registrados");
}
catch(Throwable ex){
showMsgError(ex);
}
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
}
)
);
columns.add(
new JTableColumn<Clientes>(
6,
"Fecha Registro",
"cliFechareg",
String.class,
new DefGSVCol<Clientes>() {
public Object getValueAt(Clientes row, int rowIndex) {
return row.getCliFechareg()!=null? FechasUtil.format(row.getCliFechareg()):"" ;
}
}
)
);
}
public void buscar(){
try{
String filtro = jTFFiltro.getText();
clientesDM.setFiltro(filtro);
clientesDM.loadFromDataBase();
clientesDM.fireTableDataChanged();
}
catch(Throwable ex){
showMsgError(ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTableMain = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jLabelTit = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jTFFiltro = new javax.swing.JTextField();
jBtnBuscar = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
btnHistServ1 = new javax.swing.JButton();
btnHistServ = new javax.swing.JButton();
btnFacturar = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jPanel1.setLayout(new java.awt.BorderLayout());
jTableMain.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jTableMain.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTableMain.setRowHeight(20);
jScrollPane1.setViewportView(jTableMain);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new java.awt.BorderLayout());
jLabelTit.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
jLabelTit.setText("LISTA DE PERSONAS");
jPanel2.add(jLabelTit, java.awt.BorderLayout.NORTH);
jPanel4.setLayout(new java.awt.BorderLayout());
jTFFiltro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTFFiltroActionPerformed(evt);
}
});
jTFFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTFFiltroKeyReleased(evt);
}
});
jPanel4.add(jTFFiltro, java.awt.BorderLayout.CENTER);
jBtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/smf/gui/icons/icons8-search.png"))); // NOI18N
jBtnBuscar.setText("Buscar");
jBtnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnBuscarActionPerformed(evt);
}
});
jPanel4.add(jBtnBuscar, java.awt.BorderLayout.EAST);
jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH);
jPanel3.setLayout(new java.awt.GridLayout(8, 1));
btnHistServ1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
btnHistServ1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/smf/gui/icons/Plus_25px.png"))); // NOI18N
btnHistServ1.setText("Nuevo");
btnHistServ1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHistServ1ActionPerformed(evt);
}
});
jPanel3.add(btnHistServ1);
btnHistServ.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
btnHistServ.setIcon(new javax.swing.ImageIcon(getClass().getResource("/smf/gui/icons/icons8-view_details.png"))); // NOI18N
btnHistServ.setText("Historia");
btnHistServ.setEnabled(false);
btnHistServ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHistServActionPerformed(evt);
}
});
jPanel3.add(btnHistServ);
btnFacturar.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
btnFacturar.setText("Facturar");
btnFacturar.setEnabled(false);
btnFacturar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFacturarActionPerformed(evt);
}
});
jPanel3.add(btnFacturar);
btnClose.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/smf/gui/icons/icons8-close_pane_filled.png"))); // NOI18N
btnClose.setText("Cerrar");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
jPanel3.add(btnClose);
getContentPane().add(jPanel3, java.awt.BorderLayout.EAST);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
//this.setVisible(false);
SmartFactMain farmaApp = (SmartFactMain)this.root;
farmaApp.logicaClosePane(this.getClass().getName()+String.valueOf(tipo));
}//GEN-LAST:event_btnCloseActionPerformed
private void jBtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnBuscarActionPerformed
buscar();
}//GEN-LAST:event_jBtnBuscarActionPerformed
private void jTFFiltroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTFFiltroKeyReleased
buscar();
}//GEN-LAST:event_jTFFiltroKeyReleased
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
}//GEN-LAST:event_formWindowActivated
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
try{
buscar();
}
catch(Throwable ex){
showMsgError(ex);
}
}//GEN-LAST:event_formWindowOpened
private void btnHistServActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHistServActionPerformed
try{
int[] rows = jTableMain.getSelectedRows();
Clientes cliente = clientesDM.getValueAt(rows[0]);
HistServCliFrame histServCliFrame = new HistServCliFrame(cliente.getCliId());
histServCliFrame.setPreferredSize(new Dimension(800, 500));
histServCliFrame.pack();
histServCliFrame.centerOnScreen();
histServCliFrame.setVisible(true);
}
catch(Throwable ex){
showMsgError(ex);
}
}//GEN-LAST:event_btnHistServActionPerformed
private void jTFFiltroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTFFiltroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTFFiltroActionPerformed
private void btnFacturarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFacturarActionPerformed
try{
EstadoAPP estadoApp =SmartFactMain.estadosApp.get(FacturaVentaFrame.class.getName()+"1");
FacturaVentaFrame fvframe = (FacturaVentaFrame)estadoApp.getFrame();
int[] rows = jTableMain.getSelectedRows();
Clientes cliente = clientesDM.getValueAt(rows[0]);
if (cliente.getCliCi().trim().length()>0){
fvframe.loadDatosCli(cliente.getCliCi());
((SmartFactMain)root).logicaOpenPane(estadoApp);
}
else{
showMsg("No se puede crear factura, no tiene asignado CI/RUC");
}
}
catch(Throwable ex){
showMsgError(ex);
}
}//GEN-LAST:event_btnFacturarActionPerformed
private void btnHistServ1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHistServ1ActionPerformed
NewPersonaFrame newPersonaFrame = new NewPersonaFrame(this, this.tipo);
newPersonaFrame.centerOnScreen();
newPersonaFrame.setVisible(true);
}//GEN-LAST:event_btnHistServ1ActionPerformed
public void afterCloseNewPersona(){
try{
System.out.println("afterCloseNewPersona----->");
buscar();
}
catch(Throwable ex){
showMsgError(ex);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnFacturar;
private javax.swing.JButton btnHistServ;
private javax.swing.JButton btnHistServ1;
private javax.swing.JButton jBtnBuscar;
private javax.swing.JLabel jLabelTit;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTFFiltro;
private javax.swing.JTable jTableMain;
// End of variables declaration//GEN-END:variables
}
| true |
519c81f67c2a6e37ce488441fb5bc81a2ac7eece | Java | YeeeeahRight/SymbolsErrorFixer | /src/main/java/com/fixer/data/acquirer/impl/FileDataAcquirer.java | UTF-8 | 1,550 | 3.109375 | 3 | [] | no_license | package com.fixer.data.acquirer.impl;
import com.fixer.data.acquirer.DataAcquirer;
import com.fixer.exceptions.InputStreamException;
import com.fixer.exceptions.TextFileNotFoundException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileDataAcquirer implements DataAcquirer {
private static final String FILE_NOT_FOUND_MESSAGE = "Your file is not found.";
private static final String INPUT_ERROR_EXCEPTION = "Something wrong with file input.";
private static final String CLOSE_EXCEPTION_MESSAGE = "Error with closing reader.";
private String filePath;
public FileDataAcquirer(final String filePath) {
this.filePath = filePath;
}
public String getText() throws TextFileNotFoundException, InputStreamException {
BufferedReader fileReader = null;
String text;
try {
fileReader = new BufferedReader(new FileReader(filePath));
text = fileReader.readLine();
} catch (FileNotFoundException e) {
throw new TextFileNotFoundException(FILE_NOT_FOUND_MESSAGE);
} catch (IOException e) {
throw new InputStreamException(INPUT_ERROR_EXCEPTION);
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
System.out.println(CLOSE_EXCEPTION_MESSAGE);
}
}
}
return text;
}
}
| true |
5952279ce9a84bd5aab27383137707b88eb8e1ae | Java | cckmit/htd | /mes-service/src/main/java/com/skeqi/mes/util/chenj/RestTemplateHttpUtils.java | UTF-8 | 1,791 | 2.203125 | 2 | [
"MIT"
] | permissive | package com.skeqi.mes.util.chenj;
import com.skeqi.mes.mapper.wf.linesidelibrary.CLslDictionaryTMapper;
import com.skeqi.mes.pojo.wf.linesidelibrary.CLslDictionaryT;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author ChenJ
* @date 2021/7/30
* @Classname RestTemplateHttp
* @Description
*/
@Component
public class RestTemplateHttpUtils {
@Resource
private RestTemplate restTemplate;
@Resource
private CLslDictionaryTMapper cLslDictionaryTMapper;
/**
* 发送post请求远程调用
* @param map
* @throws Exception
*/
public String sendPostRequestKThree(Map<String, Object> map) {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("jktype", "PORequest");
// map.put("method", "view");
// map.put("filter", "");
// 将编码改为utf-8
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
// 获取请求路径
// kThreeUrl K3接口访问地址
CLslDictionaryT kThreeUrl = cLslDictionaryTMapper.selectByKey(String.valueOf(map.get("key")));
String requestUrl = kThreeUrl.getValue();
ResponseEntity<String> forEntity = restTemplate.postForEntity(requestUrl, map, String.class);
return forEntity.getBody();
// } else {
// return Rjson.error("服务不可用,请稍后再试"+String.valueOf(System.currentTimeMillis()).substring(0,10));
// return null;
// }
}
}
| true |
94675fad8be04df77b4311969bdb2ef435ceac16 | Java | fangke-ray/RVS-main-OSH | /rvs7.6/src/com/osh/rvs/action/partial/PartialOrderManageAction.java | UTF-8 | 10,663 | 1.867188 | 2 | [] | no_license | package com.osh.rvs.action.partial;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionManager;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.osh.rvs.bean.LoginData;
import com.osh.rvs.bean.data.MaterialEntity;
import com.osh.rvs.bean.partial.MaterialPartialEntity;
import com.osh.rvs.common.RvsConsts;
import com.osh.rvs.form.data.MaterialForm;
import com.osh.rvs.form.partial.PartialOrderManageForm;
import com.osh.rvs.service.MaterialPartialService;
import com.osh.rvs.service.partial.PartialOrderManageService;
import framework.huiqing.action.BaseAction;
import framework.huiqing.bean.message.MsgInfo;
import framework.huiqing.common.util.copy.BeanUtil;
import framework.huiqing.common.util.copy.CopyOptions;
import framework.huiqing.common.util.copy.IntegerConverter;
import framework.huiqing.common.util.validator.Validators;
public class PartialOrderManageAction extends BaseAction {
private Logger log = Logger.getLogger(getClass());
private PartialOrderManageService service = new PartialOrderManageService();
public void init(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res,
SqlSession conn) throws Exception {
log.info("PartialOrderManageAction.init start");
actionForward = mapping.findForward(FW_INIT);
log.info("PartialOrderManageAction.init end");
}
/**
* 查询未完成和已经完成的维修对象
* @param mapping
* @param form
* @param req
* @param res
* @param conn
* @throws Exception
*/
public void search(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res, SqlSession conn) throws Exception {
log.info("PartialOrderManageAction.search start");
// Ajax回馈对象
Map<String, Object> listResponse = new HashMap<String, Object>();
// 检索条件表单合法性检查
Validators v = BeanUtil.createBeanValidators(form, BeanUtil.CHECK_TYPE_PASSEMPTY);
List<MsgInfo> errors = v.validate();
LoginData user = (LoginData) req.getSession().getAttribute(RvsConsts.SESSION_USER);
String fact = RvsConsts.ROLE_FACTINLINE.equals(user.getRole_id()) ? "fact" : null;
if (errors.size() == 0) {
// 执行检索
List<PartialOrderManageForm> partialOrderManageFormList = service.searchMaterial(form, fact, conn, errors);
// 查询结果放入Ajax响应对象
listResponse.put("partialOrderManageFormList", partialOrderManageFormList);
}
listResponse.put("fact", fact);
// 检查发生错误时报告错误信息
listResponse.put("errors", errors);
// 返回Json格式响应信息
returnJsonResponse(res, listResponse);
log.info("PartialOrderManageAction.search end");
}
/**
* 维修对象详细信息
*
* @param mapping
* @param form
* @param req
* @param response
* @param conn
* @throws Exception
*/
public void detail(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse response,
SqlSession conn) throws Exception {
log.info("PartialOrderManageAction.detail start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
MaterialEntity materialEntity = new MaterialEntity();
PartialOrderManageForm partialOrderManageForm = (PartialOrderManageForm) form;
materialEntity.setMaterial_id(partialOrderManageForm.getMaterial_id());
//判断双击时才出发维修详细信息的查找,其他情况就只对订购零件的信息查询
if(req.getParameter("append").equals("true")){
/* 查询维修对象的详细显示信息 */
List<MaterialForm> materialDetail = service.searchMaterialDetail(materialEntity, conn);
for (int i = 0; i < materialDetail.size(); i++) {
MaterialForm materialForm = materialDetail.get(0);
listResponse.put("materialDetail", materialForm);
}
}
/*根据belongs查询所有零件 */
List<PartialOrderManageForm> partialOrderManageFormList = service.searchPartialOrder(partialOrderManageForm,conn);
listResponse.put("partialOrderManageFormList", partialOrderManageFormList);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.detail end");
}
/**
* 双击根据KEY获取material_partial_detail详细数据
* @param mapping
* @param form
* @param req
* @param response
* @param conn
* @throws Exception
*/
public void materialPartialDetail(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse response,
SqlSession conn) throws Exception {
log.info("PartialOrderManageAction.materialPartialDetail start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
//维修对象零件详细信息显示-零件追加分配的时候弹出的dialog
PartialOrderManageForm partialOrderManageForm= service.getDBMaterialPartialDetail(req.getParameter("material_partial_detail_key"),req.getParameter("modelID"),conn,errors,listResponse);
listResponse.put("partialOrderManageForm", partialOrderManageForm);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.materialPartialDetail end");
}
/**
* 进行追加编辑(分配工位)
* @param mapping
* @param form
* @param request
* @param response
* @param conn
* @throws Exception
*/
public void doupdatePosition(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,
SqlSessionManager conn) throws Exception {
log.info("PartialOrderManageAction.doupdatePosition start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
PartialOrderManageForm partialOrderManageForm = (PartialOrderManageForm) form;
//直接更新双击的零件的工位
service.updateMaterialPartialDetailProcesscode(partialOrderManageForm, conn,errors);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.doupdatePosition end");
}
/**
* 选择零件任意零件点击删除按钮,进行零件的删除
* @param mapping
* @param form
* @param request
* @param response
* @param conn
* @throws Exception
*/
public void dodeletePartial(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,
SqlSessionManager conn) throws Exception {
log.info("PartialOrderManageAction.dodeletePartial start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
PartialOrderManageForm partialOrderManageForm = (PartialOrderManageForm) form;
//直接删除零件
service.deletePartial(partialOrderManageForm, conn,errors);
// bo状态重新设定
MaterialPartialService mpservice = new MaterialPartialService();
MaterialPartialEntity materialPartialEntity = new MaterialPartialEntity();
CopyOptions cos = new CopyOptions();
cos.include("material_id", "occur_times");
cos.converter(IntegerConverter.getInstance(), "occur_times");
BeanUtil.copyToBean(partialOrderManageForm, materialPartialEntity, cos);
mpservice.updateBoFlgWithDetail(materialPartialEntity, conn);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.dodeletePartial end");
}
/**
* 取消零件发放
* @param mapping
* @param form
* @param request
* @param response
* @param conn
* @throws Exception
*/
public void doupdatedetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,
SqlSessionManager conn) throws Exception {
log.info("PartialOrderManageAction.doupdatedetail start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
PartialOrderManageForm partialOrderManageForm = (PartialOrderManageForm) form;
//更新零件待发放数量是订购数量、没有最后发放时间
service.updateMaterialPartialDetail(partialOrderManageForm, conn,errors);
// bo状态重新设定
MaterialPartialService mpservice = new MaterialPartialService();
MaterialPartialEntity materialPartialEntity = new MaterialPartialEntity();
CopyOptions cos = new CopyOptions();
cos.include("material_id", "occur_times");
cos.converter(IntegerConverter.getInstance(), "occur_times");
BeanUtil.copyToBean(partialOrderManageForm, materialPartialEntity, cos);
mpservice.updateBoFlgWithDetailMaintance(materialPartialEntity, conn);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.doupdatedetail end");
}
/**
* 取消订购
* @param mapping
* @param form
* @param request
* @param response
* @param conn
* @throws Exception
*/
public void dodeletematerialpartial(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,
SqlSessionManager conn) throws Exception {
log.info("PartialOrderManageAction.dodeletematerialpartial start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
PartialOrderManageForm partialOrderManageForm = (PartialOrderManageForm) form;
//更新零件待发放数量是订购数量、没有最后发放时间
service.deleteMaterialPartial(partialOrderManageForm,conn,errors);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.dodeletematerialpartial end");
}
/**
* 无BO
* @param mapping
* @param form
* @param request
* @param response
* @param conn
* @throws Exception
*/
public void doNoBo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,SqlSessionManager conn) throws Exception {
log.info("PartialOrderManageAction.doNoBo start");
Map<String, Object> listResponse = new HashMap<String, Object>();
List<MsgInfo> errors = new ArrayList<MsgInfo>();
service.nobo(form, conn);
listResponse.put("errors", errors);
returnJsonResponse(response, listResponse);
log.info("PartialOrderManageAction.doNoBo start");
}
} | true |
f9f2117203866ee47308bc7d49e9018918038e9c | Java | Jallal/dataStructures | /sortingAlgorithms/src/MergeSort.java | UTF-8 | 1,637 | 3.671875 | 4 | [] | no_license |
public class MergeSort {
/**
* Merge sort is optimal with respect to # compares
* Merge sort is not optimal with respect to space usage
*/
public static void sort(Comparable[] a) {
Comparable[] aux= new Comparable[a.length];
sort(a,aux,0,a.length);
}
public static void sort(Comparable[] a, Comparable[] aux, int lo, int hi){
if(hi<=lo){
int mid = lo+(hi-lo)/2; //compute the value of the mid point
sort(a,aux,lo,mid);//sort the first half
sort(a,aux,mid+1,hi);//sort the 2nd half
merge(a,aux,lo,mid,hi);//merge the 2 together
}
}
public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
for (int k = 0; k <= hi; k++) {
aux[k] = a[k];
}
int i = lo;
int j = mid + 1;
for (int k = 0; i <= hi; k++) {
if (i > mid) {
a[k] = aux[j++]; //i is exhausted
} else if (j > hi) {
a[k] = aux[j++]; //j is exhausted
} else if (less(aux[j], aux[i])) {
a[k] = aux[j++];
} else {
a[k] = aux[i++];
}
}
}
/*
*is item v less than w
*/
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < SelectionSort.ZERO;
}
/**
* swap item in array a[] at index i with the one at index j
*/
private static void exch(Comparable[] a, int i, int j) {
Comparable swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
| true |
d0229567318ad7f19b256b5a3940046328e8c836 | Java | CIResearchGroup/enunciate | /core/src/main/java/com/webcohesion/enunciate/module/ApiRegistryProviderModule.java | UTF-8 | 305 | 1.757813 | 2 | [
"Apache-2.0"
] | permissive | package com.webcohesion.enunciate.module;
/**
* Marker interface for a module that provides elements to the API registry.
*
* @author Ryan Heaton
*/
public interface ApiRegistryProviderModule extends ApiRegistryAwareModule {
enum DataTypeDetectionStrategy {
passive,
aggressive,
local
}
}
| true |
9c979eec87060a271ec91fdc75edbbb6c4b51e4e | Java | foxycom/reval-android | /app/src/test/java/pl/edu/amu/wmi/reval/subject/SubjectServiceTest.java | UTF-8 | 1,121 | 2.140625 | 2 | [] | no_license | package pl.edu.amu.wmi.reval.subject;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import pl.edu.amu.wmi.reval.SignedDaggerServiceTest;
import retrofit2.Response;
public class SubjectServiceTest extends SignedDaggerServiceTest {
SubjectService subjectService;
@Before
@Override
public void setUp() {
super.setUp();
subjectService = retrofit.create(SubjectService.class);
}
@Test
public void getSubjectsTestAdmin() throws InterruptedException, TimeoutException, IOException {
super.setUpAdmin();
Response<List<Subject>> response = subjectService.getSubjects().execute();
Assert.assertTrue(response.body().size() > 0);
}
@Test
public void getSubjectsTestStudent() throws InterruptedException, TimeoutException, IOException {
super.setUpStudent();
Response<List<Subject>> response = subjectService.getSubjects().execute();
Assert.assertTrue(response.body().size() > 0);
}
}
| true |
34bdd926a2fd1b6dba48111b8445cd21b481534a | Java | vishnuaggarwal23/quartzscheduler | /quartz-core/src/main/java/com/vishnu/aggarwal/quartz/core/service/BaseService.java | UTF-8 | 2,508 | 2.375 | 2 | [] | no_license | package com.vishnu.aggarwal.quartz.core.service;
/*
Created by vishnu on 5/3/18 10:37 AM
*/
import com.vishnu.aggarwal.quartz.core.config.BaseMessageResolver;
import lombok.NonNull;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import static java.text.MessageFormat.format;
import static org.apache.commons.lang3.ObjectUtils.allNotNull;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* The type Base service.
*/
@CommonsLog
public abstract class BaseService {
/**
* The Base message resolver.
*/
@Autowired
protected BaseMessageResolver baseMessageResolver;
/**
* Gets message.
*
* @param messageCode the message code
* @return the message
*/
@NonNull
@NotEmpty
@NotBlank
protected final String getMessage(@NonNull @NotBlank @NotEmpty final String messageCode) {
return baseMessageResolver.getMessage(messageCode);
}
@NonNull
@NotEmpty
@NotBlank
protected final String getMessage(@NonNull @NotEmpty @NotBlank final String messageCode, @NonNull @NotEmpty @NotBlank final String defaultMessage) {
return baseMessageResolver.getMessage(messageCode, defaultMessage);
}
@NonNull
@NotEmpty
@NotBlank
final public String getMessage(@NonNull @NotEmpty @NotBlank final String messageCode, @NonNull @NotEmpty @NotBlank final String defaultMessage, @NonNull @NotEmpty final Object... args) {
return baseMessageResolver.getMessage(messageCode, args, defaultMessage);
}
@NonNull
@NotEmpty
@NotBlank
final public String getMessage(@NonNull @NotEmpty @NotBlank final String messageCode,@NonNull @NotEmpty final Object... args) {
return baseMessageResolver.getMessage(messageCode, args);
}
/**
* Format message string.
*
* @param messagePattern the message pattern
* @param messageArguments the message arguments
* @return the string
*/
protected String formatMessage(String messagePattern, Object... messageArguments) {
if (isNotBlank(messagePattern)) {
if (allNotNull(messageArguments)) {
return format(messagePattern, messageArguments);
}
return format(messagePattern);
}
return EMPTY;
}
}
| true |
fbc959f23d69767ef76c066fd864077ff802cb64 | Java | Abdera7mane/ClanZ | /src/main/java/me/abdera7mane/clans/types/Clan.java | UTF-8 | 13,712 | 2.765625 | 3 | [
"MIT"
] | permissive | package me.abdera7mane.clans.types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import me.abdera7mane.clans.events.ClanDeleteEvent;
import me.abdera7mane.clans.events.PlayerJoinClanEvent;
import me.abdera7mane.clans.events.PlayerLeaveClanEvent;
import me.abdera7mane.clans.messages.formatter.Formatter;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.metadata.Metadatable;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class Clan implements Metadatable, Formatter {
private final String name;
private final Date creationDate;
private final Map<UUID, ClanMember> members = new HashMap<>();
private final Map<String, List<MetadataValue>> metadataValues = new HashMap<>();
private ClanMember leader;
private String description = "";
private int level;
private int totalKills;
private Status state = Status.PUBLIC;
/**
* Represents the possible clan's states
* which determine if a player can join the clan or not
*/
public enum Status {
/**
* All players are allowed to join
*/
PUBLIC,
/**
* The player needs to send a join request
* which will be approved by one of the clan's who meet certain permissions
*/
INVITE_ONLY,
/**
* No one can join the clan unless they have received an invitation
*/
CLOSED
}
public enum LeaveReason {
/**
* The player left on his own desire
*/
QUIT,
/**
* Kicked by a clan's member
*/
KICK,
/**
* Kicked because the clan was deleted
*/
DELETE
}
/**
* Constructor which creates a new <code>Clan</code> instance
* from a defined <i>name</i> and a <i>leader</i> and takes default clan configuration
*
* @param name name of the clan
* @param leader owner of the clan
*/
public Clan(@NotNull String name, @NotNull OfflinePlayer leader) {
this.name = name;
this.creationDate = new Date();
ClanMember member = new ClanMember(this, leader);
member.setRole(ClanRole.LEADER);
this.members.put(leader.getUniqueId(), member);
this.leader = member;
}
/**
* Constructor that creates an new <code>Clan</code> instance from a {@link ClanBuilder}
*
* @param builder {@link ClanBuilder} instance
*/
public Clan(@NotNull ClanBuilder builder) {
this.name = builder.getName();
this.creationDate = builder.getCreationDate();
this.setDescription(builder.getDescription());
this.setKills(builder.getKills());
this.setLevel(builder.getLevel());
this.setStatus(builder.getStatus());
for (ClanMemberBuilder memberBuilder : builder.getMemberBuilders()) {
UUID uuid = memberBuilder.getOfflinePlayer().getUniqueId();
this.members.put(uuid, memberBuilder.build(this));
}
this.leader = this.getMember(builder.getLeader());
}
/**
* Add a new member to the clan
*
* @param player player who will be add to the clan
*/
public void addMember(@NotNull OfflinePlayer player) {
if (!this.hasMember(player)) {
PlayerJoinClanEvent event = new PlayerJoinClanEvent(player, this);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) return;
ClanMember member = new ClanMember(this, player);
this.members.put(player.getUniqueId(), member);
}
}
/**
* Removes a player from clan,
* does nothing if the player isn't a member of the clan
*
* @param player the player who will get removed
* @param reason the reason why they left the clan
*/
@SuppressWarnings("ConstantConditions")
public void removeMember(@NotNull OfflinePlayer player, @NotNull Clan.LeaveReason reason) {
if (!this.hasMember(player)) {
return;
}
PlayerLeaveClanEvent event = new PlayerLeaveClanEvent(player, this, reason);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
ClanMember member = this.getMember(player.getUniqueId());
member.leaveClan();
this.members.remove(player.getUniqueId());
}
}
/**
* Sets a new leader to the clan,
* the new leader is a player who must be a member in the same clan
* and the old leader will get demoted to a lower rank
*
* @param newLeader new leader
*/
@SuppressWarnings("ConstantConditions")
public void setLeader(@NotNull OfflinePlayer newLeader) {
if (newLeader != null && this.hasMember(newLeader)) {
if (this.leader != null) {
if (this.leader.getOfflinePlayer() == newLeader) {
return;
}
this.leader.demote();
}
ClanMember member = this.getMember(newLeader);
member.setRole(ClanRole.LEADER);
this.leader = member;
}
}
/**
* Gets the clan's name
*
* @return name of the clan
*/
public String getName() {
return this.name;
}
/**
* Gets the clan's description
*
* @return description of the clan
*/
public String getDescription() {
return this.description;
}
/**
* Gets the creation date of the clan
*
* @return Clan's creation <code>Date</code>
*/
public Date getCreationDate() {
return this.creationDate;
}
/**
* Gets the leader of the clan
*
* @return Leader's <code>ClanMember</code> instance
*/
public ClanMember getLeader() {
return this.leader;
}
/**
* Gets the total kills of the clan,
* the value isn't affected when a player leaves the clan
* as it is independent from total members' kills
*
* @return clan's total kills
*/
public int getKills() {
return this.totalKills;
}
/**
* Gets the clan's level
*
* @return level of the clan
*/
public long getLevel() {
return this.level;
}
/**
* Gets the ClanMember instance of a given player
* this method returns null if the player isn't an actual member of the clan
*
* @param player the player whose associated to a <code>ClanMember</code>
* @return a <code>ClanMember</code> instance, null if the player wasn't found in the clan
*/
@Nullable
public ClanMember getMember(@NotNull OfflinePlayer player) {
return this.getMember(player.getUniqueId());
}
@Nullable
public ClanMember getMember(UUID playerUUID) {
return this.members.get(playerUUID);
}
/**
* Checks whether a player is a member of the clan
*
* @param player the player which will be examined
* @return true if the player is a found within clan's members
*/
public boolean hasMember(OfflinePlayer player) {
return this.hasMember(player.getUniqueId());
}
public boolean hasMember(UUID playerUUID) {
return this.members.containsKey(playerUUID);
}
public Collection<ClanMember> getMembers() {
return this.getMembers(false);
}
/**
* Gets all members of the clan
*
* @param online weather it should return online members only or otherwise
* @return a <code>Collection of</code> <code>ClanMember</code>s
*/
public Collection<ClanMember> getMembers(boolean online) {
return this.members.values().stream()
.filter((member) -> !online || member.isOnline())
.collect(Collectors.toSet());
}
/**
* Gets the current clan's state
*
* @return Status value
*/
public Status getStatus() {
return this.state;
}
/**
* Sets the clan's state
*
* @param newState newState - represent the new state for the clan
*/
public void setStatus(@NotNull Clan.Status newState) {
this.state = newState;
}
/**
* Sets description of the clan
*
* @param description new description
*/
public void setDescription(@NotNull String description) {
this.description = description;
}
/**
* Sets clan's kills
*
* @param kills total kills
*/
public void setKills(int kills) {
this.totalKills = Math.max(kills, 0);
}
/**
* Sets clan's level
*
* @param level level value
*/
public void setLevel(int level) {
this.level = Math.max(level, 0);
}
/**
* Send a message to all clan members
*
* @param message message to send
*/
public void sendMessage(String message) {
this.getMembers(true).forEach(member -> member.sendMessage(message));
}
/**
* This method is similar to {@link #sendMessage(String)}
* but it takes an extra parameter `<b>broadcaster</b>`
* it sends a message to all clan members including the one who sent the broadcast
*
* @param message message to send
* @param broadcaster the sender
*/
public void broadcast(String message, @NotNull Player broadcaster) {
this.sendMessage("[" + this.name + "] " + broadcaster.getDisplayName() + " >> " + message);
}
/**
* delete the clan, this will kick all the players and removes the clan from cache
* also deletes its configuration file from disk at the default save path
*/
public void delete() {
ClanDeleteEvent event = new ClanDeleteEvent(this);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
this.getMembers().forEach(member -> this.removeMember(member.getOfflinePlayer(), LeaveReason.DELETE));
}
}
@Nullable
public OfflinePlayer getOfflinePlayer(@NotNull String name) {
for (ClanMember member : this.getMembers()) {
OfflinePlayer target = member.getOfflinePlayer();
String targetName = target.getName();
if (targetName == null) continue;
if (targetName.equals(name)) {
return target;
}
}
return null;
}
@Override
public void setMetadata(@NotNull String metadataKey, @NotNull MetadataValue newMetadataValue) {
List<MetadataValue> values = this.getMetadata(metadataKey);
this.clearMetaData(metadataKey, newMetadataValue.getOwningPlugin());
values.add(newMetadataValue);
}
@NotNull
@Override
public List<MetadataValue> getMetadata(@NotNull String metadataKey) {
this.metadataValues.putIfAbsent(metadataKey, new ArrayList<>());
return this.metadataValues.get(metadataKey);
}
@Override
public boolean hasMetadata(@NotNull String metadataKey) {
return this.metadataValues.containsKey(metadataKey);
}
@Override
public void removeMetadata(@NotNull String metadataKey, @NotNull Plugin owningPlugin) {
this.clearMetaData(metadataKey, owningPlugin);
}
private void clearMetaData(String metadataKey, Plugin owningPlugin) {
this.getMetadata(metadataKey)
.removeIf(value -> Objects.equals(value.getOwningPlugin(), owningPlugin));
}
@SuppressWarnings("ConstantConditions")
@NotNull
@Override
public String format(@NotNull String message) {
String formatted = message;
final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
final String formattedDate = dateFormat.format(this.getCreationDate());
formatted = formatted.replace("{clan}", this.getName());
formatted = formatted.replace("{clan.leader}", this.getLeader().getOfflinePlayer().getName());
formatted = formatted.replace("{clan.description}", this.getDescription());
formatted = formatted.replace("{clan.kills}", String.valueOf(this.getKills()));
formatted = formatted.replace("{clan.level}", String.valueOf(this.getLevel()));
formatted = formatted.replace("{clan.status}", this.getStatus().toString());
formatted = formatted.replace("{clan.members}", String.valueOf(this.members.size()));
formatted = formatted.replace("{clan.creationdate}", formattedDate);
return formatted;
}
@Override
public boolean equals(Object object) {
return object instanceof Clan && ((Clan) object).getName().equals(this.name);
}
@Override
public int hashCode() {
int hash = name.hashCode();
hash = 31 * hash + creationDate.hashCode();
return hash;
}
@SuppressWarnings("StringBufferReplaceableByString")
@Override
public String toString() {
return new StringBuilder(this.getClass().getSimpleName())
.append("[name=")
.append(this.getName())
.append(", leader=")
.append(this.getLeader().getOfflinePlayer().getUniqueId())
.append(", members.size=")
.append(this.members.size())
.append("]")
.toString();
}
} | true |
ed87879a341dfbb9e76c678d411f13fc463f8b60 | Java | apache/jackrabbit-oak | /oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/file/FileStoreGCMonitor.java | UTF-8 | 3,534 | 1.890625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | 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.jackrabbit.oak.segment.file;
import static org.apache.jackrabbit.guava.common.base.Preconditions.checkNotNull;
import static org.slf4j.helpers.MessageFormatter.arrayFormat;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.jackrabbit.oak.segment.compaction.SegmentGCStatus;
import org.apache.jackrabbit.oak.spi.gc.GCMonitor;
import org.apache.jackrabbit.oak.stats.Clock;
import org.jetbrains.annotations.NotNull;
/**
* {@link GCMonitor} implementation providing the file store gc status.
*/
public class FileStoreGCMonitor implements GCMonitor {
private final Clock clock;
private long lastCompaction;
private long lastCleanup;
private long lastRepositorySize;
private long lastReclaimedSize;
private String lastError;
private String lastLogMessage;
private String status = SegmentGCStatus.IDLE.message();
public FileStoreGCMonitor(@NotNull Clock clock) {
this.clock = checkNotNull(clock);
}
//------------------------------------------------------------< GCMonitor >---
@Override
public void info(String message, Object... arguments) {
lastLogMessage = arrayFormat(message, arguments).getMessage();
}
@Override
public void warn(String message, Object... arguments) {
lastLogMessage = arrayFormat(message, arguments).getMessage();
}
@Override
public void error(String message, Exception exception) {
StringWriter sw = new StringWriter();
sw.write(message + ": ");
exception.printStackTrace(new PrintWriter(sw));
lastError = sw.toString();
}
@Override
public void skipped(String reason, Object... arguments) {
lastLogMessage = arrayFormat(reason, arguments).getMessage();
}
@Override
public void compacted() {
lastCompaction = clock.getTime();
}
@Override
public void cleaned(long reclaimed, long current) {
lastCleanup = clock.getTime();
lastReclaimedSize = reclaimed;
lastRepositorySize = current;
}
@Override
public void updateStatus(String status) {
this.status = status;
}
public long getLastCompaction() {
return lastCompaction;
}
public long getLastCleanup() {
return lastCleanup;
}
public long getLastRepositorySize() {
return lastRepositorySize;
}
public long getLastReclaimedSize() {
return lastReclaimedSize;
}
public String getLastError() {
return lastError;
}
@NotNull
public String getLastLogMessage() {
return lastLogMessage;
}
@NotNull
public String getStatus() {
return status;
}
}
| true |
8a1d5c8688232689db8567a0b0fcd29ae0ea87b1 | Java | nextreports/nextreports-designer | /src/ro/nextreports/designer/ui/wizard/util/LookAndFeelTweaks.java | UTF-8 | 3,477 | 2.015625 | 2 | [
"Apache-2.0"
] | 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 ro.nextreports.designer.ui.wizard.util;
import java.awt.Font;
import java.io.StringReader;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
import javax.swing.text.html.HTMLDocument;
/**
* @author Decebal Suiu
*/
public class LookAndFeelTweaks {
public static void tweak() {
Object listFont = UIManager.get("List.font");
UIManager.put("Table.font", listFont);
UIManager.put("ToolTip.font", listFont);
UIManager.put("TextField.font", listFont);
UIManager.put("FormattedTextField.font", listFont);
UIManager.put("Viewport.background", "Table.background");
}
public static void makeBold(JComponent component) {
component.setFont(component.getFont().deriveFont(Font.BOLD));
}
public static void makeMultilineLabel(JTextComponent area) {
area.setFont(UIManager.getFont("Label.font"));
area.setEditable(false);
area.setOpaque(false);
if (area instanceof JTextArea) {
((JTextArea) area).setWrapStyleWord(true);
((JTextArea) area).setLineWrap(true);
}
}
public static void htmlize(JComponent component) {
Font defaultFont = UIManager.getFont("Button.font");
String stylesheet = "body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0; font-family: "
+ defaultFont.getName()
+ "; font-size: "
+ defaultFont.getSize()
+ "pt; }"
+ "a, p, li { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0; font-family: "
+ defaultFont.getName()
+ "; font-size: "
+ defaultFont.getSize() + "pt; }";
try {
HTMLDocument doc = null;
if (component instanceof JEditorPane) {
if (((JEditorPane) component).getDocument() instanceof HTMLDocument) {
doc = (HTMLDocument) ((JEditorPane) component).getDocument();
}
} else {
View v = (View) component.getClientProperty(BasicHTML.propertyKey);
if (v != null && v.getDocument() instanceof HTMLDocument) {
doc = (HTMLDocument) v.getDocument();
}
}
if (doc != null) {
doc.getStyleSheet().loadRules(new StringReader(stylesheet), null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
a253174bb75bea4e98ab6a5f585964e170153153 | Java | nirzonpop192/GPath-LOC-02040215 | /app/src/main/java/com/siddiquinoor/restclient/activity/sub_activity/dynamic_table/DT_QuestionActivity.java | UTF-8 | 54,546 | 1.546875 | 2 | [] | no_license | package com.siddiquinoor.restclient.activity.sub_activity.dynamic_table;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.siddiquinoor.restclient.R;
import com.siddiquinoor.restclient.data_model.DTQResModeDataModel;
import com.siddiquinoor.restclient.data_model.DTResponseTableDataModel;
import com.siddiquinoor.restclient.data_model.DT_ATableDataModel;
import com.siddiquinoor.restclient.fragments.BaseActivity;
import com.siddiquinoor.restclient.manager.SQLiteHandler;
import com.siddiquinoor.restclient.manager.sqlsyntax.SQLServerSyntaxGenerator;
import com.siddiquinoor.restclient.utils.KEY;
import com.siddiquinoor.restclient.views.adapters.DynamicDataIndexDataModel;
import com.siddiquinoor.restclient.views.adapters.DynamicTableQuesDataModel;
import com.siddiquinoor.restclient.views.helper.SpinnerHelper;
import com.siddiquinoor.restclient.views.notifications.ADNotificationManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class DT_QuestionActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
public static final String TEXT = "Text";
public static final String NUMBER = "Number";
public static final String Date = "Date";
public static final String Date_OR_Time = "Datetime";
public static final String Textbox = "Textbox";
public static final String COMBO_BOX = "Combobox";
public static final String GEO_LAYER_3 = "Geo Layer 3";
public static final String GEO_LAYER_2 = "Geo Layer 2";
public static final String GEO_LAYER_1 = "Geo Layer 1";
public static final String GEO_LAYER_4 = "Geo Layer 4";
public static final String GEO_LAYER_ADDRESS = "Geo Layer Address";
public static final String SERVICE_SITE = "Service Site";
public static final String DISTRIBUTION_POINT = "Distribution Point";
public static final String COMMUNITY_GROUP = "Community Group";
public static final String CHECK_BOX = "Checkbox";
public static final String RADIO_BUTTON = "Radio Button";
public static final String DATE_TIME = "Datetime";
public static final String DATE = "Date";
public static final String RADIO_BUTTON_N_TEXTBOX = "Radio Button, Textbox";
public static final String CHECKBOX_N_TEXTBOX = "Checkbox, Textbox";
public static final String LOOKUP_LIST = "Lookup List";
/**
* Database helper
*/
private SQLiteHandler sqlH;
/**
* alert Dialog
*/
private ADNotificationManager dialog;
private final Context mContext = DT_QuestionActivity.this;
private DynamicDataIndexDataModel dyIndex;
private int totalQuestion;
private TextView tv_DtQuestion;
private Button btnNextQues;
private Button btnHome;
private DynamicTableQuesDataModel mDTQ;
private Button btnPreviousQus;
int mQusIndex;
/**
* For Date time picker
*/
private SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
private Calendar calendar = Calendar.getInstance();
/**
* Dynamic view
*/
private Spinner dt_spinner;
private EditText dt_edt;
private TextView _dt_tv_DatePicker;
private RadioGroup radioGroup;
// private RadioButton rdbtn;
/**
* To determined the either any Check box is Selected or nor
*/
private int countChecked = 0;
private String idSpinner;
private String strSpinner;
/**
* DTQResMode
*/
DTQResModeDataModel mDTQResMode;
/**
* #mDTATable is Deliminator of Check Box item & value
* it is assigned by {@link #displayQuestion(DynamicTableQuesDataModel)} method
*/
List<DT_ATableDataModel> mDTATableList;
/**
* List for Dynamic
*/
private List<RadioButton> mRadioButton_List = new ArrayList<RadioButton>();
private List<CheckBox> mCheckBox_List = new ArrayList<CheckBox>();
/**
* todo modifies
*/
private RadioGroup radioGroupForRadioAndEditText;
// private LinearLayout llRadioGroupAndEditText;
private List<RadioButton> mRadioButtonForRadioAndEdit_List = new ArrayList<RadioButton>();
private List<EditText> mEditTextForRadioAndEdit_List = new ArrayList<EditText>();
private List<EditText> mEditTextForCheckBoxAndEdit_List = new ArrayList<EditText>();
private List<CheckBox> mCheckBoxForCheckBoxAndEdit_List = new ArrayList<CheckBox>();
private LinearLayout dt_layout_Radio_N_EditText;
/**
* Layout
*/
private LinearLayout parent_layout_onlyFor_CB;
private LinearLayout parent_layout_FOR_CB_N_ET;
/**
* This layout is child of
* {@link #parent_layout_FOR_CB_N_ET}
*/
private LinearLayout subParent_CB_layout_FOR_CB_N_ET;
/**
* This layout is child of
* {@link #parent_layout_FOR_CB_N_ET}
*/
private LinearLayout subParent_ET_layout_FOR_CB_N_ET;
private LinearLayout ll_editText;
// private TextView tv_ErrorDisplay;
/**
* mDTResponse Sequence DTRSeq
*/
private int mDTRSeq;
/**
* @param sIState savedInstanceState
*/
@Override
protected void onCreate(Bundle sIState) {
super.onCreate(sIState);
setContentView(R.layout.activity_dt__qustion);
inti();
setListener();
}
private void setListener() {
btnNextQues.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveProcessValidation();
}
});
btnPreviousQus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
previousQuestion();
}
});
btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToHomeWithDialog();
}
});
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void addIconHomeButton() {
btnHome.setText("");
Drawable imageHome = getResources().getDrawable(R.drawable.home_b);
btnHome.setCompoundDrawablesRelativeWithIntrinsicBounds(imageHome, null, null, null);
setPaddingButton(mContext, imageHome, btnHome);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void addNextOrPreviousButton(Button button) {
button.setText("");
Drawable imageHome;
if (button == btnNextQues)
imageHome = getResources().getDrawable(R.drawable.goto_forward);
else
imageHome = getResources().getDrawable(R.drawable.goto_back);
button.setCompoundDrawablesRelativeWithIntrinsicBounds(imageHome, null, null, null);
setPaddingButton(mContext, imageHome, button);
}
/**
* calling getWidth() and getHeight() too early:
* When the UI has not been sized and laid out on the screen yet..
*
* @param hasFocus the value will be true when UI is focus
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
addIconHomeButton();
addNextOrPreviousButton(btnNextQues);
addNextOrPreviousButton(btnPreviousQus);
}
/**
* {@link #deleteFromResponseTable()}
*/
private void goToHomeWithDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
/**
* in unfinished condition if anyone press home button
* Setting Dialog Title
*/
alertDialog.setTitle("Home");
String massage;
if (mQusIndex < totalQuestion) {
massage = "Your response is incomplete.\nDo you want to quit ?";
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
confirmationDialog();
}
});
} else {
massage = " Do you want to go to Home page ?";
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
goToMainActivity((Activity) mContext);
}
});
}
// Setting Dialog Message
alertDialog.setMessage(massage);
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
private void confirmationDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
/**
* in unfinished condition if anyone press home button
* Setting Dialog Title
*/
alertDialog.setTitle("Home");
String massage;
massage = "Incomplete response will be deleted!!";
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteFromResponseTable();
goToMainActivity((Activity) mContext);
}
});
// Setting Dialog Message
alertDialog.setMessage(massage);
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
/**
* Change The Color of Question to Indicate the Eror
*/
private void errorIndicator() {
tv_DtQuestion.setTextColor(getResources().getColor(R.color.red));
}
private void normalIndicator() {
tv_DtQuestion.setTextColor(getResources().getColor(R.color.blue_dark));
}
/**
* Check All type of Validation For
*/
private void saveProcessValidation() {
int i = 0;
String responseControl = mDTQResMode.getDtResponseValueControl();
if (mDTQ.getAllowNullFlag().equals("N")) {
switch (responseControl) {
case Textbox:
String edtInput = dt_edt.getText().toString();
if (edtInput.equals("Text") || edtInput.equals("Number") || edtInput.length() == 0) {
errorIndicator();
displayError("Insert Text");
/**
* todo : show Dialog
*/
} else {
normalIndicator();
saveData(edtInput, mDTATableList.get(0));
// NEXT QUESTION
nextQuestion();
}
break;
case Date_OR_Time:
if (_dt_tv_DatePicker.getText().toString().equals("Click for Date")) {
// Toast.makeText(DT_QuestionActivity.this, "Set Date First ", Toast.LENGTH_SHORT).show();
errorIndicator();
displayError("Set Date First");
/**
* todo : show Dialog
*/
} else {
normalIndicator();
/**
* mDTATableList.get(0) wil be single
*/
saveData(_dt_tv_DatePicker.getText().toString(), mDTATableList.get(0));
nextQuestion();
}
break;
case COMBO_BOX:
if (idSpinner.equals("00")) {
// Toast.makeText(mContext, "Select Item", Toast.LENGTH_SHORT).show();
errorIndicator();
displayError("Select Item");
/**
* todo : show Dialog
*/
} else {
normalIndicator();
/**
* {@link DT_QuestionActivity#saveData(String, DT_ATableDataModel)}
*/
saveData(strSpinner, mDTATableList.get(0));
/**
* NEXT QUESTION
*/
nextQuestion();
}
break;
case CHECK_BOX:
if (countChecked <= 0) {
// Toast.makeText(DT_QuestionActivity.this, " Please select a option.", Toast.LENGTH_SHORT).show();
errorIndicator();
displayError("Select a option.");
} else {
normalIndicator();
i = 0;
for (CheckBox cb : mCheckBox_List) {
if (cb.isChecked()) {
//
saveData("", mDTATableList.get(i));
}// end of if condition
i++;
}// end of for each loop
}// end of else
nextQuestion();
break;
case RADIO_BUTTON:
i = 0;
for (RadioButton rb : mRadioButton_List) {
if (rb.isChecked()) {
Toast.makeText(mContext, "Radio Button no:" + (i + 1) + " is checked", Toast.LENGTH_SHORT).show();
saveData("", mDTATableList.get(i));
}
i++;
}
nextQuestion();
break;
case RADIO_BUTTON_N_TEXTBOX:
boolean error = false;
i = 0;
for (RadioButton rb : mRadioButtonForRadioAndEdit_List) {
if (rb.isChecked()) {
Toast.makeText(mContext, "Radio Button no:" + (i + 1) + " is checked"
+ " the value of the : " + mEditTextForRadioAndEdit_List.get(i).getText(), Toast.LENGTH_SHORT).show();
if (mEditTextForRadioAndEdit_List.get(i).getText().length() == 0) {
errorIndicator();
displayError("Insert value for Selected Option");
error = true;
break;
} else {
normalIndicator();
saveData(mEditTextForRadioAndEdit_List.get(i).getText().toString(), mDTATableList.get(i));
}
}
i++;
}
if (!error)
nextQuestion();
break;
case CHECKBOX_N_TEXTBOX:
normalIndicator();
int k = 0;
for (CheckBox cb : mCheckBoxForCheckBoxAndEdit_List) {
if (cb.isChecked()) {
Toast.makeText(mContext, "Radio Button no:" + (k + 1) + " is checked"
+ " the value of the : " + mEditTextForCheckBoxAndEdit_List.get(k).getText(), Toast.LENGTH_SHORT).show();
if (mEditTextForCheckBoxAndEdit_List.get(k).getText().length() == 0) {
errorIndicator();
displayError("Insert value for Selected Option");
break;
} else {
normalIndicator();
saveData(mEditTextForCheckBoxAndEdit_List.get(k).getText().toString(), mDTATableList.get(k));
}
}
k++;
}
nextQuestion();
break;
}// end of switch
}// end of the AllowNullFlag
else {
/**
* TODO: 9/29/2016 save method & update method
*/
// saveData("");
/**
* NEXT QUESTION
*/
nextQuestion();
}// end of else where ans is not magneto
}
/**
* @param errorMsg Massage In valid
*/
private void displayError(String errorMsg) {
dialog.showWarningDialog(mContext, errorMsg);
}
private void saveData(String ansValue, DT_ATableDataModel dtATable) {
saveOnResponseTable(ansValue, dtATable);
}
/**
* @param ansValue user input
* @param dtATable DTA Table
*/
private void saveOnResponseTable(String ansValue, DT_ATableDataModel dtATable) {
String DTBasic = dyIndex.getDtBasicCode();
String AdmCountryCode = dyIndex.getcCode();
String AdmDonorCode = dyIndex.getDonorCode();
String AdmAwardCode = dyIndex.getAwardCode();
String AdmProgCode = dyIndex.getProgramCode();
String DTEnuID = getStaffID();
String DTQCode = mDTQ.getDtQCode();
String DTACode = dtATable.getDt_ACode();
/** DTRSeq is user input serial no */
int DTRSeq = mDTRSeq;
String DTAValue = null;
String ProgActivityCode = dyIndex.getProgramActivityCode();
String DTTimeString = null;
try {
DTTimeString = getDateTime();
} catch (ParseException e) {
e.printStackTrace();
}
String OpMode = dyIndex.getOpMode();
String OpMonthCode = dyIndex.getOpMonthCode();
/**
* todo : set the DT Q data type
*/
String DataType = dtATable.getDataType();
DTAValue = dtATable.getDt_AValue().equals("null") || dtATable.getDt_AValue().length() == 0 ? ansValue : dtATable.getDt_AValue();
Log.d("MOR_1", " for save process"
+ "\n DTBasic : " + DTBasic
+ "\n AdmCountryCode : " + AdmCountryCode
+ "\n AdmDonorCode : " + AdmDonorCode
+ "\n AdmAwardCode : " + AdmAwardCode
+ "\n AdmProgCode : " + AdmProgCode
+ "\n DTEnuID : " + DTEnuID
+ "\n DTQCode : " + DTQCode
+ "\n DTACode : " + DTACode
+ "\n DTRSeq : " + DTRSeq
+ "\n DTAValue : " + DTAValue
+ "\n ProgActivityCode : " + ProgActivityCode
+ "\n DTTimeString : " + DTTimeString
+ "\n OpMode : " + OpMode
+ "\n OpMonthCode : " + OpMonthCode
+ "\n DataType : " + DataType
);
/**
* todo set upload syntax variable here
*/
SQLServerSyntaxGenerator syntaxGenerator = new SQLServerSyntaxGenerator();
syntaxGenerator.setDTBasic(DTBasic);
syntaxGenerator.setAdmCountryCode(AdmCountryCode);
syntaxGenerator.setAdmDonorCode(AdmDonorCode);
syntaxGenerator.setAdmAwardCode(AdmAwardCode);
syntaxGenerator.setAdmProgCode(AdmProgCode);
syntaxGenerator.setDTEnuID(DTEnuID);
syntaxGenerator.setDTQCode(DTQCode);
syntaxGenerator.setDTACode(DTACode);
syntaxGenerator.setDTRSeq(String.valueOf(mDTRSeq));
syntaxGenerator.setDTAValue(DTAValue);
syntaxGenerator.setProgActivityCode(ProgActivityCode);
syntaxGenerator.setDTTimeString(DTTimeString);
syntaxGenerator.setOpMode(OpMode);
syntaxGenerator.setOpMonthCode(OpMonthCode);
syntaxGenerator.setDataType(DataType);
syntaxGenerator.setCompleteness("Y");
/**
* main execute
* Insert or update operation
*/
if (sqlH.isDataExitsInDTAResponse_Table(DTBasic, AdmCountryCode, AdmDonorCode, AdmAwardCode, AdmProgCode, DTEnuID, DTQCode, DTACode, mDTRSeq)) {
sqlH.updateIntoDTResponseTable(DTBasic, AdmCountryCode, AdmDonorCode, AdmAwardCode, AdmProgCode, DTEnuID, DTQCode, DTACode,
String.valueOf(DTRSeq), DTAValue, ProgActivityCode, DTTimeString, OpMode, OpMonthCode, DataType);
/**
* upload syntax
*/
sqlH.insertIntoUploadTable(syntaxGenerator.updateIntoDTResponseTable());
} else {
sqlH.addIntoDTResponseTable(DTBasic, AdmCountryCode, AdmDonorCode, AdmAwardCode, AdmProgCode, DTEnuID, DTQCode, DTACode,
String.valueOf(DTRSeq), DTAValue, ProgActivityCode, DTTimeString, OpMode, OpMonthCode, DataType);
/**
* upload syntax
*/
sqlH.insertIntoUploadTable(syntaxGenerator.insertIntoDTResponseTable());
}
}
/**
* delete the unfinished data form the
*/
private void deleteFromResponseTable() {
String DTBasic = dyIndex.getDtBasicCode();
String AdmCountryCode = dyIndex.getcCode();
String AdmDonorCode = dyIndex.getDonorCode();
String AdmAwardCode = dyIndex.getAwardCode();
String AdmProgCode = dyIndex.getProgramCode();
String OpMode = dyIndex.getOpMode();
String getOpMonthCode = dyIndex.getOpMonthCode();
String DTEnuID = getStaffID();
int DTRSeq = mDTRSeq;
/**
* total Question no is less then index no
* the Delete Syntax in the {@link SQLiteHandler#deleteFromDTResponseTable(String, String, String, String, String, String, int, String, String)}
*
*/
if (DTBasic != null && AdmCountryCode != null && AdmDonorCode != null && AdmAwardCode != null
&& AdmProgCode != null && DTEnuID != null && DTRSeq != 0) {
sqlH.deleteFromDTResponseTable(DTBasic, AdmCountryCode, AdmDonorCode, AdmAwardCode, AdmProgCode, DTEnuID, DTRSeq, OpMode, getOpMonthCode);
}
}
/**
* Load the next Ques
*/
private void nextQuestion() {
++mQusIndex;
/**
* to check does index exceed the max value
*/
if (mQusIndex != totalQuestion)
hideViews();
if (mQusIndex < totalQuestion) {
DynamicTableQuesDataModel nextQus = loadNextQuestion(dyIndex.getDtBasicCode(), mQusIndex);
displayQuestion(nextQus);
/**
* set previous state of previous button
*/
removeStopIconNextButton(btnPreviousQus);
if (mQusIndex == totalQuestion - 1) {
// addSaveIconButton(btnNextQues);
}
} else if (mQusIndex == totalQuestion) {
Toast.makeText(mContext, "Saved Successfully", Toast.LENGTH_SHORT).show();
/* Bellow Code end the*/
Log.d("ICON", "before set icon ");
addStopIconButton(btnNextQues);
} else if (mQusIndex > totalQuestion) {
/**
* new set of ans
* set icon next button
*/
continueDialog();
}
}
private void continueDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
/**
* in unfinished condition if anyone press home button
* Setting Dialog Title
*/
alertDialog.setTitle("Continue !!");
String massage;
massage = "Do you want to continue ?";
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
removeStopIconNextButton(btnNextQues);
initialWithFirstQues();
}
});
// Setting Dialog Message
alertDialog.setMessage(massage);
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
goToMainActivity((Activity) mContext);
}
});
// Showing Alert Message
alertDialog.show();
}
private void previousQuestion() {
--mQusIndex;
hideViews();
/**
* to check does index exceed the min value
*/
if (mQusIndex >= 0) {
DynamicTableQuesDataModel nextQus = loadPreviousQuestion(dyIndex.getDtBasicCode(), mQusIndex);
displayQuestion(nextQus);
if (mQusIndex == 0)
addStopIconButton(btnPreviousQus);
} else if (mQusIndex < 0) {
mQusIndex = 0;
}
}
/**
* @param qusObject DTQTable object
* {@link #mDTATableList} must be assigned before invoking {@link #loadDT_QResMode(String)}
* {@link #mDTATableList} needed in {@link #saveData(String, DT_ATableDataModel)} (String)} method
*/
private void displayQuestion(DynamicTableQuesDataModel qusObject) {
tv_DtQuestion.setText(qusObject.getqText());
mDTATableList = sqlH.getDTA_Table(qusObject.getDtBasicCode(), qusObject.getDtQCode());
/**
* {@link #mDTATableList} if it's size is zero than there will be IndexOutOfBoundsException
* occur
* the poxy data prevent to occur that Exception
*/
if (mDTATableList.size() == 0) {
DT_ATableDataModel proxyDATA_data = new DT_ATableDataModel(mDTQ.getDtBasicCode(), mDTQ.getDtQCode(), "null", "No Recoded in DB", "null", "null", "null", "null", "null", "null", "N", 0, 0, "Text", "null");
mDTATableList.add(proxyDATA_data);
}
loadDT_QResMode(qusObject.getqResModeCode());
}
/**
* initial state
* also views refer
*
* @see :{@link #viewReference()}
*/
private void inti() {
viewReference();
sqlH = new SQLiteHandler(mContext);
dialog = new ADNotificationManager();
Intent intent = getIntent();
dyIndex = intent.getParcelableExtra(KEY.DYNAMIC_INDEX_DATA_OBJECT_KEY);
totalQuestion = intent.getIntExtra(KEY.DYNAMIC_T_QUES_SIZE, 0);
initialWithFirstQues();
}
private void initialWithFirstQues() {
mQusIndex = 0;
mDTRSeq = sqlH.getNextDTResponseSequence(dyIndex.getDtBasicCode(), dyIndex.getcCode(), dyIndex.getDonorCode(), dyIndex.getAwardCode(), dyIndex.getProgramCode(), getStaffID());
Log.d("RES", "DTRSec for next mDTRSeq: " + mDTRSeq);
hideViews();
DynamicTableQuesDataModel qus = fistQuestion(dyIndex.getDtBasicCode());
displayQuestion(qus);
}
/**
* Hide the view
*/
private void hideViews() {
_dt_tv_DatePicker.setVisibility(View.GONE);
dt_edt.setVisibility(View.GONE);
dt_spinner.setVisibility(View.GONE);
parent_layout_onlyFor_CB.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
dt_layout_Radio_N_EditText.setVisibility(View.GONE);
parent_layout_FOR_CB_N_ET.setVisibility(View.GONE);
}
/**
* Refer the all the necessary view in java object
*/
private void viewReference() {
tv_DtQuestion = (TextView) findViewById(R.id.tv_DtQuestion);
/**
* set up home button
*/
btnHome = (Button) findViewById(R.id.btnHomeFooter);
Button btnGone = (Button) findViewById(R.id.btnRegisterFooter);
btnGone.setVisibility(View.GONE);
/**
* next & preview button
*/
btnNextQues = (Button) findViewById(R.id.btn_dt_next);
btnPreviousQus = (Button) findViewById(R.id.btn_dt_preview);
btnNextQues.setText("Next");
btnPreviousQus.setText("Previous");
/**
* dynamic view reference
*/
parent_layout_onlyFor_CB = (LinearLayout) findViewById(R.id.ll_checkBox);
_dt_tv_DatePicker = (TextView) findViewById(R.id.tv_dtTimePicker);
dt_edt = (EditText) findViewById(R.id.edt_dt);
dt_spinner = (Spinner) findViewById(R.id.dt_sp);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
/**
* todo re name
*/
ll_editText = (LinearLayout) findViewById(R.id.llEditText);
radioGroupForRadioAndEditText = (RadioGroup) findViewById(R.id.radioGroupForRadioAndEdit);
/**
* CheckBox and EditText
*/
parent_layout_FOR_CB_N_ET = (LinearLayout) findViewById(R.id.ll_CheckBoxAndEditTextParent);
subParent_CB_layout_FOR_CB_N_ET = (LinearLayout) findViewById(R.id.ll_checkBoxAndEditTextCheckbox);
subParent_ET_layout_FOR_CB_N_ET = (LinearLayout) findViewById(R.id.et_CheckBoxAndEditText);
dt_layout_Radio_N_EditText = (LinearLayout) findViewById(R.id.ll_radioGroupAndEditText);
/**
* Error label
*/
// tv_ErrorDisplay = (TextView) findViewById(R.id.tv_dt_errorLable);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void addStopIconButton(Button button) {
Log.d("ICON", "in icon set icon ");
button.setText("");
Drawable imageHome = getResources().getDrawable(R.drawable.stop);
button.setCompoundDrawablesRelativeWithIntrinsicBounds(imageHome, null, null, null);
setPaddingButton(mContext, imageHome, button);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void addSaveIconButton(Button button) {
Log.d("ICON", "in icon set icon ");
button.setText("");
Drawable imageHome = getResources().getDrawable(R.drawable.save_b);
button.setCompoundDrawablesRelativeWithIntrinsicBounds(imageHome, null, null, null);
setPaddingButton(mContext, imageHome, button);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void removeStopIconNextButton(Button button) {
button.setText("");
Drawable imageHome;
if (button == btnPreviousQus)
imageHome = getResources().getDrawable(R.drawable.goto_back);
else
imageHome = getResources().getDrawable(R.drawable.goto_forward);
button.setCompoundDrawablesRelativeWithIntrinsicBounds(imageHome, null, null, null);
setPaddingButton(mContext, imageHome, button);
}
/**
* the method invoked once in {@link #onCreate(Bundle)}
*
* @param dtBasic dtBasic code as primary key
* @return Ques object of first index
*/
private DynamicTableQuesDataModel fistQuestion(final String dtBasic) {
return loadQuestion(dtBasic, 0);
}
/**
* invoking in {@link #btnNextQues}
*
* @param dtBasic dtBasic code as primary key
* @param qusIndex Qus index
* @return Ques object of given index
*/
private DynamicTableQuesDataModel loadNextQuestion(final String dtBasic, final int qusIndex) {
return loadQuestion(dtBasic, qusIndex);
}
/**
* invoking in {@link #btnPreviousQus}
*
* @param dtBasic dtBasic code as primary key
* @param qusIndex Qus index
* @return Ques object of given index
*/
private DynamicTableQuesDataModel loadPreviousQuestion(final String dtBasic, final int qusIndex) {
return loadQuestion(dtBasic, qusIndex);
}
public DynamicTableQuesDataModel loadQuestion(final String dtBasic, final int qusIndex) {
mDTQ = sqlH.getSingleDynamicQuestion(dtBasic, qusIndex);
return mDTQ;
}
/**
* loadDT_QResMode(String) is equivalent to ans view loader
*
* @param resMode repose Mode
*/
private void loadDT_QResMode(String resMode) {
/**
* the {@link #mDTQResMode} is needed in the save process in {@link #saveProcessValidation()}
*/
mDTQResMode = sqlH.getDT_QResMode(resMode);
String responseControl = mDTQResMode.getDtResponseValueControl();
String dataType = mDTQResMode.getDtDataType();
String resLupText = mDTQResMode.getDtQResLupText();
Log.d("Nir", "responseControl :" + responseControl + "\n dataType:" + dataType + " \n resLupText :" + resLupText);
/**
* Resort Data if Data exits
*/
DTResponseTableDataModel loadAns = sqlH.getDTResponseTableData(dyIndex.getDtBasicCode(), dyIndex.getcCode(), dyIndex.getDonorCode(), dyIndex.getAwardCode(), dyIndex.getProgramCode(), getStaffID(), mDTQ.getDtQCode(), mDTATableList.get(0).getDt_ACode(), mDTRSeq);
countChecked = 0;
if (dataType != null) {
switch (responseControl) {
case Textbox:
dt_edt.setVisibility(View.VISIBLE);
/**
* if data exit show data
*/
if (loadAns != null)
dt_edt.setText(loadAns.getDtaValue());
else
dt_edt.setText("");
switch (dataType) {
case TEXT:
dt_edt.setHint("Text");
dt_edt.setInputType(InputType.TYPE_CLASS_TEXT);
break;
case NUMBER:
dt_edt.setHint("Number");
if (resLupText.equals("Number (not decimal)"))
dt_edt.setInputType(InputType.TYPE_CLASS_NUMBER);
else
dt_edt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
break;
}// end of switch
break;
case Date_OR_Time:
_dt_tv_DatePicker.setVisibility(View.VISIBLE);
/**
* if data exit show data
*/
if (loadAns != null)
_dt_tv_DatePicker.setText(loadAns.getDtaValue());
else
_dt_tv_DatePicker.setText("Select Date");
switch (dataType) {
case DATE_TIME:
getTimeStamp(_dt_tv_DatePicker);
break;
case DATE:
_dt_tv_DatePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setDate();
}
});
break;
}
break;
case COMBO_BOX:
dt_spinner.setVisibility(View.VISIBLE);
/**
* if data exist get the Spinner String
* set position •
*/
if (loadAns != null)
strSpinner = loadAns.getDtaValue();
else
strSpinner = null;
loadSpinnerList(dyIndex.getcCode(), resLupText);
break;
case CHECK_BOX:
parent_layout_onlyFor_CB.setVisibility(View.VISIBLE);
if (mDTATableList.size() > 0)
loadDynamicCheckBox(mDTATableList);
break;
case RADIO_BUTTON:
radioGroup.setVisibility(View.VISIBLE);
if (mDTATableList.size() > 0)
loadRadioButtons(mDTATableList);
break;
case RADIO_BUTTON_N_TEXTBOX:
dt_layout_Radio_N_EditText.setVisibility(View.VISIBLE);
if (mDTATableList.size() > 0)
loadRadioButtonAndEditText(mDTATableList, dataType);
break;
case CHECKBOX_N_TEXTBOX:
parent_layout_FOR_CB_N_ET.setVisibility(View.VISIBLE);
if (mDTATableList.size() > 0)
loadDynamicCheckBoxAndEditText(mDTATableList, dataType);
break;
}// end of switch
}// end of if
}// end of loadDT_QResMode
/**
* Shuvo vai
*
* @param dtA_Table_Data ans Mode
*/
private void loadDynamicCheckBox(List<DT_ATableDataModel> dtA_Table_Data) {
/**
* If there are any Children in layout Container it will reMove
* And the list of the Check Box {@link #mCheckBox_List} clear
*
*/
if (parent_layout_onlyFor_CB.getChildCount() > 0) {
mCheckBox_List.clear();
parent_layout_onlyFor_CB.removeAllViews();
}
for (int i = 0; i < dtA_Table_Data.size(); i++) {
TableRow row = new TableRow(this);
row.setId(i);
LinearLayout.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(layoutParams);
CheckBox checkBox = new CheckBox(this);
checkBox.setOnCheckedChangeListener(DT_QuestionActivity.this);
checkBox.setId(i);
/**
* set Text label
*/
checkBox.setText(dtA_Table_Data.get(i).getDt_ALabel());
/**
* set check box is checked or not
*/
DTResponseTableDataModel loadAns = sqlH.getDTResponseTableData(dyIndex.getDtBasicCode(), dyIndex.getcCode(), dyIndex.getDonorCode(), dyIndex.getAwardCode(), dyIndex.getProgramCode(), getStaffID(), mDTQ.getDtQCode(), dtA_Table_Data.get(i).getDt_ACode(), mDTRSeq);
if (loadAns != null) {
if (loadAns.getDtaValue().equals("Y")) {
checkBox.setChecked(true);
}
}
row.addView(checkBox);
/**
* {@link #btnNextQues} needed
*/
mCheckBox_List.add(checkBox);
parent_layout_onlyFor_CB.addView(row);
}
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
/**
* increase number of Selected Check box
*/
countChecked++;
} else {
/**
* decrease number of Selected Check box
*/
countChecked--;
}
}
/**
* Date & time Session
*/
public void getCurrentDate() {
Calendar calendar = Calendar.getInstance();
String strDate = mFormat.format(calendar.getTime());
displayDate(strDate);
}
private void displayDate(String strDate) {
_dt_tv_DatePicker.setText(strDate);
}
public void setDate() {
new DatePickerDialog(mContext, datePickerListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
/**
* date Time picker Listener
* The Date Listener invoke in {@link #setDate()}
*/
DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDate();
}
};
public void updateDate() {
displayDate(mFormat.format(calendar.getTime()));
}
/**
* todo details in latter
*
* @param cCode Country Code
* @param resLupText res lup
*/
private void loadSpinnerList(final String cCode, final String resLupText) {
int position = 0;
String udf;
List<SpinnerHelper> list = new ArrayList<SpinnerHelper>();
switch (resLupText) {
case GEO_LAYER_3:
udf = "SELECT " + SQLiteHandler.UNIT_TABLE + "." + SQLiteHandler.LAY_R3_LIST_CODE_COL
+ ", " + SQLiteHandler.UNIT_TABLE + "." + SQLiteHandler.UNITE_NAME_COL
+ " FROM " + SQLiteHandler.UNIT_TABLE
+ " WHERE " + SQLiteHandler.UNIT_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case GEO_LAYER_2:
udf = "SELECT " + SQLiteHandler.UPAZILLA_TABLE + "." + SQLiteHandler.LAY_R2_LIST_CODE_COL
+ ", " + SQLiteHandler.UPAZILLA_TABLE + "." + SQLiteHandler.UPZILLA_NAME_COL
+ " FROM " + SQLiteHandler.UPAZILLA_TABLE
+ " WHERE " + SQLiteHandler.UPAZILLA_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case GEO_LAYER_1:
udf = "SELECT " + SQLiteHandler.DISTRICT_TABLE + "." + SQLiteHandler.LAY_R1_LIST_CODE_COL
+ ", " + SQLiteHandler.DISTRICT_TABLE + "." + SQLiteHandler.DISTRICT_NAME_COL
+ " FROM " + SQLiteHandler.DISTRICT_TABLE
+ " WHERE " + SQLiteHandler.DISTRICT_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case GEO_LAYER_4:
udf = "SELECT " + SQLiteHandler.VILLAGE_TABLE + "." + SQLiteHandler.LAY_R4_LIST_CODE_COL
+ ", " + SQLiteHandler.VILLAGE_TABLE + "." + SQLiteHandler.VILLAGE_NAME_COL
+ " FROM " + SQLiteHandler.VILLAGE_TABLE
+ " WHERE " + SQLiteHandler.VILLAGE_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case GEO_LAYER_ADDRESS:
udf = "SELECT " + SQLiteHandler.LUP_REGN_ADDRESS_LOOKUP_TABLE + "." + SQLiteHandler.REGN_ADDRESS_LOOKUP_CODE_COL
+ ", " + SQLiteHandler.LUP_REGN_ADDRESS_LOOKUP_TABLE + "." + SQLiteHandler.REGN_ADDRESS_LOOKUP_NAME_COL
+ " FROM " + SQLiteHandler.LUP_REGN_ADDRESS_LOOKUP_TABLE
+ " WHERE " + SQLiteHandler.LUP_REGN_ADDRESS_LOOKUP_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case SERVICE_SITE:
udf = "SELECT " + SQLiteHandler.SERVICE_CENTER_TABLE + "." + SQLiteHandler.SERVICE_CENTER_CODE_COL
+ ", " + SQLiteHandler.SERVICE_CENTER_TABLE + "." + SQLiteHandler.SERVICE_CENTER_NAME_COL
+ " FROM " + SQLiteHandler.SERVICE_CENTER_TABLE
+ " WHERE " + SQLiteHandler.SERVICE_CENTER_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case DISTRIBUTION_POINT:
udf = "SELECT " + SQLiteHandler.FDP_MASTER_TABLE + "." + SQLiteHandler.FDP_CODE_COL
+ ", " + SQLiteHandler.FDP_MASTER_TABLE + "." + SQLiteHandler.FDP_NAME_COL
+ " FROM " + SQLiteHandler.FDP_MASTER_TABLE
+ " WHERE " + SQLiteHandler.FDP_MASTER_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case LOOKUP_LIST:
udf = "SELECT " + SQLiteHandler.DT_LUP_TABLE + "." + SQLiteHandler.LIST_CODE_COL
+ ", " + SQLiteHandler.DT_LUP_TABLE + "." + SQLiteHandler.LIST_NAME_COL
+ " FROM " + SQLiteHandler.DT_LUP_TABLE
+ " WHERE " + SQLiteHandler.DT_LUP_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "= '" + cCode + "' "
+ " AND " + SQLiteHandler.DT_LUP_TABLE + "." + SQLiteHandler.TABLE_NAME_COL + "= '" + mDTQ.getLup_TableName() + "'"
;
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
case COMMUNITY_GROUP:
udf = "SELECT " + SQLiteHandler.COMMUNITY_GROUP_TABLE + "." + SQLiteHandler.GROUP_CODE_COL
+ ", " + SQLiteHandler.COMMUNITY_GROUP_TABLE + "." + SQLiteHandler.GROUP_NAME_COL
+ " FROM " + SQLiteHandler.COMMUNITY_GROUP_TABLE
+ " WHERE " + SQLiteHandler.COMMUNITY_GROUP_TABLE + "." + SQLiteHandler.COUNTRY_CODE_COL + "='" + cCode + "'";
list = sqlH.getListAndID(SQLiteHandler.CUSTOM_QUERY, udf, cCode, false);
break;
default:
list.clear();
break;
}
ArrayAdapter<SpinnerHelper> dataAdapter = new ArrayAdapter<SpinnerHelper>(this, R.layout.spinner_layout, list);
dataAdapter.setDropDownViewResource(R.layout.spinner_layout);
dt_spinner.setAdapter(dataAdapter);
/** Retrieving Code for previous button */
if (strSpinner != null) {
for (int i = 0; i < dt_spinner.getCount(); i++) {
String union = dt_spinner.getItemAtPosition(i).toString();
if (union.equals(strSpinner)) {
position = i;
}
}
dt_spinner.setSelection(position);
}
dt_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strSpinner = ((SpinnerHelper) dt_spinner.getSelectedItem()).getValue();
idSpinner = ((SpinnerHelper) dt_spinner.getSelectedItem()).getId();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void loadRadioButtons(List<DT_ATableDataModel> radioButtonItemName) {
if (radioGroup.getChildCount() > 0) {
mRadioButton_List.clear();
radioGroup.removeAllViews();
}
for (int i = 0; i < radioButtonItemName.size(); i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(i);
rdbtn.setTextSize(24); // set text size
rdbtn.setPadding(0, 10, 0, 10); // set padding
rdbtn.setText(radioButtonItemName.get(i).getDt_ALabel()); // set lable
radioGroup.addView(rdbtn);
mRadioButton_List.add(rdbtn);
}// end of for loop
}
/**
* Radio - EditText & CheckBox - EditText
*/
/**
* @param List_DtATable
*/
public void loadRadioButtonAndEditText(List<DT_ATableDataModel> List_DtATable, String dataType) {
if (ll_editText.getChildCount() > 0) {
mRadioButtonForRadioAndEdit_List.clear();
mEditTextForRadioAndEdit_List.clear();
radioGroupForRadioAndEditText.removeAllViews();
ll_editText.removeAllViews();
}
for (int i = 0; i < List_DtATable.size(); i++) {
String label = List_DtATable.get(i).getDt_ALabel();
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(i);
rdbtn.setText(label); // set label
rdbtn.setTextSize(24); // set text size
rdbtn.setPadding(0, 10, 0, 10); // set padding
rdbtn.setOnCheckedChangeListener(DT_QuestionActivity.this);
EditText et = new EditText(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 5, 0, 5);
et.setLayoutParams(params);
et.setHint(label);
et.setId(i);
/**
* sof keyboard type
*/
if (dataType.equals(NUMBER)) {
et.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
et.setBackgroundColor(Color.WHITE);
/**
*
* todo aad index after set DTRespose Sequn {@link #saveOnResponseTable(String, DT_ATableDataModel)}
*/
DTResponseTableDataModel loadAns = sqlH.getDTResponseTableData(dyIndex.getDtBasicCode(), dyIndex.getcCode(), dyIndex.getDonorCode(), dyIndex.getAwardCode(), dyIndex.getProgramCode(), getStaffID(), mDTQ.getDtQCode(), List_DtATable.get(i).getDt_ACode(), mDTRSeq);
if (loadAns != null) {
rdbtn.setChecked(true);
String value = loadAns.getDtaValue();
et.setText(value);
}
radioGroupForRadioAndEditText.addView(rdbtn);
mRadioButtonForRadioAndEdit_List.add(rdbtn);
ll_editText.addView(et);
mEditTextForRadioAndEdit_List.add(et);
}
}
/**
* If there are any Children in layout Container it will reMove
* And the list of the Check Box {@link #mEditTextForCheckBoxAndEdit_List}
* and {@link #mCheckBoxForCheckBoxAndEdit_List }
* clear
*/
private void loadDynamicCheckBoxAndEditText(List<DT_ATableDataModel> List_DtATable, String dataType) {
if (subParent_CB_layout_FOR_CB_N_ET.getChildCount() > 0) {
subParent_ET_layout_FOR_CB_N_ET.removeAllViews();
subParent_CB_layout_FOR_CB_N_ET.removeAllViews();
mCheckBoxForCheckBoxAndEdit_List.clear();
mEditTextForCheckBoxAndEdit_List.clear();
}
for (int i = 0; i < List_DtATable.size(); i++) {
String label = List_DtATable.get(i).getDt_ALabel();
TableRow row = new TableRow(this);
row.setId(i);
LinearLayout.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(layoutParams);
CheckBox checkBox = new CheckBox(this);
checkBox.setOnCheckedChangeListener(DT_QuestionActivity.this);
checkBox.setId(i);
checkBox.setText(label); // set Text label
row.addView(checkBox);
EditText et = new EditText(this);
et.setHint(label);
et.setId(i);
/**
* sof keyboard type
*/
if (dataType.equals(NUMBER)) {
et.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
et.setBackgroundColor(Color.WHITE);
/**
* This snippets work for Check Box Well but not for the radio button
* todo aad index after set DTRespose Sequn {@link #saveOnResponseTable(String, DT_ATableDataModel)}
*/
DTResponseTableDataModel loadAns = sqlH.getDTResponseTableData(dyIndex.getDtBasicCode(), dyIndex.getcCode(), dyIndex.getDonorCode(), dyIndex.getAwardCode(), dyIndex.getProgramCode(), getStaffID(), mDTQ.getDtQCode(), List_DtATable.get(i).getDt_ACode(), mDTRSeq);
if (loadAns != null) {
checkBox.setChecked(true);
String value = loadAns.getDtaValue();
et.setText(value);
}
subParent_ET_layout_FOR_CB_N_ET.addView(et);
/**
* {@link #btnNextQues} needed
*
*/
mEditTextForCheckBoxAndEdit_List.add(et);
subParent_CB_layout_FOR_CB_N_ET.addView(row);
mCheckBoxForCheckBoxAndEdit_List.add(checkBox);
}
}
/**
* Shuvo
* this method only show the System Current Time
*
* @param tv Text view For Show
*/
private void getTimeStamp(TextView tv) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DATE);
int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
String am_pm = (hourOfDay < 12) ? "AM" : "PM";
String timeStamp = year + "/" + month + "/" + day + " " + hourOfDay + ":" + minute + " " + am_pm;
tv.setText(timeStamp);
}
}
| true |
674bdda7998b2cf68530d7b473f31a84be49e176 | Java | lite5408/jf-plus | /jf-plus-common/src/main/java/com/jf/plus/common/core/enums/DistSource.java | UTF-8 | 814 | 2.578125 | 3 | [] | no_license | package com.jf.plus.common.core.enums;
public enum DistSource {
ORGANIZATION_DIST(1, "机构分发"),
SITE_DIST(0, "站点管理员分发"),
MANAGER_DIST(2, "业务经理分发");
private int type;
private String description;
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
private DistSource(int type, String description)
{
this.type = type;
this.description = description;
}
public static DistSource getByType(int type)
{
for(DistSource at:DistSource.values()){
if(at.type==type){
return at;
}
}
throw new IllegalArgumentException("Not supported client type:" + type);
}
}
| true |
a9b9ce77d404e19ba6b5fc4c0a4e1ffdafe741cc | Java | julioserafim/ofertaacademica-v1.0 | /ofertaacademica-v1.0/aplicacao/oferta-academica/src/main/java/ufc/quixada/npi/ap/controller/CursoController.java | UTF-8 | 5,021 | 2.1875 | 2 | [] | no_license | package ufc.quixada.npi.ap.controller;
import static ufc.quixada.npi.ap.util.Constants.SWAL_STATUS_SUCCESS;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import ufc.quixada.npi.ap.exception.AlocacaoProfessorException;
import ufc.quixada.npi.ap.model.Curso;
import ufc.quixada.npi.ap.model.Curso.Turno;
import ufc.quixada.npi.ap.model.Papel;
import ufc.quixada.npi.ap.model.Professor;
import ufc.quixada.npi.ap.service.CursoService;
import ufc.quixada.npi.ap.service.ProfessorService;
import ufc.quixada.npi.ap.util.Constants;
import ufc.quixada.npi.ap.validation.CursoValidator;
@Controller
@RequestMapping("/cursos")
public class CursoController {
@Autowired
public CursoService cursoService;
@Autowired
public ProfessorService professorService;
@Autowired
CursoValidator validator;
@RequestMapping(value = { "", "/" }, method = RequestMethod.GET)
public ModelAndView listarCursos() {
ModelAndView modelAndView = new ModelAndView(Constants.CURSO_LISTAR);
List<Curso> cursos = cursoService.buscarTodosCursos();
modelAndView.addObject("cursos", cursos);
return modelAndView;
}
@RequestMapping(path = "/cadastrar", method = RequestMethod.GET)
public ModelAndView cadastrarCurso(@ModelAttribute("curso") Curso curso) {
ModelAndView modelAndView = new ModelAndView(Constants.CURSO_CADASTRAR);
List<Curso> cursos = cursoService.buscarTodosCursos();
List<Professor> professores = professorService.buscarTodosProfessores();
modelAndView.addObject("cursos", cursos);
modelAndView.addObject("turnos", Turno.values());
modelAndView.addObject("professores", professores);
return modelAndView;
}
@RequestMapping(path = "/cadastrar", method = RequestMethod.POST)
public ModelAndView cadastrarCurso(@ModelAttribute("curso") @Valid Curso curso, BindingResult result, RedirectAttributes redirectAttributes, ModelAndView modelAndView) throws AlocacaoProfessorException {
validator.validate(curso, result);
if(result.hasErrors()){
return cadastrarCurso(curso);
}
if(null == curso.getTurno())
curso.setTurno(Turno.MANHA);
if(null == curso.getSemestres())
curso.setSemestres(8);
cursoService.salvar(curso);
redirectAttributes.addFlashAttribute(SWAL_STATUS_SUCCESS, Constants.MSG_CURSO_CADASTRADO);
modelAndView.setViewName(Constants.CURSO_REDIRECT_LISTAR);
return modelAndView;
}
@RequestMapping(path = "/editar/{id}", method = RequestMethod.GET)
public ModelAndView editarCurso(@PathVariable("id") Integer idCurso) {
ModelAndView modelAndView = new ModelAndView(Constants.CURSO_EDITAR);
Curso curso = cursoService.buscarCurso(idCurso);
List<Professor> professores = professorService.buscarTodosProfessores();
if (curso == null){
modelAndView.setViewName(Constants.CURSO_REDIRECT_LISTAR);
return modelAndView;
}
modelAndView.addObject("curso", curso);
modelAndView.addObject("turnos", Turno.values());
modelAndView.addObject("professores", professores);
return modelAndView;
}
@RequestMapping(value = "/editar/", method = RequestMethod.POST)
public @ResponseBody ModelAndView editarCurso(@ModelAttribute("curso") @Valid Curso curso, BindingResult result, RedirectAttributes redirectAttributes, ModelAndView modelAndView) throws AlocacaoProfessorException {
Papel pl = new Papel();
pl.setId(1);
Curso cursoBD = cursoService.buscarCurso(curso.getId());
Professor coordenadorAntigo = cursoBD.getCoordenador();
Professor viceCoordenadorAntigo = cursoBD.getViceCoordenador();
coordenadorAntigo.getPapeis().remove(pl);
viceCoordenadorAntigo.getPapeis().remove(pl);
professorService.editar(coordenadorAntigo);
professorService.editar(viceCoordenadorAntigo);
validator.validate(curso, result);
if(result.hasErrors()){
modelAndView.setViewName(Constants.CURSO_EDITAR);
List<Curso> cursos = cursoService.buscarTodosCursos();
List<Professor> professores = professorService.buscarTodosProfessores();
modelAndView.addObject("cursos", cursos);
modelAndView.addObject("turnos", Turno.values());
modelAndView.addObject("professores", professores);
return modelAndView;
}
cursoService.salvar(curso);
redirectAttributes.addFlashAttribute(SWAL_STATUS_SUCCESS, Constants.MSG_CURSO_EDITADO);
modelAndView.setViewName(Constants.CURSO_REDIRECT_LISTAR);
return modelAndView;
}
}
| true |
9e07ceb7ae03028f3444eb20e347a1746db0a312 | Java | xhh0895/xhh | /java/algorith/src/com/xhh/algorithm/NC117.java | UTF-8 | 2,561 | 3.40625 | 3 | [] | no_license | package com.xhh.algorithm;
import java.util.Arrays;
/**
* @description:
* @author: xhh
* @date: 2021/6/18 10:30
*/
public class NC117 {
public static void main(String[] args) {
System.out.println(solve("100"));
}
/**
* 解码
* @param nums string字符串 数字串
* @return int整型
*/
public static int solve (String nums) {
// write code here
if (nums.length() == 0 || nums.charAt(0) == '0') return 0;
if (nums.length() == 1) return 1;
int pre1 = 1, pre2 = 1, cur = 0;
for (int i = 1; i < nums.length(); i++) {
cur = 0;
if (nums.charAt(i) != '0') {
if (i == 1) {
cur = pre1;
} else {
cur = pre2;
}
}
int num = (nums.charAt(i - 1) - '0') * 10 + (nums.charAt(i) - '0');
if (num >= 10 && num <= 26) {
if (i == 1) {
cur += 1;
} else {
cur += pre1;
}
}
pre1 = pre2;
pre2 = cur;
}
return cur;
}
public int maxProfit (int[] prices) {
// write code here
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] - prices[i - 1] > 0) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
/**
* 二叉树镜像
* @param pRoot
* @return
*/
public static TreeNode Mirror (TreeNode pRoot) {
// write code here
mirror(pRoot);
return pRoot;
}
public static void mirror(TreeNode pRoot) {
if (pRoot == null) {
return;
}
if (pRoot.left != null || pRoot.right != null) {
TreeNode t = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = t;
mirror(pRoot.left);
mirror(pRoot.right);
}
}
/**
* 奇偶调换
* @param array
* @return
*/
public int[] reOrderArray (int[] array) {
// write code here
int[] dst = new int[array.length];
int i = 0;
for (int k = 0; k < array.length; k++) {
if (array[k] % 2 != 0) {
dst[i++] = array[k];
}
}
for (int k = 0; k < array.length; k++) {
if (array[k] % 2 == 0) {
dst[i++] = array[k];
}
}
return dst;
}
}
| true |
344fe5c29aae9bbbb669cee735fe200c9593c0be | Java | rpryjda/RestApi | /src/main/java/com/pryjda/RestApi/exceptions/WrongLectureIdException.java | UTF-8 | 189 | 1.875 | 2 | [] | no_license | package com.pryjda.RestApi.exceptions;
public class WrongLectureIdException extends RuntimeException {
public WrongLectureIdException(String message) {
super(message);
}
}
| true |
1678cbd7258706a00df1ad9032c81c31be11d24a | Java | AndriiCorez/automationtesttaks | /src/test/java/helpers/Await.java | UTF-8 | 1,641 | 3.140625 | 3 | [] | no_license | package helpers;
import base.TestSettings;
import org.awaitility.core.ConditionFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.with;
/**
* Contains functionality for waiting any for conditions to be true
* Default values for delay, interval are:
* 100 milliseconds, 100 milliseconds
*/
public class Await {
private static ConditionFactory withListener(){
return with().conditionEvaluationListener(conditionListener -> System.out.println(conditionListener.getDescription() +
"|elapsed:" + conditionListener.getElapsedTimeInMS() +
"|remained:" + conditionListener.getRemainingTimeInMS()));
}
/**
* Waits during the timeout specified as Custom wait in .properties settings until true output of
* @param condition conditional statement
*/
public static void waitUntil(Callable<Boolean> condition){
withListener().
await().
atMost(TestSettings.getInstance().getWaitCustom(), TimeUnit.SECONDS).
until(condition);
}
/**
* Waits ignoring any thrown exceptions during the timeout specified as Custom wait in .properties settings until true output of
* @param condition conditional statement
*/
public static void waitUntilIgnoringExceptions(Callable<Boolean> condition){
withListener().
given().
ignoreExceptions().
await().
atMost(TestSettings.getInstance().getWaitCustom(), TimeUnit.SECONDS).
until(condition);
}
}
| true |
a3b53f10ce4f5a92ca9fff15c4be0a13fc22ab6a | Java | sangdo913/OpenGLESPractice | /NDKPractice2/app/src/main/java/com/example/sd/ndkpractice2/Store.java | UTF-8 | 399 | 2.390625 | 2 | [] | no_license | package com.example.sd.ndkpractice2;
// JNI를 위한 클래스
public class Store {
static{
System.loadLibrary("native-lib");
//System.loadLibrary("Store");
}
//네이티브 함수들!
public native int add(int a, int b);
public native int mul(int a, int b);
public native String getString(int key);
public native void setString(int key, String str);
}
| true |
34d999853eaba86bb82a71bdfa7adfd3b351bc1c | Java | Jefferson-Euclides/test-ilegra | /src/test/java/com/teste/ilegra/ilegra/service/data/DataAnalyserTest.java | UTF-8 | 3,850 | 1.914063 | 2 | [] | no_license | package com.teste.ilegra.ilegra.service.data;
import com.teste.ilegra.ilegra.BaseTest;
import com.teste.ilegra.ilegra.service.client.ClientService;
import com.teste.ilegra.ilegra.service.file.FileWriter;
import com.teste.ilegra.ilegra.service.sale.SaleService;
import com.teste.ilegra.ilegra.service.salesman.SalesmanService;
import com.teste.ilegra.ilegra.service.salesman.SalesmanServiceTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.*;
@AutoConfigureMockMvc
@SpringBootTest
@RunWith(SpringRunner.class)
public class DataAnalyserTest extends BaseTest {
@Mock
FileWriter fileWriter;
@Mock
ClientService clientService;
@Mock
SalesmanService salesmanService;
@Mock
SaleService saleService;
@InjectMocks
DataAnalyser dataAnalyser;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldCallGetClientsTotalQuantityOneTime() {
when(clientService.getClientsTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getSalesmanTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(saleService.getBiggestSaleId(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getWorstSalesman(anyList())).thenReturn(String.valueOf('a'));
dataAnalyser.analyzeFileData(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), "");
verify(clientService, times(1)).getClientsTotalQuantity(anyList());
}
@Test
public void shouldCallGetSalesmanTotalQuantityOneTime() {
when(clientService.getClientsTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getSalesmanTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(saleService.getBiggestSaleId(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getWorstSalesman(anyList())).thenReturn(String.valueOf('a'));
dataAnalyser.analyzeFileData(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), "");
verify(salesmanService, times(1)).getSalesmanTotalQuantity(anyList());
}
@Test
public void shouldCallGetBiggestSaleOneTime() {
when(clientService.getClientsTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getSalesmanTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(saleService.getBiggestSaleId(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getWorstSalesman(anyList())).thenReturn(String.valueOf('a'));
dataAnalyser.analyzeFileData(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), "");
verify(saleService, times(1)).getBiggestSaleId(anyList());
}
@Test
public void shouldCallGetWorstSalesmanOneTime() {
when(clientService.getClientsTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getSalesmanTotalQuantity(anyList())).thenReturn(Long.valueOf(1l));
when(saleService.getBiggestSaleId(anyList())).thenReturn(Long.valueOf(1l));
when(salesmanService.getWorstSalesman(anyList())).thenReturn(String.valueOf('a'));
dataAnalyser.analyzeFileData(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), "");
verify(salesmanService, times(1)).getWorstSalesman(anyList());
}
}
| true |
f6a0e21b708fca42ebebad563ca84066d14b0e6c | Java | zhxysky/thinginjava | /src/com/zhxy/test/NodeChain.java | UTF-8 | 1,614 | 3.6875 | 4 | [] | no_license | package com.zhxy.test;
public class NodeChain {
Node head;// 头节点
Node tail; // 尾节点
private int size;
public void addNode(Node node) {
if (head == null) {
head = node;
tail = node;
tail.next = null;
} else {
tail.next = node;
node.pre = tail;
tail = tail.next;
tail.next = null;
}
}
public void printChain() {
for (Node temp = head; temp != null; temp = temp.next) {
temp.printNode();
}
System.out.println();
}
public void removeRepeatedNode() {
Node curr = head;
while (curr != null) {
for (Node temp = curr.next; temp != null; temp = temp.next) {
if (curr.value == temp.value) {
if (temp.next != null) {
// 移除该node
temp.pre.next = temp.next;
temp.next.pre = temp.pre;
} else {
temp.pre.next = null;
}
}
}
curr = curr.next;
}
printChain();
}
public static void main(String[] args) {
NodeChain nodeChain = new NodeChain();
Node node = null;
for (int i = 0; i < 10; i++) {
node = new Node();
node.setValue(i % 2);
nodeChain.addNode(node);
}
nodeChain.printChain();
System.out.println("*****");
nodeChain.removeRepeatedNode();
}
}
class Node {
Node pre;
Node next;
int value;
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public void printNode() {
System.out.print(this.value + "\t");
}
}
| true |
75970e48af7931b62bc38f85ee6fdc11e3114070 | Java | sun654321/javaweb-jy5 | /rlg/rlg_1/src/com/controller/CategoryController.java | UTF-8 | 2,654 | 2.65625 | 3 | [] | no_license | package com.controller;
import com.common.ResponseCode;
import com.service.CategoryService;
import com.util.PathUtil;
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 java.io.IOException;
@WebServlet(name = "CategoryController",value = "/manage/category/*")
public class CategoryController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private CategoryService cs = new CategoryService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo();
String path = PathUtil.getPath(pathInfo);
ResponseCode rs = null;
//判断是什么请求
switch (path) {
case "get_category":
rs = get_categorydo(request);
break;
case "add_category":
rs=add_categorydo(request);
case "set_category_name":
rs=set_category_namedo(request);
case "get_deep_category":
rs=get_deep_categorydo(request);
}
//返回响应的数据
response.getWriter().write(rs.toString());
}
//获取品类子节点
private ResponseCode get_categorydo(HttpServletRequest request) {
//传入的值为null
String categoryId = request.getParameter("categoryId");
ResponseCode rs=cs.selectone(categoryId); //调用业务层处理业务
return rs;
}
//增加节点
private ResponseCode add_categorydo(HttpServletRequest request) {
String parentId=request.getParameter("parentId");
String categoryName=request.getParameter("categoryName");
ResponseCode rs = cs.selectone1(parentId, categoryName);
return rs;
}
//修改品类姓名
private ResponseCode set_category_namedo(HttpServletRequest request) {
String categoryId=request.getParameter("categoryId");
String categoryName=request.getParameter("categoryName");
ResponseCode rs = cs.selectone2(categoryId, categoryName);
return rs;
}
//获取当前分类id及递归子节点categoryId
private ResponseCode get_deep_categorydo(HttpServletRequest request){
String categoryId = request.getParameter("categoryId");
ResponseCode rs=cs.selectone3(categoryId);
return rs;
}
}
| true |
70a97f4496e4bd446b6d10bde02bdce089319f54 | Java | rhysanchez/COE127_DOE_Bank_Multrithread | /src/Time.java | UTF-8 | 370 | 2.8125 | 3 | [] | no_license | import java.util.*;
import java.io.*;
public class Time implements Runnable{
public void run()
{
int count = 0;
for(int i=0; i<10000000;i++)
{
try {
Thread.sleep(1000);
count ++;
System.out.println("Elapsed Time: "+count+"s");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| true |
d749b990c5c754993c636224b971285cc71d0c6b | Java | jackieju/ngus | /src/myWeb/myWeb/src/main/java/com/ngus/myweb/action/SearchText.java | UTF-8 | 1,409 | 1.976563 | 2 | [] | no_license | package com.ngus.myweb.action;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import com.ngus.message.MessageObject;
import com.ngus.message.MessageEngine;
import com.ngus.myweb.form.SearchTextForm;
public final class SearchText extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages errors = new ActionMessages();
String postId = (String)((SearchTextForm)form).getPostId();
String text = (String)((SearchTextForm)form).getText();
List<MessageObject> result = new ArrayList<MessageObject>();
result = MessageEngine.instance().searchText(postId,text);
int lenss = result.size();
if(result.size() > 0 ){
request.setAttribute("result" , result );
}
request.setAttribute("text" , text );
request.setAttribute("lenss" , lenss);
return (mapping.findForward("list"));
}
}
| true |
926e50a03b4216ee11c0a8a073559ed33a78dce5 | Java | 870235784/netty-wechat | /netty-wechat-server/src/main/java/com/tca/netty/wechat/server/WechatServerApplication.java | UTF-8 | 555 | 1.726563 | 2 | [] | no_license | package com.tca.netty.wechat.server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author zhoua
* @Date 2020/11/22
* 启动类
*/
@SpringBootApplication
@EnableConfigurationProperties
@Slf4j
public class WechatServerApplication {
public static void main(String[] args) {
SpringApplication.run(WechatServerApplication.class, args);
}
}
| true |
44792b8c9adcf7f66ba973ee80db2401507878c1 | Java | evertoncastro/sudbrain | /sudbrain/src/br/com/project/sudbrain/model/dao/UsuarioDAO.java | UTF-8 | 372 | 1.921875 | 2 | [] | no_license | package br.com.project.sudbrain.model.dao;
import java.util.List;
import br.com.project.sudbrain.model.vo.Usuario;
public interface UsuarioDAO {
public Usuario buscaUsuario(String login, String senha);
public boolean cadastrarUsuario(Usuario usuario);
public boolean alterarPontos(int id, int pontos);
public List<Usuario> buscarMelhorPontuacao();
}
| true |
598ea6d44f2432d74f1cc7a8eaa231f3b58c4e04 | Java | aritzg/Lifedroid | /src/main/java/net/sareweb/lifedroid/rest/DLFolderRESTClient.java | UTF-8 | 1,233 | 2.265625 | 2 | [] | no_license | package net.sareweb.lifedroid.rest;
import net.sareweb.lifedroid.model.DLFolder;
import net.sareweb.lifedroid.rest.generic.LDRESTClient;
import org.springframework.http.HttpMethod;
public class DLFolderRESTClient extends LDRESTClient<DLFolder> {
public DLFolderRESTClient(ConnectionData connectionData) {
super(connectionData);
}
public DLFolder addFolder(DLFolder dLFolder) {
String requestURL = getBaseURL() +"/add-folder/";
requestURL = addParamToRequestURL(requestURL, "group_id", dLFolder.getGroupId());
requestURL = addParamToRequestURL(requestURL, "repository-id", dLFolder.getRepositoryId());
requestURL = addParamToRequestURL(requestURL, "mount-point", false);
requestURL = addParamToRequestURL(requestURL, "parent-polder-id", dLFolder.getParentFolderId());
requestURL = addParamToRequestURL(requestURL, "name", dLFolder.getName(), true);
requestURL = addParamToRequestURL(requestURL, "description", dLFolder.getDescription(),true);
requestURL = addParamToRequestURL(requestURL, "service-context", "{}");
return run(requestURL, HttpMethod.POST);
}
@Override
public String getPorltetContext() {
return "";
}
@Override
public String getModelName() {
return "dlapp";
}
}
| true |
c754f3d2cb52dcb43887c0b87199a828d5f544bf | Java | duslee/jokes | /pushPlug_v2018/src/com/common/as/image/FileImageCache.java | UTF-8 | 4,562 | 2.453125 | 2 | [] | no_license | package com.common.as.image;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.common.as.base.log.BaseLog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
public class FileImageCache extends ImageCache {
private final File mCacheDir;
public Context mContext;
private static final String FILE_DIR = "img";
public static final int DEFAULT_MAX_PIXS = 128*128;
public FileImageCache(Context context) {
File dir = context.getFilesDir();
mCacheDir = new File(dir+File.separator+FILE_DIR+ File.separator);
BaseLog.d("main4", "mCacheDir.getAbsolutePath()="+mCacheDir.getAbsolutePath());
if (!mCacheDir.exists()) {
mCacheDir.mkdir();
}
mContext = context;
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
//Android提供了一种动态计算采样率的方法。
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) &&
(minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
public Bitmap getBitmap(String url,boolean isOral){
if (isOral) {
String key = generateKey(url);
Bitmap bitmap = null;
File file = new File(mCacheDir, key);
if (file.exists() && file.isFile()) {
try {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (OutOfMemoryError err) {
}
}
return bitmap;
} else {
return getBitmap(url);
}
}
@Override
public Bitmap getBitmap(String url) {
String key = generateKey(url);
Bitmap bitmap = null;
File file = new File(mCacheDir, key);
if (file.exists() && file.isFile()) {
BitmapFactory.Options opts = new BitmapFactory.Options();
//设置inJustDecodeBounds为true后,decodeFile并不分配空间,但可计算出原始图片的长度和宽度,即opts.width和opts.height。有了这两个参数,再通过一定的算法,即可得到一个恰当的inSampleSize。
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
opts.inSampleSize = computeSampleSize(opts, -1, DEFAULT_MAX_PIXS);
opts.inJustDecodeBounds = false;
try {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
} catch (OutOfMemoryError err) {
}
}
return bitmap;
}
@Override
public synchronized boolean putBitmap(String url, Bitmap bitmap) {
String key = generateKey(url);
if (bitmap != null) {
File file = new File(mCacheDir, key);
if (file.exists() && file.isFile()) {
return true; // file exists
}
try {
FileOutputStream fos = new FileOutputStream(file);
//new FileOutputStream(file);
boolean saved = bitmap.compress(CompressFormat.PNG, 80, fos);
fos.flush();
fos.close();
return saved;
} catch (IOException e) {
System.out.println("mingo:err");
e.printStackTrace();
}
}
return false;
}
public void cleanCacheDir(){
if (mCacheDir.exists()) {
File[] files =mCacheDir.listFiles();
for (File file : files) {
if (file.exists() && file.isFile()) {
file.delete(); // file exists
}
}
}
}
public void cleanCacheFile(String url){
String key = generateKey(url);
File file = new File(mCacheDir, key);
if (file.exists() && file.isFile()) {
file.delete();
}
}
public Context getContext(){
return this.mContext;
}
}
| true |
341f38186112429cc43857723d286632b6bcce8d | Java | dfzunigah/Genius-Computer | /Source/UI/AnimatedLabel.java | UTF-8 | 1,312 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | package UI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AnimatedLabel extends JPanel {
private JTextArea label;
private int charIndex = 0;
public AnimatedLabel(ResourceBundle traductor, String text) {
setLayout(new GridBagLayout());
label = new JTextArea();
label.setFont(new Font("Serif", Font.PLAIN, 20));
label.setBackground(Color.WHITE);
add(label);
Timer timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String labelText = label.getText();
labelText += text.charAt(charIndex);
label.setText(labelText);
charIndex++;
if (charIndex >= text.length()) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
label.setEnabled(false);
}
}
| true |
491df1c19086f63d15e7c42847fb41889fc681d7 | Java | jayantak/Biblioteca | /src/biblioteca/library/Library.java | UTF-8 | 2,026 | 3.046875 | 3 | [] | no_license | package biblioteca.library;
import biblioteca.library.lendableItems.Book;
import biblioteca.library.lendableItems.Lendable;
import biblioteca.library.lendableItems.Movie;
import biblioteca.library.user.User;
import biblioteca.library.user.UserAuthenticator;
//Understands lending and returning of books
public class Library {
private LendableList inventory;
private UserAuthenticator userAuthenticator;
public Library(LendableList inventory, UserAuthenticator userAuthenticator) {
this.inventory = inventory;
this.userAuthenticator = userAuthenticator;
}
public void checkoutLendable(Lendable foundLendable, User user) {
inventory.replace(foundLendable, User.NO_USER, user);
}
public Lendable getAvailableBookByName(String bookTitle) {
Lendable found = inventory.findByName(bookTitle, User.NO_USER);
if (found.getClass() != Book.class) {
return Lendable.NO_LENDABLE;
}
return found;
}
public void returnLendable(Lendable foundLendable, User user) {
inventory.replace(foundLendable, user, User.NO_USER);
}
public Lendable getCheckedOutBookByName(String bookTitle) {
Lendable found = inventory.findByName(bookTitle, userAuthenticator.getCurrentUser());
if (found.getClass() != Book.class) {
return Lendable.NO_LENDABLE;
}
return found;
}
public LendableList available() {
return inventory;
}
public Lendable getCheckedOutMovieByName(String title) {
Lendable found = inventory.findByName(title, User.NO_USER);
if (found.getClass() != Movie.class) {
return Lendable.NO_LENDABLE;
}
return found;
}
public Lendable getAvailableMovieByName(String bookTitle) {
Lendable found = inventory.findByName(bookTitle, userAuthenticator.getCurrentUser());
if (found.getClass() != Movie.class) {
return Lendable.NO_LENDABLE;
}
return found;
}
}
| true |
2e9941f1976ade7cb91294b78c8bd47b1305c125 | Java | G631233828/MicroserviceTest | /app/app-admin/src/main/java/zhongchiedu/com/controller/ResourceController.java | UTF-8 | 5,891 | 2.09375 | 2 | [] | no_license | package zhongchiedu.com.controller;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import lombok.extern.slf4j.Slf4j;
import zhongchiedu.annotation.SystemControllerLog;
import zhongchiedu.com.pojo.Resource;
import zhongchiedu.com.service.ResourceService;
import zhongchiedu.com.utils.BasicDataResult;
import zhongchiedu.com.utils.Common;
import zhongchiedu.framework.pagination.Pagination;
@Controller
@RequestMapping("/admin")
@Slf4j
public class ResourceController {
@Autowired
private ResourceService resourceService;
@GetMapping("/resources")
@RequiresPermissions(value = "admin:resource:list")
@SystemControllerLog(description = "查询所有资源")
public String list(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model,
@RequestParam(value = "pageSize", defaultValue = "9999") Integer pageSize) {
// 分页查询数据
try {
Pagination<Resource> pagination = this.resourceService.list(pageNo, pageSize);
model.addAttribute("pageList", pagination);
} catch (Exception e) {
log.info("查询资源信息失败{}", e.toString());
}
return "admin/resource/list";
}
@ResponseBody
@GetMapping("/resourcestest")
public List<Resource> test(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model,
@RequestParam(value = "pageSize", defaultValue = "9999") Integer pageSize) {
List<Resource> lists = this.resourceService.findAllResource();
return lists;
}
/**
* 跳转到添加页面
*/
@GetMapping("/resource")
@RequiresPermissions(value = "admin:resource:add")
public String addUserPage(Model model) {
//获取所有的启用的资源目录
List<Resource> list = this.resourceService.findResourcesByType(0);
model.addAttribute("resList", list);
return "admin/resource/add";
}
@PostMapping("/resource")
@RequiresPermissions(value = "admin:resource:add")
@SystemControllerLog(description = "添加资源")
public String addResource(
@ModelAttribute("resource") Resource resource,
@RequestParam(value = "parentSubId", defaultValue = "") String parentSubId) {
if(Common.isNotEmpty(parentSubId)){
resource.setParentId(parentSubId);
}
if(resource.getType() == 0){
resource.setParentId("0");
}
this.resourceService.saveOrUpdateUser(resource);
return "redirect:/admin/resources";
}
@PutMapping("/resource")
@RequiresPermissions(value = "admin:resource:edit")
@SystemControllerLog(description = "修改资源")
public String editResource(
@ModelAttribute("resource") Resource resource,
@RequestParam(value = "parentSubId", defaultValue = "") String parentSubId) {
if(Common.isNotEmpty(parentSubId)){
resource.setParentId(parentSubId);
}
if(resource.getType() == 0){
resource.setParentId("0");
}
this.resourceService.saveOrUpdateUser(resource);
return "redirect:/admin/resources";
}
/**
* 根据选择的目录获取菜单
* @param parentId
* @return
*/
@RequestMapping(value="/getparentmenu",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
@ResponseBody
public BasicDataResult getparentmenu(@RequestParam(value = "parentId", defaultValue = "") String parentId){
List<Resource> list = this.resourceService.findResourceMenu(parentId);
return list!=null?BasicDataResult.build(200, "success",list):BasicDataResult.build(400, "error",null);
}
/**
* 跳转到编辑界面
*
* @return
*/
@GetMapping("/resource/{id}")
@RequiresPermissions(value = "admin:resource:edit")
public String toeditPage(@PathVariable String id, Model model) {
Resource resource = this.resourceService.findResourceById(id);
//resource获取到之后需要查看资源
if(resource!=null){
int type = resource.getType();
//如果type是1需要获取所有目录
List resList = this.resourceService.findResourcesByType(0);
List resmenu = null;
//如果type是2需要获取所有目录与菜单
if(type == 2){
resmenu = this.resourceService.findResourceMenuByid(resource.getParentId());
model.addAttribute("resourssubmenuId", resource.getParentId());
Resource ressup = this.resourceService.findResourceById(resource.getParentId());
model.addAttribute("resourssupmenuId", ressup.getParentId());
}
if(type == 1){
model.addAttribute("resourssupmenuId", resource.getParentId());
}
model.addAttribute("resList", resList);
model.addAttribute("resmenu", resmenu);
}
model.addAttribute("resource", resource);
return "admin/resource/add";
}
@DeleteMapping("/resource/{id}")
@RequiresPermissions(value = "admin:resource:delete")
@SystemControllerLog(description = "删除资源")
public String delete(@PathVariable String id){
this.resourceService.remove(id);
return "redirect:/admin/resources";
}
@RequestMapping(value = "/resource/disable", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
@ResponseBody
public BasicDataResult resourceDisable(@RequestParam(value = "id", defaultValue = "") String id) {
return this.resourceService.resourceDisable(id);
}
}
| true |
99ed11aa3edc694893c3c5d1be60dfd1a3c4ad19 | Java | panikhil/MyFirstJava | /MyFirstJava/src/com/rakuten/basics/ChemicalElements.java | UTF-8 | 1,593 | 3.265625 | 3 | [] | no_license | package com.rakuten.basics;
public class ChemicalElements implements Comparable<ChemicalElements> {
int atomicNumber;
String name;
String symbol;
static boolean[] alkaliMetals = new boolean[120];
static {
alkaliMetals[3] = true;
alkaliMetals[11] = true;
alkaliMetals[19] = true;
alkaliMetals[37] = true;
alkaliMetals[55] = true;
alkaliMetals[87] = true;
}
public ChemicalElements(int atomicNumber, String name, String symbol) {
this.atomicNumber = atomicNumber;
this.name = name;
this.symbol = symbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + atomicNumber;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChemicalElements other = (ChemicalElements) obj;
if (atomicNumber != other.atomicNumber)
return false;
return true;
}
public boolean isTransitionMetal() {
return (atomicNumber >= 21 && atomicNumber <= 31)
||(atomicNumber >= 39 && atomicNumber <= 48)
||(atomicNumber >= 72 && atomicNumber <= 80)
||(atomicNumber >= 104 && atomicNumber <= 112);
}
public boolean isAlkaliMetal() {
return alkaliMetals[atomicNumber];
}
@Override
public int compareTo(ChemicalElements other) {
if(this.atomicNumber> other.atomicNumber) {
return 1; //we are returning positive i.e. this Object is > than other
}
else if(other.atomicNumber > this.atomicNumber ) {
return -1;
}
else {
return 0;
}
}
}
| true |
debe0bc0416b63a3fe536bb7e3c17d565f655b1a | Java | CSID-DGU/2017-2-CSP-Revergence-4 | /DBhelper.java | UTF-8 | 2,026 | 2.671875 | 3 | [] | no_license | package com.example.audiocheck.audiocheck;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
// 데이터 저장
public class DBhelper extends SQLiteOpenHelper {
private static final String DB_NAME="dadev"; //db 이름
private static final int DB_VER = 1; // db 버전
private static final String DB_TABLE="audiocheck"; //table 이름
public DBhelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
// 디비 테이블 생성
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE audiocheck(_id INTEGER PRIMARY KEY AUTOINCREMENT, newdate TEXT, " +
"newscore INTEGER);");
}
// 버전변경시 업데이트
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = String.format("DELETE TABLE IF EXISTS %s",DB_TABLE);
db.execSQL(query); // 테이블 삭제
onCreate(db); // 완료한다.
}
//회원가입
public void insert(String date,int score){
SQLiteDatabase db = getWritableDatabase(); // getWritableDatabase = 읽고 쓸수 있게
db.execSQL("INSERT INTO audiocheck VALUES(NULL,'"+date+"', "+score+");");
db.close();
}
// 게시판 글 목록 조회
public ArrayList<DbModel> getdata() {
ArrayList<DbModel> itemmodels = new ArrayList<DbModel>();
SQLiteDatabase db = getReadableDatabase();
String query = "select * from "+DB_TABLE;
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()){
DbModel model = new DbModel();
String date = c.getString(1);
int score = c.getInt(2);
model.setDate(date);
model.setScore(score);
itemmodels.add(model);
}
c.close();
db.close();
return itemmodels;
}
}
| true |
d375a9e4bb334cb0f345ec580b92de2f9c926a62 | Java | vinfai/hy_project | /marketingcenter/marketing-core/src/main/java/com/mockuai/marketingcenter/core/manager/DistributorManager.java | UTF-8 | 806 | 1.820313 | 2 | [] | no_license | package com.mockuai.marketingcenter.core.manager;
import java.util.List;
import com.mockuai.distributioncenter.common.domain.dto.DistShopDTO;
import com.mockuai.distributioncenter.common.domain.dto.GainsSetDTO;
import com.mockuai.distributioncenter.common.domain.dto.ItemSkuDistPlanDTO;
import com.mockuai.distributioncenter.common.domain.qto.DistShopQTO;
import com.mockuai.marketingcenter.core.exception.MarketingException;
/**
* Created by edgar.zr on 5/23/2016.
*/
public interface DistributorManager {
List<DistShopDTO> queryShop(DistShopQTO distShopQTO, String appKey) throws MarketingException;
GainsSetDTO getGainsSet(String appKey) throws MarketingException;
List<ItemSkuDistPlanDTO> getItemSkuDistPlanList(Long itemId , String appKey) throws MarketingException;
} | true |
36dcaa78d741796b9afd453050d5ba1ac4d768b6 | Java | rafiulgits/HelloJava | /design-pattern/command/Processor.java | UTF-8 | 419 | 2.6875 | 3 | [
"MIT"
] | permissive | package sdp.command;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author rafiul islam
*/
public class Processor {
List<Task> processList;
public Processor(){
processList = new ArrayList<>();
}
public void add(Task task){
processList.add(task);
}
public void run(){
for(Task task : processList){
task.execute();
}
}
}
| true |
b10f89c30376f9a41673cb0c654b02b4dcd692f0 | Java | eladfeld/MyNetwork | /spl-net/src/main/java/bgu/spl/net/impl/stomp/StompServer.java | UTF-8 | 860 | 2.515625 | 3 | [] | no_license | package bgu.spl.net.impl.stomp;
import bgu.spl.net.srv.Server;
public class StompServer {
public static void main(String[] args) {
if(args.length < 1)throw new IllegalArgumentException("No argument given for server pattern");
if(args.length < 2)throw new IllegalArgumentException("No port given for server pattern");
int port = Integer.parseInt(args[1]);
int numberOfThreads = 8;
if(args[0].equals("TPC")){
Server.threadPerClient(
port,
StompProtocol::new,
EncoderDecoder::new
).serve();
}
else {
Server.reactor(
numberOfThreads,
port,
StompProtocol::new,
EncoderDecoder::new
).serve();
}
}
}
| true |
c65666c04aeaf36f8a89ce7b6bb910aa299ed6e0 | Java | JofreyLuc/CMIAndroid | /projet/CMI/app/src/main/java/com/univ/lorraine/cmi/MyFilePickerActivity.java | UTF-8 | 2,476 | 2.703125 | 3 | [] | no_license | package com.univ.lorraine.cmi;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.widget.Toast;
import com.nononsenseapps.filepicker.AbstractFilePickerActivity;
import com.nononsenseapps.filepicker.AbstractFilePickerFragment;
import com.nononsenseapps.filepicker.FilePickerFragment;
import java.io.File;
/**
* Created by alexis on 11/05/2016.
*/
public class MyFilePickerActivity extends AbstractFilePickerActivity<File> {
public MyFilePickerActivity() {
super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// On affiche un toast informant l'utilisateur qu'il peut choisir des fichiers epub
Toast.makeText(MyFilePickerActivity.this, "Veuillez sélectionner les livres au format EPUB que vous souhaitez importer", Toast.LENGTH_SHORT).show();
}
@Override
protected AbstractFilePickerFragment<File> getFragment(
final String startPath, final int mode, final boolean allowMultiple,
final boolean allowCreateDir) {
// Only the fragment in this line needs to be changed
AbstractFilePickerFragment<File> fragment = new MyFilePickerFragment();
fragment.setArgs(startPath, mode, allowMultiple, allowCreateDir);
return fragment;
}
public static class MyFilePickerFragment extends FilePickerFragment {
// Filtre sur les extensions de fichier
private static final String EXTENSION = ".epub";
/**
* Retourne l'extension d'un fichier.
* @param file Le fichier
* @return L'extension du fichier, si le fichier n'a pas d'extension, retourne null.
*/
private String getExtension(@NonNull File file) {
String path = file.getPath();
int i = path.lastIndexOf(".");
if (i < 0) {
return null;
} else {
return path.substring(i);
}
}
@Override
protected boolean isItemVisible(final File file) {
boolean ret = super.isItemVisible(file);
if (ret && !isDir(file) && (mode == MODE_FILE || mode == MODE_FILE_AND_DIR)) {
String ext = getExtension(file);
return ext != null && EXTENSION.equalsIgnoreCase(ext);
}
return ret;
}
}
}
| true |
d778b4d2b473330a9cf92b3da340ef3b1a1c568a | Java | huizhongyu/SudiVCAndroidClient | /app/src/main/java/cn/closeli/rtc/UpgradeAppUtil.java | UTF-8 | 9,590 | 1.992188 | 2 | [
"Apache-2.0"
] | permissive | package cn.closeli.rtc;
import android.app.DownloadManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import cn.closeli.rtc.service.AutoInstallService;
import cn.closeli.rtc.utils.L;
import cn.closeli.rtc.utils.SystemUtil;
import cn.closeli.rtc.utils.UtilsKt;
import cn.closeli.rtc.utils.ext.Act1;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class UpgradeAppUtil {
private static String[] paths = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/", "/su/bin/"};
public static boolean isUpgrade(String versionName, String upgradeType) {
L.d("cur versionCode:%1$s", SystemUtil.getVersionName(App.getInstance().getApplicationContext()));
L.d("upgrade dst versionCode:%1$s", versionName);
int compareRes = compareVersion(versionName, SystemUtil.getVersionName(App.getInstance().getApplicationContext()));
if ((upgradeType.equalsIgnoreCase("forceUpgrade") && compareRes != 0) ||
(upgradeType.equalsIgnoreCase("generalUpgrade") && compareRes > 0)) {
L.d("upgradeType:%1$s", upgradeType);
return true;
}
return false;
}
public static int compareVersion(String s1, String s2) {
String[] s1Split = s1.split("\\.", -1);
String[] s2Split = s2.split("\\.", -1);
int len1 = s1Split.length;
int len2 = s2Split.length;
int lim = Math.min(len1, len2);
int i = 0;
while (i < lim) {
int c1 = "".equals(s1Split[i]) ? 0 : Integer.parseInt(s1Split[i]);
int c2 = "".equals(s2Split[i]) ? 0 : Integer.parseInt(s2Split[i]);
if (c1 != c2) {
return c1 - c2;
}
i++;
}
return len1 - len2;
}
/**
* 检查无障碍服务
*
* @return
*/
private static boolean checkAccessibility(Context cxt) {
try {
int enable = Settings.Secure.getInt(cxt.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0);
if (enable != 1) {
return false;
}
String services = Settings.Secure.getString(cxt.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (!TextUtils.isEmpty(services)) {
TextUtils.SimpleStringSplitter split = new TextUtils.SimpleStringSplitter(':');
split.setString(services);
// 遍历所有已开启的辅助服务名
while (split.hasNext()) {
if (split.next().equalsIgnoreCase(cxt.getPackageName() + "/" + AutoInstallService.class.getName())) {
return true;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 静默安装
*/
private static void slientInstall(Context context, String downloadUrl, UpgradCallback callback) {
downLoadApk(downloadUrl, callback, file -> UtilsKt.install(context, context.getPackageName(), file));
}
/**
* 是否root
*
* @return
*/
private static boolean isRoot() {
try {
for (String path : paths) {
File file = new File(path + "su");
if (file.exists() && file.canExecute()) {
return true;
}
}
} catch (Exception x) {
x.printStackTrace();
}
return false;
}
/**
* 更新升级
* @param context
* @param downloadUrl
* @param callback
* @return
*/
public static boolean upgrade(Context context, String downloadUrl, UpgradCallback callback) {
String packageName = context.getPackageName();
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (isRoot()) {
if (devicePolicyManager.isDeviceOwnerApp(packageName)) {
//静默安装
slientInstall(context, downloadUrl, callback);
} else if (checkAccessibility(context)) {
installByAccessibility(context,downloadUrl,callback);
} else {
normalInstall(downloadUrl);
}
} else {
if (checkAccessibility(context)) {
installByAccessibility(context,downloadUrl,callback);
} else {
normalInstall(downloadUrl);
}
}
return true;
}
private static void downLoadApk(String downloadUrl, UpgradCallback callback, Act1<String> act1) {
String fileName = downloadUrl.split("/")[downloadUrl.split("/").length - 1];
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request
.Builder()
.get()
.url(downloadUrl)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if (callback != null) {
callback.onError("下载失败");
}
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
File dir = new File("/data/local/tmp");
if (!dir.exists()) {
dir.mkdir();
}
ResponseBody body;
if ((body = response.body()) != null) {
InputStream is = body.byteStream();
File apkFile = new File(dir, fileName);
if (apkFile.exists()) {
apkFile.delete();
}
FileOutputStream fos = new FileOutputStream(apkFile);
int len;
byte[] buffer = new byte[2048];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.flush();
fos.close();
act1.run(fileName);
} else {
callback.onError("下载失败");
}
}
});
}
/**
* 通过无障碍服务安装
*/
private static void installByAccessibility(Context cxt,String downloadURL,UpgradCallback callback) {
downLoadApk(downloadURL,callback,apkFile -> {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(cxt, cxt.getPackageName() + ".fileProvider", new File(apkFile));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(new File(apkFile));
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
cxt.startActivity(intent);
} catch (Throwable e) {
normalInstall(downloadURL);
}
});
}
private static void normalInstall(String downloadUrl) {
String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-debug.apk";
File file = new File(downLoadPath);
if (file.exists()) {
L.d("%1$s file exists", downLoadPath);
file.delete();
}
L.d("downloadUrl %1$s", downloadUrl);
L.d("downloadPath %1$s", downLoadPath);
DownloadManager downloadManager;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
//设置在什么网络情况下进行下载
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setVisibleInDownloadsUi(true);
request.setTitle("云视讯");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setAllowedOverRoaming(true);
request.setMimeType("application/vnd.android.package-archive");
request.setDestinationUri(Uri.parse("file://" + downLoadPath));
downloadManager = (DownloadManager) App.getInstance().getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
long enqueue = downloadManager.enqueue(request);
SharedPreferences usericonpreferencess = App.getInstance().getApplicationContext().getSharedPreferences("sudi", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = usericonpreferencess.edit();
edit.putLong("refernece", enqueue);
edit.apply();
}
public interface UpgradCallback {
void onError(String msg);
void onSuccess();
}
}
| true |
cba7dd478607f172b5b77e62080fbd8849661e79 | Java | pudilan/learning | /sc-parent/scs-redis/src/test/java/com/sintmo/redis/TestRedisConnect.java | UTF-8 | 2,192 | 2.546875 | 3 | [] | no_license | package com.sintmo.redis;
import org.junit.Test;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
public class TestRedisConnect {
@Test
public void ConnectToRedis() {
// Syntax: redis://[password@]host[:port][/databaseNumber]
RedisClient redisClient = RedisClient.create("redis://abab1456@192.168.56.140:6379/0");
System.out.println("create a client");
StatefulRedisConnection<String, String> connection = redisClient.connect();
System.out.println("Connected to Redis");
connection.close();
redisClient.shutdown();
}
@Test
public void ConnectToRedisSSL() {
// Syntax: rediss://[password@]host[:port][/databaseNumber]
// Adopt the port to the stunnel port in front of your Redis instance
RedisClient redisClient = RedisClient.create("rediss://password@localhost:6443/0");
StatefulRedisConnection<String, String> connection = redisClient.connect();
System.out.println("Connected to Redis using SSL");
connection.close();
redisClient.shutdown();
}
@Test
public void ConnectToRedisUsingRedisSentinel() {
// Syntax:
// redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#sentinelMasterId
RedisClient redisClient = RedisClient.create("redis-sentinel://localhost:26379,localhost:26380/0#mymaster");
StatefulRedisConnection<String, String> connection = redisClient.connect();
System.out.println("Connected to Redis using Redis Sentinel");
connection.close();
redisClient.shutdown();
}
@Test
public void ConnectToRedisCluster() {
// Syntax: redis://[password@]host[:port]
RedisClusterClient redisClient = RedisClusterClient.create("redis://password@localhost:7379");
StatefulRedisClusterConnection<String, String> connection = redisClient.connect();
System.out.println("Connected to Redis");
connection.close();
redisClient.shutdown();
}
}
| true |
7838c145a9d513b60b7adcd825af585d657daac2 | Java | laboratoriologin/cardapio | /CardapioADM/src/com/login/cardapio/model/Item.java | UTF-8 | 3,370 | 2.15625 | 2 | [] | no_license | package com.login.cardapio.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import br.com.topsys.database.hibernate.TSActiveRecordAb;
import br.com.topsys.util.TSUtil;
@SuppressWarnings("serial")
@Entity
@Table(name = "itens")
public class Item extends TSActiveRecordAb<Item> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "nome")
private String nome;
@Column (name = "descricao")
private String descricao;
@Column (name = "guarnicoes")
private String guarnicoes;
@Column (name = "ingredientes")
private String ingredientes;
@Column (name = "imagem")
private String imagem;
@Column (name = "tempo_medio_preparo")
private Long tempoMedioPreparo;
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@OneToMany(mappedBy = "item", cascade = CascadeType.ALL)
private List<SubItem> subItens;
@ManyToOne
@JoinColumn (name = "id_empresa_categoria_cardapio")
private EmpresaCategoriaCardapio empresaCategoriaCardapio;
public Long getId() {
return TSUtil.tratarLong(id);
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getGuarnicoes() {
return guarnicoes;
}
public void setGuarnicoes(String guarnicoes) {
this.guarnicoes = guarnicoes;
}
public String getIngredientes() {
return ingredientes;
}
public void setIngredientes(String ingredientes) {
this.ingredientes = ingredientes;
}
public String getImagem() {
return imagem;
}
public void setImagem(String imagem) {
this.imagem = imagem;
}
public EmpresaCategoriaCardapio getEmpresaCategoriaCardapio() {
return empresaCategoriaCardapio;
}
public void setEmpresaCategoriaCardapio(EmpresaCategoriaCardapio empresaCategoriaCardapio) {
this.empresaCategoriaCardapio = empresaCategoriaCardapio;
}
public List<SubItem> getSubItens() {
return subItens;
}
public void setSubItens(List<SubItem> subItens) {
this.subItens = subItens;
}
public Long getTempoMedioPreparo() {
return tempoMedioPreparo;
}
public void setTempoMedioPreparo(Long tempoMedioPreparo) {
this.tempoMedioPreparo = tempoMedioPreparo;
}
@Override
public List<Item> findByModel(String... fieldsOrderBy) {
return this.findByCategoria();
}
public List<Item> findByCategoria() {
String nomeFiltro = TSUtil.isEmpty(this.nome) ? null: "%" + this.nome.toLowerCase() + "%";
Long categoriaFiltro = TSUtil.isEmpty(this.empresaCategoriaCardapio) ? null : TSUtil.tratarLong(this.empresaCategoriaCardapio.getId());
return this.find("SELECT i FROM Item i, EmpresaCategoriaCardapio ECC where i.empresaCategoriaCardapio.id = ECC.id and lower(i.nome) like coalesce(?,lower(i.nome)) and ECC.id = coalesce(?,ECC.id)","i.nome", nomeFiltro,categoriaFiltro);
}
}
| true |
15a2cfefb8c1da8f8cfa80858d1e40b0ad991e14 | Java | krokyk/betting-helper | /src/org/kroky/betting/gui/custom/tables/ProvidersTableModel.java | UTF-8 | 3,746 | 2.640625 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.kroky.betting.gui.custom.tables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.apache.log4j.Logger;
import org.kroky.betting.db.DAO;
import org.kroky.betting.db.objects.Provider;
/**
*
* @author Kroky
*/
public class ProvidersTableModel extends AbstractTableModel {
private static final Logger LOG = Logger.getLogger(ProvidersTableModel.class);
private List<Provider> providers = new ArrayList<Provider>();
private static final String[] COLUMN_NAMES = new String[] {
"Country", "Sport", "League", "Season", "URL"
};
private static final Class<?>[] COLUMN_CLASSES = new Class<?>[] {
String.class, String.class, String.class, String.class, String.class
};
@Override
public Class<?> getColumnClass(int columnIndex) {
return COLUMN_CLASSES[columnIndex];
}
@Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
@Override
public int getRowCount() {
return providers.size();
}
@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Provider provider = providers.get(rowIndex);
switch(columnIndex) {
case 0: return provider.getCountry();
case 1: return provider.getSport();
case 2: return provider.getLeague();
case 3: return provider.getSeason();
case 4: return provider.getUrl();
default: throw new IndexOutOfBoundsException("Invalid column index: " + String.valueOf(columnIndex));
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex != 4;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Object oldValue = getValueAt(rowIndex, columnIndex);
if (oldValue != null && oldValue.equals(aValue)) {
return;
}
String newValue = (String) aValue;
Provider provider = providers.get(rowIndex);
switch(columnIndex) {
case 0:
provider.setCountry(newValue);
break;
case 1:
provider.setSport(newValue);
break;
case 2:
provider.setLeague(newValue);
break;
case 3:
provider.setSeason(newValue);
break;
default: throw new IndexOutOfBoundsException("Invalid column index: " + String.valueOf(columnIndex));
}
DAO.saveOrUpdateProvider(provider);
fireTableCellUpdated(rowIndex, columnIndex);
}
public void addProvider(Provider provider) {
providers.add(provider);
fireTableRowsInserted(providers.size() - 1, providers.size() - 1);
}
public Provider getProvider(int rowIndex) {
return providers.get(rowIndex);
}
public void clear() {
this.providers.clear();
fireTableDataChanged();
}
public void addAll(Collection<Provider> providers) {
this.providers.addAll(providers);
fireTableDataChanged();
}
public void replaceAll(Collection<Provider> providers) {
this.providers.clear();
addAll(providers);
}
public void remove(Provider provider) {
int index = providers.indexOf(provider);
if(providers.remove(provider)) {
fireTableRowsDeleted(index, index);
}
}
}
| true |
d7fe936064c0afa89bf75cb87cf25d3ebbf0640f | Java | DobyLov/opusbeaute_middleware | /src/main/java/fr/labonbonniere/opusbeaute/middleware/dao/AdresseClientDao.java | UTF-8 | 6,115 | 2.625 | 3 | [] | no_license | package fr.labonbonniere.opusbeaute.middleware.dao;
import java.util.List;
import java.util.Objects;
import javax.ejb.Stateless;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import fr.labonbonniere.opusbeaute.middleware.objetmetier.adresseclient.AdresseClient;
import fr.labonbonniere.opusbeaute.middleware.objetmetier.adresseclient.AdresseExistanteException;
import fr.labonbonniere.opusbeaute.middleware.objetmetier.adresseclient.AdresseInexistanteException;
/**
* Gere la persistance des AdresseClient
*
* @author fred
*
*/
@Stateless
@Transactional
public class AdresseClientDao {
static final Logger logger = LogManager.getLogger(AdresseClientDao.class);
@PersistenceContext(unitName = "opusBeautePU")
private EntityManager em;
/**
* Retourne la liste des Adresse Client
*
* @return La liste des adresses Client
* @throws DaoException Exception
*/
public List<AdresseClient> obtenirListeAdresse() throws DaoException {
try {
logger.info("AdresseDao log : Demande a la bdd la liste des Adresses");
String requete = "SELECT A FROM Adresse A" + " ORDER BY idAdresse asc";
;
TypedQuery<AdresseClient> query = em.createQuery(requete, AdresseClient.class);
List<AdresseClient> listeAdresses = query.getResultList();
logger.info("AdresseDao log : Envoi de la liste des Adresses");
return listeAdresses;
} catch (Exception message) {
logger.error("AdresseDAO Exception : Probleme de la bdd.");
throw new DaoException("AdresseDao Exception : Probleme de la bdd.");
}
}
/**
* Retourne l adresse d un Client via son Id
*
* @param idAdresse Integer
* @return AdresseClient
* @throws AdresseInexistanteException Exception
*/
public AdresseClient obtenirAdresse(final Integer idAdresse) throws AdresseInexistanteException {
logger.info("AdresseDao log : Demande a la bdd l adresse id : " + idAdresse);
AdresseClient adresse = null;
adresse = em.find(AdresseClient.class, idAdresse);
if (Objects.isNull(adresse)) {
logger.error("AdresseDao log : L adresse id : " + idAdresse + " demande est introuvable");
throw new AdresseInexistanteException(
"AdresseDao Exception : L' Id : " + idAdresse + " est introuvable dans la base");
}
logger.info("AdresseDao log : Adresse " + idAdresse + " trouve, envoie de l adresse a AdresseService");
return adresse;
}
/**
* Persiste une nouvelle Adresseclient
*
* @param adresse AdresseClient
* @throws AdresseExistanteException Exception
*/
public void ajouterUneAdresse(AdresseClient adresse) throws AdresseExistanteException {
try {
logger.info("AdresseDao log : Demande d ajout d une nouvelle Adresse dans la Bdd.");
em.persist(adresse);
em.flush();
logger.info("AdresseDao log : Nouvelle Adresse ajoutee, avec l id : " + adresse.getIdAdresse());
} catch (EntityExistsException message) {
logger.error("GenreDao log : Impossible d ajouter cette Adresse dans la Bdd.");
throw new AdresseExistanteException(
"AdresseDao Exception : Probleme, cette Adresse a l air d'être deja persistee");
}
}
/**
* Modifie l AdresseClient Persistee
*
* @param adresse AdresseClient
* @throws AdresseInexistanteException Exception
*/
public void modifieUneAdresse(AdresseClient adresse) throws AdresseInexistanteException {
logger.info(
"AdresseDao log : Demande de modification de l adresse id : " + adresse.getIdAdresse() + " a la Bdd.");
AdresseClient adresseBdd = em.find(AdresseClient.class, adresse.getIdAdresse());
if (Objects.nonNull(adresseBdd)) {
em.merge(adresse);
em.flush();
logger.info("AdresseDao log : Adresse id : " + adresse.getIdAdresse() + " a ete modifie dans la Bdd.");
} else {
logger.error(
"AdresseDao log : Adresse id : " + adresse.getIdAdresse() + " ne peut etre modifie dans la Bdd.");
throw new AdresseInexistanteException("AdresseDao log : Modification impossible,"
+ "il n'y a pas d adresse à modifier pour l'id : " + adresse.getIdAdresse() + " demande.");
}
}
/**
* Remise a Zero d une AdresseClient
*
* @param adresse AdresseClient
* @throws AdresseInexistanteException Exception
*/
public void reinitUneAdresse(AdresseClient adresse) throws AdresseInexistanteException {
logger.info("AdresseDao log : Demande de reinitialisation de l adresse id : " + adresse.getIdAdresse()
+ " a la Bdd.");
AdresseClient adresseBdd = em.find(AdresseClient.class, adresse.getIdAdresse());
if (Objects.nonNull(adresseBdd)) {
em.merge(adresse);
em.flush();
logger.info("AdresseDao log : Adresse id : " + adresse.getIdAdresse() + " a ete reinitialise dans la Bdd.");
} else {
logger.error("AdresseDao log : Adresse id : " + adresse.getIdAdresse()
+ " ne peut etre reinitialisee dans la Bdd.");
throw new AdresseInexistanteException("AdresseDao log : Reinitialisation impossible,"
+ "il n'y a pas d adresse à reinitialiser pour l'id : " + adresse.getIdAdresse() + " demande.");
}
}
/**
* Sumpression d une AdresseClient persistee
*
* @param idAdresse Integer
* @throws AdresseInexistanteException Exception
*/
public void supprimeUneAdresse(final Integer idAdresse) throws AdresseInexistanteException {
logger.info("AdresseDao log : Demande de suppression de l Adresse id : " + idAdresse + " dans la Bdd.");
AdresseClient adresse = null;
adresse = em.find(AdresseClient.class, idAdresse);
if (Objects.nonNull(adresse)) {
em.remove(adresse);
em.flush();
logger.info("AdresseDao log : Adresse id : " + idAdresse + " a bien ete supprime de la Bdd.");
} else {
logger.error("AdresseDao log : Adresse id : " + idAdresse
+ " inexistante alors elle ne peut etre supprimee de la Bdd.");
throw new AdresseInexistanteException(
"AdresseDao Exception : Adresse id : " + idAdresse + " ne peut etre supprimee de la Bdd.");
}
}
}
| true |
96ac91a690c5aa44a89e37e4c21cb6c303cab5b6 | Java | Neembuu/neembuunow | /vfs/test/neembuu/vfs/progresscontrol/GeneralThrottleTestMeasurement.java | UTF-8 | 6,341 | 2.109375 | 2 | [] | no_license | /*
* Copyright (C) 2014 Shashank Tulsyan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package neembuu.vfs.progresscontrol;
import info.monitorenter.gui.chart.TracePoint2D;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
/**
*
* @author Shashank Tulsyan
*/
public class GeneralThrottleTestMeasurement extends OutputStream{
private final ControlThrottle controlThrottle;
volatile double sleepPerByteDownloaded = 0;
volatile double requestSpeed_Bps = 30*1024;
volatile boolean throttleEnabled = true;
SpeedObv downloadSpeedObv = new SpeedObv();
long lstTime = System.currentTimeMillis();
float a = 0;
boolean dir = true; // under throttle
int dc = downloadSpeedObv.getL();
int buffSize = 0;
public GeneralThrottleTestMeasurement() throws Exception{
controlThrottle = new ControlThrottle(this);
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
controlThrottle.setVisible(true);
}
});
DefaultHttpClient myClient = new DefaultHttpClient();
myClient.execute(new HttpGet(
//"http://neembuu.com/test_videos/test120k.rmvb"
"http://localhost:8080/LocalFileServer-war/servlet/FileServer?"
+ "totalFileSpeedLimit=8000&"
// + "mode=constantAverageSpeed"
+ "mode=constantFlow"
+ "&newConnectionTimemillisec=1&file=wal.avi"
)
).getEntity().writeTo(this);
}
@Override
public void write(int b) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
write(b);
}
private boolean firstObv = false;
/*double ift = 0;
int ind = 0;*/
@Override
public void write(byte[] b) throws IOException {
if(!firstObv){
new Throwable().printStackTrace();
firstObv = true;
}
if(buffSize!=b.length){
buffSize = b.length;
//System.out.println("buffchanged to "+buffSize);
}
downloadSpeedObv.progressed(b.length);
//long i = System.currentTimeMillis();
controlThrottle.trace.addPoint(
new TracePoint2D(
System.currentTimeMillis(),
downloadSpeedObv.getSpeed_KiBps() ));
controlThrottle.smallDownloadSpeedLabel.setText(downloadSpeedObv.getSpeed_KiBps()+ "KiBps");
controlThrottle.averageSpeed.setText(downloadSpeedObv.getAverage_KiBps()+" KBps");
/*long f = System.currentTimeMillis();
ift*=ind;
ift+=(f-i);
ind++;
ift/=ind;
System.out.println("tog="+ift);*/
calculateSleepInterval();
try{
if(throttleEnabled){
if(sleepPerByteDownloaded>0){
double millis = sleepPerByteDownloaded*b.length*1000;
int nanos = ((int)(millis*1000000))%1000000;
//if(millis>2){
Thread.sleep(
(int)(millis),nanos);
//}
}
}
}catch(Exception a){
}
}
double calculateSleepInterval(){
/*System.out.println("obt="+(System.currentTimeMillis()-lstTime)
+" desired="+(sleepPerByteDownloaded*buffSize*1000)
);
System.out.println("sl="+sleepPerByteDownloaded+" bf="+buffSize+" r="+requestSpeed_Bps+" a="+a);
*/
lstTime = System.currentTimeMillis();
double r = requestSpeed_Bps;
double d = downloadSpeedObv.getSpeed_Bps();
if(!throttleEnabled){return 0;}
if(d<r){
if(a<0.99f){
if(dir==false){
if(dc>0)dc--;
else {
dir = true;
dc = /*dc_reset*/downloadSpeedObv.getL();
controlThrottle.directionLable.setText("under throttle");
}
}else dc = /*dc_reset*/downloadSpeedObv.getL();
if(dir==true){
a+=0.00004f*r*r/(d*d);
if(a>0.99f)a=0.99f;
if(controlThrottle!=null)
controlThrottle.a_value.setText(""+(a*100));
}
}
}else if(d>r){
if(a>0.0f){
if(dir==true){
if(dc>0)dc--;
else {
dir = false;
dc = /*dc_reset*/downloadSpeedObv.getL();
controlThrottle.directionLable.setText("over throttle");
}
}else dc = /*dc_reset*/downloadSpeedObv.getL();
if(dir==false){
a-=0.00004f*d*d/(r*r);
if(a<0.0f)a=0.0f;
controlThrottle.a_value.setText(""+(a*100));
}
}else a=0f;
}
sleepPerByteDownloaded = (1/r)*(1-a);
//if(sleepPerByteDownloaded<0.1){return sleepPerByteDownloaded=0;}
return sleepPerByteDownloaded;
}
public static void main(String[] args) throws Exception{
new GeneralThrottleTestMeasurement();
}
}
| true |
8a109a9bb190759c8f7debf4225a3808309c2c74 | Java | manishselenium/VatsanaAutomationProjects | /Thepopple/src/test/java/PoppleTestCases/UserProfileTestCasesTest.java | UTF-8 | 3,083 | 1.898438 | 2 | [] | no_license | package PoppleTestCases;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import PopplePages.UserProfilePage;
import PoppleUtils.ReadPropertiesFilesPopple;
public class UserProfileTestCasesTest extends ReportGenerateThePoopleTest {
static Properties properties = null;
// WebDriver driver = new ChromeDriver();
// String st = System.setProperty("webdriver.chrome.driver", "chromedriver");
UserProfilePage obj = new UserProfilePage();
// @BeforeTest
// public void OpenBrowser() throws IOException {
//
// ReadPropertiesFilesPopple readConfigFile = new ReadPropertiesFilesPopple();
//
// properties = readConfigFile.LoadPropertiess();
// driver.get(properties.getProperty("URL"));
// driver.manage().window().maximize();
//
// }
@Test(priority = 123)
public void ClickAuthorName() throws IOException {
ReadPropertiesFilesPopple readConfigFile = new ReadPropertiesFilesPopple();
properties = readConfigFile.LoadPropertiess();
driver.get(properties.getProperty("URL"));
driver.manage().window().maximize();
test = extent.createTest("Test 123 - Click Author Name");
obj.ClickAuthorName(driver);
}
@Test(priority = 124)
public void CheckBackgroundImage() {
test = extent.createTest("Test 124 - Check Background Image");
obj.BackgroundImage(driver);
}
@Test(priority = 125)
public void CheckAuthorName() {
test = extent.createTest("Test 125 - Check Author Name");
obj.AuthorName(driver);
}
@Test(priority = 126)
public void CheckAuthorImage() {
test = extent.createTest("Test 126 - Check Author Image");
obj.AuthorImage(driver);
}
@Test(priority = 127)
public void CheckWriterName() {
test = extent.createTest("Test 127 - Check Writer Name");
obj.WriterName(driver);
}
@Test(priority = 128)
public void CheckEditor() {
test = extent.createTest("Test 128 - Check Editor");
obj.Editor(driver);
}
// @Test(priority = 7)
// public void CheckFacebookLink() {
// test = extent.createTest("Test 1 - Check Facebook Link");
//
//
// obj.FacebookLink(driver);
//
// }
//
// @Test(priority = 8)
// public void CheckTwitterLink() {
// test = extent.createTest("Test 1 - Check Twitter Link");
// obj.TwitterLink(driver);
//
// }
//
// @Test(priority = 9)
// public void CheckLinkedinLink() {
// test = extent.createTest("Test 1 - Check Linkedin Link");
// obj.LinkedinLink(driver);
//
// }
// @Test(priority = 129)
// public void CheckProfileDesc() {
// test = extent.createTest("Test 129 - Check Profile Desc");
// obj.ProfileDesc(driver);
// }
//
// @Test(priority = 130)
// public void CheckDontMissThisStory() {
//
// test = extent.createTest("Test 130 - Check Dont Miss This Story");
// obj.DontMissThisStory(driver);
//
// }
//
// @Test(priority = 131)
// public void LatestStories() {
//
// test = extent.createTest("Test 131 - Latest Stories");
// obj.LatestStories(driver);
//
// }
}
| true |
92afd38224f22909b4e01fcde5255241e2674c8d | Java | TelegaOvoshey/JavaCourse | /src/Strings.java | UTF-8 | 11,949 | 4.03125 | 4 | [] | no_license | import java.io.*;
import java.util.*;
public class Strings {
public static void main(String[] args) {
System.out.printf("\nЗадание 1\n");
// Выведите на экран все возможные символы с ASCII-кодами от 32 до 255 и их ASCII-коды (символы с кодами до 32 являются служебными и их вывод на экран может привести к забавным последствиям). Формат вывода: сначала ASCII-код, затем символ
for (char i = 32; i < 255; i++)
System.out.print((int)i + " " + i + " \n");
System.out.printf("\nЗадание 2\n");
// Напишите функцию bool IsDigit(unsigned char c), определяющую, является ли данный символ цифрой или нет. Напишите программу, которая получает на вход один символ и выводит строку yes, если символ является цифрой и строку no, в противном случае.
Scanner in = new Scanner(System.in);
System.out.printf("Введите данные\n");
if (IsDigit(in.next().charAt(0)))
System.out.print("YES");
else
System.out.print("NO");
System.out.printf("\nЗадание 3\n");
// Перевод в верхний регистр. Программа получает на вход один символ. Если этот символ является строчной буквой латинского алфавита (то есть буквой от a до z), выведите вместо него аналогичную заглавную букву, иначе выведите тот же самый символ. Для этого сделайте функцию char toUpper(char c), которая переводит данный символ в верхний регистр.
System.out.print(toUpper(in.next().charAt(0)));
System.out.printf("\nЗадание 4\n");
// Измените регистр символа: если он был латинской буквой: сделайте его заглавным, если он был строчной буквой и наоборот. Для этого напишите отдельную функцию, меняющую регистр символа.
System.out.print(SwitchCase(in.next().charAt(0)));
System.out.printf("\nЗадание 5\n");
// Даны две строки. Определите, совпадают ли они, сравнив их посимвольно. Напишите для этого функцию boolean compare(String S1, String S2).
// Вход: две строки. Выход: слово yes, если строки совпадают, слово no в противном случае.
String S1,S2;
S1 = in.nextLine();
S2 = in.nextLine();
if (compare(S1, S2))
System.out.print("YES");
else
System.out.print("NO");
System.out.printf("\nЗадание 6\n");
// Дана строка, содержащая пробелы. Найдите, сколько в ней слов (слово – это последовательность непробельных символов, слова разделены одним пробелом, первый и последний символ строки – не пробел).
// Дана строка, содержащая пробелы. Найдите, сколько в ней слов (слово – это последовательность непробельных символов, слова разделены одним пробелом, первый и последний символ строки – не пробел).
// Вход: На вход подается несколько строк. Входная строка должна считываться методом getline (В случае использования Scanner).
// Выход: количество слов в первой из введенных строк.
S1=in.nextLine();
String[] StringArray = S1.split(" ");
System.out.print(StringArray.length);
System.out.printf("\nЗадание 7\n");
// Дана строка, содержащая пробелы. Найдите в ней самое длинное слово, выведите на экран это слово и его длину.
// Вход: одна строка, содержащая пробелы. Слова разделены ровно одним пробелом. Строка должна считываться методом getline (программа должна считывать только одну первую строку). Выход: самое длинное слово в строке и его длина.
int length = 0;
String nextWord, maxWord = "";
StringTokenizer st = new StringTokenizer(in.nextLine());
while (st.hasMoreTokens())
{
nextWord = st.nextToken();
if (nextWord.length() > length) {
length = nextWord.length();
maxWord=nextWord;
}
}
System.out.println(maxWord + length);
System.out.printf("\nЗадание 8\n");
// По данной строке, определите, является ли она палиндромом (то есть можно ли прочесть ее наоборот, как, например,
// слово `топот').
// Вход: одна строка без пробелов. Выход: yes, если слово является палиндромом, no в противном случае.
S1="топот";
boolean b=false;
for (int i=0; i < (S1.length()/2); i++)
{
if (S1.charAt(i)==S1.charAt(S1.length()-i-1))
b=true;
else
b=false;
}
if (b)
System.out.print("Палиндром");
else
System.out.print("Не палиндром");
System.out.printf("\nЗадание 9\n");
// Дана строка. Известно, что она содержит ровно две одинаковые буквы. Найдите эти буквы. Вход: одна строка.
String s = "помогите";
char[] chars = s.toCharArray();
Arrays.sort(chars);
for (int i=1; i < chars.length; i++)
if (chars[i-1]==chars[i])
System.out.print(chars[i]);
System.out.printf("\nЗадание 10\n");
// Даны две строки. Определите, является ли первая строка подстрокой второй строки. Вход: две строки. Выход: слово yes, если первая строка является подстрокой второй строки, или слово no в противном случае.
String source = "aabaaaaa", template = "abaa";
int sourceLen = source.length();
int templateLen = template.length();
if (templateLen > sourceLen) {
System.out.print("No");
}
HashMap<Character, Integer> HM = new HashMap<Character, Integer>();
for (int i = 0; i < 256; i++) {
HM.put((char) i, templateLen);
}
for (int i = 0; i < templateLen - 1; i++) {
HM.put(template.charAt(i), templateLen - i - 1);
}
int h = templateLen - 1;
int j = h;
int k = h;
while (j >= 0 && h < sourceLen) {
j = templateLen - 1;
k = h;
while (j >= 0 && source.charAt(k) == template.charAt(j)) {
k--;
j--;
}
h += HM.get(source.charAt(h));
}
if (k >= sourceLen - templateLen) {
System.out.print("No");
} else {
System.out.print("Yes");
}
System.out.printf("\nЗадание 11\n");
// Капитан Флинт зарыл клад на Острове сокровищ. Он оставил описание, как найти клад. Описание состоит из строк вида: "North 5", где первое слово – одно из "North", "South", "East", "West", а второе число – количество шагов, необходимое пройти в этом направлении.
// Напишите программу, которая по описанию пути к кладу определяет точные координаты клада, считая, что начало координат находится в начале пути, ось OX направлена на восток, ось OY – на север.
// Вход: последовательность строк указанного формата. Выход: координаты клада – два целых числа через пробел.
// Например, при вводе
// North 5
// East 3
// South 1
// программа должна вывести координаты 3 4.
List<String> StringList = new ArrayList<String>();
int NS=0, WE=0;
String der;
try{
Scanner sc = new Scanner(new File("Silver.txt"));
while(sc.hasNextLine())
StringList.add(sc.nextLine());
sc.close();
} catch(FileNotFoundException e){e.printStackTrace();}
for (String str : StringList) {
StringTokenizer strt = new StringTokenizer(str);
der = strt.nextToken();
if (der.equals("North"))
NS += Integer.parseInt(strt.nextToken());
else if (der.equals("South"))
NS -= Integer.parseInt(strt.nextToken());
else if (der.equals("East"))
WE += Integer.parseInt(strt.nextToken());
else WE -= Integer.parseInt(strt.nextToken());
}
System.out.print(NS + " " + WE);
System.out.printf("\nЗадание 12\n");
StringBuilder SB = new StringBuilder();
// Дана строка, содержащая пробелы. Проверьте, является ли она палиндромом без учета пробелов (например, ‘аргентина манит негра’).
// Вход: одна строка, содержащая пробелы. Подряд может идти произвольное число пробелов.
// Выход: yes, если данная строка является палиндромом и no в противном случае.
S1="аргентина манит негра ";
SB.insert(0,S1.replaceAll("\\s", ""));
b=false;
for (int i=0; i < (SB.length()/2); i++)
{
if (SB.charAt(i)==SB.charAt(SB.length()-i-1))
b=true;
else
b=false;
}
if (b)
System.out.print("Палиндром");
else
System.out.print("Не палиндром");
}
static boolean IsDigit(char c) {
return (c > 47 && c<58);
}
static char toUpper(char c) {
if (c > 97 && c < 123)
c-=32;
return c;
}
static char SwitchCase(char c) {
if (c > 97 && c < 123)
c-=32;
if (c > 64 && c < 91)
c+=32;
return c;
}
static boolean compare(String S1, String S2) {
return (S1.hashCode()==S2.hashCode());
}
}
| true |
737b82cd39bfa3b86cf0fd5045461d73432a0bef | Java | niarroyo/AddMovieTDD | /NewMovieTDD/src/test/java/com/sans/movieTDD/utilities/webactionutils/WaitUtil.java | UTF-8 | 410 | 2.296875 | 2 | [] | no_license | package com.sans.movieTDD.utilities.webactionutils;
import org.openqa.selenium.WebDriver;
public class WaitUtil {
private WebDriver driver;
public WaitUtil(WebDriver incomingDriver) {
this.driver = incomingDriver;
}
public void pause(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true |
88939f2e012572a2d2eb093b5a101f9f1c52b4ad | Java | ruibiaozhong/mybatis-generator | /src/main/java/com/leihou/so/service/impl/UserServiceImpl.java | UTF-8 | 525 | 1.625 | 2 | [] | no_license | package com.leihou.so.service.impl;
import com.leihou.so.mapper.UserMapper;
import com.leihou.so.entity.User;
import com.leihou.so.service.UserService;
import com.leihou.so.base.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* Created by ruibiaozhong on 2018/10/26.
*/
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
}
| true |
b3dfe3be73b4534b318d61d6e00226bd4bc784fd | Java | MouseWeb/Java-Fundamentos | /src/operadoresRelecionaisLogicos/OperadoresRelecionaisLogicos.java | ISO-8859-1 | 1,518 | 3.5625 | 4 | [] | no_license | package operadoresRelecionaisLogicos;
public class OperadoresRelecionaisLogicos {
// OPERADORES -> = (ATRIBUIO)
// OPERADORES -> == (IGUAL)
// OPERADORES -> != (DIFERENTE)
// OPERADORES -> > (MAIOR)
// OPERADORES -> < (MENOR)
// OPERADORES -> >= (MAIOR OU IGUAL)
// OPERADORES -> <= (MENOR OU IGUAL)
// OPERADORES LGICOS -> && (E)
// OPERADORES LGICOS -> || (OU)
public static void main(String[] args) {
boolean d1 = 2 > 3 || 4 != 5; // true
boolean d2 = !(2>3) && 4 != 5; // true
System.out.println(d1);
System.out.println(d2);
System.out.println("--------------");
boolean d3 = 10 < 5; // false
boolean d4 = d1 || d2 && d3; // true
System.out.println(d4);
System.out.println("--------------");
////////////////////////////////////////////
boolean resultado;
int numero1;
int numero2;
numero1 = 5;
numero2 = 5;
resultado = numero1 == numero2;
System.out.println(resultado);
System.out.println("--------------");
///////////////////////////////////////////
int a = 10;
boolean c1 = a < 10;
boolean c2 = a < 20;
boolean c3 = a > 10;
boolean c4 = a > 5;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println("------------");
boolean c5 = a <= 10;
boolean c6 = a >= 10;
boolean c7 = a == 10;
boolean c8 = a != 10;
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
}
}
| true |
ac3bfd899bd2c00109e8bc5cdf71346a90b4ae50 | Java | Justin-Hinds/Portfolio | /Sticks/app/src/main/java/com/arcane/sticks/Frags/PlayersFrag.java | UTF-8 | 3,954 | 2.328125 | 2 | [] | no_license | package com.arcane.sticks.frags;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.arcane.sticks.models.Player;
import com.arcane.sticks.adapters.PlayersRecyclerAdapter;
import com.arcane.sticks.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class PlayersFrag extends Fragment {
private PlayersRecyclerAdapter mAdapter;
private ArrayList myDataset = new ArrayList();
private final FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("Users");
public static PlayersFrag newInstance(){return new PlayersFrag();}
private PlayersRecyclerAdapter.OnPlayerSelectedListener mListener;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.players_frag_layout,container,false);
myDataset = new ArrayList();
RecyclerView mRecyclerView = (RecyclerView) root.findViewById(R.id.rec_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new PlayersRecyclerAdapter(myDataset,getContext());
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnPlayerInteraction(mListener);
myRef.addValueEventListener(valueEventListener);
return root;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
getListenerFromContext(context);
}
private void getListenerFromContext(Context context) {
if (context instanceof PlayersRecyclerAdapter.OnPlayerSelectedListener) {
mListener = (PlayersRecyclerAdapter.OnPlayerSelectedListener) context;
} else {
throw new ClassCastException("Containing activity must " +
"implement OnPersonInteractionListener");
}
}
private final ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
myDataset.clear();
//Log.i("USERS: ", dataSnapshot.getValue().toString());
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
//Log.d("USERS ", "Name is: " + childSnapshot.getValue(Player.class).getName());
Player player = childSnapshot.getValue(Player.class);
// Log.d(TAG, "Time is: " + post.time);
//noinspection unchecked
if(!player.getId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){
myDataset.add(player);
}
}
//noinspection unchecked
mAdapter.update(myDataset);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
@Override
public void onDestroy() {
super.onDestroy();
myRef.removeEventListener(valueEventListener);
}
}
| true |