blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
313
82e98a183af390b8f5bf3d4ab122456c523613a2
25080eebe15154dc80153ceefa63d40059b32ab5
/design_pattern_demo/src/main/java/factory/AmericaDessertFactory.java
1214bde683a2e638a579be0b0ab0c359892e0bf5
[]
no_license
king-180/my_code
bffe28bff7effc96acfb46cb228b21fceb05b8c0
274dd32271720feaec2e1c5ef3cae662dd0eefc2
refs/heads/master
2023-07-05T22:27:48.416651
2021-07-31T08:41:04
2021-07-31T08:41:04
357,848,310
1
0
null
null
null
null
UTF-8
Java
false
false
316
java
package factory; /** * @author wangxing * @date 2021/2/25 11:12 */ public class AmericaDessertFactory implements DessertFactory{ @Override public Coffee createCoffee() { return new AmericaCoffee(); } @Override public Dessert createDessert() { return new Mochamusi(); } }
d5b96ad6431d862e128e53ba1c0e7131f683a458
097def45197c4e1a298756d980ed22cdd6148683
/src/main/java/system/model/User.java
0df70b0ffd64f953e798d42a47b8165d99df5fbd
[]
no_license
antonyuksofi/spring_users
23598ad1354ac20d94563d0fc095bc05e164d315
3594eee1a15a27e647b2be99f35dec4fd35e49bd
refs/heads/master
2021-01-20T02:15:50.352710
2019-01-06T17:57:20
2019-01-06T17:57:20
101,311,588
0
0
null
null
null
null
UTF-8
Java
false
false
763
java
package system.model; /** * Created by София on 23.08.2017. */ public class User { private String name; private String password; public User() { } public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
44f61ef2780deaee18d55491ddbb154d50ae9c57
e2f3f2fc6f56b6ddcc0e251ec6a781cc1fc49801
/L1.1 Simple web server/src/main/java/main/Mirror.java
c25a9b88a2d83b995a083cbd25d917e4fde676be
[ "MIT" ]
permissive
BioQwer/stepic_java_webserver
9d74acf17bcdcf64d949a84181b9aa65d8b20325
d59fcb7c8a7b9b24828a666e20e6646d6e851e97
refs/heads/master
2020-12-07T03:52:22.525493
2019-02-16T14:42:53
2019-02-16T14:42:53
48,451,532
1
0
null
2015-12-22T20:04:42
2015-12-22T20:04:41
Java
UTF-8
Java
false
false
613
java
package main; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author bioqwer */ public class Mirror extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println(req.getParameter("key")); resp.setContentType("text/html;charset=utf-8"); resp.setStatus(HttpServletResponse.SC_OK); } }
8b330c5905a396cb948208a98ec53d09d318ad2d
56106d7646ed6537bb844cd2eb04a8a9dafeee1d
/web-admin/src/main/java/com/creatoo/hn/model/WhFetchFrom.java
2e549dbf2c9e9ed769c7ed5e69e1dcdba8d5dfd8
[]
no_license
nantiandeai/guangdong
64efc759fa87ad7b292812e579a13d349bed332b
7be3729bdce31acce345b796aab299a677ef495b
refs/heads/master
2021-01-22T05:42:53.769264
2017-05-25T03:16:14
2017-05-25T03:16:14
92,489,159
0
2
null
null
null
null
UTF-8
Java
false
false
5,958
java
package com.creatoo.hn.model; import javax.persistence.*; @Table(name = "wh_fetch_from") public class WhFetchFrom { /** * 采集来源标识 */ @Id private String fromid; /** * 采集来源名称 */ private String fromname; /** * 采集数据类型:对应数据库表名 */ private String fromfetchtype; /** * 采集数据列表页URL,分页值可以用${page}来代替. */ private String fromlisturl; /** * 采集数据列表页URL中分页变量的初始值. */ private String fromlistvalinitval; /** * 采集数据列表页URL中分页变量的递增值 */ private String fromlistvaladdval; /** * 如何查找列表页中的每个元素 */ private String fromlistitemmatch; /** * 如何查找列表页每个元素的详细页地址 */ private String frominfoaddrmatch; /** * 在列表页如何查找元素唯一主键 */ private String fromitemidmatch; /** * 采集来源状态:0-无效;1-有效. */ private Integer fromstate; /** * 获取采集来源标识 * * @return fromid - 采集来源标识 */ public String getFromid() { return fromid; } /** * 设置采集来源标识 * * @param fromid 采集来源标识 */ public void setFromid(String fromid) { this.fromid = fromid; } /** * 获取采集来源名称 * * @return fromname - 采集来源名称 */ public String getFromname() { return fromname; } /** * 设置采集来源名称 * * @param fromname 采集来源名称 */ public void setFromname(String fromname) { this.fromname = fromname; } /** * 获取采集数据类型:对应数据库表名 * * @return fromfetchtype - 采集数据类型:对应数据库表名 */ public String getFromfetchtype() { return fromfetchtype; } /** * 设置采集数据类型:对应数据库表名 * * @param fromfetchtype 采集数据类型:对应数据库表名 */ public void setFromfetchtype(String fromfetchtype) { this.fromfetchtype = fromfetchtype; } /** * 获取采集数据列表页URL,分页值可以用${page}来代替. * * @return fromlisturl - 采集数据列表页URL,分页值可以用${page}来代替. */ public String getFromlisturl() { return fromlisturl; } /** * 设置采集数据列表页URL,分页值可以用${page}来代替. * * @param fromlisturl 采集数据列表页URL,分页值可以用${page}来代替. */ public void setFromlisturl(String fromlisturl) { this.fromlisturl = fromlisturl; } /** * 获取采集数据列表页URL中分页变量的初始值. * * @return fromlistvalinitval - 采集数据列表页URL中分页变量的初始值. */ public String getFromlistvalinitval() { return fromlistvalinitval; } /** * 设置采集数据列表页URL中分页变量的初始值. * * @param fromlistvalinitval 采集数据列表页URL中分页变量的初始值. */ public void setFromlistvalinitval(String fromlistvalinitval) { this.fromlistvalinitval = fromlistvalinitval; } /** * 获取采集数据列表页URL中分页变量的递增值 * * @return fromlistvaladdval - 采集数据列表页URL中分页变量的递增值 */ public String getFromlistvaladdval() { return fromlistvaladdval; } /** * 设置采集数据列表页URL中分页变量的递增值 * * @param fromlistvaladdval 采集数据列表页URL中分页变量的递增值 */ public void setFromlistvaladdval(String fromlistvaladdval) { this.fromlistvaladdval = fromlistvaladdval; } /** * 获取如何查找列表页中的每个元素 * * @return fromlistitemmatch - 如何查找列表页中的每个元素 */ public String getFromlistitemmatch() { return fromlistitemmatch; } /** * 设置如何查找列表页中的每个元素 * * @param fromlistitemmatch 如何查找列表页中的每个元素 */ public void setFromlistitemmatch(String fromlistitemmatch) { this.fromlistitemmatch = fromlistitemmatch; } /** * 获取如何查找列表页每个元素的详细页地址 * * @return frominfoaddrmatch - 如何查找列表页每个元素的详细页地址 */ public String getFrominfoaddrmatch() { return frominfoaddrmatch; } /** * 设置如何查找列表页每个元素的详细页地址 * * @param frominfoaddrmatch 如何查找列表页每个元素的详细页地址 */ public void setFrominfoaddrmatch(String frominfoaddrmatch) { this.frominfoaddrmatch = frominfoaddrmatch; } /** * 获取在列表页如何查找元素唯一主键 * * @return fromitemidmatch - 在列表页如何查找元素唯一主键 */ public String getFromitemidmatch() { return fromitemidmatch; } /** * 设置在列表页如何查找元素唯一主键 * * @param fromitemidmatch 在列表页如何查找元素唯一主键 */ public void setFromitemidmatch(String fromitemidmatch) { this.fromitemidmatch = fromitemidmatch; } /** * 获取采集来源状态:0-无效;1-有效. * * @return fromstate - 采集来源状态:0-无效;1-有效. */ public Integer getFromstate() { return fromstate; } /** * 设置采集来源状态:0-无效;1-有效. * * @param fromstate 采集来源状态:0-无效;1-有效. */ public void setFromstate(Integer fromstate) { this.fromstate = fromstate; } }
67a7f9bd4d75fc03f58cf056c9b55799f95a4ec4
00b5878f83ecdf70e8650420f0484c639d46ac1b
/app/src/main/java/com/example/android/newsreader/NewsAdapter.java
5edf27682254d507448459144e3ffca04755b9ca
[]
no_license
brookemperry/NewsReader
a155f5e8457b985d52f86f10a1fe4ec546a998ad
20f67b8f76310f64d3bedc9b953ccad0e599c1c7
refs/heads/master
2020-03-27T08:16:25.632120
2018-09-09T16:44:22
2018-09-09T16:44:22
146,238,669
0
0
null
null
null
null
UTF-8
Java
false
false
2,291
java
package com.example.android.newsreader; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class NewsAdapter extends ArrayAdapter { private static final String DATE_SEPARATOR = "T"; public NewsAdapter(@NonNull MainActivity context, ArrayList<News> articles) { super(context, 0, articles); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { //Get the News item at this position the list News currentNews = (News) getItem(position); String title = currentNews.getTitle(); String author = currentNews.getAuthor(); //time is stored here in case app is changed to include time in the future. It is not currently used. String originalDate = currentNews.getDate(); String date; String time; //Split the time from the string containing the date & time if (originalDate.contains(DATE_SEPARATOR)) { String[] parts = originalDate.split(DATE_SEPARATOR); date = parts[0]; time = parts[1]; } else { date = originalDate; time = null; } String section = currentNews.getSection(); //Check if view is being reused, otherwise inflate View listItemView = convertView; if (listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false); } //Find the correct TextViews in item.xml and set the correct text in the TextViews. TextView titleTextView = listItemView.findViewById(R.id.title); titleTextView.setText(title); TextView authorTextView = listItemView.findViewById(R.id.author); authorTextView.setText(author); TextView sectionTextView = listItemView.findViewById(R.id.section); sectionTextView.setText(section); TextView dateTextView = listItemView.findViewById(R.id.date); dateTextView.setText(date); return listItemView; } }
8f9bb6eaee57bdc894e28d6508f3f7cc2a8715c9
5fb575d357c560e26d6ba9c30ba00a89a4f80010
/src/main/java/com/burning8393/spring_boot_mvc/SpringBootMvcApplication.java
fd581639634b5a2d69555003d018d2195c70b0ca
[]
no_license
BurnJinji/spring_boot_mvc
7339576ffc9c089588815ca2bf55c8ae9582978c
8ecd7f8b6b6fe465e19ec64e2117bcda192dae16
refs/heads/master
2020-09-24T12:59:10.312473
2019-12-04T02:45:14
2019-12-04T02:45:14
225,763,989
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package com.burning8393.spring_boot_mvc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootMvcApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMvcApplication.class, args); } }
0bf33a69c2627a6a1fb4eec15a2d7c9e6b5dbef1
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/imgsearch-20200320/src/main/java/com/aliyun/imgsearch20200320/models/AddImageResponseBody.java
b4a8beb8b3ca61e4a5949b07656a037f231fa373
[ "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
1,506
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.imgsearch20200320.models; import com.aliyun.tea.*; public class AddImageResponseBody extends TeaModel { @NameInMap("Data") public AddImageResponseBodyData data; @NameInMap("RequestId") public String requestId; public static AddImageResponseBody build(java.util.Map<String, ?> map) throws Exception { AddImageResponseBody self = new AddImageResponseBody(); return TeaModel.build(map, self); } public AddImageResponseBody setData(AddImageResponseBodyData data) { this.data = data; return this; } public AddImageResponseBodyData getData() { return this.data; } public AddImageResponseBody setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } public static class AddImageResponseBodyData extends TeaModel { @NameInMap("DataId") public String dataId; public static AddImageResponseBodyData build(java.util.Map<String, ?> map) throws Exception { AddImageResponseBodyData self = new AddImageResponseBodyData(); return TeaModel.build(map, self); } public AddImageResponseBodyData setDataId(String dataId) { this.dataId = dataId; return this; } public String getDataId() { return this.dataId; } } }
d62693b615c92e43b64b77f27fdac91f8ee432aa
17319c2ae161be17d546114007942afaf215785e
/cassandra/src/main/java/org/restexpress/scaffold/cassandra/Routes.java
24252505aeebccfad1527b4936343bee8ff6b337
[]
no_license
nandanad/RestExpress-Scaffold
eb75e7a1fa58dd72e8dbdb6f7391dfd89a54f194
456ccc9bb08e3567998026c1276632fa4e1f3381
refs/heads/master
2021-01-18T14:54:34.803065
2014-12-02T21:41:12
2014-12-02T21:41:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,283
java
package org.restexpress.scaffold.cassandra; import org.jboss.netty.handler.codec.http.HttpMethod; import org.restexpress.RestExpress; import org.restexpress.scaffold.cassandra.config.Configuration; public abstract class Routes { public static void define(Configuration config, RestExpress server) { // TODO: Your routes here... server.uri("/samples/uuid/{uuid}.{format}", config.getSampleUuidEntityController()) .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) .name(Constants.Routes.SINGLE_UUID_SAMPLE); server.uri("/samples/uuid.{format}", config.getSampleUuidEntityController()) .method(HttpMethod.POST) .name(Constants.Routes.SAMPLE_UUID_COLLECTION); server.uri("/samples/compound/{key1}/{key2}/{key3}.{format}", config.getSampleCompoundIdentifierEntityController()) .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE) .name(Constants.Routes.SINGLE_COMPOUND_SAMPLE); server.uri("/samples/compound/{key1}/{key2}.{format}", config.getSampleCompoundIdentifierEntityController()) .action("readAll", HttpMethod.GET) .method(HttpMethod.POST) .name(Constants.Routes.SAMPLE_COMPOUND_COLLECTION); // or REGEX matching routes... // server.regex("/some.regex", config.getRouteController()); } }
c8415ef3f2f71df9e207f79588dc0187cbcba307
1c88a96a435d27e15156bef6a9a2df3f28088f48
/YDYYMH/src/com/ideal/zsyy/activity/MZSMActivity.java
e1a3dfd71ff51dff0820dc281e0041ae6bf2ab75
[]
no_license
RayMonChina/water_xingcheng
f56aa7569e97f92dafb5da84b1653bf4ed3e2785
2176c38dcfa6f4954970727886b75641b13e4a72
refs/heads/master
2021-08-31T23:03:26.139602
2017-12-23T09:03:12
2017-12-23T09:03:12
109,460,142
0
0
null
null
null
null
UTF-8
Java
false
false
662
java
package com.ideal.zsyy.activity; import com.jijiang.wtapp.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MZSMActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mzsm_info); Button btn_back = (Button) findViewById(R.id.btn_back); btn_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
2de8732abe6ec1416d4d43aed1644599254728da
1a8e9d4bd8d8eef38a2c3a6b4108cbb2f586d6aa
/vip-20170405/gupaoedu-vip-template/src/com/gupaoedu/vip/template/TestTemplate.java
f086cd47fe620f066da3c23f1b31fc2a944387ff
[]
no_license
marcodeba/mySpringMVC
484c4302b7caa24a485188a00ae3f03321df2bd9
7f22cbc6a249076f465aafb8387d4e338261c897
refs/heads/master
2022-12-20T03:58:06.751153
2020-04-04T09:03:08
2020-04-04T09:03:08
251,573,930
0
0
null
2022-12-16T03:33:09
2020-03-31T10:43:41
Java
GB18030
Java
false
false
526
java
package com.gupaoedu.vip.template; public class TestTemplate { public static void main(String[] args) { // Coffee coffee = new Coffee(); // coffee.create(); Tea tea = new Tea(); tea.create(); } //SpringJDBC //是java规范,各个数据库厂商自己去实现 //1、加载驱动类DriverManager //2、建立连接 //3、创建语句集(标准语句集、预处理语句集)(语句集? MySQL、Oracle、SQLServer、Access) //4、执行语句集 //5、结果集ResultSet 游标 //ORM(?) }
54d83eac461a43cc312033723148b449c8519675
18ed574c5a2f9c43bacf9cf262dba73623087617
/공통/getski/backend/src/main/java/com/getski/exception/DataAlreadyExistsException.java
1ceb5f8f5851c46ecd3d086cafb5e8534b080078
[ "MIT" ]
permissive
fastz123/Projects_GETSKI
e24f54674a62239fad0e3eedb5072513a803cc11
be3e38a93b2a3f113ba13e97287e72167c62edca
refs/heads/master
2023-02-12T14:53:49.108341
2020-10-19T14:37:29
2020-10-19T14:37:29
245,100,864
0
0
null
2021-01-05T23:01:20
2020-03-05T07:51:55
JavaScript
UTF-8
Java
false
false
185
java
package com.getski.exception; public class DataAlreadyExistsException extends RuntimeException { public DataAlreadyExistsException(String message) { super(message); } }
0554577c1f27403fbe07f4462fddfbca72368db0
d08abfffd968faea4570e28e6a13b36942144011
/Serializable/src/lel/Serializable3/Teacher.java
9b09f6a568affc900160c4bdcf10b294cd6e8eb1
[]
no_license
long-lang/long
db1a52ded85d164220ef8976090cd8ed5ab12372
9bc2fdbeb72793c0bcf4ea9af241bb1e8a47bd14
refs/heads/master
2020-07-17T16:02:13.389176
2020-02-22T04:08:49
2020-02-22T04:08:49
206,049,847
1
0
null
null
null
null
UTF-8
Java
false
false
172
java
package lel.Serializable3; import java.io.Serializable; public class Teacher { //private static final long serialVersionUID = 1L; private String position = "无"; }
14b9888e329348d15e567cd72d073fb82baf6804
d4e8adf5e1769f50d404350707d89217bc6e7f5e
/homework1/src/main/java/ru/otus/valeev/domain/Answer.java
89e6184b65550f84cf38bcc925c325090c69abf4
[]
no_license
webster91/2020-02-otus-spring-valeev
7cbe245dc8f2222b4a8682fe26e3f2db99edacf0
124bb94d962d125e89f21af212e4825423bc8b0c
refs/heads/master
2023-01-10T07:51:53.021263
2020-08-16T13:11:08
2020-08-16T13:11:08
244,459,229
0
0
null
2023-01-06T12:27:00
2020-03-02T19:40:39
Java
UTF-8
Java
false
false
85
java
package ru.otus.valeev.domain; import lombok.Value; @Value public class Answer { }
daac715b7fba4137b5930ca9a1b79b698335ccd6
cae8ecd6f9158a8ee988cafb68d6e69b51cec71d
/src/test/java/AutomationTestGropp/AutomationPratice/AppTest.java
27c7f1e890a435d6d134466016395c8a55fdad2e
[]
no_license
ramkrishna123p/AutomationPractice
f623535f70bd8374d8ed1c953f87bd0bfcbfab03
15586dbf48cf51d7120ea5af2d8081aab3c6f581
refs/heads/master
2022-12-29T08:53:35.711485
2020-07-02T04:34:03
2020-07-02T04:34:03
276,548,466
0
0
null
2020-10-13T23:14:37
2020-07-02T04:29:40
Java
UTF-8
Java
false
false
665
java
package AutomationTestGropp.AutomationPratice; 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 ); } }
74cfab784c13d4cfaad13d8330b02d4caaf5c68b
793f829ebcf385a23773ff7199b131f8dbf174f3
/src/org/onlineshopping/decorator/RentItem.java
e870e1ab0c7058a9034f16c97d493a01f57812e8
[]
no_license
kishorenekkalapudi/E-Commerce-Online-Shopping-by-using-Design-Patterns
006523ddfb4cb8b8ed20de2f1fa72a3deb62c69a
53bea554dc675a6e739aa6d3315d2756bf754e97
refs/heads/master
2016-09-05T12:57:29.504092
2013-06-05T18:10:33
2013-06-05T18:10:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
358
java
package org.onlineshopping.decorator; import org.onlineshopping.bridge.PaymentOptions; public class RentItem extends RentableDecorator { @Override public void RentItemByItemId(int Item_Id) { PaymentOptions paymentoptions=new PaymentOptions(); try{ setTotalNumberOfItems(); paymentoptions.BuyItemMenu(); } catch(Exception er){ } } }
5cc2f6a3338824a0690ba03c1cfe3228182ddcce
164fa61cfbc89a8e3e22f5c102d1d62f9046dea3
/src/cn/codercheng/source/java/net/URLStreamHandler.java
c47782b815326c8d83f0f9492a9dec0d04d0579d
[]
no_license
codeChengWenY/JavaSourceLearn
1426723baceeb0db57d0533f2d74f186809a93f8
d36d2f98527d3abc9985f34c78a5f776e6cf60ed
refs/heads/master
2022-12-05T06:52:26.969508
2020-08-14T06:36:43
2020-08-14T06:36:43
287,459,086
0
0
null
null
null
null
UTF-8
Java
false
false
22,094
java
/* * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.net; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.OutputStream; import java.util.Hashtable; import sun.net.util.IPAddressUtil; import sun.net.www.ParseUtil; /** * The abstract class {@code URLStreamHandler} is the common * superclass for all stream protocol handlers. A stream protocol * handler knows how to make a connection for a particular protocol * type, such as {@code http} or {@code https}. * <p> * In most cases, an instance of a {@code URLStreamHandler} * subclass is not created directly by an application. Rather, the * first time a protocol name is encountered when constructing a * {@code URL}, the appropriate stream protocol handler is * automatically loaded. * * @author James Gosling * @see java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) * @since JDK1.0 */ public abstract class URLStreamHandler { /** * Opens a connection to the object referenced by the * {@code URL} argument. * This method should be overridden by a subclass. * * <p>If for the handler's protocol (such as HTTP or JAR), there * exists a public, specialized URLConnection subclass belonging * to one of the following packages or one of their subpackages: * java.lang, java.io, java.util, java.net, the connection * returned will be of that subclass. For example, for HTTP an * HttpURLConnection will be returned, and for JAR a * JarURLConnection will be returned. * * @param u the URL that this connects to. * @return a {@code URLConnection} object for the {@code URL}. * @exception IOException if an I/O error occurs while opening the * connection. */ abstract protected URLConnection openConnection(URL u) throws IOException; /** * Same as openConnection(URL), except that the connection will be * made through the specified proxy; Protocol handlers that do not * support proxying will ignore the proxy parameter and make a * normal connection. * * Calling this method preempts the system's default ProxySelector * settings. * * @param u the URL that this connects to. * @param p the proxy through which the connection will be made. * If direct connection is desired, Proxy.NO_PROXY * should be specified. * @return a {@code URLConnection} object for the {@code URL}. * @exception IOException if an I/O error occurs while opening the * connection. * @exception IllegalArgumentException if either u or p is null, * or p has the wrong type. * @exception UnsupportedOperationException if the subclass that * implements the protocol doesn't support this method. * @since 1.5 */ protected URLConnection openConnection(URL u, Proxy p) throws IOException { throw new UnsupportedOperationException("Method not implemented."); } /** * Parses the string representation of a {@code URL} into a * {@code URL} object. * <p> * If there is any inherited context, then it has already been * copied into the {@code URL} argument. * <p> * The {@code parseURL} method of {@code URLStreamHandler} * parses the string representation as if it were an * {@code http} specification. Most URL protocol families have a * similar parsing. A stream protocol handler for a protocol that has * a different syntax must override this routine. * * @param u the {@code URL} to receive the result of parsing * the spec. * @param spec the {@code string} representing the URL that * must be parsed. * @param start the character index at which to begin parsing. This is * just past the '{@code :}' (if there is one) that * specifies the determination of the protocol name. * @param limit the character position to stop parsing at. This is the * end of the string or the position of the * "{@code #}" character, if present. All information * after the sharp sign indicates an anchor. */ protected void parseURL(URL u, String spec, int start, int limit) { // These fields may receive context content if this was relative URL String protocol = u.getProtocol(); String authority = u.getAuthority(); String userInfo = u.getUserInfo(); String host = u.getHost(); int port = u.getPort(); String path = u.getPath(); String query = u.getQuery(); // This field has already been parsed String ref = u.getRef(); boolean isRelPath = false; boolean queryOnly = false; // FIX: should not assume query if opaque // Strip off the query part if (start < limit) { int queryStart = spec.indexOf('?'); queryOnly = queryStart == start; if ((queryStart != -1) && (queryStart < limit)) { query = spec.substring(queryStart+1, limit); if (limit > queryStart) limit = queryStart; spec = spec.substring(0, queryStart); } } int i = 0; // Parse the authority part if any boolean isUNCName = (start <= limit - 4) && (spec.charAt(start) == '/') && (spec.charAt(start + 1) == '/') && (spec.charAt(start + 2) == '/') && (spec.charAt(start + 3) == '/'); if (!isUNCName && (start <= limit - 2) && (spec.charAt(start) == '/') && (spec.charAt(start + 1) == '/')) { start += 2; i = spec.indexOf('/', start); if (i < 0 || i > limit) { i = spec.indexOf('?', start); if (i < 0 || i > limit) i = limit; } host = authority = spec.substring(start, i); int ind = authority.indexOf('@'); if (ind != -1) { if (ind != authority.lastIndexOf('@')) { // more than one '@' in authority. This is not server based userInfo = null; host = null; } else { userInfo = authority.substring(0, ind); host = authority.substring(ind+1); } } else { userInfo = null; } if (host != null) { // If the host is surrounded by [ and ] then its an IPv6 // literal address as specified in RFC2732 if (host.length()>0 && (host.charAt(0) == '[')) { if ((ind = host.indexOf(']')) > 2) { String nhost = host ; host = nhost.substring(0,ind+1); if (!IPAddressUtil. isIPv6LiteralAddress(host.substring(1, ind))) { throw new IllegalArgumentException( "Invalid host: "+ host); } port = -1 ; if (nhost.length() > ind+1) { if (nhost.charAt(ind+1) == ':') { ++ind ; // port can be null according to RFC2396 if (nhost.length() > (ind + 1)) { port = Integer.parseInt(nhost.substring(ind+1)); } } else { throw new IllegalArgumentException( "Invalid authority field: " + authority); } } } else { throw new IllegalArgumentException( "Invalid authority field: " + authority); } } else { ind = host.indexOf(':'); port = -1; if (ind >= 0) { // port can be null according to RFC2396 if (host.length() > (ind + 1)) { port = Integer.parseInt(host.substring(ind + 1)); } host = host.substring(0, ind); } } } else { host = ""; } if (port < -1) throw new IllegalArgumentException("Invalid port number :" + port); start = i; // If the authority is defined then the path is defined by the // spec only; See RFC 2396 Section 5.2.4. if (authority != null && authority.length() > 0) path = ""; } if (host == null) { host = ""; } // Parse the file path if any if (start < limit) { if (spec.charAt(start) == '/') { path = spec.substring(start, limit); } else if (path != null && path.length() > 0) { isRelPath = true; int ind = path.lastIndexOf('/'); String seperator = ""; if (ind == -1 && authority != null) seperator = "/"; path = path.substring(0, ind + 1) + seperator + spec.substring(start, limit); } else { String seperator = (authority != null) ? "/" : ""; path = seperator + spec.substring(start, limit); } } else if (queryOnly && path != null) { int ind = path.lastIndexOf('/'); if (ind < 0) ind = 0; path = path.substring(0, ind) + "/"; } if (path == null) path = ""; if (isRelPath) { // Remove embedded /./ while ((i = path.indexOf("/./")) >= 0) { path = path.substring(0, i) + path.substring(i + 2); } // Remove embedded /../ if possible i = 0; while ((i = path.indexOf("/../", i)) >= 0) { /* * A "/../" will cancel the previous segment and itself, * unless that segment is a "/../" itself * i.e. "/a/b/../c" becomes "/a/c" * but "/../../a" should stay unchanged */ if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 && (path.indexOf("/../", limit) != 0)) { path = path.substring(0, limit) + path.substring(i + 3); i = 0; } else { i = i + 3; } } // Remove trailing .. if possible while (path.endsWith("/..")) { i = path.indexOf("/.."); if ((limit = path.lastIndexOf('/', i - 1)) >= 0) { path = path.substring(0, limit+1); } else { break; } } // Remove starting . if (path.startsWith("./") && path.length() > 2) path = path.substring(2); // Remove trailing . if (path.endsWith("/.")) path = path.substring(0, path.length() -1); } setURL(u, protocol, host, port, authority, userInfo, path, query, ref); } /** * Returns the default port for a URL parsed by this handler. This method * is meant to be overidden by handlers with default port numbers. * @return the default port for a {@code URL} parsed by this handler. * @since 1.3 */ protected int getDefaultPort() { return -1; } /** * Provides the default equals calculation. May be overidden by handlers * for other protocols that have different requirements for equals(). * This method requires that none of its arguments is null. This is * guaranteed by the fact that it is only called by java.net.URL class. * @param u1 a URL object * @param u2 a URL object * @return {@code true} if the two urls are * considered equal, ie. they refer to the same * fragment in the same file. * @since 1.3 */ protected boolean equals(URL u1, URL u2) { String ref1 = u1.getRef(); String ref2 = u2.getRef(); return (ref1 == ref2 || (ref1 != null && ref1.equals(ref2))) && sameFile(u1, u2); } /** * Provides the default hash calculation. May be overidden by handlers for * other protocols that have different requirements for hashCode * calculation. * @param u a URL object * @return an {@code int} suitable for hash table indexing * @since 1.3 */ protected int hashCode(URL u) { int h = 0; // Generate the protocol part. String protocol = u.getProtocol(); if (protocol != null) h += protocol.hashCode(); // Generate the host part. InetAddress addr = getHostAddress(u); if (addr != null) { h += addr.hashCode(); } else { String host = u.getHost(); if (host != null) h += host.toLowerCase().hashCode(); } // Generate the file part. String file = u.getFile(); if (file != null) h += file.hashCode(); // Generate the port part. if (u.getPort() == -1) h += getDefaultPort(); else h += u.getPort(); // Generate the ref part. String ref = u.getRef(); if (ref != null) h += ref.hashCode(); return h; } /** * Compare two urls to see whether they refer to the same file, * i.e., having the same protocol, host, port, and path. * This method requires that none of its arguments is null. This is * guaranteed by the fact that it is only called indirectly * by java.net.URL class. * @param u1 a URL object * @param u2 a URL object * @return true if u1 and u2 refer to the same file * @since 1.3 */ protected boolean sameFile(URL u1, URL u2) { // Compare the protocols. if (!((u1.getProtocol() == u2.getProtocol()) || (u1.getProtocol() != null && u1.getProtocol().equalsIgnoreCase(u2.getProtocol())))) return false; // Compare the files. if (!(u1.getFile() == u2.getFile() || (u1.getFile() != null && u1.getFile().equals(u2.getFile())))) return false; // Compare the ports. int port1, port2; port1 = (u1.getPort() != -1) ? u1.getPort() : u1.handler.getDefaultPort(); port2 = (u2.getPort() != -1) ? u2.getPort() : u2.handler.getDefaultPort(); if (port1 != port2) return false; // Compare the hosts. if (!hostsEqual(u1, u2)) return false; return true; } /** * Get the IP address of our host. An empty host field or a DNS failure * will result in a null return. * * @param u a URL object * @return an {@code InetAddress} representing the host * IP address. * @since 1.3 */ protected synchronized InetAddress getHostAddress(URL u) { if (u.hostAddress != null) return u.hostAddress; String host = u.getHost(); if (host == null || host.equals("")) { return null; } else { try { u.hostAddress = InetAddress.getByName(host); } catch (UnknownHostException ex) { return null; } catch (SecurityException se) { return null; } } return u.hostAddress; } /** * Compares the host components of two URLs. * @param u1 the URL of the first host to compare * @param u2 the URL of the second host to compare * @return {@code true} if and only if they * are equal, {@code false} otherwise. * @since 1.3 */ protected boolean hostsEqual(URL u1, URL u2) { InetAddress a1 = getHostAddress(u1); InetAddress a2 = getHostAddress(u2); // if we have internet address for both, compare them if (a1 != null && a2 != null) { return a1.equals(a2); // else, if both have host names, compare them } else if (u1.getHost() != null && u2.getHost() != null) return u1.getHost().equalsIgnoreCase(u2.getHost()); else return u1.getHost() == null && u2.getHost() == null; } /** * Converts a {@code URL} of a specific protocol to a * {@code string}. * * @param u the URL. * @return a string representation of the {@code URL} argument. */ protected String toExternalForm(URL u) { // pre-compute length of StringBuffer int len = u.getProtocol().length() + 1; if (u.getAuthority() != null && u.getAuthority().length() > 0) len += 2 + u.getAuthority().length(); if (u.getPath() != null) { len += u.getPath().length(); } if (u.getQuery() != null) { len += 1 + u.getQuery().length(); } if (u.getRef() != null) len += 1 + u.getRef().length(); StringBuffer result = new StringBuffer(len); result.append(u.getProtocol()); result.append(":"); if (u.getAuthority() != null && u.getAuthority().length() > 0) { result.append("//"); result.append(u.getAuthority()); } if (u.getPath() != null) { result.append(u.getPath()); } if (u.getQuery() != null) { result.append('?'); result.append(u.getQuery()); } if (u.getRef() != null) { result.append("#"); result.append(u.getRef()); } return result.toString(); } /** * Sets the fields of the {@code URL} argument to the indicated values. * Only classes derived from URLStreamHandler are able * to use this method to set the values of the URL fields. * * @param u the URL to modify. * @param protocol the protocol name. * @param host the remote host value for the URL. * @param port the port on the remote machine. * @param authority the authority part for the URL. * @param userInfo the userInfo part of the URL. * @param path the path component of the URL. * @param query the query part for the URL. * @param ref the reference. * @exception SecurityException if the protocol handler of the URL is * different from this one * @see java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String) * @since 1.3 */ protected void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) { if (this != u.handler) { throw new SecurityException("handler for url different from " + "this handler"); } // ensure that no one can reset the protocol on a given URL. u.set(u.getProtocol(), host, port, authority, userInfo, path, query, ref); } /** * Sets the fields of the {@code URL} argument to the indicated values. * Only classes derived from URLStreamHandler are able * to use this method to set the values of the URL fields. * * @param u the URL to modify. * @param protocol the protocol name. This value is ignored since 1.2. * @param host the remote host value for the URL. * @param port the port on the remote machine. * @param file the file. * @param ref the reference. * @exception SecurityException if the protocol handler of the URL is * different from this one * @deprecated Use setURL(URL, string, string, int, string, string, string, * string); */ @Deprecated protected void setURL(URL u, String protocol, String host, int port, String file, String ref) { /* * Only old URL handlers call this, so assume that the host * field might contain "user:passwd@host". Fix as necessary. */ String authority = null; String userInfo = null; if (host != null && host.length() != 0) { authority = (port == -1) ? host : host + ":" + port; int at = host.lastIndexOf('@'); if (at != -1) { userInfo = host.substring(0, at); host = host.substring(at+1); } } /* * Assume file might contain query part. Fix as necessary. */ String path = null; String query = null; if (file != null) { int q = file.lastIndexOf('?'); if (q != -1) { query = file.substring(q+1); path = file.substring(0, q); } else path = file; } setURL(u, protocol, host, port, authority, userInfo, path, query, ref); } }
77c29b8d6876f0f4ba0c411b86c4eb084b8a75e5
2694a1d2b77ba61190ae874a707c8e2b80928636
/tool/src/main/java/org/jboss/mgmt/generator/Generator.java
4293cf200f50d257a317e7bef176e9ff9803c569
[]
no_license
maeste/protoglop
9c97386097ac20b6b29e576c45d9b6657cc41072
38209da33c1d9b521e03abbc8b52df4dd6dd44df
refs/heads/master
2020-12-25T11:58:46.955623
2012-10-30T17:21:05
2012-10-30T17:21:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
35,778
java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.mgmt.generator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import nu.xom.Attribute; import nu.xom.Element; import org.jboss.mgmt.AbstractResource; import org.jboss.mgmt.Entry; import org.jboss.mgmt.ExceptionThrowingValidationContext; import org.jboss.mgmt.Resource; import org.jboss.mgmt.annotation.Access; import org.jboss.mgmt.annotation.Schema; import org.jboss.mgmt.annotation.XmlRender; import org.jboss.mgmt.ResourceNode; import org.jboss.jdeparser.JBlock; import org.jboss.jdeparser.JClass; import org.jboss.jdeparser.JClassAlreadyExistsException; import org.jboss.jdeparser.JDeparser; import org.jboss.jdeparser.JDefinedClass; import org.jboss.jdeparser.JDocComment; import org.jboss.jdeparser.JExpr; import org.jboss.jdeparser.JExpression; import org.jboss.jdeparser.JFieldVar; import org.jboss.jdeparser.JInvocation; import org.jboss.jdeparser.JMethod; import org.jboss.jdeparser.JType; import org.jboss.jdeparser.JTypeVar; import org.jboss.jdeparser.JVar; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.annotation.Generated; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import static org.jboss.jdeparser.ClassType.CLASS; import static org.jboss.jdeparser.ClassType.INTERFACE; import static org.jboss.jdeparser.JMod.FINAL; import static org.jboss.jdeparser.JMod.NONE; import static org.jboss.jdeparser.JMod.PRIVATE; import static org.jboss.jdeparser.JMod.PUBLIC; import static org.jboss.jdeparser.JMod.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; import static javax.tools.Diagnostic.Kind.WARNING; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class Generator {/* private static final String GENERATOR_VERSION = "1.0"; private final ProcessingEnvironment env; private final RoundEnvironment roundEnv; private final Filer filer; private final Messager messager; private final Types types; private final Elements elements; private final SessionImpl session; private final JDeparser deparser = new JDeparser(); // -------------------------------------------------- // Accumulated output // -------------------------------------------------- static class DocInfo { final Map<String, Element> typeDecls = new TreeMap<String, Element>(); final Map<String, Element> rootElementDecls = new TreeMap<String, Element>(); final Set<String> altXmlNamespaces = new HashSet<String>(); String schemaLocation; Schema.Kind resourceNamespaceKind = Schema.Kind.EXTENSION; String version; String namespace; // just the module part } private final Map<String, DocInfo> namespaceSchemas = new HashMap<String, DocInfo>(); private final Set<String> generatedResourceTypes = new HashSet<String>(); private final Set<String> generatedAttributeTypes = new HashSet<String>(); private final Set<String> generatedAttributeGroups = new HashSet<String>(); Generator(final ProcessingEnvironment env, final RoundEnvironment roundEnv, final SessionImpl session) { this.roundEnv = roundEnv; this.session = session; this.env = env; filer = env.getFiler(); messager = env.getMessager(); types = env.getTypeUtils(); elements = env.getElementUtils(); } void generate() { final List<RootResourceBuilderImpl> resources = session.getResources(); for (RootResourceBuilderImpl resource : resources) { // -------------------------------------------------- // Root-specific stuff // -------------------------------------------------- final String version = def(resource.getVersion(), "1.0"); final String namespace = def(resource.getNamespace(), "unspecified"); final String schemaLocation = resource.getSchemaLocation(); final Schema.Kind resourceNamespaceKind = def(resource.getKind(), Schema.Kind.EXTENSION); final String xmlNamespace = buildNamespace(resourceNamespaceKind, namespace, version); final DocInfo docInfo; if (! namespaceSchemas.containsKey(xmlNamespace)) { docInfo = new DocInfo(); docInfo.schemaLocation = schemaLocation; docInfo.namespace = namespace; docInfo.resourceNamespaceKind = resourceNamespaceKind; docInfo.version = version; namespaceSchemas.put(xmlNamespace, docInfo); } else { docInfo = namespaceSchemas.get(xmlNamespace); if (false && ! schemaLocation.equals(docInfo.schemaLocation)) { messager.printMessage(WARNING, "Namespace '" + xmlNamespace + "' declared with conflicting schema locations"); } } // Root resources declare elements in the root schema. new ResourceWriter(resource, docInfo, xmlNamespace, null).generate(); } // -------------------------------------------------- // Emit results (if no error) // -------------------------------------------------- } class ResourceWriter { private final GeneralResourceBuilderImpl<?> resource; private final DocInfo docInfo; private final String xmlNamespace; private final Element parentType; ResourceWriter(final GeneralResourceBuilderImpl<?> resource, final DocInfo docInfo, final String xmlNamespace, final Element parentType) { this.resource = resource; this.docInfo = docInfo; this.xmlNamespace = xmlNamespace; this.parentType = parentType; } void generate() { // -------------------------------------------------- // Gather resource information // -------------------------------------------------- final TypeElement resourceInterfaceElement = (TypeElement) ((DeclaredType) resource.getResourceInterface()).asElement(); final String resourceFqcn = resourceInterfaceElement.getQualifiedName().toString(); final String resourceScn = resourceInterfaceElement.getSimpleName().toString(); if (! resourceFqcn.endsWith("Resource")) { messager.printMessage(ERROR, "Resource type " + resourceFqcn + " must end in \"...Resource\"", resourceInterfaceElement); return; } final String fqcn = resourceFqcn.substring(0, resourceFqcn.length() - 8); final String scn = resourceScn.substring(0, resourceScn.length() - 8); final String xmlName = def(resource.getXmlName(), xmlify(scn)); // -------------------------------------------------- // Schema root element for root resource // -------------------------------------------------- final Element elementElement = new Element("xs:element", XSD); elementElement.addAttribute(new Attribute("name", xmlName)); final Element typeElement = new Element("xs:complexType", XSD); if (parentType == null) { elementElement.appendChild(typeElement); docInfo.rootElementDecls.put(xmlName, elementElement); } else { parentType.appendChild(elementElement); elementElement.addAttribute(new Attribute("type", xmlName)); typeElement.addAttribute(new Attribute("name", xmlName)); docInfo.typeDecls.put(xmlName, typeElement); } final Element typeSeqElement = new Element("xs:sequence", XSD); typeElement.appendChild(typeSeqElement); addDocumentation(elementElement, "RESOURCE DESCRIPTION"); // -------------------------------------------------- // Code model class instances // -------------------------------------------------- final JDefinedClass parserClass; final JDefinedClass deparserClass; final JDefinedClass builderInterface; final JDefinedClass builderClass; final JDefinedClass builderFactoryClass; final JDefinedClass implementationClass; final JDefinedClass resourceNodeClass; final JDefinedClass coreClass; final JClass resourceInterface = (JClass) CodeModelUtils.typeFor(env, deparser, resource.getResourceInterface()); try { parserClass = deparser._class(PUBLIC | FINAL, fqcn + "ParserImpl", CLASS); deparserClass = deparser._class(PUBLIC | FINAL, fqcn + "DeparserImpl", CLASS); builderInterface = deparser._class(PUBLIC, fqcn + "Builder", INTERFACE); builderClass = deparser._class(PUBLIC | FINAL, fqcn + "BuilderImpl", CLASS); implementationClass = deparser._class(PUBLIC | FINAL, fqcn + "ResourceImpl", CLASS); resourceNodeClass = deparser._class(PUBLIC | FINAL, fqcn + "NodeImpl", CLASS); coreClass = parentType == null ? deparser._class(PUBLIC | FINAL, fqcn, CLASS) : null; builderFactoryClass = deparser._class(PUBLIC | FINAL, fqcn + "BuilderFactory", CLASS); } catch (JClassAlreadyExistsException e) { messager.printMessage(ERROR, "Duplicate class generation for " + fqcn); return; } // -------------------------------------------------- // Class headers, extends/implements // -------------------------------------------------- parserClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); deparserClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); builderInterface.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); builderClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); implementationClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); resourceNodeClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); if (parentType == null) coreClass.annotate(Generated.class).paramArray("value").param(Generator.class.getName()).param(GENERATOR_VERSION); final JMethod implConstructor = implementationClass.constructor(PUBLIC); final JBlock implConstructorBody = implConstructor.body(); final JInvocation implConstructorSuperCall = implConstructorBody.invoke("super"); implConstructorSuperCall.arg(implConstructor.param(FINAL, deparser.ref(String.class), "preComment")); implConstructorSuperCall.arg(implConstructor.param(FINAL, deparser.ref(String.class), "postComment")); implConstructorSuperCall.arg(implConstructor.param(FINAL, deparser.ref(String.class), "name")); implConstructorSuperCall.arg(implConstructor.param(FINAL, deparser.ref(ResourceNode.class).narrow(deparser.wildcard()), "parent")); // The core class is not instantiatable coreClass.constructor(PRIVATE); // -------------------------------------------------- // Impl class stuff // -------------------------------------------------- final JMethod implNavigateMethod = implementationClass.method(PUBLIC, Resource.class, "navigate"); final JVar implNavigateMethodKey = implNavigateMethod.param(FINAL, String.class, "key"); final JVar implNavigateMethodValue = implNavigateMethod.param(FINAL, String.class, "value"); final JBlock implNavigateMethodBody = implNavigateMethod.body(); implNavigateMethodBody._return(JExpr._null()); // todo // -------------------------------------------------- // Builder stuff // -------------------------------------------------- final JFieldVar builderClassParentField = builderClass.field(PRIVATE | FINAL, builderClassP, "parent"); final JMethod builderClassConstructor = builderClass.constructor(NONE); builderClassConstructor.body().assign(JExpr._this().ref(builderClassParentField), builderClassConstructor.param(FINAL, builderClassP, "parent")); builderClass.method(PUBLIC, builderClassP, "end").body()._return(builderClassParentField); final JMethod builderFactoryConstructMethod = builderFactoryClass.method(PUBLIC, builderClass.narrow(builderFactoryP), "construct"); builderFactoryConstructMethod.body()._return(JExpr._new(builderClass.narrow(builderFactoryP)).arg(builderFactoryConstructMethod.param(FINAL, builderFactoryP, "parent"))); if (parentType == null) { final JMethod coreBuildMethod = coreClass.method(PUBLIC | STATIC, builderFactoryClass, "build"); coreBuildMethod.javadoc().add("Introduce this resource type into a builder which supports nested polymorphic types."); coreBuildMethod.javadoc().add("Normally this method should not be directly invoked, but rather as part of a builder invocation chain."); coreBuildMethod.javadoc().addReturn().add("the appropriate builder factory"); final JTypeVar coreBuildMethodP = coreBuildMethod.generify("P"); coreBuildMethod.type(builderFactoryClass.narrow(coreBuildMethodP)); coreBuildMethod.body()._return(JExpr._new(builderFactoryClass.narrow(coreBuildMethodP))); } // -------------------------------------------------- // Resource parse/deparse methods // -------------------------------------------------- final JMethod parseMethod = parserClass.method(PUBLIC, deparser.VOID, "parse"); parseMethod._throws(deparser.ref(XMLStreamException.class)); final JVar parseMethodStreamReader = parseMethod.param(deparser.ref(XMLStreamReader.class), "streamReader"); final JVar parseMethodBuilder = parseMethod.param(builderInterface.narrow(deparser.wildcard()), "builder"); final JBlock parseMethodBody = parseMethod.body(); final JMethod deparseMethod = deparserClass.method(PUBLIC, deparser.VOID, "deparse"); deparseMethod._throws(deparser.ref(XMLStreamException.class)); final JVar deparseMethodStreamWriter = deparseMethod.param(deparser.ref(XMLStreamWriter.class), "streamWriter"); final JVar deparseMethodResource = deparseMethod.param(resourceInterface, "resource"); final JBlock deparseMethodBody = deparseMethod.body(); final JVar deparsePreComment = deparseMethodBody.decl(FINAL, deparser.ref(String.class), "preComment", JExpr.invoke(deparseMethodResource, "getPreComment")); final JVar deparsePostComment = deparseMethodBody.decl(FINAL, deparser.ref(String.class), "postComment", JExpr.invoke(deparseMethodResource, "getPostComment")); deparseMethodBody._if(deparsePreComment.ne(JExpr._null()))._then().invoke(deparseMethodStreamWriter, "writeComment").arg(deparsePreComment); deparseMethodBody.invoke(deparseMethodStreamWriter, "writeStartElement").arg(xmlNamespace).arg(xmlName); final JBlock deparseMethodAttributesBlock = deparseMethodBody.block(); final JBlock deparseMethodElementsBlock = deparseMethodBody.block(); deparseMethodBody._if(deparsePostComment.ne(JExpr._null()))._then().invoke(deparseMethodStreamWriter, "writeComment").arg(deparsePostComment); deparseMethodBody.invoke(deparseMethodStreamWriter, "writeEndElement"); // -------------------------------------------------- // Sub-resources // -------------------------------------------------- for (SubResourceBuilderImpl<?> resourceBuilder : resource.getSubResources()) { new ResourceWriter(resourceBuilder, docInfo, xmlNamespace, typeElement).generate(); } // -------------------------------------------------- // Attributes // -------------------------------------------------- class AttributeGenerator { final AttributeBuilderImpl<?> attributeBuilder; AttributeGenerator(final AttributeBuilderImpl<?> builder) { attributeBuilder = builder; } void generate() { // -------------------------------------------------- // Gather information about the attribute // -------------------------------------------------- final XmlRender.As as = attributeBuilder.getXmlRenderAs(); final boolean required = attributeBuilder.isRequired(); final String defaultValue = attributeBuilder.getDefaultValue(); final Access access = attributeBuilder.getAccess(); final List<DeclaredType> validators = attributeBuilder.getValidators(); final DeclaredType virtual = attributeBuilder.getVirtual(); final String name = attributeBuilder.getName(); final String attrVarName = fieldify(name); final String getterName; final String attrXmlName = def(attributeBuilder.getXmlName(), xmlify(name)); final TypeMirror attributeType = attributeBuilder.getType(); final JType attributeJType = CodeModelUtils.typeFor(env, deparser, attributeType); final JExpression defaultValueExpr = defaultValue == null ? null : JExpr._null(); // todo convert defaultValue if (attributeType.equals(types.getPrimitiveType(TypeKind.BOOLEAN))) { getterName = "is" + name; } else { getterName = "get" + name; } // -------------------------------------------------- // Add to XSD // -------------------------------------------------- if (as == XmlRender.As.ELEMENT) { final Element elem = new Element("xs:element", XSD); typeSeqElement.appendChild(elem); elem.addAttribute(new Attribute("name", attrXmlName)); elem.addAttribute(new Attribute("type", "???")); // todo XML type elem.addAttribute(new Attribute("minOccurs", required ? "1" : "0")); elem.addAttribute(new Attribute("maxOccurs", "1")); addDocumentation(elem, attributeBuilder.getRootDescription()); } else { assert as == XmlRender.As.ATTRIBUTE; final Element attr = new Element("xs:attribute", XSD); elementElement.appendChild(attr); attr.addAttribute(new Attribute("name", attrXmlName)); attr.addAttribute(new Attribute("type", "???"));// todo XML type attr.addAttribute(new Attribute("use", required ? "required" : "optional")); addDocumentation(attr, attributeBuilder.getRootDescription()); } // -------------------------------------------------- // Parser / Deparser // -------------------------------------------------- if (deparser.ref(VirtualAttribute.class).erasure() == null) { // ---------------------------------------------- // Deparser // ---------------------------------------------- if (as == XmlRender.As.ELEMENT) { // real attributes get persisted deparseMethodElementsBlock.invoke(deparseMethodStreamWriter, "writeStartElement").arg(JExpr.lit(xmlNamespace)).arg(JExpr.lit(xmlName)); // todo emit attribute content deparseMethodElementsBlock.invoke(deparseMethodStreamWriter, "writeEndElement"); } else { deparseMethodAttributesBlock.invoke(deparseMethodStreamWriter, "writeAttribute").arg(JExpr.lit(xmlName)).arg("...value..."); } // ---------------------------------------------- // Parser // ---------------------------------------------- } // -------------------------------------------------- // Generate impl class field, getter, & constructor param // -------------------------------------------------- final JMethod getterMethod = implementationClass.method(PUBLIC, attributeJType, getterName); final JBlock getterMethodBody = getterMethod.body(); if (access.isReadable()) { if (virtual != null) { // todo - cache virtual instances getterMethodBody._return(JExpr.invoke(JExpr._new(deparser.ref(VirtualAttribute.class).erasure().narrow(attributeJType)), "getValue")); } else { final JFieldVar field = implementationClass.field(PRIVATE | FINAL, attributeJType, attrVarName); implConstructorBody.assign(JExpr._this().ref(field), implConstructor.param(FINAL, attributeJType, attrVarName)); getterMethodBody._return(field); } } else { getterMethodBody._throw(deparser.ref(AbstractResource.class).staticInvoke("notReadable")); } // -------------------------------------------------- // Generate builder field and setter method // -------------------------------------------------- if (access.isWritable()) { final JMethod builderInterfaceSetMethod; final JMethod builderClassSetMethod; // todo - better classification needed if (attributeJType.erasure().fullName().equals("java.util.Map")) { final JClass attributeJClass = (JClass) attributeJType; final JClass keyType; final JClass valueType; if (attributeJClass.getTypeParameters().size() != 2) { keyType = valueType = deparser.ref(Object.class); } else { keyType = attributeJClass.getTypeParameters().get(0); valueType = attributeJClass.getTypeParameters().get(1); } if (true) { // value is a simple type final JClass listType = deparser.ref(ArrayList.class).narrow(deparser.ref(Entry.class).narrow(keyType, valueType)); final JFieldVar attributeField = builderClass.field(PRIVATE | FINAL, listType, attrVarName); attributeField.init(JExpr._new(listType)); builderInterfaceSetMethod = builderInterface.method(NONE, builderInterface.narrow(builderInterfaceP), "add" + GeneratorUtils.singular(name)); builderInterfaceSetMethod.param(keyType, "key"); builderInterfaceSetMethod.param(valueType, "value"); builderClassSetMethod = builderClass.method(PUBLIC, builderInterface.narrow(builderInterfaceP), "add" + GeneratorUtils.singular(name)); final JVar keyParam = builderClassSetMethod.param(FINAL, keyType, "key"); final JVar valueParam = builderClassSetMethod.param(FINAL, valueType, "value"); final JBlock body = builderClassSetMethod.body(); attributeField.invoke("add").arg(JExpr._new(deparser.ref(Entry.class).narrow(keyType, valueType)).arg(keyParam).arg(valueParam)); body._return(JExpr._this()); } else { // value is a complex (resource) type final String nestedBuilderTypeName = valueType.fullName() + "BuilderImpl"; final JClass nestedBuilderType = deparser._getClass(nestedBuilderTypeName); if (nestedBuilderType == null) { messager.printMessage(ERROR, "No builder was generated for non-simple attribute type " + nestedBuilderTypeName); return; } final JClass listType = deparser.ref(ArrayList.class).narrow(deparser.ref(Entry.class).narrow(keyType, nestedBuilderType)); final JFieldVar attributeField = builderClass.field(PRIVATE | FINAL, listType, attrVarName); attributeField.init(JExpr._new(listType)); final JClass narrowedBuilderType = nestedBuilderType.narrow(builderInterface.narrow(builderInterfaceP)); builderInterfaceSetMethod = builderInterface.method(NONE, narrowedBuilderType, "add" + GeneratorUtils.singular(name)); builderInterfaceSetMethod.param(keyType, "key"); builderClassSetMethod = builderClass.method(PUBLIC, narrowedBuilderType, "add" + GeneratorUtils.singular(name)); final JVar keyParam = builderClassSetMethod.param(FINAL, keyType, "key"); final JBlock body = builderClassSetMethod.body(); final JVar valueVar = body.decl(nestedBuilderType, "_builder", JExpr._new(narrowedBuilderType).arg(JExpr._this())); attributeField.invoke("add").arg(JExpr._new(deparser.ref(Entry.class).narrow(keyType, valueType)).arg(keyParam).arg(valueVar)); body._return(valueVar); } } else { // value is a simple type... // todo collections, sub-resources, attribute groups all need special builders final JFieldVar attributeField = builderClass.field(PRIVATE, attributeJType, attrVarName); if (defaultValueExpr != null) { attributeField.assign(defaultValueExpr); } builderInterfaceSetMethod = builderInterface.method(NONE, builderInterface.narrow(builderInterfaceP), attrVarName); builderClassSetMethod = builderClass.method(PUBLIC, builderInterface.narrow(builderInterfaceP), attrVarName); final JDocComment javadoc = builderInterfaceSetMethod.javadoc(); javadoc.add("Set the " + attributeBuilder.getRootDescription() + " for this resource."); if (required) { javadoc.add(" This attribute is required."); } else { javadoc.add(" This attribute is optional."); if (defaultValue != null) { javadoc.add(" If not specified, this attribute will default to \"" + defaultValue + "\"."); } } javadoc.addParam(attrVarName).append("the " + attributeBuilder.getRootDescription()); javadoc.addReturn().append("this builder"); // todo for complex types, we must deconstruct the type and create a method param for each component... builderInterfaceSetMethod.param(attributeJType, attrVarName); final JVar newValueParam = builderClassSetMethod.param(attributeJType, attrVarName); final JBlock body = builderClassSetMethod.body(); if (! validators.isEmpty()) { // -------------------------------------------------- // Emit validation block // -------------------------------------------------- final JVar context = body.decl(FINAL, deparser.ref(ExceptionThrowingValidationContext.class), "_context", JExpr._new(deparser.ref(ExceptionThrowingValidationContext.class))); for (DeclaredType validator : validators) { final JClass validatorType = (JClass) CodeModelUtils.typeFor(env, deparser, validator); // todo - cache validator instances final JInvocation inv = body.invoke(JExpr._new(validatorType.erasure().narrow(resourceInterface, attributeJType.boxify())), "validate"); inv.arg(JExpr._null()); // TODO - no resource yet...? inv.arg(JExpr.lit(attrVarName)); inv.arg(JExpr._null()); inv.arg(newValueParam); inv.arg(context); } body.invoke(context, "throwProblems"); } body.assign(attributeField, newValueParam); body._return(JExpr._this()); } } } } for (AttributeBuilderImpl<?> attributeBuilder : resource.getAttributes()) { new AttributeGenerator(attributeBuilder).generate(); } } } private static <T> T def(T test, T def) { return test == null ? def : test; } private static String xmlify(String camelHumpsName) { final int length = camelHumpsName.length(); final StringBuilder builder = new StringBuilder(length + length >> 1); int idx = 0; int c = camelHumpsName.codePointAt(idx), n; boolean wordDone = false; for (;;) { idx = camelHumpsName.offsetByCodePoints(idx, 1); if (idx < length) { n = camelHumpsName.codePointAt(idx); if (Character.isLowerCase(c) && Character.isUpperCase(n)) { builder.appendCodePoint(c); wordDone = true; } else if (builder.length() > 0 && Character.isUpperCase(c) && Character.isLowerCase(n) || wordDone) { builder.append('-'); builder.appendCodePoint(Character.toLowerCase(c)); wordDone = false; } else { builder.appendCodePoint(Character.toLowerCase(c)); } c = n; continue; } else { builder.appendCodePoint(Character.toLowerCase(c)); return builder.toString(); } } } private static String fieldify(String camelHumpsName) { final int length = camelHumpsName.length(); final StringBuilder builder = new StringBuilder(length); int idx = 0; int c = camelHumpsName.codePointAt(idx), n; if (Character.isLowerCase(c)) { return camelHumpsName; } builder.appendCodePoint(Character.toLowerCase(c)); idx = camelHumpsName.offsetByCodePoints(idx, 1); c = camelHumpsName.codePointAt(idx); for (;;) { idx = camelHumpsName.offsetByCodePoints(idx, 1); if (idx < length) { n = camelHumpsName.codePointAt(idx); if (Character.isLowerCase(n)) { // next is lowercase; we're done builder.appendCodePoint(c); builder.append(camelHumpsName.substring(idx)); return builder.toString(); } else { builder.appendCodePoint(Character.toLowerCase(c)); c = n; } } else { builder.appendCodePoint(Character.toLowerCase(c)); return builder.toString(); } } } private static String buildNamespace(final Schema.Kind kind, final String namespace, final String version) { StringBuilder b = new StringBuilder(64); if (kind == Schema.Kind.SYSTEM) { b.append("sys:"); } else { b.append("ext:"); } b.append(namespace).append(':').append(version); return b.toString(); } private static void addDocumentation(final Element element, final String documentation) { final Element annotation = new Element("xs:annotation", XSD); element.appendChild(annotation); final Element documentationElement = new Element("xs:documentation", XSD); annotation.appendChild(documentationElement); documentationElement.appendChild(documentation); } */}
4b5d4d62c9e01b1684f841bb37a93b41bde27154
4609c0869901fabd41a3928632d5d75e6ba62a67
/Addition.java
d6e7a0f1f5f647ad339d060820b7a1bcc4f7854e
[]
no_license
julielaursen/JavaFXScripts
fbaa3223c589c733dce9ba680753e84abfb1c6a3
9cc677537195320dd5cae5ab602d9bcac8cb9fd1
refs/heads/master
2020-03-29T11:12:43.919449
2018-10-15T00:14:08
2018-10-15T00:14:08
149,841,441
0
0
null
2018-09-24T02:01:15
2018-09-22T03:20:56
Java
UTF-8
Java
false
false
1,102
java
package application; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Addition extends Application { @Override public void start(Stage primaryStage) throws Exception{ // Button btn = new Button("Calculate"); //btn.setOnAction(new EventHandler<ActionEvent>(){ // // @Override //public void handle(ActionEvent event) { // System.out.println("Hello world"); ///} //}); try { Parent root = FXMLLoader.load(getClass().getResource("/application/Main.fxml")); Scene scene = new Scene(root, 500, 300); primaryStage.setTitle("Addition"); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
f6fd79b62914d4230ee940cd512f1a2ce4a9ac32
73b9ca4bb1078061a6a56c015d476745f608474f
/src/main/java/com/cpm/upload/UploadAllImageActivity.java
57dfbf6c1ef2e66e2e9cd524b7ef087691b859cf
[]
no_license
YadavendraSinghYaduvanshi/VOTOMobile
775dc9a143e5bdfe98d92df8ae2f8ad3ee37f3ef
1cdf67e98d5fe2f5eda5a7e94c9be9ee26bcd912
refs/heads/master
2021-06-28T18:00:55.591923
2017-09-13T10:22:34
2017-09-13T10:22:34
103,385,358
0
0
null
null
null
null
UTF-8
Java
false
false
23,794
java
package com.cpm.upload; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.util.ArrayList; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.WindowManager; import android.widget.ProgressBar; import android.widget.TextView; import com.cpm.Constants.CommonString; import com.cpm.database.GSKDatabase; import com.cpm.delegates.CoverageBean; import com.cpm.capitalfoods.R; import com.cpm.message.AlertMessage; import com.cpm.xmlGetterSetter.AssetInsertdataGetterSetter; import com.cpm.xmlGetterSetter.FailureGetterSetter; import com.cpm.xmlGetterSetter.POIGetterSetter; import com.cpm.xmlGetterSetter.PromotionInsertDataGetterSetter; import com.cpm.xmlGetterSetter.StockNewGetterSetter; import com.cpm.xmlHandler.FailureXMLHandler; public class UploadAllImageActivity extends Activity { private Dialog dialog; private ProgressBar pb; private TextView percentage, message; private String visit_date; private SharedPreferences preferences; private GSKDatabase database; private int factor, k; private FailureGetterSetter failureGetterSetter = null; String result, username; String datacheck = ""; String[] words; String validity, storename; String mid = ""; String errormsg = ""; static int counter = 1; String Path,status; private ArrayList<CoverageBean> coverageBeanlist = new ArrayList<CoverageBean>(); private ArrayList<AssetInsertdataGetterSetter> assetInsertdata = new ArrayList<AssetInsertdataGetterSetter>(); private ArrayList<PromotionInsertDataGetterSetter> promotionData = new ArrayList<PromotionInsertDataGetterSetter>(); private ArrayList<POIGetterSetter> poiInsertdata = new ArrayList<POIGetterSetter>(); ArrayList<StockNewGetterSetter> stockImgData = new ArrayList<StockNewGetterSetter>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); preferences = PreferenceManager.getDefaultSharedPreferences(this); visit_date = preferences.getString(CommonString.KEY_DATE, null); username = preferences.getString(CommonString.KEY_USERNAME, null); database = new GSKDatabase(this); database.open(); Path= Environment.getExternalStorageDirectory() + "/CapitalFoods_Images/"; new UploadTask(this).execute(); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); // database.close(); } private class UploadTask extends AsyncTask<Void, Void, String> { private Context context; UploadTask(Context context) { this.context = context; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog = new Dialog(context); dialog.setContentView(R.layout.custom_upload); dialog.setTitle("Uploading Image"); dialog.setCancelable(false); dialog.show(); pb = (ProgressBar) dialog.findViewById(R.id.progressBar1); percentage = (TextView) dialog.findViewById(R.id.percentage); message = (TextView) dialog.findViewById(R.id.message); } @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub try { coverageBeanlist=database.getCoverageData(visit_date); if(coverageBeanlist.size()>0){ for(int i=0;i<coverageBeanlist.size();i++){ status=coverageBeanlist.get(i).getStatus(); if(status.equals(CommonString.STORE_STATUS_LEAVE)){ String path=coverageBeanlist.get(i).getImage(); if(path!=null && !path.equals("")){ result = UploadImage(path); } else{ result = CommonString.KEY_SUCCESS; } } assetInsertdata = database.getAssetUpload(coverageBeanlist.get(i).getStoreId()); if (assetInsertdata.size()>0) { for (int j = 0; j < assetInsertdata.size(); j++) { if (assetInsertdata.get(j).getImg() != null && !assetInsertdata.get(j) .getImg().equals("")) { if (new File( Environment.getExternalStorageDirectory() + "/CapitalFoods_Images/" + assetInsertdata.get(j).getImg()) .exists()) { result = UploadAssetImage(assetInsertdata.get(j).getImg()); if (result .toString() .equalsIgnoreCase( CommonString.KEY_FALSE)) { return "Asset Images"; } else if (result .equalsIgnoreCase(CommonString.KEY_FAILURE)) { return "Asset Images" + "," + errormsg; } runOnUiThread(new Runnable() { public void run() { message.setText("Asset Images Uploaded"); } }); } } } } promotionData = database.getPromotionUpload(coverageBeanlist.get(i).getStoreId()); if (promotionData.size()>0) { for (int j = 0; j < promotionData.size(); j++) { if (promotionData.get(j).getImg() != null && !promotionData.get(j) .getImg().equals("")) { if (new File( Environment.getExternalStorageDirectory() + "/CapitalFoods_Images/" + promotionData.get(j).getImg()) .exists()) { result = UploadPromotionImage(promotionData.get(j).getImg()); if (result .toString() .equalsIgnoreCase( CommonString.KEY_FALSE)) { return "Asset Images"; } else if (result .equalsIgnoreCase(CommonString.KEY_FAILURE)) { return "Asset Images" + "," + errormsg; } runOnUiThread(new Runnable() { public void run() { message.setText("Asset Images Uploaded"); } }); } } } } poiInsertdata = database.getPOIData(coverageBeanlist.get(i).getStoreId()); if (poiInsertdata.size()>0) { for (int j = 0; j < poiInsertdata.size(); j++) { if (poiInsertdata.get(j).getImage() != null && !poiInsertdata.get(j) .getImage().equals("")) { if (new File( Environment.getExternalStorageDirectory() + "/CapitalFoods_Images/" + poiInsertdata.get(j).getImage()) .exists()) { result = UploadPOIImage(poiInsertdata.get(j).getImage()); if (result .toString() .equalsIgnoreCase( CommonString.KEY_FALSE)) { return "POI Images"; } else if (result .equalsIgnoreCase(CommonString.KEY_FAILURE)) { return "POI Images" + "," + errormsg; } runOnUiThread(new Runnable() { public void run() { message.setText("POI Images Uploaded"); } }); } } } } stockImgData = database.getHeaderStockImageData(coverageBeanlist.get(i).getStoreId(), visit_date); if (stockImgData.size()>0) { for (int j = 0; j < stockImgData.size(); j++) { if (stockImgData.get(j).getImg_cam() != null && !stockImgData.get(j) .getImg_cam().equals("")) { if (new File( Environment.getExternalStorageDirectory() + "/CapitalFoods_Images/" + stockImgData.get(j).getImg_cam()) .exists()) { result = UploadStockImage(stockImgData.get(j).getImg_cam()); if (result .toString() .equalsIgnoreCase( CommonString.KEY_FALSE)) { return "Stock Images"; } else if (result .equalsIgnoreCase(CommonString.KEY_FAILURE)) { return "Stock Images" + "," + errormsg; } runOnUiThread(new Runnable() { public void run() { message.setText("Stock Images Uploaded"); } }); } } } } return CommonString.KEY_SUCCESS; } } } catch (MalformedURLException e) { final AlertMessage message = new AlertMessage( UploadAllImageActivity.this, AlertMessage.MESSAGE_EXCEPTION, "socket_uploadimagesall", e); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub message.showMessage(); } }); } catch (IOException e) { final AlertMessage message = new AlertMessage( UploadAllImageActivity.this, AlertMessage.MESSAGE_SOCKETEXCEPTION, "socket_uploadimagesall", e); counter++; runOnUiThread(new Runnable() { @Override public void run() { message.showMessage(); // TODO Auto-generated method stub /* * if (counter < 3) { new * UploadTask(UploadAllImageActivity.this).execute(); } * else { message.showMessage(); counter = 1; } */ } }); } catch (Exception e) { final AlertMessage message = new AlertMessage( UploadAllImageActivity.this, AlertMessage.MESSAGE_EXCEPTION, "socket_uploadimagesall", e); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub message.showMessage(); } }); } return ""; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); dialog.dismiss(); if (result.equals(CommonString.KEY_SUCCESS)) { database.open(); database.deleteAllTables(); AlertMessage message = new AlertMessage( UploadAllImageActivity.this, AlertMessage.MESSAGE_UPLOAD_IMAGE, "success", null); message.showMessage(); } else if (!result.equals("")) { AlertMessage message = new AlertMessage( UploadAllImageActivity.this, result, "success", null); message.showMessage(); } } public String UploadImage(String path) throws Exception { errormsg = ""; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(Path + path, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile( Path + path, o2); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); String ba1 = Base64.encodeBytes(ba); SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_IMAGE); String[] split = path.split("/"); String path1 = split[split.length - 1]; request.addProperty("img", ba1); request.addProperty("name", path1); request.addProperty("FolderName", "StoreImages"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( CommonString.URL); androidHttpTransport .call(CommonString.SOAP_ACTION_UPLOAD_IMAGE, envelope); Object result = (Object) envelope.getResponse(); if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) { return CommonString.KEY_FALSE; } SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // for failure FailureXMLHandler failureXMLHandler = new FailureXMLHandler(); xmlR.setContentHandler(failureXMLHandler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(result.toString())); xmlR.parse(is); failureGetterSetter = failureXMLHandler .getFailureGetterSetter(); if (failureGetterSetter.getStatus().equalsIgnoreCase( CommonString.KEY_FAILURE)) { errormsg = failureGetterSetter.getErrorMsg(); return CommonString.KEY_FAILURE; } } else { new File(Path + path).delete(); } return ""; } public String UploadPromotionImage(String path) throws Exception { errormsg = ""; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(Path + path, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile( Path + path, o2); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); String ba1 = Base64.encodeBytes(ba); SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_IMAGE); String[] split = path.split("/"); String path1 = split[split.length - 1]; request.addProperty("img", ba1); request.addProperty("name", path1); request.addProperty("FolderName", "PromotionImages"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( CommonString.URL); androidHttpTransport .call(CommonString.SOAP_ACTION_UPLOAD_IMAGE, envelope); Object result = (Object) envelope.getResponse(); if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) { return CommonString.KEY_FALSE; } SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // for failure FailureXMLHandler failureXMLHandler = new FailureXMLHandler(); xmlR.setContentHandler(failureXMLHandler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(result.toString())); xmlR.parse(is); failureGetterSetter = failureXMLHandler .getFailureGetterSetter(); if (failureGetterSetter.getStatus().equalsIgnoreCase( CommonString.KEY_FAILURE)) { errormsg = failureGetterSetter.getErrorMsg(); return CommonString.KEY_FAILURE; } } else { new File(Path + path).delete(); } return ""; } public String UploadAssetImage(String path) throws Exception { errormsg = ""; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(Path + path, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile( Path + path, o2); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); String ba1 = Base64.encodeBytes(ba); SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_IMAGE); String[] split = path.split("/"); String path1 = split[split.length - 1]; request.addProperty("img", ba1); request.addProperty("name", path1); request.addProperty("FolderName", "AssetImages"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( CommonString.URL); androidHttpTransport .call(CommonString.SOAP_ACTION_UPLOAD_IMAGE, envelope); Object result = (Object) envelope.getResponse(); if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) { return CommonString.KEY_FALSE; } SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // for failure FailureXMLHandler failureXMLHandler = new FailureXMLHandler(); xmlR.setContentHandler(failureXMLHandler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(result.toString())); xmlR.parse(is); failureGetterSetter = failureXMLHandler .getFailureGetterSetter(); if (failureGetterSetter.getStatus().equalsIgnoreCase( CommonString.KEY_FAILURE)) { errormsg = failureGetterSetter.getErrorMsg(); return CommonString.KEY_FAILURE; } } else { new File(Path + path).delete(); } return ""; } public String UploadPOIImage(String path) throws Exception { errormsg = ""; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(Path + path, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile( Path + path, o2); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); String ba1 = Base64.encodeBytes(ba); SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_IMAGE); String[] split = path.split("/"); String path1 = split[split.length - 1]; request.addProperty("img", ba1); request.addProperty("name", path1); request.addProperty("FolderName", "POIImages"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( CommonString.URL); androidHttpTransport .call(CommonString.SOAP_ACTION_UPLOAD_IMAGE, envelope); Object result = (Object) envelope.getResponse(); if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) { return CommonString.KEY_FALSE; } SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // for failure FailureXMLHandler failureXMLHandler = new FailureXMLHandler(); xmlR.setContentHandler(failureXMLHandler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(result.toString())); xmlR.parse(is); failureGetterSetter = failureXMLHandler .getFailureGetterSetter(); if (failureGetterSetter.getStatus().equalsIgnoreCase( CommonString.KEY_FAILURE)) { errormsg = failureGetterSetter.getErrorMsg(); return CommonString.KEY_FAILURE; } } else { new File(Path + path).delete(); } return ""; } public String UploadStockImage(String path) throws Exception { errormsg = ""; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(Path + path, o); // The new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile( Path + path, o2); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] ba = bao.toByteArray(); String ba1 = Base64.encodeBytes(ba); SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_IMAGE); String[] split = path.split("/"); String path1 = split[split.length - 1]; request.addProperty("img", ba1); request.addProperty("name", path1); request.addProperty("FolderName", "StockImages"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( CommonString.URL); androidHttpTransport .call(CommonString.SOAP_ACTION_UPLOAD_IMAGE, envelope); Object result = (Object) envelope.getResponse(); if (!result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) { if (result.toString().equalsIgnoreCase(CommonString.KEY_FALSE)) { return CommonString.KEY_FALSE; } SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // for failure FailureXMLHandler failureXMLHandler = new FailureXMLHandler(); xmlR.setContentHandler(failureXMLHandler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(result.toString())); xmlR.parse(is); failureGetterSetter = failureXMLHandler .getFailureGetterSetter(); if (failureGetterSetter.getStatus().equalsIgnoreCase( CommonString.KEY_FAILURE)) { errormsg = failureGetterSetter.getErrorMsg(); return CommonString.KEY_FAILURE; } } else { new File(Path + path).delete(); } return ""; } } }
42f418b938c07f08f21a12b04388d481c0daadde
98ea4160cf0e7815e5a7706f44258e21060bc9ea
/src/main/java/pl/companymanagementhelper/domain/address/AddressRepository.java
8142023502dd38622a9e94027d0b5da834819250
[]
no_license
Mehip/CMH
f03204b92b2825f2ed57b9bb1170d71565e09022
d27fdfa03d66e46d5cd9bc8dd45e65e4dee83e8e
refs/heads/master
2022-12-02T15:42:00.489790
2020-08-26T16:36:34
2020-08-26T16:36:34
286,276,955
0
0
null
null
null
null
UTF-8
Java
false
false
253
java
package pl.companymanagementhelper.domain.address; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface AddressRepository extends JpaRepository<Address, Long> { }
bde2d2a2b7fc3e4b2835823d11c386e704aec73b
d4146d689fdea5efd317dcdc35b682b645526b0c
/day1103/thread/BarThread.java
8b2e3790bc3ad061e33271283afd01a43059c3e3
[]
no_license
dyd1047/java_workspace
67f4015eefffed758bc1d876056f5094afd4a403
789900d6c767cf90557fae989d39641458bfee65
refs/heads/master
2023-01-15T10:31:18.707280
2020-11-20T09:04:53
2020-11-20T09:04:53
305,318,310
0
0
null
null
null
null
UTF-8
Java
false
false
603
java
package day1103.thread; import javax.swing.JProgressBar; public class BarThread extends Thread{ int n; int interval; JProgressBar bar; //이 쓰레드를 이용하고자 하는 자는, 바를 넘기시오 public BarThread(JProgressBar bar, int interval) { this.bar = bar; this.interval = interval; } @Override public void run() { while(true) { n++; bar.setValue(n); try { Thread.sleep(interval); //non-runnable 에 빠져있다가 0.5초 뒤 복귀하라는 명령 } catch (InterruptedException e) { e.printStackTrace(); } } } }
76ef2f70d35265b0170d16ccf14d9a9b0a52a71a
8312ca5c4472121cc2a08d0a869c7955799f5bf4
/kite-data/kite-data-core/src/test/java/org/kitesdk/data/event/ReflectStandardEvent.java
fb8dcd5b200254a65d0fbc5cacbf631a70c65536
[ "Apache-2.0" ]
permissive
carlosmarin/kite
5a8250d6e7131a9e026862603b6c055fce4382f3
f6fb3fa2cf8396f165a5811f34f62152d6c5da13
refs/heads/main
2023-06-02T04:53:26.570703
2021-06-18T16:29:59
2021-06-18T16:29:59
378,196,535
0
0
Apache-2.0
2021-06-18T15:42:16
2021-06-18T15:42:16
null
UTF-8
Java
false
false
3,473
java
/* * Copyright 2014 Cloudera, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.event; import com.google.common.base.Objects; public class ReflectStandardEvent { /** * Where the event was triggered from in the format * {client,server}_{user,app}, e.g. 'client_user'. Required. */ private String event_initiator; /** * A hierarchical name for the event, with parts separated by ':'. Required. */ private String event_name; /** * A unique identifier for the user. Required. */ private long user_id; /** * A unique identifier for the session. Required. */ private String session_id; /** * The IP address of the host where the event originated. Required. */ private String ip; /** * The point in time when the event occurred, represented as the number of * milliseconds since January 1, 1970, 00:00:00 GMT. Required. */ private long timestamp; public ReflectStandardEvent() { } public ReflectStandardEvent(StandardEvent event) { setEvent_initiator(event.getEventInitiator()); setEvent_name(event.getEventName()); setIp(event.getIp()); setSession_id(event.getSessionId()); setTimestamp(event.getTimestamp()); setUser_id(event.getUserId()); } public String getEvent_initiator() { return event_initiator; } public final void setEvent_initiator(String event_initiator) { this.event_initiator = event_initiator; } public String getEvent_name() { return event_name; } public final void setEvent_name(String event_name) { this.event_name = event_name; } public String getIp() { return ip; } public final void setIp(String ip) { this.ip = ip; } public String getSession_id() { return session_id; } public final void setSession_id(String session_id) { this.session_id = session_id; } public long getTimestamp() { return timestamp; } public final void setTimestamp(long timestamp) { this.timestamp = timestamp; } public long getUser_id() { return user_id; } public final void setUser_id(long user_id) { this.user_id = user_id; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !Objects.equal(getClass(), obj.getClass())) { return false; } final ReflectStandardEvent other = (ReflectStandardEvent) obj; return Objects.equal(this.getEvent_initiator(), other.getEvent_initiator()) && Objects.equal(this.getEvent_name(), other.getEvent_name()) && Objects.equal(this.getIp(), other.getIp()) && Objects.equal(this.getSession_id(), other.getSession_id()) && Objects.equal(this.getTimestamp(), other.getTimestamp()) && Objects.equal(this.getUser_id(), other.getUser_id()); } @Override public int hashCode() { return Objects.hashCode(getEvent_initiator(), getEvent_name(), getIp(), getSession_id(), getTimestamp(), getUser_id()); } }
e26b16b695d0417d159ff57d81bddf06230df67c
d2860fce140826afeff66893e3f1c129224aa05b
/src/Debugging/FixDebugFive2.java
0bf6a920f37b5a5efeb846a2314d4eb754f9cef4
[]
no_license
ac116232/chapter-5
6e8a4df39cba527b1703984c25537a41ebe4721c
5a5e1283ff3144d338d373cde86227dcae604642
refs/heads/master
2020-03-30T09:56:11.917972
2018-10-01T14:06:25
2018-10-01T14:06:25
151,098,615
0
0
null
null
null
null
UTF-8
Java
false
false
700
java
package Debugging; import java.util.Scanner; public class FixDebugFive2 { public static void main(String[] args) { // TODO Auto-generated method stub int num; int num2; @SuppressWarnings("resource") Scanner input = new Scanner(System.in); System.out.print("Enter a number "); num = input.nextInt(); System.out.print("Enter another number "); num2 = (int) input.nextDouble(); if((num % num2 <= 0) | (num2 / num) <= 0); System.out.println("One of these numbers is evenly divisible into the other"); System.out.println("Neither of these numbers is evenly divisible into the other"); } }
a9b5691c3fafe307868a23fecc979d918096401c
58417a458f922317d0b35b57597a82a198bc4351
/bukkit-legacy/loader/src/main/java/me/lucko/luckperms/bukkit/loader/BukkitLegacyLoaderPlugin.java
b843f1f737d1af776704140e6b8e878aff54c5d3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LuckPerms/LuckPerms
72358e677669fd767b2ac24ca7483f828e93e000
f12d3cd8ba47fb0d25f7c13e1f3a89d770bd34a6
refs/heads/master
2023-08-15T01:31:25.175005
2023-08-05T09:49:57
2023-08-05T09:49:57
59,388,335
601
247
MIT
2023-09-05T08:59:16
2016-05-22T00:49:12
Java
UTF-8
Java
false
false
2,211
java
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * Copyright (c) contributors * * 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 me.lucko.luckperms.bukkit.loader; import me.lucko.luckperms.common.loader.JarInJarClassLoader; import me.lucko.luckperms.common.loader.LoaderBootstrap; import org.bukkit.plugin.java.JavaPlugin; public class BukkitLegacyLoaderPlugin extends JavaPlugin { private static final String JAR_NAME = "luckperms-bukkitlegacy.jarinjar"; private static final String BOOTSTRAP_CLASS = "me.lucko.luckperms.bukkit.LPBukkitBootstrap"; private final LoaderBootstrap plugin; public BukkitLegacyLoaderPlugin() { JarInJarClassLoader loader = new JarInJarClassLoader(getClass().getClassLoader(), JAR_NAME); this.plugin = loader.instantiatePlugin(BOOTSTRAP_CLASS, JavaPlugin.class, this); } @Override public void onLoad() { this.plugin.onLoad(); } @Override public void onEnable() { this.plugin.onEnable(); } @Override public void onDisable() { this.plugin.onDisable(); } }
d0cfd8bae9f0e5199e03b30197ff1509974cd69b
9d963cafe49067766b40f247e4c88f8f89402a39
/src/main/java/com/houjiahui/core/security/UsernamePasswordToken.java
43066fea9a6ab159714ee1fc0ed8c1115a9042aa
[]
no_license
houjiahui90/DyingWish
be1ce83ba1ff8562ae9e0be3f79f09a621c0cd33
ebf540fe835adb719aae346740fdc9d835f099d1
refs/heads/master
2020-03-22T07:06:08.971866
2018-07-04T06:30:01
2018-07-04T06:30:01
139,463,971
0
0
null
null
null
null
UTF-8
Java
false
false
922
java
/** * Copyright &copy; 2015-2020 <a href="http://www.nxzhxt.com/">nxzhxt</a> All rights reserved. */ package com.houjiahui.core.security; /** * 用户和密码(包含验证码)令牌类 * @author nxzhxt * @version 2016-5-19 */ public class UsernamePasswordToken extends org.apache.shiro.authc.UsernamePasswordToken { private static final long serialVersionUID = 1L; private String captcha; private boolean mobileLogin; public UsernamePasswordToken() { super(); } public UsernamePasswordToken(String username, char[] password, boolean rememberMe, String host, String captcha, boolean mobileLogin) { super(username, password, rememberMe, host); this.captcha = captcha; this.mobileLogin = mobileLogin; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } public boolean isMobileLogin() { return mobileLogin; } }
d8cadcbabac405485581fed58f14d67b61277d40
0d1835c1fbfe08dad1d59cd1f6261e706146e609
/CardioMRI/src/com/pixelmed/dicom/GeometryOfVolumeFromAttributeList.java
dc182a92f5e4008175f01d84536ee2f045733e52
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
inevitably2484848/MRI
c57dc4313b06f47796e7ac6b200485b20af04d66
2185d5a9dcbe4cca09dcce49d43b77df35677f84
refs/heads/master
2021-01-14T08:25:25.978877
2016-04-27T19:31:10
2016-04-27T19:31:10
29,896,364
2
2
null
2015-11-30T23:39:51
2015-01-27T03:53:59
Java
UTF-8
Java
false
false
9,917
java
/* Copyright (c) 2001-2013, David A. Clunie DBA Pixelmed Publishing. All rights reserved. */ package com.pixelmed.dicom; import javax.vecmath.*; import com.pixelmed.geometry.*; import java.util.SortedSet; /** * <p>A class to extract and describe the spatial geometry of an entire volume of contiguous cross-sectional image slices, given a list of DICOM attributes.</p> * * @author dclunie */ public class GeometryOfVolumeFromAttributeList extends GeometryOfVolume { private static final String identString = "@(#) $Header: /userland/cvs/pixelmed/imgbook/com/pixelmed/dicom/GeometryOfVolumeFromAttributeList.java,v 1.14 2013/10/16 16:08:58 dclunie Exp $"; /** * <p>Construct the geometry from the Per-frame and Shared Functional Group Sequences * of a subset of frames of a multi-frame object, or from the Image Plane Module and related attributes, * if there is only a single frame of a non-multi-frame object.</p> * * @param list the list of DICOM attributes * @param subsetOfFrames the subset of frames to include or null if entire set */ public GeometryOfVolumeFromAttributeList(AttributeList list,int[] subsetOfFrames) throws DicomException { //System.err.println("GeometryOfVolumeFromAttributeList:"); frames=null; isVolume=false; int rows = Attribute.getSingleIntegerValueOrDefault(list,TagFromName.Rows,0); int columns = Attribute.getSingleIntegerValueOrDefault(list,TagFromName.Columns,0); SequenceAttribute sharedFunctionalGroupsSequence = (SequenceAttribute)(list.get(TagFromName.SharedFunctionalGroupsSequence)); SequenceAttribute perFrameFunctionalGroupsSequence = (SequenceAttribute)(list.get(TagFromName.PerFrameFunctionalGroupsSequence)); int numberOfFrames = Attribute.getSingleIntegerValueOrDefault(list,TagFromName.NumberOfFrames,1); int subsetNumberOfFrames = subsetOfFrames == null ? numberOfFrames : subsetOfFrames.length; if (numberOfFrames == 1 && sharedFunctionalGroupsSequence == null && perFrameFunctionalGroupsSequence == null && list.containsKey(TagFromName.ImagePositionPatient)) { //System.err.println("GeometryOfVolumeFromAttributeList: single frame with no functional groups and ImagePositionPatient"); // possibly old-fashioned single frame DICOM image GeometryOfSlice frame = null; try { frame = new GeometryOfSliceFromAttributeList(list); } catch (Exception e) { // don't print exception, because it is legitimate for (some or all) images to be missing this information //e.printStackTrace(System.err); frame=null; } if (frame != null) { frames = new GeometryOfSlice[1]; frames[0] = frame; } } else if (subsetNumberOfFrames > 0 && sharedFunctionalGroupsSequence != null && perFrameFunctionalGroupsSequence != null) { //System.err.println("GeometryOfVolumeFromAttributeList: multi frame with functional groups"); SequenceAttribute sharedPlaneOrientationSequence = (SequenceAttribute)(SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( sharedFunctionalGroupsSequence,TagFromName.PlaneOrientationSequence)); SequenceAttribute sharedPlanePositionSequence = (SequenceAttribute)(SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( sharedFunctionalGroupsSequence,TagFromName.PlanePositionSequence)); SequenceAttribute sharedPixelMeasuresSequence = (SequenceAttribute)(SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( sharedFunctionalGroupsSequence,TagFromName.PixelMeasuresSequence)); frames = new GeometryOfSlice[subsetNumberOfFrames]; for (int subsetFrame=0; subsetFrame<subsetNumberOfFrames; ++subsetFrame) { int parentFrame = subsetOfFrames == null ? subsetFrame : subsetOfFrames[subsetFrame]; Attribute aImageOrientationPatient = null; SequenceAttribute usePlaneOrientationSequence = sharedPlaneOrientationSequence; if (usePlaneOrientationSequence == null) { usePlaneOrientationSequence = (SequenceAttribute)( perFrameFunctionalGroupsSequence.getItem(parentFrame).getAttributeList().get(TagFromName.PlaneOrientationSequence)); } if (usePlaneOrientationSequence != null) { aImageOrientationPatient = SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( usePlaneOrientationSequence,TagFromName.ImageOrientationPatient); //System.err.println("GeometryOfVolumeFromAttributeList: "+aImageOrientationPatient); } Attribute aImagePositionPatient = null; SequenceAttribute usePlanePositionSequence = sharedPlanePositionSequence; if (usePlanePositionSequence == null) { usePlanePositionSequence = (SequenceAttribute)( perFrameFunctionalGroupsSequence.getItem(parentFrame).getAttributeList().get(TagFromName.PlanePositionSequence)); } if (usePlanePositionSequence != null) { aImagePositionPatient = SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( usePlanePositionSequence,TagFromName.ImagePositionPatient); //System.err.println("GeometryOfVolumeFromAttributeList: "+aImagePositionPatient); } Attribute aPixelSpacing = null; Attribute aSliceThickness = null; SequenceAttribute usePixelMeasuresSequence = sharedPixelMeasuresSequence; if (usePixelMeasuresSequence == null) { usePixelMeasuresSequence = (SequenceAttribute)( perFrameFunctionalGroupsSequence.getItem(parentFrame).getAttributeList().get(TagFromName.PixelMeasuresSequence)); } if (usePixelMeasuresSequence != null) { aPixelSpacing = SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( usePixelMeasuresSequence,TagFromName.PixelSpacing); aSliceThickness = SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( usePixelMeasuresSequence,TagFromName.SliceThickness); //System.err.println("GeometryOfVolumeFromAttributeList: "+aPixelSpacing); //System.err.println("GeometryOfVolumeFromAttributeList: "+aSliceThickness); } if (aImagePositionPatient != null && aPixelSpacing != null && aImageOrientationPatient != null) { double[] tlhc = aImagePositionPatient.getDoubleValues(); double [] pixelSpacingArray = aPixelSpacing.getDoubleValues(); double [] voxelSpacingArray = new double[3]; voxelSpacingArray[0] = pixelSpacingArray[0]; voxelSpacingArray[1] = pixelSpacingArray[1]; voxelSpacingArray[2] = 0; // set later by checkAndSetVolumeSampledRegularlyAlongFrameDimension() IFF a volume double sliceThickness = (aSliceThickness == null ? 0.0 : aSliceThickness.getSingleDoubleValueOrDefault(0.0)); double[] orientation = aImageOrientationPatient.getDoubleValues(); double[] row = new double[3]; row[0]=orientation[0]; row[1]=orientation[1]; row[2]=orientation[2]; double[] column = new double[3]; column[0]=orientation[3]; column[1]=orientation[4]; column[2]=orientation[5]; double[] dimensions = new double[3]; dimensions[0] = rows; dimensions[1] = columns; dimensions[2] = 1; frames[subsetFrame] = new GeometryOfSlice(row,column,tlhc,voxelSpacingArray,sliceThickness,dimensions); } else { //frames[i] = null; frames = null; // abandon effort to extract volume geometry if all frames can't be used break; } } } checkAndSetVolumeSampledRegularlyAlongFrameDimension(); } /** * <p>Construct the geometry from the Per-frame and Shared Functional Group Sequences * of a multi-frame object, or from the Image Plane Module and related attributes, * if there is only a single frame of a non-multi-frame object.</p> * * @param list the list of DICOM attributes */ public GeometryOfVolumeFromAttributeList(AttributeList list) throws DicomException { this(list,null); } /** * <p>Retrieve the ImageOrientationPatient values if the same for all frames or a single frame conventional object.</p> * * @param list the top level attribute list for the object * @return a double array of six values, or null if not present or not shared */ public static double[] getImageOrientationPatientFromAttributeList(AttributeList list) { //System.err.println("GeometryOfVolumeFromAttributeList.getImageOrientationPatientFromAttributeList():"); double[] vImageOrientationPatient = null; try { Attribute aImageOrientationPatient = null; SequenceAttribute sharedFunctionalGroupsSequence = (SequenceAttribute)(list.get(TagFromName.SharedFunctionalGroupsSequence)); int numberOfFrames = Attribute.getSingleIntegerValueOrDefault(list,TagFromName.NumberOfFrames,0); if (numberOfFrames == 1 && sharedFunctionalGroupsSequence == null) { // possibly old-fashioned single frame DICOM image aImageOrientationPatient=list.get(TagFromName.ImageOrientationPatient); } else if (numberOfFrames > 0 && sharedFunctionalGroupsSequence != null) { SequenceAttribute sharedPlaneOrientationSequence = (SequenceAttribute)(SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( sharedFunctionalGroupsSequence,TagFromName.PlaneOrientationSequence)); if (sharedPlaneOrientationSequence != null) { aImageOrientationPatient = SequenceAttribute.getNamedAttributeFromWithinSequenceWithSingleItem( sharedPlaneOrientationSequence,TagFromName.ImageOrientationPatient); } } //System.err.println("GeometryOfVolumeFromAttributeList.getImageOrientationPatientFromAttributeList(): "+aImageOrientationPatient); if (aImageOrientationPatient != null) { vImageOrientationPatient = aImageOrientationPatient.getDoubleValues(); } } catch (DicomException e) { e.printStackTrace(System.err); } return vImageOrientationPatient; } }
c10e67a9f890fb2542b701a1c289feeadd262909
9c99029bf9fd15cee303f815989085ffe2e3adb9
/src/chap02/type/ShortType.java
1a922a0a7b9eb6acdbdcc4034f1cb7c15905cd50
[]
no_license
dlwl0005/java20200929
d1ac4c3280441e4be3bc96194bd44a585af4fddc
0e5750036384974f659248d3910c3b173472e61a
refs/heads/master
2023-01-05T17:01:34.559107
2020-11-03T08:28:06
2020-11-03T08:28:06
299,485,582
0
0
null
null
null
null
UTF-8
Java
false
false
283
java
package chap02.type; public class ShortType { public static void main(String[] args) { // short :2byte short shortValue1; shortValue1 = 32767; System.out.println(shortValue1); // shortValue1 = 32768;//x shortValue1= -32768; System.out.println(shortValue1); } }
80237405122cceaaf3d90a297d27642c6f1987fb
c12bcd01f4d0da79386cf85b0aa43c8d081c53e7
/app/src/main/java/com/example/praktikum5/TimePickerFragment.java
ef424cfb83a01318c21913a1c00f04740dcb7e8e
[]
no_license
Pranandahabib/TUGAS5-1918029-PRANANDAHABIB
d959c664b8499659cf969127d8b120af81abc94c
8a64c737cbfb883370a783f9163370d2093714bd
refs/heads/main
2023-08-27T08:14:17.898708
2021-11-07T09:42:57
2021-11-07T09:42:57
425,463,717
0
0
null
null
null
null
UTF-8
Java
false
false
804
java
package com.example.praktikum5; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.text.format.DateFormat; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import java.util.Calendar; public class TimePickerFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity())); } }
092495fa85873751e6326c124d099c85caf72515
693995978adb623590dfc215fa166961af70fe8f
/core/core-push/src/main/java/com/shanjin/push/ios/apns/APNS.java
72c4d3146fa745fdd890b774504087de26679921
[]
no_license
yxxcrtd/omeng.cc
13ea163bee5cd89bd5a50388e7aae81da3355ca0
dffea0dbc666272712e82ef4ce25e427f97d05a1
refs/heads/master
2022-12-24T07:36:07.662048
2019-06-05T07:38:14
2019-06-05T07:38:14
190,348,103
1
1
null
2022-12-16T07:52:01
2019-06-05T07:35:46
Java
UTF-8
Java
false
false
2,225
java
package com.shanjin.push.ios.apns; /* * Copyright 2009, Mahmood Ali. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Mahmood Ali. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The main class to interact with the APNS Service. * * Provides an interface to create the {@link ApnsServiceBuilder} and * {@code ApnsNotification} payload. * */ public final class APNS { private APNS() { throw new AssertionError("Uninstantiable class"); } /** * Returns a new Payload builder */ public static PayloadBuilder newPayload() { return new PayloadBuilder(); } /** * Returns a new APNS Service for sending iPhone notifications */ public static ApnsServiceBuilder newService() { return new ApnsServiceBuilder(); } }
ddd116a3b6837b46c5765ff59ce5905e4a4033d1
9a7973a1e55910db66c6d95f0c1ee3ac0950ff38
/src/test/java/com/jdown/controller/JDownControllerTest.java
6c28aa6136d31eb484973828f009539cf26eb425
[]
no_license
rowokop80/JSONDownload
0d9c7d1894e275ca26480bcf0dab9d57732cc50f
540cdb3c0626c4ecc4089e230b18e8d1438bc141
refs/heads/master
2022-11-18T17:04:22.428111
2020-07-06T07:38:03
2020-07-06T07:38:03
277,473,417
0
0
null
null
null
null
UTF-8
Java
false
false
2,269
java
package com.jdown.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Spy; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.web.server.ResponseStatusException; import com.jdown.exception.JsonDownloadException; import com.jdown.model.Post; import com.jdown.service.JDownService; @SpringBootTest class JDownControllerTest { @Spy JDownController jDownControllerSpy; @Mock JDownService jDownServiceMock; public List<Post> preparePostList() { List<Post> postList = new ArrayList<Post>(); Post p1 = new Post(); p1.setId(1); p1.setTitle("title 1"); Post p2 = new Post(); p2.setId(2); p2.setTitle("title 2"); Post p3 = new Post(); p3.setId(3); p3.setTitle("title 3"); Post p4 = new Post(); p4.setId(4); p4.setTitle("title 4"); postList.add(p1); postList.add(p2); postList.add(p3); postList.add(p4); return postList; } @Test void testGetPosts_all_ok() { jDownControllerSpy.setjDownService(jDownServiceMock); doReturn(preparePostList()).when(jDownServiceMock).getPosts(); List<Post> retPostList = jDownControllerSpy.jsonPosts(); verify(jDownServiceMock, times(1)).getPosts(); assertNotNull(retPostList); assertEquals(4, retPostList.size()); } @Test void testGetPosts_ThrowException() { jDownControllerSpy.setjDownService(jDownServiceMock); JsonDownloadException throwException = new JsonDownloadException("test content error"); doThrow(throwException).when(jDownServiceMock).getPosts(); ResponseStatusException exception = assertThrows(ResponseStatusException.class, () -> jDownControllerSpy.jsonPosts()); assertEquals("400 BAD_REQUEST \"test content error\"; nested exception is com.jdown.exception.JsonDownloadException: test content error", exception.getLocalizedMessage()); } }
dbf2ea9eb4f1b7a72aeafd89577c2d22827d9235
d548238acdaf51df910bdc70db0e8f7d1ee7075e
/MyJAX-B_App_MarshallingAndUnMarshalling/src/main/java/com/nt/test/UnMarshallingTest.java
87c8b78cfa02551645c150f6f240a8610f369ba9
[]
no_license
saurabh23patre93/Webservice_Raghu
7009820a04616476e087090eab34bed609917697
4054987d1fc9a60e4a586b922b5241cd830fabe3
refs/heads/master
2023-04-07T18:24:17.770615
2021-04-17T09:01:14
2021-04-17T09:01:14
355,806,461
0
0
null
null
null
null
UTF-8
Java
false
false
645
java
package com.nt.test; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import com.nt.model.Student; public class UnMarshallingTest { public static void main(String[] args) { try { //1.create Context object for student JAXBContext context=JAXBContext.newInstance(Student.class); //2.create Unmarshaller Unmarshaller um=context.createUnmarshaller(); //3.call unmarshaller Student st=(Student) um.unmarshal(new File("E:/data.xml")); //Print data System.out.println(st); } catch (Exception e) { e.printStackTrace(); } } }
[ "asus@DESKTOP-5V94U0C-Saurabh" ]
asus@DESKTOP-5V94U0C-Saurabh
4dca4f15ce6313d030d2372370e7a5e030df1467
2437c9eadfae6449b3b5dba2890ad891d4a154d8
/My_LMS/src/main/java/com/yildirimbayrakci/lms/UserManagement_user.java
67f51ca0bde320cd184aaf31825f7cbc2b6e7ca1
[ "MIT" ]
permissive
yildirim2189/Library_Management_System-Java_Swing
3f4f546f411fc849c52df5bde56dea798fe1b62a
28e8da2cb4034c68b2f6e80924e8d7e39d8aa0e8
refs/heads/master
2022-07-07T12:48:48.152216
2019-12-15T17:14:22
2019-12-15T17:14:22
228,094,459
1
0
MIT
2022-02-10T00:27:53
2019-12-14T21:57:37
Java
UTF-8
Java
false
false
28,276
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 com.yildirimbayrakci.lms; import com.yildirimbayrakci.entity.Account; import com.yildirimbayrakci.entity.Book; import com.yildirimbayrakci.entity.BorrowHistory; import com.yildirimbayrakci.util.DateUtils; import com.yildirimbayrakci.util.HibernateUtils; import com.yildirimbayrakci.util.Search; import com.yildirimbayrakci.util.TableColumnAdjuster; import com.yildirimbayrakci.util.MyPdfWriter; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JTable; import javax.swing.plaf.basic.BasicInternalFrameUI; import javax.swing.table.DefaultTableModel; /** * * @author YILDIRIM */ public class UserManagement_user extends javax.swing.JInternalFrame { /** * Creates new form UserManagement */ private Account account; public UserManagement_user(Account account) { initComponents(); setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); BasicInternalFrameUI bif = (BasicInternalFrameUI) getUI(); bif.setNorthPane(null); this.account = account; jTextField_account_type.setEnabled(false); jTextField_userId.setEnabled(false); jTextField_userName.setEnabled(false); jTextField_userSurname.setEnabled(false); showUserInfo(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable_lending = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel_numberOfBooksBorrowed = new javax.swing.JLabel(); jTextField_userId = new javax.swing.JTextField(); jTextField_userName = new javax.swing.JTextField(); jTextField_email = new javax.swing.JTextField(); jTextField_userSurname = new javax.swing.JTextField(); jTextField_phone = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jPasswordField_userPassword = new javax.swing.JPasswordField(); jLabel_messageField = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel12 = new javax.swing.JLabel(); jButton_bringBooks = new javax.swing.JButton(); jCheckBox_bringReturnedBooks = new javax.swing.JCheckBox(); jButton_createPDF1 = new javax.swing.JButton(); jTextField_account_type = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); JButton_updateUserInfo = new javax.swing.JButton(); jPasswordField_newPw = new javax.swing.JPasswordField(); jPasswordField_newPwConfirm = new javax.swing.JPasswordField(); JButton_changePw = new javax.swing.JButton(); jCheckBox_showPassword = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_reserved = new javax.swing.JTable(); jLabel9 = new javax.swing.JLabel(); jButton_cancelReservation = new javax.swing.JButton(); setBackground(new java.awt.Color(222, 222, 222)); setPreferredSize(new java.awt.Dimension(930, 510)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(222, 222, 222)); jPanel1.setPreferredSize(new java.awt.Dimension(870, 500)); jTable_lending.setModel(new javax.swing.table.DefaultTableModel( null, new String [] { "İşlem Id","Kitap Id", "Başlık", "Ödünç Tarihi", "Bitiş Tarihi","Teslim Tarihi" } )); jTable_lending.setName("Kullanıcı Kitapları"); // NOI18N jTable_lending.getTableHeader().setReorderingAllowed(false); jScrollPane2.setViewportView(jTable_lending); jLabel1.setText("Kullanıcı Id"); jLabel4.setText("Şifre"); jLabel5.setText("Ad"); jLabel6.setText("Soyad"); jLabel7.setText("Email"); jLabel8.setText("Telefon"); jLabel_numberOfBooksBorrowed.setText("Ödünç Alınan Kitap Sayısı:"); jLabel10.setText("Tip"); jLabel_messageField.setForeground(new java.awt.Color(204, 0, 0)); jLabel12.setText("Mesaj"); jButton_bringBooks.setText("Kitap Getir"); jButton_bringBooks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_bringBooksActionPerformed(evt); } }); jCheckBox_bringReturnedBooks.setBackground(new java.awt.Color(222, 222, 222)); jCheckBox_bringReturnedBooks.setText("Teslim edilmiş kitapları getir"); jButton_createPDF1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/media/pdf.png"))); // NOI18N jButton_createPDF1.setText("PDF Oluştur"); jButton_createPDF1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_createPDF1ActionPerformed(evt); } }); jLabel2.setText("Yeni Şifre"); jLabel3.setText("Yeni Şifre (Tekrar)"); JButton_updateUserInfo.setText("Bilgilerimi Güncelle"); JButton_updateUserInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JButton_updateUserInfoActionPerformed(evt); } }); JButton_changePw.setText("Şifre Değiştir"); JButton_changePw.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JButton_changePwActionPerformed(evt); } }); jCheckBox_showPassword.setBackground(new java.awt.Color(222, 222, 222)); jCheckBox_showPassword.setText(" Şifreyi göster"); jCheckBox_showPassword.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox_showPasswordActionPerformed(evt); } }); jTable_reserved.setModel(new javax.swing.table.DefaultTableModel( null, new String [] { "Id", "Başlık", "Yazar" } )); jScrollPane1.setViewportView(jTable_reserved); jLabel9.setText("Rezerve Edilmiş Kitaplar"); jButton_cancelReservation.setText("Rezerve İptal"); jButton_cancelReservation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_cancelReservationActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(jScrollPane2) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton_bringBooks, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(31, 31, 31) .addComponent(jCheckBox_bringReturnedBooks) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_createPDF1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel12) .addGap(43, 43, 43) .addComponent(jLabel_messageField, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_numberOfBooksBorrowed, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34) .addComponent(jTextField_userId, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jTextField_userName, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField_userSurname, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(74, 74, 74) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(54, 54, 54) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_email, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_phone, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_account_type, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(JButton_updateUserInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(82, 82, 82) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JButton_changePw, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPasswordField_userPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE) .addComponent(jPasswordField_newPwConfirm) .addComponent(jPasswordField_newPw))))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_cancelReservation, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jCheckBox_showPassword))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_bringBooks) .addComponent(jButton_createPDF1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jCheckBox_bringReturnedBooks)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel_messageField, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE) .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_numberOfBooksBorrowed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField_userId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(jTextField_email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jPasswordField_userPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jTextField_phone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(jTextField_userName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jPasswordField_newPw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextField_userSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jTextField_account_type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jPasswordField_newPwConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(JButton_updateUserInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(JButton_changePw, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jCheckBox_showPassword)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_cancelReservation)) .addGap(339, 339, 339)) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 531)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_createPDF1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_createPDF1ActionPerformed // TODO add your handling code here: new MyPdfWriter().write(jTable_lending); }//GEN-LAST:event_jButton_createPDF1ActionPerformed private void jButton_bringBooksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_bringBooksActionPerformed updateLendTable(account.getAccountId()); }//GEN-LAST:event_jButton_bringBooksActionPerformed private void JButton_updateUserInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JButton_updateUserInfoActionPerformed String email = jTextField_email.getText(); String phone = jTextField_phone.getText(); Account temp = HibernateUtils.updateUserContact(account.getAccountId(), email, phone); if (temp != null) { jLabel_messageField.setText("İletişim bilgileriniz güncellendi"); account = temp; AdminScreen.setAccount(account); showUserInfo(); } }//GEN-LAST:event_JButton_updateUserInfoActionPerformed private void JButton_changePwActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JButton_changePwActionPerformed String password = new String(jPasswordField_userPassword.getPassword()); String newPassword = new String(jPasswordField_newPw.getPassword()); String newPasswordConfirm = new String(jPasswordField_newPwConfirm.getPassword()); password = password.trim(); newPassword = newPassword.trim(); newPasswordConfirm = newPasswordConfirm.trim(); if (password.equals("") || newPassword.equals("") || newPasswordConfirm.equals("")) { jLabel_messageField.setText("Lütfen alanları boş bırakmayınız."); } else if (!newPassword.equals(newPasswordConfirm)) { jLabel_messageField.setText("Yeni şifre ile tekrar alanı eşleşmiyor."); } else { boolean correctPw = HibernateUtils.authenticateUser(account.getAccountId(), password); if (!correctPw) { jLabel_messageField.setText("Yanlış hesap şifresi girdiniz."); } else { HibernateUtils.changePw(account.getAccountId(), newPassword); jLabel_messageField.setText("Şifreniz başarıyla değiştirildi."); jPasswordField_userPassword.setText(""); jPasswordField_newPw.setText(""); jPasswordField_newPwConfirm.setText(""); } } }//GEN-LAST:event_JButton_changePwActionPerformed private void jCheckBox_showPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_showPasswordActionPerformed if (jCheckBox_showPassword.isSelected()) { jPasswordField_newPw.setEchoChar((char) 0); jPasswordField_newPwConfirm.setEchoChar((char) 0); jPasswordField_userPassword.setEchoChar((char) 0); } else { jPasswordField_newPw.setEchoChar('●'); jPasswordField_newPwConfirm.setEchoChar('●'); jPasswordField_userPassword.setEchoChar('●'); } }//GEN-LAST:event_jCheckBox_showPasswordActionPerformed private void jButton_cancelReservationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_cancelReservationActionPerformed int selected = jTable_reserved.getSelectedRow(); if(selected == -1){ jLabel_messageField.setText("Lütfen iptal etmek için bir kayıt seçiniz."); }else{ jLabel_messageField.setText("Rezervasyon iptal edildi."); int bookId = (int)jTable_reserved.getValueAt(selected, 0); HibernateUtils.removeReservation(bookId, account.getAccountId()); updateLendTable(account.getAccountId()); } }//GEN-LAST:event_jButton_cancelReservationActionPerformed private void updateLendTable(String accountId) { DefaultTableModel dtm = (DefaultTableModel) jTable_lending.getModel(); dtm.setRowCount(0); List<BorrowHistory> history; if (jCheckBox_bringReturnedBooks.isSelected()) { history = Search.searchBorrowHistory(accountId, true); } else { history = Search.searchBorrowHistory(accountId, false); } Account account = Search.searchUser(accountId); Set<Book> reservedBooks = account.getReservedBooks(); history.forEach((bh) -> { dtm.addRow(new Object[]{bh.getBorrowId(), bh.getBook().getBookId(), bh.getBook().getTitle(), DateUtils.formatDate(bh.getBorrowDate()), DateUtils.formatDate(bh.getDueDate()), DateUtils.formatDate(bh.getReturnDate())}); }); DefaultTableModel dtm2 = (DefaultTableModel) jTable_reserved.getModel(); dtm2.setRowCount(0); for (Book b : reservedBooks) { dtm2.addRow(new Object[]{b.getBookId(),b.getTitle(),b.getAuthor()}); } jTable_reserved.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); TableColumnAdjuster tca = new TableColumnAdjuster(jTable_reserved); tca.adjustColumns(); jTable_lending.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); tca = new TableColumnAdjuster(jTable_lending); tca.adjustColumns(); jLabel_numberOfBooksBorrowed.setText("Ödünç Alınan Kitap Sayısı: " + history.size()); } public void showUserInfo() { jTextField_email.setText(account.getEmail()); jTextField_phone.setText(account.getPhone()); jTextField_account_type.setText(account.getType().displayName()); jTextField_userId.setText(account.getAccountId()); jTextField_userName.setText(account.getFirstName()); jTextField_userSurname.setText(account.getLastName()); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton JButton_changePw; private javax.swing.JButton JButton_updateUserInfo; private javax.swing.JButton jButton_bringBooks; private javax.swing.JButton jButton_cancelReservation; private javax.swing.JButton jButton_createPDF1; private javax.swing.JCheckBox jCheckBox_bringReturnedBooks; private javax.swing.JCheckBox jCheckBox_showPassword; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabel_messageField; private javax.swing.JLabel jLabel_numberOfBooksBorrowed; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField jPasswordField_newPw; private javax.swing.JPasswordField jPasswordField_newPwConfirm; private javax.swing.JPasswordField jPasswordField_userPassword; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JTable jTable_lending; private javax.swing.JTable jTable_reserved; private javax.swing.JTextField jTextField_account_type; private javax.swing.JTextField jTextField_email; private javax.swing.JTextField jTextField_phone; private javax.swing.JTextField jTextField_userId; private javax.swing.JTextField jTextField_userName; private javax.swing.JTextField jTextField_userSurname; // End of variables declaration//GEN-END:variables }
4ac23b661e8aa0cb599a245ef342fcfafdd3d1ac
6ddfef584a834362c15b2a755407e05f9d318873
/Alice/src/main/java/com/hs/alice/util/crypt/AliceCrypt.java
e48c6a5ad78bb72f6cf53915a605897d7bc40350
[]
no_license
CrazyJK/kamoru-antique
f6f30d1698aee9cd9e76e63859d708d06c5212d8
a15b0666a812fadaf93ba0a923787b124e160e55
refs/heads/master
2020-04-12T18:57:02.764638
2014-11-03T12:52:29
2014-11-03T12:52:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
138
java
package com.hs.alice.util.crypt; public interface AliceCrypt { String decrypt(String encryptString); String encrypt(String string); }
[ "[email protected]@e3ab8832-cd79-4ee9-3d71-893b5bf6c76a" ]
[email protected]@e3ab8832-cd79-4ee9-3d71-893b5bf6c76a
0fe9c4d70729a4302d97dd88acf79af04a507051
a6e2cd9ea01bdc5cfe58acce25627786fdfe76e9
/src/main/java/com/alipay/api/response/KoubeiServindustryExerciseRecordcourseSyncResponse.java
1184ee8389f64504d7a6b77c7584bfb6f1f51cfd
[ "Apache-2.0" ]
permissive
cc-shifo/alipay-sdk-java-all
38b23cf946b73768981fdeee792e3dae568da48c
938d6850e63160e867d35317a4a00ed7ba078257
refs/heads/master
2022-12-22T14:06:26.961978
2020-09-23T04:00:10
2020-09-23T04:00:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: koubei.servindustry.exercise.recordcourse.sync response. * * @author auto create * @since 1.0, 2020-06-18 11:51:22 */ public class KoubeiServindustryExerciseRecordcourseSyncResponse extends AlipayResponse { private static final long serialVersionUID = 5851718815724351644L; }
b92220f45fe5533a6be0bd4e90ab5569dcc1f460
3d9132b92e6418f4e451716bc4716093608ec1c2
/remote_demo/src/androidTest/java/com/xuexiang/remotedemo/ExampleInstrumentedTest.java
65942538e384cf74234789d580d3fd90220ed8a0
[]
no_license
doujinhai123/XIPC
19bda8cc4ea8ba4d9bfb9227f8660efba537b754
1113736f9298b4acb6d4743b6c42a2ec4d90399c
refs/heads/master
2021-09-23T15:38:22.942120
2018-09-25T10:39:26
2018-09-25T10:39:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,353
java
/* * Copyright (C) 2018 xuexiangjys([email protected]) * * 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.xuexiang.remotedemo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.xuexiang.remotedemo", appContext.getPackageName()); } }
86b9b0b6c65c5ea7d0ca6471acecbbf97f0ea699
53189efbfed5423821a84f631da404d07a80e404
/storage/app/Al-QuranIndonesia_com.andi.alquran.id_source_from_JADX/com/google/android/gms/location/C2095m.java
5b3d83d3cb2d96f77ebfb9ba44d75c4ffaad0a30
[ "MIT" ]
permissive
dwijpr/islam
0c9b77028d34862b6d06858c5b0d6ffec91b5014
6077291a619ac2f5b30a77e284c0a7361e7c8ad4
refs/heads/master
2021-01-19T17:16:49.818251
2017-03-13T23:00:08
2017-03-13T23:00:08
82,430,213
0
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
package com.google.android.gms.location; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.C1354a; import com.google.android.gms.common.internal.safeparcel.C1354a.C1353a; import com.google.android.gms.common.internal.safeparcel.C1355b; import com.google.android.gms.maps.GoogleMap; import java.util.List; /* renamed from: com.google.android.gms.location.m */ public class C2095m implements Creator<zzj> { static void m9850a(zzj com_google_android_gms_location_zzj, Parcel parcel, int i) { int a = C1355b.m4826a(parcel); C1355b.m4839a(parcel, 1, com_google_android_gms_location_zzj.m9899b(), false); C1355b.m4831a(parcel, 1000, com_google_android_gms_location_zzj.m9898a()); C1355b.m4827a(parcel, a); } public zzj m9851a(Parcel parcel) { int b = C1354a.m4804b(parcel); int i = 0; List list = null; while (parcel.dataPosition() < b) { int a = C1354a.m4798a(parcel); switch (C1354a.m4797a(a)) { case GoogleMap.MAP_TYPE_NORMAL /*1*/: list = C1354a.m4824s(parcel, a); break; case 1000: i = C1354a.m4811f(parcel, a); break; default: C1354a.m4805b(parcel, a); break; } } if (parcel.dataPosition() == b) { return new zzj(i, list); } throw new C1353a("Overread allowed size end=" + b, parcel); } public zzj[] m9852a(int i) { return new zzj[i]; } public /* synthetic */ Object createFromParcel(Parcel parcel) { return m9851a(parcel); } public /* synthetic */ Object[] newArray(int i) { return m9852a(i); } }
d1531c2456bcd01eeabe109da58f0504eb4c5596
f3933b0573150fa64dbb55ca06af778c27069c95
/Posit_IF/src/main/java/dao/JpaUtil.java
e03e4fea785fcedd1ed5d03e2c3ad9e40e82fd0b
[]
no_license
arbaforce/Posit_IF
754f4dd6bc07e161b9b08e91c2ca836d79972e01
d68eead720c63cc5e4dc751cc08d9000a62b1cce
refs/heads/master
2020-03-15T20:21:38.771861
2018-05-17T13:55:07
2018-05-17T13:55:07
132,330,843
0
0
null
null
null
null
UTF-8
Java
false
false
6,748
java
package dao; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; /** * Cette classe fournit des méthodes statiques utiles pour accéder aux * fonctionnalités de JPA (Entity Manager, Entity Transaction). Le nom de * l'unité de persistance (PERSISTENCE_UNIT_NAME) doit être conforme à la * configuration indiquée dans le fichier persistence.xml du projet. * * @author DASI Team */ public class JpaUtil { // ************************************************************************************* // * TODO: IMPORTANT -- Adapter le nom de l'Unité de Persistance (cf. persistence.xml) * // ************************************************************************************* /** * Nom de l'unité de persistance utilisée par la Factory de Entity Manager. * <br><strong>Vérifier le nom de l'unité de persistance * (cf.&nbsp;persistence.xml)</strong> */ public static final String PERSISTENCE_UNIT_NAME = "persistence"; /** * Factory de Entity Manager liée à l'unité de persistance. * <br/><strong>Vérifier le nom de l'unité de persistance indiquée dans * l'attribut statique PERSISTENCE_UNIT_NAME * (cf.&nbsp;persistence.xml)</strong> */ private static EntityManagerFactory entityManagerFactory = null; /** * Gère les instances courantes de Entity Manager liées aux Threads. * L'utilisation de ThreadLocal garantie une unique instance courante par * Thread. */ private static final ThreadLocal<EntityManager> threadLocalEntityManager = new ThreadLocal<EntityManager>() { @Override protected EntityManager initialValue() { return null; } }; // Méthode pour avoir des messages de Log dans le bon ordre (pause) private static void pause(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException ex) { ex.hashCode(); } } // Méthode pour avoir des messages de Log dans le bon ordre (log) private static void log(String message) { System.out.flush(); pause(5); System.err.println("[JpaUtil:Log] " + message); System.err.flush(); pause(5); } /** * Initialise la Factory de Entity Manager. * <br><strong>À utiliser uniquement au début de la méthode main() [projet * Java Application] ou dans la méthode init() de la Servlet Contrôleur * (ActionServlet) [projet Web Application].</strong> */ public static synchronized void init() { log("Initialisation de la factory de contexte de persistance"); if (entityManagerFactory != null) { entityManagerFactory.close(); } entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); } /** * Libère la Factory de Entity Manager. * <br><strong>À utiliser uniquement à la fin de la méthode main() [projet * Java Application] ou dans la méthode destroy() de la Servlet Contrôleur * (ActionServlet) [projet Web Application].</strong> */ public static synchronized void destroy() { log("Libération de la factory de contexte de persistance"); if (entityManagerFactory != null) { entityManagerFactory.close(); entityManagerFactory = null; } } /** * Créée l'instance courante de Entity Manager (liée à ce Thread). * <br><strong>À utiliser uniquement au niveau Service.</strong> */ public static void creerEntityManager() { log("Création du contexte de persistance"); threadLocalEntityManager.set(entityManagerFactory.createEntityManager()); } /** * Ferme l'instance courante de Entity Manager (liée à ce Thread). * <br><strong>À utiliser uniquement au niveau Service.</strong> */ public static void fermerEntityManager() { log("Fermeture du contexte de persistance"); EntityManager em = threadLocalEntityManager.get(); em.close(); threadLocalEntityManager.set(null); } /** * Démarre une transaction sur l'instance courante de Entity Manager. * <br><strong>À utiliser uniquement au niveau Service.</strong> */ public static void ouvrirTransaction() { log("Ouverture de la transaction (begin)"); try { EntityManager em = threadLocalEntityManager.get(); em.getTransaction().begin(); } catch (Exception ex) { log("Erreur lors de l'ouverture de la transaction"); throw ex; } } /** * Valide la transaction courante sur l'instance courante de Entity Manager. * <br><strong>À utiliser uniquement au niveau Service.</strong> * * @exception RollbackException lorsque le <em>commit</em> n'a pas réussi. */ public static void validerTransaction() throws RollbackException { log("Validation de la transaction (commit)"); try { EntityManager em = threadLocalEntityManager.get(); em.getTransaction().commit(); } catch (Exception ex) { log("Erreur lors de la validation (commit) de la transaction"); throw ex; } } /** * Annule la transaction courante sur l'instance courante de Entity Manager. * Si la transaction courante n'est pas démarrée, cette méthode n'effectue * aucune opération. * <br><strong>À utiliser uniquement au niveau Service.</strong> */ public static void annulerTransaction() { try { log("Annulation de la transaction (rollback)"); EntityManager em = threadLocalEntityManager.get(); if (em.getTransaction().isActive()) { log("Annulation effective de la transaction (rollback d'une transaction active)"); em.getTransaction().rollback(); } } catch (Exception ex) { log("Erreur lors de l'annulation (rollback) de la transaction"); throw ex; } } /** * Retourne l'instance courante de Entity Manager. * <br><strong>À utiliser uniquement au niveau DAO.</strong> * * @return instance de Entity Manager */ protected static EntityManager obtenirEntityManager() { log("Obtention du contexte de persistance"); return threadLocalEntityManager.get(); } }
6b53ceea8f47d4d2e55974897bac8b478340a61b
bb205c730f7179bb750e89806d2d26a201e34f8f
/src/com/nullpointerworks/gui/elements/CheckElement.java
33c8557adf342ad5152b219d44656f511c1c6b44
[ "Unlicense" ]
permissive
NullpointerWorks/libgui
51d31f71bf10b2827ecfc4ca96b0faed82afe39d
3ef7ebefefc92364473844a8d971d9f30108e39b
refs/heads/master
2023-04-01T19:04:41.925048
2021-04-08T18:11:23
2021-04-08T18:11:23
288,923,902
0
0
null
null
null
null
UTF-8
Java
false
false
1,328
java
package com.nullpointerworks.gui.elements; import com.nullpointerworks.core.input.Mouse; import com.nullpointerworks.core.input.MouseInput; import com.nullpointerworks.util.concurrency.Lock; public abstract class CheckElement extends ButtonElement { private Boolean state = false; private Lock _presslock = new Lock(); @Override public void onUpdate(MouseInput mi, float dt) { if (!isEnabled()) return; float ox = getParent().getGeometry().getBoundingBox().x; float oy = getParent().getGeometry().getBoundingBox().y; float mouse_x = mi.getMouseX() - ox; float mouse_y = mi.getMouseY() - oy; if (!onGeometryTest(mouse_x, mouse_y)) { _presslock.unlock(); return; } onHover(); if (!_presslock.isLocked()) if (mi.isClicked( Mouse.LEFT )) { _presslock.lock(); onPressed(); } if (_presslock.isLocked()) { if(mi.isClicked( Mouse.LEFT )) { onPressing(); } else { setChecked(!state); onRelease(); _presslock.unlock(); } } } /** * Returns the state of the checkbox */ public boolean isChecked() { synchronized(state) { return state; } } /** * Set the state of the box */ public void setChecked(boolean c) { synchronized(state) { if (state != c) { state = c; onRefresh(); } } } }
702bcbc1efa36dd8a446079d3638825e2fc9df77
b0c35c21d402b08d3fac210ee912df248b90c7e8
/src/kubajj/lekce9/OtoceniIIdouble.java
a809793dec22b85b6585a3a5b6a7573a5449ad19
[]
no_license
kubajj/Programovani
1d945661823dea7b5f6bd6842ece738ea2392eb3
f1ca06fab1fc1e9b63661619f04842e664ba0eed
refs/heads/master
2021-10-20T12:29:26.799786
2019-02-27T17:33:19
2019-02-27T17:33:19
111,451,600
0
0
null
null
null
null
UTF-8
Java
false
false
710
java
package kubajj.lekce9; public class OtoceniIIdouble { public static void main(String args[]) { int pocet = 0; double cisla[] = new double[1]; System.out.printf("Zadejte neomezeny pocet cisel:\n"); java.util.Scanner sc = new java.util.Scanner(System.in); while (sc.hasNextDouble()) { if (pocet == cisla.length) { double cislanew[] = new double[cisla.length * 2]; for (int i = 0; i < cisla.length; i++) { cislanew[i] = cisla[i]; } cisla = cislanew; } cisla[pocet++] = sc.nextDouble(); } System.out.println(); System.out.printf("Pozpatku:"); for (int a = pocet - 1; a >= 0; a-- ){ System.out.printf(" %f", cisla[a]); } System.out.println(); } }
c88f665cd0debe09eb47800495bbbcbf4da976b7
8a2837522519f64cf45d54e7e2e11b95a38a4efe
/src/main/java/com/drpicox/game/runners/CR500StarBuildStarbase.java
3794abeb89685c847db051b0fb87d1ad00a26b9c
[]
no_license
drpicox/planets-game-exam
22761fd8d56ede25aa5ed553cfb4737a40192ea0
ad4988c7cacd0b81a12dc505bf2660adf28b117a
refs/heads/master
2023-02-03T01:21:26.851034
2020-01-21T09:19:02
2020-01-21T09:19:02
235,301,371
0
1
null
2023-01-05T05:24:40
2020-01-21T09:27:23
HTML
UTF-8
Java
false
false
2,064
java
package com.drpicox.game.runners; import com.drpicox.game.commands.CommandController; import com.drpicox.game.entities.Entity; import com.drpicox.game.messages.MessageController; import com.drpicox.game.players.Player; import com.drpicox.game.starbases.StarbaseController; import com.drpicox.game.stars.StarController; import org.springframework.stereotype.Component; @Component public class CR500StarBuildStarbase implements CommandRunner { private CommandController commandController; private StarbaseController starbaseController; private MessageController messageController; private StarController starController; public CR500StarBuildStarbase(CommandController commandController, StarbaseController starbaseController, MessageController messageController, StarController starController) { this.commandController = commandController; this.starbaseController = starbaseController; this.messageController = messageController; this.starController = starController; } @Override public int getPriority() { return 500; } @Override public void run() { var commands = commandController.listAllByType("BuildStarbase"); for (var command : commands) { var player = command.getPlayer(); var entity = command.getEntity(); var name = command.getValue(); buildStarbase(player, entity, name); } } private void buildStarbase(Player player, Entity entity, String name) { var coordinates = entity.getCoordinates(); var star = starController.getStar(coordinates); var hasMinerals = starController.consumeMinerals(star,10); if (hasMinerals) { starbaseController.createStarbase(star, name); messageController.sendMessage(player, "Created the " + name + " starbase", coordinates); } else { messageController.sendMessage(player, "Cannot build starbase " + name + " due to a lack of available minerals", coordinates); } } }
5bafc466653784d510c62c8466efc6c647aeac9e
53d677a55e4ece8883526738f1c9d00fa6560ff7
/com/tencent/mm/wallet_core/ui/formview/WalletFormView$2.java
b8fa3b276b725a1a60617bded6bbf80758e81a06
[]
no_license
0jinxing/wechat-apk-source
544c2d79bfc10261eb36389c1edfdf553d8f312a
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
refs/heads/master
2020-06-07T20:06:03.580028
2019-06-21T09:17:26
2019-06-21T09:17:26
193,069,132
9
4
null
null
null
null
UTF-8
Java
false
false
678
java
package com.tencent.mm.wallet_core.ui.formview; import android.view.View; import android.view.View.OnClickListener; import com.tencent.matrix.trace.core.AppMethodBeat; final class WalletFormView$2 implements View.OnClickListener { WalletFormView$2(WalletFormView paramWalletFormView) { } public final void onClick(View paramView) { AppMethodBeat.i(49411); this.Ais.cey(); AppMethodBeat.o(49411); } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes3-dex2jar.jar * Qualified Name: com.tencent.mm.wallet_core.ui.formview.WalletFormView.2 * JD-Core Version: 0.6.2 */
f7243e0809574e9560eda41831b62e583b5a1620
2de38094b3062f34ecc222fe3401ca9e6f29fdee
/Day4-Homework3/src/GamerManager.java
0bc8fc3524017e8c07c8634f8f7abb938f5fc880
[]
no_license
umitceeelik/JavaCamp
ce48e9ea7d31edee057bdf6e97a2907519c60d7e
5a230723a96fa764306e468440cacf69727e0e67
refs/heads/master
2023-04-26T03:34:11.596353
2021-05-07T15:36:24
2021-05-07T15:36:24
362,830,753
0
0
null
null
null
null
ISO-8859-9
Java
false
false
831
java
public class GamerManager extends BaseUserManager { private UserCheckServise userCheckServise; public GamerManager(UserCheckServise userCheckServise) { super(); this.userCheckServise = userCheckServise; } @Override public void register(User user) { if(userCheckServise.CheckIfRealPerson(user)) { System.out.println("Bilgiler eşleşti : " + user.getFirstName()); super.register(user); } else { System.out.println("Bilgiler eşleşmedi : " + user.getFirstName()); } } @Override public void updateInformation(User user) { System.out.println(user.getFirstName() + " isimli oyuncu bilgilerini güncelledi ."); } @Override public void deregistration(User user) { System.out.println(user.getFirstName() + " isimli oyuncu kaydını sildi ."); } }
[ "steelfamily@Steelfamily" ]
steelfamily@Steelfamily
59ce4595ebe84704751ed21b132548a620dbb767
fa31bc3b859254c98222a79855025ac9f0d4fbd6
/src/ConvertSortedListtoBinarySearchTree.java
addee577c3d80871c8ff2bd4fb26c968d31a4ef7
[]
no_license
luoyangylh/MyLeetCodeRepo
2d36ad2e6036bd2dffefd3094f5661f3a5b03aee
48613cd6f58eb1d0c545f74f08dbe09bc737ae1a
refs/heads/master
2020-09-22T12:48:30.290389
2014-07-24T04:19:17
2014-07-24T04:19:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,322
java
// Convert Sorted List to Binary Search Tree /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } */ /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; TreeNode res = new TreeNode(-1); ListNode mid = findMid(head); res.val = mid.val; //if mid == head, means there left only one node or two if (mid == head) { res.left = null; } else { res.left = sortedListToBST(head); } res.right = sortedListToBST(mid.next); return res; } //find the mid node to be the root public ListNode findMid(ListNode head) { if (head == null) return null; ListNode mid = head; ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; if (fast.next == null || fast.next.next == null) { mid = slow.next; slow.next = null; break; } else { slow = slow.next; } } return mid; } }
acb09bc5f746e6af242e3b4157efc7ede4a98456
0b421cea4da6649fe3ce3bdde3db2b641fe56fb0
/src/test/java/codist/garmin/uploader/fit/FitFileParserTest.java
546a6ee409a39963dc1d49cce0d9cb79bcf91ecf
[]
no_license
xarling/garmin-uploader
1ab3555a6ca6ce7bb999db320ada7cfb203e5865
b7bb37856d20f02fb2667f3633187bda82f9b597
refs/heads/master
2020-05-18T16:31:41.853669
2014-08-28T07:38:39
2014-08-28T07:38:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package codist.garmin.uploader.fit; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import org.junit.Test; public class FitFileParserTest { @Test public void testParseFile() throws IOException, URISyntaxException { File file = new File(FitFileParserTest.class.getResource("/fitfiles/63542097220000000061.fit").toURI()); new FitFileParser().parseFile(file); } }
f8068bb67f71bdc417bf3791c1c112b9e10a9cd3
b75e7c8f2d4d57cd17c084a9c3b197de099beffc
/jvm-experiments-hibernate/src/main/java/kr/nsoft/data/hibernate/usertype/compress/XZStringUserType.java
dd48e9475e5a8d5aa497793f6b75ed0bed3fcdc1
[]
no_license
debop/jvm-experiments
56327e5c631a6e747b29a80589da514dcb35862b
284fe8865fc6b642b809aada1df98c54b3ba122a
refs/heads/master
2020-06-02T08:12:36.076635
2013-06-16T15:01:33
2013-06-16T15:01:33
6,716,406
0
1
null
null
null
null
UTF-8
Java
false
false
572
java
package kr.nsoft.data.hibernate.usertype.compress; import kr.nsoft.commons.compress.ICompressor; import kr.nsoft.commons.compress.XZCompressor; /** * XZ 알고리즘 ({@link XZCompressor} 으로 문자열 속성 값을 압축하여 Binary로 저장합니다. * User: [email protected] * Date: 12. 9. 18 */ public class XZStringUserType extends AbstractCompressedStringUserType { private static final ICompressor compressor = new XZCompressor(); @Override public ICompressor getCompressor() { return compressor; } }
4a6ce304cb1744eb0ddbba1f28ac28132ac57335
02b5ea08832decc8fe7dbec1c25ac0b7b0e08619
/src/main/java/raubach/fricklweb/server/database/tables/pojos/LatLngs.java
9baee6dfed321547c1604d0bf9ebd02782529b74
[ "Apache-2.0" ]
permissive
sebastian-raubach/frickl-web-server
25d05ce1ec1c84b61f72a26d3a907f07ddbc909c
6b1447c039763d571db227ba38c37ddf2d56bfb0
refs/heads/master
2023-06-09T08:57:19.834383
2023-05-31T13:29:27
2023-05-31T13:29:27
179,822,827
2
0
null
null
null
null
UTF-8
Java
false
true
3,732
java
/* * This file is generated by jOOQ. */ package raubach.fricklweb.server.database.tables.pojos; import java.io.Serializable; import java.math.BigDecimal; /** * VIEW */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class LatLngs implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String path; private Integer albumId; private Byte isPublic; private BigDecimal latitude; private BigDecimal longitude; public LatLngs() {} public LatLngs(LatLngs value) { this.id = value.id; this.path = value.path; this.albumId = value.albumId; this.isPublic = value.isPublic; this.latitude = value.latitude; this.longitude = value.longitude; } public LatLngs( Integer id, String path, Integer albumId, Byte isPublic, BigDecimal latitude, BigDecimal longitude ) { this.id = id; this.path = path; this.albumId = albumId; this.isPublic = isPublic; this.latitude = latitude; this.longitude = longitude; } /** * Getter for <code>frickl.lat_lngs.id</code>. Auto incremented id of this * table. */ public Integer getId() { return this.id; } /** * Setter for <code>frickl.lat_lngs.id</code>. Auto incremented id of this * table. */ public void setId(Integer id) { this.id = id; } /** * Getter for <code>frickl.lat_lngs.path</code>. The path to the image * relative to the base path of the setup. */ public String getPath() { return this.path; } /** * Setter for <code>frickl.lat_lngs.path</code>. The path to the image * relative to the base path of the setup. */ public void setPath(String path) { this.path = path; } /** * Getter for <code>frickl.lat_lngs.album_id</code>. The album this image * belongs to. This will be the containing folder. */ public Integer getAlbumId() { return this.albumId; } /** * Setter for <code>frickl.lat_lngs.album_id</code>. The album this image * belongs to. This will be the containing folder. */ public void setAlbumId(Integer albumId) { this.albumId = albumId; } /** * Getter for <code>frickl.lat_lngs.is_public</code>. */ public Byte getIsPublic() { return this.isPublic; } /** * Setter for <code>frickl.lat_lngs.is_public</code>. */ public void setIsPublic(Byte isPublic) { this.isPublic = isPublic; } /** * Getter for <code>frickl.lat_lngs.latitude</code>. */ public BigDecimal getLatitude() { return this.latitude; } /** * Setter for <code>frickl.lat_lngs.latitude</code>. */ public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } /** * Getter for <code>frickl.lat_lngs.longitude</code>. */ public BigDecimal getLongitude() { return this.longitude; } /** * Setter for <code>frickl.lat_lngs.longitude</code>. */ public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } @Override public String toString() { StringBuilder sb = new StringBuilder("LatLngs ("); sb.append(id); sb.append(", ").append(path); sb.append(", ").append(albumId); sb.append(", ").append(isPublic); sb.append(", ").append(latitude); sb.append(", ").append(longitude); sb.append(")"); return sb.toString(); } }
ca12ae5c145b19846c81dcc1dd175bd8629752e2
bb7d720d65ae4119fad9527f37f9d9182452b2c0
/BACKEND/Polifight/src/java/rest/AbstractFacade.java
b6b22dd0e7f70bd5457b7a9e526a19592b527102
[ "MIT" ]
permissive
juankrlos08/Pacto-de-Honor
ca8ee23ffa926bc8cd629f14602d5ecb7071b981
e1d706ef8b48dc4b1cab5a52883e1c9c95254936
refs/heads/master
2020-12-30T16:41:25.296918
2017-05-11T18:14:01
2017-05-11T18:14:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,965
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 rest; import java.util.List; import javax.persistence.EntityManager; /** * * @author ahsierra */ public abstract class AbstractFacade<T> { private Class<T> entityClass; public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public void create(T entity) { getEntityManager().persist(entity); } public void edit(T entity) { getEntityManager().merge(entity); } public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public T find(Object id) { return getEntityManager().find(entityClass, id); } public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0] + 1); q.setFirstResult(range[0]); return q.getResultList(); } public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } }
91e9aef43cefb09ca4c61dd127d1c5cf78c6fd73
2fd998f604724d6ecf3fe85d0bb4e7b7d14610e9
/design-mode/src/com/xinqushi/designpattern/bridge/BridgeDemo.java
e46ab1ab46c5b1ad1d13105974186e8a680306b8
[]
no_license
yangli1168/sustain-project
ad0d2d50a9253f4382450bb5a3e501188fd48aa2
a18415a90290c83af9b245e734174ddd86a48c8a
refs/heads/master
2021-01-19T15:30:21.238999
2018-04-03T22:53:02
2018-04-03T22:53:02
88,217,925
3
0
null
null
null
null
UTF-8
Java
false
false
694
java
package com.xinqushi.designpattern.bridge; /** * 桥接模式demo * </p>定义:将抽象部分与它的实现部分分离,使它们都可以独立变化; * 实现指的是抽象类和它的派生类用来实现自己的对象</p> * </p>使用:实现系统可能有多角度分类,每一种分类都有可能变化, * 此时把这种多角度分离出来让它们独立变化</p> * </p></p> * @author yangli */ public class BridgeDemo { public static void main(String[] args) { Abstracion ab = new RefindAbstraction(); ab.setImplementor(new ConcreteImplementorA()); ab.operation(); ab.setImplementor(new ConcreteImplementorB()); ab.operation(); } }
03c777a827103c8f7030710a69afe5d4ade68788
18dbc17e2d1bac968ba53efa50c3837f7df53759
/TastyRoad05/src/main/java/com/dwf/tastyroad/service/impl/AdminDaoImpl.java
111c72a2d55fd25aa818348e95a9da9278d08576
[]
no_license
josephkwon7/graBeacon-Web-Repository
f0fb99b6989f6eae58d7e0cbb9414fa8f87551f2
c4a3b64634e2627d34ae44d720f5d87f85e9017b
refs/heads/master
2021-01-13T01:49:14.234441
2014-07-06T07:48:55
2014-07-06T07:48:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
947
java
package com.dwf.tastyroad.service.impl; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.dwf.tastyroad.model.Admin; import com.dwf.tastyroad.service.AdminDao; @Repository public class AdminDaoImpl implements AdminDao { ///Field @Autowired @Qualifier("sqlSessionTemplate") private SqlSession sqlSession; ///Constructor public AdminDaoImpl(){ System.out.println("::"+getClass()+" Default Constructor Call"); } ///Method public void setSqlsession(SqlSession sqlSession){ System.out.println("::"+getClass()+".setSqlSession() Call"); this.sqlSession = sqlSession; } @Override public Admin findAdmin(String adminId) throws Exception { return sqlSession.selectOne("AdminMapper.findAdmin", adminId); } }
5a992336bf24a74372ccff2875da2ec1ebcaba00
6821be123a8359d121cb53404bda84031bd8bf13
/src/main/java/com/zzy/cvmanagementsystem/dto/CourseDto.java
610d89a72a1469fcafe6b9db9676b17224aee48c
[]
no_license
ZengZiyao/cv-management-backend
16e0882e718fe0733fa0fa8ba8d22defd9cc4602
bb6b61b14040675f13aa0b19e591cf4b2a62b44f
refs/heads/master
2023-04-04T20:05:14.473672
2021-04-08T11:29:50
2021-04-08T11:29:50
289,640,481
0
0
null
null
null
null
UTF-8
Java
false
false
547
java
package com.zzy.cvmanagementsystem.dto; import com.zzy.cvmanagementsystem.model.CourseLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class CourseDto { private String id; private String courseCode; private String title; private Date startYear; private Date endYear; private CourseLevel courseLevel; private String courseType; private int semester; }
17711e188d94fc51a59709d313ae8713c4ea06d1
a28be84cbcaa3dccfbc0017afb55f6dbfa3c9e94
/src/java/linh_dto/BookErr.java
fcd06a491c8a9faf34700dff349ffc147a6bf32f
[]
no_license
linhcnse130515/ProjectPRJ321
443982cc565191fd4aebc1c9ba833f8c9f746cd5
ba9491d1eb55232f4289860c6f24566f176ad8b8
refs/heads/master
2022-11-11T13:14:30.018430
2020-07-01T07:19:02
2020-07-01T07:19:02
268,097,750
0
0
null
null
null
null
UTF-8
Java
false
false
1,149
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 linh_dto; import java.io.Serializable; /** * * @author duyan */ public class BookErr implements Serializable{ private String bookIDErr; private String bookNameErr; private String bookQuanErr; private String statusErr; public BookErr() { } public String getBookIDErr() { return bookIDErr; } public void setBookIDErr(String bookIDErr) { this.bookIDErr = bookIDErr; } public String getBookNameErr() { return bookNameErr; } public void setBookNameErr(String bookNameErr) { this.bookNameErr = bookNameErr; } public String getBookQuanErr() { return bookQuanErr; } public void setBookQuanErr(String bookQuanErr) { this.bookQuanErr = bookQuanErr; } public String getStatusErr() { return statusErr; } public void setStatusErr(String statusErr) { this.statusErr = statusErr; } }
9b30fc4838375dc288b620bb392abf72379fd486
d5f09c7b0e954cd20dd613af600afd91b039c48a
/sources/com/gongwen/marqueen/MarqueeFactory.java
12098f3bdc2cccc38c4a210da3a6256359b5a6ea
[]
no_license
t0HiiBwn/CoolapkRelease
af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3
a6a2b03e32cde0e5163016e0078391271a8d33ab
refs/heads/main
2022-07-29T23:28:35.867734
2021-03-26T11:41:18
2021-03-26T11:41:18
345,290,891
5
2
null
null
null
null
UTF-8
Java
false
false
2,691
java
package com.gongwen.marqueen; import android.content.Context; import android.view.View; import java.util.ArrayList; import java.util.List; public abstract class MarqueeFactory<T extends View, E> { protected List<E> datas; private boolean isOnItemClickRegistered; protected Context mContext; private MarqueeView mMarqueeView; protected List<T> mViews; protected OnItemClickListener onItemClickListener; public interface OnItemClickListener<V extends View, E> { void onItemClickListener(ViewHolder<V, E> viewHolder); } public abstract T generateMarqueeItemView(E e); public MarqueeFactory(Context context) { this.mContext = context; } public void setData(List<E> list) { if (!(list == null || list.size() == 0)) { this.datas = list; this.mViews = new ArrayList(); for (int i = 0; i < list.size(); i++) { this.mViews.add(generateMarqueeItemView(list.get(i))); } registerOnItemClick(); MarqueeView marqueeView = this.mMarqueeView; if (marqueeView != null) { marqueeView.setMarqueeFactory(this); } } } public void setOnItemClickListener(OnItemClickListener<T, E> onItemClickListener2) { this.onItemClickListener = onItemClickListener2; registerOnItemClick(); } public List<T> getMarqueeViews() { return this.mViews; } private void registerOnItemClick() { if (!(this.isOnItemClickRegistered || this.onItemClickListener == null || this.datas == null)) { for (int i = 0; i < this.datas.size(); i++) { T t = this.mViews.get(i); t.setTag(new ViewHolder(t, this.datas.get(i), i)); t.setOnClickListener(new View.OnClickListener() { /* class com.gongwen.marqueen.MarqueeFactory.AnonymousClass1 */ @Override // android.view.View.OnClickListener public void onClick(View view) { MarqueeFactory.this.onItemClickListener.onItemClickListener((ViewHolder) view.getTag()); } }); } this.isOnItemClickRegistered = true; } } public static class ViewHolder<V extends View, P> { public P data; public V mView; public int position; public ViewHolder(V v, P p, int i) { this.mView = v; this.data = p; this.position = i; } } public void setAttachedToMarqueeView(MarqueeView marqueeView) { this.mMarqueeView = marqueeView; } }
e5fe51b7ef59c471825f3cdeb25e644936601ed6
45444d64a0bd6c97dd8bd60f3dcd6888ee0cc981
/Fandorin/src/com/javacore/profile/ProfileController.java
c492bcce82f9c3cdd44320b7614e93df0190596e
[]
no_license
golotamaxim/EPAM
e23be5acd47d923b074396a4e9f40085840acd5a
5524742b741bf1c23bfc3307dd94c5cdec87d8ef
refs/heads/master
2020-05-05T14:03:52.398165
2019-04-29T13:21:51
2019-04-29T13:21:51
180,105,595
0
0
null
null
null
null
UTF-8
Java
false
false
1,597
java
package com.javacore.profile; import com.javacore.command.ACommand; import com.javacore.common.Canvas; import com.javacore.Application; import java.io.IOException; public class ProfileController implements ACommand { private ProfileModel profileModel; //private ProfileStore profileStore; private ProfileView profileView; private Canvas canvas; // filling with random profiles, executing test-method; static { ProfileStore.INSTANCE.loadProfileData(); } { profileView = new ProfileView(); } @Override public void execute() { try { int requestedId = Integer.parseInt(Application.br.readLine()); if (ProfileStore.INSTANCE.hasProfile(requestedId)) { profileView.setProfileModel(ProfileStore.INSTANCE.getProfileModel(requestedId)); profileView.drawWithCanvas(); } else { System.out.println("There is no crimes with this Id"); } } catch (IOException ex) { ex.printStackTrace(); } } public ProfileModel getProfileModel() { return profileModel; } public void setProfileModel(ProfileModel profileModel) { this.profileModel = profileModel; } public ProfileView getProfileView() { return profileView; } public void setProfileView(ProfileView profileView) { this.profileView = profileView; } public Canvas getCanvas() { return canvas; } public void setCanvas(Canvas canvas) { this.canvas = canvas; } }
c86aa0d059800203710cfcff768b08cb39fc2110
467b74dfc6768b9f34f52595779e6fc420b656ac
/app/src/main/java/com/geekhive/foodeydeliveryboy/notifications/MyFirebaseMessagingService.java
ed75e0b37f4552e0cd4f2ea6317631047a831d88
[]
no_license
dprasad554/FoodeyDeliveryPartner
426f0a7c7c50573d44e8192aba35e7f7523f79f6
357ad5e61c7fc7f84219c918abd1e69cff8bb5e2
refs/heads/master
2023-04-17T07:09:43.317949
2021-05-03T08:57:23
2021-05-03T08:57:23
363,870,853
0
0
null
null
null
null
UTF-8
Java
false
false
18,484
java
/** * Copyright 2016 Google Inc. 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. * 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.geekhive.foodeydeliveryboy.notifications; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.media.AudioAttributes; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.DebugUtils; import android.util.Log; import android.widget.RemoteViews; import androidx.core.app.NotificationCompat; import com.geekhive.foodeydeliveryboy.R; import com.geekhive.foodeydeliveryboy.activities.CakeNewOrderAlert; import com.geekhive.foodeydeliveryboy.activities.GroceryNewOrderAlert; import com.geekhive.foodeydeliveryboy.activities.MainActivity; import com.geekhive.foodeydeliveryboy.activities.NewOrderAlertActivity; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; Uri soundUri; private MediaPlayer player; public static final String ACTION_1 = "action_1"; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ // [START receive_message] @Override public void onMessageReceived(RemoteMessage remoteMessage) { // [START_EXCLUDE] // There are two types of messages data messages and notification messages. LoginUserData messages // are handled // here in onMessageReceived whether the app is in the foreground or background. LoginUserData // messages are the type // traditionally used with GCM. Notification messages are only received here in // onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated // notification is displayed. // When the user taps on the notification they are returned to the app. Messages // containing both notification // and data payloads are treated as notification messages. The Firebase console always // sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // [END_EXCLUDE] // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); handleNow(); /* if (*//* Check if data needs to be processed by long running job *//* true) { // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); }*/ } // Check if message contains a notification payload. if (remoteMessage.getData() != null) { sendNotification(remoteMessage); Log.d(TAG, "Message Notification Body: " + remoteMessage.getData().toString()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. } // [END receive_message] // [START on_new_token] /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ @Override public void onNewToken(String token) { Log.d(TAG, "Refreshed token: " + token); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. sendRegistrationToServer(token); } // [END on_new_token] /** * Schedule a job using FirebaseJobDispatcher. */ /** * Handle time allotted to BroadcastReceivers. */ private void handleNow() { Log.d(TAG, "Short lived task is done."); } /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // TODO: Implement this method to send token to your app server. } private void sendNotification(RemoteMessage remoteMessage) { if (remoteMessage != null) { if (remoteMessage.getData().get("topic").equals("Resturant")){ String channelId = getString(R.string.app_name); Intent intent = new Intent(MyFirebaseMessagingService.this, NewOrderAlertActivity.class); intent.putExtra("position", 0); intent.putExtra("topic", remoteMessage.getData().get("topic")); intent.putExtra("ms", remoteMessage.getData().get("body")); Bundle bundle = new Bundle(); bundle.putString("ms", remoteMessage.getData().get("body")); Intent myIntent = new Intent("FBR-IMAGE"); myIntent.putExtra("position", 0); myIntent.putExtra("topic", remoteMessage.getData().get("topic")); myIntent.putExtra("ms", remoteMessage.getData().get("body")); myIntent.putExtra("NOTIF_BODY",bundle); this.sendStickyBroadcast(myIntent); PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMessagingService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT); if(remoteMessage.getData().get("body").contains("resturant confirm this order and preparing food")){ soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.howl); }else { soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.hold); } final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.remoteview_notification); String name = remoteMessage.getData().get("title") + "\n" + remoteMessage.getData().get("body"); remoteViews.setTextViewText(R.id.remoteview_notification_headline, name); remoteViews.setTextColor(R.id.remoteview_notification_headline, getResources().getColor(android.R.color.black)); // build notification final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MyFirebaseMessagingService.this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(remoteMessage.getData().get("title")) .setContentText(remoteMessage.getData().get("body")) .setAutoCancel(true) .setSound(soundUri) .setContent(remoteViews) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH); final Notification notification = mBuilder.build(); if (remoteMessage.getData().get("body").contains("resturant confirm this order and preparing food")){ notification.flags |= Notification.FLAG_INSISTENT; } // set big content view for newer androids if (android.os.Build.VERSION.SDK_INT >= 16) { notification.bigContentView = remoteViews; } NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); NotificationChannel mChannel = new NotificationChannel(channelId, getApplicationContext().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); // Configure the notification channel. mChannel.setDescription(remoteMessage.getData().get("body")); mChannel.enableLights(true); mChannel.enableVibration(true); mChannel.setSound(soundUri, attributes); // This is IMPORTANT if (mNotificationManager != null) mNotificationManager.createNotificationChannel(mChannel); } mNotificationManager.notify(0, notification); } else if(remoteMessage.getData().get("topic").equals("Grocery")){ String channelId = getString(R.string.app_name); Intent intent = new Intent(MyFirebaseMessagingService.this, GroceryNewOrderAlert.class); intent.putExtra("topic", remoteMessage.getData().get("topic")); intent.putExtra("ms", remoteMessage.getData().get("body")); Bundle bundle = new Bundle(); bundle.putString("ms", remoteMessage.getData().get("body")); Intent myIntent = new Intent("FBR-IMAGE"); myIntent.putExtra("position", 0); myIntent.putExtra("topic", remoteMessage.getData().get("topic")); myIntent.putExtra("ms", remoteMessage.getData().get("body")); myIntent.putExtra("NOTIF_BODY",bundle); this.sendStickyBroadcast(myIntent); PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMessagingService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT); Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.hold); final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.remoteview_notification); String name = remoteMessage.getData().get("title") + "\n" + remoteMessage.getData().get("body"); remoteViews.setTextViewText(R.id.remoteview_notification_headline, name); remoteViews.setTextColor(R.id.remoteview_notification_headline, getResources().getColor(android.R.color.black)); // build notification final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MyFirebaseMessagingService.this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(remoteMessage.getData().get("title")) .setContentText(remoteMessage.getData().get("body")) .setAutoCancel(true) .setSound(soundUri) .setContent(remoteViews) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH); final Notification notification = mBuilder.build(); // set big content view for newer androids if (android.os.Build.VERSION.SDK_INT >= 16) { notification.bigContentView = remoteViews; } NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); NotificationChannel mChannel = new NotificationChannel(channelId, getApplicationContext().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); // Configure the notification channel. mChannel.setDescription(remoteMessage.getData().get("body")); mChannel.enableLights(true); mChannel.enableVibration(true); mChannel.setSound(soundUri, attributes); // This is IMPORTANT if (mNotificationManager != null) mNotificationManager.createNotificationChannel(mChannel); } mNotificationManager.notify(1, notification); }else if (remoteMessage.getData().get("topic").equals("Cake")){ String channelId = getString(R.string.app_name); Intent intent = new Intent(MyFirebaseMessagingService.this, CakeNewOrderAlert.class); intent.putExtra("topic", remoteMessage.getData().get("topic")); intent.putExtra("ms", remoteMessage.getData().get("body")); Bundle bundle = new Bundle(); bundle.putString("ms", remoteMessage.getData().get("body")); Intent myIntent = new Intent("FBR-IMAGE"); myIntent.putExtra("position", 0); myIntent.putExtra("topic", remoteMessage.getData().get("topic")); myIntent.putExtra("ms", remoteMessage.getData().get("body")); myIntent.putExtra("NOTIF_BODY",bundle); this.sendStickyBroadcast(myIntent); PendingIntent pendingIntent = PendingIntent.getActivity(MyFirebaseMessagingService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT); Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.hold); final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.remoteview_notification); String name = remoteMessage.getData().get("title") + "\n" + remoteMessage.getData().get("body"); remoteViews.setTextViewText(R.id.remoteview_notification_headline, name); remoteViews.setTextColor(R.id.remoteview_notification_headline, getResources().getColor(android.R.color.black)); // build notification final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MyFirebaseMessagingService.this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(remoteMessage.getData().get("title")) .setContentText(remoteMessage.getData().get("body")) .setAutoCancel(true) .setSound(soundUri) .setContent(remoteViews) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH); final Notification notification = mBuilder.build(); // set big content view for newer androids if (android.os.Build.VERSION.SDK_INT >= 16) { notification.bigContentView = remoteViews; } NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); NotificationChannel mChannel = new NotificationChannel(channelId, getApplicationContext().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); // Configure the notification channel. mChannel.setDescription(remoteMessage.getData().get("body")); mChannel.enableLights(true); mChannel.enableVibration(true); mChannel.setSound(soundUri, attributes); // This is IMPORTANT if (mNotificationManager != null) mNotificationManager.createNotificationChannel(mChannel); } mNotificationManager.notify(1, notification); } } } public static class NotificationActionService extends IntentService { public NotificationActionService() { super(NotificationActionService.class.getSimpleName()); } @Override protected void onHandleIntent(Intent intent) { String action = intent.getAction(); Log.e("Received notification: " , action); if (ACTION_1.equals(action)) { // TODO: handle action 1. // If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID); } } } }
3b5025cd3ee0fb769f772a65d088f1598bbadd8b
384374289661905d16c99cd5e170313a25901764
/simple_net_framework/app/src/main/java/rainbow/com/simple_net_framework/base/Response.java
e4f1e572b46e59da8b619db4da5a215a9522bb37
[]
no_license
rhythmic-zone/personal
b3cbcaccb375a1fa8454d7c00e725d8842689892
214dad682215c87177cbc412afaaff8f81bfa631
refs/heads/master
2021-05-31T02:24:30.496455
2016-05-05T09:54:06
2016-05-05T09:54:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,159
java
package rainbow.com.simple_net_framework.base; import org.apache.http.HttpEntity; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.message.BasicHttpResponse; import org.apache.http.util.EntityUtils; import java.io.IOException; /** * Created by blue on 2015/7/6. */ public class Response extends BasicHttpResponse { public byte[] rawData = new byte[0]; public Response(StatusLine statusLine) { super(statusLine); } public Response(ProtocolVersion ver, int code, String reason) { super(ver, code, reason); } @Override public void setEntity(HttpEntity entity) { super.setEntity(entity); rawData = entityToBytes(entity); } public int getStatusCode() { return getStatusLine().getStatusCode(); } public String getStatusMessage() { return getStatusLine().getReasonPhrase(); } private byte[] entityToBytes(HttpEntity entity) { try { return EntityUtils.toByteArray(entity); } catch (IOException e) { e.printStackTrace(); } return new byte[0]; } }
995a23d228aadd2d47e63ffe84e5626853070303
10668fb9ddbcbcd9561462dafbfca8de522799f9
/LWJGL-Engine/src/renderEngine/MasterRenderer.java
156815401af79da4aac06461e471461f677f53a1
[]
no_license
c33-cooper/LWJGL-Engine
1c5b18b0346f6cac1d37a5b9adc49c87434bff83
09a91cfdf2a0c0d73053f4a13824acdc8c3eaab0
refs/heads/master
2021-01-17T13:01:42.939512
2016-06-26T16:54:03
2016-06-26T16:54:03
56,784,833
0
0
null
null
null
null
UTF-8
Java
false
false
3,366
java
package renderEngine; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Matrix4f; import entities.Camera; import entities.Entity; import entities.Light; import models.TexturedModel; import shaders.StaticShader; import shaders.TerrainShader; import terrains.Terrain; public class MasterRenderer { private static final float FOV = 70; private static final float NEAR_PLANE = 0.1f; private static final float FAR_PLANE = 1000; // Sky colour constants private static final float RED = 0.678431f; private static final float GREEN = 0.917647f; private static final float BLUE = 0.917647f; private Matrix4f projectionMatrix; private StaticShader shader = new StaticShader(); private EntityRenderer renderer; private TerrainRenderer terrainRenderer; private TerrainShader terrainShader = new TerrainShader(); private Map<TexturedModel, List<Entity>> entities = new HashMap<TexturedModel, List<Entity>>(); private List<Terrain> terrains = new ArrayList<Terrain>(); // Class constructor public MasterRenderer() { enableCulling(); createProjectionMatrix(); renderer = new EntityRenderer(shader, projectionMatrix); terrainRenderer = new TerrainRenderer(terrainShader, projectionMatrix); } public void render(List<Light> lights, Camera camera) { prepare(); shader.start(); shader.loadSkyColour(RED, GREEN, BLUE); shader.loadLights(lights); shader.loadViewMatrix(camera); renderer.render(entities); shader.stop(); terrainShader.start(); terrainShader.loadSkyColour(RED, GREEN, BLUE); terrainShader.loadLights(lights); terrainShader.loadViewMatrix(camera); terrainRenderer.render(terrains); terrainShader.stop(); // Clear lists and maps upon shutdown terrains.clear(); entities.clear(); } public static void enableCulling() { GL11.glEnable(GL11.GL_CULL_FACE); GL11.glCullFace(GL11.GL_BACK); } public static void disableCulling() { GL11.glDisable(GL11.GL_CULL_FACE); } public void processTerrain(Terrain terrain) { terrains.add(terrain); } public void processEntity(Entity entity) { TexturedModel entityModel = entity.getModel(); List<Entity> batch = entities.get(entityModel); if (batch != null) { batch.add(entity); }else { List<Entity> newBatch = new ArrayList<Entity>(); newBatch.add(entity); entities.put(entityModel, newBatch); } } public void prepare(){ GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glClearColor(RED, GREEN, BLUE, 1); } private void createProjectionMatrix() { float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight(); float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio); float x_scale = y_scale / aspectRatio; float frustum_length = FAR_PLANE - NEAR_PLANE; projectionMatrix = new Matrix4f(); projectionMatrix.m00 = x_scale; projectionMatrix.m11 = y_scale; projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length); projectionMatrix.m23 = -1; projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length); projectionMatrix.m33 = 0; } public void cleanpUp() { shader.cleanUp(); terrainShader.cleanUp(); } }
d0a01ab252daab461092f3488f7389febcfa5213
67ac451563029fa699a27cf40e7eaed2d327ebf5
/src/com/steadfast/annotations/Coach.java
905796598f713410a345f98e2ce91e0cb4d6424f
[]
no_license
lopezjronald/spring-annutation-components
45d12bb9ed790c6aac79f5fdce7a921fcc18e8fc
41889685c89e5a166251fcf74ec8551f776e7834
refs/heads/main
2023-06-12T21:04:16.293585
2021-06-29T09:13:06
2021-06-29T09:13:06
381,170,893
0
0
null
null
null
null
UTF-8
Java
false
false
157
java
package com.steadfast.annotations; public interface Coach { String getDailyWorkout(); String getDailyChallenge(); String getDailyFortune(); }
e4a776cb914b8c24c28affeedffe549db69ebb7a
4b6092d2eff199d0251b57e4ab8aeac183e3708a
/boot/src/main/java/com/junhwan/BootApplication.java
5d4a206d11a97452ac6ec91b60d0e7e9ce9c6405
[]
no_license
JunHwan94/20180410
ea059fcc01d152c79cebc19c46fc585db0a684bd
198ae0260174b7c1b9189fb9878fbf7d7e03253f
refs/heads/master
2020-03-10T20:46:37.150219
2018-04-15T04:43:20
2018-04-15T04:43:20
129,576,980
0
0
null
null
null
null
UTF-8
Java
false
false
299
java
package com.junhwan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BootApplication { public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); } }
30eafc9c09c663f6092cdf6bde2861a39a72f840
a33363a625e2da7886fe16bd4a1405a95648e11f
/src/main/java/designpatterns/structural/proxy/ComplexImage.java
2d3ec977d00e400f5e84badfa4ef64d1a5fdb2fc
[]
no_license
dimitar-iliyanov-stoyanov/game-platform
beee07a492988ec0349eb63e304e289ea5e4a4a6
88e4d854d26f110cdc7df486fc548833360c16c4
refs/heads/master
2021-04-03T09:13:54.194164
2018-05-03T23:56:34
2018-05-03T23:56:34
125,066,719
0
0
null
null
null
null
UTF-8
Java
false
false
97
java
package designpatterns.structural.proxy; public interface ComplexImage { void flyingColors(); }
acd854a2a4efc44995b7e10f19942d24d5119cac
6f0c21fdad5ef04b99d3fed90899a69ac66be1f8
/app/src/main/java/cn/droidlover/txzn/sys/utils/AssetsJsonReader.java
d625aee88d1cd0f193f3e2e9ff90ba29cdef5078
[ "MIT" ]
permissive
ronaldoWang/2018008
e25b649c321aa49a22efab4c9dd638c0362c06ba
8b91e2538c176c0efc3f24275016db5a2d2391eb
refs/heads/master
2020-03-22T18:08:03.803021
2018-07-10T13:49:17
2018-07-10T13:49:17
140,428,907
0
0
null
null
null
null
UTF-8
Java
false
false
1,082
java
package cn.droidlover.txzn.sys.utils; import android.content.Context; import android.content.res.AssetManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by ronaldo on 2017/7/14. */ public class AssetsJsonReader { /** * 读取asset下的json文件 * * @param context * @param path assets下json文件路径 * @return */ public static String getJsonString(Context context, String path) { AssetManager assetManager = context.getAssets(); try { InputStream is = assetManager.open(path); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer stringBuffer = new StringBuffer(); String str = null; while ((str = br.readLine()) != null) { stringBuffer.append(str); } return stringBuffer.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } }
60884623be9d6e509eed18e082184080c71984a6
e7f51c439383cada899cea71fe013767c80d8c69
/OA/src/main/java/com/app/OA/domain/User.java
61f7db00e52a540ff6f5c485ee52664cdd6082ae
[]
no_license
shaozicheng/demo
24ba2e84bcff8dd4c13787f0f58cf4fc6f360c4d
70926b6ab8bf57770cd1bb921d070afea0303829
refs/heads/master
2020-03-29T21:28:30.401720
2018-11-15T06:47:42
2018-11-15T06:47:42
150,368,690
0
0
null
null
null
null
UTF-8
Java
false
false
3,041
java
package com.app.OA.domain; import java.io.Serializable; import java.util.List; public class User implements Serializable{ private static final long serialVersionUID = 2416069058255000796L; //用户序列id private Integer id; //用户唯一id private String guid; //用户账户 private String name; //密码 private String passWard; //姓名 private String userName; //手机号 private String userPhone; //性别 private Integer userSex; //生日 private String userBoth; //角色 private Integer roleGrade; //角色名称 private String roleName; //最后一次登录时间 private String lastLoginTime; //账户创建时间 private String createTime; //状态 private Integer status; //最后一次登出时间 private String lastOutTime; //最后一次修改时间 private String updateTime; //所获取的系列ID List<Integer> ids; public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; } public String getUserBoth() { return userBoth; } public void setUserBoth(String userBoth) { this.userBoth = userBoth; } public Integer getRoleGrade() { return roleGrade; } public void setRoleGrade(Integer roleGrade) { this.roleGrade = roleGrade; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public Integer getUserSex() { return userSex; } public void setUserSex(Integer userSex) { this.userSex = userSex; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public static long getSerialversionuid() { return serialVersionUID; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassWard() { return passWard; } public void setPassWard(String passWard) { this.passWard = passWard; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(String lastLoginTime) { this.lastLoginTime = lastLoginTime; } public String getLastOutTime() { return lastOutTime; } public void setLastOutTime(String lastOutTime) { this.lastOutTime = lastOutTime; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
4e8c0bcbfce0b60368d980b7dd0b3aa6817fca7b
d90bb274b54a26dab4da84174e03b56726cae47d
/app/src/main/java/com/example/submission3/detail/DetailMovieActivity.java
f3449cee30217395d634bccead564dcbc04da835
[]
no_license
kuroiyuki48/Made---Submission3
ee61e1b497051e8085453db7cea5bbb5f8c6345f
9469d4e3613eac081f78c6c19d228bd799fad7ef
refs/heads/master
2020-08-02T10:10:04.230487
2019-09-29T01:29:22
2019-09-29T01:29:22
211,313,121
0
0
null
null
null
null
UTF-8
Java
false
false
1,588
java
package com.example.submission3.detail; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.submission3.R; import com.example.submission3.model.MovieData; public class DetailMovieActivity extends AppCompatActivity { public static final String EXTRA_MOVIE = "extra_movie"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_movie); TextView mvTitle = findViewById(R.id.tv_item_name); TextView releaseDate = findViewById(R.id.tv_item_release); TextView voteAverage = findViewById(R.id.tv_item_score); TextView tvPopularity = findViewById(R.id.tv_popularity); TextView contentOverview = findViewById(R.id.tv_item_overview); ImageView posterPath = findViewById(R.id.img_item_photo); MovieData movieData = getIntent().getParcelableExtra(EXTRA_MOVIE); mvTitle.setText(movieData.getTitle()); releaseDate.setText(movieData.getReleaseDate()); String voteNumber = movieData.getVoteAverage().toString(); String percent = "/10"; String voteValue =voteNumber + percent; voteAverage.setText(voteValue); tvPopularity.setText(String.valueOf(movieData.getPopularity())); contentOverview.setText(movieData.getOverview()); Glide.with(this).load(movieData.getPosterPath()) .into(posterPath); } }
fd14cd2a882e7bdbad6c6431218ca947519288f1
e1654b40d77069dc5ea89bf99e61133ba7d8abdf
/src/main/java/com/yogesh/leetcode/hard/Leetcode1278.java
e58526ca59812b72fb62712fe8198d21cf5b0294
[]
no_license
yoshrawat/DataStructuresAndAlgo
e7503741d19b2fdb4a07ba97a6200432867f8ba6
4f0f56f091b37181c3229920bdaa19bd1549d857
refs/heads/master
2020-12-27T07:08:16.693713
2020-05-17T12:15:16
2020-05-17T12:15:16
237,808,080
0
0
null
null
null
null
UTF-8
Java
false
false
3,504
java
package com.yogesh.leetcode.hard; import java.util.*; public class Leetcode1278 { public static void main(String[] args) { String str = "uyskbebqrhfoythvwazswib"; // String str = "abc"; System.out.println(palindromePartition_1(str,2)); } // bottom up approach static Map<String, Integer> map = new HashMap<>(); public static int palindromePartition_1(String s, int k) { int len = s.length(); char[] ch = s.toCharArray(); int[][] dp = new int[k][len]; for( int i =0; i < len; i++) { dp[0][i] = helper( ch, 0, i); } //dp[i][j] min cost to split string [0,j] into i part for (int i = 1; i < k; ++i){ for (int j = i; j < len; ++j){ int cur = Integer.MAX_VALUE; for (int p = j; p >= i; p--){ cur = Math.min(cur, dp[i - 1][p - 1] + helper(ch, p-1, j-1)); } dp[i][j] = cur; } } return dp[k-1][len-1]; } private static int helper(String str){ if (str == null || str.length() == 0) return 0; if (map.containsKey(str)) return map.get(str); int res = 0; for (int i = 0; i < str.length(); ++i){ if (str.charAt(i) != str.charAt(str.length() - i - 1)) res++; } res /= 2; map.put(str, res); return res; } private static int helper(char[] ch, int left, int right) { String key = left+ "_" + right; if( map.containsKey(key)) return map.get(key); int ans=0; while( left < right) { if(ch[left] != ch[right]) { ans++; } left++; right--; } map.put(key, ans); return ans; } public static int palindromePartition(String s, int k) { char[] ch = s.toCharArray(); int len = ch.length; int[][] dp = new int[len][len]; // for len 1 for( int i =0; i < len; i++) { dp[i][i] = 0; } // for lem 2 for( int i =0; i < len-1; i++) { if( ch[i] == ch[i+1]) dp[i][i+1] = 0; else dp[i][i+1] = 1; } // for len > 2 for( int window =2; window < len; window++) { for( int i =0, j = window; j < len; ++j, ++i) { if( ch[i] == ch[j]) dp[i][j] = dp[i+1][j-1]; else dp[i][j] = dp[i+1][j-1] + 1; } } for( int[] rows : dp) { System.out.println( Arrays.toString(rows)); } int result = dfs(dp, ch,0, k, 0); System.out.println( result); return result == Integer.MAX_VALUE ? 0 : result; } private static int dfs( int[][] dp , char[] ch, int index , int k , int ans ) { // base condition if( (index == ch.length) && k == 0 ) return ans; if( k != 0 && index >= ch.length ) return Integer.MAX_VALUE; if( k < 0 ) return Integer.MAX_VALUE; String key = index + "_" + k; /*if( map.containsKey(key)) return map.get(key);*/ int result = Integer.MAX_VALUE; for( int i = index; i < ch.length; i++) { result = Math.min( result, dfs( dp, ch, i+1, k -1, ans + dp[index][i])); } map.put(key, result); return result; } }
fcd2fb72d5f45cf44454f2752625b7460c773620
1d4ce8e99856761a472fcc66a6843d091404fea2
/app/src/main/java/doistres/werewolf/Player.java
7710e438ba7500dd113ee1073c7d66500b23bf5f
[]
no_license
allan-pires/werewolf-moderator-helper
c8a4d30f4000c254566913e0d751484800160b49
bd168db3933c08e8ac37c7877bc3646b8a2009fd
refs/heads/master
2021-08-24T07:44:19.370452
2017-12-08T17:56:51
2017-12-08T17:56:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
905
java
package doistres.werewolf; import android.widget.ImageView; /** * Created by doisl_000 on 21/01/2015. */ public class Player { // Classe do jogador Role role; // Amante, caso o jogador tenha sido selecionado pelo cupido Player bound; // Indicador de ligação amorosa realizada pelo cupido boolean love_bind; // Indicador de morte boolean dead; ImageView img; // Construtor padrão Player(){ this.role= new Role(); this.bound = new Player(); this.love_bind = false; this.dead = false; } // Construtor de roles Player(Role role){ this.role = role; this.dead = false; } // Retorna se o jogador está morto public boolean isDead(){ return this.dead; } // Retorna se o jogador tem um amante public boolean isLoveBind(){ return this.love_bind; } }
12384bad71e2c67929e401e448c12e65e5a78965
a55ef0a8cbfbaff689d1fcaa0a61d2918442b4ec
/src/Model/SanPhamNhap.java
8003429236b4dc6ef837d3208490d54bc53e4695
[]
no_license
khoaihdkg3/QuanLyBanHang
92718205ac2408a3784c803ae8b15af415cca5ca
1016b53732694c4807ce2ba2e60aa8392e6e8a0f
refs/heads/master
2021-05-08T08:04:44.034639
2017-10-24T14:50:20
2017-10-24T14:50:20
106,977,773
0
0
null
null
null
null
UTF-8
Java
false
false
1,447
java
package Model; import java.util.Date; /* * 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 student */ public class SanPhamNhap { private SanPham SanPham; private Date NgayNhap; private float DonGiaNhap; private int SoLuong; public SanPhamNhap(SanPham SanPham, Date NgayNhap, float DonGiaNhap, int SoLuong) { this.SanPham = SanPham; this.NgayNhap = NgayNhap; this.DonGiaNhap = DonGiaNhap; this.SoLuong = SoLuong; } public float getDonGiaNhap() { return DonGiaNhap; } public Date getNgayNhap() { return NgayNhap; } public SanPham getSanPham() { return SanPham; } public int getSoLuong() { return SoLuong; } public void setDonGiaNhap(float DonGiaNhap) { this.DonGiaNhap = DonGiaNhap; } public void setNgayNhap(Date NgayNhap) { this.NgayNhap = NgayNhap; } public void setSanPham(SanPham SanPham) { this.SanPham = SanPham; } public void setSoLuong(int SoLuong) { this.SoLuong = SoLuong; } @Override public String toString() { return getSanPham().getMa()+"|"+getNgayNhap()+"|"+getDonGiaNhap()+"|"+getSoLuong(); } }
[ "THINH@THINH-PC" ]
THINH@THINH-PC
d229dbf31fa1bba2ad8696ad4aa19c04205b94bb
689fecc15eea018212536a736f636fcbc8333549
/src/org/home/mazi/functionalprogramming/chapter2/Chapter2Video8.java
f654c0b585a4608f6d55e3b16a9a23ee992667f8
[]
no_license
MAZIShadow/FunctionalProgramming-training
e675c22ff1addf271cb1611f9f8edf8e5c2ef2b5
92db34e8cfb5a8b4e4d78230e48e672fe4c5f86d
refs/heads/main
2023-03-08T12:24:10.128945
2021-02-19T22:56:41
2021-02-19T22:56:41
338,279,084
0
0
null
null
null
null
UTF-8
Java
false
false
659
java
package org.home.mazi.functionalprogramming.chapter2; import java.util.function.BiFunction; import java.util.function.Function; public class Chapter2Video8 { public static void main(String[] args) { BiFunction<Float, Float, Float> divide = (x, y) -> x / y; Function<BiFunction<Float, Float, Float>, BiFunction<Float, Float, Float>> secondArgIsntZeroCheck = (func) -> (x, y) -> { if (y == 0f){ System.out.println("Error: second argument is zero!"); return 0f; } return func.apply(x,y); }; BiFunction<Float, Float, Float> divideSafe = secondArgIsntZeroCheck.apply(divide); System.out.println(divideSafe.apply(10f,2f)); } }
4a2bc7b95948f045900bbb8b5a0de1654ffd2099
5d9e3ef718665d4a830c5f131de774662fe80753
/src/main/java/com/gravlle/portal/security/SecurityContextAccessorImpl.java
69007742bb03ab36c9b5f608773b8326bcd09aa5
[]
no_license
robinvk6/Gravlle
681aa3fec01726461b584e2e2d3aa1eb108bc16b
ef13dd726a463b88bc94144a6bc9eb41d4aad768
refs/heads/master
2021-01-23T18:51:06.919986
2014-10-26T06:03:33
2014-10-26T06:03:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
716
java
package com.gravlle.portal.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; public final class SecurityContextAccessorImpl implements SecurityContextAccessor { @Autowired private AuthenticationTrustResolver authenticationTrustResolver; public boolean isCurrentAuthenticationAnonymous() { final Authentication authentication = SecurityContextHolder .getContext().getAuthentication(); return authenticationTrustResolver.isAnonymous(authentication); } }
11970c316085a250dcde260550dc856efabc8586
a2ef440e4876b6cee4a14f4d81b96c624bb16aea
/works-ts/src/main/java/de/kp/works/ts/ar/TsYuleWalker.java
262999e70cf251895d71a24bbc6794be47e4498b
[ "Apache-2.0" ]
permissive
patilbasanagowdaec/cdap-spark
5323867fa4c37b41b90d372b9fe5ad6cf1b11e51
0084c75e64a102ac4c02d6e9bf1dc31a04a679da
refs/heads/master
2023-03-29T09:33:29.792957
2021-03-31T06:05:33
2021-03-31T06:05:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,111
java
package de.kp.works.ts.ar; /* * Copyright (c) 2019 Dr. Krusche & Partner PartG. 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. 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. * * @author Stefan Krusche, Dr. Krusche & Partner PartG * */ import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import io.cdap.cdap.api.annotation.Description; import io.cdap.cdap.api.annotation.Name; import io.cdap.cdap.api.annotation.Plugin; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.cdap.etl.api.PipelineConfigurer; import io.cdap.cdap.etl.api.StageConfigurer; import io.cdap.cdap.etl.api.batch.SparkCompute; import io.cdap.cdap.etl.api.batch.SparkExecutionPluginContext; import de.kp.works.ts.model.ARYuleWalkerModel; @Plugin(type = SparkCompute.PLUGIN_TYPE) @Name("TsYuleWalker") @Description("A prediction stage that leverages a trained Apache Spark based Yule Walker AR time series model.") public class TsYuleWalker extends ARCompute { private static final long serialVersionUID = -3512433728877952854L; private TsYuleWalkerConfig config; private ARYuleWalkerModel model; public TsYuleWalker(TsYuleWalkerConfig config) { this.config = config; } @Override public void initialize(SparkExecutionPluginContext context) throws Exception { config.validate(); ARRecorder recorder = new ARRecorder(); /* * STEP #1: Retrieve the trained regression model * that refers to the provide name, stage and option */ model = recorder.readYuleWalker(context, config.modelName, config.modelStage, config.modelOption); if (model == null) throw new IllegalArgumentException( String.format("[%s] A Yule Walker AutoRegression model with name '%s' does not exist.", this.getClass().getName(), config.modelName)); /* * STEP #2: Retrieve the profile of the trained * regression model for subsequent annotation */ profile = recorder.getProfile(); } @Override public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { config.validate(); StageConfigurer stageConfigurer = pipelineConfigurer.getStageConfigurer(); /* * Try to determine input and output schema; if these schemas are not explicitly * specified, they will be inferred from the provided data records */ inputSchema = stageConfigurer.getInputSchema(); if (inputSchema != null) { validateSchema(inputSchema); /* * In cases where the input schema is explicitly provided, we determine the * output schema by explicitly adding the prediction column */ outputSchema = getOutputSchema(config.timeCol, config.valueCol, STATUS_FIELD); stageConfigurer.setOutputSchema(outputSchema); } } @Override public Dataset<Row> compute(SparkExecutionPluginContext context, Dataset<Row> source) throws Exception { TsYuleWalkerConfig computeConfig = (TsYuleWalkerConfig)(config); /* Time & value column may have names different from traing phase */ model.setTimeCol(computeConfig.timeCol); model.setValueCol(computeConfig.valueCol); Dataset<Row> forecast = model.forecast(source, config.steps); return assembleAndAnnotate(source, forecast, config.timeCol, config.valueCol); } @Override public void validateSchema(Schema inputSchema) { config.validateSchema(inputSchema); } public static class TsYuleWalkerConfig extends ARComputeConfig { private static final long serialVersionUID = -864185065637543716L; public TsYuleWalkerConfig() { modelOption = "BEST_MODEL"; modelStage = "experiment"; steps = 1; } public void validate() { super.validate(); } } }
8dbc70418f2f108a7e27f3400c9f472b64c5966e
4a90b65f27d6b0ba4b79c00cc550e2902ac58038
/HomeworkJava CollectionsBasics/_20_LogsAggregator.java
d740251852aafec70701255a0c746b1578f58edd
[]
no_license
MirenaAngelova/Java
9e8b00954e50228bcc5bceb9ea525348e8432bf5
72698074a36baae895140ad1203165b389e1ce14
refs/heads/master
2021-05-04T10:20:14.004100
2016-09-06T18:52:20
2016-09-06T18:52:20
54,633,916
0
0
null
null
null
null
UTF-8
Java
false
false
1,214
java
import java.util.*; public class _20_LogsAggregator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numsOfInputLines = scanner.nextInt(); scanner.nextLine(); TreeMap<String, Integer> logDuration = new TreeMap<>(); HashMap<String, TreeSet<String>> logIp = new HashMap<>(); for (int i = 0; i < numsOfInputLines; i++) { String[] tokens = scanner.nextLine().trim().split(" "); String ipAddress = tokens[0]; String name = tokens[1]; int duration = Integer.parseInt(tokens[2]); Integer res = logDuration.get(name); if (res == null) { res = 0; } logDuration.put(name, res + duration); TreeSet<String> resIp = logIp.get(name); if (resIp == null) { resIp = new TreeSet<>(); } resIp.add(ipAddress); logIp.put(name, resIp); } for (Map.Entry<String, Integer> entry : logDuration.entrySet()) { System.out.printf("%s: %d " + logIp.get(entry.getKey()) + "\n", entry.getKey(), entry.getValue()); } } }
6cacb4368e05b201ffb44dcc931c817950a04622
8dbb35905bd968d46334c706584bd0211b5d5912
/app/src/androidTest/java/com/example/zyilin/timecheckapplication/ExampleInstrumentedTest.java
9207ff6df0c2200f440217588c2db97e9f29162d
[]
no_license
Zyilin/COMP231-001_Group4_Project
234966ce1506063988ef4d5abc183f7544b8ad81
cf179b889d52d6812cf911ac17d20b71f5238c83
refs/heads/master
2020-07-24T06:08:16.717987
2019-11-10T09:11:45
2019-11-10T09:11:45
207,823,251
3
0
null
null
null
null
UTF-8
Java
false
false
762
java
package com.example.zyilin.timecheckapplication; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.zyilin.timecheckapplication", appContext.getPackageName()); } }
e2fdeb319043cb2236530fc5dbaf56b256743814
349f314c07582402b790f64229a3f40231ba269f
/hemesh/wblut/geom/WB_ClassifyPointToPlane.java
860de650909abb6e8110bbe0e9913fd97dfb06f5
[]
no_license
blvkoblsk/Meshia
33b645194b7c0e9ad1ad3f56531365a084ff2e28
c92764a4069ac00669923c17e9d0bf5d3875f6d8
refs/heads/master
2021-01-19T20:55:59.629816
2015-06-16T19:50:59
2015-06-16T19:50:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
360
java
/** * */ package wblut.geom; // TODO: Auto-generated Javadoc /** * The Enum WB_ClassifyPointToPlane. * * @author Frederik Vanhoutte, W:Blut */ public enum WB_ClassifyPointToPlane { /** Point on plane. */ POINT_ON_PLANE, /** Point on positive side of plane. */ POINT_IN_FRONT_OF_PLANE, /** Point on negative side of plane. */ POINT_BEHIND_PLANE }
c6331daff30521cbaddca387bfc12f196c77ea2f
830960be3aa4879159a6d03c39f192e5bb741a65
/BootM7Exception07-CustomRestExceptions/src/main/java/siva/bootexception/BootM7Exception07CustomRestExceptionsApplication.java
daf2e0e5761f18675bbbfaa57af268aaed8f6275
[]
no_license
siva1855/WS-SpringBoot4
addbe3f5df76130d7c74adcdcd398c80b9ad2146
89d0bbc6bbade5b296c7bb8eb70d7ea32e875de3
refs/heads/master
2023-04-05T05:23:05.384756
2021-04-15T15:12:51
2021-04-15T15:12:51
358,295,217
0
0
null
null
null
null
UTF-8
Java
false
false
373
java
package siva.bootexception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BootM7Exception07CustomRestExceptionsApplication { public static void main(String[] args) { SpringApplication.run(BootM7Exception07CustomRestExceptionsApplication.class, args); } }
8a57d7916aa16c40b1d40449f0f5336915d2f277
ff97e8426cbe9423780ca61aae4eaf9e8b182a55
/src/test/java/au/edu/ardc/registry/common/controller/api/resources/VersionResourceControllerIT.java
ca264886edac2e152ba57f846216db4ff869e03f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
au-research/igsn-metadata-registry
9903104f10bceac60096a9934f4b330b20841e1e
ccabd9d1ce05a9409fa74defecc66b8e8c277363
refs/heads/master
2023-08-12T03:55:07.761514
2021-09-26T23:10:54
2021-09-26T23:10:54
409,016,652
0
0
null
null
null
null
UTF-8
Java
false
false
2,965
java
package au.edu.ardc.registry.common.controller.api.resources; import au.edu.ardc.registry.KeycloakIntegrationTest; import au.edu.ardc.registry.TestHelper; import au.edu.ardc.registry.common.dto.VersionDTO; import au.edu.ardc.registry.common.entity.Record; import au.edu.ardc.registry.common.repository.RecordRepository; import au.edu.ardc.registry.common.service.SchemaService; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import reactor.core.publisher.Mono; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import static org.exparity.hamcrest.date.DateMatchers.sameDay; class VersionResourceControllerIT extends KeycloakIntegrationTest { @Autowired RecordRepository recordRepository; @Test void store_NotLoggedIn_401() { // when POST without logging in, 401 this.webTestClient.post().uri("/api/resources/versions/").exchange().expectStatus().isUnauthorized(); } @Test void store_ValidRequest_201() { // has a record that the user owns Record record = TestHelper.mockRecord(); record.setOwnerID(UUID.fromString(userID)); record.setOwnerType(Record.OwnerType.User); recordRepository.saveAndFlush(record); // dto of a new version VersionDTO dto = new VersionDTO(); dto.setRecord(record.getId().toString()); dto.setSchema(SchemaService.IGSNDESCv1); dto.setContent(Base64.encodeBase64String("some-string".getBytes())); // when POST, expects 201 with a header this.webTestClient.post().uri("/api/resources/versions/") .header("Authorization", getBasicAuthenticationHeader(username, password)) .body(Mono.just(dto), VersionDTO.class).exchange().expectStatus().isCreated().expectHeader() .exists("Location").expectBody().jsonPath("$.id").exists().jsonPath("$.createdAt").exists(); } @Test void store_ImportPermission_201OverwriteData() throws ParseException { // has a record that the user owns Record record = TestHelper.mockRecord(); record.setOwnerID(UUID.fromString(userID)); record.setOwnerType(Record.OwnerType.User); recordRepository.saveAndFlush(record); // dto of a new version VersionDTO dto = new VersionDTO(); dto.setRecord(record.getId().toString()); dto.setSchema(SchemaService.IGSNDESCv1); dto.setContent(Base64.encodeBase64String("stuff".getBytes())); Date expectedDate = new SimpleDateFormat("dd/MM/yyyy").parse("02/02/1989"); dto.setCreatedAt(expectedDate); // when POST, expects 201 with a Location header, overwritten createdAt this.webTestClient.post().uri("/api/resources/versions/") .header("Authorization", getBasicAuthenticationHeader(username, password)) .body(Mono.just(dto), VersionDTO.class).exchange().expectStatus().isCreated().expectHeader() .exists("Location").expectBody().jsonPath("$.id").exists() .jsonPath("$.createdAt", sameDay(expectedDate)).hasJsonPath(); } }
a5cdb8390e726c0f2a700f54fefc0309f123fccb
054e4fcdd220f2b2be7c99a0b3465c1221a77d63
/JuegoPreguntasV2CF/app/src/main/java/com/example/juegopreguntasv2cf/LoginActivity.java
77dd0d24dee992a24e87b56e9b771c05baeb5f7a
[]
no_license
juanra1997/PMDM
0d23f0e17782c2c728825e04f122c65252b9bc5d
e0f383aa466a127c9ef3aa618ada28b42178671e
refs/heads/master
2020-03-30T01:27:17.295589
2019-03-12T19:56:15
2019-03-12T19:56:15
150,576,896
0
0
null
null
null
null
UTF-8
Java
false
false
949
java
package com.example.juegopreguntasv2cf; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; public class LoginActivity extends AppCompatActivity { EditText e1, e2, e3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); e1 = (EditText) findViewById(R.id.p1); e2 = (EditText) findViewById(R.id.p2); e3 = (EditText) findViewById(R.id.p3); } public void entrar(View v) { if (!e1.getText().toString().equals("juanra3") && !e2.getText().toString().equals("23334373E") && !e3.getText().toString().equals("jrmg010203tmg")) { finish(); } else { Intent i = new Intent(this, VisualizarActivity.class); startActivity(i); } } }
042e8c92758d14e090f6c965b6d2a3cea85ee0af
c04581e0455dc4ce42e876f4f0cfaec174dec9c2
/app/src/main/java/lzn/chat/absActivity.java
5ff81cbd32f996957bf0d690411e1790f2eacc10
[]
no_license
13824122863/Chat
5514745bb697c9406f11b3b485257e0ec1c96e9f
cbf35e5d1c69034ab75d405fa3547630edb45308
refs/heads/master
2020-02-26T16:41:53.725308
2016-06-17T08:57:22
2016-06-17T08:57:22
59,191,755
0
0
null
null
null
null
UTF-8
Java
false
false
5,942
java
package lzn.chat; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.NotificationCompat; import android.view.WindowManager; import com.hyphenate.EMMessageListener; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMMessage; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import lzn.chat.db.DBManager; import lzn.chat.main.item.contactItem.chat.model.MsgModel; import lzn.chat.main.item.contactItem.chat.view.ChatActivity; import lzn.chat.main.view.MainActivity; import lzn.chat.tools.ConstantManager; import lzn.chat.tools.Utils; /** * Created by Allen on 2016/5/24. */ public abstract class absActivity extends AppCompatActivity { protected myApplication mvApplication; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置状态栏透明,经测试在代码里直接声明透明状态栏更有效 WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes(); localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags); mvApplication = myApplication.getInstance(); } @Override protected void onResume() { super.onResume(); registerReceiver(); } private void registerReceiver() { IntentFilter lvIntentFliter = new IntentFilter(); lvIntentFliter.addAction(ConstantManager.CHAT_RECEIVER); registerReceiver(mvChatListenertReceiver, lvIntentFliter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mvChatListenertReceiver); } BroadcastReceiver mvChatListenertReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent pIntent) { if (pIntent.getAction().equals(ConstantManager.CHAT_RECEIVER)) { List<MsgModel> lvList = (ArrayList) pIntent.getExtras().getSerializable(ConstantManager.CHAT_RECEIVE_MSG_LIST); DBManager lvDBManager = mvApplication.getDBManager(); lvDBManager.addChatMsg(lvList); newMsg(lvList); } } }; public abstract void newMsg(List<MsgModel> pMessage); @Override protected void onDestroy() { super.onDestroy(); EMClient.getInstance().chatManager().removeMessageListener(msgListener); } public EMMessageListener msgListener = new EMMessageListener() { @Override public void onMessageReceived(List<EMMessage> pMessage) { //收到消息,应该先存消息到数据库SQLite! Intent lvIntent = new Intent(); lvIntent.setAction(ConstantManager.CHAT_RECEIVER); Bundle lvBundle = new Bundle(); lvBundle.putSerializable(ConstantManager.CHAT_RECEIVE_MSG_LIST, getSerializable(pMessage)); lvIntent.putExtras(lvBundle); sendBroadcast(lvIntent); } @Override public void onCmdMessageReceived(List<EMMessage> messages) { //收到透传消息 } @Override public void onMessageReadAckReceived(List<EMMessage> messages) { //收到已读回执 } @Override public void onMessageDeliveryAckReceived(List<EMMessage> message) { //收到已送达回执 } @Override public void onMessageChanged(EMMessage message, Object change) { //消息状态变动 } }; private Serializable getSerializable(List<EMMessage> pMessage) { ArrayList<MsgModel> lvList = new ArrayList<>(); MsgModel lvMsgModel; for (EMMessage lvMsg : pMessage) { lvMsgModel = new MsgModel(); lvMsgModel.setContent(Utils.replaceMsgContent(lvMsg.getBody().toString())); lvMsgModel.setFrom(lvMsg.getFrom()); lvMsgModel.setTo(lvMsg.getTo()); lvMsgModel.setReceiveTime(Utils.long2String(lvMsg.getMsgTime())); lvList.add(lvMsgModel); } return lvList; } public void NewMsgNotification(List<MsgModel> pModelList) { for (MsgModel lvModel : pModelList) { this.NewMsgNotification(lvModel); } } public void NewMsgNotification(MsgModel pMsgModel) { NotificationCompat.Builder lvBuilder = new NotificationCompat.Builder(this); NotificationManager lvManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); lvBuilder.setContentTitle(pMsgModel.getFrom()); lvBuilder.setContentText(pMsgModel.getContent()); lvBuilder.setSmallIcon(R.drawable.account_icon); lvBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); Intent lvIntent1 = new Intent(this, ChatActivity.class); lvIntent1.putExtra(ChatActivity.CHATTOWHO, pMsgModel.getFrom()); lvIntent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); Intent lvIntent0 = new Intent(this, MainActivity.class); Intent[] lvIntents = new Intent[2]; lvIntents[0] = lvIntent0; lvIntents[1] = lvIntent1; PendingIntent resultPendingIntent = PendingIntent.getActivities(this, 0, lvIntents, PendingIntent.FLAG_CANCEL_CURRENT); lvBuilder.setContentIntent(resultPendingIntent); // lvBuilder.setFullScreenIntent(resultPendingIntent, true); lvBuilder.setAutoCancel(true); lvBuilder.setColor(ContextCompat.getColor(this, R.color.colorAccent)); lvManager.notify(1, lvBuilder.build() ); } }
f46e725129b6467efce2f56ea442add3938e905f
44c4827bd6fce2c47406744572f83211266bd973
/src/main/java/xyz/kingsword/course/service/impl/ExecutionVerifyImpl.java
3efbd860d51ef1a59244168c85d47672e12da323
[]
no_license
Deathlightning/teachingProcess
34a297616edb29e88325cdb68e2fba9adbd0c17b
77a829098a8949fad403ceb10cd0e6bd207a389d
refs/heads/dev
2022-06-23T20:38:27.576818
2020-01-08T08:51:20
2020-01-08T08:51:20
213,849,774
0
0
null
2022-06-21T02:24:25
2019-10-09T07:25:29
Java
UTF-8
Java
false
false
7,678
java
package xyz.kingsword.course.service.impl; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import xyz.kingsword.course.VO.VerifyField; import xyz.kingsword.course.VO.VerifyResult; import xyz.kingsword.course.enmu.ErrorEnum; import xyz.kingsword.course.exception.BaseException; import xyz.kingsword.course.exception.DataException; import xyz.kingsword.course.pojo.ExecutionPlan; import xyz.kingsword.course.pojo.TrainingProgram; import xyz.kingsword.course.service.ExecutionVerify; import xyz.kingsword.course.util.ConditionUtil; import java.util.*; import java.util.stream.Collectors; @Slf4j @Service public class ExecutionVerifyImpl implements ExecutionVerify { /** * 验证培养方案与执行计划的不同 * * @param executionPlanList executionPlanList * @param trainingProgramList trainingProgramList */ @Override public VerifyResult verify(List<ExecutionPlan> executionPlanList, List<TrainingProgram> trainingProgramList) { ConditionUtil.validateTrue(!trainingProgramList.isEmpty()).orElseThrow(() -> new DataException(ErrorEnum.TRAINING_PROGRAM_ERROR)); ConditionUtil.validateTrue(!executionPlanList.isEmpty()).orElseThrow(() -> new DataException(ErrorEnum.EXECUTION_PLAN_ERROR)); // 预处理 preprocess(trainingProgramList, executionPlanList); // 按课程号排序 trainingProgramList = trainingProgramList.parallelStream().sorted(Comparator.comparing(TrainingProgram::getCourseId)).collect(Collectors.toList()); executionPlanList = executionPlanList.parallelStream().sorted(Comparator.comparing(ExecutionPlan::getCourseId)).collect(Collectors.toList()); ConditionUtil.validateTrue(trainingProgramList.size() == executionPlanList.size()).orElseThrow(() -> new BaseException(ErrorEnum.ERROR)); int len = executionPlanList.size(); List<Map<String, List<VerifyField>>> trainingProgramDifferenceList = new ArrayList<>(len); List<Map<String, List<VerifyField>>> executionPlanDifferenceList = new ArrayList<>(len); for (int i = 0; i < len; i++) { Map<String, Map<String, List<VerifyField>>> map = verifySingleCourse(executionPlanList.get(i), trainingProgramList.get(i)); trainingProgramDifferenceList.add(map.get("trainingProgram")); executionPlanDifferenceList.add(map.get("executionPlan")); } return VerifyResult.builder().executionResult(executionPlanDifferenceList).trainingProgramResult(trainingProgramDifferenceList).build(); } /** * 预处理,解决执行计划和培养方案课程数量,种类不同的问题 * 处理后的两个list课程数量及种类相同,并按课程号从小到大排序 * * @param trainingProgramList 培养方案list * @param executionPlanList 执行计划list */ private void preprocess(List<TrainingProgram> trainingProgramList, List<ExecutionPlan> executionPlanList) { // 将课程号和课程id转换为set,便于集合做差 Set<String> trainingProgramSet = trainingProgramList.parallelStream().map(TrainingProgram::getCourseId).collect(Collectors.toSet()); Set<String> executionPlanSet = executionPlanList.parallelStream().map(ExecutionPlan::getCourseId).collect(Collectors.toSet()); // trainingProgramSet剩余的是培养方案里面有,但执行计划里面没有的课程id trainingProgramSet.removeAll(executionPlanSet); // executionPlanSet剩余的是执行计划里面有,但培养方案里面没有的课程id executionPlanSet.removeAll(trainingProgramSet); executionPlanSet.forEach(v -> trainingProgramList.add(TrainingProgram.builder().courseId(v).build())); trainingProgramSet.forEach(v -> executionPlanList.add(ExecutionPlan.builder().courseId(v).build())); } /** * @param e 执行计划 * @param t 培养方案 * @return 同课程各属性验证情况 */ private Map<String, Map<String, List<VerifyField>>> verifySingleCourse(ExecutionPlan e, TrainingProgram t) { log.debug("执行计划,{}", e); log.debug("培养方案,{}", t); // 对是否能进行比较进行验证 boolean sameCourse = StrUtil.equals(t.getCourseId(), e.getCourseId()); ConditionUtil.validateTrue(sameCourse).orElseThrow(() -> new DataException(ErrorEnum.VERIFY_ERROR)); // 开始比较 boolean courseNameFlag = Objects.equals(t.getCourseName(), e.getCourseName()); boolean creditFlag = Objects.equals(t.getCredit(), e.getCredit()); boolean examinationWayFlag = Objects.equals(t.getExaminationWay(), e.getExaminationWay()); boolean timeAllFlag = Objects.equals(t.getTimeAll(), e.getTimeAll()); boolean timeTheoryFlag = Objects.equals(t.getTimeTheory(), e.getTimeTheory()); boolean timeLabFlag = Objects.equals(t.getTimeLab(), e.getTimeLab()); boolean timeComputerFlag = Objects.equals(t.getTimeComputer(), e.getTimeComputer()); boolean timeOtherFlag = Objects.equals(t.getTimeOther(), e.getTimeOther()); boolean startSemesterFlag = Objects.equals(t.getStartSemester(), e.getStartSemester()); // 构建结果 List<VerifyField> tVerifyFieldList = new ArrayList<>(12); tVerifyFieldList.add(new VerifyField("courseName", t.getCourseName(), courseNameFlag)); tVerifyFieldList.add(new VerifyField("credit", String.valueOf(t.getCredit()), creditFlag)); tVerifyFieldList.add(new VerifyField("examinationWay", t.getExaminationWay(), examinationWayFlag)); tVerifyFieldList.add(new VerifyField("timeAll", String.valueOf(t.getTimeAll()), timeAllFlag)); tVerifyFieldList.add(new VerifyField("timeTheory", String.valueOf(t.getTimeAll()), timeTheoryFlag)); tVerifyFieldList.add(new VerifyField("timeLab", String.valueOf(t.getTimeLab()), timeLabFlag)); tVerifyFieldList.add(new VerifyField("timeComputer", String.valueOf(t.getTimeComputer()), timeComputerFlag)); tVerifyFieldList.add(new VerifyField("timeOther", String.valueOf(t.getTimeOther()), timeOtherFlag)); tVerifyFieldList.add(new VerifyField("startSemester", String.valueOf(t.getStartSemester()), startSemesterFlag)); List<VerifyField> eVerifyFieldList = new ArrayList<>(12); eVerifyFieldList.add(new VerifyField("courseName", e.getCourseName(), courseNameFlag)); eVerifyFieldList.add(new VerifyField("credit", String.valueOf(e.getCredit()), creditFlag)); eVerifyFieldList.add(new VerifyField("examinationWay", e.getExaminationWay(), examinationWayFlag)); eVerifyFieldList.add(new VerifyField("timeAll", String.valueOf(e.getTimeAll()), timeAllFlag)); eVerifyFieldList.add(new VerifyField("timeTheory", String.valueOf(e.getTimeAll()), timeTheoryFlag)); eVerifyFieldList.add(new VerifyField("timeLab", String.valueOf(e.getTimeLab()), timeLabFlag)); eVerifyFieldList.add(new VerifyField("timeComputer", String.valueOf(e.getTimeComputer()), timeComputerFlag)); eVerifyFieldList.add(new VerifyField("timeOther", String.valueOf(e.getTimeOther()), timeOtherFlag)); eVerifyFieldList.add(new VerifyField("startSemester", String.valueOf(e.getStartSemester()), startSemesterFlag)); Map<String, Map<String, List<VerifyField>>> map = new HashMap<>(); map.put("trainingProgram", MapUtil.builder(t.getCourseId(), tVerifyFieldList).build()); map.put("executionPlan", MapUtil.builder(e.getCourseId(), eVerifyFieldList).build()); return map; } }
d22eff6bc0469dd47ba2ae0cc8d8229724fc6309
517817a24a9f1b4190307ef4c311b9b9e2354659
/src/main/java/de/sikeller/theoretical/turing_machine/machine/head/IHead.java
d30bc51be36abaaa73c6f22be0c0e8b8363777b1
[]
no_license
sikell/java_turing_machine
bcf195d3a8cdcb7b961b39eade9cfd8cbedbdf74
0df4e3fed9d96c01d8c4f6b6777073503273bffd
refs/heads/master
2021-08-24T13:43:41.975289
2017-11-21T08:46:53
2017-11-21T08:46:53
109,800,525
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package de.sikeller.theoretical.turing_machine.machine.head; import de.sikeller.theoretical.turing_machine.tape.ITape; public interface IHead<A> { void moveRight(); void moveLeft(); A read(); void write(A symbol); void useTape(ITape<A> tape); }
4f2e49ab4de00985d2480e07b02c584095a1b5e5
d309dec127afc984a40fca5457faff45d8badfc1
/src/main/java/com/bunker/rffz/domain/ranking/dto/RankingList.java
1f83e03ee3607217ee30292717d4c964107f295d
[]
no_license
thezaorish/rffz-server
01c7a891dfed13fb023bded038d4aa1148b65153
8c2dedd49438173ee77e63fe517d954270a02498
refs/heads/master
2021-01-17T07:32:58.072423
2013-07-21T21:49:12
2013-07-21T21:49:12
5,557,881
0
0
null
null
null
null
UTF-8
Java
false
false
1,140
java
package com.bunker.rffz.domain.ranking.dto; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.bunker.rffz.domain.ranking.Ranking; @XmlRootElement(name = "rankingList") @XmlAccessorType(XmlAccessType.NONE) public class RankingList { @XmlElement private List<Ranking> rankings; public RankingList() { // INFO needed by JAX-B } public RankingList(List<Ranking> rankings) { this.rankings = rankings; } public List<Ranking> getRankings() { return rankings; } public void setRankings(List<Ranking> rankings) { this.rankings = rankings; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public String toString() { return "RankingList [rankings=" + rankings + "]"; } }
acdac09e1661474c164ea5d8d46f9d20a5003ff7
63b1f4694326cab1392c3a036e2d0132fd847524
/UICustomView/app/src/main/java/com/example/uicustomview/MainActivity.java
f8df5d365e0c832e106473dc65154fe1e16a775c
[]
no_license
ziiyan/AndroidStudioProjects
232e7dbdfc7f0520c6f0c501057a9271778c9aa0
949f2da1a6f6a7f3aa6f830a21311dbfc8448bef
refs/heads/master
2020-12-09T06:06:14.911053
2020-01-11T10:44:49
2020-01-11T10:44:49
233,215,828
0
0
null
null
null
null
UTF-8
Java
false
false
541
java
package com.example.uicustomview; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionbar = getSupportActionBar(); if (actionbar != null) { actionbar.hide(); } } }
1fbb6269bd5bd6302e03d0ce1ef7506370c9525e
35cc6c50128f116e1826aeb7f170b3f407e4adfc
/Connector/app/src/main/java/com/web/connector/CustomProgressDialog.java
44f56b985aa6560307acf179721c0a52a46b000b
[]
no_license
ConnectorPj/AndroidConnector
91519216510d1a9d9ba93d184d9bca9d5ec5178c
4dcecd7d2487e52ea4c918303ff1d1bf250faa89
refs/heads/master
2020-09-06T12:37:18.979806
2017-06-22T07:09:01
2017-06-22T07:09:01
94,419,465
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package com.web.connector; import android.app.Dialog; import android.content.Context; import android.view.Window; /** * Created by BAN on 2017-06-19. */ public class CustomProgressDialog extends Dialog { public CustomProgressDialog(Context context) { super(context); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.custom_dialog); } }
cc0677f287f15e50c6d30ec20b6d5631ad4c80ca
e8fc19f6301ceddebe1c76b29dbf6753f4d63da8
/AutomationFramework/src/com/inflectra/remotelaunch/services/soap/TestCaseRetrieveByTestSetIdResponse.java
9723f86ce7417eb27c16562cf046eaf9e30fbe05
[]
no_license
ravinder1414/AutomationFrameworkUpdated
524b91f29400dd1c906cc6b06a56b06ff8e6fc55
0cf3e56fc9b6b5a4bac47d0a7c7e424a49c9845a
refs/heads/master
2021-07-02T22:31:46.280362
2017-09-22T04:28:38
2017-09-22T04:28:38
104,431,215
0
1
null
null
null
null
UTF-8
Java
false
false
2,236
java
package com.inflectra.remotelaunch.services.soap; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TestCase_RetrieveByTestSetIdResult" type="{http://schemas.datacontract.org/2004/07/Inflectra.SpiraTest.Web.Services.v4_0.DataObjects}ArrayOfRemoteTestCase" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "testCaseRetrieveByTestSetIdResult" }) @XmlRootElement(name = "TestCase_RetrieveByTestSetIdResponse") public class TestCaseRetrieveByTestSetIdResponse { @XmlElementRef(name = "TestCase_RetrieveByTestSetIdResult", namespace = "http://www.inflectra.com/SpiraTest/Services/v4.0/", type = JAXBElement.class) protected JAXBElement<ArrayOfRemoteTestCase> testCaseRetrieveByTestSetIdResult; /** * Gets the value of the testCaseRetrieveByTestSetIdResult property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link ArrayOfRemoteTestCase }{@code >} * */ public JAXBElement<ArrayOfRemoteTestCase> getTestCaseRetrieveByTestSetIdResult() { return testCaseRetrieveByTestSetIdResult; } /** * Sets the value of the testCaseRetrieveByTestSetIdResult property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link ArrayOfRemoteTestCase }{@code >} * */ public void setTestCaseRetrieveByTestSetIdResult(JAXBElement<ArrayOfRemoteTestCase> value) { this.testCaseRetrieveByTestSetIdResult = ((JAXBElement<ArrayOfRemoteTestCase> ) value); } }
9a2d1992ae151ff00419b146cf4604cb89f6c198
4de66c464d0fd16801c099805f35a01f3c28be4d
/mathematics/13241.java
1153dda88b56d459ab1f64a82909de11d7474c1d
[]
no_license
wlsgussla123/Algorithms
9ec745dea4e45dbc21fff28119e923b3bedf0b5f
f7fe0c2509dcb852182dd1f8a673991362f6d174
refs/heads/master
2021-01-23T09:35:23.721109
2020-11-15T06:36:49
2020-11-15T06:36:49
102,583,416
6
2
null
null
null
null
UTF-8
Java
false
false
1,355
java
package algo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.EmptyStackException; import java.util.Iterator; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Task().run(); } static class Task { private long A,B; private BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer st = null; private StringTokenizer getStringTokenizer() throws IOException { return new StringTokenizer(br.readLine(), " "); } private void input() throws IOException { st = getStringTokenizer(); A = Long.parseLong(st.nextToken()); B = Long.parseLong(st.nextToken()); } private long solve(long p, long q) { if(q==0) { return p; } return solve(q, p%q); } public void run() throws IOException { input(); long gcd = 0; if(A>B) { gcd = solve(A,B); } else { gcd = solve(B,A); } System.out.println((A*B)/gcd); close(); } private void close() throws IOException { bw.close(); br.close(); } } }
4b18887b551a9872510438ddf3b340047164a7a4
4b2b6fe260ba39f684f496992513cb8bc07dfcbc
/com/planet_ink/coffee_mud/WebMacros/StatRejuvCharts.java
7a30991ed9e817a123e985930520c56136869d41
[ "Apache-2.0" ]
permissive
vjanmey/EpicMudfia
ceb26feeac6f5b3eb48670f81ea43d8648314851
63c65489c673f4f8337484ea2e6ebfc11a09364c
refs/heads/master
2021-01-18T20:12:08.160733
2014-06-22T04:38:14
2014-06-22T04:38:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,867
java
package com.planet_ink.coffee_mud.WebMacros; import com.planet_ink.miniweb.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2014 Bo Zimmerman 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. */ public class StatRejuvCharts extends StdWebMacro { @Override public String name() {return "StatRejuvCharts";} protected String getReq(HTTPRequest httpReq, String tag) { String s=httpReq.getUrlParameter(tag); if(s==null) s=""; return s; } @Override public String runMacro(HTTPRequest httpReq, String parm) { final StringBuffer buf=new StringBuffer(""); final String which=httpReq.getUrlParameter("WHICH"); final MOB mob=CMClass.getMOB("StdMOB"); mob.baseState().setMana(100); mob.baseState().setMovement(100); mob.baseState().setHitPoints(100); mob.recoverMaxState(); mob.resetToMaxState(); mob.curState().setHunger(1000); mob.curState().setThirst(1000); if((which!=null)&&(which.equals("HP"))) buf.append("<BR>Chart: Hit Points<BR>"); else if((which!=null)&&(which.equals("MN"))) buf.append("<BR>Chart: Mana<BR>"); else if((which!=null)&&(which.equals("MV"))) buf.append("<BR>Chart: Movement<BR>"); else buf.append("<BR>Chart: Hit Points<BR>"); buf.append("Flags: "); int disposition=0; if((getReq(httpReq,"SITTING").length()>0)) { disposition=PhyStats.IS_SITTING; buf.append("Sitting ");} if((getReq(httpReq,"SLEEPING").length()>0)) { disposition=PhyStats.IS_SLEEPING; buf.append("Sleeping ");} if((getReq(httpReq,"FLYING").length()>0)) { disposition=PhyStats.IS_FLYING; buf.append("Flying ");} if((getReq(httpReq,"SWIMMING").length()>0)) { disposition=PhyStats.IS_SWIMMING; buf.append("Swimming ");} if((getReq(httpReq,"RIDING").length()>0)) { mob.setRiding((Rideable)CMClass.getMOB("GenRideable")); buf.append("Riding ");} final boolean hungry=(httpReq.getUrlParameter("HUNGRY")!=null)&&(httpReq.getUrlParameter("HUNGRY").length()>0); if(hungry){ buf.append("Hungry "); mob.curState().setHunger(0);} final boolean thirsty=(httpReq.getUrlParameter("THIRSTY")!=null)&&(httpReq.getUrlParameter("THIRSTY").length()>0); if(thirsty){ buf.append("Thirsty "); mob.curState().setThirst(0);} mob.basePhyStats().setDisposition(disposition); mob.recoverPhyStats(); buf.append("<P><TABLE WIDTH=100% BORDER=1>"); buf.append("<TR><TD><B>STATS:</B></TD>"); for(int stats=4;stats<=25;stats++) buf.append("<TD><B>"+stats+"</B></TD>"); buf.append("</TR>"); for(int level=1;level<=30;level++) { buf.append("<TR>"); buf.append("<TD><B>LVL "+level+"</B></TD>"); for(int stats=4;stats<=25;stats++) { for(final int c: CharStats.CODES.BASECODES()) mob.baseCharStats().setStat(c,stats); mob.recoverCharStats(); mob.basePhyStats().setLevel(level); mob.recoverPhyStats(); mob.curState().setMana(0); mob.curState().setMovement(0); mob.curState().setHitPoints(0); double con=mob.charStats().getStat(CharStats.STAT_CONSTITUTION); double man=mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)+mob.charStats().getStat(CharStats.STAT_WISDOM); double str=mob.charStats().getStat(CharStats.STAT_STRENGTH); if(mob.curState().getHunger()<1) { con=con*0.85; man=man*0.75; str=str*0.85; } if(mob.curState().getThirst()<1) { con=con*0.85; man=man*0.75; str=str*0.85; } if(mob.curState().getFatigue()>CharState.FATIGUED_MILLIS) man=man*.5; final double lvl=mob.phyStats().level(); final double lvlby1p5=CMath.div(lvl,1.5); //double lvlby2=CMath.div(lvl,2.0); //double lvlby3=CMath.div(lvl,3.0); double hpGain=(con>1.0)?((con/40.0)*lvlby1p5)+(con/4.5)+2.0:1.0; double manaGain=(man>2.0)?((man/80.0)*lvl)+(man/4.5)+2.0:1.0; double moveGain=(str>1.0)?((str/40.0)*lvl)+(str/3.0)+5.0:1.0; if(CMLib.flags().isSleeping(mob)) { hpGain+=(hpGain/2.0); manaGain+=(manaGain/2.0); moveGain+=(moveGain/2.0); if((mob.riding()!=null)&&(mob.riding() instanceof Item)) { hpGain+=(hpGain/8.0); manaGain+=(manaGain/8.0); moveGain+=(moveGain/8.0); } } else if((CMLib.flags().isSitting(mob))||(mob.riding()!=null)) { hpGain+=(hpGain/4.0); manaGain+=(manaGain/4.0); moveGain+=(moveGain/4.0); if((mob.riding()!=null)&&(mob.riding() instanceof Item)) { hpGain+=(hpGain/8.0); manaGain+=(manaGain/8.0); moveGain+=(moveGain/8.0); } } else { if(CMLib.flags().isFlying(mob)) moveGain+=(moveGain/8.0); else if(CMLib.flags().isSwimming(mob)) { hpGain-=(hpGain/2.0); manaGain-=(manaGain/4.0); moveGain-=(moveGain/2.0); } } if((!mob.isInCombat()) &&(!CMLib.flags().isClimbing(mob))) { if((hpGain>0)&&(!CMLib.flags().isGolem(mob))) mob.curState().adjHitPoints((int)Math.round(hpGain),mob.maxState()); if(manaGain>0) mob.curState().adjMana((int)Math.round(manaGain),mob.maxState()); if(moveGain>0) mob.curState().adjMovement((int)Math.round(moveGain),mob.maxState()); } if((which!=null)&&(which.equals("HP"))) buf.append("<TD>"+mob.curState().getHitPoints()+"</TD>"); else if((which!=null)&&(which.equals("MN"))) buf.append("<TD>"+mob.curState().getMana()+"</TD>"); else if((which!=null)&&(which.equals("MV"))) buf.append("<TD>"+mob.curState().getMovement()+"</TD>"); else buf.append("<TD>"+mob.curState().getHitPoints()+"</TD>"); } buf.append("</TR>"); } mob.destroy(); buf.append("</TABLE>"); return clearWebMacros(buf); } }
68ae0682532b25c4c194edd2f3281de0cc64d155
d4f1e1603353e762174f729aefb2b8aa3839b6cc
/jqueryPro/src/kr/or/ddit/lprod/dao/LprodDaoImpl.java
4b3ab657ef59f55f4f7836232c695a68a05f1e7e
[]
no_license
zxc5608/jqureyclass
ae97908483ab93a724e8c1f8a4a72eaba4323141
1dee2432c27aabb2e95ad047dafbf64eb7d081b8
refs/heads/master
2023-04-04T15:26:44.610360
2021-04-10T01:28:51
2021-04-10T01:28:51
356,437,185
0
0
null
null
null
null
UTF-8
Java
false
false
627
java
package kr.or.ddit.lprod.dao; import java.sql.SQLException; import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; import kr.or.ddit.ibatis.config.SqlMapClientFactory; import kr.or.ddit.lprod.vo.LprodVo; public class LprodDaoImpl implements IlprodDao { private SqlMapClient smc; private static IlprodDao dao; private LprodDaoImpl() { smc= SqlMapClientFactory.getSqlMapClient(); } public static IlprodDao getDao() { if(dao==null)dao = new LprodDaoImpl(); return dao; } @Override public List<LprodVo> getAllLprod() throws SQLException { return smc.queryForList("lprod.selectLprod"); } }
8e4ec2d897b2318048a59fd56e736057bb117283
8f188151fac558101d1da3f353f99103d3479fa6
/app/build/generated/source/r/debug/com/firebase/ui/database/R.java
fef7bda4d9cde292e86f60129a0afa2ed5e8770e
[]
no_license
leenabhandari/EventFlix
6ff5ebb1b47b1c27721fef8217482679ab510f1a
dd6d09129f908453c7ad46de748adee9099a3386
refs/heads/master
2020-03-30T12:09:31.855008
2019-08-31T11:19:11
2019-08-31T11:19:11
151,211,119
0
0
null
null
null
null
UTF-8
Java
false
false
2,246
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.firebase.ui.database; public final class R { public static final class attr { public static final int layoutManager = 0x7f0400f3; public static final int reverseLayout = 0x7f04016b; public static final int spanCount = 0x7f04017b; public static final int stackFromEnd = 0x7f040181; } public static final class dimen { public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f070082; public static final int item_touch_helper_swipe_escape_max_velocity = 0x7f070083; public static final int item_touch_helper_swipe_escape_velocity = 0x7f070084; } public static final class id { public static final int item_touch_helper_previous_elevation = 0x7f0a0097; } public static final class integer { public static final int google_play_services_version = 0x7f0b0007; } public static final class string { public static final int common_google_play_services_unknown_issue = 0x7f0f0028; } public static final class styleable { public static final int[] RecyclerView = { 0x010100c4, 0x010100f1, 0x7f0400c3, 0x7f0400c4, 0x7f0400c5, 0x7f0400c6, 0x7f0400c7, 0x7f0400f3, 0x7f04016b, 0x7f04017b, 0x7f040181 }; public static final int RecyclerView_android_orientation = 0; public static final int RecyclerView_android_descendantFocusability = 1; public static final int RecyclerView_fastScrollEnabled = 2; public static final int RecyclerView_fastScrollHorizontalThumbDrawable = 3; public static final int RecyclerView_fastScrollHorizontalTrackDrawable = 4; public static final int RecyclerView_fastScrollVerticalThumbDrawable = 5; public static final int RecyclerView_fastScrollVerticalTrackDrawable = 6; public static final int RecyclerView_layoutManager = 7; public static final int RecyclerView_reverseLayout = 8; public static final int RecyclerView_spanCount = 9; public static final int RecyclerView_stackFromEnd = 10; } }
cb7d672f58a53596bad0eeb82f1992e91eac12c9
281fc20ae4900efb21e46e8de4e7c1e476f0d132
/framework/impl/src/main/java/org/ajax4jsf/resource/UserResource.java
eaccf5ddf80cebe183a53270127798383dbbd1ad
[]
no_license
nuxeo/richfaces-3.3
c23b31e69668810219cf3376281f669fa4bf256f
485749c5f49ac6169d9187cc448110d477acab3b
refs/heads/master
2023-08-25T13:27:08.790730
2015-01-05T10:42:11
2015-01-05T10:42:11
10,627,040
3
5
null
null
null
null
UTF-8
Java
false
false
5,921
java
/** * License Agreement. * * Rich Faces - Natural Ajax for Java Server Faces (JSF) * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.ajax4jsf.resource; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.Date; import javax.el.ELContext; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; /** * @author shura * */ public class UserResource extends InternetResourceBase { private String contentType; /** * */ public UserResource(boolean cacheable, boolean session, String mime) { super(); setCacheable(cacheable); setSessionAware(session); setContentType(mime); } /** * @return Returns the contentType. */ public String getContentType(ResourceContext resourceContext) { return contentType; } /** * @param contentType The contentType to set. */ public void setContentType(String contentType) { this.contentType = contentType; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object) */ public Object getDataToStore(FacesContext context, Object data) { UriData dataToStore = null; if (data instanceof ResourceComponent2) { ResourceComponent2 resource = (ResourceComponent2) data; dataToStore = new UriData(); dataToStore.value = resource.getValue(); dataToStore.createContent = UIComponentBase.saveAttachedState(context,resource.getCreateContentExpression()); if (data instanceof UIComponent) { UIComponent component = (UIComponent) data; ValueExpression expires = component.getValueExpression("expires"); if (null != expires) { dataToStore.expires = UIComponentBase.saveAttachedState(context,expires); } ValueExpression lastModified = component.getValueExpression("lastModified"); if (null != lastModified) { dataToStore.modified = UIComponentBase.saveAttachedState(context,lastModified); } } } return dataToStore; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#send(org.ajax4jsf.resource.ResourceContext) */ public void send(ResourceContext context) throws IOException { UriData data = (UriData) restoreData(context); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); // if(data.expires != null){ // ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires); // Date expires = (Date) binding.getValue(elContext); // context.setDateHeader("Expires",expires.getTime()); // } // if(data.modified != null){ // ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified); // Date modified = (Date) binding.getValue(elContext); // context.setDateHeader("Last-Modified",modified.getTime()); // } // Send content OutputStream out = context.getOutputStream(); MethodExpression send = (MethodExpression) UIComponentBase.restoreAttachedState(facesContext,data.createContent); send.invoke(elContext,new Object[]{out,data.value}); } } @Override public Date getLastModified(ResourceContext resourceContext) { UriData data = (UriData) restoreData(resourceContext); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); if(data.modified != null){ ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified); Date modified = (Date) binding.getValue(elContext); if (null != modified) { return modified; } } } return super.getLastModified(resourceContext); } @Override public long getExpired(ResourceContext resourceContext) { UriData data = (UriData) restoreData(resourceContext); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); if(data.expires != null){ ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires); Date expires = (Date) binding.getValue(elContext); if (null != expires) { return expires.getTime()-System.currentTimeMillis(); } } } return super.getExpired(resourceContext); } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext() */ public boolean requireFacesContext() { // TODO Auto-generated method stub return true; } public static class UriData implements SerializableResource { /** * */ private static final long serialVersionUID = 1258987L; private Object value; private Object createContent; private Object expires; private Object modified; } }
8af967510867a636c224d6d4d2e90ff5fb360116
a9b7bb35dacfe2a14478b239acc0fe6b14e436ee
/src/oops/encapsulation/Student.java
487bd01630f215dfa26c54f93321b511faf39f82
[]
no_license
naman22/SlidingWindowMaximum
3b5a8417d1a46a5b972fb32c2ef613b90cb15a1e
9f70a273455376bc176f32545cc233c3f03d8487
refs/heads/master
2023-02-09T20:53:05.935883
2021-01-06T08:03:31
2021-01-06T08:03:31
327,241,888
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package oops.encapsulation; public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
f4fea0463fd29d6825d6906788995b2faec68c83
107a10ec7259ce6bfe0ce9400004d574264464ee
/app/src/test/java/com/example/android/block_app/ExampleUnitTest.java
4667668f5bc1909ff326d4f2a1f58135803d6456
[]
no_license
sumitra773/Block_App
ae494b4809e05eae3024c0ed5d0b798ec1da86e6
af780c6f6e77495522a3b78dbc62cf5b5f0ecd32
refs/heads/master
2023-04-30T03:25:36.297921
2021-05-24T12:18:02
2021-05-24T12:18:02
370,334,131
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.example.android.block_app; 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() { assertEquals(4, 2 + 2); } }
02ff915f702be113bd465c6f6a8494685eca9d77
f1f83f36cb1376d3d289d0889e73a483b467de0c
/LeetCode/medium/House_Robber_III/Solution_2.java
e5df77143c7667c4686f86c8441272c5ede6d2c5
[]
no_license
JisooOh94/Algorithm
b2efbe3618a60599d3c5f8a5f05580a7eead75c2
d2341a1222c068ddcab76c006919492a59e782e6
refs/heads/master
2023-03-05T14:55:44.685216
2023-02-16T14:04:48
2023-02-16T14:04:48
233,358,885
2
0
null
2020-10-14T00:16:29
2020-01-12T08:08:19
Java
UTF-8
Java
false
false
1,163
java
package medium.House_Robber_III; import java.util.HashMap; import java.util.Map; import org.junit.Test; import util.TreeNode; /** * Runtime : 3ms(43.43%) * Memory : 38.7mb(10.50%) */ public class Solution_2 { private static final int TRUE = 0; private static final int FALSE = 1; private int recursion (TreeNode cur, int neighborSelected, Map<TreeNode, Integer>[] record) { if(cur == null) return 0; else if(record[neighborSelected].containsKey(cur)) return record[neighborSelected].get(cur); int max = 0; if(neighborSelected == FALSE) { int selectedLeftResult = recursion(cur.left, TRUE, record); int selectedRightResult= recursion(cur.right, TRUE, record); max = cur.val + selectedLeftResult + selectedRightResult; } int leftResult = recursion(cur.left, FALSE, record); int rightResult = recursion(cur.right, FALSE, record); max = Math.max(max, leftResult + rightResult); record[neighborSelected].put(cur, max); return max; } public int rob(TreeNode root) { Map<TreeNode, Integer>[] record = new HashMap[2]; record[0] = new HashMap<>(); record[1] = new HashMap<>(); return recursion(root, FALSE, record); } }
224f82e8af2beff1838ea8bf88447db0820467da
52dd661fb1faaed14f7e7767e55eebe06070af72
/Vacuna.java
01fde73fc869202f6ed668f193c21e8d21055385
[]
no_license
ObiOscar/ClaseGranja
f88e39702d9fc2162f491e1011f6095e0483b03a
74aaeaaca676d15925c5e87fdfab9e2a2861fccd
refs/heads/master
2021-01-20T09:19:55.483583
2017-05-04T07:54:14
2017-05-04T07:54:14
90,236,503
0
0
null
null
null
null
UTF-8
Java
false
false
93
java
/**es la interface vacuna*/ public interface Vacuna { public abstract void vacunar(); }
5902b17e33d3a6a514705542fe183c2a416a19eb
399e0c9be4d631812f25f92370270f9c971674fe
/src/main/java/org/diplomatiq/diplomatiqbackend/domain/entities/abstracts/AbstractIdentifiableNodeEntity.java
7aa3a6a997f283524f3fe0524411e517abc13884
[ "MIT" ]
permissive
Diplomatiq/diplomatiq-backend
a89bd2baf3d533612f8f51ee36bd3c94d50a1995
97ed829e42f6bfaa48607b33e1e7543b3aec061c
refs/heads/develop
2021-05-23T14:18:53.161411
2020-05-10T23:47:08
2020-05-10T23:47:08
253,334,403
0
0
MIT
2021-02-27T08:01:24
2020-04-05T21:20:40
Java
UTF-8
Java
false
false
1,140
java
package org.diplomatiq.diplomatiqbackend.domain.entities.abstracts; import org.diplomatiq.diplomatiqbackend.utils.crypto.random.EntityIdGenerator; import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; public abstract class AbstractIdentifiableNodeEntity { @Id @GeneratedValue(strategy = EntityIdGenerator.class) private String id; public final String getId() { return id; } public final void setId(String id) { this.id = id; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof AbstractIdentifiableNodeEntity)) { return false; } AbstractIdentifiableNodeEntity otherAbstractIdentifiableNodeEntity = (AbstractIdentifiableNodeEntity)other; if (id == null || otherAbstractIdentifiableNodeEntity.getId() == null) { return false; } return id.equals(otherAbstractIdentifiableNodeEntity.getId()); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } }
fbf19831bafa9b9de9645544118d389d9d43282d
7337f37bffd85c7db7a0191833855e1ef83c27a0
/abberwoult/src/main/java/com/github/sarxos/abberwoult/ActorRefFactory.java
e418222358d1c9c58fb16aab617718de1bc14b16
[ "MIT" ]
permissive
sarxos/abberwoult
88e0add52022ebe46d86c34d1ffd13e262832d40
1339669952ab6a0fc762e7ec0a7bde78aa46da93
refs/heads/master
2021-06-16T09:45:49.977233
2021-03-09T21:32:10
2021-03-09T21:32:10
175,262,118
0
1
null
null
null
null
UTF-8
Java
false
false
1,383
java
package com.github.sarxos.abberwoult; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import javax.inject.Singleton; import org.jboss.logging.Logger; import com.github.sarxos.abberwoult.annotation.ActorOf; import com.github.sarxos.abberwoult.util.ActorUtils; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; @Singleton public class ActorRefFactory extends AbstractActorInjectFactory { private static final Logger LOG = Logger.getLogger(ActorRefFactory.class); private final Propser propser; private final ActorSystem system; @Inject public ActorRefFactory(final Propser propser, final ActorSystem system) { this.propser = propser; this.system = system; } @Produces @Dependent @ActorOf public ActorRef create(final InjectionPoint injection) { if (injection == null) { throw new NoActorClassProvidedException(injection); } final Class<? extends Actor> clazz = getActorClass(injection); final Props props = propser.props(clazz); LOG.debugf("Creating actor %s", clazz); LOG.tracef("Creating actor %s with props %s", clazz, props); return ActorUtils .getActorName(clazz) .map(name -> system.actorOf(props, name)) .getOrElse(() -> system.actorOf(props)); } }
e931bf29939236d9c89e1bb7781338bd72e8907e
be6e6d8af85adf044bf79676b7276c252407e010
/spec/java/src/io/kaitai/struct/spec/TestUserType.java
8fb375eabaed75c3296c56731f6c41e0fada7d5a
[ "MIT" ]
permissive
kaitai-io/kaitai_struct_tests
516e864d29d1eccc5fe0360d1b111af7a5d3ad2b
3d8a6c00c6bac81ac26cf1a87ca84ec54bf1078d
refs/heads/master
2023-08-19T19:42:47.281953
2023-08-04T20:26:50
2023-08-04T20:26:50
52,155,797
12
41
MIT
2023-07-30T23:30:30
2016-02-20T13:55:39
Ruby
UTF-8
Java
false
false
513
java
// Autogenerated from KST: please remove this line if doing any edits by hand! package io.kaitai.struct.spec; import io.kaitai.struct.testformats.UserType; import org.testng.annotations.Test; import static org.testng.Assert.*; public class TestUserType extends CommonSpec { @Test public void testUserType() throws Exception { UserType r = UserType.fromFile(SRC_DIR + "repeat_until_s4.bin"); assertIntEquals(r.one().width(), 66); assertIntEquals(r.one().height(), 4919); } }
c8ff243bb7636a2e1aeaa534077b1b33069b003c
30fd21a00f5276edef41c97a6eb4b84cd386634d
/2ano/2semestre/POO/projPOO/Projeto POO 1516 v3/Vendedor.java
6b2729c727aa5431acdbc193f0be8d11fab9a8e1
[]
no_license
JoaoPalmeira/MaterialLicenciaturaMIEINF
00b4639cb6ac0c094437e1bccc6c58e725757577
1f1d59e9010ad18e02e5dfb3b597330054e681a3
refs/heads/master
2020-07-02T12:05:37.430589
2019-08-09T18:25:42
2019-08-09T18:25:42
201,519,160
3
0
null
null
null
null
UTF-8
Java
false
false
1,098
java
import java.util.List; public class Vendedor extends Utilizador{ // Variaveis de Instancia private List<Imovel> pVenda; private List<Imovel> vendidos; // Construtor public Vendedor(String m, String n, String p, String mo, int na) { super(m,n,p,mo,na); pVenda = null; vendidos = null; } // Métodos de Instancia public class ImovelExisteException extends Exception { public ImovelExisteException(String m) { super(m); // Não funciona corretamente. } } //isto public class SemAutorizacaoException extends Exception { public SemAutorizacaoException(String m) { super(m); // Não funciona corretamente. } } public void registaImovel (Imovel im) throws ImovelExisteException{ if (pVenda.contains(im)){ throw new ImovelExisteException("Imovel já existe."); } else pVenda.add(im); System.out.println("Imóvel registado com sucesso."); } /*public List <Consulta> getConsultas (){ }*/ }
d2074fa2fa35a1e32494d6d7727e06e06f28c86e
0adbac98aa54a1d3ece052b584ba42e51ab0da97
/multiplier/src/main/java/com/fox/multiplier/config/KafkaConfig.java
31e90bb851ca7bf072d6471b218b5148d5b80853
[]
no_license
max-moroz/kafka-project
92c9b871977bebb0cf65b7c345b1fadb8593d80c
4f801529061383aa8bddc0898fab93125f00b75b
refs/heads/master
2022-12-24T07:29:14.447343
2020-09-30T16:48:20
2020-09-30T16:48:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,258
java
package com.fox.multiplier.config; import com.fox.generator.Number; import com.fox.multiplier.SquaringKafkaMessage; import io.confluent.kafka.serializers.KafkaAvroDeserializer; import io.confluent.kafka.serializers.KafkaAvroSerializer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.config.KafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; import java.util.HashMap; import java.util.Map; import java.util.Properties; @EnableKafka @Configuration public class KafkaConfig { @Value("${kafka.boot.server}") private String kafkaServer; @Value("${kafka.consumer.group.id}") private String kafkaGroupId; @Value("${schema.registry.url}") String schemaRegistryUrl; @Bean public KafkaProducer<String, SquaringKafkaMessage> kafkaProducer() { return new KafkaProducer<>(producerConfig()); } @Bean public Properties producerConfig() { Properties config = new Properties(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class); config.put("schema.registry.url", schemaRegistryUrl); config.setProperty("auto.register.schemas", "false"); config.setProperty("use.latest.version", "true"); return config; } @Bean public ConsumerFactory<String, Number> consumerConfig() { Map<String, Object> config = new HashMap<>(); config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer); config.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaGroupId); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class); config.put("schema.registry.url", schemaRegistryUrl); config.put("auto.commit.enable", "false"); config.put("auto.offset.reset", "earliest"); config.put("specific.avro.reader", "true"); return new DefaultKafkaConsumerFactory<>(config); } @Bean public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Number>> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Number> listener = new ConcurrentKafkaListenerContainerFactory<>(); listener.setConsumerFactory(consumerConfig()); return listener; } }
d225bae960037c0df597dd2203e100c7301d0d65
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/gdanol/gda/com/gensym/classes/modules/gdluisup/GdlPathItemEventImpl.java
8f28f9515d3e1352dffab0d72556a8b864ff26c3
[]
no_license
UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559378
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
UTF-8
Java
false
false
4,517
java
/* * Copyright (C) 1986-2017 Gensym Corporation. * All Rights Reserved. * * GdlPathItemEventImpl.java * * Description: Generated Interface file. Do not edit! * * Author: Gensym Corp. * * Version: 5.1 Rev. 1 * * Date: Mon May 15 13:58:18 GMT+04:00 2000 * */ package com.gensym.classes.modules.gdluisup; import com.gensym.classes.*; import com.gensym.util.Structure; import com.gensym.util.Sequence; import com.gensym.util.Symbol; import com.gensym.util.symbol.SystemAttributeSymbols; import com.gensym.jgi.*; import com.gensym.classes.Object; public class GdlPathItemEventImpl extends com.gensym.classes.modules.g2evliss.G2EventObjectImpl implements GdlPathItemEvent { static final long serialVersionUID = 2L; private static final Symbol GDL_PATH_DATA_VALUES_ = Symbol.intern ("GDL-PATH-DATA-VALUES"); /* Generated constructors */ public GdlPathItemEventImpl() { super(); } public GdlPathItemEventImpl(G2Access context, int handle, Structure attributes) { super (context, handle, attributes); } /** * Generated Property Setter for attribute -- GDL-PATH-DATA-VALUES * @param gdlPathDataValues new value to conclude for GDL-PATH-DATA-VALUES * @exception G2AccessException if there are any communication problems * or the value does not match with the type specification */ public void setGdlPathDataValues(com.gensym.util.Sequence gdlPathDataValues) throws G2AccessException { setAttributeValue (GDL_PATH_DATA_VALUES_, gdlPathDataValues); } /** * Generated Property Getter for attribute -- GDL-PATH-DATA-VALUES * @return the value of the GDL-PATH-DATA-VALUES attribute of this item * @exception G2AccessException if there are any communication problems */ public com.gensym.util.Sequence getGdlPathDataValues() throws G2AccessException { java.lang.Object retnValue = getAttributeValue (GDL_PATH_DATA_VALUES_); return (com.gensym.util.Sequence)retnValue; } /** * Generated Property Setter for attribute -- ATTRIBUTE-DISPLAYS * @param attributeDisplays new value to conclude for ATTRIBUTE-DISPLAYS * @exception G2AccessException if there are any communication problems * or the value does not match with the type specification */ public void setAttributeDisplaysForClass(java.lang.Object attributeDisplays) throws G2AccessException { setStaticAttributeValue (SystemAttributeSymbols.ATTRIBUTE_DISPLAYS_, attributeDisplays); } /** * Generated Property Getter for attribute -- ATTRIBUTE-DISPLAYS * @return the value of the ATTRIBUTE-DISPLAYS attribute of this class * @exception G2AccessException if there are any communication problems */ public java.lang.Object getAttributeDisplaysForClass() throws G2AccessException { java.lang.Object retnValue = getStaticAttributeValue (SystemAttributeSymbols.ATTRIBUTE_DISPLAYS_); return (java.lang.Object)retnValue; } /** * Generated Property Setter for attribute -- STUBS * @param stubs new value to conclude for STUBS * @exception G2AccessException if there are any communication problems * or the value does not match with the type specification */ public void setStubsForClass(java.lang.Object stubs) throws G2AccessException { setStaticAttributeValue (SystemAttributeSymbols.STUBS_, stubs); } /** * Generated Property Getter for attribute -- STUBS * @return the value of the STUBS attribute of this class * @exception G2AccessException if there are any communication problems */ public java.lang.Object getStubsForClass() throws G2AccessException { java.lang.Object retnValue = getStaticAttributeValue (SystemAttributeSymbols.STUBS_); return (java.lang.Object)retnValue; } /** * Generated Property Getter for attribute -- DEFAULT-SETTINGS * @return the value of the DEFAULT-SETTINGS attribute of this class * @exception G2AccessException if there are any communication problems */ public java.lang.Object getDefaultSettingsForClass() throws G2AccessException { java.lang.Object retnValue = getStaticAttributeValue (SystemAttributeSymbols.DEFAULT_SETTINGS_); return (java.lang.Object)retnValue; } /* com.gensym.classes.G2_EventObject support */ public Class getExternalEventClass() { return com.gensym.classes.modules.gdluisup.G2_GdlPathItemEvent.class; } private static String NoBodyExceptionString = "This method has no implementation for local access"; }
83e73c2f978247c6c5efa8d01ff1125cb7a4423a
3fe223236585083810b0d31b9d8c83481c7926ee
/src/test/java/ru/tw1911/test/universalStub/UniversalStubApplicationTests.java
be30545a205ac7be6b064a473ba31ea84cc423d3
[]
no_license
tw1911/universalStub
289346b6bae93cfff1bd9872eee20db60903e534
1d4e2ecad6c07ce313676c8396fa5d233b96517f
refs/heads/master
2020-07-14T21:52:43.254675
2019-09-02T16:55:36
2019-09-02T16:55:36
205,411,289
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
package ru.tw1911.test.universalStub; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class UniversalStubApplicationTests { @Test public void contextLoads() { } }
60608969fdf102697f5b9438309d8bab6d731cbc
6cb7f747fde286e9276678774808dbea2bc8ff8e
/src/main/java/pom/irctc/pages/CovidAlertPage.java
dbc61e46f0863331daad88b9279edc8051d22357
[]
no_license
syamssk/PageObjectModel
998e3c18a6ac5c4db7ed45c44d6ba6a24bea517b
eaef015e30fea6fce3a5235db5b157a05359ef61
refs/heads/master
2023-06-27T02:08:25.043457
2021-07-29T04:14:23
2021-07-29T04:14:23
390,593,241
1
0
null
2021-07-29T04:14:23
2021-07-29T03:51:18
HTML
UTF-8
Java
false
false
463
java
package pom.irctc.pages; import org.openqa.selenium.remote.RemoteWebDriver; import com.relevantcodes.extentreports.ExtentTest; import wrappers.GenericWrappers; public class CovidAlertPage extends GenericWrappers { public CovidAlertPage(RemoteWebDriver driver, ExtentTest test) { this.driver=driver; this.test=test; } public HomePage clickOnOk() { clickByXpath(prop.getProperty("CovidAlertPage.Ok.XPath")); return new HomePage(driver,test); } }
c6acf36473377ffe72935443bd43a98970b64656
36a1cf75f994f913097fcea9db3435bbd6154a6e
/app/src/main/java/per/goweii/wanandroid/module/main/activity/WebActivity.java
11abcebfc742a606be65c19722f62f6357ecb033
[]
no_license
locojiminjie/WanAndroid
d8bab3f9b93536167aaedcecbbc9dc8538135358
12e69ce9e4146218601f5a5e0e40b50eef5efd9e
refs/heads/master
2020-07-17T08:48:28.391350
2019-09-01T07:44:45
2019-09-01T07:44:45
205,987,470
1
0
null
2019-09-03T04:14:05
2019-09-03T04:14:04
null
UTF-8
Java
false
false
7,559
java
package per.goweii.wanandroid.module.main.activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import com.just.agentweb.AgentWeb; import com.just.agentweb.WebChromeClient; import com.just.agentweb.WebViewClient; import butterknife.BindView; import per.goweii.actionbarex.common.ActionBarSuper; import per.goweii.basic.core.base.BaseActivity; import per.goweii.basic.ui.toast.ToastMaker; import per.goweii.basic.utils.IntentUtils; import per.goweii.basic.utils.listener.OnClickListener2; import per.goweii.wanandroid.R; import per.goweii.wanandroid.module.main.dialog.WebGuideDialog; import per.goweii.wanandroid.module.main.dialog.WebMenuDialog; import per.goweii.wanandroid.module.main.presenter.WebPresenter; import per.goweii.wanandroid.utils.AgentWebCreator; import per.goweii.wanandroid.utils.GuideSPUtils; import per.goweii.wanandroid.utils.RealmHelper; import per.goweii.wanandroid.utils.SettingUtils; import per.goweii.wanandroid.widget.WebContainer; /** * @author CuiZhen * @date 2019/5/15 * QQ: 302833254 * E-mail: [email protected] * GitHub: https://github.com/goweii */ public class WebActivity extends BaseActivity<WebPresenter> implements per.goweii.wanandroid.module.main.view.WebView { @BindView(R.id.abs) ActionBarSuper abs; @BindView(R.id.wc) WebContainer wc; private int mArticleId = -1; private String mTitle = ""; private String mAuthor = ""; private String mUrl = ""; private String mCurrTitle = ""; private String mCurrUrl = ""; private AgentWeb mAgentWeb = null; private RealmHelper mRealmHelper = null; private WebGuideDialog mWebGuideDialog = null; public static void start(Context context, int articleId, String title, String url) { Intent intent = new Intent(context, WebActivity.class); intent.putExtra("articleId", articleId); intent.putExtra("title", title); intent.putExtra("url", url); context.startActivity(intent); } public static void start(Context context, String title, String author, String url) { Intent intent = new Intent(context, WebActivity.class); intent.putExtra("title", title); intent.putExtra("author", author); intent.putExtra("url", url); context.startActivity(intent); } public static void start(Context context, String title, String url) { Intent intent = new Intent(context, WebActivity.class); intent.putExtra("title", title); intent.putExtra("url", url); context.startActivity(intent); } @Override protected boolean swipeBackOnlyEdge() { return SettingUtils.getInstance().isWebSwipeBackEdge(); } @Override protected int getLayoutId() { return R.layout.activity_web; } @Nullable @Override protected WebPresenter initPresenter() { return new WebPresenter(); } @Override protected void initView() { mArticleId = getIntent().getIntExtra("articleId", -1); mTitle = getIntent().getStringExtra("title"); mAuthor = getIntent().getStringExtra("author"); mUrl = getIntent().getStringExtra("url"); mCurrUrl = mUrl; mCurrTitle = mTitle; // forceHttpsForAndroid9(); abs.getTitleTextView().setText(mTitle); abs.getLeftActionView(0).setOnClickListener(new OnClickListener2() { @Override public void onClick2(View v) { if (!mAgentWeb.back()) { finish(); } } }); abs.getRightActionView(0).setOnClickListener(new OnClickListener2() { @Override public void onClick2(View v) { WebMenuDialog.show(abs, new WebMenuDialog.OnMenuClickListener() { @Override public void onCollect() { collect(); } @Override public void onReadLater() { if (mRealmHelper != null) { mRealmHelper.add(mCurrTitle, mCurrUrl); ToastMaker.showShort("已加入稍后阅读"); } } @Override public void onBrowser() { IntentUtils.openBrowser(getContext(), mUrl); } }); } }); wc.setOnDoubleClickListener(new WebContainer.OnDoubleClickListener() { @Override public void onDoubleClick() { collect(); } }); mRealmHelper = RealmHelper.create(); } @Override protected void loadData() { mAgentWeb = AgentWebCreator.create(this, wc, mUrl, new WebChromeClient() { @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); mCurrTitle = title; mCurrUrl = view.getUrl(); if (abs.getTitleTextView() != null) { abs.getTitleTextView().setText(title); } } }, new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!GuideSPUtils.getInstance().isWebGuideShown()) { if (mWebGuideDialog == null) { mWebGuideDialog = new WebGuideDialog(abs); mWebGuideDialog.show(); } } } }); } @Override protected void onPause() { mAgentWeb.getWebLifeCycle().onPause(); super.onPause(); } @Override protected void onResume() { mAgentWeb.getWebLifeCycle().onResume(); super.onResume(); } @Override protected void onDestroy() { mAgentWeb.getWebLifeCycle().onDestroy(); if (mRealmHelper != null) { mRealmHelper.destroy(); } super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mAgentWeb.handleKeyEvent(keyCode, event)) { return true; } return super.onKeyDown(keyCode, event); } private void collect() { if (TextUtils.equals(mCurrUrl, mUrl)) { if (mArticleId != -1) { presenter.collect(mArticleId); } else { if (TextUtils.isEmpty(mAuthor)) { presenter.collect(mTitle, mUrl); } else { presenter.collect(mTitle, mAuthor, mUrl); } } } else { presenter.collect(mCurrTitle, mCurrUrl); } } private void forceHttpsForAndroid9() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { return; } if (mUrl == null) { return; } if (mUrl.startsWith("http://")) { mUrl = mUrl.replace("http://", "https://"); } } @Override public void collectSuccess() { ToastMaker.showShort("收藏成功"); } @Override public void collectFailed(String msg) { ToastMaker.showShort(msg); } }
c2cac8444564d0332f9a99b838a7a8438b8bff84
f92163502a0a33994f265a6719ff2c592d1e13b2
/test/org/traccar/protocol/Tk103ProtocolDecoderTest.java
b7e4ab849180526aca1214b399522432c9a17a37
[ "Apache-2.0" ]
permissive
jimmyuk/traccar
4cf7b218441cc8b1bbdc873d27b46bb9b7f090a7
0696ac5b815e8a3e4001656b3c70d9a50fee0d20
refs/heads/master
2021-01-17T07:51:37.858140
2013-01-30T10:01:22
2013-01-30T10:01:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
799
java
package org.traccar.protocol; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; public class Tk103ProtocolDecoderTest { @Test public void testDecode() throws Exception { Tk103ProtocolDecoder decoder = new Tk103ProtocolDecoder(null); decoder.setDataManager(new TestDataManager()); assertNull(decoder.decode(null, null, "(090411121854BP0000001234567890HSO")); assertNotNull(decoder.decode(null, null, "(035988863964BP05000035988863964110524A4241.7977N02318.7561E000.0123536356.5100000000L000946BB")); assertNotNull(decoder.decode(null, null, "(013632782450BP05000013632782450120803V0000.0000N00000.0000E000.0174654000.0000000000L00000000")); } }