blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
777577e41374ee404ed4bad19c8a8d4a03db3b99 | a291c2ca62af9c9c4c46dfb9b7e51c8904a39d45 | /src/PuzzleState.java | 166210aadca1bd075dd94253f348100d253e8c07 | [] | no_license | sohaibsalman/NPuzzleSolver | feab101016f626f7e92fcf74c993cc5ff2614bc2 | 781a143d2a9081fda44a6c2db4fd8dd6d0fb97ae | refs/heads/master | 2022-04-10T05:23:21.216882 | 2020-03-23T09:40:04 | 2020-03-23T09:40:04 | 249,366,455 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,520 | java | /*
* 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.
*/
/**
*
* @author sohai
*/
public class PuzzleState
{
int [][] state;
int size;
Position zeroPosition = new Position();
PuzzleState parent = null;
public PuzzleState(int size)
{
this.size = size;
state = new int[size][size];
}
public PuzzleState(int[][] state, int size)
{
this.state = state;
this.size = size;
}
public PuzzleState(PuzzleState ref)
{
this.size = ref.size;
this.state = new int[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
this.state[i][j] = ref.state[i][j];
}
}
this.zeroPosition.i = ref.zeroPosition.i;
this.zeroPosition.j = ref.zeroPosition.j;
parent = ref;
}
@Override
public String toString()
{
String str = "(";
int count = 0;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
str += state[i][j];
if(++count != size*size)
str += ", ";
}
}
str += ")";
return str;
}
}
class Position
{
int i;
int j;
} | [
"53570067+sohaibsalman@users.noreply.github.com"
] | 53570067+sohaibsalman@users.noreply.github.com |
bcc5f41e1ecc793271bbfc1e87ea667f085f0657 | 7754a71d0a1f4c0b0cd8bc4e7c3093ff74a18599 | /src/main/java/com/thinkgem/jeesite/modules/ty/dao/TywjingphkDao.java | 37dd3e75e5ae1a59a219cffcb52eb4d4673dab69 | [
"Apache-2.0"
] | permissive | gxhs/jeesite | 16f7ef0edfb812d3f98e097fcd60a99bbb86348c | 081db2cef935f2bf6d52cfaeda06e6269e9bcb9a | refs/heads/master | 2020-04-11T07:14:37.654958 | 2018-12-16T14:00:48 | 2018-12-16T14:00:48 | 161,605,109 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 494 | java | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.ty.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.ty.entity.Tywjingphk;
/**
* 艺海画库DAO接口
* @author wf
* @version 2018-12-14
*/
@MyBatisDao
public interface TywjingphkDao extends CrudDao<Tywjingphk> {
} | [
"15029378233@163.com"
] | 15029378233@163.com |
4280225c6c6ced762c985f4836ececac64c3e3f8 | 480f5108ca2f767bd702f2e8c8c6ed752a5fb746 | /Bindings/src/main/java/com/aiconoa/bindings/MainApp.java | 6aebfa019fe4e56d5363f2b48f91f6309be3ccdf | [] | no_license | aiconoa/JavaFX2-demos | 007a8be1fe8e6058d133e8248cb537aaba0c4901 | 6ee1551df70aede8df7c774381a46ab2c718321b | refs/heads/master | 2020-05-30T09:13:30.406693 | 2014-02-13T10:22:34 | 2014-02-13T10:22:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,254 | java | /*
* The MIT License (MIT)
*
* Copyright 2014 AICONOA.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.aiconoa.bindings;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setTitle("Bindings");
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| [
"thomas.gros@gmail.com"
] | thomas.gros@gmail.com |
6dce769f8abea788cab5807387f8ec42ae700ef9 | 730c52f6446c0ef8343539572c5486b7ab57ff55 | /Vector/VectorExample17.java | c6929cb435b0674eed22accb27b0fae0ab4efe82 | [] | no_license | nicknkm2020/CollectionFramework | 21ede7bb21071611035215ccbe815b4b6ed04025 | 274a8dbe0e1c3a17c3521109b41b27ac948af1cb | refs/heads/master | 2021-06-13T12:51:49.158316 | 2017-03-22T02:41:08 | 2017-03-22T02:41:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | package Vector;
import java.util.Vector;
/*
* Example of indexOf(Object o,int index) method.
*/
public class VectorExample17
{
public static void main( String[] args )
{
Vector<Integer> vector = new Vector<Integer>();
vector.add(10);
vector.add(30);
vector.add(30);
vector.add(40);
vector.add(30);
vector.add(50);
vector.add(30);
System.out.println("vector : " + vector + "\n");
/*
* Returns the index of the first occurrence of the specified element in
* this vector, searching forwards from index, or returns -1 if the
* element is not found.
*/
int indexPosition = vector.indexOf(30, 3);
System.out.println("indexPosition : " + indexPosition + "\n");
}
} | [
"namanmandli@gmail.com"
] | namanmandli@gmail.com |
cdf73373a132f22bbb7caa532ae21b95ed00c01f | cecffdf2f0f00ee6552e52b1559b14f26e4dc988 | /src/main/java/br/edu/ifnmg/avaliar/logic/GenericLogic.java | 057e32e533afec61d868356b7d5c06d5e4630f3a | [
"Apache-2.0"
] | permissive | dsalinux/if-avaliar | e0aebd5fddeb3144a66972059f7e9588cf013668 | 336adfa2109fd08418387816ae82cc2225d1feac | refs/heads/master | 2016-09-13T04:13:52.960318 | 2016-04-12T13:40:38 | 2016-04-12T13:40:38 | 56,066,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 505 | java | package br.edu.ifnmg.avaliar.logic;
import br.edu.ifnmg.avaliar.util.exception.BusinessException;
import br.edu.ifnmg.avaliar.util.exception.SystemException;
import java.util.List;
public interface GenericLogic<E> {
E save(E entity) throws BusinessException, SystemException;
void delete(E entity) throws BusinessException, SystemException;
E refresh(E entity) throws BusinessException, SystemException;
List<E> find(E entity) throws BusinessException, SystemException;
}
| [
"danilo@danilo-System-Product-Name"
] | danilo@danilo-System-Product-Name |
dc5b9b5197d5a8f1dd0c0585fedbdd344278415f | fe47608c29ed846885339f4055a1679bea331aaa | /src/main/java/io/javaweb/community/common/BaseEntity.java | 1a2f111ed3ff2af55ac1488151aabd229d341806 | [] | no_license | fhapp5/javaweb-community | 120232b54fc7fb573c44115a8f651dd48422de69 | 69d6fd9f13e8de74354bc973cc6be75085593055 | refs/heads/master | 2020-03-08T02:56:08.826572 | 2018-04-08T10:34:31 | 2018-04-08T10:34:31 | 127,875,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,895 | java | package io.javaweb.community.common;
import java.io.Serializable;
import java.util.Date;
import com.alibaba.fastjson.annotation.JSONField;
import io.javaweb.community.entity.UserEntity;
import io.javaweb.community.enums.Status;
import io.javaweb.community.generate.Ignore;
/**
* Created by KevinBlandy on 2017/10/30 16:56
*/
public abstract class BaseEntity implements Serializable{
private static final long serialVersionUID = -6026749715808202093L;
//创建用户
private String createUser;
//创建时间
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createDate;
//最后一次修改时间
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date modifyDate;
//记录状态
private Status status;
//备注信息
private String remark;
//排序字段
private Long sorted;
//当前会话用户
@Ignore
private UserEntity sessionUser;
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Long getSorted() {
return sorted;
}
public void setSorted(Long sorted) {
this.sorted = sorted;
}
public UserEntity getSessionUser() {
return sessionUser;
}
public void setSessionUser(UserEntity sessionUser) {
this.sessionUser = sessionUser;
}
}
| [
"747692844@qq.com"
] | 747692844@qq.com |
6bdc97d5c8a5d5ca741774436893514bb2beb569 | c9b8db6ceff0be3420542d0067854dea1a1e7b12 | /web/KoreanAir/src/main/java/com/ke/css/cimp/fbl/fbl2/Rule_DIM.java | 86aecd8232a6f90ef8d3f9adeb4cac94884f3811 | [
"Apache-2.0"
] | permissive | ganzijo/portfolio | 12ae1531bd0f4d554c1fcfa7d68953d1c79cdf9a | a31834b23308be7b3a992451ab8140bef5a61728 | refs/heads/master | 2021-04-15T09:25:07.189213 | 2018-03-22T12:11:00 | 2018-03-22T12:11:00 | 126,326,291 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,408 | java | package com.ke.css.cimp.fbl.fbl2;
/* -----------------------------------------------------------------------------
* Rule_DIM.java
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.5
* Produced : Fri Feb 23 16:06:09 KST 2018
*
* -----------------------------------------------------------------------------
*/
import java.util.ArrayList;
final public class Rule_DIM extends Rule
{
public Rule_DIM(String spelling, ArrayList<Rule> rules)
{
super(spelling, rules);
}
public Object accept(Visitor visitor)
{
return visitor.visit(this);
}
public static Rule_DIM parse(ParserContext context)
{
context.push("DIM");
boolean parsed = true;
int s0 = context.index;
ParserAlternative a0 = new ParserAlternative(s0);
ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>();
parsed = false;
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
Rule rule = Rule_MId_DIM.parse(context);
if ((f1 = rule != null))
{
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
@SuppressWarnings("unused")
int c1 = 0;
while (f1)
{
Rule rule = Rule_DIMS.parse(context);
if ((f1 = rule != null))
{
a1.add(rule, context.index);
c1++;
}
}
parsed = true;
}
if (parsed)
{
as1.add(a1);
}
context.index = s1;
}
ParserAlternative b = ParserAlternative.getBest(as1);
parsed = b != null;
if (parsed)
{
a0.add(b.rules, b.end);
context.index = b.end;
}
Rule rule = null;
if (parsed)
{
rule = new Rule_DIM(context.text.substring(a0.start, a0.end), a0.rules);
}
else
{
context.index = s0;
}
context.pop("DIM", parsed);
return (Rule_DIM)rule;
}
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
| [
"whdnfka111@gmail.com"
] | whdnfka111@gmail.com |
0fe070e02e9c86e4c8949b56de3669b891974557 | ede31642c10480bf7a20fa67341dc76035b8bf55 | /src/main/java/com/barbaktech/schedulerbackend/configuration/SecurityConfiguration.java | 16c6e07a79671f68d7632168e382a2670ff3195c | [] | no_license | arifahmet/scheduler-backend | 0a8fa7f7159b94dc2a69eaf074a2fb076c45ffec | ae16f45c64f8eb1fbd4712abb2bcdb84e5ef444a | refs/heads/master | 2023-03-09T13:56:13.628296 | 2021-02-28T21:23:16 | 2021-02-28T21:23:16 | 341,696,431 | 0 | 0 | null | 2021-03-01T23:10:33 | 2021-02-23T21:33:58 | Java | UTF-8 | Java | false | false | 902 | java | package com.barbaktech.schedulerbackend.configuration;
import com.okta.spring.boot.oauth.Okta;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer().jwt(); //or .opaqueToken();
http.cors();
// force a non-empty response body for 401's to make the response more browser friendly
Okta.configureResourceServer401ResponseBody(http);
}
}
| [
"arifahmetbarbak@gmail.com"
] | arifahmetbarbak@gmail.com |
63b974827b4efe77299349a2aa523ce761e54267 | 60134ae3c1d0ad6c28474522d4e0fe4e41c2c270 | /app/src/main/java/com/example/administrator/diaokes/Bean/CommentDetailBean.java | 0a731b7d0321921e3e60f0c22a07a2b62c1de220 | [] | no_license | Zenggangyang/Diaokes | f5aeccee0175be351c4d5af78df6323147bf7e0e | e0a7a7fcd5d2131763060462a8344d6158371548 | refs/heads/master | 2020-04-08T19:02:28.032306 | 2018-08-27T04:51:26 | 2018-08-27T04:51:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,414 | java | package com.example.administrator.diaokes.Bean;
import android.graphics.Bitmap;
import java.util.List;
/**
* Created by Administrator on 2018/7/19.
*/
public class CommentDetailBean {
/*
private int id;
private String nickName;
private String userLogo;
private String content;
private String imgId;
private int replyTotal;
private String createDate;
private List<ReplyDetailBean> replyList;
private Bitmap bitmap;
public CommentDetailBean(String nickName, String content, String createDate,Bitmap bitmap) {
this.nickName = nickName;
this.content = content;
this.createDate = createDate;
this.bitmap = bitmap;
}
public Bitmap getBitmap(){
return bitmap;
}
public void setBitmap(Bitmap bitmap){
this.bitmap = bitmap;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNickName() {
return nickName;
}
public void setUserLogo(String userLogo) {
this.userLogo = userLogo;
}
public String getUserLogo() {
return userLogo;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setImgId(String imgId) {
this.imgId = imgId;
}
public String getImgId() {
return imgId;
}
public void setReplyTotal(int replyTotal) {
this.replyTotal = replyTotal;
}
public int getReplyTotal() {
return replyTotal;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getCreateDate() {
return createDate;
}
public void setReplyList(List<ReplyDetailBean> replyList) {
this.replyList = replyList;
}
public List<ReplyDetailBean> getReplyList() {
return replyList;
}
*/
String name;
String content;
String imgpath;
String zan;
List<ReplyDetailBean> lists;
String time;
Bitmap bitmap;
public CommentDetailBean(String name,String content,String time,Bitmap imgpath) {
this.name = name;
this.content = content;
this.time = time;
this.bitmap = imgpath;
}
public Bitmap getBitmap(){
return bitmap;
}
public void setBitmap(Bitmap bitmap){
this.bitmap = bitmap;
}
public void setCreateDate(String createDate) {
this.time = createDate;
}
public String getCreateDate() {
return time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImgpath() {
return imgpath;
}
public void setImgpath(String imgpath) {
this.imgpath = imgpath;
}
public String getZan() {
return zan;
}
public void setZan(String zan) {
this.zan = zan;
}
public List<ReplyDetailBean> getList(){
return lists;
}
public void setList(List<ReplyDetailBean> lists) {
this.lists = lists;
}
}
| [
"2385656176@qq.com"
] | 2385656176@qq.com |
0fd9a0b26dbe0a06b506120c8d6b324449f9d063 | ff6068ffc3d1d627daa6f42655eed19b9a06ed7e | /src/main/java/rcms/utilities/daqaggregator/datasource/HardwareConnector.java | 4de833f91cf7632d7bdd8b7a3e09bfab148f39c9 | [] | no_license | andreh12/DAQAggregator | a78b4b375bfa0bf123b3b51abbf493166a0b517a | a49a48f6b7203173faad6b05af4d7baa42c7289c | refs/heads/master | 2020-12-28T23:15:59.990067 | 2016-11-29T15:48:17 | 2016-11-29T15:48:17 | 56,579,088 | 0 | 0 | null | 2016-04-19T08:29:22 | 2016-04-19T08:29:22 | null | UTF-8 | Java | false | false | 1,554 | java | package rcms.utilities.daqaggregator.datasource;
import rcms.common.db.DBConnectorException;
import rcms.common.db.DBConnectorIF;
import rcms.common.db.DBConnectorMySQL;
import rcms.common.db.DBConnectorOracle;
import rcms.utilities.daqaggregator.Application;
import rcms.utilities.hwcfg.HWCfgConnector;
import rcms.utilities.hwcfg.HWCfgDescriptor;
import rcms.utilities.hwcfg.HardwareConfigurationException;
import rcms.utilities.hwcfg.InvalidNodeTypeException;
import rcms.utilities.hwcfg.PathNotFoundException;
import rcms.utilities.hwcfg.dp.DAQPartition;
import rcms.utilities.hwcfg.dp.DAQPartitionSet;
public class HardwareConnector {
protected static DBConnectorIF _dbconn = null;
protected static HWCfgConnector _hwconn = null;
public DAQPartition getPartition(String _dpsetPath)
throws HardwareConfigurationException, PathNotFoundException, InvalidNodeTypeException {
HWCfgDescriptor dp_node = _hwconn.getNode(_dpsetPath);
DAQPartitionSet dpset = _hwconn.retrieveDPSet(dp_node);
return dpset.getDPs().values().iterator().next();
}
public void initialize(String url, String host, String port, String sid, String user, String passwd)
throws DBConnectorException, HardwareConfigurationException {
String _dbType = "ORACLE";
if (url == null || url.isEmpty()) {
url = "jdbc:oracle:thin:@" + host + ":" + port + "/" + sid;
}
if (_dbType.equals("ORACLE"))
_dbconn = new DBConnectorOracle(url, user, passwd);
else
_dbconn = new DBConnectorMySQL(url, user, passwd);
_hwconn = new HWCfgConnector(_dbconn);
}
}
| [
"maciej.gladki@gmail.com"
] | maciej.gladki@gmail.com |
e5438862dd3d81f230cc6d4840e4c5dc5281bc09 | 57bccc9613f4d78acd0a6ede314509692f2d1361 | /pbk-webapp/src/main/java/ru/armd/pbk/controllers/pbk/admin/AuditTypesControllerApi.java | cf166181cb7826cd8a66722614a4c630d87377dc | [] | no_license | mannyrobin/Omnecrome | 70f27fd80a9150b89fe3284d5789e4348cba6a11 | 424d484a9858b30c11badae6951bccf15c2af9cb | refs/heads/master | 2023-01-06T16:20:50.181849 | 2020-11-06T14:37:14 | 2020-11-06T14:37:14 | 310,620,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,237 | java | package ru.armd.pbk.controllers.pbk.admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.armd.pbk.core.controllers.BaseDomainControllerApi;
import ru.armd.pbk.core.utils.ControllerMethods;
import ru.armd.pbk.domain.core.AuditType;
import ru.armd.pbk.dto.core.AuditTypeDTO;
import ru.armd.pbk.services.core.AuditTypeService;
/**
* Контроллер типов аудита.
*/
@Controller
@RequestMapping(AuditTypesControllerApi.RM_CONTROLLER_PATH)
public class AuditTypesControllerApi
extends BaseDomainControllerApi<AuditType, AuditTypeDTO> {
public static final String RM_PATH = "/admin/audit-types";
public static final String RM_CONTROLLER_PATH = RM_API_PATH + RM_PATH;
static final String PERM_READ_AUDIT_TYPES = "hasAnyRole('DEBUG_TO_REPLACE','ADMIN_AUDIT_TYPES')";
@Autowired
AuditTypesControllerApi(AuditTypeService service) {
this.service = service;
this.auth.put(ControllerMethods.GET_SLIST, PERM_ALLOW_ALL);
this.auth.put(ControllerMethods.GET_VIEWS, PERM_READ_AUDIT_TYPES);
this.auth.put(ControllerMethods.GET_DTO, PERM_READ_AUDIT_TYPES);
}
}
| [
"malike@hipcreativeinc.com"
] | malike@hipcreativeinc.com |
a727b920975c69b3b7a9580c0c2c76b01b74f174 | d8083cda55a04ea72728675591e841bb3530aef1 | /admin/src/main/java/com/newproj/report/quotasituation/service/SchoolQuotaSituationService.java | 1e00425cdc27c4740f1dae6c9a9834374c5d305a | [] | no_license | zhongren/report2 | b788fafc7d1067ed7aa5786bd4c2e59b4f6ff6f9 | 1fcfd9a3166822c364877c99f4ba9a738c1b7497 | refs/heads/master | 2023-08-04T16:15:33.162495 | 2019-09-05T08:39:15 | 2019-09-05T08:39:15 | 206,013,762 | 0 | 0 | null | 2023-07-22T16:09:34 | 2019-09-03T07:18:41 | JavaScript | UTF-8 | Java | false | false | 12,203 | java | package com.newproj.report.quotasituation.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.newproj.core.beans.BeanUtil;
import com.newproj.core.beans.MapParam;
import com.newproj.core.exception.BusinessException;
import com.newproj.core.json.JsonSerializer;
import com.newproj.core.rest.support.AbstractBaseService;
import com.newproj.core.util.JoinUtil;
import com.newproj.core.util.NumberUtil;
import com.newproj.core.util.ScriptUtil;
import com.newproj.report.collection.dal.dao.CollectionDao;
import com.newproj.report.collection.dto.Collection;
import com.newproj.report.quotasituation.constant.SituationConstant.InstType;
import com.newproj.report.quotasituation.constant.SituationConstant.SchoolTypeEnum;
import com.newproj.report.quotasituation.dal.dao.InstQuotaSituationDao;
import com.newproj.report.quotasituation.dal.dao.QuotaSituationDao;
import com.newproj.report.quotasituation.dal.dao.VariableDao;
import com.newproj.report.quotasituation.dto.InstQuotaSituationParam;
import com.newproj.report.quotasituation.dto.QuotaSituation;
import com.newproj.report.quotasituation.dto.Variable;
import com.newproj.report.school.dal.dao.SchoolCollectionDao;
import com.newproj.report.school.dal.dao.SchoolDao;
import com.newproj.report.school.dal.dao.SchoolTypeDao;
import com.newproj.report.school.dto.School;
import com.newproj.report.school.dto.SchoolCollection;
import com.newproj.report.school.dto.SchoolType;
import com.newproj.report.sys.dal.dao.SqlExecutor;
@Service
public class SchoolQuotaSituationService extends AbstractBaseService{
@Autowired
private InstQuotaSituationDao schoolSituationDao ;
@Autowired
private QuotaSituationDao situationDao ;
@Autowired
private SchoolCollectionDao schoolCollectionDao ;
@Autowired
private CollectionDao collectionDao ;
@Autowired
private SchoolDao schoolDao ;
@Autowired
private VariableDao variableDao ;
@Autowired
private SchoolTypeDao schoolTypeDao ;
private JsonSerializer jsonse = new JsonSerializer() ;
public void init() {
setMapper( schoolSituationDao );
}
/**
* 计算学校标准化建设监测数据统计 .
* 内部参数:当前学校所有填报指标值,当前学校信息,监测计算结果
*
* @param schoolId
* @param reportingId
* @return
*/
private List<InstQuotaSituationParam> calculate( int schoolId , int reportingId ){
Map<String,Object> args = new HashMap<String,Object>() ;
School school = schoolDao.findBeanBy("id", schoolId, School.class ) ;
if( school == null )
throw new BusinessException("学校数据不存在!") ;
//获取学校参数
args.putAll( getSchoolArgs( school ) ) ;
SchoolType schoolType = schoolTypeDao.findBeanBy("id", school.getType() , SchoolType.class ) ;
//统计小学初中9年 12年义务教育学校
if( schoolType == null || !Arrays.asList(1,2,3).contains( schoolType.getType() ) )
return null ;
List<QuotaSituation> situationList = findSchoolQuotaSituation( schoolType.getType() ) ;
if( situationList == null || situationList.isEmpty() )
return null ;
//获取学校类型参数
args.putAll( getSchoolTypeArgs() );
//获取填报数据参数
Map<String,Object> collectionArgs = getCollectionArgs( reportingId , schoolId ) ;
if( collectionArgs == null || collectionArgs.isEmpty() )
//throw new BusinessException("当前学校无填报数据!") ;
return null ;
List<InstQuotaSituationParam> instSituationList = new ArrayList<InstQuotaSituationParam>() ;
for( QuotaSituation situation : situationList ){
InstQuotaSituationParam instSituation = new InstQuotaSituationParam() ;
instSituation.setSituationName( situation.getName() );
instSituation.setSituationId(situation.getId());
instSituation.setInstId( schoolId );
instSituation.setInstType( situation.getInstType() );
instSituation.setSchoolType( situation.getSchoolType() );
instSituation.setReportingId(reportingId);
//计算监测结果
String calculateScript = situation.getCalculatedFormula() , calculateResult = null ;
if( calculateScript != null && calculateScript.trim().length() > 0 ){
Map<String,Object> calculateNote = new HashMap<String,Object>() ;
try{
Map<String,Object> inArgs = getVarsValueMap(calculateScript , args) ;
//保存计算信息 .
calculateNote.put("inArgs", inArgs ) ;
calculateNote.put("script", calculateScript ) ;
calculateResult = ScriptUtil.eval( calculateScript , inArgs ) ;
instSituation.setCalculatedValue( calculateResult );
calculateNote.put("result", "计算结果:[" + calculateResult + "]" ) ;
instSituation.setState( 0 );
}catch(Exception e){
logger.error(String.format("监测结果计算出错:SCHOOL_ID:%s,SITUATION_NAME:%s,SCRIPT:%s",
schoolId , situation.getName() , situation.getCalculatedFormula() ) , e );
calculateNote.put("result", "计算出错:[" + e.getMessage() +"]" ) ;
instSituation.setState( 1 );
}
//保存计算计算结果
instSituation.setCalculatedExtra( jsonse.toJson( calculateNote ) );
}
//指标计算成功,计算是否合格 .
if( instSituation.getState() == null || instSituation.getState() == 0 ) {
Map<String,Object> eligNote = new HashMap<String,Object>() ;
//计算是否合格
args.put("$calculatedValue", NumberUtil.parsePossible( calculateResult ) ) ;
String eligibleFormula = situation.getEligibleFormula() , eligibleResult = null ;
if( eligibleFormula != null && eligibleFormula.trim() .length() > 0 ){
try{
Map<String,Object> inArgs = getVarsValueMap( eligibleFormula ,args ) ;
eligNote.put("inArgs", inArgs ) ;
eligNote.put("script", eligibleFormula ) ;
eligibleResult = ScriptUtil.eval( eligibleFormula , inArgs ) ;
instSituation.setEligibleValue(eligibleResult);
eligNote.put("result", String.format("计算结果:[%s]", eligibleResult) ) ;
instSituation.setState( 0 );
}catch(Exception e){
logger.error(String.format("监测结果计算出错:SCHOOL_ID:%s,SITUATION_NAME:%s,SCRIPT:%s",
schoolId , situation.getName() , situation.getCalculatedFormula() ) ,e);
eligNote.put("result", String.format("计算出错:[%s]", e.getMessage() ) ) ;
instSituation.setState( 1 );
}
}
instSituation.setEligibleExtra( jsonse.toJson( eligNote ) );
}
instSituationList.add( instSituation ) ;
}
return instSituationList ;
}
private List<QuotaSituation> findSchoolQuotaSituation( int schoolType ){
//统计指标
List<String> schoolTypes = new ArrayList<String>() ;
schoolTypes.add( SchoolTypeEnum.SCHOOL.name() ) ;
switch( schoolType ){
case 1 :
schoolTypes.add( SchoolTypeEnum.PRIMARY.name() ) ;
break ;
case 2 :
schoolTypes.add( SchoolTypeEnum.MIDDLE.name() ) ;
case 3 :
schoolTypes.add( SchoolTypeEnum.MIDDLE.name() ) ;
schoolTypes.add( SchoolTypeEnum.PRIMARY.name() ) ;
}
Map<String,Object> situationParam = new HashMap<String,Object>() ;
situationParam.put("instType", InstType.SCHOOL.name() ) ;
situationParam.put("schoolType", schoolTypes ) ;
List<QuotaSituation> situationList = situationDao.findBeanList(
situationParam , QuotaSituation.class ) ;
if( situationList == null || situationList.isEmpty() )
return null ;
return situationList ;
}
private Map<String,Object> getSchoolArgs( School school ){
//获取学校信息参数 .
Map<String,Object> schoolMap = BeanUtil.getBeanMap( school, false ) ;
Map<String,Object> args = new HashMap<String,Object>() ;
for( Map.Entry<String,Object> item : schoolMap.entrySet() ){
args.put( String.format("$school_%s", item.getKey() ) , NumberUtil.parsePossible( item.getValue() ) ) ;
}
return args ;
}
private Map<String,Object> getSchoolTypeArgs( ){
List<SchoolType> types = schoolTypeDao.findBeanList( null , SchoolType.class ) ;
Map<String,Object> typeArgs = new HashMap<String,Object>() ;
if( types == null || types.isEmpty() )
return typeArgs ;
for( SchoolType type : types ){
typeArgs.put( String.format("$school_type_%s", type.getId() ), type.getId() ) ;
//权重参数
typeArgs.put( String.format("$school_type_%s_%s", type.getId() , "primary_rate" ),
NumberUtil.parseFloat( type.getPrimaryRate() , 0f ) ) ;
typeArgs.put( String.format("$school_type_%s_%s", type.getId() , "middle_rate" ),
NumberUtil.parseFloat( type.getMiddleRate() , 0f ) ) ;
typeArgs.put( String.format("$school_type_%s_%s", type.getId() , "high_rate" ),
NumberUtil.parseFloat( type.getHighRate() , 0f ) ) ;
}
return typeArgs ;
}
private Map<String,Object> getCollectionArgs( int reportingId , int schoolId ){
//填报参数 .
List<SchoolCollection> collectionList = schoolCollectionDao.findBeanList(new MapParam<String,Object>()
.push("schoolId" , schoolId )
.push("reportId" , reportingId ) , SchoolCollection.class ) ;
if( collectionList == null || collectionList.isEmpty() )
return null ;
Map<String,Object> typeArgs = new HashMap<String,Object>() ;
JoinUtil.join( collectionList , new String[]{"dataType"}, "collectionId",
collectionDao.findBeanListBy("id", JoinUtil.fieldsValue(collectionList, "collectionId"), Collection.class, "id" , "valueType"),
new String[]{"valueType"}, "id");
for( SchoolCollection collection : collectionList ){
typeArgs.put(String.format("$%s", collection.getCollectionId() ), collection.getContent() ) ;
}
return typeArgs ;
}
private Map<String,Object> getVarsValueMap( String script , Map<String,Object> busiValueMap ){
if( StringUtils.isEmpty( script ) )
return null ;
List<String> vars = ScriptUtil.scriptVars( script ) ;
if( vars.isEmpty() ) return null ;
List<Variable> variables = variableDao.findBeanListBy("varName", vars , Variable.class ) ;
Map<String,Variable> variableMap = new HashMap<String,Variable>() ;
if( variables != null && !variables.isEmpty() ){
for( Variable variable : variables )
variableMap.put( variable.getVarName() , variable ) ;
}
Map<String,Object> result = new HashMap<String,Object>() ;
for( String var : vars ){
if( !variableMap.containsKey( var ) ){
result.put( var , null ) ;
continue ;
}
Variable variable = variableMap.get( var ) ;
if( "static".equalsIgnoreCase( variable.getType() ) ){
result.put( var , NumberUtil.parsePossible( variable.getValue() ) ) ;
}else if( "var".equalsIgnoreCase( variable.getType() ) ){
String keyName = StringUtils.isEmpty(
variable.getValue() ) ? var : variable.getValue() ;
result.put(var ,NumberUtil.parsePossible( busiValueMap.get( keyName ) ) ) ;
}else if( "sql".equalsIgnoreCase( variable.getType() ) ){
result.put(var, SqlExecutor.get( variable.getValue() , getVarsValueMap( variable.getValue() , busiValueMap ) ) ) ;
}
}
return result ;
}
@Transactional( propagation=Propagation.REQUIRED , rollbackFor= Exception.class )
public void calculate( int reportingId , int ... schoolsId ){
if( schoolsId == null || schoolsId.length == 0 )
throw new BusinessException("请选择学校!") ;
for( int schoolId : schoolsId ){
List<InstQuotaSituationParam> situations = calculate( schoolId , reportingId ) ;
//删除重建 .
schoolSituationDao.delete( new MapParam<String,Object>()
.push("instId" , schoolId )
.push("instType" ,InstType.SCHOOL.name() )
.push("schoolType" , Arrays.asList( SchoolTypeEnum.SCHOOL.name() ,
SchoolTypeEnum.PRIMARY.name() , SchoolTypeEnum.MIDDLE.name() ) )
.push("reportingId" , reportingId ) ) ;
if( situations == null || situations.isEmpty() )
continue ;
for( InstQuotaSituationParam situation : situations )
schoolSituationDao.createBean( situation , InstQuotaSituationParam.class ) ;
}
}
}
| [
"2674235651@qq.com"
] | 2674235651@qq.com |
68361a5950ac1d77e0a72a91a7d20bb2549462e5 | 68feeb501a9a159b67412151c07ddb9a45b7c304 | /2_Project/Test/temp src/ver. 2 (Sep 16)/Blocks.java | 8cd1f7c0a9b157a79d72f8374793f0949fd6b6b9 | [] | no_license | hiro727/mario-engine | d3f8e8c453ac4d694192d8d4ebff33ebfa4ed92a | f47ba30a6d6aac2669d8f96a2d34b6be9c799dfe | refs/heads/master | 2021-05-30T07:01:32.666068 | 2015-09-25T17:46:09 | 2015-09-25T17:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,864 | java | package test;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Blocks {
private static Frames f;
private static Characters c;
private static Image[] images;
private static Blocks start;
private static Blocks shownStart;
private Blocks ptr;
private Shape block;
// private Map map;
private int type;
private int x, y;
private int inside;
private boolean onScreen;
private boolean available = true;
private int squareSize = 15;
private double dy;
private double counter;
public Blocks(Frames f) {
Blocks.f = f;
try{
File[] file = new File("test/images/blocks").listFiles();
images = new Image[file.length];
for(int i=0;i<file.length;i++){
images[i] = ImageIO.read(file[i]);
}
} catch(IOException e){
e.printStackTrace();
}
}
public Blocks(int x, int y, int type) {
this.x = x;
this.y = y;
this.type = type;
GeneralPath temp = new GeneralPath();
temp.moveTo(x, y);
temp.lineTo(x+30, y);
temp.lineTo(x+30, y+25);
temp.lineTo(x, y+25);
temp.closePath();
// map = new Map(this, temp);
block = temp;
add(this);
}
public Blocks(int x, int y, int type, int inside) {
this.x = x;
this.y = y;
this.type = type;
this.inside = inside;
GeneralPath temp = new GeneralPath();
temp.moveTo(x, y);
temp.lineTo(x+30, y);
temp.lineTo(x+30, y+25);
temp.lineTo(x, y+25);
temp.closePath();
block = temp;
add(this);
}
public static void resetAll(){
if(start == null)
return;
Blocks temp1 = start;
Blocks temp2 = temp1.ptr;
while(temp2 != null){
temp1 = null;
temp1 = temp2;
temp2 = temp2.ptr;
}temp1 = null;
start = null;
shownStart = null;
}
public static void update(){
shownStart = null;
Blocks temp = start;
while(temp != null){
if(temp.x < f.getScreenx()+600){
if(shownStart == null)
shownStart = temp;
temp.onScreen = true;
}
if(temp.type == 0 && !temp.available){
temp.dy += .5*9.81;
temp.y += temp.dy*.5+.5*9.81*.5*.5;
temp.squareSize += 4;
if(temp.y-temp.squareSize/2>500)
delete(temp);
}else if(temp.type == 1 && temp.onScreen){
temp.counter+=.4;
if(temp.counter >= 3)
temp.counter = 0;
}temp = temp.ptr;
}
}
public static void checkFirstShown() {
shownStart = null;
Blocks temp = start;
while(temp != null){
if(temp.x < f.getScreenx()+600){
if(shownStart == null)
shownStart = temp;
temp.onScreen = true;
}
temp = temp.ptr;
}
}
public static void add(Blocks b) {
if(b.x<600)
b.onScreen = true;
if(start == null){
start = b;
return;
}
if(b.x < start.x || (b.x == start.x && b.y < start.y)){
b.ptr = start;
start = b;
return;
}
Blocks temp1 = start;
Blocks temp2 = start.ptr;
while(temp2 != null){
if(b.x < temp2.x || (b.x == temp2.x && b.y < temp2.y)){
b.ptr = temp2;
temp1.ptr = b;
return;
}else{
temp1 = temp1.ptr;
temp2 = temp2.ptr;
}
}
temp1.ptr = b;
}
public static void delete(Blocks deleted){//System.out.println(start.x+" "+start.y);
if(start == deleted)
start = deleted.ptr;
else{
Blocks temp1 = start;
Blocks temp2 = start.ptr;
while(temp2 != deleted){
temp1 = temp1.ptr;
temp2 = temp2.ptr;
}temp1.ptr = temp2.ptr;
temp2 = null;
}checkFirstShown();
}
public static void paintAll(Graphics g){
if(shownStart == null) return;
Blocks temp = shownStart;
while(temp.onScreen){
if(temp.available){
if(temp.type == 0)
g.drawImage(images[temp.type], temp.x+f.getInsets().left-f.getScreenx(), temp.y+f.getInsets().top, f);
else if(temp.type == 1)
g.drawImage(images[temp.type], temp.x+f.getInsets().left-f.getScreenx(), temp.y+f.getInsets().top, temp.x+f.getInsets().left-f.getScreenx()+30, temp.y+f.getInsets().top+25, (int) (temp.counter)*30, 0, (int) (temp.counter)*30+30, 25, f);
}else{
g.drawImage(images[2], temp.x-temp.squareSize/2+f.getInsets().left-f.getScreenx(), temp.y-temp.squareSize/2+f.getInsets().top, f);
g.drawImage(images[2], temp.x+temp.squareSize/2+f.getInsets().left-f.getScreenx(), temp.y-temp.squareSize/2+f.getInsets().top, f);
g.drawImage(images[2], temp.x-temp.squareSize/2+f.getInsets().left-f.getScreenx(), temp.y+temp.squareSize/2+f.getInsets().top, f);
g.drawImage(images[2], temp.x+temp.squareSize/2+f.getInsets().left-f.getScreenx(), temp.y+temp.squareSize/2+f.getInsets().top, f);
}
temp = temp.ptr;
if(temp == null)
return;
}
}
public static Shape addBlockPositions(GeneralPath map, int x) {
if(shownStart == null)
return map;
Blocks temp = shownStart;
GeneralPath map2 = (GeneralPath) map.clone();
while(x+15 > temp.x){
if(temp.available){
map2.moveTo(temp.x, temp.y);
map2.lineTo(temp.x+30, temp.y);
map2.lineTo(temp.x+30, temp.y+25);
map2.lineTo(temp.x, temp.y+25);
map2.closePath();
}
temp = temp.ptr;
if(temp == null)
break;
}return map2;
}
public static void checkIfExist(double x, double y) {
Blocks temp = shownStart;//System.out.println(x+" "+" & "+y);
while(temp != null && x+17 > temp.x){//System.out.println(x+" "+temp.x+" & "+y+" "+temp.y);
if(x<temp.x+20 && y>temp.y && y< temp.y+20){
temp.hitOperation();
return;
}temp = temp.ptr;
}
}
private void hitOperation() {
if(type == 0){
//System.out.println("broken");
available = false;
dy = -40;
Enemies.checkIfExistOnTheBlock(x, y);
}else if(type == 1){
}else if(type == 2){
}
}
}
| [
"lazysealion1995@gmail.com"
] | lazysealion1995@gmail.com |
28db7cccd00f11ce3f910c2302befc96fbe15c56 | c4ca11707cfba84a15b788b455bbf920349bd664 | /redisLock/src/main/java/com/project/RedisTool.java | 2dfc80c1f35769697a4c0046bec08b0bb5d7c803 | [] | no_license | smilemilk1992/RedisDistributeLock | f25354ef0cd22d85f5ad3829b807291cff96f2a2 | 6eccf9f85d552c060559c48fca0afd4ded8fede0 | refs/heads/master | 2020-05-02T18:48:46.123825 | 2019-03-28T06:46:41 | 2019-03-28T06:46:41 | 178,140,758 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,582 | java | package com.project;
import redis.clients.jedis.Jedis;
import java.util.Collections;
/**
* @author haochen
* @date 2019/3/27 10:45 PM
*/
public class RedisTool {
private static final Long RELEASE_SUCCESS = 1L;
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
/**
* 尝试获取分布式锁
*
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间
* @return 是否获取成功
* **/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
* 释放分布式锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}
| [
"702660780@qq.com"
] | 702660780@qq.com |
7d749656d15d5c668ba4c691bf9abc9c77117ee0 | c283bb8d92f050de02e24253bb1d356ab4327a93 | /src/com/ggdsn/algorithms/alg4work/week5/Board.java | 21bf5f172ebbfd93ed6cc7478c79eb26f3b6ff6f | [] | no_license | gdannyliao/algorithms | 9d379938174038bad13128c637388e17578ec2f1 | a384dfe667f514d4239cdb25a038995bfd6603d6 | refs/heads/master | 2021-01-17T14:43:54.922183 | 2018-12-14T11:40:46 | 2018-12-14T11:40:46 | 44,114,065 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,164 | java | package com.ggdsn.algorithms.alg4work.week5;
import java.util.ArrayList;
public class Board {
private int[][] blocks;
public Board(int[][] blocks) {
if (blocks == null) throw new IllegalArgumentException();
int length = blocks.length;
this.blocks = new int[length][length];
for (int i = 0; i < length; i++) {
System.arraycopy(blocks[i], 0, this.blocks[i], 0, length);
}
this.blocks = blocks;
} // construct a board from an n-by-n array of blocks
// (where blocks[i][j] = block in row i, column j)
public int dimension() {
return blocks.length;
} // board dimension n
public int hamming() {
int n = dimension();
int dis = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = blocks[i][j];
if (num == 0) continue;
//求错误的块数量
if (num != i * n + j + 1) dis++;
}
}
return dis;
} // number of blocks out of place
private int calManhattanDistance(int num, int x, int y) {
int n = dimension();
int targetX;
int targetY;
//右边界需要换到上一行
if (num % n == 0) {
targetX = num / n - 1;
targetY = n - 1;
} else {
targetX = num / n;
targetY = num % n - 1;
}
return Math.abs(x - targetX) + Math.abs(y - targetY);
}
public int manhattan() {
int sum = 0;
int n = dimension();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = blocks[i][j];
if (num != 0) {
sum += calManhattanDistance(num, i, j);
}
}
}
return sum;
} // sum of Manhattan distances between blocks and goal
public boolean isGoal() {
return hamming() == 0;
} // is this board the goal board?
public Board twin() {
int n = dimension();
int[][] another = new int[n][n];
int x = -1, y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
another[i][j] = blocks[i][j];
if (j < n - 1 && blocks[i][j] != 0 && blocks[i][j + 1] != 0) {
x = i;
y = j;
}
}
}
if (x == -1) throw new IllegalArgumentException();
exch(another, x, y, x, y + 1);
return new Board(another);
} // a board that is obtained by exchanging any pair of blocks
public boolean equals(Object y) {
if (y == null) return false;
if (!(y instanceof Board)) return false;
Board that = (Board) y;
int n = dimension();
if (that.dimension() != n) return false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (blocks[i][j] != that.blocks[i][j]) {
return false;
}
}
}
return true;
} // does this board equal y?
public Iterable<Board> neighbors() {
int n = dimension();
int blankX = 0, blankY = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (blocks[i][j] == 0) {
blankX = i;
blankY = j;
}
}
}
/*
* 1 2 4 8 分别代表左上右下
*/
int calFlag = 0;
int neighborCount = 0;
if (blankX == 0) {
if (blankY == 0) {
calFlag = 12;
neighborCount = 2;
} else if (blankY == n - 1) {
calFlag = 9;
neighborCount = 2;
} else {
calFlag = 13;
neighborCount = 3;
}
} else if (blankX == n - 1) {
if (blankY == 0) {
calFlag = 6;
neighborCount = 2;
} else if (blankY == n - 1) {
calFlag = 3;
neighborCount = 2;
} else {
calFlag = 7;
neighborCount = 3;
}
} else {
if (blankY == 0) {
calFlag = 14;
neighborCount = 3;
} else if (blankY == n - 1) {
calFlag = 11;
neighborCount = 3;
} else {
calFlag = 15;
neighborCount = 4;
}
}
ArrayList<Board> boards = new ArrayList<>(neighborCount);
for (int k = 0; k < neighborCount; k++) {
int[][] neighbour = new int[n][n];
for (int i = 0; i < n; i++) {
System.arraycopy(blocks[i], 0, neighbour[i], 0, n);
}
//根据flag来判断上下左右是否可以交换
switch (calFlag) {
case 15:
case 13:
case 11:
case 9:
case 7:
case 5:
case 3:
case 1:
exch(neighbour, blankX, blankY, blankX, blankY - 1);
calFlag -= 1;
break;
case 14:
case 10:
case 6:
case 2:
exch(neighbour, blankX, blankY, blankX - 1, blankY);
calFlag -= 2;
break;
case 12:
case 4:
exch(neighbour, blankX, blankY, blankX, blankY + 1);
calFlag -= 4;
break;
case 8:
exch(neighbour, blankX, blankY, blankX + 1, blankY);
calFlag -= 8;
break;
}
boards.add(new Board(neighbour));
}
return boards;
} // all neighboring boards
private void exch(int[][] board, int x1, int y1, int x2, int y2) {
int tmp = board[x1][y1];
board[x1][y1] = board[x2][y2];
board[x2][y2] = tmp;
}
private int bitCount(int num) {
int count = 1;
while (num / 10 > 0) {
count++;
num /= 10;
}
return count;
}
public String toString() {
int n = dimension();
StringBuilder sb = new StringBuilder(n + "\n");
//这里进位了,所以减一
int bitCount = bitCount(n * n - 1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = blocks[i][j];
int bitDelta = bitCount - bitCount(num);
for (int k = 0; k < bitDelta; k++) {
sb.append(' ');
}
sb.append(num).append(' ');
}
sb.append("\n");
}
return sb.toString();
} // string representation of this board (in the output format specified below)
} | [
"gdannyliao@gmail.com"
] | gdannyliao@gmail.com |
edf17c534a274d11e8aaa1e16af51a0333d80d4c | a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb | /imm-20200930/src/main/java/com/aliyun/imm20200930/models/CreateOfficeConversionTaskShrinkRequest.java | ebc4b9737c9ee77593c7d27fdb7829a4db1a138b | [
"Apache-2.0"
] | permissive | aliyun/alibabacloud-java-sdk | 83a6036a33c7278bca6f1bafccb0180940d58b0b | 008923f156adf2e4f4785a0419f60640273854ec | refs/heads/master | 2023-09-01T04:10:33.640756 | 2023-09-01T02:40:45 | 2023-09-01T02:40:45 | 288,968,318 | 40 | 45 | null | 2023-06-13T02:47:13 | 2020-08-20T09:51:08 | Java | UTF-8 | Java | false | false | 9,503 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.imm20200930.models;
import com.aliyun.tea.*;
public class CreateOfficeConversionTaskShrinkRequest extends TeaModel {
@NameInMap("CredentialConfig")
public String credentialConfigShrink;
@NameInMap("EndPage")
public Long endPage;
@NameInMap("FirstPage")
public Boolean firstPage;
@NameInMap("FitToHeight")
public Boolean fitToHeight;
@NameInMap("FitToWidth")
public Boolean fitToWidth;
@NameInMap("HoldLineFeed")
public Boolean holdLineFeed;
@NameInMap("ImageDPI")
public Long imageDPI;
@NameInMap("LongPicture")
public Boolean longPicture;
@NameInMap("LongText")
public Boolean longText;
@NameInMap("MaxSheetColumn")
public Long maxSheetColumn;
@NameInMap("MaxSheetRow")
public Long maxSheetRow;
@NameInMap("Notification")
public String notificationShrink;
@NameInMap("Pages")
public String pages;
@NameInMap("PaperHorizontal")
public Boolean paperHorizontal;
@NameInMap("PaperSize")
public String paperSize;
@NameInMap("Password")
public String password;
@NameInMap("ProjectName")
public String projectName;
@NameInMap("Quality")
public Long quality;
@NameInMap("ScalePercentage")
public Long scalePercentage;
@NameInMap("SheetCount")
public Long sheetCount;
@NameInMap("SheetIndex")
public Long sheetIndex;
@NameInMap("ShowComments")
public Boolean showComments;
@NameInMap("SourceType")
public String sourceType;
@NameInMap("SourceURI")
public String sourceURI;
@NameInMap("StartPage")
public Long startPage;
@NameInMap("Tags")
public String tagsShrink;
@NameInMap("TargetType")
public String targetType;
@NameInMap("TargetURI")
public String targetURI;
@NameInMap("TargetURIPrefix")
public String targetURIPrefix;
@NameInMap("TrimPolicy")
public String trimPolicyShrink;
@NameInMap("UserData")
public String userData;
public static CreateOfficeConversionTaskShrinkRequest build(java.util.Map<String, ?> map) throws Exception {
CreateOfficeConversionTaskShrinkRequest self = new CreateOfficeConversionTaskShrinkRequest();
return TeaModel.build(map, self);
}
public CreateOfficeConversionTaskShrinkRequest setCredentialConfigShrink(String credentialConfigShrink) {
this.credentialConfigShrink = credentialConfigShrink;
return this;
}
public String getCredentialConfigShrink() {
return this.credentialConfigShrink;
}
public CreateOfficeConversionTaskShrinkRequest setEndPage(Long endPage) {
this.endPage = endPage;
return this;
}
public Long getEndPage() {
return this.endPage;
}
public CreateOfficeConversionTaskShrinkRequest setFirstPage(Boolean firstPage) {
this.firstPage = firstPage;
return this;
}
public Boolean getFirstPage() {
return this.firstPage;
}
public CreateOfficeConversionTaskShrinkRequest setFitToHeight(Boolean fitToHeight) {
this.fitToHeight = fitToHeight;
return this;
}
public Boolean getFitToHeight() {
return this.fitToHeight;
}
public CreateOfficeConversionTaskShrinkRequest setFitToWidth(Boolean fitToWidth) {
this.fitToWidth = fitToWidth;
return this;
}
public Boolean getFitToWidth() {
return this.fitToWidth;
}
public CreateOfficeConversionTaskShrinkRequest setHoldLineFeed(Boolean holdLineFeed) {
this.holdLineFeed = holdLineFeed;
return this;
}
public Boolean getHoldLineFeed() {
return this.holdLineFeed;
}
public CreateOfficeConversionTaskShrinkRequest setImageDPI(Long imageDPI) {
this.imageDPI = imageDPI;
return this;
}
public Long getImageDPI() {
return this.imageDPI;
}
public CreateOfficeConversionTaskShrinkRequest setLongPicture(Boolean longPicture) {
this.longPicture = longPicture;
return this;
}
public Boolean getLongPicture() {
return this.longPicture;
}
public CreateOfficeConversionTaskShrinkRequest setLongText(Boolean longText) {
this.longText = longText;
return this;
}
public Boolean getLongText() {
return this.longText;
}
public CreateOfficeConversionTaskShrinkRequest setMaxSheetColumn(Long maxSheetColumn) {
this.maxSheetColumn = maxSheetColumn;
return this;
}
public Long getMaxSheetColumn() {
return this.maxSheetColumn;
}
public CreateOfficeConversionTaskShrinkRequest setMaxSheetRow(Long maxSheetRow) {
this.maxSheetRow = maxSheetRow;
return this;
}
public Long getMaxSheetRow() {
return this.maxSheetRow;
}
public CreateOfficeConversionTaskShrinkRequest setNotificationShrink(String notificationShrink) {
this.notificationShrink = notificationShrink;
return this;
}
public String getNotificationShrink() {
return this.notificationShrink;
}
public CreateOfficeConversionTaskShrinkRequest setPages(String pages) {
this.pages = pages;
return this;
}
public String getPages() {
return this.pages;
}
public CreateOfficeConversionTaskShrinkRequest setPaperHorizontal(Boolean paperHorizontal) {
this.paperHorizontal = paperHorizontal;
return this;
}
public Boolean getPaperHorizontal() {
return this.paperHorizontal;
}
public CreateOfficeConversionTaskShrinkRequest setPaperSize(String paperSize) {
this.paperSize = paperSize;
return this;
}
public String getPaperSize() {
return this.paperSize;
}
public CreateOfficeConversionTaskShrinkRequest setPassword(String password) {
this.password = password;
return this;
}
public String getPassword() {
return this.password;
}
public CreateOfficeConversionTaskShrinkRequest setProjectName(String projectName) {
this.projectName = projectName;
return this;
}
public String getProjectName() {
return this.projectName;
}
public CreateOfficeConversionTaskShrinkRequest setQuality(Long quality) {
this.quality = quality;
return this;
}
public Long getQuality() {
return this.quality;
}
public CreateOfficeConversionTaskShrinkRequest setScalePercentage(Long scalePercentage) {
this.scalePercentage = scalePercentage;
return this;
}
public Long getScalePercentage() {
return this.scalePercentage;
}
public CreateOfficeConversionTaskShrinkRequest setSheetCount(Long sheetCount) {
this.sheetCount = sheetCount;
return this;
}
public Long getSheetCount() {
return this.sheetCount;
}
public CreateOfficeConversionTaskShrinkRequest setSheetIndex(Long sheetIndex) {
this.sheetIndex = sheetIndex;
return this;
}
public Long getSheetIndex() {
return this.sheetIndex;
}
public CreateOfficeConversionTaskShrinkRequest setShowComments(Boolean showComments) {
this.showComments = showComments;
return this;
}
public Boolean getShowComments() {
return this.showComments;
}
public CreateOfficeConversionTaskShrinkRequest setSourceType(String sourceType) {
this.sourceType = sourceType;
return this;
}
public String getSourceType() {
return this.sourceType;
}
public CreateOfficeConversionTaskShrinkRequest setSourceURI(String sourceURI) {
this.sourceURI = sourceURI;
return this;
}
public String getSourceURI() {
return this.sourceURI;
}
public CreateOfficeConversionTaskShrinkRequest setStartPage(Long startPage) {
this.startPage = startPage;
return this;
}
public Long getStartPage() {
return this.startPage;
}
public CreateOfficeConversionTaskShrinkRequest setTagsShrink(String tagsShrink) {
this.tagsShrink = tagsShrink;
return this;
}
public String getTagsShrink() {
return this.tagsShrink;
}
public CreateOfficeConversionTaskShrinkRequest setTargetType(String targetType) {
this.targetType = targetType;
return this;
}
public String getTargetType() {
return this.targetType;
}
public CreateOfficeConversionTaskShrinkRequest setTargetURI(String targetURI) {
this.targetURI = targetURI;
return this;
}
public String getTargetURI() {
return this.targetURI;
}
public CreateOfficeConversionTaskShrinkRequest setTargetURIPrefix(String targetURIPrefix) {
this.targetURIPrefix = targetURIPrefix;
return this;
}
public String getTargetURIPrefix() {
return this.targetURIPrefix;
}
public CreateOfficeConversionTaskShrinkRequest setTrimPolicyShrink(String trimPolicyShrink) {
this.trimPolicyShrink = trimPolicyShrink;
return this;
}
public String getTrimPolicyShrink() {
return this.trimPolicyShrink;
}
public CreateOfficeConversionTaskShrinkRequest setUserData(String userData) {
this.userData = userData;
return this;
}
public String getUserData() {
return this.userData;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
36c2e96b82681d19f7b4fca7289de3a1bf90dbad | 1dbb735f07e09d9e7655d7251f5393dcaf28affb | /Cloud Center/CC/src/main/java/controlModule/ComputingInterface.java | cf83e38b796eaf8c36d2d580c5a31e27f6e80fb3 | [] | no_license | sirius93123/EdgeFlow | f72b14a997d53d7a6c8852de0b6c8d37868bc9c0 | 5067caae26b6a22cad3661f841f3a60364cf1436 | refs/heads/master | 2021-09-12T16:33:49.763275 | 2018-04-18T18:11:38 | 2018-04-18T18:11:38 | 115,795,357 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 212 | java | package controlModule;
/**
* computing module interface
*/
public interface ComputingInterface {
/**
* the computing interface
* @param temp
*/
void computingFunction(taskFile temp);
}
| [
"chao.yao@pku.edu.cn"
] | chao.yao@pku.edu.cn |
831e663b7763c7ee7c37f4d9b3584cb1656b446d | 98fe6213ddd0fa16958590b7a2d46d85965d034b | /api/src/main/java/org/openmrs/module/htmlformentry/substitution/HtmlFormSubstitutionUtils.java | 8bb7a5a8eef56d44a458524c6a9f5cda255e2715 | [] | no_license | JyothsnaAshok/openmrs-module-htmlformentry | 038379e12ccc7bdbb199116b2c45aac4c65d0791 | b02c00c569dac0e9ed3f8b8da1154d6fda707a41 | refs/heads/master | 2021-04-25T01:27:30.546797 | 2017-12-01T20:15:18 | 2017-12-01T20:15:18 | 115,688,834 | 1 | 0 | null | 2017-12-29T05:10:28 | 2017-12-29T05:10:28 | null | UTF-8 | Java | false | false | 8,546 | java | package org.openmrs.module.htmlformentry.substitution;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.openmrs.OpenmrsObject;
import org.openmrs.api.context.Context;
import org.openmrs.module.htmlformentry.HtmlForm;
import org.openmrs.module.htmlformentry.HtmlFormEntryService;
import org.openmrs.module.htmlformentry.HtmlFormEntryUtil;
import org.openmrs.module.htmlformentry.handler.AttributeDescriptor;
import org.openmrs.module.htmlformentry.handler.TagHandler;
public class HtmlFormSubstitutionUtils {
/**
* Replaces all the ids in a form with uuids. This method operates using the AttributeDescriptors
* property of TagHandlers; if you have have a new attribute that you want to configure for
* id-to-uuid substitution, add a descriptor for that attribute to the appropriate tag handler
* and set the class property of that descriptor to the appropriate class. Can currently handle
* ids for the following classes: Concept, Program, Person, PatientIdentifierType, Location, and
* Drug
*/
public static void replaceIdsWithUuids(HtmlForm form) {
performSubstitution(form, new IdToUuidSubstituter(), null);
}
/**
* Replaces all the program name in a form with uuids. This method operates using the AttributeDescriptors
* property of TagHandlers; if you have have a new attribute that you want to configure for
* program-name-to-uuid substitution, add a descriptor for that attribute to the appropriate tag handler.
*/
public static void replaceProgramNamesWithUuids(HtmlForm form) {
performSubstitution(form, new ProgramNameToUuidSubstituter(), null);
}
/**
* Given an map of OpenmrsObjects to OpenmrsObjects, searches through the form for any references to
* OpenmrsObjects in the key set, and replaces those references to the references to the corresponding
* OpenmrsObject in the value set. Used to handle any metadata replacement that may need to take place
* when sharing a form via Metadata Sharing
* @param form
* @param substitutionMap
*/
public static void replaceIncomingOpenmrsObjectsWithExistingOpenmrsObjects(HtmlForm form, Map<OpenmrsObject, OpenmrsObject> substitutionMap) {
performSubstitution(form, new OpenmrsObjectSubstituter(), substitutionMap);
}
/**
* Reads through the content of a form and finds all values listed in any attributes defined in AttributeDescriptors
* Then used the passed Substituter to determine which values need to be substituted.
*/
private static void performSubstitution(HtmlForm form, Substituter substituter, Map<OpenmrsObject, OpenmrsObject> substitutionMap) {
// if the form is has no content, nothing to do
if(StringUtils.isEmpty(form.getXmlData())) {
return;
}
// get the tag handlers so we can gain access to the attribute descriptors
Map<String, TagHandler> tagHandlers = Context.getService(HtmlFormEntryService.class).getHandlers();
// loop through all the attribute descriptors for all the tags that have been registered
for (String tagName : tagHandlers.keySet()) {
HtmlFormEntryUtil.log.debug("Handling substitutions for tag " + tagName);
if (tagHandlers.get(tagName).getAttributeDescriptors() != null) {
for (AttributeDescriptor attributeDescriptor : tagHandlers.get(tagName).getAttributeDescriptors()) {
// we only need to deal with descriptors that have an associated class
if (attributeDescriptor.getClazz() != null) {
// build the attribute string we are searching for
// pattern matches <tagName .* attribute
// to break down the regex in detail, ?: simply means that we don't want include this grouping in the groups that we backreference
// the grouping itself is an "or", that matches either "\\s" (a single whitespace character) or
// "\\s[^>]*\\s" (a single whitespace character plus 0 to n characters of any type but a >, followed by another single whitespace character)
String pattern = "<" + tagName + "(?:\\s|\\s[^>]*\\s)" + attributeDescriptor.getName();
HtmlFormEntryUtil.log.debug("substitution pattern: " + pattern);
form.setXmlData(HtmlFormSubstitutionUtils.performSubstitutionHelper(form.getXmlData(), pattern,
attributeDescriptor.getClazz(), substituter, substitutionMap, true));
}
}
}
}
}
/**
* Helper method used by performSubstitution
*/
private static String performSubstitutionHelper(String formXmlData, String tagAndAttribute,
Class<?> clazz, Substituter substituter,
Map<OpenmrsObject, OpenmrsObject> substitutionMap, Boolean includeQuotes) {
Pattern substitutionPattern;
if (includeQuotes) {
// pattern to find the specified attribute and pull out its values; regex matches any characters within quotes after an equals, i.e. ="a2-32" would match a232
// we use () to break the match into three groups: 1) the characters up to the including the first quotes; 2) the characters in the quotes; and 3) then the trailing quote
// (put a space before the attribute name so we don't get border= instead of order=)
substitutionPattern = Pattern.compile("(" + tagAndAttribute + "=\")(.*?)(\")", Pattern.CASE_INSENSITIVE);
} else {
// the same pattern as above, but without the quotes (to handle the macro assignments),
// and with a blank space at the end (which we need to account for when we do the replace)
substitutionPattern = Pattern.compile("(" + tagAndAttribute + "=)(.*?)(\\s)", Pattern.CASE_INSENSITIVE);
}
Matcher matcher = substitutionPattern.matcher(formXmlData);
// lists to keep track of any "repeat" keys and macros we are going to have to substitute out as well
Set<String> repeatKeysToReplace = new HashSet<String>();
Set<String> macrosToReplace = new HashSet<String>();
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
// split the group into the various ids
String[] ids = matcher.group(2).split(",");
StringBuffer idBuffer = new StringBuffer();
// now loop through each id
for (String id : ids) {
// make the id substitution by calling the substituter's substitute method
idBuffer.append(substituter.substitute(id, clazz, substitutionMap) + ",");
// if this id is a repeat key (i.e., something in curly braces) we need to keep track of it so that we can perform key substitutions
// pattern matches one or more characters of any type within curly braces
Matcher repeatKeyMatcher = Pattern.compile("\\{(.+)\\}").matcher(id);
if (repeatKeyMatcher.find()) {
repeatKeysToReplace.add(repeatKeyMatcher.group(1));
}
// if this id is a macro reference (i.e, something that starts with a $) we need to keep track of it so that we can perform macro substitution
Matcher macroMatcher = Pattern.compile("\\$(.+)").matcher(id);
if (macroMatcher.find()) {
macrosToReplace.add(macroMatcher.group(1));
}
}
// trim off the trailing comma
idBuffer.deleteCharAt(idBuffer.length() - 1);
// now do the replacement
// create the replacement string from the matched sequence, substituting out group(2) with the updated ids
String replacementString = matcher.group(1) + idBuffer.toString() + matcher.group(3);
// we need to escape any $ characters in the buffer or we run into errors with the appendReplacement method since
// the $ has a special meaning to that method
replacementString = replacementString.replace("$", "\\$");
// now append the replacement string to the buffer
matcher.appendReplacement(buffer, replacementString);
}
// append the rest of htmlform
matcher.appendTail(buffer);
formXmlData = buffer.toString();
// now handle any repeat keys we have discovered during this substitution
for (String key : repeatKeysToReplace) {
formXmlData = performSubstitutionHelper(formXmlData, key, clazz, substituter, substitutionMap, true);
}
// and now handle any macros we have discovered during this substitution
for (String key : macrosToReplace) {
formXmlData = performSubstitutionHelper(formXmlData, key, clazz, substituter, substitutionMap, false);
}
return formXmlData;
}
}
| [
"mgoodrich@pih.org"
] | mgoodrich@pih.org |
52ecedc92f0cba1c5a613d2a8d5f44614f09bc05 | 31cd3061480c72cdedcf55f94f8b30046c9d2eaf | /tiger/src/test/java/tiger/test/name/NameA.java | b5b06abcbfa9b1984c91bfdc81f09e323d16c5f4 | [
"Apache-2.0"
] | permissive | Justice-love/tiger | 930970c9164a01786ae7103788961b5e88b9728e | ed15f9be3025cfeecfa91291b958bddde3ed63db | refs/heads/master | 2021-01-19T02:44:13.755898 | 2014-11-14T13:17:46 | 2014-11-14T13:17:46 | 25,665,172 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 218 | java | /**
*
* @creatTime 下午4:12:46
* @author Eddy
*/
package tiger.test.name;
import javax.inject.Named;
import javax.inject.Singleton;
/**
* @author Eddy
*
*/
@Named("name")
@Singleton
public class NameA {
}
| [
"eddyxu1213@126.com"
] | eddyxu1213@126.com |
981c096a211ce9eaf4f30b0750743e675946f288 | 8fa1b82e4523fa5e7540f96516d0f1f80249ea47 | /FuelSupplyChecker/src/fuelsupplychecker/model/Analyzers/RecordsIntervalAnalyzerTerminal.java | 02a6e2aa6ec0d577067456f53935264d08725c97 | [] | no_license | TomaszHalemba/TPDiA | a1a85a9da5f13e5cb1e5ee32e578a7d8884609ed | 0f0d025510f9b38f11c27889f41d8141b8dc0c1a | refs/heads/master | 2020-07-08T20:12:59.289523 | 2019-08-22T09:48:30 | 2019-08-22T09:48:30 | 203,759,516 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,992 | java | /*
* 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 fuelsupplychecker.model.Analyzers;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import fuelsupplychecker.model.Supply;
/**
*
* @author michi
*/
public class RecordsIntervalAnalyzerTerminal {
private ArrayList<TerminalAnalyzer> recordsIntervalAnalysis;
public ArrayList<TerminalAnalyzer> getRecordsIntervalAnalysis() {
return recordsIntervalAnalysis;
}
private Date startDate;
private Date endDate;
public String getFolderName()
{
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.format(startDate) + " " + simpleDateFormat.format(endDate);
}
private void setData()
{
startDate=endDate=recordsIntervalAnalysis.get(0).supplies.get(0).getStartTime();
for(TerminalAnalyzer column:recordsIntervalAnalysis)
{
for(Supply entry:column.supplies)
{
if(entry.getStartTime().before(startDate))startDate=entry.getStartTime();
if(entry.getStartTime().after(endDate))endDate=entry.getStartTime();
}
}
}
public RecordsIntervalAnalyzerTerminal(ArrayList<BaseRecordAnalyzer> recordsIntervalAnalysis) {
this.recordsIntervalAnalysis = new ArrayList<>();
for (BaseRecordAnalyzer rec : recordsIntervalAnalysis)
{
this.recordsIntervalAnalysis.add((TerminalAnalyzer)rec);
}
}
public void sortByErrorPercentage()
{
this.recordsIntervalAnalysis.sort(new Comparator<BaseRecordAnalyzer>() {
@Override
public int compare(BaseRecordAnalyzer sup1, BaseRecordAnalyzer sup2) {
if(!sup1.getErrorPercentage().equals(sup2.getErrorPercentage()))
{
return (int) Math.floor(sup2.getErrorPercentage()-sup1.getErrorPercentage());
}
else
if (!sup2.getErrorCount().equals(sup1.getErrorCount()))
{
return sup2.getErrorCount()-sup1.getErrorCount();
}
else
return (int) Math.floor(sup2.getProbDetectorErrorPercentage()-sup1.getProbDetectorErrorPercentage());
}
});
}
/**
* Analiza całej listy
*/
public void analyzeAll()
{
for (BaseRecordAnalyzer analyzer : this.recordsIntervalAnalysis)
{
analyzer.analyze();
}
setData();
sortByErrorPercentage();
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
| [
"TomaszHalemba@gmail.com"
] | TomaszHalemba@gmail.com |
6fe20489ec366a72fc6eadd82fc046cc3d5bdbbc | 74b47b895b2f739612371f871c7f940502e7165b | /aws-java-sdk-discovery/src/main/java/com/amazonaws/services/applicationdiscovery/model/DescribeContinuousExportsResult.java | 6192ce69f09e202c1731a7e8149356c99658d663 | [
"Apache-2.0"
] | permissive | baganda07/aws-sdk-java | fe1958ed679cd95b4c48f971393bf03eb5512799 | f19bdb30177106b5d6394223a40a382b87adf742 | refs/heads/master | 2022-11-09T21:55:43.857201 | 2022-10-24T21:08:19 | 2022-10-24T21:08:19 | 221,028,223 | 0 | 0 | Apache-2.0 | 2019-11-11T16:57:12 | 2019-11-11T16:57:11 | null | UTF-8 | Java | false | false | 6,688 | java | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.applicationdiscovery.model;
import java.io.Serializable;
import javax.annotation.Generated;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeContinuousExportsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of continuous export descriptions.
* </p>
*/
private java.util.List<ContinuousExportDescription> descriptions;
/**
* <p>
* The token from the previous call to <code>DescribeExportTasks</code>.
* </p>
*/
private String nextToken;
/**
* <p>
* A list of continuous export descriptions.
* </p>
*
* @return A list of continuous export descriptions.
*/
public java.util.List<ContinuousExportDescription> getDescriptions() {
return descriptions;
}
/**
* <p>
* A list of continuous export descriptions.
* </p>
*
* @param descriptions
* A list of continuous export descriptions.
*/
public void setDescriptions(java.util.Collection<ContinuousExportDescription> descriptions) {
if (descriptions == null) {
this.descriptions = null;
return;
}
this.descriptions = new java.util.ArrayList<ContinuousExportDescription>(descriptions);
}
/**
* <p>
* A list of continuous export descriptions.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setDescriptions(java.util.Collection)} or {@link #withDescriptions(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param descriptions
* A list of continuous export descriptions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeContinuousExportsResult withDescriptions(ContinuousExportDescription... descriptions) {
if (this.descriptions == null) {
setDescriptions(new java.util.ArrayList<ContinuousExportDescription>(descriptions.length));
}
for (ContinuousExportDescription ele : descriptions) {
this.descriptions.add(ele);
}
return this;
}
/**
* <p>
* A list of continuous export descriptions.
* </p>
*
* @param descriptions
* A list of continuous export descriptions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeContinuousExportsResult withDescriptions(java.util.Collection<ContinuousExportDescription> descriptions) {
setDescriptions(descriptions);
return this;
}
/**
* <p>
* The token from the previous call to <code>DescribeExportTasks</code>.
* </p>
*
* @param nextToken
* The token from the previous call to <code>DescribeExportTasks</code>.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token from the previous call to <code>DescribeExportTasks</code>.
* </p>
*
* @return The token from the previous call to <code>DescribeExportTasks</code>.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token from the previous call to <code>DescribeExportTasks</code>.
* </p>
*
* @param nextToken
* The token from the previous call to <code>DescribeExportTasks</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeContinuousExportsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDescriptions() != null)
sb.append("Descriptions: ").append(getDescriptions()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeContinuousExportsResult == false)
return false;
DescribeContinuousExportsResult other = (DescribeContinuousExportsResult) obj;
if (other.getDescriptions() == null ^ this.getDescriptions() == null)
return false;
if (other.getDescriptions() != null && other.getDescriptions().equals(this.getDescriptions()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDescriptions() == null) ? 0 : getDescriptions().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public DescribeContinuousExportsResult clone() {
try {
return (DescribeContinuousExportsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| [
""
] | |
3b4e158485761b6f3d6f94058f16bc6e3d445d59 | ddd6f41364b104579224af63615a1cc8374a8f55 | /src/test/java/com/epam/lab/task1/PassengerTest.java | 0660706e428547070199d68c84c387fff8b42156 | [] | no_license | RomanKarpyn/KarpynTaskk3 | 4497473306e84e8afc75bc846d47bf97acf6fa3d | ee37c2b31b9346513a350e496d22e3bce057c210 | refs/heads/master | 2020-03-22T15:59:02.879881 | 2018-07-09T14:07:48 | 2018-07-09T14:07:48 | 140,293,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,441 | java | package com.epam.lab.task1;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
import static org.junit.Assert.*;
public class PassengerTest {
private final static Logger log = Logger.getLogger(PassengerTest.class);
private static Passenger passenger1;
private static Passenger passenger2;
@BeforeClass
public static void initTest() {
passenger1 = new Passenger("Women", 33);
passenger2 = new Passenger("Son", 14);
}
@AfterClass
public static void finishTest() {
passenger1 = null;
passenger2 = null;
}
@Test
public void testAreAgeNotSame() {
log.info("AreAgeNotSame");
assertFalse(passenger1.getAge() < passenger2.getAge());
}
@Test
public void testNotNull() {
log.info("AreNameNotNull");
assertNotNull(passenger1.getName());
}
@Test
public void testNotSame() {
log.info("AreNameNotSame");
assertNotSame(passenger1.getName(), passenger2.getName());
}
@Test
public void testIfArrayEquals() {
log.info("AreArrayEquals");
int[] array1 = {1, 2, 3, 4, 5, 6};
int[] array2 = {1, 2, 3, 4, 5, 6};
assertArrayEquals(array1, array2);
}
} | [
"roma2014q@gmail.com"
] | roma2014q@gmail.com |
db3b9c976b0820a192aa12612d3a9991948b956e | 3ca2b9c83060b4811606d8f44b115b55de7824fb | /android/src/com/blackhornetworkshop/flowrush/AndroidConstants.java | 11b144f1cb3956f534687ed95b706301a9dfc4e8 | [
"Apache-2.0"
] | permissive | ks228/flowrush | 1c34cf65ffa8965d2dc36b38fa007557ff3515c8 | b04c636f17f1dd158b08fc2064f4d7552260df14 | refs/heads/master | 2020-03-12T07:53:56.048435 | 2018-03-25T21:21:24 | 2018-03-25T21:21:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 413 | java | package com.blackhornetworkshop.flowrush;
// Created by TScissors
class AndroidConstants {
final static String TAG = "FlowRush";
final static boolean IS_DEBUG = false;
final static int RC_SIGN_IN = 9001;
final static int RC_LIST_SAVED_GAMES = 9002;
final static int RC_ACHIEVEMENT_UI = 9003;
final static int RC_PURCHASE = 1001;
final static int BILLING_RESPONSE_RESULT_OK = 0;
}
| [
"tscissors@zoho.com"
] | tscissors@zoho.com |
9ae7c682af3083269b9ee082629345300887d8ed | 15783e25206e6b14cdd2217dcc01e5914134cb5d | /app/src/main/java/com/wyw/jiangsu/activity/wuhaihua/YangzhihuDetailActivity.java | 0480b40deeefb794d3d0dd2573626a6ff210308b | [] | no_license | 993739033/JiangSu | 7e1e0f2a457ea8e88629e716b8201f936c191bdb | d4b9524c06a103848631036d568c5577b70cad1a | refs/heads/master | 2020-06-12T10:59:46.695256 | 2019-06-28T13:19:04 | 2019-06-28T13:19:04 | 194,276,952 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,719 | java | package com.wyw.jiangsu.activity.wuhaihua;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.wyw.jiangsu.R;
import com.wyw.jiangsu.activity.MVPActivity;
import com.wyw.jiangsu.bean.BaseMsgBean;
import com.wyw.jiangsu.bean.WuHaiHuaCXbean;
import com.wyw.jiangsu.bean.YangzhihuDetailActivityBean;
import com.wyw.jiangsu.interfac.Constance;
import com.wyw.jiangsu.interfac.IYangzhihuDetailActivity;
import com.wyw.jiangsu.presenter.YangzhihuDetailActivityPresenter;
import com.wyw.jiangsu.service.UploadPictureService;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 查询养殖场申报表详情
*/
public class YangzhihuDetailActivity extends MVPActivity<YangzhihuDetailActivityPresenter> implements IYangzhihuDetailActivity {
@BindView(R.id.bt_back)
ImageView btBack;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_yonghu_mingzi)
TextView tvYonghuMingzi;
@BindView(R.id.bt_add)
ImageView btAdd;
@BindView(R.id.app_bar)
AppBarLayout appBar;
@BindView(R.id.yzhname)
EditText yzhname;
@BindView(R.id.dz)
TextView dz;
@BindView(R.id.phone)
EditText phone;
@BindView(R.id.yzhlx)
EditText yzhlx;
@BindView(R.id.number)
EditText number;
@BindView(R.id.numleixing)
TextView numleixing;
@BindView(R.id.shenfennum)
EditText shenfennum;
@BindView(R.id.yikanum)
EditText yikanum;
@BindView(R.id.date)
TextView date;
@BindView(R.id.anmilzl)
EditText anmilzl;
@BindView(R.id.photo_view_group_photo)
ImageView photoViewIcId;
@BindView(R.id.swnum)
EditText swnum;
@BindView(R.id.cbnum)
EditText cbnum;
@BindView(R.id.erbiao)
EditText erbiao;
@BindView(R.id.bignyin)
EditText bignyin;
@BindView(R.id.chuzhuqianzhi)
ImageView chuzhuqianzhi;
@BindView(R.id.lin_qianimg)
LinearLayout linQianimg;
@BindView(R.id.tv_qianming)
EditText tvQianming;
@BindView(R.id.lin_tvqian)
RelativeLayout linTvqian;
@BindView(R.id.feizhengchang_death)
EditText feizhengchangDeath;
@BindView(R.id.ll_feizhangchang)
RelativeLayout llFeizhangchang;
@BindView(R.id.name)
EditText name;
@BindView(R.id.et_cl_method)
EditText et_cl_method;
private WuHaiHuaCXbean.DataListBean dataListBeen;
YangzhihuDetailActivityBean.DataBean dateben = new YangzhihuDetailActivityBean.DataBean();
private PopupWindow popupwindow;
private TextView tv_update;
private TextView tv_del;
private String uuid;
private static int fStId;
private static YangzhihuDetailActivityPresenter mpresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yangzhihu_detail);
ButterKnife.bind(this);
}
@Override
protected YangzhihuDetailActivityPresenter createPresenter() {
return new YangzhihuDetailActivityPresenter(this);
}
@Override
public void bindData() {
setTitle("养殖场(户)申报表");
Intent intent = getIntent();
dataListBeen = (WuHaiHuaCXbean.DataListBean) intent.getSerializableExtra(Constance.ACTIVITY_DATA);
if (dataListBeen.getZPID()!=null&&dataListBeen.getFSuserId()!=null) {
if (dataListBeen.getFSuserId().equals(getPresenter().getUserId()) && dataListBeen.getZPID().equals("")) {
tvYonghuMingzi.setVisibility(View.VISIBLE);
tvYonghuMingzi.setText("更多");
}
}
mpresenter = getPresenter();
fStId = Integer.valueOf(dataListBeen.getFStId());
getPresenter().getFarmDeclare("HT_BSDWSWSB", fStId);
initmPopupWindowView();
}
@Override
public void bindListener() {
/* getTitltView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//2fbfc016-8db6-4fe8-9ae1-a225835e60ce_A1.jpg
Glide.with(YangzhihuDetailActivity.this).load(Constance.IMAGE_PATH + "2fbfc016-8db6-4fe8-9ae1-a225835e60ce_A1.jpg")
.diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache( true )
.into(photoViewIcId);
linTvqian.setVisibility(View.GONE);
}
});*/
tvYonghuMingzi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (popupwindow != null && popupwindow.isShowing()) {
popupwindow.dismiss();
return;
} else {
popupwindow.showAsDropDown(appBar, appBar.getWidth() - popupwindow.getWidth(), 0);
}
}
});
}
@Override
public void onError() {
}
@Override
public void refreshNone() {
}
@Override
public void setData(YangzhihuDetailActivityBean.DataBean dataListEntity) {
dateben = dataListEntity;
phone.setText(dateben.getLxdh()); //联系电话
dz.setText(dateben.getFxxdz()); //地址
name.setText(dateben.getXm()); //地址
yzhlx.setText(dateben.getFyzclx()); //养殖场类型
yzhname.setText(dataListEntity.getFxzxm());//养殖场名称
number.setText(dateben.getFxcll()); //现存栏量
numleixing.setText(dateben.getFdw1());//单位
shenfennum.setText(dateben.getFsfzh()); //身份证号
yikanum.setText(dataListEntity.getFykth()); //一卡通号
date.setText(dateben.getFsbrq()); //申报日期
anmilzl.setText(dateben.getFbsdwzl()); //病死动物种类
swnum.setText(dateben.getFsws()); //死亡数
cbnum.setText(dateben.getFcbs()); //参保数
erbiao.setText(dateben.getQDWErBiaoHao()); //耳标号
bignyin.setText(dateben.getFysswyy()); //疑似死亡原因
et_cl_method.setText(dateben.getFclfs()); //新增处理方式
if (dateben.getFysswyy().equals("正常死亡")) {
llFeizhangchang.setVisibility(View.GONE);
} else {
llFeizhangchang.setVisibility(View.VISIBLE);
feizhengchangDeath.setText(dateben.getFsiwh()); //非正常死亡原因
}
uuid = dataListEntity.getPictures1().getA1().split("_")[0];
// dataListEntity.getPictures1().getA2();
//图片赋值
if (!TextUtils.isEmpty(dataListEntity.getPictures1().getA1())) { //身份证和一卡通照片
Glide.with(YangzhihuDetailActivity.this).load(Constance.IMAGE_PATH + dataListEntity.getPictures1().getA1())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true).into(photoViewIcId);
} else {
Glide.with(YangzhihuDetailActivity.this).load("")
.diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true)
.into(photoViewIcId);
}
if (!TextUtils.isEmpty(dataListEntity.getPictures1().getA2())) { //养殖场负责人签名
String file = jieQu(dataListEntity.getPictures1().getA2());
if (file.equals("jpg")) {
//2fbfc016-8db6-4fe8-9ae1-a225835e60ce_A1.jpg
Glide.with(YangzhihuDetailActivity.this).load(Constance.IMAGE_PATH + dataListEntity.getPictures1().getA2())
.diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(chuzhuqianzhi);
linTvqian.setVisibility(View.GONE);
} else {
tvQianming.setText(dataListEntity.getPictures1().getA2());
linQianimg.setVisibility(View.GONE);
}
} else {
linTvqian.setVisibility(View.GONE);
// linQianimg.setVisibility(View.GONE);
}
}
@Override
public void deletesucess(BaseMsgBean msg) {
if (msg.getErrorCode() == 0) {
Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
}
finish();
}
private String jieQu(String str) {
File f = new File(str);
String fiename = f.getName();
String fie = fiename.substring(fiename.lastIndexOf(".") + 1);
return fie;
}
//初始化PopWindowView
public void initmPopupWindowView() {
View customView = getLayoutInflater().inflate(R.layout.popview_item,
null, false);
// 创建PopupWindow实例,200,150分别是宽度和高度
popupwindow = new PopupWindow(customView, 250, LinearLayout.LayoutParams.WRAP_CONTENT);
popupwindow.setOutsideTouchable(true);
popupwindow.setBackgroundDrawable(getResources().getDrawable(R.color.white));
customView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (popupwindow != null && popupwindow.isShowing()) {
popupwindow.dismiss();
}
return false;
}
});
tv_update = ((TextView) customView.findViewById(R.id.tv_update));
tv_del = ((TextView) customView.findViewById(R.id.tv_del));
tv_del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openDeleteDialog();
popupwindow.dismiss();
}
});
tv_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(YangzhihuDetailActivity.this, UpdateYangzhihuActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(Constance.ACTIVITY_DATA, dateben);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
popupwindow.dismiss();
}
});
if (!dataListBeen.getFSm1().equals("移动端")) {
tv_update.setVisibility(View.GONE);
}
}
private void openDeleteDialog() {
getPresenter().deteleData(dateben.getFStId(), uuid);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
getPresenter().getFarmDeclare("HT_BSDWSWSB", fStId);
}
super.onActivityResult(requestCode, resultCode, data);
}
public static class InnerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UploadPictureService.NEW_LIFEFORM_DETECTED1))
if (mpresenter != null)
mpresenter.getFarmDeclare("HT_BSDWSWSB", Integer.valueOf(fStId));
}
}
}
| [
"993739033@qq.com"
] | 993739033@qq.com |
d3bc5a5222c1d62d51f9799b0db1f08936e3c2b3 | ac33a1154fcfd617d7cd8012bbedd2f1f0351375 | /src/test/java/com/rothsmith/utils/database/JdbcUtilsTest.java | e7da7a365120d0700dbb6e37e56a27f63804121c | [] | no_license | drothauser/rothsmith-database | d5309a2348a427fe370cdff96e3e4d5b2dd3d3a8 | 237da6466ea31d28b3fb1acd490c5484fb1df20d | refs/heads/master | 2022-07-23T17:21:42.298811 | 2019-06-04T16:49:54 | 2019-06-04T16:49:54 | 139,078,136 | 0 | 0 | null | 2022-06-29T19:25:20 | 2018-06-28T23:30:32 | Java | UTF-8 | Java | false | false | 2,803 | java | /*
* (c) 2011 Rothsmith, LLC All Rights Reserved.
*/
package com.rothsmith.utils.database;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.rothsmith.utils.database.jboss.JBossDatasourceParser;
/**
* Tests for {@link JdbcUtils}.
*
* @version $Revision: 1160 $
*
* @author drothauser
*
*/
@Ignore
// Jenkins null pointer on getting the /test-ds.xml file.
public class JdbcUtilsTest {
/**
* Bootstrap JNDI using a JBoss datasource file.
*/
@BeforeClass
public static void setUpBeforeClass() {
URL url = JdbcUtilsTest.class.getResource("/test-ds.xml");
File datasourceFile = new File(url.getFile());
JndiDatasourceBootstrapper bootstrapper =
new JndiDatasourceBootstrapper(new JBossDatasourceParser());
bootstrapper.bind(datasourceFile);
}
/**
* Test method for {@link JdbcUtils#rollbackQuietly(Connection)} .
*
* @throws NamingException
* possible JNDI error
* @throws SQLException
* possible SQL error
*/
@Test
public void testRollbackQuietly() throws NamingException, SQLException {
Connection conn = null;
Statement statement = null;
try {
JDBCServiceLocator jdbcServiceLocator =
JDBCServiceLocator.getInstance();
DataSource dataSource =
jdbcServiceLocator.getDataSource("JavaDbDS");
assertNotNull(dataSource);
conn = dataSource.getConnection();
JdbcUtils.setAutoCommit(conn, false);
statement = conn.createStatement();
statement
.execute("select current_timestamp from sysibm.sysdummy1");
assertTrue(JdbcUtils.rollbackQuietly(conn));
} finally {
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
}
}
/**
* Test method for {@link JdbcUtils#setAutoCommit(Connection, boolean)}.
*
* @throws NamingException
* possible JNDI error
* @throws SQLException
* possible SQL error
*/
@Test
public void testSetAutoCommit() throws NamingException, SQLException {
Connection conn = null;
try {
JDBCServiceLocator jdbcServiceLocator =
JDBCServiceLocator.getInstance();
DataSource dataSource =
jdbcServiceLocator.getDataSource("JavaDbDS");
assertNotNull(dataSource);
conn = dataSource.getConnection();
boolean ok = JdbcUtils.setAutoCommit(conn, false);
assertTrue(ok);
assertFalse(conn.getAutoCommit());
} finally {
if (conn != null) {
conn.close();
}
}
}
}
| [
"drothauser@yahoo.com"
] | drothauser@yahoo.com |
ecffd3330b881937b6b29c38c182c70fef18f65d | 3a009bbf04156cbb7f2eb47de8b126ec0b7f4d00 | /app/src/main/java/com/cameraappchat2me/camerafilter/filter/BlueFilter.java | 8f3f2b3b1caf3a4cbc5dd70af708ff8e05df3486 | [] | no_license | Seemagiri/CameraApp | 925a52287420463c520deb4890ec53afc7a1d53a | cbc6ee013eb9a56b1e3cc5141d073a47777af4ba | refs/heads/master | 2021-01-20T08:21:28.668534 | 2017-05-09T07:23:02 | 2017-05-09T07:23:02 | 90,133,994 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,010 | java | package com.cameraappchat2me.camerafilter.filter;
import android.content.Context;
import android.opengl.GLES20;
import com.cameraappchat2me.camerafilter.MyGLUtils;
import com.cameraappchat2me.camerafilter.R;
/**
* Created by Machine Vision on 09-05-2017.
*/
public class BlueFilter extends CameraFilter
{
private int program;
private int texture2Id;
public BlueFilter(Context context) {
super(context);
// Build shaders
program = MyGLUtils.buildProgram(context, R.raw.vertext, R.raw.mapping);
// Load the texture will need for the shader
texture2Id = MyGLUtils.loadTexture(context, R.raw.bluess, new int[2]);
}
@Override
public void onDraw(int cameraTexId, int canvasWidth, int canvasHeight) {
setupShaderInputs(program,
new int[]{canvasWidth, canvasHeight},
new int[]{cameraTexId, texture2Id},
new int[][]{});
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
}
}
| [
"seemagi@gmail.com"
] | seemagi@gmail.com |
2a1c1016a2879f8726476e99066bb980c5a80bc9 | f13a8579eabcd947c127a699968c2b9f1ffae4f6 | /src/main/java/org/benben/modules/online/cgreport/mapper/OnlCgreportParamMapper.java | d44ffb9efec1ec0c7575281df15819c582a9a16c | [] | no_license | tanlei945/nckf | 13da9b00993338a0e8cb30d276319a79b19d917a | d1a1838d56df1c11a0dff52335db2065bd0c6d66 | refs/heads/master | 2023-08-29T09:11:56.227613 | 2019-08-06T03:20:41 | 2019-08-06T03:20:41 | 200,949,781 | 0 | 0 | null | 2023-07-22T12:53:43 | 2019-08-07T01:33:04 | Java | UTF-8 | Java | false | false | 374 | java | package org.benben.modules.online.cgreport.mapper;
import org.benben.modules.online.cgreport.entity.OnlCgreportParam;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @Description: 在线报表配置
* @author: benben-boot
* @date: 2019-03-08
* @version: V1.0
*/
public interface OnlCgreportParamMapper extends BaseMapper<OnlCgreportParam> {
}
| [
"wanghao@31a602a2-70d2-49ef-bb5e-4fe84f325a75"
] | wanghao@31a602a2-70d2-49ef-bb5e-4fe84f325a75 |
864ab90784ad23dd6092481477169056995fd1a0 | 94e1df4ba72f06de9d108cdc6f0ef86183f8d0ed | /src/Exa2/TipoArreglo.java | 311c4b65e9e92bd58b57c2db7baf6cce53fac9e3 | [] | no_license | UnitecSPS/Programacion2_2_1_2012 | d6c73ea08c2b7355647ede212f691dbead54bd3f | 203c8b53b6adc6b39feaeb655bfa5111bac77b1a | refs/heads/master | 2020-05-17T11:05:17.395701 | 2012-09-20T13:54:55 | 2012-09-20T13:54:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 215 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Exa2;
/**
*
* @author Gotcha
*/
public enum TipoArreglo {
INTEGER, CHAR, BOOLEAN, STRING, DOUBLE
}
| [
"carlos.gochez@unitec.edu"
] | carlos.gochez@unitec.edu |
2c3c9c613377a8ef120f7b6a1877c15c053d9a6c | 6b0e18bc795e68b877d8df2ca16b9fd311a41174 | /src/main/java/com/example/demo/UiService.java | 7f329578b84bdae6bcefeeb06f9c42d9f9dac2b2 | [] | no_license | tkaburagi/springboot-vault-consul-demo-ui | da6734d4abf91dd2a88194468714b752fe26b214 | 5e8f7c67737bbcda6803ddd7d06984b6b4e25226 | refs/heads/master | 2020-05-19T01:32:27.120057 | 2019-05-03T14:23:39 | 2019-05-03T14:23:39 | 184,759,508 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,653 | java | package com.example.demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
@Service
public class UiService {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
LoadBalancerClient loadBalancerClient;
public UiService(RestTemplateBuilder builder, ObjectMapper objectMapper, LoadBalancerClient loadBalancerClient) {
this.restTemplate = builder.build();
this.objectMapper = objectMapper;
this.loadBalancerClient = loadBalancerClient;
}
public String getUrl() {
return this.loadBalancerClient.choose("hashiboot-api").getUri().toString();
}
public Book[] getAllBooks() throws Exception {
String url = getUrl();
System.out.println("You accessed the API, " + url);
String result = this.restTemplate.getForObject(url + "/allbooks", String.class);
Book[] bList = this.objectMapper.readValue(result, Book[].class);
return bList;
}
// public Book getBookById(@RequestParam("id") String id) throws Exception {
// String targetUrl = UriComponentsBuilder.fromUriString(apiUrl + "/book").queryParam("id", id).build().toString();
// String result = this.restTemplate.getForObject(targetUrl, String.class);
// Book b = this.objectMapper.readValue(result, Book.class);
// return b;
// }
} | [
"t.kaburagi@me.com"
] | t.kaburagi@me.com |
e47bfb424fc686c3624f15de410cd45379f51af2 | 95e0f8d403895bca2744a58050e79ff7585a0335 | /src/main/java/com/backend/estadisticas/controller/Controlador.java | 5283e0b9688c8693bb8c64682f83ce8fb4972e6f | [] | no_license | Benitomo/backend-estadisticas | 7b93769b6c8d81a006af2cc263c68ee433b441ee | d5b6e4dc5d490525602bab904343bbc72dfe574c | refs/heads/main | 2023-07-14T18:52:18.702171 | 2021-08-25T18:49:09 | 2021-08-25T18:49:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,206 | java |
package com.backend.estadisticas.controller ;
import com.backend.estadisticas.service.EstadisticasService;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "http://localhost:4200",maxAge = 3600)
@RestController
@RequestMapping({"/estadisticas"})
public class Controlador {
@Autowired
EstadisticasService service;
// Traer article_filter de Informix e insertar en SqlServer
@GetMapping(path = {"/estadistica"})
public ResponseEntity Estadisticas()throws IOException{
return service.estadisticasSelect();
}
// Test
@GetMapping(path = {"/hello-world"})
public String helloWorld(){
return "Hola Oscar";
}
}
| [
"82038169+oscarosorio3@users.noreply.github.com"
] | 82038169+oscarosorio3@users.noreply.github.com |
f65a4d736d49280a6effd44d81d2cb625032ef1d | dda25827c52ee42d11f8c1197ed0041a66138453 | /app/src/main/java/cl/telematica/android/certamen3/presenters/contract/FeedPresenter.java | ce2cb13d4c69e9ba60db5dd761366b3675f23ff5 | [] | no_license | rvalencia90/Certamen3_2016_2_p1 | 713e1857ede43bed862a65ccc59acb57b7eccfce | cb04564bb9f19f87e2a9d818d9506a422eb98eb9 | refs/heads/master | 2021-05-01T22:25:56.731666 | 2016-12-24T00:15:02 | 2016-12-24T00:15:02 | 77,251,602 | 0 | 0 | null | 2016-12-23T21:31:33 | 2016-12-23T21:31:33 | null | UTF-8 | Java | false | false | 300 | java | package cl.telematica.android.certamen3.presenters.contract;
import java.util.List;
import cl.telematica.android.certamen3.models.Feed;
/**
* Created by telusm on 23-12-2016.
*/
public interface FeedPresenter {
public List<Feed> getFeeds(String result);
public List<Feed> getDatos();
}
| [
"ricardo.valencia@alumnos.usm.cl"
] | ricardo.valencia@alumnos.usm.cl |
4c98017b6a5bf8cdd76e3e60abd1b16783852813 | 4f3fbd90662e4e0607809025c3709017c305c2d7 | /iters-web/src/main/java/com.xinghui/Config/AdminWebSecurityConfig.java | 58b6bbc18ad8383ec2262880de683f28d6359662 | [] | no_license | chenkuanxing/iters | f76332aec5648317f35683c51c7a52b3d57a3043 | 4e65eab3445e98e60023cf03ff94ad3cb1d4d453 | refs/heads/master | 2022-07-09T07:29:30.128430 | 2020-05-22T09:00:37 | 2020-05-22T09:00:37 | 195,210,743 | 1 | 0 | null | 2022-06-29T17:29:19 | 2019-07-04T09:23:47 | JavaScript | UTF-8 | Java | false | false | 2,831 | java | package com.xinghui.Config;
import com.xinghui.handler.CustAccessDeniedHandler;
import com.xinghui.handler.SignInFailureHandler;
import com.xinghui.handler.SignInSuccessHandler;
import com.xinghui.handler.SignOutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @Author chenkuanxing
* @Date 2019/6/21
* spring security 配置类
*/
@EnableWebSecurity
public class AdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AdminUserDetailsService custUserDetailsService;
@Autowired
private SignInSuccessHandler signInSuccessHandler;
@Autowired
private SignInFailureHandler signInFailureHandler;
@Autowired
private CustAccessDeniedHandler custAccessDeniedHandler;
@Autowired
private SignOutSuccessHandler signOutSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/").permitAll()
.antMatchers("/statics/**", "/templates/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/signIn")
.successHandler(signInSuccessHandler) //登录成功处理返回json
.failureHandler(signInFailureHandler) //登录失败处理返回json
.permitAll()
.and()
.logout().logoutUrl("/signOut")
.logoutSuccessHandler(signOutSuccessHandler) //处理登出成功返回json
.permitAll()
.and()
.headers().frameOptions().disable()
.and()
.csrf().disable()
.exceptionHandling()
.accessDeniedHandler(custAccessDeniedHandler); //权限不足处理
}
/**
* 密码加密方式
*
* @return
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(custUserDetailsService).passwordEncoder(passwordEncoder());
}
}
| [
"12345678"
] | 12345678 |
5ea811ab871f33cfca3712749e6a1402c8e33b33 | 4b93a2d0350b8fb673967ac84ca219a54c4d0648 | /ims/framework/delegates/BedPlannerBedEdited.java | c0fe5817e052b6d632a91eb4d36f40ac51a24cc0 | [] | no_license | LibreHIS/framework | f1b91f9a3d9bb35c13ffb2b1396ca546d8ef6ff1 | 8eda310fb9fc208fce53d9e7f2714fb4dcd8930a | refs/heads/master | 2021-01-13T03:02:05.452729 | 2016-12-21T10:39:39 | 2016-12-21T10:39:39 | 77,041,739 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 200 | java | package ims.framework.delegates;
import ims.framework.controls.Bed;
public interface BedPlannerBedEdited
{
public void handle(Bed bed) throws ims.framework.exceptions.PresentationLogicException;
}
| [
"dgray123321"
] | dgray123321 |
9950adf3a82712afa85de0ee24953c468fe45448 | 250c226c79f6b2d5a61a0c7510e713b1af97c887 | /app/src/main/java/msgcopy/com/retrofit2/DataResponse.java | 6af648edad83c10db157340dcadf04d3286e1e65 | [] | no_license | androidlinpeng/Retrofit2_Rxjava_Okhttp3 | 7fd5010cfc1780f4293da26ec045850d2d3636a1 | 1559587f670679421c66539381537c0a3c56d682 | refs/heads/master | 2021-01-19T20:12:35.667573 | 2017-04-17T10:04:14 | 2017-04-17T10:05:08 | 88,495,857 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 552 | java | package msgcopy.com.retrofit2;
/**
* Created by liang on 2017/4/17.
*/
public class DataResponse<T> {
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| [
"linpd@msgcopy.com"
] | linpd@msgcopy.com |
654eaf6b1ff62fdada735888b4affe9a07a26874 | a2b520ef7a017dd2788513223c3ff965d945bb1d | /app/src/main/java/com/example/lkjhgf/helper/closeUp/CloseUp.java | c01326e7d6ca6c2e56b2c2bb66b350503a48939d | [] | no_license | Murphius/planer | b8e0cf5b3ac5b82c24e11a99fc34e3258ba32f6e | 0021254b7ed3bc6cb9ecd3ee9f94f4a46d65fb89 | refs/heads/master | 2021-01-14T04:26:13.457003 | 2020-07-09T12:44:56 | 2020-07-09T12:44:56 | 242,597,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,520 | java | package com.example.lkjhgf.helper.closeUp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;
import com.example.lkjhgf.activities.MainMenu;
import com.example.lkjhgf.helper.MyURLParameter;
import com.example.lkjhgf.helper.util.UtilsList;
import com.example.lkjhgf.publicTransport.query.QueryParameter;
import com.example.lkjhgf.publicTransport.query.QueryRefresh;
import com.example.lkjhgf.recyclerView.futureTrips.TripItem;
import de.schildbach.pte.dto.QueryTripsResult;
import de.schildbach.pte.dto.Trip;
import static com.example.lkjhgf.helper.form.Form.EXTRA_MYURLPARAMETER;
/**
* Handhabung von der detaillierten Ansicht einer Fahrt
*/
public abstract class CloseUp {
TextViewClass textViewClass;
ButtonClass buttons;
CloseUpRecyclerView recyclerView;
/**
* Fahrt die betrachtet wird
*/
Trip trip;
Activity activity;
View view;
/**
* Ob die Fahrt bei der Verbindungsabfrage gefunden wurde
*/
boolean changed;
/**
* Parameter, mit denen nach der Verbindung gesucht werden soll
*/
MyURLParameter myURLParameter;
/**
* Initialisierung der Attribute <br/>
* <p>
* Mittels Intent wird die Fahrt geladen, welche aktuell betrachtet werden soll
*
* @param activity - wird für die Textfarbe von Verspätungen benötigt, sowie für das Starten von Aktivitäten,
* enthält den Informationen aus der vorherigen Aktivität
* @param view - Layout
*/
CloseUp(Activity activity, View view) {
this.activity = activity;
this.view = view;
// Fahrt die betrachtet werden soll
this.trip = (Trip) activity.getIntent().getSerializableExtra(MainMenu.EXTRA_TRIP);
myURLParameter = (MyURLParameter) activity.getIntent().getSerializableExtra(EXTRA_MYURLPARAMETER);
textViewClass = new TextViewClass(view, activity.getResources(), this);
buttons = new ButtonClass(activity, view, this);
recyclerView = new CloseUpRecyclerView(activity, view, this);
}
/**
* Initialisierung der Attribute <br/>
* <p>
* Wenn eine bereits optimierte Fahrt betrachtet wird, so werden die Informationen nicht mittels Intent übergeben,
* sondern sind im TripItem enthalten.
*
* @param tripItem Fahrt, die betrachtet wird
* @param activity aufrufende Aktivität - für Farben und das Starten weiterer Aktivitäten benötigt
* @param view - Layout
*/
CloseUp(TripItem tripItem, Activity activity, View view) {
this.trip = tripItem.getTrip();
this.activity = activity;
myURLParameter = tripItem.getMyURLParameter();
textViewClass = new TextViewClass(view, activity.getResources(), this);
buttons = new ButtonClass(activity, view, this);
recyclerView = new CloseUpRecyclerView(activity, view, this);
}
/**
* Der Nutzer will die Fahrt speichern <br/>
*
* @preconditions Klick auf die "Pinnnadel"
*/
public abstract void onAcceptClicked();
/**
* Ansicht von geplanten Fahrten <br/>
* <p>
* Abhängig davon, ob der Nutzer gerade mehrere zu optimierende Fahrten plant, oder eine
* einzelne Fahrt, wird eine andere Ansicht gestartet. Welche, ist in dem Intent der als
* Parameter übergeben wird enthalten. Unabhängig von der zu startenden Aktivität, wird
* die aktuell betrachtete Fahrt in den Intent gepackt. <br/>
*
* @param newIntent enthält die Informationen über die neue Aktivität, so wie Informationen, die
* an diese übergeben werden sollen
* @preconditions Der Nutzer hat "Fahrt merken" geklickt, der Zeitpunkt der Fahrt liegt in
* der Zukunft
* @postconditions Ansichtswechsel, in die Übersicht mit geplanten Fahrten; wenn diese
* Fahrt noch nicht enthalten ist, so soll diese in der Liste enthalten sein
*/
void onAcceptClicked(Intent newIntent) {
newIntent.putExtra(MainMenu.EXTRA_TRIP, trip);
//Merken, mit welchen Informationen nach der Fahrt gesucht wurde
newIntent.putExtra(EXTRA_MYURLPARAMETER, myURLParameter);
activity.startActivity(newIntent);
}
/**
* Aktualisierung der Informationen zum Trip <br/>
*
* @preconditions Der Nutzer hat auf Aktualisieren geklickt
* @postconditions Die aktualisierten Informationen werden angezeigt und gegebenenfalls gespeichert
*/
void refreshTrip() {
setChanged(false);
QueryParameter q = new QueryParameter(myURLParameter);
refreshTrip(q);
}
/**
* Akutalisierung der Informationen zum Trip
*
* @param q Parameter, die benötigt werden, um die Fahrt zu suchen
*/
private void refreshTrip(QueryParameter q) {
new QueryRefresh(activity, this::findTripOuter).execute(q);
}
/**
* Sucht die Verbindung in der ersten Anfrage an den Server <br/>
*
* @param result Ergebnis der Serveranfrage
* @postconditions Falls die gesuchte Verbindung nicht in der Liste der Fahrten enthalten ist,
* wird die Zeit des MyURLParameters nicht auf die gleiche Zeit wie bei der Suche gestellt, sondern
* auf die Abfahrtszeit der Fahrt und es folgt eine erneute Anfrage {@link #findTripInner} <br/>
* @preconditions Sollte die Fahrt in der Verbindungsliste enthalten sein, ist die Ansicht an
* diese aktualisiert worden {@link #findTrip(QueryTripsResult)}
*/
private void findTripOuter(QueryTripsResult result) {
findTrip(result);
if (!changed) {
myURLParameter.changeDate(trip.getFirstDepartureTime());
QueryParameter q = new QueryParameter(myURLParameter);
new QueryRefresh(activity, this::findTripInner).execute(q);
}
}
/**
* Prüft, ob eine Fahrt in der Liste an Verbindungen enthalten ist <br/>
*
* @param result Liste mit möglichen Verbindungen
* @preconditions Der Nutzer hat auf Aktualiseren geklickt
* @postconditions Wenn die Fahrt in der Liste der Verbindungen enthalten ist, wird die Ansicht
* an die neuen Informationen angepasst. <br/>
* Wenn die Fahrt in der Liste enthalten ist, wird dies in der Variablen changed vermerkt.
*/
private void findTrip(QueryTripsResult result) {
if (result == null || result.status != QueryTripsResult.Status.OK) {
Toast.makeText(activity.getApplicationContext(), "Keine Verbindung gefunden", Toast.LENGTH_SHORT).show();
} else {
for (Trip t : result.trips) {
if (t.getId().equals(trip.getId())) {
trip = t;
textViewClass.fillTextView();
recyclerView.update(UtilsList.fillDetailedConnectionList(trip.legs));
setChanged(true);
break;
}
}
}
}
/**
* Prüft, ob eine Fahrt in der Liste an Verbindungen enthalten ist <br/>
*
* @param result Ergebnis der zweiten Anfrage an den Server mit der Startzeit der Fahrt als
* Abfahrts- bzw. Ankunftszeit.
* @preconditions Die Originalanfrage enthält nicht die Fahrt
* @postconditions Wenn die Fahrt auch in der erneuten Anfrage nicht enthalten ist, wird der
* Nutzer informiert, dass er sich eine andere Lösung suchen sollte (zB löschen der Fahrt und
* eine alternative Verbindung suchen) <br/>
* Ist die Fahrt hingegen enthalten gewesen, so ist die Ansicht aktualisiert.
*/
private void findTripInner(QueryTripsResult result) {
findTrip(result);
if (!changed) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Diese Fahrt konnte nicht mehr gefunden werden.\n" +
"Eventuell ist die Fahrt nicht mehr möglich. \n" +
"Unter Umständen muss diese bearbeitet werden.");
builder.setCancelable(false);
builder.setNegativeButton("Okay", (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
dialog.show();
}
}
public void onBackPressed(Intent intent) {
activity.startActivity(intent);
}
private void setChanged(boolean b) {
changed = b;
}
public Trip getTrip() {
return trip;
}
} | [
"merle1996@gmx.net"
] | merle1996@gmx.net |
b2098cb798e46e7490b198f33bfd09e8b9b48f8c | dcade8cf80e2220686a62db15d43a926eb9b3eeb | /Android/socket实现camera实时传输预览/socket_ser_demo/app/src/main/java/com/example/socket_ser_demo/CameraUtils.java | 49e9d6961542b88e31f4b9ed59282f06e933ec17 | [] | no_license | xiaoAmor/Android_Test_Demo | 4a9f7a6b26d882101ab4bdc1762e138e88bd5396 | 6e0488a9606d680cc88255e73b5ecdae583b24fe | refs/heads/master | 2020-06-27T12:11:16.933276 | 2019-09-09T05:29:17 | 2019-09-09T05:29:17 | 199,951,815 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,850 | java | package com.example.socket_ser_demo;
import android.hardware.Camera;
import android.view.Window;
import java.util.Iterator;
import java.util.List;
/**
* Created by blueberry on 2017/7/14.
*/
public class CameraUtils {
private CameraUtils()
{
}
public static int getCameraBackId() {
return getCameraId(0);
}
private static int getCameraId(int type) {
int numberOfCameras = Camera.getNumberOfCameras();
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for(int i = 0; i < numberOfCameras; ++i) {
Camera.getCameraInfo(i, cameraInfo);
if(cameraInfo.facing == type) {
return i;
}
}
return -1;
}
public static int getCameraFrontId() {
return getCameraId(1);
}
public static int getCameraDisplayOrientation(Window window, int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = window.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch(rotation) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
}
int result;
if(info.facing == 1) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
public static Camera.Size getCameraPictureSize(Camera camera, int nearResolution) {
return getCameraSize(camera.getParameters().getSupportedPictureSizes(), nearResolution);
}
private static Camera.Size getCameraSize(List<Camera.Size> sizes, int nearResolution) {
Camera.Size pre = null;
Camera.Size size;
for(Iterator var4 = sizes.iterator(); var4.hasNext(); pre = size) {
size = (Camera.Size)var4.next();
int pixs = size.width * size.height;
if(pixs == nearResolution) {
return size;
}
if(pixs < nearResolution) {
if(pre == null) {
return size;
}
int preDis = pre.width * pre.height - nearResolution;
int curDis = nearResolution - pixs;
if(preDis <= curDis) {
return pre;
}
return size;
}
}
return pre;
}
public static Camera.Size getCameraPreviewSize(Camera camera, int nearResolution) {
return getCameraSize(camera.getParameters().getSupportedPreviewSizes(), nearResolution);
}
public static Camera.Size getCameraVideoSize(Camera camera, int nearResolution) {
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedVideoSizes();
return sizes == null?getCameraSize(parameters.getSupportedPreviewSizes(), nearResolution):getCameraSize(sizes, nearResolution);
}
public static Camera.Size getOptimalVideoSize(List<Camera.Size> supportedVideoSizes,
List<Camera.Size> previewSizes, int w, int h) {
// Use a very small tolerance because we want an exact match.
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
// Supported video sizes list might be null, it means that we are allowed to use the preview
// sizes
List<Camera.Size> videoSizes;
if (supportedVideoSizes != null) {
videoSizes = supportedVideoSizes;
} else {
videoSizes = previewSizes;
}
Camera.Size optimalSize = null;
// Start with max value and refine as we iterate over available video sizes. This is the
// minimum difference between view and camera height.
double minDiff = Double.MAX_VALUE;
// Target view height
int targetHeight = h;
// Try to find a video size that matches aspect ratio and the target view size.
// Iterate over all available sizes and pick the largest size that can fit in the view and
// still maintain the aspect ratio.
for (Camera.Size size : videoSizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find video size that matches the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : videoSizes) {
if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
/**
* 通过对比得到与宽高比最接近的尺寸(如果有相同尺寸,优先选择)
*
* @param surfaceWidth
* 需要被进行对比的原宽
* @param surfaceHeight
* 需要被进行对比的原高
* @param preSizeList
* 需要对比的预览尺寸列表
* @return 得到与原宽高比例最接近的尺寸
*/
public static Camera.Size getCloselyPreSize(int surfaceWidth, int surfaceHeight,
List<Camera.Size> preSizeList) {
//因为预览相机图像需要旋转90度,所以在找相机预览size时切换长宽
int ReqTmpWidth = surfaceHeight;
int ReqTmpHeight = surfaceWidth;
// 得到与传入的宽高比最接近的size
float reqRatio = ((float) ReqTmpWidth) / ReqTmpHeight;
float curRatio, deltaRatio;
float deltaRatioMin = Float.MAX_VALUE;
Camera.Size retSize = null;
for (Camera.Size size : preSizeList) {
if ((size.width == ReqTmpWidth) && (size.height == ReqTmpHeight)) {
return size;
}
curRatio = ((float) size.width) / size.height;
deltaRatio = Math.abs(reqRatio - curRatio);
if (deltaRatio < deltaRatioMin) {
deltaRatioMin = deltaRatio;
retSize = size;
}
}
return retSize;
}
}
| [
"38721845+xiaoAmor@users.noreply.github.com"
] | 38721845+xiaoAmor@users.noreply.github.com |
33443810c9f633bb8abbb2310b93d0bd6680f666 | 1d8d8065c9bedfc21f9cf9838d08506f3fccea08 | /jParent/report/src/main/java/br/com/report/poi/excel/ReportExcel.java | bed6d3e14db29d3dad64ed82133fdfb15883d76a | [] | no_license | MarioVieira6/templates | 18167b8c3837a07253e079fdeacb2c5059c7b70b | fcfb219911facb3a5217b40bad5a10ad18643b75 | refs/heads/master | 2023-03-05T21:51:54.220226 | 2022-12-03T06:15:31 | 2022-12-03T06:15:31 | 167,748,701 | 0 | 0 | null | 2023-03-02T18:12:13 | 2019-01-26T23:06:02 | HTML | UTF-8 | Java | false | false | 4,830 | java | /**
*
*/
package br.com.report.poi.excel;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.xssf.streaming.*;
/**
* Generic functionality to read and write Excel file.
*/
public class ReportExcel {
/**
* Logs.
*/
private static final Log LOGGER = LogFactory.getLog(ReportExcel.class);
private static final String ROOT_PATH = System.getProperty("user.home") + "/Downloads/";
private final String fileName;
private final List<String> fieldNames;
/**
* Initialize parameters.
*
* @param fileName
*/
public ReportExcel(String fileName) {
this.fileName = fileName;
this.fieldNames = new ArrayList<>();
}
/**
* @return Initialize creation of sheet.
*/
private SXSSFWorkbook getWorkbook() {
return new SXSSFWorkbook(100);
}
/**
* Initialize dynamic writing in the excel sheet.
*
* @param data Sheet data
*/
public <T> SXSSFWorkbook writeSheet(List<T> data) {
SXSSFSheet sheet = getWorkbook().createSheet(data.get(0).getClass().getName());
try {
Field[] fields = data.get(0).getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fieldNames.add(fields[i].getName());
}
int rowCount = 0;
int columnCount = 0;
SXSSFRow row = sheet.createRow(rowCount++);
for (String fieldName : fieldNames) {
SXSSFCell cell = row.createCell(columnCount++);
cell.setCellValue(fieldName);
}
Class<? extends Object> clazz = data.get(0).getClass();
for (T t : data) {
row = sheet.createRow(rowCount++);
columnCount = 0;
for (String fieldName : fieldNames) {
SXSSFCell cell = row.createCell(columnCount);
Method method = clazz.getMethod("get" + StringUtils.capitalize(fieldName));
Object value = method.invoke(t, (Object[]) null);
if (value != null) {
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
}
}
columnCount++;
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.error("[POI]-ERROR TO ACCESS METHOD OF THE CLASS: " + e.getMessage());
throw new RuntimeException("[POI]-ERROR TO ACCESS METHOD OF THE CLASS: " + e.getMessage());
} catch (NoSuchMethodException | SecurityException e) {
LOGGER.error("[POI]-NOT FOUND METHOD OF THE CLASS: " + e.getMessage());
throw new RuntimeException("[POI]-NOT FOUND METHOD OF THE CLASS: " + e.getMessage());
}
return sheet.getWorkbook();
}
/**
* Generate filled workbook with data.
*
* @param workbook Filled workbook
*/
public void generateSheet(SXSSFWorkbook workbook) {
Path filePath = Paths.get(ROOT_PATH + fileName);
try (FileOutputStream fileOut = new FileOutputStream(filePath.toFile())) {
workbook.write(fileOut);
} catch (IOException e) {
LOGGER.error("[POI]-ERROR TO WRITE WORKBOOK: " + e.getMessage());
throw new RuntimeException("[POI]-ERROR TO WRITE WORKBOOK: " + e.getMessage());
}
}
/**
* Make download of the workbook.
*
* @param workbook Filled workbook
* @param response Information to send generated workbook to client
*/
public void downloadSheet(SXSSFWorkbook workbook, HttpServletResponse response) {
Path filePath = Paths.get(ROOT_PATH + fileName);
try (FileOutputStream fileOut = new FileOutputStream(filePath.toFile())) {
workbook.write(fileOut);
FileInputStream inputStream = new FileInputStream(filePath.toFile());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/octet-stream");
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
Files.delete(filePath);
} catch (Exception e) {
LOGGER.info("[POI]-ERROR TO MAKE DOWNLOAD: " + e.getMessage());
}
}
/**
* Close processing of the Workbook.
*/
public void closeWorkbook() {
try {
getWorkbook().close();
} catch (IOException e) {
LOGGER.error("[POI]-ERROR TO CLOSE WORKBOOK: " + e.getMessage());
}
}
}
| [
"marioviera.mvj@hotmail.com"
] | marioviera.mvj@hotmail.com |
d3f292493ea53505029e033a0538989b10619337 | 0ccc49d95b852823e77b2eec556ac41db47148dc | /server/BattleServer.java | 6afd620b0e05f2abbaf44181efe997083b8637a8 | [] | no_license | Solorank20/NetworkProject3 | fc8a4f529a1d3b3e7231eeb83f2887234f2fbe4f | 04f10791f2e4d9b2f636501cc76a0e0e4c51bcb3 | refs/heads/master | 2020-06-03T15:20:22.682005 | 2019-06-12T18:44:51 | 2019-06-12T18:44:51 | 191,626,095 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,237 | java | package server;
import common.ConnectionAgent;
import common.MessageListener;
import common.MessageSource;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
* server side logic contains and instance of the battleship game when it receives a message from a connectionAgent
* it will parse it and return information reguarding to game state and other information depending on message
* @author Austin Powers, Caleb Dineheart
* @version 12/4/2018
*/
public class BattleServer extends MessageSource implements MessageListener {
/* list of players connection agents*/
protected ArrayList<ConnectionAgent> connectedPlayers;
private ArrayList<String> pregamePlayers;
/* port connected to*/
private int port;
/* server socket*/
private ServerSocket serverSocket;
/*current player*/
private int current;
/*Current game*/
private Game game;
/*size of board*/
private int size;
/**
* default constructor
* @param port port to connect to
*/
public BattleServer(int port , int size) throws IOException {
this.game = new Game(size);
this.port = port;
this.size = size;
this.serverSocket = new ServerSocket(port);
this.connectedPlayers = new ArrayList<>();
this.pregamePlayers = new ArrayList<>();
listen();
}
public void listen(){
while(!serverSocket.isClosed()) {
try {
Socket client = serverSocket.accept();
ConnectionAgent connection = new ConnectionAgent(client);
connection.addMessageListener(BattleServer.this);
connectedPlayers.add(connection);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
/**
* broadcast a message to all players
* @param message message to broadcast
*/
public void broadcast(String message) {
for (ConnectionAgent c : connectedPlayers) {
c.sendMessage(message);
}
}
/**
* signals when a message is received and parses it
*
* @param message message to parse it
* @param source source message come from
*/
public void messageReceived(String message, MessageSource source) throws IndexOutOfBoundsException{
ConnectionAgent playerSource = (ConnectionAgent)source;
String[] command = message.split("\\s+"); //splits the string into an array
switch (command[0]) {
case ("/join"):
boolean freeName = true;
for (int i = 0; i < pregamePlayers.size(); i++){
if (command[1].equals(pregamePlayers.get(i))){
freeName =false;
}
}
if(freeName){
pregamePlayers.add(command[1]);
broadcast(command[1] + " Has joined!!");
}else{
playerSource.sendMessage("Name taken /join to try again");
}
break;
case ("/play"):
play(playerSource);
break;
case ("/attack"):
attack(playerSource, command);
break;
case ("/show"):
show(playerSource,command);
break;
case ("/quit"):
quit(playerSource);
break;
}
}
/**
* used to attack a place on the board checks to ensure it is the correct player attempting to attack
* @param playerSource player who wants to attack
* @param command coordinates he wants to attack
*/
public void attack(ConnectionAgent playerSource,String[] command){
String playerShooting = "";
String shotPlayer = command[1];
int firstcoord = Integer.parseInt(command[2]);
int secondcoord = Integer.parseInt(command[3]);
if (game.getinProgress()) {
for (int i = 0; i < game.playerNum(); i++) {
if (playerSource.equals(connectedPlayers.get(i))) {
playerShooting = game.getPlayers().get(i); //gets who is attacking
}
}
if (!playerShooting.equals(shotPlayer)) {
if (game.isPlayersTurn(playerShooting, current)) {
if (firstcoord < size && secondcoord < size &&
firstcoord >= 0 && secondcoord >= 0) { //ensure its a valid shot
game.shootAt(shotPlayer, firstcoord, secondcoord);
broadcast("Shots Fired at " + shotPlayer + " by " + playerShooting);
if (!game.checkProgress()) { // checks to see if the game is over if not continues broadcasting for attacks
broadcast("GAME OVER: " + game.getPlayers().get(0) + " wins!");
} else {
if (current == game.playerNum() - 1) { //resets to first player
current = 0;
} else {
current++;
}
broadcast("it is " + pregamePlayers.get(current) + "'s turn");
}
} else {
playerSource.sendMessage("Not a valid position. Please shoot again.");
}
} else {
playerSource.sendMessage("It is not your turn.");
}
}else {
playerSource.sendMessage("Cannot attack yourself");
}
} else {
playerSource.sendMessage("Game has not been started /play to start");
}
}
/**
* shows a grid to the player depending on if it is his or not
* @param playerSource player who wants the grid
* @param command grid the player wants
*/
public void show(ConnectionAgent playerSource, String[] command){
if(game.getinProgress()) {
for (int i = 0; i < game.playerNum(); i++) {
if (playerSource.equals(connectedPlayers.get(i))) {
playerSource.sendMessage(game.showGrid(command[1], i));
}
}
}else{
playerSource.sendMessage("Game not started");
}
}
/**
* starts the game
* @param playerSource player who wants to start the game
*/
public void play(ConnectionAgent playerSource){
if (!game.getinProgress()) {
if (connectedPlayers.size() < 2) {
playerSource.sendMessage("Not enough players to play the game");
} else {
broadcast("The game begins");
current = 0;
for (String s : pregamePlayers) {
game.addPlayer(s);
game.start();
}
broadcast("it is " + pregamePlayers.get(0) + "'s turn");
}
} else {
playerSource.sendMessage("Game already in progress");
}
}
/**
* logic for a player quitting
* @param playerSource the players connection agent that is quitting
*/
public void quit(ConnectionAgent playerSource){
for (int i = 0; i < connectedPlayers.size(); i++) {
if(i < game.playerNum()){
if(playerSource.equals(connectedPlayers.get(i))) {
broadcast(game.getPlayers().get(i) + " has surrendered!");
game.removePlayer(pregamePlayers.get(i));
}
if(playerSource.equals(connectedPlayers.get(i))){
try {
connectedPlayers.get(i).close();
}catch(IOException e){
System.out.println(e.getMessage());
}
connectedPlayers.remove(i);
sourceClosed(playerSource);
pregamePlayers.remove(i);
}
if(connectedPlayers.isEmpty()) {
sourceClosed(this);
System.out.println("All players have quit.");
try {
serverSocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
else if(!game.checkProgress() && !connectedPlayers.isEmpty()){
broadcast("GAME OVER: " + game.getPlayers().get(0) + " wins!" );
}
}
}
}
/**
* removes this as a listener from the source
* @param source The <code>MessageSource</code> that does not expect more messages.
*/
public void sourceClosed(MessageSource source) {
source.removeMessageListener(this);
}
}
| [
"noreply@github.com"
] | Solorank20.noreply@github.com |
c3afafab8a9c5eda92b9d1545b671b59cf6fae2c | 2f9fb47d286093e9aeaeabb5bc3dbdca2b631c34 | /SwitchCase.java | fe3b11584fadc35bc6259b9323cd25d98344804c | [] | no_license | pooja2629/java | d85f3ab1daf5c5ccbb117a0f20b93086615b1a55 | 7b80c69181a7533ddfc61fd3d5909d3c3b7d6aff | refs/heads/master | 2021-07-09T05:28:56.517839 | 2017-10-05T06:47:16 | 2017-10-05T06:47:16 | 103,230,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 676 | java | package variablesAndData;
public class SwitchCase {
void show() {
int casenumber = 1;
switch (casenumber) {
case 1:
if (casenumber == 1) {
System.out.println("in case 1");
}
break;
case 2:
System.out.println("in case 2");
break;
case 3:
System.out.println("in case 3");
break;
default:
System.out.println("not available");
}
}
public static void main(String[] args) {
SwitchCase switchcase=new SwitchCase();
switchcase.show();
}
}
| [
"poojaborhade29@yahoo.in"
] | poojaborhade29@yahoo.in |
9a1a5720dd377b990108aef10b38b479a7eb5da5 | 6d109557600329b936efe538957dfd0a707eeafb | /src/com/google/api/ads/dfp/v201308/ReconciliationOrderReport.java | 58c98b36a0211c21b09eb7eb3dca053f9e3df851 | [
"Apache-2.0"
] | permissive | google-code-export/google-api-dfp-java | 51b0142c19a34cd822a90e0350eb15ec4347790a | b852c716ef6e5d300363ed61e15cbd6242fbac85 | refs/heads/master | 2020-05-20T03:52:00.420915 | 2013-12-19T23:08:40 | 2013-12-19T23:08:40 | 32,133,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,882 | java | /**
* ReconciliationOrderReport.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201308;
/**
* A {@link ReconciliationOrderReport} represents one order
* in the reconciliation report.
*/
public class ReconciliationOrderReport implements java.io.Serializable {
/* Uniquely identifies the {@code ReconciliationOrderReport}.
* This value is read-only and is assigned by Google
* when the order report is created. */
private java.lang.Long id;
/* The ID of the {@link ReconciliationReport} which owns this
* order report.
* This value is read-only and is assigned by Google
* when the order report is created. */
private java.lang.Long reconciliationReportId;
/* The ID of the {@link Order} to which this order report belongs.
* This value is read-only and is assigned by Google when the order report
* is created. */
private java.lang.Long orderId;
/* The reconciliation status of this order.
* This value is read-only and is assigned by Google
* when the order report is created. */
private com.google.api.ads.dfp.v201308.ReconciliationOrderReportStatus status;
/* The time when this order report is submitted.
* This value is read-only and is assigned by Google
* when the order report is created. */
private com.google.api.ads.dfp.v201308.DateTime submissionDateTime;
/* The ID of the {@link User} who submitted this order report.
* This value is read-only and is assigned by Google when the order report
* is created. */
private java.lang.Long submitterId;
public ReconciliationOrderReport() {
}
public ReconciliationOrderReport(
java.lang.Long id,
java.lang.Long reconciliationReportId,
java.lang.Long orderId,
com.google.api.ads.dfp.v201308.ReconciliationOrderReportStatus status,
com.google.api.ads.dfp.v201308.DateTime submissionDateTime,
java.lang.Long submitterId) {
this.id = id;
this.reconciliationReportId = reconciliationReportId;
this.orderId = orderId;
this.status = status;
this.submissionDateTime = submissionDateTime;
this.submitterId = submitterId;
}
/**
* Gets the id value for this ReconciliationOrderReport.
*
* @return id * Uniquely identifies the {@code ReconciliationOrderReport}.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this ReconciliationOrderReport.
*
* @param id * Uniquely identifies the {@code ReconciliationOrderReport}.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the reconciliationReportId value for this ReconciliationOrderReport.
*
* @return reconciliationReportId * The ID of the {@link ReconciliationReport} which owns this
* order report.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public java.lang.Long getReconciliationReportId() {
return reconciliationReportId;
}
/**
* Sets the reconciliationReportId value for this ReconciliationOrderReport.
*
* @param reconciliationReportId * The ID of the {@link ReconciliationReport} which owns this
* order report.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public void setReconciliationReportId(java.lang.Long reconciliationReportId) {
this.reconciliationReportId = reconciliationReportId;
}
/**
* Gets the orderId value for this ReconciliationOrderReport.
*
* @return orderId * The ID of the {@link Order} to which this order report belongs.
* This value is read-only and is assigned by Google when the order report
* is created.
*/
public java.lang.Long getOrderId() {
return orderId;
}
/**
* Sets the orderId value for this ReconciliationOrderReport.
*
* @param orderId * The ID of the {@link Order} to which this order report belongs.
* This value is read-only and is assigned by Google when the order report
* is created.
*/
public void setOrderId(java.lang.Long orderId) {
this.orderId = orderId;
}
/**
* Gets the status value for this ReconciliationOrderReport.
*
* @return status * The reconciliation status of this order.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public com.google.api.ads.dfp.v201308.ReconciliationOrderReportStatus getStatus() {
return status;
}
/**
* Sets the status value for this ReconciliationOrderReport.
*
* @param status * The reconciliation status of this order.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public void setStatus(com.google.api.ads.dfp.v201308.ReconciliationOrderReportStatus status) {
this.status = status;
}
/**
* Gets the submissionDateTime value for this ReconciliationOrderReport.
*
* @return submissionDateTime * The time when this order report is submitted.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public com.google.api.ads.dfp.v201308.DateTime getSubmissionDateTime() {
return submissionDateTime;
}
/**
* Sets the submissionDateTime value for this ReconciliationOrderReport.
*
* @param submissionDateTime * The time when this order report is submitted.
* This value is read-only and is assigned by Google
* when the order report is created.
*/
public void setSubmissionDateTime(com.google.api.ads.dfp.v201308.DateTime submissionDateTime) {
this.submissionDateTime = submissionDateTime;
}
/**
* Gets the submitterId value for this ReconciliationOrderReport.
*
* @return submitterId * The ID of the {@link User} who submitted this order report.
* This value is read-only and is assigned by Google when the order report
* is created.
*/
public java.lang.Long getSubmitterId() {
return submitterId;
}
/**
* Sets the submitterId value for this ReconciliationOrderReport.
*
* @param submitterId * The ID of the {@link User} who submitted this order report.
* This value is read-only and is assigned by Google when the order report
* is created.
*/
public void setSubmitterId(java.lang.Long submitterId) {
this.submitterId = submitterId;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ReconciliationOrderReport)) return false;
ReconciliationOrderReport other = (ReconciliationOrderReport) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.reconciliationReportId==null && other.getReconciliationReportId()==null) ||
(this.reconciliationReportId!=null &&
this.reconciliationReportId.equals(other.getReconciliationReportId()))) &&
((this.orderId==null && other.getOrderId()==null) ||
(this.orderId!=null &&
this.orderId.equals(other.getOrderId()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.submissionDateTime==null && other.getSubmissionDateTime()==null) ||
(this.submissionDateTime!=null &&
this.submissionDateTime.equals(other.getSubmissionDateTime()))) &&
((this.submitterId==null && other.getSubmitterId()==null) ||
(this.submitterId!=null &&
this.submitterId.equals(other.getSubmitterId())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getReconciliationReportId() != null) {
_hashCode += getReconciliationReportId().hashCode();
}
if (getOrderId() != null) {
_hashCode += getOrderId().hashCode();
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getSubmissionDateTime() != null) {
_hashCode += getSubmissionDateTime().hashCode();
}
if (getSubmitterId() != null) {
_hashCode += getSubmitterId().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ReconciliationOrderReport.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ReconciliationOrderReport"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reconciliationReportId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "reconciliationReportId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("orderId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "orderId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ReconciliationOrderReportStatus"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("submissionDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "submissionDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("submitterId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "submitterId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| [
"api.arogal@gmail.com@e5600b00-1bfd-11df-acd4-e1cde50d4098"
] | api.arogal@gmail.com@e5600b00-1bfd-11df-acd4-e1cde50d4098 |
6f8c07fb4465bfdc46bb730df4974ab875438db6 | 44bdd7fccc6d6ee8268fa3f1b15eff6b0607beeb | /DMPD4/src/decoder/discr/Point.java | 9fc6e498f6f363df52e74bec6f7bdddadc96f8c8 | [] | no_license | HannahAmanda/DMPD | 79adc045b812d224da9097a724efa9c873713948 | 3d0477a8079bba99bf56ae7209c16a6c23c8b969 | refs/heads/master | 2021-01-17T09:11:43.182847 | 2016-05-19T09:07:39 | 2016-05-19T09:07:39 | 34,171,013 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,541 | java | package decoder.discr;
import java.util.ArrayList;
import java.util.List;
import message.Message;
import message.recieveMessage;
import code.graph.Node;
import f4.GF4Element;
public class Point extends Node implements recieveMessage {
private double[] softInfo;
private boolean isLeaf;
private Calculator calc = new Calculator();
private List<Message> leafMssg = new ArrayList<Message>();
private List<Message> internalMssg = new ArrayList<Message>();
public Point(int id) {
nodeId = id;
nodeName = "M" + id;
}
@Override
public void passMessageTo(Node theOther) {
if (isLeaf()) {
passSoftInfo(theOther);
} else{
double[] leaves = new double[4];
double[] internals = new double[4];
if (theOther.isLeaf()) {
leaves = combineAllLeaves(theOther);
internals = combineAllInternal();
} else {
leaves = combineAllLeaves();
internals = combineAllInternals(theOther);
}
passMessage(theOther, leaves, internals);
}
}
private void passMessage(Node theOther, double[] leaves, double[] internals) {
if (internals != null){
double[] m = calc.dSX(leaves, softInfo);
m = calc.dSS(m, internals);
((Point) theOther).receiveMessage(new Message(nodeName, normalize(m)));
} else {
double[] m = calc.dSS(leaves, softInfo);
((Point) theOther).receiveMessage(new Message(nodeName, normalize(m)));
}
}
private void passSoftInfo(Node theOther) {
((Point) theOther).receiveMessage(new Message(nodeName, normalize(softInfo)));
}
private double[] combineAllInternals(Node theOther) {
ArrayList<Message> mB = removeInternalMessage(theOther);
if (mB.isEmpty()) {
return null;
} else {
double[] result = mB.get(0).getMessage();
for (int i = 1; i < mB.size(); i++) {
result = calc.dSX(result, mB.get(i).getMessage());
}
return result;
}
}
private double[] combineAllInternal() {
if (internalMssg.isEmpty()) {
return null;
} else {
double[] result = internalMssg.get(0).getMessage();
for (int i = 1; i < internalMssg.size(); i++) {
result = calc.dSX(result, internalMssg.get(i).getMessage());
}
return result;
}
}
private double[] combineAllLeaves(Node theOther) {
double[] leaves = new double[]{1,0,1,0};
for (int i = 0; i < leafMssg.size(); i++) {
if(!leafMssg.get(i).getSenderName().equals(theOther.getNodeName())) {
leaves = calc.tSX(leafMssg.get(i).getMessage(), leaves);
}
}
return leaves;
}
private double[] combineAllLeaves() {
double[] leaves = new double[] {1,0,1,0};
for (int i = 0; i < leafMssg.size(); i++) {
leaves = calc.tSX(leafMssg.get(i).getMessage(), leaves);
}
return leaves;
}
private double[] marginalize() {
double[] result = new double[4];
if (isLeaf) {
result = calc.dot(softInfo, internalMssg.get(0).getMessage());
} else {
double[] leaves = combineAllLeaves();
double[] internals = combineAllInternal();
if (internals != null && leafMssg.size() != 0) {
// leaves and internals exist
double[] messages = calc.dSX(internals, leaves);
result = calc.dot(messages, softInfo);
} else if (internals == null) {
// only leaves exist
result = calc.dot(leaves, softInfo);
} else if (internals != null && leafMssg.size() == 0) {
// only internals
result = calc.dot(softInfo, internals);
}
}
return normalize(result);
}
@Override
public GF4Element getState() {
double[] marginal = marginalize();
// System.out.println(nodeName + " : " + marginal[0] + ", " + marginal[1]+ ", " + marginal[2] + ", " + marginal[3]);
int index = 0;
for (int i = 0; i < marginal.length; i++) {
if ( marginal[index] < marginal[i]) {
index = i;
}
}
if (index == 0) {
return GF4Element.ZERO;
} else if (index == 1) {
return GF4Element.ONE;
} else if (index == 2) {
return GF4Element.OMEGA;
} else if (index == 3) {
return GF4Element.OMEGASQ;
}
return null;
}
private ArrayList<Message> removeInternalMessage(Node except) {
ArrayList<Message> mB = new ArrayList<Message>();
mB.addAll(internalMssg);
int index = -1;
for (Message m: mB) {
if (m.getSenderName().equals(except.getNodeName())) {
index = mB.indexOf(m);
}
}
mB.remove(index);
return mB;
}
@Override
public void receiveSoftInfo(double[] softInfo) {
this.softInfo = softInfo;
}
@Override
public void passIdentityMessages() {
double[] identityMessage = {1.0,1.0,1.0,1.0};
for (Node n: neighbors) {
((Point) n).receiveMessage(new Message(toString(), identityMessage));
}
}
public boolean hasMessageFrom(Node to) {
boolean has = false;
if (to.isLeaf()) {
for (Message m: leafMssg) {
if (m.getSenderName().equals(to.getNodeName())) {
has = true;
}
}
} else {
for (Message m: internalMssg) {
if (m.getSenderName().equals(to.getNodeName())) {
has = true;
}
}
}
return has;
}
@Override
public void receiveMessage(Message m) {
// System.out.println(nodeName + " <--- " + m.toString());
String name = m.getSenderName();
boolean leaf = ((Point) neighbors.get(findNeighborIndex(name))).isLeaf();
int index = -1;
if (leaf) {
for (Message a: leafMssg) {
if (a.getSenderName().equals(name)) {
index = leafMssg.indexOf(a);
}
}
if (index != -1) {
leafMssg.remove(index);
}
leafMssg.add(m);
} else {
for (Message b: internalMssg) {
if(b.getSenderName().equals(name)) {
index = internalMssg.indexOf(b);
}
}
if (index != -1) {
internalMssg.remove(index);
}
internalMssg.add(m);
}
}
private int findNeighborIndex(String name) {
int index = -1;
for (Node v: neighbors) {
if (v.getNodeName().equals(name)) {
index = neighbors.indexOf(v);
}
}
return index;
}
@Override
public boolean hasLeaves() {
return !isLeaf() && leafMssg.size() > 0;
}
@Override
public void finalSetup() {
if (neighbors.size() == 1) {
isLeaf = true;
} else {
isLeaf = false;
}
}
@Override
public void reset() {
leafMssg.clear();
internalMssg.clear();
}
@Override
public void addNeighbor(Node n) {
neighbors.add(n);
}
private double[] normalize(double[] t) {
double sum = 0.0;
for (int i = 0; i < t.length; i++) {
sum+= t[i];
}
for (int i = 0; i < t.length; i++) {
t[i] /= sum;
}
return t;
}
@Override
public double[] getMarginal() {
return marginalize();
}
}
| [
"hannah.hansen2@gmail.com"
] | hannah.hansen2@gmail.com |
803521f53b82b124096e4655d975f6366a0f47b4 | 2a940a531c6e806407e36f06ef9fcd28ee6a3eaf | /gremlin-python/src/main/java/org/apache/tinkerpop/gremlin/python/jsr223/SymbolHelper.java | ce4ad7fb85abdd7e203f2410fb3e1ba648940ded | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | JamesRandall/tinkerpop | c4cf62d57f83f1c73fa6e6a30ca2d3c4a0a544f9 | bdd2130a47d1c1cd23935bbb5e342364b41f7253 | refs/heads/master | 2020-03-07T09:33:12.211276 | 2018-04-04T05:27:46 | 2018-04-04T05:27:46 | 127,410,679 | 3 | 0 | Apache-2.0 | 2018-03-30T09:39:57 | 2018-03-30T09:39:57 | null | UTF-8 | Java | false | false | 2,081 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.python.jsr223;
import java.util.HashMap;
import java.util.Map;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public final class SymbolHelper {
private final static Map<String, String> TO_PYTHON_MAP = new HashMap<>();
private final static Map<String, String> FROM_PYTHON_MAP = new HashMap<>();
static {
TO_PYTHON_MAP.put("global", "global_");
TO_PYTHON_MAP.put("as", "as_");
TO_PYTHON_MAP.put("in", "in_");
TO_PYTHON_MAP.put("and", "and_");
TO_PYTHON_MAP.put("or", "or_");
TO_PYTHON_MAP.put("is", "is_");
TO_PYTHON_MAP.put("not", "not_");
TO_PYTHON_MAP.put("from", "from_");
TO_PYTHON_MAP.put("list", "list_");
TO_PYTHON_MAP.put("set", "set_");
TO_PYTHON_MAP.put("all", "all_");
//
TO_PYTHON_MAP.forEach((k, v) -> FROM_PYTHON_MAP.put(v, k));
}
private SymbolHelper() {
// static methods only, do not instantiate
}
public static String toPython(final String symbol) {
return TO_PYTHON_MAP.getOrDefault(symbol, symbol);
}
public static String toJava(final String symbol) {
return FROM_PYTHON_MAP.getOrDefault(symbol, symbol);
}
}
| [
"okrammarko@gmail.com"
] | okrammarko@gmail.com |
60ac2550c160a1b5e58c988e9e6b6cfe8dc4691b | 29da318ba204f293a35026d9f8f5632692aff905 | /src/test/java/com/xyzcorp/demos/reactive/HotVsColdObservableTest.java | f3bab1c0fef12c4acf92640231f708e8ffcfc74a | [] | no_license | keeplearningandtrying/advanced_java | f385e892ace7b7f624bbd3688fa8bfa10e00b9c6 | 588fce52d61e13367fdb3c35a6fb4529e3a2f4fc | refs/heads/master | 2022-02-21T21:48:59.879683 | 2019-10-17T21:13:57 | 2019-10-17T21:13:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,256 | java | package com.xyzcorp.demos.reactive;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
public class HotVsColdObservableTest {
@Test
public void testColdObservable() throws InterruptedException {
Observable<Long> observable = Observable
.interval(1, TimeUnit.SECONDS)
.map(x -> x + 1);
observable
.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(1000);
observable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(10000);
}
@Test
public void testColdFlowable() throws InterruptedException {
Flowable<Long> flowable = Flowable.interval
(1, TimeUnit.SECONDS).map(x -> x + 1);
flowable
.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(1000);
flowable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(10000);
}
@Test
public void testHotObservable() throws InterruptedException {
Observable<Long> observable = Observable
.interval(1, TimeUnit.SECONDS)
.map(x -> x + 1);
Observable<Long> longObservable = observable
.publish().autoConnect();
Thread.sleep(4000);
longObservable.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(3000);
longObservable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(10000);
}
@Test
public void testHotObservableWithRefCount() throws InterruptedException {
Observable<Long> observable = Observable
.interval(1, TimeUnit.SECONDS)
.map(x -> x + 1);
Observable<Long> longObservable = observable
.publish().refCount();
Thread.sleep(4000);
longObservable.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(3000);
longObservable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(10000);
}
@Test
public void testHotObservableShare() throws InterruptedException {
Observable<Long> observable = Observable
.interval(1, TimeUnit.SECONDS)
.map(x -> x + 1);
Observable<Long> longObservable = observable.share();
Thread.sleep(4000);
longObservable.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(3000);
longObservable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(500);
Thread.sleep(10000);
}
@Test
public void testHotFlowable() throws InterruptedException {
Flowable<Long> flowable = Flowable
.interval(1, TimeUnit.SECONDS)
.map(x -> x + 1);
Flowable<Long> longObservable = flowable
.publish().autoConnect();
Thread.sleep(4000);
longObservable.subscribe(x -> System.out.println("Observer 1: " + x));
Thread.sleep(3000);
longObservable.subscribe(x -> System.out.println("Observer 2: " + x));
Thread.sleep(10000);
}
}
| [
"dhinojosa@evolutionnext.com"
] | dhinojosa@evolutionnext.com |
9e19269d980f5975694419d347a385a3b62f137f | 908e57d5b7e8d3cada68608fe1f52c6de0476e01 | /Ipi-TSP/src/test/java/tsp/algorithms/BruteForceRuntimeTests.java | d1a5cbf50e6bf898ad322fc125f337b603f2496c | [] | no_license | Ilpolainen/Ipin-TSP | 7dcbb49b988c0ea4fec69f47b6dd4b9d896f65f3 | 08425a334da39ee4b5e4e2c8afc98cdad176ab6d | refs/heads/master | 2021-01-21T14:23:37.181151 | 2016-06-10T13:41:04 | 2016-06-10T13:41:04 | 58,750,133 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,406 | java | /*
* 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 tsp.algorithms;
import java.util.ArrayList;
import java.util.Random;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import tsp.citytools.City;
import tsp.citytools.CityHandler;
import tsp.citytools.RouteHandler;
/**
*
* @author vipohjol
*/
public class BruteForceRuntimeTests {
private ArrayList<City> citylist;
public BruteForceRuntimeTests() {
}
@Before
public void setUp() {
this.citylist = new ArrayList();
konstruoiKaupungit();
// this.chS = new CityHandler();
// syotaKaupungit(chS, 4);
teeEtaisyysMatriisit();
// rhS = new RouteHandler(chS);
konstruoiYhteydet();
}
private void konstruoiYhteydet() {
// rhS.constructAllConnections();
//
}
public void konstruoiKaupungit() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
City c = new City(i * 4 + j, i, j);
citylist.add(c);
}
}
citylist.remove(citylist.size() - 1);
citylist.remove(citylist.size() - 1);
}
public void teeEtaisyysMatriisit() {
// chS.makeDistanceMatrix();
}
public void syotaKaupungit(CityHandler ch, int size) {
for (int i = 0; i < size; i++) {
ch.addCity(citylist.get(i).getX(), citylist.get(i).getY());
}
}
@After
public void tearDown() {
}
@Test
public void algoritmiSuorittaaKahdellatoistaRandomKaupungillaLaskennanAlleSekuntiin() {
CityHandler ch = new CityHandler();
RouteHandler rh = new RouteHandler(ch);
Random random = new Random();
for (int i = 0; i < 12; i++) {
ch.addCity(random.nextInt(300), random.nextInt(300));
}
ch.makeDistanceMatrix();
rh.constructAllConnections();
BruteForce bf = new BruteForce(rh, ch);
Long previousTime = System.nanoTime();
bf.run();
Long currentTime = System.nanoTime();
assertEquals(true, previousTime-currentTime < 1000000000);
}
} | [
"vipohjol@da3-cs-dk110-16.helsinki.fi"
] | vipohjol@da3-cs-dk110-16.helsinki.fi |
acf6fc6f303a5e076d6482a9c12c5ef8ad91b93f | 27dac1e55d34188f4b17d2c39dc2f1fd439b2f24 | /SeleniumProject/src/day3/CheckBoxEg.java | f1cd94739a07c6db2a5b3840a294f1d90209dd53 | [] | no_license | shaath/Rashmi | eb71f28a67b8636589910210111f1464c87d909e | 25bb69e8188cf3574806af56a6602ed607f5fdc5 | refs/heads/master | 2021-01-15T22:02:00.830589 | 2017-08-10T04:45:14 | 2017-08-10T04:45:14 | 99,882,352 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 503 | java | package day3;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckBoxEg {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://echoecho.com/htmlforms09.htm");
driver.manage().window().maximize();
WebElement check=driver.findElement(By.name("option1"));
if (!check.isSelected())
{
check.click();
}
}
}
| [
"you@example.com"
] | you@example.com |
1987ddcdb348a32e6643a32adf38f80158ba285f | 8de2ce0d05b11eae1931b5395eee3a1096975f7f | /Final Project/src/World/terrain/Rock.java | 43f69c7a4d11e77b174b02ff66f47c197fd6c590 | [] | no_license | rooseveltcs/ant-simulator | 8bd80162f9c1335f36aa64b70a451068756c4352 | 8b9da598cd89bb0e87833ed6268e709953abd23f | refs/heads/master | 2021-01-20T09:09:23.992792 | 2014-06-18T19:01:20 | 2014-06-18T19:01:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 191 | java | package World.terrain;
/**
* Created by ros_aljacobson001 on 5/20/2014.
*/
public class Rock implements Terrain {
@Override
public int getDurability() {
return 15;
}
}
| [
"alj@hushmail.me"
] | alj@hushmail.me |
4681dba1cb862db761ea2d858daa88323bf42cb2 | 126fc08be44867cdc77bb053d379e1ec7510ff15 | /src/Bt3/ShapeFactory.java | 17719b68bfc7722bf7cd59c5bbc3aede57367b55 | [] | no_license | luongtungthien59cntt/LuongTungThien_59132385_Creational | ea75a4592b60fcd32887069c36483f5bcbba367b | 13c27cbe407c3a227cef768a8ee5d48890bc69d3 | refs/heads/master | 2022-07-02T04:52:36.735886 | 2020-05-13T15:00:21 | 2020-05-13T15:00:21 | 263,661,102 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 626 | java | /*
* 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 Bt3;
/**
*
* @author dell
*/
public class ShapeFactory {
public Shape createShape(ShapeType type){
switch (type) {
case RECTANGLE:
return Rectangle.getInstance();
case TRIANGLE:
return Triangle.getInstance();
case CIRCLE:
return Circle.getInstance();
default:
return null;
}
}
}
| [
"thanboy8x@gmail.com"
] | thanboy8x@gmail.com |
3bbbe6c1b424ca98c5e81d0ab7715e7459b7fe09 | 2baf0df2637ed9c47292162d4902bb0eeeeb2e28 | /app/src/main/java/com/example/android/sunshine/data/network/WeatherResponse.java | 5b647f6df1f932898bc1d5ffb5c884759d3bb75e | [
"Apache-2.0"
] | permissive | ShamsKeshk/Sunshine_MVVM | d80fcec8ac4f87b4ce554c967e4c4243a66af3ee | 1c90632ef835366a0b691fa55a720a42a646e5b4 | refs/heads/master | 2020-05-05T13:08:05.976758 | 2019-04-08T11:25:29 | 2019-04-08T11:25:29 | 180,061,836 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,172 | java | /*
* Copyright (C) 2017 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.example.android.sunshine.data.network;
import android.support.annotation.NonNull;
import com.example.android.sunshine.data.database.WeatherEntry;
/**
* Weather response from the backend. Contains the weather forecasts.
*/
public class WeatherResponse {
@NonNull
private final WeatherEntry[] mWeatherForecast;
public WeatherResponse(@NonNull final WeatherEntry[] weatherForecast) {
mWeatherForecast = weatherForecast;
}
public WeatherEntry[] getWeatherForecast() {
return mWeatherForecast;
}
} | [
"shams.keshk@gmail.com"
] | shams.keshk@gmail.com |
d72a7100624acdd69687def691c68876811c9cfd | 3bded3eb5c260308205d9c63a6867c8b399f1d6a | /app/src/main/java/com/bin/fish/myproject/activity/MainActivity.java | 2966add42cf8e5aef153ba48769e083ac63fbe0d | [] | no_license | Fish-Bin/MyProject | e0f2d783c7d82ede7ee54149f53118d625cfb8e8 | 8f70966e25c0ddc2a60f1ecb758aad45bf4dcbf9 | refs/heads/master | 2020-03-27T21:52:22.844814 | 2018-09-03T09:38:30 | 2018-09-03T09:38:30 | 147,182,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 918 | java | package com.bin.fish.myproject.activity;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bin.fish.myproject.R;
import com.bin.fish.myproject.annotation.InjectRes;
import com.bin.fish.myproject.arouter.ArouterConst;
import com.bin.fish.myproject.base.BaseActivity;
import com.bin.fish.myproject.util.L;
@InjectRes(value = R.layout.activity_main)
@Route(path = ArouterConst.Activity_MainActivity)
public class MainActivity extends BaseActivity {
@Override
protected void init() {
mPresenter.getBanner(bean -> L.i("url=" + bean.get(0).getPic_url() + ""));
mPresenter.getArticleList(baseBean -> {
});
mPresenter.getAllTradeArea(baseBean -> {
});
findViewById(R.id.tv_login).setOnClickListener(view -> ARouter.getInstance().build(ArouterConst.Activity_SkipActivity).navigation());
}
}
| [
"474174309@qq.com"
] | 474174309@qq.com |
5cd8989898f5c5b9ef58f3f33444a86e5fe5f052 | f334e14cffb92a373574f14ddf640c45264e7e47 | /app/src/main/java/com/yahoo/search/yhssdk/showcase/custom/CustomSearchBar.java | 748d80a0dcc4b7bedbfe41e5dc9145cac3034619 | [
"BSD-3-Clause"
] | permissive | yahoo/YHSShowcaseApp | 38c99fdf8624857126391627c153abb113f43069 | 0bf462963e643e069a2395dba060643e4d7d14c5 | refs/heads/master | 2023-06-21T03:06:50.276574 | 2017-04-28T21:46:14 | 2017-04-28T21:46:14 | 68,059,660 | 4 | 3 | null | 2017-04-01T01:07:47 | 2016-09-13T00:37:22 | Java | UTF-8 | Java | false | false | 1,460 | java | // Copyright 2016, Yahoo Inc
// Licensed under the terms of the BSD license. Please see LICENSE file associated with this project for terms.
package com.yahoo.search.yhssdk.showcase.custom;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.yahoo.search.yhssdk.interfaces.ISearchViewHolder;
import com.yahoo.search.yhssdk.showcase.R;
/**
* TODO: document your custom view class.
*/
public class CustomSearchBar extends LinearLayout implements ISearchViewHolder {
private EditText mSearchBox;
private ImageView mCancelButton;
public CustomSearchBar(Context context) {
super(context);
}
public CustomSearchBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSearchBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
init();
}
private void init() {
mSearchBox = (EditText) this.findViewById(R.id.searchbox);
mCancelButton = (ImageView) this.findViewById(R.id.cancel);
}
@Override
public EditText getSearchEditText() {
return mSearchBox;
}
@Override
public View getClearTextButton() {
return mCancelButton;
}
}
| [
"surendar@yahoo-inc.com"
] | surendar@yahoo-inc.com |
8409a2936b5b3b096f5bc2b5e19545d03c5becb9 | f7fbc015359f7e2a7bae421918636b608ea4cef6 | /base-one/tags/hsqldb_1_7_0/src/org/hsqldb/util/ScriptTool.java | a89855c475159a46f9f46aaf49ad99410a44b84a | [] | no_license | svn2github/hsqldb | cdb363112cbdb9924c816811577586f0bf8aba90 | 52c703b4d54483899d834b1c23c1de7173558458 | refs/heads/master | 2023-09-03T10:33:34.963710 | 2019-01-18T23:07:40 | 2019-01-18T23:07:40 | 155,365,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,375 | java | /* Copyright (c) 2001-2002, The HSQL Development Group
* 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 the HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.
*/
package org.hsqldb.util;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.sql.*;
import java.net.*;
import java.io.*;
import java.util.*;
// fredt@users 20011220 - patch 481239 by yfl@users - new class
/**
* Script tool - command line tool to read in sql script and execute it.
*
*
* @version 1.7.0
*/
public class ScriptTool {
private static Properties pProperties = new Properties();
private Connection cConn;
private Statement sStatement;
/**
* Main method
*
*
* @param arg
*/
public static void main(String arg[]) {
for (int i = 0; i < arg.length; i++) {
String p = arg[i];
if (p.equals("-?")) {
printHelp();
}
if (p.charAt(0) == '-') {
pProperties.put(p.substring(1), arg[i + 1]);
i++;
}
}
ScriptTool tool = new ScriptTool();
tool.execute();
}
public void execute() {
Properties p = pProperties;
String driver = p.getProperty("driver", "org.hsqldb.jdbcDriver");
String url = p.getProperty("url", "jdbc:hsqldb:");
String database = p.getProperty("database", "test");
String user = p.getProperty("user", "sa");
String password = p.getProperty("password", "");
String script = p.getProperty("script", "import.sql");
boolean log = p.getProperty("log", "false").equalsIgnoreCase("true");
try {
if (log) {
trace("driver =" + driver);
trace("url =" + url);
trace("database=" + database);
trace("user =" + user);
trace("password=" + password);
trace("script =" + script);
trace("log =" + log);
jdbcSystem.setLogToSystem(true);
}
// As described in the JDBC FAQ:
// http://java.sun.com/products/jdbc/jdbc-frequent.html;
// Why doesn't calling class.forName() load my JDBC driver?
// There is a bug in the JDK 1.1.x that can cause Class.forName() to fail.
// new org.hsqldb.jdbcDriver();
Class.forName(driver).newInstance();
cConn = DriverManager.getConnection(url + database, user,
password);
} catch (Exception e) {
System.out.println("QueryTool.init: " + e.getMessage());
e.printStackTrace();
}
try {
sStatement = cConn.createStatement();
String sql = fileToString(script);
if (log) {
trace("SQL : " + sql);
}
sStatement.execute(sql);
ResultSet results = sStatement.getResultSet();
int updateCount = sStatement.getUpdateCount();
if (updateCount == -1) {
trace(toString(results));
} else {
trace("update count " + updateCount);
}
} catch (SQLException e) {
System.out.println("SQL Error : " + e);
}
System.exit(0);
}
/**
* Translate ResultSet to String representation
* @param r
*/
private String toString(ResultSet r) {
try {
if (r == null) {
return "No Result";
}
ResultSetMetaData m = r.getMetaData();
int col = m.getColumnCount();
StringBuffer strbuf = new StringBuffer();
for (int i = 1; i <= col; i++) {
strbuf = strbuf.append(m.getColumnLabel(i) + "\t");
}
strbuf = strbuf.append("\n");
while (r.next()) {
for (int i = 1; i <= col; i++) {
strbuf = strbuf.append(r.getString(i) + "\t");
if (r.wasNull()) {
strbuf = strbuf.append("(null)\t");
}
}
strbuf = strbuf.append("\n");
}
return strbuf.toString();
} catch (SQLException e) {
return null;
}
}
/**
* Read file and convert it to string.
*/
private String fileToString(String filename) {
StringBuffer a = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while ((line = in.readLine()) != null) {
a.append(line);
a.append('\n');
}
a.append('\n');
return a.toString();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
* Method declaration
*
*
* @param s
*/
private void trace(String s) {
System.out.println(s);
}
/**
* Method declaration
*
*/
private static void printHelp() {
System.out.println(
"Usage: java ScriptTool [-options]\n"
+ "where options include:\n"
+ " -driver <classname> name of the driver class\n"
+ " -url <name> first part of the jdbc url\n"
+ " -database <name> second part of the jdbc url\n"
+ " -user <name> username used for connection\n"
+ " -password <name> password for this user\n"
+ " -log <true/false> write log to system out\n"
+ " -script <script file> reads from script file\n");
System.exit(0);
}
}
| [
"(no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667"
] | (no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667 |
291535bc5746fc2d2e5e0151aa3c9a6c8f7204ee | 2b67cd30731ae70930aa986355edf9a03dbc6fe5 | /src/test/java/finaldata/finaldata/AppTest.java | 3092fe98a86fa88832fe6b265711b24a3a1eab25 | [] | no_license | shbm1505/SmsResult | 03bb177e14a914430236de9f1e3ce5fee08fa394 | 7c9a6a06fb78ca3d353adffdbed9111268f762bf | refs/heads/master | 2021-01-10T04:18:45.386189 | 2016-03-28T12:57:07 | 2016-03-28T12:57:07 | 54,892,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 647 | java | package finaldata.finaldata;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"kshubham155@gmail.com"
] | kshubham155@gmail.com |
01d87662d584edc9e45a731fd5ff29c0b6d70e70 | 080c196d977840b54ab541ed52bf22b821b0ea61 | /InstitutionSimulator/src/payment/simulator/institution/tx/p2p/Tx3151.java | cc6140ef11c533d337ed8e9903dd6a28be297b53 | [] | no_license | jinxiaoyi/myTest | 39419918636df39da3673f955f0dac62b474c81b | a338db9c8e701ce240b3b239c532fa1528fdad23 | refs/heads/master | 2020-03-27T23:48:12.784075 | 2018-09-04T13:16:45 | 2018-09-04T13:16:45 | 147,347,442 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,866 | java | package payment.simulator.institution.tx.p2p;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cpcn.institution.tools.util.StringUtil;
import payment.api.tx.p2p.Tx3151Request;
import payment.api.vo.P2PLoanerItem;
public class Tx3151 extends HttpServlet {
private static final long serialVersionUID = 6697471785410663173L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// 1.取得参数
String institutionID = StringUtil.trim(request.getParameter("InstitutionID"));
String batchNo = StringUtil.trim(request.getParameter("BatchNo"));
String projectNo = StringUtil.trim(request.getParameter("ProjectNo"));
String projectName = StringUtil.trim(request.getParameter("ProjectName"));
String projectURL = StringUtil.trim(request.getParameter("ProjectURL"));
String projectScale = StringUtil.trim(request.getParameter("ProjectScale"));
int returnRate = Integer.parseInt(StringUtil.trim(request.getParameter("ReturnRate")));
int projectPeriod = Integer.parseInt(StringUtil.trim(request.getParameter("ProjectPeriod")));
String startDate = StringUtil.trim(request.getParameter("StartDate"));
String endDate = StringUtil.trim(request.getParameter("EndDate"));
String loaneeAccountType = StringUtil.trim(request.getParameter("LoaneeAccountType"));
String loaneeBankID = StringUtil.trim(request.getParameter("LoaneeBankID"));
String loaneeBankAccountName = StringUtil.trim(request.getParameter("LoaneeBankAccountName"));
String loaneeBankAccountNumber = StringUtil.trim(request.getParameter("LoaneeBankAccountNumber"));
String guaranteeAccountType = StringUtil.trim(request.getParameter("GuaranteeAccountType"));
String guaranteeBankID = StringUtil.trim(request.getParameter("GuaranteeBankID"));
String guaranteeBankAccountName = StringUtil.trim(request.getParameter("GuaranteeBankAccountName"));
String guaranteeBankAccountNumber = StringUtil.trim(request.getParameter("GuaranteeBankAccountNumber"));
String loaneePaymentAccountName = StringUtil.trim(request.getParameter("LoaneePaymentAccountName"));
String loaneePaymentAccountNumber = StringUtil.trim(request.getParameter("LoaneePaymentAccountNumber"));
String guaranteePaymentAccountName = StringUtil.trim(request.getParameter("GuaranteePaymentAccountName"));
String guaranteePaymentAccountNumber = StringUtil.trim(request.getParameter("GuaranteePaymentAccountNumber"));
String[] paymentNos = request.getParameterValues("PaymentNo");
String[] amounts = request.getParameterValues("Amount");
String[] loanerPaymentAccountNames = request.getParameterValues("LoanerPaymentAccountName");
String[] loanerPaymentAccountNumbers = request.getParameterValues("LoanerPaymentAccountNumber");
ArrayList<P2PLoanerItem> P2PLoanerItemList = new ArrayList<P2PLoanerItem>();
if (paymentNos != null && paymentNos.length > 0) {
for (int i = 0; i < paymentNos.length; i++) {
P2PLoanerItem loaner = new P2PLoanerItem();
loaner.setPaymentNo(StringUtil.trim(paymentNos[i]));
loaner.setAmount(Long.parseLong(StringUtil.trim(amounts[i])));
loaner.setLoanerPaymentAccountName(StringUtil.trim(loanerPaymentAccountNames[i]));
loaner.setLoanerPaymentAccountNumber(StringUtil.trim(loanerPaymentAccountNumbers[i]));
P2PLoanerItemList.add(loaner);
}
}
// 2.创建交易请求对象
Tx3151Request tx3151Request = new Tx3151Request();
tx3151Request.setInstitutionID(institutionID);
tx3151Request.setBatchNo(batchNo);
tx3151Request.setProjectNo(projectNo);
tx3151Request.setProjectName(projectName);
tx3151Request.setProjectURL(projectURL);
tx3151Request.setProjectScale(projectScale);
tx3151Request.setReturnRate(returnRate);
tx3151Request.setProjectPeriod(projectPeriod);
tx3151Request.setStartDate(startDate);
tx3151Request.setEndDate(endDate);
tx3151Request.setLoaneeAccountType(loaneeAccountType);
tx3151Request.setLoaneeBankID(loaneeBankID);
tx3151Request.setLoaneeBankAccountName(loaneeBankAccountName);
tx3151Request.setLoaneeBankAccountNumber(loaneeBankAccountNumber);
tx3151Request.setLoaneePaymentAccountName(loaneePaymentAccountName);
tx3151Request.setLoaneePaymentAccountNumber(loaneePaymentAccountNumber);
tx3151Request.setGuaranteeAccountType(guaranteeAccountType);
tx3151Request.setGuaranteeBankID(guaranteeBankID);
tx3151Request.setGuaranteeBankAccountName(guaranteeBankAccountName);
tx3151Request.setGuaranteeBankAccountNumber(guaranteeBankAccountNumber);
tx3151Request.setGuaranteePaymentAccountName(guaranteePaymentAccountName);
tx3151Request.setGuaranteePaymentAccountNumber(guaranteePaymentAccountNumber);
tx3151Request.setP2PLoanerItemList(P2PLoanerItemList);
// 3.执行报文处理
tx3151Request.process();
// 4.将参数放置到request对象
request.setAttribute("plainText", tx3151Request.getRequestPlainText());
request.setAttribute("message", tx3151Request.getRequestMessage());
request.setAttribute("signature", tx3151Request.getRequestSignature());
request.setAttribute("txCode", "3151");
request.setAttribute("txName", "自动投资(基本户)");
request.setAttribute("Flag", "20");
request.setAttribute("action", request.getContextPath() + "/SendMessage");
// 5.转向Request.jsp页面
request.getRequestDispatcher("/Request.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
processException(request, response, e.getMessage());
}
}
private void processException(HttpServletRequest request, HttpServletResponse response, String errorMessage) {
try {
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
} catch (Exception e) {
}
}
}
| [
"jinxiaoyi2@163.com"
] | jinxiaoyi2@163.com |
4c22933785a7db1ad5b9063371c76aa2efe763ac | 890ed66c75d5294a582d0765b0f0437913cb9127 | /android/app/src/main/java/com/bluetooth/BTSerialComm.java | 032199318e968b74a45d2ddab3694d7c21fa5df2 | [] | no_license | jiumogaoao/yzj | ef663b594317e6db26d37faee9f3878977591f73 | d100fe5334fea46695f2a58d7f65bd365a00a05d | refs/heads/master | 2021-09-05T13:57:56.847281 | 2018-01-28T13:25:38 | 2018-01-28T13:25:38 | 114,569,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,861 | java | package com.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.AsyncTask;
import android.os.Build;
import android.os.SystemClock;
/**
* 蓝牙串口通信类
* @version 1.1 2014-05-07
* @author JerryLi (lijian@dzs.mobi)
* @see 抽象类,不要对其直接实例化。SendData()需要继承后再定义对外公开方法。<br />
* 使用本类,需要有以下两个权限<br />
* <uses-permission android:name="android.permission.BLUETOOTH"/><br />
* <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><br />
* Android 支持版本 LEVEL 4以上,并且LEVEL 17支持bluetooth 4的ble设备
* */
public abstract class BTSerialComm{
/**常量:SPP的Service UUID*/
public final static String UUID_SPP = "00001101-0000-1000-8000-00805F9B34FB";
/**接收缓存池大小,50k*/
private static final int iBUF_TOTAL = 1024 * 50;
/**接收缓存池*/
private final byte[] mbReceiveBufs = new byte[iBUF_TOTAL];
/**接收缓存池指针(指示缓冲池保存的数据量)*/
private int miBufDataSite = 0;
/**蓝牙地址码*/
private String msMAC;
/**蓝牙连接状态*/
private boolean mbConectOk = false;
/* Get Default Adapter */
private BluetoothAdapter mBT = BluetoothAdapter.getDefaultAdapter();
/**蓝牙串口连接对象*/
private BluetoothSocket mbsSocket = null;
/** 输入流对象 */
private InputStream misIn = null;
/** 输出流对象 */
private OutputStream mosOut = null;
/**接收到的字节数*/
private long mlRxd = 0;
/**发送的字节数*/
private long mlTxd = 0;
/**连接建立的时间*/
private long mlConnEnableTime = 0;
/**连接关闭时间*/
private long mlConnDisableTime = 0;
/**接收线程状态,默认不启动接收线程,只有当调用接收函数后,才启动接收线程*/
private boolean mbReceiveThread = false;
/**公共接收缓冲区资源信号量(通过PV操作来保持同步)*/
private final CResourcePV mresReceiveBuf = new CResourcePV(1);
/**操作开关,强制结束本次接收等待*/
private boolean mbKillReceiveData_StopFlg = false;
/**常量:未设限制的AsyncTask线程池(重要)*/
private static ExecutorService FULL_TASK_EXECUTOR;
/**常量:当前的Adnroid SDK 版本号*/
private static final int SDK_VER;
static{
FULL_TASK_EXECUTOR = (ExecutorService) Executors.newCachedThreadPool();
SDK_VER = Build.VERSION.SDK_INT;
};
/**
* 构造函数
* @param String sMAC 需要连接的蓝牙设备MAC地址码
* */
public BTSerialComm(String sMAC){
this.msMAC = sMAC;
}
/**
* 获取连接保持的时间
* @return 单位 秒
* */
public long getConnectHoldTime(){
if (0 == this.mlConnEnableTime)
return 0;
else if (0 == this.mlConnDisableTime)
return (System.currentTimeMillis() - this.mlConnEnableTime) / 1000;
else
return (this.mlConnDisableTime - this.mlConnEnableTime) / 1000;
}
/**
* 断开蓝牙设备的连接
* @return void
* */
public void closeConn(){
if ( this.mbConectOk ){
try{
if (null != this.misIn)
this.misIn.close();
if (null != this.mosOut)
this.mosOut.close();
if (null != this.mbsSocket)
this.mbsSocket.close();
this.mbConectOk = false;//标记连接已被关闭
}catch (IOException e){
//任何一部分报错,都将强制关闭socket连接
this.misIn = null;
this.mosOut = null;
this.mbsSocket = null;
this.mbConectOk = false;//标记连接已被关闭
}finally{ //保存连接中断时间
this.mlConnDisableTime = System.currentTimeMillis();
}
}
}
/**
* 建立蓝牙设备串口通信连接<br />
* <strong>备注</strong>:这个函数最好放到线程中去调用,因为调用时会阻塞系统
* @return boolean false:连接创建失败 / true:连接创建成功
* */
final public boolean createConn(){
if (! mBT.isEnabled())
return false;
//如果连接已经存在,则断开连接
if (mbConectOk)
this.closeConn();
/*开始连接蓝牙设备*/
final BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(this.msMAC);
final UUID uuidSPP = UUID.fromString(BluetoothSppClient.UUID_SPP);
try{
//得到设备连接后,立即创建SPP连接
if (SDK_VER >= 10)//2.3.3以上的设备需要用这个方式创建通信连接
this.mbsSocket = device.createInsecureRfcommSocketToServiceRecord(uuidSPP);
else//创建SPP连接 API level 5
this.mbsSocket = device.createRfcommSocketToServiceRecord(uuidSPP);
this.mbsSocket.connect();
this.mosOut = this.mbsSocket.getOutputStream();//获取全局输出流对象
this.misIn = this.mbsSocket.getInputStream(); //获取流输入对象
this.mbConectOk = true; //设备连接成功
this.mlConnEnableTime = System.currentTimeMillis(); //保存连接建立时间
}catch (IOException e){
this.closeConn();//断开连接
return false;
}finally{
this.mlConnDisableTime = 0; //连接终止时间初始化
}
return true;
}
/**
* 设备的通信是否已建立
* @return boolean true:通信已建立 / false:通信丢失
* */
public boolean isConnect() {
return this.mbConectOk;
}
/**
* 接收到的字节数
* @return long
* */
public long getRxd(){
return this.mlRxd;
}
/**
* 发送的字节数
* @return long
* */
public long getTxd(){
return this.mlTxd;
}
/**
* 接收缓冲池的数据量
* @return int
* */
public int getReceiveBufLen(){
int iBufSize = 0;
this.P(this.mresReceiveBuf);//夺取缓存访问权限
iBufSize = this.miBufDataSite;
this.V(this.mresReceiveBuf);//归还缓存访问权限
return iBufSize;
}
/**
* 发送数据
* @param byte bD[] 需要发送的数据位
* @return int >=0 发送正常, -2:连接未建立; -3:连接丢失
* */
protected int SendData(byte[] btData){
if (this.mbConectOk){
try{
mosOut.write(btData);//发送字符串值
this.mlTxd += btData.length;
return btData.length;
}catch (IOException e){
//到这儿表示蓝牙连接已经丢失,关闭socket
this.closeConn();
return -3;
}
}
else
return -2;
}
/**
* 接收数据<br />
* <strong>备注:</strong>getReceiveBufLen()>0时,本函数能够取出数据。一般在线程中使用这个函数
*
* @return null:未连接或连接中断/byte[]:取到的新数据
* */
final protected synchronized byte[] ReceiveData(){
byte[] btBufs = null;
if (mbConectOk){
if (!this.mbReceiveThread){
if(SDK_VER >= 11)
//LEVEL 11时的特殊处理
new ReceiveThread().executeOnExecutor(FULL_TASK_EXECUTOR);
else
//启动接收线程
new ReceiveThread().execute("");
return null; //首次启动线程直接返回空字符串
}
this.P(this.mresReceiveBuf);//夺取缓存访问权限
if (this.miBufDataSite > 0){
btBufs = new byte[this.miBufDataSite];
for(int i=0; i<this.miBufDataSite; i++)
btBufs[i] = this.mbReceiveBufs[i];
this.miBufDataSite = 0;
}
this.V(this.mresReceiveBuf);//归还缓存访问权限
}
return btBufs;
}
/**
* 比较两个Byte数组是否相同
* @param src 源数据
* @param dest 目标数据
* @return boolean
* */
private static boolean CompByte(byte[] src, byte[] dest){
if (src.length != dest.length)
return false;
for (int i=0, iLen=src.length; i<iLen; i++)
if (src[i] != dest[i])
return false;//当前位发现不同
return true;//未发现差异
}
/**
* 接收数据(带结束标识符的接收方式)<br />
* <strong>注意:</strong>本函数以阻塞模式工作,如果未收到结束符,将一直等待。<br />
* <strong>备注:</strong>只有遇到结束标示符时才会终止等待,并送出结果。适合于命令行模式。<br />
* 如果想要终止柱塞等待可调用killReceiveData_StopFlg()
* @param btStopFlg 结束符 (例如: '\n')
* @return null:未连接或连接中断/byte[]:取到数据
* */
final protected byte[] ReceiveData_StopFlg(byte[] btStopFlg){
int iStopCharLen = btStopFlg.length; //终止字符的长度
int iReceiveLen = 0; //临时变量,保存接收缓存中数据的长度
byte[] btCmp = new byte[iStopCharLen];
byte[] btBufs = null; //临时输出缓存
if (mbConectOk){
if (!this.mbReceiveThread){
if(SDK_VER >= 11)
//LEVEL 11时的特殊处理
new ReceiveThread().executeOnExecutor(FULL_TASK_EXECUTOR);
else
//启动接收线程
new ReceiveThread().execute("");
SystemClock.sleep(50);//延迟,给线程启动的时间
}
while(true){
this.P(this.mresReceiveBuf);//夺取缓存访问权限
iReceiveLen = this.miBufDataSite - iStopCharLen;
this.V(this.mresReceiveBuf);//归还缓存访问权限
if (iReceiveLen > 0)
break; //发现数据结束循环等待
else
SystemClock.sleep(50);//等待缓冲区被填入数据(死循环等待)
}
//当缓冲池收到数据后,开始等待接收数据段
this.mbKillReceiveData_StopFlg = false; //可用killReceiveData_StopFlg()来终止阻塞状态
while(this.mbConectOk && !this.mbKillReceiveData_StopFlg){
/*复制末尾待检查终止符*/
this.P(this.mresReceiveBuf);//夺取缓存访问权限
for(int i=0; i<iStopCharLen; i++)
btCmp[i] = this.mbReceiveBufs[this.miBufDataSite - iStopCharLen + i];
this.V(this.mresReceiveBuf);//归还缓存访问权限
if (CompByte(btCmp,btStopFlg)){ //检查是否为终止符
//取出数据时,去掉结尾的终止符
this.P(this.mresReceiveBuf);//夺取缓存访问权限
btBufs = new byte[this.miBufDataSite-iStopCharLen]; //分配存储空间
for(int i=0, iLen=this.miBufDataSite-iStopCharLen; i<iLen; i++)
btBufs[i] = this.mbReceiveBufs[i];
this.miBufDataSite = 0;
this.V(this.mresReceiveBuf);//归还缓存访问权限
break;
}
else
SystemClock.sleep(10);//死循环,等待数据回复
}
}
return btBufs;
}
/**
* 强制终止ReceiveData_StopFlg()的阻塞等待状态
* @return void
* @see 必须在ReceiveData_StopFlg()执行后,才有使用价值
* */
public void killReceiveData_StopFlg(){
this.mbKillReceiveData_StopFlg = true;
}
/**
* 互斥锁P操作:夺取资源
* @param res CResourcePV 资源对象
* */
private void P(CResourcePV res){
while(!res.seizeRes())
SystemClock.sleep(2);//资源被占用,延迟检查
}
/**
* 互斥锁V操作:释放资源
* @param res CResourcePV 资源对象
* */
private void V(CResourcePV res){
res.revert(); //归还资源
}
//----------------
/*多线程处理*/
private class ReceiveThread extends AsyncTask<String, String, Integer>{
/**常量:缓冲区最大空间*/
static private final int BUFF_MAX_CONUT = 1024*5;
/**常量:连接丢失*/
static private final int CONNECT_LOST = 0x01;
/**常量:接收线程正常结束*/
static private final int THREAD_END = 0x02;
/**
* 线程启动初始化操作
*/
@Override
public void onPreExecute(){
mbReceiveThread = true;//标记启动接收线程
miBufDataSite = 0; //缓冲池指针归0
}
@Override
protected Integer doInBackground(String... arg0){
int iReadCnt = 0; //本次读取的字节数
byte[] btButTmp = new byte[BUFF_MAX_CONUT]; //临时存储区
/*只要连接建立完成就开始进入读取等待处理*/
while(mbConectOk){
try{
iReadCnt = misIn.read(btButTmp); //没有数据,将一直锁死在这个位置等待
}catch (IOException e){
return CONNECT_LOST;
}
//开始处理接收到的数据
P(mresReceiveBuf);//夺取缓存访问权限
mlRxd += iReadCnt; //记录接收的字节总数
/*检查缓冲池是否溢出,如果溢出则指针标志位归0*/
if ( (miBufDataSite + iReadCnt) > iBUF_TOTAL)
miBufDataSite = 0;
/*将取到的数据复制到缓冲池中*/
for(int i=0; i<iReadCnt; i++)
mbReceiveBufs[miBufDataSite + i] = btButTmp[i];
miBufDataSite += iReadCnt; //保存本次接收的数据长度
V(mresReceiveBuf);//归还缓存访问权限
}
return THREAD_END;
}
/**
* 阻塞任务执行完后的清理工作
*/
@Override
public void onPostExecute(Integer result){
mbReceiveThread = false;//标记接收线程结束
if (CONNECT_LOST == result){
//判断是否为串口连接失败
closeConn();
}else{ //正常结束,关闭接收流
try{
misIn.close();
misIn = null;
}catch (IOException e){
misIn = null;
}
}
}
}
}
| [
"394127821@qq.com"
] | 394127821@qq.com |
157edfe11985e86a02625ae1afd049f407bb8220 | 1d8b72c0e713880b0a76f5ff17de4a9e5345c401 | /src/main/java/com/gpch/login/service/CustomerUserDetailsService.java | c4602a0565674e26c50a746ce0679d3a113e2559 | [] | no_license | weitiancai/auth-server | 06ac746d101560c0e4163a173da64e8ef30c9b32 | 0b99f8017511b9492b6e0753976458710309d01e | refs/heads/master | 2023-06-25T22:04:29.109605 | 2019-05-23T11:06:47 | 2019-05-23T11:06:47 | 188,025,557 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,059 | java | package com.gpch.login.service;
import com.gpch.login.model.CustomerUserDetail;
import com.gpch.login.model.User;
import com.gpch.login.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class CustomerUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("username="+username);
Optional<User> UserOptional = userRepository.findByName(username);
UserOptional.orElseThrow(()->new UsernameNotFoundException("Username not found"));
return UserOptional.map(CustomerUserDetail::new).get();
}
}
| [
"1711952372@qq.com"
] | 1711952372@qq.com |
f98a08ee7fc49a89da10a1dfdc16a3a7f5dfd624 | 6745f46be3f9145a61b4aa0545d8173add98e9bd | /common/am/lib/src/test/java/org/apache/syncope/common/lib/SerializationTest.java | 95453f2c4b211323bc386934c542ff3b1d01c9b4 | [
"Apache-2.0"
] | permissive | gulixciurli/syncope | 0860e84b635fd220cdc583b83d333c306bd6e29e | 97fad264948214b11f0707179877dac8977da5ea | refs/heads/main | 2023-06-17T23:43:17.197896 | 2021-07-04T18:49:58 | 2021-07-04T18:49:58 | 382,308,673 | 0 | 1 | Apache-2.0 | 2021-07-02T10:30:46 | 2021-07-02T10:17:38 | Java | UTF-8 | Java | false | false | 1,934 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.common.lib;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.syncope.common.lib.policy.AccessPolicyTO;
import org.apache.syncope.common.lib.policy.DefaultAccessPolicyConf;
import org.junit.jupiter.api.Test;
public abstract class SerializationTest {
protected abstract ObjectMapper objectMapper();
@Test
public void accessPolicyConf() throws IOException {
AccessPolicyTO policy = new AccessPolicyTO();
policy.setName("Test Access policy");
policy.setEnabled(true);
DefaultAccessPolicyConf conf = new DefaultAccessPolicyConf();
conf.getRequiredAttrs().add(new Attr.Builder("cn").values("admin", "Admin", "TheAdmin").build());
policy.setConf(conf);
StringWriter writer = new StringWriter();
objectMapper().writeValue(writer, policy);
AccessPolicyTO actual = objectMapper().readValue(writer.toString(), AccessPolicyTO.class);
assertEquals(policy, actual);
}
}
| [
"scricchiola.7@icloud.com"
] | scricchiola.7@icloud.com |
f9158900a3246537d806642a269f2ae750743740 | 291cea39a0b3952a5fb6fb5be7603f96747dee7a | /app/src/main/java/lcc/ishuhui/http/request/HttpRequest.java | 19165fdd01551a1fa34c9b94a30e3ba6f130fb8e | [] | no_license | lccLuffy/IShuHui | 2b0fd2ac70cc4bc996ad155a83ace263d8387dff | 2411d48671aee53cd43125bdb341efd04e55623d | refs/heads/master | 2021-01-21T13:49:18.162282 | 2016-05-27T08:07:13 | 2016-05-27T08:07:13 | 51,687,225 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,011 | java | package lcc.ishuhui.http.request;
import java.io.IOException;
import lcc.ishuhui.http.HttpUtil;
import lcc.ishuhui.http.builders.RequestBuilder;
import lcc.ishuhui.http.callback.HttpCallBack;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by lcc_luffy on 2016/1/25.
*/
public class HttpRequest {
private Call call;
private Request request;
private RequestBuilder requestBuilder;
public HttpRequest(RequestBuilder requestBuilder) {
this.requestBuilder = requestBuilder;
}
public Call getCall() {
return call;
}
public void execute(HttpCallBack callBack)
{
generateCall();
HttpUtil.getInstance().execute(this,callBack);
}
public Response execute() throws IOException
{
generateCall();
return call.execute();
}
private void generateCall()
{
call = HttpUtil.getInstance().getOkHttpClient().newCall(request = requestBuilder.generateRequest());
}
}
| [
"528360256@qq.com"
] | 528360256@qq.com |
4797680793cafe8c94adeee8c2dfc960a7cd307a | 4d37505edab103fd2271623b85041033d225ebcc | /spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java | 6e8125b52e991c54c34c8e8b82724f86a944e14a | [
"Apache-2.0"
] | permissive | huifer/spring-framework-read | 1799f1f073b65fed78f06993e58879571cc4548f | 73528bd85adc306a620eedd82c218094daebe0ee | refs/heads/master | 2020-12-08T08:03:17.458500 | 2020-03-02T05:51:55 | 2020-03-02T05:51:55 | 232,931,630 | 6 | 2 | Apache-2.0 | 2020-03-02T05:51:57 | 2020-01-10T00:18:15 | Java | UTF-8 | Java | false | false | 6,739 | java | /*
* Copyright 2002-2016 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.math.BigInteger;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ServletRequestAttributesTests {
private static final String KEY = "ThatThingThatThing";
@SuppressWarnings("serial")
private static final Serializable VALUE = new Serializable() {
};
@Test(expected = IllegalArgumentException.class)
public void ctorRejectsNullArg() throws Exception {
new ServletRequestAttributes(null);
}
@Test
public void setRequestScopedAttribute() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
Object value = request.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void setRequestScopedAttributeAfterCompletion() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
request.close();
try {
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
@Test
public void setSessionScopedAttribute() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
assertSame(VALUE, session.getAttribute(KEY));
}
@Test
public void setSessionScopedAttributeAfterCompletion() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION));
attrs.requestCompleted();
request.close();
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
assertSame(VALUE, session.getAttribute(KEY));
}
@Test
public void getSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertNull(value);
verify(request).getSession(false);
}
@Test
public void removeSessionScopedAttribute() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertNull(value);
}
@Test
public void removeSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
verify(request).getSession(false);
}
@Test
public void updateAccessedAttributes() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpSession session = mock(HttpSession.class);
given(request.getSession(anyBoolean())).willReturn(session);
given(session.getAttribute(KEY)).willReturn(VALUE);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION));
attrs.requestCompleted();
verify(session, times(2)).getAttribute(KEY);
verify(session).setAttribute(KEY, VALUE);
verifyNoMoreInteractions(session);
}
@Test
public void skipImmutableString() {
doSkipImmutableValue("someString");
}
@Test
public void skipImmutableCharacter() {
doSkipImmutableValue(new Character('x'));
}
@Test
public void skipImmutableBoolean() {
doSkipImmutableValue(Boolean.TRUE);
}
@Test
public void skipImmutableInteger() {
doSkipImmutableValue(new Integer(1));
}
@Test
public void skipImmutableFloat() {
doSkipImmutableValue(new Float(1.1));
}
@Test
public void skipImmutableBigInteger() {
doSkipImmutableValue(new BigInteger("1"));
}
private void doSkipImmutableValue(Object immutableValue) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpSession session = mock(HttpSession.class);
given(request.getSession(anyBoolean())).willReturn(session);
given(session.getAttribute(KEY)).willReturn(immutableValue);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
attrs.requestCompleted();
verify(session, times(2)).getAttribute(KEY);
verifyNoMoreInteractions(session);
}
}
| [
"huifer97@163.com"
] | huifer97@163.com |
8ae7fe6a85565e3a15d481f6992080d6a633cfc4 | cfc7cf0b19e0842245444da0ed77b4205d613efe | /src/java/elpoeta/felurian/util/CredencialApi.java | 97c78c1cd2299d3c44e5c2fd5555faca8e33f88b | [
"MIT"
] | permissive | elPoeta/ecommerceWineStore | bd36f478dd4c3f525d296cbe9ded52d95002a7bc | cbeb3c6e64ec55e6e922edef033df0e5a7c2a882 | refs/heads/master | 2020-04-01T02:57:14.843328 | 2018-11-03T00:59:25 | 2018-11-03T00:59:25 | 152,803,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 407 | java |
package elpoeta.felurian.util;
/**
*
* @author elpoeta
*/
public class CredencialApi {
public static final String CLIENTE_ID = "AfTtYYNm-p54vj8UmaEaVYaUUJMY9k5lrNFpJcsYTAQzgcO6Om0SfvcDEDAC0eJbBqLCuS01qBauMyQq";
public static final String CLIENTE_SECRET = "EH-S8RHgRKtDgvv07LWQql8b9gayrOAlNkeFkfjdv_lR9fqhrjKRm8CD0sU83kwC1B-aRtYl3v-N0zVG";
public static final String MODO = "sandbox";
}
| [
"leonardo.a.tosetto@gmail.com"
] | leonardo.a.tosetto@gmail.com |
9d368c0dd557bd8c0f70192045a713144cfda996 | 97021240b0283f6f6e9e834595a95d5090a6d66c | /src/test/java/com/service/customer/ItemApplicationTests.java | 223ff2b35d34ee2d1907b381a0e6973a97746bbc | [] | no_license | gokul225/item | f3bb6ce5a6155cbb366f7a89b08b5f69b1d5b692 | f6fcdb6ca5594cbe8e9c3a72ac580b46929688b8 | refs/heads/master | 2020-09-05T19:54:49.025845 | 2019-11-07T09:37:10 | 2019-11-07T09:37:10 | 220,198,982 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 214 | java | package com.service.customer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CustomerApplicationTests {
@Test
void contextLoads() {
}
}
| [
"gokulkris225@gmail.com"
] | gokulkris225@gmail.com |
c99fc57f0c2baf27be6661f0b8eb04eeda2d8d7b | fc85f14f2979ba1a31f2f99a2de463dfb14fe3e5 | /authentication/src/main/java/com/authentication/dto/UserTokenState.java | 061c186664e726e4bf3c7cc8974a9828ef1e6a80 | [] | no_license | petarcurcin/Rent-a-Car-MicroservicesApp | 0220d2a43c12dc6040379c6296abd1b30df87ff1 | cfe492db8248cc48a5bb5c54519b5c745b30b51f | refs/heads/master | 2022-11-09T12:22:20.648992 | 2020-06-30T16:55:40 | 2020-06-30T16:55:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 948 | java | package com.authentication.dto;
public class UserTokenState {
private String accessToken;
private Long expiresIn;
private UserDTO userDto;
public UserTokenState() {
this.accessToken = null;
this.expiresIn = null;
this.userDto = null;
}
public UserTokenState(String accessToken, long expiresIn, UserDTO userDto) {
this.accessToken = accessToken;
this.expiresIn = expiresIn;
this.userDto = userDto;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
public UserDTO getUser() {
return userDto;
}
public void setUser(UserDTO user) {
this.userDto = user;
}
}
| [
"jekibp@gmail.com"
] | jekibp@gmail.com |
270e2f6be34e6c1cb363469f6abdc1676af4eb45 | fa66d88901fb730c33639f3378ec3dfed8ad30fb | /src/main/java/com/Whodundid/slc/util/LayerTypes.java | 06cb57457067ccc7cb2dab679398ce43d3f686ee | [
"BSD-3-Clause"
] | permissive | Whodundid/EnhancedMC-Core | 84cd3bc760a282f1e8889b40845130a45707f8ca | c663eb8d1ba89123154af4abaa48d1b7d9b9d9aa | refs/heads/master | 2020-07-20T07:18:25.704992 | 2020-06-24T07:12:55 | 2020-06-24T07:12:55 | 206,596,038 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 779 | java | package com.Whodundid.slc.util;
import net.minecraft.entity.player.EnumPlayerModelParts;
public enum LayerTypes {
LL("ll"),
RL("rl"),
LA("la"),
RA("ra"),
J("j"),
CA("ca"),
H("h");
private final String type;
LayerTypes(String type) {
this.type = type;
}
public String getLayerType() { return type; }
public EnumPlayerModelParts getMCType() {
switch (type) {
case "ll": return EnumPlayerModelParts.LEFT_PANTS_LEG;
case "rl": return EnumPlayerModelParts.RIGHT_PANTS_LEG;
case "la": return EnumPlayerModelParts.LEFT_SLEEVE;
case "ra": return EnumPlayerModelParts.RIGHT_SLEEVE;
case "j": return EnumPlayerModelParts.JACKET;
case "ca": return EnumPlayerModelParts.CAPE;
case "h": return EnumPlayerModelParts.HAT;
default: return null;
}
}
} | [
"HTBragg7@gmail.com"
] | HTBragg7@gmail.com |
c7527982203317901d40d79884aa0d079d95d173 | 44e7adc9a1c5c0a1116097ac99c2a51692d4c986 | /aws-java-sdk-connectparticipant/src/main/java/com/amazonaws/services/connectparticipant/model/SendMessageResult.java | 7fb34cde28898ccc59e08d2389e92837f1175f33 | [
"Apache-2.0"
] | permissive | QiAnXinCodeSafe/aws-sdk-java | f93bc97c289984e41527ae5bba97bebd6554ddbe | 8251e0a3d910da4f63f1b102b171a3abf212099e | refs/heads/master | 2023-01-28T14:28:05.239019 | 2020-12-03T22:09:01 | 2020-12-03T22:09:01 | 318,460,751 | 1 | 0 | Apache-2.0 | 2020-12-04T10:06:51 | 2020-12-04T09:05:03 | null | UTF-8 | Java | false | false | 5,872 | java | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.connectparticipant.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/connectparticipant-2018-09-07/SendMessage" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SendMessageResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The ID of the message.
* </p>
*/
private String id;
/**
* <p>
* The time when the message was sent.
* </p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
* </p>
*/
private String absoluteTime;
/**
* <p>
* The ID of the message.
* </p>
*
* @param id
* The ID of the message.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The ID of the message.
* </p>
*
* @return The ID of the message.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The ID of the message.
* </p>
*
* @param id
* The ID of the message.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SendMessageResult withId(String id) {
setId(id);
return this;
}
/**
* <p>
* The time when the message was sent.
* </p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
* </p>
*
* @param absoluteTime
* The time when the message was sent.</p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
public void setAbsoluteTime(String absoluteTime) {
this.absoluteTime = absoluteTime;
}
/**
* <p>
* The time when the message was sent.
* </p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
* </p>
*
* @return The time when the message was sent.</p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
*/
public String getAbsoluteTime() {
return this.absoluteTime;
}
/**
* <p>
* The time when the message was sent.
* </p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
* </p>
*
* @param absoluteTime
* The time when the message was sent.</p>
* <p>
* It's specified in ISO 8601 format: yyyy-MM-ddThh:mm:ss.SSSZ. For example, 2019-11-08T02:41:28.172Z.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SendMessageResult withAbsoluteTime(String absoluteTime) {
setAbsoluteTime(absoluteTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: ").append(getId()).append(",");
if (getAbsoluteTime() != null)
sb.append("AbsoluteTime: ").append(getAbsoluteTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SendMessageResult == false)
return false;
SendMessageResult other = (SendMessageResult) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
if (other.getAbsoluteTime() == null ^ this.getAbsoluteTime() == null)
return false;
if (other.getAbsoluteTime() != null && other.getAbsoluteTime().equals(this.getAbsoluteTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode + ((getAbsoluteTime() == null) ? 0 : getAbsoluteTime().hashCode());
return hashCode;
}
@Override
public SendMessageResult clone() {
try {
return (SendMessageResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| [
""
] | |
1125ff486403c8a4a923ce99190f70f552aec064 | 6ab9ef6bfc6eb43eb00bff00ea5f25d0c207c1a7 | /BreakoutApplet/src/usrinput/MouseControl.java | 89a28d6adfdc680e99721a02ecd1dc1b21f4a638 | [] | no_license | EPSUND/Breakout | 35006c77130a575208dccdd9adb3780c27fffaf1 | 091adf78739e98fb94d3151caddee19f1487b91d | refs/heads/master | 2020-03-29T19:08:52.280745 | 2014-06-07T11:10:21 | 2014-06-07T11:10:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,647 | java | package usrinput;
import gui.BreakoutCanvas;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import main.Player;
import main.Shooter;
import shapes.Ball;
/***
* A class handling mouse events
* @author Erik
*
*/
public class MouseControl implements MouseListener {
private Ball ball;
private Player player;
private BreakoutCanvas canvas;
/***
* The constructor for MouseControl
* @param ball The ball to control
* @param player The player object
* @param canvas The game canvas
*/
public MouseControl(Ball ball, Player player, BreakoutCanvas canvas) {
this.ball = ball;
this.player = player;
this.canvas = canvas;
}
public synchronized void mouseClicked(MouseEvent me) {
if(me.getButton() == MouseEvent.BUTTON1) {
if(!player.getRelativeMouse()) {
player.setRelativeMouse(true);
canvas.hideCursor();
}
else {
ball.releaseBall();
Shooter shooter = player.getPaddleShooter();
if(shooter != null)
{
shooter.shoot();
}
}
}
else if(me.getButton() == MouseEvent.BUTTON3) {
player.setRelativeMouse(false);
canvas.showCursor();
}
}
public void mouseEntered(MouseEvent me) {
//Nothing happens
}
public void mouseExited(MouseEvent me) {
//Nothing happens
}
public void mousePressed(MouseEvent me) {
//Nothing happens
}
public void mouseReleased(MouseEvent me) {
//Nothing happens
}
/**
* Sets the ball to control with the mouse
* @param ball The ball
*/
public void setBall(Ball ball) {
this.ball = ball;
}
}
| [
"ESundholm@gmail.com"
] | ESundholm@gmail.com |
5205083bcf5f5bdb83e874db00b15c42e2cd62a3 | 579ddfb4d9c2b39aa71d9302ea44d352d2952079 | /demo_sikuli/src/tut1/TestGenericButton.java | 779cd52f19a9a403fbc37baab3cf1983ab99c0a7 | [] | no_license | tannth/sikuli | b4a713ccd1a318ee3d2356655383cdfcfe9c3680 | 760a6d1e56924c8b1ea460ca200c5883a7394eb3 | refs/heads/master | 2021-05-27T15:02:30.861777 | 2013-10-27T08:45:55 | 2013-10-27T08:45:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | package tut1;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.sikuli.script.Screen;
public class TestGenericButton {
/**
* @param args
*/
public static void main(String[] args) {
GenericButton.click("imgs/start.PNG");
GenericButton.click("imgs/start.PNG", .8, 5);
}
}
| [
"nguyentranhuytan@gmail.com"
] | nguyentranhuytan@gmail.com |
f1b14e3ba56984823d6976f2bdff9f343bc14d7e | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_579dcaf54dc9d6835fca275bbff4bf92622fb9f3/Context/2_579dcaf54dc9d6835fca275bbff4bf92622fb9f3_Context_s.java | 0056539e60a5720bcb7357a2d827e6efedf5588d | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 75,299 | java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Brendan Eich
* Roger Lawrence
* Mike McCabe
* Ian D. Stewart
* Andi Vajda
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
import java.beans.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.lang.reflect.*;
import org.mozilla.javascript.debug.*;
/**
* This class represents the runtime context of an executing script.
*
* Before executing a script, an instance of Context must be created
* and associated with the thread that will be executing the script.
* The Context will be used to store information about the executing
* of the script such as the call stack. Contexts are associated with
* the current thread using the <a href="#enter()">enter()</a> method.<p>
*
* The behavior of the execution engine may be altered through methods
* such as <a href="#setLanguageVersion>setLanguageVersion</a> and
* <a href="#setErrorReporter>setErrorReporter</a>.<p>
*
* Different forms of script execution are supported. Scripts may be
* evaluated from the source directly, or first compiled and then later
* executed. Interactive execution is also supported.<p>
*
* Some aspects of script execution, such as type conversions and
* object creation, may be accessed directly through methods of
* Context.
*
* @see Scriptable
* @author Norris Boyd
* @author Brendan Eich
*/
public class Context {
public static final String languageVersionProperty = "language version";
public static final String errorReporterProperty = "error reporter";
/**
* Create a new Context.
*
* Note that the Context must be associated with a thread before
* it can be used to execute a script.
*
* @see org.mozilla.javascript.Context#enter
*/
public Context() {
init();
}
/**
* Create a new context with the associated security support.
*
* @param securitySupport an encapsulation of the functionality
* needed to support security for scripts.
* @see org.mozilla.javascript.SecuritySupport
*/
public Context(SecuritySupport securitySupport) {
this.securitySupport = securitySupport;
init();
}
private void init() {
setLanguageVersion(VERSION_DEFAULT);
optimizationLevel = codegenClass != null ? 0 : -1;
Object[] array = contextListeners;
if (array != null) {
for (int i = array.length; i-- != 0;) {
((ContextListener)array[i]).contextCreated(this);
}
}
}
/**
* Get a context associated with the current thread, creating
* one if need be.
*
* The Context stores the execution state of the JavaScript
* engine, so it is required that the context be entered
* before execution may begin. Once a thread has entered
* a Context, then getCurrentContext() may be called to find
* the context that is associated with the current thread.
* <p>
* Calling <code>enter()</code> will
* return either the Context currently associated with the
* thread, or will create a new context and associate it
* with the current thread. Each call to <code>enter()</code>
* must have a matching call to <code>exit()</code>. For example,
* <pre>
* Context cx = Context.enter();
* ...
* cx.evaluateString(...);
* Context.exit();
* </pre>
* @return a Context associated with the current thread
* @see org.mozilla.javascript.Context#getCurrentContext
* @see org.mozilla.javascript.Context#exit
*/
public static Context enter() {
return enter(null);
}
/**
* Get a Context associated with the current thread, using
* the given Context if need be.
* <p>
* The same as <code>enter()</code> except that <code>cx</code>
* is associated with the current thread and returned if
* the current thread has no associated context and <code>cx</code>
* is not associated with any other thread.
* @param cx a Context to associate with the thread if possible
* @return a Context associated with the current thread
*/
public static Context enter(Context cx) {
// There's some duplication of code in this method to avoid
// unnecessary synchronizations.
Thread t = Thread.currentThread();
Context current = (Context) threadContexts.get(t);
if (current != null) {
synchronized (current) {
current.enterCount++;
}
}
else if (cx != null) {
synchronized (cx) {
if (cx.currentThread == null) {
cx.currentThread = t;
threadContexts.put(t, cx);
cx.enterCount++;
}
}
current = cx;
}
else {
current = new Context();
current.currentThread = t;
threadContexts.put(t, current);
current.enterCount = 1;
}
Object[] array = contextListeners;
if (array != null) {
for (int i = array.length; i-- != 0;) {
((ContextListener)array[i]).contextEntered(current);
}
}
return current;
}
/**
* Exit a block of code requiring a Context.
*
* Calling <code>exit()</code> will remove the association between
* the current thread and a Context if the prior call to
* <code>enter()</code> on this thread newly associated a Context
* with this thread.
* Once the current thread no longer has an associated Context,
* it cannot be used to execute JavaScript until it is again associated
* with a Context.
*
* @see org.mozilla.javascript.Context#enter
*/
public static void exit() {
Context cx = getCurrentContext();
boolean released = false;
if (cx != null) {
synchronized (cx) {
if (--cx.enterCount == 0) {
threadContexts.remove(cx.currentThread);
cx.currentThread = null;
released = true;
}
}
Object[] array = contextListeners;
if (array != null) {
for (int i = array.length; i-- != 0;) {
ContextListener l = (ContextListener)array[i];
l.contextExited(cx);
if (released) { l.contextReleased(cx); }
}
}
}
}
/**
* Get the current Context.
*
* The current Context is per-thread; this method looks up
* the Context associated with the current thread. <p>
*
* @return the Context associated with the current thread, or
* null if no context is associated with the current
* thread.
* @see org.mozilla.javascript.Context#enter
* @see org.mozilla.javascript.Context#exit
*/
public static Context getCurrentContext() {
Thread t = Thread.currentThread();
return (Context) threadContexts.get(t);
}
/**
* Language versions
*
* All integral values are reserved for future version numbers.
*/
/**
* The unknown version.
*/
public static final int VERSION_UNKNOWN = -1;
/**
* The default version.
*/
public static final int VERSION_DEFAULT = 0;
/**
* JavaScript 1.0
*/
public static final int VERSION_1_0 = 100;
/**
* JavaScript 1.1
*/
public static final int VERSION_1_1 = 110;
/**
* JavaScript 1.2
*/
public static final int VERSION_1_2 = 120;
/**
* JavaScript 1.3
*/
public static final int VERSION_1_3 = 130;
/**
* JavaScript 1.4
*/
public static final int VERSION_1_4 = 140;
/**
* JavaScript 1.5
*/
public static final int VERSION_1_5 = 150;
/**
* Get the current language version.
* <p>
* The language version number affects JavaScript semantics as detailed
* in the overview documentation.
*
* @return an integer that is one of VERSION_1_0, VERSION_1_1, etc.
*/
public int getLanguageVersion() {
return version;
}
/**
* Set the language version.
*
* <p>
* Setting the language version will affect functions and scripts compiled
* subsequently. See the overview documentation for version-specific
* behavior.
*
* @param version the version as specified by VERSION_1_0, VERSION_1_1, etc.
*/
public void setLanguageVersion(int version) {
Object[] array = listeners;
if (array != null && version != this.version) {
firePropertyChangeImpl(array, languageVersionProperty,
new Integer(this.version),
new Integer(version));
}
this.version = version;
}
/**
* Get the implementation version.
*
* <p>
* The implementation version is of the form
* <pre>
* "<i>name langVer</i> <code>release</code> <i>relNum date</i>"
* </pre>
* where <i>name</i> is the name of the product, <i>langVer</i> is
* the language version, <i>relNum</i> is the release number, and
* <i>date</i> is the release date for that specific
* release in the form "yyyy mm dd".
*
* @return a string that encodes the product, language version, release
* number, and date.
*/
public String getImplementationVersion() {
return "Rhino 1.5 release 2 2000 06 15";
}
/**
* Get the current error reporter.
*
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter getErrorReporter() {
if (errorReporter == null) {
errorReporter = new DefaultErrorReporter();
}
return errorReporter;
}
/**
* Change the current error reporter.
*
* @return the previous error reporter
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter setErrorReporter(ErrorReporter reporter) {
ErrorReporter result = errorReporter;
Object[] array = listeners;
if (array != null && errorReporter != reporter) {
firePropertyChangeImpl(array, errorReporterProperty,
errorReporter, reporter);
}
errorReporter = reporter;
return result;
}
/**
* Get the current locale. Returns the default locale if none has
* been set.
*
* @see java.util.Locale
*/
public Locale getLocale() {
if (locale == null)
locale = Locale.getDefault();
return locale;
}
/**
* Set the current locale.
*
* @see java.util.Locale
*/
public Locale setLocale(Locale loc) {
Locale result = locale;
locale = loc;
return result;
}
/**
* Register an object to receive notifications when a bound property
* has changed
* @see java.beans.PropertyChangeEvent
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
synchronized (this) {
listeners = ListenerArray.add(listeners, listener);
}
}
/**
* Remove an object from the list of objects registered to receive
* notification of changes to a bounded property
* @see java.beans.PropertyChangeEvent
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
synchronized (this) {
listeners = ListenerArray.remove(listeners, listener);
}
}
/**
* Notify any registered listeners that a bounded property has changed
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @see java.beans.PropertyChangeListener
* @see java.beans.PropertyChangeEvent
* @param property the bound property
* @param oldValue the old value
* @param newVale the new value
*/
void firePropertyChange(String property, Object oldValue,
Object newValue)
{
Object[] array = listeners;
if (array != null) {
firePropertyChangeImpl(array, property, oldValue, newValue);
}
}
private void firePropertyChangeImpl(Object[] array, String property,
Object oldValue, Object newValue)
{
for (int i = array.length; i-- != 0;) {
Object obj = array[i];
if (obj instanceof PropertyChangeListener) {
PropertyChangeListener l = (PropertyChangeListener)obj;
l.propertyChange(new PropertyChangeEvent(
this, property, oldValue, newValue));
}
}
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = Context.getContext();
cx.getErrorReporter().warning(message, sourceName, lineno,
lineSource, lineOffset);
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportWarning(message, filename, linep[0], null, 0);
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.errorCount++;
cx.getErrorReporter().error(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message);
}
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportError(message, filename, linep[0], null, 0);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @return a runtime exception that will be thrown to terminate the
* execution of the script
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message,
String sourceName,
int lineno,
String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.errorCount++;
return cx.getErrorReporter().
runtimeError(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message);
}
}
static EvaluatorException reportRuntimeError0(String messageId) {
return reportRuntimeError(getMessage0(messageId));
}
static EvaluatorException reportRuntimeError1
(String messageId, Object arg1)
{
return reportRuntimeError(getMessage1(messageId, arg1));
}
static EvaluatorException reportRuntimeError2
(String messageId, Object arg1, Object arg2)
{
return reportRuntimeError(getMessage2(messageId, arg1, arg2));
}
static EvaluatorException reportRuntimeError3
(String messageId, Object arg1, Object arg2, Object arg3)
{
return reportRuntimeError(getMessage3(messageId, arg1, arg2, arg3));
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
return Context.reportRuntimeError(message, filename, linep[0], null, 0);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @return the initialized scope
*/
public Scriptable initStandardObjects(ScriptableObject scope) {
return initStandardObjects(scope, false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added or
* removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
* @since 1.4R3
*/
public ScriptableObject initStandardObjects(ScriptableObject scope,
boolean sealed)
{
if (scope == null)
scope = new NativeObject();
BaseFunction.init(this, scope, sealed);
NativeObject.init(this, scope, sealed);
Scriptable objectProto = ScriptableObject.getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.getFunctionPrototype(scope);
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
NativeError.init(this, scope, sealed);
NativeGlobal.init(this, scope, sealed);
NativeArray.init(this, scope, sealed);
NativeString.init(this, scope, sealed);
NativeBoolean.init(this, scope, sealed);
NativeNumber.init(this, scope, sealed);
NativeDate.init(this, scope, sealed);
NativeMath.init(this, scope, sealed);
NativeWith.init(this, scope, sealed);
NativeCall.init(this, scope, sealed);
NativeScript.init(this, scope, sealed);
new LazilyLoadedCtor(scope,
"RegExp",
"org.mozilla.javascript.regexp.NativeRegExp",
sealed);
// This creates the Packages and java package roots.
new LazilyLoadedCtor(scope,
"Packages",
"org.mozilla.javascript.NativeJavaPackage",
sealed);
new LazilyLoadedCtor(scope,
"java",
"org.mozilla.javascript.NativeJavaPackage",
sealed);
new LazilyLoadedCtor(scope,
"getClass",
"org.mozilla.javascript.NativeJavaPackage",
sealed);
// Define the JavaAdapter class, allowing it to be overridden.
String adapterClass = "org.mozilla.javascript.JavaAdapter";
String adapterProperty = "JavaAdapter";
try {
adapterClass = System.getProperty(adapterClass, adapterClass);
adapterProperty = System.getProperty
("org.mozilla.javascript.JavaAdapterClassName",
adapterProperty);
}
catch (SecurityException e) {
// We may not be allowed to get system properties. Just
// use the default adapter in that case.
}
new LazilyLoadedCtor(scope, adapterProperty, adapterClass, sealed);
return scope;
}
/**
* Get the singleton object that represents the JavaScript Undefined value.
*/
public static Object getUndefinedValue() {
return Undefined.instance;
}
/**
* Evaluate a JavaScript source string.
*
* The provided source name and line number are used for error messages
* and for producing debug information.
*
* @param scope the scope to execute in
* @param source the JavaScript source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the string
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the source string
* @see org.mozilla.javascript.SecuritySupport
*/
public Object evaluateString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
throws JavaScriptException
{
try {
Reader in = new StringReader(source);
return evaluateReader(scope, in, sourceName, lineno,
securityDomain);
}
catch (IOException ioe) {
// Should never occur because we just made the reader from a String
throw new RuntimeException();
}
}
/**
* Evaluate a reader as JavaScript source.
*
* All characters of the reader are consumed.
*
* @param scope the scope to execute in
* @param in the Reader to get JavaScript source from
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the source
*
* @exception IOException if an IOException was generated by the Reader
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the Reader
*/
public Object evaluateReader(Scriptable scope, Reader in,
String sourceName, int lineno,
Object securityDomain)
throws IOException, JavaScriptException
{
Script script = compileReader(scope, in, sourceName, lineno,
securityDomain);
if (script != null)
return script.exec(this, scope);
else
return null;
}
/**
* Check whether a string is ready to be compiled.
* <p>
* stringIsCompilableUnit is intended to support interactive compilation of
* javascript. If compiling the string would result in an error
* that might be fixed by appending more source, this method
* returns false. In every other case, it returns true.
* <p>
* Interactive shells may accumulate source lines, using this
* method after each new line is appended to check whether the
* statement being entered is complete.
*
* @param source the source buffer to check
* @return whether the source is ready for compilation
* @since 1.4 Release 2
*/
synchronized public boolean stringIsCompilableUnit(String source)
{
Reader in = new StringReader(source);
// no source name or source text manager, because we're just
// going to throw away the result.
TokenStream ts = new TokenStream(in, null, null, 1);
// Temporarily set error reporter to always be the exception-throwing
// DefaultErrorReporter. (This is why the method is synchronized...)
ErrorReporter currentReporter =
setErrorReporter(new DefaultErrorReporter());
boolean errorseen = false;
try {
IRFactory irf = new IRFactory(ts, null);
Parser p = new Parser(irf);
p.parse(ts);
} catch (IOException ioe) {
errorseen = true;
} catch (EvaluatorException ee) {
errorseen = true;
} finally {
// Restore the old error reporter.
setErrorReporter(currentReporter);
}
// Return false only if an error occurred as a result of reading past
// the end of the file, i.e. if the source could be fixed by
// appending more source.
if (errorseen && ts.eof())
return false;
else
return true;
}
/**
* Compiles the source in the given reader.
* <p>
* Returns a script that may later be executed.
* Will consume all the source in the reader.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param in the input reader
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
* @exception IOException if an IOException was generated by the Reader
*/
public Script compileReader(Scriptable scope, Reader in, String sourceName,
int lineno, Object securityDomain)
throws IOException
{
return (Script) compile(scope, in, sourceName, lineno, securityDomain,
false);
}
/**
* Compile a JavaScript function.
* <p>
* The function source must be a function definition as defined by
* ECMA (e.g., "function f(a) { return a; }").
*
* @param scope the scope to compile relative to
* @param source the function definition source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a Function that may later be called
* @see org.mozilla.javascript.Function
*/
public Function compileFunction(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
Reader in = new StringReader(source);
try {
return (Function) compile(scope, in, sourceName, lineno,
securityDomain, true);
}
catch (IOException ioe) {
// Should never happen because we just made the reader
// from a String
throw new RuntimeException();
}
}
/**
* Decompile the script.
* <p>
* The canonical source of the script is returned.
*
* @param script the script to decompile
* @param scope the scope under which to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the script source
*/
public String decompileScript(Script script, Scriptable scope,
int indent)
{
NativeScript ns = (NativeScript) script;
ns.initScript(scope);
return ns.decompile(this, indent, false);
}
/**
* Decompile a JavaScript Function.
* <p>
* Decompiles a previously compiled JavaScript function object to
* canonical source.
* <p>
* Returns function body of '[native code]' if no decompilation
* information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function source
*/
public String decompileFunction(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, false);
else
return "function " + fun.getClassName() +
"() {\n\t[native code]\n}\n";
}
/**
* Decompile the body of a JavaScript Function.
* <p>
* Decompiles the body a previously compiled JavaScript Function
* object to canonical source, omitting the function header and
* trailing brace.
*
* Returns '[native code]' if no decompilation information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function body source.
*/
public String decompileFunctionBody(Function fun, int indent) {
if (fun instanceof BaseFunction)
return ((BaseFunction)fun).decompile(this, indent, true);
else
// not sure what the right response here is. JSRef currently
// dumps core.
return "[native code]\n";
}
/**
* Create a new JavaScript object.
*
* Equivalent to evaluating "new Object()".
* @param scope the scope to search for the constructor and to evaluate
* against
* @return the new object
* @exception PropertyException if "Object" cannot be found in
* the scope
* @exception NotAFunctionException if the "Object" found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
return newObject(scope, "Object", null);
}
/**
* Create a new JavaScript object by executing the named constructor.
*
* The call <code>newObject(scope, "Foo")</code> is equivalent to
* evaluating "new Foo()".
*
* @param scope the scope to search for the constructor and to evaluate against
* @param constructorName the name of the constructor to call
* @return the new object
* @exception PropertyException if a property with the constructor
* name cannot be found in the scope
* @exception NotAFunctionException if the property found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
return newObject(scope, constructorName, null);
}
/**
* Creates a new JavaScript object by executing the named constructor.
*
* Searches <code>scope</code> for the named constructor, calls it with
* the given arguments, and returns the result.<p>
*
* The code
* <pre>
* Object[] args = { "a", "b" };
* newObject(scope, "Foo", args)</pre>
* is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo
* constructor has been defined in <code>scope</code>.
*
* @param scope The scope to search for the constructor and to evaluate
* against
* @param constructorName the name of the constructor to call
* @param args the array of arguments for the constructor
* @return the new object
* @exception PropertyException if a property with the constructor
* name cannot be found in the scope
* @exception NotAFunctionException if the property found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurs while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName,
Object[] args)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
Object ctorVal = ScriptRuntime.getTopLevelProp(scope, constructorName);
if (ctorVal == Scriptable.NOT_FOUND) {
String message = getMessage1("msg.ctor.not.found", constructorName);
throw new PropertyException(message);
}
if (!(ctorVal instanceof Function)) {
String message = getMessage1("msg.not.ctor", constructorName);
throw new NotAFunctionException(message);
}
Function ctor = (Function) ctorVal;
return ctor.construct(this, ctor.getParentScope(),
(args == null) ? ScriptRuntime.emptyArgs : args);
}
/**
* Create an array with a specified initial length.
* <p>
* @param scope the scope to create the object in
* @param length the initial length (JavaScript arrays may have
* additional properties added dynamically).
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, int length) {
Scriptable result = new NativeArray(length);
newArrayHelper(scope, result);
return result;
}
/**
* Create an array with a set of initial elements.
* <p>
* @param scope the scope to create the object in
* @param elements the initial elements. Each object in this array
* must be an acceptable JavaScript type.
* @return the new array object
*/
public Scriptable newArray(Scriptable scope, Object[] elements) {
Scriptable result = new NativeArray(elements);
newArrayHelper(scope, result);
return result;
}
/**
* Get the elements of a JavaScript array.
* <p>
* If the object defines a length property, a Java array with that
* length is created and initialized with the values obtained by
* calling get() on object for each value of i in [0,length-1]. If
* there is not a defined value for a property the Undefined value
* is used to initialize the corresponding element in the array. The
* Java array is then returned.
* If the object doesn't define a length property, null is returned.
* @param object the JavaScript array or array-like object
* @return a Java array of objects
* @since 1.4 release 2
*/
public Object[] getElements(Scriptable object) {
double doubleLen = NativeArray.getLengthProperty(object);
if (doubleLen != doubleLen)
return null;
int len = (int) doubleLen;
Object[] result = new Object[len];
for (int i=0; i < len; i++) {
Object elem = object.get(i, object);
result[i] = elem == Scriptable.NOT_FOUND ? Undefined.instance
: elem;
}
return result;
}
/**
* Convert the value to a JavaScript boolean value.
* <p>
* See ECMA 9.2.
*
* @param value a JavaScript value
* @return the corresponding boolean value converted using
* the ECMA rules
*/
public static boolean toBoolean(Object value) {
return ScriptRuntime.toBoolean(value);
}
/**
* Convert the value to a JavaScript Number value.
* <p>
* Returns a Java double for the JavaScript Number.
* <p>
* See ECMA 9.3.
*
* @param value a JavaScript value
* @return the corresponding double value converted using
* the ECMA rules
*/
public static double toNumber(Object value) {
return ScriptRuntime.toNumber(value);
}
/**
* Convert the value to a JavaScript String value.
* <p>
* See ECMA 9.8.
* <p>
* @param value a JavaScript value
* @return the corresponding String value converted using
* the ECMA rules
*/
public static String toString(Object value) {
return ScriptRuntime.toString(value);
}
/**
* Convert the value to an JavaScript object value.
* <p>
* Note that a scope must be provided to look up the constructors
* for Number, Boolean, and String.
* <p>
* See ECMA 9.9.
* <p>
* Additionally, arbitrary Java objects and classes will be
* wrapped in a Scriptable object with its Java fields and methods
* reflected as JavaScript properties of the object.
*
* @param value any Java object
* @param scope global scope containing constructors for Number,
* Boolean, and String
* @return new JavaScript object
*/
public static Scriptable toObject(Object value, Scriptable scope) {
return ScriptRuntime.toObject(scope, value, null);
}
/**
* Convert the value to an JavaScript object value.
* <p>
* Note that a scope must be provided to look up the constructors
* for Number, Boolean, and String.
* <p>
* See ECMA 9.9.
* <p>
* Additionally, arbitrary Java objects and classes will be
* wrapped in a Scriptable object with its Java fields and methods
* reflected as JavaScript properties of the object. If the
* "staticType" parameter is provided, it will be used as the static
* type of the Java value to create.
*
* @param value any Java object
* @param scope global scope containing constructors for Number,
* Boolean, and String
* @param staticType the static type of the Java value to create
* @return new JavaScript object
*/
public static Scriptable toObject(Object value, Scriptable scope,
Class staticType) {
if (value == null && staticType != null)
return null;
return ScriptRuntime.toObject(scope, value, staticType);
}
/**
* Tell whether debug information is being generated.
* @since 1.3
*/
public boolean isGeneratingDebug() {
return generatingDebug;
}
/**
* Specify whether or not debug information should be generated.
* <p>
* Setting the generation of debug information on will set the
* optimization level to zero.
* @since 1.3
*/
public void setGeneratingDebug(boolean generatingDebug) {
generatingDebugChanged = true;
if (generatingDebug)
setOptimizationLevel(0);
this.generatingDebug = generatingDebug;
}
/**
* Tell whether source information is being generated.
* @since 1.3
*/
public boolean isGeneratingSource() {
return generatingSource;
}
/**
* Specify whether or not source information should be generated.
* <p>
* Without source information, evaluating the "toString" method
* on JavaScript functions produces only "[native code]" for
* the body of the function.
* Note that code generated without source is not fully ECMA
* conformant.
* @since 1.3
*/
public void setGeneratingSource(boolean generatingSource) {
this.generatingSource = generatingSource;
}
/**
* Get the current optimization level.
* <p>
* The optimization level is expressed as an integer between -1 and
* 9.
* @since 1.3
*
*/
public int getOptimizationLevel() {
return optimizationLevel;
}
/**
* Set the current optimization level.
* <p>
* The optimization level is expected to be an integer between -1 and
* 9. Any negative values will be interpreted as -1, and any values
* greater than 9 will be interpreted as 9.
* An optimization level of -1 indicates that interpretive mode will
* always be used. Levels 0 through 9 indicate that class files may
* be generated. Higher optimization levels trade off compile time
* performance for runtime performance.
* The optimizer level can't be set greater than -1 if the optimizer
* package doesn't exist at run time.
* @param optimizationLevel an integer indicating the level of
* optimization to perform
* @since 1.3
*
*/
public void setOptimizationLevel(int optimizationLevel) {
if (optimizationLevel < 0) {
optimizationLevel = -1;
} else if (optimizationLevel > 9) {
optimizationLevel = 9;
}
if (codegenClass == null)
optimizationLevel = -1;
this.optimizationLevel = optimizationLevel;
}
/**
* Get the current target class file name.
* <p>
* If nonnull, requests to compile source will result in one or
* more class files being generated.
* @since 1.3
*/
public String getTargetClassFileName() {
return nameHelper == null
? null
: nameHelper.getTargetClassFileName();
}
/**
* Set the current target class file name.
* <p>
* If nonnull, requests to compile source will result in one or
* more class files being generated. If null, classes will only
* be generated in memory.
*
* @since 1.3
*/
public void setTargetClassFileName(String classFileName) {
if (nameHelper != null)
nameHelper.setTargetClassFileName(classFileName);
}
/**
* Get the current package to generate classes into.
*
* @since 1.3
*/
public String getTargetPackage() {
return (nameHelper == null) ? null : nameHelper.getTargetPackage();
}
/**
* Set the package to generate classes into.
*
* @since 1.3
*/
public void setTargetPackage(String targetPackage) {
if (nameHelper != null)
nameHelper.setTargetPackage(targetPackage);
}
/**
* Get the current interface to write class bytes into.
*
* @see ClassOutput
* @since 1.5 Release 2
*/
public ClassOutput getClassOutput() {
return nameHelper == null ? null : nameHelper.getClassOutput();
}
/**
* Set the interface to write class bytes into.
* Unless setTargetClassFileName() has been called classOutput will be
* used each time the javascript compiler has generated the bytecode for a
* script class.
*
* @see ClassOutput
* @since 1.5 Release 2
*/
public void setClassOutput(ClassOutput classOutput) {
if (nameHelper != null)
nameHelper.setClassOutput(classOutput);
}
/**
* Add a Context listener.
*/
public static void addContextListener(ContextListener listener) {
synchronized (staticDataLock) {
contextListeners = ListenerArray.add(contextListeners, listener);
}
}
/**
* Remove a Context listener.
* @param listener the listener to remove.
*/
public static void removeContextListener(ContextListener listener) {
synchronized (staticDataLock) {
contextListeners = ListenerArray.remove(contextListeners, listener);
}
}
/**
* Set the security support for this context.
* <p> SecuritySupport may only be set if it is currently null.
* Otherwise a SecurityException is thrown.
* @param supportObj a SecuritySupport object
* @throws SecurityException if there is already a SecuritySupport
* object for this Context
*/
public synchronized void setSecuritySupport(SecuritySupport supportObj) {
if (securitySupport != null) {
throw new SecurityException("Cannot overwrite existing " +
"SecuritySupport object");
}
securitySupport = supportObj;
}
/**
* Return true if a security domain is required on calls to
* compile and evaluate scripts.
*
* @since 1.4 Release 2
*/
public static boolean isSecurityDomainRequired() {
return requireSecurityDomain;
}
/**
* Returns the security context associated with the innermost
* script or function being executed by the interpreter.
* @since 1.4 release 2
*/
public Object getInterpreterSecurityDomain() {
return interpreterSecurityDomain;
}
/**
* Returns true if the class parameter is a class in the
* interpreter. Typically used by embeddings that get a class
* context to check security. These embeddings must know
* whether to get the security context associated with the
* interpreter or not.
*
* @param cl a class to test whether or not it is an interpreter
* class
* @return true if cl is an interpreter class
* @since 1.4 release 2
*/
public boolean isInterpreterClass(Class cl) {
return cl == Interpreter.class;
}
/**
* Set the class that the generated target will extend.
*
* @param extendsClass the class it extends
*/
public void setTargetExtends(Class extendsClass) {
if (nameHelper != null) {
nameHelper.setTargetExtends(extendsClass);
}
}
/**
* Set the interfaces that the generated target will implement.
*
* @param implementsClasses an array of Class objects, one for each
* interface the target will extend
*/
public void setTargetImplements(Class[] implementsClasses) {
if (nameHelper != null) {
nameHelper.setTargetImplements(implementsClasses);
}
}
/**
* Get a value corresponding to a key.
* <p>
* Since the Context is associated with a thread it can be
* used to maintain values that can be later retrieved using
* the current thread.
* <p>
* Note that the values are maintained with the Context, so
* if the Context is disassociated from the thread the values
* cannot be retreived. Also, if private data is to be maintained
* in this manner the key should be a java.lang.Object
* whose reference is not divulged to untrusted code.
* @param key the key used to lookup the value
* @return a value previously stored using putThreadLocal.
*/
public Object getThreadLocal(Object key) {
if (hashtable == null)
return null;
return hashtable.get(key);
}
/**
* Put a value that can later be retrieved using a given key.
* <p>
* @param key the key used to index the value
* @param value the value to save
*/
public void putThreadLocal(Object key, Object value) {
if (hashtable == null)
hashtable = new Hashtable();
hashtable.put(key, value);
}
/**
* Remove values from thread-local storage.
* @param key the key for the entry to remove.
* @since 1.5 release 2
*/
public void removeThreadLocal(Object key) {
if (hashtable == null)
return;
hashtable.remove(key);
}
/**
* Return whether functions are compiled by this context using
* dynamic scope.
* <p>
* If functions are compiled with dynamic scope, then they execute
* in the scope of their caller, rather than in their parent scope.
* This is useful for sharing functions across multiple scopes.
* @since 1.5 Release 1
*/
public boolean hasCompileFunctionsWithDynamicScope() {
return compileFunctionsWithDynamicScopeFlag;
}
/**
* Set whether functions compiled by this context should use
* dynamic scope.
* <p>
* @param flag if true, compile functions with dynamic scope
* @since 1.5 Release 1
*/
public void setCompileFunctionsWithDynamicScope(boolean flag) {
compileFunctionsWithDynamicScopeFlag = flag;
}
/**
* Set whether to cache some values statically.
* <p>
* By default, the engine will cache some values statically
* (reflected Java classes, for instance). This can speed
* execution dramatically, but increases the memory footprint.
* Also, with caching enabled, references may be held to
* objects past the lifetime of any real usage.
* <p>
* If caching is enabled and this method is called with a
* <code>false</code> argument, the caches will be emptied.
* So one strategy could be to clear the caches at times
* appropriate to the application.
* <p>
* Caching is enabled by default.
*
* @param cachingEnabled if true, caching is enabled
* @since 1.5 Release 1
*/
public static void setCachingEnabled(boolean cachingEnabled) {
if (isCachingEnabled && !cachingEnabled) {
// Caching is being turned off. Empty caches.
JavaMembers.classTable = new Hashtable();
nameHelper.reset();
}
isCachingEnabled = cachingEnabled;
FunctionObject.setCachingEnabled(cachingEnabled);
}
/**
* Set a WrapHandler for this Context.
* <p>
* The WrapHandler allows custom object wrapping behavior for
* Java object manipulated with JavaScript.
* @see org.mozilla.javascript.WrapHandler
* @since 1.5 Release 2
*/
public void setWrapHandler(WrapHandler wrapHandler) {
this.wrapHandler = wrapHandler;
}
/**
* Return the current WrapHandler, or null if none is defined.
* @see org.mozilla.javascript.WrapHandler
* @since 1.5 Release 2
*/
public WrapHandler getWrapHandler() {
return wrapHandler;
}
public DebuggableEngine getDebuggableEngine() {
if (debuggableEngine == null)
debuggableEngine = new DebuggableEngineImpl(this);
return debuggableEngine;
}
/**
* if hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true,
* Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000
* in deviation with Ecma B.2.4
*/
public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
/**
* Controls certain aspects of script semantics.
* Should be overwritten to alter default behavior.
* @param featureIndex feature index to check
* @return true if the <code>featureIndex</code> feature is turned on
* @see #FEATURE_NON_ECMA_GET_YEAR
*/
public boolean hasFeature(int featureIndex) {
if (featureIndex == FEATURE_NON_ECMA_GET_YEAR) {
/*
* During the great date rewrite of 1.3, we tried to track the
* evolving ECMA standard, which then had a definition of
* getYear which always subtracted 1900. Which we
* implemented, not realizing that it was incompatible with
* the old behavior... now, rather than thrash the behavior
* yet again, we've decided to leave it with the - 1900
* behavior and point people to the getFullYear method. But
* we try to protect existing scripts that have specified a
* version...
*/
return (version == Context.VERSION_1_0
|| version == Context.VERSION_1_1
|| version == Context.VERSION_1_2);
}
throw new RuntimeException("Bad feature index: " + featureIndex);
}
/**
* Get/Set threshold of executed instructions counter that triggers call to
* <code>observeInstructionCount()</code>.
* When the threshold is zero, instruction counting is disabled,
* otherwise each time the run-time executes at least the threshold value
* of script instructions, <code>observeInstructionCount()</code> will
* be called.
*/
public int getInstructionObserverThreshold() {
return instructionThreshold;
}
public void setInstructionObserverThreshold(int threshold) {
instructionThreshold = threshold;
}
/**
* Allow application to monitor counter of executed script instructions
* in Context subclasses.
* Run-time calls this when instruction counting is enabled and the counter
* reaches limit set by <code>setInstructionObserverThreshold()</code>.
* The method is useful to observe long running scripts and if necessary
* to terminate them.
* @param instructionCount amount of script instruction executed since
* last call to <code>observeInstructionCount</code>
* @throws Error to terminate the script
*/
protected void observeInstructionCount(int instructionCount) {}
/********** end of API **********/
void pushFrame(DebugFrame frame) {
if (frameStack == null)
frameStack = new java.util.Stack();
frameStack.push(frame);
}
void popFrame() {
frameStack.pop();
}
static String getMessage0(String messageId) {
return getMessage(messageId, null);
}
static String getMessage1(String messageId, Object arg1) {
Object[] arguments = {arg1};
return getMessage(messageId, arguments);
}
static String getMessage2(String messageId, Object arg1, Object arg2) {
Object[] arguments = {arg1, arg2};
return getMessage(messageId, arguments);
}
static String getMessage3
(String messageId, Object arg1, Object arg2, Object arg3) {
Object[] arguments = {arg1, arg2, arg3};
return getMessage(messageId, arguments);
}
/**
* Internal method that reports an error for missing calls to
* enter().
*/
static Context getContext() {
Thread t = Thread.currentThread();
Context cx = (Context) threadContexts.get(t);
if (cx == null) {
throw new RuntimeException(
"No Context associated with current Thread");
}
return cx;
}
/* OPT there's a noticable delay for the first error! Maybe it'd
* make sense to use a ListResourceBundle instead of a properties
* file to avoid (synchronized) text parsing.
*/
static final String defaultResource =
"org.mozilla.javascript.resources.Messages";
static String getMessage(String messageId, Object[] arguments) {
Context cx = getCurrentContext();
Locale locale = cx != null ? cx.getLocale() : Locale.getDefault();
// ResourceBundle does cacheing.
ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
String formatString;
try {
formatString = rb.getString(messageId);
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException
("no message resource found for message property "+ messageId);
}
/*
* It's OK to format the string, even if 'arguments' is null;
* we need to format it anyway, to make double ''s collapse to
* single 's.
*/
// TODO: MessageFormat is not available on pJava
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
// debug flags
static final boolean printTrees = false;
/**
* Compile a script.
*
* Reads script source from the reader and compiles it, returning
* a class for either the script or the function depending on the
* value of <code>returnFunction</code>.
*
* @param scope the scope to compile relative to
* @param in the Reader to read source from
* @param sourceName the name of the origin of the source (usually
* a file or URL)
* @param lineno the line number of the start of the source
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @param returnFunction if true, will expect the source to contain
* a function; return value is assumed to
* then be a org.mozilla.javascript.Function
* @return a class for the script or function
* @see org.mozilla.javascript.Context#compileReader
*/
private Object compile(Scriptable scope, Reader in, String sourceName,
int lineno, Object securityDomain,
boolean returnFunction)
throws IOException
{
if (debugger != null && in != null) {
in = new DebugReader(in);
}
TokenStream ts = new TokenStream(in, scope, sourceName, lineno);
return compile(scope, ts, securityDomain, in, returnFunction);
}
private static Class codegenClass;
private static ClassNameHelper nameHelper;
static {
try {
codegenClass = Class.forName(
"org.mozilla.javascript.optimizer.Codegen");
Class nameHelperClass = Class.forName(
"org.mozilla.javascript.optimizer.OptClassNameHelper");
nameHelper = (ClassNameHelper)nameHelperClass.newInstance();
} catch (ClassNotFoundException x) {
// ...must be running lite, that's ok
codegenClass = null;
} catch (IllegalAccessException x) {
codegenClass = null;
} catch (InstantiationException x) {
codegenClass = null;
}
}
private Interpreter getCompiler() {
if (codegenClass != null) {
try {
return (Interpreter) codegenClass.newInstance();
}
catch (SecurityException x) {
}
catch (IllegalArgumentException x) {
}
catch (InstantiationException x) {
}
catch (IllegalAccessException x) {
}
// fall through
}
return new Interpreter();
}
private Object compile(Scriptable scope, TokenStream ts,
Object securityDomain, Reader in,
boolean returnFunction)
throws IOException
{
Interpreter compiler = optimizationLevel == -1
? new Interpreter()
: getCompiler();
errorCount = 0;
IRFactory irf = compiler.createIRFactory(ts, nameHelper, scope);
Parser p = new Parser(irf);
Node tree = (Node) p.parse(ts);
if (tree == null)
return null;
tree = compiler.transform(tree, ts, scope);
if (printTrees)
System.out.println(tree.toStringTree());
if (returnFunction) {
Node first = tree.getFirstChild();
if (first == null)
return null;
tree = (Node) first.getProp(Node.FUNCTION_PROP);
if (tree == null)
return null;
}
if (in instanceof DebugReader) {
DebugReader dr = (DebugReader) in;
tree.putProp(Node.DEBUGSOURCE_PROP, dr.getSaved());
}
Object result = compiler.compile(this, scope, tree, securityDomain,
securitySupport, nameHelper);
return errorCount == 0 ? result : null;
}
static String getSourcePositionFromStack(int[] linep) {
Context cx = getCurrentContext();
if (cx == null)
return null;
if (cx.interpreterLine > 0 && cx.interpreterSourceFile != null) {
linep[0] = cx.interpreterLine;
return cx.interpreterSourceFile;
}
/**
* A bit of a hack, but the only way to get filename and line
* number from an enclosing frame.
*/
CharArrayWriter writer = new CharArrayWriter();
RuntimeException re = new RuntimeException();
re.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
int open = -1;
int close = -1;
int colon = -1;
for (int i=0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ':')
colon = i;
else if (c == '(')
open = i;
else if (c == ')')
close = i;
else if (c == '\n' && open != -1 && close != -1 && colon != -1 &&
open < colon && colon < close)
{
String fileStr = s.substring(open + 1, colon);
if (fileStr.endsWith(".js")) {
String lineStr = s.substring(colon + 1, close);
try {
linep[0] = Integer.parseInt(lineStr);
return fileStr;
}
catch (NumberFormatException e) {
// fall through
}
}
open = close = colon = -1;
}
}
return null;
}
RegExpProxy getRegExpProxy() {
if (regExpProxy == null) {
try {
Class c = Class.forName(
"org.mozilla.javascript.regexp.RegExpImpl");
regExpProxy = (RegExpProxy) c.newInstance();
return regExpProxy;
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
}
return regExpProxy;
}
private void newArrayHelper(Scriptable scope, Scriptable array) {
array.setParentScope(scope);
Object ctor = ScriptRuntime.getTopLevelProp(scope, "Array");
if (ctor != null && ctor instanceof Scriptable) {
Scriptable s = (Scriptable) ctor;
array.setPrototype((Scriptable) s.get("prototype", s));
}
}
final boolean isVersionECMA1() {
return version == VERSION_DEFAULT || version >= VERSION_1_3;
}
/**
* Get the security context from the given class.
* <p>
* When some form of security check needs to be done, the class context
* must retrieved from the security manager to determine what class is
* requesting some form of privileged access.
* @since 1.4 release 2
*/
Object getSecurityDomainFromClass(Class cl) {
if (cl == Interpreter.class)
return interpreterSecurityDomain;
return securitySupport.getSecurityDomain(cl);
}
SecuritySupport getSecuritySupport() {
return securitySupport;
}
Object getSecurityDomainForStackDepth(int depth) {
Object result = null;
if (securitySupport != null) {
Class[] classes = securitySupport.getClassContext();
if (classes != null) {
if (depth != -1) {
int depth1 = depth + 1;
result = getSecurityDomainFromClass(classes[depth1]);
} else {
for (int i=1; i < classes.length; i++) {
result = getSecurityDomainFromClass(classes[i]);
if (result != null)
break;
}
}
}
}
if (result != null)
return result;
if (requireSecurityDomain)
checkSecurityDomainRequired();
return null;
}
private static boolean requireSecurityDomain = true;
private static boolean resourceMissing = false;
final static String securityResourceName =
"org.mozilla.javascript.resources.Security";
static {
try {
ResourceBundle rb = ResourceBundle.getBundle(securityResourceName);
String s = rb.getString("security.requireSecurityDomain");
requireSecurityDomain = s.equals("true");
} catch (java.util.MissingResourceException mre) {
requireSecurityDomain = true;
resourceMissing = true;
} catch (SecurityException se) {
requireSecurityDomain = true;
}
}
final public static void checkSecurityDomainRequired() {
if (requireSecurityDomain) {
String msg = "Required security context not found";
if (resourceMissing) {
msg += ". Didn't find properties file at " +
securityResourceName;
}
throw new SecurityException(msg);
}
}
public boolean isGeneratingDebugChanged() {
return generatingDebugChanged;
}
/**
* Add a name to the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to add to the list
*/
public void addActivationName(String name) {
if (activationNames == null)
activationNames = new Hashtable(5);
activationNames.put(name, name);
}
/**
* Check whether the name is in the list of names of objects
* forcing the creation of activation objects.
*
* @param name the name of the object to test
*
* @return true if an function activation object is needed.
*/
public boolean isActivationNeeded(String name) {
if ("arguments".equals(name))
return true;
return activationNames != null && activationNames.containsKey(name);
}
/**
* Remove a name from the list of names forcing the creation of real
* activation objects for functions.
*
* @param name the name of the object to remove from the list
*/
public void removeActivationName(String name) {
if (activationNames != null)
activationNames.remove(name);
}
// Rudimentary support for Design-by-Contract
static void codeBug() {
throw new RuntimeException("FAILED ASSERTION");
}
static final boolean check = true;
static final boolean useJSObject = false;
/**
* The activation of the currently executing function or script.
*/
NativeCall currentActivation;
// for Objects, Arrays to tag themselves as being printed out,
// so they don't print themselves out recursively.
Hashtable iterating;
Object interpreterSecurityDomain;
int version;
int errorCount;
static boolean isCachingEnabled = true;
private SecuritySupport securitySupport;
private ErrorReporter errorReporter;
private Thread currentThread;
private static Hashtable threadContexts = new Hashtable(11);
private RegExpProxy regExpProxy;
private Locale locale;
private boolean generatingDebug;
private boolean generatingDebugChanged;
private boolean generatingSource=true;
private boolean compileFunctionsWithDynamicScopeFlag;
private int optimizationLevel;
WrapHandler wrapHandler;
Debugger debugger;
DebuggableEngine debuggableEngine;
boolean inLineStepMode;
java.util.Stack frameStack;
private int enterCount;
private Object[] listeners;
private Hashtable hashtable;
/**
* This is the list of names of objects forcing the creation of
* function activation records.
*/
private Hashtable activationNames;
// Private lock for static fields to avoid a possibility of denial
// of service via synchronized (Context.class) { while (true) {} }
private static final Object staticDataLock = new Object();
private static Object[] contextListeners;
// For the interpreter to indicate line/source for error reports.
int interpreterLine;
String interpreterSourceFile;
// For instruction counting (interpreter only)
int instructionCount;
int instructionThreshold;
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
7278dc9a39a6b14d754107fda2cb80030c32c4cf | 296fa935b0678fd04406ed44b2a545af53535ec9 | /src/DominioDoProblema/Lance.java | 1194e7a651b446757bad4e08a93df6afd3a3670f | [] | no_license | Cleberton-Oliveira/SHISIMA | 551f1b8ab4ebab0df9b4ea195b9b7095f1bfe8f7 | 982bbc1a254324f723277e5b7525b36ca474f0ec | refs/heads/master | 2023-01-29T19:46:08.913942 | 2020-12-14T00:03:55 | 2020-12-14T00:03:55 | 296,119,870 | 0 | 0 | null | 2020-12-14T00:03:56 | 2020-09-16T18:47:28 | Java | UTF-8 | Java | false | false | 892 | java | package DominioDoProblema;
import br.ufsc.inf.leobr.cliente.Jogada;
public class Lance implements Jogada {
private static final long serialVersionUID = 1L;
protected int linhaOrigem;
protected int linhaDestino;
protected int colunaOrigem;
protected int colunaDestino;
public Lance() {
}
public void definirLinhaOrigem(int valor) {
this.linhaOrigem = valor;
}
public void definirLinhaDestino(int valor) {
this.linhaDestino = valor;
}
public void definirColunaOrigem(int valor) {
this.colunaOrigem = valor;
}
public void definirColunaDestino(int valor) {
this.colunaDestino = valor;
}
public int obterLinhaOrigem() {
return this.linhaOrigem;
}
public int obterColunhaOrigem() {
return this.colunaOrigem;
}
public int obterLinhaDestino() {
return this.linhaDestino;
}
public int obterColunaDestino() {
return this.colunaDestino;
}
}
| [
"camposmrc01@gmail.com"
] | camposmrc01@gmail.com |
d5e082fdf1dac8aa48d592569cebdf8d004e9de1 | 703c0f9cc62bf55a4155818d5a46e3a68afb0b10 | /FirstCodeAndroid/chapter10/ServiceBestPractice/app/src/main/java/com/isure/servicebestpractice/DownloadService.java | 7328ddd79dc28577808c39c711591e7ddc14f25b | [] | no_license | aosure1204/MyLearn | 77b4185d7fb9f5e38e8dffc79414724ca7c6686f | 6e491f52e2c70248d9347c17e3939ecc391a6d62 | refs/heads/master | 2021-07-17T04:28:57.720307 | 2020-05-30T02:30:55 | 2020-05-30T02:30:55 | 162,260,352 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package com.isure.servicebestpractice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class DownloadService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
private DownloadTask mTask;
public DownloadService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder{
public void startDownload(String url){
mTask = new DownloadTask(DownloadService.this);
mTask.execute(url);
}
public void pauseDownload(){
}
public void cancelDownload(){
}
}
}
| [
"1026526473@qq.com"
] | 1026526473@qq.com |
67dcc11c55ffa49e83a59c936c118e6350e4e8ff | 218376ec828a6952fbb1d985a2b79abf388ec1c2 | /src/common/java/Automation_Common/DriverContext.java | b9b0e41373f1d862ae0ad3f245051d0c9d4ed524 | [] | no_license | DreamNk/Testauto | f3017f653b13ff6fcc8ec1cbc89cec120a80409e | 0ef9b8927d27d3aaf3fa589d4a38e68612f22ecb | refs/heads/master | 2022-09-16T16:19:15.091928 | 2020-04-27T15:46:28 | 2020-04-27T15:46:28 | 227,049,053 | 0 | 0 | null | 2022-09-01T23:17:23 | 2019-12-10T06:50:48 | HTML | UTF-8 | Java | false | false | 2,217 | java | package test.Automation_Common;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Capabilities;
public class DriverContext {
public static WebDriver Driver;
public static Capabilities Capabilities;
@SuppressWarnings("deprecation")
public static void getDriver(String browser) throws Exception {
switch (browser) {
case "Chrome":
Driver = new ChromeDriver();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
break;
case "Firefox":
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setBrowserName(browser);
desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
desiredCapabilities.setCapability("marionette", false);
Driver = new FirefoxDriver(desiredCapabilities);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
break;
case "InternetExplorer":
DesiredCapabilities capabilities2 = new DesiredCapabilities();
capabilities2.setBrowserName(browser);
capabilities2.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities2.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
capabilities2.setVersion("11.765.17134.0");
System.setProperty("webdriver.ie.driver", "D:/Driver/IE/IEDriverServer.exe");
Driver = new InternetExplorerDriver(capabilities2);
Driver.manage().deleteAllCookies();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
break;
default:
throw new Exception("Invalid browser");
}
Capabilities = ((RemoteWebDriver) Driver).getCapabilities();
}
public void back(WebDriver driver) {
driver.navigate().back();
}
public static void refresh(WebDriver driver) {
driver.navigate().refresh();
}
}
| [
"nban@netchexonline.com"
] | nban@netchexonline.com |
842dbc480f593b271f87974369d4211f1503fc2f | 02db4fd8b83846ff9166b8ca950586c4e5eb8d88 | /Concurrency-Project/concurrency/src/main/java/com/donaldy/concurrency/ConcurrencyApplication.java | b4fcbd951ba07679729619b541411800e30cb7a8 | [] | no_license | DonaldY/Java-Practice | d87ae1c2561322386df57c5e10533645f028d1d6 | ba4735cfc84c66722f1860c23a02b5406b437344 | refs/heads/master | 2022-06-24T08:03:33.832581 | 2021-07-27T07:35:49 | 2021-07-27T07:35:49 | 83,669,924 | 2 | 0 | null | 2022-06-21T04:14:05 | 2017-03-02T11:22:32 | Java | UTF-8 | Java | false | false | 1,156 | java | package com.donaldy.concurrency;
import com.donaldy.concurrency.filter.HttpFilter;
import com.donaldy.concurrency.filter.HttpInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@SpringBootApplication
public class ConcurrencyApplication extends WebMvcConfigurationSupport {
public static void main(String[] args) {
SpringApplication.run(ConcurrencyApplication.class, args);
}
@Bean
public FilterRegistrationBean httpFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new HttpFilter());
registrationBean.addUrlPatterns("/threadLocal/*");
return registrationBean;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HttpInterceptor()).addPathPatterns("/**");
}
}
| [
"448641125@qq.com"
] | 448641125@qq.com |
19b71fe901293fb45970adaf820ca9a8ccc52688 | bfa0508e748f1f266a5acbacb68f55264b35ed2c | /inmobiliaria/src/inmo/action/cargar/CargaRegistrarEventosAction.java | 3023fbb54a06db3510b884cad6610a6d0c8d8d2c | [] | no_license | yeisonestiben/inmobiliaria-web | 1b59d730a46d2623991dd797a7f4beaec70a1f8f | 82dec3889e0b08090138e42f3a2c01f50ac596d2 | refs/heads/master | 2021-01-01T18:29:41.411553 | 2011-01-13T13:06:19 | 2011-01-13T13:06:19 | 34,739,750 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 930 | java | package inmo.action.cargar;
import inmo.db.TipoEvento;
import inmo.db.TipoEventoDAO;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class CargaRegistrarEventosAction extends Action{
@SuppressWarnings("unchecked")
public ActionForward execute (ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
TipoEventoDAO tipoEvento = new TipoEventoDAO();
ArrayList<TipoEvento> arrayTipoEvento;
arrayTipoEvento = (ArrayList<TipoEvento>) tipoEvento.findAll();
request.setAttribute("arrayTipoEvento",arrayTipoEvento);
return mapping.findForward("registrarEvento");
}
}
| [
"nicopozo@6a927537-1675-0bca-4a87-7d446362da1b"
] | nicopozo@6a927537-1675-0bca-4a87-7d446362da1b |
2f9e94a5cd3217cfa590c35e9afe2aa887fd5258 | 42cc77c5810366fa817ac80417597a5589ab43b0 | /src/main/java/com/personalproject/coronavirustracker/CoronavirusTrackerApplication.java | f5fe66f6c136cdaf6130eeb6ece619e7e1c09d1c | [] | no_license | akhilsuryadevara/coronavirus-tracker | 5501a4bb26ea68cbd9889caf7dd0ca90438d128e | 2b54aaf5776610f97125f1a32355711ba3420a09 | refs/heads/master | 2021-02-20T03:53:10.769651 | 2020-03-06T04:30:05 | 2020-03-06T04:30:05 | 245,326,555 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 441 | java | package com.personalproject.coronavirustracker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class CoronavirusTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(CoronavirusTrackerApplication.class, args);
}
}
| [
"Akhil.Suryadevara@searshc.com"
] | Akhil.Suryadevara@searshc.com |
2cf23d9a845f286f97a807142822f6352dff08cb | e003a721e8246fd3cb85750ced1a06a05df4cae5 | /slather/sim/Pherome.java | 26428e232ddd356a2bc0d42f5b45eb7e8944cb2a | [] | no_license | julianedwards/comsw4444proj2 | 09f669f933937619c3e84a7a1be5ce3c8c30b3ee | a558d0424d1e1edbb535a78e4f40d4a0b2076a4d | refs/heads/master | 2021-01-18T12:48:47.441642 | 2016-10-21T00:42:00 | 2016-10-21T00:42:00 | 68,602,964 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 484 | java | package slather.sim;
public class Pherome extends GridObject{
public final int max_duration;
private int duration = 0;
public Pherome(Point position, int player, int max_duration) {
super(position, player);
this.max_duration = max_duration;
}
public double distance(GridObject other) {
return super.distance(other);
}
protected boolean step() {
return (++duration > max_duration);
}
protected void refresh() {
duration = 0;
}
}
| [
"jse2122@columbia.edu"
] | jse2122@columbia.edu |
4776ceef6027db164d0ebb0da2c9455b2c0d2fe6 | b6df04dc3ea0644a03744ef661d1a828e6f9735e | /src/main/java/com/hzitshop/util/LayuiEntity.java | f0988106b4fd975ea11aefb7ca13dce26aaf7ba1 | [] | no_license | lvyou12/hzit-newcrm3 | 911a51284cc86fe6cf3bf59e9e2d2a755df2f311 | d0e85d54179b93247432cc5085c3276136d6a2c1 | refs/heads/master | 2021-09-27T04:35:07.819192 | 2018-11-06T05:34:12 | 2018-11-06T05:34:12 | 103,082,512 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 789 | java | package com.hzitshop.util;
import java.util.List;
/**
* layui接收的分页数据格式
* {
code: 0,
msg: "",
count: 1000,
data: []
}
*/
public class LayuiEntity<T> {
private int code;
private String msg;
private long count;
private List<T> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
| [
"3267672731@qq.com"
] | 3267672731@qq.com |
58d1ea9856febf1314e5d99353b76bba8fae4112 | d712481949caf7400062205f96e16d78697e74e5 | /NCWITMOBILEAPP-AppEngine/src/com/ncwitmobileapp/server/MessageLocator.java | f64e29c98b0414d7c20d1d85947608ebd2ba670d | [] | no_license | ncwitmobileapp/Application | 2085ae1e8db68543d13b542916387c710a008504 | c414bb62da4b62b581e783b5e53486a105ab8a7e | refs/heads/master | 2021-01-10T21:19:07.200317 | 2012-10-28T22:15:01 | 2012-10-28T22:15:01 | 3,593,025 | 3 | 10 | null | 2020-10-01T09:11:57 | 2012-03-01T15:17:38 | Java | UTF-8 | Java | false | false | 1,761 | java | /*******************************************************************************
* Copyright 2011 Google Inc. All Rights Reserved.
*
* 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
*
* 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.ncwitmobileapp.server;
import com.google.web.bindery.requestfactory.server.RequestFactoryServlet;
import com.google.web.bindery.requestfactory.shared.Locator;
public class MessageLocator extends Locator<Message, Void> {
@Override
public Message create(Class<? extends Message> clazz) {
return new Message(RequestFactoryServlet.getThreadLocalRequest().getSession().getServletContext());
}
@Override
public Message find(Class<? extends Message> clazz, Void id) {
throw new UnsupportedOperationException();
}
@Override
public Class<Message> getDomainType() {
throw new UnsupportedOperationException();
}
@Override
public Void getId(Message domainObject) {
throw new UnsupportedOperationException();
}
@Override
public Class<Void> getIdType() {
throw new UnsupportedOperationException();
}
@Override
public Object getVersion(Message domainObject) {
throw new UnsupportedOperationException();
}
}
| [
"ncwitmobileapp@gmail.com"
] | ncwitmobileapp@gmail.com |
3812f90e2654d7322d37b6f6a6aa8c4d45687ba4 | 7aa6973eb7c1e54111e786378c73256db6581bc6 | /proxy/src/main/java/net/md_5/bungee/connection/InitialHandler.java | d7c84def681a39a386544e6d80718297ea2e16a7 | [] | no_license | PizzanTrop/AntiBot | bd77ed0844b1d03c8452a2fb50174824a7cf7337 | 5aa18d14aa933018bd0964f16b543e9764696077 | refs/heads/master | 2021-01-01T18:16:30.282479 | 2017-07-25T10:36:14 | 2017-07-25T10:36:14 | 98,295,177 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,372 | java | package net.md_5.bungee.connection;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.crypto.SecretKey;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.BungeeServerInfo;
import net.md_5.bungee.EncryptionUtil;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.Util;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ListenerInfo;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.Connection.Unsafe;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PlayerHandshakeEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.chat.ComponentSerializer;
import net.md_5.bungee.http.HttpClient;
import net.md_5.bungee.jni.cipher.BungeeCipher;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.netty.cipher.CipherDecoder;
import net.md_5.bungee.netty.cipher.CipherEncoder;
import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.Protocol;
import net.md_5.bungee.protocol.ProtocolConstants;
import net.md_5.bungee.protocol.packet.EncryptionRequest;
import net.md_5.bungee.protocol.packet.EncryptionResponse;
import net.md_5.bungee.protocol.packet.Handshake;
import net.md_5.bungee.protocol.packet.Kick;
import net.md_5.bungee.protocol.packet.LegacyHandshake;
import net.md_5.bungee.protocol.packet.LegacyPing;
import net.md_5.bungee.protocol.packet.LoginRequest;
import net.md_5.bungee.protocol.packet.LoginSuccess;
import net.md_5.bungee.protocol.packet.PingPacket;
import net.md_5.bungee.protocol.packet.PluginMessage;
import net.md_5.bungee.protocol.packet.StatusRequest;
import net.md_5.bungee.protocol.packet.StatusResponse;
import net.md_5.bungee.util.BoundedArrayList;
import ru.leymooo.gameguard.Config;
import ru.leymooo.gameguard.GGConnector;
import ru.leymooo.gameguard.utils.GeoIpUtils;
import ru.leymooo.gameguard.utils.Proxy;
import ru.leymooo.gameguard.utils.Utils;
@RequiredArgsConstructor
public class InitialHandler extends PacketHandler implements PendingConnection
{
private final BungeeCord bungee;
private ChannelWrapper ch;
@Getter
private final ListenerInfo listener;
@Getter
private Handshake handshake;
@Getter
private LoginRequest loginRequest;
private EncryptionRequest request;
@Getter
private final List<PluginMessage> relayMessages = new BoundedArrayList<>( 128 );
private State thisState = State.HANDSHAKE;
private final Unsafe unsafe = new Unsafe()
{
@Override
public void sendPacket(DefinedPacket packet)
{
ch.write( packet );
}
};
@Getter
private boolean onlineMode = BungeeCord.getInstance().config.isOnlineMode();
@Getter
private InetSocketAddress virtualHost;
private String name;
@Getter
private UUID uniqueId;
@Getter
private UUID offlineId;
@Getter
private LoginResult loginProfile;
@Getter
private boolean legacy;
@Getter
private String extraDataInHandshake = "";
@Override
public boolean shouldHandle(PacketWrapper packet) throws Exception
{
return !ch.isClosing();
}
private enum State
{
HANDSHAKE, STATUS, PING, USERNAME, ENCRYPT, FINISHED;
}
@Override
public void connected(ChannelWrapper channel) throws Exception
{
this.ch = channel;
}
@Override
public void exception(Throwable t) throws Exception
{
disconnect( ChatColor.RED + Util.exception( t ) );
}
@Override
public void handle(PluginMessage pluginMessage) throws Exception
{
// TODO: Unregister?
if ( PluginMessage.SHOULD_RELAY.apply( pluginMessage ) )
{
relayMessages.add( pluginMessage );
}
}
@Override
public void handle(LegacyHandshake legacyHandshake) throws Exception
{
this.legacy = true;
ch.close( bungee.getTranslation( "outdated_client" ) );
}
@Override
public void handle(LegacyPing ping) throws Exception
{
this.legacy = true;
final boolean v1_5 = ping.isV1_5();
ServerPing legacy = new ServerPing( new ServerPing.Protocol( "GG 1.8-1.12 by vk.com Leymooo_s", bungee.getProtocolVersion() ), //GameGuard
new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCountWithGG(), null ), //GameGuard
new TextComponent( TextComponent.fromLegacyText( listener.getMotd() ) ), (Favicon) null );
Callback<ProxyPingEvent> callback = new Callback<ProxyPingEvent>()
{
@Override
public void done(ProxyPingEvent result, Throwable error)
{
if ( ch.isClosed() )
{
return;
}
ServerPing legacy = result.getResponse();
String kickMessage;
if ( v1_5 )
{
kickMessage = ChatColor.DARK_BLUE
+ "\00" + 127
+ '\00' + legacy.getVersion().getName()
+ '\00' + getFirstLine( legacy.getDescription() )
+ '\00' + legacy.getPlayers().getOnline()
+ '\00' + legacy.getPlayers().getMax();
} else
{
// Clients <= 1.3 don't support colored motds because the color char is used as delimiter
kickMessage = ChatColor.stripColor( getFirstLine( legacy.getDescription() ) )
+ '\u00a7' + legacy.getPlayers().getOnline()
+ '\u00a7' + legacy.getPlayers().getMax();
}
ch.getHandle().writeAndFlush( kickMessage );
ch.close();
}
};
bungee.getPluginManager().callEvent( new ProxyPingEvent( this, legacy, callback ) );
}
private static String getFirstLine(String str)
{
int pos = str.indexOf( '\n' );
return pos == -1 ? str : str.substring( 0, pos );
}
@Override
public void handle(StatusRequest statusRequest) throws Exception
{
Preconditions.checkState( thisState == State.STATUS, "Not expecting STATUS" );
ServerInfo forced = AbstractReconnectHandler.getForcedHost( this );
final String motd = ( forced != null ) ? forced.getMotd() : listener.getMotd();
Callback<ServerPing> pingBack = new Callback<ServerPing>()
{
@Override
public void done(ServerPing result, Throwable error)
{
if ( error != null )
{
result = new ServerPing();
result.setDescription( bungee.getTranslation( "ping_cannot_connect" ) );
bungee.getLogger().log( Level.WARNING, "Error pinging remote server", error );
}
Callback<ProxyPingEvent> callback = new Callback<ProxyPingEvent>()
{
@Override
public void done(ProxyPingEvent pingResult, Throwable error)
{
Gson gson = BungeeCord.getInstance().gson;
unsafe.sendPacket( new StatusResponse( gson.toJson( pingResult.getResponse() ) ) );
}
};
bungee.getPluginManager().callEvent( new ProxyPingEvent( InitialHandler.this, result, callback ) );
}
};
if ( forced != null && listener.isPingPassthrough() )
{
( (BungeeServerInfo) forced ).ping( pingBack, handshake.getProtocolVersion() );
} else
{
int protocol = ( ProtocolConstants.SUPPORTED_VERSION_IDS.contains( handshake.getProtocolVersion() ) ) ? handshake.getProtocolVersion() : bungee.getProtocolVersion();
pingBack.done( new ServerPing(
new ServerPing.Protocol( "GG 1.8-1.12 by vk.com Leymooo_s", protocol ), //GameGuard
new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCountWithGG(), null ), //GameGuard
motd, BungeeCord.getInstance().config.getFaviconObject() ),
null );
}
thisState = State.PING;
}
@Override
public void handle(PingPacket ping) throws Exception
{
Preconditions.checkState( thisState == State.PING, "Not expecting PING" );
unsafe.sendPacket( ping );
disconnect( "" );
}
@Override
public void handle(Handshake handshake) throws Exception
{
Preconditions.checkState( thisState == State.HANDSHAKE, "Not expecting HANDSHAKE" );
this.handshake = handshake;
ch.setVersion( handshake.getProtocolVersion() );
// Starting with FML 1.8, a "\0FML\0" token is appended to the handshake. This interferes
// with Bungee's IP forwarding, so we detect it, and remove it from the host string, for now.
// We know FML appends \00FML\00. However, we need to also consider that other systems might
// add their own data to the end of the string. So, we just take everything from the \0 character
// and save it for later.
if ( handshake.getHost().contains( "\0" ) )
{
String[] split = handshake.getHost().split( "\0", 2 );
handshake.setHost( split[0] );
extraDataInHandshake = "\0" + split[1];
}
// SRV records can end with a . depending on DNS / client.
if ( handshake.getHost().endsWith( "." ) )
{
handshake.setHost( handshake.getHost().substring( 0, handshake.getHost().length() - 1 ) );
}
this.virtualHost = InetSocketAddress.createUnresolved( handshake.getHost(), handshake.getPort() );
bungee.getPluginManager().callEvent( new PlayerHandshakeEvent( InitialHandler.this, handshake ) );
//GameGuard Я тут гдето убрал строку которая выводить InitialHandler has connected
switch ( handshake.getRequestedProtocol() )
{
case 1:
// Ping
thisState = State.STATUS;
ch.setProtocol( Protocol.STATUS );
break;
case 2:
// Login
thisState = State.USERNAME;
ch.setProtocol( Protocol.LOGIN );
if ( !ProtocolConstants.SUPPORTED_VERSION_IDS.contains( handshake.getProtocolVersion() ) )
{
if ( handshake.getProtocolVersion() > bungee.getProtocolVersion() )
{
disconnect( bungee.getTranslation( "outdated_server" ) );
} else
{
disconnect( bungee.getTranslation( "outdated_client" ) );
}
return;
}
//gameguard start
if ( Utils.isManyChecks( getAddress().getAddress().getHostAddress(), false ) )
{
disconnect( Config.getConfig().getErrorManyChecks() );
return;
}
//gameguard end
if ( bungee.getConnectionThrottle() != null && bungee.getConnectionThrottle().throttle( getAddress().getAddress() ) )
{
disconnect( bungee.getTranslation( "join_throttle_kick", TimeUnit.MILLISECONDS.toSeconds( bungee.getConfig().getThrottle() ) ) );
}
break;
default:
throw new IllegalArgumentException( "Cannot request protocol " + handshake.getRequestedProtocol() );
}
}
@Override
public void handle(LoginRequest loginRequest) throws Exception
{
Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" );
this.loginRequest = loginRequest;
if ( getName().contains( "." ) )
{
disconnect( bungee.getTranslation( "name_invalid" ) );
return;
}
if ( getName().length() > 16 )
{
disconnect( bungee.getTranslation( "name_too_long" ) );
return;
}
//gameguard start
Config config = Config.getConfig();
GeoIpUtils geo = config.getGeoUtils();
InetAddress address = getAddress().getAddress();
boolean proxy = config.getProxy().isProxy( address.getHostAddress() );
if ( ( config.isUnderAttack() && config.isForceKick() && config.needCheck( getName(), address.getHostAddress() ) ) )
{
if ( !geo.isAllowed( geo.getCountryCode( address.getHostAddress() ), false ) || proxy )
{
disconnect( proxy ? config.getErrorProxy() : config.getErrorConutry() );
return;
}
}
//gameguard end
int limit = BungeeCord.getInstance().config.getPlayerLimit();
if ( limit > 0 && bungee.getOnlineCountWithGG() > limit )//GameGuard
{
disconnect( bungee.getTranslation( "proxy_full" ) );
return;
}
// If offline mode and they are already on, don't allow connect
// We can just check by UUID here as names are based on UUID
if ( !isOnlineMode() && bungee.getPlayer( getUniqueId() ) != null )
{
disconnect( bungee.getTranslation( "already_connected_proxy" ) );
return;
}
Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>()
{
@Override
public void done(PreLoginEvent result, Throwable error)
{
if ( result.isCancelled() )
{
disconnect( result.getCancelReasonComponents() );
return;
}
if ( ch.isClosed() )
{
return;
}
if ( onlineMode )
{
unsafe().sendPacket( request = EncryptionUtil.encryptRequest() );
} else
{
finish();
}
thisState = State.ENCRYPT;
}
};
// fire pre login event
bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) );
}
@Override
public void handle(final EncryptionResponse encryptResponse) throws Exception
{
Preconditions.checkState( thisState == State.ENCRYPT, "Not expecting ENCRYPT" );
SecretKey sharedKey = EncryptionUtil.getSecret( encryptResponse, request );
BungeeCipher decrypt = EncryptionUtil.getCipher( false, sharedKey );
ch.addBefore( PipelineUtils.FRAME_DECODER, PipelineUtils.DECRYPT_HANDLER, new CipherDecoder( decrypt ) );
BungeeCipher encrypt = EncryptionUtil.getCipher( true, sharedKey );
ch.addBefore( PipelineUtils.FRAME_PREPENDER, PipelineUtils.ENCRYPT_HANDLER, new CipherEncoder( encrypt ) );
String encName = URLEncoder.encode( InitialHandler.this.getName(), "UTF-8" );
MessageDigest sha = MessageDigest.getInstance( "SHA-1" );
for ( byte[] bit : new byte[][]
{
request.getServerId().getBytes( "ISO_8859_1" ), sharedKey.getEncoded(), EncryptionUtil.keys.getPublic().getEncoded()
} )
{
sha.update( bit );
}
String encodedHash = URLEncoder.encode( new BigInteger( sha.digest() ).toString( 16 ), "UTF-8" );
String preventProxy = ( ( BungeeCord.getInstance().config.isPreventProxyConnections() ) ? "&ip=" + URLEncoder.encode( getAddress().getAddress().getHostAddress(), "UTF-8" ) : "" );
String authURL = "https://sessionserver.mojang.com/session/minecraft/hasJoined?username=" + encName + "&serverId=" + encodedHash + preventProxy;
Callback<String> handler = new Callback<String>()
{
@Override
public void done(String result, Throwable error)
{
if ( error == null )
{
LoginResult obj = BungeeCord.getInstance().gson.fromJson( result, LoginResult.class );
if ( obj != null && obj.getId() != null )
{
loginProfile = obj;
name = obj.getName();
uniqueId = Util.getUUID( obj.getId() );
finish();
return;
}
disconnect( bungee.getTranslation( "offline_mode_player" ) );
} else
{
disconnect( bungee.getTranslation( "mojang_fail" ) );
bungee.getLogger().log( Level.SEVERE, "Error authenticating " + getName() + " with minecraft.net", error );
}
}
};
HttpClient.get( authURL, ch.getHandle().eventLoop(), handler );
}
private void finish()
{
if ( isOnlineMode() )
{
// Check for multiple connections
// We have to check for the old name first
ProxiedPlayer oldName = bungee.getPlayer( getName() );
if ( oldName != null )
{
// TODO See #1218
oldName.disconnect( bungee.getTranslation( "already_connected_proxy" ) );
}
// And then also for their old UUID
ProxiedPlayer oldID = bungee.getPlayer( getUniqueId() );
if ( oldID != null )
{
// TODO See #1218
oldID.disconnect( bungee.getTranslation( "already_connected_proxy" ) );
}
} else
{
// In offline mode the existing user stays and we kick the new one
ProxiedPlayer oldName = bungee.getPlayer( getName() );
if ( oldName != null )
{
// TODO See #1218
disconnect( bungee.getTranslation( "already_connected_proxy" ) );
return;
}
}
offlineId = java.util.UUID.nameUUIDFromBytes( ( "OfflinePlayer:" + getName() ).getBytes( Charsets.UTF_8 ) );
if ( uniqueId == null )
{
uniqueId = offlineId;
}
Callback<LoginEvent> complete = new Callback<LoginEvent>()
{
@Override
public void done(LoginEvent result, Throwable error)
{
if ( result.isCancelled() )
{
disconnect( result.getCancelReasonComponents() );
return;
}
if ( ch.isClosed() )
{
return;
}
ch.getHandle().eventLoop().execute( new Runnable()
{
@Override
public void run()
{
if ( !ch.isClosing() )
{
bungee.getLogger().log( Level.INFO, "{0} has connected", InitialHandler.this ); //GameGuard
UserConnection userCon = new UserConnection( bungee, ch, getName(), InitialHandler.this );
userCon.setCompressionThreshold( BungeeCord.getInstance().config.getCompressionThreshold() );
userCon.init();
unsafe.sendPacket( new LoginSuccess( getUniqueId().toString(), getName() ) ); // With dashes in between
ch.setProtocol( Protocol.GAME );
if ( Config.getConfig().needCheck( getName(), getAddress().getAddress().getHostAddress() ) ) //GameGuard
{
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new GGConnector( userCon ) ); //GameGuard
} else
{
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new UpstreamBridge( bungee, userCon ) ); //GameGuard
bungee.getPluginManager().callEvent( new PostLoginEvent( userCon ) ); //GameGuard
ServerInfo server;
if ( bungee.getReconnectHandler() != null )
{
server = bungee.getReconnectHandler().getServer( userCon );
} else
{
server = AbstractReconnectHandler.getForcedHost( InitialHandler.this );
}
if ( server == null )
{
server = bungee.getServerInfo( listener.getDefaultServer() );
}
userCon.connect( server, null, true );
}
thisState = State.FINISHED;
}
}
} );
}
};
// fire login event
bungee.getPluginManager().callEvent( new LoginEvent( InitialHandler.this, complete ) );
}
@Override
public void disconnect(String reason)
{
disconnect( TextComponent.fromLegacyText( reason ) );
}
@Override
public void disconnect(final BaseComponent... reason)
{
if ( thisState != State.STATUS && thisState != State.PING )
{
ch.delayedClose( new Kick( ComponentSerializer.toString( reason ) ) );
} else
{
ch.close();
}
}
@Override
public void disconnect(BaseComponent reason)
{
disconnect( new BaseComponent[]
{
reason
} );
}
@Override
public String getName()
{
return ( name != null ) ? name : ( loginRequest == null ) ? null : loginRequest.getData();
}
@Override
public int getVersion()
{
return ( handshake == null ) ? -1 : handshake.getProtocolVersion();
}
@Override
public InetSocketAddress getAddress()
{
return ch.getRemoteAddress();
}
@Override
public Unsafe unsafe()
{
return unsafe;
}
@Override
public void setOnlineMode(boolean onlineMode)
{
Preconditions.checkState( thisState == State.USERNAME, "Can only set online mode status whilst state is username" );
this.onlineMode = onlineMode;
}
@Override
public void setUniqueId(UUID uuid)
{
Preconditions.checkState( thisState == State.USERNAME, "Can only set uuid while state is username" );
Preconditions.checkState( !onlineMode, "Can only set uuid when online mode is false" );
this.uniqueId = uuid;
}
@Override
public String getUUID()
{
return uniqueId.toString().replaceAll( "-", "" );
}
@Override
public String toString()
{
return "[" + ( ( getName() != null ) ? getName() : getAddress() ) + "] <-> InitialHandler";
}
@Override
public boolean isConnected()
{
return !ch.isClosed();
}
}
| [
"den213den@yandex.ru"
] | den213den@yandex.ru |
0cdbeb2f2c085fb10badc574941da0d18c34a2a1 | ec88df0e676700b5d2a630076937e43a81c658dc | /src/main/java/com/mavennet/album/auth/jwt/JwtAuthenticationEntryPoint.java | e10267f0af1597b44446d4119c148b49d9044fa8 | [] | no_license | k17l/album-app-backend | d166de3efdbf8da70f01118dd39310b3da94757f | acbffe2b907fb2a77b99989750d9597ffa5bb5f9 | refs/heads/master | 2022-07-02T07:52:15.439311 | 2019-09-25T15:32:21 | 2019-09-25T15:32:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package com.mavennet.album.auth.jwt;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized Access, Please provide JWT to access this resource");
}
} | [
"kalaiselvan@outlook.com"
] | kalaiselvan@outlook.com |
46b7e6db5f50899689deeeb5ad38967fb64cb552 | 7adec7df47f805229a0facdff9f3d286d033d29e | /archetype/jsf-jpa-rs-common/target/classes/archetype-resources/src/main/java/api/BookmarkAPI.java | a5ee152b11b1c1bf9384746796a3e07b91505d2b | [] | no_license | CEAMSO/tekoporu-framework | 9e661f2e1b81d8a5f8f4e44d6039a1fb726f6585 | fe14569d037a0d2519ccf8af6ff09825d76d4609 | refs/heads/master | 2016-09-09T20:15:55.601471 | 2014-10-24T16:02:35 | 2014-10-24T16:02:35 | 33,945,657 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,206 | java | package ${package}.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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 ${package}.domain.Bookmark;
/**
* Interfaz de servicios para Bookmark
*
* @author desa2
*
*/
@Path("/bookmark")
public interface BookmarkAPI {
/**
* Obtiene una lista de Bookmarks paginada, ordenada y filtrada
*
* @param page
* Página
* @param limit
* Cantidad por página
* @param sortField
* Campo de ordenamiento
* @param sortOrder
* Tipo de ordenamiento (ASCENDING, DESCENDING)
* @param bookmark
* Bookmark con datos de filtrado
* @return
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getBookmarks(@QueryParam("page") int page,
@QueryParam("limit") int limit,
@QueryParam("sortField") String sortField,
@QueryParam("sortOrder") String sortOrder,
@QueryParam("filtros") Bookmark bookmark);
/**
* Recupera un bookmark por su id
*
* @param id
* id del bookmark
* @return
*/
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getBookmark(@PathParam("id") Long id);
/**
* Elimina un Trámite
*
* @param id
* @return
*/
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteBookmark(@PathParam("id") Long id);
/**
* Crea un Trámite
*
* @param bookmark
* Bookmark a ser creado
* @return
*/
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createBookmark(Bookmark bookmark);
/**
* Actualiza un bookmark
*
* @param id
* id del bookmark a ser actualizado
* @param bookmark
* Bookmark a ser actualizado
* @return
*/
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateBookmark(@PathParam("id") Long id, Bookmark bookmark);
}
| [
"vereojeda@gmail.com"
] | vereojeda@gmail.com |
bf0efd90b171a7de8daf2d975181d6a192efb38b | f04370cfde73b0a2579f893fc32c8a1c8b62a8f2 | /estructuras/src/jerarquicas/dinamicas/NodoArbolBin.java | 38ddd8f87faf0e1b47dc814b8720303abd846a48 | [] | no_license | fabian-sepulveda-S/estructuras | c9877f44ace88c758c09b46f139f87d13bdca98e | fe466bf2cee68d63fafb5211869588062701743b | refs/heads/main | 2023-04-10T10:21:37.686549 | 2021-04-28T01:10:18 | 2021-04-28T01:10:18 | 360,291,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 682 | java | package jerarquicas.dinamicas;
public class NodoArbolBin {
private Object elem;
private NodoArbolBin izquierdo;
private NodoArbolBin derecho;
public NodoArbolBin(Object elem) {
this.elem = elem;
izquierdo = null;
derecho = null;
}
public Object getElem() {
return elem;
}
public NodoArbolBin getIzquierdo() {
return izquierdo;
}
public NodoArbolBin getDerecho() {
return derecho;
}
public void setElem(Object elem) {
this.elem = elem;
}
public void setIzquierdo(NodoArbolBin izquierdo) {
this.izquierdo = izquierdo;
}
public void setDerecho(NodoArbolBin derecho) {
this.derecho = derecho;
}
}
| [
"fabian@DESKTOP-VHARO06"
] | fabian@DESKTOP-VHARO06 |
f7bb2528ddaf4f338a296ab50faa1a328520b72e | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project92/src/test/java/org/gradle/test/performance92_2/Test92_188.java | a084101b8cb19bdb42c739856ff9896c39176b82 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 292 | java | package org.gradle.test.performance92_2;
import static org.junit.Assert.*;
public class Test92_188 {
private final Production92_188 production = new Production92_188("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
fb3c8b3d60da4fd671d73817c167524779fe6ca9 | ef8c8fb8b0feec228bdbe0a92820e6013aaf085a | /src/main/java/com/mawujun/convert/package-info.java | 6f85abd84196236cfdbede954417e79a4b573773 | [] | no_license | mawujun1234/leon-tools-bak | f51436aba08b4f17347e01a9831a2177f5af41bb | e26e57e26dce42a504f6f994ef832dbcd7bdae5d | refs/heads/main | 2023-05-07T12:58:57.902824 | 2021-05-31T12:48:43 | 2021-05-31T12:48:43 | 372,504,466 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 199 | java | /**
* 万能类型转换器以及各种类型转换的实现类,其中Convert为转换器入口,提供各种toXXX方法和convert方法
*
* @author mawujun
*
*/
package com.mawujun.convert; | [
"mawujun1234@163.com"
] | mawujun1234@163.com |
1cffd43e91a0c0f59b2feb8eead16dc76cd6b054 | 8eb029197157e860229b7dfe59c11e07155b8cdc | /lab2/lab/src/main/java/com/ulasevich/scooters/Service/ScooterService.java | a3b6eb1d5f148358d8991ac401085a5d6475422d | [] | no_license | YuraUlasevich/java-lab | 1561fa93508c222b8f70c41245c01a26dbd2ebe3 | ca9d50a54305159b5c9c981b901079c357250de7 | refs/heads/master | 2023-02-09T18:54:03.013809 | 2020-12-28T01:26:52 | 2020-12-28T01:26:52 | 302,044,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 773 | java | package com.ulasevich.scooters.Service;
import com.ulasevich.scooters.domain.Role;
import com.ulasevich.scooters.domain.Scooters;
import com.ulasevich.scooters.domain.User;
import com.ulasevich.scooters.repository.ScootersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class ScooterService {
@Autowired
ScootersRepository scootersRepository;
public void saveScooter(String location, Integer charge_level, Scooters scooter) {
scooter.setLocation(location);
scooter.setCharge_level(charge_level);
scootersRepository.save(scooter);
}
}
| [
"y.ulasevich@andersenlab.com"
] | y.ulasevich@andersenlab.com |
de96e4ab398fed26abcb773e7497b9d5f9b3c459 | b91b89a107cd70018a31f8ff721d25d98dcf2b63 | /design-mode/src/main/java/a3factorymethod/FileLoggerFactory.java | 858d0754196f585bb54b4abfaab7f0cb2f3456f0 | [] | no_license | zhpliu29/java-base-test | 6ce36cb08cf04d81254c5ceff154cc05c962e7b0 | 00832ed40006a17dace34929e26c0d766fc6edef | refs/heads/master | 2021-07-09T01:33:22.390042 | 2019-08-14T15:19:48 | 2019-08-14T15:19:48 | 201,078,561 | 0 | 0 | null | 2020-10-13T15:20:09 | 2019-08-07T15:35:33 | Java | UTF-8 | Java | false | false | 241 | java | package a3factorymethod;
public class FileLoggerFactory implements LoggerFactory{
public Logger createLogger() {
//连接数据库
//..
Logger logger=new FileLogger();
//..
return logger;
}
}
| [
"liuzhongpeng@example.com"
] | liuzhongpeng@example.com |
c30a237b8bf1f35d55d468b8aaec5ad698ffac29 | 12fe6dad3e0cbc33929459658bfcd53a4a12e239 | /src/MainPanel.java | 3f4b94157502029295e0d6e0c5d082841c3c0f7f | [] | no_license | vera0302/GameOfLife | b9a9371acb7e70e3e385f94256bc84fd1a7a2a80 | 7264787b11f83118c7f20f7860a1b10a3aebdd33 | refs/heads/master | 2020-09-23T21:15:44.059953 | 2016-11-11T21:17:41 | 2016-11-11T21:17:41 | 73,511,664 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,601 | java | import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MainPanel extends JPanel {
// Current configuration
private Cell[][] _cells;
// Backup configuration
private Cell[][] _backupCells;
private int _size = 0;
private int _maxCount = 10000;
public int _r = 1000;
private boolean _running = false;
public int getCellsSize() {
return _size;
}
public void setCells(Cell[][] cells) {
_cells = cells;
}
public Cell[][] getCells() {
return _cells;
}
private int convertToInt(int x)
{
// Second change: I removed some codes from here, which are time-consuming.
// Since the defined parameter is already an int type, there's not need to convert to int repeatly.
// We should just simply return the value, that's what we expect.
// In this case, I keep this method exist so as to avoid other bugs of other functions calling issue.
return x;
}
// Adding this method which can be used in the pinning tests for the original function. Testify if it changes the functionality.
public int intConvert(int x)
{
return convertToInt(x);
}
private int getNumNeighbors(int x, int y) {
int size = _size;
int leftX = (x - 1) % size;
int rightX = (x + 1) % size;
int upY = (y - 1) % size;
int downY = (y + 1) % size;
if (leftX == -1) { leftX = size - 1; }
if (rightX == -1) { rightX = size - 1; }
if (upY == -1) { upY = size - 1; }
if (downY == -1) { downY = size - 1; }
int numNeighbors = 0;
if (_cells[leftX][upY].getAlive()) { numNeighbors++; }
if (_cells[leftX][downY].getAlive()) { numNeighbors++; }
if (_cells[leftX][y].getAlive()) { numNeighbors++; }
if (_cells[rightX][upY].getAlive()) { numNeighbors++; }
if (_cells[rightX][downY].getAlive()) { numNeighbors++; }
if (_cells[rightX][y].getAlive()) { numNeighbors++; }
if (_cells[x][upY].getAlive()) { numNeighbors++; }
if (_cells[x][downY].getAlive()) { numNeighbors++; }
return convertToInt(numNeighbors);
}
private boolean iterateCell(int x, int y) {
boolean toReturn = false;
boolean alive = _cells[x][y].getAlive();
int numNeighbors = getNumNeighbors(x, y);
if (alive) {
if (numNeighbors < 2 || numNeighbors > 3) {
toReturn = false;
} else {
toReturn = true;
}
} else {
if (numNeighbors == 3) {
toReturn = true;
} else {
toReturn = false;
}
}
return toReturn;
}
private void displayIteration(boolean[][] nextIter) {
System.out.println("\tDisplaying...");
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
_cells[j][k].setAlive(nextIter[j][k]);
}
}
setVisible(true);
}
/**
* For each of the cells, calculate what their
* state will be for the next iteration.
*/
private void calculateNextIteration() {
System.out.println("\tCalculating..");
boolean[][] nextIter = new boolean[_size][_size];
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
nextIter[j][k] = iterateCell(j, k);
}
}
displayIteration(nextIter);
}
/**
* Make a copy of the current cells and put
* the copy in the backup cells.
*/
public void backup()
{
// Third change: The original new object was created at each time from the original method.
// Here I changed the method and create the new backupCell with the active cell's getAlive() function.
for (int j = 0; j < _size; j++)
{
for (int k = 0; k < _size; k++)
{
_backupCells[j][k].setAlive(_cells[j][k].getAlive());
}
}
}
// Adding this method which is in the pinning tests for the functionality of the backup method.
public boolean backupTest()
{
for(int i = 0; i < _size; i++)
{
for(int j = 0; j < _size; j++)
{
if(_backupCells[i][j].getAlive() != _cells[i][j].getAlive())
{
return false;
}
}
}
return true;
}
/**
* This is for debug use. It will display
* the state of cells in a convenient format.
* First it will display backup cells and then
* the current cells. Backup cells are what
* you revert to when you press Undo.
*/
public void debugPrint() {
System.out.println("Backup cells");
try {
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
if (_backupCells[j][k].getAlive()) {
System.out.print("X");
} else {
System.out.print(".");
}
}
System.out.println("");
}
System.out.println("Current cells:");
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
if (_cells[j][k].getAlive()) {
System.out.print("X");
} else {
System.out.print(".");
}
}
System.out.println("");
}
} catch (Exception ex) {
System.out.println("Nothin' yet");
}
}
/**
* Convert the Main Panel into a String
* which can be written to a file.
*/
public String toString() {
// Loop through all of the cells, and
// if they are alive, add an "X" to
// the String, if dead, a ".".
String toWrite = "";
for (int j = 0; j < _size; j++) {
for(int k = 0; k < _size; k++) {
if (_cells[j][k].getAlive()) {
toWrite += _cells[j][k].toString();
} else {
toWrite += _cells[j][k].toString();
}
}
toWrite += "\n";
}
return toWrite;
}
/**
* Run one iteration of the Game of Life
*/
public void run() {
backup();
calculateNextIteration();
}
/**
* Run the system continuously.
*/
public void runContinuous()
{
_running = true;
while (_running)
{
// Forth change: I deleted the original loop, which was supposed to change the value of _r and then reseting it to the original value after the loop.
// This function significantly runs a lot CPU time as shown in VisualVM, which is naturally caused.
// However, deleting the unnecessary loop will definitely save much time to take more runnings of the game.
// I don't give pinning tests for this modification as there are neither input nor output values in this function.
System.out.println("Running...");
try
{
Thread.sleep(20);
}
catch (InterruptedException iex) { }
backup();
calculateNextIteration();
}
}
/**
* Stop a continuously running system.
*/
public void stop() {
_running = false;
}
/**
* Convert the array of Cell objects into an
* array of booleans.
*/
public boolean[][] convertToBoolean(Cell[][] cells) {
// 2-D array to return. Remember everything
// is false by default for boolean arrays!
boolean[][] toReturn = new boolean[_size][_size];
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
if (cells[j][k].getAlive()) {
toReturn[j][k] = true;
} else {
// Nothing to do! Already
// set to false by default.
// toReturn[j][k] = false;
}
}
}
return toReturn;
}
/**
* Revert back to the previous iteration,
* which we have saved in _backupCells.
*/
public void undo() {
displayIteration(convertToBoolean(_backupCells));
}
/**
* Loop through the entire array and reset
* each of the Cells in the MainPanel.
*/
public void clear() {
for (int j = 0; j < _size; j++) {
for (int k = 0; k < _size; k++) {
_cells[j][k].reset();
}
}
// Need to call setVisible() since
// we did not do a displayIteration()
// call.
setVisible(true);
}
/**
* Load in a previously saved Game of Life
* configuration.
*/
public void load(ArrayList<String> lines) {
boolean[][] loaded = new boolean[_size][_size];
for (int j = 0; j < _size; j++) {
String l = lines.get(j);
for (int k = 0; k < _size; k++) {
// Reset the "been alive" count
_cells[j][k].resetBeenAlive();
// For each line, get each character.
// If it's a '.', the cell stays
// dead. Otherwise, the cell is alive.
// We could specifically check for
// an 'X' for alive and throw an
// error if we get an unexpected char.
if (l.charAt(k) == '.') {
_cells[j][k].setAlive(false);
loaded[j][k] = false;
} else {
_cells[j][k].setAlive(true);
loaded[j][k] = true;
}
}
}
// Now that we have set the Cells to what
// we expect, display the iteration.
displayIteration(loaded);
// debugPrint();
}
public MainPanel(int size)
{
super();
_size = size;
setLayout(new GridLayout(size, size));
// Final change: I make the backupCell array here with new cells filled-in.
// In this way, we can save the running time from making new cells for each one backup.
_backupCells = new Cell[size][size];
_cells = new Cell[size][size];
for (int j = 0; j < size; j++)
{
for (int k = 0; k < size; k++)
{
// change here for the same reason, too.
_backupCells[j][k] = new Cell();
_cells[j][k] = new Cell();
this.add(_cells[j][k]);
_cells[j][k].setAlive(false);
}
}
}
}
| [
"yiz105@pitt.edu"
] | yiz105@pitt.edu |
66efbde8d173cc5d27c98506322969311ef94ad6 | 0552ba39efd5eb835b1d4070da11836fc0a23914 | /app/src/test/java/ko/sh/com/mini_project_movie/ExampleUnitTest.java | fa17056398896d525d0a62273f1638b150152be9 | [] | no_license | create-ko/MPM | 11d23d4d1f17298b89a026eeab111eb888fe7e13 | f91e72d95be771b0041fd8128669329876a9ccc7 | refs/heads/master | 2020-09-02T17:44:45.030863 | 2017-06-15T05:07:33 | 2017-06-15T05:07:33 | 94,401,719 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 406 | java | package ko.sh.com.mini_project_movie;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"create_ko@naver.com"
] | create_ko@naver.com |
6e2c2338abaffb8a4fa88caeb811513957e6afe3 | 62e334192393326476756dfa89dce9f0f08570d4 | /tk_code/tiku-essay-app/essay-server/src/main/java/com/huatu/tiku/essay/web/controller/api/V2/ApiUserCorrectGoodsControllerV2.java | fc0154f6898727e24e0505f0a08221a59f86df2e | [] | no_license | JellyB/code_back | 4796d5816ba6ff6f3925fded9d75254536a5ddcf | f5cecf3a9efd6851724a1315813337a0741bd89d | refs/heads/master | 2022-07-16T14:19:39.770569 | 2019-11-22T09:22:12 | 2019-11-22T09:22:12 | 223,366,837 | 1 | 2 | null | 2022-06-30T20:21:38 | 2019-11-22T09:15:50 | Java | UTF-8 | Java | false | false | 5,118 | java | package com.huatu.tiku.essay.web.controller.api.V2;
import com.huatu.common.exception.BizException;
import com.huatu.tiku.common.bean.user.UserSession;
import com.huatu.tiku.essay.constant.error.EssayErrors;
import com.huatu.tiku.essay.entity.UpdateCorrectTimesOrderVO;
import com.huatu.tiku.essay.vo.resp.EssayOrderVO;
import com.huatu.tiku.essay.vo.resp.UpdateCorrectTimesByUserVO;
import com.huatu.tiku.essay.service.UserCorrectGoodsService;
import com.huatu.tiku.essay.util.LogPrint;
import com.huatu.tiku.essay.util.PageUtil;
import com.huatu.tiku.springboot.users.support.Token;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@Slf4j
@RequestMapping("api/v2/user")
/**
* 用户&&批改商品关系
*/
public class ApiUserCorrectGoodsControllerV2 {
@Autowired
UserCorrectGoodsService userCorrectGoodsService;
/**
* PHP 购买课程赠送批改次数 或 批改免费(加入白名单)
*/
@LogPrint
@PostMapping(value = "course", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object buyCourse(@RequestBody UpdateCorrectTimesByUserVO vo) {
//userId错误
String userName = vo.getUserName();
Long orderId = vo.getOrderId();
if(null == orderId || orderId <= 0){
//订单ID错误
log.warn("订单ID错误,orderId:{}",orderId);
throw new BizException(EssayErrors.ORDER_ID_ERROR);
}
if(StringUtils.isEmpty(userName)){
//用户名称错误
log.warn("用户名称错误,userName:{}",userName);
throw new BizException(EssayErrors.USER_NAME_ERROR);
}
int userId = userCorrectGoodsService.findIdByName( userName);
if(userId <= 0){
//1. 模拟登录接口,同步用户信息
userCorrectGoodsService.fakeLogin(userName);
//2. 再次查询用户信息(查询成功 or 查询失败(信息同步失败))
userId = userCorrectGoodsService.findIdByName( userName);
//用户id还是错误。再抛出异常
if(userId <= 0){
log.warn("用户id错误,userName:{},userId:{}",userName,userId);
throw new BizException(EssayErrors.USER_ID_ERROR);
}
}
List<UpdateCorrectTimesOrderVO> list = vo.getList();
if(CollectionUtils.isEmpty(list)){
log.warn("课程列表为空,updateVO:{}",vo);
throw new BizException(EssayErrors.COURSE_LIST_NOT_EXIST);
}
for(UpdateCorrectTimesOrderVO updateVO:list){
/** 操作类型 1加批改次数 2 批改免费**/
int saveType = updateVO.getSaveType();
if(saveType == 1){
return userCorrectGoodsService.updateCorrectTimesByUser(updateVO, userId, orderId);
}else if(saveType == 2){
return userCorrectGoodsService.addFreeUserV2(updateVO, userId, orderId);
}else{
log.warn("操作类型异常,saveType:{}",saveType);
throw new BizException(EssayErrors.SAVE_TYPE_ERROR);
}
}
return true;
}
/**
* 订单列表
* 全部:-1, 待付款0,已付款1, 已取消2
* @param userSession
* @param page
* @param pageSize
* @return
*/
@LogPrint
@GetMapping(value="order/list",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public PageUtil<EssayOrderVO> correctGoods(@Token UserSession userSession,
@RequestParam(name = "type", defaultValue = "-1") int type,
@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "pageSize", defaultValue = "20") int pageSize) {
PageRequest pageRequest = new PageRequest(page - 1, pageSize, Sort.Direction.DESC, "id");
return userCorrectGoodsService.orderList(userSession.getId(),type,pageRequest);
}
/**
* 删除订单
* @param userSession
* @return
*/
@LogPrint
@DeleteMapping(value="order/{id}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Map order(@Token UserSession userSession,
@PathVariable long id) {
return userCorrectGoodsService.delOrder(id);
}
/**
* 删除订单
* @param userSession
* @return
*/
@LogPrint
@PutMapping(value="cancel/{id}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Map cancelOrder(@Token UserSession userSession,
@PathVariable long id) {
return userCorrectGoodsService.cancelOrder(id);
}
}
| [
"jelly_b@126.com"
] | jelly_b@126.com |
75d52d60b15729e86aa414c27cdc3578a0e5975f | dd9ff3365441f78f72531a5fc1f4199c20b73096 | /src/main/java/com/jsx/conf/data/DataSourceConfig.java | ee90bebfaa10ab74fb3969e6217898c7902afed2 | [] | no_license | jsx112/springboot-quartz | c044586c50922790cebf34ca4451878f2bbe9046 | 6b7a11a994c9aae0f61d4c37cd77e7fa7c0195f8 | refs/heads/master | 2021-07-06T05:12:34.739690 | 2017-09-25T06:28:48 | 2017-09-25T06:28:48 | 104,697,926 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 703 | java | package com.jsx.conf.data;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 数据源,如果有多个在这里进行读取
* @author jiasx
* @create 2017/9/15 15:33
**/
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return new DruidDataSource();
}
} | [
"jsx7@163.com"
] | jsx7@163.com |
785e24cb21e730bd0e61101ecf0aaba5a5b0fcca | a2a584b003dbe290418ac17273b14ba8ce0749d3 | /lib/src/main/java/com/llew/reflect/FieldUtils.java | 65febc7697e0c7ac0ded4ba4654509d7b2313010 | [
"Apache-2.0"
] | permissive | fanlysir/Reflection | bda02779cbebe1fdfdded2336e254426fc0b485d | fa5ff0773095ede9c39ba65ff7092e08a89c47c7 | refs/heads/master | 2023-03-18T12:58:29.453402 | 2018-01-14T03:20:20 | 2018-01-14T03:20:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,137 | java | package com.llew.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import static com.llew.reflect.ReflectUtils.print;
public class FieldUtils {
private static Map<String, Field> sFieldCache = new HashMap<String, Field>();
private static String getKey(Class<?> cls, String fieldName) {
StringBuilder sb = new StringBuilder();
sb.append(cls.toString()).append("#").append(fieldName);
return sb.toString();
}
private static Field getField(Class<?> cls, String fieldName, final boolean forceAccess) {
Validate.isTrue(cls != null, "The class must not be null");
Validate.isTrue(!ReflectUtils.isEmpty(fieldName), "The field name must not be blank/empty");
String key = getKey(cls, fieldName);
Field cachedField;
synchronized (sFieldCache) {
cachedField = sFieldCache.get(key);
}
if (cachedField != null) {
if (forceAccess && !cachedField.isAccessible()) {
cachedField.setAccessible(true);
}
return cachedField;
}
// check up the superclass hierarchy
for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
try {
final Field field = acls.getDeclaredField(fieldName);
// getDeclaredField checks for non-public scopes as well
// and it returns accurate results
if (!Modifier.isPublic(field.getModifiers())) {
if (forceAccess) {
field.setAccessible(true);
} else {
continue;
}
}
synchronized (sFieldCache) {
sFieldCache.put(key, field);
}
return field;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
// check the public interface case. This must be manually searched for
// incase there is a public supersuperclass field hidden by a private/package
// superclass field.
Field match = null;
for (final Class<?> class1 : ReflectUtils.getAllInterfaces(cls)) {
try {
final Field test = class1.getField(fieldName);
Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s"
+ "; a matching field exists on two or more implemented interfaces.", fieldName, cls);
match = test;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
synchronized (sFieldCache) {
sFieldCache.put(key, match);
}
return match;
}
public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException {
Validate.isTrue(field != null, "The field must not be null");
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
MemberUtils.setAccessibleWorkaround(field);
}
return field.get(target);
}
public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess)
throws IllegalAccessException {
Validate.isTrue(field != null, "The field must not be null");
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
MemberUtils.setAccessibleWorkaround(field);
}
field.set(target, value);
}
public static Object readField(final Field field, final Object target) throws IllegalAccessException {
return readField(field, target, true);
}
public static Field getField(final String cls, final String fieldName) {
try {
return getField(Class.forName(cls), fieldName, true);
} catch (Throwable ignore) {
print(ignore);
}
return null;
}
public static Field getField(final Class<?> cls, final String fieldName) {
return getField(cls, fieldName, true);
}
public static Object readField(final Object target, final String fieldName) throws IllegalAccessException {
Validate.isTrue(target != null, "target object must not be null");
final Class<?> cls = target.getClass();
final Field field = getField(cls, fieldName, true);
Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
// already forced access above, don't repeat it here:
return readField(field, target, false);
}
public static Object readField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
Validate.isTrue(target != null, "target object must not be null");
final Class<?> cls = target.getClass();
final Field field = getField(cls, fieldName, forceAccess);
Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
// already forced access above, don't repeat it here:
return readField(field, target, forceAccess);
}
public static void writeField(final Object target, final String fieldName, final Object value) throws IllegalAccessException {
writeField(target, fieldName, value, true);
}
public static void writeField(final Object target, final String fieldName, final Object value, final boolean forceAccess) throws IllegalAccessException {
Validate.isTrue(target != null, "target object must not be null");
final Class<?> cls = target.getClass();
final Field field = getField(cls, fieldName, true);
Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
// already forced access above, don't repeat it here:
writeField(field, target, value, forceAccess);
}
public static void writeField(final Field field, final Object target, final Object value) throws IllegalAccessException {
writeField(field, target, value, true);
}
public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
Validate.isTrue(field != null, "The field must not be null");
Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName());
return readField(field, (Object) null, forceAccess);
}
public static Object readStaticField(final String cls, final String fieldName) throws IllegalAccessException {
try {
return readStaticField(Class.forName(cls), fieldName);
} catch (Throwable ignored) {
print(ignored);
}
return null;
}
public static Object readStaticField(final Class<?> cls, final String fieldName) throws IllegalAccessException {
final Field field = getField(cls, fieldName, true);
Validate.isTrue(field != null, "Cannot locate field '%s' on %s", fieldName, cls);
// already forced access above, don't repeat it here:
return readStaticField(field, true);
}
public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException {
Validate.isTrue(field != null, "The field must not be null");
Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static", field.getDeclaringClass().getName(),
field.getName());
writeField(field, (Object) null, value, forceAccess);
}
public static void writeStaticField(final String cls, final String fieldName, final Object value) throws IllegalAccessException {
try {
writeStaticField(Class.forName(cls), fieldName, value);
} catch (Throwable ignore) {
ReflectUtils.print(ignore);
}
}
public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value) throws IllegalAccessException {
final Field field = getField(cls, fieldName, true);
Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
// already forced access above, don't repeat it here:
writeStaticField(field, value, true);
}
public static Field getDeclaredField(final String cls, final String fieldName, final boolean forceAccess) {
try {
return getDeclaredField(Class.forName(cls), fieldName, forceAccess);
} catch (Throwable ignore) {
print(ignore);
}
return null;
}
public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
Validate.isTrue(cls != null, "The class must not be null");
Validate.isTrue(!ReflectUtils.isEmpty(fieldName), "The field name must not be blank/empty");
try {
// only consider the specified class by using getDeclaredField()
final Field field = cls.getDeclaredField(fieldName);
if (!MemberUtils.isAccessible(field)) {
if (forceAccess) {
field.setAccessible(true);
} else {
return null;
}
}
return field;
} catch (final NoSuchFieldException e) { // NOPMD
// ignore
}
return null;
}
public static void writeDeclaredField(final Object target, final String fieldName, final Object value) throws IllegalAccessException {
Validate.isTrue(target != null, "target object must not be null");
final Class<?> cls = target.getClass();
final Field field = getDeclaredField(cls, fieldName, true);
Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
// already forced access above, don't repeat it here:
writeField(field, target, value, false);
}
}
| [
"wei.liu@ushow.media"
] | wei.liu@ushow.media |
bf59c4883eb0f2ad09b15bccb1c881317ca0fa9b | 993063847137efbe6feee99047c065adc007ecde | /accessModifier/NewClass.java | 30729400c2d8ad76e60eb7f7d6c6c06e681b3153 | [] | no_license | sebaek/20171122java | 857821803deac3915623ad12e836e98c93c79dc5 | 3cb45dd3b3d613c697d87709357ec32531d5012f | refs/heads/master | 2021-05-06T12:42:28.150926 | 2017-12-08T07:41:47 | 2017-12-08T07:41:47 | 113,126,023 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 123 | java | package accessModifier;
public class NewClass {
private int privateField;
public int publicField;
int defaultField;
}
| [
"302@choongang"
] | 302@choongang |
e2ec33b0ef1e4dfbe7eb5bc9b1edfca30332daf3 | b193fb2c07fb3f37172a5b65a33ac7eb3fd51738 | /app/src/main/java/com/example/user/todoapplication/AddTask.java | f206db325152ffb62ea966781a4ee6cd264fd900 | [] | no_license | alexlindroos/TodoApplication | ddef52ed57e89678bf32fba9c36d1fe867c398e0 | ac78f89ba7bc2857188064b8133573e8aabbc55e | refs/heads/master | 2021-01-17T22:11:51.243141 | 2017-05-16T11:42:13 | 2017-05-16T11:42:13 | 84,115,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,524 | java | package com.example.user.todoapplication;
import android.app.AlarmManager;
import android.app.DialogFragment;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import io.realm.Realm;
import io.realm.RealmResults;
/**
* Created by User on 7.3.2017.
*/
public class AddTask extends FragmentActivity implements TimePickerFragment.OnCompleteListener {
private TextView taskTime;
private EditText taskName;
private EditText taskDescription;
private Button addTask,setTime;
private Realm realm;
private String notifyTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addtask);
//Initializing Realm
Realm.init(this);
realm = Realm.getDefaultInstance();
taskName = (EditText)findViewById(R.id.add_task_name);
taskDescription = (EditText)findViewById(R.id.add_task_description);
addTask = (Button)findViewById(R.id.btn_add);
setTime = (Button)findViewById(R.id.btn_time);
taskTime = (TextView)findViewById(R.id.txt_time);
//AlarmService
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
final PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Set 30second timer for notification just for demo purpose
final android.icu.util.Calendar cal = android.icu.util.Calendar.getInstance();
cal.add(android.icu.util.Calendar.SECOND, 30);
//Add task button onClickListener
addTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("CLICKED");
//Saves data to the Realm
saveDataToDatabase();
//Launch alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
Toast.makeText(AddTask.this, R.string.taskCreated, Toast.LENGTH_SHORT).show();
}
});
//Add time button onClickListener
setTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("CLICKED");
showTimePickerDialog(view);
}
});
}
//Method for saving data in to database
public void saveDataToDatabase() {
final String name = taskName.getText().toString();
final String description = taskDescription.getText().toString();
final String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
final String notify = taskTime.getText().toString();
// If EditTexts are empty make a toast
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(description) || TextUtils.isEmpty(notify)) {
Toast.makeText(AddTask.this, R.string.error_values, Toast.LENGTH_SHORT).show();
}else{
//Get current time
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2:00"));
Date currentLocalTime = cal.getTime();
DateFormat dateFormatter = new SimpleDateFormat("HH:mm");
dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT+2:00"));
final String localTime = dateFormatter.format(currentLocalTime);
//Realm transaction
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// Add a task
TodoItemModel todoItemModel = realm.createObject(TodoItemModel.class);
todoItemModel.setName(name);
todoItemModel.setDescription(description);
todoItemModel.setDate(date);
todoItemModel.setTime(localTime);
todoItemModel.setNotifyTime(notifyTime);
System.out.println("Task added");
//Checking what is in the realm
RealmResults<TodoItemModel> results = realm.where(TodoItemModel.class)
.findAll();
System.out.println(results);
}
});
finish();
}
}
//Method makes a new TimePickerFragment
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
//When TimePicking completed puts time in to textview
public void onComplete(String time) {
notifyTime = time;
taskTime.setText(notifyTime);
}
@Override
protected void onDestroy () {
super.onDestroy();
// Closes Realm connection
realm.close();
}
}
| [
"alex.lindroos@metropolia.fi"
] | alex.lindroos@metropolia.fi |
d8caa0400c4168fc401a4802d75d9850f6ac1eb1 | ea340b8073d6d094b46901b4394e2a5a4ca1d07a | /src/test/java/com/jakubzegar/pracadyplomowaserwer/controller/HeatmapDataControllerTest.java | 0917e3ea66ca59537de09d05b27ba03497b6f818 | [] | no_license | JakubZegar/Web-Analytics-Tool-Serwer | 81de4d522747d5ca40d9aaf1ef36e3a42596dfb8 | d99f31d2a8eef60148772f703cd8259aed450f67 | refs/heads/master | 2023-02-28T08:11:38.105701 | 2021-02-02T12:35:35 | 2021-02-02T12:35:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,766 | java | package com.jakubzegar.pracadyplomowaserwer.controller;
import com.jakubzegar.pracadyplomowaserwer.payload.LoginRequest;
import com.jakubzegar.pracadyplomowaserwer.security.JwtTokenProvider;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class HeatmapDataControllerTest {
private LoginRequest loginRequest = new LoginRequest();
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private MockMvc mockMvc;
@Test
void getHeatmap() throws Exception {
loginRequest.setUsernameOrEmail("Vastar");
loginRequest.setPassword("admin");
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsernameOrEmail(),
loginRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.generateToken(authentication);
assertNotNull(token);
mockMvc.perform(MockMvcRequestBuilders.post("/api/heatmapData/get").header("Authorization", "Bearer " + token)
.content("hgft4jdb6h3hjuemp9a1283jdk342"))
.andExpect(status().isOk());
}
@Test
void createHeatmapData() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/heatmapData/create")
.content("{\"apiKey\":\"hgft4jdb6h3hjuemp9a1283jdk342\",\"coordinateX\":\"802\",\"coordinateY\":\"812\",\"date\":\"04-01-2021\"}")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated());
}
} | [
"jakubzegar3@gmail.com"
] | jakubzegar3@gmail.com |
bc31a46de7b832edb1846fd17272c2f117a1534d | ddba98f91563dcd516e02e6c61485958be326751 | /src/main/java/com/leo/algorithm/easy/array/MagicIndexLcci.java | 56871dfab37e37654cdf2d95833bccc557c39393 | [] | no_license | LIULE8/leecode-store | b2c120f333125641bc9f0d003b522db7ffeb7c3d | 379e5c4feeb80b35cceffd3485a698da568a31bd | refs/heads/master | 2022-01-01T00:39:52.260151 | 2021-11-24T13:59:54 | 2021-11-24T13:59:54 | 227,330,529 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,664 | java | // 魔术索引。 在数组A[0...n-1]中,有所谓的魔术索引,满足条件A[i] = i。给定一个有序整数数组,编写一种方法找出魔术索引,若有的话,在数组A中找
// 出一个魔术索引,如果没有,则返回-1。若有多个魔术索引,返回索引值最小的一个。
//
// 示例1:
//
// 输入:nums = [0, 2, 3, 4, 5]
// 输出:0
// 说明: 0下标的元素为0
//
//
// 示例2:
//
// 输入:nums = [1, 1, 1]
// 输出:1
//
//
// 说明:
//
//
// nums长度在[1, 1000000]之间
// 此题为原书中的 Follow-up,即数组中可能包含重复元素的版本
//
// Related Topics 数组 二分查找
// 面试题 08.03. 魔术索引
package com.leo.algorithm.easy.array;
import com.leo.algorithm.utils.DataBuilder;
import com.leo.algorithm.utils.Printer;
public class MagicIndexLcci {
public static void main(String[] args) {
Printer.printCorrectAnswer(
0, new Solution().findMagicIndex(DataBuilder.buildIntArray("0, 2, 3, 4, 5")));
Printer.printCorrectAnswer(
1, new Solution().findMagicIndex(DataBuilder.buildIntArray("1, 1, 1")));
Printer.printCorrectAnswer(
0, new Solution().findMagicIndex(DataBuilder.buildIntArray("0, 0, 2")));
}
static class Solution {
/**
* 执行用时: 1 ms , 在所有 Java 提交中击败了 46.91% 的用户
*
* <p>内存消耗: 40.3 MB , 在所有 Java 提交中击败了 98.14% 的用户
*
* @param nums
* @return
*/
public int findMagicIndex(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i == nums[i]) return i;
}
return -1;
}
}
}
| [
"scau_lzc@163.com"
] | scau_lzc@163.com |
47c82a786065738eef71c35b6eba067a8958147a | caf8a37bb98e323e58ce91ec4022402cc4f799f8 | /G4G/Tree/SizeTree.java | 34058425c84886a499c69c1cda9aaf34e0e4d9c5 | [] | no_license | Debugger3/Coding | a0e3d326a28349cff64639bdc8d562c3e2da159a | b6dd5d8b7af9432863db42a3c05fe2aa31a2e886 | refs/heads/master | 2021-01-17T12:51:30.265803 | 2016-06-26T17:56:28 | 2016-06-26T17:56:28 | 58,266,385 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 793 | java | /* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Node{
int data;
Node left,right;
Node(int d)
{
data=d;
left=right=null;
}
}
class Solution
{
public static int size(Node root)
{
Node current =root;
if(root==null)
return 0;
return 1+size(root.left)+size(root.right);
}
public static void main(String args[])
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
System.out.println(size(root));
}
}
| [
"aditi.raghuvanshi@iiitb.org"
] | aditi.raghuvanshi@iiitb.org |
8497079538a6bd3778adfa19ff6de12ec0fd9473 | 4f37840cebe7ecc3242b72a968e960009ebc21bb | /app/src/main/java/com/example/quiz/QuizContract.java | 7ef9228f75b69482fb71d232d191f4eeeeada386 | [] | no_license | Salman53/Quiz_App_SQlite | 99874be768d922c870124dd155fb8c1ee65d818a | 53da07a21aea5b5561ef70bf1355880cd0be31d4 | refs/heads/master | 2020-11-25T14:53:25.849636 | 2019-12-18T00:49:10 | 2019-12-18T00:49:10 | 228,727,240 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 913 | java | package com.example.quiz;
import android.provider.BaseColumns;
public final class QuizContract {
private QuizContract()
{
}
public static class CategoriesTable implements BaseColumns{
public static final String TABLE_NAME = "quiz_categories";
public static final String COLUMN_NAME = "name";
}
public static class QuestionsTable implements BaseColumns {
public static final String TABLE_NAME = "quiz_questions";
public static final String COLUMN_QUESTION ="question";
public static final String COLUMN_OPTION1 ="option1";
public static final String COLUMN_OPTION2 ="option2";
public static final String COLUMN_OPTION3 ="option3";
public static final String COLUMN_ANSWER_NR="answer_nr";
public static final String COLUMN_DIFFICULTY="difficulty";
public static final String COLUMN_CATEGORY_ID = "category_id";
}
}
| [
"53404505+Salman53@users.noreply.github.com"
] | 53404505+Salman53@users.noreply.github.com |
968b7da2da7b84e18fba93ff7c938fc62e2f4f4d | 54fab4d1609334577c8a00a503a5ef427f889868 | /design-pattern/src/simply_factory/Client.java | 4f42682e7b86e8b6cda23c4427da4bf6df65c094 | [] | no_license | KimiQianMin/design-pattern | 38795564a05a17ea9d03b57eb60878200d8105a4 | 2c63428999bba06c02d3d91a0a00153fc3369381 | refs/heads/master | 2021-01-04T19:17:02.695222 | 2020-04-16T05:16:49 | 2020-04-16T05:16:49 | 240,725,200 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 473 | java | package simply_factory;
public class Client {
public static void main(String[] args) {
System.out.println("This is simply factory ...");
Mcdonald mcdonald = new Mcdonald();
IFood food = mcdonald.getFood("FrenchFries");
if (food != null) {
food.eat();
}
food = mcdonald.getFood("McChicken");
if (food != null) {
food.eat();
}
food = mcdonald.getFood("ChickenRice");
if (food != null) {
food.eat();
}
}
}
| [
"attpnxg1@GIT51-NB.PSAI.PSA.COM.SG"
] | attpnxg1@GIT51-NB.PSAI.PSA.COM.SG |
33049d876df38b0136a8ea2325eec9d1b263f7a8 | c04f812bea53c3d180baeea583f43176a6565005 | /app/src/main/java/com/yuyh/github/support/RefreshTreeTask.java | c27da5e5450b83393b4b0ba0502b80747f581ed8 | [
"Apache-2.0"
] | permissive | tim0523/GithubClient | 4fd83457be59e9c7124655c115d9dff2c189e2bc | 2ab35289f21f9cb1cb7ee955c9df3c5577d5a139 | refs/heads/master | 2021-05-02T11:37:28.020500 | 2016-11-02T09:41:59 | 2016-11-02T09:41:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,946 | java | package com.yuyh.github.support;
import android.text.TextUtils;
import com.yuyh.github.api.git.CommitInfoClient;
import com.yuyh.github.api.git.GitTreeInfoClient;
import com.yuyh.github.api.git.ReferenceInfoClient;
import com.yuyh.github.api.repo.RepoInfoClient;
import com.yuyh.github.bean.resp.GitCommit;
import com.yuyh.github.bean.resp.GitReference;
import com.yuyh.github.bean.resp.GitTree;
import com.yuyh.github.bean.resp.Repo;
import com.yuyh.github.utils.core.InfoUtils;
import com.yuyh.github.utils.core.RefUtils;
import java.io.IOException;
import rx.Observable;
import rx.Subscriber;
/**
* Task to load the tree for a repository's default branch
*/
public class RefreshTreeTask implements Observable.OnSubscribe<FullTree> {
private static final String TAG = "RefreshTreeTask";
private final Repo repository;
private final GitReference reference;
/**
* Create task to refresh repository's tree
*
* @param repository
* @param reference
*/
public RefreshTreeTask(final Repo repository,
final GitReference reference) {
this.repository = repository;
this.reference = reference;
}
private boolean isValidRef(GitReference ref) {
return ref != null && ref.object != null
&& !TextUtils.isEmpty(ref.object.sha);
}
@Override
public void call(Subscriber<? super FullTree> subscriber) {
GitReference ref = reference;
String branch = RefUtils.getPath(ref);
if (branch == null) {
branch = repository.default_branch;
if (TextUtils.isEmpty(branch)) {
branch = new RepoInfoClient(InfoUtils.createRepoInfo(repository))
.observable().toBlocking().first().default_branch;
if (TextUtils.isEmpty(branch))
subscriber.onError(new IOException("Repo does not have master branch"));
}
branch = "refs/heads/" + branch;
}
if (!isValidRef(ref)) {
ref = new ReferenceInfoClient(InfoUtils.createRepoInfo(repository, branch))
.observable()
.toBlocking()
.first();
if (!isValidRef(ref))
subscriber.onError(new IOException("Reference does not have associated commit SHA-1"));
}
GitCommit commit = new CommitInfoClient(InfoUtils.createRepoInfo(repository, ref.object.sha))
.observable().toBlocking().first();
if (commit == null || commit.tree == null
|| TextUtils.isEmpty(commit.tree.sha))
subscriber.onError(new IOException("Commit does not have associated tree SHA-1"));
GitTree tree = new GitTreeInfoClient(InfoUtils.createRepoInfo(repository, commit.tree.sha), true)
.observable().toBlocking().first();
subscriber.onNext(new FullTree(tree, ref));
}
} | [
"352091626@qq.com"
] | 352091626@qq.com |
10de677fa76055e3b7b6a5625758c7c07ed2ac74 | ed55867fa839a8582e60abdb04cf111215c1e0e4 | /src/main/java/actions/views/EmployeeConverter.java | 4cddf4b41ddefa2958ccc817f660c78c872f6d73 | [] | no_license | Hossori/daily_report_system | 0fa330fd06f3da76dd585658d942fa5d440f8ae4 | 294994bfcded47c2ecd01f5ccc781353112018dc | refs/heads/main | 2023-06-29T08:21:02.326141 | 2021-07-23T13:37:05 | 2021-07-23T13:37:05 | 386,568,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,503 | java | package actions.views;
import java.util.ArrayList;
import java.util.List;
import constants.AttributeConst;
import constants.JpaConst;
import models.Employee;
/*
* 従業員データのDTOモデル⇔Viewモデルの変換を行うクラス
*/
public class EmployeeConverter {
/*
* ViewモデルのインスタンスからDTOモデルのインスタンスを作成する
* @param ev EmployeeViewのインスタンス
* @return Employeeのインスタンス
*/
public static Employee toModel(EmployeeView ev) {
return new Employee(
ev.getId(),
ev.getCode(),
ev.getName(),
ev.getPassword(),
ev.getAdminFlag() == null
? null
: ev.getAdminFlag() == AttributeConst.ROLE_ADMIN.getIntegerValue()
? JpaConst.ROLE_ADMIN
: JpaConst.ROLE_GENERAL,
ev.getCreatedAt(),
ev.getUpdatedAt(),
ev.getDeleteFlag() == null
? null
: ev.getDeleteFlag() == AttributeConst.DEL_FLAG_TRUE.getIntegerValue()
? JpaConst.EMP_DEL_TRUE
: JpaConst.EMP_DEL_FALSE);
}
/*
* DTOモデルのインスタンスからViewモデルのインスタンスを作成する
* @param e Employeeのインスタンス
* @return EmployeeViewのインスタンス
*/
public static EmployeeView toView(Employee e) {
if(e == null) {
return null;
}
return new EmployeeView(
e.getId(),
e.getCode(),
e.getName(),
e.getPassword(),
e.getAdminFlag() == null
? null
: e.getAdminFlag() == JpaConst.ROLE_ADMIN
? AttributeConst.ROLE_ADMIN.getIntegerValue()
: AttributeConst.ROLE_GENERAL.getIntegerValue(),
e.getCreatedAt(),
e.getUpdatedAt(),
e.getDeleteFlag() == null
? null
: e.getDeleteFlag() == JpaConst.EMP_DEL_TRUE
? AttributeConst.DEL_FLAG_TRUE.getIntegerValue()
: AttributeConst.DEL_FLAG_FALSE.getIntegerValue());
}
/*
* DTOモデルのチストからViewモデルのリストを作成する
* @param list DTOモデルのリスト
* @return Viewモデルのリスト
*/
public static List<EmployeeView> toViewList(List<Employee> list) {
List<EmployeeView> evs = new ArrayList<>();
for(Employee e : list) {
evs.add(toView(e));
}
return evs;
}
/*
* Viewモデルの全フィールドの内容をDTOモデルのフィールドにコピーする
* @param e DTOモデル(コピー先)
* @param ev Viewモデル(コピー元)
*/
public static void copyViewToModel(Employee e, EmployeeView ev) {
e.setId(ev.getId());
e.setCode(ev.getCode());
e.setName(ev.getName());
e.setPassword(ev.getPassword());
e.setAdminFlag(ev.getAdminFlag());
e.setCreatedAt(ev.getCreatedAt());
e.setUpdatedAt(ev.getUpdatedAt());
e.setDeleteFlag(ev.getDeleteFlag());
}
}
| [
"law.f1.vegas@gmail.com"
] | law.f1.vegas@gmail.com |
df17d2c8674d4eb59896f92bd46a4642cba82e25 | aa869bf37faccbcdfeb855d0443ca751666bd079 | /playground/emo3/src/com/example/emo3/CameraPreview.java | 285c6cdc093dc2b901dca0b51660d641e4c36698 | [] | no_license | gyan-garcia/Garage_iPal | b1fa12ca7c5cba23be0e726e36606abac24b70d5 | a798fccc570159179553a818a0afc67e3c7a2676 | refs/heads/master | 2021-01-01T17:59:27.055484 | 2017-08-03T21:37:30 | 2017-08-03T21:37:30 | 98,213,085 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,277 | java | package com.example.emo3;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
//this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
} | [
"deminw@winse.microsoft.com"
] | deminw@winse.microsoft.com |
8b4ea65119abc8a4a2640ac39e5c723313e32fb7 | 0613bb6cf1c71b575419651fc20330edb9f916d2 | /CheatBreaker/src/main/java/net/minecraft/command/server/CommandEmote.java | 0671e814fd4ae778611cabb273cae8b9c2989c48 | [] | no_license | Decencies/CheatBreaker | 544fdae14e61c6e0b1f5c28d8c865e2bbd5169c2 | 0cf7154272c8884eee1e4b4c7c262590d9712d68 | refs/heads/master | 2023-09-04T04:45:16.790965 | 2023-03-17T09:51:10 | 2023-03-17T09:51:10 | 343,514,192 | 98 | 38 | null | 2023-08-21T03:54:20 | 2021-03-01T18:18:19 | Java | UTF-8 | Java | false | false | 1,609 | java | package net.minecraft.command.server;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
public class CommandEmote extends CommandBase
{
public String getCommandName()
{
return "me";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 0;
}
public String getCommandUsage(ICommandSender p_71518_1_)
{
return "commands.me.usage";
}
public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_)
{
if (p_71515_2_.length > 0)
{
IChatComponent var3 = func_147176_a(p_71515_1_, p_71515_2_, 0, p_71515_1_.canCommandSenderUseCommand(1, "me"));
MinecraftServer.getServer().getConfigurationManager().func_148539_a(new ChatComponentTranslation("chat.type.emote", new Object[] {p_71515_1_.func_145748_c_(), var3}));
}
else
{
throw new WrongUsageException("commands.me.usage", new Object[0]);
}
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_)
{
return getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().getAllUsernames());
}
}
| [
"66835910+Decencies@users.noreply.github.com"
] | 66835910+Decencies@users.noreply.github.com |
32c5562d5c59f15b7db16585c524093f1bd44bc3 | 67664a4e07978b3fde696c907e284c54d342c9e3 | /app/src/main/java/com/example/daniel/arbolesapp/MainActivity.java | 1dce55d71172a2fa49fa18f36e955db1f29bc3f4 | [] | no_license | dmolinae/ArbolesApp | df31a508d83e4bd6d82541737fe3400d614a4437 | 70ef59765aa1129804dbce122eef1087ec2df5fc | refs/heads/master | 2021-01-17T17:23:43.830042 | 2016-07-05T22:45:10 | 2016-07-05T22:45:10 | 62,530,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,690 | java | package com.example.daniel.arbolesapp;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.getBackground().setAlpha(0);
toolbar.setTitle("");
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "ÁrbolesAPP 2016", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
} else if (id == R.id.nav_identify) {
} else if (id == R.id.nav_glossary) {
} else if (id == R.id.nav_forests) {
} else if (id == R.id.nav_fav) {
} else if (id == R.id.nav_about) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| [
"dmolinae@outlook.com"
] | dmolinae@outlook.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.