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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ad5c79300aad803ad60be6da31ebb43db3bb412c | Java | JakubGajewski/JavaTester | /src/main/java/pl/javatester/JavaTester/models/QuestionModel.java | UTF-8 | 525 | 1.921875 | 2 | [] | no_license | package pl.javatester.JavaTester.models;
import lombok.Data;
import lombok.NoArgsConstructor;
import pl.javatester.JavaTester.models.forms.AnswerForm;
import javax.persistence.*;
@Entity
@Table(name = "javatestquestion")
@Data
@NoArgsConstructor
public class QuestionModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String content;
private String answer1;
private String answer2;
private String answer3;
private String answer4;
private int correct;
} | true |
c9753f592110784cc45707044d6299964108ec82 | Java | zhangzhiwang/GuPaoEdu | /src/main/java/com/asiainfo/p6_2020/designPatterns/chainOfResponsibility/ValidHandler.java | UTF-8 | 416 | 2.625 | 3 | [] | no_license | package com.asiainfo.p6_2020.designPatterns.chainOfResponsibility;
import org.jsoup.helper.StringUtil;
public class ValidHandler extends Handler {
@Override
protected boolean handle(User user) {
if (StringUtil.isBlank(user.getName()) || StringUtil.isBlank(user.getPassword())) {
System.out.println("validate:用户名或密码为空!");
return false;
}
return this.nextHandler.handle(user);
}
}
| true |
7f5c3cdbb62ba1fd0079233c2886e5ccbfdd0cba | Java | yang755994/wemirr-platform | /wemirr-platform-authority/src/main/java/com/wemirr/platform/authority/domain/vo/VueRouter.java | UTF-8 | 1,138 | 1.679688 | 2 | [
"Apache-2.0"
] | permissive | package com.wemirr.platform.authority.domain.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 构建 Vue路由
*
* @author Levin
* @since 2019-10-20 15:17
*/
@Data
public class VueRouter {
private static final long serialVersionUID = -3327478146308500708L;
private Long id;
private Long parentId;
@Schema(description = "路径")
private String path;
@Schema(description = "按钮名称")
private String name;
@Schema(description = "菜单名称")
private String label;
@Schema(description = "图标")
private String icon;
@Schema(description = "组件")
private String component;
@Schema(description = "重定向")
private String redirect;
@Schema(description = "元数据")
private RouterMeta meta;
private String model;
private String permission;
/**
* 排序
*/
@Schema(description = "排序")
private Integer sequence;
@Schema(description = "类型(1=菜单;2=按钮;3=路由;5=一键发布模板)")
private Integer type;
private Boolean global;
private Boolean status;
}
| true |
21cad586ea610f392019f6c3c70660c11e252e3a | Java | RabbitTea/JavaWeb-project | /基于Java和MySQL的旅游预订系统/TravelBooking/src/com/ustc/bean/MainApplication.java | UTF-8 | 501 | 2.21875 | 2 | [] | no_license | package com.ustc.bean;
import java.util.ArrayList;
import com.ustc.dao.jdbcHelper;
public class MainApplication {
public static void main(String[] args) {
jdbcHelper helper = new jdbcHelper();
ArrayList<CustomersBean> custs = helper.searchCustomer();
//helper.cusRegister(cust);
//helper.searchFlight();
for(int i=0;i<custs.size();i++) {
System.out.println("name="+custs.get(i).getCustName());
System.out.println("pass="+custs.get(i).getPassWord());
}
}
}
| true |
bc7f2cb905ad8ec46032de37f80c81991bc770e5 | Java | HuLi00/SpringBoot-Blog | /blog-api/src/main/java/com/blog/handler/LoginInterceptor.java | UTF-8 | 2,991 | 2.46875 | 2 | [] | no_license | package com.blog.handler;
import com.alibaba.fastjson.JSON;
import com.blog.controller.vo.ErrorCode;
import com.blog.controller.vo.Result;
import com.blog.dao.pojo.SysUser;
import com.blog.service.LoginService;
import com.blog.utils.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author: hu
* @create: 2021-08-18 21:17
* 对需要登录才能访问的接口进行验证拦截
*/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private LoginService loginService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//在Controller方法之前执行
/*
* 1、需要判断请求接口路径是否为HandlerMethod(controller方法)
* 2、判断token是否为空, 如果为空则判定未登录
* 3、如果token不为空,登录验证 loginService checkToken
* 4、如果认证成功 放行
* */
if(!(handler instanceof HandlerMethod)){
//handler 可能是 RequestResourceHandler springboot程序访问静态资源,默认到classpath下的static目录去查询
return true;
}
String token = request.getHeader("Authorization");
log.info("============ request start ===============");
String requestURI = request.getRequestURI();
log.info("request uri:{}",requestURI);
log.info("request method:{}", request.getMethod());
log.info("token:{}", token);
log.info("============= request end ============");
if(StringUtils.isBlank(token)){
Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSONString(result));
return false;
}
SysUser sysUser = loginService.checkToken(token);
if(sysUser == null){
Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSONString(result));
return false;
}
//使用ThreadLocal来保存用户的信息,在其他地方都可以使用
UserThreadLocalUtils.put(sysUser);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//ThreadLocal保存的用户信息在这里要进行销毁,不然会造成内存泄漏的问题(不会再继续使用了,但是JVM无法清理)
UserThreadLocalUtils.remove();
}
}
| true |
4e18b5fdf00466f0c058cb64337b0ec2daf677fb | Java | kholodovitch/adfox_sdk_java | /src/main/java/com/github/kholodovitch/adfox/ActionAccountAdd.java | UTF-8 | 2,341 | 2.359375 | 2 | [] | no_license | package com.github.kholodovitch.adfox;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import com.github.kholodovitch.adfox.exceptions.AdFoxException;
import com.github.kholodovitch.adfox.interfaces.IActionAccountAdd;
import com.github.kholodovitch.adfox.objects.Advertiser;
import com.github.kholodovitch.adfox.objects.Banner;
import com.github.kholodovitch.adfox.objects.Campaign;
import com.github.kholodovitch.adfox.objects.ContentType;
public class ActionAccountAdd implements IActionAccountAdd {
private ApiClient apiClient;
public ActionAccountAdd(ApiClient apiClient) {
this.apiClient = apiClient;
}
public int advertiser(Advertiser advertiser, String passSha256) throws AdFoxException {
if (advertiser == null)
throw new AdFoxException("advertiser is undefined");
if (StringUtils.isBlank(passSha256))
throw new AdFoxException("password is blank");
String account = advertiser.getAccount();
if (StringUtils.isBlank(account))
throw new AdFoxException("advertiser.account is blank");
String eMail = advertiser.getEMail();
if (StringUtils.isBlank(eMail))
throw new AdFoxException("advertiser.email is blank");
return apiClient.addItem("account", "advertiser", "password=" + passSha256, "account=" + account, "eMail=" + eMail, "company=" + advertiser.getCompany() != null ? advertiser.getCompany() : "");
}
public int campaign(Campaign campaign, boolean isFlayt) throws AdFoxException {
ArrayList<String> params = new ArrayList<String>();
params.add("name=" + campaign.getName());
if (!isFlayt)
params.add("advertiserID=" + campaign.getAdvertiserID());
return apiClient.addItem("account", "campaign", params.toArray(new String[0]));
}
public int banner(Banner banner, ContentType contentType) throws AdFoxException {
ArrayList<String> params = new ArrayList<String>();
params.add("campaignID=" + banner.getCampaignID());
if (StringUtils.isEmpty(banner.getTemplateID())) {
params.add("bannerTypeID=" + banner.getBannerTypeID());
params.add("contentType=" + contentType.toString());
params.add("imageURL=" + banner.getImageURL());
params.add("hitURL=" + banner.getHitURL());
} else {
params.add("templateID=" + banner.getTemplateID());
}
return apiClient.addItem("account", "banner", params.toArray(new String[0]));
}
}
| true |
96d13521878dd1bedd3a1a2ae66ccf9d97cfaceb | Java | bellmit/paiche | /guns-vip-master/guns-vip-main/src/main/java/cn/stylefeng/guns/pojo/CoursePackage.java | UTF-8 | 1,548 | 2.125 | 2 | [] | no_license | package cn.stylefeng.guns.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author
* @since 2020-03-05
*/
@TableName("tb_course_package")
public class CoursePackage implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 课包名称
*/
@TableField("t_name")
private String tName;
@TableField("row_guid")
private Integer rowGuid;
@TableField("group_guid")
private Integer groupGuid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String gettName() {
return tName;
}
public void settName(String tName) {
this.tName = tName;
}
public Integer getRowGuid() {
return rowGuid;
}
public void setRowGuid(Integer rowGuid) {
this.rowGuid = rowGuid;
}
public Integer getGroupGuid() {
return groupGuid;
}
public void setGroupGuid(Integer groupGuid) {
this.groupGuid = groupGuid;
}
@Override
public String toString() {
return "CoursePackage{" +
"id=" + id +
", tName=" + tName +
", rowGuid=" + rowGuid +
", groupGuid=" + groupGuid +
"}";
}
}
| true |
9bf0a94378df11ca87e38b3efc9a2063b29086b4 | Java | pf666nb/sell | /src/main/java/com/imooc/repository/ProductInfoRepository.java | UTF-8 | 457 | 1.835938 | 2 | [] | no_license | package com.imooc.repository;
import com.imooc.dataobject.ProductInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author wpf
* @version 1.0
* @date 2020/4/4 12:48
*/
public interface ProductInfoRepository extends JpaRepository<ProductInfo,String> {
List<ProductInfo> findByProductStatus(Integer productStatus);
List<ProductInfo> findByCategoryType(Integer categoryType);
}
| true |
3ff5e4f9a94cffb90ae8fdf4b6af4a90b1bb787b | Java | qpy1992/Christie | /app/src/main/java/com/example/administrator/christie/activity/ShenqingActivity.java | UTF-8 | 6,285 | 2.1875 | 2 | [] | no_license | package com.example.administrator.christie.activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.christie.R;
import com.example.administrator.christie.TApplication;
import com.example.administrator.christie.util.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ShenqingActivity extends BaseActivity {
private TextView tv_shenqing,tv_remind;
private Button btn_now,btn_no;
private String code;
public static final int SHOW_RESPONSE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shenqing);
setViews();
setListeners();
}
protected void setViews(){
Intent intent =getIntent();
code = intent.getStringExtra("code");
Log.i("当前的权限代码",code+"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
tv_shenqing = (TextView)findViewById(R.id.tv_shenqing);
tv_shenqing.setText(intent.getStringExtra("title"));
tv_remind = (TextView)findViewById(R.id.tv_remind);
btn_now = (Button)findViewById(R.id.btn_now);
btn_no = (Button)findViewById(R.id.btn_no);
if(TApplication.user.getApplylist().contains(code)){
tv_remind.setText(getString(R.string.remind));
btn_now.setVisibility(View.INVISIBLE);
btn_no.setText(getString(R.string.no1));
}
}
protected void setListeners(){
btn_now.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
JSONObject json = new JSONObject();
json.put("id", TApplication.user.getId());
json.put("function_code",code);
PostThread thread = new PostThread(json);
thread.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
btn_no.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
if(response.equals("1")){
Toast.makeText(ShenqingActivity.this,"提交成功",Toast.LENGTH_SHORT).show();
TApplication.user.getApplylist().add(code);
tv_remind.setText(getString(R.string.remind));
btn_now.setVisibility(View.INVISIBLE);
btn_no.setText(getString(R.string.no1));
}else{
Toast.makeText(ShenqingActivity.this,"提交失败,请重新尝试!",Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
};
//子线程:使用POST方法向服务器发送数据
class PostThread extends Thread {
JSONObject json;
public PostThread(JSONObject json) {
this.json = json;
}
@Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
String url = Consts.URL+"apply";
//第二步:生成使用POST方法的请求对象
HttpPost httpPost = new HttpPost(url);
//NameValuePair对象代表了一个需要发往服务器的键值对
NameValuePair pair1 = new BasicNameValuePair("application", json.toString());
//将准备好的键值对对象放置在一个List当中
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(pair1);
try {
//创建代表请求体的对象(注意,是请求体)
HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);
//将请求体放置在请求对象当中
httpPost.setEntity(requestEntity);
//执行请求对象
try {
//第三步:执行请求对象,获取服务器发还的相应对象
HttpResponse response = httpClient.execute(httpPost);
//第四步:检查相应的状态是否正常:检查状态码的值是200表示正常
if (response.getStatusLine().getStatusCode() == 200) {
//第五步:从相应对象当中取出数据,放到entity当中
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String result = reader.readLine();
Log.d("HTTP", "POST:" + result);
//在子线程中将Message对象发出去
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = result;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true |
f0e6569188655ebafe67e372a0f68c096eefae6b | Java | rutgerkok/WorldGeneratorApi | /worldgeneratorapi-impl/src/main/java/nl/rutgerkok/worldgeneratorapi/internal/PropertyRegistryImpl.java | UTF-8 | 6,014 | 2.46875 | 2 | [
"MIT"
] | permissive | package nl.rutgerkok.worldgeneratorapi.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_19_R1.block.CraftBlock;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import nl.rutgerkok.worldgeneratorapi.WorldGeneratorApi;
import nl.rutgerkok.worldgeneratorapi.WorldRef;
import nl.rutgerkok.worldgeneratorapi.property.AbstractProperty;
import nl.rutgerkok.worldgeneratorapi.property.FloatProperty;
import nl.rutgerkok.worldgeneratorapi.property.Property;
import nl.rutgerkok.worldgeneratorapi.property.PropertyRegistry;
/**
* Default implementation of {@link PropertyRegistry}. Use
* {@link WorldGeneratorApi#getPropertyRegistry()} to get an instance.
*
*/
public final class PropertyRegistryImpl implements PropertyRegistry {
/**
* Be careful with thread safety. For example, this is wrong:
*
* <pre>
* if (map.containsKey("example")) {
* map.get("example").doSomething();
* }
* </pre>
*
* After all, another thread could delete the value in between the first and
* second line, making your code throw an exception. Instead, use this:
*
* <pre>
* var value = map.get("example");
* if (value != null) {
* value.doSomething();
* }
* </pre>
*
* See for example the {@link Map#computeIfAbsent(Object, Function)} function
* for safely putting a value if (and only if) there is no value yet.
*/
private final Map<NamespacedKey, AbstractProperty> properties = new ConcurrentHashMap<>();
public PropertyRegistryImpl() {
addMinecraftBiomeFloatProperty(TEMPERATURE, Biome::getBaseTemperature);
addMinecraftBiomeFloatProperty(WETNESS, Biome::getDownfall);
addMinecraftWorldProperty(WORLD_SEED, world -> (Long) world.getSeed(), -1L);
addSeaLevelProperty(SEA_LEVEL, world -> (float) world.getSeaLevel());
}
private void addMinecraftBiomeFloatProperty(NamespacedKey name, Function<Biome, Float> value) {
FloatProperty property = new FloatProperty(name,
value.apply(BuiltinRegistries.BIOME.get(Biomes.PLAINS))) {
@Override
public float getBiomeDefault(org.bukkit.block.Biome biome) {
if (biome == org.bukkit.block.Biome.CUSTOM) {
return 0;
}
Biome base = CraftBlock.biomeToBiomeBase(BuiltinRegistries.BIOME, biome).value();
return value.apply(base);
}
@Override
public void setBiomeDefault(org.bukkit.block.Biome biome, float value) {
throw new UnsupportedOperationException(
"Cannot change " + getKey().getKey() + " globally for biomes. Try"
+ " setting it per-world instead.");
}
};
this.properties.put(name, property);
}
private <T> void addMinecraftWorldProperty(NamespacedKey name, Function<World, T> value, T defaultValue) {
Property<T> property = new Property<>(name, defaultValue) {
@Override
public @Nullable T getWorldDefault(WorldRef worldRef) {
World world = Bukkit.getWorld(worldRef.getName());
if (world == null) {
return null;
}
return value.apply(world);
}
@Override
public void setWorldDefault(WorldRef world, T value) {
throw new UnsupportedOperationException(
"Cannot change " + getKey().getKey() + " for worlds.");
}
};
this.properties.put(name, property);
}
private void addSeaLevelProperty(NamespacedKey name, Function<World, Float> value) {
FloatProperty property = new FloatProperty(name, 0f) {
@Override
public float getWorldDefault(WorldRef worldRef) {
World world = Bukkit.getWorld(worldRef.getName());
if (world == null) {
return Float.NaN;
}
return value.apply(world);
}
@Override
public void setWorldDefault(WorldRef worldRef, float value) {
throw new UnsupportedOperationException("Setting the sea level is not possible"
+ " in Minecraft >= 1.14 - world.getSeaLevel() is hardcoded to return 63.");
}
};
this.properties.put(name, property);
}
@Override
public Collection<? extends AbstractProperty> getAllProperties() {
return Collections.unmodifiableCollection(this.properties.values());
}
@Override
public FloatProperty getFloat(NamespacedKey name, float defaultValue) {
return (FloatProperty) properties.computeIfAbsent(name, n -> new FloatProperty(name, defaultValue));
}
@Override
public <T> Property<T> getProperty(NamespacedKey name, T defaultValue) {
@SuppressWarnings("unchecked") // Will be checked on lines following
Property<T> property = (Property<T>) properties.computeIfAbsent(name, n -> new Property<>(name, defaultValue));
if (!property.getDefault().getClass().equals(defaultValue.getClass())) {
throw new ClassCastException("Cannot cast Property<" + property.getDefault().getClass().getSimpleName()
+ "> to Property<" + defaultValue.getClass().getSimpleName() + ">");
}
return property;
}
@Override
public Optional<AbstractProperty> getRegisteredProperty(NamespacedKey key) {
return Optional.ofNullable(properties.get(key));
}
}
| true |
9235f25a879499c19d80732349e1d3872306331f | Java | CoderHahs/ICS-2-3-4-U | /ICS2U/Unit 1/madlibs/MadLibs.java | UTF-8 | 1,092 | 3.375 | 3 | [] | no_license | public class MadLibs
{
public static void main (String args [])
{
new MadLibs ();
}
public MadLibs ()
{
String name = IBIO.inputString ("Enter a made-up name: ");
String name2 = IBIO.inputString ("Enter a another made-up name: ");
String col = IBIO.inputString ("Enter a colour: ");
String col2 = IBIO.inputString ("Enter another colour: ");
String num = IBIO.inputString("Enter a number for diameter: ");
String num2 = IBIO.inputString("Enter another number for weight: ");
String planet = IBIO.inputString ("Enter a madeup planet name: ");
String theend = IBIO.inputString ("Enter a ending: ");
System.out.println ("");
System.out.println ("To the " +planet+ " ....");
System.out.println ("There was a boy named " +name+ " who dreamed to go to Planet "+planet );
System.out.println ("This planet is "+col+" and "+col2+" in colour");
System.out.println ("It is "+num+" metres in diameter and "+num2+" kg in mass");
System.out.println (name2+ " , his mother, said that first he needs to build a big spaceship to get him there.");
System.out.println ("\n\n"+theend);
}
}
| true |
8265a5f0b2b4e7ec42c8225fa422b86bd145120c | Java | aniskoubaa/CS102 | /src/topic02/classes/StudentTest.java | UTF-8 | 3,425 | 3.484375 | 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 topic02.classes;
import java.util.ArrayList;
/* Driver or Test Class */
public class StudentTest {
public static void main(String []args){
ArrayList<Student> studentList = new ArrayList<Student>();
Date birthDate1 = new Date(1,2,1980);
//new Student(): creates a new object in the memory
Student student1 = new Student("Mohamed", "Ali",
"0501020304", 3.3, "Riyadh", birthDate1);
System.out.println("count= "+Student.getCount());
//Date birthDate2 = new Date(4,3,1983);
//Date bd2 = new Date(4,12,1985);
Student student2 = new Student("Ahmed", "Mounir",
"0511223344", 3.45, "Riyadh", new Date(4,3,1983));
System.out.println("count= "+Student.getCount());
Student student3 = new Student("Ahmed", "Mounir",
"0511223344", 3.45, "Riyadh", new Date(5,5,1982));
Student st4 = new Student();
System.out.println("count = " + Student.getCount());
//student1.printInfo();
//student2.printInfo();
//student1.printGPA();
studentList.add(student1);
studentList.add(student2);
//for (int i=0;i<studentList.size();i++){
// studentList.get(i).printInfo();
//}
for (Student s : studentList){
s.printInfo();
}
/* not longer needed */
//student1.firstName = "Kamel";
//student1.lastName = "Anis";
//student1.phone = "t253usi93";
try{
student1.setPhone("0501020304");
}catch (IllegalArgumentException e){
System.out.println("Wrong Phone Number. The program will exit");
}
//student1.gpa = 3.5;
//student1.address = "Riyadh";
System.out.println("Student1 Phone: "+ student1.getPhone());
/* not longer needed */
//student2.firstName = "Ahmed";
//student2.lastName = "Mounir";
//student2.phone = "051122334454";
//student2.GPA = 3.45;
//student2.address = "Riyadh";
System.out.println("student1 : "+ student1);
System.out.println("student2 : "+ student2);
System.out.println("Year of birth of student1: "+
student1.getBirthDate().getYear());
System.out.println("Month of birth of student2: "+
student2.getBirthDate().getMonth());
System.out.println("Student3 birth date before change: "+
student3.getBirthDate());
//modify the day of birth of student3 to 28
student3.getBirthDate().setDay(28);
System.out.println("Student3 birth date after change: "+
student3.getBirthDate());
//change the birth date of student2 to 5/6/1990
//Date newBirthDate = new Date (5,6,1990);
student2.setBirthDate(new Date (5,6,1990));
System.out.println("Student2 birth date after change: "+
student2.getBirthDate());
}
}
| true |
a23514ae52f823aba28206f0f9e82d2166143556 | Java | dmr5bq/Java-Code-Samples | /src/edu/virginia/engine/game/Message.java | UTF-8 | 272 | 2.453125 | 2 | [] | no_license | package edu.virginia.engine.game;
public class Message {
public double start;
public double duration;
public String text;
public Message(String message, double start, double duration) {
this.start = start;
this.duration = duration;
this.text = message;
}
}
| true |
a9dd476c6dc8ac45f94aed9718935d3cb74b8243 | Java | omnia100/PyramidsDAO | /src/PyramidDAO.java | UTF-8 | 101 | 1.796875 | 2 | [] | no_license | import java.util.List;
public interface PyramidDAO {
List<Pyramid> readFile(String fileName);
}
| true |
4cf36c82f9a40f939ea150833d2ea336f1c465c8 | Java | DanielOrDany/Databases | /lab5/src/main/java/ua/lviv/iot/nikulshyn/model/Current.java | UTF-8 | 7,920 | 2.203125 | 2 | [
"MIT"
] | permissive | package ua.lviv.iot.nikulshyn.model;
import javax.persistence.*;
@Entity
public class Current {
private Integer id;
private Integer wind;
private Integer temperature;
private Double latitude;
private Double longtitude;
private Integer verticalSpeed;
private Integer gpsAltitude;
private Integer track;
private Integer groundSpeed;
private Integer trueSpeed;
private Integer indicatedSpeed;
private Integer march;
private Integer calibratedAltitude;
private Integer icao;
private Integer squawk;
private String dateTime;
private Airplane airplaneByAirplaneId;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "wind", nullable = false)
public Integer getWind() {
return wind;
}
public void setWind(Integer wind) {
this.wind = wind;
}
@Basic
@Column(name = "temperature", nullable = false)
public Integer getTemperature() {
return temperature;
}
public void setTemperature(Integer temperature) {
this.temperature = temperature;
}
@Basic
@Column(name = "latitude", nullable = false, precision = 0)
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
@Basic
@Column(name = "longtitude", nullable = false, precision = 0)
public Double getLongtitude() {
return longtitude;
}
public void setLongtitude(Double longtitude) {
this.longtitude = longtitude;
}
@Basic
@Column(name = "vertical_speed", nullable = false)
public Integer getVerticalSpeed() {
return verticalSpeed;
}
public void setVerticalSpeed(Integer verticalSpeed) {
this.verticalSpeed = verticalSpeed;
}
@Basic
@Column(name = "gps_altitude", nullable = false)
public Integer getGpsAltitude() {
return gpsAltitude;
}
public void setGpsAltitude(Integer gpsAltitude) {
this.gpsAltitude = gpsAltitude;
}
@Basic
@Column(name = "track", nullable = false)
public Integer getTrack() {
return track;
}
public void setTrack(Integer track) {
this.track = track;
}
@Basic
@Column(name = "ground_speed", nullable = false)
public Integer getGroundSpeed() {
return groundSpeed;
}
public void setGroundSpeed(Integer groundSpeed) {
this.groundSpeed = groundSpeed;
}
@Basic
@Column(name = "true_speed", nullable = false)
public Integer getTrueSpeed() {
return trueSpeed;
}
public void setTrueSpeed(Integer trueSpeed) {
this.trueSpeed = trueSpeed;
}
@Basic
@Column(name = "indicated_speed", nullable = false)
public Integer getIndicatedSpeed() {
return indicatedSpeed;
}
public void setIndicatedSpeed(Integer indicatedSpeed) {
this.indicatedSpeed = indicatedSpeed;
}
@Basic
@Column(name = "march", nullable = false)
public Integer getMarch() {
return march;
}
public void setMarch(Integer march) {
this.march = march;
}
@Basic
@Column(name = "calibrated_altitude", nullable = false)
public Integer getCalibratedAltitude() {
return calibratedAltitude;
}
public void setCalibratedAltitude(Integer calibratedAltitude) {
this.calibratedAltitude = calibratedAltitude;
}
@Basic
@Column(name = "icao", nullable = false)
public Integer getIcao() {
return icao;
}
public void setIcao(Integer icao) {
this.icao = icao;
}
@Basic
@Column(name = "squawk", nullable = false)
public Integer getSquawk() {
return squawk;
}
public void setSquawk(Integer squawk) {
this.squawk = squawk;
}
@Basic
@Column(name = "date_time", nullable = false, length = 45)
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Current current = (Current) o;
if (id != null ? !id.equals(current.id) : current.id != null) return false;
if (wind != null ? !wind.equals(current.wind) : current.wind != null) return false;
if (temperature != null ? !temperature.equals(current.temperature) : current.temperature != null) return false;
if (latitude != null ? !latitude.equals(current.latitude) : current.latitude != null) return false;
if (longtitude != null ? !longtitude.equals(current.longtitude) : current.longtitude != null) return false;
if (verticalSpeed != null ? !verticalSpeed.equals(current.verticalSpeed) : current.verticalSpeed != null)
return false;
if (gpsAltitude != null ? !gpsAltitude.equals(current.gpsAltitude) : current.gpsAltitude != null) return false;
if (track != null ? !track.equals(current.track) : current.track != null) return false;
if (groundSpeed != null ? !groundSpeed.equals(current.groundSpeed) : current.groundSpeed != null) return false;
if (trueSpeed != null ? !trueSpeed.equals(current.trueSpeed) : current.trueSpeed != null) return false;
if (indicatedSpeed != null ? !indicatedSpeed.equals(current.indicatedSpeed) : current.indicatedSpeed != null)
return false;
if (march != null ? !march.equals(current.march) : current.march != null) return false;
if (calibratedAltitude != null ? !calibratedAltitude.equals(current.calibratedAltitude) : current.calibratedAltitude != null)
return false;
if (icao != null ? !icao.equals(current.icao) : current.icao != null) return false;
if (squawk != null ? !squawk.equals(current.squawk) : current.squawk != null) return false;
if (dateTime != null ? !dateTime.equals(current.dateTime) : current.dateTime != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (wind != null ? wind.hashCode() : 0);
result = 31 * result + (temperature != null ? temperature.hashCode() : 0);
result = 31 * result + (latitude != null ? latitude.hashCode() : 0);
result = 31 * result + (longtitude != null ? longtitude.hashCode() : 0);
result = 31 * result + (verticalSpeed != null ? verticalSpeed.hashCode() : 0);
result = 31 * result + (gpsAltitude != null ? gpsAltitude.hashCode() : 0);
result = 31 * result + (track != null ? track.hashCode() : 0);
result = 31 * result + (groundSpeed != null ? groundSpeed.hashCode() : 0);
result = 31 * result + (trueSpeed != null ? trueSpeed.hashCode() : 0);
result = 31 * result + (indicatedSpeed != null ? indicatedSpeed.hashCode() : 0);
result = 31 * result + (march != null ? march.hashCode() : 0);
result = 31 * result + (calibratedAltitude != null ? calibratedAltitude.hashCode() : 0);
result = 31 * result + (icao != null ? icao.hashCode() : 0);
result = 31 * result + (squawk != null ? squawk.hashCode() : 0);
result = 31 * result + (dateTime != null ? dateTime.hashCode() : 0);
return result;
}
@ManyToOne
@JoinColumn(name = "airplane_id", referencedColumnName = "id")
public Airplane getAirplaneByAirplaneId() {
return airplaneByAirplaneId;
}
public void setAirplaneByAirplaneId(Airplane airplaneByAirplaneId) {
this.airplaneByAirplaneId = airplaneByAirplaneId;
}
}
| true |
2bb775e4c08fa0a04ac2863d81702d85afbd851e | Java | CamiloHernandezC/ClienteV3.1 | /test/Test/PersistenceTest.java | UTF-8 | 2,900 | 2.296875 | 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 Test;
import com.anarsoft.vmlens.concurrent.junit.ConcurrentTestRunner;
import com.clienteV31.facades.PersonasFacade;
import com.clienteV31.entities.Personas;
import com.clienteV31.entities.TiposDocumento;
import com.clienteV31.utils.Result;
import com.clienteV31.utils.Constants;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.NamingException;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
*
* @author chernandez
*/
@RunWith(ConcurrentTestRunner.class)
public class PersistenceTest {
private static Context ctx;
private static EJBContainer ejbContainer;
private PersonasFacade personasFacade;
private int counter;
public PersistenceTest() {
}
@BeforeClass
public static void setUp() {
Map<String, Object> properties = new HashMap<>();
properties.put("org.glassfish.ejb.embedded.glassfish.instance.root", "C:/Workspace/GlasfishServer/glassfish/domains/camilo");
ejbContainer = EJBContainer.createEJBContainer(properties);
System.out.println("Opening the container" );
ctx = ejbContainer.getContext();
}
@AfterClass
public static void tearDown() {
ejbContainer.close();
System.out.println("Closing the container" );
}
@Test
public void createPerson() throws NamingException {
//EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
personasFacade = (PersonasFacade)ctx.lookup("java:global/classes/PersonasFacade");
Personas person = new Personas();
person.setTipoDocumento(new TiposDocumento(1));
person.setNumeroDocumento(String.valueOf(getCounter()));
person.setNombre1("Camilo");
person.setApellido1("Hernandez");
Result result = personasFacade.create(person);
assertEquals(Constants.OK, result.errorCode);
}
private synchronized int getCounter(){
return counter++;
}
/*
private PersonasFacade lookupPersonasFacadeBean() {
try {
PersonasFacade dao = (PersonasFacade) ctx.lookup("java:global/ClienteV3.1/PersonasFacade");
assertNotNull(dao);
return dao;
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}*/
}
| true |
da9aa9c040a5c6d62c708c4a467472a36be89a7b | Java | Ulisesbh087/Sys-designers-Hackaton | /Proyectov3/src/main/java/com/mycompany/proyectov3/Clasificacion.java | UTF-8 | 1,970 | 2.921875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.proyectov3;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Clasificacion {
public void Principal(String direccion) {
System.out.println(direccion);
Scanner teclado = new Scanner(System.in);
String separador = System.getProperty("file.separator"); //Se obtiene el separador de ruta
String direccionXML = "";
String rutaProyecto = new File(".").getAbsolutePath();//Se obtiene la ruta del proyecto
direccionXML = rutaProyecto + separador+"xml";
System.out.println("Dirección?");
//final String direccion = teclado.nextLine();
Procesamiento procesamiento = new Procesamiento();
try {
Files.walk(Paths.get(direccionXML)).forEach(ruta -> { //Se lista el directorio ingresado
if (Files.isRegularFile(ruta)) {
//Se valida que sea una ruta válida
try {
File archivo = ruta.toFile();//Se convierte la ruta a tipo archivo
procesamiento.Principal(direccion, archivo.getName());
System.out.println("XML: "+archivo.getName());
} catch (IOException ex) {
Logger.getLogger(Clasificacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
JOptionPane.showMessageDialog(null, "Proceso terminado");
} catch (IOException ex) {
Logger.getLogger(Clasificacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true |
d2f0664fb1b9c6149d95455b425d059cb3a48889 | Java | appium/java-client | /src/test/java/io/appium/java_client/android/AndroidTouchTest.java | UTF-8 | 9,245 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package io.appium.java_client.android;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.MultiTouchAction;
import io.appium.java_client.TouchAction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import java.util.List;
import static io.appium.java_client.TestUtils.getCenter;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static io.appium.java_client.touch.TapOptions.tapOptions;
import static io.appium.java_client.touch.WaitOptions.waitOptions;
import static io.appium.java_client.touch.offset.ElementOption.element;
import static io.appium.java_client.touch.offset.PointOption.point;
import static java.time.Duration.ofSeconds;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class AndroidTouchTest extends BaseAndroidTest {
@BeforeEach
public void setUp() {
driver.resetApp();
}
@Test public void dragNDropByElementTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo");
driver.startActivity(activity);
WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1"));
WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3"));
WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text"));
assertEquals("Drag text not empty", "", dragText.getText());
TouchAction dragNDrop = new TouchAction(driver)
.longPress(element(dragDot1))
.moveTo(element(dragDot3))
.release();
dragNDrop.perform();
assertNotEquals("Drag text empty", "", dragText.getText());
}
@Test public void dragNDropByElementAndDurationTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo");
driver.startActivity(activity);
WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1"));
WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3"));
WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text"));
assertEquals("Drag text not empty", "", dragText.getText());
TouchAction dragNDrop = new TouchAction(driver)
.longPress(longPressOptions()
.withElement(element(dragDot1))
.withDuration(ofSeconds(2)))
.moveTo(element(dragDot3))
.release();
dragNDrop.perform();
assertNotEquals("Drag text empty", "", dragText.getText());
}
@Test public void dragNDropByCoordinatesTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo");
driver.startActivity(activity);
WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1"));
WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3"));
WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text"));
assertEquals("Drag text not empty", "", dragText.getText());
Point center1 = getCenter(dragDot1);
Point center2 = getCenter(dragDot3);
TouchAction dragNDrop = new TouchAction(driver)
.longPress(point(center1.x, center1.y))
.moveTo(point(center2.x, center2.y))
.release();
dragNDrop.perform();
assertNotEquals("Drag text empty", "", dragText.getText());
}
@Test public void dragNDropByCoordinatesAndDurationTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo");
driver.startActivity(activity);
WebElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1"));
WebElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3"));
WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text"));
assertEquals("Drag text not empty", "", dragText.getText());
Point center1 = getCenter(dragDot1);
Point center2 = getCenter(dragDot3);
TouchAction dragNDrop = new TouchAction(driver)
.longPress(longPressOptions()
.withPosition(point(center1.x, center1.y))
.withDuration(ofSeconds(2)))
.moveTo(point(center2.x, center2.y))
.release();
dragNDrop.perform();
assertNotEquals("Drag text empty", "", dragText.getText());
}
@Test public void pressByCoordinatesTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.Buttons1");
driver.startActivity(activity);
Point point = driver.findElement(By.id("io.appium.android.apis:id/button_toggle")).getLocation();
new TouchAction(driver)
.press(point(point.x + 20, point.y + 30))
.waitAction(waitOptions(ofSeconds(1)))
.release()
.perform();
assertEquals("ON", driver.findElement(By.id("io.appium.android.apis:id/button_toggle")).getText());
}
@Test public void pressByElementTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.Buttons1");
driver.startActivity(activity);
new TouchAction(driver)
.press(element(driver.findElement(By.id("io.appium.android.apis:id/button_toggle"))))
.waitAction(waitOptions(ofSeconds(1)))
.release()
.perform();
assertEquals("ON", driver.findElement(By.id("io.appium.android.apis:id/button_toggle")).getText());
}
@Test public void tapActionTestByElement() throws Exception {
Activity activity = new Activity("io.appium.android.apis", ".view.ChronometerDemo");
driver.startActivity(activity);
WebElement chronometer = driver.findElement(By.id("io.appium.android.apis:id/chronometer"));
TouchAction startStop = new TouchAction(driver)
.tap(tapOptions().withElement(element(driver.findElement(By.id("io.appium.android.apis:id/start")))))
.waitAction(waitOptions(ofSeconds(2)))
.tap(tapOptions().withElement(element(driver.findElement(By.id("io.appium.android.apis:id/stop")))));
startStop.perform();
String time = chronometer.getText();
assertNotEquals(time, "Initial format: 00:00");
Thread.sleep(2500);
assertEquals(time, chronometer.getText());
}
@Test public void tapActionTestByCoordinates() throws Exception {
Activity activity = new Activity("io.appium.android.apis", ".view.ChronometerDemo");
driver.startActivity(activity);
WebElement chronometer = driver.findElement(By.id("io.appium.android.apis:id/chronometer"));
Point center1 = getCenter(driver.findElement(By.id("io.appium.android.apis:id/start")));
TouchAction startStop = new TouchAction(driver)
.tap(point(center1.x, center1.y))
.tap(element(driver.findElement(By.id("io.appium.android.apis:id/stop")), 5, 5));
startStop.perform();
String time = chronometer.getText();
assertNotEquals(time, "Initial format: 00:00");
Thread.sleep(2500);
assertEquals(time, chronometer.getText());
}
@Test public void horizontalSwipingTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.Gallery1");
driver.startActivity(activity);
WebElement gallery = driver.findElement(By.id("io.appium.android.apis:id/gallery"));
List<WebElement> images = gallery.findElements(AppiumBy.className("android.widget.ImageView"));
int originalImageCount = images.size();
Point location = gallery.getLocation();
Point center = getCenter(gallery);
TouchAction swipe = new TouchAction(driver)
.press(element(images.get(2),-10, center.y - location.y))
.waitAction(waitOptions(ofSeconds(2)))
.moveTo(element(gallery,10,center.y - location.y))
.release();
swipe.perform();
assertNotEquals(originalImageCount,
gallery.findElements(AppiumBy.className("android.widget.ImageView")).size());
}
@Test public void multiTouchTest() {
Activity activity = new Activity("io.appium.android.apis", ".view.Buttons1");
driver.startActivity(activity);
TouchAction press = new TouchAction(driver)
.press(element(driver.findElement(By.id("io.appium.android.apis:id/button_toggle"))))
.waitAction(waitOptions(ofSeconds(1)))
.release();
new MultiTouchAction(driver)
.add(press)
.perform();
assertEquals("ON", driver.findElement(By.id("io.appium.android.apis:id/button_toggle")).getText());
}
}
| true |
94388fc420a5cba6cd1997a254ea18188a7a4e32 | Java | ybakkali/INFO-H417-Project | /src/main/java/info/h417/model/algo/BaseAlgo.java | UTF-8 | 768 | 2.609375 | 3 | [] | no_license | package info.h417.model.algo;
import info.h417.model.stream.Generator;
public class BaseAlgo {
protected final Generator generator;
protected Generator writeGenerator;
protected String outputFilename;
/**
* A generic Constructor that takes a generator as parameter
*
* @param generator The generator
*/
public BaseAlgo(Generator generator) {
this.generator = generator;
}
/**
* A generic Constructor that takes a generator as parameter
*
* @param generator The read generator
* @param writeGenerator The write generator
*/
public BaseAlgo(Generator generator,Generator writeGenerator) {
this.generator = generator;
this.writeGenerator = writeGenerator;
}
}
| true |
7760b4dbcd260f3721b90227422387a86db05303 | Java | PankajSAgarwal/JavaDesignPattern | /JavaSpecialists-AbstractFactory/src/exercise1/AbstractFactoryTest.java | UTF-8 | 1,655 | 3.328125 | 3 | [] | no_license | package exercise1;
import org.junit.*;
import java.lang.reflect.*;
import static org.junit.Assert.*;
//DON'T CHANGE
public class AbstractFactoryTest {
@Test
public void testSlowEarth() {
Earth earth = new SlowEarth();
Animal animal = earth.createAnimal();
Vehicle vehicle = earth.createVehicle();
assertEquals("Sloth", animal.getClass().getSimpleName());
assertEquals("Tractor", vehicle.getClass().getSimpleName());
}
@Test
public void testFastEarth() {
Earth earth = new FastEarth();
Animal animal = earth.createAnimal();
Vehicle vehicle = earth.createVehicle();
assertEquals("Cheetah", animal.getClass().getSimpleName());
assertEquals("Lamborghini", vehicle.getClass().getSimpleName());
}
@Test
public void testCreationUsingProperties() throws Exception {
resetEarthField();
System.getProperties().setProperty("earthclass",
getClass().getPackageName() + ".SlowEarth");
Earth slow_earth = Earth.getEarth();
assertEquals(SlowEarth.class, slow_earth.getClass());
resetEarthField();
System.getProperties().setProperty("earthclass",
getClass().getPackageName() + ".FastEarth");
Earth fast_earth = Earth.getEarth();
assertEquals(FastEarth.class, fast_earth.getClass());
}
private void resetEarthField() throws NoSuchFieldException, IllegalAccessException {
// initialValue earth field
Field earthField = Earth.class.getDeclaredField("earth");
earthField.setAccessible(true);
earthField.set(null, null);
}
}
| true |
d7a934d19f2f65d1c94ddfe6a3984544aea86f02 | Java | dveyarangi/libgdx-utils | /src/game/systems/rendering/SpriteTextureDef.java | UTF-8 | 977 | 2.453125 | 2 | [] | no_license | package game.systems.rendering;
import game.resources.TextureName;
public class SpriteTextureDef extends SpriteDef <SpriteTextureComponent>
{
public TextureName textureName;
public SpriteTextureDef(String textureName)
{
this(new TextureName(textureName), 0, 0, 0, 1, 1);
}
public SpriteTextureDef(TextureName textureName, float xOffset, float yOffset, float zOffset, float w, float h)
{
super(xOffset, yOffset, zOffset, w, h);
this.textureName = textureName;
}
@Override
public Class<SpriteTextureComponent> getComponentClass() { return SpriteTextureComponent.class; }
/* @Override
public void initComponent( SpriteComponent component, Entity entity, Level level )
{
//ComponentType.registerFor(IRenderingComponent.class, component.getClass());
//ResourceFactory factory = level.getModules().getGameFactory();
component.init( entity, this, level );
component.origRegion = ResourceFactory.getTextureRegion(this.textureName.getName());
}*/
}
| true |
ecab0ec91c8a6131fad3eaeca903d65b28a9ae41 | Java | mirek190/x86-android-5.0 | /pdk/apps/TestingCamera2/src/com/android/testingcamera2/RequestControlPane.java | UTF-8 | 10,352 | 1.664063 | 2 | [] | no_license | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.testingcamera2;
import android.content.Context;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CaptureRequest;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class RequestControlPane extends ControlPane {
// XML attributes
/** Name of pane tag */
private static final String PANE_NAME = "request_pane";
/** Attribute: ID for pane (integer) */
private static final String PANE_ID = "id";
// End XML attributes
private enum TemplateType {
MANUAL(CameraDevice.TEMPLATE_MANUAL),
PREVIEW(CameraDevice.TEMPLATE_PREVIEW),
RECORD(CameraDevice.TEMPLATE_RECORD),
STILL_CAPTURE(CameraDevice.TEMPLATE_STILL_CAPTURE),
VIDEO_SNAPSHOT(CameraDevice.TEMPLATE_VIDEO_SNAPSHOT),
ZERO_SHUTTER_LAG(CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
private int mTemplateVal;
TemplateType(int templateVal) {
mTemplateVal = templateVal;
}
int getTemplateValue() {
return mTemplateVal;
}
}
private static int mRequestPaneIdCounter = 0;
private final int mPaneId;
private List<CameraControlPane> mCameraPanes;
private final List<TargetControlPane> mTargetPanes = new ArrayList<TargetControlPane>();
private Spinner mCameraSpinner;
private Spinner mTemplateSpinner;
private ListView mOutputListView;
private CheckableListAdapter mOutputAdapter;
/**
* Constructor for tooling only
*/
public RequestControlPane(Context context, AttributeSet attrs) {
super(context, attrs, null, null);
mPaneId = 0;
setUpUI(context);
}
public RequestControlPane(TestingCamera21 tc, AttributeSet attrs, StatusListener listener) {
super(tc, attrs, listener, tc.getPaneTracker());
mPaneId = mRequestPaneIdCounter++;
setUpUI(tc);
}
public RequestControlPane(TestingCamera21 tc, XmlPullParser configParser,
StatusListener listener) throws XmlPullParserException, IOException {
super(tc, null, listener, tc.getPaneTracker());
this.setName(tc.getResources().getString(R.string.request_pane_title));
configParser.require(XmlPullParser.START_TAG, XmlPullParser.NO_NAMESPACE, PANE_NAME);
int paneId = getAttributeInt(configParser, PANE_ID, -1);
if (paneId == -1) {
mPaneId = mRequestPaneIdCounter++;
} else {
mPaneId = paneId;
if (mPaneId >= mRequestPaneIdCounter) {
mRequestPaneIdCounter = mPaneId + 1;
}
}
configParser.next();
configParser.require(XmlPullParser.END_TAG, XmlPullParser.NO_NAMESPACE, PANE_NAME);
setUpUI(tc);
}
public void notifyPaneEvent(ControlPane sourcePane, PaneTracker.PaneEvent event) {
switch (event) {
case NEW_CAMERA_SELECTED:
if (mCameraPanes.size() > 0
&& sourcePane == mCameraPanes.get(mCameraSpinner.getSelectedItemPosition())) {
updateOutputList();
}
break;
case CAMERA_CONFIGURED:
if (mCameraPanes.size() > 0
&& sourcePane == mCameraPanes.get(mCameraSpinner.getSelectedItemPosition())) {
updateOutputList();
}
break;
default:
super.notifyPaneEvent(sourcePane, event);
}
}
private void setUpUI(Context context) {
String paneName =
String.format(Locale.US, "%s %d",
context.getResources().getString(R.string.request_pane_title), mPaneId);
this.setName(paneName);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.request_pane, this);
Button captureButton = (Button) findViewById(R.id.request_pane_capture_button);
captureButton.setOnClickListener(mCaptureButtonListener);
Button repeatButton = (Button) findViewById(R.id.request_pane_repeat_button);
repeatButton.setOnClickListener(mRepeatButtonListener);
mCameraSpinner = (Spinner) findViewById(R.id.request_pane_camera_spinner);
mTemplateSpinner = (Spinner) findViewById(R.id.request_pane_template_spinner);
mOutputListView = (ListView) findViewById(R.id.request_pane_output_listview);
mOutputAdapter = new CheckableListAdapter(context, R.layout.checkable_list_item,
new ArrayList<CheckableListAdapter.CheckableItem>());
mOutputListView.setAdapter(mOutputAdapter);
String[] templateNames = new String[TemplateType.values().length];
for (int i = 0; i < templateNames.length; i++) {
templateNames[i] = TemplateType.values()[i].toString();
}
mTemplateSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.spinner_item,
templateNames));
mPaneTracker.addPaneListener(new CameraPanesListener());
mCameraPanes = mPaneTracker.getPanes(CameraControlPane.class);
updateCameraPaneList();
}
private class CameraPanesListener extends PaneTracker.PaneSetChangedListener<CameraControlPane> {
public CameraPanesListener() {
super(CameraControlPane.class);
}
@Override
public void onPaneAdded(ControlPane pane) {
mCameraPanes.add((CameraControlPane) pane);
updateCameraPaneList();
}
@Override
public void onPaneRemoved(ControlPane pane) {
mCameraPanes.remove((CameraControlPane) pane);
updateCameraPaneList();
}
}
private OnClickListener mCaptureButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (mCameraPanes.size() == 0) {
TLog.e("No camera selected for request");
return;
}
CameraControlPane camera = mCameraPanes.get(mCameraSpinner.getSelectedItemPosition());
CaptureRequest request = createRequest(camera);
if (request != null) {
camera.capture(request);
}
}
};
private OnClickListener mRepeatButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (mCameraPanes.size() == 0) {
TLog.e("No camera selected for request");
return;
}
CameraControlPane camera = mCameraPanes.get(mCameraSpinner.getSelectedItemPosition());
CaptureRequest request = createRequest(camera);
if (request != null) {
camera.repeat(request);
}
}
};
private CaptureRequest createRequest(CameraControlPane camera) {
if (mTargetPanes.size() == 0) {
TLog.e("No target(s) selected for request");
return null;
}
TemplateType template = TemplateType.valueOf((String) mTemplateSpinner.getSelectedItem());
CaptureRequest.Builder builder = camera.getRequestBuilder(template.getTemplateValue());
// TODO: Add setting overrides
List<Integer> targetPostions = mOutputAdapter.getCheckedPositions();
for (int i : targetPostions) {
TargetControlPane target = mTargetPanes.get(i);
Surface targetSurface = target.getTargetSurfaceForCameraPane(camera.getPaneName());
if (targetSurface == null) {
TLog.e("Target not configured for camera");
return null;
}
builder.addTarget(targetSurface);
}
CaptureRequest request = builder.build();
return request;
}
private void updateCameraPaneList() {
String currentSelection = (String) mCameraSpinner.getSelectedItem();
int newSelectionIndex = 0;
String[] cameraSpinnerItems = new String[mCameraPanes.size()];
for (int i = 0; i < cameraSpinnerItems.length; i++) {
cameraSpinnerItems[i] = mCameraPanes.get(i).getPaneName();
if (cameraSpinnerItems[i].equals(currentSelection)) {
newSelectionIndex = i;
}
}
mCameraSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.spinner_item,
cameraSpinnerItems));
mCameraSpinner.setSelection(newSelectionIndex);
updateOutputList();
}
private void updateOutputList() {
if (mCameraPanes.size() > 0) {
CameraControlPane currentCamera =
mCameraPanes.get(mCameraSpinner.getSelectedItemPosition());
mTargetPanes.clear();
List<TargetControlPane> newPanes = currentCamera.getCurrentConfiguredTargets();
if (newPanes != null) {
mTargetPanes.addAll(currentCamera.getCurrentConfiguredTargets());
}
String[] outputSpinnerItems = new String[mTargetPanes.size()];
for (int i = 0; i < outputSpinnerItems.length; i++) {
outputSpinnerItems[i] = mTargetPanes.get(i).getPaneName();
}
mOutputAdapter.updateItems(outputSpinnerItems);
}
}
}
| true |
279e4770bdc43603f000cae7d23049b362aba888 | Java | ChoiSunHo/WEB_SPRING | /project/src/musicvideo/RM_MusicVideo.java | UTF-8 | 645 | 2.140625 | 2 | [] | no_license | package musicvideo;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class RM_MusicVideo implements RowMapper<MusicVideoVO>{
@Override
public MusicVideoVO mapRow(ResultSet rs, int arg1) throws SQLException {
MusicVideoVO vo = new MusicVideoVO();
vo.setNo( rs.getInt(1) );
vo.setTitle( rs.getString(2) );
vo.setText( rs.getString(3) );
vo.setTheTime( rs.getString(4) );
vo.setClientIp( rs.getString(5) );
vo.setUserId( rs.getString(6) );
vo.setViewNo( rs.getInt(7));
vo.setLikeNo( rs.getInt(8));
return vo;
}
}
| true |
1bd2b90f3d73c7e7bb21dc6a713c370f44dd1944 | Java | aditya7188/CoreJava | /Thread1.java | UTF-8 | 303 | 2.796875 | 3 | [] | no_license | class RamaThread extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println("RamaThread:"+i);
}
}
public static void main(String[] args)
{
RamaThread r1=new RamaThread();
r1.start();
}
} | true |
351a251f4070b46d4ae18d4fcc1024000ba5ba03 | Java | techism/techism-monitoring2 | /src/test/java/org/techism/monitoring/service/PageCheckServiceTest.java | UTF-8 | 1,186 | 2.078125 | 2 | [] | no_license | package org.techism.monitoring.service;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.techism.monitoring.domain.PageCheck;
import org.techism.monitoring.domain.PageCheckRepository;
@RunWith(MockitoJUnitRunner.class)
public class PageCheckServiceTest {
private static PageCheckRepository repository;
@Before
public void setUp (){
repository = mock(PageCheckRepository.class);
// TODO findAll
}
@Test
public void getStatus(){
PageCheckService service = new PageCheckService();
service.repository = repository;
List<PageCheck> result = service.getStatus();
assertEquals(0, result.size());
verify(repository, times(1)).findAll();
}
@Test
public void check(){
PageCheckService service = new PageCheckService();
service.repository = repository;
String result = service.check();
assertEquals("done", result);
verify(repository, times(1)).findAll();
}
}
| true |
6095997cdaf6fba2bfd0a82fc451d3c90538dabb | Java | kmin135/algospot | /Algospot/src/khs/algo/easy/JUMPGAME.java | UTF-8 | 1,703 | 3.265625 | 3 | [] | no_license | package khs.algo.easy;
import java.util.Scanner;
/**
* 시작 : 16-04-13 15:00
* 종료 : 16-04-13 15:33
* https://algospot.com/judge/problem/read/JUMPGAME
*
*
최악의 입력. 동적 계획법을 쓰자!
1
7
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 2
1 1 1 1 1 2 0
*/
public class JUMPGAME {
private static int[][] cache = new int[100][100];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc-- > 0) {
int n = sc.nextInt();
int[][] map = new int[n][n];
for(int i=0;i<map.length;i++) {
for(int j=0;j<map[i].length;j++) {
map[i][j] = sc.nextInt();
}
}
// start
long st = System.nanoTime();
boolean result = move(map, 0, 0);
cache = new int[100][100];
/* 걍 새로만드는게 빠르다...
* for(int i=0;i<cache.length;i++) {
for(int j=0;j<cache[i].length;j++) {
if(cache[i][j] == 1)
cache[i][j] = 0;
}
}*/
System.out.println("# elapsed " + (System.nanoTime() - st) + " ns ...");
if(result) {
System.out.println("YES");
} else {
System.out.println("NO");
}
// end
}
sc.close();
}
static boolean move(int[][] map, int nx, int ny) {
if(nx < 0 || nx > map.length-1 || ny < 0 || ny > map.length-1) {
return false;
} else if(nx == map.length-1 && ny == map.length-1) {
return true;
}
if(cache[ny][nx] == 1)
return false;
if(move(map, nx+map[ny][nx], ny) || move(map, nx, ny+map[ny][nx])) {
return true;
}
cache[ny][nx] = 1;
return false;
}
}
| true |
eb89e6ec4c35273844f09e5dd3495000608a8d45 | Java | buriosca/cz.burios.uniql-jpa | /src/cz/burios/uniql/persistence/annotations/CacheIndex.java | UTF-8 | 2,181 | 1.921875 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
******************************************************************************/
package cz.burios.uniql.persistence.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Allow a cache index to be define.
* A cache index allow singleResult queries to obtain a cache hit when querying on the indexed fields.
* resultList queries cannot obtain cache hits, as it is unknown if all of the objects are in memory,
* (unless the cache usage query hint is used).
* The index should be unique, but if not unique, the first indexed object will be returned.
* Cache indexes are only relevant when caching is enabled.
* The @CacheIndex can be defined on a Entity class, or on an attribute.
* The column is defaulted when defined on a attribute.
*
* @author James Sutherland
* @since EclipseLink 2.4
*/
@Target({METHOD, FIELD, TYPE})
@Retention(RUNTIME)
public @interface CacheIndex {
/**
* Specify the set of columns to define the index on.
* Not required when annotated on a field/method.
*/
String[] columnNames() default {};
/**
* Specify if the indexed field is updateable.
* If updateable the object will be re-indexed on each update/refresh.
*/
boolean updateable() default true;
}
| true |
55e6c3530527486e91f30f852745fce9d7dbccf0 | Java | 1218683832/noproject | /module_view/src/main/java/com/mrrun/module_view/loadingview/LoadingLineView.java | UTF-8 | 4,557 | 2.4375 | 2 | [] | no_license | package com.mrrun.module_view.loadingview;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import com.mrrun.module_view.Debug;
/**
* 从中心向两端扩散的动态加载进度动态View。
* 需求1:水平方向动态加载;
* 需求2:从中心向两端扩散;
*
* @author lipin
* @version 1.0
* @date 2018 /07/09
*/
public class LoadingLineView extends View {
private Context mContext;
private Paint mProgressPaint;
private int mViewWidth, mViewHeight;
/**
* View中心点坐标
*/
private int mViewCenterX,mViewCenterY;
/**
* 从中心点到左右两边最大可绘制的距离
*/
private int mMaxDistanceX;
/**
* 从中心点到左右两边当前可绘制的距离
*/
private int mCurDistanceX;
private AnimatorSet animatorSet = new AnimatorSet();
public LoadingLineView(Context context) {
super(context);
mContext = context;
init();
}
public LoadingLineView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
private void init() {
initData();
initPaint();
}
private void initPaint() {
mProgressPaint = new Paint();
mProgressPaint.setStyle(Paint.Style.FILL);
mProgressPaint.setAntiAlias(true);
mProgressPaint.setColor(Color.parseColor("#ff8000"));
}
private void initData() {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Debug.D("onSizeChanged");
mViewWidth = w;
mViewHeight = h;
mViewCenterX = w / 2;
mViewCenterY = h / 2;
mMaxDistanceX = mViewWidth / 2;
Debug.D("onSizeChanged mMaxDistanceX = " + mMaxDistanceX);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(mViewCenterX - mCurDistanceX, 0,mViewCenterX + mCurDistanceX, mViewHeight, mProgressPaint);
}
private ValueAnimator horizontalGrowthAnimation(){
ValueAnimator animator = ValueAnimator.ofInt(0, mMaxDistanceX);
animator.setInterpolator(new DecelerateInterpolator());
animator.setDuration(1000);
animator.setRepeatCount(-1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mCurDistanceX = (int) animation.getAnimatedValue();
Debug.D(String.format("从中心点到左右两边当前可绘制的距离%d", mCurDistanceX));
invalidate();
}
});
return animator;
}
private ValueAnimator alphaAnimation(){
ValueAnimator animator = ValueAnimator.ofInt(0,255,0);
animator.setDuration(1000);
animator.setRepeatCount(-1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int a = (int) animation.getAnimatedValue();
mProgressPaint.setAlpha(a);
Debug.D(String.format("当前alpha值%d", a));
}
});
return animator;
}
public void startAnimation(){
if (!animatorSet.isRunning()){
// 让布局实例化好之后再去开启动画
post(new Runnable() {
@Override
public void run() {
animatorSet.play(horizontalGrowthAnimation()).with(alphaAnimation());
animatorSet.setDuration(800);
animatorSet.start();
}
});
}
}
private void stopAnimation(){
if (animatorSet.isRunning() || animatorSet.isPaused()){
animatorSet.cancel();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stopAnimation();
}
} | true |
daecf6d6bda1acb85723564ec3c2f9de53d8817e | Java | drh0534/gs | /src/main/java/com/gs/pp/validator/CheckPasswordValidator.java | UTF-8 | 1,065 | 2.296875 | 2 | [] | no_license | package com.gs.pp.validator;
import com.gs.pp.common.annotation.CheckPassword;
import com.gs.pp.orm.User;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* Created by duronghong on 2016/3/3.
* Email: drh0534@163.com
*/
public class CheckPasswordValidator implements ConstraintValidator<CheckPassword,User> {
@Override
public void initialize(CheckPassword checkPassword) {
}
@Override
public boolean isValid(User user, ConstraintValidatorContext context) {
if(user==null){
return false;
}
if(!StringUtils.hasText(user.getPassword())){
//禁用默认的约束
context.disableDefaultConstraintViolation();
//定义我们自己的约束
context.buildConstraintViolationWithTemplate("{user.password.null}")
.addPropertyNode("password")
.addConstraintViolation();
return false;
}
return true;
}
}
| true |
f0bc3b6dbabed3ddb8b27e4636a9e9b05756ad91 | Java | hahaha28/APT-Demo | /sss/src/main/java/com/example/sss/SssActivity.java | UTF-8 | 390 | 1.632813 | 2 | [] | no_license | package com.example.sss;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.apt_annotation.Routing;
@Routing(key="sss")
public class SssActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sss);
}
} | true |
7ef7e002ba2819d9aac399093b00fb84e0884013 | Java | hongyuxiong/AutoTest | /src/Arraylist/YiWeiArrary2.java | UTF-8 | 956 | 3.5625 | 4 | [] | no_license | package Arraylist;
public class YiWeiArrary2 {
public static void main(String[] args){
/**byte short int long的数组初始值都是0*/
int[] arr = new int[1];
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
/**char型的数组的初始值是0,不是'0'*/
char[] arr1 = new char[1];
for(int i=0;i<arr.length;i++){
System.out.println("实际上是0--"+arr[i]+"--前后没字就会不显示");
}
/**布尔型的初始值是false*/
boolean[] arr2 = new boolean[1];
for(int i=0;i<arr.length;i++){
/**打印角标/索引为0的数组的值*/
System.out.println(arr2[0]);
}
/**引用数据类型的初始值是 null */
String[] arr3 = new String[5];
System.out.println(arr3[0]);
if(arr3[0]==null){
System.out.println("的确是null");
}
}
}
| true |
e8d235685bcaec274d13072ba55700a71322c5c5 | Java | waterwitness/dazhihui | /classes/com/android/dazhihui/ui/widget/ky.java | UTF-8 | 810 | 1.953125 | 2 | [] | no_license | package com.android.dazhihui.ui.widget;
import android.view.View;
class ky
implements Runnable
{
ky(StickyScrollView paramStickyScrollView) {}
public void run()
{
if (StickyScrollView.a(this.a) != null)
{
int i = StickyScrollView.a(this.a, StickyScrollView.a(this.a));
int j = StickyScrollView.b(this.a, StickyScrollView.a(this.a));
int k = StickyScrollView.c(this.a, StickyScrollView.a(this.a));
int m = (int)(this.a.getScrollY() + (StickyScrollView.a(this.a).getHeight() + StickyScrollView.b(this.a)));
this.a.invalidate(i, j, k, m);
}
this.a.postDelayed(this, 16L);
}
}
/* Location: E:\apk\dazhihui2\classes-dex2jar.jar!\com\android\dazhihui\ui\widget\ky.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
961ed9ca721f40b0f9491ee45ac02b2ee0ff4dc1 | Java | hxxy2003/zhl-cloud-master | /zhl-resources/src/main/java/net/tfedu/zhl/cloud/resource/resSearch/controller/ResSearchController.java | UTF-8 | 7,310 | 2.109375 | 2 | [] | no_license | package net.tfedu.zhl.cloud.resource.resSearch.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tfedu.zhl.cloud.resource.poolTypeFormat.entity.SysFrom;
import net.tfedu.zhl.cloud.resource.resSearch.entity.ResSearchResultEntity;
import net.tfedu.zhl.cloud.resource.resSearch.service.ResSearchService;
import net.tfedu.zhl.cloud.resource.resourceList.entity.Pagination;
import net.tfedu.zhl.cloud.resource.resourceList.util.ResThumbnailPathUtil;
import net.tfedu.zhl.cloud.utils.datatype.StringUtils;
import net.tfedu.zhl.helper.CustomException;
import net.tfedu.zhl.helper.ResultJSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 资源跨库检索的controller
*
* @author WeiCuicui
*
*/
@Controller
@RequestMapping("/resRestAPI")
public class ResSearchController {
@Resource
ResSearchService resSearchService;
//写入日志
Logger logger = LoggerFactory.getLogger(ResSearchController.class);
/**
* 根据检索内容,跨库检索所有资源
*
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/v1.0/resSearchResults")
@ResponseBody
public ResultJSON getAllResources(HttpServletRequest request, HttpServletResponse response) throws IOException {
/**
* 返回json的结果对象
*/
ResultJSON resultJSON = new ResultJSON();
// 异常
CustomException exception = (CustomException) request.getAttribute(CustomException.request_key);
// 当前登录用户id
Long currentUserId = (Long) request.getAttribute("currentUserId");
// 分页查询结果
Pagination<ResSearchResultEntity> pagination = null;
try {
// 若当前用户已经登录系统
if (exception == null && currentUserId != null) {
//获取文件服务器的访问url
String resServiceLocal = (String)request.getAttribute("resServiceLocal");
String currentResPath = (String)request.getAttribute("currentResPath");
// 检索范围 0 全部资源 1 系统资源 3 校本资源 4 区本资源
int fromFlag = 0;
// 检索的关键词
String searchKeyword = "";
// 资源格式:全部,文本,图片......
String format = "全部";
// 页码
int page = 1;
// 每页记录数目
int perPage = 10;
if(StringUtils.isNotEmpty(request.getParameter("fromFlag"))){
fromFlag = Integer.parseInt(request.getParameter("fromFlag").toString().trim());
}
if(StringUtils.isNotEmpty(request.getParameter("searchKeyword"))){
searchKeyword = request.getParameter("searchKeyword").toString().trim();
}
if(StringUtils.isNotEmpty(request.getParameter("format"))){
format = request.getParameter("format").toString().trim();
}
if(StringUtils.isNotEmpty(request.getParameter("page"))){
page = Integer.parseInt(request.getParameter("page").toString().trim());
}
if(StringUtils.isNotEmpty(request.getParameter("perPage"))){
perPage = Integer.parseInt(request.getParameter("perPage").toString().trim());
}
pagination = resSearchService.getResources(fromFlag, SysFrom.sys_from, searchKeyword, format, page,
perPage,currentUserId);
//生成文件的缩略图路径
ResThumbnailPathUtil.convertToPurpos_resSearch(pagination.getList(), resServiceLocal, currentResPath);
logger.debug("检索关键字:" + searchKeyword);
logger.debug("资源格式:" + format);
logger.debug("资源来源fromFlag:" + fromFlag);
logger.debug("检索结果的当前页:" + pagination.getPage());
logger.debug("检索结果每页资源数目:" + pagination.getPerPage());
logger.debug("检索到的资源总页:" + pagination.getTotal());
logger.debug("检索到的资源总数:" + pagination.getTotalLines());
exception = CustomException.SUCCESS;
} else {
exception = CustomException.INVALIDACCESSTOKEN;
}
} catch (Exception e) {
// TODO: handle exception
// 捕获异常信息
exception = CustomException.getCustomExceptionByCode(e.getMessage());
e.printStackTrace();
} finally {
// 封装结果集
resultJSON.setCode(exception.getCode());
resultJSON.setData(pagination);
resultJSON.setMessage(exception.getMessage());
resultJSON.setSign("");
}
return resultJSON;
}
/**
* 查询资源检索结果中的格式
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/v1.0/resSearchResults/formats")
@ResponseBody
public ResultJSON getResFormats(HttpServletRequest request,HttpServletResponse response)throws IOException{
/**
* 返回json的结果对象
*/
ResultJSON resultJSON = new ResultJSON();
// 异常
CustomException exception = (CustomException) request.getAttribute(CustomException.request_key);
// 当前登录用户id
Long currentUserId = (Long) request.getAttribute("currentUserId");
List<String> resultList = new ArrayList<String>();
try {
// 若当前用户已经登录系统
if (exception == null && currentUserId != null) {
// 检索范围 0 全部资源 1 系统资源 3 校本资源 4 区本资源
int fromFlag = Integer.parseInt(request.getParameter("fromFlag"));
// 检索的关键词
String searchKeyword = request.getParameter("searchKeyword");
resultList = resSearchService.getFileFormats(searchKeyword, fromFlag, SysFrom.sys_from,currentUserId);
exception = CustomException.SUCCESS;
}
} catch (Exception e) {
// TODO: handle exception
// 捕获异常信息
exception = CustomException.getCustomExceptionByCode(e.getMessage());
e.printStackTrace();
} finally {
// 封装结果集
resultJSON.setCode(exception.getCode());
resultJSON.setData(resultList);
resultJSON.setMessage(exception.getMessage());
resultJSON.setSign("");
}
return resultJSON;
}
}
| true |
497e46b97f352a8e0a6e2b496c3c1efb2540fa24 | Java | vbalakrishna/Tarvel-Guide | /app/src/main/java/com/example/raghu/travelguide/StartActivity.java | UTF-8 | 2,379 | 2.21875 | 2 | [] | no_license | package com.example.raghu.travelguide;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class StartActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] items = { "Places", "Restaurants", "Hotels" };
String interestedin = "";
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final Spinner s = (Spinner) findViewById(R.id.spinner);
final EditText e = (EditText) findViewById(R.id.editText);
s.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setPrompt("Choose Your Interest");
s.setAdapter(aa);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String place = e.getText().toString();
if (place.equals("") || interestedin.equals("")){
Toast.makeText(getApplicationContext(),"Make sure to fill all the fields :)" ,Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(StartActivity.this, ResultActivity.class);
String message = interestedin+" in "+place+"-";
message += "https://maps.googleapis.com/maps/api/place/textsearch/json?query="+interestedin+"+in+"+place+"&key=AIzaSyDiOuDDV7yRdHk9mvQMP4uenZ05B1KYSbw";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
});
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
interestedin = items[position];
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| true |
299becb6b57b9e15fd3276d063ef9296f36cba6a | Java | gmp237/tp1 | /Livre.java | UTF-8 | 1,957 | 2.921875 | 3 | [] | no_license |
public class Livre implements Comparable<Livre>
{
public String titre, categorie;
private int codeAuteur, codeLivre, nbPages;
private double prix;
public Livre( int codeLivre, String titre, String categorie, int codeAuteur, double prix, int nbPages)
{
this.titre = titre;
this.categorie = categorie;
this.codeAuteur = codeAuteur;
this.codeLivre = codeLivre;
this.prix = prix;
this.nbPages = nbPages;
}
Livre(int codeLivre) {
this(codeLivre, "", "", 0, 0.0, 0);
}
Livre(String titre) {
this(0, titre, "", 0, 0.0, 0);
}
public void setTitre(String titre)
{
this.titre = titre;
}
public void setCategorie(String categorie)
{
this.categorie = categorie;
}
public void setCodeAuteur(int codeAuteur)
{
this.codeAuteur = codeAuteur;
}
public void setCodeLivre(int codeLivre)
{
this.codeLivre = codeLivre;
}
public void setNbPages(int nbPages)
{
this.nbPages = nbPages;
}
public void setPrix(double prix)
{
this.prix = prix;
}
public String getTitre()
{
return titre;
}
public String getCategorie()
{
return categorie ;
}
public int getCodeAuteur()
{
return codeAuteur;
}
public int getCodeLivre()
{
return codeLivre;
}
public int getPages()
{
return nbPages;
}
public double getPrix()
{
return prix;
}
public int compareTo(Livre autre)
{
return titre.compareToIgnoreCase(autre.titre);
}
public boolean equals(Object autre) {
if (this == autre) // Lui-même
return true;
else
if ( ! (autre instanceof Livre) ) // Incomparable
return false;
else
return titre == ((Livre) autre).getTitre();
}
public String toString()
{
return "Livre [Code du livre" + codeLivre+ "Titre:"+ titre+ "Categorie:" + categorie + "Code de l'auteur"
+ codeAuteur + "Prix:"+ prix+ "pages:"+ nbPages+ "]";
}
}
| true |
2856c06012c50c4eba76b83a6daa3f735b85ea44 | Java | jeffreson19/Faith_BDay | /Faith_BDAY/ConfettiGun.java | UTF-8 | 4,856 | 2.828125 | 3 | [] | no_license | import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ConfettiGun {
ArrayList<Confetti> arrayOfConfetti = new ArrayList<>();
Main main;
boolean isSpacePressed = false;
ConfettiGun (Main main) {
this.main = main;
refreshGun();
}
public void tick() {
if(isSpacePressed) {
for (int i = 0; i < arrayOfConfetti.size(); i++) {
arrayOfConfetti.get(i).tick();
}
}
if(arrayOfConfetti.size() == 0) isSpacePressed = false;
killConfetti();
}
public void paint(Graphics2D g2d) {
if(isSpacePressed) {
for (int i = 0; i < arrayOfConfetti.size(); i++) {
arrayOfConfetti.get(i).paint(g2d);
}
}
}
public void refreshGun() {
arrayOfConfetti.clear();
// bottom left corner
arrayOfConfetti.add(new Confetti(0, 500, 5f, -5f, 0.1f,0.002f, 2f, Color.orange));
arrayOfConfetti.add(new Confetti(0, 500, 7f, -7f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(0, 500, 9f, -6f, 0.1f,0.002f, 2f, Color.magenta));
arrayOfConfetti.add(new Confetti(0, 500, 2f, -6f, 0.1f,0.002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(0, 500, 3f, -5f, 0.1f,0.002f, 2f, Color.orange));
arrayOfConfetti.add(new Confetti(0, 500, 6f, -8f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(0, 500, 4f, -3f, 0.1f,0.002f, 2f, Color.magenta));
arrayOfConfetti.add(new Confetti(0, 500, 8f, -4f, 0.1f,0.002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(0, 500, 1f, -5f, 0.1f,0.002f, 2f, Color.orange)); //
arrayOfConfetti.add(new Confetti(0, 500, 8f, -8f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(0, 500, 6f, -6f, 0.1f,0.002f, 2f, Color.magenta));
arrayOfConfetti.add(new Confetti(0, 500, 2f, -4f, 0.1f,0.002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(0, 500, 9f, -5f, 0.1f,0.002f, 2f, Color.orange));
arrayOfConfetti.add(new Confetti(0, 500, 5f, -3f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(0, 500, 7f, -3f, 0.1f,0.002f, 2f, Color.magenta));
arrayOfConfetti.add(new Confetti(0, 500, 8f, -9f, 0.1f,0.002f, 2f, Color.cyan));
// bottom right corner
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -5f, -5f, 0.1f,0.002f, 2f, Color.red));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -7f, -7f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -9f, -4f, 0.1f,0.0002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -2f, -6f, 0.1f,0.0002f, 2f, Color.pink));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -3f, -5f, 0.1f,0.002f, 2f, Color.red));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -6f, -8f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -4f, -3f, 0.1f,0.0002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -8f, -4f, 0.1f,0.0002f, 2f, Color.pink));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -1f, -5f, 0.1f,0.002f, 2f, Color.red)); //
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -8f, -8f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -6f, -6f, 0.1f,0.0002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -2f, -4f, 0.1f,0.0002f, 2f, Color.pink));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -9f, -5f, 0.1f,0.002f, 2f, Color.red));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -5f, -3f, 0.1f,0.002f, 2f, Color.yellow));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -7f, -3f, 0.1f,0.0002f, 2f, Color.cyan));
arrayOfConfetti.add(new Confetti(main.getWidth(), 500, -8f, -9f, 0.1f,0.0002f, 2f, Color.pink));
}
public void killConfetti() {
// this method removes a confetti when it is out of the screen
for (int i = 0; i < arrayOfConfetti.size(); i++) {
if(arrayOfConfetti.get(i).x < 0 || arrayOfConfetti.get(i).x > main.getWidth()){
arrayOfConfetti.remove(i);
}
else if(arrayOfConfetti.get(i).y < 0 || arrayOfConfetti.get(i).y > main.getHeight()){
arrayOfConfetti.remove(i);
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE){
refreshGun();
isSpacePressed = true;
}
}
}
| true |
4662c74bf476eabcc1ce4950d70aa0a774b7de3b | Java | Neumann789/springboot-learn | /jode-1.1.2/output/com/javosize/agent/memory/StaticVariableSize.java | UTF-8 | 1,690 | 2.578125 | 3 | [] | no_license | /* StaticVariableSize - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
package com.javosize.agent.memory;
public class StaticVariableSize implements Comparable
{
private String className;
private String variableName;
private String type;
private long size;
public StaticVariableSize(String className, String variableName,
String type, long size) {
this.className = className;
this.variableName = variableName;
this.type = type;
this.size = size;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public int compareTo(StaticVariableSize o) {
if (o.getSize() < size)
return 1;
if (o.getSize() > size)
return -1;
return 0;
}
public String toString() {
return new StringBuilder().append("").append(getClassName()).append
(".").append
(getVariableName()).append
("[").append
(getType()).append
("]: ").append
(getSize()).append
("bytes\n").toString();
}
public volatile int compareTo(Object object) {
return compareTo((StaticVariableSize) object);
}
}
| true |
e73c657470222ef2fc5ba3282257874907aaa5b5 | Java | shailuamu/TestAutoThon | /init/testExec.java | UTF-8 | 2,766 | 2.296875 | 2 | [] | no_license | package init;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import Report.Report;
public class testExec {
public static boolean executeVerifyKeyword(String verifyKey, LinkedHashMap<String, String> data) {
boolean status = false;
Method myMethod = null;
Class<?> c = null;
try {
c = Class.forName("Execution.verifyPoints");
Object createInstance = c.newInstance();
Method[] h = c.getMethods();
for (Method r : h) {
if (r.getName().equalsIgnoreCase(verifyKey)) {
int a = r.getParameterCount();
if (a > 0) {
myMethod = c.getDeclaredMethod(verifyKey, LinkedHashMap.class);
status = (Boolean) myMethod.invoke(createInstance, data);
} else {
myMethod = c.getDeclaredMethod(verifyKey);
status = (Boolean) myMethod.invoke(createInstance);
}
}
}
} catch (Exception e) {
Report.log("unable to run keyword");
}
if (status) {
return true;
} else {
return false;
}
}
public static boolean executeV(WebDriver driver,String tckey,LinkedHashMap<String, String> data){
LinkedHashMap<String,String> vReports = new LinkedHashMap<String,String>();
int cc=0,ff=0;
String srNo = data.get("SRNO");
if(Report.isVerify(tckey))
{
Report.addVerifyPoints(tckey,srNo);
LinkedHashMap<String,String> vKeys=Report.getVerifyStatus(tckey);
try{
for(Map.Entry m:vKeys.entrySet()){
String vk = m.getKey().toString();
boolean status =executeVerifyKeyword(vk,data);
if(status){
Report.updateVerifyStatus(tckey, vk, "PASS",srNo);
vReports.put(vk, "PASS");
}else{
Report.updateVerifyStatus(tckey, vk, "FAIL",srNo);
vReports.put(vk, "FAIL");
}
}
}catch(Exception e){
Report.log(e.getMessage());
}
finally{
for(Map.Entry c:vReports.entrySet()){
String statusC = c.getValue().toString();
if(statusC.equalsIgnoreCase("PASS")){
cc++;
}
if(statusC.equalsIgnoreCase("FAIL")){
ff++;
}
}
if(ff>0){
data.replace("STATUS", "FAIL");
data.replace("COMMENT", "Verify points fail");
String screenshotName = tckey + "_" + srNo;
data.put("SCREENSHOT", screenshotName);
Report.takeScreenShot(driver,screenshotName);
}
else{
data.replace("STATUS", "PASS");
data.replace("COMMENT", "Verify points pass");
String screenshotName = tckey + "_" + srNo;
data.put("SCREENSHOT", screenshotName);
Report.takeScreenShot(driver,screenshotName);
}
Report.updateFormStatus(tckey, data);
}
}
if(ff>0){
return false;
}
else {
return true;
}
}
}
| true |
5de334d10166373f290fa28118f3fca411aca643 | Java | 2170987947/JavaWeb | /2020_1110shopping/src/Servlet/AddServlet.java | UTF-8 | 1,411 | 2.40625 | 2 | [] | no_license | package Servlet;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import vo.book;
/**
* Servlet implementation class AddServlet
*/
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
HttpSession session=request.getSession();
HashMap books=(HashMap) session.getAttribute("books");
String bookno=request.getParameter("bookno");
String bookname=request.getParameter("bookname");
String strBooknumber=request.getParameter("booknumber");
book booki=new book();
booki.setBookno(bookno);
booki.setBookname(bookname);
int booknumber=Integer.parseInt(strBooknumber);
booki.setBooknumber(booknumber);
books.put(bookno, booki);
response.sendRedirect("showCart.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
eaa34109d48f9e7873a14afe11a38b540d8b9b7c | Java | roilat/roilat_study_code | /roilat-study/roilat-study-java/src/main/java/cn/roilat/study/j2ee/http/clientpool/Signature.java | UTF-8 | 6,963 | 2.234375 | 2 | [] | no_license | package cn.roilat.study.j2ee.http.clientpool;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
/**
* 璇锋眰鍙傛暟瀹夊叏鍔犵绫� Created by guowei.lu on 2016-9-29.
*/
public class Signature {
private static final char SEPERATOR = (char) 1;
private static final char DELIMITER = '\n';
private static final byte[] EMPTY_BYTES = new byte[] {};
private static final String HMAC_SHA256 = "HmacSHA256";
private static final String MD5 = "MD5";
// 鐢ㄦ潵灏嗗瓧鑺傝浆鎹㈡垚 16 杩涘埗琛ㄧず鐨勫瓧绗�
private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
private String method;
private String timestamp;
private String nonce;
private String path;
private TreeMap<String, String> parameter;
private String secretKey;
private Signature(){
parameter = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
}
public static Signature newInstance() {
return new Signature();
}
public Signature path(String path) {
this.path = path;
return this;
}
public Signature method(String method) {
this.method = method;
return this;
}
public Signature secretKey(String secretKey) {
this.secretKey = secretKey;
return this;
}
/**
* hmacsha256鍔犵绠楁硶
*
* @return
*/
public String sign() {
// 缁勮绛惧悕涓�
ByteArrayOutputStream output = this.buildByteStream();
return hmacSha256(output.toByteArray());
}
/**
* md5鍔犵绠楁硶
*
* @return
*/
public String signMd5() {
// 缁勮绛惧悕涓�
ByteArrayOutputStream output = this.buildByteStream();
// 鏈�鍚庡姞涓婂瘑閽ヤ覆
output.write(DELIMITER);
try {
output.write(this.secretKey.getBytes(Consts.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
return md5hex(output.toByteArray());
}
/**
* 鎸夊姞绛剧畻娉曡姹傜粍瑁呯鍚嶄覆
*
* @return
*/
private ByteArrayOutputStream buildByteStream() {
byte[] parameterBytes = assembleParameter();
this.timestamp = this.currentNow();
this.nonce = StringUtils.join(String.valueOf(System.nanoTime()), RandomStringUtils.randomNumeric(4));
// 缁勮绛惧悕涓�
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
output.write(this.method.getBytes(Consts.UTF_8));
output.write(DELIMITER);
output.write(this.timestamp.getBytes(Consts.UTF_8));
output.write(DELIMITER);
output.write(this.nonce.getBytes(Consts.UTF_8));
output.write(DELIMITER);
output.write(this.path.getBytes(Consts.UTF_8));
if (ArrayUtils.isNotEmpty(parameterBytes)) {
output.write(DELIMITER);
output.write(parameterBytes);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return output;
}
public void addParameter(String name, String value) {
if (StringUtils.isEmpty(value) || StringUtils.isEmpty(name)) {
return;
}
if (parameter.containsKey(name)) {
StringBuilder sb = new StringBuilder();
sb.append(parameter.get(name)).append(SEPERATOR).append(value);
parameter.put(name, sb.toString());
return;
}
parameter.put(name, value);
}
private byte[] assembleParameter() {
if (parameter.isEmpty()) {
return EMPTY_BYTES;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : parameter.entrySet()) {
if (StringUtils.contains(entry.getValue(), SEPERATOR)) {
String[] arr = StringUtils.split(entry.getValue(), SEPERATOR);
List<String> list = new ArrayList<String>();
for (String element : arr) {
list.add(element);
}
Collections.sort(list);
for (String str : list) {
sb.append("&").append(String.format("%s=%s", entry.getKey(), str));
}
} else {
sb.append("&").append(String.format("%s=%s", entry.getKey(), entry.getValue()));
}
}
String content = sb.substring(1);
return content.getBytes(Consts.UTF_8);
}
private String currentNow() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_DATE;
return dateTimeFormatter.toString();
}
private String hmacSha256(byte[] message) {
byte[] secretKeyBytes = this.secretKey.getBytes(Consts.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, HMAC_SHA256);
Mac mac;
try {
mac = Mac.getInstance(HMAC_SHA256);
mac.init(secretKeySpec);
mac.update(message);
byte[] digestBytes = Base64.encodeBase64(mac.doFinal());
return new String(digestBytes, Consts.UTF_8);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}
private String md5hex(byte[] message) {
try {
MessageDigest messageDigest = MessageDigest.getInstance(MD5);
messageDigest.update(message);
byte[] digest = messageDigest.digest();
int j = digest.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = digest[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getNonce() {
return nonce;
}
public String getTimestamp() {
return timestamp;
}
}
| true |
f2a59d5d3a6a7a15a6c02e6deefe769bf7cf201c | Java | ynsamzni/java-source-code-management-tool | /src/java_source_code_management_tool/model/dto/Version.java | UTF-8 | 3,529 | 3.234375 | 3 | [] | no_license | package java_source_code_management_tool.model.dto;
import java.util.ArrayList;
import java.sql.Timestamp;
/**
* This class consists of methods that operate on or return a version.
*
* @author Jordan and Yanis (Group 4 - Pair 10)
*
*/
public class Version
{
private String versionNumber;
private String author;
private Timestamp date;
private ArrayList<Description> listDescriptions = new ArrayList<Description>();
/**
* Constructs a new version.
*/
public Version()
{
listDescriptions= new ArrayList<Description>();
}
/**
* Constructs a new version with the specified version number and author.
*
* @param versionNumber the version number.
* @param author the author username.
*/
public Version(String versionNumber, String author)
{
this.versionNumber = versionNumber;
this.author = author;
date = new Timestamp(System.currentTimeMillis());
}
/**
* Constructs a new version with the specified version number, author and date.
*
* @param versionNumber the version number.
* @param author the author username.
* @param date the version date.
*/
public Version(String versionNumber, String author, Timestamp date)
{
this.versionNumber = versionNumber;
this.author = author;
this.date = date;
}
/**
* Sets the the version number.
*
* @param versionNumber the version number.
*/
public void setVersion(String versionNumber)
{
this.versionNumber = versionNumber;
}
/**
* Returns the saved version number.
*
* @return the saved version number.
*/
public String getVersion()
{
return versionNumber;
}
/**
* Sets the author username.
*
* @param author the author username.
*/
public void setAuthor(String author)
{
this.author = author;
}
/**
* Returns the saved author username.
*
* @return the saved author username.
*/
public String getAuthor()
{
return author;
}
/**
* Sets the version date.
*
* @param date the version date.
*/
public void setDate(Timestamp date)
{
this.date = date;
}
/**
* Returns the saved version date.
*
* @return the saved version date.
*/
public Timestamp getDate()
{
return date;
}
/**
* Sets the list of the descriptions of the version.
*
* @param listDescriptions the list of the descriptions of the version.
*/
public void setListDescriptions(ArrayList<Description> listDescriptions)
{
this.listDescriptions = listDescriptions;
}
/**
* Returns the saved list of the descriptions of the version.
*
* @return the saved list of the descriptions of the version.
*/
public ArrayList<Description> getListDescriptions()
{
return listDescriptions;
}
/**
* Adds the specified description to the version.
*
* @param description the description to add to the version.
*/
public void addDescription(Description description)
{
listDescriptions.add(description);
}
/**
* Returns from the saved list of version descriptions the description stored at the specified index number.
*
* @param index the index number at which the desired description is stored in the list of version descriptions.
* @return the specified description of the version.
*/
public Description getDescription(int index)
{
return listDescriptions.get(index);
}
/**
* Translates the object to String for display.
*
* @return object translated to String for display.
*/
public String toString()
{
return "versionNumber: " + versionNumber + " | author: " + author + " | date: " + date;
}
}
| true |
5f3968e374d80ff818704816888733fac128df69 | Java | osman705/jessrobocode | /brain/src/events/BulletHit.java | UTF-8 | 581 | 2.421875 | 2 | [] | no_license | package events;
import java.io.Serializable;
public class BulletHit extends Event implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7807252159144889448L;
double energy;
public BulletHit(double energy, String name) {
super();
this.energy = energy;
this.name = name;
}
public double getEnergy() {
return energy;
}
public void setEnergy(double energy) {
this.energy = energy;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String name;
}
| true |
0667ee923e45e68f61a6045502294ee0ed3ade73 | Java | martinezcarlos/mssc-beer-service | /src/main/java/guru/sfg/brewery/service/service/brewing/BrewingService.java | UTF-8 | 1,516 | 2.234375 | 2 | [] | no_license | package guru.sfg.brewery.service.service.brewing;
import guru.sfg.brewery.model.events.BrewBeerEvent;
import guru.sfg.brewery.service.config.JmsConfig;
import guru.sfg.brewery.service.domain.Beer;
import guru.sfg.brewery.service.repository.BeerRepository;
import guru.sfg.brewery.service.service.inventory.BeerInventoryService;
import guru.sfg.brewery.service.web.mapper.BeerMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Log4j2
@Service
@RequiredArgsConstructor
public class BrewingService {
private final BeerRepository beerRepository;
private final BeerInventoryService beerInventoryService;
private final JmsTemplate jmsTemplate;
private final BeerMapper beerMapper;
@Scheduled(fixedRate = 5000) // Every 5 sec
public void checkForLowInventory() {
beerRepository.findAll().forEach(this::checkInventory);
}
private void checkInventory(final Beer b) {
final Integer onHandInventory = beerInventoryService.getOnHandInventory(b.getId());
log.debug("Min on hand is {}", b.getMinOnHand());
log.debug("Inventory is {}", onHandInventory);
if (b.getMinOnHand() >= onHandInventory) {
log.info("Requesting new inventory for beer {}", b.getName());
jmsTemplate.convertAndSend(JmsConfig.BREWING_REQUEST_QUEUE,
new BrewBeerEvent(beerMapper.entityToDto(b)));
}
}
}
| true |
84a28024e6fb996a9d3be5fd731e019f32093fd1 | Java | JeikWazAlreadyTaken/Housamo_AuthKey_Switch | /app/src/main/java/com/jeik/authamo/InitActivity.java | UTF-8 | 1,109 | 1.882813 | 2 | [] | no_license | package com.jeik.authamo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class InitActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
//firstStartCheck();
}
private void firstStartCheck() {
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (!isFirstRun) {
startActivity(new Intent(InitActivity.this, MainActivity.class));
}
else
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
public void discordInvite(View view) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://discord.gg/guVeuQr")));
}
public void yeetOn(View view) {
startActivity(new Intent(InitActivity.this, MainActivity.class));
}
}
| true |
6b4b047bb4347d52d8038623629171f9a9ef43dd | Java | jhoon12/study_java | /자바수업/자바수업2/0709_base/src/num3.java | UTF-8 | 442 | 3.609375 | 4 | [] | no_license | import java.util.Scanner;
public class num3 {
public static void main(String[] args) {
System.out.println(factorial(5));
System.out.println(factorial(1,5));
System.out.println(factorial(3,5));
System.out.println(factorial(10,5));
}
static int factorial(int x) {
int r = 1;
while(x > 0) {
r *= x--;
}
return r;
}
static int factorial(int x, int y) {
int r = 1;
while(x <= y) {
r *= x++;
}
return r;
}
}
| true |
857db9133ed4bf1bc49105e6bbb188b24e921fcc | Java | xinpengfa/work | /cmfz_admin/src/main/java/com/wcf/controller/ManagerController.java | UTF-8 | 3,170 | 2.3125 | 2 | [] | no_license | package com.wcf.controller;
import com.wcf.service.ManagerService;
import com.wcf.utils.ImageUtil;
import com.wcf.vo.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.net.URLEncoder;
@Controller
@RequestMapping("/manager")
public class ManagerController {
@Resource
private ManagerService managerService;
@ResponseBody
@RequestMapping("/login")
public Result login(HttpSession session,String name,String password,boolean ischeck,String code,HttpServletResponse response){
Result result = new Result();
String validationCode = (String) session.getAttribute("validationCode");
System.out.println(code);
System.out.println(validationCode);
System.out.println(ischeck);
// 通过安全工具类获取主体对象
Subject subject = SecurityUtils.getSubject();
if(validationCode.equalsIgnoreCase(code)){
try {
subject.login(new UsernamePasswordToken(name,password,ischeck)); // true 使用记住我的功能 false 不使用
result.setSuccess(true);
/*if(ischeck){
String encode = URLEncoder.encode(manager.getName(), "utf-8");
Cookie cookie = new Cookie("name",encode);
//setPath "/" 代表cookie可以应用于整个项目
cookie.setPath("/");
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
} else{
Cookie cookie = new Cookie("name",null);
cookie.setMaxAge(0);
}*/
return result;
} catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
result.setMessage(e.getMessage());
return result;
}
} else{
result.setSuccess(false);
result.setMessage("验证码输入错误");
return result;
}
}
@RequestMapping("/valicode")
public void valicode(HttpServletResponse response, HttpSession session) throws Exception{
//利用图片工具生成图片
//第一个参数是生成的验证码,第二个参数是生成的图片
Object[] objs = ImageUtil.createImage();
//将验证码存入Session
session.setAttribute("validationCode",objs[0]);
//将图片输出给浏览器
BufferedImage image = (BufferedImage) objs[1];
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
}
}
| true |
5432534c93ed9f509858d61553314d58ea010de3 | Java | getolly/OllyCreditBhamashah | /app/src/main/java/com/ollycredit/ui/onboarding/signup/verify_email/VerifyEmailActivity.java | UTF-8 | 4,313 | 1.789063 | 2 | [] | no_license | package com.ollycredit.ui.onboarding.signup.verify_email;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ollycredit.R;
import com.ollycredit.api.local.PreferencesHelper;
import com.ollycredit.api.model.ResponseModel;
import com.ollycredit.base.BaseActivity;
import com.ollycredit.ui.card.card_home.CardHomeActivity;
import com.ollycredit.utils.GlobalConstants;
import com.squareup.picasso.Picasso;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
public class VerifyEmailActivity extends BaseActivity implements VerifyEmailView {
@BindView(R.id.btn_verify_email_already_confirm)
Button btnAlreadyConfirm;
@BindView(R.id.btn_verify_email_resend_edit_mail)
Button btnEmailResend;
@BindView(R.id.card_img_mask)
ImageView cardImage;
@BindView(R.id.tv_user_email)
TextView tvUserEmail;
@Inject
PreferencesHelper preferencesHelper;
@Inject
VerifyEmailPresenter verifyEmailPresenter;
private BroadcastReceiver networkReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verify);
getActivityComponent().inject(this);
ButterKnife.bind(this);
verifyEmailPresenter.attachView(this);
setUp();
}
@OnClick(R.id.btn_verify_email_already_confirm)
public void onClick(View view) {
showProgressDialog("Please wait ...");
verifyEmailPresenter.getUserInfo(preferencesHelper.getToken());
}
@Override
public void onBackPressed() {
finish();
}
@OnClick(R.id.btn_verify_email_resend_edit_mail)
public void resendEmail() {
verifyEmailPresenter.resendEmail(preferencesHelper.getToken());
}
@Override
protected void onPause() {
super.onPause();
hideErrorConnection();
}
@Override
protected void onStart() {
super.onStart();
registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(networkReceiver);
}
@Override
protected void setUp() {
tvUserEmail.setText("Your Card is now being generated. Meanwhile check your inbox and verify your email ID \n("+preferencesHelper.getString(GlobalConstants.PREF_USER_EMAIL_KEY,"")+")");
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isOnline = isOnline(VerifyEmailActivity.this);
if (isOnline) {
hideErrorConnection();
} else {
showErrorConnection();
}
}
};
Picasso.with(this).load(R.mipmap.card_image_1024)
.transform(new CropCircleTransformation()).into((ImageView) findViewById(R.id.card_img_mask));
}
@Override
public void reqFailed(int failedCode, String message) {
hideProgressDialog();
showDialogBox(message);
}
@Override
public void getUserSuccess(ResponseModel responseModel) {
hideProgressDialog();
if (responseModel.getUser().getEmailValidated() == 1) {
Intent i;
i = new Intent(this, CardHomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
} else {
showDialogBox("Email not verified");
}
}
@Override
public void resendEmailSuccess(ResponseModel responseModel) {
Toast.makeText(this, "mail sent!", Toast.LENGTH_SHORT).show();
}
}
| true |
951c69dd4f7015e70da85543b653bfcd87e15551 | Java | Pavithra-Krish/product1 | /ECOM/product-integration-models/src/main/java/com/services/product/integration/models_c1/request/RESTGetBulkProductItemRequest.java | UTF-8 | 605 | 1.929688 | 2 | [] | no_license | package com.services.product.integration.models_c1.request;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;
/**
* Created by Pavithra on 3/12/14.
*/
public class RESTGetBulkProductItemRequest {
private List<RESTBulkProductRequest> products;
@XmlElement(name = "product")
@XmlElementWrapper(name = "products")
public List<RESTBulkProductRequest> getProducts() {
return products;
}
public void setProducts(final List<RESTBulkProductRequest> products) {
this.products = products;
}
}
| true |
b8ae955118108ca933db7afa9565214de87fb30e | Java | Indranil03/TMA | /src/main/java/com/tma/Application.java | UTF-8 | 696 | 1.8125 | 2 | [] | no_license | package com.tma;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* Spring Boot Main Application
*
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
// SpringApplication.run(Application.class, args);
ApplicationContext ctx = SpringApplication.run(Application.class, args);
DispatcherServlet dispatcherServlet = (DispatcherServlet) ctx.getBean("dispatcherServlet");
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
}
}
| true |
aa9cc961e7f1770ea7788d15915126cdcd6f911e | Java | airidas338/mc-dev | /src/main/java/net/minecraft/server/BlockPistonMoving.java | UTF-8 | 5,597 | 2.078125 | 2 | [] | no_license | package net.minecraft.server;
import java.util.Random;
public class BlockPistonMoving extends BlockContainer {
public static final beu a = BlockPistonExtension.a;
public static final bev b = BlockPistonExtension.b;
public BlockPistonMoving() {
super(Material.PISTON);
this.j(this.L.b().a(a, EnumFacing.NORTH).a(b, bdu.a));
this.c(-1.0F);
}
public TileEntity a(World var1, int var2) {
return null;
}
public static TileEntity a(IBlockData var0, EnumFacing var1, boolean var2, boolean var3) {
return new TileEntityPiston(var0, var1, var2, var3);
}
public void remove(World var1, Location var2, IBlockData var3) {
TileEntity var4 = var1.getTileEntity(var2);
if(var4 instanceof TileEntityPiston) {
((TileEntityPiston)var4).h();
} else {
super.remove(var1, var2, var3);
}
}
public boolean canPlace(World var1, Location var2) {
return false;
}
public boolean canPlace(World var1, Location var2, EnumFacing var3) {
return false;
}
public void postBreak(World var1, Location var2, IBlockData var3) {
Location var4 = var2.a(((EnumFacing)var3.b(a)).d());
IBlockData var5 = var1.getData(var4);
if(var5.c() instanceof BlockPiston && ((Boolean)var5.b(BlockPiston.b)).booleanValue()) {
var1.setAir(var4);
}
}
public boolean c() {
return false;
}
public boolean d() {
return false;
}
public boolean interact(World var1, Location var2, IBlockData var3, EntityHuman var4, EnumFacing var5, float var6, float var7, float var8) {
if(!var1.isStatic && var1.getTileEntity(var2) == null) {
var1.setAir(var2);
return true;
} else {
return false;
}
}
public Item a(IBlockData var1, Random var2, int var3) {
return null;
}
public void dropNaturally(World var1, Location var2, IBlockData var3, float var4, int var5) {
if(!var1.isStatic) {
TileEntityPiston var6 = this.e(var1, var2);
if(var6 != null) {
IBlockData var7 = var6.b();
var7.c().b(var1, var2, var7, 0);
}
}
}
public MovingObjectPosition a(World var1, Location var2, Vec3D var3, Vec3D var4) {
return null;
}
public void doPhysics(World var1, Location var2, IBlockData var3, Block var4) {
if(!var1.isStatic) {
var1.getTileEntity(var2);
}
}
public AxisAlignedBB a(World var1, Location var2, IBlockData var3) {
TileEntityPiston var4 = this.e(var1, var2);
if(var4 == null) {
return null;
} else {
float var5 = var4.a(0.0F);
if(var4.d()) {
var5 = 1.0F - var5;
}
return this.a(var1, var2, var4.b(), var5, var4.e());
}
}
public void updateShape(IBlockAccess var1, Location var2) {
TileEntityPiston var3 = this.e(var1, var2);
if(var3 != null) {
IBlockData var4 = var3.b();
Block var5 = var4.c();
if(var5 == this || var5.getMaterial() == Material.AIR) {
return;
}
float var6 = var3.a(0.0F);
if(var3.d()) {
var6 = 1.0F - var6;
}
var5.updateShape(var1, var2);
if(var5 == Blocks.PISTON || var5 == Blocks.PISTON_STICKEY) {
var6 = 0.0F;
}
EnumFacing var7 = var3.e();
this.B = var5.z() - (double)((float)var7.g() * var6);
this.C = var5.B() - (double)((float)var7.h() * var6);
this.D = var5.D() - (double)((float)var7.i() * var6);
this.E = var5.A() - (double)((float)var7.g() * var6);
this.F = var5.C() - (double)((float)var7.h() * var6);
this.G = var5.E() - (double)((float)var7.i() * var6);
}
}
public AxisAlignedBB a(World var1, Location var2, IBlockData var3, float var4, EnumFacing var5) {
if(var3.c() != this && var3.c().getMaterial() != Material.AIR) {
AxisAlignedBB var6 = var3.c().a(var1, var2, var3);
if(var6 == null) {
return null;
} else {
double var7 = var6.a;
double var9 = var6.b;
double var11 = var6.c;
double var13 = var6.d;
double var15 = var6.e;
double var17 = var6.f;
if(var5.g() < 0) {
var7 -= (double)((float)var5.g() * var4);
} else {
var13 -= (double)((float)var5.g() * var4);
}
if(var5.h() < 0) {
var9 -= (double)((float)var5.h() * var4);
} else {
var15 -= (double)((float)var5.h() * var4);
}
if(var5.i() < 0) {
var11 -= (double)((float)var5.i() * var4);
} else {
var17 -= (double)((float)var5.i() * var4);
}
return new AxisAlignedBB(var7, var9, var11, var13, var15, var17);
}
} else {
return null;
}
}
private TileEntityPiston e(IBlockAccess var1, Location var2) {
TileEntity var3 = var1.getTileEntity(var2);
return var3 instanceof TileEntityPiston?(TileEntityPiston)var3:null;
}
public IBlockData a(int var1) {
return this.P().a(a, BlockPistonExtension.b(var1)).a(b, (var1 & 8) > 0?bdu.b:bdu.a);
}
public int c(IBlockData var1) {
byte var2 = 0;
int var3 = var2 | ((EnumFacing)var1.b(a)).a();
if(var1.b(b) == bdu.b) {
var3 |= 8;
}
return var3;
}
protected bed e() {
return new bed(this, new bex[]{a, b});
}
}
| true |
81f7e64dd31f4375630d642ebce6162c73b5c32d | Java | bert-janzwanepol/Spotitube-REST-API | /src/main/java/oose/dea/spotitube/dao/ITrackDAO.java | UTF-8 | 1,834 | 2.78125 | 3 | [] | no_license | package oose.dea.spotitube.dao;
import oose.dea.spotitube.domain.Track;
import java.util.ArrayList;
public interface ITrackDAO
{
/**
* Gets all tracks in a playlists.
* @param playlistid The id of the playlist that contains the tracks
* @return All tracks in a specific playlist.
*/
public ArrayList<Track> getTracks(int playlistid);
/**
* Gets all tracks from the database.
* @return All tracks whether or not they are in a playlist
*/
public ArrayList<Track> getTracks();
/**
* Gets all tracks not in a playlists.
* @param playlistid The id of the playlist that contains tracks that need to be excluded.
* @return All tracks not in a specific playlist.
*/
public ArrayList<Track> getTracksNotInPlayList(int playlistid);
/**
* Adds a track to a playlist
* @param trackid The id of the track that will be added
* @param playlistid The id of the playlist that the track will be added to.
* @param offlineAvailable A flag that will determine whether or not a tracks is available without internet connection.
* @param username The username of the user doing the request. Used to check if the user owns the playlist.
* @return {@link #getTracks(int)}
*/
public ArrayList<Track> addTrack(int trackid, int playlistid, boolean offlineAvailable, String username);
/**
* Deletes a track from a playlist
* @param username The username of the user doing the request. Used to check if the user owns the playlist.
* @param playlistid The id of the playlist that the track will be deleted from.
* @param trackid The id of the track that will be deleted.
* @return {@link #getTracks(int)}
*/
public ArrayList<Track> deleteTrack(String username, int playlistid, int trackid);
}
| true |
f3f1a48324f55032dd57d3af483d55dfabe63981 | Java | vgaray/sic-tintegro | /pivo-dominio/src/main/java/pe/com/tintegro/dto/response/ListaMarcaTelefonoResponse.java | UTF-8 | 434 | 2.03125 | 2 | [] | no_license | package pe.com.tintegro.dto.response;
import java.util.List;
import pe.com.tintegro.dominio.MarcaTelefono;
public class ListaMarcaTelefonoResponse extends ResponseBase
{
private List<MarcaTelefono> marcaTelefonoList;
public List<MarcaTelefono> getMarcaTelefonoList()
{
return marcaTelefonoList;
}
public void setMarcaTelefonoList(List<MarcaTelefono> marcaTelefonoList)
{
this.marcaTelefonoList = marcaTelefonoList;
}
} | true |
3df3a269c6fbdfe3a42f14559ddbd195f01d3b95 | Java | andonghyuk/javastudy | /src/s0624/StringArray2.java | UTF-8 | 340 | 3.109375 | 3 | [] | no_license | package s0624;
public class StringArray2 {
public static void main(String[] args) {
String str="1,24,52,346,85,6,";
String[] strs = str.split(",");
int[] nums = new int[strs.length];
for(int i=0;i<strs.length;i++) {
nums[i] = Integer.parseInt(strs[i]);
}
for(int num:nums) {
System.out.println(num);
}
}
}
| true |
ab9959830db9ede9f83bc519d94fc81f446d1ea0 | Java | renaudpawlak/tura | /org.eclipse.e4.xwt/bundles/org.eclipse.e4.xwt.tools.ui.designer.core/src/org/eclipse/e4/xwt/tools/ui/designer/core/editor/dnd/DropTargetAdapter.java | UTF-8 | 3,096 | 2.140625 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2006, 2010 Soyatec (http://www.soyatec.com) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Soyatec - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.xwt.tools.ui.designer.core.editor.dnd;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
/**
* @author jliu (jin.liu@soyatec.com)
*/
public class DropTargetAdapter implements DropTargetListener {
private List<DropAdapter> dropAdapters = new ArrayList<DropAdapter>();
private DropAdapter acceptAdapter;
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#dragOver(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void dragOver(DropTargetEvent event) {
updateAcceptAdapter();
if (acceptAdapter != null) {
acceptAdapter.dragOver(event);
}
}
/**
* @param event
*/
private void updateAcceptAdapter() {
for (DropAdapter drop : dropAdapters) {
if (drop.isAccept()) {
acceptAdapter = drop;
break;
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#dropAccept(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void dropAccept(DropTargetEvent event) {
if (acceptAdapter != null) {
acceptAdapter.dropAccept(event);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#drop(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void drop(DropTargetEvent event) {
if (acceptAdapter != null) {
acceptAdapter.drop(event);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void dragEnter(DropTargetEvent event) {
updateAcceptAdapter();
if (acceptAdapter != null) {
acceptAdapter.dragEnter(event);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void dragOperationChanged(DropTargetEvent event) {
updateAcceptAdapter();
if (acceptAdapter != null) {
acceptAdapter.dragOperationChanged(event);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.dnd.DropTargetAdapter#dragLeave(org.eclipse.swt.dnd.DropTargetEvent)
*/
public void dragLeave(DropTargetEvent event) {
if (acceptAdapter != null) {
acceptAdapter.dragLeave(event);
}
}
public void addDropAdapter(DropAdapter adapter) {
dropAdapters.add(adapter);
}
/**
* @param dndAdapters
* the dndAdapters to set
*/
public void setDropAdapters(List<DropAdapter> dndAdapters) {
this.dropAdapters = dndAdapters;
}
/**
* @return the dndAdapters
*/
public List<DropAdapter> getDropAdapters() {
return dropAdapters;
}
}
| true |
f8aa85af2872d2df396da99788b8bd6b99804974 | Java | zyao89/ZRouter | /zrouter-api/src/main/java/com/zyao89/zrouter/inter/ILogger.java | UTF-8 | 651 | 2.046875 | 2 | [] | no_license | package com.zyao89.zrouter.inter;
/**
* Created by zyao89 on 2017/3/5.
* Contact me at 305161066@qq.com or zyao89@gmail.com
* For more projects: https://github.com/zyao89
*/
public interface ILogger
{
enum STATUS
{
INFO, DEBUG, WARN, ERROR, FULL, NONE;
}
void showStackTrace(boolean isShowStackTrace);
void d(String tag, String message);
void d(String message);
void i(String tag, String message);
void i(String message);
void w(String tag, String message);
void w(String message);
void e(String tag, String message);
void e(String message);
void z(String message);
String getCurrTag();
}
| true |
8950121c55ded6e01bdc7de4f39c2b8f0f1273bd | Java | GreenHand-zmy/xblog | /src/main/java/service/Impl/PostsServiceImpl.java | UTF-8 | 6,722 | 2.40625 | 2 | [] | no_license | package service.Impl;
import dao.Impl.PostDaoImpl;
import dao.PostDao;
import service.PostsService;
import bean.Post;
import constant.PostStatusConstant;
import constant.XBlogConstant;
import utils.PageBean;
import java.util.List;
import java.util.stream.Collectors;
import static utils.CheckUtil.check;
/**
* Created by Fang on 2018/5/21.
*/
public class PostsServiceImpl implements PostsService {
PostDao postDao = new PostDaoImpl();
/**
* 添加文章
*
* @param post 文章实体
* @return
*/
@Override
public int addPost(Post post) {
int num1 = postDao.isExits(post.getId());
check(num1 == 0, "用户名已存在");
check(post.getAuthorId() != 0, "作者名不能为空");
check(post.getFeatured() != -1, "推荐状态不能为空");
check(post.getStatus() != -1, "文章状态不能为空");
check(post.getWeight() != -1, "置顶状态不能为空");
check(post.getContent() != null, "内容不能为空");
int num = postDao.addPost(post);
return num;
}
/**
* 更新文章
*
* @param post 文章实体
* @return
*/
@Override
public int updatePost(Post post) {
int num1 = postDao.isExits(post.getId());
check(num1 == 1, "用户名不存在");
check(post.getChannelId() != 0, "频道编号不能为空");
check(post.getContent() != null, "内容不能为空");
check(post.getTitle() != null, "标题不能为空");
int num = postDao.updatePost(post);
return num;
}
/**
* 删除文章
*
* @param id
* @return
*/
@Override
public int deletePost(Long id) {
Post post = postDao.getPost(id);
check(post != null, "该文章不存在");
post.setStatus(PostStatusConstant.DELETED_STATUS);
return postDao.updatePost(post);
}
/**
* 修改文章点赞数
*
* @param post 文章实体
* @return
*/
@Override
public int updatePostFavors(Post post) {
int num = postDao.updatePostFavors(post);
return num;
}
/**
* 修改文章阅读数
*
* @param post 文章实体
* @return
*/
@Override
public int updatePostViews(Post post) {
int num = postDao.updatePostViews(post);
return num;
}
/**
* 修改文章评论数
*
* @param post 文章实体
* @return
*/
@Override
public int updatePostComments(Post post) {
int num = postDao.updatePostComments(post);
return num;
}
/**
* 按文章标题查找
*
* @param title 标题
* @return
*/
@Override
public List<Post> getPostTitle(String title) {
List<Post> list = postDao.getPostTitle(title);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章作者id查找
*
* @param authorId 作者id
* @return
*/
@Override
public List<Post> getPostAuthorId(Long authorId) {
List<Post> list = postDao.getPostAuthorId(authorId);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章栏目查询
*
* @param channel 栏目
* @return
*/
@Override
public List<Post> getChannelPosts(Long channel) {
List<Post> list = postDao.getChannelPosts(channel);
check(list != null, "无查询结果");
return list;
}
/**
* 查询所有文章
*
* @return
*/
@Override
public List<Post> getAllPosts() {
List<Post> list = postDao.getAllPosts();
check(list != null, "无查询结果");
return list;
}
/**
* 按文章时间顺序查询
*
* @param LIMIT 条数
* @return
*/
@Override
public List<Post> findNewPostsLimit(int LIMIT) {
List<Post> list = postDao.findNewPostsLimit(LIMIT);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章点赞数从多到少查询
*
* @param LIMIT 条数
* @return
*/
@Override
public List<Post> findNewPostsLimit2(int LIMIT) {
List<Post> list = postDao.findNewPostsLimit2(LIMIT);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章评论数从多到少查询
*
* @param LIMIT 条数
* @return
*/
@Override
public List<Post> findNewPostsLimit3(int LIMIT) {
List<Post> list = postDao.findNewPostsLimit3(LIMIT);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章阅读数数从多到少查询
*
* @param LIMIT 条数
* @return
*/
@Override
public List<Post> findNewPostsLimit4(int LIMIT) {
List<Post> list = postDao.findNewPostsLimit4(LIMIT);
check(list != null, "无查询结果");
return list;
}
/**
* 按文章id查询
*
* @param id 文章id
* @return
*/
@Override
public Post getPost(Long id) {
check(id != null, "查找文章必须输入文章编号");
Post post = postDao.getPost(id);
return post;
}
@Override
public PageBean<Post> findByPage(int pageIndex, int pageSize, Long channelId, String orderBy) {
Integer totalRecords;
// 如果频道不为空查找该频道下所有文章的数量
if (channelId != null) {
totalRecords = postDao.countByChannelId(channelId);
}
// 如果为空查询所有文章的数量
else {
totalRecords = postDao.countAll();
}
// 构造分页对象
PageBean<Post> pageBean = new PageBean<>(totalRecords, pageIndex, pageSize);
// 查询数据库并将数据注入到分页对象中
// 筛选出状态为正常的文章
List<Post> postList = postDao.findByOffsetAndLimit(channelId, pageBean.getOffset(), pageBean.getPageSize(), orderBy)
.stream()
.filter(post -> PostStatusConstant.NORMAL_STATUS.equals(post.getStatus()))
.collect(Collectors.toList());
pageBean.setData(postList);
return pageBean;
}
@Override
public PageBean<Post> findByPage(int pageIndex, Long channelId, String orderBy) {
return findByPage(pageIndex, XBlogConstant.DEFAULT_PAGE_SIZE, channelId, orderBy);
}
@Override
public Integer countAll() {
return postDao.countAll();
}
@Override
public Integer countByAuthorId(Long authorId) {
return postDao.countByAuthorId(authorId);
}
}
| true |
2151017a1d158575e784ae3660e92a5ac2d3e9e1 | Java | d0bz/pt_test | /src/com/playtech/testassignment/client/RandomGeneratorServiceAsync.java | UTF-8 | 266 | 1.671875 | 2 | [] | no_license | package com.playtech.testassignment.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RandomGeneratorServiceAsync {
void getNumbers(int columns, int symbols, AsyncCallback<int[]> callback)
throws IllegalArgumentException;
}
| true |
a991b029133625a3177302031dee5bccfd3d4a3f | Java | caofengbin/BookCode | /2.设计模式之禅/Interceptor/src/test/Client.java | GB18030 | 1,492 | 3.234375 | 3 | [] | no_license | package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class Client {
public static void main(String[] args) {
String expStr = getExpStr();
HashMap<String, Integer> var = getValue(expStr);
Calculator cal = new Calculator(expStr);
System.out.println("Ϊ" + expStr + "=" + cal.run(var));
}
public static String getExpStr() {
try {
System.out.print("ʽ");
return (new BufferedReader(new InputStreamReader(System.in))).readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static HashMap<String, Integer> getValue(String expStr) {
System.out.println("execute getValue(String expStr)");
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(char ch: expStr.toCharArray()) {
if(ch != '+' && ch != '-') {
if(!map.containsKey(String.valueOf(ch))) {
try {
System.out.print("" + ch + "ֵ");
String in = (new BufferedReader(new InputStreamReader(System.in))).readLine();
map.put(String.valueOf(ch), Integer.valueOf(in));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
System.out.println("exit getValue(String expStr)");
return map;
}
}
| true |
ee5a59995e6eb4d824e275979777d02b43578f0d | Java | fernandospr/java-mpns | /src/main/java/com/notnoop/mpns/notifications/CycleTileNotification.java | UTF-8 | 5,543 | 1.8125 | 2 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright 2011, Mahmood Ali.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Mahmood Ali. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Contributed by vhong
*/
package com.notnoop.mpns.notifications;
import static com.notnoop.mpns.internal.Utilities.xmlElement;
import static com.notnoop.mpns.internal.Utilities.xmlElementClear;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import com.notnoop.mpns.DeliveryClass;
import com.notnoop.mpns.MpnsNotification;
import com.notnoop.mpns.internal.Utilities;
public class CycleTileNotification implements MpnsNotification {
private final Builder builder;
private final List<? extends Entry<String, String>> headers;
protected CycleTileNotification(Builder builder, List<? extends Entry<String, String>> headers) {
this.builder = builder;
this.headers = headers;
}
public byte[] getRequestBody() {
return this.builder.toByteArray();
}
public List<? extends Entry<String, String>> getHttpHeaders() {
return Collections.unmodifiableList(this.headers);
}
public static class Builder extends AbstractNotificationBuilder<Builder, CycleTileNotification> {
private String tileId;
private boolean isClear;
private String smallBackgroundImage;
private String[] cycleImages;
private int count;
private String title;
public static final int MAX_IMAGES = 9;
public Builder() {
super("token");
contentType(Utilities.XML_CONTENT_TYPE);
cycleImages = new String[MAX_IMAGES];
}
public Builder tileId(String tileId) {
this.tileId = tileId;
return this;
}
public Builder isClear(boolean clear) {
this.isClear = clear;
return this;
}
public Builder smallBackgroundImage(String smallBackgroundImage) {
this.smallBackgroundImage = smallBackgroundImage;
return this;
}
public Builder cycleImage(int index, String imageName) {
if( index >= MAX_IMAGES ) {
throw new IllegalArgumentException("index " + index + " is greater than maximum allowed cycle images of " + MAX_IMAGES);
}
cycleImages[index] = imageName;
return this;
}
public Builder count(int count) {
this.count = count;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
@Override
protected int deliveryValueOf(DeliveryClass delivery) {
return Utilities.getTileDelivery(delivery);
}
@Override
public CycleTileNotification build() {
return new CycleTileNotification(this, this.headers);
}
protected byte[] toByteArray() {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<wp:Notification xmlns:wp=\"WPNotification\">");
sb.append("<wp:Tile");
if( tileId != null ) {
sb.append(" Id=\"");
sb.append(tileId);
sb.append("\"");
}
sb.append(" Template=\"CycleTile\">");
if( isClear ) {
sb.append(xmlElementClear("SmallBackgroundImage", smallBackgroundImage));
} else {
sb.append(xmlElement("SmallBackgroundImage", smallBackgroundImage));
}
for( int i = 0; i < MAX_IMAGES; i++ ) {
if( cycleImages[i] != null ) {
sb.append(xmlElementClear("CycleImage"+(i+1), cycleImages[i]));
}
}
sb.append(xmlElementClear("Count", ""+count));
sb.append(xmlElementClear("Title", title));
sb.append("</wp:Tile>");
sb.append("</wp:Notification>");
return Utilities.toUTF8(sb.toString());
}
}
}
| true |
4b2b75c1a51fb2c461f33702ad7c5bd38f3fb0df | Java | adminhaoge/anticorrosiveApp | /AndroidStudioProjects/MyAppNotepad/app/src/main/java/com/example/myappnotepad/notepadAdapter.java | UTF-8 | 1,082 | 2.203125 | 2 | [] | no_license | package com.example.myappnotepad;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.myappnotepad.R;
import com.example.myappnotepad.bean.TitleBean;
import java.util.List;
public class notepadAdapter extends ArrayAdapter<TitleBean> {
private int resourceId ;
public notepadAdapter(@NonNull Context context, int resource, @NonNull List<TitleBean> objects) {
super(context, resource, objects);
resourceId = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
TitleBean item = getItem(position);
View view = LayoutInflater.from(parent.getContext()).inflate(resourceId, parent, false);
TextView title = view.findViewById(R.id.tiitle_body);
title.setText(item.getTitle());
return view;
}
}
| true |
71d70ae9c7b7c17245a008c41e95000ca6188138 | Java | joshbasden/TTRServer | /SQL/src/SQL.java | UTF-8 | 7,367 | 2.890625 | 3 | [] | no_license |
import Database.Database;
import Database.DatabaseException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SQL implements Database {
UserDAO userDAO;
CommandDAO commandDAO;
GameDAO gameDAO;
private Connection conn;
public SQL(){
userDAO = new UserDAO();
commandDAO = new CommandDAO();
gameDAO = new GameDAO();
}
@Override
public boolean addNewUser(String s, String s1) throws DatabaseException {
return userDAO.addNewUser(s, s1);
}
@Override
public boolean updateGame(String s, String s1) throws DatabaseException {
return gameDAO.updateGame(s, s1);
}
@Override
public boolean addCommand(String s, String s1, String s2) throws DatabaseException {
return commandDAO.addCommand(s, s1, s2);
}
@Override
public boolean clearCommandsForGame(String s) throws DatabaseException {
return commandDAO.clearCommandsForGame(s);
}
@Override
public int getCommandsLength(String s) throws DatabaseException {
return 0;
}
@Override
public boolean verifyPassword(String s, String s1) throws DatabaseException {
return userDAO.verifyPassword(s, s1);
}
@Override
public boolean openConnection() throws DatabaseException {
try {
Class.forName("org.sqlite.JDBC");
final String CONNECTION_URL = "jdbc:sqlite:SQLDB.db";
// Open a database connection
conn = DriverManager.getConnection(CONNECTION_URL);
userDAO.setConn(conn);
gameDAO.setConn(conn);
commandDAO.setConn(conn);
// Start a transaction
conn.setAutoCommit(false);
return true;
}
catch (SQLException | ClassNotFoundException e) {
throw new DatabaseException("Could not open a connection", e);
}
}
@Override
public boolean closeConnection(boolean commit) throws DatabaseException {
try {
if (commit) {
conn.commit();
}
else {
conn.rollback();
}
conn.close();
conn = null;
return true;
}
catch (SQLException e) {
throw new DatabaseException("error while closing connection", e);
}
}
@Override
public boolean initializeSchemas() throws DatabaseException {
String command = "CREATE TABLE IF NOT EXISTS 'Commands' ('ID' INTEGER PRIMARY KEY AUTOINCREMENT," +
"'Command' BLOB, 'GameName' TEXT, 'Type' TEXT)";
String game = "CREATE TABLE IF NOT EXISTS 'Games' ('GameName' TEXT NOT NULL UNIQUE," +
"'Data' BLOB NOT NULL)";
String user = "CREATE TABLE IF NOT EXISTS 'Users' ('Username' TEXT NOT NULL, 'Password' TEXT NOT NULL)";
try {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(game);
stmt.executeUpdate(command);
stmt.executeUpdate(user);
return true;
}
finally {
if (stmt != null) {
stmt.close();
stmt = null;
}
}
}
catch (SQLException e) {
throw new DatabaseException("createTables failed ", e);
}
}
@Override
public ArrayList<String> getGames() throws DatabaseException {
return gameDAO.getGames();
}
@Override
public ArrayList<String> getCommandsForGame(String s) throws DatabaseException {
return commandDAO.getCommandsForGame(s);
}
@Override
public boolean clear() throws DatabaseException {
String dropComm = "DROP TABLE IF EXISTS Commands";
String dropUser = "DROP TABLE IF EXISTS Users";
String dropGame = "DROP TABLE IF EXISTS Games";
try {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(dropComm);
stmt.executeUpdate(dropUser);
stmt.executeUpdate(dropGame);
return true;
}
finally {
if (stmt != null) {
stmt.close();
stmt = null;
}
}
}
catch (SQLException e) {
throw new DatabaseException("createTables failed ", e);
}
}
@Override
public ArrayList<String> getUsers() throws DatabaseException {
return userDAO.getUsers();
}
public static void main(String[] args){
SQL mongoDB = new SQL();
try{
mongoDB.openConnection();
mongoDB.initializeSchemas();
mongoDB.closeConnection(true);
mongoDB.openConnection();
mongoDB.addCommand("Dallin", "NewUser","bla");
mongoDB.closeConnection(true);
mongoDB.openConnection();
System.out.println();
System.out.println(mongoDB.getCommandsForGame("Dallin").toString());
System.out.println();
mongoDB.closeConnection(true);
}catch (DatabaseException d){
try{
mongoDB.closeConnection(false);
d.printStackTrace();
}catch (DatabaseException e){
}
}
// mongoDB.openConnection();
// mongoDB.initializeSchemas();
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addCommand("weirdo", "blah");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addCommand("Dallin", "blah");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addCommand("Dallin", "b");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addCommand("Dallin", "bla");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addCommand("Dallin", "blahasdfasdfs");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// System.out.println();
// System.out.println(mongoDB.getCommandsForGame("Dallin").toString());
// System.out.println();
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.clearCommandsForGame("Dallin");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// System.out.println();
// System.out.println(mongoDB.getCommandsForGame("weirdo").toString());
// System.out.println();
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.updateGame("dallinajfdlajsd", "jlasdfjlaksfjdTED!");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.updateGame("dadlajsd", "TED!");
// mongoDB.closeConnection();
// mongoDB.openConnection();
// System.out.println(mongoDB.getGames().toString());
// mongoDB.closeConnection();
// mongoDB.openConnection();
// mongoDB.addNewUser("dallin", "boop");
// mongoDB.closeConnection();
}
}
| true |
90831a39249a4e275bdc8d7aaff729578407e418 | Java | mleduque/plugin-java | /codenvy-ext-java/src/main/java/com/codenvy/ide/ext/java/server/format/XMLParser.java | UTF-8 | 1,393 | 1.8125 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.ide.ext.java.server.format;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.HashMap;
import java.util.Map;
/**
* @author Roman Nikitenko
*/
public class XMLParser extends DefaultHandler {
private Map settings;
public Map getSettings() {
return settings;
}
@Override
public void startDocument()
throws SAXException {
settings = new HashMap<String, String>();
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if (qName.equals("setting")) {
String id = attributes.getValue("id");
String value = attributes.getValue("value");
settings.put(id, value);
}
}
}
| true |
b1f84b59b17776b21044f9570d2e7f931a2a954d | Java | mtyurt/spring-core-examples | /src/main/java/profiling/HistoryEnvironmentTest.java | UTF-8 | 798 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package profiling;
import common.Book;
import common.HistoryBook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
/**
* Created by mt on 26.03.2015.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = BookEnvironmentConfig.class)
@ActiveProfiles("hist")
public class HistoryEnvironmentTest {
@Autowired
public Book book;
@Test
public void shouldInitializeHistoryBook() {
assertEquals( book.talk(), HistoryBook.ONCE_UPON_A_TIME);
}
}
| true |
f1db764f54131d38f7075bf3ff4f47b919931e20 | Java | wstzx/goods | /src/com/tzx/filter/Filter.java | UTF-8 | 1,082 | 2.15625 | 2 | [] | no_license | package com.tzx.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(filterName = "Filter", urlPatterns = {"/jsps/order/*", "/jsps/cart/*", "/com/tzx/cart/*", "/com/tzx/order/*"})
public class Filter implements javax.servlet.Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//判断session中的user是否为null
HttpServletRequest request = (HttpServletRequest) req;
Object user = request.getSession().getAttribute("sessionUser");
if (user == null) {
req.setAttribute("code", "error");
req.setAttribute("msg", "您还未登录,请先登录再试!");
req.getRequestDispatcher("/jsps/msg.jsp").forward(req, resp);
} else {
chain.doFilter(req, resp); //放行
}
}
public void init(FilterConfig config) throws ServletException {
}
}
| true |
6ceb38b9c7ca46eafda8bdbfc8a8d0d4ee8eabdb | Java | harishmurari07/Trac | /app/src/main/java/com/example/trac/viewmodel/DeviceStatusViewModel.java | UTF-8 | 1,567 | 2.3125 | 2 | [] | no_license | package com.example.trac.viewmodel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.trac.model.DeviceStatusResponse;
import com.example.trac.repository.DeviceRepository;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
public class DeviceStatusViewModel extends ViewModel {
private MutableLiveData<DeviceStatusResponse> deviceStatusResponseMutableLiveData = new MutableLiveData<>();
private DeviceRepository deviceRepository;
public DeviceStatusViewModel() {
deviceRepository = new DeviceRepository();
}
public void checkDeviceStatus(String deviceId) {
deviceRepository.getDeviceStatus(deviceId).observeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableSingleObserver<DeviceStatusResponse>() {
@Override
public void onSuccess(DeviceStatusResponse deviceStatusResponse) {
deviceStatusResponseMutableLiveData.setValue(deviceStatusResponse);
}
@Override
public void onError(Throwable e) {
deviceStatusResponseMutableLiveData.setValue(null);
}
});
}
public LiveData<DeviceStatusResponse> getDeviceStatus() {
return deviceStatusResponseMutableLiveData;
}
}
| true |
f920d2dcdab281cbf1c006801db86367b7253fa3 | Java | Lava-shr/Java_SpringMVC | /studentreview/src/main/java/com/elec5619/sr/domain/User.java | UTF-8 | 2,937 | 2.34375 | 2 | [] | no_license | package com.elec5619.sr.domain;
import java.io.Serializable;
import java.util.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.*;
import javax.persistence.CascadeType;
/*
* Please set the table attribute to lower letter
*
*/
// POJO CLASS
@Entity
@Table(name="user")
public class User implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Id
@Column(name="username")
private String username;
@Column(name="fullName")
private String fullName;
@Column(name="hashPass")
private String hashPass;
@Column(name="email")
private String email;
@Column(name="phoneNumber")
private String phoneNumber;
@Column(name="age")
private int age;
@Column(name="university")
private String university;
@Column(name="gender")
private String gender;
@Column(name="biography")
private String biography;
@Lob
@Column(name="avatar")
private byte[] avatar;
// @OneToMany(mappedBy="userCourseEnrolled", cascade = CascadeType.ALL)
// Set userCourseEnrolled = new HashSet();
// @OneToMany(mappedBy="userGroup", cascade = CascadeType.ALL)
// Set userGroup = new HashSet();
//
// @OneToMany(mappedBy="userStudentReview", cascade = CascadeType.ALL)
// Set userStudentReview = new HashSet();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getHashPass() {
return this.hashPass;
}
public void setHashPass(String hashPass) {
this.hashPass = hashPass;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getUniversity() {
return this.university;
}
public void setUniversity(String university) {
this.university = university;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBiography() {
return this.biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public byte[] getAvatar() {
return this.avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
}
| true |
f54ccf84775f68236d2275ae0624f4e352dc3383 | Java | aBaranowska/hibernateApp | /src/main/java/com/recglobal/hibernate/rest/OrderService.java | UTF-8 | 17,439 | 2.359375 | 2 | [] | no_license | package com.recglobal.hibernate.rest;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.recglobal.hibernate.model.CardPayment;
import com.recglobal.hibernate.model.ChequePayment;
import com.recglobal.hibernate.model.Order;
import com.recglobal.hibernate.model.OrderStatus;
import com.recglobal.hibernate.model.PaymentStatus;
import com.recglobal.hibernate.model.Product;
import com.recglobal.hibernate.model.ProductOrder;
import com.recglobal.hibernate.model.User;
import com.recglobal.hibernate.rest.json.JsonCardOrder;
import com.recglobal.hibernate.rest.json.JsonChequeOrder;
import com.recglobal.hibernate.rest.json.JsonProductOrder;
@Path("/orders")
public class OrderService extends BaseService {
@POST
@Path("/card")
@Consumes(MediaType.APPLICATION_JSON)
public Response addCardOrder(JsonCardOrder jsonOrder) {
User user = null;
if (jsonOrder.getUserId() != null) {
user = userDao.get(jsonOrder.getUserId());
}
CardPayment payment = null;
if (jsonOrder.getCard() != null) {
payment = new CardPayment(jsonOrder.getCard());
}
List<ProductOrder> products = new ArrayList<ProductOrder>();
if (jsonOrder.getProducts() != null) {
products = getProductOrders(jsonOrder.getProducts());
}
if (user != null && payment != null && products != null) {
Order order = new Order(user, payment, products.toArray(new ProductOrder[products.size()]));
if (jsonOrder.getCreateDate() != null) {
order.setCreateDate(jsonOrder.getCreateDate());
}
if (orderDao.saveOrUpdate(order)) {
int status = STATUS_OK;
String result = "Saved order: " + jsonOrder.toString();
return Response.status(status).entity(result).build();
}
}
int status = STATUS_ERROR;
String result = "Can't save order: " + jsonOrder.toString();
return Response.status(status).entity(result).build();
}
@POST
@Path("/cheque")
@Consumes(MediaType.APPLICATION_JSON)
public Response addChequeOrder(JsonChequeOrder jsonOrder) {
User user = null;
if (jsonOrder.getUserId() != null) {
user = userDao.get(jsonOrder.getUserId());
}
ChequePayment payment = null;
if (jsonOrder.getBank() != null) {
payment = new ChequePayment(jsonOrder.getBank());
}
List<ProductOrder> products = new ArrayList<ProductOrder>();
if (jsonOrder.getProducts() != null) {
products = getProductOrders(jsonOrder.getProducts());
}
if (user != null && payment != null && products != null) {
Order order = new Order(user, payment, products.toArray(new ProductOrder[products.size()]));
if (jsonOrder.getCreateDate() != null) {
order.setCreateDate(jsonOrder.getCreateDate());
}
if (orderDao.saveOrUpdate(order)) {
int status = STATUS_OK;
String result = "Saved order: " + jsonOrder.toString();
return Response.status(status).entity(result).build();
}
}
int status = STATUS_ERROR;
String result = "Can't save order: " + jsonOrder.toString();
return Response.status(status).entity(result).build();
}
@GET
@Path("/card")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonCardOrder> getCardOrders(@QueryParam("page") Integer pageNumber) {
pageNumber = getPageNumber(pageNumber);
List<JsonCardOrder> jsonCardOrders = getJsonCardOrders(null, null, pageNumber);
return jsonCardOrders;
}
@GET
@Path("/cheque")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonChequeOrder> getChequeOrders(@QueryParam("page") Integer pageNumber) {
pageNumber = getPageNumber(pageNumber);
List<JsonChequeOrder> jsonChequeOrders = getJsonChequeOrders(null, null, pageNumber);
return jsonChequeOrders;
}
@GET
@Path("/card/{orderIds}")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonCardOrder> getSelectedCardOrders(@PathParam("orderIds") String orderIds) {
List<Integer> ids = getNumericIds(orderIds);
List<JsonCardOrder> jsonCardOrders = getJsonCardOrders(null, ids, null);
return jsonCardOrders;
}
@GET
@Path("/cheque/{orderIds}")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonChequeOrder> getSelectedChequeOrders(@PathParam("orderIds") String orderIds) {
List<Integer> ids = getNumericIds(orderIds);
List<JsonChequeOrder> jsonChequeOrders = getJsonChequeOrders(null, ids, null);
return jsonChequeOrders;
}
@GET
@Path("card/users/{userIds}")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonCardOrder> getUserCardOrders(@PathParam("userIds") String userIds,
@QueryParam("page") Integer pageNumber) {
pageNumber = getPageNumber(pageNumber);
List<Integer> ids = getNumericIds(userIds);
List<JsonCardOrder> jsonCardOrders = getJsonCardOrders(ids, null, pageNumber);
return jsonCardOrders;
}
@GET
@Path("cheque/users/{userIds}")
@Produces(MediaType.APPLICATION_JSON)
public List<JsonChequeOrder> getUserChequeOrders(@PathParam("userIds") String userIds,
@QueryParam("page") Integer pageNumber) {
pageNumber = getPageNumber(pageNumber);
List<Integer> ids = getNumericIds(userIds);
List<JsonChequeOrder> jsonChequeOrders = getJsonChequeOrders(ids, null, pageNumber);
return jsonChequeOrders;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/top/categories")
@Produces(MediaType.TEXT_PLAIN)
public String getTopCategories() {
List rows = orderDao.getTopCategories();
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/top/products")
@Produces(MediaType.TEXT_PLAIN)
public String getTopProducts() {
List rows = orderDao.getTopProducts();
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/top/users/individual")
@Produces(MediaType.TEXT_PLAIN)
public String getTopUsersIndividual() {
List rows = orderDao.getTopIndividualUsers();
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/top/users/corporation")
@Produces(MediaType.TEXT_PLAIN)
public String getTopUsersCorporation() {
List rows = orderDao.getTopCorporationUsers();
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/category")
@Produces(MediaType.TEXT_PLAIN)
public String getOrderIdsByCategory(@QueryParam("name") String categoryName) {
List rows = orderDao.getByCategory(categoryName);
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/product")
@Produces(MediaType.TEXT_PLAIN)
public String getOrderIdsByProduct(@QueryParam("name") String productName) {
List rows = orderDao.getByProduct(productName);
String result = getText(rows);
return result;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/create")
@Produces(MediaType.TEXT_PLAIN)
public String getOrderIdsByDate(@QueryParam("from") String fromDate, @QueryParam("to") String toDate) {
try {
Date from = Date.valueOf(fromDate);
Date to = Date.valueOf(toDate);
List rows = orderDao.getByDate(from, to);
String result = getText(rows);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@SuppressWarnings("rawtypes")
@GET
@Path("/status")
@Produces(MediaType.TEXT_PLAIN)
public String getOrderIdsByStatus(@QueryParam("name") String orderStatuses) {
List<OrderStatus> statusList = getStatusList(orderStatuses);
List rows = orderDao.getByStatus(statusList.toArray(new OrderStatus[statusList.size()]));
String result = getText(rows);
return result;
}
@PUT
@Path("/{orderIds}/cancel")
public Response cancelOrders(@PathParam("orderIds") String orderIds) {
List<Order> orders = new ArrayList<Order>();
List<Integer> ids = getNumericIds(orderIds);
for (Integer id : ids) {
Order order = orderDao.get(id);
if (order != null && order.getStatus().equals(OrderStatus.NOT_PAID)
&& order.getPayment().getStatus().equals(PaymentStatus.UNKNOWN)) {
order.setStatus(OrderStatus.CANCELLED);
orders.add(order);
} else {
orders = null;
break;
}
}
if (orders != null) {
if (orderDao.saveOrUpdate(orders.toArray(new Order[orders.size()]))) {
int status = STATUS_OK;
String result = "Orders cancelled";
return Response.status(status).entity(result).build();
}
}
int status = STATUS_ERROR;
String result = "Can't cancel orders";
return Response.status(status).entity(result).build();
}
@PUT
@Path("/{orderIds}/accept")
public Response acceptPayments(@PathParam("orderIds") String orderIds) {
List<Order> orders = new ArrayList<Order>();
List<Integer> ids = getNumericIds(orderIds);
for (Integer id : ids) {
Order order = orderDao.get(id);
if (order != null && order.getProducts().size() > 0 && order.getStatus().equals(OrderStatus.NOT_PAID)
&& order.getPayment().getStatus().equals(PaymentStatus.UNKNOWN)) {
order.getPayment().setStatus(PaymentStatus.ACCEPTED);
order.setStatus(OrderStatus.PAID);
orders.add(order);
} else {
orders = null;
break;
}
}
if (orders != null) {
if (orderDao.saveOrUpdate(orders.toArray(new Order[orders.size()]))) {
int status = STATUS_OK;
String result = "Payments accepted";
return Response.status(status).entity(result).build();
}
}
int status = STATUS_ERROR;
String result = "Can't accept payments";
return Response.status(status).entity(result).build();
}
@PUT
@Path("/{orderIds}/reject")
public Response rejectPayments(@PathParam("orderIds") String orderIds) {
List<Order> orders = new ArrayList<Order>();
List<Integer> ids = getNumericIds(orderIds);
for (Integer id : ids) {
Order order = orderDao.get(id);
if (order != null && order.getProducts().size() > 0 && order.getStatus().equals(OrderStatus.NOT_PAID)
&& order.getPayment().getStatus().equals(PaymentStatus.UNKNOWN)) {
order.getPayment().setStatus(PaymentStatus.REJECTED);
orders.add(order);
} else {
orders = null;
break;
}
}
if (orders != null) {
if (orderDao.saveOrUpdate(orders.toArray(new Order[orders.size()]))) {
int status = STATUS_OK;
String result = "Payments rejected";
return Response.status(status).entity(result).build();
}
}
int status = STATUS_ERROR;
String result = "Can't reject payments";
return Response.status(status).entity(result).build();
}
@PUT
@Path("/{orderId}/add")
@Consumes(MediaType.APPLICATION_JSON)
public Response addProduct(@PathParam("orderId") Integer orderId, JsonProductOrder jsonProductOrder) {
if (jsonProductOrder.getProductId() != null && jsonProductOrder.getQuantity() != null) {
Order order = orderDao.get(orderId);
if (order != null && order.getStatus().equals(OrderStatus.NOT_PAID)
&& order.getPayment().getStatus().equals(PaymentStatus.UNKNOWN)) {
List<ProductOrder> productOrders = getProductOrders(Arrays.asList(jsonProductOrder));
if (productOrders != null && productOrders.size() == 1) {
ProductOrder productOrder = productOrders.get(0);
order.addProduct(productOrder);
if (orderDao.saveOrUpdate(order)) {
int status = STATUS_OK;
String result = "Product added";
return Response.status(status).entity(result).build();
}
}
}
}
int status = STATUS_ERROR;
String result = "Can't add product";
return Response.status(status).entity(result).build();
}
@PUT
@Path("/{orderId}/delete")
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteProduct(@PathParam("orderId") Integer orderId, JsonProductOrder jsonProductOrder) {
if (jsonProductOrder.getProductId() != null && jsonProductOrder.getQuantity() != null) {
Order order = orderDao.get(orderId);
if (order != null && order.getStatus().equals(OrderStatus.NOT_PAID)
&& order.getPayment().getStatus().equals(PaymentStatus.UNKNOWN)) {
for (ProductOrder productOrder : order.getProducts()) {
if (productOrder.getId().equals(jsonProductOrder.getProductId())) {
int oldQuantity = productOrder.getQuantity();
int newQuantity = oldQuantity - jsonProductOrder.getQuantity();
if (newQuantity > 0) {
productOrder.setQuantity(newQuantity);
} else {
order.removeProduct(productOrder);
}
if (orderDao.saveOrUpdate(order)) {
int status = STATUS_OK;
String result = "Product deleted";
return Response.status(status).entity(result).build();
}
break;
}
}
}
}
int status = STATUS_ERROR;
String result = "Can't delete product";
return Response.status(status).entity(result).build();
}
/**
* return empty list if there was no product<br>
* order can exist without products<br>
* return null in case of error (bad product id)
*/
private List<ProductOrder> getProductOrders(List<JsonProductOrder> jsonProductOrders) {
List<ProductOrder> productOrders = new ArrayList<ProductOrder>();
for (JsonProductOrder jsonProductOrder : jsonProductOrders) {
Product product = null;
if (jsonProductOrder.getProductId() != null) {
product = productDao.get(jsonProductOrder.getProductId());
}
Integer quantity = jsonProductOrder.getQuantity();
if (product != null && quantity != null) {
ProductOrder productOrder = new ProductOrder(product, quantity);
productOrders.add(productOrder);
} else {
return null;
}
}
return productOrders;
}
private List<JsonCardOrder> getJsonCardOrders(List<Integer> userIds, List<Integer> orderIds, Integer pageNumber) {
List<JsonCardOrder> jsonCardOrders = new ArrayList<JsonCardOrder>();
List<Order> cardOrders = orderDao.getAll(CardPayment.class, userIds, orderIds, pageNumber, ORDERS_PER_PAGE,
CREATE_DATE_ORDER_PROPERTY);
for (Order cardOrder : cardOrders) {
Set<ProductOrder> productOrders = cardOrder.getProducts();
JsonCardOrder jsonCardOrder = new JsonCardOrder();
jsonCardOrder.setId(cardOrder.getId());
jsonCardOrder.setCreateDate(cardOrder.getCreateDate());
jsonCardOrder.setUserId(cardOrder.getUser().getId());
jsonCardOrder.setProducts(getJsonProductOrders(productOrders));
jsonCardOrder.setCard(((CardPayment) cardOrder.getPayment()).getCardType());
jsonCardOrder.setOrderStatus(cardOrder.getStatus().toString());
jsonCardOrder.setPaymentStatus(cardOrder.getPayment().getStatus().toString());
jsonCardOrder.setAmount(getAmount(productOrders));
jsonCardOrders.add(jsonCardOrder);
}
return jsonCardOrders;
}
private List<JsonChequeOrder> getJsonChequeOrders(List<Integer> userIds, List<Integer> orderIds, Integer pageNumber) {
List<JsonChequeOrder> jsonChequeOrders = new ArrayList<JsonChequeOrder>();
List<Order> chequeOrders = orderDao.getAll(ChequePayment.class, userIds, orderIds, pageNumber, ORDERS_PER_PAGE,
CREATE_DATE_ORDER_PROPERTY);
for (Order chequeOrder : chequeOrders) {
Set<ProductOrder> productOrders = chequeOrder.getProducts();
JsonChequeOrder jsonChequeOrder = new JsonChequeOrder();
jsonChequeOrder.setId(chequeOrder.getId());
jsonChequeOrder.setCreateDate(chequeOrder.getCreateDate());
jsonChequeOrder.setUserId(chequeOrder.getUser().getId());
jsonChequeOrder.setProducts(getJsonProductOrders(productOrders));
jsonChequeOrder.setBank(((ChequePayment) chequeOrder.getPayment()).getBankName());
jsonChequeOrder.setOrderStatus(chequeOrder.getStatus().toString());
jsonChequeOrder.setPaymentStatus(chequeOrder.getPayment().getStatus().toString());
jsonChequeOrder.setAmount(getAmount(productOrders));
jsonChequeOrders.add(jsonChequeOrder);
}
return jsonChequeOrders;
}
private List<JsonProductOrder> getJsonProductOrders(Set<ProductOrder> productOrders) {
List<JsonProductOrder> jsonProductOrders = new ArrayList<JsonProductOrder>();
for (ProductOrder productOrder : productOrders) {
JsonProductOrder jsonProductOrder = new JsonProductOrder();
jsonProductOrder.setId(productOrder.getId());
jsonProductOrder.setName(productOrder.getName());
jsonProductOrder.setPrice(productOrder.getPrice());
jsonProductOrder.setCategoryIds(getCategoryIds(productOrder.getCategories()));
jsonProductOrder.setQuantity(productOrder.getQuantity());
jsonProductOrder.setProductId(productOrder.getProduct().getId());
jsonProductOrders.add(jsonProductOrder);
}
return jsonProductOrders;
}
private Double getAmount(Set<ProductOrder> productOrders) {
Double total = 0.0;
for (ProductOrder productOrder : productOrders) {
double product = productOrder.getQuantity() * productOrder.getPrice();
total += product;
}
return total;
}
@SuppressWarnings("rawtypes")
private String getText(List rows) {
StringBuilder sb = new StringBuilder();
if (rows != null) {
for (Object object : rows) {
if (object instanceof Object[]) {
Object[] oa = (Object[]) object;
for (Object o : oa) {
sb.append(o + ",");
}
sb.append("\n");
} else {
sb.append(object + ",");
}
}
}
return sb.toString();
}
private List<OrderStatus> getStatusList(String statutes) {
List<OrderStatus> list = new ArrayList<OrderStatus>();
String[] sa = statutes.split(",");
for (String s : sa) {
OrderStatus status = OrderStatus.valueOf(s);
list.add(status);
}
return list;
}
}
| true |
245a9ab298d2a8a8787150ee3b6af7d6a44da06e | Java | llka/Depreciation | /backend/src/main/java/depreciation/backend/command/user/CreateEquipmentCommand.java | UTF-8 | 1,579 | 2.390625 | 2 | [] | no_license | package depreciation.backend.command.user;
import depreciation.backend.command.ActionCommand;
import depreciation.backend.dao.CompanyDAO;
import depreciation.backend.dao.EquipmentDAO;
import depreciation.backend.exception.ApplicationException;
import depreciation.backend.util.JsonUtil;
import depreciation.entity.Equipment;
import depreciation.entity.technical.CommandRequest;
import depreciation.entity.technical.CommandResponse;
import depreciation.entity.technical.Session;
import depreciation.enums.ResponseStatus;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class CreateEquipmentCommand implements ActionCommand {
private static final Logger logger = LogManager.getLogger(CreateEquipmentCommand.class);
private static final String COMPANY_ID_PARAM = "companyId";
@Override
public CommandResponse execute(CommandRequest request, CommandResponse response, Session session) throws ApplicationException {
EquipmentDAO equipmentDAO = new EquipmentDAO();
CompanyDAO companyDAO = new CompanyDAO();
Equipment equipment = JsonUtil.deserialize(request.getBody(), Equipment.class);
int companyId = 0;
try {
companyId = Integer.parseInt(request.getParameter(COMPANY_ID_PARAM));
} catch (NumberFormatException e) {
throw new ApplicationException("Invalid company id!", ResponseStatus.BAD_REQUEST);
}
companyDAO.getById(companyId);
equipmentDAO.save(equipment, companyId);
return new CommandResponse(ResponseStatus.OK);
}
}
| true |
673c59eed00dd244d0ea04207277b52817514e54 | Java | dukang199409/hnjg | /jshl-manager/src/main/java/com/bsl/reportbean/BslOutProductDetailInfo.java | UTF-8 | 5,064 | 1.882813 | 2 | [] | no_license | package com.bsl.reportbean;
import java.util.Date;
public class BslOutProductDetailInfo {
private String bsCustomer;//销售客户
private String bsOrderNo;//订单号
private String bsInputuser;//制单人员
private String prodRuc;//出库仓库
private String prodOutPlan;//出库单号
private String prodSaleSerno;//出库详细流水
private Date outDate;//出库日期
private String prodName;//物料名称
private String prodNorm;//物料规格
private String prodMaterial;//物料钢种
private Float prodLength;//物料定尺
private String prodUnitz;//主单位
private String prodUnit;//单位
private int sumProdNum;//出库数量
private Float sumProdWeight;//出库重量
private Float sumChaweight;//磅差重量
private Float sumRetweight;//退货重量
private Float salePrice;//出库单价
private Float sumAmt;//出库金额
private Float sumChaAmt;//磅差金额
private Float sumRetAmt;//退货金额
private String prodCurr;//币种
private String prodOutCarno;//车号
private String prodDclFlag;//外协厂标志
private String bsFlag;//通知单类型
private String bsGettype;//通知单类型
private int printNum;//打印数量
public int getPrintNum() {
return printNum;
}
public void setPrintNum(int printNum) {
this.printNum = printNum;
}
public String getBsGettype() {
return bsGettype;
}
public void setBsGettype(String bsGettype) {
this.bsGettype = bsGettype;
}
public String getProdDclFlag() {
return prodDclFlag;
}
public void setProdDclFlag(String prodDclFlag) {
this.prodDclFlag = prodDclFlag;
}
public String getBsFlag() {
return bsFlag;
}
public void setBsFlag(String bsFlag) {
this.bsFlag = bsFlag;
}
public String getProdOutCarno() {
return prodOutCarno;
}
public void setProdOutCarno(String prodOutCarno) {
this.prodOutCarno = prodOutCarno;
}
public String getBsCustomer() {
return bsCustomer;
}
public void setBsCustomer(String bsCustomer) {
this.bsCustomer = bsCustomer;
}
public String getBsOrderNo() {
return bsOrderNo;
}
public void setBsOrderNo(String bsOrderNo) {
this.bsOrderNo = bsOrderNo;
}
public String getBsInputuser() {
return bsInputuser;
}
public void setBsInputuser(String bsInputuser) {
this.bsInputuser = bsInputuser;
}
public String getProdRuc() {
return prodRuc;
}
public void setProdRuc(String prodRuc) {
this.prodRuc = prodRuc;
}
public String getProdOutPlan() {
return prodOutPlan;
}
public void setProdOutPlan(String prodOutPlan) {
this.prodOutPlan = prodOutPlan;
}
public String getProdSaleSerno() {
return prodSaleSerno;
}
public void setProdSaleSerno(String prodSaleSerno) {
this.prodSaleSerno = prodSaleSerno;
}
public Date getOutDate() {
return outDate;
}
public void setOutDate(Date outDate) {
this.outDate = outDate;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public String getProdNorm() {
return prodNorm;
}
public void setProdNorm(String prodNorm) {
this.prodNorm = prodNorm;
}
public String getProdMaterial() {
return prodMaterial;
}
public void setProdMaterial(String prodMaterial) {
this.prodMaterial = prodMaterial;
}
public Float getProdLength() {
return prodLength;
}
public void setProdLength(Float prodLength) {
this.prodLength = prodLength;
}
public String getProdUnitz() {
return prodUnitz;
}
public void setProdUnitz(String prodUnitz) {
this.prodUnitz = prodUnitz;
}
public String getProdUnit() {
return prodUnit;
}
public void setProdUnit(String prodUnit) {
this.prodUnit = prodUnit;
}
public int getSumProdNum() {
return sumProdNum;
}
public void setSumProdNum(int sumProdNum) {
this.sumProdNum = sumProdNum;
}
public Float getSumProdWeight() {
return sumProdWeight;
}
public void setSumProdWeight(Float sumProdWeight) {
this.sumProdWeight = sumProdWeight;
}
public Float getSumChaweight() {
return sumChaweight;
}
public void setSumChaweight(Float sumChaweight) {
this.sumChaweight = sumChaweight;
}
public Float getSumRetweight() {
return sumRetweight;
}
public void setSumRetweight(Float sumRetweight) {
this.sumRetweight = sumRetweight;
}
public Float getSalePrice() {
return salePrice;
}
public void setSalePrice(Float salePrice) {
this.salePrice = salePrice;
}
public Float getSumAmt() {
return sumAmt;
}
public void setSumAmt(Float sumAmt) {
this.sumAmt = sumAmt;
}
public Float getSumChaAmt() {
return sumChaAmt;
}
public void setSumChaAmt(Float sumChaAmt) {
this.sumChaAmt = sumChaAmt;
}
public Float getSumRetAmt() {
return sumRetAmt;
}
public void setSumRetAmt(Float sumRetAmt) {
this.sumRetAmt = sumRetAmt;
}
public String getProdCurr() {
return prodCurr;
}
public void setProdCurr(String prodCurr) {
this.prodCurr = prodCurr;
}
}
| true |
e880fd7f154867152d7693013f0feb4103d8dfe8 | Java | Dova81/ReactBichomonGO | /Grupo_1_2018_C2-TP-TP6/src/main/java/epers/bichomon/dao/NivelDAO.java | UTF-8 | 240 | 1.875 | 2 | [] | no_license | package epers.bichomon.dao;
import epers.bichomon.model.entrenador.Nivel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface NivelDAO extends JpaRepository<Nivel, Integer> {
Nivel findByNro(Integer nro);
}
| true |
049d97f967dfd51fed260133d8f1dc2730a36615 | Java | WICKW/Studying.Spring.IoC | /src/main/java/com/yurii/aplicationcontext/MsgProvider.java | UTF-8 | 99 | 1.71875 | 2 | [] | no_license | package com.yurii.aplicationcontext;
public interface MsgProvider {
public String getMsg();
}
| true |
56b419c3f1c571438fec007d77174e83c68e111c | Java | Niyaz-90/stc-21_gafurov_niyaz | /Homework11/src/main/java/ru/inno/hw11/task1/MainClient.java | UTF-8 | 372 | 2.40625 | 2 | [] | no_license | package ru.inno.hw11.task1;
import java.io.IOException;
import java.net.Socket;
public class MainClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 34642);
SocketClient client = new SocketClient(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
1f7773f4ff2aca9f1c88587efb3961ba0e044c36 | Java | acastroy/safiserver-all | /com.safi.asterisk.figures/src/com/safi/asterisk/figures/DefaultToolstepFigure.java | UTF-8 | 2,026 | 2.3125 | 2 | [] | no_license | package com.safi.asterisk.figures;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel;
/**
* @generated
*/
public class DefaultToolstepFigure extends ToolstepFigure {
IFigure tooltip;
boolean minimized = false;
public DefaultToolstepFigure(){
super();
}
public DefaultToolstepFigure(IFigure rootPane){
super(rootPane);
}
/**
* @generated
*/
protected ActionstepWrapLabel toolstepNameLabel;
/**
* @generated
*/
protected void createContents() {
getRootPane().add(createToolstepNameLabel());
}
protected WrapLabel createToolstepNameLabel(){
tooltip = new Label();
toolstepNameLabel = new ActionstepWrapLabel();
toolstepNameLabel.setToolTip(tooltip);
// toolstepNameLabel.setText("");
return toolstepNameLabel;
}
/**
* @generated
*/
public WrapLabel getToolstepNameLabel() {
return toolstepNameLabel;
}
public boolean isMinimized() {
return minimized;
}
public void setMinimized(boolean minimized) {
if (minimized){
toolstepNameLabel.setTextHidden(true);
}
else
toolstepNameLabel.setTextHidden(false);
invalidate();
// layout();
}
class ActionstepWrapLabel extends WrapLabel {
boolean textHidden;
String cachedText = null;
public boolean isTextHidden() {
return textHidden;
}
public void setTextHidden(boolean textHidden) {
this.textHidden = textHidden;
if (textHidden)
super.setText("");
else
super.setText(cachedText);
invalidate();
}
@Override
public String getText() {
return textHidden ? "" : super.getText();
}
@Override
public void setText(String s) {
cachedText = s;
super.setText(s);
if (tooltip != null)
((Label)tooltip).setText(s);
}
}
}
| true |
ab68b393021e1e4e3935a9bb809fb6793c95e2f4 | Java | UQ-RCC/nimrodok | /nimroda/src/test/java/net/vs49688/nimrod/CrashTest.java | UTF-8 | 1,590 | 1.742188 | 2 | [
"BSD-3-Clause"
] | permissive | package net.vs49688.nimrod;
import com.sun.jna.*;
import junit.framework.Assert;
import net.vs49688.nimrod.nimroda.INimrodA;
import net.vs49688.nimrod.nimroda.NimAlgorithm;
import net.vs49688.nimrod.nimroda.NimBatch;
import net.vs49688.nimrod.nimroda.NimCallbacks;
import net.vs49688.nimrod.nimroda.NimConfig;
import net.vs49688.nimrod.nimroda.NimKVPair;
import net.vs49688.nimrod.nimroda.NimDefinitions;
import net.vs49688.nimrod.nimroda.NimOptimStatus;
import net.vs49688.nimrod.nimroda.NimPoint;
import net.vs49688.nimrod.nimroda.NimVarbleAttrib;
import net.vs49688.nimrod.nimroda.NimrodA;
import net.vs49688.nimrod.nimroda.SizeT;
import org.junit.Test;
public class CrashTest {
private static int getPID() {
try {
java.lang.management.RuntimeMXBean runtime
= java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt
= (sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method
= mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
int pid = (Integer) pid_method.invoke(mgmt);
System.err.printf("PID is %d\n", pid);
return pid;
} catch(Exception e) {
return -1;
}
}
public static int pid = getPID();
@Test
public void structureSizesTest() throws Exception {
//INimrodA nimroda = NimrodA.getInterface();
//NimCallbacks cbk = NimCallbacks.class.newInstance();
NimConfig cfg = NimConfig.class.newInstance();
int x = 0;
}
}
| true |
0cabb7de3612844c172e8a9dde33e033b2a61c48 | Java | SteveDLosk/SewingPatternApp | /app/src/main/java/com/weebly/stevelosk/sewingpatternapp/BasicSearchActivity.java | UTF-8 | 5,833 | 2.203125 | 2 | [] | no_license | package com.weebly.stevelosk.sewingpatternapp;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class BasicSearchActivity extends AppCompatActivity implements IAsyncCalling {
private String savedSearchString = "";
private EditText searchEditText;
private TextView resultsTextView;
private ArrayList<Pattern> patterns = new ArrayList<>();
private ImageView placeHolderImage;
private ListView resultsListView;
private Toast toast;
// a Timer to wait between text changes before firing a search event
private Timer textChangedTimer;
protected int TIMER_DELAY = 100;
private PatternAdapter pa = null;
private PatternDBAdapter db = null;
private AsyncSearchTask searchTask = null;
private int searchMode = AsyncSearchTask.CLOSE_ANY_TEXT_FIELD_MATCH;
private final String TAG = "SDL BasicSearchActivity";
private BasicSearchActivity mActivity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_search);
// open database onCreate
db = new PatternDBAdapter(this);
db.open();
toast = new Toast(getApplicationContext());
searchEditText = (EditText) findViewById(R.id.searchEditText);
resultsTextView = (TextView) findViewById(R.id.searchActivity_resultsTextView);
placeHolderImage = (ImageView) findViewById(R.id.placeHolderImage);
// ListView
resultsListView = (ListView) findViewById(R.id.basicSearch_ListView);
pa = new PatternAdapter(this, patterns);
resultsListView.setAdapter(pa);
resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Pattern p = patterns.get(i);
Intent examineIntent = new Intent(getApplicationContext(),
ExaminePatternActivity.class);
examineIntent.putExtra("PASSED_PATTERN_INSTANCE", p);
startActivity(examineIntent);
}
});
// TODO: use Handler instead?
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
if (textChangedTimer != null)
textChangedTimer.cancel();
}
@Override
public void afterTextChanged(final Editable s) {
//avoid triggering event when time is too short
textChangedTimer = new Timer();
textChangedTimer.schedule(new TimerTask() {
@Override
public void run() {
if (searchTask != null) {
// cancel previously running search, a search might have started
// before the user was done entering text
// could make a difference for a large database
searchTask.cancel(true);
}
try {
IAsyncCalling caller = (IAsyncCalling) mActivity;
searchTask = new AsyncSearchTask();
Object[] params = {searchEditText.getText().toString(),
patterns, db, pa, searchMode, caller};
searchTask.execute(params);
}
catch (SQLException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, TIMER_DELAY);
}
});
}
@Override
protected void onResume() {
super.onResume();
try {
searchTask = new AsyncSearchTask();
Object[] params = {searchEditText.getText().toString(),
patterns, db, pa, searchMode};
searchTask.execute(params);
}
catch (SQLException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPause() {
super.onPause();
savedSearchString = searchEditText.getText().toString();
}
@Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
public void reportNoResults () {
toast.cancel();
toast = Toast.makeText(getApplicationContext(), R.string.noPatternsFound,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
| true |
32c0776c677f05ce6b2302385e85c7b2d7b78e52 | Java | kylegosen/sports-schedule-api | /data/src/main/java/com/gosenk/sports/schedule/data/processor/NBAProcessor.java | UTF-8 | 366 | 1.890625 | 2 | [] | no_license | package com.gosenk.sports.schedule.data.processor;
import org.springframework.stereotype.Service;
@Service
public class NBAProcessor extends MySportsFeedsProcessor implements Processor {
public NBAProcessor(){
super("NBA", "nba", "2018-2019-regular");
}
@Override
public void process() throws Exception {
super.process();
}
}
| true |
6e65b8e0d1dc78d1d8ff859844c5bd3a37b897a9 | Java | jackbill749/famewiki | /src/main/java/com/sparks/jack/famewiki/db/model/Introduce.java | UTF-8 | 1,081 | 2.1875 | 2 | [] | no_license | // auto generated do not edit
package com.sparks.jack.famewiki.db.model;
import java.io.Serializable;
public class Introduce implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long immortalid;
private String content;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getImmortalid() {
return this.immortalid;
}
public void setImmortalid(Long immortalid) {
this.immortalid = immortalid;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("introduce[");
builder.append("id=");
builder.append(id);
builder.append(", ");
builder.append("immortalid=");
builder.append(immortalid);
builder.append(", ");
builder.append("content=");
builder.append(content);
builder.append("]");
return builder.toString();
}
}
| true |
b02839ccb6040f67563b8cfcbd52086d5faccb0f | Java | DenisShustrov/job4j | /chapter_007/src/main/java/ru/job4j/magnit/Config.java | UTF-8 | 835 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package ru.job4j.magnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* Class Config.
*
* @author dshustrov
* @version 1
* @since 21.02.2019
*/
public class Config {
private final Properties values = new Properties();
private static final Logger LOG = LogManager.getLogger(Config.class);
public void init() {
try (InputStream in = Config.class.getClassLoader().getResourceAsStream("config.properties")) {
values.load(in);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public String get(String key) {
return this.values.getProperty(key);
}
}
| true |
9c4bf4add8a0ed065d67da5b43bf9226166c5547 | Java | IlyaSkiba/labs | /lab3/src/main/java/bsu/lab/presentation/servlet/add/AddUserHandler.java | UTF-8 | 1,234 | 2.34375 | 2 | [] | no_license | package bsu.lab.presentation.servlet.add;
import bsu.lab.business.businessObjects.Client;
import bsu.lab.business.scripts.ClientService;
import bsu.lab.presentation.model.ClientModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Ilya SKiba
* Date: 11.10.12
*/
@Controller("addUser")
public class AddUserHandler implements HttpRequestHandler {
@Autowired
private ClientService clientService;
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ClientModel clientModel = (ClientModel) request.getAttribute("clientModel");
Client newClient = new Client();
newClient.setAddress(clientModel.getAddress());
newClient.setName(clientModel.getName());
newClient.setTelephone(clientModel.getPhone());
clientService.create(newClient);
response.sendRedirect("/list");
}
}
| true |
358944fdcdc05becae6d9787a9a3f8d3b990bf9a | Java | mfernandmx/MyBrotherhoodApp | /app/src/main/java/com/example/marcos/mybrotherhoodapp/adapters/GridViewAdapter.java | UTF-8 | 2,441 | 2.671875 | 3 | [] | no_license | package com.example.marcos.mybrotherhoodapp.adapters;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.marcos.mybrotherhoodapp.R;
import com.example.marcos.mybrotherhoodapp.items.ImageItem;
import java.util.ArrayList;
/**
* Class GridViewAdapter
* Adapter used for showing the images in the gallery
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context mContext;
private int layoutResourceId;
private ArrayList<ImageItem> mDataList = new ArrayList<>();
private boolean nightMode = false;
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> dataList) {
super(context, layoutResourceId, dataList);
this.layoutResourceId = layoutResourceId;
this.mContext = context;
this.mDataList = dataList;
}
@Override
@NonNull
public View getView(int position, View convertView, @Nullable ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.gridText);
holder.image = (ImageView) row.findViewById(R.id.gridImage);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = mDataList.get(position);
holder.image.setImageBitmap(item.getImage());
holder.imageTitle.setText(item.getTitle());
// Change text color if the night mode is active
int textColor;
if (!nightMode){
textColor = Color.BLACK;
} else{
textColor = Color.WHITE;
}
holder.imageTitle.setTextColor(textColor);
return row;
}
private static class ViewHolder {
TextView imageTitle;
ImageView image;
}
public void setNightMode(boolean nightMode){
this.nightMode = nightMode;
}
} | true |
16375a39992e17e3734546290437df67d89c55ba | Java | AyoPrez/DeilyQ | /mobile/src/main/java/com/ayoprez/deilyquote/ReviewList.java | UTF-8 | 2,389 | 2.25 | 2 | [] | no_license | package com.ayoprez.deilyquote;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.ListView;
import com.ayoprez.database.UserMomentsRepository;
import com.ayoprez.notification.StartAndCancelAlarmManager;
import com.ayoprez.utils.Utils;
import java.util.List;
import deilyquote.UserMoments;
/**
* Created by AyoPrez on 10.10.15.
*/
public class ReviewList {
private static final String LOG_TAG = "ReviewList";
protected ReviewAdapter reviewAdapter;
private ListView reviewList;
public ReviewList(ListView reviewList){
this.reviewList = reviewList;
}
private List<UserMoments> getDataFromDatabaseToListView(Context context) {
return new UserMomentsRepository().getAllMoments(context);
}
public void showReviewList(Context context) {
reviewAdapter = new ReviewAdapter(context, getDataFromDatabaseToListView(context));
reviewList.setAdapter(reviewAdapter);
}
public void showAlertDialogToDeleteItem(final Context context, final int selectedItem) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
deleteItemFromDatabase(context, selectedItem);
showReviewList(context);
} catch (Exception e) {
ErrorHandle.getInstance().Error(LOG_TAG, e);
ErrorHandle.getInstance().informUser(context, context.getString(R.string.errorDefault));
}
}
};
Utils.Create_Dialog_DoNotFinishActivity(context, context.getString(R.string.deleteMomentDialog),
context.getString(android.R.string.yes), context.getString(R.string.deleteMomentDialogTitle), onClickListener);
}
private void deleteItemFromDatabase(Context context, int selectedItem) {
try {
new StartAndCancelAlarmManager(context, getDataFromDatabaseToListView(context).get(selectedItem)).cancelAlarmManager();
new UserMomentsRepository().deleteSelectedMoment(context, selectedItem);
}catch(Exception e){
ErrorHandle.getInstance().Error(LOG_TAG, e);
ErrorHandle.getInstance().informUser(context, context.getString(R.string.errorDeletingMoment));
}
}
}
| true |
07633c0450527d568b4ab53ec1cf05853d49fe5e | Java | loktevalexey/JD2017-02-20 | /src/by/it/radivonik/jd02_10/beans/Tovars.java | UTF-8 | 2,123 | 2.3125 | 2 | [] | no_license | package by.it.radivonik.jd02_10.beans;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Tovars complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Tovars">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Tovar" type="{http://generate.beans.jd02_09.radivonik.it.by}Tovar" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Tovars", propOrder = {
"tovar"
})
public class Tovars {
@XmlElement(name = "Tovar", required = true)
protected List<Tovar> tovar;
/**
* Gets the value of the tovar property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the tovar property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTovar().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Tovar }
*
*
*/
public List<Tovar> getTovar() {
if (tovar == null) {
tovar = new ArrayList<Tovar>();
}
return this.tovar;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder("Tovars{");
String delim = "";
for (Tovar tovar: getTovar()) {
res.append(delim).append("\n").append(tovar);
delim = ",";
}
res.append("}");
return res.toString();
}
}
| true |
b8441dae55f7e3eb3b030bb2efdb3541a95fd60d | Java | jambestwick/HackWechat | /app/src/main/java/com/tencent/mm/ui/conversation/BizConversationUI$a$15.java | UTF-8 | 426 | 1.554688 | 2 | [] | no_license | package com.tencent.mm.ui.conversation;
import android.view.View;
import com.tencent.mm.ui.base.MMSlideDelView.f;
import com.tencent.mm.ui.conversation.BizConversationUI.a;
class BizConversationUI$a$15 implements f {
final /* synthetic */ a yWk;
BizConversationUI$a$15(a aVar) {
this.yWk = aVar;
}
public final void t(View view, int i) {
a.d(this.yWk).performItemClick(view, i, 0);
}
}
| true |
620b751129c3292ebd7b5de5883d4acb2c659613 | Java | batc8t/Calculator-in-Java | /src/main/java/com/bayethehlongwane/calculator/StandardCalcGUI.java | UTF-8 | 31,068 | 2.078125 | 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 com.bayethehlongwane.calculator;
import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.*;
/**
*
* @author Ghost
*/
public class StandardCalcGUI extends javax.swing.JFrame {
/**
* Creates new form Calculator
*/
public StandardCalcGUI() {
initComponents();
}
/**
* 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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
BtnMemorySubtract = new javax.swing.JButton();
BtnMemoryAdd = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
BtnMemory = new javax.swing.JButton();
LabelSecondary = new javax.swing.JLabel();
LabelPrimary = new javax.swing.JLabel();
BtnPercent = new javax.swing.JButton();
BtnReset = new javax.swing.JButton();
BtnInvert = new javax.swing.JButton();
BtnSquare = new javax.swing.JButton();
BtnRoot = new javax.swing.JButton();
BtnDivide = new javax.swing.JButton();
Btn7 = new javax.swing.JButton();
Btn8 = new javax.swing.JButton();
Btn9 = new javax.swing.JButton();
BtnMultiply = new javax.swing.JButton();
Btn4 = new javax.swing.JButton();
Btn5 = new javax.swing.JButton();
Btn6 = new javax.swing.JButton();
BtnSubtract = new javax.swing.JButton();
Btn1 = new javax.swing.JButton();
Btn2 = new javax.swing.JButton();
Btn3 = new javax.swing.JButton();
BtnPlus = new javax.swing.JButton();
BtnPlusMinus = new javax.swing.JButton();
Btn0 = new javax.swing.JButton();
Btndot = new javax.swing.JButton();
BtnEqualls = new javax.swing.JButton();
BtnDelete = new javax.swing.JButton();
BtnPie = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
Currency = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("calculator");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jButton1.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
jButton1.setText("MC");
jButton1.setEnabled(false);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
jButton2.setText("MR");
jButton2.setEnabled(false);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
BtnMemorySubtract.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
BtnMemorySubtract.setText("M-");
BtnMemorySubtract.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnMemorySubtractActionPerformed(evt);
}
});
BtnMemoryAdd.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
BtnMemoryAdd.setText("M+");
BtnMemoryAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnMemoryAddActionPerformed(evt);
}
});
jButton5.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
jButton5.setText("M*");
jButton5.setEnabled(false);
BtnMemory.setFont(new java.awt.Font("Segoe UI", 1, 10)); // NOI18N
BtnMemory.setText("MS");
BtnMemory.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnMemoryActionPerformed(evt);
}
});
LabelSecondary.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
LabelSecondary.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
LabelSecondary.setText("5 x 0 =");
LabelPrimary.setFont(new java.awt.Font("Trebuchet MS", 1, 36)); // NOI18N
LabelPrimary.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
LabelPrimary.setText("0");
BtnPercent.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnPercent.setText("%");
BtnReset.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnReset.setText("CE");
BtnInvert.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnInvert.setText("1/x");
BtnSquare.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnSquare.setText("x^2");
BtnRoot.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnRoot.setText("√X");
BtnDivide.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnDivide.setText("/");
BtnDivide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnDivideActionPerformed(evt);
}
});
Btn7.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn7.setText("7");
Btn8.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn8.setText("8");
Btn9.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn9.setText("9");
Btn9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn9ActionPerformed(evt);
}
});
BtnMultiply.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnMultiply.setText("X");
Btn4.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn4.setText("4");
Btn5.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn5.setText("5");
Btn6.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn6.setText("6");
BtnSubtract.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnSubtract.setText("-");
Btn1.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn1.setText("1");
Btn2.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn2.setText("2");
Btn3.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn3.setText("3");
BtnPlus.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnPlus.setText("+");
BtnPlusMinus.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnPlusMinus.setText("+/-");
Btn0.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btn0.setText("0");
Btndot.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
Btndot.setText(".");
BtnEqualls.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnEqualls.setText("=");
BtnDelete.setFont(new java.awt.Font("Segoe UI", 1, 36)); // NOI18N
BtnDelete.setText("←");
BtnPie.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
BtnPie.setText("π");
jMenu1.setText("MENU");
jMenu1.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
jMenu1.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
jMenu1MenuSelected(evt);
}
});
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem1.setText("Standard");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem2.setText("Scientific");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_DOWN_MASK));
jMenuItem3.setText("Date Calculation");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
jMenu1.add(jSeparator1);
Currency.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_DOWN_MASK));
Currency.setText("Currency");
Currency.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CurrencyActionPerformed(evt);
}
});
jMenu1.add(Currency);
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.ALT_DOWN_MASK));
jMenuItem4.setText("Volume");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem4);
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.ALT_DOWN_MASK));
jMenuItem5.setText("Length");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem5);
jMenuBar1.add(jMenu1);
jMenu2.setText("Standard");
jMenu2.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LabelPrimary, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(LabelSecondary, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnMemoryAdd)
.addGap(18, 18, 18)
.addComponent(BtnMemorySubtract, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnMemory)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(BtnPlusMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(BtnPercent, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(BtnInvert, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnSquare, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(Btndot, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnEqualls, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnSubtract, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnMultiply, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(BtnRoot, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnDivide, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(BtnPie, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {BtnMemoryAdd, BtnMemorySubtract, jButton1, jButton2});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {LabelPrimary, LabelSecondary});
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {BtnDelete, BtnPie});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LabelSecondary, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(LabelPrimary, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1)
.addComponent(BtnMemoryAdd)
.addComponent(BtnMemorySubtract)
.addComponent(BtnMemory)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BtnPercent, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnPie, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(BtnDelete, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BtnInvert, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnSquare, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnRoot, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnDivide, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnMultiply, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnSubtract, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BtnPlusMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btndot, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnEqualls, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {LabelPrimary, LabelSecondary});
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {BtnDelete, BtnPie});
pack();
}// </editor-fold>//GEN-END:initComponents
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WelcomeScreenGUI().setVisible(true);
}
});
}
public void close()
{
WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
//this.setResizable(true);
//this.setSize(350, 600);
new ScientificCalcGUI().setVisible(true);
close();
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void BtnMemoryAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnMemoryAddActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_BtnMemoryAddActionPerformed
private void BtnMemoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnMemoryActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_BtnMemoryActionPerformed
private void BtnMemorySubtractActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnMemorySubtractActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_BtnMemorySubtractActionPerformed
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
//this.setResizable(true);
//this.setSize(350, 525);
}//GEN-LAST:event_formWindowActivated
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
//this.setResizable(true);
//this.setSize(350, 525);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
this.setResizable(true);
this.setSize(350, 525);
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void CurrencyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CurrencyActionPerformed
this.setResizable(true);
this.setSize(350, 525);
}//GEN-LAST:event_CurrencyActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
this.setResizable(true);
this.setSize(350, 525);
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
this.setResizable(true);
this.setSize(350, 525);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void BtnDivideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnDivideActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_BtnDivideActionPerformed
private void Btn9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn9ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Btn9ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void jMenu1MenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_jMenu1MenuSelected
// TODO add your handling code here:
}//GEN-LAST:event_jMenu1MenuSelected
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Btn0;
private javax.swing.JButton Btn1;
private javax.swing.JButton Btn2;
private javax.swing.JButton Btn3;
private javax.swing.JButton Btn4;
private javax.swing.JButton Btn5;
private javax.swing.JButton Btn6;
private javax.swing.JButton Btn7;
private javax.swing.JButton Btn8;
private javax.swing.JButton Btn9;
private javax.swing.JButton BtnDelete;
private javax.swing.JButton BtnDivide;
private javax.swing.JButton BtnEqualls;
private javax.swing.JButton BtnInvert;
private javax.swing.JButton BtnMemory;
private javax.swing.JButton BtnMemoryAdd;
private javax.swing.JButton BtnMemorySubtract;
private javax.swing.JButton BtnMultiply;
private javax.swing.JButton BtnPercent;
private javax.swing.JButton BtnPie;
private javax.swing.JButton BtnPlus;
private javax.swing.JButton BtnPlusMinus;
private javax.swing.JButton BtnReset;
private javax.swing.JButton BtnRoot;
private javax.swing.JButton BtnSquare;
private javax.swing.JButton BtnSubtract;
private javax.swing.JButton Btndot;
private javax.swing.JMenuItem Currency;
private javax.swing.JLabel LabelPrimary;
private javax.swing.JLabel LabelSecondary;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPopupMenu.Separator jSeparator1;
// End of variables declaration//GEN-END:variables
}
| true |
374c29edd6f41b4612db68c3fc2cfdb7538bc21f | Java | mahmoudelgamal1997/Tasks | /app/src/main/java/com/example2017/android/tasks/Chat/ChatPrivate.java | UTF-8 | 11,626 | 1.9375 | 2 | [] | no_license | package com.example2017.android.tasks.Chat;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example2017.android.tasks.R;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
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.Calendar;
public class ChatPrivate extends AppCompatActivity {
DatabaseReference chat,temp,RecieveMessage,Notification;
RecyclerView recyclerView;
EditText Message;
Button butSend;
FirebaseAuth.AuthStateListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_private);
define();
Intent i = getIntent();
final String RecieverId = i.getStringExtra("id");
final String SenderId = FirebaseAuth.getInstance().getCurrentUser().getUid();
chat = FirebaseDatabase.getInstance().getReference().child("chat");
Notification=FirebaseDatabase.getInstance().getReference().child("Notification");
RecieveMessage=FirebaseDatabase.getInstance().getReference().child("chat");
recyclerView = (RecyclerView) findViewById(R.id.ChatView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
chat.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(SenderId).child(RecieverId).hasChildren() ) {
chat=chat.child(SenderId).child(RecieverId);
display();
}
if (dataSnapshot.child(RecieverId).child(SenderId).hasChildren() ) {
chat=chat.child(RecieverId).child(SenderId);
display();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
butSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chat.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(SenderId).child(RecieverId).hasChildren()){
// check if reference exist or not
temp = RecieveMessage.child(SenderId).child(RecieverId).push();
temp.child("message").setValue(Message.getText().toString());
temp.child("from").setValue(SenderId);
temp.child("Time").setValue(MessageTime());
//Notification
DatabaseReference username = FirebaseDatabase.getInstance().getReference().child("username").child(SenderId);
username.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (dataSnapshot.child("name").getValue(String.class));
Notification.child(RecieverId).child(SenderId).child("from").setValue(name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Message.setText("");
display();
}else if (dataSnapshot.child(RecieverId).child(SenderId).hasChildren()){
//check by reverse
temp = RecieveMessage.child(RecieverId).child(SenderId).push();
temp.child("message").setValue(Message.getText().toString());
temp.child("from").setValue(RecieverId);
temp.child("Time").setValue(MessageTime());
DatabaseReference username = FirebaseDatabase.getInstance().getReference().child("username").child(SenderId);
username.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (dataSnapshot.child("name").getValue(String.class));
Notification.child(RecieverId).child(SenderId).child("from").setValue(name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Message.setText("");
display();
}else{
//then database reference isn't exist
//So we create it
temp = RecieveMessage.child(SenderId).child(RecieverId).push();
temp.child("message").setValue(Message.getText().toString());
temp.child("from").setValue(SenderId);
temp.child("Time").setValue(MessageTime());
DatabaseReference username = FirebaseDatabase.getInstance().getReference().child("username").child(SenderId);
username.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (dataSnapshot.child("name").getValue(String.class));
Notification.child(RecieverId).child(SenderId).child("from").setValue(name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Message.setText("");
display();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
public void display(){
FirebaseRecyclerAdapter<ChatMessage,view_holder> firebaseRecyclerAdapter =new FirebaseRecyclerAdapter<ChatMessage, view_holder>(
ChatMessage.class,
R.layout.message_cardview,
view_holder.class,
chat
) {
@Override
protected void populateViewHolder(final view_holder viewHolder, final ChatMessage model, final int position) {
viewHolder.SetData(model.getfrom(),model.getTime(),model.getMessage());
Toast.makeText(ChatPrivate.this, model.getfrom(), Toast.LENGTH_SHORT).show();
chat.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
//recyclerView.smoothScrollToPosition(firebaseRecyclerAdapter.getItemCount());
}
public static class view_holder extends RecyclerView.ViewHolder{
View view;
public view_holder(View itemView)
{
super(itemView);
view=itemView;
}
public void SetData(String Id , final String Time , final String Message){
final TextView txtName=(TextView)view.findViewById(R.id.textview_username);
final TextView txtTime=(TextView)view.findViewById(R.id.textview_timeSent);
final TextView txtMessage=(TextView)view.findViewById(R.id.textview_Message);
CardView cardView=(CardView)view.findViewById(R.id.Card_message);
// if your message color it to orange
if (FirebaseAuth.getInstance().getCurrentUser().getUid().equals(Id)){
txtName.setText("You");
txtName.setTextColor(view.getResources().getColor(R.color.icons));
txtTime.setText(Time);
txtTime.setTextColor(view.getResources().getColor(R.color.icons));
txtMessage.setText(Message);
txtMessage.setTextColor(view.getResources().getColor(R.color.icons));
cardView.setCardBackgroundColor(view.getResources().getColor(R.color.colorPrimary));
ViewGroup.MarginLayoutParams cardViewMarginParams = (ViewGroup.MarginLayoutParams) cardView.getLayoutParams();
cardViewMarginParams.setMargins(700, 0, 0, 10);
cardView.requestLayout(); //Dont forget this line
}else {
DatabaseReference username=FirebaseDatabase.getInstance().getReference().child("username").child(Id);
username.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
txtName.setText(dataSnapshot.child("name").getValue(String.class));
txtTime.setText(Time);
txtMessage.setText(Message);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
public void define(){
recyclerView=(RecyclerView) findViewById(R.id.ChatView);
Message=(EditText)findViewById(R.id.sendMessage);
butSend=(Button)findViewById(R.id.but_send);
}
public String MessageTime(){
Calendar calendar=Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day =calendar.get(Calendar.DAY_OF_MONTH);
int hour=calendar.get(Calendar.HOUR_OF_DAY);
int minute=calendar.get(Calendar.MINUTE);
final String CollectionDate=""+year+"-"+month+"-"+day+" "+hour+":"+minute;
return CollectionDate;
}
}
| true |
f3076e2ffbde9f2c8f9ad7afe2b066c39d4c964e | Java | legilmo/selecao-java | /apirest-avaliacao-indra/src/main/java/br/com/indra/avaliacao/apirest/models/state/services/impl/StateService.java | UTF-8 | 1,847 | 2.265625 | 2 | [] | no_license | package br.com.indra.avaliacao.apirest.models.state.services.impl;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.indra.avaliacao.apirest.models.state.entity.State;
import br.com.indra.avaliacao.apirest.models.state.repository.StateRepository;
import br.com.indra.avaliacao.apirest.models.state.services.IStateService;
@Service
public class StateService implements IStateService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private StateRepository stateRepository;
@Autowired
public void setStateRepository(StateRepository stateRepository ) {
this.stateRepository = stateRepository;
}
@Override
public Iterable<State> listAllStates() {
logger.debug("StateService::listAllStates called");
Iterable<State> states = stateRepository.findAll();
return states;
}
@Override
public State getStateById(Integer id) {
logger.debug("StateService::getStateById called");
Optional<State> State = stateRepository.findById(id);
if(State.isPresent()) {
State r = State.get();
return r;
} else {
return null;
}
}
@Override
public State saveState(State State) {
logger.debug("StateService::saveState called");
return stateRepository.save(State);
}
@Override
public void deleteState(Integer id) {
logger.debug("StateService::deleteState called");
stateRepository.deleteById(id);
}
@Override
public State getStateByInitials(String initials) {
logger.debug("StateService::getStateByName called");
return stateRepository.getStateByInitials(initials);
}
}
| true |
fe604a2fca2ed813110b161dd5b57b3e82c8533f | Java | khalifandiaye/bus-reservation | /WIP/Source/Project/src/main/java/vn/edu/fpt/capstone/busReservation/action/bus/SaveBusAction.java | UTF-8 | 2,312 | 2.171875 | 2 | [] | no_license | package vn.edu.fpt.capstone.busReservation.action.bus;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import vn.edu.fpt.capstone.busReservation.action.BaseAction;
import vn.edu.fpt.capstone.busReservation.dao.BusDAO;
import vn.edu.fpt.capstone.busReservation.dao.BusTypeDAO;
import vn.edu.fpt.capstone.busReservation.dao.bean.BusBean;
import vn.edu.fpt.capstone.busReservation.dao.bean.BusTypeBean;
@ParentPackage("jsonPackage")
public class SaveBusAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private String plateNumber;
private int busTypeBeans;
private String message = "Save Bus Success!";
private int resultId = 0;
private BusTypeDAO busTypeDAO;
private BusDAO busDAO;
@Action(value = "/saveBus", results = { @Result(type = "json", name = SUCCESS) })
public String execute() {
try {
List<BusBean> busBeans = busDAO.getBusByplateNumber(plateNumber);
if (busBeans.size() == 0) {
BusTypeBean busTypeBean = busTypeDAO.getById(busTypeBeans);
BusBean busBean = new BusBean();
busBean.setBusType(busTypeBean);
busBean.setPlateNumber(plateNumber);
busBean.setStatus("active");
busDAO.insert(busBean);
}
if (busBeans.size() != 0) {
if (busBeans.get(0).getStatus().equals("inactive")) {
busBeans.get(0).setStatus("active");
busDAO.update(busBeans.get(0));
} else {
setMessage("Bus Plate number is existed!");
resultId = 1;
}
}
} catch (Exception ex) {
setMessage("Save bus failed!");
resultId = 2;
}
return SUCCESS;
}
public int getResultId() {
return resultId;
}
public void setBusTypeDAO(BusTypeDAO busTypeDAO) {
this.busTypeDAO = busTypeDAO;
}
public void setPlateNumber(String plateNumber) {
this.plateNumber = plateNumber;
}
public void setBusTypeBeans(int busTypeBeans) {
this.busTypeBeans = busTypeBeans;
}
public void setBusDAO(BusDAO busDAO) {
this.busDAO = busDAO;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| true |
c7ba8d23702509d6de517e993c7a4759933a94c0 | Java | enaawy/gproject | /output/com.google.android.finsky.cv.a.es.java | UTF-8 | 13,573 | 1.5 | 2 | [] | no_license | package com.google.android.finsky.cv.a;
import com.google.protobuf.nano.CodedOutputByteBufferNano;
import com.google.protobuf.nano.a;
import com.google.protobuf.nano.b;
import com.google.protobuf.nano.e;
import com.google.protobuf.nano.h;
import com.google.protobuf.nano.i;
import com.google.protobuf.nano.l;
public final class com.google.android.finsky.cv.a.es extends com.google.protobuf.nano.b
{
public int a;
public int b;
public long c;
public ch[] d;
public int e;
public int f;
public long g;
public String[] h;
public int i;
public int j;
public int k;
public String[] l;
es() {
com.google.protobuf.nano.b();
this.a = 0;
this.b = 0;
this.c = 0;
this.d = com.google.android.finsky.cv.a.ch.aP_();
this.e = 0;
this.f = 0;
this.g = 0;
this.h = com.google.protobuf.nano.l.j;
this.i = 0;
this.j = 0;
this.k = 0;
this.l = com.google.protobuf.nano.l.j;
this.aO = 0;
this.aP = -1;
}
public static com.google.android.finsky.cv.a.es a(byte[] p0) {
return (com.google.android.finsky.cv.a.es)com.google.protobuf.nano.i.a(new com.google.android.finsky.cv.a.es(), p0);
}
private final com.google.android.finsky.cv.a.es b(com.google.protobuf.nano.a p0) {
1: v0 = p0.a();
5: switch (v0) {
case 0:
5: goto 14;
case 8:
5: goto 15;
case 16:
5: goto 50;
case 26:
5: goto 63;
case 32:
5: goto 126;
case 40:
5: goto 140;
case 50:
5: goto 154;
case 56:
5: goto 206;
case 64:
5: goto 269;
case 72:
5: goto 283;
case 80:
5: goto 320;
case 90:
5: goto 334;
default:
}
12: if (super.a(p0, v0)) goto 1;
14: return this;
19: this.a = this.a | 1;
25: try {
33: this.b = com.google.android.finsky.cv.a.jt.d(p0.i());
39: this.a = this.a | 1;
}
catch (IllegalArgumentException ex) {
43: p0.e(p0.o());
46: this.a(p0, v0);
}
41: goto 1;
54: this.c = p0.j();
60: this.a = this.a | 2;
62: goto 1;
71: if (this.d == 0)
73: v0 = 0;
else
109: v0 = this.d.length;
75: v2 = new ch[com.google.protobuf.nano.l.a(p0, 26) + v0];
77: if (v0 != 0)
81: System.arraycopy(this.d, 0, v2, 0, v0);
84: while (v0 < v2.length - 1) {
94: v2[v0] = new com.google.android.finsky.cv.a.ch();
98: p0.a(v2[v0]);
101: p0.a();
104: v0 = v0 + 1;
}
106: goto 111;
116: v2[v0] = new com.google.android.finsky.cv.a.ch();
120: p0.a(v2[v0]);
123: this.d = v2;
125: goto 1;
130: this.e = p0.i();
136: this.a = this.a | 4;
138: goto 1;
144: this.f = p0.i();
150: this.a = this.a | 8;
152: goto 1;
162: if (this.h == 0)
164: v0 = 0;
else
194: v0 = this.h.length;
166: v2 = new String[com.google.protobuf.nano.l.a(p0, 50) + v0];
168: if (v0 != 0)
172: System.arraycopy(this.h, 0, v2, 0, v0);
175: while (v0 < v2.length - 1) {
184: v2[v0] = p0.f();
186: p0.a();
189: v0 = v0 + 1;
}
191: goto 196;
200: v2[v0] = p0.f();
202: this.h = v2;
204: goto 1;
210: this.a = this.a | 32;
216: try {
216: v3 = p0.i();
220: switch (v3) {
case 0:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 1:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 2:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 3:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 4:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 5:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 6:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 7:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
case 8:
259: try {
259: this.i = v3;
265: this.a = this.a | 32;
}
catch (IllegalArgumentException ex) {
251: p0.e(p0.o());
254: this.a(p0, v0);
}
389: break;
default:
249: throw new IllegalArgumentException(47 + v3 + " is not a valid enum AndroidCategory");
}
}
catch (IllegalArgumentException ex) {
}
251: p0.e(p0.o());
254: this.a(p0, v0);
257: goto 1;
273: this.j = p0.i();
279: this.a = this.a | 64;
281: goto 1;
287: this.a = this.a | 128;
293: try {
301: this.k = com.google.android.finsky.cv.a.l.a(p0.i());
307: this.a = this.a | 128;
}
catch (IllegalArgumentException ex) {
312: p0.e(p0.o());
315: this.a(p0, v0);
}
309: goto 1;
324: this.g = p0.j();
330: this.a = this.a | 16;
332: goto 1;
342: if (this.l == 0)
344: v0 = 0;
else
374: v0 = this.l.length;
346: v2 = new String[com.google.protobuf.nano.l.a(p0, 90) + v0];
348: if (v0 != 0)
352: System.arraycopy(this.l, 0, v2, 0, v0);
355: while (v0 < v2.length - 1) {
364: v2[v0] = p0.f();
366: p0.a();
369: v0 = v0 + 1;
}
371: goto 376;
380: v2[v0] = p0.f();
382: this.l = v2;
384: goto 1;
}
public final com.google.protobuf.nano.i a(com.google.protobuf.nano.a p0) {
return this.b(p0);
}
public final void a(CodedOutputByteBufferNano p0) {
v1 = 0;
if (this.a & 1)
p0.a(1, this.b);
if (this.a & 2)
p0.b(2, this.c);
if (this.d != 0 && this.d.length > 0) {
v0 = 0;
while (v0 < this.d.length) {
if (this.d[v0] != 0)
p0.b(3, this.d[v0]);
v0 = v0 + 1;
}
}
if (this.a & 4)
p0.a(4, this.e);
if (this.a & 8)
p0.a(5, this.f);
if (this.h != 0 && this.h.length > 0) {
v0 = 0;
while (v0 < this.h.length) {
if (this.h[v0] != 0)
p0.a(6, this.h[v0]);
v0 = v0 + 1;
}
}
if (this.a & 32)
p0.a(7, this.i);
if (this.a & 64)
p0.a(8, this.j);
if (this.a & 128)
p0.a(9, this.k);
if (this.a & 16)
p0.b(10, this.g);
if (this.l != 0 && this.l.length > 0)
while (v1 < this.l.length) {
if (this.l[v1] != 0)
p0.a(11, this.l[v1]);
v1 = v1 + 1;
}
super.a(p0);
}
protected final int b() {
v1 = 0;
v0 = super.b();
if (this.a & 1)
v0 = v0 + CodedOutputByteBufferNano.d(1, this.b);
if (this.a & 2)
v0 = v0 + CodedOutputByteBufferNano.f(2, this.c);
if (this.d != 0 && this.d.length > 0) {
v2 = v0;
v0 = 0;
while (v0 < this.d.length) {
if (this.d[v0] != 0)
v2 = v2 + CodedOutputByteBufferNano.d(3, this.d[v0]);
v0 = v0 + 1;
}
v0 = v2;
}
if (this.a & 4)
v0 = v0 + CodedOutputByteBufferNano.d(4, this.e);
if (this.a & 8)
v0 = v0 + CodedOutputByteBufferNano.d(5, this.f);
if (this.h != 0 && this.h.length > 0) {
v2 = 0;
v3 = 0;
v4 = 0;
while (v2 < this.h.length) {
if (this.h[v2] != 0) {
v4 = v4 + 1;
v3 = v3 + CodedOutputByteBufferNano.b(this.h[v2]);
}
v2 = v2 + 1;
}
v0 = v0 + v3 + v4 * 1;
}
if (this.a & 32)
v0 = v0 + CodedOutputByteBufferNano.d(7, this.i);
if (this.a & 64)
v0 = v0 + CodedOutputByteBufferNano.d(8, this.j);
if (this.a & 128)
v0 = v0 + CodedOutputByteBufferNano.d(9, this.k);
if (this.a & 16)
v0 = v0 + CodedOutputByteBufferNano.f(10, this.g);
if (this.l != 0 && this.l.length > 0) {
v2 = 0;
v3 = 0;
while (v1 < this.l.length) {
if (this.l[v1] != 0) {
v3 = v3 + 1;
v2 = v2 + CodedOutputByteBufferNano.b(this.l[v1]);
}
v1 = v1 + 1;
}
v0 = v0 + v2 + v3 * 1;
}
return v0;
}
public final boolean equals(Object p0) {
v0 = 1;
if (p0 != this) {
if (!(p0 instanceof com.google.android.finsky.cv.a.es))
v0 = 0;
else {
p0 = (com.google.android.finsky.cv.a.es)p0;
if ((this.a & 1) != (p0.a & 1))
v0 = 0;
else if (this.b != p0.b)
v0 = 0;
else if ((this.a & 2) != (p0.a & 2))
v0 = 0;
else if (this.c != p0.c)
v0 = 0;
else if (!com.google.protobuf.nano.h.a(this.d, p0.d))
v0 = 0;
else if ((this.a & 4) != (p0.a & 4))
v0 = 0;
else if (this.e != p0.e)
v0 = 0;
else if ((this.a & 8) != (p0.a & 8))
v0 = 0;
else if (this.f != p0.f)
v0 = 0;
else if ((this.a & 16) != (p0.a & 16))
v0 = 0;
else if (this.g != p0.g)
v0 = 0;
else if (!com.google.protobuf.nano.h.a(this.h, p0.h))
v0 = 0;
else if ((this.a & 32) != (p0.a & 32))
v0 = 0;
else if (this.i != p0.i)
v0 = 0;
else if ((this.a & 64) != (p0.a & 64))
v0 = 0;
else if (this.j != p0.j)
v0 = 0;
else if ((this.a & 128) != (p0.a & 128))
v0 = 0;
else if (this.k != p0.k)
v0 = 0;
else if (!com.google.protobuf.nano.h.a(this.l, p0.l))
v0 = 0;
else if (this.aO == 0 || this.aO.b()) {
if (p0.aO != 0 && !p0.aO.b())
v0 = 0;
}
else
v0 = this.aO.equals(p0.aO);
}
}
return v0;
}
public final int hashCode() {
if (this.aO == 0 || this.aO.b())
v0 = 0;
else
v0 = this.aO.hashCode();
return v0 + ((((((((((((this.getClass().getName().hashCode() + 527) * 31 + this.b) * 31 + (int)(this.c ^ this.c >>> 32)) * 31 + com.google.protobuf.nano.h.a(this.d)) * 31 + this.e) * 31 + this.f) * 31 + (int)(this.g ^ this.g >>> 32)) * 31 + com.google.protobuf.nano.h.a(this.h)) * 31 + this.i) * 31 + this.j) * 31 + this.k) * 31 + com.google.protobuf.nano.h.a(this.l)) * 31;
}
}
| true |
43cf7af1d06c7298fa93e493f44270e67fc108a7 | Java | bellmit/testeMauricio | /cobranca/src/main/java/br/com/politec/sao/iso/ISOMessageLogger.java | ISO-8859-1 | 4,652 | 2.453125 | 2 | [] | no_license | package br.com.politec.sao.iso;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Date;
import br.com.politec.sao.util.Appender;
import br.com.politec.sao.util.Assertions;
import br.gov.caixa.iso.ISOMsg;
import br.gov.caixa.sigcb.util.LogUtilSigcb;
/**
* <B>Projeto: Framework Politec Generic Beans</B><BR>
* Utilitrio para formatao de log de mensagens ISO. Utilizado em ambiente de
* desenvolvimento.
*
* @author Daniel Yukio Yokomiso - Politec Informatica
* @version release 1.3
*/
public class ISOMessageLogger {
private final StringBuffer out;
private final String type;
public ISOMessageLogger(String type) {
Assertions.requires(type != null);
this.type = type;
this.out = new StringBuffer(1024);
}
public void printOn(OutputStream stream, ISOMsg[] messages)
throws IOException {
printOn(messages);
}
public void printOn(ISOMsg[] messages) throws IOException {
Assertions.requires(messages != null);
appendMessagesHeader(messages);
appendMessages(messages);
appendMessagesFooter();
StringWriter str = new StringWriter();
Appender out = new Appender(str);
writeToStream(out);
out.close();
String messageText = str.toString();
LogUtilSigcb.info(messageText);
if (LogUtilSigcb.isWarnEnabled()) {
if (messageText.indexOf("outgoing:message") >= 0) {
int inicioNomeTransacao = messageText.indexOf("bitNumber='63'>")
+ "bitNumber='63'>".length();
int fimNomeTransacao = inicioNomeTransacao + 4;
LogUtilSigcb.warn(messageText.substring(inicioNomeTransacao,
fimNomeTransacao));
}
}
}
/**
* @param messages
* @throws IOException
*/
public String geraMensagem(ISOMsg[] messages) {
Assertions.requires(messages != null);
appendMessagesHeader(messages);
appendMessages(messages);
appendMessagesFooter();
return out.toString();
}
private void appendMessagesHeader(ISOMsg[] messages) {
out.append("<");
out.append(type);
out.append(":messages count='");
out.append(messages.length);
out.append("' date='");
out.append(new Date());
out.append("'>").append("\r\n");
}
private void appendMessages(ISOMsg[] messages) {
for (int i = 0; i < messages.length; i++) {
appendMessage(i, messages[i]);
}
}
private void appendMessagesFooter() {
out.append("</").append(type).append(":messages>").append("\r\n");
}
private void appendMessage(int index, ISOMsg message) {
appendMessageHeader(index);
if (message != null) {
appendISOFields(message);
} else {
out.append(" NULL").append("\r\n");
}
appendMessageFooter();
}
private void appendMessageHeader(int index) {
out.append(" <");
out.append(type);
out.append(":message index='");
out.append(index);
out.append("'>").append("\r\n");
}
private void appendISOFields(ISOMsg message) {
appendISOField(0, message);
appendISOField(3, message);
appendISOField(33, message);
appendISOField(39, message);
appendISOField(62, message);
appendISOField(63, message);
appendISOField(71, message);
appendISOField(72, message);
appendISOField(100, message);
appendISOField(120, message);
}
private void appendMessageFooter() {
out.append(" </");
out.append(type);
out.append(":message>").append("\r\n");
}
private void appendISOField(int isoField, ISOMsg message) {
if (message.hasField(isoField)) {
out.append(" <iso:field bitNumber='");
out.append(isoField);
out.append("'>");
if (isoField==63){
out.append(message.getString(isoField));
}else{
out.append(message.getString(isoField));
}
out.append("</iso:field>").append("\r\n");
}
}
private void writeToStream(OutputStream stream) throws IOException {
stream.write(this.out.toString().getBytes());
stream.flush();
this.out.setLength(0);
}
} | true |
c459884378ad682022228627613f33ee09baa908 | Java | iNotEsco/My-work | /Eclipse Workspace Java/workspace/Assignment02/assg5_Escobar/TestComplexNum.java | UTF-8 | 2,781 | 3.203125 | 3 | [] | no_license | package assg5_Escobar;
import junit.framework.TestCase;
public class TestComplexNum extends TestCase{
private ComplexNum x, y, z;
protected void setUp(){
x = new ComplexNum();
y = new ComplexNum(4.1);
z = new ComplexNum(4.1,1.3);
}
public void testDefaultConstructor() {
assertEquals("Real Value: ", 0, x.getReal(), 0.00001);
assertEquals("Imaginary Value: ", 0, x.getImaginary(), 0.00001);
}
public void testOneParamConstructor() {
assertEquals("Real Value: ", 4.1, y.getReal(), 0.00001);
assertEquals("Imaginary Value: ", 0, y.getImaginary(), 0.00001);
}
public void testTwoParamConstructor() {
assertEquals("Real Value: ", 4.1, z.getReal(), 0.00001);
assertEquals("Imaginary Value: ", 1.3, z.getImaginary(), 0.00001);
}
public void testGetReal(){
assertEquals("Get Real Value: ", 4.1, z.getReal(), 0.00001);
}
public void testGetImaginary(){
assertEquals("Get Imaginary Value: ", 1.3, z.getImaginary(), 0.00001);
}
public void testSetReal(){
x.setReal(9.6);
assertEquals("Set Real: ", 9.6, x.getReal());
}
public void testSetImaginary(){
x.setImaginary(5.4);
assertEquals("Set Imaginary: ", 5.4, x.getImaginary());
}
public void testAdd(){
ComplexNum temp = new ComplexNum(2.2, 3.2);
ComplexNum sum = z.add(temp);
assertEquals("Real Value: ", 6.3, sum.getReal(), 0.00001);
assertEquals("Imaginary Value: ", 4.5, sum.getImaginary(), 0.00001);
}
public void testSub(){
ComplexNum temp = new ComplexNum(2.3, 3.2);
ComplexNum diff = z.sub(temp);
assertEquals("Real Value: ", 1.8, diff.getReal(), 0.00001);
assertEquals("Imaginary Value: ", -1.9, diff.getImaginary(), 0.00001);
}
public void testMul(){
ComplexNum temp = new ComplexNum(2.3, 3.2);
ComplexNum product = z.mul(temp);
assertEquals("Real Value: ", 5.27, product.getReal(), 0.00001);
assertEquals("Imaginary Value: ", 16.11, product.getImaginary(), 0.00001);
}
public void testNeg(){
ComplexNum neg = new ComplexNum(-z.getReal(),-z.getImaginary());
assertEquals("Real Value: ", -4.1, neg.getReal(), 0.00001);
assertEquals("Imaginary Value: ", -1.3, neg.getImaginary(), 0.00001);
}
public void testToString(){
assertEquals("Test toString when real and imaginary are 0: ", "",x.toString());
assertEquals("Test toString when imaginary is 0: ", "4.1", y.toString());
x.setImaginary(-5.4);
assertEquals("Test toString when real is 0: ", "-5.4i", x.toString());
assertEquals("Test toString when none are 0: ", "4.1 + 1.3i", z.toString());
assertEquals("Test toString when both are negative: ", "-4.1 - 1.3i", z.neg().toString());
}
public void testEquals(){
ComplexNum temp = z;
assertEquals("Test toString when true: ", true, temp.equals(z));
assertEquals("Test toString when false: ", false, temp.equals(x));
}
} | true |
9db6d5e8781cfe29c5214b286f00088339a8fa7f | Java | Hronoz87/coursework-Transfer_of_money | /src/main/java/ru/netology/coursework/service/ConfirmOperationDTO.java | UTF-8 | 888 | 2.28125 | 2 | [] | no_license | package ru.netology.coursework.service;
public class ConfirmOperationDTO {
public String operationId;
public String code;
public ConfirmOperationDTO(String operationId, String code) {
this.operationId = operationId;
this.code = code;
}
public ConfirmOperationDTO() {
}
public String getOperationId() {
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public String getVerificationCode() {
return code;
}
public void setVerificationCode(String verificationCode) {
this.code = verificationCode;
}
@Override
public String toString() {
return "ConfirmOperationDTO{" +
"operationId='" + operationId + '\'' +
", verificationCode='" + code + '\'' +
'}';
}
}
| true |
7f41fe0e07b21127f85623b4de0af2be72ded67d | Java | asiekierka/LagssieMC | /src/main/java/pl/asie/lagssie/Lagssie.java | UTF-8 | 2,150 | 2.109375 | 2 | [
"MIT"
] | permissive | package pl.asie.lagssie;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(modid = Lagssie.MODID, version = Lagssie.VERSION, acceptableRemoteVersions = "*", acceptedMinecraftVersions = "[1.9,1.13)")
public class Lagssie {
public static final String MODID = "lagssie";
public static final String VERSION = "@VERSION@";
public static Logger logger;
public static Configuration config;
public static double intervalClient, intervalServer;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
logger = LogManager.getLogger("lagssie");
config = new Configuration(event.getSuggestedConfigurationFile());
intervalClient = config.getFloat("intervalClient", "general", 0.25f, 0f, 1000.0f, "If the client is stuck longer than this amount of time (in seconds), dump a stacktrace of what it is doing. Set to 0 to disable.");
intervalServer = config.getFloat("intervalServer", "general", 0.25f, 0f, 1000.0f, "If the server is stuck longer than this amount of time (in seconds), dump a stacktrace of what it is doing. Set to 0 to disable.");
config.save();
}
@EventHandler
public void init(FMLInitializationEvent event) {
if (intervalServer > 0) {
MinecraftForge.EVENT_BUS.register(new LagssieServer());
}
if (FMLCommonHandler.instance().getSide() == Side.CLIENT && intervalClient > 0) {
initClient();
}
}
@SideOnly(Side.CLIENT)
public void initClient() {
MinecraftForge.EVENT_BUS.register(new LagssieClient());
}
}
| true |
94c2aab28ee2275834e36a98cf916fe834d55dd1 | Java | Tboy70/BusNetworkSimulator | /src/fr/utbm/info/gl52/Graphics/Itinerary/GraphicItinerary.java | UTF-8 | 395 | 1.960938 | 2 | [] | no_license | package fr.utbm.info.gl52.Graphics.Itinerary;
import java.awt.Color;
import java.awt.Point;
import fr.utbm.info.gl52.Middle.Itineraire;
import fr.utbm.set.io.shape.ESRIBounds;
public class GraphicItinerary extends AbstractGraphicItinerary {
public GraphicItinerary(Itineraire iti, Point off, Color c, ESRIBounds b) {
super(iti, off, c, b);
// TODO Auto-generated constructor stub
}
}
| true |
219c4ea28a05ac9eddfbadc54cb15c2f69669519 | Java | stebog92/acs | /Proiectarea Algoritmilor/Lab06/codeBase/Java/src/Maze.java | UTF-8 | 2,164 | 3.4375 | 3 | [] | no_license |
import java.util.Scanner;
public class Maze implements Readable {
private int height, width;
private char[][] cell;
private void allocate() {
cell = new char[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cell[i][j] = 1;
}
}
}
public Maze(int height, int width) {
this.height = height;
this.width = width;
allocate();
}
public int get_width() {
return width;
}
public int get_height() {
return height;
}
public boolean is_walkable(int line, int column) {
if (line >= 0 && line < height && column >= 0 && column < width) {
return cell[line][column] != '#';
} else {
return false;
}
}
public boolean is_walkable(Coord coord) {
return is_walkable(coord.lin, coord.col);
}
public boolean is_exit_point(int line, int column) {
if (line >= 0 && line < height && column >= 0 && column < width) {
return is_walkable(line, column)
&& (line == 0 || line == height - 1 || column == 0 || column == width - 1);
} else {
return false;
}
}
public boolean is_exit_point(Coord coord) {
return is_exit_point(coord.lin, coord.col);
}
public void mark_solution_step(int line, int column) {
if (line >= 0 && line < height && column >= 0 && column < width) {
cell[line][column] = '*';
}
}
public void mark_solution_step(Coord coord) {
mark_solution_step(coord.lin, coord.col);
}
//@Override
public void read(Scanner scanner) {
for (int i = 0; i < height; i++) {
String cLine = scanner.nextLine();
for (int j = 0; j < width; j++) {
cell[i][j] = cLine.charAt(j);
}
}
}
public void print() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(cell[i][j]);
}
System.out.println();
}
}
}
| true |
43fa33e0fde23deb44e4e7290e47fe0ba1f0bdd1 | Java | xiaolowe/zwhs_sp_api | /zwhs_sp_api/.svn/pristine/ea/eadda27fbf69375d987e3cbcaf7792d644f02057.svn-base | UTF-8 | 2,592 | 2.09375 | 2 | [] | no_license | /*
* 文 件 名: ServiceSearch.java
* 版 权: CCDC Copyright 2016, All rights reserved
* 描 述: 服务商平台
* 修 改 人: Lanbo
* 创建时间: 2016年1月26日
*/
package cn.org.citycloud.zwhs.bean;
/**
* 服务列表查询
*
* @author lanbo
* @version [V1.0, 2016年1月26日]
* @since [B2C/V1.0]
*/
public class ServiceSearch
{
private String serviceName;
private int type = 0;
private int serviceState = -1;
private int serviceVerify = -1;
private int page = 1;
private int pageSize = 10;
/**
* 获取 serviceName
*
* @return 返回 serviceName
*/
public String getServiceName()
{
return serviceName;
}
/**
* 设置 serviceName
*
* @param 对serviceName进行赋值
*/
public void setServiceName(String serviceName)
{
this.serviceName = serviceName;
}
/**
* 获取 type
*
* @return 返回 type
*/
public int getType()
{
return type;
}
/**
* 设置 type
*
* @param 对type进行赋值
*/
public void setType(int type)
{
this.type = type;
}
/**
* 获取 serviceState
*
* @return 返回 serviceState
*/
public int getServiceState()
{
return serviceState;
}
/**
* 设置 serviceState
*
* @param 对serviceState进行赋值
*/
public void setServiceState(int serviceState)
{
this.serviceState = serviceState;
}
/**
* 获取 page
*
* @return 返回 page
*/
public int getPage()
{
return page;
}
/**
* 设置 page
*
* @param 对page进行赋值
*/
public void setPage(int page)
{
this.page = page;
}
/**
* 获取 pageSize
*
* @return 返回 pageSize
*/
public int getPageSize()
{
return pageSize;
}
/**
* 设置 pageSize
*
* @param 对pageSize进行赋值
*/
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}
/**
* 获取 serviceVerify
*
* @return 返回 serviceVerify
*/
public int getServiceVerify()
{
return serviceVerify;
}
/**
* 设置 serviceVerify
*
* @param 对serviceVerify进行赋值
*/
public void setServiceVerify(int serviceVerify)
{
this.serviceVerify = serviceVerify;
}
}
| true |
f6c3a91f4dd44586d31ca0f8e7be339496423dec | Java | Dreyer1/dreyer-common | /src/main/java/com/dreyer/common/enums/MessageType.java | UTF-8 | 432 | 2.421875 | 2 | [] | no_license | package com.dreyer.common.enums;
/**
* @author: Dreyer
* @date: 16/6/19 上午9:04
* @description: 消息类型
*/
public enum MessageType {
/**
* 邮件消息
*/
EMAIL(1);
private Integer value;
MessageType(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
| true |
6f4c92b4e67691d3111e2cc0d3d19804e14940c6 | Java | IGPGroup17/frontend2 | /app/src/main/java/com/example/personalprofile/activities/ReadReviewsActivity.java | UTF-8 | 2,644 | 1.914063 | 2 | [
"MIT"
] | permissive | package com.example.personalprofile.activities;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import com.example.personalprofile.AppUser;
import com.example.personalprofile.R;
import com.example.personalprofile.activities.meta.ObservingActivity;
import com.example.personalprofile.models.Review;
import com.example.personalprofile.repositories.AllReviewRepository;
import com.example.personalprofile.repositories.context.ReviewModificationContext;
import com.example.personalprofile.repositories.meta.observer.NotificationContext;
import com.example.personalprofile.views.ReviewRecyclerViewAdapter;
import java.util.ArrayList;
import java.util.List;
public class ReadReviewsActivity extends ObservingActivity<List<Review>> {
private final List<Review> currentReviews = new ArrayList<>();
private RecyclerView recyclerView;
private ReviewRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_my_reviews);
recyclerView = findViewById(R.id.review_recycler_view);
adapter = new ReviewRecyclerViewAdapter(currentReviews);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
findViewById(R.id.homebutton).setOnClickListener(listener -> onClickHomeButton()); // home button
findViewById(R.id.chatbutton).setOnClickListener(listener -> onClickChatButton());
findViewById(R.id.personalprofile).setOnClickListener(listener -> onClickPersonalProfileButton());
AllReviewRepository.getInstance().sendRequest(this, ReviewModificationContext.ReadAll.of(AppUser.getInstance().getCurrentReviewOrganiserId()));
}
public void onClickHomeButton() {
Intent intent = new Intent(this, HomePageActivity.class);
startActivity(intent);
}
public void onClickChatButton() {
Intent intent = new Intent(this, EventChatActivity.class);
startActivity(intent);
}
public void onClickPersonalProfileButton() {
Intent intent = new Intent(this, OrganiserProfileActivity.class);
startActivity(intent);
}
@Override
public void onNotification(NotificationContext<List<Review>> notificationContext) {
currentReviews.clear();
currentReviews.addAll(notificationContext.getData());
adapter.notifyDataSetChanged();
}
} | true |
0324c3dbb80d1de38067e39ea31f4514df4daacb | Java | Cognizant-Training-Coimbatore/Lab-Excercise-Batch-2 | /Parvathy S/22-01-2020/prog17_square.java | UTF-8 | 280 | 3.015625 | 3 | [] | no_license | import java.util.Scanner;
public class prog17_square {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no: ");
int a=sc.nextInt();
int x;
x=a*a;
System.out.println("Square= "+x);
}
}
| true |
db42c5b561c46bde2f70bfd378918442a843cb75 | Java | chenhq/newrelic_ref | /src/rewriter/com/newrelic/javassist/tools/framedump.java | UTF-8 | 1,029 | 2.203125 | 2 | [] | no_license | /* */ package com.newrelic.javassist.tools;
/* */
/* */ import com.newrelic.javassist.ClassPool;
/* */ import com.newrelic.javassist.CtClass;
/* */ import com.newrelic.javassist.bytecode.analysis.FramePrinter;
/* */ import java.io.PrintStream;
/* */
/* */ public class framedump
/* */ {
/* */ public static void main(String[] args)
/* */ throws Exception
/* */ {
/* 37 */ if (args.length != 1) {
/* 38 */ System.err.println("Usage: java javassist.tools.framedump <class file name>");
/* 39 */ return;
/* */ }
/* */
/* 42 */ ClassPool pool = ClassPool.getDefault();
/* 43 */ CtClass clazz = pool.get(args[0]);
/* 44 */ System.out.println("Frame Dump of " + clazz.getName() + ":");
/* 45 */ FramePrinter.print(clazz, System.out);
/* */ }
/* */ }
/* Location: /home/think/Downloads/newrelic-android-4.120.0/lib/class.rewriter.jar
* Qualified Name: com.newrelic.javassist.tools.framedump
* JD-Core Version: 0.6.2
*/ | true |
d356506b2156c5277866f430a43cc8680040ec70 | Java | Kitty-Kitty/FastBle | /app/src/main/java/com/clj/blesample/service/connect/BleConnectCallbackWrap.java | UTF-8 | 1,658 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | package com.clj.blesample.service.connect;
import com.clj.blesample.service.BleSensor;
import com.clj.fastble.callback.BleGattCallback;
/**
* 对BleConnectCallback的封装,包含BleSensor对象信息
*
* @author f
* @version 1.0
* @created 25-7月-2020 21:06:06
*/
public abstract class BleConnectCallbackWrap extends BleGattCallback {
/**
* 连接服务回调函数对象
*/
private ConnectServiceCallback connectServiceCallback;
/**
* 表示当前操作的bleSensor对象
*/
private BleSensor bleSensor;
private BleConnectCallbackWrap() {
}
public void finalize() throws Throwable {
}
/**
* @param bleSensor 表示当前操作的bleSensor对象
* @param cc 连接服务回调函数对象
*/
public BleConnectCallbackWrap(BleSensor bleSensor, ConnectServiceCallback cc) {
this.bleSensor = bleSensor;
this.connectServiceCallback = cc;
}
/**
* 连接服务回调函数对象
*/
public ConnectServiceCallback getConnectServiceCallback() {
return connectServiceCallback;
}
/**
* 连接服务回调函数对象
*
* @param newVal
*/
public void setConnectServiceCallback(ConnectServiceCallback newVal) {
connectServiceCallback = newVal;
}
/**
* 表示当前操作的bleSensor对象
*/
public BleSensor getBleSensor() {
return bleSensor;
}
/**
* 表示当前操作的bleSensor对象
*
* @param newVal
*/
public void setBleSensor(BleSensor newVal) {
bleSensor = newVal;
}
}//end BleConnectCallbackWrap | true |