blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
fb04bfbe9d79de1536239e36081e1196b3ff6e2a
b5f8ce4f162e41501d71aabf480bb9b8df94201b
/src/main/java/sn/seysoo/web/rest/TroupeauResource.java
990148299961df04bf1a1dfde43fe9c173bb291c
[]
no_license
abdoulayeyoussoufa/betail
56b589928844939a02a00b429f91471228f96000
ddc8274f002f9e3d8618514f55b857fe79e31268
refs/heads/master
2020-03-23T08:09:43.006792
2017-05-11T12:00:29
2017-05-11T12:00:29
141,308,588
0
0
null
null
null
null
UTF-8
Java
false
false
4,575
java
package sn.seysoo.web.rest; import com.codahale.metrics.annotation.Timed; import sn.seysoo.domain.Troupeau; import sn.seysoo.repository.TroupeauRepository; import sn.seysoo.web.rest.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing Troupeau. */ @RestController @RequestMapping("/api") public class TroupeauResource { private final Logger log = LoggerFactory.getLogger(TroupeauResource.class); private static final String ENTITY_NAME = "troupeau"; private final TroupeauRepository troupeauRepository; public TroupeauResource(TroupeauRepository troupeauRepository) { this.troupeauRepository = troupeauRepository; } /** * POST /troupeaus : Create a new troupeau. * * @param troupeau the troupeau to create * @return the ResponseEntity with status 201 (Created) and with body the new troupeau, or with status 400 (Bad Request) if the troupeau has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/troupeaus") @Timed public ResponseEntity<Troupeau> createTroupeau(@Valid @RequestBody Troupeau troupeau) throws URISyntaxException { log.debug("REST request to save Troupeau : {}", troupeau); if (troupeau.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new troupeau cannot already have an ID")).body(null); } Troupeau result = troupeauRepository.save(troupeau); return ResponseEntity.created(new URI("/api/troupeaus/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /troupeaus : Updates an existing troupeau. * * @param troupeau the troupeau to update * @return the ResponseEntity with status 200 (OK) and with body the updated troupeau, * or with status 400 (Bad Request) if the troupeau is not valid, * or with status 500 (Internal Server Error) if the troupeau couldnt be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/troupeaus") @Timed public ResponseEntity<Troupeau> updateTroupeau(@Valid @RequestBody Troupeau troupeau) throws URISyntaxException { log.debug("REST request to update Troupeau : {}", troupeau); if (troupeau.getId() == null) { return createTroupeau(troupeau); } Troupeau result = troupeauRepository.save(troupeau); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, troupeau.getId().toString())) .body(result); } /** * GET /troupeaus : get all the troupeaus. * * @return the ResponseEntity with status 200 (OK) and the list of troupeaus in body */ @GetMapping("/troupeaus") @Timed public List<Troupeau> getAllTroupeaus() { log.debug("REST request to get all Troupeaus"); List<Troupeau> troupeaus = troupeauRepository.findAll(); return troupeaus; } /** * GET /troupeaus/:id : get the "id" troupeau. * * @param id the id of the troupeau to retrieve * @return the ResponseEntity with status 200 (OK) and with body the troupeau, or with status 404 (Not Found) */ @GetMapping("/troupeaus/{id}") @Timed public ResponseEntity<Troupeau> getTroupeau(@PathVariable String id) { log.debug("REST request to get Troupeau : {}", id); Troupeau troupeau = troupeauRepository.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(troupeau)); } /** * DELETE /troupeaus/:id : delete the "id" troupeau. * * @param id the id of the troupeau to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/troupeaus/{id}") @Timed public ResponseEntity<Void> deleteTroupeau(@PathVariable String id) { log.debug("REST request to delete Troupeau : {}", id); troupeauRepository.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
[ "layoussou@gmail.com" ]
layoussou@gmail.com
c57bb89e59c6badfd6dbcc4064aa4dd265455fac
988c56e627f6e41f56c60acefc9475df4d149b24
/src/main/java/com/zzg/spider/MasterApp.java
49e23846473de215d6eb5b0a00a52d8b9fc8340c
[]
no_license
zhangzeguang88/spider
65f1d9ddb259e053c06ee99dddd97e449ef073a3
1a32d8ee9b6e3f8d81f52b6a8eb1fe71e53781ce
refs/heads/master
2021-09-05T14:42:26.721142
2018-01-29T01:08:39
2018-01-29T01:08:39
119,313,775
0
0
null
null
null
null
UTF-8
Java
false
false
2,719
java
package com.zzg.spider; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.annotation.Resource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; import com.zzg.spider.cache.RedisUtil; import com.zzg.spider.parse.BloomFilter; import com.zzg.spider.parse.LinkFilter; public class MasterApp { public static void main(String args[]){ ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); final LinkFilter linkFilter = (LinkFilter)context.getBean("linkFilter"); List<String> seed = readSeed("D:/spider_init.txt"); for(int i=0;i<seed.size();i++){ RedisUtil.lpush("queue", seed.get(i)); } // 启动解析线程 ExecutorService pool = Executors.newFixedThreadPool(2); Runnable ra = new Runnable(){ @Override public void run() { while(true){ String source = (String) RedisUtil.rpop("sourceQueue"); if(source == null){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } continue; } try { linkFilter.findLinkByJ(source); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; pool.submit(ra); //pool.submit(new MasterThreadRunnable()); pool.shutdown(); } public static List<String> readSeed(String filePath){ List<String> seed= new ArrayList<String>(); try { String encoding="utf-8"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ seed.add(lineTxt); } read.close(); }else{ System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } return seed; } }
[ "zhangzeguang88@sina.com" ]
zhangzeguang88@sina.com
7eab9c48ec3d31db8a6f0d01a2ab3e60369ee377
a62bddb3c9d9a311029a0c547b6c978bbddf3955
/src/main/java/pl/jkan/weatherapp/Cli.java
0a2f951ebc343c2ccf0af9f515e21484a4b17251
[]
no_license
Riserax/weather-station-java
430b64a0ec866170b470daf78de6da87147c4865
99a5f5569bf4690ebe4662de9098d5aca0110dfa
refs/heads/master
2021-08-19T20:18:59.278857
2017-11-27T10:46:36
2017-11-27T10:46:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
954
java
package pl.jkan.weatherapp; import pl.jkan.http.SimpleBrowser; import pl.jkan.openweatherapi.ApiClient; import pl.jkan.openweatherapi.TempParser; import pl.jkan.weatherstation.WeatherStation; import pl.jkan.weatherstation.sensors.ApiTempSensor; import pl.jkan.weatherstation.TempSensor; public class Cli { public static void main(String[] args) { String city = ""; try { city = args[0]; } catch (ArrayIndexOutOfBoundsException e) { city = "Krakow"; } TempSensor tempSensor = new ApiTempSensor( new ApiClient( new SimpleBrowser(), new TempParser(), city, System.getenv("OPEN_WEATHER_API_KEY") ) ); WeatherStation station = new WeatherStation(tempSensor); Double temp = station.temperature(); System.out.printf("Weather in %s| Temp: %s\n", city, temp); } }
[ "jakub.kanclerz@gmail.com" ]
jakub.kanclerz@gmail.com
07d2e0c070271c2cf0089abb86af6e3176fcabde
a452b04796e0e0ca3eb85a5f772df650cd903a26
/311_example_01/app/src/test/java/com/ch/a311_example_01/ExampleUnitTest.java
1d27f12cce978f244e73bcaefd3c3e155de371cd
[]
no_license
Chsengni/CZL_Android_Examples
a0bfd9041417dd2d07ef7422cbf54b5b64a24040
1242de1e2822c17cd9ae157a2778136f40ce8e76
refs/heads/master
2020-04-26T16:34:36.846660
2019-03-04T06:57:31
2019-03-04T06:57:31
173,684,090
1
0
null
null
null
null
UTF-8
Java
false
false
383
java
package com.ch.a311_example_01; 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); } }
[ "2371778707@qq.com" ]
2371778707@qq.com
56581ea0840edb0e19bb56dc0da1e38aa2048fee
92fdf061b26f90bea9e883d302ca3b0f5bb84ff0
/src/main/java/okkpp/model/investment/RegisteredOfBusiness.java
91c1f55143ea2fb91dba9ea9f5afacb6a49fcbe2
[]
no_license
YoYB/CEECDATA
3fea138cea87925a94d3a82d0d3a0ea0b558ed8e
d1991220a76a9a96dd89de3c3a666643d4b40c5c
refs/heads/master
2021-01-25T13:17:40.834622
2018-03-02T03:04:46
2018-03-02T03:04:46
null
0
0
null
null
null
null
GB18030
Java
false
false
1,384
java
package okkpp.model.investment; import java.util.Date; /** * 新注册企业数 New Businesses Registered * * @author wcyong * * @date 2018-02-09 */ public class RegisteredOfBusiness { private Integer id; /** * 国家代码 */ private String country; /** * 年份 */ private Integer year; /** * 新注册企业数(个) */ private Integer number; /** * 更新时间 */ private Date update; /** * 排序 */ private Integer sort; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country == null ? null : country.trim(); } public Integer getYear() { return year; } public void setYear(Integer year) { this.year = year; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public Date getUpdate() { return update; } public void setUpdate(Date update) { this.update = update; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } }
[ "409896482@qq.com" ]
409896482@qq.com
0d2f5de4a32e9b66cddf119e290039a00bc844d9
9e632588def0ba64442d92485b6d155ccb89a283
/mx-webadmin/webadmin-dao/src/main/java/com/balicamp/soap/ws/sertifikasi/Inquiry.java
bd8c41bff0a154b370d5ef6f5a57f009409738a6
[]
no_license
prihako/sims2019
6986bccbbd35ec4d1e5741aa77393f01287d752a
f5e82e3d46c405d4c3c34d529c8d67e8627adb71
refs/heads/master
2022-12-21T07:38:06.400588
2021-04-29T07:30:37
2021-04-29T07:30:37
212,565,332
0
0
null
2022-12-16T00:41:00
2019-10-03T11:41:00
Java
UTF-8
Java
false
false
1,489
java
package com.balicamp.soap.ws.sertifikasi; 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 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="req" type="{urn:PaymentManagerControllerwsdl}InquiryRequest"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "req" }) @XmlRootElement(name = "inquiry") public class Inquiry { @XmlElement(required = true, nillable = true) protected InquiryRequest req; /** * Gets the value of the req property. * * @return * possible object is * {@link InquiryRequest } * */ public InquiryRequest getReq() { return req; } /** * Sets the value of the req property. * * @param value * allowed object is * {@link InquiryRequest } * */ public void setReq(InquiryRequest value) { this.req = value; } }
[ "nurukat@gmail.com" ]
nurukat@gmail.com
4a3653d699215c33e6ef381436689a69994137da
7991248e6bccacd46a5673638a4e089c8ff72a79
/web/application/src/main/java/org/artifactory/webapp/servlet/SessionFilter.java
81213ddba814aa40acd7ca14d7a42c5a684a78b2
[]
no_license
theoriginalshaheedra/artifactory-oss
69b7f6274cb35c79db3a3cd613302de2ae019b31
415df9a9467fee9663850b4b8b4ee5bd4c23adeb
refs/heads/master
2023-04-23T15:48:36.923648
2021-05-05T06:15:24
2021-05-05T06:15:24
364,455,815
1
0
null
2021-05-05T07:11:40
2021-05-05T03:57:33
Java
UTF-8
Java
false
false
2,173
java
/* * * Artifactory is a binaries repository manager. * Copyright (C) 2018 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. * */ package org.artifactory.webapp.servlet; import org.artifactory.api.context.ArtifactoryContext; import org.springframework.session.SessionRepository; import org.springframework.session.web.http.SessionRepositoryFilter; import javax.servlet.*; import java.io.IOException; /** * Delegating filter from a delayed context filter to {@link SessionRepositoryFilter} * * @author Shay Yaakov */ public class SessionFilter extends DelayedFilterBase { private SessionRepositoryFilter delegate; @Override public void initLater(FilterConfig filterConfig) throws ServletException { ServletContext servletContext = filterConfig.getServletContext(); ArtifactoryContext context = RequestUtils.getArtifactoryContext(servletContext); SessionRepository sessionRepository = context.beanForType(SessionRepository.class); delegate = new SessionRepositoryFilter(sessionRepository); delegate.setServletContext(servletContext); } @Override public void destroy() { if (delegate != null) { delegate.destroy(); } } @Override public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException { if (shouldSkipFilter(req)) { chain.doFilter(req, resp); return; } delegate.doFilter(req, resp, chain); } }
[ "david.monichi@gmail.com" ]
david.monichi@gmail.com
6c0a47a45bdc6c72bba30e1361d6aa36de8783a9
08be4f0862fcc8dafc69f6237da9401f152f2c48
/sprd/UniverseUI/SprdLauncher1/src/com/sprd/sprdlauncher1/effect/FadeEffect.java
d9e39d624582f4add95cf798f62ed9553653e4e7
[ "Apache-2.0" ]
permissive
harryxiao/Sc7731-Sc8830-Vendor_Source
c41df77c7919c4b50457c3f35b55401d756301c4
c069804190c37465c27bfd982a9b82e1241795dd
refs/heads/master
2020-04-19T23:41:32.458177
2018-03-01T08:40:31
2018-03-01T08:40:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,331
java
/** Created by Spreadst */ package com.sprd.launcher3.effect; import android.content.Context; import android.graphics.Camera; import android.graphics.Matrix; import android.view.View; import android.view.ViewGroup; import android.view.animation.Transformation; import android.widget.Scroller; public class FadeEffect extends EffectInfo{ public FadeEffect(int id) { super(id); } @Override public boolean getCellLayoutChildStaticTransformation(ViewGroup viewGroup, View viewiew, Transformation transformation, Camera camera, float offset) { return false; } @Override public boolean getWorkspaceChildStaticTransformation(ViewGroup viewGroup, View viewiew, Transformation transformation, Camera camera, float offset) { if (offset == 0.0F || offset >= 1.0F || offset <= -1.0F) return false; Matrix tMatrix = transformation.getMatrix(); float absOffset = Math.abs(offset); float mAlpha = (1.0F - absOffset) * 0.7F + 0.3F; transformation.setAlpha(mAlpha); tMatrix.setScale(mAlpha, mAlpha, viewiew.getWidth()/2.0f, viewiew.getHeight()/2.0f); transformation.setTransformationType(Transformation.TYPE_BOTH); // transformation.setTransformationType(Transformation.TYPE_ALPHA); return true; } /* SPRD: Fix bug257614 @{ */ @Override public void getTransformationMatrix(View view ,float offset, int pageWidth, int pageHeight, boolean overScroll, boolean overScrollLeft){ /* @} */ float absOffset = Math.abs(offset); float mAlpha = 1.0F - absOffset; int mViewWidth = pageWidth; int mViewHeight = pageHeight; int mViewHalfWidth = mViewWidth >> 1; int mViewHalfHeight = mViewHeight >> 1; view.setTranslationX(0f); view.setPivotY(mViewHalfHeight); view.setPivotX(mViewHalfWidth); view.setRotationX(0f); view.setRotation(0f); view.setRotationY(0f); view.setScaleX(1.0f); view.setScaleY(1.0f); view.setAlpha(mAlpha); } @Override public Scroller getScroller(Context context) { // TODO Auto-generated method stub return new Scroller(context); } @Override public int getSnapTime() { return 240; } }
[ "nayemur9800@gmail.com" ]
nayemur9800@gmail.com
8641838737d6ec7d9613526d94846a0ab10b61ab
63e7a50adc729dad1dc8e752c48c501bfc5bdab4
/src/com/dataStuctureAndAlgorithm/LeetCode/BinaryTree/BalanceBT_110.java
89c3509dedf90ceaa3cd62590f86149fac442a36
[]
no_license
weiruchenai/DSandA
585582b411db70c0f90f82b9f40cc7b8ee6b20ed
0cf6a30923e122e29376a5d4f3074b56a342ae33
refs/heads/master
2023-01-19T22:37:21.725817
2020-11-18T05:36:18
2020-11-18T05:36:18
284,951,968
0
0
null
null
null
null
UTF-8
Java
false
false
1,091
java
package com.dataStuctureAndAlgorithm.LeetCode.BinaryTree; import com.sun.source.tree.Tree; import java.util.Collections; import java.util.LinkedList; import java.util.List; /* * 110. 平衡二叉树 *给定一个二叉树,判断它是否是高度平衡的二叉树(一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1) * * 思路,对于一个root而言,找到左子树和右子树的最大深度,两者相减的绝对值大于1则返回false,否则返回true * */ public class BalanceBT_110 { public boolean isBalanced(TreeNode root) { if(root == null) return true; //若当前root的左右子树最大深度差值>1,返回false,否则递归调用 int depthDiffer = Math.abs(getMaxDepth(root.left) - getMaxDepth(root.right)); if(depthDiffer > 1) return false; return isBalanced(root.left) && isBalanced(root.right); } public int getMaxDepth(TreeNode root){ if(root == null) return 0; int leftHeight = getMaxDepth(root.left); int rightHeight = getMaxDepth(root.right); return Math.max(leftHeight, rightHeight) + 1; } }
[ "475596527@qq.com" ]
475596527@qq.com
7b3cdf3f14b1c7c574782b11bfc16e0df37d153a
7565725272da0b194a7a6b1a06a7037e6e6929a0
/spring-cql/src/test/java/org/springframework/cassandra/core/ConsistencyLevelResolverUnitTests.java
12b0b75d335b5f2c6b2d282fa02facd7fdc6d4fd
[ "LicenseRef-scancode-generic-cla" ]
no_license
paulokinho/spring-data-cassandra
460abd2b3f6160b67464f3a86b1c7171a8e94e35
44671e4854e8395ac33efcc144c1de3bd3d3f270
refs/heads/master
2020-02-26T16:12:25.391964
2017-03-05T22:17:01
2017-03-05T22:17:01
68,550,589
0
3
null
2017-03-05T22:17:02
2016-09-18T22:25:43
Java
UTF-8
Java
false
false
3,462
java
/* * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.cassandra.core; import static org.assertj.core.api.Assertions.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Unit tests for {@link ConsistencyLevelResolver}. * * @author Mark Paluch */ @RunWith(Parameterized.class) public class ConsistencyLevelResolverUnitTests { private final ConsistencyLevel from; private final com.datastax.driver.core.ConsistencyLevel expected; public ConsistencyLevelResolverUnitTests(ConsistencyLevel from, com.datastax.driver.core.ConsistencyLevel expected) { this.from = from; this.expected = expected; } @Parameters(name = "{0}") public static List<Object[]> parameters() { Map<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel> expectations = new LinkedHashMap<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel>(); expectations.put(ConsistencyLevel.ALL, com.datastax.driver.core.ConsistencyLevel.ALL); expectations.put(ConsistencyLevel.ANY, com.datastax.driver.core.ConsistencyLevel.ANY); expectations.put(ConsistencyLevel.QUOROM, com.datastax.driver.core.ConsistencyLevel.QUORUM); expectations.put(ConsistencyLevel.QUORUM, com.datastax.driver.core.ConsistencyLevel.QUORUM); expectations.put(ConsistencyLevel.LOCAL_QUOROM, com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM); expectations.put(ConsistencyLevel.LOCAL_QUORUM, com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM); expectations.put(ConsistencyLevel.EACH_QUOROM, com.datastax.driver.core.ConsistencyLevel.EACH_QUORUM); expectations.put(ConsistencyLevel.EACH_QUORUM, com.datastax.driver.core.ConsistencyLevel.EACH_QUORUM); expectations.put(ConsistencyLevel.LOCAL_ONE, com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE); expectations.put(ConsistencyLevel.LOCAL_SERIAL, com.datastax.driver.core.ConsistencyLevel.LOCAL_SERIAL); expectations.put(ConsistencyLevel.SERIAL, com.datastax.driver.core.ConsistencyLevel.SERIAL); expectations.put(ConsistencyLevel.ONE, com.datastax.driver.core.ConsistencyLevel.ONE); expectations.put(ConsistencyLevel.TWO, com.datastax.driver.core.ConsistencyLevel.TWO); expectations.put(ConsistencyLevel.THREE, com.datastax.driver.core.ConsistencyLevel.THREE); List<Object[]> parameters = new ArrayList<Object[]>(); for (Entry<ConsistencyLevel, com.datastax.driver.core.ConsistencyLevel> entry : expectations.entrySet()) { parameters.add(new Object[] { entry.getKey(), entry.getValue() }); } return parameters; } @Test // DATACASS-202 public void shouldResolveCorrectly() { assertThat(ConsistencyLevelResolver.resolve(from)).isEqualTo(expected); } }
[ "mpaluch@pivotal.io" ]
mpaluch@pivotal.io
a4a43f819d06da4798d4f521b755d6d3b01b2433
7b8b47b06bb5415fbd476059635a9c71b5e8f430
/app/src/androidTest/java/org/rdtoolkit/FlatInputTranslatorTest.java
2aa0186c9c862fa979259ebf522dceb73aa5bccf
[ "Apache-2.0" ]
permissive
cws1121/rd-toolkit
451758dc2180dbd33e34870fe5c34866cd162634
f78d019af891968d8de02fd49e6cf8eb71b000d0
refs/heads/master
2023-03-03T06:12:18.762161
2021-02-02T05:12:31
2021-02-02T05:12:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,614
java
package org.rdtoolkit; import android.content.Intent; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.rdtoolkit.support.interop.BundleToConfiguration; import org.rdtoolkit.interop.translator.InteropRepository; import org.rdtoolkit.support.model.session.ClassifierMode; import org.rdtoolkit.support.model.session.ProvisionMode; import org.rdtoolkit.support.model.session.SessionMode; import org.rdtoolkit.support.model.session.TestSession; import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_CLASSIFIER_MODE; import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_CONFIG_SESSION_TYPE; import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_PROVISION_MODE; import static org.rdtoolkit.support.interop.IntentObjectMappingsKt.INTENT_EXTRA_RDT_PROVISION_MODE_DATA; import static org.rdtoolkit.interop.translator.TranslatorsKt.TRANSLATOR_PROVISION_FLAT; import static org.rdtoolkit.support.interop.RdtIntentBuilder.INTENT_EXTRA_RDT_CONFIG_BUNDLE; import static org.rdtoolkit.support.model.session.SessionFlagsKt.FLAG_SESSION_NO_EXPIRATION_OVERRIDE; import static org.rdtoolkit.support.model.session.SessionFlagsKt.FLAG_VALUE_SET; /** * 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 FlatInputTranslatorTest { @Test public void testStructure() { Intent testIntent = new Intent(); testIntent.putExtra(INTENT_EXTRA_RDT_PROVISION_MODE, ProvisionMode.TEST_PROFILE.toString()); testIntent.putExtra(INTENT_EXTRA_RDT_PROVISION_MODE_DATA, "TestType"); testIntent.putExtra(INTENT_EXTRA_RDT_CONFIG_SESSION_TYPE, SessionMode.ONE_PHASE.toString()); testIntent.putExtra(INTENT_EXTRA_RDT_CLASSIFIER_MODE, ClassifierMode.PRE_POPULATE.toString()); testIntent.putExtra(FLAG_SESSION_NO_EXPIRATION_OVERRIDE, FLAG_VALUE_SET); Intent output = new InteropRepository().getTranslator(TRANSLATOR_PROVISION_FLAT).map(testIntent); Assert.assertTrue(output.hasExtra(INTENT_EXTRA_RDT_CONFIG_BUNDLE)); TestSession.Configuration config = new BundleToConfiguration().map(output.getBundleExtra(INTENT_EXTRA_RDT_CONFIG_BUNDLE)); Assert.assertEquals(SessionMode.ONE_PHASE, config.getSessionType()); Assert.assertEquals(FLAG_VALUE_SET, config.getFlags().get(FLAG_SESSION_NO_EXPIRATION_OVERRIDE)); } }
[ "csims@dimagi.com" ]
csims@dimagi.com
894206f14f08c8c93d88a09cbd0dfae52c6fd963
5a47617ff6befde02bd748c99655bbe7f4e6b6f5
/app/build/generated/source/r/debug/com/google/android/gms/maps/R.java
89ad251296efaa3ed4618fc04e9b8fb404bd4c0a
[]
no_license
Bubbles2/EasySnap
13ee7007375d28620fe491ac99432d2f8e9d61b7
22172a34d2006d676e17f97daa328adcd23d6fad
refs/heads/master
2016-09-01T04:17:49.922511
2015-10-20T10:01:32
2015-10-20T10:01:32
44,597,621
0
0
null
null
null
null
UTF-8
Java
false
false
16,438
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms.maps; public final class R { public static final class attr { public static final int adSize = 0x7f010026; public static final int adSizes = 0x7f010027; public static final int adUnitId = 0x7f010028; public static final int ambientEnabled = 0x7f01004e; public static final int appTheme = 0x7f0100e9; public static final int buyButtonAppearance = 0x7f0100f0; public static final int buyButtonHeight = 0x7f0100ed; public static final int buyButtonText = 0x7f0100ef; public static final int buyButtonWidth = 0x7f0100ee; public static final int cameraBearing = 0x7f01003f; public static final int cameraTargetLat = 0x7f010040; public static final int cameraTargetLng = 0x7f010041; public static final int cameraTilt = 0x7f010042; public static final int cameraZoom = 0x7f010043; public static final int circleCrop = 0x7f01003d; public static final int environment = 0x7f0100ea; public static final int fragmentMode = 0x7f0100ec; public static final int fragmentStyle = 0x7f0100eb; public static final int imageAspectRatio = 0x7f01003c; public static final int imageAspectRatioAdjust = 0x7f01003b; public static final int liteMode = 0x7f010044; public static final int mapType = 0x7f01003e; public static final int maskedWalletDetailsBackground = 0x7f0100f3; public static final int maskedWalletDetailsButtonBackground = 0x7f0100f5; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f0100f4; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f0100f2; public static final int maskedWalletDetailsLogoImageType = 0x7f0100f7; public static final int maskedWalletDetailsLogoTextColor = 0x7f0100f6; public static final int maskedWalletDetailsTextAppearance = 0x7f0100f1; public static final int uiCompass = 0x7f010045; public static final int uiMapToolbar = 0x7f01004d; public static final int uiRotateGestures = 0x7f010046; public static final int uiScrollGestures = 0x7f010047; public static final int uiTiltGestures = 0x7f010048; public static final int uiZoomControls = 0x7f010049; public static final int uiZoomGestures = 0x7f01004a; public static final int useViewLifecycle = 0x7f01004b; public static final int windowTransitionStyle = 0x7f01002f; public static final int zOrderOnTop = 0x7f01004c; } public static final class color { public static final int common_action_bar_splitter = 0x7f0c0012; public static final int common_signin_btn_dark_text_default = 0x7f0c0013; public static final int common_signin_btn_dark_text_disabled = 0x7f0c0014; public static final int common_signin_btn_dark_text_focused = 0x7f0c0015; public static final int common_signin_btn_dark_text_pressed = 0x7f0c0016; public static final int common_signin_btn_default_background = 0x7f0c0017; public static final int common_signin_btn_light_text_default = 0x7f0c0018; public static final int common_signin_btn_light_text_disabled = 0x7f0c0019; public static final int common_signin_btn_light_text_focused = 0x7f0c001a; public static final int common_signin_btn_light_text_pressed = 0x7f0c001b; public static final int common_signin_btn_text_dark = 0x7f0c005a; public static final int common_signin_btn_text_light = 0x7f0c005b; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0c0043; public static final int wallet_bright_foreground_holo_dark = 0x7f0c0044; public static final int wallet_bright_foreground_holo_light = 0x7f0c0045; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0c0046; public static final int wallet_dim_foreground_holo_dark = 0x7f0c0047; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0c0048; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0c0049; public static final int wallet_highlighted_text_holo_dark = 0x7f0c004a; public static final int wallet_highlighted_text_holo_light = 0x7f0c004b; public static final int wallet_hint_foreground_holo_dark = 0x7f0c004c; public static final int wallet_hint_foreground_holo_light = 0x7f0c004d; public static final int wallet_holo_blue_light = 0x7f0c004e; public static final int wallet_link_text_light = 0x7f0c004f; public static final int wallet_primary_text_holo_light = 0x7f0c005e; public static final int wallet_secondary_text_holo_dark = 0x7f0c005f; } public static final class drawable { public static final int cast_ic_notification_0 = 0x7f020043; public static final int cast_ic_notification_1 = 0x7f020044; public static final int cast_ic_notification_2 = 0x7f020045; public static final int cast_ic_notification_connecting = 0x7f020046; public static final int cast_ic_notification_on = 0x7f020047; public static final int common_full_open_on_phone = 0x7f020048; public static final int common_ic_googleplayservices = 0x7f020049; public static final int common_signin_btn_icon_dark = 0x7f02004a; public static final int common_signin_btn_icon_disabled_dark = 0x7f02004b; public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f02004c; public static final int common_signin_btn_icon_disabled_focus_light = 0x7f02004d; public static final int common_signin_btn_icon_disabled_light = 0x7f02004e; public static final int common_signin_btn_icon_focus_dark = 0x7f02004f; public static final int common_signin_btn_icon_focus_light = 0x7f020050; public static final int common_signin_btn_icon_light = 0x7f020051; public static final int common_signin_btn_icon_normal_dark = 0x7f020052; public static final int common_signin_btn_icon_normal_light = 0x7f020053; public static final int common_signin_btn_icon_pressed_dark = 0x7f020054; public static final int common_signin_btn_icon_pressed_light = 0x7f020055; public static final int common_signin_btn_text_dark = 0x7f020056; public static final int common_signin_btn_text_disabled_dark = 0x7f020057; public static final int common_signin_btn_text_disabled_focus_dark = 0x7f020058; public static final int common_signin_btn_text_disabled_focus_light = 0x7f020059; public static final int common_signin_btn_text_disabled_light = 0x7f02005a; public static final int common_signin_btn_text_focus_dark = 0x7f02005b; public static final int common_signin_btn_text_focus_light = 0x7f02005c; public static final int common_signin_btn_text_light = 0x7f02005d; public static final int common_signin_btn_text_normal_dark = 0x7f02005e; public static final int common_signin_btn_text_normal_light = 0x7f02005f; public static final int common_signin_btn_text_pressed_dark = 0x7f020060; public static final int common_signin_btn_text_pressed_light = 0x7f020061; public static final int ic_plusone_medium_off_client = 0x7f02007d; public static final int ic_plusone_small_off_client = 0x7f02007e; public static final int ic_plusone_standard_off_client = 0x7f02007f; public static final int ic_plusone_tall_off_client = 0x7f020080; public static final int powered_by_google_dark = 0x7f020096; public static final int powered_by_google_light = 0x7f020097; } public static final class id { public static final int adjust_height = 0x7f0d0018; public static final int adjust_width = 0x7f0d0019; public static final int book_now = 0x7f0d0033; public static final int buyButton = 0x7f0d0030; public static final int buy_now = 0x7f0d0034; public static final int buy_with = 0x7f0d0035; public static final int buy_with_google = 0x7f0d0036; public static final int cast_notification_id = 0x7f0d0004; public static final int classic = 0x7f0d003a; public static final int donate_with = 0x7f0d0037; public static final int donate_with_google = 0x7f0d0038; public static final int google_wallet_classic = 0x7f0d003b; public static final int google_wallet_grayscale = 0x7f0d003c; public static final int google_wallet_monochrome = 0x7f0d003d; public static final int grayscale = 0x7f0d003e; public static final int holo_dark = 0x7f0d002a; public static final int holo_light = 0x7f0d002b; public static final int hybrid = 0x7f0d001a; public static final int logo_only = 0x7f0d0039; public static final int match_parent = 0x7f0d0032; public static final int monochrome = 0x7f0d003f; public static final int none = 0x7f0d000f; public static final int normal = 0x7f0d000b; public static final int production = 0x7f0d002c; public static final int sandbox = 0x7f0d002d; public static final int satellite = 0x7f0d001b; public static final int selectionDetails = 0x7f0d0031; public static final int slide = 0x7f0d0014; public static final int strict_sandbox = 0x7f0d002e; public static final int terrain = 0x7f0d001c; public static final int test = 0x7f0d002f; public static final int wrap_content = 0x7f0d0024; } public static final class integer { public static final int google_play_services_version = 0x7f0b0004; } public static final class raw { public static final int gtm_analytics = 0x7f060000; } public static final class string { public static final int accept = 0x7f07005a; public static final int auth_google_play_services_client_facebook_display_name = 0x7f07005b; public static final int auth_google_play_services_client_google_display_name = 0x7f07005c; public static final int cast_notification_connected_message = 0x7f07005d; public static final int cast_notification_connecting_message = 0x7f07005e; public static final int cast_notification_disconnect = 0x7f07005f; public static final int common_android_wear_notification_needs_update_text = 0x7f07000d; public static final int common_android_wear_update_text = 0x7f07000e; public static final int common_android_wear_update_title = 0x7f07000f; public static final int common_google_play_services_api_unavailable_text = 0x7f070010; public static final int common_google_play_services_enable_button = 0x7f070011; public static final int common_google_play_services_enable_text = 0x7f070012; public static final int common_google_play_services_enable_title = 0x7f070013; public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f070014; public static final int common_google_play_services_install_button = 0x7f070015; public static final int common_google_play_services_install_text_phone = 0x7f070016; public static final int common_google_play_services_install_text_tablet = 0x7f070017; public static final int common_google_play_services_install_title = 0x7f070018; public static final int common_google_play_services_invalid_account_text = 0x7f070019; public static final int common_google_play_services_invalid_account_title = 0x7f07001a; public static final int common_google_play_services_needs_enabling_title = 0x7f07001b; public static final int common_google_play_services_network_error_text = 0x7f07001c; public static final int common_google_play_services_network_error_title = 0x7f07001d; public static final int common_google_play_services_notification_needs_update_title = 0x7f07001e; public static final int common_google_play_services_notification_ticker = 0x7f07001f; public static final int common_google_play_services_sign_in_failed_text = 0x7f070020; public static final int common_google_play_services_sign_in_failed_title = 0x7f070021; public static final int common_google_play_services_unknown_issue = 0x7f070022; public static final int common_google_play_services_unsupported_text = 0x7f070023; public static final int common_google_play_services_unsupported_title = 0x7f070024; public static final int common_google_play_services_update_button = 0x7f070025; public static final int common_google_play_services_update_text = 0x7f070026; public static final int common_google_play_services_update_title = 0x7f070027; public static final int common_google_play_services_updating_text = 0x7f070028; public static final int common_google_play_services_updating_title = 0x7f070029; public static final int common_open_on_phone = 0x7f07002a; public static final int common_signin_button_text = 0x7f070060; public static final int common_signin_button_text_long = 0x7f070061; public static final int create_calendar_message = 0x7f070062; public static final int create_calendar_title = 0x7f070063; public static final int decline = 0x7f070064; public static final int store_picture_message = 0x7f07006a; public static final int store_picture_title = 0x7f07006b; public static final int wallet_buy_button_place_holder = 0x7f070031; } public static final class style { public static final int Theme_IAPTheme = 0x7f0900e1; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0900e9; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0900ea; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0900eb; public static final int WalletFragmentDefaultStyle = 0x7f0900ec; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010026, 0x7f010027, 0x7f010028 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] CustomWalletTheme = { 0x7f01002f }; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] LoadingImageView = { 0x7f01003b, 0x7f01003c, 0x7f01003d }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f01003e, 0x7f01003f, 0x7f010040, 0x7f010041, 0x7f010042, 0x7f010043, 0x7f010044, 0x7f010045, 0x7f010046, 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c, 0x7f01004d, 0x7f01004e }; public static final int MapAttrs_ambientEnabled = 16; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] WalletFragmentOptions = { 0x7f0100e9, 0x7f0100ea, 0x7f0100eb, 0x7f0100ec }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f0100ed, 0x7f0100ee, 0x7f0100ef, 0x7f0100f0, 0x7f0100f1, 0x7f0100f2, 0x7f0100f3, 0x7f0100f4, 0x7f0100f5, 0x7f0100f6, 0x7f0100f7 }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
[ "donncha.finlay@gmail.com" ]
donncha.finlay@gmail.com
9e3d795b834fee71f3242d16bfbb205f8ff2b2a8
da845f70689a6f45cdc4675d80fa86d150c94fa9
/src/java/com/twitter/elephantbird/mapred/output/DeprecatedLzoProtobufBlockRecordWriter.java
3f065f2eb5808a20d43eab4260a806c979735d4c
[ "Apache-2.0" ]
permissive
panisson/elephant-bird
9baef703e964db8e81551ade830929d383cd1d49
fe8fa0c79736cd3e6904d726a035f44c7f2a6989
refs/heads/master
2021-01-15T21:03:36.947442
2012-03-30T21:30:36
2012-03-30T21:30:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
535
java
package com.twitter.elephantbird.mapred.output; import com.google.protobuf.Message; import com.twitter.elephantbird.mapreduce.io.ProtobufBlockWriter; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; /** * A writer for LZO-encoded blocks of Protobuf objects. * */ public class DeprecatedLzoProtobufBlockRecordWriter<M extends Message> extends DeprecatedLzoBinaryBlockRecordWriter<M, ProtobufWritable<M>> { public DeprecatedLzoProtobufBlockRecordWriter(ProtobufBlockWriter<M> writer) { super(writer); } }
[ "argyris@twitter.com" ]
argyris@twitter.com
ec44204217bd65bceb0d267d51fa0149174b0929
0e3afedb74f41d92898c2a2d786d57006b5c3dc1
/src/main/java/org/yousharp/pointatoffer/linkedlist/DeleteOneNode.java
452f9e790c3510b69b8e5dada52989a94e14936b
[]
no_license
xianlaioy/my-algorithm-practice
eb6ec9e653ca65713ab6367b6fc2c97a81373705
562974c18c3a96b5733004771d63543241ccfff5
refs/heads/master
2021-01-17T14:06:48.121011
2014-12-15T15:00:07
2014-12-15T15:00:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,770
java
package org.yousharp.pointatoffer.linkedlist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yousharp.ds.ListNode; /** * 问题: * 给定一个链表和其中一个节点,删除该节点; * * 思路: * 节点的差异体现在节点对象的内容不同。要删除当前节点,可以将当前节点与下一节点的值互换,然后删除下一个节点即可; * 复杂度为O(1); * 需要注意两种特殊情况: * - 如果要删除的节点是最后一个节点,没有下一个节点,此时需要从头遍历了;复杂度为O(n); * - 如果链表只有一个节点,则删除后链表为空; * * User: lingguo * Date: 14-3-10 * Time: 下午11:49 */ public class DeleteOneNode { private static Logger logger = LoggerFactory.getLogger(DeleteOneNode.class); /** * 从链表中删除某一个节点 * * @param head 链表的头节点 * @param toDelete 要删除的节点 * @return 头节点 */ public static ListNode delete(ListNode head, ListNode toDelete) { // param error if (head == null || toDelete == null) { logger.info("param error."); return null; } // 最后一个节点 if (toDelete.next == null) { // 也是头节点 if (head == toDelete) { logger.info("deleted the only one node."); return null; } // 遍历查找前一个节点 ListNode node = head; while (node.next != toDelete) { node = node.next; } node.next = node.next.next; return head; } // 不是最后一个节点,将下一个节点的值覆盖当前节点的值,删除下一个节点 toDelete.value = toDelete.next.value; toDelete.next = toDelete.next.next; return head; } }
[ "daniel5hbs@gmail.com" ]
daniel5hbs@gmail.com
ff211d7d0001ced7244e221d715aa476bc67cfd5
2843dcee70a0a0408eeb46345401b93214071f8b
/app/src/main/java/com/abct/tljr/ui/activity/tools/OneBasis.java
c49c0d0f72cb9d84b88b816fbcca62b25a914c74
[]
no_license
xiaozhugua/tuling
16ac6a778e18c99bd1433912195b186a30fbf86a
f3470c5dfca05b47d8d96a9dc33d4738175de59a
refs/heads/master
2021-01-12T16:42:27.496392
2016-10-20T07:00:12
2016-10-20T07:00:12
71,434,177
1
0
null
null
null
null
UTF-8
Java
false
false
792
java
package com.abct.tljr.ui.activity.tools; /** * @author xbw * @version 创建时间:2015年11月14日 下午6:27:45 */ public class OneBasis { private long time; private float basis; private float close; private String name; public long getVolume() { return volume; } public void setVolume(long volume) { this.volume = volume; } private long volume; public long getTime() { return time; } public void setTime(long time) { this.time = time; } public float getBasis() { return basis; } public void setBasis(float basis) { this.basis = basis; } public float getClose() { return close; } public void setClose(float close) { this.close = close; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[ "1343012815@qq.com" ]
1343012815@qq.com
af4e0c729d02386e616ec900282e48744c789413
a2de1cb6968bedd3f73cf9533561ce1d4f55f8d3
/app/src/main/java/com/iiitd/hammad13060/trackme/SourceDestinationClasses/ContactAdapter.java
d68ea4c82097aab482af49afcab340618d703f01
[]
no_license
hammad13060-zz/TrackMe
a7e5e08bf0d621cb137929e8c342decf0800b883
e0066e702ac569009d1b1cd9c39f256525184355
refs/heads/master
2021-06-05T11:02:41.755335
2016-05-18T17:48:53
2016-05-18T17:48:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,413
java
package com.iiitd.hammad13060.trackme.SourceDestinationClasses; /** * Created by Pushkin on 02-Feb-16. */ import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import com.iiitd.hammad13060.trackme.R; import com.iiitd.hammad13060.trackme.helpers.Contact; public class ContactAdapter extends ArrayAdapter<Contact>{ SparseBooleanArray checkContacts; int layoutResourceId; public static List<Contact> contList; public ContactAdapter(Context context, List<Contact> users) { super(context, 0, users); contList = users; } @Override public int getCount() { return contList.size(); } @Override public Contact getItem(int position) { return contList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Contact user = getContact(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view, parent, false); } TextView tvName = (TextView) convertView.findViewById(R.id.name); CheckBox chk = (CheckBox) convertView.findViewById(R.id.chk_box); tvName.setText(user.name); chk.setOnCheckedChangeListener(myCheckChangList); chk.setTag(position); chk.setChecked(user.box); return convertView; } Contact getContact(int position) { return ((Contact) getItem(position)); } static List<Contact> getBox() { List<Contact> box = new ArrayList<>(); for (Contact p : contList) { if (p.box) box.add(p); } return box; } CompoundButton.OnCheckedChangeListener myCheckChangList = new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { getContact((Integer) buttonView.getTag()).box = isChecked; } }; }
[ "pushkinsoni@yahoo.in" ]
pushkinsoni@yahoo.in
213e9262eb2601d8f68137c635dd87a43c2863f4
5d18ca56692ee88c53b01137cbaa28df153c85c8
/STG/GUI.java
eb4399095e1123735b211bd5efe010791ab9d566
[]
no_license
fullop2/Greenfoot
319f8af3418d59c97db2b251c206d7cbf0294fe0
283bfb192b012393f6690641ba54af78c7e451ee
refs/heads/master
2021-01-11T06:51:09.184544
2016-12-04T15:30:26
2016-12-04T15:30:26
72,400,270
0
0
null
null
null
null
UTF-8
Java
false
false
563
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class GUI here. * * @author (your name) * @version (a version number or a date) */ public class GUI extends Actor { /** * Act - do whatever the GUI wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } public GUI() {} public GUI(String location) { setImage(location); } }
[ "parkth32@gmail.com" ]
parkth32@gmail.com
6bc68d457fdedd893314fb1f1d7c0c9b9497b257
025cc529c5ccb46db51707d17190b858e062225a
/src/pojo_summoner/SummonersBy.java
4628be9a18ebdc753fb002b3074b255b5e1b4ea4
[]
no_license
philzor/Riot-API-Testing
5c076f5b1c2eda79190d11f3fdfa517a95f127ae
6186aa1c412f0a4e5e550334dd3bcccf28b41a6c
refs/heads/master
2021-01-19T06:30:15.480085
2014-04-02T20:28:19
2014-04-02T20:28:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
393
java
package pojo_summoner; public class SummonersBy { public long id; // Summoner ID. public String name; // Summoner name. public int profileIconId; // ID of the summoner icon associated with the summoner. public long revisionDate; //Date summoner was last modified specified as epoch milliseconds. public long summonerLevel; //Summoner level associated with the summoner. }
[ "thomas-w-@web.de" ]
thomas-w-@web.de
a0e887e9ed1c6fa7bec7709884e8d18752b47274
89b27262a916c413fcb979629cc74d1759f02d75
/app/src/main/java/com/lite/main/mvvm/repo/Repository.java
7b71885502723977c520f62d6c524df745cccfb8
[]
no_license
saketp18/MVVM_Retrofit
bbf04ff3adfcfaec7d135856f794431056995867
64dd226f1d90f8e372c15fd10253a1d15de5bc41
refs/heads/master
2020-07-07T17:33:24.338661
2019-08-21T22:16:13
2019-08-21T22:16:13
203,423,032
1
0
null
null
null
null
UTF-8
Java
false
false
2,054
java
package com.lite.main.mvvm.repo; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.lite.main.mvvm.models.ErrorResponse; import com.lite.main.mvvm.models.ImageSource; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import java.util.List; public class Repository { private static Repository repository = null; private MutableLiveData<List<ImageSource>> data = new MutableLiveData<>(); private MutableLiveData<ErrorResponse> error = new MutableLiveData<>(); private Repository() { } public static Repository getRepository(){ if(repository == null){ repository = new Repository(); } return repository; } public LiveData<List<ImageSource>> getLiveData(){ return data; } public LiveData<ErrorResponse> getError() { return error; } public void getData(int page, int pageSize){ Call<List<ImageSource>> call = RetrofitClientInstance.getClient().getImages(page); call.enqueue(new Callback<List<ImageSource>>() { @Override public void onResponse(Call<List<ImageSource>> call, Response<List<ImageSource>> response) { if(response.isSuccessful()){ data.setValue(response.body()); }else { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setError(response.errorBody().toString()); errorResponse.setStatus(ErrorResponse.STATUS.RESPONSE_FAIL.ordinal()); error.setValue(errorResponse); } } @Override public void onFailure(Call<List<ImageSource>> call, Throwable t) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setError(t.getMessage()); errorResponse.setStatus(ErrorResponse.STATUS.FAILURE.ordinal()); error.setValue(errorResponse); } }); } }
[ "saketp18@users.noreply.github.com" ]
saketp18@users.noreply.github.com
ae5261aabd70a15c200428fe9eaa6108f9de8fd3
886ef86d03e51da931bca03d8bbcdd870477c7fb
/TimeTest.java
96b4a6bbed1983264c737ae3f6c074380ffe7578
[]
no_license
Wei-Xia/Java_Foundation
447681c601d262f16c26c2dbe9ed24e1e9fb7ac9
1fa612127a749d74d023d2c57b1d25c83e2fa856
refs/heads/master
2016-09-06T12:20:08.264777
2015-06-30T02:04:54
2015-06-30T02:04:54
31,133,447
1
0
null
null
null
null
UTF-8
Java
false
false
1,858
java
/* class Time { private int hour; private int minute; private int second; public void Time( ) { } public void setTime(int hr , int min, int sec) { } public void printTime( ) { } public void tick( ) { // tick method defined } } The class Time defines a time object. It represents time (military time) in 2400 hours. 10 AM = 10 hours, 0 minutes and 0 seconds 4 PM = 16 hours, 0 minutes and 0 seconds 7:26PM = 19 hours, 26 minutes and 0 seconds Assume 0 represents 00 in this case. 1) Implement the constructor Time that will set the instance variables to zero. 2) Implement the setTime method to set the instance variables according to the values passed in. 3) Implement the printTime method to print time in hours:minutes:seconds e.g. 16:37:23 4) Implement the tick( ) method that will increment the time object by one second. Remember that 60 seconds = 1 minute, 60 minutes = 1 hour, and the max hours is 24. 5) Test the time object. Increment the Time object by 60 seconds and print out the time. Repeat question 5 for several different instances of the Time object. Each instance should have a different starting time. */ import java.util.*; public class TimeTest{ public static void main(String args[]) { Scanner scan = new Scanner (System.in); Time current = new Time(); System.out.println ("Please enter hour"); int hour=scan.nextInt(); System.out.println ("Please enter minute"); int minute=scan.nextInt(); System.out.println ("Please enter second"); int second=scan.nextInt(); current.setTime(hour,minute,second); System.out.println ("Please enter ticks"); int ticks = scan.nextInt(); while (ticks !=-1) { current.tick(ticks); System.out.println(current.printTime()); System.out.println("Please enter ticks"); ticks = scan.nextInt(); } } }
[ "xw900812@gmail.com" ]
xw900812@gmail.com
8434fd9b437ae8b129f68b05893c820216c69e6c
302eae5c4a1ba68d3434f03d9e5e2c4d4add8851
/app/src/main/java/com/ahuo/myapp2/net/retrfit/FastJsonResponseBodyConverter.java
e3870575046253a3e9dd69377dd6e4e66726e6ef
[]
no_license
wanhuo6/BaseApp
9a33e9abb801406590da344e6f4ba7fd103e72b9
f5c65756577d12b5de1ce93e7590ee7561016a61
refs/heads/master
2022-02-18T17:11:08.686690
2019-07-29T03:06:12
2019-07-29T03:06:12
104,046,372
1
0
null
null
null
null
UTF-8
Java
false
false
844
java
package com.ahuo.myapp2.net.retrfit; import android.util.Log; import com.alibaba.fastjson.JSON; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.ResponseBody; import okio.BufferedSource; import okio.Okio; import retrofit2.Converter; /** * Created on 17-8-1 * * @author liuhuijie */ public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { private final Type type; public FastJsonResponseBodyConverter(Type type){ this.type = type; } @Override public T convert(ResponseBody value) throws IOException { BufferedSource bufferedSource = Okio.buffer(value.source()); String tempStr = bufferedSource.readUtf8(); bufferedSource.close(); Log.e("response-----",tempStr); return JSON.parseObject(tempStr, type); } }
[ "857166619@qq.com" ]
857166619@qq.com
f3f57b9ab555d3679194f2eefea4e3a30494f40d
b84437b566fe4083183efca2bb58567bb7dea5ec
/src/pi_from_circle/Double_Thread.java
db006ccd7f8bce8e1e51f5f34ca953c7ab9a4750
[]
no_license
fmmmlee/Monte-Carlo-Practice
9435ac82f104ecd7b68519d2c48ba47c7ef7f3d2
4f14d218088a1e8360ed8cbfdf80df0684eb991e
refs/heads/master
2021-06-14T14:29:57.754596
2019-07-16T21:54:39
2019-07-16T21:54:39
187,552,908
0
0
null
2021-04-26T19:11:43
2019-05-20T02:13:28
Java
UTF-8
Java
false
false
896
java
package pi_from_circle; import java.util.concurrent.atomic.AtomicLong; /* * * Matthew Lee * Spring 2019 * Practicing Monte Carlo Simulation * * * * Using double to see how much faster it is * */ public class Double_Thread implements Runnable{ final long ITERATIONS; int in_circle = 0; AtomicLong output; Double_Thread(long iterations, AtomicLong shared_output) { ITERATIONS = iterations; output = shared_output; } public void run() { /* looping */ for(int i = 0; i <= ITERATIONS; i++) { in_circle++; /*Double x = ThreadLocalRandom.current().nextDouble(); Double y = ThreadLocalRandom.current().nextDouble(); if((x*x)+(y*y) <= 1) //checks if value is within the section, based on the formula for an ellipse in_circle++;*/ } /* adding final result of operation to the shared result */ output.getAndAdd(in_circle); } }
[ "30479162+fmmmlee@users.noreply.github.com" ]
30479162+fmmmlee@users.noreply.github.com
b29253d55354bee9c21322c7a1cac90dce259e15
66ac0f0289e1c2308463f0422a04e100a9a14d98
/server/modules/platform/api/src/org/labkey/api/query/QueryNestingOption.java
7a174f3c6aa7284a04a09a01787565855e8add39
[ "MIT" ]
permissive
praveenmunagapati/ms-registration-server
b4f860978f4b371cfb1fcb3c794d1315298638c2
49a851285dfbccbd0dc667f4a5ba1fcdbb2f0665
refs/heads/master
2022-04-19T00:15:59.055397
2020-04-14T06:12:38
2020-04-14T06:12:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,685
java
/* * Copyright (c) 2012-2019 LabKey Corporation * * 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.labkey.api.query; import org.labkey.api.data.*; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.Collections; import java.util.ArrayList; /** * Configuration for a NestedQueryView that understands which columns should be associated with the outer and inner * grids. Also tracks the URL at which a specific nested grid can be requested independently via AJAX. * * User: jeckels * Date: Apr 9, 2007 */ public class QueryNestingOption { private FieldKey _rowIdFieldKey; private FieldKey _aggregateRowIdFieldKey; private final String _ajaxNestedGridURL; private DataColumn _groupIdColumn; /** * @param aggregateRowIdColumn the column that's an FK to the table that should be shown in the parent grids * @param rowIdColumn the column that's the PK (the target of the FK from aggregateRowIdColumn) * @param ajaxNestedGridURL the URL to use to request the child grid via AJAX */ public QueryNestingOption(FieldKey aggregateRowIdColumn, FieldKey rowIdColumn, String ajaxNestedGridURL) { _aggregateRowIdFieldKey = aggregateRowIdColumn; _rowIdFieldKey = rowIdColumn; _ajaxNestedGridURL = ajaxNestedGridURL; } public void setupGroupIdColumn(List<DisplayColumn> allColumns, List<DisplayColumn> outerColumns, TableInfo parentTable) { if (_groupIdColumn != null) { return; } Map<FieldKey, ColumnInfo> infos = QueryService.get().getColumns(parentTable, Collections.singleton(_rowIdFieldKey)); assert infos.size() == 1; ColumnInfo info = infos.values().iterator().next(); _groupIdColumn = new DataColumn(info); _groupIdColumn.setVisible(false); allColumns.add(_groupIdColumn); outerColumns.add(_groupIdColumn); } public boolean isNested(List<DisplayColumn> columns) { boolean foundInner = false; boolean foundOuter = false; for (DisplayColumn column : columns) { if (isOuter(column)) { foundOuter = true; } else { foundInner = true; } } return foundOuter && foundInner; } private boolean isOuter(DisplayColumn column) { ColumnInfo colInfo = column.getColumnInfo(); return colInfo != null && isOuter(colInfo.getFieldKey()); } public boolean isOuter(FieldKey fieldKey) { return fieldKey.toString().toLowerCase().startsWith(_aggregateRowIdFieldKey.toString().toLowerCase() + "/"); } public FieldKey getRowIdFieldKey() { return _rowIdFieldKey; } public FieldKey getAggregateRowIdFieldKey() { return _aggregateRowIdFieldKey; } public NestableDataRegion createDataRegion(List<DisplayColumn> originalColumns, String dataRegionName, boolean expanded) { List<DisplayColumn> innerColumns = new ArrayList<>(); List<DisplayColumn> outerColumns = new ArrayList<>(); List<DisplayColumn> allColumns = new ArrayList<>(originalColumns); for (DisplayColumn column : originalColumns) { if (isOuter(column)) { setupGroupIdColumn(allColumns, outerColumns, column.getColumnInfo().getParentTable()); outerColumns.add(column); } else { innerColumns.add(column); } } NestableDataRegion dataRegion = new NestableDataRegion(allColumns, _groupIdColumn.getColumnInfo().getAlias(), _ajaxNestedGridURL); // Set the nested button bar as not visible so that we don't render a bunch of nested <form>s which mess up IE. dataRegion.setButtonBar(new ButtonBar()); dataRegion.setExpanded(expanded); dataRegion.setRecordSelectorValueColumns(_groupIdColumn.getColumnInfo().getAlias()); DataRegion nestedRgn = new DataRegion() { @Override protected void renderHeaderScript(RenderContext ctx, Writer out, Map<String, String> messages, boolean showRecordSelectors) { // Issue 11405: customized grid does not work MS2 query based views. // Nested DataRegions don't need to re-render the "new LABKEY.DataRegion(...)" script. } }; nestedRgn.setName(dataRegionName); ButtonBar bar = new ButtonBar(); bar.setVisible(false); nestedRgn.setShowFilterDescription(false); nestedRgn.setButtonBar(bar); nestedRgn.setDisplayColumns(innerColumns); dataRegion.setNestedRegion(nestedRgn); for (DisplayColumn column : outerColumns) { column.setCaption(column.getColumnInfo().getLabel()); } dataRegion.setDisplayColumns(outerColumns); return dataRegion; } }
[ "risto.autio@wunderdog.fi" ]
risto.autio@wunderdog.fi
4d6a2abdedb7787fd86403e2a1a79a4923aaf0d4
55ef186e267cd0ca525295d6c601044409bca843
/Json Builder/src/amdocs/iam/pd/webservices/referenceattributevalues/referenceattributevaluesoutput/impl/PopulatedFieldImpl.java
4987fbd6c6f94cb90601f933bdd4b7c31ef4a0a2
[]
no_license
gbarsky/OE
4771d868fb2239fafe058cac92af9bce7f734b5f
2e2a3e2143ab8ef5e1f09e1c4047793c6dbf7ffa
refs/heads/master
2020-05-29T22:35:00.138746
2013-04-04T02:49:51
2013-04-04T02:49:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,457
java
/* * XML Type: PopulatedField * Namespace: http://amdocs/iam/pd/webservices/referenceAttributeValues/ReferenceAttributeValuesOutput * Java type: amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.PopulatedField * * Automatically generated - do not modify. */ package amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.impl; /** * An XML PopulatedField(@http://amdocs/iam/pd/webservices/referenceAttributeValues/ReferenceAttributeValuesOutput). * * This is a complex type. */ public class PopulatedFieldImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.PopulatedField { public PopulatedFieldImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName ATTRIBUTECODE$0 = new javax.xml.namespace.QName("", "attributeCode"); private static final javax.xml.namespace.QName POPULATEDCOLUMN$2 = new javax.xml.namespace.QName("", "populatedColumn"); private static final javax.xml.namespace.QName POPULATEDFIELDCUSTOM$4 = new javax.xml.namespace.QName("", "PopulatedFieldCustom"); /** * Gets the "attributeCode" element */ public java.lang.String getAttributeCode() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(ATTRIBUTECODE$0, 0); if (target == null) { return null; } return target.getStringValue(); } } /** * Gets (as xml) the "attributeCode" element */ public org.apache.xmlbeans.XmlString xgetAttributeCode() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(ATTRIBUTECODE$0, 0); return target; } } /** * Sets the "attributeCode" element */ public void setAttributeCode(java.lang.String attributeCode) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(ATTRIBUTECODE$0, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(ATTRIBUTECODE$0); } target.setStringValue(attributeCode); } } /** * Sets (as xml) the "attributeCode" element */ public void xsetAttributeCode(org.apache.xmlbeans.XmlString attributeCode) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(ATTRIBUTECODE$0, 0); if (target == null) { target = (org.apache.xmlbeans.XmlString)get_store().add_element_user(ATTRIBUTECODE$0); } target.set(attributeCode); } } /** * Gets the "populatedColumn" element */ public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column getPopulatedColumn() { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().find_element_user(POPULATEDCOLUMN$2, 0); if (target == null) { return null; } return target; } } /** * Sets the "populatedColumn" element */ public void setPopulatedColumn(amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column populatedColumn) { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().find_element_user(POPULATEDCOLUMN$2, 0); if (target == null) { target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().add_element_user(POPULATEDCOLUMN$2); } target.set(populatedColumn); } } /** * Appends and returns a new empty "populatedColumn" element */ public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column addNewPopulatedColumn() { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutput.Column)get_store().add_element_user(POPULATEDCOLUMN$2); return target; } } /** * Gets the "PopulatedFieldCustom" element */ public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom getPopulatedFieldCustom() { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().find_element_user(POPULATEDFIELDCUSTOM$4, 0); if (target == null) { return null; } return target; } } /** * True if has "PopulatedFieldCustom" element */ public boolean isSetPopulatedFieldCustom() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(POPULATEDFIELDCUSTOM$4) != 0; } } /** * Sets the "PopulatedFieldCustom" element */ public void setPopulatedFieldCustom(amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom populatedFieldCustom) { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().find_element_user(POPULATEDFIELDCUSTOM$4, 0); if (target == null) { target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().add_element_user(POPULATEDFIELDCUSTOM$4); } target.set(populatedFieldCustom); } } /** * Appends and returns a new empty "PopulatedFieldCustom" element */ public amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom addNewPopulatedFieldCustom() { synchronized (monitor()) { check_orphaned(); amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom target = null; target = (amdocs.iam.pd.webservices.referenceattributevalues.referenceattributevaluesoutputimpl.PopulatedFieldCustom)get_store().add_element_user(POPULATEDFIELDCUSTOM$4); return target; } } /** * Unsets the "PopulatedFieldCustom" element */ public void unsetPopulatedFieldCustom() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(POPULATEDFIELDCUSTOM$4, 0); } } }
[ "georabarsky@gmail.com" ]
georabarsky@gmail.com
499288abbeb755e73e0034907fbcc0d4d2c569ec
39a4e939640d5249f253f8883ed39e1dd3254c94
/src/test/java/enteties/UserTest.java
a6cd1c3f6b5157a289274389f6a88853fc1d09a3
[]
no_license
Sendrikz/AdmissionCampaign
b4e759ff721bbe414a4e1771a73404080bf49c8d
3fb3e1d8421ee0f6f23d524e191abd98fda6a318
refs/heads/master
2020-03-23T22:59:06.092759
2018-09-09T12:14:01
2018-09-09T12:14:01
142,210,127
0
0
null
null
null
null
UTF-8
Java
false
false
4,090
java
package enteties; import model.builder.UserBuilder; import model.enteties_enum.Users; import model.enteties.User; import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.assertEquals; /** * @author Olha Yuryeva * @version 1.0 */ public class UserTest { private User user; @Before public void setUp() { user = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser(); } @Test public void setLastNameTest() { user.setLastName(Users.MUHAYLO.getLastName()); assertEquals(Users.MUHAYLO.getLastName(), user.getLastName()); } @Test public void setFirstNameTest() { user.setFirstName(Users.MUHAYLO.getFirstName()); assertEquals(Users.MUHAYLO.getFirstName(), user.getFirstName()); } @Test public void setPatronymicTest() { user.setPatronymic(Users.MUHAYLO.getPatronymic()); assertEquals(Users.MUHAYLO.getPatronymic(), user.getPatronymic()); } @Test public void setBirthdayTest() { user.setBirthday(Users.MUHAYLO.getBirthday()); assertEquals(Users.MUHAYLO.getBirthday(), user.getBirthday()); } @Test public void setCityTest() { user.setCity(Users.MUHAYLO.getCity()); assertEquals(Users.MUHAYLO.getCity(), user.getCity()); } @Test public void setRoleTest() { user.setRole(1); assertEquals(1, user.getRole()); } @Test public void setIdTest() { user.setId(1); assertEquals(1, user.getId()); } @Test public void setEmailTest() { user.setEmail(Users.MUHAYLO.getEmail()); assertEquals(Users.MUHAYLO.getEmail(), user.getEmail()); } @Test public void setPasswordTest() { user.setPassword(Users.MUHAYLO.getPassword()); assertEquals(Users.MUHAYLO.getPassword(), user.getPassword()); } @Test public void equalsTest() { User userCopy = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser(); assertEquals(true, user.equals(userCopy)); } @Test public void hashCodeTest() { User userCopy = new UserBuilder().setLastName(Users.KOSTYA.getLastName()).setFirstName(Users.KOSTYA.getFirstName()).setPatronymic(Users.KOSTYA.getPatronymic()).setBirthday(Users.KOSTYA.getBirthday()).setCity(Users.KOSTYA.getCity()).setEmail(Users.KOSTYA.getEmail()).setPassword(Users.KOSTYA.getPassword()).setRole(2).createUser(); assertEquals(user.hashCode(), userCopy.hashCode()); } @Test public void notEqualsTest() { User userCopy = new UserBuilder().setLastName(Users.ANDRIY.getLastName()).setFirstName(Users.ANDRIY.getFirstName()).setPatronymic(Users.ANDRIY.getPatronymic()).setBirthday(Users.ANDRIY.getBirthday()).setCity(Users.ANDRIY.getCity()).setEmail(Users.ANDRIY.getEmail()).setPassword(Users.ANDRIY.getPassword()).setRole(1).createUser(); assertEquals(false, user.equals(userCopy)); } @Test public void getString() { assertEquals("User{" + "id=" + user.getId() + ", lastName='" + user.getLastName() + '\'' + ", firstName='" + user.getFirstName() + '\'' + ", patronymic='" + user.getPatronymic() + '\'' + ", birthday=" + user.getBirthday() + ", city='" + user.getCity() + '\'' + ", email='" + user.getEmail() + '\'' + ", password='" + user.getPassword() + '\'' + ", role=" + user.getRole() + '}', user.toString()); } }
[ "yuryeva.olga99@gmail.com" ]
yuryeva.olga99@gmail.com
cc038c9d249e75bc672e8aac930b4e831d7d081c
21f0bf27aba68fc2db706b481b31c9728b5e96c4
/TPs/tp1/TP01Q15 - RECURSIVO - Is em Java/isR.java
a1fc617c1fcd67709570e355296e48281444a57a
[]
no_license
W-F-S/AED2
939e91f349b316b43e47945c65d4160202f15517
91b77399c2c6b5f189a8a2c0cbbd00b1eac2b0f8
refs/heads/master
2023-03-02T20:13:42.580689
2021-01-27T16:28:01
2021-01-27T16:28:01
323,716,396
0
0
null
null
null
null
UTF-8
Java
false
false
6,092
java
class isR{ /**setPalavra(String imput) * * Setar a string lida * * @param: String imput - string lida * @return: nda */ public static boolean fim(String palavra){ return ((palavra.length() == 3) && (palavra.charAt(0) == 'F') && (palavra.charAt(1) == 'I') && (palavra.charAt(2) == 'M'));//vendo a palavra especial } /** Metodo para verificar se um determinado char e' uma letra @param: char let: char a ser analizado @return: true: caso seja uma letra false: caso nao seja uma letra */ public static boolean letra(char let){ return (let >='A' && let <= 'Z' || let >='a' && let <= 'z');//vendo a palavra especial } /** Metodo para escrever na tela um Sim ou Nao @param: boolean resp; true: caso resp seja true false: caso nao seja uma letra @return: ... */ public static void simNao(boolean resp){ //apenas para mover os prints do main para um local mais isolado if (resp){ System.out.printf("SIM "); }else{ System.out.printf("NAO "); } } /** Metodo para ver se um certo char e um numero @param: char let: char a ser analizado @return: true: caso seja um numero false: caso nao seja um numero */ public static boolean num(char letra){ return( letra >= '0' && letra <= '9'); } /** Function to see if a char is a vowel // @param: char let: char a ser analizado @return: true: caso seja uma vogal false: caso nao seja uma vogal */ public static boolean vol(char let){ return (let == 'a' || let == 'A' || let == 'e' || let == 'E' || let == 'o' || let == 'O' || let == 'i' || let == 'I' || let == 'u' || let == 'U'); } /** metodo para ver se e uma consoante @param: char let: char a ser analizado @return: true: caso seja uma consoante false: caso nao seja uma consoante */ public static boolean con(char let){ return ( (!vol(let)) && ((let >= 'A' && let <= 'Z') || (let >= 'a' && let <= 'z')) ); } /** metodo para ver se e um numero real @param: string palavra: string a ser analisada int i : usado para a recursividade, sempre igual a zero int garantia : usado para garantir que so exista uma , ou . @return: true: caso seja um numero real false: caso nao seja um numero real */ public static boolean isReal(String palavra, int i, int garantia){ boolean resp = true; if( i < palavra.length()){ char L = palavra.charAt(i); if(!(num(L)) ){ if ( (L == '.' || L == ',') && garantia < 1 ){ garantia++; i++; resp = isReal(palavra, i, garantia); }else{ resp = false; } }else{ i++; resp = isReal(palavra, i, garantia); } } return resp; } /** metodo para ver se e um numero inteiro @param: string palavra: string a ser analisada int i : usado para a recursividade, sempre igual a zero @return: true: caso seja um numero inteiro false: caso nao seja um numero inteiro */ public static boolean isInt(String palavra, int i){//funcionando d boa boolean resp = true; if(i < palavra.length()){ if( !num(palavra.charAt(i)) ){ //MyIO.println("\nNao e int == "+ palavra.charAt(i)); resp = false; } else { resp = isInt(palavra, i+1); } } return (resp); } /** metodo para ver se e uma consoante @param: string palavra: string a ser analisada int i : usado para a recursividade, sempre igual a zero @return: true: caso seja uma consoante false: caso nao seja uma consoante */ public static boolean isConsoantes(String palavra, int i){//funcionando de boa boolean resp = true; if(i < palavra.length()){ if( !con(palavra.charAt(i)) ){ //MyIO.println("\nNao e consoante == "+ palavra.charAt(i)); resp = false; } else { resp = isConsoantes(palavra, i+1); } } return (resp ); } /** metodo para ver se e uma vogal @param: string palavra: string a ser analisada int i : usado para a recursividade, sempre igual a zero @return: true: caso seja uma vogal false: caso nao seja uma vogal */ public static boolean isVogais(String palavra, int i){//ver se vogao boolean resp = true; if(i < palavra.length()){ if( !vol(palavra.charAt(i)) ){//ver se e' vogal maiuscula ou minuscula. // MyIO.println("\nNao e vogal == "+ palavra.charAt(i)); resp = false; } else { resp = isVogais(palavra, i+1); } } return resp;//retorna false se nao for vogal } public static void main(String[] args){ String palavra = MyIO.readLine(); while(!fim(palavra)){ simNao(isVogais(palavra, 0)); simNao(isConsoantes(palavra, 0)); simNao(isInt(palavra, 0 )); simNao(isReal(palavra, 0 , 0)); MyIO.print("\n"); palavra = MyIO.readLine();; } } }
[ "walkerf082@gmail.com" ]
walkerf082@gmail.com
e5e7082ced4fe9794edcbbaf3d7c46989c32e2b1
b9469e1bde90abece9648eb4f8f343210e0b4a9d
/src/main/java/com/isabo/battletank/repository/UserRepository.java
fc68e4effe57f8794ddba04318896df3a6cb86c9
[]
no_license
MatthieuBlm/TankDeluxe3000
d52aabdf62b901d2eec5df7a95550dd45c7b5557
0a9391b7ec6846fc58648d11ec6dca425d961db6
refs/heads/master
2020-07-31T08:15:53.718888
2019-09-23T17:27:28
2019-09-23T17:27:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
259
java
package com.isabo.battletank.repository; import org.springframework.data.repository.CrudRepository; import com.isabo.battletank.entity.User; public interface UserRepository extends CrudRepository<User, Long> { public User findByLogin(String username); }
[ "lucas.moura-de-oliveira@isabo.ai" ]
lucas.moura-de-oliveira@isabo.ai
d0a070c6b232374819f2aa583342a2a5b9bc9d1f
6d60a8adbfdc498a28f3e3fef70366581aa0c5fd
/codebase/selected/1047866.java
cec0c8ad33c8fe9bf71b0d93b3b6dce92e112741
[]
no_license
rayhan-ferdous/code2vec
14268adaf9022d140a47a88129634398cd23cf8f
c8ca68a7a1053d0d09087b14d4c79a189ac0cf00
refs/heads/master
2022-03-09T08:40:18.035781
2022-02-27T23:57:44
2022-02-27T23:57:44
140,347,552
0
1
null
null
null
null
UTF-8
Java
false
false
10,870
java
package org.springframework.richclient.table; import java.awt.EventQueue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import javax.swing.SwingUtilities; import javax.swing.event.TableModelEvent; import javax.swing.table.TableModel; import org.springframework.core.style.StylerUtils; import org.springframework.util.Assert; import org.springframework.util.comparator.NullSafeComparator; /** * A sorter for TableModels. The sorter has a model (conforming to TableModel) * and itself implements TableModel. TableSorter does not store or copy the * model in the TableModel, instead it maintains an array of integers which it * keeps the same size as the number of rows in its model. When the model * changes it notifies the sorter that something has changed eg. "rowsAdded" so * that its internal array of integers can be reallocated. As requests are made * of the sorter (like getValueAt(row, col) it redirects them to its model via * the mapping array. That way the TableSorter appears to hold another copy of * the table with the rows in a different order. The sorting algorthm used is * stable which means that it does not move around rows when its comparison * function returns 0 to denote that they are equivalent. */ public class ShuttleSortableTableModel extends AbstractTableModelFilter implements SortableTableModel { private static final Comparator OBJECT_COMPARATOR = new NullSafeComparator(ToStringComparator.INSTANCE, true); private static final Comparator COMPARABLE_COMPARATOR = NullSafeComparator.NULLS_LOW; private Comparator[] columnComparators; private List columnsToSort = new ArrayList(4); private int[] indexes; private int compares; private boolean autoSortEnabled = true; private Runnable notifyTableRunnable = new Runnable() { public void run() { fireTableDataChanged(); } }; public ShuttleSortableTableModel(TableModel model) { super(model); allocateIndexes(); resetComparators(); } private void allocateIndexes() { int rowCount = filteredModel.getRowCount(); indexes = new int[rowCount]; for (int row = 0; row < rowCount; row++) { indexes[row] = row; } } public void resetComparators() { resetComparators(Collections.EMPTY_MAP); } /** * Reset the <code>columnComparartos</code>.<br> * Useful when the columns of the model were changed, and by consequence * their comparators. * @param comparators - map with comparators where the key is the column of * the comparator. */ public void resetComparators(Map comparators) { int colCount = filteredModel.getColumnCount(); columnComparators = new Comparator[colCount]; Comparator newComparator; Class clazz; for (int i = 0; i < columnComparators.length; i++) { newComparator = (Comparator) comparators.get(Integer.valueOf(i)); if (newComparator != null) setComparator(i, newComparator); else { clazz = filteredModel.getColumnClass(i); if (clazz == Object.class || !Comparable.class.isAssignableFrom(clazz)) columnComparators[i] = OBJECT_COMPARATOR; } } } public boolean isCellEditable(int row, int column) { return filteredModel.isCellEditable(indexes[row], column); } public boolean isAutoSortEnabled() { return autoSortEnabled; } public void setAutoSortEnabled(boolean autoSortEnabled) { this.autoSortEnabled = autoSortEnabled; } public Comparator getComparator(int columnIndex) { return this.columnComparators[columnIndex]; } public void setComparator(int columnIndex, Comparator comparator) { Assert.notNull(comparator); this.columnComparators[columnIndex] = comparator; } public Object getValueAt(int row, int column) { return filteredModel.getValueAt(indexes[row], column); } public void setValueAt(Object value, int row, int column) { filteredModel.setValueAt(value, indexes[row], column); } public void sortByColumn(ColumnToSort columnToSort) { columnsToSort.clear(); columnsToSort.add(columnToSort); sort(); SwingUtilities.invokeLater(notifyTableRunnable); } public void sortByColumns(ColumnToSort[] columnsToSort) { this.columnsToSort = Arrays.asList(columnsToSort); sort(); notifyTableChanged(); } public int[] sortByColumns(ColumnToSort[] columnsToSort, int[] preSortSelectedRows) { int[] modelIndexes = new int[preSortSelectedRows.length]; if (logger.isDebugEnabled()) { logger.debug("Selected row indexes before sort" + StylerUtils.style(preSortSelectedRows)); } for (int i = 0; i < preSortSelectedRows.length; i++) { modelIndexes[i] = convertSortedIndexToDataIndex(preSortSelectedRows[i]); } this.columnsToSort = Arrays.asList(columnsToSort); sort(); int[] postSortSelectedRows = new int[modelIndexes.length]; for (int i = 0; i < modelIndexes.length; i++) { postSortSelectedRows[i] = convertModelToRowIndex(modelIndexes[i]); } if (logger.isDebugEnabled()) { logger.debug("Selected row indexes after sort" + StylerUtils.style(postSortSelectedRows)); } notifyTableChanged(); return postSortSelectedRows; } protected void notifyTableChanged() { if (!EventQueue.isDispatchThread()) { SwingUtilities.invokeLater(notifyTableRunnable); } else { notifyTableRunnable.run(); } } public int convertSortedIndexToDataIndex(int index) { return indexes[index]; } public int[] convertSortedIndexesToDataIndexes(int[] indexes) { int[] converted = new int[indexes.length]; for (int i = 0; i < indexes.length; i++) { converted[i] = convertSortedIndexToDataIndex(indexes[i]); } return converted; } public int convertModelToRowIndex(int index) { for (int i = 0; i < indexes.length; i++) { if (index == indexes[i]) { return i; } } return 0; } public int[] convertDataIndexesToSortedIndexes(int[] indexes) { int[] converted = new int[indexes.length]; for (int i = 0; i < indexes.length; i++) { converted[i] = convertModelToRowIndex(indexes[i]); } return converted; } private void sort() { if (columnsToSort.size() > 0) { checkModel(); compares = 0; doShuttleSort((int[]) indexes.clone(), indexes, 0, indexes.length); } } private void checkModel() { if (indexes.length != filteredModel.getRowCount()) { throw new IllegalStateException("Sorter not informed of a change in model."); } } private void doShuttleSort(int from[], int to[], int low, int high) { if (high - low < 2) { return; } int middle = (low + high) / 2; doShuttleSort(to, from, low, middle); doShuttleSort(to, from, middle, high); int p = low; int q = middle; if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) { for (int i = low; i < high; i++) { to[i] = from[i]; } return; } for (int i = low; i < high; i++) { if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) { to[i] = from[p++]; } else { to[i] = from[q++]; } } } public int compare(int row1, int row2) { compares++; for (int level = 0; level < columnsToSort.size(); level++) { ColumnToSort column = (ColumnToSort) columnsToSort.get(level); int result = compareRowsByColumn(row1, row2, column.getColumnIndex()); if (result != 0) { return column.getSortOrder() == SortOrder.ASCENDING ? result : -result; } } return 0; } private int compareRowsByColumn(int row1, int row2, int column) { Object o1 = filteredModel.getValueAt(row1, column); Object o2 = filteredModel.getValueAt(row2, column); Comparator comparator = columnComparators[column]; if (comparator != null) { return comparator.compare(o1, o2); } return COMPARABLE_COMPARATOR.compare(o1, o2); } public void tableChanged(final TableModelEvent e) { if (e.getType() == TableModelEvent.INSERT) { if (autoSortEnabled) { reallocateIndexesOnInsert(e.getFirstRow(), e.getLastRow()); sort(); final int[] insertedRows = new int[e.getLastRow() - e.getFirstRow() + 1]; int row = e.getFirstRow(); for (int i = 0; i < insertedRows.length; i++) { insertedRows[i] = convertModelToRowIndex(row++); } for (int i = 0; i < insertedRows.length; i++) { fireTableRowsInserted(insertedRows[i], insertedRows[i]); } } else { reallocateIndexesOnInsert(e.getFirstRow(), e.getLastRow()); super.tableChanged(e); } } else if (e.getType() == TableModelEvent.DELETE) { final int[] deletedRows = new int[e.getLastRow() - e.getFirstRow() + 1]; int row = e.getFirstRow(); for (int i = 0; i < deletedRows.length; i++) { deletedRows[i] = convertModelToRowIndex(row); row++; } allocateIndexes(); for (int i = 0; i < deletedRows.length; i++) { fireTableRowsDeleted(deletedRows[i], deletedRows[i]); } sort(); } else if (e.getType() == TableModelEvent.UPDATE) { allocateIndexes(); sort(); fireTableDataChanged(); } else { logger.warn("Doing an unknown table change type: " + e.getType()); allocateIndexes(); sort(); super.tableChanged(e); } } private void reallocateIndexesOnInsert(int firstRow, int lastRow) { int rowCount = filteredModel.getRowCount(); int[] newIndexes = new int[rowCount]; for (int row = 0; row < indexes.length; row++) { newIndexes[row] = indexes[row]; } for (int row = firstRow; row <= lastRow; row++) { newIndexes[row] = row; } indexes = newIndexes; } }
[ "aaponcseku@gmail.com" ]
aaponcseku@gmail.com
2b3e53e5ae6cfec426f89092d975db0c12a64ca3
40507d7cead34ca96d808cca0ec4b39685680c9f
/src/main/java/uk/co/businessitsolution/ui/crud/CrudEntityPresenter.java
1fc8e3e3bf8089cc9cf3a584b6fe76718e4d4e39
[ "Unlicense" ]
permissive
bits-ltd/RecruitmentSpring
7addd6f4b947e68349f0741c2d73644152479e7d
f63f508a4ea20257391cb48fd35f62f320219ab7
refs/heads/master
2023-01-09T16:40:30.345416
2020-02-07T18:02:07
2020-02-07T18:02:07
229,152,264
0
0
Unlicense
2023-01-07T14:35:56
2019-12-19T23:01:20
Java
UTF-8
Java
false
false
2,755
java
package uk.co.businessitsolution.ui.crud; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.OptimisticLockingFailureException; import uk.co.businessitsolution.app.HasLogger; import uk.co.businessitsolution.app.security.CurrentUser; import uk.co.businessitsolution.backend.entity.AbstractEntity; import uk.co.businessitsolution.backend.service.CrudService; import uk.co.businessitsolution.backend.service.UserFriendlyDataException; import uk.co.businessitsolution.ui.HasNotifications; import uk.co.businessitsolution.ui.utils.messages.CrudErrorMessage; import javax.persistence.EntityNotFoundException; import javax.validation.ConstraintViolationException; import java.util.function.Consumer; public class CrudEntityPresenter<E extends AbstractEntity> implements HasLogger { private final CrudService<E> crudService; private final CurrentUser currentUser; private final HasNotifications view; public CrudEntityPresenter(CrudService<E> crudService, CurrentUser currentUser, HasNotifications view) { this.crudService = crudService; this.currentUser = currentUser; this.view = view; } public void delete(E entity, Consumer<E> onSuccess, Consumer<E> onFail) { if (executeOperation(() -> crudService.delete(currentUser.getUser(), entity))) { onSuccess.accept(entity); } else { onFail.accept(entity); } } public void save(E entity, Consumer<E> onSuccess, Consumer<E> onFail) { if (executeOperation(() -> saveEntity(entity))) { onSuccess.accept(entity); } else { onFail.accept(entity); } } private boolean executeOperation(Runnable operation) { try { operation.run(); return true; } catch (UserFriendlyDataException e) { // Commit failed because of application-level data constraints consumeError(e, e.getMessage(), true); } catch (DataIntegrityViolationException e) { // Commit failed because of validation errors consumeError( e, CrudErrorMessage.OPERATION_PREVENTED_BY_REFERENCES, true); } catch (OptimisticLockingFailureException e) { consumeError(e, CrudErrorMessage.CONCURRENT_UPDATE, true); } catch (EntityNotFoundException e) { consumeError(e, CrudErrorMessage.ENTITY_NOT_FOUND, false); } catch (ConstraintViolationException e) { consumeError(e, CrudErrorMessage.REQUIRED_FIELDS_MISSING, false); } return false; } private void consumeError(Exception e, String message, boolean isPersistent) { getLogger().debug(message, e); view.showNotification(message, isPersistent); } private void saveEntity(E entity) { crudService.save(currentUser.getUser(), entity); } public boolean loadEntity(Long id, Consumer<E> onSuccess) { return executeOperation(() -> onSuccess.accept(crudService.load(id))); } }
[ "ryan.alton@businessitsolution.co.uk" ]
ryan.alton@businessitsolution.co.uk
a2d6a818acc40e90746c845725a5d982d205af72
ce0478e1c168424e006c31b502c130b69d447d4a
/RunnerApp/src/org/dicadeveloper/runnerapp/io/gdata/maps/XmlMapsGDataParser.java
9cb4c611e09f0159791aef70cb1e4411545b8fe2
[]
no_license
birkhimerjr/RunnerApp
2deeb3ec98d8281e0ef3b03773b170bce99966ae
f340ef1fb56844c1178aefd9fea3664bb8a52e5a
refs/heads/master
2021-05-05T00:37:35.053868
2015-04-26T07:52:49
2015-04-26T07:52:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,056
java
// Copyright 2009 Google Inc. All Rights Reserved. package org.dicadeveloper.runnerapp.io.gdata.maps; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.Feed; import com.google.wireless.gdata.data.XmlUtils; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.xml.XmlGDataParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Parser for XML gdata maps data. */ class XmlMapsGDataParser extends XmlGDataParser { public XmlMapsGDataParser(InputStream is, XmlPullParser xpp) throws ParseException { super(is, xpp); } @Override protected Feed createFeed() { return new Feed(); } @Override protected Entry createEntry() { return new MapFeatureEntry(); } @Override protected void handleExtraElementInFeed(Feed feed) { // Do nothing } @Override protected void handleExtraLinkInEntry( String rel, String type, String href, Entry entry) throws XmlPullParserException, IOException { if (!(entry instanceof MapFeatureEntry)) { throw new IllegalArgumentException("Expected MapFeatureEntry!"); } if (rel.endsWith("#view")) { return; } super.handleExtraLinkInEntry(rel, type, href, entry); } /** * Parses the current entry in the XML document. Assumes that the parser is * currently pointing just after an &lt;entry&gt;. * * @param plainEntry The entry that will be filled. * @throws XmlPullParserException Thrown if the XML cannot be parsed. * @throws IOException Thrown if the underlying inputstream cannot be read. */ @Override protected void handleEntry(Entry plainEntry) throws XmlPullParserException, IOException, ParseException { XmlPullParser parser = getParser(); if (!(plainEntry instanceof MapFeatureEntry)) { throw new IllegalArgumentException("Expected MapFeatureEntry!"); } MapFeatureEntry entry = (MapFeatureEntry) plainEntry; int eventType = parser.getEventType(); entry.setPrivacy("public"); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); if ("entry".equals(name)) { // stop parsing here. return; } else if ("id".equals(name)) { entry.setId(XmlUtils.extractChildText(parser)); } else if ("title".equals(name)) { entry.setTitle(XmlUtils.extractChildText(parser)); } else if ("link".equals(name)) { String rel = parser.getAttributeValue(null /* ns */, "rel"); String type = parser.getAttributeValue(null /* ns */, "type"); String href = parser.getAttributeValue(null /* ns */, "href"); if ("edit".equals(rel)) { entry.setEditUri(href); } else if ("alternate".equals(rel) && "text/html".equals(type)) { entry.setHtmlUri(href); } else { handleExtraLinkInEntry(rel, type, href, entry); } } else if ("summary".equals(name)) { entry.setSummary(XmlUtils.extractChildText(parser)); } else if ("content".equals(name)) { StringBuilder contentBuilder = new StringBuilder(); int parentDepth = parser.getDepth(); while (parser.getEventType() != XmlPullParser.END_DOCUMENT) { int etype = parser.next(); switch (etype) { case XmlPullParser.START_TAG: contentBuilder.append('<'); contentBuilder.append(parser.getName()); contentBuilder.append('>'); break; case XmlPullParser.TEXT: contentBuilder.append("<![CDATA["); contentBuilder.append(parser.getText()); contentBuilder.append("]]>"); break; case XmlPullParser.END_TAG: if (parser.getDepth() > parentDepth) { contentBuilder.append("</"); contentBuilder.append(parser.getName()); contentBuilder.append('>'); } break; } if (etype == XmlPullParser.END_TAG && parser.getDepth() == parentDepth) { break; } } entry.setContent(contentBuilder.toString()); } else if ("category".equals(name)) { String category = parser.getAttributeValue(null /* ns */, "term"); if (category != null && category.length() > 0) { entry.setCategory(category); } String categoryScheme = parser.getAttributeValue(null /* ns */, "scheme"); if (categoryScheme != null && category.length() > 0) { entry.setCategoryScheme(categoryScheme); } } else if ("published".equals(name)) { entry.setPublicationDate(XmlUtils.extractChildText(parser)); } else if ("updated".equals(name)) { entry.setUpdateDate(XmlUtils.extractChildText(parser)); } else if ("deleted".equals(name)) { entry.setDeleted(true); } else if ("draft".equals(name)) { String draft = XmlUtils.extractChildText(parser); entry.setPrivacy("yes".equals(draft) ? "unlisted" : "public"); } else if ("customProperty".equals(name)) { String attrName = parser.getAttributeValue(null, "name"); String attrValue = XmlUtils.extractChildText(parser); entry.setAttribute(attrName, attrValue); } else if ("deleted".equals(name)) { entry.setDeleted(true); } else { handleExtraElementInEntry(entry); } break; default: break; } eventType = parser.next(); } } }
[ "vyaslav@gmail.com" ]
vyaslav@gmail.com
631f611e99fbc6a1771e2c972f4d5d8306a56e5c
461619a84c6617ceaf2b7913ef58c99ff32c0fb5
/android/SimpleCursorAdapter/setViewBinder/src/SimpleCursorAdapter/SimpleCursorAdapter_/src/com/bgstation0/android/sample/simplecursoradapter_/MainActivity.java
13a80ec04ffe6a9e578d869018cdfa85117906ed
[ "MIT" ]
permissive
bg1bgst333/Sample
cf066e48facac8ecd203c56665251fa1aa103844
298a4253dd8123b29bc90a3569f2117d7f6858f8
refs/heads/master
2023-09-02T00:46:31.139148
2023-09-01T02:41:42
2023-09-01T02:41:42
27,908,184
9
10
MIT
2023-09-06T20:49:55
2014-12-12T06:22:49
Java
SHIFT_JIS
Java
false
false
4,971
java
package com.bgstation0.android.sample.simplecursoradapter_; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class MainActivity extends Activity { // メンバフィールドの定義. public CustomDBHelper mHlpr = null; // CustomDBHelperオブジェクトmHlprをnullにしておく. public SQLiteDatabase mSqlite = null; // SQLiteDatabaseオブジェクトmSqliteをnullにしておく. public SimpleCursorAdapter mAdapter = null; // SimpleCursorAdapterオブジェクトmAdapterをnullにしておく. public Cursor mCursor = null; // CursorオブジェクトmCursorをnullにしておく. // Activityが生成されたとき. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ListViewの取得. ListView listView1 = (ListView)findViewById(R.id.listview1); // listView1を取得. // DBへの行の挿入. mCursor = null; // mCursorにnullをセット. try{ if (mHlpr == null){ // mHlprがnullなら. mHlpr = new CustomDBHelper(getApplicationContext()); // mHlpr作成. if (mSqlite == null){ // mSqliteがnullなら. mSqlite = mHlpr.getWritableDatabase(); // mSqlite取得. if (mSqlite != null){ // mSqliteが取得できれば. // 挿入. ContentValues values1 = new ContentValues(); // values1の生成. values1.put("name", "Taro"); // キーが"name", 値が"Taro". values1.put("age", "20"); // キーが"age", 値が"20". long i = mSqlite.insert("custom", null, values1); // 挿入. ContentValues values2 = new ContentValues(); // values2の生成. values2.put("name", "Jiro"); // キーが"name", 値が"Jiro". values2.put("age", "18"); // キーが"age", 値が"18". long i2 = mSqlite.insert("custom", null, values2); // 挿入. ContentValues values3 = new ContentValues(); // values3の生成. values3.put("name", "Saburo"); // キーが"name", 値が"Saburo". values3.put("age", "16"); // キーが"age", 値が"16". long i3 = mSqlite.insert("custom", null, values3); // 挿入. // 選択. String[] projection = new String[]{ "_id", // ID. "name", // 名前. "age" // 年齢. }; mCursor = mSqlite.query("custom", projection, null, null, null, null, "age desc"); // クエリ結果をmCursorに格納. mAdapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[]{"name", "age"}, new int[]{R.id.list_item_name, R.id.list_item_age}, 0); // SimpleCursorAdapterオブジェクトmAdapterの生成. mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { // TODO Auto-generated method stub // カラムが1番目かどうか.(_idが0番目.) if (columnIndex == 1){ // 1番目.(name) int color = getResources().getColor(android.R.color.holo_red_light); // 赤のcolor取得. ((TextView)view).setTextColor(color); //viewにセット. } else{ // 1番目以外.(age) int color = getResources().getColor(android.R.color.holo_blue_light); // 青のcolor取得. ((TextView)view).setTextColor(color); //viewにセット. } return false; } }); listView1.setAdapter(mAdapter); // listView1にmAdapterをセット. } } } } catch (Exception ex){ // 例外. Log.e("SimpleCursorAdapter_", ex.toString()); // ex.toStringをLogに出力. } finally{ // 必須処理 if (mSqlite != null){ // mSqliteがあれば. mSqlite.close(); // 閉じる. mSqlite = null; // nullをセット. } if (mHlpr != null){ // mHlprがあれば. mHlpr.close(); // 閉じる. mHlpr = null; // nullをセット. } } } // Activityが破棄されたとき. protected void onDestroy() { // onDestroyの定義 // 親クラスの処理 super.onDestroy(); // super.onDestroyで親クラスの既定処理. // カーソルを閉じる. if (mCursor != null){ // mCursorがあれば. mCursor.close(); // 閉じる. mCursor = null; // nullをセット. } } }
[ "bg1bgst333@gmail.com" ]
bg1bgst333@gmail.com
abfc5306225ff9e1140f22b2b53698c01254bac9
4bb83687710716d91b5da55054c04f430474ee52
/dsrc/sku.0/sys.server/compiled/game/script/conversation/junk_reggi_nym.java
e33ca3f5284b545a8c9502cd017a5dab4403c5f5
[]
no_license
geralex/SWG-NGE
0846566a44f4460c32d38078e0a1eb115a9b08b0
fa8ae0017f996e400fccc5ba3763e5bb1c8cdd1c
refs/heads/master
2020-04-06T11:18:36.110302
2018-03-19T15:42:32
2018-03-19T15:42:32
157,411,938
1
0
null
2018-11-13T16:35:01
2018-11-13T16:35:01
null
UTF-8
Java
false
false
9,234
java
package script.conversation; import script.*; import script.base_class.*; import script.combat_engine.*; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import script.base_script; import script.library.ai_lib; import script.library.chat; import script.library.smuggler; import script.library.utils; public class junk_reggi_nym extends script.base_script { public junk_reggi_nym() { } public static String c_stringFile = "conversation/junk_reggi_nym"; public boolean junk_reggi_nym_condition__defaultCondition(obj_id player, obj_id npc) throws InterruptedException { return true; } public boolean junk_reggi_nym_condition_check_inv(obj_id player, obj_id npc) throws InterruptedException { return smuggler.checkInventory(player, npc); } public void junk_reggi_nym_action_start_dealing(obj_id player, obj_id npc) throws InterruptedException { dictionary params = new dictionary(); params.put("player", player); messageTo(npc, "startDealing", params, 1.0f, false); } public void junk_reggi_nym_action_face_to(obj_id player, obj_id npc) throws InterruptedException { faceTo(npc, player); } public int junk_reggi_nym_handleBranch1(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_ef8c7236")) { if (junk_reggi_nym_condition__defaultCondition(player, npc)) { string_id message = new string_id(c_stringFile, "s_14e5bdc0"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (junk_reggi_nym_condition_check_inv(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (junk_reggi_nym_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_b8e27f3c"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_2e005077"); } utils.setScriptVar(player, "conversation.junk_reggi_nym.branchId", 2); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_53d778d8")) { if (junk_reggi_nym_condition__defaultCondition(player, npc)) { string_id message = new string_id(c_stringFile, "s_f25d9c2"); utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int junk_reggi_nym_handleBranch2(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_b8e27f3c")) { if (junk_reggi_nym_condition__defaultCondition(player, npc)) { junk_reggi_nym_action_start_dealing(player, npc); string_id message = new string_id(c_stringFile, "s_5c453a2f"); utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } if (response.equals("s_2e005077")) { if (junk_reggi_nym_condition__defaultCondition(player, npc)) { string_id message = new string_id(c_stringFile, "s_233f3214"); utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int OnInitialize(obj_id self) throws InterruptedException { if ((!isMob(self)) || (isPlayer(self))) { detachScript(self, "conversation.junk_reggi_nym"); } setCondition(self, CONDITION_CONVERSABLE); return SCRIPT_CONTINUE; } public int OnAttach(obj_id self) throws InterruptedException { setCondition(self, CONDITION_CONVERSABLE); return SCRIPT_CONTINUE; } public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info menuInfo) throws InterruptedException { int menu = menuInfo.addRootMenu(menu_info_types.CONVERSE_START, null); menu_info_data menuInfoData = menuInfo.getMenuItemById(menu); menuInfoData.setServerNotify(false); setCondition(self, CONDITION_CONVERSABLE); return SCRIPT_CONTINUE; } public int OnIncapacitated(obj_id self, obj_id killer) throws InterruptedException { clearCondition(self, CONDITION_CONVERSABLE); detachScript(self, "conversation.junk_reggi_nym"); return SCRIPT_CONTINUE; } public boolean npcStartConversation(obj_id player, obj_id npc, String convoName, string_id greetingId, prose_package greetingProse, string_id[] responses) throws InterruptedException { Object[] objects = new Object[responses.length]; System.arraycopy(responses, 0, objects, 0, responses.length); return npcStartConversation(player, npc, convoName, greetingId, greetingProse, objects); } public int OnStartNpcConversation(obj_id self, obj_id player) throws InterruptedException { obj_id npc = self; if (ai_lib.isInCombat(npc) || ai_lib.isInCombat(player)) { return SCRIPT_OVERRIDE; } if (junk_reggi_nym_condition__defaultCondition(player, npc)) { junk_reggi_nym_action_face_to(player, npc); string_id message = new string_id(c_stringFile, "s_60d2f507"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (junk_reggi_nym_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (junk_reggi_nym_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_ef8c7236"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_53d778d8"); } utils.setScriptVar(player, "conversation.junk_reggi_nym.branchId", 1); npcStartConversation(player, npc, "junk_reggi_nym", message, responses); } else { chat.chat(npc, player, message); } return SCRIPT_CONTINUE; } chat.chat(npc, "Error: All conditions for OnStartNpcConversation were false."); return SCRIPT_CONTINUE; } public int OnNpcConversationResponse(obj_id self, String conversationId, obj_id player, string_id response) throws InterruptedException { if (!conversationId.equals("junk_reggi_nym")) { return SCRIPT_CONTINUE; } obj_id npc = self; int branchId = utils.getIntScriptVar(player, "conversation.junk_reggi_nym.branchId"); if (branchId == 1 && junk_reggi_nym_handleBranch1(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 2 && junk_reggi_nym_handleBranch2(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } chat.chat(npc, "Error: Fell through all branches and responses for OnNpcConversationResponse."); utils.removeScriptVar(player, "conversation.junk_reggi_nym.branchId"); return SCRIPT_CONTINUE; } }
[ "tmoflash@gmail.com" ]
tmoflash@gmail.com
4816333ce93ba597566f6d85e5553d3a0bae7e05
75de3b3c11eca42afe8a127adc0196cdb5936572
/src/learning/java/source/concurrent/util/CountDownLatchTest.java
e640b6f07116e7cbcd7617441a9264af6f26ff96
[]
no_license
zhcwang/learning_javasrc
3417ee8815cab25feeed4228573006775c30c637
22372dbc7cfb504415d313471e8982d96baac8b7
refs/heads/master
2020-06-09T01:00:14.288821
2019-07-08T12:49:36
2019-07-08T12:49:36
193,338,843
0
0
null
2019-07-08T12:49:38
2019-06-23T11:16:31
Java
UTF-8
Java
false
false
1,809
java
package learning.java.source.concurrent.util; import java.util.Random; import java.util.concurrent.*; /** * CountDownLatch主要是用来并行计算,当所有线程都计算完后,主线程再进行其他操作 * 以下测试模仿工作中compare并发从源和目标读数据的相关功能代码 * 在CountDownLatch的源码示例中,还可以通过两个latch让任务同时开始,同时结束 * CountDownLatch是AQS的一个基本应用,原理如下: * 初始一个状态 = CountDownLatch定义的线程数 * countdown()方法就是CAS state - 1 操作 * await()方法就是自旋阻塞等待state = 0 */ public class CountDownLatchTest { static class WaitForTheLast implements Runnable{ private CountDownLatch latch; public WaitForTheLast(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { // 随机休眠0-5秒 int time = new Random().nextInt(5000); System.out.println("休眠 " + time + "秒"); Thread.sleep(time); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(10); long start = System.currentTimeMillis(); Executor e = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { e.execute(new WaitForTheLast(latch)); } latch.await(); long duration = System.currentTimeMillis() - start; // 可以看到duration一定比所有执行线程的最长执行时间略大 System.out.println(duration); } }
[ "zhengcaowang@163.com" ]
zhengcaowang@163.com
3f38659469b5daa46943860a76de9a7a6f30cb5b
74837bd6f03a44bdae0ca7a3cb9ced88ff4ced51
/src/com/devol/client/view/uimantprestamo/UIMantPrestamo.java
ad1e5b25ac0b5c9e2a410570454c601acab9b7ed
[]
no_license
jofrantoba/devol
493f1d5db4c929af420a3151d4e554c97d22f69a
17b55450e4242273ef94a40fe8d7246b56770047
refs/heads/master
2020-04-15T02:35:51.815640
2019-11-25T01:32:51
2019-11-25T01:32:51
40,623,734
2
1
null
null
null
null
UTF-8
Java
false
false
16,378
java
package com.devol.client.view.uimantprestamo; import java.math.BigDecimal; import com.devol.client.beanproxy.ClienteProxy; import com.devol.client.beanproxy.PrestamoProxy; import com.devol.client.beanproxy.UsuarioProxy; import com.devol.client.model.ContentForm; import com.devol.client.model.HeaderPanelM; import com.devol.client.model.TextBoxCalendar; import com.devol.client.resource.MyResource; import com.devol.client.util.Notification; import com.devol.i18n.DevolConstants; import com.devol.shared.FieldVerifier; import com.google.gwt.core.shared.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.TouchEndEvent; import com.google.gwt.event.dom.client.TouchEndHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.googlecode.mgwt.ui.client.MGWT; import com.googlecode.mgwt.ui.client.MGWTSettings; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.PushButton; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; //import com.googlecode.mgwt.ui.client.widget.panel.scroll.ScrollPanel; public class UIMantPrestamo extends Composite implements InterUIMantPrestamo, TouchEndHandler,KeyUpHandler,BlurHandler,ClickHandler { private DevolConstants constants = GWT.create(DevolConstants.class); private VerticalPanel main; private HeaderPanelM header; private Label lblCenter; private PushButton btnBack; //private FlowPanel container; public ScrollPanel scrollPanel; private FlowPanel contenido; private FlowPanel pnlForm; private ContentForm contentForm; protected TextBox txtCodigo; protected TextBoxCalendar txtFecha; protected TextBox txtMonto; protected TextBox txtTasa; protected TextBox txtADevolver; protected TextBox txtDevuelto; protected TextBox txtCliente; protected TextBox txtTipoPrestamo; protected TextBox txtGlosa; protected Button btnGuardar; private FlowPanel pnlTxtCliente; //private FlowPanel pnlTxtCalendar; private PushButton btnClienteAdd; //private ButtonBarButtonBase btnCalendarAdd; private FlexTable flexTable; //private FlexTable flexTableCalendar; protected ClienteProxy beanCliente; protected PrestamoProxy beanPrestamo; //private UIClienteSelect dialogCliente; protected String modo; protected String modoPrestamo; public UIMantPrestamo() { init(); initWidgetListener(); style(); reCalcularWindows(); } private void init() { beanCliente=null; main = new VerticalPanel(); initWidget(main); //Window.addResizeHandler(this); header = new HeaderPanelM(); lblCenter = new Label(constants.modoNuevo()); header.setCenterWidget(lblCenter); main.add(header); btnBack = new PushButton(new Image(MyResource.INSTANCE.getImgBack32())); header.setLeftWidget(btnBack); //container = new FlowPanel(); //main.add(container); scrollPanel = new ScrollPanel(); /*scrollPanel.setScrollingEnabledY(true); scrollPanel.setScrollingEnabledX(false); scrollPanel.setAutoHandleResize(true);*/ /*scrollPanel.setScrollingEnabledX(false); scrollPanel.setScrollingEnabledY(true); scrollPanel.setAutoHandleResize(true);*/ //scrollPanel.setUsePos(MGWT.getOsDetection().isAndroid()); contenido = new FlowPanel(); scrollPanel.setWidget(contenido); pnlForm = new FlowPanel(); contenido.add(pnlForm); contentForm = new ContentForm(); pnlForm.add(contentForm); txtCodigo = new TextBox(); //contentForm.addWidget("Codigo", txtCodigo); //pnlTxtCalendar = new FlowPanel(); txtFecha = new TextBoxCalendar(); contentForm.addWidget("* "+constants.fecha(), txtFecha); //flexTableCalendar = new FlexTable(); //pnlTxtCalendar.add(flexTableCalendar); //flexTableCalendar.setWidget(0, 0, txtFecha); //btnCalendarAdd = new ButtonBarButtonBase( // MyResource.INSTANCE.getImgCalendar32()); //flexTableCalendar.setWidget(0, 1, btnCalendarAdd); txtMonto = new TextBox(); contentForm.addWidget("* "+constants.monto(), txtMonto); txtTasa = new TextBox(); contentForm.addWidget("* "+constants.tasa()+"(%) ", txtTasa); txtADevolver = new TextBox(); contentForm.addWidget(constants.aDevolver(), txtADevolver); txtDevuelto = new TextBox(); contentForm.addWidget(constants.devuelto(), txtDevuelto); pnlTxtCliente = new FlowPanel(); contentForm.addWidget("* "+constants.clientes(), pnlTxtCliente); txtTipoPrestamo=new TextBox(); contentForm.addWidget("Tipo Prestamo", txtTipoPrestamo); txtGlosa=new TextBox(); contentForm.addWidget("Glosa", txtGlosa); flexTable = new FlexTable(); pnlTxtCliente.add(flexTable); txtCliente = new TextBox(); txtCliente.setReadOnly(true); flexTable.setWidget(0, 0, txtCliente); btnClienteAdd = new PushButton( new Image(MyResource.INSTANCE.getImgClieAdd32())); flexTable.setWidget(0, 1, btnClienteAdd); btnGuardar = new Button(constants.guardar()); //btnGuardar.setConfirm(true); contenido.add(btnGuardar); scrollPanel.setWidget(contenido); main.add(scrollPanel); Window.addResizeHandler(new ResizeHandler(){ @Override public void onResize(ResizeEvent event) { // TODO Auto-generated method stub reCalcularWindows(); }}); } private void reCalcularWindows(){ //setWidthGrid(); setHeightContainer(100); setWidthPnlFlexTable(); } private void setWidthPnlFlexTable() { int width = Window.getClientWidth(); width = width - 20; // pnlForm.setWidth(width + "px"); } public void setModo(String modo) { this.modo = modo; lblCenter.setText(modo); } public void setBean(PrestamoProxy bean) { this.beanPrestamo = bean; llenarCampos(); } private void llenarCampos() { txtCodigo.setText(beanPrestamo.getIdPrestamo()); txtADevolver.setText(beanPrestamo.getaDevolver().toString()); txtDevuelto.setText(beanPrestamo.getDevuelto().toString()); txtMonto.setText(beanPrestamo.getMonto().toString()); txtTasa.setText(beanPrestamo.getTasa().toString()); DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy"); String fecha=format.format(beanPrestamo.getFecha()); txtFecha.getTxtFecha().setText(fecha); txtCliente.setText(beanPrestamo.getBeanCliente().getNombre()+" "+beanPrestamo.getBeanCliente().getApellido()); beanCliente=beanPrestamo.getBeanCliente(); txtTipoPrestamo.setText(beanPrestamo.getTipoPrestamo()); txtGlosa.setText(beanPrestamo.getGlosa()); } public void activarCampos() { if(modo.equalsIgnoreCase(constants.modoEliminar())){ txtCodigo.setReadOnly(true); txtADevolver.setReadOnly(true); txtDevuelto.setReadOnly(true); txtMonto.setReadOnly(true); txtTasa.setReadOnly(true); txtTipoPrestamo.setReadOnly(true); txtGlosa.setReadOnly(true); btnGuardar.setVisible(true); }else if(modo.equalsIgnoreCase(constants.modoEditar())){ txtCodigo.setReadOnly(true); txtADevolver.setReadOnly(true); txtDevuelto.setReadOnly(true); txtMonto.setReadOnly(false); txtTasa.setReadOnly(false); txtTipoPrestamo.setReadOnly(false); txtGlosa.setReadOnly(false); if(modoPrestamo.equals("HISTORIAL")){ btnGuardar.setVisible(true); }else{ btnGuardar.setVisible(true); } }else{ txtCodigo.setReadOnly(true); txtADevolver.setReadOnly(true); txtDevuelto.setReadOnly(true); txtMonto.setReadOnly(false); txtTasa.setReadOnly(false); txtTipoPrestamo.setReadOnly(false); txtGlosa.setReadOnly(false); if(modoPrestamo.equals("HISTORIAL")){ btnGuardar.setVisible(false); }else{ btnGuardar.setVisible(true); } } } private void initWidgetListener() { btnClienteAdd.addClickHandler(this); btnBack.addClickHandler(this); txtMonto.addKeyUpHandler(this); txtMonto.addBlurHandler(this); txtTasa.addKeyUpHandler(this); txtTasa.addBlurHandler(this); btnGuardar.addTouchEndHandler(this); btnGuardar.addClickHandler(this); } protected void setHeightContainer(int heightHeader) { int height = Window.getClientHeight(); scrollPanel.setHeight((height - heightHeader) + "px"); //this.scrollPanel.refresh(); } private void style() { Window.setMargin("0px"); MGWT.applySettings(MGWTSettings.getAppSetting()); btnGuardar.setWidth("97%"); btnGuardar.getElement().getStyle().setMarginBottom(50, Unit.PX); btnGuardar.getElement().getStyle().setFontSize(2, Style.Unit.EM); contenido.getElement().getStyle().setTextAlign(Style.TextAlign.CENTER); MyResource.INSTANCE.getStlModel().ensureInjected(); btnBack.addStyleName(MyResource.INSTANCE.getStlModel().pushButton()); //main.setWidth("100%"); //container.setWidth("100%"); //setHeightContainer(41); //scrollPanel.setWidth("100%"); //scrollPanel.setHeight("100%"); pnlForm.setWidth("100%"); contenido.setWidth("100%"); //pnlForm.getElement().getStyle().setOverflow(Overflow.HIDDEN); flexTable.setCellPadding(0); flexTable.setCellSpacing(0); flexTable.setWidth("100%"); txtCliente.setWidth("100%"); FlexCellFormatter cellFormatter = flexTable.getFlexCellFormatter(); cellFormatter.setWidth(0, 1, "40"); flexTable.addStyleName(MyResource.INSTANCE.getStlModel() .flexTableTextBoxCalendar()); txtCliente.addStyleName(MyResource.INSTANCE.getStlModel() .textBoxFechaTextBoxCalendar()); btnClienteAdd.setHeight("25px"); //btnClienteAdd.getElement().getStyle().setBackgroundColor("#0C0FB8"); /*flexTableCalendar.setCellPadding(0); flexTableCalendar.setCellSpacing(0); flexTableCalendar.setWidth("100%"); txtFecha.setWidth("100%"); FlexCellFormatter cellFormatterCal = flexTableCalendar.getFlexCellFormatter(); cellFormatterCal.setWidth(0, 1, "40"); flexTableCalendar.addStyleName(MyResource.INSTANCE.getStlModel() .flexTableTextBoxCalendar()); txtFecha.addStyleName(MyResource.INSTANCE.getStlModel() .textBoxFechaTextBoxCalendar()); btnCalendarAdd.setHeight("32px");*/ //btnCalendarAdd.getElement().getStyle().setBackgroundColor("#0C0FB8"); } /*@Override public void onResize(ResizeEvent event) { // TODO Auto-generated method stub setHeightContainer(41); setWidthDialog(); }*/ /*public void setWidthDialog(){ int width = Window.getClientWidth(); int height = Window.getClientHeight(); dialogCliente.setWidth((width-60)+"px"); dialogCliente.setHeight((height-80)+"px"); }*/ public void setBeanCliente(ClienteProxy bean){ beanCliente = bean; txtCliente.setText(beanCliente.getNombre()+" "+beanCliente.getApellido()); } @Override public void goToUIPrestamo() { // TODO Auto-generated method stub } @Override public void registrar() { // TODO Auto-generated method stub } @Override public void goToUIClienteAdd() { // TODO Auto-generated method stub } protected void calcularMontos(){ String monto=txtMonto.getText(); String tasa=txtTasa.getText(); String devuelto=txtDevuelto.getText(); BigDecimal vMonto=BigDecimal.ZERO; BigDecimal vTasa=BigDecimal.ZERO; BigDecimal vAdevolver=BigDecimal.ZERO; BigDecimal vDevuelto=BigDecimal.ZERO; if(monto!=null&&!monto.isEmpty()){ try{ if(modo.equalsIgnoreCase(constants.modoNuevo())){ vMonto=BigDecimal.valueOf(Double.parseDouble(monto)); }else if(modo.equalsIgnoreCase(constants.modoEditar())){ vMonto=BigDecimal.valueOf(Double.parseDouble(monto)); vDevuelto=BigDecimal.valueOf(Double.parseDouble(devuelto)); if(vMonto.compareTo(vDevuelto)<0){ vMonto=BigDecimal.valueOf(beanPrestamo.getMonto()); txtMonto.setText(vMonto.toString()); } } }catch(Exception ex){ vMonto=BigDecimal.ZERO; txtMonto.setText(BigDecimal.ZERO.toString()); } }else{ vMonto=BigDecimal.ZERO; txtMonto.setText(vMonto.toString()); } if(tasa!=null&&!tasa.isEmpty()){ try{ vTasa=BigDecimal.valueOf(Double.parseDouble(tasa)); }catch(Exception ex){ vTasa=BigDecimal.ZERO; txtTasa.setText(vTasa.toString()); } }else{ vTasa=BigDecimal.ZERO; txtTasa.setText(vTasa.toString()); } if(devuelto!=null&&!devuelto.isEmpty()){ try{ vDevuelto=BigDecimal.valueOf(Double.parseDouble(devuelto)); }catch(Exception ex){ vDevuelto=BigDecimal.ZERO; txtDevuelto.setText(vDevuelto.toString()); } }else{ vDevuelto=BigDecimal.ZERO; txtDevuelto.setText(vDevuelto.toString()); } //vAdevolver=vMonto.add(vTasa.divide(BigDecimal.valueOf(100)).multiply(vMonto)).subtract(vDevuelto); vAdevolver=vMonto.add(vTasa.divide(BigDecimal.valueOf(100)).multiply(vMonto)); txtADevolver.setText(vAdevolver.toString()); txtDevuelto.setText(vDevuelto.toString()); } @Override public void onKeyUp(KeyUpEvent event) { // TODO Auto-generated method stub if(event.getSource().equals(txtMonto)||event.getSource().equals(txtTasa)) if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { calcularMontos(); } } @Override public void onBlur(BlurEvent event) { // TODO Auto-generated method stub if(event.getSource().equals(txtMonto)||event.getSource().equals(txtTasa)) calcularMontos(); } @Override public boolean isValidData() { // TODO Auto-generated method stub if(!modo.equalsIgnoreCase(constants.modoEliminar())){ if(FieldVerifier.isEmpty(txtFecha.getText())){ //Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null); //Window.alert(constants.camposObligatorios()); Notification not=new Notification(Notification.ALERT,constants.camposObligatorios()); not.showPopup(); return false; }else if(FieldVerifier.isEmpty(txtMonto.getText())){ //Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null); //Window.alert(constants.camposObligatorios()); Notification not=new Notification(Notification.ALERT,constants.camposObligatorios()); not.showPopup(); return false; }else if(FieldVerifier.isEmpty(txtTasa.getText())){ //Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null); //Window.alert(constants.camposObligatorios()); Notification not=new Notification(Notification.ALERT,constants.camposObligatorios()); not.showPopup(); return false; }else if(FieldVerifier.isEmpty(txtCliente.getText())){ //Dialogs.alert("Alerta", "Campos con (*) son obligatorios", null); //Window.alert(constants.camposObligatorios()); Notification not=new Notification(Notification.ALERT,constants.camposObligatorios()); not.showPopup(); return false; } }else{ BigDecimal vDevuelto=BigDecimal.valueOf(Double.valueOf(txtDevuelto.getText())); if(vDevuelto.compareTo(BigDecimal.ZERO)==1){ //Dialogs.alert("Alerta", "Existen amortizaciones", null); //Window.alert("Existen amortizaciones"); Notification not=new Notification(Notification.ALERT,"Existen amortizaciones"); not.showPopup(); return false; } } return true; } @Override public void activarModoPrestamo() { // TODO Auto-generated method stub } @Override public void onTouchEnd(TouchEndEvent event) { // TODO Auto-generated method stub if (event.getSource().equals(btnGuardar)) { registrar(); } } @Override public void onClick(ClickEvent event) { // TODO Auto-generated method stub if (event.getSource().equals(btnBack)) { goToUIPrestamo(); }else if (event.getSource().equals(this.btnClienteAdd)) { goToUIClienteAdd(); /*dialogCliente = new UIClienteSelect(this); setWidthDialog(); dialogCliente.center(); dialogCliente.show();*/ }else if (event.getSource().equals(btnGuardar)) { registrar(); } } }
[ "chescot2302@gmail.com" ]
chescot2302@gmail.com
f09465ccc736891a77c0a237be9a7437d5739e12
9254e7279570ac8ef687c416a79bb472146e9b35
/sae-20190506/src/main/java/com/aliyun/sae20190506/models/ListTagResourcesQuery.java
085bced636330ce0d9d26b455c8598405d0d524a
[ "Apache-2.0" ]
permissive
lquterqtd/alibabacloud-java-sdk
3eaa17276dd28004dae6f87e763e13eb90c30032
3e5dca8c36398469e10cdaaa34c314ae0bb640b4
refs/heads/master
2023-08-12T13:56:26.379027
2021-10-19T07:22:15
2021-10-19T07:22:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,745
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sae20190506.models; import com.aliyun.tea.*; public class ListTagResourcesQuery extends TeaModel { @NameInMap("RegionId") @Validation(required = true) public String regionId; @NameInMap("ResourceType") @Validation(required = true) public String resourceType; @NameInMap("NextToken") public String nextToken; @NameInMap("ResourceIds") public String resourceIds; @NameInMap("Tags") public String tags; public static ListTagResourcesQuery build(java.util.Map<String, ?> map) throws Exception { ListTagResourcesQuery self = new ListTagResourcesQuery(); return TeaModel.build(map, self); } public ListTagResourcesQuery setRegionId(String regionId) { this.regionId = regionId; return this; } public String getRegionId() { return this.regionId; } public ListTagResourcesQuery setResourceType(String resourceType) { this.resourceType = resourceType; return this; } public String getResourceType() { return this.resourceType; } public ListTagResourcesQuery setNextToken(String nextToken) { this.nextToken = nextToken; return this; } public String getNextToken() { return this.nextToken; } public ListTagResourcesQuery setResourceIds(String resourceIds) { this.resourceIds = resourceIds; return this; } public String getResourceIds() { return this.resourceIds; } public ListTagResourcesQuery setTags(String tags) { this.tags = tags; return this; } public String getTags() { return this.tags; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
a10bcba49de4b25bb13c2f94444503c777357d9b
ec5ff737fbe8eca3075ef5da7dccc3ca7803e1e0
/src/main/java/tests/DeSerializationToObject.java
ef02d54cc784d4e3c6ec21877120b47603ddfbd5
[]
no_license
kumzme/Learn_Java
ce0924e8700da93dcb1a43e13c30139aa28a5e98
b37da0bae6c3e066b36ea67da52cbd16045d7ca4
refs/heads/master
2020-03-26T20:50:30.059574
2019-03-01T02:58:07
2019-03-01T02:58:07
145,349,407
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package tests; import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeSerializationToObject { public static Object DeSerailizedtoObject(String fileName) throws Exception{ FileInputStream fin = new FileInputStream(new File(fileName)); ObjectInputStream ObjIn = new ObjectInputStream(fin); Object deSerialzedObj = ObjIn.readObject(); ObjIn.close(); fin.close(); return deSerialzedObj; } public static void main(String args[]) throws Exception { Serializable_EmployeeClass deSearlizedempC = (Serializable_EmployeeClass) DeSerailizedtoObject("empTest"); System.out.println(deSearlizedempC.getEmpName()); System.out.println(deSearlizedempC.getDeptName()); } }
[ "deepa.patri.ctr@telesishq.com" ]
deepa.patri.ctr@telesishq.com
2aba653cd37b0bdfe349812d58adf4e932e686e3
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/drjava_cluster/12757/src_1.java
ac877a691c5de4f26bdcbeb581b4af7e8cc62de0
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,958
java
/*BEGIN_COPYRIGHT_BLOCK * * This file is part of DrJava. Download the current version of this project: * http://sourceforge.net/projects/drjava/ or http://www.drjava.org/ * * DrJava Open Source License * * Copyright (C) 2001-2003 JavaPLT group at Rice University (javaplt@rice.edu) * All rights reserved. * * Developed by: Java Programming Languages Team * Rice University * http://www.cs.rice.edu/~javaplt/ * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal with 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: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimers. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * - Neither the names of DrJava, the JavaPLT, Rice University, nor the * names of its contributors may be used to endorse or promote products * derived from this Software without specific prior written permission. * - Products derived from this software may not be called "DrJava" nor * use the term "DrJava" as part of their names without prior written * permission from the JavaPLT group. For permission, write to * javaplt@rice.edu. * * 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 CONTRIBUTORS 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 WITH THE SOFTWARE. * END_COPYRIGHT_BLOCK*/ package edu.rice.cs.drjava.model.compiler; import java.io.*; import junit.framework.*; import edu.rice.cs.util.classloader.LimitingClassLoader; import edu.rice.cs.util.ClasspathVector; import edu.rice.cs.drjava.DrJava; /** * Test cases for {@link CompilerRegistry}. * Here we test that the compiler registry correctly finds * available compilers. * * @version $Id$ */ public final class CompilerRegistryTest extends TestCase { private static final CompilerRegistry _registry = CompilerRegistry.ONLY; private static final String[][] _defaultCompilers = CompilerRegistry.DEFAULT_COMPILERS; private static final CompilerInterface[] _allAvailableCompilers = _registry.getAvailableCompilers(); /** * Stores the old state of {@link CompilerRegistry#getBaseClassLoader}, * so it can be reset later. */ private ClassLoader _oldBaseLoader; /** * Constructor. * @param name */ public CompilerRegistryTest(String name) { super(name); } /** * Creates a test suite for JUnit to run. * @return a test suite based on the methods in this class */ public static Test suite() { return new TestSuite(CompilerRegistryTest.class); } /** Test setup method, which saves the old base class loader. */ public void setUp() { _oldBaseLoader = _registry.getBaseClassLoader(); _registry.setActiveCompiler(NoCompilerAvailable.ONLY); } /** Test teardown method, which restores the old base class loader. */ public void tearDown() { _registry.setBaseClassLoader(_oldBaseLoader); } /** * Test that the default compilers are available and what we expect. * This requires the environment (CLASSPATH) to have these compilers * available. This is OK though, since the build environment needs them! * * This test is now commented out because it put too must restriction * on the developer's build environment. It required them to have all the * compilers available, which they may not. Oh well. These matters * of configuration are really hard to test nicely. */ /* public void testExpectedDefaultCompilers() { CompilerInterface[] compilers = _registry.getAvailableCompilers(); assertEquals("Number of available compilers vs. number of default compilers", _defaultCompilers.length, compilers.length); for (int i = 0; i < compilers.length; i++) { assertEquals("Name of available compiler #" + i + " is the same as the " + "name of the corresponding default compiler", _defaultCompilers[i], compilers[i].getClass().getName()); } } */ /** * Tests that list of available compilers effectively is restricted * when the class is not available. * Here this is done by limiting the available compilers one at a time. */ public void testLimitOneByOne() { for (int i = 0; i < _allAvailableCompilers.length; i++) { //CompilerInterface[] compilers = _getCompilersAfterDisablingOne(i); // That method includes all the tests we need! } } /** * Tests that list of available compilers effectively is restricted * when all default compilers are not available. */ public void testLimitAllAtOnce() { LimitingClassLoader loader = new LimitingClassLoader(_oldBaseLoader); _registry.setBaseClassLoader(loader); for (int i = 0; i < _defaultCompilers.length; i++) { for (int j = 0; j < _defaultCompilers[i].length; j++) { loader.addToRestrictedList(_defaultCompilers[i][j]); } } CompilerInterface[] compilers = _registry.getAvailableCompilers(); assertEquals("Number of available compilers should be 1 " + "because all real compilers are restricted.", 1, compilers.length); assertEquals("Only available compiler should be NoCompilerAvailable.ONLY", NoCompilerAvailable.ONLY, compilers[0]); assertEquals("Active compiler", NoCompilerAvailable.ONLY, _registry.getActiveCompiler()); assertEquals("DrJava.java should not see an available compiler", false, DrJava.hasAvailableCompiler()); } /** * Tests that DrJava.java can see whether CompilerRegistry has an * available compiler. */ public void testAvailableCompilerSeenByDrJava() { assertEquals("DrJava.java should agree with CompilerRegistry", _registry.getActiveCompiler() != NoCompilerAvailable.ONLY, DrJava.hasAvailableCompiler()); } /** * Tests that {@link CompilerRegistry#setActiveCompiler} and * {@link CompilerRegistry#getActiveCompiler} work. */ public void testActiveCompilerAllAvailable() { CompilerInterface[] compilers = _registry.getAvailableCompilers(); assertEquals("active compiler before any setActive", compilers[0], _registry.getActiveCompiler()); for (int i = 0; i < compilers.length; i++) { // TODO: deal with the problem that sometimes not all compilers avail! //if (compilers[i].isAvailable()) { _registry.setActiveCompiler(compilers[i]); assertEquals("active compiler after setActive", compilers[i], _registry.getActiveCompiler()); //} } } /** * Returns the list of available compilers after disabling one of them. * This method includes checks for the correctness of the list * after disabling one. * * @param i Index of default compiler to disable. */ private CompilerInterface[] _getCompilersAfterDisablingOne(int i) { return _getCompilersAfterDisablingSome(new int[] { i }); } /** * Returns the list of available compilers after disabling some of them. * This method includes checks for the correctness of the list * after disabling them. * * @param indices Array of ints signifying which of the default compilers * to disable. */ private CompilerInterface[] _getCompilersAfterDisablingSome(int[] indices) { LimitingClassLoader loader = new LimitingClassLoader(_oldBaseLoader); _registry.setBaseClassLoader(loader); //for (int j = 0; j < _allAvailableCompilers.length; j++) { // System.out.println("all available compilers: " + _allAvailableCompilers[j].getClass().getName()); //} for (int i = 0; i < indices.length; i++) { //System.out.println("restricting compiler: " + _allAvailableCompilers[indices[i]].getClass().getName()); loader.addToRestrictedList(_allAvailableCompilers[indices[i]].getClass().getName()); } CompilerInterface[] compilers = _registry.getAvailableCompilers(); //for (int j = 0; j < compilers.length; j++) { // System.out.println("available compiler: " + compilers[j].getClass().getName()); //} // NOTE: 03.28.2004 We don't know how to check this since making the change // to only display one compiler of each type. JH & NH // assertEquals("Number of available compilers", // _allAvailableCompilers.length - indices.length, // compilers.length); int indicesIndex = 0; for (int j = 0; j < _allAvailableCompilers.length; j++) { if ((indicesIndex < indices.length) && (j == indices[indicesIndex])) { // this is an index to skip. indicesIndex++; continue; } // Now indicesIndex is at the number of indices to skip! int indexInAvailable = j - indicesIndex; assertEquals("Class of available compiler #" + indexInAvailable, _allAvailableCompilers[j].getClass().getName(), compilers[indexInAvailable].getClass().getName()); } return compilers; } /** * Ensure that the active compiler in the registry cannot be set to null. */ public void testCannotSetCompilerToNull() { try { _registry.setActiveCompiler(null); fail("Setting active compiler to null should have caused an exception!"); } catch (IllegalArgumentException e) { // Good-- exception was thrown. } } static class Without implements CompilerInterface { public boolean testField = false; public Without() { testField = true; } public void addToBootClassPath(File s) { } public CompilerError[] compile(File[] sourceRoots, File[] files) { return null; } public CompilerError[] compile(File sourceRoot, File[] files) { return null; } public String getName() { return "Without"; } public boolean isAvailable() { return false; } public void setAllowAssertions(boolean allow) { } public void setWarningsEnabled(boolean warningsEnabled) { } public void setExtraClassPath(String extraClassPath) { } public void setExtraClassPath(ClasspathVector extraClassPath) { } public String toString() { return "Without"; } public void setBuildDirectory(File builddir) { } } /** * Test that createCompiler() does successfully instantiate * compilers that do not have the ONLY static field, and those which * do have it. */ public void testCreateCompiler() { try{ _registry.createCompiler(Without.class); } catch(Throwable e) { e.printStackTrace(); fail("testCreateCompiler: Unexpected Exception for class without ONLY field\n" + e); } try{ _registry.createCompiler(JavacFromClasspath.ONLY.getClass()); } catch(Throwable e2) { fail("testCreateCompiler: Unexpected Exception for class with ONLY field\n" + e2); } } }
[ "375833274@qq.com" ]
375833274@qq.com
0b24f54ffd2150c27fcf1e7957c178abf440e8a8
3efaa0b164bf250dd29fcec49e522a15d1deaaf8
/src/noorteck/Demo4.java
261ce63a9d8ea61ee0fd1d1c0b9e776855b5f759
[]
no_license
fernanda102017/Coding1
a1405b0b6355a63e0930c44d24ac277485822ab4
a0b3b9869129552a2c64f6785ecb97cb899a8b16
refs/heads/master
2022-06-28T14:40:09.940466
2020-05-15T17:34:48
2020-05-15T17:34:48
264,258,344
0
0
null
null
null
null
UTF-8
Java
false
false
126
java
package noorteck; public class Demo4 { public static void main(String[] args) { System.out.println("Integer"); } }
[ "andreamejia@10.0.0.186" ]
andreamejia@10.0.0.186
ccb9d4927dc19b0bd17c0f5c30e29de387ce5bd3
a3548b736c69de0439313765d14a092dae519e09
/src/main/java/cn/zhr/util/DynamicDataSource.java
a0977bad12248cca6c1d74e7b71901e5c3741d5f
[]
no_license
Fortmrw/activiti
b3a91552ab07edd2c9116386d153ffb1bd30493c
8c9d32fdb9d7430b6830bb6dd9c5c3f982116e63
refs/heads/master
2021-05-14T10:27:30.583472
2018-01-05T07:16:06
2018-01-05T07:16:06
116,353,782
0
0
null
null
null
null
UTF-8
Java
false
false
302
java
package cn.zhr.util; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDbType(); } }
[ "zhr1024@sina.cn" ]
zhr1024@sina.cn
509f84bcdea6521d38131796541fc26947a82cc6
4ab11aac2a3b4e8d11902dfcfb967d5742d5ecb9
/knowledge/demo/boot/empty/src/main/java/com/mg/empty/demo/alt/sort/SelectSort.java
a36e050e13da71540134193697893077fbd72e01
[]
no_license
MT-GMZ/mg
af72d0d71ce1b6a8100cddc84af4bbaa14efb9e8
020a6796fafa494a6a875689da202835c680f04e
refs/heads/master
2023-01-19T23:56:13.961811
2020-11-29T06:06:21
2020-11-29T06:06:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
875
java
package com.mg.empty.demo.alt.sort; import com.mg.empty.demo.alt.util.ShowUtill; /** * 算法思路,将最小的放在第一个 * 然后 获取出剩余的最小值 放在第二个位置 * 依次排序成功 */ public class SelectSort { public void selectSort(int[] array) { for(int i=0;i<array.length-1;i++) { int index =i; for(int j=i+1;j<array.length;j++) { if(array[j]<array[index]) { index = j; } } int tmp = array[i]; array[i] = array[index]; array[index] = tmp; } ShowUtill.showArray(array); } public static void main(String[] args) { SelectSort selectSort = new SelectSort(); selectSort.selectSort(new int[]{100,9,3,2,7,15,300,12}); } }
[ "mataoshou@163.com" ]
mataoshou@163.com
9a14f22794e2b18dea9bc14b33c66806f34e01cd
ffe58d32e5e78cd51934a5e27e76b6442db557f3
/src/proj/HashMap.java
1ed732f51ad4f65bce35152e782adcd48e0c6dbe
[]
no_license
Data-Struct-Proj/proj-files
155ef5843b890711dfe8f85c1b99f2a9bda6eb9c
549f302e923a334319b6e3c70656832fdd0967ca
refs/heads/master
2022-10-22T21:29:07.929300
2020-06-17T09:33:35
2020-06-17T09:33:35
264,357,870
0
0
null
null
null
null
UTF-8
Java
false
false
1,003
java
package proj; public class HashMap { class Data { int key; String value; public Data(int k,String v){ key=k; value=v; } public boolean equals(Data that) { return (this.key==that.key); } @Override public int hashCode() { return key; } }; class Node{ Data data; Node next,prev; public Node(Data d) { data = d; next=prev=null; } }; Node[] map; public HashMap(int size) { map=new Node[size]; } public int hash(Data n) { return n.hashCode() % map.length; } public void put(int k ,String v) { Data d = new Data (k,v); int h = hash(d); Node n = new Node(d); if (map[h]==null) map[h]=n; else { Node ptr = map[h]; for(;ptr.next!=null;ptr=ptr.next); ptr.next = n; n.prev=ptr; } } public String get(int k) { int h = k%map.length; Node ptr = map[h]; while(ptr!=null && ptr.data.key!=k) { ptr = ptr.next; } return (ptr==null) ? null:ptr.data.value; //else is a colon,? is a then } }
[ "rrohith2001@gmail.com" ]
rrohith2001@gmail.com
dd9fa645633f9ac45b329eddb93ce85dcabf86a7
af29b4fb6f754876c376d90b1d940bcd6f06729e
/src/test/java/ar/edu/utn/frro/web/rest/TestUtil.java
b557211951bb2533b997191b387188c6a668e300
[ "MIT" ]
permissive
iisidro/iisidro-server
0d0040ba1f7f98ca59f3aa3b5314932c5c5fb00f
ded27b5debb3039ea748274c5cd85e5beef933fa
refs/heads/development
2021-01-16T23:28:20.453175
2017-03-16T00:58:54
2017-03-16T00:58:54
54,026,785
0
3
MIT
2020-12-01T16:53:49
2016-03-16T11:39:04
Java
UTF-8
Java
false
false
2,333
java
package ar.edu.utn.frro.web.rest; import ar.edu.utn.frro.domain.util.JSR310DateTimeSerializer; import ar.edu.utn.frro.domain.util.JSR310LocalDateDeserializer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.http.MediaType; import java.io.IOException; import java.nio.charset.Charset; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; /** * Utility class for testing REST controllers. */ public class TestUtil { /** MediaType for JSON UTF8 */ public static final MediaType APPLICATION_JSON_UTF8 = new MediaType( MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); /** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); JavaTimeModule module = new JavaTimeModule(); module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE); module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE); mapper.registerModule(module); return mapper.writeValueAsBytes(object); } /** * Create a byte array with a specific size filled with specified data. * * @param size the size of the byte array * @param data the data to put in the byte array */ public static byte[] createByteArray(int size, String data) { byte[] byteArray = new byte[size]; for (int i = 0; i < size; i++) { byteArray[i] = Byte.parseByte(data, 2); } return byteArray; } }
[ "fanky10@gmail.com" ]
fanky10@gmail.com
addf836fffc6161f91a5bd3b83fc154df3edfd67
838376338d007faad8ecae04eebd623393139569
/com.rufang.leetcode/src/com/rufang/leetcode/array/ContainerWithMostWater.java
e2e7004ca4ecc44055e776fc74318faf88563229
[]
no_license
amyfang/InterviewCode
35bc3287fa78f8b26e6b41413d5d029251fb68ec
4ecca02b0689e8a46775ad53f2cadcd2cf29a86c
refs/heads/master
2021-01-25T05:57:50.929525
2019-09-25T19:11:48
2019-09-25T19:11:48
27,024,267
0
0
null
null
null
null
UTF-8
Java
false
false
1,444
java
package com.rufang.leetcode.array; public class ContainerWithMostWater { public static void main(String[] args) { // TODO Auto-generated method stub int[] input1 = {1,8,6,2,5,4,8,3,7}; int result1 = maxArea(input1); int result1_1 = maxArea2(input1); System.out.println(result1); System.out.println(result1_1); int[] input2 = {1}; int result2 = maxArea(input2); System.out.println(result2); } //brute force O(n2) public static int maxArea(int[] height) { if(null == height) return 0; if(height.length == 1) return 0; int maxValue = 0; for(int i=0; i<height.length-1; i++){ for(int j=i+1; j<height.length; j++){ int value = (j-i) * Math.min(height[i], height[j]); System.out.println("i=" + i + " j=" +j + " value=" + value); if(value > maxValue){ maxValue = value; } } } return maxValue; } //two pointer solution, O(n) public static int maxArea2(int[] height) { if(null == height) return 0; if(height.length == 1) return 0; int maxValue = 0; int left = 0, right = height.length - 1; while(left < right){ int value = (right - left) * Math.min(height[left], height[right]); System.out.println("left=" + left + " right=" +right + " value=" + value); maxValue = maxValue < value ? value : maxValue; if(height[left] < height[right]){ left ++; } else { right --; } } return maxValue; } }
[ "ru_fang@apple.com" ]
ru_fang@apple.com
d06c7da9afb9fea7f7a92e7b1b988f69de24ccb3
0bb711323711c4a9c7ca38638ae691e7a063978c
/Week-08/greenfoxws03/src/main/java/Account.java
f0da524a4dc217ae5a5de06bbcec737724ecce39
[]
no_license
greenfox-zerda-raptors/vikukzs
462a592c61f5d4e996c36859117f697980b0ffb4
b8370b279d79e9b153d70ed37eded709b1d791da
refs/heads/master
2021-01-12T18:15:21.934253
2017-02-17T09:11:28
2017-02-17T09:11:28
71,352,666
0
0
null
null
null
null
UTF-8
Java
false
false
858
java
/** * Created by Zsuzska on 2016. 12. 14.. */ import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import lombok.Getter; import lombok.Setter; @Getter @Setter @DatabaseTable(tableName = "accounts") public class Account { @DatabaseField(id = true) private String name; @DatabaseField private String password; @DatabaseField(foreign = true) public Address address; public Account() {} public Account(String name, String password ) { this.name = name; this.password = password; } public Account(String name, String password, Address address){ this.name = name; this.password = password; this.address = address; } @Override public String toString() { return "Name: " + getName() + "Address: " + address.toString(); } }
[ "vikuk.zs@gmail.com" ]
vikuk.zs@gmail.com
668053f32acac60691b3810a121474b935504557
96209005e1ff0506b5789ab83fdc1277ef20255d
/src/main/java/app/dao/ItemExameDAO.java
46cc2f2658fe937d4f61c088b4950773dd01a61b
[]
no_license
thiagowenceslau/hygya
4f2d66749cab3de0ba3b7bf482bf33913be21743
da419596dbc574f42624d096d7607daa0d812a4d
refs/heads/master
2020-03-15T14:56:52.292156
2018-06-05T19:12:31
2018-06-05T19:12:31
132,200,855
0
0
null
null
null
null
UTF-8
Java
false
false
1,969
java
package app.dao; import app.entity.*; import java.util.*; import org.springframework.stereotype.*; import org.springframework.data.jpa.repository.*; import org.springframework.data.domain.*; import org.springframework.data.repository.query.*; import org.springframework.transaction.annotation.*; /** * Realiza operação de Create, Read, Update e Delete no banco de dados. * Os métodos de create, edit, delete e outros estão abstraídos no JpaRepository * * @see org.springframework.data.jpa.repository.JpaRepository * * @generated */ @Repository("ItemExameDAO") @Transactional(transactionManager="app-TransactionManager") public interface ItemExameDAO extends JpaRepository<ItemExame, java.lang.String> { /** * Obtém a instância de ItemExame utilizando os identificadores * * @param id * Identificador * @return Instância relacionada com o filtro indicado * @generated */ @Query("SELECT entity FROM ItemExame entity WHERE entity.id = :id") public ItemExame findOne(@Param(value="id") java.lang.String id); /** * Remove a instância de ItemExame utilizando os identificadores * * @param id * Identificador * @return Quantidade de modificações efetuadas * @generated */ @Modifying @Query("DELETE FROM ItemExame entity WHERE entity.id = :id") public void delete(@Param(value="id") java.lang.String id); /** * OneToMany Relation * @generated */ @Query("SELECT entity FROM ItemValorExame entity WHERE entity.itemExame.id = :id") public Page<ItemValorExame> findItemValorExame(@Param(value="id") java.lang.String id, Pageable pageable); /** * Foreign Key resultado * @generated */ @Query("SELECT entity FROM ItemExame entity WHERE entity.resultado.id = :id") public Page<ItemExame> findItemExamesByResultado(@Param(value="id") java.lang.String id, Pageable pageable); }
[ "thwonet@hotmail.com" ]
thwonet@hotmail.com
04e8f981d33b04e8423dc6844cb6c03bb07d39b1
89904f6c80aab728d197f879b5a0167f7198ea96
/integration-tests/google-cloud-functions-http/src/main/java/io/quarkus/it/gcp/functions/http/GreetingServlet.java
1065e3f6499e0f51c44e319e794462c8df15b78e
[ "Apache-2.0" ]
permissive
loicmathieu/quarkus
54b27952bbdbf16772ce52086bed13165a6c0aec
f29b28887af4b50e7484dd1faf252b15f1a9f61a
refs/heads/main
2023-08-30T23:58:38.586507
2022-11-10T15:01:09
2022-11-10T15:01:09
187,598,844
3
1
Apache-2.0
2023-03-02T20:56:56
2019-05-20T08:23:48
Java
UTF-8
Java
false
false
987
java
package io.quarkus.it.gcp.functions.http; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "ServletGreeting", urlPatterns = "/servlet/hello") public class GreetingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(200); resp.addHeader("Content-Type", "text/plain"); resp.getWriter().write("hello"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getReader().readLine(); resp.setStatus(200); resp.addHeader("Content-Type", "text/plain"); resp.getWriter().write("hello " + name); } }
[ "loikeseke@gmail.com" ]
loikeseke@gmail.com
a1249ef747983c30f42fe89008933ad966eead8c
aa10130655e199caab844460ec3a53b8e1947e47
/Trabajos/cesarvicuna/TrabajoNota/src/pe/eeob/consolidadnotas/dto/consolidadDto.java
8d89e422ab795e10fd454ea56b37e53f519602f2
[]
no_license
Vobregon/SISTUNI_PROG_JAVA_003
0ace48fbc731798b2565bc970cac93adfa60aff3
f920a8fd2a63fffeba52575f41d1d897d3c2a456
refs/heads/master
2021-01-24T01:30:13.231379
2016-02-21T06:14:55
2016-02-21T06:14:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,270
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 pe.eeob.consolidadnotas.dto; /** * * @author Cesar Vicuña */ public class consolidadDto { public float notaeparcial; public float notaefinal; public float notaproyecto; public int tipo; public float notafinal; public consolidadDto() { } public float getNotaeparcial() { return notaeparcial; } public void setNotaeparcial(float notaeparcial) { this.notaeparcial = notaeparcial; } public float getNotaefinal() { return notaefinal; } public void setNotaefinal(float notaefinal) { this.notaefinal = notaefinal; } public float getNotaproyecto() { return notaproyecto; } public void setNotaproyecto(float notaproyecto) { this.notaproyecto = notaproyecto; } public int getTipo() { return tipo; } public void setTipo(int tipo) { this.tipo = tipo; } public float getNotafinal() { return notafinal; } public void setNotafinal(float notafinal) { this.notafinal = notafinal; } }
[ "gcoronelc@gmail.com" ]
gcoronelc@gmail.com
88766418347850daa792d1b682d253f247fe0f21
54ced7a1d869bef5a3ccb7c6b0da76fc37eccf7f
/cucumber2/src/test/java/stepDefinations/StepDefination.java
57c498d59296cc8b13c7d679538c356e9e87def2
[]
no_license
vibhubrt/QAtest
9536fe4756a6dd22e1b9f035940c2154d7335495
34b83451186927c5faf8e5ebbb3dbd28b9fc8526
refs/heads/master
2023-01-07T04:08:21.426571
2020-11-06T14:30:14
2020-11-06T14:30:14
310,475,024
0
0
null
null
null
null
UTF-8
Java
false
false
5,348
java
package stepDefinations; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import static org.junit.Assert.*; import java.text.ParseException; import io.restassured.parsing.Parser; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import pojo.GetResponse; import pojo.InvalidResponse; import resources.Utils; import static io.restassured.RestAssured.*; public class StepDefination extends Utils { RequestSpecification request; GetResponse responsebody; InvalidResponse invalidresponse; Response resp; JsonPath js; // calls requestSpecification method to set base URI and query parameters as latitude and longitude @Given("valid latitude {double} and longitude {double}") public void valid_latitude_and_longitude(Double latitude, Double longitude) { request = given().log().all().spec(requestSpecification(latitude, longitude)); } // calls requestSpecification method to set base URI and query parameters latitude,longitude,date,format @Given("valid latitude {double} and longitude {double} and validdate {string} and format {int}") public void valid_latitude_and_longitude_and_validdate_and_format(Double latitude, Double longitude, String date, int format) { request = given().log().all().spec(requestSpecification(latitude, longitude, date, format)); } // calls requestSpecification method to set base URI and query parameters latitude,longitude,format @Given("valid latitude {double} and longitude {double} and format {int}") public void valid_latitude_and_longitude_and_dateformat(Double latitude, Double longitude, int format) { request = given().log().all().spec(requestSpecification(latitude, longitude, format)); } // calls requestSpecification method to set base URI and query parameters latitude,longitude,date @Given("valid latitude {double} and longitude {double} and invaliddate {string}") public void valid_latitude_and_longitude_and_invaliddate(Double latitude, Double longitude, String date) { request = given().log().all().spec(requestSpecification(latitude, longitude, date)); } // Response body which is returned from API is stored in POJO class based on response code @When("user calls API with get Http request") public void user_calls_api_with_get_http_request() { resp = request.when().get("/json").then().extract().response(); if (resp.getStatusCode() == 400) { invalidresponse = request.expect().defaultParser(Parser.JSON).when().get("/json").as(InvalidResponse.class); } else if (resp.getStatusCode() == 200) { responsebody = request.expect().defaultParser(Parser.JSON).when().get("/json").as(GetResponse.class); System.out.println(responsebody.getResults().getDay_length()); } } //Verifying API response code with expected value @Then("API call code is {string}") public void api_call_success_code_is(String code) { assertEquals(Integer.toString(resp.getStatusCode()), code); } //Verifying Status of API with expected value @Then("{string} in response body is {string}") public void in_response_body_is(String key, String expectedvalue) { String response = resp.asString(); System.out.println(response); js = new JsonPath(response); assertEquals(js.get(key).toString(), expectedvalue); } //Verifies whether sunrise and sunset time are returned for specified location @Then("verify sunrise and sunset times") public void verify_sunrise_and_sunset_times() { assertNotNull(responsebody.getResults().getSunrise()); assertNotNull(responsebody.getResults().getSunset()); } //To check date returned from response is equal to today's date @Then("check default date is today") public void check_default_date_is_today() throws ParseException { String date =getDatefromResponse(responsebody.getResults().getSunrise()); assertEquals(gettodayUTCDate(), date); } //Checks if response body contains date @Then("verify if data is unformatted") public void verify_if_data_is_unformatted() throws ParseException { String date = getDatefromResponse(responsebody.getResults().getSunset()); assertTrue(responsebody.getResults().getSunrise().contains(date)); } //Sunrise date and sunset date are extracted from response body and compared with inputdate @Then("check sunrise and sunset of {string}") public void check_sunrise_and_sunset_of(String inputdate) throws ParseException { String sunrisedate = getDatefromResponse(responsebody.getResults().getSunset()); String sunsetdate = getDatefromResponse(responsebody.getResults().getSunrise()); assertEquals(sunrisedate,inputdate); assertEquals(sunsetdate,inputdate); } //checks if calculated day length is equal to day length received from response body/payload @Then("check time between sunrise and sunset is equal to daylength") public void check_time_between_sunrise_and_sunset_is_equal_to_daylength() { String daylength = getDaylength(responsebody.getResults().getSunrise(), responsebody.getResults().getSunset()); assertEquals(daylength, responsebody.getResults().getDay_length()); } }
[ "vibhubrt@gmail.com" ]
vibhubrt@gmail.com
d168a27f3b64c51e9bc383a9a311aad6e93b7787
3eb3438640806ed125c3a29c14885a7ae8269856
/src/main/java/sk/akademiasovy/tipos/Server/TiposApplication.java
bba8b275589472d19228de0695e75eef5cee2314
[]
no_license
JakuSel/projektTiposServer
ab9b3732cf03863dd796127fa3a3c9d191ecc616
8ae3fa1cca0b4209e55d5cdc427fcaa823d579e8
refs/heads/master
2021-04-25T08:30:26.102931
2018-05-10T19:18:30
2018-05-10T19:18:30
122,194,460
0
0
null
null
null
null
UTF-8
Java
false
false
1,719
java
package sk.akademiasovy.tipos.Server; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.eclipse.jetty.servlets.CrossOriginFilter; import sk.akademiasovy.tipos.Server.resources.Bets; import sk.akademiasovy.tipos.Server.resources.Draws; import sk.akademiasovy.tipos.Server.resources.Login; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import java.util.EnumSet; public class TiposApplication extends Application<TiposConfiguration> { public static void main(final String[] args) throws Exception { new TiposApplication().run(args); } @Override public String getName() { return "Tipos"; } @Override public void initialize(final Bootstrap<TiposConfiguration> bootstrap) { // TODO: application initialization } @Override public void run(final TiposConfiguration configuration, final Environment environment) { // TODO: implement application environment.jersey().register( new Login()); environment.jersey().register( new Bets()); environment.jersey().register( new Draws()); final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); } }
[ "jakub.seliga@akademiasovy.sk" ]
jakub.seliga@akademiasovy.sk
d2902f2a85e22ae92dfc5b0a01ea9b3bdbba256f
ff774c9a856a47cd59b94a27c3586260c412751e
/tokenengine-common/src/main/java/com/mchain/tokenengine/service/CoinService.java
f9b8bfd54957f7a5699f20d0e022d3f2a7c42139
[]
no_license
zhangdongle/token-engine
f9637aca5b5d62dcc929a8abaf58c078a8cf6502
95a96d2a274ebfea84b7cf3ff04d8cd4660dccf2
refs/heads/master
2023-03-24T09:20:39.793992
2021-03-15T08:13:55
2021-03-15T08:13:55
347,885,656
0
0
null
null
null
null
UTF-8
Java
false
false
330
java
package com.mchain.tokenengine.service; import com.baomidou.mybatisplus.service.IService; import com.mchain.tokenengine.entity.Coin; /** * <p> * 币种表 服务类 * </p> * * @author koc * @since 2018-09-06 */ public interface CoinService extends IService<Coin> { Coin getByCoinName(String name); }
[ "lezai@sina.cn" ]
lezai@sina.cn
821e0b79f90b46ad1b6184ef85f2a9710244f14f
e418aaef69d8b5e189ac8e1d8e1e0d0eb14462d2
/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/androidx/core/R.java
7fa760b7339f94b60df81be780de21f325cbbbb7
[]
no_license
NowGotAMountain/FragmentExampleV2_homework
389d1b3a41b014d5c8e6e5abe0028242d1ea9026
22af83b0911442bfe08892ced3babd61d4cbe03b
refs/heads/master
2022-11-26T05:51:38.054835
2020-08-03T10:17:18
2020-08-03T10:17:18
284,668,451
0
0
null
null
null
null
UTF-8
Java
false
false
10,444
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 androidx.core; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f020027; public static final int font = 0x7f02007a; public static final int fontProviderAuthority = 0x7f02007c; public static final int fontProviderCerts = 0x7f02007d; public static final int fontProviderFetchStrategy = 0x7f02007e; public static final int fontProviderFetchTimeout = 0x7f02007f; public static final int fontProviderPackage = 0x7f020080; public static final int fontProviderQuery = 0x7f020081; public static final int fontStyle = 0x7f020082; public static final int fontVariationSettings = 0x7f020083; public static final int fontWeight = 0x7f020084; public static final int ttcIndex = 0x7f02013c; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f040040; public static final int notification_icon_bg_color = 0x7f040041; public static final int ripple_material_light = 0x7f04004c; public static final int secondary_text_default_material_light = 0x7f04004e; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f05004d; public static final int compat_button_inset_vertical_material = 0x7f05004e; public static final int compat_button_padding_horizontal_material = 0x7f05004f; public static final int compat_button_padding_vertical_material = 0x7f050050; public static final int compat_control_corner_material = 0x7f050051; public static final int compat_notification_large_icon_max_height = 0x7f050052; public static final int compat_notification_large_icon_max_width = 0x7f050053; public static final int notification_action_icon_size = 0x7f050060; public static final int notification_action_text_size = 0x7f050061; public static final int notification_big_circle_margin = 0x7f050062; public static final int notification_content_margin_start = 0x7f050063; public static final int notification_large_icon_height = 0x7f050064; public static final int notification_large_icon_width = 0x7f050065; public static final int notification_main_column_padding_top = 0x7f050066; public static final int notification_media_narrow_margin = 0x7f050067; public static final int notification_right_icon_size = 0x7f050068; public static final int notification_right_side_padding_top = 0x7f050069; public static final int notification_small_icon_background_padding = 0x7f05006a; public static final int notification_small_icon_size_as_large = 0x7f05006b; public static final int notification_subtext_size = 0x7f05006c; public static final int notification_top_pad = 0x7f05006d; public static final int notification_top_pad_large_text = 0x7f05006e; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f060058; public static final int notification_bg = 0x7f060059; public static final int notification_bg_low = 0x7f06005a; public static final int notification_bg_low_normal = 0x7f06005b; public static final int notification_bg_low_pressed = 0x7f06005c; public static final int notification_bg_normal = 0x7f06005d; public static final int notification_bg_normal_pressed = 0x7f06005e; public static final int notification_icon_background = 0x7f06005f; public static final int notification_template_icon_bg = 0x7f060060; public static final int notification_template_icon_low_bg = 0x7f060061; public static final int notification_tile_bg = 0x7f060062; public static final int notify_panel_notification_icon_bg = 0x7f060063; } public static final class id { private id() {} public static final int action_container = 0x7f07000e; public static final int action_divider = 0x7f070010; public static final int action_image = 0x7f070011; public static final int action_text = 0x7f070017; public static final int actions = 0x7f070018; public static final int async = 0x7f070020; public static final int blocking = 0x7f070023; public static final int chronometer = 0x7f07002c; public static final int forever = 0x7f070041; public static final int icon = 0x7f070049; public static final int icon_group = 0x7f07004a; public static final int info = 0x7f07004f; public static final int italic = 0x7f070051; public static final int line1 = 0x7f070053; public static final int line3 = 0x7f070054; public static final int normal = 0x7f07005e; public static final int notification_background = 0x7f07005f; public static final int notification_main_column = 0x7f070060; public static final int notification_main_column_container = 0x7f070061; public static final int right_icon = 0x7f07006f; public static final int right_side = 0x7f070070; public static final int tag_transition_group = 0x7f070091; public static final int tag_unhandled_key_event_manager = 0x7f070092; public static final int tag_unhandled_key_listeners = 0x7f070093; public static final int text = 0x7f070094; public static final int text2 = 0x7f070095; public static final int time = 0x7f070098; public static final int title = 0x7f070099; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f080004; } public static final class layout { private layout() {} public static final int notification_action = 0x7f09001f; public static final int notification_action_tombstone = 0x7f090020; public static final int notification_template_custom_big = 0x7f090027; public static final int notification_template_icon_group = 0x7f090028; public static final int notification_template_part_chronometer = 0x7f09002c; public static final int notification_template_part_time = 0x7f09002d; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0b0035; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0c00ec; public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00ed; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00ef; public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00f2; public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00f4; public static final int Widget_Compat_NotificationActionContainer = 0x7f0c015d; public static final int Widget_Compat_NotificationActionText = 0x7f0c015e; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f020027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f020081 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f02007a, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f02013c }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "kongha-wm19@student.tarc.edu.my" ]
kongha-wm19@student.tarc.edu.my
c7992f0bad4b44729c5c283a239d68371a7a06f1
9200174e3ba816033815d9c54e7b5d44c30f32f6
/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java
9ece0f55f60d76a70011e74009900afeb0ceb6e9
[ "BSD-3-Clause" ]
permissive
NotBugThisFicha/Unobtainium
f9c059b77af6c85f8612308f56a2b92f32db80cd
708de84c55b01e0deba1f6f505a7b2cea3f0a38b
refs/heads/master
2022-04-04T17:05:00.777549
2018-06-22T14:09:52
2018-06-22T14:09:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
99,628
java
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.SearchManager; import android.app.assist.AssistContent; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.os.SystemClock; import android.support.annotation.CallSuper; import android.util.DisplayMetrics; import android.util.Pair; import android.view.Display; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewStub; import android.view.Window; import android.view.WindowManager; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener; import android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener; import org.chromium.base.ActivityState; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ApplicationStatus; import org.chromium.base.BaseSwitches; import org.chromium.base.Callback; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.DiscardableReferencePool; import org.chromium.base.SysUtils; import org.chromium.base.TraceEvent; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.IntentHandler.IntentHandlerDelegate; import org.chromium.chrome.browser.IntentHandler.TabOpenType; import org.chromium.chrome.browser.appmenu.AppMenu; import org.chromium.chrome.browser.appmenu.AppMenuHandler; import org.chromium.chrome.browser.appmenu.AppMenuObserver; import org.chromium.chrome.browser.appmenu.AppMenuPropertiesDelegate; import org.chromium.chrome.browser.bookmarks.BookmarkModel; import org.chromium.chrome.browser.bookmarks.BookmarkUtils; import org.chromium.chrome.browser.compositor.CompositorViewHolder; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.StateChangeReason; import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.LayoutManager; import org.chromium.chrome.browser.compositor.layouts.SceneChangeObserver; import org.chromium.chrome.browser.compositor.layouts.content.ContentOffsetProvider; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.contextual_suggestions.ContextualSuggestionsCoordinator; import org.chromium.chrome.browser.contextual_suggestions.PageViewTimer; import org.chromium.chrome.browser.contextualsearch.ContextualSearchFieldTrial; import org.chromium.chrome.browser.contextualsearch.ContextualSearchManager; import org.chromium.chrome.browser.contextualsearch.ContextualSearchManager.ContextualSearchTabPromotionDelegate; import org.chromium.chrome.browser.datausage.DataUseTabUIManager; import org.chromium.chrome.browser.device.DeviceClassManager; import org.chromium.chrome.browser.dom_distiller.DomDistillerUIUtils; import org.chromium.chrome.browser.dom_distiller.ReaderModeManager; import org.chromium.chrome.browser.download.DownloadManagerService; import org.chromium.chrome.browser.download.DownloadUtils; import org.chromium.chrome.browser.download.items.OfflineContentAggregatorNotificationBridgeUiFactory; import org.chromium.chrome.browser.firstrun.ForcedSigninProcessor; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.gsa.ContextReporter; import org.chromium.chrome.browser.gsa.GSAAccountChangeListener; import org.chromium.chrome.browser.gsa.GSAState; import org.chromium.chrome.browser.help.HelpAndFeedback; import org.chromium.chrome.browser.history.HistoryManagerUtils; import org.chromium.chrome.browser.infobar.InfoBarContainer; import org.chromium.chrome.browser.init.AsyncInitializationActivity; import org.chromium.chrome.browser.init.ProcessInitializationHandler; import org.chromium.chrome.browser.locale.LocaleManager; import org.chromium.chrome.browser.media.PictureInPicture; import org.chromium.chrome.browser.media.PictureInPictureController; import org.chromium.chrome.browser.metrics.LaunchMetrics; import org.chromium.chrome.browser.metrics.StartupMetrics; import org.chromium.chrome.browser.metrics.UmaSessionStats; import org.chromium.chrome.browser.metrics.WebApkUma; import org.chromium.chrome.browser.modaldialog.AppModalPresenter; import org.chromium.chrome.browser.modaldialog.ModalDialogManager; import org.chromium.chrome.browser.multiwindow.MultiWindowUtils; import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.nfc.BeamController; import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.ntp.NewTabPageUma; import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; import org.chromium.chrome.browser.omaha.UpdateMenuItemHelper; import org.chromium.chrome.browser.page_info.PageInfoPopup; import org.chromium.chrome.browser.partnercustomizations.PartnerBrowserCustomizations; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.PreferencesLauncher; import org.chromium.chrome.browser.printing.TabPrinter; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.share.ShareMenuActionHandler; import org.chromium.chrome.browser.snackbar.BottomContainer; import org.chromium.chrome.browser.snackbar.DataUseSnackbarController; import org.chromium.chrome.browser.snackbar.SnackbarManager; import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarManageable; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.chrome.browser.sync.SyncController; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.AsyncTabParamsManager; import org.chromium.chrome.browser.tabmodel.EmptyTabModel; import org.chromium.chrome.browser.tabmodel.TabCreatorManager; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabObserver; import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.chrome.browser.tabmodel.TabWindowManager; import org.chromium.chrome.browser.toolbar.BottomToolbarController; import org.chromium.chrome.browser.toolbar.Toolbar; import org.chromium.chrome.browser.toolbar.ToolbarControlContainer; import org.chromium.chrome.browser.toolbar.ToolbarManager; import org.chromium.chrome.browser.util.AccessibilityUtil; import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.vr_shell.VrIntentUtils; import org.chromium.chrome.browser.vr_shell.VrShellDelegate; import org.chromium.chrome.browser.webapps.AddToHomescreenManager; import org.chromium.chrome.browser.widget.ControlContainer; import org.chromium.chrome.browser.widget.FadingBackgroundView; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController; import org.chromium.chrome.browser.widget.findinpage.FindToolbarManager; import org.chromium.chrome.browser.widget.textbubble.TextBubble; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.content.browser.ContentVideoView; import org.chromium.content.common.ContentSwitches; import org.chromium.content_public.browser.ContentViewCore; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.SelectionPopupController; import org.chromium.content_public.browser.WebContents; import org.chromium.policy.CombinedPolicyProvider; import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener; import org.chromium.printing.PrintManagerDelegateImpl; import org.chromium.printing.PrintingController; import org.chromium.printing.PrintingControllerImpl; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.base.DeviceFormFactor; import org.chromium.ui.base.PageTransition; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.display.DisplayAndroid; import org.chromium.ui.widget.Toast; import org.chromium.webapk.lib.client.WebApkNavigationClient; import org.chromium.webapk.lib.client.WebApkValidator; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * A {@link AsyncInitializationActivity} that builds and manages a {@link CompositorViewHolder} * and associated classes. */ public abstract class ChromeActivity extends AsyncInitializationActivity implements TabCreatorManager, AccessibilityStateChangeListener, PolicyChangeListener, ContextualSearchTabPromotionDelegate, SnackbarManageable, SceneChangeObserver { /** * Factory which creates the AppMenuHandler. */ public interface AppMenuHandlerFactory { /** * @return AppMenuHandler for the given activity and menu resource id. */ public AppMenuHandler get(Activity activity, AppMenuPropertiesDelegate delegate, int menuResourceId); } /** * No control container to inflate during initialization. */ static final int NO_CONTROL_CONTAINER = -1; /** * No toolbar layout to inflate during initialization. */ static final int NO_TOOLBAR_LAYOUT = -1; private static final int RECORD_MULTI_WINDOW_SCREEN_WIDTH_DELAY_MS = 5000; /** * Timeout in ms for reading PartnerBrowserCustomizations provider. */ private static final int PARTNER_BROWSER_CUSTOMIZATIONS_TIMEOUT_MS = 10000; private static AppMenuHandlerFactory sAppMenuHandlerFactory = (activity, delegate, menuResourceId) -> new AppMenuHandler(activity, delegate, menuResourceId); private TabModelSelector mTabModelSelector; private TabModelSelectorTabObserver mTabModelSelectorTabObserver; private TabCreatorManager.TabCreator mRegularTabCreator; private TabCreatorManager.TabCreator mIncognitoTabCreator; private TabContentManager mTabContentManager; private UmaSessionStats mUmaSessionStats; private ContextReporter mContextReporter; private boolean mPartnerBrowserRefreshNeeded; protected IntentHandler mIntentHandler; /** Set if {@link #postDeferredStartupIfNeeded()} is called before native has loaded. */ private boolean mDeferredStartupQueued; /** Whether or not {@link #postDeferredStartupIfNeeded()} has already successfully run. */ private boolean mDeferredStartupPosted; private boolean mTabModelsInitialized; private boolean mNativeInitialized; private boolean mRemoveWindowBackgroundDone; // The class cannot implement TouchExplorationStateChangeListener, // because it is only available for Build.VERSION_CODES.KITKAT and later. // We have to instantiate the TouchExplorationStateChangeListner object in the code. @SuppressLint("NewApi") private TouchExplorationStateChangeListener mTouchExplorationStateChangeListener; // Observes when sync becomes ready to create the mContextReporter. private ProfileSyncService.SyncStateChangedListener mSyncStateChangedListener; private ChromeFullscreenManager mFullscreenManager; private boolean mCreatedFullscreenManager; // The PictureInPictureController is initialized lazily https://crbug.com/729738. private PictureInPictureController mPictureInPictureController; private CompositorViewHolder mCompositorViewHolder; private InsetObserverView mInsetObserverView; private ContextualSearchManager mContextualSearchManager; protected ReaderModeManager mReaderModeManager; private SnackbarManager mSnackbarManager; private ModalDialogManager mModalDialogManager; private DataUseSnackbarController mDataUseSnackbarController; private AppMenuPropertiesDelegate mAppMenuPropertiesDelegate; private AppMenuHandler mAppMenuHandler; private ToolbarManager mToolbarManager; private FindToolbarManager mFindToolbarManager; private BottomSheetController mBottomSheetController; private BottomToolbarController mBottomToolbarController; private BottomSheet mBottomSheet; private ContextualSuggestionsCoordinator mContextualSuggestionsCoordinator; private FadingBackgroundView mFadingBackgroundView; // Time in ms that it took took us to inflate the initial layout private long mInflateInitialLayoutDurationMs; private int mUiMode; private int mDensityDpi; private int mScreenWidthDp; private Runnable mRecordMultiWindowModeScreenWidthRunnable; private final DiscardableReferencePool mReferencePool = new DiscardableReferencePool(); private AssistStatusHandler mAssistStatusHandler; // A set of views obscuring all tabs. When this set is nonempty, // all tab content will be hidden from the accessibility tree. private Set<View> mViewsObscuringAllTabs = new HashSet<>(); // See enableHardwareAcceleration() private boolean mSetWindowHWA; /** Whether or not a PolicyChangeListener was added. */ private boolean mDidAddPolicyChangeListener; /** Adds TabObserver and TabModelObserver to measure page view times. */ private PageViewTimer mPageViewTimer; /** * @param factory The {@link AppMenuHandlerFactory} for creating {@link #mAppMenuHandler} */ @VisibleForTesting public static void setAppMenuHandlerFactoryForTesting(AppMenuHandlerFactory factory) { sAppMenuHandlerFactory = factory; } @Override protected ActivityWindowAndroid createWindowAndroid() { return new ChromeWindow(this); } @Override public void preInflationStartup() { super.preInflationStartup(); if (VrShellDelegate.bootsToVr()) { // TODO(mthiesse): Remove this once b/78108624 is fixed. This is a workaround for a // platform bug where Chrome crashes on launch for standalone devices if not launched // onto the primary display (There's a virtual display 2D apps are default launched onto // with different display properties). Re-launch with the same intent but to the primary // display. if (DisplayAndroid.getNonMultiDisplay(this).getDisplayId() != Display.DEFAULT_DISPLAY) { finish(); startActivity(getIntent(), ApiCompatibilityUtils.createLaunchDisplayIdActivityOptions( Display.DEFAULT_DISPLAY)); return; } } // We need to explicitly enable VR mode here so that the system doesn't kick us out of VR, // or drop us into the 2D-in-VR rendering mode, while we prepare for VR rendering. if (VrIntentUtils.isVrIntent(getIntent()) || VrIntentUtils.wouldUse2DInVrRenderingMode(this)) { VrShellDelegate.setVrModeEnabled(this, true); } // Force a partner customizations refresh if it has yet to be initialized. This can happen // if Chrome is killed and you refocus a previous activity from Android recents, which does // not go through ChromeLauncherActivity that would have normally triggered this. mPartnerBrowserRefreshNeeded = !PartnerBrowserCustomizations.isInitialized(); ApplicationInitialization.enableFullscreenFlags( getResources(), this, getControlContainerHeightResource()); getWindow().setBackgroundDrawable(getBackgroundDrawable()); mFullscreenManager = createFullscreenManager(); mCreatedFullscreenManager = true; } @SuppressLint("NewApi") @Override public void postInflationStartup() { super.postInflationStartup(); Intent intent = getIntent(); if (intent != null && getSavedInstanceState() == null) { VrShellDelegate.maybeHandleVrIntentPreNative(this, intent); } mSnackbarManager = new SnackbarManager(this, null); mDataUseSnackbarController = new DataUseSnackbarController(this, getSnackbarManager()); mAssistStatusHandler = createAssistStatusHandler(); if (mAssistStatusHandler != null) { if (mTabModelSelector != null) { mAssistStatusHandler.setTabModelSelector(mTabModelSelector); } mAssistStatusHandler.updateAssistState(); } // This check is only applicable for JB since in KK svelte was supported from the start. // See https://crbug.com/826460 for context. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // If a user had ALLOW_LOW_END_DEVICE_UI explicitly set to false then we manually // override SysUtils.isLowEndDevice() with a switch so that they continue to see the // normal UI. This is only the case for grandfathered-in svelte users. We no longer do // so for newer users. if (!ChromePreferenceManager.getInstance().getAllowLowEndDeviceUi()) { CommandLine.getInstance().appendSwitch(BaseSwitches.DISABLE_LOW_END_DEVICE_MODE); } } AccessibilityManager manager = (AccessibilityManager) getBaseContext().getSystemService(Context.ACCESSIBILITY_SERVICE); manager.addAccessibilityStateChangeListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mTouchExplorationStateChangeListener = enabled -> checkAccessibility(); manager.addTouchExplorationStateChangeListener(mTouchExplorationStateChangeListener); } // Make the activity listen to policy change events CombinedPolicyProvider.get().addPolicyChangeListener(this); mDidAddPolicyChangeListener = true; // Set up the animation placeholder to be the SurfaceView. This disables the // SurfaceView's 'hole' clipping during animations that are notified to the window. getWindowAndroid().setAnimationPlaceholderView(mCompositorViewHolder.getCompositorView()); // Inform the WindowAndroid of the keyboard accessory view. getWindowAndroid().setKeyboardAccessoryView( (ViewGroup) findViewById(R.id.keyboard_accessory)); initializeToolbar(); initializeTabModels(); if (!isFinishing() && getFullscreenManager() != null) { getFullscreenManager().initialize( (ControlContainer) findViewById(R.id.control_container), getTabModelSelector(), getControlContainerHeightResource()); } ((BottomContainer) findViewById(R.id.bottom_container)).initialize(mFullscreenManager); mModalDialogManager = createModalDialogManager(); mPageViewTimer = new PageViewTimer(mTabModelSelector); } @Override protected View getViewToBeDrawnBeforeInitializingNative() { View controlContainer = findViewById(R.id.control_container); return controlContainer != null ? controlContainer : super.getViewToBeDrawnBeforeInitializingNative(); } /** * This function builds the {@link CompositorViewHolder}. Subclasses *must* call * super.setContentView() before using {@link #getTabModelSelector()} or * {@link #getCompositorViewHolder()}. */ @Override protected final void setContentView() { final long begin = SystemClock.elapsedRealtime(); TraceEvent.begin("onCreate->setContentView()"); SelectionPopupController.setShouldGetReadbackViewFromWindowAndroid(); enableHardwareAcceleration(); setLowEndTheme(); int controlContainerLayoutId = getControlContainerLayoutId(); WarmupManager warmupManager = WarmupManager.getInstance(); if (warmupManager.hasViewHierarchyWithToolbar(controlContainerLayoutId)) { View placeHolderView = new View(this); setContentView(placeHolderView); ViewGroup contentParent = (ViewGroup) placeHolderView.getParent(); warmupManager.transferViewHierarchyTo(contentParent); contentParent.removeView(placeHolderView); } else { warmupManager.clearViewHierarchy(); // Allow disk access for the content view and toolbar container setup. // On certain android devices this setup sequence results in disk writes outside // of our control, so we have to disable StrictMode to work. See crbug.com/639352. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites(); try { setContentView(R.layout.main); if (controlContainerLayoutId != NO_CONTROL_CONTAINER) { ViewStub toolbarContainerStub = ((ViewStub) findViewById(R.id.control_container_stub)); toolbarContainerStub.setLayoutResource(controlContainerLayoutId); toolbarContainerStub.inflate(); } // It cannot be assumed that the result of toolbarContainerStub.inflate() will be // the control container since it may be wrapped in another view. ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); // Inflate the correct toolbar layout for the device. int toolbarLayoutId = getToolbarLayoutId(); if (toolbarLayoutId != NO_TOOLBAR_LAYOUT && controlContainer != null) { controlContainer.initWithToolbar(toolbarLayoutId); } } finally { StrictMode.setThreadPolicy(oldPolicy); } } TraceEvent.end("onCreate->setContentView()"); mInflateInitialLayoutDurationMs = SystemClock.elapsedRealtime() - begin; // Set the status bar color to black by default. This is an optimization for // Chrome not to draw under status and navigation bars when we use the default // black status bar setStatusBarColor(null, Color.BLACK); ViewGroup rootView = (ViewGroup) getWindow().getDecorView().getRootView(); mCompositorViewHolder = (CompositorViewHolder) findViewById(R.id.compositor_view_holder); mCompositorViewHolder.setRootView(rootView); // Setting fitsSystemWindows to false ensures that the root view doesn't consume the insets. rootView.setFitsSystemWindows(false); // Add a custom view right after the root view that stores the insets to access later. // ContentViewCore needs the insets to determine the portion of the screen obscured by // non-content displaying things such as the OSK. mInsetObserverView = InsetObserverView.create(this); rootView.addView(mInsetObserverView, 0); } @Override public boolean shouldStartGpuProcess() { return true; } /** * Constructs {@link ToolbarManager} and the handler necessary for controlling the menu on the * {@link Toolbar}. Extending classes can override this call to avoid creating the toolbar. */ protected void initializeToolbar() { final View controlContainer = findViewById(R.id.control_container); assert controlContainer != null; ToolbarControlContainer toolbarContainer = (ToolbarControlContainer) controlContainer; mAppMenuPropertiesDelegate = createAppMenuPropertiesDelegate(); mAppMenuHandler = sAppMenuHandlerFactory.get(this, mAppMenuPropertiesDelegate, getAppMenuLayoutId()); Callback<Boolean> urlFocusChangedCallback = hasFocus -> onOmniboxFocusChanged(hasFocus); mToolbarManager = new ToolbarManager(this, toolbarContainer, mAppMenuHandler, mAppMenuPropertiesDelegate, getCompositorViewHolder().getInvalidator(), urlFocusChangedCallback); mFindToolbarManager = new FindToolbarManager( this, mToolbarManager.getActionModeController().getActionModeCallback()); mAppMenuHandler.addObserver(new AppMenuObserver() { @Override public void onMenuVisibilityChanged(boolean isVisible) { if (isVisible && !isInOverviewMode()) { // The app menu badge should be removed the first time the menu is opened. if (mToolbarManager.getToolbar().isShowingAppMenuUpdateBadge()) { mToolbarManager.getToolbar().removeAppMenuUpdateBadge(true); mCompositorViewHolder.requestRender(); } } if (!isVisible) { mAppMenuPropertiesDelegate.onMenuDismissed(); MenuItem updateMenuItem = mAppMenuHandler.getAppMenu().getMenu().findItem( R.id.update_menu_id); if (updateMenuItem != null && updateMenuItem.isVisible()) { UpdateMenuItemHelper.getInstance().onMenuDismissed(); } } } @Override public void onMenuHighlightChanged(boolean highlighting) {} }); } /** * Initialize the {@link TabModelSelector}, {@link TabModel}s, and * {@link org.chromium.chrome.browser.tabmodel.TabCreatorManager.TabCreator} needed by * this activity. */ protected final void initializeTabModels() { if (mTabModelsInitialized) return; mTabModelSelector = createTabModelSelector(); if (mTabModelSelector == null) { assert isFinishing(); mTabModelsInitialized = true; return; } Pair<? extends TabCreator, ? extends TabCreator> tabCreators = createTabCreators(); mRegularTabCreator = tabCreators.first; mIncognitoTabCreator = tabCreators.second; OfflinePageUtils.observeTabModelSelector(this, mTabModelSelector); NewTabPageUma.monitorNTPCreation(mTabModelSelector); if (mTabModelSelectorTabObserver != null) mTabModelSelectorTabObserver.destroy(); mTabModelSelectorTabObserver = new TabModelSelectorTabObserver(mTabModelSelector) { @Override public void didFirstVisuallyNonEmptyPaint(Tab tab) { if (DataUseTabUIManager.checkAndResetDataUseTrackingStarted(tab) && DataUseTabUIManager.shouldShowDataUseStartedUI()) { mDataUseSnackbarController.showDataUseTrackingStartedBar(); } else if (DataUseTabUIManager.shouldShowDataUseEndedUI() && DataUseTabUIManager.shouldShowDataUseEndedSnackbar( getApplicationContext()) && DataUseTabUIManager.checkAndResetDataUseTrackingEnded(tab)) { mDataUseSnackbarController.showDataUseTrackingEndedBar(); } /* // Only alert about data savings once the first paint has happened. It doesn't make // sense to show a snackbar about savings when nothing has been displayed yet. if (DataReductionProxySettings.getInstance().isSnackbarPromoAllowed(tab.getUrl())) { if (mDataReductionPromoSnackbarController == null) { mDataReductionPromoSnackbarController = new DataReductionPromoSnackbarController( getApplicationContext(), getSnackbarManager()); } mDataReductionPromoSnackbarController.maybeShowDataReductionPromoSnackbar( DataReductionProxySettings.getInstance() .getTotalHttpContentLengthSaved()); }*/ } @Override public void onShown(Tab tab) { setStatusBarColor(tab, tab.getThemeColor()); } @Override public void onHidden(Tab tab) { mDataUseSnackbarController.dismissDataUseBar(); } @Override public void onDestroyed(Tab tab) { mDataUseSnackbarController.dismissDataUseBar(); } @Override public void onLoadStopped(Tab tab, boolean toDifferentDocument) { postDeferredStartupIfNeeded(); } @Override public void onPageLoadFinished(Tab tab) { postDeferredStartupIfNeeded(); OfflinePageUtils.showOfflineSnackbarIfNecessary(tab); } @Override public void onCrash(Tab tab, boolean sadTabShown) { postDeferredStartupIfNeeded(); } @Override public void onDidChangeThemeColor(Tab tab, int color) { if (getActivityTab() != tab) return; setStatusBarColor(tab, color); if (getToolbarManager() == null) return; getToolbarManager().updatePrimaryColor(color, true); ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); controlContainer.getToolbarResourceAdapter().invalidate(null); } @Override public void onContentChanged(Tab tab) { if (getBottomSheet() != null) setStatusBarColor(tab, tab.getDefaultThemeColor()); } }; if (mAssistStatusHandler != null) { mAssistStatusHandler.setTabModelSelector(mTabModelSelector); } mTabModelsInitialized = true; } /** * @return The {@link TabModelSelector} owned by this {@link ChromeActivity}. */ protected abstract TabModelSelector createTabModelSelector(); /** * @return The {@link org.chromium.chrome.browser.tabmodel.TabCreatorManager.TabCreator}s owned * by this {@link ChromeActivity}. The first item in the Pair is the normal model tab * creator, and the second is the tab creator for incognito tabs. */ protected abstract Pair<? extends TabCreator, ? extends TabCreator> createTabCreators(); /** * @return {@link ToolbarManager} that belongs to this activity. */ public ToolbarManager getToolbarManager() { return mToolbarManager; } /** * @return {@link FindToolbarManager} that belongs to this activity. */ public FindToolbarManager getFindToolbarManager() { return mFindToolbarManager; } /** * @return The resource id for the menu to use in {@link AppMenu}. Default is R.menu.main_menu. */ protected int getAppMenuLayoutId() { return R.menu.main_menu; } /** * Get the Chrome Home bottom sheet if it exists. * @return The bottom sheet or null. */ @Nullable public BottomSheet getBottomSheet() { return mBottomSheet; } /** * @return The View used to obscure content and bring focus to a foreground view. */ public FadingBackgroundView getFadingBackgroundView() { return mFadingBackgroundView; } /** * @return {@link AppMenuPropertiesDelegate} instance that the {@link AppMenuHandler} * should be using in this activity. */ protected AppMenuPropertiesDelegate createAppMenuPropertiesDelegate() { return new AppMenuPropertiesDelegate(this); } /** * @return The assist handler for this activity. */ protected AssistStatusHandler getAssistStatusHandler() { return mAssistStatusHandler; } /** * @return A newly constructed assist handler for this given activity type. */ protected AssistStatusHandler createAssistStatusHandler() { return new AssistStatusHandler(this); } /** * @return The resource id for the layout to use for {@link ControlContainer}. 0 by default. */ protected int getControlContainerLayoutId() { return NO_CONTROL_CONTAINER; } /** * @return The layout ID for the toolbar to use. */ protected int getToolbarLayoutId() { return NO_TOOLBAR_LAYOUT; } /** * @return Whether contextual search is allowed for this activity or not. */ protected boolean isContextualSearchAllowed() { return true; } @Override public void initializeState() { super.initializeState(); IntentHandler.setTestIntentsEnabled( CommandLine.getInstance().hasSwitch(ContentSwitches.ENABLE_TEST_INTENTS)); mIntentHandler = new IntentHandler(createIntentHandlerDelegate(), getPackageName()); } @Override public void initializeCompositor() { TraceEvent.begin("ChromeActivity:CompositorInitialization"); super.initializeCompositor(); setTabContentManager(new TabContentManager(this, getContentOffsetProvider(), DeviceClassManager.enableSnapshots())); mCompositorViewHolder.onNativeLibraryReady(getWindowAndroid(), getTabContentManager()); if (isContextualSearchAllowed() && ContextualSearchFieldTrial.isEnabled()) { mContextualSearchManager = new ContextualSearchManager(this, this); if (mFindToolbarManager != null) { mContextualSearchManager.setFindToolbarManager(mFindToolbarManager); } } if (ReaderModeManager.isEnabled(this)) { mReaderModeManager = new ReaderModeManager(getTabModelSelector(), this); } TraceEvent.end("ChromeActivity:CompositorInitialization"); } @Override public void onStartWithNative() { assert mNativeInitialized : "onStartWithNative was called before native was initialized."; super.onStartWithNative(); UpdateMenuItemHelper.getInstance().onStart(); ChromeActivitySessionTracker.getInstance().onStartWithNative(); // postDeferredStartupIfNeeded() is called in TabModelSelectorTabObsever#onLoadStopped(), // #onPageLoadFinished() and #onCrash(). If we are not actively loading a tab (e.g. // in Android N multi-instance, which is created by re-parenting an existing tab), // ensure onDeferredStartup() gets called by calling postDeferredStartupIfNeeded() here. if (mDeferredStartupQueued || getActivityTab() == null || !getActivityTab().isLoading()) { postDeferredStartupIfNeeded(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); maybeRemoveWindowBackground(); Tab tab = getActivityTab(); if (hasFocus) { if (tab != null) tab.onActivityShown(); VrShellDelegate.onActivityShown(this); } else { boolean stopped = ApplicationStatus.getStateForActivity(this) == ActivityState.STOPPED; if (stopped) { VrShellDelegate.onActivityHidden(this); if (tab != null) tab.onActivityHidden(); } } } /** * Set device status bar to a given color. * @param tab The tab that is currently showing. * @param color The color that the status bar should be set to. */ protected void setStatusBarColor(@Nullable Tab tab, int color) { boolean useModernDesign = supportsModernDesign() && FeatureUtilities.isChromeModernDesignEnabled(); int statusBarColor = color; boolean supportsDarkStatusIcons = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; View root = getWindow().getDecorView().getRootView(); if (useModernDesign && supportsDarkStatusIcons) { int systemUiVisibility = root.getSystemUiVisibility(); boolean needsDarkStatusBarIcons = !ColorUtils.shouldUseLightForegroundOnBackground(statusBarColor); if (needsDarkStatusBarIcons) { systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else if (!needsDarkStatusBarIcons) { systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } root.setSystemUiVisibility(systemUiVisibility); } else { statusBarColor = (tab != null && tab.isDefaultThemeColor()) ? Color.BLACK : ColorUtils.getDarkenedColorForStatusBar(color); } ApiCompatibilityUtils.setStatusBarColor(getWindow(), statusBarColor); } private void createContextReporterIfNeeded() { if (mContextReporter != null || getActivityTab() == null) return; final SyncController syncController = SyncController.get(this); final ProfileSyncService syncService = ProfileSyncService.get(); if (syncController != null && syncController.isSyncingUrlsWithKeystorePassphrase()) { assert syncService != null; mContextReporter = AppHooks.get().createGsaHelper().getContextReporter(this); if (mSyncStateChangedListener != null) { syncService.removeSyncStateChangedListener(mSyncStateChangedListener); mSyncStateChangedListener = null; } return; } else { ContextReporter.reportSyncStatus(syncService); } if (mSyncStateChangedListener == null && syncService != null) { mSyncStateChangedListener = () -> createContextReporterIfNeeded(); syncService.addSyncStateChangedListener(mSyncStateChangedListener); } } @Override public void onResumeWithNative() { super.onResumeWithNative(); markSessionResume(); RecordUserAction.record("MobileComeToForeground"); if (getActivityTab() != null) { LaunchMetrics.commitLaunchMetrics(getActivityTab().getWebContents()); } for (TabModel model : getTabModelSelector().getModels()) { int count = model.getCount(); for (int i = 0; i < count; ++i) { ContentViewCore cvc = model.getTabAt(i).getActiveContentViewCore(); if (cvc != null) cvc.onResume(); } } FeatureUtilities.setCustomTabVisible(isCustomTab()); FeatureUtilities.setIsInMultiWindowMode( MultiWindowUtils.getInstance().isInMultiWindowMode(this)); if (getActivityTab() != null) { getActivityTab().setPictureInPictureEnabled( PictureInPicture.isEnabled(getApplicationContext())); } if (mPictureInPictureController != null) { mPictureInPictureController.cleanup(this); } VrShellDelegate.maybeRegisterVrEntryHook(this); } @Override protected void onUserLeaveHint() { super.onUserLeaveHint(); if (mPictureInPictureController == null) { mPictureInPictureController = new PictureInPictureController(); } mPictureInPictureController.attemptPictureInPicture(this); } @Override public void onPauseWithNative() { RecordUserAction.record("MobileGoToBackground"); Tab tab = getActivityTab(); if (tab != null) getTabContentManager().cacheTabThumbnail(tab); for (TabModel model : getTabModelSelector().getModels()) { int count = model.getCount(); for (int i = 0; i < count; ++i) { ContentViewCore cvc = model.getTabAt(i).getActiveContentViewCore(); if (cvc != null) cvc.onPause(); } } VrShellDelegate.maybeUnregisterVrEntryHook(this); markSessionEnd(); super.onPauseWithNative(); } @Override public void onStopWithNative() { Tab tab = getActivityTab(); if (!hasWindowFocus()) { VrShellDelegate.onActivityHidden(this); if (tab != null) tab.onActivityHidden(); } if (mAppMenuHandler != null) mAppMenuHandler.hideAppMenu(); if (GSAState.getInstance(this).isGsaAvailable() && !SysUtils.isLowEndDevice()) { GSAAccountChangeListener.getInstance().disconnect(); if (mSyncStateChangedListener != null) { ProfileSyncService syncService = ProfileSyncService.get(); if (syncService != null) { syncService.removeSyncStateChangedListener(mSyncStateChangedListener); } mSyncStateChangedListener = null; } } if (mContextReporter != null) mContextReporter.disable(); super.onStopWithNative(); } @Override protected void onNewIntent(Intent intent) { // This should be called before the call to super so that the needed VR flags are set as // soon as the VR intent is received. VrShellDelegate.maybeHandleVrIntentPreNative(this, intent); super.onNewIntent(intent); } @Override public void onNewIntentWithNative(Intent intent) { if (mPictureInPictureController != null) { mPictureInPictureController.cleanup(this); } super.onNewIntentWithNative(intent); if (mIntentHandler.shouldIgnoreIntent(intent)) return; // We send this intent so that we can enter WebVr presentation mode if needed. This // call doesn't consume the intent because it also has the url that we need to load. VrShellDelegate.onNewIntentWithNative(this, intent); mIntentHandler.onNewIntent(intent); } /** * @return Whether the given activity contains a CustomTab. */ public boolean isCustomTab() { return false; } /** * @return Whether the given activity can show the publisher URL from a trusted CDN. */ public boolean canShowTrustedCdnPublisherUrl() { return false; } /** * Actions that may be run at some point after startup. Place tasks that are not critical to the * startup path here. This method will be called automatically. */ private void onDeferredStartup() { initDeferredStartupForActivity(); ProcessInitializationHandler.getInstance().initializeDeferredStartupTasks(); DeferredStartupHandler.getInstance().queueDeferredTasksOnIdleHandler(); } /** * All deferred startup tasks that require the activity rather than the app should go here. * * Overriding methods should queue tasks on the DeferredStartupHandler before or after calling * super depending on whether the tasks should run before or after these ones. */ @CallSuper protected void initDeferredStartupForActivity() { DeferredStartupHandler.getInstance().addDeferredTask(() -> { if (isActivityDestroyed()) return; BeamController.registerForBeam(ChromeActivity.this, () -> { Tab currentTab = getActivityTab(); if (currentTab == null) return null; if (!currentTab.isUserInteractable()) return null; return currentTab.getUrl(); }); UpdateMenuItemHelper.getInstance().checkForUpdateOnBackgroundThread( ChromeActivity.this); }); final String simpleName = getClass().getSimpleName(); DeferredStartupHandler.getInstance().addDeferredTask(() -> { if (isActivityDestroyed()) return; if (mToolbarManager != null) { RecordHistogram.recordTimesHistogram( "MobileStartup.ToolbarInflationTime." + simpleName, mInflateInitialLayoutDurationMs, TimeUnit.MILLISECONDS); mToolbarManager.onDeferredStartup(getOnCreateTimestampMs(), simpleName); } if (MultiWindowUtils.getInstance().isInMultiWindowMode(ChromeActivity.this)) { onDeferredStartupForMultiWindowMode(); } long intentTimestamp = IntentHandler.getTimestampFromIntent(getIntent()); if (intentTimestamp != -1) { recordIntentToCreationTime(getOnCreateTimestampMs() - intentTimestamp); } }); DeferredStartupHandler.getInstance().addDeferredTask(() -> { if (isActivityDestroyed()) return; ForcedSigninProcessor.checkCanSignIn(ChromeActivity.this); }); // GSA connection is not needed on low-end devices because Icing is disabled. if (!SysUtils.isLowEndDevice()) { if (isActivityDestroyed()) return; DeferredStartupHandler.getInstance().addDeferredTask(() -> { if (!GSAState.getInstance(this).isGsaAvailable()) { ContextReporter.reportStatus(ContextReporter.STATUS_GSA_NOT_AVAILABLE); return; } GSAAccountChangeListener.getInstance().connect(); createContextReporterIfNeeded(); }); } } /** * Actions that may be run at some point after startup for Android N multi-window mode. Should * be called from #onDeferredStartup() if the activity is in multi-window mode. */ protected void onDeferredStartupForMultiWindowMode() { // If the Activity was launched in multi-window mode, record a user action and the screen // width. recordMultiWindowModeChangedUserAction(true); recordMultiWindowModeScreenWidth(); } /** * Records the time it takes from creating an intent for {@link ChromeActivity} to activity * creation, including time spent in the framework. * @param timeMs The time from creating an intent to activity creation. */ @CallSuper protected void recordIntentToCreationTime(long timeMs) { RecordHistogram.recordTimesHistogram( "MobileStartup.IntentToCreationTime", timeMs, TimeUnit.MILLISECONDS); } @Override public void onStart() { if (AsyncTabParamsManager.hasParamsWithTabToReparent()) { mCompositorViewHolder.prepareForTabReparenting(); } super.onStart(); if (mPartnerBrowserRefreshNeeded) { mPartnerBrowserRefreshNeeded = false; PartnerBrowserCustomizations.initializeAsync(getApplicationContext(), PARTNER_BROWSER_CUSTOMIZATIONS_TIMEOUT_MS); PartnerBrowserCustomizations.setOnInitializeAsyncFinished(() -> { if (PartnerBrowserCustomizations.isIncognitoDisabled()) { terminateIncognitoSession(); } }); } if (mCompositorViewHolder != null) mCompositorViewHolder.onStart(); mSnackbarManager.onStart(); // Explicitly call checkAccessibility() so things are initialized correctly when Chrome has // been re-started after closing due to the last tab being closed when homepage is enabled. // See crbug.com/541546. checkAccessibility(); Configuration config = getResources().getConfiguration(); mUiMode = config.uiMode; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { mDensityDpi = config.densityDpi; } else { mDensityDpi = getResources().getDisplayMetrics().densityDpi; } mScreenWidthDp = config.screenWidthDp; } @Override public void onStop() { super.onStop(); // We want to refresh partner browser provider every onStart(). mPartnerBrowserRefreshNeeded = true; if (mCompositorViewHolder != null) mCompositorViewHolder.onStop(); mSnackbarManager.onStop(); } @Override @TargetApi(Build.VERSION_CODES.M) public void onProvideAssistContent(AssistContent outContent) { if (getAssistStatusHandler() == null || !getAssistStatusHandler().isAssistSupported()) { // No information is provided in incognito mode. return; } Tab tab = getActivityTab(); if (tab != null && !isInOverviewMode()) { outContent.setWebUri(Uri.parse(tab.getUrl())); } } @Override public long getOnCreateTimestampMs() { return super.getOnCreateTimestampMs(); } /** * This cannot be overridden in order to preserve destruction order. Override * {@link #onDestroyInternal()} instead to perform clean up tasks. */ @SuppressLint("NewApi") @Override protected final void onDestroy() { if (mPageViewTimer != null) { mPageViewTimer.destroy(); mPageViewTimer = null; } if (mReaderModeManager != null) { mReaderModeManager.destroy(); mReaderModeManager = null; } if (mContextualSearchManager != null) { mContextualSearchManager.destroy(); mContextualSearchManager = null; } if (mTabModelSelectorTabObserver != null) { mTabModelSelectorTabObserver.destroy(); mTabModelSelectorTabObserver = null; } if (mCompositorViewHolder != null) { if (mCompositorViewHolder.getLayoutManager() != null) { mCompositorViewHolder.getLayoutManager().removeSceneChangeObserver(this); } mCompositorViewHolder.shutDown(); mCompositorViewHolder = null; } onDestroyInternal(); if (mToolbarManager != null) { mToolbarManager.destroy(); mToolbarManager = null; } if (mBottomSheet != null) { mBottomSheet.destroy(); mBottomSheet = null; } if (mBottomToolbarController != null) { mBottomToolbarController.destroy(); mBottomToolbarController = null; } if (mContextualSuggestionsCoordinator != null) { mContextualSuggestionsCoordinator.destroy(); mContextualSuggestionsCoordinator = null; } if (mTabModelsInitialized) { TabModelSelector selector = getTabModelSelector(); if (selector != null) selector.destroy(); } if (mDidAddPolicyChangeListener) { CombinedPolicyProvider.get().removePolicyChangeListener(this); mDidAddPolicyChangeListener = false; } if (mTabContentManager != null) { mTabContentManager.destroy(); mTabContentManager = null; } AccessibilityManager manager = (AccessibilityManager) getBaseContext().getSystemService(Context.ACCESSIBILITY_SERVICE); manager.removeAccessibilityStateChangeListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { manager.removeTouchExplorationStateChangeListener(mTouchExplorationStateChangeListener); } super.onDestroy(); } /** * Override this to perform destruction tasks. Note that by the time this is called, the * {@link CompositorViewHolder} will be destroyed, but the {@link WindowAndroid} and * {@link TabModelSelector} will not. * <p> * After returning from this, the {@link TabModelSelector} will be destroyed followed * by the {@link WindowAndroid}. */ protected void onDestroyInternal() { } /** * @return The unified manager for all snackbar related operations. */ @Override public SnackbarManager getSnackbarManager() { return mBottomSheetController != null && mBottomSheetController.getBottomSheet().isSheetOpen() ? mBottomSheetController.getSnackbarManager() : mSnackbarManager; } /** * @return The {@link ModalDialogManager} created for this class. */ protected ModalDialogManager createModalDialogManager() { return new ModalDialogManager(new AppModalPresenter(this), ModalDialogManager.APP_MODAL); } /** * @return The {@link ModalDialogManager} that manages the display of modal dialogs (e.g. * JavaScript dialogs). */ public ModalDialogManager getModalDialogManager() { return mModalDialogManager; } /** * Sets the modal dialog mangaer. */ public void setModalDialogManager(ModalDialogManager modalDialogManager) { mModalDialogManager = modalDialogManager; } protected Drawable getBackgroundDrawable() { return new ColorDrawable( ApiCompatibilityUtils.getColor(getResources(), R.color.light_background_color)); } private void maybeRemoveWindowBackground() { // Only need to do this logic once. if (mRemoveWindowBackgroundDone) return; // Remove the window background only after native init and window getting focus. It's done // after native init because before native init, a fake background gets shown. The window // focus dependency is because doing it earlier can cause drawing bugs, e.g. crbug/673831. if (!mNativeInitialized || !hasWindowFocus()) return; // The window background color is used as the resizing background color in Android N+ // multi-window mode. See crbug.com/602366. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { getWindow().setBackgroundDrawable(new ColorDrawable( ApiCompatibilityUtils.getColor(getResources(), R.color.resizing_background_color))); } else { // Post the removeWindowBackground() call as a separate task, as doing it synchronously // here can cause redrawing glitches. See crbug.com/686662 for an example problem. Handler handler = new Handler(); handler.post(() -> removeWindowBackground()); } mRemoveWindowBackgroundDone = true; } @Override public void finishNativeInitialization() { mNativeInitialized = true; OfflineContentAggregatorNotificationBridgeUiFactory.instance(); maybeRemoveWindowBackground(); DownloadManagerService.getDownloadManagerService().onActivityLaunched(); if (getSavedInstanceState() == null && getIntent() != null) { VrShellDelegate.onNewIntentWithNative(this, getIntent()); } VrShellDelegate.onNativeLibraryAvailable(); super.finishNativeInitialization(); if (FeatureUtilities.isChromeDuplexEnabled()) { ViewGroup coordinator = findViewById(R.id.coordinator); mBottomToolbarController = new BottomToolbarController(mFullscreenManager, mCompositorViewHolder.getResourceManager(), mCompositorViewHolder.getLayoutManager(), coordinator); } if (supportsContextualSuggestionsBottomSheet() && FeatureUtilities.isContextualSuggestionsBottomSheetEnabled(isTablet())) { ViewGroup coordinator = (ViewGroup) findViewById(R.id.coordinator); getLayoutInflater().inflate(R.layout.bottom_sheet, coordinator); mBottomSheet = coordinator.findViewById(R.id.bottom_sheet); mBottomSheet.init(coordinator, this); ((BottomContainer) findViewById(R.id.bottom_container)).setBottomSheet(mBottomSheet); mFadingBackgroundView = (FadingBackgroundView) findViewById(R.id.fading_focus_target); mBottomSheetController = new BottomSheetController(this, getTabModelSelector(), getCompositorViewHolder().getLayoutManager(), mFadingBackgroundView, getContextualSearchManager(), mBottomSheet); mContextualSuggestionsCoordinator = new ContextualSuggestionsCoordinator( this, mBottomSheetController, getTabModelSelector()); } } /** * @return Whether native initialization has been completed for this activity. */ public boolean didFinishNativeInitialization() { return mNativeInitialized; } /** * Called when the accessibility status of this device changes. This might be triggered by * touch exploration or general accessibility status updates. It is an aggregate of two other * accessibility update methods. * * @see #onAccessibilityStateChanged * @see #mTouchExplorationStateChangeListener * @param enabled Whether or not accessibility and touch exploration are currently enabled. */ protected void onAccessibilityModeChanged(boolean enabled) { InfoBarContainer.setIsAllowedToAutoHide(!enabled); if (mToolbarManager != null) mToolbarManager.onAccessibilityStatusChanged(enabled); if (mContextualSearchManager != null) { mContextualSearchManager.onAccessibilityModeChanged(enabled); } if (mContextualSuggestionsCoordinator != null) { mContextualSuggestionsCoordinator.onAccessibilityModeChanged(enabled); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item != null && onMenuOrKeyboardAction(item.getItemId(), true)) { return true; } return super.onOptionsItemSelected(item); } /** * Triggered when the share menu item is selected. * This creates and shows a share intent picker dialog or starts a share intent directly. * @param shareDirectly Whether it should share directly with the activity that was most * recently used to share. * @param isIncognito Whether currentTab is incognito. */ @VisibleForTesting public void onShareMenuItemSelected(final boolean shareDirectly, final boolean isIncognito) { ShareMenuActionHandler.getInstance().onShareMenuItemSelected( this, getActivityTab(), shareDirectly, isIncognito); } /** * @return Whether the activity is in overview mode. */ public boolean isInOverviewMode() { return false; } /** * @return Whether the app menu should be shown. */ public boolean shouldShowAppMenu() { // Do not show the menu if Contextual Search panel is opened. if (mContextualSearchManager != null && mContextualSearchManager.isSearchPanelOpened()) { return false; } // Do not show the menu if we are in find in page view. if (mFindToolbarManager != null && mFindToolbarManager.isShowing() && !isTablet()) { return false; } return true; } /** * Shows the app menu (if possible) for a key press on the keyboard with the correct anchor view * chosen depending on device configuration and the visible menu button to the user. */ protected void showAppMenuForKeyboardEvent() { if (getAppMenuHandler() == null) return; TextBubble.dismissBubbles(); boolean hasPermanentMenuKey = ViewConfiguration.get(this).hasPermanentMenuKey(); getAppMenuHandler().showAppMenu( hasPermanentMenuKey ? null : getToolbarManager().getMenuButton(), false); } /** * Allows Activities that extend ChromeActivity to do additional hiding/showing of menu items. * @param menu Menu that is going to be shown when the menu button is pressed. */ public void prepareMenu(Menu menu) { } protected IntentHandlerDelegate createIntentHandlerDelegate() { return new IntentHandlerDelegate() { @Override public void processWebSearchIntent(String query) { final Intent searchIntent = new Intent(Intent.ACTION_WEB_SEARCH); searchIntent.putExtra(SearchManager.QUERY, query); Callback<Boolean> callback = result -> { if (result != null && result) startActivity(searchIntent); }; LocaleManager.getInstance().showSearchEnginePromoIfNeeded( ChromeActivity.this, callback); } @Override public void processUrlViewIntent(String url, String referer, String headers, TabOpenType tabOpenType, String externalAppId, int tabIdToBringToFront, boolean hasUserGesture, Intent intent) { } }; } /** * @return The resource id that contains how large the browser controls are. */ public int getControlContainerHeightResource() { return R.dimen.control_container_height; } @Override public final void onAccessibilityStateChanged(boolean enabled) { checkAccessibility(); } private void checkAccessibility() { onAccessibilityModeChanged(AccessibilityUtil.isAccessibilityEnabled()); } /** * @return A casted version of {@link #getApplication()}. */ public ChromeApplication getChromeApplication() { return (ChromeApplication) getApplication(); } /** * Add the specified tab to bookmarks or allows to edit the bookmark if the specified tab is * already bookmarked. If a new bookmark is added, a snackbar will be shown. * @param tabToBookmark The tab that needs to be bookmarked. */ public void addOrEditBookmark(final Tab tabToBookmark) { if (tabToBookmark == null || tabToBookmark.isFrozen()) { return; } // Defense in depth against the UI being erroneously enabled. if (!mToolbarManager.getBookmarkBridge().isEditBookmarksEnabled()) { assert false; return; } // Note the use of getUserBookmarkId() over getBookmarkId() here: Managed bookmarks can't be // edited. If the current URL is only bookmarked by managed bookmarks, this will return // INVALID_BOOKMARK_ID, so the code below will fall back on adding a new bookmark instead. // TODO(bauerb): This does not take partner bookmarks into account. final long bookmarkId = tabToBookmark.getUserBookmarkId(); final BookmarkModel bookmarkModel = new BookmarkModel(); bookmarkModel.finishLoadingBookmarkModel(() -> { // Gives up the bookmarking if the tab is being destroyed. if (!tabToBookmark.isClosing() && tabToBookmark.isInitialized()) { // The BookmarkModel will be destroyed by BookmarkUtils#addOrEditBookmark() when // done. BookmarkId newBookmarkId = BookmarkUtils.addOrEditBookmark(bookmarkId, bookmarkModel, tabToBookmark, getSnackbarManager(), ChromeActivity.this, isCustomTab()); // If a new bookmark was created, try to save an offline page for it. if (newBookmarkId != null && newBookmarkId.getId() != bookmarkId) { OfflinePageUtils.saveBookmarkOffline(newBookmarkId, tabToBookmark); } } else { bookmarkModel.destroy(); } }); } /** * @return Whether the tab models have been fully initialized. */ public boolean areTabModelsInitialized() { return mTabModelsInitialized; } /** * {@link TabModelSelector} no longer implements TabModel. Use getTabModelSelector() or * getCurrentTabModel() depending on your needs. * @return The {@link TabModelSelector}, possibly null. */ public TabModelSelector getTabModelSelector() { if (!mTabModelsInitialized) { throw new IllegalStateException( "Attempting to access TabModelSelector before initialization"); } return mTabModelSelector; } /** * Returns the {@link InsetObserverView} that has the current system window * insets information. * @return The {@link InsetObserverView}, possibly null. */ public InsetObserverView getInsetObserverView() { return mInsetObserverView; } @Override public TabCreatorManager.TabCreator getTabCreator(boolean incognito) { if (!mTabModelsInitialized) { throw new IllegalStateException( "Attempting to access TabCreator before initialization"); } return incognito ? mIncognitoTabCreator : mRegularTabCreator; } /** * Convenience method that returns a tab creator for the currently selected {@link TabModel}. * @return A tab creator for the currently selected {@link TabModel}. */ public TabCreatorManager.TabCreator getCurrentTabCreator() { return getTabCreator(getTabModelSelector().isIncognitoSelected()); } /** * Gets the {@link TabContentManager} instance which holds snapshots of the tabs in this model. * @return The thumbnail cache, possibly null. */ public TabContentManager getTabContentManager() { return mTabContentManager; } /** * Sets the {@link TabContentManager} owned by this {@link ChromeActivity}. * @param tabContentManager A {@link TabContentManager} instance. */ protected void setTabContentManager(TabContentManager tabContentManager) { mTabContentManager = tabContentManager; } /** * Gets the current (inner) TabModel. This is a convenience function for * getModelSelector().getCurrentModel(). It is *not* equivalent to the former getModel() * @return Never null, if modelSelector or its field is uninstantiated returns a * {@link EmptyTabModel} singleton */ public TabModel getCurrentTabModel() { TabModelSelector modelSelector = getTabModelSelector(); if (modelSelector == null) return EmptyTabModel.getInstance(); return modelSelector.getCurrentModel(); } /** * Returns the tab being displayed by this ChromeActivity instance. This allows differentiation * between ChromeActivity subclasses that swap between multiple tabs (e.g. ChromeTabbedActivity) * and subclasses that only display one Tab (e.g. FullScreenActivity and DocumentActivity). * * The default implementation grabs the tab currently selected by the TabModel, which may be * null if the Tab does not exist or the system is not initialized. */ public Tab getActivityTab() { return TabModelUtils.getCurrentTab(getCurrentTabModel()); } /** * @return The current ContentViewCore, or null if the tab does not exist or is not showing a * ContentViewCore. */ public ContentViewCore getCurrentContentViewCore() { return TabModelUtils.getCurrentContentViewCore(getCurrentTabModel()); } /** * @return A {@link CompositorViewHolder} instance. */ public CompositorViewHolder getCompositorViewHolder() { return mCompositorViewHolder; } /** * Gets the full screen manager. * @return The fullscreen manager, possibly null */ public ChromeFullscreenManager getFullscreenManager() { if (!mCreatedFullscreenManager) { throw new IllegalStateException( "Attempting to access FullscreenManager before it has been created."); } return mFullscreenManager; } /** * Sets the overlay mode. * Overlay mode means that we are currently using AndroidOverlays to display video, and * that the compositor's surface should support alpha and not be marked as opaque. */ public void setOverlayMode(boolean useOverlayMode) { if (mCompositorViewHolder != null) mCompositorViewHolder.setOverlayMode(useOverlayMode); } /** * @return The content offset provider, may be null. */ public ContentOffsetProvider getContentOffsetProvider() { return mCompositorViewHolder; } /** * @return The {@code ContextualSearchManager} or {@code null} if none; */ public ContextualSearchManager getContextualSearchManager() { return mContextualSearchManager; } /** * @return The {@code ReaderModeManager} or {@code null} if none; */ @VisibleForTesting public ReaderModeManager getReaderModeManager() { return mReaderModeManager; } /** * Create a full-screen manager to be used by this activity. * Note: This is called during {@link #postInflationStartup}, so native code may not have been * initialized, but Android Views will have been. * @return A {@link ChromeFullscreenManager} instance that's been created. */ protected ChromeFullscreenManager createFullscreenManager() { return new ChromeFullscreenManager(this, ChromeFullscreenManager.CONTROLS_POSITION_TOP); } /** * Exits the fullscreen mode, if any. Does nothing if no fullscreen is present. * @return Whether the fullscreen mode is currently showing. */ protected boolean exitFullscreenIfShowing() { ContentVideoView view = ContentVideoView.getContentVideoView(); if (view != null && view.getContext() == this) { view.exitFullscreen(false); return true; } if (getFullscreenManager() != null && getFullscreenManager().getPersistentFullscreenMode()) { getFullscreenManager().setPersistentFullscreenMode(false); return true; } return false; } /** * Initializes the {@link CompositorViewHolder} with the relevant content it needs to properly * show content on the screen. * @param layoutManager A {@link LayoutManager} instance. This class is * responsible for driving all high level screen content and * determines which {@link Layout} is shown when. * @param urlBar The {@link View} representing the URL bar (must be * focusable) or {@code null} if none exists. * @param contentContainer A {@link ViewGroup} that can have content attached by * {@link Layout}s. * @param controlContainer A {@link ControlContainer} instance to draw. */ protected void initializeCompositorContent(LayoutManager layoutManager, View urlBar, ViewGroup contentContainer, ControlContainer controlContainer) { if (mContextualSearchManager != null) { mContextualSearchManager.initialize(contentContainer); mContextualSearchManager.setSearchContentViewDelegate(layoutManager); } layoutManager.addSceneChangeObserver(this); mCompositorViewHolder.setLayoutManager(layoutManager); mCompositorViewHolder.setFocusable(false); mCompositorViewHolder.setControlContainer(controlContainer); mCompositorViewHolder.setFullscreenHandler(getFullscreenManager()); mCompositorViewHolder.setUrlBar(urlBar); mCompositorViewHolder.onFinishNativeInitialization(getTabModelSelector(), this, getTabContentManager(), contentContainer, mContextualSearchManager); if (controlContainer != null && DeviceClassManager.enableToolbarSwipe() && getCompositorViewHolder().getLayoutManager().getTopSwipeHandler() != null) { controlContainer.setSwipeHandler( getCompositorViewHolder().getLayoutManager().getTopSwipeHandler()); } } /** * Called when the back button is pressed. * @return Whether or not the back button was handled. */ protected abstract boolean handleBackPressed(); @Override public void onOrientationChange(int orientation) { if (mToolbarManager != null) mToolbarManager.onOrientationChange(); Tab tab = getActivityTab(); if (tab != null) tab.onOrientationChange(); } /** * Notified when the focus of the omnibox has changed. * * @param hasFocus Whether the omnibox currently has focus. */ protected void onOmniboxFocusChanged(boolean hasFocus) {} @Override public void onConfigurationChanged(Configuration newConfig) { if (mAppMenuHandler != null) mAppMenuHandler.hideAppMenu(); super.onConfigurationChanged(newConfig); // We only handle VR UI mode changes. Any other changes should follow the default behavior // of recreating the activity. if (didChangeNonVrUiMode(mUiMode, newConfig.uiMode)) { recreate(); return; } mUiMode = newConfig.uiMode; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (newConfig.densityDpi != mDensityDpi) { if (!VrShellDelegate.onDensityChanged(mDensityDpi, newConfig.densityDpi)) { recreate(); return; } mDensityDpi = newConfig.densityDpi; } } if (newConfig.screenWidthDp != mScreenWidthDp) { mScreenWidthDp = newConfig.screenWidthDp; final Activity activity = this; if (mRecordMultiWindowModeScreenWidthRunnable != null) { mHandler.removeCallbacks(mRecordMultiWindowModeScreenWidthRunnable); } // When exiting Android N multi-window mode, onConfigurationChanged() gets called before // isInMultiWindowMode() returns false. Delay to avoid recording width when exiting // multi-window mode. This also ensures that we don't record intermediate widths seen // only for a brief period of time. mRecordMultiWindowModeScreenWidthRunnable = () -> { mRecordMultiWindowModeScreenWidthRunnable = null; if (MultiWindowUtils.getInstance().isInMultiWindowMode(activity)) { recordMultiWindowModeScreenWidth(); } }; mHandler.postDelayed(mRecordMultiWindowModeScreenWidthRunnable, RECORD_MULTI_WINDOW_SCREEN_WIDTH_DELAY_MS); } } private static boolean didChangeNonVrUiMode(int oldMode, int newMode) { if (oldMode == newMode) return false; return isInVrUiMode(oldMode) == isInVrUiMode(newMode); } private static boolean isInVrUiMode(int uiMode) { return (uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET; } /** * Called by the system when the activity changes from fullscreen mode to multi-window mode * and visa-versa. * @param isInMultiWindowMode True if the activity is in multi-window mode. */ @Override public void onMultiWindowModeChanged(boolean isInMultiWindowMode) { // If native is not initialized, the multi-window user action will be recorded in // #onDeferredStartupForMultiWindowMode() and FeatureUtilities#setIsInMultiWindowMode() // will be called in #onResumeWithNative(). Both of these methods require native to be // initialized, so do not call here to avoid crashing. See https://crbug.com/797921. if (mNativeInitialized) { recordMultiWindowModeChangedUserAction(isInMultiWindowMode); if (!isInMultiWindowMode && ApplicationStatus.getStateForActivity(this) == ActivityState.RESUMED) { // Start a new UMA session when exiting multi-window mode if the activity is // currently resumed. When entering multi-window Android recents gains focus, so // ChromeActivity will get a call to onPauseWithNative(), ending the current UMA // session. When exiting multi-window, however, if ChromeActivity is resumed it // stays in that state. markSessionEnd(); markSessionResume(); FeatureUtilities.setIsInMultiWindowMode( MultiWindowUtils.getInstance().isInMultiWindowMode(this)); } } VrShellDelegate.onMultiWindowModeChanged(isInMultiWindowMode); super.onMultiWindowModeChanged(isInMultiWindowMode); } /** * Records user actions associated with entering and exiting Android N multi-window mode * @param isInMultiWindowMode True if the activity is in multi-window mode. */ protected void recordMultiWindowModeChangedUserAction(boolean isInMultiWindowMode) { if (isInMultiWindowMode) { RecordUserAction.record("Android.MultiWindowMode.Enter"); } else { RecordUserAction.record("Android.MultiWindowMode.Exit"); } } @Override public final void onBackPressed() { if (mNativeInitialized) RecordUserAction.record("SystemBack"); TextBubble.dismissBubbles(); if (VrShellDelegate.onBackPressed()) return; if (mCompositorViewHolder != null) { LayoutManager layoutManager = mCompositorViewHolder.getLayoutManager(); if (layoutManager != null && layoutManager.onBackPressed()) return; } SelectionPopupController controller = getSelectionPopupController(); if (controller != null && controller.isSelectActionBarShowing()) { controller.clearSelection(); return; } if (mContextualSearchManager != null && mContextualSearchManager.onBackPressed()) return; if (handleBackPressed()) return; super.onBackPressed(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); // The conditions are expressed using ranges to capture intermediate levels possibly added // to the API in the future. if ((level >= TRIM_MEMORY_RUNNING_LOW && level < TRIM_MEMORY_UI_HIDDEN) || level >= TRIM_MEMORY_MODERATE) { mReferencePool.drain(); clearToolbarResourceCache(); } } private ContentViewCore getContentViewCore() { Tab tab = getActivityTab(); if (tab == null) return null; return tab.getContentViewCore(); } private WebContents getWebContents() { Tab tab = getActivityTab(); if (tab == null) return null; return tab.getWebContents(); } private SelectionPopupController getSelectionPopupController() { WebContents webContents = getWebContents(); return webContents != null ? SelectionPopupController.fromWebContents(webContents) : null; } @Override public void createContextualSearchTab(String searchUrl) { Tab currentTab = getActivityTab(); if (currentTab == null) return; TabCreator tabCreator = getTabCreator(currentTab.isIncognito()); if (tabCreator == null) return; tabCreator.createNewTab( new LoadUrlParams(searchUrl, PageTransition.LINK), TabModel.TabLaunchType.FROM_LINK, getActivityTab()); } /** * @return The {@link AppMenuHandler} associated with this activity. */ @VisibleForTesting public AppMenuHandler getAppMenuHandler() { return mAppMenuHandler; } /** * @return The {@link AppMenuPropertiesDelegate} associated with this activity. */ @VisibleForTesting public AppMenuPropertiesDelegate getAppMenuPropertiesDelegate() { return mAppMenuPropertiesDelegate; } /** * Callback after UpdateMenuItemHelper#checkForUpdateOnBackgroundThread is complete. * @param updateAvailable Whether an update is available. */ public void onCheckForUpdate(boolean updateAvailable) { if (UpdateMenuItemHelper.getInstance().shouldShowToolbarBadge(this)) { mToolbarManager.getToolbar().showAppMenuUpdateBadge(); mCompositorViewHolder.requestRender(); } else { mToolbarManager.getToolbar().removeAppMenuUpdateBadge(false); } } /** * Handles menu item selection and keyboard shortcuts. * * @param id The ID of the selected menu item (defined in main_menu.xml) or * keyboard shortcut (defined in values.xml). * @param fromMenu Whether this was triggered from the menu. * @return Whether the action was handled. */ public boolean onMenuOrKeyboardAction(int id, boolean fromMenu) { if (id == R.id.preferences_id) { PreferencesLauncher.launchSettingsPage(this, null); RecordUserAction.record("MobileMenuSettings"); } else if (id == R.id.show_menu) { showAppMenuForKeyboardEvent(); } else if (id == R.id.find_in_page_id) { if (mFindToolbarManager == null) return false; mFindToolbarManager.showToolbar(); if (mContextualSearchManager != null) { getContextualSearchManager().hideContextualSearch(StateChangeReason.UNKNOWN); } if (fromMenu) { RecordUserAction.record("MobileMenuFindInPage"); } else { RecordUserAction.record("MobileShortcutFindInPage"); } return true; } if (id == R.id.update_menu_id) { UpdateMenuItemHelper.getInstance().onMenuItemClicked(this); return true; } final Tab currentTab = getActivityTab(); if (id == R.id.help_id) { String url = currentTab != null ? currentTab.getUrl() : ""; Profile profile = mTabModelSelector.isIncognitoSelected() ? Profile.getLastUsedProfile().getOffTheRecordProfile() : Profile.getLastUsedProfile().getOriginalProfile(); startHelpAndFeedback(url, "MobileMenuFeedback", profile); return true; } // All the code below assumes currentTab is not null, so return early if it is null. if (currentTab == null) { return false; } else if (id == R.id.forward_menu_id) { if (currentTab.canGoForward()) { currentTab.goForward(); RecordUserAction.record("MobileMenuForward"); } } else if (id == R.id.bookmark_this_page_id) { addOrEditBookmark(currentTab); RecordUserAction.record("MobileMenuAddToBookmarks"); } else if (id == R.id.offline_page_id) { DownloadUtils.downloadOfflinePage(this, currentTab); RecordUserAction.record("MobileMenuDownloadPage"); } else if (id == R.id.reload_menu_id) { if (currentTab.isLoading()) { currentTab.stopLoading(); RecordUserAction.record("MobileMenuStop"); } else { currentTab.reload(); RecordUserAction.record("MobileMenuReload"); } } else if (id == R.id.info_menu_id) { PageInfoPopup.show(this, currentTab, null, PageInfoPopup.OPENED_FROM_MENU); } else if (id == R.id.open_history_menu_id) { if (NewTabPage.isNTPUrl(currentTab.getUrl())) { NewTabPageUma.recordAction(NewTabPageUma.ACTION_OPENED_HISTORY_MANAGER); } RecordUserAction.record("MobileMenuHistory"); HistoryManagerUtils.showHistoryManager(this, currentTab); StartupMetrics.getInstance().recordOpenedHistory(); } else if (id == R.id.share_menu_id || id == R.id.direct_share_menu_id) { onShareMenuItemSelected(id == R.id.direct_share_menu_id, getCurrentTabModel().isIncognito()); } else if (id == R.id.print_id) { PrintingController printingController = PrintingControllerImpl.getInstance(); if (printingController != null && !printingController.isBusy() && PrefServiceBridge.getInstance().isPrintingEnabled()) { printingController.startPrint(new TabPrinter(currentTab), new PrintManagerDelegateImpl(this)); RecordUserAction.record("MobileMenuPrint"); } } else if (id == R.id.add_to_homescreen_id) { // Record whether or not we have finished installability checks for this page when the // user clicks the add to homescren menu item. This will let us determine how effective // an on page-load check will be in speeding up WebAPK installation. currentTab.getAppBannerManager().recordMenuItemAddToHomescreen(); AddToHomescreenManager addToHomescreenManager = new AddToHomescreenManager(this, currentTab); addToHomescreenManager.start(); RecordUserAction.record("MobileMenuAddToHomescreen"); } else if (id == R.id.open_webapk_id) { Context context = ContextUtils.getApplicationContext(); String packageName = WebApkValidator.queryWebApkPackage(context, currentTab.getUrl()); Intent launchIntent = WebApkNavigationClient.createLaunchWebApkIntent( packageName, currentTab.getUrl(), false); try { context.startActivity(launchIntent); RecordUserAction.record("MobileMenuOpenWebApk"); WebApkUma.recordWebApkOpenAttempt(WebApkUma.WEBAPK_OPEN_LAUNCH_SUCCESS); } catch (ActivityNotFoundException e) { WebApkUma.recordWebApkOpenAttempt(WebApkUma.WEBAPK_OPEN_ACTIVITY_NOT_FOUND); Toast.makeText(context, R.string.open_webapk_failed, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.request_desktop_site_id || id == R.id.request_desktop_site_check_id) { final boolean reloadOnChange = !currentTab.isNativePage(); final boolean usingDesktopUserAgent = currentTab.getUseDesktopUserAgent(); currentTab.setUseDesktopUserAgent(!usingDesktopUserAgent, reloadOnChange); RecordUserAction.record("MobileMenuRequestDesktopSite"); } else if (id == R.id.reader_mode_prefs_id) { DomDistillerUIUtils.openSettings(currentTab.getWebContents()); } else { return false; } return true; } /** * Shows HelpAndFeedback and records the user action as well. * @param url The URL of the tab the user is currently on. * @param recordAction The user action to record. * @param profile The current {@link Profile}. */ public void startHelpAndFeedback(String url, String recordAction, Profile profile) { // Since reading back the compositor is asynchronous, we need to do the readback // before starting the GoogleHelp. String helpContextId = HelpAndFeedback.getHelpContextIdFromUrl( this, url, getCurrentTabModel().isIncognito()); HelpAndFeedback.getInstance(this).show(this, helpContextId, profile, url); RecordUserAction.record(recordAction); } /** * Add a view to the set of views that obscure the content of all tabs for * accessibility. As long as this set is nonempty, all tabs should be * hidden from the accessibility tree. * * @param view The view that obscures the contents of all tabs. */ public void addViewObscuringAllTabs(View view) { mViewsObscuringAllTabs.add(view); Tab tab = getActivityTab(); if (tab != null) tab.updateAccessibilityVisibility(); } /** * Remove a view that previously obscured the content of all tabs. * * @param view The view that no longer obscures the contents of all tabs. */ public void removeViewObscuringAllTabs(View view) { mViewsObscuringAllTabs.remove(view); Tab tab = getActivityTab(); if (tab != null) tab.updateAccessibilityVisibility(); } /** * Returns whether or not any views obscure all tabs. */ public boolean isViewObscuringAllTabs() { return !mViewsObscuringAllTabs.isEmpty(); } private void markSessionResume() { // Start new session for UMA. if (mUmaSessionStats == null) { mUmaSessionStats = new UmaSessionStats(this); } UmaSessionStats.updateMetricsServiceState(); mUmaSessionStats.startNewSession(getTabModelSelector()); } /** * Mark that the UMA session has ended. */ private void markSessionEnd() { if (mUmaSessionStats == null) { // If you hit this assert, please update crbug.com/172653 on how you got there. assert false; return; } // Record session metrics. mUmaSessionStats.logMultiWindowStats(windowArea(), displayArea(), TabWindowManager.getInstance().getNumberOfAssignedTabModelSelectors()); mUmaSessionStats.logAndEndSession(); } private int windowArea() { Window window = getWindow(); if (window != null) { View view = window.getDecorView(); return view.getWidth() * view.getHeight(); } return -1; } private int displayArea() { if (getResources() != null && getResources().getDisplayMetrics() != null) { DisplayMetrics metrics = getResources().getDisplayMetrics(); return metrics.heightPixels * metrics.widthPixels; } return -1; } protected final void postDeferredStartupIfNeeded() { if (!mNativeInitialized) { // Native hasn't loaded yet. Queue it up for later. mDeferredStartupQueued = true; return; } mDeferredStartupQueued = false; if (!mDeferredStartupPosted) { mDeferredStartupPosted = true; onDeferredStartup(); } } @Override public void terminateIncognitoSession() {} @Override public void onTabSelectionHinted(int tabId) { } @Override public void onSceneChange(Layout layout) { } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); // See enableHardwareAcceleration() if (mSetWindowHWA) { mSetWindowHWA = false; getWindow().setWindowManager( getWindow().getWindowManager(), getWindow().getAttributes().token, getComponentName().flattenToString(), true /* hardwareAccelerated */); } } private boolean shouldDisableHardwareAcceleration() { // Low end devices should disable hardware acceleration for memory gains. if (SysUtils.isLowEndDevice()) return true; // Turning off hardware acceleration reduces crash rates. See http://crbug.com/651918 // GT-S7580 on JDQ39 accounts for 42% of crashes in libPowerStretch.so on dev and beta. if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.MODEL.equals("GT-S7580")) { return true; } // SM-N9005 on JSS15J accounts for 44% of crashes in libPowerStretch.so on stable channel. if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2 && Build.MODEL.equals("SM-N9005")) { return true; } return false; } private void enableHardwareAcceleration() { // HW acceleration is disabled in the manifest and may be re-enabled here. if (!shouldDisableHardwareAcceleration()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); // When HW acceleration is enabled manually for an activity, child windows (e.g. // dialogs) don't inherit HW acceleration state. However, when HW acceleration is // enabled in the manifest, child windows do inherit HW acceleration state. That // looks like a bug, so I filed b/23036374 // // In the meanwhile the workaround is to call // window.setWindowManager(..., hardwareAccelerated=true) // to let the window know that it's HW accelerated. However, since there is no way // to know 'appToken' argument until window's view is attached to the window (!!), // we have to do the workaround in onAttachedToWindow() mSetWindowHWA = true; } } /** @return the theme ID to use. */ public static int getThemeId() { boolean useLowEndTheme = SysUtils.isLowEndDevice() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; return (useLowEndTheme ? R.style.MainTheme_LowEnd : R.style.MainTheme); } /** * Looks up the Chrome activity of the given web contents. This can be null. Should never be * cached, because web contents can change activities, e.g., when user selects "Open in Chrome" * menu item. * * @param webContents The web contents for which to lookup the Chrome activity. * @return Possibly null Chrome activity that should never be cached. */ @Nullable public static ChromeActivity fromWebContents(@Nullable WebContents webContents) { if (webContents == null) return null; if (webContents.isDestroyed()) return null; WindowAndroid window = webContents.getTopLevelNativeWindow(); if (window == null) return null; Activity activity = window.getActivity().get(); if (activity == null) return null; if (!(activity instanceof ChromeActivity)) return null; return (ChromeActivity) activity; } private void setLowEndTheme() { if (getThemeId() == R.style.MainTheme_LowEnd) setTheme(R.style.MainTheme_LowEnd); } /** * Records UMA histograms for the current screen width. Should only be called when the activity * is in Android N multi-window mode. */ protected void recordMultiWindowModeScreenWidth() { if (!isTablet()) return; RecordHistogram.recordBooleanHistogram( "Android.MultiWindowMode.IsTabletScreenWidthBelow600", mScreenWidthDp < DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP); if (mScreenWidthDp < DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP) { RecordHistogram.recordLinearCountHistogram("Android.MultiWindowMode.TabletScreenWidth", mScreenWidthDp, 1, DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP, 50); } } @Override public boolean onActivityResultWithNative(int requestCode, int resultCode, Intent intent) { if (super.onActivityResultWithNative(requestCode, resultCode, intent)) return true; if (VrShellDelegate.onActivityResultWithNative(requestCode, resultCode)) return true; return false; } /** * Called when VR mode is entered using this activity. 2D UI components that steal focus or * draw over VR contents should be hidden in this call. */ public void onEnterVr() {} /** * Called when VR mode using this activity is exited. Any state set for VR should be restored * in this call, including showing 2D UI that was hidden. */ public void onExitVr() {} /** * Whether this Activity supports moving a {@link Tab} to the {@link FullscreenActivity} when it * enters fullscreen. */ public boolean supportsFullscreenActivity() { return false; } /** * @return Whether this Activity supports modern design. */ public boolean supportsModernDesign() { return false; } /** * @return Whether this Activity supports showing contextual suggestions in a bottom sheet. */ public boolean supportsContextualSuggestionsBottomSheet() { return false; } /** * @return the reference pool for this activity. * @deprecated Use {@link ChromeApplication#getReferencePool} instead. */ // TODO(bauerb): Migrate clients to ChromeApplication#getReferencePool. @Deprecated public DiscardableReferencePool getReferencePool() { return mReferencePool; } private void clearToolbarResourceCache() { ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); controlContainer.getToolbarResourceAdapter().dropCachedBitmap(); } @Override public void startActivity(Intent intent) { startActivity(intent, null); } @Override public void startActivity(Intent intent, Bundle options) { if (VrShellDelegate.canLaunch2DIntents() || VrIntentUtils.isVrIntent(intent)) { super.startActivity(intent, options); return; } VrShellDelegate.requestToExitVrAndRunOnSuccess(() -> { if (!VrShellDelegate.canLaunch2DIntents()) { throw new IllegalStateException("Still in VR after having exited VR."); } super.startActivity(intent, options); }); } @Override public void startActivityForResult(Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null); } @Override public void startActivityForResult(Intent intent, int requestCode, Bundle options) { if (VrShellDelegate.canLaunch2DIntents() || VrIntentUtils.isVrIntent(intent)) { super.startActivityForResult(intent, requestCode, options); return; } VrShellDelegate.requestToExitVrAndRunOnSuccess(() -> { if (!VrShellDelegate.canLaunch2DIntents()) { throw new IllegalStateException("Still in VR after having exited VR."); } super.startActivityForResult(intent, requestCode, options); }); } @Override public boolean startActivityIfNeeded(Intent intent, int requestCode) { return startActivityIfNeeded(intent, requestCode, null); } @Override public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options) { // Avoid starting Activities when possible while in VR. if (VrShellDelegate.isInVr() && !VrIntentUtils.isVrIntent(intent)) return false; return super.startActivityIfNeeded(intent, requestCode, options); } /** * If the density of the device changes while Chrome is in the background (not resumed), we * won't have received an onConfigurationChanged yet for this new density. In this case, the * density this Activity thinks it's in, and the actual display density will differ. * @return The density this Activity thinks it's in (the density it was in last time it was in * the resumed state). */ public float getLastActiveDensity() { return mDensityDpi; } @VisibleForTesting public ContextualSuggestionsCoordinator getContextualSuggestionsCoordinatorForTesting() { return mContextualSuggestionsCoordinator; } }
[ "thermatk@thermatk.com" ]
thermatk@thermatk.com
e84b47f565686d77e4e451ce00b4ab1504298552
f065d03dca5b2bb71ac7fef2c476fcbe505a4f9e
/src/main/java/mathModel/manufacturing/Prices.java
7465644ea2522a537745d50244166c9d97446bd2
[]
no_license
vladyslav-kramarenko/project_Simulation
7f5475701c07f5c2338bf1ac633bdd771ba3fd5b
998776e2c8d7fd28a4bac4682f8633a7f761a97e
refs/heads/master
2022-12-15T14:01:28.029493
2017-06-20T08:53:55
2017-06-20T08:53:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,321
java
package mathModel.manufacturing; import mathModel.Statistics; import org.apache.log4j.Logger; public class Prices { private static Logger LOG = Logger.getLogger(Prices.class); static void prices(Statistics coefOutcome, Statistics coefProdPrice, Statistics coefRawPrice, Statistics prodPrice, Statistics rawPrice, Statistics wc) { LOG.debug("Calculate prices"); double value; LOG.debug("coefProdPrice = " + coefProdPrice); LOG.debug("prodPriceValue=prodPrice(0) * multiply(coefProdPrice, i)"); LOG.debug("coefRawPrice = " + coefRawPrice); LOG.debug("rawPriceValue = rawPrice(0) * multiply(coefRawPrice, i)"); for (byte i = 1; i < coefOutcome.size(); i++) { LOG.debug("i = " + i); value = prodPrice.getValue(0) * Multiply.multiply(coefProdPrice, i); LOG.debug("prodPriceValue = " + prodPrice.getValue(0) + " * " + Multiply.multiply(coefProdPrice, i) + " = " + value); prodPrice.add(wc.getYear(i), value); LOG.debug("prodPrice.add(" + wc.getYear(i) + "," + value + ")"); value = rawPrice.getValue(0) * Multiply.multiply(coefRawPrice, i); LOG.debug("rawPriceValue = " + rawPrice.getValue(0) + " * " + Multiply.multiply(coefRawPrice, i) + " = " + value); rawPrice.add(wc.getYear(i), value); LOG.debug("rawPrice.add(" + wc.getYear(i) + "," + value + ")"); } } }
[ "razorvlad1992@gmail.com" ]
razorvlad1992@gmail.com
f8c354ad89cbe0e10764c553ee1f3b7483e06df3
35c23bc154dadf5af29508a285311ad073eec132
/src/main/java/net/programDemo/service/MembersService.java
d6e773939b47dd65d4b49e59278f0d9f6ef0fb86
[]
no_license
lifeBoolean/programDemo
23e1bb167bf7dfdc89c22eed1e8aa847fad63b26
c8f6e1c88e9fafb6e59cb3a652682e1679a7823b
refs/heads/master
2022-12-17T14:39:37.470470
2020-09-23T11:42:40
2020-09-23T11:42:40
289,659,258
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package net.programDemo.service; import net.programDemo.model.MembersVo; public interface MembersService { void memberInsert(MembersVo membersVo) throws Exception; public MembersVo memberLogin(MembersVo membersVo) throws Exception; public void memberModify(MembersVo membersVo) throws Exception; public int memberDelete(MembersVo membersVo) throws Exception; }
[ "lifeboolean@gmail.com" ]
lifeboolean@gmail.com
ef91c8a2509e9c62d65b1a569a5aef75611c6e54
e53daa94a988135b8b1379c2a1e19e25bb045091
/new_application/app/src/main/java/com/example/new_application/adapter/ServerInfoAdapter.java
e642872ee88e8e710175d77974b37539f8708a60
[]
no_license
2020xiaotu/trunk
f90c9bf15c9000a1bb18c7c0a3c0a96d4daf8e68
ba19836c64828c2994e1f0db22fb5d26b4a014f5
refs/heads/master
2023-08-27T08:10:41.709940
2021-10-05T06:27:12
2021-10-05T06:27:12
413,684,673
0
0
null
null
null
null
UTF-8
Java
false
false
681
java
package com.example.new_application.adapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.example.new_application.bean.ServerInfoEntity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class ServerInfoAdapter extends BaseQuickAdapter<ServerInfoEntity, BaseViewHolder> { public ServerInfoAdapter(int layoutResId, @Nullable List<ServerInfoEntity> data) { super(layoutResId, data); } @Override protected void convert(@NotNull BaseViewHolder baseViewHolder, ServerInfoEntity serverInfoEntity) { } }
[ "xiaotu20201016@gmail.com" ]
xiaotu20201016@gmail.com
c47ba0d546384ac5bbb4281d656fa8a1871e0166
10cd391ef94399b623e75eafa45a907aaa8602cd
/app/src/main/java/com/demoproject/custom/CTextView.java
6ccd92963ce645ee8281311c53a1d6d15a2297e5
[]
no_license
GaneshajDivekar/SynerzipDemoProject
672943524f7e85466672985869b482d46b083501
8c74195499e562d0b90f197ff9323bb7e3f414b7
refs/heads/master
2023-01-12T04:28:56.466432
2020-11-04T04:52:03
2020-11-04T04:52:03
302,827,918
0
0
null
null
null
null
UTF-8
Java
false
false
1,161
java
package com.demoproject.custom; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatTextView; import com.demoproject.R; public class CTextView extends AppCompatTextView { public CTextView(Context context) { super(context); init(null); } public CTextView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public CTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } public void init(AttributeSet attrs){ if(attrs!=null){ try{ TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextFont); String font=typedArray.getString(R.styleable.CustomTextFont_fontName); setTypeface(FontCache.getTypeface(getContext(), font)); typedArray.recycle(); }catch (Exception e){ e.printStackTrace(); } }else{ setTypeface(FontCache.getTypeface(getContext())); } } }
[ "softdev5@artiligent.in" ]
softdev5@artiligent.in
6fe1db6734f488d42721a5392a5dd886ac161bce
aed3740053d41f15ad5cdf57084dd297b0766637
/quickcoding_pedometer/src/androidTest/java/com/example/quickcoding_pedometer/ExampleInstrumentedTest.java
ad8715890523c5743b9508f48227daa5c48ea87e
[]
no_license
guswo9496ver2/Android_Mobileprogramming
bd3ecbaa96456026459ef531d0c429749fb01c43
3454d4b1bd3ab677e9c1ac589fbbca7f75f338fa
refs/heads/master
2021-01-12T09:57:57.848721
2016-12-13T01:31:16
2016-12-13T01:31:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.example.quickcoding_pedometer; 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.*; /** * Instrumentation 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() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.quickcoding_pedometer", appContext.getPackageName()); } }
[ "guswo9496@naver.com" ]
guswo9496@naver.com
7974a9f2747823433b603d6e5e3fd5fa6df81da9
ab91bc6461c219a189ea4b90e729e109fef64189
/app/src/main/java/com/ps/myapplication/AboutUsActivity.java
52eccd2105c925c2eeeaa1fe452c451593fd559a
[]
no_license
hsshamloo/NEAR_EAST_HOSPITAL_ANDROID_APP
2af0adf2b87cc21447027eb6a4cc4b1f50804b3b
de4dad9e1bfb93693f4cd6846b9a547dac203858
refs/heads/master
2020-04-24T14:38:28.317348
2019-02-22T08:57:13
2019-02-22T08:57:13
172,023,755
0
0
null
null
null
null
UTF-8
Java
false
false
2,583
java
package com.ps.myapplication; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class AboutUsActivity extends ActionBarActivity { private Toolbar toolbar; ViewPager pager; ViewPagerAdapter adapter; SlidingTabLayout tabs; CharSequence Titles[] = {"About Us", "Events"}; int Numboftabs = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aboutus_activity); toolbar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.tabsScrollColor); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_aboutus_activity, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
[ "h.s.shamloo@gmail.com" ]
h.s.shamloo@gmail.com
c962914e0d6422d188c1a9fcbf5e14b9b98c173c
65981f65e5d1dd676e4b5f48f3b81e1f55ed39ce
/konig-gae-generator/src/test/java/io/konig/gae/datastore/SimpleDaoNamerTest.java
747f0722bb8c1fcd1a363ab3081103159313bad9
[]
no_license
konigio/konig
dd49aa70aa63e6bdeb1161f26cf9fba8020e1bfb
2c093aa94be40ee6a0fa533020f4ef14cecc6f1d
refs/heads/master
2023-08-11T12:12:53.634492
2019-12-02T17:05:03
2019-12-02T17:05:03
48,807,429
4
3
null
2022-12-14T20:21:51
2015-12-30T15:42:21
Java
UTF-8
Java
false
false
1,436
java
package io.konig.gae.datastore; /* * #%L * Konig GAE Generator * %% * Copyright (C) 2015 - 2017 Gregory McFall * %% * 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. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import io.konig.core.NamespaceManager; import io.konig.core.impl.MemoryNamespaceManager; import io.konig.core.vocab.Schema; import io.konig.gae.datastore.SimpleDaoNamer; public class SimpleDaoNamerTest { @Test public void test() { NamespaceManager nsManager = new MemoryNamespaceManager(); nsManager.add("schema", Schema.NAMESPACE); String basePackage = "com.example.gae.datastore"; SimpleDaoNamer namer = new SimpleDaoNamer(basePackage, nsManager); String daoClass = namer.daoName(Schema.Person); assertEquals("com.example.gae.datastore.schema.PersonDao", daoClass); } }
[ "gregory.mcfall@gmail.com" ]
gregory.mcfall@gmail.com
18ba06c773877e68120a2fb37503dc2d67b19606
1d8ff79e8566b7e8d290fce884b74e51608fc187
/task3-Minesweeper/src/main/java/ru/gaidamaka/ui/MinesweeperView.java
c958512ccaf6d3a256e187189f24903a53705683
[]
no_license
Dross0/FocusStart-Projects
c4f30307c509393a61c003d87f232fe545897100
0d83f815586945e1c24f99e519dced136d6c024d
refs/heads/master
2023-02-08T07:33:48.381529
2020-12-27T18:46:38
2020-12-27T18:46:38
324,404,522
0
0
null
null
null
null
UTF-8
Java
false
false
12,806
java
package ru.gaidamaka.ui; import org.jetbrains.annotations.NotNull; import ru.gaidamaka.exception.ImageReadException; import ru.gaidamaka.game.cell.Cell; import ru.gaidamaka.game.cell.CellType; import ru.gaidamaka.highscoretable.HighScoreTable; import ru.gaidamaka.presenter.Presenter; import ru.gaidamaka.ui.gamefield.GameFieldView; import ru.gaidamaka.ui.highscore.HighScoreWindow; import ru.gaidamaka.userevent.*; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class MinesweeperView implements View { private static final String FONT = "Serif"; private static final int MAX_SCORE_FIELD_CHAR_NUMBER = 3; private static final int IMAGE_SIZE = 50; private static final int MAX_FIELD_WIDTH_SIZE = 32; private static final int MAX_FIELD_HEIGHT_SIZE = 32; private static final int MAX_BOMBS_NUMBER_SIZE = 32; private final JFrame mainWindow; private GameFieldView gameFieldView; private List<ImageIcon> nearBombsIcons; private ImageIcon flagIcon; private ImageIcon bombIcon; private ImageIcon closedCellIcon; private ImageIcon newGameConfigIcon; private ImageIcon highScoreWindowIcon; private Presenter presenter; private JLabel scoreLabel; private JLabel flagsLabel; public MinesweeperView(int gameFieldWidth, int gameFieldHeight) { mainWindow = new JFrame(); mainWindow.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); mainWindow.setTitle("Сапёр"); mainWindow.setResizable(false); mainWindow.setLayout(new GridBagLayout()); initScoreBar(); initGameField(gameFieldWidth, gameFieldHeight); initMenu(); try { initIcons(); } catch (ImageReadException e) { showErrorMessage("Технические неполадки: Отсутсвуют необходимые иконки"); throw e; } mainWindow.pack(); mainWindow.setVisible(true); } public void showErrorMessage(@NotNull String errorMessage) { JPanel contentPanel = new JPanel(); JLabel errorMessageLabel = new JLabel(errorMessage); contentPanel.add(errorMessageLabel); JOptionPane.showMessageDialog( mainWindow, contentPanel, "Ошибка", JOptionPane.ERROR_MESSAGE ); closeApp(); } @Override public void showAbout(@NotNull String aboutText) { Objects.requireNonNull(aboutText, "About text cant be null"); JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(new BoxLayout(aboutPanel, BoxLayout.Y_AXIS)); String[] lines = aboutText.split("\n"); for (String line : lines) { aboutPanel.add(new JLabel(line)); } JOptionPane.showMessageDialog( mainWindow, aboutPanel, "Информация о игре", JOptionPane.INFORMATION_MESSAGE ); } private void closeApp() { mainWindow.setVisible(false); mainWindow.dispatchEvent(new WindowEvent(mainWindow, WindowEvent.WINDOW_CLOSING)); } private void initGameField(int gameFieldWidth, int gameFieldHeight) { GridBagConstraints c = new GridBagConstraints(); c.gridy = 1; c.gridwidth = 2; gameFieldView = new GameFieldView(); gameFieldView.setButtonPreferredWidth(IMAGE_SIZE); gameFieldView.setButtonPreferredHeight(IMAGE_SIZE); gameFieldView.reset(gameFieldWidth, gameFieldHeight, this::fireEvent); mainWindow.add(gameFieldView.getGameFieldPanel(), c); } private void initScoreBar() { scoreLabel = new JLabel(); scoreLabel.setFont(new Font(FONT, Font.BOLD, 20)); flagsLabel = new JLabel(); flagsLabel.setFont(new Font(FONT, Font.BOLD, 20)); resetScoreBoard(); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.anchor = GridBagConstraints.WEST; mainWindow.add(scoreLabel, c); c.gridx = 1; c.anchor = GridBagConstraints.EAST; mainWindow.add(flagsLabel, c); } private ImageIcon readImage(String imageName) { URL imageRes = MinesweeperView.class.getClassLoader().getResource(imageName); if (imageRes == null) { throw new ImageReadException("Cant read image from = {" + imageName + "}"); } return new ImageIcon(imageRes); } private ImageIcon readAndResizeImage(String imageName){ Image scaledImage = readImage(imageName) .getImage() .getScaledInstance(IMAGE_SIZE, IMAGE_SIZE, Image.SCALE_DEFAULT); return new ImageIcon(scaledImage); } private void initIcons() { nearBombsIcons = new ArrayList<>(); for (int i = 0; i < 9; i++) { nearBombsIcons.add(readAndResizeImage(i + ".png")); } closedCellIcon = readAndResizeImage("closedCell.png"); bombIcon = readAndResizeImage("bomb.png"); flagIcon = readAndResizeImage("flag.png"); newGameConfigIcon = readImage("newGameSettings.png"); highScoreWindowIcon = readImage("recordDialog.png"); } private void initMenu() { JMenuBar menu = new JMenuBar(); addMenuItem(menu, "Новая игра", new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { newGameStart(); } } }); addMenuItem(menu, "Таблица рекордов", new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { presenter.onEvent(new ShowHighScoreTableEvent()); } } }); addMenuItem(menu, "О игре", new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { presenter.onEvent(new ShowAboutEvent()); } } }); addMenuItem(menu, "Выход", new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { presenter.onEvent(new ExitGameEvent()); closeApp(); } } }); mainWindow.setJMenuBar(menu); } private void addMenuItem(JMenuBar menuBar, String menuItemTitle, MouseAdapter mouseAdapter) { JMenuItem menuItem = new JMenuItem(menuItemTitle); menuItem.addMouseListener(mouseAdapter); menuBar.add(menuItem); } private JSlider createNewGameConfigSlider(int min, int max, int defaultValue, int majorTickSpacing) { JSlider slider = new JSlider(SwingConstants.HORIZONTAL, min, max, defaultValue); slider.setMajorTickSpacing(majorTickSpacing); slider.setMinorTickSpacing(1); slider.setPaintTicks(true); slider.setPaintLabels(true); return slider; } private void newGameStart() { JPanel newGameConfigurationPanel = new JPanel(); newGameConfigurationPanel.setLayout(new BoxLayout(newGameConfigurationPanel, BoxLayout.Y_AXIS)); JLabel fieldWidthLabel = new JLabel("Ширина поля"); JSlider fieldWidthSlider = createNewGameConfigSlider(1, MAX_FIELD_WIDTH_SIZE, 10, 10); newGameConfigurationPanel.add(fieldWidthLabel); newGameConfigurationPanel.add(fieldWidthSlider); JLabel fieldHeightLabel = new JLabel("Высота поля"); JSlider fieldHeightSlider = createNewGameConfigSlider(1, MAX_FIELD_HEIGHT_SIZE, 10, 10); newGameConfigurationPanel.add(fieldHeightLabel); newGameConfigurationPanel.add(fieldHeightSlider); JLabel bombsNumberLabel = new JLabel("Количество бомб"); JSlider bombsNumberSlider = createNewGameConfigSlider(1, MAX_BOMBS_NUMBER_SIZE, 10, 10); newGameConfigurationPanel.add(bombsNumberLabel); newGameConfigurationPanel.add(bombsNumberSlider); showMessageDialog( newGameConfigurationPanel, "Новая игра", newGameConfigIcon ); int fieldWidth = fieldWidthSlider.getValue(); int fieldHeight = fieldHeightSlider.getValue(); int bombsNumber = bombsNumberSlider.getValue(); gameFieldView.reset(fieldWidth, fieldHeight, this::fireEvent); resetScoreBoard(); mainWindow.pack(); presenter.onEvent(new NewGameEvent( fieldWidth, fieldHeight, bombsNumber )); } private void resetScoreBoard() { updateFlagsNumber(0); updateScore(0); } @Override public void drawCell(@NotNull Cell cell) { Objects.requireNonNull(cell, "Cell cant be null"); if (cell.isMarked()) { gameFieldView.updateCell(cell.getX(), cell.getY(), flagIcon); return; } if (cell.isHidden()) { gameFieldView.updateCell(cell.getX(), cell.getY(), closedCellIcon); } else{ if (cell.getType() == CellType.BOMB){ gameFieldView.updateCell(cell.getX(), cell.getY(), bombIcon); } else{ gameFieldView.updateCell(cell.getX(), cell.getY(), nearBombsIcons.get(cell.getNearBombNumber())); } } } @Override public void fireEvent(@NotNull UserEvent event) { presenter.onEvent(Objects.requireNonNull(event, "Event cant be null")); } private void showDialogWithCenterLabel(JLabel label, int gap) { JDialog dialog = new JDialog(); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); JPanel content = new JPanel(); content.setLayout(new BorderLayout(gap, gap)); content.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap)); content.add(label); dialog.add(content); dialog.setVisible(true); dialog.pack(); } @Override public void showLoseScreen() { JLabel loseLabel = new JLabel("Вы проиграли!"); loseLabel.setFont(new Font(FONT, Font.BOLD, 30)); showDialogWithCenterLabel(loseLabel, 30); } @Override public void showWinScreen() { JLabel winLabel = new JLabel("Вы выиграли!"); winLabel.setFont(new Font(FONT, Font.BOLD, 30)); showDialogWithCenterLabel(winLabel, 30); } @Override public void showHighScoreTable(@NotNull HighScoreTable table) { Objects.requireNonNull(table, "Table cant be null"); HighScoreWindow highScoreWindow = new HighScoreWindow(table, new Font(FONT, Font.BOLD, 20)); highScoreWindow.show(); } private String formatScore(int score) { int charsAtScore = String.valueOf(score).length(); return "0".repeat(MAX_SCORE_FIELD_CHAR_NUMBER - charsAtScore) + score; } @Override public void updateScore(int score) { scoreLabel.setText(formatScore(score)); } @Override public void updateFlagsNumber(int flagsNumber) { flagsLabel.setText(String.valueOf(flagsNumber)); } @Override @NotNull public String readPlayerName() { JPanel userNameInputPanel = new JPanel(); userNameInputPanel.setLayout(new BorderLayout()); JTextField userNameInputField = new JTextField(30); userNameInputPanel.add(new JLabel("Ваше имя: "), BorderLayout.LINE_START); userNameInputPanel.add(userNameInputField); do { showMessageDialog( userNameInputPanel, "Вы попали в таблицу рекордов", highScoreWindowIcon ); } while (userNameInputField.getText().isBlank()); return userNameInputField.getText(); } private void showMessageDialog(JPanel panel, String title, ImageIcon image) { JOptionPane.showMessageDialog(mainWindow, panel, title, JOptionPane.QUESTION_MESSAGE, image ); } @Override public void setPresenter(@NotNull Presenter presenter) { this.presenter = Objects.requireNonNull(presenter, "Presenter cant be null"); } }
[ "andrew.gaidamaka@gmail.com" ]
andrew.gaidamaka@gmail.com
ff2af89382854d9215ba1587e952de7056e41628
90183ad77a2a00b800de89bc0430188d782f2898
/app/src/main/java/com/wangshun/ms/activity/TaskManagerSettingActivity.java
349875bb601926d7cb49f640f42770509c483ed8
[]
no_license
WS1009/MobileSafe2
2724376b4b6878db57afd042c792132f55ee92c5
902ca814f497c208acbaee05d424bfaaf9361a2d
refs/heads/master
2021-05-08T21:17:22.381391
2018-01-31T04:36:39
2018-01-31T04:36:40
119,633,894
0
0
null
null
null
null
UTF-8
Java
false
false
2,163
java
package com.wangshun.ms.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import com.wangshun.ms.R; import com.wangshun.ms.service.KillProcessService; import com.wangshun.ms.utils.SharedPreferencesUtils; import com.wangshun.ms.utils.SystemInfoUtils; /** *任务管理器的设置界面 **/ public class TaskManagerSettingActivity extends Activity { private SharedPreferences sp; private CheckBox cb_status_kill_process; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); initUI(); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); if(SystemInfoUtils.isServiceRunning(TaskManagerSettingActivity.this, "com.itheima.mobileguard.services.KillProcessService")){ cb_status_kill_process.setChecked(true); }else{ cb_status_kill_process.setChecked(false); } } private void initUI() { setContentView(R.layout.activity_task_manager_setting); CheckBox cb_status = (CheckBox) findViewById(R.id.cb_status); //设置是否选中 cb_status.setChecked(SharedPreferencesUtils.getBoolean(TaskManagerSettingActivity.this, "is_show_system", false)); cb_status.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SharedPreferencesUtils.saveBoolean(TaskManagerSettingActivity.this, "is_show_system", isChecked); } }); //定时清理进程 cb_status_kill_process = (CheckBox) findViewById(R.id.cb_status_kill_process); final Intent intent = new Intent(this,KillProcessService.class); cb_status_kill_process.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ startService(intent); }else{ stopService(intent); } } }); } }
[ "WANGSHUN611@163.com" ]
WANGSHUN611@163.com
7f158fa657e2ab34cb443a06f0246c23cad9a628
77d288f73e52bd77c565ebe9a503167c77f37b53
/cloud-config-server/src/main/java/com/example/springonedemo/CloudConfigServerApplication.java
802a013313ff48bb93e2c4cf6bec5b3605706524
[]
no_license
Matthew-Dong/springonedemo
8221f4b24f72cc7b5598941c56c3afc836a6b960
132b1e561550c40c9c60783e0ff581c12ab77891
refs/heads/master
2020-03-29T08:32:32.807042
2018-09-17T18:12:42
2018-09-17T18:12:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
426
java
package com.example.springonedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @SpringBootApplication public class CloudConfigServerApplication { public static void main(String[] args) { SpringApplication.run(CloudConfigServerApplication.class, args); } }
[ "yaweiwang@yaweis-MacBook-Pro.local" ]
yaweiwang@yaweis-MacBook-Pro.local
647095b097c37d767412178c676c68b3d767fbe3
12a99ab3fe76e5c7c05609c0e76d1855bd051bbb
/src/main/java/com/alipay/api/domain/NoticeTemplateArgs.java
d255e9b147217a7e3901bd2baebb17558aa99435
[ "Apache-2.0" ]
permissive
WindLee05-17/alipay-sdk-java-all
ce2415cfab2416d2e0ae67c625b6a000231a8cfc
19ccb203268316b346ead9c36ff8aa5f1eac6c77
refs/heads/master
2022-11-30T18:42:42.077288
2020-08-17T05:57:47
2020-08-17T05:57:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
660
java
package com.alipay.api.domain; import java.util.Date; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 通知内容模板 * * @author auto create * @since 1.0, 2019-01-03 10:33:05 */ public class NoticeTemplateArgs extends AlipayObject { private static final long serialVersionUID = 1175121918517641389L; /** * 课程开始时间 */ @ApiField("course_start_time") private Date courseStartTime; public Date getCourseStartTime() { return this.courseStartTime; } public void setCourseStartTime(Date courseStartTime) { this.courseStartTime = courseStartTime; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
0235a5dd1cd60f5357ec853357f3100230413193
af870b9d500e6fd33fea9b3e113360865a663dc4
/regulatory_center/src/main/java/com/fotic/management/trade/providers/SubmitTradeProvider.java
b1368b58ddddc31bb763eb93e6cfdcb74421ef97
[]
no_license
dengGQ/springcloud-simple-demo
a7a3e8d3ea398fdd50ac3626137aace66dc95b20
5db15a8c9294708c670243892f75f14f0a124a71
refs/heads/master
2022-12-27T23:25:43.391648
2020-01-13T03:58:46
2020-01-13T03:58:46
189,195,731
0
1
null
2022-12-16T11:54:03
2019-05-29T09:37:58
JavaScript
UTF-8
Java
false
false
2,905
java
package com.fotic.management.trade.providers; import java.text.MessageFormat; import java.util.List; import java.util.Map; import org.apache.ibatis.jdbc.SQL; import com.fotic.common.util.PubMethod; import com.fotic.management.trade.entity.SubmitTrade; @SuppressWarnings("unchecked") public class SubmitTradeProvider { public String execCsvFileSql(Map<String, Object> map) { List<SubmitTrade> list = (List<SubmitTrade>) map.get("list"); StringBuilder sb = new StringBuilder(); sb.append("INSERT ALL "); MessageFormat mf = new MessageFormat( "(" + "#'{'list[{0}].name}, #'{'list[{0}].certtype}, #'{'list[{0}].certno},#'{'list[{0}].deptcode}, #'{'list[{0}].generaltype}, #'{'list[{0}].type}, " + "#'{'list[{0}].account}, #'{'list[{0}].tradeid},#'{'list[{0}].areacode}, #'{'list[{0}].dateopened}, #'{'list[{0}].dateclosed}, #'{'list[{0}].currency}, " + "#'{'list[{0}].creditlimit}, #'{'list[{0}].shareaccount},#'{'list[{0}].maxdebt}, #'{'list[{0}].guaranteeway}, #'{'list[{0}].termsfreq}, #'{'list[{0}].monthduration}, " + "#'{'list[{0}].monthunpaid}, #'{'list[{0}].billingdate},#'{'list[{0}].recentpaydate}, #'{'list[{0}].scheduledamount}, #'{'list[{0}].actualpayamount}, #'{'list[{0}].balance}, " + "#'{'list[{0}].curtermspastdue}, #'{'list[{0}].amountpastdue},#'{'list[{0}].amountpastdue30}, #'{'list[{0}].amountpastdue60}, #'{'list[{0}].amountpastdue90}, #'{'list[{0}].apastdue180}, " + "#'{'list[{0}].termspastdue}, #'{'list[{0}].maxtermspastdue},#'{'list[{0}].class5stat}, #'{'list[{0}].accountstat}, #'{'list[{0}].paystat24month}, " + "#'{'list[{0}].dataStatus}, #'{'list[{0}].insertDttm}, #'{'list[{0}].dataSrc}) "); for (int i = 0; i < list.size(); i++) { sb.append( "INTO RHZX_SUBMT_PER_TRADE (NAME,CERTTYPE,CERTNO,DEPTCODE,GENERALTYPE,TYPE," + "ACCOUNT,TRADEID,AREACODE,DATEOPENED,DATECLOSED,CURRENCY," + "CREDITLIMIT,SHAREACCOUNT,MAXDEBT,GUARANTEEWAY,TERMSFREQ,MONTHDURATION," + "MONTHUNPAID,BILLINGDATE,RECENTPAYDATE,SCHEDULEDAMOUNT,ACTUALPAYAMOUNT,BALANCE," + "CURTERMSPASTDUE,AMOUNTPASTDUE,AMOUNTPASTDUE30,AMOUNTPASTDUE60,AMOUNTPASTDUE90,APASTDUE180," + "TERMSPASTDUE,MAXTERMSPASTDUE,CLASS5STAT,ACCOUNTSTAT,PAYSTAT24MONTH," + "DATA_STATUS,INSERT_DTTM,DATA_SRC) VALUES "); sb.append(mf.format(new Object[] { i })); } sb.append(" SELECT 1 FROM dual"); return sb.toString(); } public String queryList(String certno,String dataStatus, String dataSrc) { String sql = new SQL() { { SELECT(" * "); FROM(" RHZX_SUBMT_PER_TRADE"); if(!PubMethod.isEmpty(certno)) { WHERE(" CERTNO ='"+certno+"'"); } if(!PubMethod.isEmpty(dataStatus) && !"0".equals(dataStatus)) { WHERE(" DATA_STATUS ="+dataStatus); } WHERE(" data_src ="+dataSrc); ORDER_BY(" ACCOUNT desc"); } }.toString(); return sql; } }
[ "565820745@qq.com" ]
565820745@qq.com
a40de8ec2a16faa4aa90e0a6d4150e210c7da27c
f7364d80f406f701f475188e6399fd37ae3c356a
/app/src/main/java/com/example/puza/mvpapiimplementation/modules/main/activities/reviewAndCall/mvp/ReviewAndCallModel.java
91423877ab5a9ea72725de3ab6b74efbd827e305
[]
no_license
puja110/Ghumgham
bd7e77947667e824aab0e70e449bf725c6e4e24a
df4691529e677aebd64c8b9eded6c4668c56c2f5
refs/heads/master
2020-05-04T21:40:12.288745
2019-04-04T12:49:47
2019-04-04T12:49:47
179,484,485
1
0
null
null
null
null
UTF-8
Java
false
false
819
java
package com.example.puza.mvpapiimplementation.modules.main.activities.reviewAndCall.mvp; import com.example.puza.mvpapiimplementation.application.network.AppNetwork; import com.example.puza.mvpapiimplementation.application.network.placeReviewsDao.PlaceReviews; import com.example.puza.mvpapiimplementation.helper.PreferencesManager; import io.reactivex.Observable; public class ReviewAndCallModel { PreferencesManager preferencesManager; AppNetwork appNetwork; public ReviewAndCallModel(PreferencesManager preferencesManager, AppNetwork appNetwork) { this.preferencesManager = preferencesManager; this.appNetwork = appNetwork; } /*get the place review */ public Observable<PlaceReviews> getPlaceReviews(String url) { return appNetwork.getPlaceReviews(url); } }
[ "csta.puja@gmail.com" ]
csta.puja@gmail.com
436eee05c9958ee4ab5c8f3506d41acfb4ce6e6c
0f6b23808498fafcf0393fef16e3711680b70efc
/fmv-mymedia/src/main/java/org/fagu/fmv/mymedia/classify/ClassifierFactory.java
3d557c3120bc074163826ec12805e7d64a5cfd5e
[]
no_license
f-agu/fmv
cedfea92b1e55e4e10e67b25716daab4ac02ef39
feda060aac3ec0beadf21e18be3858b030e97559
refs/heads/master
2023-07-09T21:59:51.464936
2023-07-05T11:59:23
2023-07-05T11:59:23
79,101,013
4
0
null
2022-12-14T11:08:04
2017-01-16T09:07:23
Java
UTF-8
Java
false
false
1,009
java
package org.fagu.fmv.mymedia.classify; /* * #%L * fmv-mymedia * %% * Copyright (C) 2014 - 2015 fagu * %% * 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. * #L% */ import java.io.File; import java.io.IOException; import org.fagu.fmv.media.Media; import org.fagu.fmv.utils.file.FileFinder; /** * @author f.agu */ public interface ClassifierFactory<F extends FileFinder<M>, M extends Media> { String getTitle(); Classifier<F, M> create(F finder, File destFolder) throws IOException; }
[ "fagu@oodrive.fr" ]
fagu@oodrive.fr
2ca16296e7eb7d28f50d1f1ccc1ce49d9312ef8a
b509baa681862a9191dc0eb0676a76cb83679817
/framework/config/src/main/java/com/minlia/cloud/framework/config/Constants.java
bbbddfc055a5903da2dc947f5cb0cd84aa7f944e
[ "Apache-2.0" ]
permissive
minlia/cloud
bbfd5af1484cedaa5adebf11c14fea428efeb0bc
8e6969e743216fc17eb93dd3fdf392d8443cd7bb
refs/heads/master
2021-01-10T06:42:49.524349
2017-08-21T15:13:28
2017-08-21T15:13:28
46,135,585
11
8
null
null
null
null
UTF-8
Java
false
false
1,458
java
/** * Copyright (C) 2004-2015 http://oss.minlia.com/license/framework/2015 * * 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.mycompany.myapp.config; // ///** // * Application constants. // */ //public final class Constants { // // // Spring profile for development, production and "fast", see http://jhipster.github.io/profiles.html // public static final String SPRING_PROFILE_DEVELOPMENT = "dev"; // public static final String SPRING_PROFILE_PRODUCTION = "prod"; // public static final String SPRING_PROFILE_FAST = "fast"; // // Spring profile used when deploying with Spring Cloud (used when deploying to CloudFoundry) // public static final String SPRING_PROFILE_CLOUD = "cloud"; // // Spring profile used when deploying to Heroku // public static final String SPRING_PROFILE_HEROKU = "heroku"; // // public static final String SYSTEM_ACCOUNT = "system"; // // private Constants() { // } //}
[ "minliacom@gmail.com" ]
minliacom@gmail.com
61f6e08bf2126d92d74f868b45925a336237f735
2cc3f62365b1e0eca6f196e93ab55eb296dac97e
/ssm/src/main/java/com/my/ssm/demo/service/IUserService.java
e7a811bead48399a8ac89a5aca7ed5c4824a2624
[]
no_license
zsxneil/ssm
a8a02a0d67ed89629b8e56ef09aef5528b64ef9c
3534432428e77efe51b39a2a30f1883258dc61e7
refs/heads/master
2021-01-19T04:54:55.331164
2017-10-13T09:38:18
2017-10-13T09:38:18
87,402,510
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
package com.my.ssm.demo.service; import com.github.pagehelper.PageInfo; import com.my.ssm.demo.model.User; public interface IUserService { User getUserById(int userId); int saveUser(User user); PageInfo<User> findUserListByName(String name); }
[ "zsxneil@hotmail.com" ]
zsxneil@hotmail.com
b1f94dc86be746bde3413fd92e0707b8e7f7da28
efa7935f77f5368e655c072b236d598059badcff
/src/com/sammyun/plugin/alipayDual/AlipayDualPlugin.java
e6f7a62bbbcfc1fbc21b918e5affef82b9f9963b
[]
no_license
ma-xu/Library
c1404f4f5e909be3e5b56f9884355e431c40f51b
766744898745f8fad31766cafae9fd4db0318534
refs/heads/master
2022-02-23T13:34:47.439654
2016-06-03T11:27:21
2016-06-03T11:27:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,109
java
/* * Copyright 2012-2014 sammyun.com.cn. All rights reserved. * Support: http://www.sammyun.com.cn * License: http://www.sammyun.com.cn/license */ package com.sammyun.plugin.alipayDual; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import com.sammyun.Setting; import com.sammyun.entity.Payment; import com.sammyun.entity.PluginConfig; import com.sammyun.plugin.PaymentPlugin; import com.sammyun.util.SettingUtils; /** * Plugin - 支付宝(双接口) * */ @Component("alipayDualPlugin") public class AlipayDualPlugin extends PaymentPlugin { @Override public String getName() { return "支付宝(双接口)"; } @Override public String getVersion() { return "1.0"; } @Override public String getAuthor() { return "Sencloud"; } @Override public String getSiteUrl() { return "http://www.sammyun.com.cn"; } @Override public String getInstallUrl() { return "alipay_dual/install.ct"; } @Override public String getUninstallUrl() { return "alipay_dual/uninstall.ct"; } @Override public String getSettingUrl() { return "alipay_dual/setting.ct"; } @Override public String getRequestUrl() { return "https://mapi.alipay.com/gateway.do"; } @Override public RequestMethod getRequestMethod() { return RequestMethod.get; } @Override public String getRequestCharset() { return "UTF-8"; } @Override public Map<String, Object> getParameterMap(String sn, String description, HttpServletRequest request) { Setting setting = SettingUtils.get(); PluginConfig pluginConfig = getPluginConfig(); Payment payment = getPayment(sn); Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("service", "trade_create_by_buyer"); parameterMap.put("partner", pluginConfig.getAttribute("partner")); parameterMap.put("_input_charset", "utf-8"); parameterMap.put("sign_type", "MD5"); parameterMap.put("return_url", getNotifyUrl(sn, NotifyMethod.sync)); parameterMap.put("notify_url", getNotifyUrl(sn, NotifyMethod.async)); parameterMap.put("out_trade_no", sn); parameterMap.put("subject", StringUtils.abbreviate(description.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 60)); parameterMap.put("body", StringUtils.abbreviate(description.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 600)); parameterMap.put("payment_type", "1"); parameterMap.put("logistics_type", "EXPRESS"); parameterMap.put("logistics_fee", "0"); parameterMap.put("logistics_payment", "SELLER_PAY"); parameterMap.put("price", payment.getAmount().setScale(2).toString()); parameterMap.put("quantity", "1"); parameterMap.put("seller_id", pluginConfig.getAttribute("partner")); parameterMap.put("total_fee", payment.getAmount().setScale(2).toString()); parameterMap.put("show_url", setting.getSiteUrl()); parameterMap.put("paymethod", "directPay"); parameterMap.put("exter_invoke_ip", request.getLocalAddr()); parameterMap.put("extra_common_param", "preschoolEdu"); parameterMap.put("sign", generateSign(parameterMap)); return parameterMap; } @Override public boolean verifyNotify(String sn, NotifyMethod notifyMethod, HttpServletRequest request) { PluginConfig pluginConfig = getPluginConfig(); Payment payment = getPayment(sn); if (generateSign(request.getParameterMap()).equals(request.getParameter("sign")) && pluginConfig.getAttribute("partner").equals(request.getParameter("seller_id")) && sn.equals(request.getParameter("out_trade_no")) && ("WAIT_SELLER_SEND_GOODS".equals(request.getParameter("trade_status")) || "TRADE_SUCCESS".equals(request.getParameter("trade_status")) || "TRADE_FINISHED".equals(request.getParameter("trade_status"))) && payment.getAmount().compareTo(new BigDecimal(request.getParameter("total_fee"))) == 0) { Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("service", "notify_verify"); parameterMap.put("partner", pluginConfig.getAttribute("partner")); parameterMap.put("notify_id", request.getParameter("notify_id")); if ("true".equals(post("https://mapi.alipay.com/gateway.do", parameterMap))) { return true; } } return false; } @Override public boolean verifyMobileNotify(String sn, NotifyMethod notifyMethod, HttpServletRequest request) { // TODO Auto-generated method stub return false; } @Override public String getNotifyMessage(String sn, NotifyMethod notifyMethod, HttpServletRequest request) { if (notifyMethod == NotifyMethod.async) { return "success"; } return null; } @Override public Integer getTimeout() { return 21600; } /** * 生成签名 * * @param parameterMap 参数 * @return 签名 */ private String generateSign(Map<String, ?> parameterMap) { PluginConfig pluginConfig = getPluginConfig(); return DigestUtils.md5Hex(joinKeyValue(new TreeMap<String, Object>(parameterMap), null, pluginConfig.getAttribute("key"), "&", true, "sign_type", "sign")); } }
[ "melody@maxudeMacBook-Pro.local" ]
melody@maxudeMacBook-Pro.local
e85d71650af54f0988c74600034ceaa80f698e32
9fe800087ef8cc6e5b17fa00f944993b12696639
/batik-svggen/src/main/java/org/apache/batik/svggen/font/table/Coverage.java
e527b12c9f8c0d1e57d75bba5abdbeb9e3ef5616
[ "Apache-2.0" ]
permissive
balabit-deps/balabit-os-7-batik
14b80a316321cbd2bc29b79a1754cc4099ce10a2
652608f9d210de2d918d6fb2146b84c0cc771842
refs/heads/master
2023-08-09T03:24:18.809678
2023-05-22T20:34:34
2023-05-27T08:21:21
158,242,898
0
0
Apache-2.0
2023-07-20T04:18:04
2018-11-19T15:03:51
Java
UTF-8
Java
false
false
1,688
java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.svggen.font.table; import java.io.IOException; import java.io.RandomAccessFile; /** * * @author <a href="mailto:david@steadystate.co.uk">David Schweinsberg</a> * @version $Id: Coverage.java 1733416 2016-03-03 07:07:13Z gadams $ */ public abstract class Coverage { public abstract int getFormat(); /** * @param glyphId The ID of the glyph to find. * @return The index of the glyph within the coverage, or -1 if the glyph * can't be found. */ public abstract int findGlyph(int glyphId); protected static Coverage read(RandomAccessFile raf) throws IOException { Coverage c = null; int format = raf.readUnsignedShort(); if (format == 1) { c = new CoverageFormat1(raf); } else if (format == 2) { c = new CoverageFormat2(raf); } return c; } }
[ "testbot@balabit.com" ]
testbot@balabit.com
1cfeda978e6c6aa4169e77ec5148409ce172d066
4a02836c2e4b96c150c5ba6814ffed710180fd77
/common/src/main/java/com/example/common/pattern/creationalPattern/simpleFactory/FactoryPatternDemo.java
28adc2d2262ff15c94b41a1866fcb313c36df0e0
[]
no_license
shanshuaiqi/JavaSE
8c0a7752eae41b977c9a5ceb33ead2d034db019a
a8448613fd039cafe9d2f58a1fb4e1cce1cc07ba
refs/heads/master
2022-07-07T00:23:30.664416
2019-11-19T09:23:26
2019-11-19T09:23:26
216,462,174
3
0
null
2022-06-21T02:15:59
2019-10-21T02:34:50
CSS
UTF-8
Java
false
false
2,911
java
package com.example.common.pattern.creationalPattern.simpleFactory; /** * 使用该工厂,通过传递类型信息来获取实体类的对象。 * * @author ssq * @date 2019-11-08 下午 2:42 */ public class FactoryPatternDemo { // 意图:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。 // // 主要解决:主要解决接口选择的问题。 // // 何时使用:我们明确地计划不同条件下创建不同实例时。 // // 如何解决:让其子类实现工厂接口,返回的也是一个抽象的产品。 // // 关键代码:创建过程在其子类执行。 // // 应用实例: 1、您需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个汽车里面的具体实现。 // 2、Hibernate 换数据库只需换方言和驱动就可以。 // // 优点: // 1、一个调用者想创建一个对象,只要知道其名称就可以了。 // 2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。 // 3、屏蔽产品的具体实现,调用者只关心产品的接口。 // // 缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度, // 同时也增加了系统具体类的依赖。这并不是什么好事。 // // 使用场景: 1、日志记录器:记录可能记录到本地硬盘、系统事件、远程服务器等,用户可以选择记录日志到什么地方。 // 2、数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。 // 3、设计一个连接服务器的框架,需要三个协议,"POP3"、"IMAP"、"HTTP",可以把这三个作为产品类,共同实现一个接口。 // // 注意事项:作为一种创建类模式,在任何需要生成复杂对象的地方,都可以使用工厂方法模式。 // 有一点需要注意的地方就是复杂对象适合使用工厂模式,而简单对象,特别是只需要通过 new 就可以完成创建的对象,无需使用工厂模式。 // 如果使用工厂模式,就需要引入一个工厂类,会增加系统的复杂度。 public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //获取 Circle 的对象,并调用它的 draw 方法 Shape shape1 = shapeFactory.getShape("CIRCLE"); //调用 Circle 的 draw 方法 shape1.draw(); //获取 Rectangle 的对象,并调用它的 draw 方法 Shape shape2 = shapeFactory.getShape("RECTANGLE"); //调用 Rectangle 的 draw 方法 shape2.draw(); //获取 Square 的对象,并调用它的 draw 方法 Shape shape3 = shapeFactory.getShape("SQUARE"); //调用 Square 的 draw 方法 shape3.draw(); } }
[ "34259256+shanshuaiqi@users.noreply.github.com" ]
34259256+shanshuaiqi@users.noreply.github.com
380656fde1091b42fd229687a979a54cb4645e75
51166ec08de08954e77bf118c1d54bd5e6210bf3
/Jpa_test02/src/main/java/cn/hdj/domain/Role.java
ad5f4a21c2c7c2ff07561893e252c3e2b99dedd8
[]
no_license
xiachuang/myJavaStudy
84f080b3a802c11338316672b2b13616bd338293
4bafe057cdc6df5552ce381e29dbcbfed7211cca
refs/heads/master
2022-12-14T16:41:13.194772
2020-09-20T17:15:46
2020-09-20T17:15:46
297,125,234
0
0
null
null
null
null
UTF-8
Java
false
false
1,539
java
package cn.hdj.domain; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "role") public class Role implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "role_id") private Integer roleId; @Column(name = "role_name") private String roleName; @Column(name = "role_level") private String roleLevel; @ManyToMany(mappedBy = "roles",cascade = CascadeType.PERSIST) @NotFound(action= NotFoundAction.IGNORE) private Set<User> users=new HashSet<>(); public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleLevel() { return roleLevel; } public void setRoleLevel(String roleLevel) { this.roleLevel = roleLevel; } @Override public String toString() { return "Role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + ", roleLevel='" + roleLevel + '\'' + '}'; } }
[ "1979277742@qq.com" ]
1979277742@qq.com
5513faeb9c62364c0fda71fb4dea00e4527b983d
93d45a4908aab9418ce4b8487e5d66d9d133eb3a
/src/main/java/com/pengjunlee/domain/BodySetEntity.java
039319dba54a0923d32b45c19a54220cdf2099df
[]
no_license
pengjunlee/pink-photo-server
d92a5465cd0518ba40bd2072e833214fbfbe3080
742e0493d9b26cff073ec49b998633be4bd9729b
refs/heads/master
2022-11-18T18:08:17.170748
2019-11-22T05:48:28
2019-11-22T05:48:28
219,399,536
0
0
null
2022-11-16T11:57:41
2019-11-04T02:18:54
Java
UTF-8
Java
false
false
1,217
java
package com.pengjunlee.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; /** * @author pengjunlee * @create 2019-09-03 9:30 */ @Data @TableName("tbl_body_set")//@TableName中的值对应着表名 public class BodySetEntity extends BaseDomain { /** * 主键 * * @TableId中可以决定主键的类型,不写会采取默认值,默认值可以在yml中配置 AUTO: 数据库ID自增 * INPUT: 用户输入ID * ID_WORKER: 全局唯一ID,Long类型的主键 * ID_WORKER_STR: 字符串全局唯一ID * UUID: 全局唯一ID,UUID类型的主键 * NONE: 该类型为未设置主键类型 */ @TableId(type = IdType.AUTO) private Long id; // 主键ID private Long deviceId; // 设备ID private String poseType; // 行 private Long poseStyleId; // 列 private Integer topBottom; private Integer leftRight; private Integer upDown; private Integer rotate; public void init() { this.topBottom = 0; this.leftRight = 0; this.upDown = 0; this.rotate = 0; } }
[ "pengjunlee@163.com" ]
pengjunlee@163.com
85f9081f53935390b550d98d9edd593e4e44b056
8d935d44c34751b53895ce3383dde49073503251
/src/main/java/org/iii/ideas/catering_service/rest/api/QuerySfschoolproductsetBySchoolResponse.java
97892598b4f9f500e6ae0ab89ea481fcc5f09815
[ "Apache-2.0" ]
permissive
NoahChian/Devops
b3483394b8e8189f4647a4ee41d8ceb8267eaebb
3d310dedfd1bd07fcda3d5f4f7ac45a07b90489f
refs/heads/master
2016-09-14T05:41:37.471624
2016-05-11T07:29:28
2016-05-11T07:29:28
58,521,704
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package org.iii.ideas.catering_service.rest.api; import java.util.ArrayList; import java.util.List; import org.iii.ideas.catering_service.rest.bo.SfSchoolproductsetBO; public class QuerySfschoolproductsetBySchoolResponse extends AbstractApiResponse { private static final long serialVersionUID = -1904135875588581166L; private List<SfSchoolproductsetBO> sfschoolproductsetList = new ArrayList<SfSchoolproductsetBO>(); public List<SfSchoolproductsetBO> getSfschoolproductsetList() { return sfschoolproductsetList; } public void setSfschoolproductsetList(List<SfSchoolproductsetBO> sfschoolproductsetList) { this.sfschoolproductsetList = sfschoolproductsetList; } }
[ "noahjian@iii.org.tw" ]
noahjian@iii.org.tw
dcd91a6698983f3e9d16c37728d2a8744971e059
9c190f0377d1374d98ccf6866dbd8719aba0be06
/app/src/main/java/me/lancer/pocket/util/FileTypeRefereeUtil.java
f7548759411fee2c701c140f341e8d512f9a128d
[]
no_license
1anc3r/Pocket
e7bb03e98947d984ef225971fbfc8610f110766d
68a49bc2ecabcbf536d7daa12145766aca05c586
refs/heads/master
2020-03-28T19:47:22.647719
2019-03-02T10:40:54
2019-03-02T10:40:54
94,602,624
11
0
null
null
null
null
UTF-8
Java
false
false
3,448
java
package me.lancer.pocket.util; import java.io.File; public class FileTypeRefereeUtil { public static final String[][] FILE_TYPE_TABLE = { {".3gp", "video/3gpp"}, {".apk", "application/vnd.android.package-archive"}, {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".class", "application/octet-stream"}, {".conf", "text/plain"}, {".cpp", "text/plain"}, {".doc", "application/msword"}, {".exe", "application/octet-stream"}, {".gif", "image/gif"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".htm", "text/html"}, {".html", "text/html"}, {".jar", "application/java-archive"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"}, {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"}, {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"}, {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"}, {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"}, {".mp4", "video/mp4"}, {".mpc", "application/vnd.mpohun.certificate"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"}, {".mpga", "audio/mpeg"}, {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".prop", "text/plain"}, {".rar", "application/x-rar-compressed"}, {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, {".sh", "text/plain"}, {".tar", "application/x-tar"}, {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, {".wmv", "audio/x-ms-wmv"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {".z", "application/x-compress"}, {".zip", "application/zip"}, {"", "*/*"} }; File file; public FileTypeRefereeUtil() { } public FileTypeRefereeUtil(File file) { this.file = file; } public String getFileType(File file) { String type = "*/*"; String name = file.getName(); int dot = name.lastIndexOf("."); if (dot < 0) { return type; } String suffix = name.substring(dot, name.length()).toLowerCase(); if (suffix == "") { return type; } for (int i = 0; i < FILE_TYPE_TABLE.length; i++) { if (suffix.equals(FILE_TYPE_TABLE[i][0])) { type = FILE_TYPE_TABLE[i][1]; } } return type; } }
[ "huangfangzhi@icloud.com" ]
huangfangzhi@icloud.com
6c999b53fb50eb884f50fc9d809ebc355fcaa28b
a83d6372cd03aa33e60f1e37bda1e43e2c166d2d
/OfficeAutomation/src/com/zdh/service/DebugWorkingService.java
f6997f55de711fe01549ab05d54ae81db90c15ff
[]
no_license
panpengcheng066516/sdmzdhOA
448735abc96b4b805b4aff8a2d6d07ca7a2c5f9e
19b860bf89230ba938cf462a408d222ce390142d
refs/heads/master
2023-02-12T20:09:51.220156
2021-01-18T02:10:38
2021-01-18T02:10:38
294,124,200
1
1
null
null
null
null
UTF-8
Java
false
false
2,322
java
package com.zdh.service; import com.zdh.dao.DebugWorkingDao; import com.zdh.domain.DebugWorking; import com.zdh.domain.DesignWorking; import com.zdh.domain.Project; import java.sql.SQLException; import java.util.List; public class DebugWorkingService { DebugWorkingDao debugWorkingDao = new DebugWorkingDao(); public int addDebugWorking(DebugWorking debugWorking) { int i =0; try { i = debugWorkingDao.addDebugWorking(debugWorking); } catch (SQLException e) { e.printStackTrace(); } return i; } public List<DebugWorking> getDebugWorkingByUsername(String username) { List<DebugWorking> list = null; try { list = debugWorkingDao.getDebugWorkingByUsername(username); } catch (SQLException e) { e.printStackTrace(); } return list; } public List<DebugWorking> getDebugWorkingByDateUsername(String year,String month,String username) { List<DebugWorking> list = null; try { list = debugWorkingDao.getDebugWorkingByDateUsername(year,month,username); } catch (SQLException e) { e.printStackTrace(); } return list; } public int updateDebugWorking(DebugWorking debugWorking) { int i =0; try { i = debugWorkingDao.updateDebugWorking(debugWorking); } catch (SQLException e) { e.printStackTrace(); } return i; } public DebugWorking getDebugWorkingInfo(String debugid) { DebugWorking debugWorking = null; try { debugWorking = debugWorkingDao.getDebugWorkingInfo(debugid); } catch (SQLException e) { e.printStackTrace(); } return debugWorking; } public Project getProjectByid(String debugid) { Project project = null; try { project = debugWorkingDao.getProjectByid(debugid); } catch (SQLException e) { e.printStackTrace(); } return project; } public int deleteDebugWorkingByid(String id) { int i =0; try { i = debugWorkingDao.deleteDebugWorkingByid(id); } catch (SQLException e) { e.printStackTrace(); } return i; } }
[ "ppc066516@163.com" ]
ppc066516@163.com
ba08df6515cabca9bd67ec36d01dcb64a232527a
d785392f8b0f6749ee29c6ac2d48c947f2c13c3b
/InterviewBit/StacksAndQueue/RainWaterTrap.java
b40bb845922536be7516cbd145fea066c9c3d506
[]
no_license
abnayak/brainz
eeae70e72d548c1b340fd7846003b6ef70f18291
a070da468522fc1276f49b4097838bb65d4b0b1f
refs/heads/master
2020-04-03T20:21:26.445618
2018-06-04T08:15:07
2018-06-04T08:15:07
28,757,396
1
2
null
null
null
null
UTF-8
Java
false
false
1,542
java
package StacksAndQueue; import java.util.ArrayList; import java.util.List; /** * Created by abhijeet on 10/11/16. * https://www.interviewbit.com/problems/rain-water-trapped/ */ public class RainWaterTrap { public static void main(String[] args) { int[] walls = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; List<Integer> list = new ArrayList<>(); for (int i : walls) { list.add(i); } System.out.println(trap(list)); } // DO NOT MODIFY THE LIST public static int trap(final List<Integer> a) { int[] fromHead = new int[a.size()]; int[] fromTail = new int[a.size()]; int waterStored = 0; if (a.size() < 3) return waterStored; fromHead[0] = a.get(0); fromTail[a.size() - 1] = a.get(a.size() - 1); for (int i = 1; i < a.size(); i++) { if (fromHead[i - 1] < a.get(i)) fromHead[i] = a.get(i); else fromHead[i] = fromHead[i - 1]; } for (int i = a.size() - 2; i >= 0; i--) { if (fromTail[i + 1] < a.get(i)) fromTail[i] = a.get(i); else fromTail[i] = fromTail[i + 1]; } for (int i = 1; i < a.size() - 1; i++) { int sideWallHeight = fromHead[i - 1] < fromTail[i + 1] ? fromHead[i - 1] : fromTail[i + 1]; if (sideWallHeight > a.get(i)) { waterStored += (sideWallHeight - a.get(i)); } } return waterStored; } }
[ "abnayak@outlook.com" ]
abnayak@outlook.com
956ca533e63d67e9ca63eb80664394287b25e67f
68e810683374564684b5397bf53acd7057f8ecfd
/src/abstraction/OnlineStudent.java
446217776c8ae6d8fb78ae847d2a0c9473e1aefc
[]
no_license
sefarash/Abstraction
11f3e9f4fe9febef9362db61a8c6bcff2df70c72
2e5b60214fe7368a660065d3f16ec418298f0207
refs/heads/master
2020-03-21T12:33:05.521747
2018-06-25T07:27:52
2018-06-25T07:27:52
138,558,557
0
0
null
null
null
null
UTF-8
Java
false
false
288
java
package abstraction; public class OnlineStudent extends Student{ @Override public void attendClass() { // TODO Auto-generated method stub } public static void main(String[] args) { //No Object can be created for Abstract CLass Student s = new Student(); } }
[ "ismayilov.rashad@gmail.com" ]
ismayilov.rashad@gmail.com
bd833eb22407b2cb66551415cc8a48d64085e0a1
d7c5121237c705b5847e374974b39f47fae13e10
/airspan.netspan/src/main/java/Netspan/NBI_17_5/Inventory/SiteCreate.java
cc5ad09ad26daefb45a870f681ce1517fcb3722f
[]
no_license
AirspanNetworks/SWITModules
8ae768e0b864fa57dcb17168d015f6585d4455aa
7089a4b6456621a3abd601cc4592d4b52a948b57
refs/heads/master
2022-11-24T11:20:29.041478
2020-08-09T07:20:03
2020-08-09T07:20:03
184,545,627
1
0
null
2022-11-16T12:35:12
2019-05-02T08:21:55
Java
UTF-8
Java
false
false
1,526
java
package Netspan.NBI_17_5.Inventory; 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 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&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Site" type="{http://Airspan.Netspan.WebServices}Site" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "site" }) @XmlRootElement(name = "SiteCreate") public class SiteCreate { @XmlElement(name = "Site") protected Site site; /** * Gets the value of the site property. * * @return * possible object is * {@link Site } * */ public Site getSite() { return site; } /** * Sets the value of the site property. * * @param value * allowed object is * {@link Site } * */ public void setSite(Site value) { this.site = value; } }
[ "ggrunwald@airspan.com" ]
ggrunwald@airspan.com
98f791ef2795e928086f79407fe1b7c591e6fd53
8b9190a8c5855d5753eb8ba7003e1db875f5d28f
/sources/com/google/android/gms/common/util/DefaultClock.java
3568b89067bfaae77c087ab6ef48409351cd7251
[]
no_license
stevehav/iowa-caucus-app
6aeb7de7487bd800f69cb0b51cc901f79bd4666b
e3c7eb39de0be6bbfa8b6b063aaa85dcbcee9044
refs/heads/master
2020-12-29T10:25:28.354117
2020-02-05T23:15:52
2020-02-05T23:15:52
238,565,283
21
3
null
null
null
null
UTF-8
Java
false
false
733
java
package com.google.android.gms.common.util; import android.os.SystemClock; import com.google.android.gms.common.annotation.KeepForSdk; @KeepForSdk public class DefaultClock implements Clock { private static final DefaultClock zzgm = new DefaultClock(); @KeepForSdk public static Clock getInstance() { return zzgm; } public long currentTimeMillis() { return System.currentTimeMillis(); } public long elapsedRealtime() { return SystemClock.elapsedRealtime(); } public long nanoTime() { return System.nanoTime(); } public long currentThreadTimeMillis() { return SystemClock.currentThreadTimeMillis(); } private DefaultClock() { } }
[ "steve@havelka.co" ]
steve@havelka.co
85d4678f2c9eb843c58e2b3e0050f554c654bb29
9ff9df8f090586eb8f8262aa5dc1d4866c1fbbe3
/src/net/kalinovcic/ld32/BombBehavior.java
e1aee1b49073d851205f306c1aef89b486de2ce6
[ "Apache-2.0" ]
permissive
Kalinovcic/LD32
06e7b6bfcd313650872eb2373c71f17a19712d01
28b1a82a93b2ee08a9b2afe9aefde45f1ccac95d
refs/heads/master
2016-08-04T13:36:43.207784
2015-04-20T12:06:11
2015-04-20T12:06:11
34,143,816
0
0
null
null
null
null
UTF-8
Java
false
false
2,406
java
package net.kalinovcic.ld32; import static org.lwjgl.opengl.GL11.*; public class BombBehavior implements Behavior { public static Behavior instance = new BombBehavior(); private BombBehavior() {} @Override public int getTexture() { return LD32.textureBomb; } @Override public float getSize() { return 48; } @Override public float getSpeedMul() { return 0.3f; } @Override public void labelColor() { glColor3f(1.0f, 0.0f, 0.0f); } @Override public void init(Enemy enemy) { enemy.cooldown = 20; } @Override public void update(Enemy enemy, double timeDelta) { long rvv11 = (long) enemy.cooldown; enemy.cooldown -= timeDelta; long rvv21 = (long) enemy.cooldown; if (enemy.cooldown >= 0 && enemy.cooldown <= 3 && rvv11 != rvv21) { AudioPlayer.setGain(0.7f); AudioPlayer.setPitch(0.9f); AudioPlayer.playWaveSound("warn"); } if (enemy.cooldown >= 0) enemy.texture = LD32.textureBomb; if (enemy.cooldown < 0) enemy.texture = LD32.textureBombIn; enemy.sppr = enemy.sppg = enemy.sppb = 1; if (enemy.cooldown <= 3) if ((int) (enemy.cooldown * 2) % 2 == 1) { enemy.sppr = 0; enemy.sppg = enemy.sppb = 0; } enemy.ang = (float) enemy.cooldown * 90; if (enemy.cooldown < 0 && enemy.cooldown + timeDelta >= 0) for (int i = 0; i < 10; i++) { char c1 = (char) (LD32.random.nextInt('z' - 'a' + 1) + 'a'); char c2 = (char) (LD32.random.nextInt('z' - 'a' + 1) + 'a'); char c3 = (char) (LD32.random.nextInt('z' - 'a' + 1) + 'a'); if (enemy.game.enemies.get(c1 - 'a') == null) { float x = BasicBehavior.instance.getSize() / 2 + (i / 9.0f) * (LD32.WW - BasicBehavior.instance.getSize()); Enemy e = new Enemy(enemy.game, c1 + "" + c2 + c3, x, -BasicBehavior.instance.getSize(), Math.max((float) enemy.game.maxSpeed * 0.2f, 50), BasicBehavior.instance); enemy.game.toAdd.add(e); enemy.game.enemies.set(c1 - 'a', e); } } } }
[ "lovro.kalinovcic@gmail.com" ]
lovro.kalinovcic@gmail.com
7a2f0acafb4e1735b05d691a9bba0447d4fb827f
a010f18a1d4d952933a8961159bfe72d3c1a72c9
/NettyRpc-server-1/src/main/java/com/zcl/nettyRpc/service/impl/GoodsServiceImpl.java
8ef9976f2ccf017cd21de2921adad8b66d983a61
[]
no_license
zcl1234/nettyRpc
4b35e9f9034bddacfb19d134389b86a769df3bcb
c03d5ea27336d210d795f7d1b8737004c15ea99b
refs/heads/master
2020-12-30T15:42:18.509107
2017-05-16T14:22:52
2017-05-16T14:22:52
91,167,025
0
0
null
null
null
null
UTF-8
Java
false
false
354
java
package com.zcl.nettyRpc.service.impl; import com.zcl.nettyRpc.Entity.Goods; import com.zcl.nettyRpc.serivce.GoodsService; /** * Created by 626hp on 2017/5/14. */ public class GoodsServiceImpl implements GoodsService { @Override public Goods getGoods(String title) { Goods goods=new Goods(title,1000); return goods; } }
[ "1185711404@qq.com" ]
1185711404@qq.com
f0d51b7e11a5c9f9da95912cd9feedd9aa908a8e
17453bea5c26ff83d226e08aad47dfc9f16562af
/src/com/whatsahandle/bountyhunter/SetBounty.java
cbbefc16334751c92dcf031e0fc8511f866b3de8
[]
no_license
whats-a-handle/minecraft-bounty-hunter
ca8d6d6f3996f115487ad805f1a0e0f68960a0b5
945e9e153ef9f94c579204f06c4e69d68020eb7f
refs/heads/master
2020-03-29T11:06:11.081529
2018-09-22T06:54:34
2018-09-22T06:54:34
149,836,032
0
0
null
null
null
null
UTF-8
Java
false
false
1,422
java
package com.whatsahandle.bountyhunter; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SetBounty implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(sender instanceof Player ) { DatabaseConnection dbConnection = new DatabaseConnection(); dbConnection.authenticate(); dbConnection.createTable(); String targetPlayer = ""; int bountyAmount = 0; if(args[0] == null) { sender.sendMessage("Sorry, you must enter a target player name."); return false; } else { targetPlayer = args[0]; } if(args[1] != null && BountyValidator.isAdminBountyValid(args[1])) { bountyAmount = Integer.valueOf(args[1]); bountyAmount = Integer.valueOf(args[1]); dbConnection.setPlayerBounty(targetPlayer, bountyAmount); sender.sendMessage("You\'ve set a bounty of $" + bountyAmount + " on " + targetPlayer); return true; } else { sender.sendMessage("Sorry, enter a bounty amount greater than or equal to 0"); return false; } } return false; } }
[ "24727927+whats-a-handle@users.noreply.github.com" ]
24727927+whats-a-handle@users.noreply.github.com
3e5dcff5e89c96aa01db944bd99810a654eb468e
9b9645faeb4728f17a62fe1248c81b9cd2f64d70
/src/main/java/org/pact/java/example/HttpServerVerticle.java
16a16c7da22a131f9028ff23707f0ef8d6f918ea
[]
no_license
cpramik/Pact
c399e3bc7dc3b947e4651829bc7c56ec263c9b92
36746bb7e6acf5235a13e4b0cfed203e31380706
refs/heads/master
2020-04-27T23:45:08.140418
2019-03-10T07:01:19
2019-03-10T07:01:19
174,788,929
0
0
null
null
null
null
UTF-8
Java
false
false
1,067
java
package org.pact.java.example; import io.vertx.core.AbstractVerticle; import io.vertx.core.Handler; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.web.Router; public class HttpServerVerticle extends AbstractVerticle{ @Override public void start() { vertx.createHttpServer(new HttpServerOptions()).requestHandler(requestHandler()) .listen(8081, result -> { if (result.succeeded()) { System.out.println("Server started---------------"); } else { System.out.println("Server failed to start---------------"); } }); } private Handler<HttpServerRequest> requestHandler() { Router router = Router.router(vertx); registerTestUserURI(router); return router::accept; } private void registerTestUserURI(Router router) { UserResource resource = new UserResource(new UserService()); router.get("/users").blockingHandler(resource::getUsers, false); router.get("/users/:userId").handler(resource::getUserById); router.post("/users").handler(resource::createUser); } }
[ "cpramik@athenahealth.com" ]
cpramik@athenahealth.com
db30d6171f0ba9b4e3107f6403f0b71905bd560c
f58e8e2a4018950066ddf30f7ced2275fbc882be
/src/main/java/com/jobexchange/model/Amount.java
2b62c97c07e0423b7646c3527acfd4188b606b4f
[]
no_license
girishkambli/job-seeker-matching-engine
c41fd0e6e9959f9964928cb014fd561217c3d834
4ce683f4c223b2bb1ae2ff87c0b2033e1b3974fd
refs/heads/master
2022-12-30T05:37:16.009122
2020-10-21T23:50:51
2020-10-21T23:50:51
175,947,285
0
0
null
null
null
null
UTF-8
Java
false
false
599
java
package com.jobexchange.model; import java.math.BigDecimal; import java.util.Currency; public class Amount { private Currency currency; private BigDecimal value; public Amount(Currency currency, BigDecimal value) { this.currency = currency; this.value = value; } public Currency getCurrency() { return currency; } public BigDecimal getValue() { return value; } @Override public String toString() { return "Amount{" + "currency=" + currency + ", value=" + value + '}'; } }
[ "jockey@MacBook-Pro.local" ]
jockey@MacBook-Pro.local
3a6366fde7476b77dfad73812c37468eea28cba3
52fe175ab4cf4642b11eaae78a2a2f3279390b93
/src/Google_Leetcode/FoodItems.java
8e2693dfdcb68d45f083027fb785e32d9c64fcd9
[]
no_license
karthikbeepi/Interview_Preparation
4ea30204cc81fd1b89d3b153a0e3018472055765
a943fe5501d802678f31af39299de4c92f7412bb
refs/heads/master
2022-11-05T18:42:07.892761
2020-06-24T04:06:39
2020-06-24T04:06:39
220,839,301
0
0
null
null
null
null
UTF-8
Java
false
false
2,033
java
package Google_Leetcode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Set; public class FoodItems { int noOfItems; HashMap<String, ArrayList<Integer>> products; HashMap<String, Integer> avgProductPrice; public FoodItems(int n) { noOfItems = n; products = new HashMap<String, ArrayList<Integer>>(); avgProductPrice = new HashMap<String, Integer>(); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int noOfCases = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for(int i=0; i<noOfCases; i++) { FoodItems obj = new FoodItems(Integer.parseInt(br.readLine())); for(int j=0; j<obj.noOfItems; j++) { obj.getItems(br.readLine()); } sb.append("Case "+(i+1)+"\n"); sb.append(obj.printDetails()); } System.out.println(sb); } private String printDetails() { StringBuilder sb = new StringBuilder(); ArrayList<String> sortedKeys = new ArrayList<String>(); sortedKeys.addAll(products.keySet()); Collections.sort(sortedKeys); for(String s: sortedKeys) { sb.append(s+" "); for(int i: products.get(s)) sb.append(i+" "); sb.append(avgProductPrice.get(s)+"\n"); } return sb.toString(); } private void getItems(String line) { String productName = line.split(" ")[0]; int productVal = Integer.parseInt(line.split(" ")[1]); ArrayList<Integer> arrVal; if(!products.containsKey(productName)) { arrVal = new ArrayList<Integer>(); } else { arrVal = products.get(productName); } arrVal.add(productVal); products.put(productName, arrVal); float avg = (float) 0.0; for(int i: arrVal) { avg+= i; } avg/=arrVal.size(); avgProductPrice.put(productName, (int) Math.round(avg)); } }
[ "karthikbeepi@gmail.com" ]
karthikbeepi@gmail.com
fc7d33469456330f0535df53eb730d6937e894e2
1b3b3a31ebc262d616b0c1d1fd8ea57e92c803bb
/src/com/itheima/domain/Book.java
a08fb723ef40b20a3cbc7c14c0857f57464b6540
[]
no_license
remix7/BookStore
a1a56cb73752098cd125e0f4a4dd47b2e45418be
ca2e19e3a03761c14b73c45c72d1ab7032b25776
refs/heads/master
2021-01-22T23:06:02.341710
2016-02-04T10:05:56
2016-02-04T10:05:56
null
0
0
null
null
null
null
GB18030
Java
false
false
1,743
java
package com.itheima.domain; import java.io.Serializable; public class Book implements Serializable { private String id; private String name; private String author; private float price; private String imageName;//与表单不一样哦 private String description; private String categoryid; public Book(){ super(); } public Book(String id, String name, String author, float price, String imageName, String description, String categoryid) { super(); this.id = id; this.name = name; this.author = author; this.price = price; this.imageName = imageName; this.description = description; this.categoryid = categoryid; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategoryid() { return categoryid; } public void setCategoryid(String categoryid) { this.categoryid = categoryid; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", author=" + author + ", price=" + price + ", imageName=" + imageName + ", description=" + description + ", categoryid=" + categoryid + "]"; } }
[ "yewmf@hehenian.com" ]
yewmf@hehenian.com
452288f7459d97f21cd7fe83a21cccbaad766012
be16366efbf614e62e66362a33ac8aae450b956c
/src/main/java/altea/pokemonshop/contoller/ShopController.java
b4b0228538dc772c3dfac199a2de41147a065f9b
[]
no_license
ALTEA-2018/shop-api-selleniackn
4b6082304db7d57b7b53f34cb881791179f3b5e4
db1be023b7036fbf0f7eb2ebf9f66667ede619a7
refs/heads/master
2020-06-12T01:27:24.359070
2019-07-05T17:13:44
2019-07-05T17:13:44
194,151,671
0
0
null
null
null
null
UTF-8
Java
false
false
2,723
java
package altea.pokemonshop.contoller; import altea.pokemonshop.bo.Item; import altea.pokemonshop.bo.Trainer; import altea.pokemonshop.service.ItemService; import altea.pokemonshop.service.TrainerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class ShopController { private TrainerService trainerService; private ItemService itemService; @GetMapping(value = "/") public ModelAndView shop() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetails principal = (UserDetails) authentication.getPrincipal(); Map<String, Object> stringObjectMap = new HashMap<>(); Trainer trainer = this.trainerService.findTrainerByName(principal.getUsername()); List<Item> items = this.itemService.findAllItems(); stringObjectMap.put("trainer", trainer); stringObjectMap.put("items", items); stringObjectMap.put("message", "Welcome to the Poke Shop !"); return new ModelAndView("shop", stringObjectMap); } @PostMapping(value = "/addItem") public ModelAndView addNewItem( int id){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetails principal = (UserDetails) authentication.getPrincipal(); Map<String, Object> stringObjectMap = new HashMap<>(); Trainer trainer = this.trainerService.findTrainerByName(principal.getUsername()); boolean added = this.trainerService.addItem(id, trainer.getName()); List<Item> items = this.itemService.findAllItems(); if (added) { stringObjectMap.put("message", "This item is yours now !!!"); } else { stringObjectMap.put("message", "You don't have enough Pokedollars"); } stringObjectMap.put("trainer", trainer); stringObjectMap.put("items", items); return new ModelAndView("shop", stringObjectMap); } @Autowired public void setTrainerService(TrainerService trainerService) { this.trainerService = trainerService; } @Autowired public void setItemService(ItemService itemService) { this.itemService = itemService; } }
[ "sellenia.chikhoune.etu@univ-lille.fr" ]
sellenia.chikhoune.etu@univ-lille.fr
d059a98a15b85fff863e0421549ef4b0905ecdb1
e5d9269646f276fd4c9cf110ae7ad6e660ad220a
/app/src/main/java/com/example/android/quizapp/MainActivity.java
826c9399667cb36158de411df84367d6791818ab
[]
no_license
erickibz/QuizApp
c8b6c9eafa845d0cf33ac96adcbc6905844bb900
659b64f1e32804c5ea9252a0e365613a36ecf678
refs/heads/master
2020-03-22T00:18:22.164162
2018-06-30T09:51:17
2018-06-30T09:51:17
139,236,560
0
0
null
null
null
null
UTF-8
Java
false
false
411
java
package com.example.android.quizapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
124478b0e7f18f98c8a3447230ff7f2b0dd39d86
fbf27d453d933352a2c8ef76e0445f59e6b5d304
/server/src/com/fy/engineserver/message/JIAZU_RELEVANT_DES_REQ.java
97e57f021fffc9e68daf3bf4965aa8008babccea
[]
no_license
JoyPanda/wangxian_server
0996a03d86fa12a5a884a4c792100b04980d3445
d4a526ecb29dc1babffaf607859b2ed6947480bb
refs/heads/main
2023-06-29T05:33:57.988077
2021-04-06T07:29:03
2021-04-06T07:29:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,078
java
package com.fy.engineserver.message; import com.xuanzhi.tools.transport.*; import java.nio.ByteBuffer; /** * 网络数据包,此数据包是由MessageComplier自动生成,请不要手动修改。<br> * 版本号:null<br> * 请求家族界面相关描述<br> * 数据包的格式如下:<br><br> * <table border="0" cellpadding="0" cellspacing="1" width="100%" bgcolor="#000000" align="center"> * <tr bgcolor="#00FFFF" align="center"><td>字段名</td><td>数据类型</td><td>长度(字节数)</td><td>说明</td></tr> * <tr bgcolor="#FFFFFF" align="center"><td>length</td><td>int</td><td>getNumOfByteForMessageLength()个字节</td><td>包的整体长度,包头的一部分</td></tr> * <tr bgcolor="#FAFAFA" align="center"><td>type</td><td>int</td><td>4个字节</td><td>包的类型,包头的一部分</td></tr> * <tr bgcolor="#FFFFFF" align="center"><td>seqNum</td><td>int</td><td>4个字节</td><td>包的序列号,包头的一部分</td></tr> * <tr bgcolor="#FAFAFA" align="center"><td>windowId</td><td>int</td><td>4个字节</td><td>配置的长度</td></tr> * <tr bgcolor="#FFFFFF" align="center"><td>targetName.length</td><td>short</td><td>2个字节</td><td>字符串实际长度</td></tr> * <tr bgcolor="#FAFAFA" align="center"><td>targetName</td><td>String</td><td>targetName.length</td><td>字符串对应的byte数组</td></tr> * </table> */ public class JIAZU_RELEVANT_DES_REQ implements RequestMessage{ static GameMessageFactory mf = GameMessageFactory.getInstance(); long seqNum; int windowId; String targetName; public JIAZU_RELEVANT_DES_REQ(){ } public JIAZU_RELEVANT_DES_REQ(long seqNum,int windowId,String targetName){ this.seqNum = seqNum; this.windowId = windowId; this.targetName = targetName; } public JIAZU_RELEVANT_DES_REQ(long seqNum,byte[] content,int offset,int size) throws Exception{ this.seqNum = seqNum; windowId = (int)mf.byteArrayToNumber(content,offset,4); offset += 4; int len = 0; len = (int)mf.byteArrayToNumber(content,offset,2); offset += 2; if(len < 0 || len > 16384) throw new Exception("string length ["+len+"] big than the max length [16384]"); targetName = new String(content,offset,len); offset += len; } public int getType() { return 0x00FF0064; } public String getTypeDescription() { return "JIAZU_RELEVANT_DES_REQ"; } public String getSequenceNumAsString() { return String.valueOf(seqNum); } public long getSequnceNum(){ return seqNum; } private int packet_length = 0; public int getLength() { if(packet_length > 0) return packet_length; int len = mf.getNumOfByteForMessageLength() + 4 + 4; len += 4; len += 2; len +=targetName.getBytes().length; packet_length = len; return len; } public int writeTo(ByteBuffer buffer) { int messageLength = getLength(); if(buffer.remaining() < messageLength) return 0; int oldPos = buffer.position(); buffer.mark(); try{ buffer.put(mf.numberToByteArray(messageLength,mf.getNumOfByteForMessageLength())); buffer.putInt(getType()); buffer.putInt((int)seqNum); buffer.putInt(windowId); byte[] tmpBytes1; tmpBytes1 = targetName.getBytes(); buffer.putShort((short)tmpBytes1.length); buffer.put(tmpBytes1); }catch(Exception e){ e.printStackTrace(); buffer.reset(); throw new RuntimeException("in writeTo method catch exception :",e); } int newPos = buffer.position(); buffer.position(oldPos); buffer.put(mf.numberToByteArray(newPos-oldPos,mf.getNumOfByteForMessageLength())); buffer.position(newPos); return newPos-oldPos; } /** * 获取属性: * 窗口id,用以区分 1:家族面板 */ public int getWindowId(){ return windowId; } /** * 设置属性: * 窗口id,用以区分 1:家族面板 */ public void setWindowId(int windowId){ this.windowId = windowId; } /** * 获取属性: * 按钮名 */ public String getTargetName(){ return targetName; } /** * 设置属性: * 按钮名 */ public void setTargetName(String targetName){ this.targetName = targetName; } }
[ "1414464063@qq.com" ]
1414464063@qq.com
cef42d87594d559a759d633da00ba5c902fe8134
6a1eeda00c2932c0a43bf5dd0fc867f565c97a01
/scconsumer-dept-80/src/main/java/wrx/sc/configclient3355/SCConsumerDept80Application.java
98fda50c08b43885e958bf5c0e9e6f13e9524a3b
[]
no_license
wuruixiong/SpringCloudDemo
0eb012c8d78e3463bda004f93b69b3a1fbf8c55b
840dd5317264e278876e4eb251652310d4a4feff
refs/heads/master
2022-11-28T00:23:52.874957
2020-08-04T02:44:32
2020-08-04T02:44:32
282,945,173
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package wrx.sc.configclient3355; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import wrx.sc.configclient3355.myrule.KuangRule; @SpringBootApplication @EnableEurekaClient //在微服务启动的时候就能去加载我们自定义Ribbon类 @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = KuangRule.class) public class SCConsumerDept80Application { public static void main(String[] args) { SpringApplication.run(SCConsumerDept80Application.class, args); } }
[ "wowuruixiong@163.com" ]
wowuruixiong@163.com
25fa62fc818f2e7ba72210309a4b1c078310f197
dc1f79b80db2287695fda7f6bcc672df04464c33
/boot-dubbo-consumer/src/main/java/com/zhenglei/dubbo/service/TestService.java
b9048511e80397776497528d6c37dcf27b3c5c9c
[]
no_license
2767131402/dubbo
7b9ed90e4319d638938eca23e5d0d97424f55ba7
8d89cf1fba3781f2c01088065615c67c644cc9de
refs/heads/master
2022-12-05T03:31:36.639267
2020-08-26T14:46:12
2020-08-26T14:46:12
290,143,766
0
0
null
null
null
null
UTF-8
Java
false
false
490
java
package com.zhenglei.dubbo.service; import com.zhenglei.dubbo.MyProviderService; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.stereotype.Service; @Service public class TestService { //stub 注解方式 配置本地存根 @DubboReference(stub = "com.zhenglei.dubbo.sub.MyProviderServiceSub") private MyProviderService myProviderService; public String sayHello(String name){ return myProviderService.sayHello(name); } }
[ "ii_zhenglei@163.com" ]
ii_zhenglei@163.com
046b3e6075c94aa68f154cc3b3b1cd483cbeae70
ec5709bfe427b7efe1599ab0e1360173c5f609a3
/app-leetcode/src/main/java/com/guce/Permute.java
a64ae66fe6f4a7b4034e5008eb70671aea4ee67e
[]
no_license
werwolfGu/JHodgepodge
b941d8ff28d0a4a7fcc46f59fcd057d62b3d9f9c
14b594970f5ca2bf842ab5094ef9d443665309ce
refs/heads/master
2022-12-22T18:11:40.932246
2022-05-15T07:25:18
2022-05-15T07:25:18
147,911,191
8
3
null
2022-12-10T05:53:09
2018-09-08T07:18:17
Java
UTF-8
Java
false
false
1,970
java
package com.guce; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * @Author chengen.gce * @DATE 2020/4/25 5:23 下午 * https://leetcode-cn.com/problems/permutations/submissions/ * <p> * 全排列 */ public class Permute { public static List<List<Integer>> solution(int[] nums) { List<List<Integer>> res = new ArrayList<>(); LinkedList list = new LinkedList(); backtrace(nums, res, list); return res; } public static void backtrace(int[] nums, List<List<Integer>> res, LinkedList<Integer> list) { if (nums.length == list.size()) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { if (list.contains(nums[i])) { continue; } list.add(nums[i]); backtrace(nums, res, list); list.removeLast(); } } public static List<List<Integer>> solution2(int[] nums) { List<List<Integer>> res = new ArrayList<>(); boolean used[] = new boolean[nums.length]; Deque<Integer> path = new ArrayDeque<>(); backtrace(nums, used, path, res); return res; } public static void backtrace(int nums[], boolean used[], Deque<Integer> path, List<List<Integer>> res) { if (nums.length == path.size()) { res.add(new ArrayList<>(path)); } for (int i = 0; i < nums.length; i++) { if (used[i]) { continue; } used[i] = true; path.addLast(nums[i]); backtrace(nums, used, path, res); used[i] = false; path.removeLast(); } } public static void main(String[] args) { System.out.println(solution(new int[]{1, 2, 3})); System.out.println(solution2(new int[]{1, 2, 3})); } }
[ "chengen.gu@vipshop.com" ]
chengen.gu@vipshop.com
c2f222e74344f2376045c2c0732755b6e354ace9
e4ef8e6dfff61c0a85aa2958c7963a5d1dec60c1
/mano/src/main/java/mano/util/Pool.java
229da987b13ab2383daae7623047298193ec74e9
[]
no_license
wlfs/mano
e94751d2635a386429383c4d387966fa9f6478ae
381df03a50275d0de8f9425b8e283dfe42bafef3
refs/heads/master
2020-12-24T10:15:59.441943
2014-09-05T01:45:04
2014-09-05T01:45:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,265
java
/* * Copyright (C) 2014 The MANO Authors. * All rights reserved. Use is subject to license terms. * * See more http://mano.diosay.com/ * */ package mano.util; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import mano.Resettable; /** * * @author jun <jun@diosay.com> * @param <T> */ public class Pool<T> { private final Queue<T> items = new LinkedBlockingQueue<>(); private ObjectFactory<T> _factory; private int count; private int keepIdelLimit; protected Pool() { } public Pool(ObjectFactory<T> factory) { _factory = factory; } public Pool(ObjectFactory<T> factory, int keepIdels) { _factory = factory; keepIdelLimit = keepIdels; } protected T create() { if (_factory == null) { throw new IllegalArgumentException(); } return _factory.create(); } public synchronized T get() { if (count < keepIdelLimit) { return create(); } T result = items.poll(); if (result == null) { result = create(); } else { count--; } return result; } public synchronized void put(T item) { if (item == null) { return; } count++; if (item instanceof Resettable) { ((Resettable) item).reset(); } items.offer(item); } public int count() { return count; } public synchronized void clear() { count = 0; items.clear(); } public static void mainsssss(String... args) { ReferenceQueue rq = new ReferenceQueue(); PhantomReference wr = new PhantomReference("abc", rq); System.gc(); try { Thread.sleep(1000); } catch (InterruptedException ex) { } System.gc(); try { Thread.sleep(1000); } catch (InterruptedException ex) { } System.gc(); System.out.println(wr.get()); System.out.println(rq.poll()); } }
[ "jun@diosay.com" ]
jun@diosay.com
bf3ac5aa8b4df27e7f9373f60f3548454afd04f4
624743174728c1ed46d5ef37b5557ed210308c22
/app/src/main/java/app/jiyi/com/mjoke/utilview/LoadMoreListView.java
d2bb0c9c05413110fe33481095d255be09ec9d7c
[]
no_license
jiyiren/mjoke
e891a9af3c3ba361820111c07e925f153bd97ed3
1b8e483e323fc9933413d4f32003a603eb70188e
refs/heads/master
2021-01-21T14:09:20.151771
2018-12-03T05:19:25
2018-12-03T05:19:25
42,521,482
56
10
null
null
null
null
UTF-8
Java
false
false
2,358
java
package app.jiyi.com.mjoke.utilview; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsListView; import android.widget.ListView; import app.jiyi.com.mjoke.R; /** * Created by JIYI on 2015/8/31. */ public class LoadMoreListView extends ListView implements AbsListView.OnScrollListener{ private int totalItem; private int lastItem; private View footer; private LayoutInflater layoutInflater; private boolean isloading=false; private OnLoadMore onLoadMore; public LoadMoreListView(Context context) { super(context); initView(context); } public LoadMoreListView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public LoadMoreListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } private void initView(Context context) { layoutInflater=LayoutInflater.from(context); footer = layoutInflater.inflate(R.layout.listview_booter, null); footer.setVisibility(View.GONE); this.addFooterView(footer); this.setOnScrollListener(this); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if ((this.totalItem == lastItem) && (scrollState == SCROLL_STATE_TOUCH_SCROLL)) { // Log.v("isLoading", "yes"); if (!isloading) { if(onLoadMore!=null) { isloading = true; footer.setVisibility(View.VISIBLE); onLoadMore.loadMore(); } } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.lastItem=firstVisibleItem+visibleItemCount; this.totalItem=totalItemCount; } public void setLoadMoreListen(OnLoadMore onLoadMore){ this.onLoadMore = onLoadMore; } /** * 加载完成调用此方法 */ public void onLoadComplete(){ footer.setVisibility(View.GONE); isloading = false; } public interface OnLoadMore{ public void loadMore(); } }
[ "1459050189@qq.com" ]
1459050189@qq.com
8d7e28773da434b6b97961d650e96eb355e14841
ea2aa36a0aa5858d31d593b08baa7ab7394276b0
/src/regras/AndarNaDiagonal.java
aba67df1d414f281c2b7d793c534db77abb8eb69
[]
no_license
ernandofvjr/Jogo-de-Damas
7415156223fa7bf9dc44df555bab15b1875923a3
4543f1a20383c40d8306f43b0e5308b85382c710
refs/heads/master
2020-04-26T21:33:38.630741
2019-03-05T00:46:43
2019-03-05T00:46:43
173,845,023
0
0
null
null
null
null
ISO-8859-1
Java
false
false
657
java
package regras; import Excecoes.DamasException; import componentes.Tabuleiro; public class AndarNaDiagonal extends Regra implements ChecarTres { public AndarNaDiagonal(Tabuleiro tabuleiro){ setTabuleiro(tabuleiro); } /** * checa se a peça está andando na diagonal */ public boolean checar(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino) throws DamasException{ int direcaoLinha = linhaDestino - linhaOrigem; int direcaoColuna = colunaDestino - colunaOrigem; if(direcaoLinha == 0 || direcaoColuna == 0){ throw new DamasException("Casas subsequentes nao podem ser ocupadas"); } return true; } }
[ "ernandofvjr@hotmail.com" ]
ernandofvjr@hotmail.com
ebfe8816450293df83932d2e99c80ee54fd2fca7
24564796b4a300ad3e52c46730385d47358c63e3
/src/main/java/com/prarui/coment/Interceptor/HelloInterceptor.java
ff98bec71c5bf066c2c81652c42768ea80c04828
[]
no_license
ThoughtRain/coment
d0eb037e184fbad7a69bac6e765f02c8b45fc011
0210263c0429c6914e50967a71508b6037453b91
refs/heads/master
2022-05-29T09:11:03.952820
2019-09-03T01:39:20
2019-09-03T01:39:20
201,191,753
0
0
null
2022-05-20T21:05:05
2019-08-08T06:22:18
Java
UTF-8
Java
false
false
1,566
java
package com.prarui.coment.Interceptor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloInterceptor extends HandlerInterceptorAdapter { /** * This implementation always returns {@code true}. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle---->execute"); return true; } /** * This implementation is empty. */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception { System.out.println("postHandle--->execute"); } /** * This implementation is empty. */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception { System.out.println("afterCompletion--->"); } /** * This implementation is empty. */ @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception { System.out.println("afterConcurrentHandlingStarted--->"); } }
[ "1807520106@qq.com" ]
1807520106@qq.com
8105ba813cafa7f09db86d05ce481e2678badca3
77cf3c4de6601eca954829868c4a9a0ffd94d8e6
/src/main/java/com/index/service/AdminService.java
04539c6c9a10919b659d759dbf5bd9e0d1931139
[]
no_license
zengxihong/PersonalProject.index
b4d3b96fa5dde18e2131bd14276993fd957765fd
2048c1a1614d650d700884e70ab58e573c20ae30
refs/heads/master
2021-01-23T16:07:07.255803
2017-06-04T02:02:55
2017-06-04T02:02:55
93,284,393
3
1
null
null
null
null
UTF-8
Java
false
false
263
java
package com.index.service; import com.index.po.Admin; /** * Created by Administrator on 2017/5/26. */ public interface AdminService { public Admin selectAdminById(Integer id) throws Exception; public Admin adminLogin(Admin admin) throws Exception; }
[ "zengxihong2008@163.com" ]
zengxihong2008@163.com
0117105663f07264fcb5384a5c68b4f8c8dbf63a
585fd0a0d83b4eeaf47e4f0cadacaff507d2154d
/codeworld-cloud-order/src/main/java/com/codeworld/fc/order/client/MerchantClient.java
6a538747c8b2c74e9d66cde8e4306f932081478f
[]
no_license
sengeiou/codeworld-cloud-shop-api
accce2ca5686dcf2dc0c0bc65c4c1eb6a467a8e9
2297f0e97d1327a9f4a48a341a08ea3a58905a62
refs/heads/master
2023-02-16T05:51:21.778190
2021-01-15T09:48:56
2021-01-15T09:48:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
690
java
package com.codeworld.fc.order.client; import com.codeworld.fc.common.response.FCResponse; import com.codeworld.fc.order.domain.MerchantResponse; import io.swagger.annotations.ApiOperation; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name = "codeworld-cloud-merchant") public interface MerchantClient { @PostMapping("/codeworld-merchant/get-merchant-number-name-id") @ApiOperation("根据商户id获取商户号和名称") FCResponse<MerchantResponse> getMerchantNumberAndNameById(@RequestParam("merchantId") Long merchantId); }
[ "1692454247@qq.com" ]
1692454247@qq.com
08d8fa3e684ebd952347392d725b50899ed9762b
dd4e5a15965ec40bfcf6d0fbb773bed4d9e87d2a
/src/main/java/com/fastdata/algorithm/medium/array/PartitionArrayIntoDisjointIntervals.java
af3f4e841cf7f2e4d781b37652f14b12eef7709f
[]
no_license
lucky0604/leetcode-practice
6d27719f5e771df75f4aba9c74141913858045f1
fc4a22ea22dbe82877f45770af8461f1b2e618af
refs/heads/main
2023-08-15T07:26:36.082453
2021-09-20T04:45:37
2021-09-20T04:45:37
334,917,997
0
0
null
null
null
null
UTF-8
Java
false
false
860
java
package com.fastdata.algorithm.medium.array; /** * @Author: lucky * @License: (C) Copyright * @Contact: lucky_soft@163.com * @Date: 2021-06-07 10:00 AM * @Version: 1.0 * @description: https://leetcode.com/problems/partition-array-into-disjoint-intervals/ **/ // TODO: to be understand public class PartitionArrayIntoDisjointIntervals { public int partitionDisjoint(int[] nums) { // init the current max and next max value int currentMax = nums[0]; int nextMax = nums[0]; int ret = 0; for (int i = 1; i < nums.length; i ++) { int currentVal = nums[i]; nextMax = Math.max(currentVal, nextMax); if (currentVal < currentMax) { currentMax = nextMax; ret = i; } } return ret + 1; } }
[ "lucky_soft@163.com" ]
lucky_soft@163.com