hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
353faeceaf0a80534de227157b64baf48103a6f4
734
package com.haarman.listviewanimations.swinginadapters.prepared; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.haarman.listviewanimations.swinginadapters.AnimationAdapter; import com.nineoldandroids.animation.Animator; public class AlphaInAnimationAdapter extends AnimationAdapter { public AlphaInAnimationAdapter(BaseAdapter baseAdapter) { super(baseAdapter); } @Override protected long getAnimationDelayMillis() { return DEFAULTANIMATIONDELAYMILLIS; } @Override protected long getAnimationDurationMillis() { return DEFAULTANIMATIONDURATIONMILLIS; } @Override public Animator[] getAnimators(ViewGroup parent, View view) { return new Animator[0]; } }
23.677419
71
0.817439
006a56b8c63369b515293cdb38986a4eabe52468
747
package addTwoNumber; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode c1 = l1, c2 = l2, res = new ListNode(0), r = res; int sum = 0; while(c1 != null || c2 != null){ sum /= 10; if(c1 != null){ sum += c1.val; c1 = c1.next; } if(c2 != null){ sum += c2.val; c2 = c2.next; } r.next = new ListNode(sum%10); r = r.next; } if(sum > 9) r.next = new ListNode(sum/10); return res.next; } }
23.34375
66
0.416332
61a108050861c9500e4db4eb3cfe37b8441817d7
1,335
/* Copyright 2020 The Kubernetes 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 io.kubernetes.client.util.credentials; import static io.kubernetes.client.util.TestUtils.getApiKeyAuthFromClient; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import io.kubernetes.client.openapi.ApiClient; import org.junit.Test; public class AccessTokenAuthenticationTest { @Test public void testTokenProvided() { final ApiClient client = new ApiClient(); new AccessTokenAuthentication("token").provide(client); assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Bearer")); assertThat(getApiKeyAuthFromClient(client).getApiKey(), is("token")); } @Test(expected = NullPointerException.class) public void testTokenNonnull() { new AccessTokenAuthentication(null); } }
36.081081
80
0.787266
bc9ab87697e7d33844d800cdbf5c4bd67efde7c1
2,327
package q900; import org.junit.runner.RunWith; import util.runner.Answer; import util.runner.LeetCodeRunner; import util.runner.TestData; import util.runner.data.DataExpectation; /** * [Hard] 878. Nth Magical Number * https://leetcode.com/problems/nth-magical-number/ * * A positive integer is magical if it is divisible by either A or B. * * Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7. * * Example 1: * * Input: N = 1, A = 2, B = 3 * Output: 2 * * Example 2: * * Input: N = 4, A = 2, B = 3 * Output: 6 * * Example 3: * * Input: N = 5, A = 2, B = 4 * Output: 10 * * Example 4: * * Input: N = 3, A = 6, B = 4 * Output: 8 * * Note: * * 1 <= N <= 10^9 * 2 <= A <= 40000 * 2 <= B <= 40000 */ @RunWith(LeetCodeRunner.class) public class Q878_NthMagicalNumber { // 暴力求解会超时 // @Answer public int nthMagicalNumber_bruteForce(int N, int A, int B) { long res = 0; while (N-- > 0) { do { res++; } while (res % A != 0 && res % B != 0); } return (int) (res % 10_0000_0007); } /** * 二分查找, 求A的倍数和B 的倍数都多少个, 并扣掉其中 A 和B 的公倍数. */ @Answer public int nthMagicalNumber(int N, int A, int B) { long gcd = gcd(A, B), lcm = A * B / gcd; long start = 1, end = Long.MAX_VALUE / gcd; while (start < end) { long mid = start + (end - start) / 2; long count = mid * gcd / A + mid * gcd / B - mid * gcd / lcm; if (count < N) { start = mid + 1; } else { end = mid; } } return (int) (end * gcd % 10_0000_0007); } private int gcd(int x, int y) { return y == 0 ? x : gcd(y, x % y); } @TestData public DataExpectation example1 = DataExpectation.createWith(1, 2, 3).expect(2); @TestData public DataExpectation example2 = DataExpectation.createWith(4, 2, 3).expect(6); @TestData public DataExpectation example3 = DataExpectation.createWith(5, 2, 4).expect(10); @TestData public DataExpectation example4 = DataExpectation.createWith(3, 6, 4).expect(8); @TestData public DataExpectation normal1 = DataExpectation.createWith(1000000000, 40000, 40000).expect(999720007); }
23.989691
108
0.560378
17800fa87c746326ff55ef4719f9a23e4ad73467
3,217
package de.dhbwka.java.exam.stadtlandfluss; // import java.io.FileWriter; // import java.io.IOException; // import java.nio.file.Paths; // import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.TreeSet; public class Game { private char firstLetter; private java.util.Set<ColumnType> columns; private List<Sheet> player = new ArrayList<Sheet>(); private int minColumns; private int maxColumns; private int remainingSeconds; private boolean running; // private List<String> validWords; public Game(int min, int max, int seconds) { minColumns = min >= 3 ? min : 3; maxColumns = max >= min ? max : min; remainingSeconds = seconds; // try { // validWords = java.nio.file.Files.readAllLines(Paths.get("io/validwords.txt")); // } catch (IOException e) { // e.printStackTrace(); // } } private char createFirstCharacter() { return (char) ('A' + Math.random() * 27); } private void createColumns() { firstLetter = createFirstCharacter(); Random r = new Random(); int colCount = r.nextInt(maxColumns - minColumns + 1) + minColumns; columns = new TreeSet<ColumnType>(); columns.add(ColumnType.CITY); columns.add(ColumnType.COUNTRY); columns.add(ColumnType.RIVER); while (columns.size() < colCount) { switch ((int) (Math.random() * 8)) { case 0: columns.add(ColumnType.PROFESSION); break; case 1: columns.add(ColumnType.ANIMAL); break; case 2: columns.add(ColumnType.NAME); break; case 3: columns.add(ColumnType.SPORT); break; case 4: columns.add(ColumnType.FOOD); break; case 5: columns.add(ColumnType.BEVERAGE); break; case 6: columns.add(ColumnType.GAME); break; default: break; } } } public void register(Sheet sheet) { player.add(sheet); } public void startGame(){ if(!running){ createColumns(); running = true; player.forEach(p -> p.start()); } } public void stopGame(){ player.forEach(p -> p.stop()); } // private void CalculateResults(){ // } // private Boolean isCorrect(String word, String category){ // Boolean isOk = word.toUpperCase().startsWith(firstLetter+"") && word.length() > 0; // if(isOk && validWords.stream().anyMatch(v -> v.equalsIgnoreCase(word))) // isOk = true; // else if (isOk){ // if(JOptionPane.YES_OPTION == JOptionPane.showOptionDialog(null, "Ist '" + word +"' korrekt für Kategorie '" + category + "'?", // "Option auswählen", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null)){ // try { // try (FileWriter fw = new FileWriter("io/validwords.txt", true)) { // fw.append(word + "\r\n"); // validWords.add(word); // } // } catch (IOException e) { // e.printStackTrace(); // } // isOk = true; // } // else{ // isOk = false; // } // } // else{ // isOk = false; // } // return isOk; // } public char getFirstLetter() { return this.firstLetter; } public java.util.Set<ColumnType> getColumns() { return this.columns; } public int getRemainingSeconds() { return this.remainingSeconds; } }
21.736486
133
0.637861
df80b1d02560a0e247ca40ef46c266fec4b5b5e5
3,002
package com.tlswe.awsmock.ec2.control; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import com.tlswe.awsmock.ec2.model.MockTags; /** * Factory class providing static methods for managing life cycle of mock Tags. The current implementations * can: * <ul> * <li>create</li> * <li>delete</li> * <li>describe</li> * </ul> * mock Tags. <br> * * * @author Davinder Kumar * */ public final class MockTagsController { /** * Singleton instance of MockTagsController. */ private static MockTagsController singletonMockTagsController = null; /** * A List of all the mock Tags, instanceID as key and {@link MockTags} as value. */ private final List<MockTags> allMockTags = new ArrayList<MockTags>(); /** * Constructor of MockTagsController is made private and only called once by {@link #getInstance()}. */ private MockTagsController() { } /** * * @return singleton instance of {@link MockTagsController} */ public static MockTagsController getInstance() { if (null == singletonMockTagsController) { // "double lock lazy loading" for singleton instance loading on first time usage synchronized (MockSubnetController.class) { if (null == singletonMockTagsController) { singletonMockTagsController = new MockTagsController(); } } } return singletonMockTagsController; } /** * List mock Tags instances in current aws-mock. * * @return a collection all of {@link MockTags} . */ public List<MockTags> describeTags() { return allMockTags; } /** * Create the mock Tags. * @param resourcesSet List of resourceIds. * @param tagSet Map for key, value of tags. * @return mock Tags. */ public MockTags createTags( final List<String> resourcesSet, final Map<String, String> tagSet) { MockTags ret = new MockTags(); ret.setResourcesSet(resourcesSet); ret.setTagSet(tagSet); allMockTags.add(ret); return ret; } /** * Delete Mock tags. * * @param resources * resources's tags to be deleted * @return Mock tags. */ public boolean deleteTags(final List<String> resources) { for (MockTags mockTags : allMockTags) { if (mockTags.getResourcesSet().containsAll(resources)) { allMockTags.remove(mockTags); return true; } } return false; } /** * Clear {@link #allMockTags} and restore it from given a collection of instances. * * @param tags * collection of MockTags to restore */ public void restoreAllMockTags(final Collection<MockTags> tags) { allMockTags.clear(); if (tags != null) { allMockTags.addAll(tags); } } }
25.87931
107
0.605596
3dacfe3d21dd5e6f37fb2ac3690d85574b62b2b4
2,804
package web.controller.member; import entity.Product; import entity.Member; import service.ProductService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/member/product/add") public class ProductAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求的参数数据 String name=request.getParameter("name"); String cate_id=request.getParameter("type"); String thub=request.getParameter("photo"); String inventory=request.getParameter("inventory"); String selling_description=request.getParameter("selling_descriptionValues"); String detail_description=request.getParameter("detail_descriptionValues"); String sales_volume=request.getParameter("sales_volume"); String price=request.getParameter("price"); String sale_price=request.getParameter("sale_price"); String sale_time=request.getParameter("sale_time"); //把散装数据封装成对象 ProductService service=new ProductService(); Product product=new Product(); product.setCate_id(Integer.parseInt(cate_id)); product.setName(name); product.setThumbnail(thub); product.setSelling_description(selling_description); product.setDetail_description(detail_description); product.setInventory(Integer.parseInt(inventory)); product.setSales_volume(Integer.parseInt(sales_volume)); BigDecimal Price=new BigDecimal(price); BigDecimal sale_Price=new BigDecimal(sale_price); product.setPrice(Price); product.setSale_price(sale_Price); DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date= null; Date currtime=new Date(); String currstr=fmt.format(currtime); try { date = fmt.parse(sale_time); currtime=fmt.parse(currstr); } catch (ParseException e) { e.printStackTrace(); } product.setCreate_time(currtime); product.setSale_time(date); service.save(product); //跳转(重定向) response.sendRedirect(request.getContextPath() + "/member/product/list"); } }
38.944444
122
0.717546
97303675b8ec0288fdd740ea3cb6fe3e9535c7d0
3,374
/* * Copyright 2020 赖柄沣 bingfengdev@aliyun.com * * 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 pers.lbf.yeju.common.domain.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import java.io.Serializable; import java.util.Date; /** * 邮件发送日志表(YejuMailLog)表实体类 * * @author 赖柄沣 bingfengdev@aliyun.com * @since 2021-04-26 10:06:05 */ @TableName("table_mail_send_log") public class MailLog extends Model<MailLog> { /** * 邮件id */ @TableId private Long id; /** * 接收方 */ private String sendTo; /** * 邮件主题 */ private String subject; /** * 内容 */ private String content; /** * 邮件发送时间 */ private Date sendDate; /** * 发送状态 */ private Integer status; /** * 邮件类型,详细见配置表,分为营销邮件、鉴权邮件、通知邮件等 */ private String type; /** * 发送失败时的报错信息 */ private String errorMessage; /** * 抄送 */ private String cc; /** * 密送 */ private String bcc; private Date createTime; public Date getSendDate() { return sendDate; } public void setSendDate(Date sendDate) { this.sendDate = sendDate; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSendTo() { return sendTo; } public void setSendTo(String sendTo) { this.sendTo = sendTo; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } /** * 获取主键值 * * @return 主键值 */ @Override protected Serializable pkVal() { return this.id; } }
19.28
75
0.598992
4df2397c135aa4524d9a4b7ffc37aed9fb1eebf3
176
package com.cg.oct12.batch3.Day7; public class App { public static void main(String[] args) { String str="abc"; int num=Integer.parseInt(str); System.out.println(num); } }
17.6
40
0.715909
fef374ddb8b68a837599512f13e151a1621d1973
1,281
package p320f.p321a.p327d.p332e.p334b; import java.util.concurrent.atomic.AtomicReference; import p320f.p321a.C13804t; import p320f.p321a.p325b.C13194b; import p320f.p321a.p327d.p328a.C13218c; /* renamed from: f.a.d.e.b.Mb */ /* compiled from: ObserverResourceWrapper */ public final class C13408Mb<T> extends AtomicReference<C13194b> implements C13804t<T>, C13194b { /* renamed from: a */ final C13804t<? super T> f40774a; /* renamed from: b */ final AtomicReference<C13194b> f40775b = new AtomicReference<>(); public C13408Mb(C13804t<? super T> actual) { this.f40774a = actual; } public void onSubscribe(C13194b s) { if (C13218c.m43153c(this.f40775b, s)) { this.f40774a.onSubscribe(this); } } public void onNext(T t) { this.f40774a.onNext(t); } public void onError(Throwable t) { dispose(); this.f40774a.onError(t); } public void onComplete() { dispose(); this.f40774a.onComplete(); } public void dispose() { C13218c.m43150a(this.f40775b); C13218c.m43150a((AtomicReference<C13194b>) this); } /* renamed from: a */ public void mo42445a(C13194b resource) { C13218c.m43152b(this, resource); } }
24.634615
96
0.637783
2e4675051ae7887c11c28e853ca977aee4599ae9
228
package xyz.d1snin.commons.server_responses.model.files; import lombok.Data; import java.io.Serializable; @Data public class FileData implements Serializable { private final byte[] bytes; private final String fileName; }
19
56
0.79386
3922769a6b43fbb81d5f2534bbcb9e83dc7f7233
884
package org.jujubeframework.util; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; public class DatesTest { @Test public void isSameDay() { long t1 = Dates.getEpochSecond(LocalDateTime.of(2021, 1, 1, 10, 45, 8)); long t2 = Dates.getEpochSecond(LocalDateTime.of(2021, 1, 1, 18, 45, 8)); Assertions.assertThat(Dates.isSameDay(t1, t2)).isTrue(); t1 = Dates.getEpochSecond(LocalDateTime.of(2021, 1, 2, 10, 45, 8)); t2 = Dates.getEpochSecond(LocalDateTime.of(2021, 1, 1, 18, 45, 8)); Assertions.assertThat(Dates.isSameDay(t1, t2)).isFalse(); t1 = Dates.getEpochSecond(LocalDateTime.of(2021, 2, 1, 10, 45, 8)); t2 = Dates.getEpochSecond(LocalDateTime.of(2021, 1, 1, 18, 45, 8)); Assertions.assertThat(Dates.isSameDay(t1, t2)).isFalse(); } }
34
80
0.660633
f303ad65d26e23a19ca7579cc91fa991cd463995
2,743
package com.shopping_cart.services.impl; import com.shopping_cart.models.entities.BlackToken; import com.shopping_cart.models.service_models.BlackTokenServiceModel; import com.shopping_cart.repositories.BlackTokenRepository; import com.shopping_cart.services.AuthService; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDateTime; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import static com.shopping_cart.constants.AuthConstants.*; @Service public class AuthServiceImpl implements AuthService { private final BlackTokenRepository blackTokenRepository; private final ModelMapper modelMapper; @Autowired public AuthServiceImpl(BlackTokenRepository blackTokenRepository, ModelMapper modelMapper) { this.blackTokenRepository = blackTokenRepository; this.modelMapper = modelMapper; } public String createJwtToken(String userId, String userRole) { List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(userRole); List<String> authorities = grantedAuthorities.stream() .map(GrantedAuthority::getAuthority).collect(Collectors.toList()); /* Create new JWT token */ String token = Jwts.builder() .setId(userId) .claim("authorities", authorities) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRY_TIME)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY.getBytes()) .compact(); return String.format("Bearer %s", token); } @Override public Boolean blackTokenExist(String token) { BlackToken blackToken = blackTokenRepository.findBlackTokenByToken(token).orElse(null); return blackToken != null; } @Override @Transactional public BlackTokenServiceModel createBlackToken(String userId, String token) { BlackTokenServiceModel blackTokenServiceModel = new BlackTokenServiceModel(userId, token); blackTokenServiceModel.setAddedOn(LocalDateTime.now()); BlackToken blackToken = this.blackTokenRepository .saveAndFlush(this.modelMapper.map(blackTokenServiceModel, BlackToken.class)); return this.modelMapper.map(blackToken, BlackTokenServiceModel.class); } }
38.633803
113
0.751367
7647c636386dd39ce5981b4373cfab099809114a
2,354
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error.future; import static java.lang.String.format; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.future.ShouldHaveFailedWithin.shouldHaveFailedWithin; import static org.assertj.core.error.future.Warning.WARNING; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.assertj.core.internal.TestDescription; import org.junit.jupiter.api.Test; class ShouldHaveFailedWithin_create_Test { @Test void should_create_error_message_with_duration() { // GIVEN CompletableFuture<Object> actual = completedFuture("ok"); // WHEN String error = shouldHaveFailedWithin(actual, Duration.ofHours(1)).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + "Expecting%n" + " <CompletableFuture[Completed: \"ok\"]>%n" + "to have failed within 1H.%n%s", WARNING)); } @Test void should_create_error_message_with_time_unit() { // GIVEN Future<Object> actual = new CompletableFuture<>(); // WHEN String error = shouldHaveFailedWithin(actual, 1, TimeUnit.HOURS).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + "Expecting%n" + " <CompletableFuture[Incomplete]>%n" + "to have failed within 1L HOURS.%n%s", WARNING)); } }
39.233333
118
0.666525
4c864957ea56193fb242a72e8a09d96b2f908e61
403
package com.lnsf.rpc.domain.vo; import com.lnsf.rpc.domain.SysBill; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * 接收前端增加订单的数据 */ @Data @NoArgsConstructor @AllArgsConstructor public class SysBillVo implements Serializable { //订单信息 private SysBill sysBill; //若成功更新后场次的座位信息 private String sessionSeats; }
15.5
48
0.764268
b2fc44dde28897ef5f673d9936960f41111bb1d4
351
package com.github.daneko.android.iab; import android.app.Activity; import rx.Observable; import com.github.daneko.android.iab.model.ActivityResults; /** * 名前はあとで考える * そもそもこのInterfaceを強要するかabstract class にするか 引数にするか… */ public interface IabContext { Activity getActivity(); Observable<ActivityResults> getActivityResultObservable(); }
19.5
62
0.780627
56059fe6f69d28f4b6b72a807d2cc03e0a3c096b
608
package com.jfinal.template; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.jfinal.kit.Kv; public class EngineTest { static Engine engine; @BeforeClass public static void init() { engine = Engine.use(); engine.setToClassPathSourceFactory(); } @AfterClass public static void exit() { } @Test public void renderToString() { Kv para = Kv.by("key", "value"); String result = Engine.use().getTemplateByString("#(key)").renderToString(para); Assert.assertEquals("value", result); } }
20.266667
83
0.682566
3e201f6f21e21fea5e57b7339b9e40a48cba64f2
243
package com.innofang.callbackdemo.call_back_demo_0; /** * Author: Inno Fang * Time: 2017/3/15 17:04 * Description: */ public class Wang { public void doWork(CallBack callBack) { // 回调老板让做的事情 callBack.call(); } }
15.1875
51
0.633745
5f6a2dfc75a30fc96147ec999b3b9c658d307ebb
6,125
package com.soecode.lyf.controller; import com.soecode.lyf.entity.Role; import com.soecode.lyf.entity.params.Layui; import com.soecode.lyf.entity.result.ResultModel; import com.soecode.lyf.service.RoleService; import net.sf.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Map; @Controller @RequestMapping("/Role") @ResponseBody @CrossOrigin(origins = "http://cxuniversity.top") //允许这个域名就行跨域访问 public class RoleController { //日志 final static Logger logger = LoggerFactory.getLogger(AdministratorsController.class); @Autowired RoleService roleService; /** * 查询角色分类 * @return */ @RequestMapping(value = "/selectAllRole", method = RequestMethod.POST, produces = "application/json") public ResultModel selectAllRole(HttpServletRequest request, @RequestBody String responseData){ logger.info("查询数据库中全部角色信息->start"); net.sf.json.JSONObject responseList = net.sf.json.JSONObject.fromObject(responseData); List<Map<String,Object>> permissionList=(List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("permissionList")), Map.class); String permissionName = (String)responseList.get("permissionName"); List<Map<String,Object>> adminParamsList = (List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("adminParamsList")), Map.class); ResultModel result = roleService.selectAllRole(permissionList,permissionName,adminParamsList); logger.info("查询数据库中全部角色信息->end"); return result; } //查询角色信息 @RequestMapping(value = "/selectRole",method = RequestMethod.POST,produces="application/json") public Layui selectRole(HttpServletRequest request, @RequestBody String responseData) { logger.info("查询数据库中角色信息->start"); net.sf.json.JSONObject responseList = net.sf.json.JSONObject.fromObject(responseData); List<Map<String,Object>> permissionList=(List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("permissionList")), Map.class); String permissionName = (String)responseList.get("permissionName"); ResultModel result = roleService.selectRole(permissionList,permissionName); logger.info("查询数据库中角色信息->end"); if(result.getData() == ""){ List layUiData = new ArrayList<>(); return Layui.data(10,layUiData); } else{ return Layui.data(10, (List<?>)result.getData()); } } //删除角色 @RequestMapping(value = "/deleteByPrimaryKey",method = RequestMethod.POST,produces="application/json") public ResultModel deleteByPrimaryKey(HttpServletRequest request, @RequestBody String responseData) { logger.info("查询数据库中角色信息->start"); net.sf.json.JSONObject responseList = net.sf.json.JSONObject.fromObject(responseData); List<Map<String,Object>> permissionList=(List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("permissionList")), Map.class); String permissionName = (String)responseList.get("permissionName"); int roleId = (int)responseList.get("roleId"); ResultModel result = roleService.deleteByPrimaryKey(permissionList,permissionName,roleId); logger.info("查询数据库中角色信息->end"); return result; } //新增角色 @RequestMapping(value = "/insertRole",method = RequestMethod.POST,produces="application/json") public ResultModel insertRole(HttpServletRequest request, @RequestBody String responseData) { logger.info("新增数据库中角色信息->start"); net.sf.json.JSONObject responseList = net.sf.json.JSONObject.fromObject(responseData); List<Map<String,Object>> permissionList=(List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("permissionList")), Map.class); String permissionName = (String)responseList.get("permissionName"); Role role = new Role(); role.setRoleName((String) responseList.get("roleName")); role.setCreateBy((String) responseList.get("createBy")); role.setCreateData((String) responseList.get("createData")); role.setRoleLevel((int) responseList.get("roleLevel")); role.setRoleNnfo((String) responseList.get("roleNnfo")); List<Map<String,Object>> permissionRoleList = (List<Map<String,Object>>)responseList.get("permissionRoleList"); ResultModel result = roleService.insertRole(permissionList,permissionName,role,permissionRoleList); logger.info("新增数据库中角色信息->end"); return result; } //修改角色 @RequestMapping(value = "/updateRole",method = RequestMethod.POST,produces="application/json") public ResultModel updateRole(HttpServletRequest request, @RequestBody String responseData) { logger.info("修改数据库中角色信息->start"); net.sf.json.JSONObject responseList = net.sf.json.JSONObject.fromObject(responseData); List<Map<String,Object>> permissionList=(List<Map<String,Object>>)JSONArray.toList(JSONArray.fromObject(responseList.get("permissionList")), Map.class); String permissionName = (String)responseList.get("permissionName"); Role role = new Role(); role.setId((int)responseList.get("id")); role.setRoleName((String) responseList.get("roleName")); role.setUpdateBate((String) responseList.get("updateBate")); role.setUpdateBy((String) responseList.get("updateBy")); role.setRoleLevel((int) responseList.get("roleLevel")); role.setRoleNnfo((String) responseList.get("roleNnfo")); List<Map<String,Object>> permissionRoleList = (List<Map<String,Object>>)responseList.get("permissionRoleList"); ResultModel result = roleService.updateRole(permissionList,permissionName,role,permissionRoleList); logger.info("修改数据库中角色信息->end"); return result; } }
51.90678
164
0.722122
7a36eb32ff529dd61f5a958e351794c274d8c67b
1,128
package outskirtslabs.ruuvi; import lombok.Builder; import lombok.Value; /** * This class contains all the possible fields/data acquirable from a RuuviTag * in a "human format", for example the temperature as a decimal number rather * than an integer meaning one 200th of a degree. Not all fields are necessarily * present depending on the data format and implementations. */ @Value @Builder public class RuuviValue { Integer dataFormat; Double temperature; Double humidity; Double pressure; Double accelerationX; Double accelerationY; Double accelerationZ; Double batteryVoltage; Integer txPower; Integer movementCounter; Integer measurementSequenceNumber; /** * Timestamp in milliseconds, normally not populated to use local time */ Long time; /** * Friendly name for the tag */ String name; /** * MAC address of the tag as seen by the receiver */ String mac; /** * Arbitrary string associated with the receiver. */ String receiver; /** * The RSSI at the receiver */ Integer rssi; }
23.020408
80
0.677305
10b9e9a7538ff5c963d4859ec59e650af524df1d
33,179
package edu.northwestern.bioinformatics.studycalendar.service; import edu.northwestern.bioinformatics.studycalendar.core.Fixtures; import edu.northwestern.bioinformatics.studycalendar.core.StudyCalendarTestCase; import edu.northwestern.bioinformatics.studycalendar.core.accesscontrol.SecurityContextHolderTestHelper; import edu.northwestern.bioinformatics.studycalendar.dao.ActivityDao; import edu.northwestern.bioinformatics.studycalendar.dao.ScheduledActivityDao; import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Activity; import edu.northwestern.bioinformatics.studycalendar.domain.Epoch; import edu.northwestern.bioinformatics.studycalendar.domain.PlannedCalendar; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivity; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityMode; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledCalendar; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledStudySegment; import edu.northwestern.bioinformatics.studycalendar.domain.Site; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudySite; import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment; import edu.northwestern.bioinformatics.studycalendar.domain.delta.ChangeAction; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Delta; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Revision; import edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationObjectFactory; import edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationScopeMappings; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscUser; import edu.northwestern.bioinformatics.studycalendar.service.presenter.StudyWorkflowStatus; import edu.northwestern.bioinformatics.studycalendar.service.presenter.TemplateAvailability; import edu.northwestern.bioinformatics.studycalendar.service.presenter.WorkflowMessageFactory; import edu.nwu.bioinformatics.commons.DateUtils; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.StaticNowFactory; import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSession; import gov.nih.nci.cabig.ctms.suite.authorization.ProvisioningSessionFactory; import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole; import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembership; import gov.nih.nci.security.authorization.domainobjects.User; import org.easymock.classextension.EasyMock; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*; import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationObjectFactory.createPscUser; import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationScopeMappings.createSuiteRoleMembership; import static org.easymock.EasyMock.*; // TODO: this test is a mockful mess. It needs more stubs so that individual cases are clearer. public class StudyServiceTest extends StudyCalendarTestCase { private static final Timestamp NOW = DateTools.createTimestamp(2001, Calendar.FEBRUARY, 4); private StudyService service; private StudyDao studyDao; private SiteDao siteDao; private ActivityDao activityDao; private Study study; StudySubjectAssignment subjectAssignment; ScheduledCalendar calendar; StaticNowFactory staticNowFactory; private DeltaService deltaService; private ScheduledActivityDao scheduledActivityDao; private NotificationService notificationService; private ProvisioningSession pSession; private ProvisioningSessionFactory psFactory; private PscUserService pscUserService; @Override protected void setUp() throws Exception { super.setUp(); pSession = registerMockFor(ProvisioningSession.class); psFactory = registerMockFor(ProvisioningSessionFactory.class); studyDao = registerMockFor(StudyDao.class); siteDao = registerMockFor(SiteDao.class); deltaService = registerMockFor(DeltaService.class); scheduledActivityDao=registerDaoMockFor(ScheduledActivityDao.class); activityDao = registerMockFor(ActivityDao.class); notificationService=registerMockFor(NotificationService.class); staticNowFactory = new StaticNowFactory(); staticNowFactory.setNowTimestamp(NOW); pscUserService = registerMockFor(PscUserService.class); expect(pscUserService.isAuthorizationSystemReadOnly()).andStubReturn(false); WorkflowService ws = new WorkflowService(); ws.setApplicationSecurityManager(applicationSecurityManager); ws.setWorkflowMessageFactory(new WorkflowMessageFactory()); ws.setDeltaService(Fixtures.getTestingDeltaService()); service = new StudyService(); service.setStudyDao(studyDao); service.setSiteDao(siteDao); service.setActivityDao(activityDao); service.setDeltaService(deltaService); service.setNowFactory(staticNowFactory); service.setScheduledActivityDao(scheduledActivityDao); service.setNotificationService(notificationService); service.setApplicationSecurityManager(applicationSecurityManager); service.setWorkflowService(ws); service.setProvisioningSessionFactory(psFactory); service.setPscUserService(pscUserService); study = setId(1 , new Study()); calendar = new ScheduledCalendar(); subjectAssignment = new StudySubjectAssignment(); subjectAssignment.setSubject(createSubject("John", "Doe")); subjectAssignment.setScheduledCalendar(calendar); } @Override protected void tearDown() throws Exception { super.tearDown(); applicationSecurityManager.removeUserSession(); } public void testScheduleReconsentAfterScheduledActivityOnOccurredEvent() throws Exception{ staticNowFactory.setNowTimestamp(DateTools.createTimestamp(2005, Calendar.JULY, 2)); ScheduledStudySegment studySegment0 = new ScheduledStudySegment(); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("AAA", 2005, Calendar.JULY, 1)); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("BBB", 2005, Calendar.JULY, 2, ScheduledActivityMode.OCCURRED.createStateInstance(DateUtils.createDate(2005, Calendar.JULY, 3), null))); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("CCC", 2005, Calendar.JULY, 4)); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("DDD", 2005, Calendar.JULY, 8)); calendar.addStudySegment(studySegment0); ScheduledStudySegment studySegment1 = new ScheduledStudySegment(); studySegment1.addEvent(Fixtures.createScheduledActivityWithStudy("EEE", 2005, Calendar.AUGUST, 1, ScheduledActivityMode.OCCURRED.createStateInstance(DateUtils.createDate(2005, Calendar.AUGUST, 2), null))); studySegment1.addEvent(edu.northwestern.bioinformatics.studycalendar.core.Fixtures.createScheduledActivityWithStudy("FFF", 2005, Calendar.AUGUST, 3)); studySegment1.addEvent(Fixtures.createScheduledActivityWithStudy("GGG", 2005, Calendar.AUGUST, 8)); calendar.addStudySegment(studySegment1); List<StudySubjectAssignment> assignments = Collections.singletonList(subjectAssignment); expect(studyDao.getAssignmentsForStudy(study.getId())).andReturn(assignments); Activity reconsent = setId(1, createNamedInstance("Reconsent", Activity.class)); expect(activityDao.getByName("Reconsent")).andReturn(reconsent); studyDao.save(study); scheduledActivityDao.save(isA(ScheduledActivity.class)); replayMocks(); service.scheduleReconsent(study, staticNowFactory.getNow(), "Reconsent Details"); verifyMocks(); List<ScheduledActivity> list = studySegment0.getActivitiesByDate().get(DateTools.createTimestamp(2005, Calendar.JULY, 4)); assertEquals("Wrong number of events on July 4th", 2, list.size()); assertEquals("Reconsent Details should be details", "Reconsent Details", list.get(0).getDetails()); assertEquals("Reconsent should be activity name", "Reconsent", list.get(0).getActivity().getName()); } public void testScheduleReconsentForSecondArmOnSameDayAsScheduledActivity() throws Exception{ staticNowFactory.setNowTimestamp(DateTools.createTimestamp(2005, Calendar.AUGUST, 3)); ScheduledStudySegment studySegment0 = new ScheduledStudySegment(); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("AAA", 2005, Calendar.JULY, 1, ScheduledActivityMode.OCCURRED.createStateInstance(DateUtils.createDate(2005, Calendar.JULY, 2), null))); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("BBB", 2005, Calendar.JULY, 3)); studySegment0.addEvent(Fixtures.createScheduledActivityWithStudy("CCC", 2005, Calendar.JULY, 8)); calendar.addStudySegment(studySegment0); ScheduledStudySegment studySegment1 = new ScheduledStudySegment(); studySegment1.addEvent(Fixtures.createScheduledActivityWithStudy("DDD", 2005, Calendar.AUGUST, 1, ScheduledActivityMode.OCCURRED.createStateInstance(DateUtils.createDate(2005, Calendar.AUGUST, 2), null))); studySegment1.addEvent(Fixtures.createScheduledActivityWithStudy("EEE", 2005, Calendar.AUGUST, 3)); studySegment1.addEvent(Fixtures.createScheduledActivityWithStudy("FFF", 2005, Calendar.AUGUST, 8)); calendar.addStudySegment(studySegment1); List<StudySubjectAssignment> assignments = Collections.singletonList(subjectAssignment); expect(studyDao.getAssignmentsForStudy(study.getId())).andReturn(assignments); Activity reconsent = setId(1, createNamedInstance("Reconsent", Activity.class)); expect(activityDao.getByName("Reconsent")).andReturn(reconsent); scheduledActivityDao.save(isA(ScheduledActivity.class)); studyDao.save(study); replayMocks(); service.scheduleReconsent(study, staticNowFactory.getNow(), "Reconsent Details"); verifyMocks(); List<ScheduledActivity> list = studySegment1.getActivitiesByDate().get(DateTools.createTimestamp(2005, Calendar.AUGUST, 3)); assertEquals("Wrong number of events on August 8th", 2, list.size()); assertEquals("Reconsent Details should be details", "Reconsent Details", list.get(0).getDetails()); assertEquals("Reconsent should be activity name", "Reconsent", list.get(0).getActivity().getName()); } public void testSendMailForScheduleReconsent() throws Exception { staticNowFactory.setNowTimestamp(DateTools.createTimestamp(2005, Calendar.JULY, 2)); study.setAssignedIdentifier("testStudy"); ScheduledStudySegment studySegment = new ScheduledStudySegment(); studySegment.addEvent(Fixtures.createScheduledActivity("AAA", 2005, Calendar.JULY, 4)); expect(activityDao.getByName("Reconsent")).andReturn(setId(1, createNamedInstance("Reconsent", Activity.class))); scheduledActivityDao.save(isA(ScheduledActivity.class)); studyDao.save(study); calendar.addStudySegment(studySegment); User SSCM = AuthorizationObjectFactory.createCsmUser(1, "testUser"); SSCM.setEmailId("testUser@email.com"); subjectAssignment.setStudySubjectCalendarManager(SSCM); expect(studyDao.getAssignmentsForStudy(study.getId())).andReturn(Arrays.asList(subjectAssignment)); String subject = "Subjects on testStudy need to be reconsented"; String message = "A reconsent activity with details Reconsent Details has been added to the schedule of each subject on testStudy." + " Check your dashboard for upcoming subjects that need to be reconsented."; notificationService.sendNotificationMailToUsers(subject, message, Arrays.asList(SSCM.getEmailId())); replayMocks(); service.scheduleReconsent(study, staticNowFactory.getNow(), "Reconsent Details"); verifyMocks(); } public void testSave() { Study expected = createNamedInstance("Study A", Study.class); Amendment amend0 = Fixtures.createAmendments("Amendment A"); Amendment amend1 = Fixtures.createAmendments("Amendment B"); amend1.setPreviousAmendment(amend0); expected.setAmendment(amend1); studyDao.save(expected); deltaService.saveRevision(amend1); deltaService.saveRevision(amend0); replayMocks(); service.save(expected); verifyMocks(); } public void testDefaultManagingSitesSetFromUser() throws Exception { List<Site> sites = Arrays.asList(createSite("A", "A"), createSite("B", "B")); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(sites); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); createAndExpectSession(principal); Study expected = createNamedInstance("A", Study.class); studyDao.save(expected); expect(siteDao.reassociate(sites)).andReturn(sites); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Wrong number of managing sites", 2, expected.getManagingSites().size()); Iterator<Site> siteIterator = expected.getManagingSites().iterator(); assertEquals("Wrong 1st managing site", "A", siteIterator.next().getAssignedIdentifier()); assertEquals("Wrong 2nd managing site", "B", siteIterator.next().getAssignedIdentifier()); } public void testDefaultManagingSitesForAllSitesUser() throws Exception { PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forAllSites(); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); createAndExpectSession(principal); Study expected = createNamedInstance("A", Study.class); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Wrong number of managing sites", 0, expected.getManagingSites().size()); } public void testNoManagingSitesSetFromNonBuilderUser() throws Exception { PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_QA_MANAGER). forSites(createSite("A", "A"), createSite("B", "B")); principal.getMemberships().put(SuiteRole.STUDY_QA_MANAGER, mem); createAndExpectSession(principal); Study expected = createNamedInstance("A", Study.class); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Wrong number of managing sites", 0, expected.getManagingSites().size()); } public void testNoManagingSitesSetWithNoUser() throws Exception { applicationSecurityManager.removeUserSession(); Study expected = createNamedInstance("A", Study.class); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Wrong number of managing sites", 0, expected.getManagingSites().size()); } public void testManagingSitesNotChangedForUpdates() throws Exception { SecurityContextHolderTestHelper.setSecurityContext( createPscUser("sherry", createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER). forSites(createSite("A", "A"), createSite("B", "B"))), "secret" ); Study expected = setId(4, createNamedInstance("A", Study.class)); expected.addManagingSite(createSite("C")); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Wrong number of managing sites", 1, expected.getManagingSites().size()); Iterator<Site> siteIterator = expected.getManagingSites().iterator(); assertEquals("Wrong 1st managing site", "C", siteIterator.next().getName()); } public void testApplyDefaultStudyAccess() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); SCTB = expectCreateAndGetMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, false, site1); createAndExpectSession(principal); pSession.replaceRole(SCTB); studyDao.save(expected); assertEquals("Membership made for specified study", 0, SCTB.getStudyIdentifiers().size()); assertFalse("Membership made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(Arrays.asList(site1)); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Membership not made for specified study", 1, SCTB.getStudyIdentifiers().size()); assertTrue("Membership not made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); } public void testApplyDefaultStudyAccessDoesNothingWhenAuthorizationSystemIsReadOnly() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); SecurityContextHolderTestHelper.setSecurityContext(principal, "secret"); expect(pscUserService.isAuthorizationSystemReadOnly()).andReturn(true); studyDao.save(expected); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(Arrays.asList(site1)); replayMocks(); service.save(expected); verifyMocks(); } public void testApplyDefaultStudyAccessWhenUserHasNoAccessToSite() throws Exception { Site site1 = createSite("Site1", "Site1"); Site site2 = createSite("Site2", "Site2"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(site2); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); SCTB = expectCreateAndGetMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, false, site2); List<Site> sites = Arrays.asList(site1); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(sites); createAndExpectSession(principal); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Membership made for specified study", 0, SCTB.getStudyIdentifiers().size()); assertFalse("Membership made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); } public void testApplyDefaultStudyAccessWhenUserIsNotBuilderAndCreator() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); List<Site> sites = Arrays.asList(site1); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(sites); SuiteRoleMembership SCTB = principal.getMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER); createAndExpectSession(principal); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); assertNull("Membership SCTB made for specified study", SCTB); assertFalse("Membership made for specified study", principal.getMembership(PscRole.STUDY_CREATOR).getStudyIdentifiers().contains(expected.getAssignedIdentifier())); } public void testApplyDefaultStudyAccessWhenBuilderUserHasAllStudies() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership mem = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, mem); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(site1).forAllStudies(); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); createAndExpectSession(principal); expect(pSession.getProvisionableRoleMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER)).andReturn(SCTB); List<Site> sites = Arrays.asList(site1); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(sites); studyDao.save(expected); replayMocks(); service.save(expected); verifyMocks(); } public void testApplyDefaultStudyAccessWhenCreatorHasAllSites() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership SC = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forAllSites(); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, SC); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); SCTB = expectCreateAndGetMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, false, site1); createAndExpectSession(principal); studyDao.save(expected); pSession.replaceRole(SCTB); assertEquals("Membership made for specified study", 0, SCTB.getStudyIdentifiers().size()); assertFalse("Membership made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Membership not made for specified study", 1, SCTB.getStudyIdentifiers().size()); assertTrue("Membership not made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); } public void testApplyDefaultStudyAccessWhenBuilderHasAllSites() throws Exception { Site site1 = createSite("Site1", "Site1"); Study expected = createNamedInstance("A", Study.class); expected.setAssignedIdentifier("StudyA"); PscUser principal = createUserAndSetCsmId(); SuiteRoleMembership SC = createSuiteRoleMembership(PscRole.STUDY_CREATOR).forSites(site1); principal.getMemberships().put(SuiteRole.STUDY_CREATOR, SC); SuiteRoleMembership SCTB = createSuiteRoleMembership(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forAllSites(); principal.getMemberships().put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, SCTB); createAndExpectSession(principal); expect(pSession.getProvisionableRoleMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER)).andReturn(SCTB); studyDao.save(expected); pSession.replaceRole(SCTB); List<Site> sites = Arrays.asList(site1); expect(siteDao.reassociate(Arrays.asList(site1))).andReturn(sites); assertEquals("Membership made for specified study", 0, SCTB.getStudyIdentifiers().size()); assertFalse("Membership made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); replayMocks(); service.save(expected); verifyMocks(); assertEquals("Membership not made for specified study", 1, SCTB.getStudyIdentifiers().size()); assertTrue("Membership not made for specified study", SCTB.getStudyIdentifiers().contains(expected.getAssignedIdentifier())); } //Helper Methods private SuiteRoleMembership expectCreateAndGetMembership(SuiteRole expectedRole, Boolean isNull, Site site){ SuiteRoleMembership srm = AuthorizationScopeMappings.createSuiteRoleMembership(PscRole.valueOf(expectedRole)).forSites(site); if (isNull) { expect(pSession.getProvisionableRoleMembership(expectedRole)).andReturn(null); } else { expect(pSession.getProvisionableRoleMembership(expectedRole)).andReturn(srm); } return srm; } private PscUser createUserAndSetCsmId() { PscUser principal = createPscUser("sherry"); principal.getCsmUser().setUserId(111L); return principal; } private void createAndExpectSession(PscUser principal) { SecurityContextHolderTestHelper.setSecurityContext(principal,"secret"); expect(psFactory.createSession(principal.getCsmUser().getUserId())).andStubReturn(pSession); } public void testGetNewStudyName() { Study study1 = createNamedInstance("[ABC 1000]", Study.class); Study study2 = createNamedInstance("[ABC temp]", Study.class); Study study3 = createNamedInstance("[ABC 1001]", Study.class); List<Study> studies = new ArrayList<Study>(); studies.add(study1); studies.add(study2); studies.add(study3); expect(service.getStudyDao().searchStudiesByAssignedIdentifier("[ABC %]")).andReturn(studies); replayMocks(); String studyName = service.getNewStudyName(); verifyMocks(); assertNotNull("New study name is null", studyName); assertEquals("Expected new study name is not the same", "[ABC 1002]", studyName); } public void testCreateInDesignStudyFromExamplePlanTree() throws Exception { Study example = Fixtures.createBasicTemplate(); PlannedCalendar expectedPC = example.getPlannedCalendar(); // copy the list since the one in the PC is destroyed in the tested method List<Epoch> expectedEpochs = new ArrayList<Epoch>(expectedPC.getEpochs()); example.setAssignedIdentifier("nerf-herder"); studyDao.save(example); deltaService.saveRevision((Revision) EasyMock.notNull()); replayMocks(); service.createInDesignStudyFromExamplePlanTree(example); verifyMocks(); assertNotNull("Development amendment not added", example.getDevelopmentAmendment()); assertEquals("Development amendment has wrong name", Amendment.INITIAL_TEMPLATE_AMENDMENT_NAME, example.getDevelopmentAmendment().getName()); assertEquals("Wrong number of deltas in the new dev amendment", 1, example.getDevelopmentAmendment().getDeltas().size()); Delta<?> actualDelta = example.getDevelopmentAmendment().getDeltas().get(0); assertEquals("Wrong kind of delta in the new dev amendment", expectedPC, actualDelta.getNode()); assertEquals("Wrong number of changes in created delta", expectedEpochs.size(), actualDelta.getChanges().size()); for (int i = 0; i < expectedEpochs.size(); i++) { assertEquals(i + " change is not an add", ChangeAction.ADD, actualDelta.getChanges().get(i).getAction()); assertSame(i + " change is not an add of the correct epoch", expectedEpochs.get(i), ((Add) actualDelta.getChanges().get(i)).getChild()); } } public void testGetVisibleTemplates() throws Exception { Site nu = setId(18, createSite("NU", "IL090")); Study readyAndInDev = assignIds(createBasicTemplate("R")); StudySite nuR = setId(81, readyAndInDev.addSite(nu)); nuR.approveAmendment(readyAndInDev.getAmendment(), new Date()); readyAndInDev.setDevelopmentAmendment(new Amendment()); Study pending = assignIds(createBasicTemplate("P"), 2); Study inDev = assignIds(createInDevelopmentBasicTemplate("D"), 5); PscUser user = AuthorizationObjectFactory.createPscUser("jo", createSuiteRoleMembership(PscRole.STUDY_QA_MANAGER).forAllSites(), createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllSites().forAllStudies()); expect(studyDao.searchVisibleStudies(user.getVisibleStudyParameters(), null)). andReturn(Arrays.asList(pending, readyAndInDev, inDev)); replayMocks(); Map<TemplateAvailability, List<StudyWorkflowStatus>> actual = service.getVisibleStudies(user); verifyMocks(); System.out.println(actual); List<StudyWorkflowStatus> actualPending = actual.get(TemplateAvailability.PENDING); assertEquals("Wrong number of pending templates", 1, actualPending.size()); assertEquals("Wrong pending template", "P", actualPending.get(0).getStudy().getAssignedIdentifier()); List<StudyWorkflowStatus> actualAvailable = actual.get(TemplateAvailability.AVAILABLE); assertEquals("Wrong number of available templates", 1, actualAvailable.size()); assertEquals("Wrong available template", "R", actualAvailable.get(0).getStudy().getAssignedIdentifier()); List<StudyWorkflowStatus> actualDev = actual.get(TemplateAvailability.IN_DEVELOPMENT); assertEquals("Wrong number of dev templates", 2, actualDev.size()); assertEquals("Wrong 1st dev template", "D", actualDev.get(0).getStudy().getAssignedIdentifier()); assertEquals("Wrong 2nd dev template", "R", actualDev.get(1).getStudy().getAssignedIdentifier()); } public void testSearchVisibleTemplates() throws Exception { Study inDev = createInDevelopmentBasicTemplate("D"); PscUser user = AuthorizationObjectFactory.createPscUser("jo", createSuiteRoleMembership(PscRole.STUDY_QA_MANAGER).forAllSites(), createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllSites().forAllStudies()); expect(studyDao.searchVisibleStudies(user.getVisibleStudyParameters(), "d")). andReturn(Arrays.asList(inDev)); replayMocks(); Map<TemplateAvailability, List<StudyWorkflowStatus>> actual = service.searchVisibleStudies(user, "d"); verifyMocks(); System.out.println(actual); assertEquals("Wrong number of pending templates", 0, actual.get(TemplateAvailability.PENDING).size()); assertEquals("Wrong number of available templates", 0, actual.get(TemplateAvailability.AVAILABLE).size()); List<StudyWorkflowStatus> actualDev = actual.get(TemplateAvailability.IN_DEVELOPMENT); assertEquals("Wrong number of dev templates", 1, actualDev.size()); assertEquals("Wrong 1st dev template", "D", actualDev.get(0).getStudy().getAssignedIdentifier()); } }
50.732416
158
0.731668
f77dbce386e7f0471d48e919a375be14939cf538
899
package com.yjl.spring.service.impl; import com.yjl.spring.dao.User2MovieTagDao; import com.yjl.spring.model.User2MovieTag; import com.yjl.spring.service.MovieTagService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; /** * Created by ziew on 2015/5/24. */ @Service public class MovieTagServiceImpl implements MovieTagService { User2MovieTagDao user2MovieTagDao; @Resource public void setUser2MovieTagDao(User2MovieTagDao user2MovieTagDao) { this.user2MovieTagDao = user2MovieTagDao; } public int addTag(int userId, int movieId, String tag) { User2MovieTag movieTag=new User2MovieTag(); movieTag.setMovieId(movieId); movieTag.setUserId(userId); movieTag.setTag(tag); movieTag.setTagTime(new Date()); return user2MovieTagDao.insertSelective(movieTag); } }
29
72
0.741935
5c9057b1314c25d5583838f6bd521157bb1c9b88
1,174
package Graphs.BFS; import java.util.ArrayDeque; import java.util.ArrayList; class Graph{ private int V; private ArrayList<ArrayList<Integer>>adj=null; Graph(int V){ this.V=V; adj=new ArrayList<>(); //intialize V empty lists for(int i=0;i<V;i++){ adj.add(new ArrayList<Integer>()); } } //add a new element to adjacency lists void add(int V,int n){ adj.get(V).add(n); } //BFD traversal void bfs(int start){ boolean[] visited=new boolean[V]; ArrayDeque<Integer> nodes=new ArrayDeque<>(); nodes.push(start); while(!nodes.isEmpty()){ Integer data=nodes.poll(); visited[data]=true; System.out.println(data); ArrayList<Integer>lis=adj.get(data); for(Integer ele : lis){ if(visited[ele]==true) continue; else{ nodes.addLast(ele); } } } } } public class BFS { public static void main(String[] args){ Graph gs=new Graph(4); gs.add(2, 0); gs.add(2,3); gs.add(0,0); gs.add(0,2); gs.add(3,1); gs.add(1,1); gs.add(1,0); gs.bfs(2); } }
18.634921
50
0.545997
79389c07a8afdb99109f33501b34ec6d08a7f18f
1,086
package es.upm.miw.apaw_ep_fernanda_guerra.order_resource; import es.upm.miw.apaw_ep_fernanda_guerra.exceptions.BadRequestException; public class OrderBasicDto { private String id; private Double total; public OrderBasicDto() { } public OrderBasicDto(Order order) { this.id = order.getId(); this.total = order.getTotal(); } public OrderBasicDto(String id, Double total) { this.id = id; this.total = total; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public void validate() { if (total == null || total.isNaN()) { throw new BadRequestException("Incomplete, lost total"); } } @Override public String toString() { return "OrderBasicDto{" + "id='" + id + '\'' + ", total='" + total + '\'' + '}'; } }
19.745455
73
0.549724
924f318db872e3c50d2a0572c1ef2b8483e86cfa
14,838
/* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package thredds.cataloggen.config; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import thredds.catalog.*; import thredds.cataloggen.TestCatalogGen; import thredds.cataloggen.DatasetEnhancer1; import java.io.*; /** * */ public class TestDatasetSource { //static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestDatasetSource.class); private boolean debugShowCatalogs = false; private DatasetSource me1 = null; private DatasetSource me2 = null; private DatasetSource me3 = null; private InvDatasetImpl parentDs1 = null; private String name1 = null; private String name2 = null; private String typeName1 = null; private String typeName2 = null; private String typeName3 = null; private String structName1 = null; private String structName2 = null; private String accessPoint1 = null; private String accessPoint2 = null; private StringBuilder out = null; @Before public void setUp() { String parentDsName1 = "parent dataset 1"; parentDs1 = new InvDatasetImpl( null, parentDsName1 ); name1 = "name 1"; name2 = "name 2"; typeName1 = "Local"; typeName2 = "DodsFileServer"; typeName3 = "DodsDir"; DatasetSourceType type1 = DatasetSourceType.getType( typeName1 ); DatasetSourceType type2 = DatasetSourceType.getType( typeName2 ); DatasetSourceType type3 = DatasetSourceType.getType( typeName3 ); structName1 = "Flat"; structName2 = "DirTree"; DatasetSourceStructure structure1 = DatasetSourceStructure.getStructure( structName1 ); accessPoint1 = "access point 1"; accessPoint2 = "access point 2"; out = new StringBuilder(); ResultService rService = new ResultService( "fred", ServiceType.DODS, "http://server/dods", null, "access point header 1"); me1 = DatasetSource.newDatasetSource( name1, type1, structure1, accessPoint1, rService ); me2 = DatasetSource.newDatasetSource( name1, type2, structure1, accessPoint1, rService ); me3 = DatasetSource.newDatasetSource( name1, type3, structure1, accessPoint1, rService ); } //protected void tearDown() //{ // out = null; // //parentDs = null; //} // Test expand on a flat collection dataset. //@Test public void testExpandFlat() throws IOException { File expectedCatDocFile = new File( "src/test/data/thredds/cataloggen/config/test1ResultCatalog1.0.dss.xml" ); String service1Name = "myServer"; String service1Type = "DODS"; String service1Base = "/dods/"; String service1Suffix = null; String service1AccessPointHeader = "./src/test/data/thredds/cataloggen/"; ResultService service1 = new ResultService( service1Name, ServiceType.getType( service1Type), service1Base, service1Suffix, service1AccessPointHeader); String accessPoint = "./src/test/data/thredds/cataloggen/testData/model"; me1 = DatasetSource.newDatasetSource( "NCEP Eta 80km CONUS model data", DatasetSourceType.LOCAL, DatasetSourceStructure.FLAT, accessPoint, service1 ); DatasetFilter dsF = new DatasetFilter( me1, "Accept netCDF Eta 211 files only", DatasetFilter.Type.REGULAR_EXPRESSION, "/[0-9]*_eta_211\\.nc$"); me1.addDatasetFilter( dsF); dsF = new DatasetFilter( me1, "reject all subdirs", DatasetFilter.Type.REGULAR_EXPRESSION, ".*", true, false, true); me1.addDatasetFilter( dsF ); InvDataset ds = me1.expand(); TestCatalogGen.compareCatalogToCatalogDocFile( ds.getParentCatalog(), expectedCatDocFile, debugShowCatalogs ); } // Expand a nested collection dataset using directory filtering. //@Test public void testExpandNotFlatWithDirFilter() throws IOException { File expectedCatalogDocFile = new File( "src/test/data/thredds/cataloggen/config/testDsfDirFilter1.ResultCatalog1.0.xml"); String service1Name = "myServer"; String service1Type = "DODS"; String service1Base = "/dods/"; String service1Suffix = null; String service1AccessPointHeader = "./src/test/data/thredds/cataloggen/"; ResultService service1 = new ResultService( service1Name, ServiceType.getType( service1Type), service1Base, service1Suffix, service1AccessPointHeader); String service1AccessPoint = "./src/test/data/thredds/cataloggen/testData/modelNotFlat"; me1 = DatasetSource.newDatasetSource( "NCEP Eta 80km CONUS model data", DatasetSourceType.LOCAL, DatasetSourceStructure.FLAT, service1AccessPoint, service1 ); DatasetFilter dsF = new DatasetFilter( me1, "Accept netCDF Eta 211 files only", DatasetFilter.Type.REGULAR_EXPRESSION, "/[0-9][^/]*_eta_211\\.nc$"); me1.addDatasetFilter( dsF); DatasetFilter dsF2 = new DatasetFilter( me1, "Accept Eta 211 directory only", DatasetFilter.Type.REGULAR_EXPRESSION, "eta_211$", true, false, false); me1.addDatasetFilter( dsF2); DatasetFilter dsF3 = new DatasetFilter( me1, "Reject .svn directory only", DatasetFilter.Type.REGULAR_EXPRESSION, ".svn$", true, false, true); me1.addDatasetFilter( dsF3); InvDataset ds = me1.expand(); // Compare the resulting catalog an the expected catalog resource. TestCatalogGen.compareCatalogToCatalogDocFile(ds.getParentCatalog(), expectedCatalogDocFile, debugShowCatalogs); } // Expand a nested collection dataset creating catalogRefs for all sub-collection datasets. //@Test public void testExpandNotFlatWithAllCatalogRef() throws IOException { File expectedCatalogDocFile = new File( "src/test/data/thredds/cataloggen/config/testDatasetSource.allCatalogRef.result.xml"); String service1Name = "myServer"; String service1Type = "DODS"; String service1Base = "/dods/"; String service1Suffix = null; String service1AccessPointHeader = "./src/test/data/thredds/cataloggen/"; ResultService service1 = new ResultService( service1Name, ServiceType.getType( service1Type ), service1Base, service1Suffix, service1AccessPointHeader ); String service1AccessPoint = "./src/test/data/thredds/cataloggen/testData/modelNotFlat"; me1 = DatasetSource.newDatasetSource( "NCEP Eta 80km CONUS model data", DatasetSourceType.LOCAL, DatasetSourceStructure.FLAT, service1AccessPoint, service1 ); me1.setCreateCatalogRefs( true ); DatasetFilter dsF = new DatasetFilter( me1, "Accept 'eta_211' and 'gfs_211' directories", DatasetFilter.Type.REGULAR_EXPRESSION, "_211$", true, false, false ); me1.addDatasetFilter( dsF ); InvDataset ds = me1.expand(); // Compare the resulting catalog an the expected catalog resource. TestCatalogGen.compareCatalogToCatalogDocFile( ds.getParentCatalog(), expectedCatalogDocFile, debugShowCatalogs ); } // Expand a nested collection dataset creating catalogRefs for all sub-collection datasets. // ToDo Fix this test. (Why String compare passes but object compare fails?) //@Test public void testExpandFlatAddTimecoverage() throws IOException { File expectedCatalogDocFile = new File( "src/test/data/thredds/cataloggen/config/testDsSource.expandFlatAddTimecoverage.result.xml" ); String serviceName = "localServer"; String serviceType = "DODS"; String serviceBase = "http://localhost:8080/thredds/dodsC/"; String serviceSuffix = null; String serviceAccessPointHeader = "./src/test/data/thredds/cataloggen/testData"; ResultService service = new ResultService( serviceName, ServiceType.getType( serviceType), serviceBase, serviceSuffix, serviceAccessPointHeader); String service1AccessPoint = "./src/test/data/thredds/cataloggen/testData/model"; me1 = DatasetSource.newDatasetSource( "NCEP Eta 80km CONUS model data", DatasetSourceType.LOCAL, DatasetSourceStructure.FLAT, service1AccessPoint, service ); me1.setCreateCatalogRefs( true); me1.addDatasetFilter( new DatasetFilter( me1, "no CVS", DatasetFilter.Type.REGULAR_EXPRESSION, "CVS", true, false, true)); me1.addDatasetEnhancer( DatasetEnhancer1.createAddTimeCoverageEnhancer( "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])", "$1-$2-$3T$4:00:00", "60 hours" ) ); InvCatalog cat = me1.fullExpand(); // Compare the resulting catalog an the expected catalog resource. TestCatalogGen.compareCatalogToCatalogDocFile( cat, expectedCatalogDocFile, true); } @Test public void testGetSet() { assertTrue( me1.getName().equals( name1)); me1.setName( name2); assertTrue( me1.getName().equals( name2)); } @Test public void testType() { // Make sure the type names set above are correct. assertTrue( DatasetSourceType.LOCAL.toString().equals( typeName1)); assertTrue( DatasetSourceType.DODS_FILE_SERVER.toString().equals( typeName2)); assertTrue( DatasetSourceType.DODS_DIR.toString().equals( typeName3)); // Test the DatasetSource.getType() function for each DatasetSource type. assertTrue( me1.getType().equals( DatasetSourceType.getType( typeName1))); assertTrue( me2.getType().equals( DatasetSourceType.getType( typeName2))); assertTrue( me3.getType().equals( DatasetSourceType.getType( typeName3))); } @Test public void testStructure() { // Make sure the structure names set above are correct. assertTrue( DatasetSourceStructure.FLAT.toString().equals( structName1)); assertTrue( DatasetSourceStructure.DIRECTORY_TREE.toString().equals( structName2)); // Test the DatasetSource.getStructure() function. assertTrue( me1.getStructure().equals( DatasetSourceStructure.getStructure( structName1))); // Test DatasetSource.setStructure( DatasetSourceStructure) me1.setStructure( DatasetSourceStructure.getStructure( structName2 ) ); assertTrue( me1.getStructure().toString().equals( structName2 ) ); } @Test public void testAccessPoint() { // Test DatasetSource.getAccessPoint() assertTrue( me1.getAccessPoint().equals( accessPoint1)); // Test DatasetSource.setAccessPoint( String) me1.setAccessPoint( accessPoint2); assertTrue( me1.getAccessPoint().equals( accessPoint2)); } @Test public void testResultService() { // Test DatasetSource.getResultService() when no ResultService. assertTrue( me1.getResultService().getAccessPointHeader() .equals( "access point header 1")); // Test ResultService getter and setter. me1.setResultService( new ResultService( "service name", ServiceType.DODS, "base url", "suffix", "access point header" ) ); assertTrue( me1.getResultService().getAccessPointHeader() .equals( "access point header")); } @Test public void testDatasetNamer() { // Test DatasetSource.getDatasetNamerList() when no namers. assertTrue( me1.getDatasetNamerList().isEmpty() ); // Test DatasetSource.addDatasetNamer( DatasetNamer) DatasetNamer namer = new DatasetNamer( parentDs1, "dsNamer name", true, DatasetNamerType.REGULAR_EXPRESSION, "match pattern", "substitute pattern", "attrib container", "attrib name" ); me1.addDatasetNamer( namer ); assertTrue( me1.getDatasetNamerList().contains( namer) ); } @Test public void testValid() { boolean bool; bool = me1.validate( out); assertTrue( out.toString(), bool ); } }
43.513196
139
0.654873
e6ba7cfbe7240506d5296462beb6d2ef0fa03e33
748
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.app; import java.util.List; // Referenced classes of package android.support.v4.app: // ActivityCompatApi23 public static abstract class ActivityCompatApi23$SharedElementCallback23 extends ActivityCompatApi21$SharedElementCallback21 { public abstract void onSharedElementsArrived(List list, List list1, tenerBridge tenerbridge); public ActivityCompatApi23$SharedElementCallback23() { // 0 0:aload_0 // 1 1:invokespecial #11 <Method void ActivityCompatApi21$SharedElementCallback21()> // 2 4:return } }
31.166667
124
0.748663
1212bc8475bf356721c830c3569eb765d08170d0
7,717
package com.jsplec.wp.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import com.jsplec.wp.dto.MyPageDto; public class MyPageDao { DataSource dataSource; public MyPageDao() { try { Context context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/mvc"); }catch (Exception e) { e.printStackTrace(); } } // 유저정보 public MyPageDto myPageUserinfoView(int userno) { MyPageDto dto = null; Connection connection = null; PreparedStatement preparedStatement = null; //검색하는거 pre이거있어야됨 ResultSet resultSet = null; try { connection = dataSource.getConnection(); String query = "select usertel,useraddress1, useraddress2,useraddress3,usergender,userjoindate,userbday,usersubscribe from userinfo where userno = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, userno); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String usertel = resultSet.getString("usertel"); String useraddress1 = resultSet.getString("useraddress1"); String useraddress2 = resultSet.getString("useraddress2"); String useraddress3 = resultSet.getString("useraddress3"); String usergender = resultSet.getString("usergender"); String userjoindate = resultSet.getString("userjoindate"); String userbday = resultSet.getString("userbday"); int usersubscribe = resultSet.getInt("usersubscribe"); dto = new MyPageDto(usertel,useraddress1,useraddress2, useraddress3,usergender,userjoindate,userbday,usersubscribe); } }catch (Exception e) { e.printStackTrace(); }finally { try { if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } return dto; } // 내가쓴 후기글 정보 public ArrayList<MyPageDto> myPageReviewView(String userid) { ArrayList<MyPageDto> dtos= new ArrayList<MyPageDto>(); MyPageDto dto = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = dataSource.getConnection(); String query = "select reno,reuserid,retitle,rescore,reinsertdate,reviewcount from review where reuserid = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, userid); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { int reno = resultSet.getInt("reno"); String reuserid = resultSet.getString("reuserid"); String retitle = resultSet.getString("retitle"); int rescore = resultSet.getInt("rescore"); String reinsertdate = resultSet.getString("reinsertdate"); int reviewcount = resultSet.getInt("reviewcount"); dto = new MyPageDto(reno,reuserid,retitle,rescore,reinsertdate,reviewcount); dtos.add(dto); } }catch (Exception e) { e.printStackTrace(); }finally { try { if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } return dtos; } // 내 구독 정보 public MyPageDto myPageSubscribeView(int userno) { MyPageDto dto = null; Connection connection = null; PreparedStatement preparedStatement = null; //검색하는거 pre이거있어야됨 ResultSet resultSet = null; try { connection = dataSource.getConnection(); String query = "select ssubno,speriod,sbottle,senddate,suserno,startdate,enddate, sprice from subscribe where suserno = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, userno); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { int ssubno = resultSet.getInt("ssubno"); String speriod = resultSet.getString("speriod"); String sbottle = resultSet.getString("sbottle"); String senddate = resultSet.getString("senddate"); int suserno = resultSet.getInt("suserno"); String startdate = resultSet.getString("startdate"); String enddate = resultSet.getString("enddate"); String sprice = resultSet.getString("sprice"); dto = new MyPageDto(ssubno,speriod,sbottle,senddate,suserno,startdate,enddate, sprice); } }catch (Exception e) { e.printStackTrace(); }finally { try { if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } return dto; } public MyPageDto deliveryUserinfoView(String duserid) { MyPageDto dto = null; Connection connection = null; PreparedStatement preparedStatement = null; //검색하는거 pre이거있어야됨 ResultSet resultSet = null; try { connection = dataSource.getConnection(); String query = "select dtel, daddress1, daddress2,daddress3, dusername, dmsg from delivery where duserid = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, duserid); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String dtel = resultSet.getString("dtel"); String daddress1 = resultSet.getString("daddress1"); String daddress2 = resultSet.getString("daddress2"); String daddress3 = resultSet.getString("daddress3"); String dusername1 = resultSet.getString("dusername"); String dmsg = resultSet.getString("dmsg"); dto = new MyPageDto(dtel,daddress1,daddress2, daddress3, dusername1, dmsg); } }catch (Exception e) { e.printStackTrace(); }finally { try { if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } return dto; } public void deliveryUpdate(String duserid, String dusername,String dtel, String daddress1,String daddress2, String daddress3, String dmsg) { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dataSource.getConnection(); String query = "update delivery set dusername=?,dtel=? , daddress1=?,daddress2=?,daddress3= ?, dmsg = ? where duserid=?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, dusername); preparedStatement.setString(2, dtel); preparedStatement.setString(3, daddress1); preparedStatement.setString(4, daddress2); preparedStatement.setString(5, daddress3); preparedStatement.setString(6, dmsg); preparedStatement.setString(7, duserid); preparedStatement.executeUpdate(); }catch (Exception e) { e.printStackTrace(); }finally { try { if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }//-------------------------end---------------------------------
27.859206
154
0.659324
02bd36ff0762bba4e1dd863974a76c8c5b34cbd5
1,187
/* * Copyright (C) 2015 Mesosphere, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hubspot.mesos.rx.java.example.framework.sleepy; import org.jetbrains.annotations.NotNull; final class Tuple2<T1, T2> { @NotNull public final T1 _1; @NotNull public final T2 _2; public Tuple2(@NotNull final T1 v1, @NotNull final T2 v2) { _1 = v1; _2 = v2; } public static <T1, T2> Tuple2<T1, T2> create(@NotNull final T1 v1, @NotNull final T2 v2) { return new Tuple2<>(v1, v2); } public static <T1, T2> Tuple2<T1, T2> t(@NotNull final T1 v1, @NotNull final T2 v2) { return create(v1, v2); } }
29.675
94
0.676495
bd1d46d8456477f2fe1bbd13d364cf24e2a86e47
5,488
/* This file is part of Intake24. © Crown copyright, 2012, 2013, 2014. This software is licensed under the Open Government Licence 3.0: http://www.nationalarchives.gov.uk/doc/open-government-licence/ */ package uk.ac.ncl.openlab.intake24.client.ui.foodlist; import org.pcollections.HashTreePMap; import org.pcollections.HashTreePSet; import org.workcraft.gwt.shared.client.Function1; import org.workcraft.gwt.shared.client.Option; import org.workcraft.gwt.shared.client.Option.Visitor; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Visibility; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.TextBox; import uk.ac.ncl.openlab.intake24.client.survey.*; import uk.ac.ncl.openlab.intake24.client.survey.prompts.messages.PromptMessages; import uk.ac.ncl.openlab.intake24.client.ui.WidgetFactory; public class EditableFoodListItem extends Composite { public final PromptMessages messages = GWT.create(PromptMessages.class); public final Option<FoodEntry> init; final public TextBox textBox; final public Button deleteButton; public boolean isChanged () { return !textBox.getText().isEmpty() && !textBox.getText().equals(messages.editMeal_listItemPlaceholder()) && init.accept(new Visitor<FoodEntry, Boolean>() { @Override public Boolean visitSome(FoodEntry item) { return !item.description().equals(textBox.getText()); } @Override public Boolean visitNone() { return true; } }); } public boolean isEmpty() { return textBox.getText().isEmpty() || textBox.getText().equals(messages.editMeal_listItemPlaceholder()); } public void clearText() { textBox.setText(""); textBox.removeStyleName("intake24-food-list-textbox-placeholder"); } public void showPlaceholderText() { textBox.setText(messages.editMeal_listItemPlaceholder()); textBox.addStyleName("intake24-food-list-textbox-placeholder"); } public FoodEntry mkFoodEntry(final boolean markAsDrink) { return init.accept(new Visitor<FoodEntry, FoodEntry>() { @Override public FoodEntry visitSome(FoodEntry existing) { if (isChanged()) return new RawFood(existing.link, textBox.getText(), markAsDrink ? HashTreePSet.<String> empty().plus(RawFood.FLAG_DRINK) : HashTreePSet.<String> empty(), HashTreePMap.<String, String> empty()); else return existing; } @Override public FoodEntry visitNone() { if (isChanged()) return new RawFood(FoodLink.newUnlinked(), textBox.getText(), markAsDrink ? HashTreePSet.<String> empty().plus(RawFood.FLAG_DRINK) : HashTreePSet.<String> empty(), HashTreePMap.<String, String> empty()); else throw new RuntimeException ("Cannot make food entry from an empty text box"); } }); } public void highlight (boolean highlighted) { if (highlighted) { addStyleName("intake24-food-list-selected-item"); //textBox.addStyleName("scran24-food-list-highlight"); deleteButton.getElement().getStyle().setVisibility(Visibility.VISIBLE); } else { removeStyleName("intake24-food-list-selected-item"); //textBox.removeStyleName("scran24-food-list-highlight"); deleteButton.getElement().getStyle().setVisibility(Visibility.HIDDEN); } } public EditableFoodListItem(Option<FoodEntry> init) { this.init = init; FlowPanel contents = new FlowPanel(); initWidget(contents); final boolean isLinked = init.map(new Function1<FoodEntry, Boolean>() { @Override public Boolean apply(FoodEntry argument) { return argument.link.isLinked(); } }).getOrElse(false); final boolean isCompound = init.map(new Function1<FoodEntry, Boolean>() { @Override public Boolean apply(FoodEntry argument) { return argument.accept(new FoodEntry.Visitor<Boolean>() { @Override public Boolean visitRaw(RawFood food) { return false; } @Override public Boolean visitEncoded(EncodedFood food) { return false; } @Override public Boolean visitTemplate(TemplateFood food) { return true; } @Override public Boolean visitMissing(MissingFood food) { return false; } @Override public Boolean visitCompound(CompoundFood food) { return true; } }); } }).getOrElse(false); addStyleName("intake24-food-list-item"); if (isLinked) addStyleName("intake24-food-list-linked-item"); textBox = new TextBox(); textBox.setEnabled(!isCompound); textBox.addStyleName("intake24-food-list-textbox"); textBox.setText(init.map(new Function1<FoodEntry, String>() { @Override public String apply(FoodEntry argument) { return argument.description(); } }).getOrElse(messages.editMeal_listItemPlaceholder())); FlowPanel textBoxContainer = new FlowPanel(); textBoxContainer.addStyleName("intake24-food-list-textbox-container"); textBoxContainer.add(textBox); deleteButton = WidgetFactory.createButton(""); deleteButton.getElement().getStyle().setVisibility(Visibility.HIDDEN); deleteButton.addStyleName("intake24-food-list-delete-button"); // deleteButton.setTitle(messages.editMeal_listItem_deleteButtonLabel()); contents.add(deleteButton); contents.add(textBoxContainer); FlowPanel clearDiv = new FlowPanel(); clearDiv.addStyleName("intake24-clear-floats"); contents.add(clearDiv); } }
30.320442
135
0.723943
9144df5432c12995b058769b4a89da7d198924b3
2,320
/* * Copyright 2020 Google LLC * * 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.mobilitydata.gtfsvalidator.validator; import org.mobilitydata.gtfsvalidator.annotation.GtfsValidator; import org.mobilitydata.gtfsvalidator.notice.NoticeContainer; import org.mobilitydata.gtfsvalidator.notice.SeverityLevel; import org.mobilitydata.gtfsvalidator.notice.ValidationNotice; import org.mobilitydata.gtfsvalidator.table.GtfsFeedInfo; /** * Validates that if one of {@code (start_date, end_date)} fields is provided for {@code * feed_info.txt}, then the second field is also provided. * * <p>Generated notice: {@link MissingFeedInfoDateNotice}. */ @GtfsValidator public class FeedServiceDateValidator extends SingleEntityValidator<GtfsFeedInfo> { @Override public void validate(GtfsFeedInfo feedInfo, NoticeContainer noticeContainer) { if (feedInfo.hasFeedStartDate() && !feedInfo.hasFeedEndDate()) { noticeContainer.addValidationNotice( new MissingFeedInfoDateNotice(feedInfo.csvRowNumber(), "feed_end_date")); } else if (!feedInfo.hasFeedStartDate() && feedInfo.hasFeedEndDate()) { noticeContainer.addValidationNotice( new MissingFeedInfoDateNotice(feedInfo.csvRowNumber(), "feed_start_date")); } } /** * Even though `feed_info.start_date` and `feed_info.end_date` are optional, if one field is * provided the second one should also be provided. * * <p>Severity: {@code SeverityLevel.WARNING} */ static class MissingFeedInfoDateNotice extends ValidationNotice { private final long csvRowNumber; private final String fieldName; MissingFeedInfoDateNotice(long csvRowNumber, String fieldName) { super(SeverityLevel.WARNING); this.csvRowNumber = csvRowNumber; this.fieldName = fieldName; } } }
37.419355
94
0.756034
65b28e049e56360107ea10e433dd936947dd8552
170
/** @testcase PR851 declaring an aspect constructor with argument should be prohibited */ aspect A { A() {} } aspect B { A.new(int i) { this(); } // CE 10 }
14.166667
89
0.6
c4ef39ce619554ad9eeadb91ec007fd204c73cdf
580
package com.github.chanming2015.cas.test.control; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * Description: * Create Date:2017年8月10日 * @author XuMaoSen * Version:1.0.0 */ @RestController public class CASTestControl { @GetMapping("/do_bussness") public String do_bussness() { return "without authentication access success"; } @GetMapping("/authen/do_bussness") public String authen_do_bussness() { return "authentication access success"; } }
21.481481
62
0.717241
22a33f3f292ca96498b60d61035694cc70d45226
447
package cn.niukid.bim.bean; import lombok.Getter; import lombok.Setter; @Getter @Setter public class BucketItemBean { String id; String text; String type; boolean children; public BucketItemBean() { super(); // TODO Auto-generated constructor stub } public BucketItemBean(String id, String text, String type, boolean children) { super(); this.id = id; this.text = text; this.type = type; this.children = children; } }
15.964286
79
0.704698
4bef809d0cee4b34d631428560f7f0b0d5ee0b10
5,342
/******************************************************************************* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.web.controller; import com.opencsv.CSVWriter; import org.apache.solr.client.solrj.SolrServerException; import org.mousephenotype.cda.enumerations.SexType; import org.mousephenotype.cda.solr.service.GenotypePhenotypeService; import org.mousephenotype.cda.solr.service.StatisticalResultService; import org.mousephenotype.cda.solr.service.dto.GenotypePhenotypeDTO; import uk.ac.ebi.phenotype.util.PhenotypeGeneSummaryDTO; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class ControllerUtils { public static void writeAsCSV(String toWrite, String fileName, HttpServletResponse response) throws IOException{ response.setContentType("text/csv;charset=utf-8"); response.setHeader("Content-Disposition","attachment; filename="+fileName); OutputStream resOs= response.getOutputStream(); OutputStream buffOs= new BufferedOutputStream(resOs); OutputStreamWriter outputwriter = new OutputStreamWriter(buffOs); outputwriter.write(toWrite); outputwriter.close(); outputwriter.close(); } public static void writeAsCSV(List<String[]> toWrite, String fileName, HttpServletResponse response) throws IOException{ response.setContentType("text/csv;charset=utf-8"); response.setHeader("Content-Disposition","attachment; filename="+fileName); OutputStream resOs= response.getOutputStream(); OutputStream buffOs= new BufferedOutputStream(resOs); CSVWriter writer = new CSVWriter(new OutputStreamWriter(buffOs)); writer.writeAll(toWrite); writer.close(); } public static void writeAsCSVMultipleTables(List<List<String[]>> toWrite, String fileName, HttpServletResponse response) throws IOException{ response.setContentType("text/csv;charset=utf-8"); response.setHeader("Content-Disposition","attachment; filename="+fileName); OutputStream resOs = response.getOutputStream(); OutputStream buffOs = new BufferedOutputStream(resOs); CSVWriter writer = new CSVWriter(new OutputStreamWriter(buffOs)); for (List<String[]> table : toWrite){ writer.writeAll(table); writer.writeNext(new String[0]); } writer.close(); } /** * * @param phenotype_id * @return <sex, percentage>, to be used on overview pie chart * @throws SolrServerException, IOException */ public static PhenotypeGeneSummaryDTO getPercentages(String phenotype_id, StatisticalResultService srService, GenotypePhenotypeService gpService) throws SolrServerException, IOException { PhenotypeGeneSummaryDTO pgs = new PhenotypeGeneSummaryDTO(); int total = 0; int nominator = 0; nominator = gpService.getGenesBy(phenotype_id, null, false).size(); total = srService.getGenesBy(phenotype_id, null).size(); pgs.setTotalPercentage(100 * (float) nominator / (float) total); pgs.setTotalGenesAssociated(nominator); pgs.setTotalGenesTested(total); boolean display = (total > 0); pgs.setDisplay(display); List<String> genesFemalePhenotype = new ArrayList<>(); List<String> genesMalePhenotype = new ArrayList<>(); List<String> genesBothPhenotype; if (display) { for (GenotypePhenotypeDTO dto : gpService.getGenesBy(phenotype_id, "female", false)) { genesFemalePhenotype.add(dto.getMarkerSymbol()); } nominator = genesFemalePhenotype.size(); total = srService.getGenesBy(phenotype_id, SexType.female.getName()).size(); pgs.setFemalePercentage(100 * (float) nominator / (float) total); pgs.setFemaleGenesAssociated(nominator); pgs.setFemaleGenesTested(total); for (GenotypePhenotypeDTO dto : gpService.getGenesBy(phenotype_id, "male", false)) { genesMalePhenotype.add(dto.getMarkerSymbol()); } nominator = genesMalePhenotype.size(); total = srService.getGenesBy(phenotype_id, SexType.male.getName()).size(); pgs.setMalePercentage(100 * (float) nominator / (float) total); pgs.setMaleGenesAssociated(nominator); pgs.setMaleGenesTested(total); } genesBothPhenotype = new ArrayList<>(genesFemalePhenotype); genesBothPhenotype.retainAll(genesMalePhenotype); genesFemalePhenotype.removeAll(genesBothPhenotype); genesMalePhenotype.removeAll(genesBothPhenotype); pgs.setBothNumber(genesBothPhenotype.size()); pgs.setFemaleOnlyNumber(genesFemalePhenotype.size()); pgs.setMaleOnlyNumber(genesMalePhenotype.size()); pgs.fillPieChartCode(phenotype_id); return pgs; } }
37.356643
146
0.740547
a57c29efee5a6460c1b8b5eefefd077af3a2620e
751
package oop.boxingmatch.boxer; /** * ShyBoxer will always do the blocking move and never attacks. * * In the implementation of this class the concept of enums is introduced. */ public class ShyBoxer implements BoxerInterface { @Override public String name() { return "Feigling"; } @Override public String imageFileName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getMovement(int round) { return BLOCK; } public Movements getMovement2(int round) { return Movements.HIT; } @Override public int getPosition(int round) { return BODY; } }
22.088235
135
0.661784
7a3ec06b9c74bcc78c60abd7cbf3a75bc55cb6f2
3,676
package lab; import java.lang.reflect.*; import java.math.BigDecimal; import org.xillium.base.beans.Beans; import org.xillium.base.type.*; import org.xillium.base.util.*; import org.testng.annotations.*; /** * ValueOf tests. */ public class ValueOfTest { @Test(groups={"util", "util-valueof", "util-valueof-simple"}) @SuppressWarnings("unchecked") public void testValueOf() throws Exception { ValueOf aValueOf = new ValueOf(A.class); ValueOf fValueOf = new ValueOf(Flags.class, B.class.getField("x").getAnnotation(typeinfo.class)); ValueOf iValueOf = new ValueOf(Integer.TYPE); ValueOf sValueOf = new ValueOf(String.class); ValueOf dValueOf = new ValueOf(java.math.BigDecimal.class); assert aValueOf.invoke("SUNDAY") == A.SUNDAY; assert aValueOf.invoke("MONDAY") == A.MONDAY; assert aValueOf.invoke("TUESDAY") == A.TUESDAY; try { aValueOf.invoke("2.17"); assert false; } catch (Exception x) {} B b = new B(); b.x = (Flags<A>)fValueOf.invoke(" SUNDAY : : TUESDAY , "); assert b.x.isSet(A.SUNDAY); assert !b.x.isSet(A.MONDAY); assert b.x.isSet(A.TUESDAY); assert b.x.toString().equals("SUNDAY:TUESDAY"); assert !b.x.isNone(); try { fValueOf.invoke("SUNDAY-TUESDAY"); assert false; } catch (Exception x) {} assert iValueOf.invoke("23").equals(new Integer(23)); assert iValueOf.invoke("") == null; assert iValueOf.invoke(null) == null; assert sValueOf.invoke("").equals(""); assert sValueOf.invoke(null) == null; assert dValueOf.invoke("3.1415").equals(new java.math.BigDecimal("3.1415")); } @Test(groups={"util", "util-valueof", "util-valueof-array"}) @SuppressWarnings("unchecked") public void testValueOfArray() throws Exception { Field coords = B.class.getField("coords"); ValueOf cValueOf = new ValueOf(coords.getType()); B b = new B(); coords.set(b, cValueOf.invoke("12.3, 6.54, 2.00")); System.err.println("B = " + Beans.toString(b)); assert b.coords.length == 3; assert b.coords[0].equals(new BigDecimal("12.3")); assert b.coords[1].equals(new BigDecimal("6.54")); assert b.coords[2].equals(new BigDecimal("2.00")); } @Test(groups={"util", "util-valueof", "util-valueof-speed"}) @SuppressWarnings("unchecked") public void testValueOfSpeed() throws Exception { String text = "MONDAY : TUESDAY"; Field f = B.class.getField("x"); typeinfo t = f.getAnnotation(typeinfo.class); B b = new B(); long now = System.currentTimeMillis(); for (int i = 0; i < 5000; ++i) Beans.setValue(b, f, "MONDAY : TUESDAY"); System.err.println("Beans.setValue: " + (System.currentTimeMillis() - now)); now = System.currentTimeMillis(); for (int i = 0; i < 5000; ++i) b.x = (Flags<A>)Beans.valueOf(Flags.class, text, t); System.err.println(" Beans.valueOf: " + (System.currentTimeMillis() - now)); now = System.currentTimeMillis(); for (int i = 0; i < 5000; ++i) b.x = (Flags<A>)new ValueOf(Flags.class, t.value()).invoke(text); System.err.println(" ValueOf: " + (System.currentTimeMillis() - now)); } public static enum A { SUNDAY, MONDAY, TUESDAY } public static class B { @typeinfo(A.class) public Flags<A> x; public BigDecimal[] coords; } }
36.39604
106
0.581882
fc6326b33e67b62328d42174715b336baf87b6c2
2,055
package Modelo; /** * * @author Mr.Glass */ public class Empresa extends EntidadeDominio{ private double faturamento; private String nomeFantasia; private String razaoSocial; private String CNPJ; private String email; private Documento DRE; private Categoria categoria; private Endereco endereco; private Telefone[] telefone; private Usuario usuario; public double getFaturamento() { return faturamento; } public void setFaturamento(double faturamento) { this.faturamento = faturamento; } public String getNomeFantasia() { return nomeFantasia; } public void setNomeFantasia(String nomeFantasia) { this.nomeFantasia = nomeFantasia; } public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } public String getCNPJ() { return CNPJ; } public void setCNPJ(String CNPJ) { this.CNPJ = CNPJ; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Documento getDRE() { return DRE; } public void setDRE(Documento DRE) { this.DRE = DRE; } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } public Telefone[] getTelefone() { return telefone; } public void setTelefone(Telefone[] telefone) { this.telefone = telefone; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } }
20.55
55
0.591241
d48a1d757454c60861993c9329a06577b4b63407
898
package omegajak.striptrease.item; import net.minecraft.block.Block; import net.minecraft.item.*; import java.util.Optional; public class ExposedAxeItem extends AxeItem { protected ExposedAxeItem(ToolMaterial material, float attackDamage, float attackSpeed, Settings settings) { super(material, attackDamage, attackSpeed, settings); } public static Optional<Block> getStrippedBlock(BlockItem blockItem) { return getStrippedBlock(blockItem.getBlock()); } public static Optional<Block> getStrippedBlock(Block block) { return Optional.ofNullable(STRIPPED_BLOCKS.get(block)); } public static boolean isStrippable(ItemStack itemStack) { return isStrippable(itemStack.getItem()); } public static boolean isStrippable(Item item) { return item instanceof BlockItem && getStrippedBlock((BlockItem)item).isPresent(); } }
30.965517
111
0.737194
1a6bbedfdb598cc5c7681e5ed8c65bd0ebf83a65
1,697
package org.mcupdater.ravenbot.features; import org.apache.commons.lang3.StringUtils; import org.mcupdater.ravenbot.AbstractListener; import org.mcupdater.ravenbot.RavenBot; import org.pircbotx.Colors; import org.pircbotx.hooks.events.MessageEvent; import java.sql.PreparedStatement; import java.sql.ResultSet; public class InfoHandler extends AbstractListener { @Override public void handleCommand(String sender, final MessageEvent event, String command, String[] args) { if (command.equals(".info") || command.equals(".i") ) { if (args.length == 0) { event.respond("No key specified."); return; } if (args.length == 1) { String key = args[0]; try { PreparedStatement getInfo = RavenBot.getInstance().getPreparedStatement("getInfo"); getInfo.setString(1, key); ResultSet results = getInfo.executeQuery(); if (results.next()) { event.respond(Colors.BOLD + key + Colors.NORMAL + " - " + results.getString(1)); } else { event.respond("No information found for: " + key); } } catch (Exception e) { e.printStackTrace(); } } if (args.length > 1) { String key = args[0]; String data = StringUtils.join(args, " ", 1, args.length); try { PreparedStatement updateInfo = RavenBot.getInstance().getPreparedStatement("updateInfo"); updateInfo.setString(1, key); updateInfo.setString(2, data); if (updateInfo.executeUpdate() > 0) { event.respond("Value set."); } else { event.respond("An error occurred while trying to set the value."); } } catch (Exception e) { e.printStackTrace(); } } } } @Override protected void initCommands() { } }
27.819672
100
0.663524
33e69aaf575f31472740fdd7535db1002a50d0c8
7,809
package net.minecraft.block; import java.util.List; import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.util.IStringSerializable; import net.minecraft.world.ColorizerGrass; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockTallGrass extends BlockBush implements IGrowable { public static final PropertyEnum field_176497_a = PropertyEnum.create("type", BlockTallGrass.EnumType.class); private static final String __OBFID = "CL_00000321"; protected BlockTallGrass() { super(Material.vine); this.setDefaultState(this.blockState.getBaseState().withProperty(field_176497_a, BlockTallGrass.EnumType.DEAD_BUSH)); float var1 = 0.4F; this.setBlockBounds(0.5F - var1, 0.0F, 0.5F - var1, 0.5F + var1, 0.8F, 0.5F + var1); } public int getBlockColor() { return ColorizerGrass.getGrassColor(0.5D, 1.0D); } public boolean canBlockStay(World worldIn, BlockPos p_180671_2_, IBlockState p_180671_3_) { return this.canPlaceBlockOn(worldIn.getBlockState(p_180671_2_.offsetDown()).getBlock()); } /** * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) */ public boolean isReplaceable(World worldIn, BlockPos pos) { return true; } public int getRenderColor(IBlockState state) { if (state.getBlock() != this) { return super.getRenderColor(state); } else { BlockTallGrass.EnumType var2 = (BlockTallGrass.EnumType)state.getValue(field_176497_a); return var2 == BlockTallGrass.EnumType.DEAD_BUSH ? 16777215 : ColorizerGrass.getGrassColor(0.5D, 1.0D); } } public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass) { return worldIn.getBiomeGenForCoords(pos).func_180627_b(pos); } /** * Get the Item that this Block should drop when harvested. * * @param fortune the level of the Fortune enchantment on the player's tool */ public Item getItemDropped(IBlockState state, Random rand, int fortune) { return rand.nextInt(8) == 0 ? Items.wheat_seeds : null; } /** * Get the quantity dropped based on the given fortune level */ public int quantityDroppedWithBonus(int fortune, Random random) { return 1 + random.nextInt(fortune * 2 + 1); } public void harvestBlock(World worldIn, EntityPlayer playerIn, BlockPos pos, IBlockState state, TileEntity te) { if (!worldIn.isRemote && playerIn.getCurrentEquippedItem() != null && playerIn.getCurrentEquippedItem().getItem() == Items.shears) { playerIn.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); spawnAsEntity(worldIn, pos, new ItemStack(Blocks.tallgrass, 1, ((BlockTallGrass.EnumType)state.getValue(field_176497_a)).func_177044_a())); } else { super.harvestBlock(worldIn, playerIn, pos, state, te); } } public int getDamageValue(World worldIn, BlockPos pos) { IBlockState var3 = worldIn.getBlockState(pos); return var3.getBlock().getMetaFromState(var3); } /** * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) */ public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) { for (int var4 = 1; var4 < 3; ++var4) { list.add(new ItemStack(itemIn, 1, var4)); } } public boolean isStillGrowing(World worldIn, BlockPos p_176473_2_, IBlockState p_176473_3_, boolean p_176473_4_) { return p_176473_3_.getValue(field_176497_a) != BlockTallGrass.EnumType.DEAD_BUSH; } public boolean canUseBonemeal(World worldIn, Random p_180670_2_, BlockPos p_180670_3_, IBlockState p_180670_4_) { return true; } public void grow(World worldIn, Random p_176474_2_, BlockPos p_176474_3_, IBlockState p_176474_4_) { BlockDoublePlant.EnumPlantType var5 = BlockDoublePlant.EnumPlantType.GRASS; if (p_176474_4_.getValue(field_176497_a) == BlockTallGrass.EnumType.FERN) { var5 = BlockDoublePlant.EnumPlantType.FERN; } if (Blocks.double_plant.canPlaceBlockAt(worldIn, p_176474_3_)) { Blocks.double_plant.func_176491_a(worldIn, p_176474_3_, var5, 2); } } /** * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(field_176497_a, BlockTallGrass.EnumType.func_177045_a(meta)); } /** * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState state) { return ((BlockTallGrass.EnumType)state.getValue(field_176497_a)).func_177044_a(); } protected BlockState createBlockState() { return new BlockState(this, new IProperty[] {field_176497_a}); } /** * Get the OffsetType for this Block. Determines if the model is rendered slightly offset. */ public Block.EnumOffsetType getOffsetType() { return Block.EnumOffsetType.XYZ; } public static enum EnumType implements IStringSerializable { DEAD_BUSH("DEAD_BUSH", 0, 0, "dead_bush"), GRASS("GRASS", 1, 1, "tall_grass"), FERN("FERN", 2, 2, "fern"); private static final BlockTallGrass.EnumType[] field_177048_d = new BlockTallGrass.EnumType[values().length]; private final int field_177049_e; private final String field_177046_f; private static final BlockTallGrass.EnumType[] $VALUES = new BlockTallGrass.EnumType[]{DEAD_BUSH, GRASS, FERN}; private static final String __OBFID = "CL_00002055"; private EnumType(String p_i45676_1_, int p_i45676_2_, int p_i45676_3_, String p_i45676_4_) { this.field_177049_e = p_i45676_3_; this.field_177046_f = p_i45676_4_; } public int func_177044_a() { return this.field_177049_e; } public String toString() { return this.field_177046_f; } public static BlockTallGrass.EnumType func_177045_a(int p_177045_0_) { if (p_177045_0_ < 0 || p_177045_0_ >= field_177048_d.length) { p_177045_0_ = 0; } return field_177048_d[p_177045_0_]; } public String getName() { return this.field_177046_f; } static { BlockTallGrass.EnumType[] var0 = values(); int var1 = var0.length; for (int var2 = 0; var2 < var1; ++var2) { BlockTallGrass.EnumType var3 = var0[var2]; field_177048_d[var3.func_177044_a()] = var3; } } } }
33.952174
152
0.642848
9993f8533e9692f3d17e7178ca1c0e1a13602937
122
package io.trading.chart.model; import lombok.Value; @Value public class PointEvent { private String description; }
13.555556
31
0.762295
2cfcdc66cef3f3494e9600e69be2f6f1e9528535
5,940
/** * Copyright 2013-2014 Guoqiang Chen, Shanghai, China. All rights reserved. * * Author: Guoqiang Chen * Email: subchen@gmail.com * WebURL: https://github.com/subchen * * 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 jetbrick.web.mvc.result; import javax.servlet.http.HttpServletResponse; import jetbrick.web.mvc.ManagedWith; @ManagedWith(HttpStatusResultHandler.class) public final class HttpStatus { public static final HttpStatus SC_CONTINUE = new HttpStatus(HttpServletResponse.SC_CONTINUE); public static final HttpStatus SC_SWITCHING_PROTOCOLS = new HttpStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); public static final HttpStatus SC_OK = new HttpStatus(HttpServletResponse.SC_OK); public static final HttpStatus SC_CREATED = new HttpStatus(HttpServletResponse.SC_CREATED); public static final HttpStatus SC_ACCEPTED = new HttpStatus(HttpServletResponse.SC_ACCEPTED); public static final HttpStatus SC_NON_AUTHORITATIVE_INFORMATION = new HttpStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION); public static final HttpStatus SC_NO_CONTENT = new HttpStatus(HttpServletResponse.SC_NO_CONTENT); public static final HttpStatus SC_RESET_CONTENT = new HttpStatus(HttpServletResponse.SC_RESET_CONTENT); public static final HttpStatus SC_PARTIAL_CONTENT = new HttpStatus(HttpServletResponse.SC_PARTIAL_CONTENT); public static final HttpStatus SC_MULTIPLE_CHOICES = new HttpStatus(HttpServletResponse.SC_MULTIPLE_CHOICES); public static final HttpStatus SC_MOVED_PERMANENTLY = new HttpStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); public static final HttpStatus SC_MOVED_TEMPORARILY = new HttpStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); public static final HttpStatus SC_FOUND = new HttpStatus(HttpServletResponse.SC_FOUND); public static final HttpStatus SC_SEE_OTHER = new HttpStatus(HttpServletResponse.SC_SEE_OTHER); public static final HttpStatus SC_NOT_MODIFIED = new HttpStatus(HttpServletResponse.SC_NOT_MODIFIED); public static final HttpStatus SC_USE_PROXY = new HttpStatus(HttpServletResponse.SC_USE_PROXY); public static final HttpStatus SC_TEMPORARY_REDIRECT = new HttpStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); public static final HttpStatus SC_BAD_REQUEST = new HttpStatus(HttpServletResponse.SC_BAD_REQUEST); public static final HttpStatus SC_UNAUTHORIZED = new HttpStatus(HttpServletResponse.SC_UNAUTHORIZED); public static final HttpStatus SC_PAYMENT_REQUIRED = new HttpStatus(HttpServletResponse.SC_PAYMENT_REQUIRED); public static final HttpStatus SC_FORBIDDEN = new HttpStatus(HttpServletResponse.SC_FORBIDDEN); public static final HttpStatus SC_NOT_FOUND = new HttpStatus(HttpServletResponse.SC_NOT_FOUND); public static final HttpStatus SC_METHOD_NOT_ALLOWED = new HttpStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); public static final HttpStatus SC_NOT_ACCEPTABLE = new HttpStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); public static final HttpStatus SC_PROXY_AUTHENTICATION_REQUIRED = new HttpStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); public static final HttpStatus SC_REQUEST_TIMEOUT = new HttpStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); public static final HttpStatus SC_CONFLICT = new HttpStatus(HttpServletResponse.SC_CONFLICT); public static final HttpStatus SC_GONE = new HttpStatus(HttpServletResponse.SC_GONE); public static final HttpStatus SC_LENGTH_REQUIRED = new HttpStatus(HttpServletResponse.SC_LENGTH_REQUIRED); public static final HttpStatus SC_PRECONDITION_FAILED = new HttpStatus(HttpServletResponse.SC_PRECONDITION_FAILED); public static final HttpStatus SC_REQUEST_ENTITY_TOO_LARGE = new HttpStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); public static final HttpStatus SC_REQUEST_URI_TOO_LONG = new HttpStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG); public static final HttpStatus SC_UNSUPPORTED_MEDIA_TYPE = new HttpStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); public static final HttpStatus SC_REQUESTED_RANGE_NOT_SATISFIABLE = new HttpStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); public static final HttpStatus SC_EXPECTATION_FAILED = new HttpStatus(HttpServletResponse.SC_EXPECTATION_FAILED); public static final HttpStatus SC_INTERNAL_SERVER_ERROR = new HttpStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); public static final HttpStatus SC_NOT_IMPLEMENTED = new HttpStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); public static final HttpStatus SC_BAD_GATEWAY = new HttpStatus(HttpServletResponse.SC_BAD_GATEWAY); public static final HttpStatus SC_SERVICE_UNAVAILABLE = new HttpStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); public static final HttpStatus SC_GATEWAY_TIMEOUT = new HttpStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT); public static final HttpStatus SC_HTTP_VERSION_NOT_SUPPORTED = new HttpStatus(HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED); private final int status; private final String message; public HttpStatus(int status) { this.status = status; this.message = null; } public HttpStatus(int status, String message) { this.status = status; this.message = message; } public int getStatus() { return status; } public String getMessage() { return message; } }
66.741573
143
0.814478
10d03f0b7811264e06aa68e491ad9e114c0d7f86
969
package com.dianping.cat.configuration.property.transform; import java.util.ArrayList; import java.util.List; import com.dianping.cat.configuration.property.entity.Property; import com.dianping.cat.configuration.property.entity.PropertyConfig; public class DefaultLinker implements ILinker { private boolean m_deferrable; private List<Runnable> m_deferedJobs = new ArrayList<Runnable>(); public DefaultLinker(boolean deferrable) { m_deferrable = deferrable; } public void finish() { for (Runnable job : m_deferedJobs) { job.run(); } } @Override public boolean onProperty(final PropertyConfig parent, final Property property) { if (m_deferrable) { m_deferedJobs.add(new Runnable() { @Override public void run() { parent.addProperty(property); } }); } else { parent.addProperty(property); } return true; } }
24.846154
84
0.657379
8249a05f27294f611f7e4ada4df09c6994c736e6
651
package com.example.jb.test4.gson; import java.util.Date; /** * Created by 666 on 2018/5/3. */ public class Wind { public double getDirection() { return direction; } public double getSpeed() { return speed; } public Date getDatetime() { return datetime; } public void setDirection(double direction) { this.direction = direction; } public void setSpeed(double speed) { this.speed = speed; } public void setDatetime(Date datetime) { this.datetime = datetime; } private double direction; private double speed; private Date datetime; }
17.131579
48
0.614439
f18cd307d8e3e6095005b6e657a7200909a701b5
589
package com.ifit.app.other; import android.graphics.Bitmap; public class rank_list_item { private String rank; private String nickname; private String weektime; private Bitmap userhead; public rank_list_item(String rank,String nickname,String weektime,Bitmap userhead){ this.rank = rank; this.nickname = nickname; this.weektime = weektime; this.userhead = userhead; } public String getrank(){ return rank; } public String getnickname(){ return nickname; } public String getweektime(){ return weektime; } public Bitmap getuserhead(){ return userhead; } }
19
84
0.743633
ee74e91e9921f31968516e49de6b866cdaa0b1d2
577
package NEO.Network; /** * 定义清单中的对象类型 */ public enum InventoryType { /** * 交易 */ TX(0x01), /** * 区块 */ Block(0x02), /** * 共识数据 */ Consensus(0xe0), ; private byte value; private InventoryType(int v) { value = (byte)v; } public int value() { return value; } public static InventoryType from(byte b) { for(InventoryType t: InventoryType.values()) { if(t.value() == b) { return t; } } throw new IllegalArgumentException(); } }
14.794872
51
0.483536
6c0ad39f5967964941ee524da213ff6fd13c1b47
612
package kr.co.programmers; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * https://programmers.co.kr/learn/courses/30/lessons/12954 */ public class P12954Test { private P12954 p = new P12954(); @Test public void example01() { assertArrayEquals(new long[]{2, 4, 6, 8, 10}, p.solution(2, 5)); } @Test public void example02() { assertArrayEquals(new long[]{4, 8, 12}, p.solution(4, 3)); } @Test public void example03() { assertArrayEquals(new long[]{-4, -8}, p.solution(-4, 2)); } }
21.103448
72
0.625817
3e9b0c4bbbac6825ceeb34d1242757322328a314
2,059
package com.frameworkium.integration.github.pages.web.components; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.core.ui.pages.Visibility; import com.frameworkium.core.ui.tests.BaseTest; import com.frameworkium.integration.github.pages.web.*; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import ru.yandex.qatools.allure.annotations.Step; import ru.yandex.qatools.htmlelements.annotations.Name; import ru.yandex.qatools.htmlelements.element.*; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; @Name("Github Header") @FindBy(css = "header") public class HeaderComponent extends HtmlElement { @Visible @Name("Home Logo/Link") @FindBy(css = "a.header-logo-invertocat") private Link homeLink; @Name("Search Box") @FindBy(name = "q") private TextInput searchBox; @Visible @Name("Explore Link") @FindBy(css = "header nav a.nav-item-explore") private Link exploreLink; @Step("Go to the explore page") public ExplorePage clickExplore() { exploreLink.click(); return PageFactory.newInstance(ExplorePage.class); } @Step("Search for the text '{0}'") public SearchResultsPage search(String searchText) { searchBox.sendKeys(searchText + Keys.ENTER); return PageFactory.newInstance(SearchResultsPage.class); } @Step("Testing Visibility.forceVisible()") public void testForceVisible() { Wait<WebDriver> wait = BaseTest.newDefaultWait(); WebElement link = homeLink.getWrappedElement(); // hide the home link BaseTest.getDriver().executeScript("arguments[0].style.visibility='hidden';", link); wait.until(ExpectedConditions.not(visibilityOf(link))); // test force visible works new Visibility().forceVisible(link); wait.until(visibilityOf(link)); } }
33.754098
92
0.723652
1ebe67c0a812fd7d9c5bd65def1205e937e5b252
2,424
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.client.common.ui.teamexplorer.actions.wit; import org.eclipse.jface.action.IAction; import com.microsoft.tfs.client.common.server.TFSServer; import com.microsoft.tfs.client.common.ui.teamexplorer.TeamExplorerEvents; import com.microsoft.tfs.client.common.ui.teamexplorer.events.QueryItemEventArg; import com.microsoft.tfs.client.common.ui.wit.qe.QueryEditor; import com.microsoft.tfs.core.clients.workitem.query.QueryDocument; import com.microsoft.tfs.core.clients.workitem.query.QueryDocumentSaveListener; import com.microsoft.tfs.core.clients.workitem.query.QueryScope; import com.microsoft.tfs.core.clients.workitem.queryhierarchy.QueryFolder; import com.microsoft.tfs.core.clients.workitem.queryhierarchy.QueryItem; public class NewQueryAction extends TeamExplorerWITBaseAction { @Override protected void doRun(final IAction action) { final String projectName = getContext().getCurrentProjectInfo().getName(); final TFSServer server = getContext().getServer(); QueryDocument queryDocument; if (selectedQueryItem instanceof QueryFolder) { final QueryFolder parent = (QueryFolder) selectedQueryItem; queryDocument = server.getQueryDocumentService().createNewQueryDocument(projectName, parent); } else if (selectedQueryItem.getParent() != null) { final QueryFolder parent = selectedQueryItem.getParent(); queryDocument = server.getQueryDocumentService().createNewQueryDocument(projectName, parent); } else { queryDocument = server.getQueryDocumentService().createNewQueryDocument(projectName, QueryScope.PRIVATE); } queryDocument.addSaveListener(new QueryDocumentSaveListener() { @Override public void onQueryDocumentSaved(final QueryDocument queryDocument) { final QueryItem savedToParent = getQueryHierarchy().find(queryDocument.getParentGUID()); if (savedToParent != null) { final QueryItemEventArg arg = new QueryItemEventArg(savedToParent); getContext().getEvents().notifyListener(TeamExplorerEvents.QUERY_ITEM_UPDATED, arg); } } }); QueryEditor.openEditor(server, queryDocument); } }
49.469388
117
0.733086
aa860b28ad8868b616eddf0a4299bfc2cda76392
4,013
package ru.stqa.pft.sandbox; import java.util.ArrayList; import java.util.List; /* Кроссворд 1. Дан двумерный массив, который содержит буквы английского алфавита в нижнем регистре. 2. Метод detectAllWords должен найти все слова из words в массиве crossword. 3. Элемент(startX, startY) должен соответствовать первой букве слова, элемент(endX, endY) - последней. text - это само слово, располагается между начальным и конечным элементами 4. Все слова есть в массиве. 5. Слова могут быть расположены горизонтально, вертикально и по диагонали как в нормальном, так и в обратном порядке. 6. Метод main не участвует в тестировании */ public class Crossword { public static void main(String[] args) { int[][] crossword = new int[][] { {'f', 'd', 'e', 'r', 'l', 'k'}, {'u', 's', 'a', 'm', 'e', 'o'}, {'l', 'n', 'g', 'r', 'o', 'v'}, {'m', 'l', 'p', 'r', 'r', 'h'}, {'p', 'o', 'e', 'e', 'j', 'j'} }; List<Word> list = detectAllWords(crossword, "home", "same"); System.out.println(list); /* Ожидаемый результат home - (5, 3) - (2, 0) same - (1, 1) - (4, 1) */ } public static List<Word> detectAllWords(int[][] crossword, String... words) { ArrayList<Word> result = new ArrayList<>(); int hor = crossword[0].length; int ver = crossword.length; int[] cords = new int[2]; boolean wordFound; int [][] steps = new int [][]{{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}}; for (String word : words) { int firstChar = word.charAt(0); for (int y = 0; y < ver; y++) { wordFound = false; for (int x = 0; x < hor; x++) { if (firstChar == crossword[y][x]){ for (int[] step : steps) { cords = wordCheck(crossword,word,y,x,step[0],step[1]); if (cords[0] != -1) { Word resultWord = new Word(word); resultWord.setStartPoint(x,y); resultWord.setEndPoint(cords[0],cords[1]); result.add(resultWord); wordFound = true; break; } } } if (wordFound){break;} } if (wordFound){break;} } } return result; } private static int[] wordCheck (int[][] crossword, String word, int startY, int startX, int stepY, int stepX) { int[] cords = new int[2]; for (int charIndex = 1;charIndex < word.length()-1;charIndex++) { startY = startY + stepY; startX = startX + stepX; if (startX < 0 || startX > crossword[0].length-1 || startY < 0 || startY > crossword.length-1 || crossword[startY][startX] != word.charAt(charIndex)) { cords [0] = -1; cords [1] = -1; return cords; } } cords [0] = startX+stepX; cords [1] = startY+stepY; return cords; } public static class Word { private String text; private int startX; private int startY; private int endX; private int endY; public Word(String text) { this.text = text; } public void setStartPoint(int i, int j) { startX = i; startY = j; } public void setEndPoint(int i, int j) { endX = i; endY = j; } @Override public String toString() { return String.format("%s - (%d, %d) - (%d, %d)", text, startX, startY, endX, endY); } } }
32.104
117
0.462248
f2b67aaa0221647ae53c69772e4a3e201b34a36e
1,114
package com.legyver.utils.mapqua; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class MapMergeTest { @Test public void mapMergeAdd() throws Exception { Map map = new HashMap<>(); Map map2 = new HashMap<>(); map2.put("value", 1); runMerge(map2, map); Object value = map.get("value"); assertThat(value).isEqualTo(1); } @Test public void nestedMapMergeAdd() throws Exception { Map map = new HashMap<>(); Map map2 = new HashMap<>(); Map childMap1 = new HashMap<>(); childMap1.put("a value", 1); Map childMap2 = new HashMap<>(); childMap2.put("another value", 3); map.put("child", childMap1); map2.put("child", childMap2); runMerge(map2, map); Map result = (Map) map.get("child"); assertThat(result.get("a value")).isEqualTo(1); assertThat(result.get("another value")).isEqualTo(3); } private void runMerge(Map map2, Map map) { for (Object key: map2.keySet()) { Object newValue = map2.get(key); map.merge(key, newValue, new MapMerge()); } } }
22.28
57
0.667864
07c7b2c1fa8585fe7596be31e528a4416f7a75ce
1,483
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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.intellij.openapi.projectRoots.ex; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; public interface ProjectRootContainer { @NotNull VirtualFile[] getRootFiles(@NotNull OrderRootType type); @NotNull ProjectRoot[] getRoots(@NotNull OrderRootType type); // must execute modifications inside this method only void changeRoots(@NotNull Runnable change); @NotNull ProjectRoot addRoot(@NotNull VirtualFile virtualFile, @NotNull OrderRootType type); void addRoot(@NotNull ProjectRoot root, @NotNull OrderRootType type); void removeRoot(@NotNull ProjectRoot root, @NotNull OrderRootType type); void removeAllRoots(@NotNull OrderRootType type); void removeAllRoots(); void removeRoot(@NotNull VirtualFile root, @NotNull OrderRootType type); void update(); }
34.488372
85
0.771409
d0fa4f7a164bc7ff7b5bb9753d7343551439280c
2,527
package com.nekrosius.asgardascension.managers; import java.util.HashMap; import java.util.Map; import org.bukkit.entity.Player; import com.nekrosius.asgardascension.Main; import com.nekrosius.asgardascension.enums.PrestigeType; public class PlayerManager { Map<String, Integer> rank; Map<String, Integer> prestige; Map<String, Integer> tokens; Main plugin; public PlayerManager(Main plugin) { this.plugin = plugin; rank = new HashMap<>(); prestige = new HashMap<>(); tokens = new HashMap<>(); } public void loadData(Player player) { plugin.getPlayerFile().createConfig(player); setRank(player, plugin.getPlayerFile().getRank()); setPrestige(player, plugin.getPlayerFile().getPrestige(), PrestigeType.HIDE); setTokens(player, plugin.getPlayerFile().getGodTokens()); } public void saveData(Player player) { plugin.getPlayerFile().createConfig(player); plugin.getPlayerFile().setRank(getRank(player)); plugin.getPlayerFile().setPrestige(getPrestige(player)); plugin.getPlayerFile().setGodTokens(getTokens(player)); plugin.getPlayerFile().saveConfig(); rank.remove(player.getName()); prestige.remove(player.getName()); tokens.remove(player.getName()); } public int getRank(Player player) { if(rank.get(player.getName()) == null) return 0; return rank.get(player.getName()); } public void setRank(Player player, int rank) { this.rank.put(player.getName(), rank); } public int getPrestige(Player player) { if(prestige.get(player.getName()) == null) return 0; return prestige.get(player.getName()); } public void setPrestige(Player player, int prestige, PrestigeType type) { this.prestige.put(player.getName(), prestige); if(!type.equals(PrestigeType.HIDE)) plugin.getLogs().log(player.getName() + " prestige set to " + prestige + " (" + type.toString() + ")"); } public int getTokens(Player player) { if(player == null) return 0; if(tokens.get(player.getName()) == null) return 0; return tokens.get(player.getName()); } public void setTokens(Player player, int tokens) { this.tokens.put(player.getName(), tokens); } public void withdrawTokens(Player player, int tokens) { this.tokens.put(player.getName(), this.tokens.get(player.getName()) - tokens); } public void addTokens(Player player, int tokens) { this.tokens.put(player.getName(), this.tokens.get(player.getName()) + tokens); } public boolean hasTokens(Player player, int tokens) { return this.tokens.get(player.getName()) >= tokens; } }
27.769231
106
0.715077
05d4a4dc38d72c7c7fd37be473d4c90c97e09b1f
1,783
package org.processmining.models.workshop.graph; import org.processmining.models.graphbased.AttributeMap; import org.processmining.models.graphbased.AttributeMap.ArrowType; import org.processmining.models.graphbased.directed.AbstractDirectedGraphEdge; /** * Edges in the workshop graph. * * @author hverbeek * */ public class WorkshopEdge extends AbstractDirectedGraphEdge<WorkshopNode, WorkshopNode> { /** * The source node. */ private WorkshopNode source; /** * The target node. */ private WorkshopNode target; /** * The cardinality. */ private Integer cardinality; /** * Creates an edge from the given source node to the given target node with * given cardinality. * * @param source * The source node. * @param target * The target node. * @param cardinality * The cardinality. */ public WorkshopEdge(WorkshopNode source, WorkshopNode target, int cardinality) { super(source, target); this.source = source; this.target = target; this.cardinality = cardinality; getAttributeMap().put(AttributeMap.LABEL, this.cardinality.toString()); getAttributeMap().put(AttributeMap.EDGEEND, ArrowType.ARROWTYPE_SIMPLE); getAttributeMap().put(AttributeMap.EDGEENDFILLED, true); getAttributeMap().put(AttributeMap.SHOWLABEL, true); } /** * Gets the source node. * * @return The source node. */ public WorkshopNode getSource() { return source; } /** * Gets the target node. * * @return The target node. */ public WorkshopNode getTarget() { return target; } /** * Gets the cardinality. * * @return The cardinality. */ public Integer getCardinality() { return cardinality; } }
23.155844
90
0.667975
482d44c7367f18f8d7ba919aced83622da93153d
1,232
package com.mizhousoft.push.huawei.internal.response; import java.util.Set; import com.fasterxml.jackson.annotation.JsonProperty; /** * 部分成功响应 * * @version */ public class HwPartSucceedResponse { // 成功数量 @JsonProperty("success") private int successNum; // 失败数量 @JsonProperty("failure") private int failureNum; // 非法Token @JsonProperty("illegal_tokens") private Set<String> illegalTokens; /** * 获取successNum * * @return */ public int getSuccessNum() { return successNum; } /** * 设置successNum * * @param successNum */ public void setSuccessNum(int successNum) { this.successNum = successNum; } /** * 获取failureNum * * @return */ public int getFailureNum() { return failureNum; } /** * 设置failureNum * * @param failureNum */ public void setFailureNum(int failureNum) { this.failureNum = failureNum; } /** * 获取illegalTokens * @return */ public Set<String> getIllegalTokens() { return illegalTokens; } /** * 设置illegalTokens * @param illegalTokens */ public void setIllegalTokens(Set<String> illegalTokens) { this.illegalTokens = illegalTokens; } }
14.666667
57
0.625812
6ff126e0be8c7141746ae1030b980c43054818b1
2,458
package org.gitlab4j.api; /* * The MIT License (MIT) * * Copyright (c) 2017 Greg Messner <greg@messners.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import org.gitlab4j.api.models.AccessToken; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URL; public class OauthApi extends AbstractApi { public OauthApi(GitLabApi gitLabApi) { super(gitLabApi); } public AccessToken oauthLogin(String hostUrl, String username, String email, String password) throws GitLabApiException, IOException { if ((username == null || username.trim().length() == 0) && (email == null || email.trim().length() == 0)) { throw new IllegalArgumentException("both username and email cannot be empty or null"); } Form formData = new Form(); addFormParam(formData, "email", email, false); addFormParam(formData, "password", password, true); addFormParam(formData, "username", username, false); addFormParam(formData, "grant_type", "password"); StringBuilder url = new StringBuilder(); url.append(hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl); url.append("/oauth/token"); Response response = post(Response.Status.OK, formData, new URL(url.toString())); return (response.readEntity(AccessToken.class)); } }
45.518519
138
0.703011
15cf341b5810063d43ca672ea93fb37180186106
102
package com.example.smartpillalarm; public interface DB { public static String DB_NAME = null; }
17
40
0.754902
23a7ba2b0c27b42027e55d5bde0587ba1e9020b1
3,545
package agents; import java.util.LinkedList; import agents.Sheeps; public class Wolfs extends Animals { private boolean alpha; public Wolfs(int x, int y, boolean alpha, ListAnimals list) { super(x, y, list); this.alpha = alpha; this.speed = 1; this.energy = 450; this.hunger = 100; this.thirsty = 300; } public Animals searchPartners(int[][] array, LinkedList<Animals> animalsList) { return null; } /** * * Gives direction to Animal if this one is hungry. Look around all prey which one is the nearest. * * @param treeArray * @param listAnimal */ public void changeOrientationHungry(int[][] tree, LinkedList<Sheeps> listPrey) { int min; if (!listPrey.isEmpty()) min = calculateDistance(x, y, listPrey.get(0).x, listPrey.get(0).y); else min = 20; int index = 0; for (Animals prey: listPrey){ if (calculateDistance(x,y, prey.x, prey.y) < min){ min = calculateDistance(x,y, prey.x, prey.y); index = listPrey.indexOf(prey); } } if (index < listPrey.size()) { if (listPrey.get(index).x < x ){ if (listPrey.get(index).y < y) if (tree[x][(y-2)%tree[0].length] > 0) orientation = 1; else orientation = 0; else if(tree[x][(y+2)%tree[0].length] > 0) orientation = 1; else orientation = 2; } else{ if (listPrey.get(index).y < y){ if(tree[x][(y+2)%tree[0].length] > 0) orientation = 1; else orientation = 2; }else{ if(tree[x][(y+2)%tree[0].length] > 0) orientation = 3; else orientation = 2; } } } } /** * * if a predator is near, go in the opposite direction. * * @param arrayTree * * @param listPredator */ public void runAwayFromPredator(int [][] tree, LinkedList<Bears> listPredator){ for (Animals predator: listPredator){ if (calculateDistance(x,y, predator.x, predator.y) <= 2){ if (predator.x < x ){ if (predator.y < y){ } else{ } } else{ if (predator.y < y){ if (Math.random()< 0.5) orientation = 2; else orientation = 1; }else{ if (Math.random()< 0.5) orientation = 2; else orientation = 3; } } return; } } } public void changeOrientation(int[][] tree, LinkedList<Sheeps> listPrey, LinkedList<Bears> listPredator){ if (Math.random() < probabilityOfChangeOrientation) orientation = (int) (Math.random() * 4); if(isHungry()) changeOrientationHungry(tree, listPrey); runAwayFromPredator(tree, listPredator); } public boolean findFood(LinkedList<Sheeps> sheeps) { for (Sheeps temporary : sheeps) { if (((temporary.x == x) /* || (temporary.x == x + 1) || (temporary.x == x - 1) */) && ((temporary.y == y) /* || (temporary.y == y + 1) || (temporary.y == y - 1) */)) { this.hunger = 100; this.isHungry = false; sheeps.remove(temporary); return true; } } if (this.hunger < 50) this.isHungry = true; return false; } public void update(int[][] altitude, int [][] tree, LinkedList<Bears> listPredator, LinkedList<Sheeps> listPrey) { this.findFood(listPrey); this.findWater(altitude); this.movement(altitude, tree); this.changeOrientation(tree, listPrey, listPredator); this.runAwayFromPredator(tree, listPredator); this.energyAndFoodVariation(); } }
22.15625
114
0.57292
64e9a324ebbcdec578636dc10e0cfdb58d4e26d8
1,769
//以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返 //回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。 // // // // 示例 1: // // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. // // // 示例 2: // // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // // // 提示: // // // 1 <= intervals.length <= 104 // intervals[i].length == 2 // 0 <= starti <= endi <= 104 // // Related Topics 排序 数组 // 👍 798 👎 0 import java.util.Arrays; import java.util.Comparator; public class _56_MergeIntervals { public static void main(String[] args) { Solution solution = new _56_MergeIntervals().new Solution(); System.out.println(solution); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[][] merge(int[][] intervals) { if (intervals.length == 0) { return new int[0][0]; } Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); int[][] merge = new int[intervals.length][2]; int idx = 0; merge[0][0] = intervals[0][0]; merge[0][1] = intervals[0][1]; for (int i = 1; i < intervals.length; i++) { if (intervals[i][0] <= merge[idx][1]) { merge[idx][1] = Math.max(intervals[i][1], merge[idx][1]); } else { idx++; merge[idx][0] = intervals[i][0]; merge[idx][1] = intervals[i][1]; } } return Arrays.copyOfRange(merge, 0, idx + 1); } } //leetcode submit region end(Prohibit modification and deletion) }
24.232877
80
0.50424
f12a070444ba5567bd6884e8b48437c4c34b3af1
4,109
package main; import domain.LimitOrder; import domain.MarketOrder; import domain.Order; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static domain.Currency.EUR; import static domain.Currency.USD; import static domain.Currency.GBP; import static domain.Currency.JPY; import static domain.Side.BUY; import static domain.Side.SELL; import static java.util.Comparator.comparing; public class Driver { public static void main(String[] args) { List<Order> orders = createOrders(); System.out.println("\nBuy side orders using stream"); orders.stream() .filter(o -> o.getSide() == BUY) .forEach(System.out::println); System.out.println("\nBuy side orders using stream sorted in ascending order"); orders.stream() .filter(o -> o.getSide() == BUY) .sorted(comparing(Order::getAmount)) .forEach(System.out::println); System.out.println("\nOrder amounts using map()"); orders.stream() .map(Order::getAmount) .forEach(System.out::println); double totalAmountOfAllOrders = orders.parallelStream() .mapToDouble(Order::getAmount) .sum(); System.out.printf("%nTotal amount of all orders %f%n", totalAmountOfAllOrders); long numberOfOrders = orders.stream() .count(); System.out.printf("%nTotal number of orders in stream %d%n", numberOfOrders); List<Order> buySideOrders = orders.stream() .filter(o -> o.getSide() == BUY) .collect(Collectors.toList()); System.out.println("\nBuy side orders using colector"); buySideOrders.stream().forEach(System.out::println); // Streams bonus System.out.println("\nInteger stream using range"); IntStream.range(1, 10).forEach(System.out::println); System.out.println("\nInteger stream using range closed"); IntStream.rangeClosed(1, 10).forEach(System.out::println); System.out.println("\nValues read from file stream"); try(Stream<String> lines = Files.lines(Paths.get(Driver.class.getClassLoader() .getResource("orders.csv").toURI()))){ lines.forEach(System.out::println); }catch(Exception e){ System.out.println(e.toString()); } } private static Function<List<Order>, Double> averageOrder = x -> { double total = 0.0; for(Order order: x) { total+= order.getAmount(); } return total/x.size(); }; private static void printMatchedOrders(List<Order> orders, Predicate<Order> predicate){ orders.forEach(o-> { if (predicate.test(o)) { System.out.println(o); } }); } private static List<Order> createOrders(){ List<Order> orders = new ArrayList<>(); Order order = new LimitOrder(EUR, 1000000.0, BUY , 1.45); orders.add(order); order = new MarketOrder(EUR, 2100000.0, SELL); orders.add(order); order = new MarketOrder(EUR, 2000000.0, BUY); orders.add(order); order = new MarketOrder(EUR, 3000000.0, BUY); orders.add(order); order = new MarketOrder(USD, 1200000.0, SELL); orders.add(order); order = new MarketOrder(USD, 3400000.0, BUY); orders.add(order); order = new MarketOrder(JPY, 2300000.0, SELL); orders.add(order); order = new MarketOrder(JPY, 9800000.0, BUY); orders.add(order); order = new MarketOrder(GBP, 6500000.0, SELL); orders.add(order); order = new MarketOrder(GBP, 4500000.0, BUY); orders.add(order); return orders; } }
30.213235
91
0.612801
f337b4ff16efba3d35030dfbe2d255d2a42ec2d8
767
package com.example.memory; public class PlayerFactory { public static Player getInstance(int type) { switch (type) { case Player.TYPE_HUMAN: return new HumanPlayer(); case Player.TYPE_COMP_BEGINNER: return new AI_PLayer_Beginner(); case Player.TYPE_COMP_MEDIUM: return new AI_PLayer_Medium(); case Player.TYPE_COMP_GOD: return new AI_PLayer_God(); default: return null; } } public static Player changeType(Player oldPlayer, int newType) { Player newPlayer = getInstance(newType); newPlayer.setNumber(oldPlayer.getNumber()); newPlayer.setColor(oldPlayer.getColor()); newPlayer.setPoints(oldPlayer.getPoints()); return newPlayer; } }
34.863636
76
0.662321
642b0d05d3801025e9f2699f23b698a663a2a17e
516
package chat.rocket.android.widget.message.autocomplete; import android.support.v7.widget.RecyclerView; import android.view.View; public abstract class AutocompleteViewHolder<I extends AutocompleteItem> extends RecyclerView.ViewHolder { public AutocompleteViewHolder(View itemView) { super(itemView); } public abstract void bind(I autocompleteItem); public abstract void showAsEmpty(); public interface OnClickListener<I extends AutocompleteItem> { void onClick(I autocompleteItem); } }
25.8
72
0.78876
a4d2790caac9b3dfd3167ddbceb040be38270d1c
325
package it.cosenonjaviste.security.jwt.exceptions; public class ValveInitializationException extends RuntimeException { public ValveInitializationException(String message) { super(message); } public ValveInitializationException(String message, Throwable cause) { super(message, cause); } }
25
74
0.747692
dcca957bf6193a51c0f2fce03bb7f329bb42e32b
2,230
package org.broadinstitute.dsm.util; import org.broadinstitute.dsm.security.RequestHandler; import org.mockserver.integration.ClientAndServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import java.util.HashMap; public class GBFMockServerRoute extends RequestHandler { private static final Logger logger = LoggerFactory.getLogger(GBFMockServerRoute.class); public static ClientAndServer mockDDP; private static final String orderNumber = "ORD3343"; HashMap<String, String> pathsAndResponses = new HashMap<>(); @Override protected Object processRequest(Request request, Response response, String userId) throws Exception { String message = TestUtil.readFile("gbf/OrderResponse.json"); String confirm = "{\"XML\":\"<ShippingConfirmations><ShippingConfirmation OrderNumber=\\\"" + orderNumber + "\\\" Shipper=\\\"B47456\\\" ShipVia=\\\"FedEx Ground\\\" ShipDate=\\\"2018-06-04\\\" ClientID=\\\"P1\\\">" + "<Tracking>78124444484</Tracking><Item ItemNumber=\\\"K-DFC-PROMISE\\\" LotNumber=\\\"I4CI8-06/26/2019\\\" SerialNumber=\\\"MB-1236741\\\" ExpireDate=\\\"2019-06-26\\\" ShippedQty=\\\"1\\\">" + "<SubItem ItemNumber=\\\"S-DFC-PROM-BROAD\\\" LotNumber=\\\"I4CD4-06/29/2019\\\" SerialNumber=\\\"RB-1234513\\\"><ReturnTracking>7958888937</ReturnTracking><Tube Serial=\\\"PS-1234567\\\"/>" + "<Tube Serial=\\\"PS-1234742\\\"/></SubItem><SubItem ItemNumber=\\\"S-DFC-PROM-MAYO\\\" LotNumber=\\\"I4CE7-06/26/2019\\\" SerialNumber=\\\"GB-1236722\\\">" + "<ReturnTracking>7959999937</ReturnTracking><Tube Serial=\\\"PR-1234471\\\"/></SubItem></Item></ShippingConfirmation></ShippingConfirmations>\"}"; String status = "{\"success\": true, \"statuses\": [{\"orderNumber\": \"" + orderNumber + "\", \"orderStatus\": \"SHIPPED\"},{\"orderNumber\": \"WRBO64NNRV2C3XVZ1WJJ\", \"orderStatus\": \"SHIPPED\"}," + "{\"orderNumber\": \"K6289XU7Z69J46FPASZ8\", \"orderStatus\": \"NOT FOUND\"}]}"; return null; } public void setResponseForPath(String path, String response){ pathsAndResponses.put(path, response); } }
48.478261
225
0.663677
47b51bccb6e538ff0984235e297ea555c4c3969e
991
package cn.ganiner.dao; import cn.ganiner.pojo.BasicInfo.*; import cn.ganiner.pojo.Student; import java.util.List; public interface BasicInfoMapper { List<Semester> findAll(); List<Major> findMaAll(Long seid); List<Blass>findCiAll(Long maid); Class findCiId(Long id); void CreateSemester(Semester semester); void CreateMajor(Major major); void CreateBlass(Blass blass); void CreateStudent(Student student); void UpSemester(Semester semester); void UpMajor(Major major); void UpBlass(Blass blass); List<Student>findClass(String classname); Integer deleteSemester(int[] id_arr);//批量删除 void DeleteClass(String cname); void DeleteMajor(Long maid); void DeleteYear(Long seid); List<Depart> AllDepart(); void InsertDepart(Depart depart); void deleteDepart(int id); void updateDepart(Depart depart); List<Sit> AllSit(); void InsertSit(Sit sit); void deleteSit(int id); void updateSit(Sit sit); }
26.078947
48
0.709384
ed8764e783df26156bb992509d16d7d476da85c2
723
package com.boluozhai.snowflake.installer.min.pojo; import com.boluozhai.snowflake.installer.min.context.ApplicationContext; public class SpringConfigBean extends DocModel { private PackageDescriptor remote; private boolean httpsOnly = true; public static SpringConfigBean getInstance(ApplicationContext ac) { Class<SpringConfigBean> clazz = SpringConfigBean.class; String key = clazz.getName(); return ac.getBean(key, clazz); } public PackageDescriptor getRemote() { return remote; } public void setRemote(PackageDescriptor remote) { this.remote = remote; } public boolean isHttpsOnly() { return httpsOnly; } public void setHttpsOnly(boolean httpsOnly) { this.httpsOnly = httpsOnly; } }
21.909091
72
0.771784
74a23244f880337664bb2c1ca09100bca3eaddd5
1,025
/** * Copyright 2008 - CommonCrawl Foundation * * CommonCrawl 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.commoncrawl.io.shared; import java.nio.ByteBuffer; /** Asynchronous data download support **/ public interface NIODataSink { /** * called whenever some data becomes available * * @param availableReadBuffer */ public void available(ByteBuffer availableReadBuffer); /** * called whenever a download has completed */ public void finished(); }
28.472222
78
0.727805
34ce33288e4dc2d2005ccea2e261dfdbeb0292d2
796
package blockchains.iaas.uni.stuttgart.de.scipcasestudy.clientapplication.backend.model.request; import java.util.List; import blockchains.iaas.uni.stuttgart.de.scipcasestudy.clientapplication.backend.model.response.Parameter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import lombok.Getter; import lombok.experimental.SuperBuilder; @SuperBuilder @Getter public class InvocationRequestMessage extends AsyncScipRequestMessage { protected String functionIdentifier; protected List<Parameter> inputs; protected List<Parameter> outputs; protected double requiredConfidence; protected long timeout; protected String signature; }
33.166667
107
0.807789
03abd5dc696e331191ba6617c96d36967aff941c
14,539
package no.nav.aura.fasit.rest; import io.restassured.http.ContentType; import no.nav.aura.envconfig.model.application.Application; import no.nav.aura.envconfig.model.deletion.LifeCycleStatus; import no.nav.aura.envconfig.model.infrastructure.*; import no.nav.aura.envconfig.rest.RestTest; import no.nav.aura.fasit.repository.ApplicationRepository; import no.nav.aura.fasit.repository.EnvironmentRepository; import no.nav.aura.fasit.rest.model.Link; import no.nav.aura.fasit.rest.model.NodePayload; import no.nav.aura.fasit.rest.model.SecretPayload; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; public class NodesRestTest extends RestTest { @BeforeAll public static void setUp() throws Exception { EnvironmentRepository envRepo = jetty.getBean(EnvironmentRepository.class); Environment u1 = new Environment("u1", EnvironmentClass.u); Cluster cluster = u1.addCluster(new Cluster("junit", Domain.Devillo)); u1.addNode(cluster, new Node("test.devillo.no", "user", "secret")); u1.addNode(cluster, new Node("deleteme.devillo.no", "user", "secret")); u1.addNode(cluster, new Node("changeme.devillo.no", "junit", "secret")); u1 = envRepo.save(u1); Environment ipEnv = new Environment("ipEnv", EnvironmentClass.t); Node nodeWithIp = new Node("1.2.3.4", "somethin", "", ipEnv.getEnvClass(), PlatformType.JBOSS); nodeWithIp.setLifeCycleStatus(LifeCycleStatus.ALERTED); ipEnv.addNode(nodeWithIp); envRepo.save(ipEnv); ApplicationRepository applicationRepository = jetty.getBean(ApplicationRepository.class); Application app1 = applicationRepository.save(new Application("app1")); Environment u2 = new Environment("u2", EnvironmentClass.u); Cluster cluster2 = u2.addCluster(new Cluster("cluster2", Domain.Devillo)); u2.addNode(cluster2, new Node("anotherNode.devillo.no", "user", "secret")); u2 = envRepo.save(u2); cluster2.addApplication(app1); envRepo.save(u2); } @Test public void findAllNodesReturnsJson() { given() .when() .get("/api/v2/nodes") .then() .statusCode(200) .contentType(ContentType.JSON) .body("hostname", hasItems("test.devillo.no")); } @Test public void findNodesWithQueryParams() { given() .queryParam("environmentClass", "u") .queryParam("environment", "u1") .when() .get("/api/v2/nodes") .then() .statusCode(200) .contentType(ContentType.JSON) .body("hostname", hasItems("test.devillo.no")); } @Test public void findNodeWithLifecycleStatusAlerted() { given() .queryParam("status", "alerted") .when() .get("/api/v2/nodes") .then() .statusCode(200) .contentType(ContentType.JSON) .body("$", hasSize(1)) .body("lifecycle.status", hasItem("alerted")); } @Test public void getNodeWithIp() { given() .queryParam("hostname", "1.2.3.4") .when() .get("/api/v2/nodes") .then() .statusCode(200) .contentType(ContentType.JSON) .body("hostname", hasItem("1.2.3.4")); } @Test public void nodeCanBeMappedToMoreThanOneCluster() { EnvironmentRepository envRepo = jetty.getBean(EnvironmentRepository.class); Environment dev = new Environment("dev", EnvironmentClass.u); ApplicationRepository applicationRepository = jetty.getBean(ApplicationRepository.class); Application app1Cluster1 = applicationRepository.save(new Application("app1Cluster1")); Application app2Cluster1 = applicationRepository.save(new Application("app2Cluster1")); Application app1Cluster2 = applicationRepository.save(new Application("app1Cluster2")); Node aNode = new Node("dev.devillo.no", "user", "secret"); Cluster cluster1 = dev.addCluster(new Cluster("cluster1", Domain.Devillo)); dev.addNode(cluster1, aNode); Cluster cluster2 = dev.addCluster(new Cluster("cluster2", Domain.Devillo)); dev.addNode(cluster2, aNode); envRepo.save(dev); cluster1.addApplication(app1Cluster1); cluster1.addApplication(app2Cluster1); cluster2.addApplication(app1Cluster2); envRepo.save(dev); given() .when() .get("/api/v2/nodes/dev.devillo.no") .then() .statusCode(200) .body("applications", hasItems("app1Cluster1", "app2Cluster1", "app1Cluster2")); } @Test public void findNodesByApplicationAndEnviornment() { given() .queryParam("environment", "u2") .queryParam("application", "app1") .when() .get("/api/v2/nodes") .then() .statusCode(200) .body("$", hasSize(1)) .body("hostname", hasItems("anotherNode.devillo.no")); ; } @Test public void findNoNodesInQ() { given() .queryParam("environmentclass", "q") .when() .get("/api/v2/nodes") .then() .statusCode(200) .contentType(ContentType.JSON) .body(not(containsString("test.devillo.no"))); } @Test public void getNode() { given() .when() .get("/api/v2/nodes/test.devillo.no") .then() .statusCode(200) .body("hostname", equalTo("test.devillo.no")) .body("environment", equalTo("u1")) .body("environmentclass", equalTo("u")) .body("username", equalTo("user")) .body("password.ref", notNullValue()) .body("type", equalTo("wildfly")) .body("cluster.name", hasItem("junit")) .body("cluster.ref", hasItem(containsString("/u1/clusters/junit"))); } @Test public void getNodeByUnknownHostname() { given() .when() .get("/api/v2/nodes/unknown.devillo.no") .then() .statusCode(404); } @Test public void deleteNodeShouldBeOk() { given() .when() .get("/api/v2/nodes/deleteme.devillo.no") .then() .statusCode(200); given() .auth().basic("user", "user") .when() .delete("/api/v2/nodes/deleteme.devillo.no") .then() .statusCode(204); given() .when() .get("/api/v2/nodes/deleteme.devillo.no") .then() .statusCode(404); } @Test public void createNodeWithDillDoesNotValidate() { given() .body("{\"dill\":\"dall\"}") .auth().basic("user", "user") .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(400) .contentType(ContentType.TEXT) .body(containsString("Input did not pass validation")) .body(containsString("hostname is required")); } @Test public void createNodeShouldBeOk() { NodePayload newNode = new NodePayload("created.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); newNode.password = SecretPayload.withValue("password"); newNode.applications.add("app1"); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(201) .log().ifError() .header("location", containsString("nodes/created.devillo.no")); given() .when() .get("/api/v2/nodes/created.devillo.no") .then() .statusCode(200); } @Test public void createsNewClusterIfProvided() { NodePayload newNode = new NodePayload("created2.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); newNode.cluster.add(new Link("test-cluster")); newNode.password = SecretPayload.withValue("password"); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(201) .log().ifError() .header("location", containsString("nodes/created2.devillo.no")); given() .when() .get("/api/v2/nodes/created2.devillo.no") .then() .body("cluster.name", hasItem("test-cluster")) .statusCode(200); } @Test public void addsNodeToExistingClusterIfProvided() { NodePayload newNode = new NodePayload("created3.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); newNode.cluster.add(new Link("test-cluster")); newNode.password = SecretPayload.withValue("password"); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(201) .log().ifError() .header("location", containsString("nodes/created3.devillo.no")); given() .when() .get("/api/v2/nodes/created3.devillo.no") .then() .body("cluster.name", hasItem("test-cluster")) .statusCode(200); } @Test public void generatesClusterNameIfNotProvided() { NodePayload newNode = new NodePayload("created4.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); newNode.password = SecretPayload.withValue("password"); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(201) .log().ifError() .header("location", containsString("nodes/created4.devillo.no")); given() .when() .get("/api/v2/nodes/created4.devillo.no") .then() .body("cluster.name", hasItem(startsWith("cluster"))) .statusCode(200); } @Test public void createNodeDuplicateShouldThrowError() { NodePayload newNode = new NodePayload("test.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(400) .body(containsString("Node with hostname test.devillo.no already exists")); } @Test public void createNodeWithMissingFieldsShouldThrowError() { NodePayload newNode = new NodePayload(); given() .auth().basic("user", "user") .body(toJson(newNode)) .contentType(ContentType.JSON) .when() .post("/api/v2/nodes") .then() .statusCode(400) .body(containsString("hostname is required"), containsString("environment is required"), containsString("type is required")); } @Test public void stopNode() { NodePayload payload = new NodePayload("changeme.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); payload.lifecycle.status = LifeCycleStatus.STOPPED; given() .auth().basic("user", "user") .body(toJson(payload)) .contentType(ContentType.JSON) .when() .put("/api/v2/nodes/changeme.devillo.no") .then() .log().ifError() .statusCode(200); given() .when() .get("/api/v2/nodes/changeme.devillo.no") .then() .body(containsString("stopped")) .statusCode(200); } @Test public void startNode() { NodePayload payload = new NodePayload("changeme.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); payload.lifecycle.status = LifeCycleStatus.RUNNING; given() .auth().basic("user", "user") .body(toJson(payload)) .contentType(ContentType.JSON) .when() .put("/api/v2/nodes/changeme.devillo.no") .then() .statusCode(200); } @Test public void checkRevisionWithComment() { NodePayload payload = new NodePayload("changeme.devillo.no", EnvironmentClass.u, "u1", PlatformType.JBOSS); payload.username = "newUser"; given() .auth().basic("user", "user") .body(toJson(payload)) .header("x-comment", "this is a comment") .header("x-onbehalfof", "someone") .contentType(ContentType.JSON) .when() .put("/api/v2/nodes/changeme.devillo.no") .then() .statusCode(200); given() .when() .get("/api/v2/nodes/changeme.devillo.no/revisions") .then() .body("message", hasItem("this is a comment")) // .log().body() .body("onbehalfof.id", hasItem("someone")) .statusCode(200); } }
34.04918
141
0.531054
dbc36f34eef90f5ac8fea0dda3ba4f21d0e53105
415
import java.util.*; public class Fabonaci { public static void main(String args[]) { Scanner sc =new Scanner(System.in); System.out.print("Enter the last term "); int n= sc.nextInt(); int a=0; int b=1; int series =0; for(int i=0;i<n;i++){ System.out.print(a+" "); series =(a+b); a=b; b=series; } } }
17.291667
49
0.472289
f03a2d7d5a8c16e0187421e70838896bc0c9531b
307
package de.suzufa.screwbox.tiled; import java.util.List; import java.util.Optional; public interface ObjectDictionary { Optional<GameObject> findByName(String name); Optional<GameObject> findById(int id); List<GameObject> allObjects(); List<GameObject> findAllWithName(String name); }
19.1875
50
0.752443
d119e4d3ef0c3777308a25b5afffb4b63bc7acee
7,705
package me.rochblondiaux.hellstar.service; import javafx.scene.layout.Pane; import lombok.NonNull; import me.rochblondiaux.hellstar.model.dialog.DialogBuilder; import me.rochblondiaux.hellstar.model.dialog.DialogType; import me.rochblondiaux.hellstar.model.project.Project; import me.rochblondiaux.hellstar.utils.FileUtils; import me.rochblondiaux.hellstar.utils.UIUtil; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.List; import java.util.Objects; /** * @author Roch Blondiaux * www.roch-blondiaux.com */ public class ProjectService { public void generate(@NonNull Project project, @NonNull Pane pane) { File copy = new File(project.getDataFolder(), "README.md"); if (copy.exists()) { new DialogBuilder() .setMessage("A README.md file already exists!") .setType(DialogType.ERROR) .build(); } try { copy.createNewFile(); FileUtils.copy("TEMPLATE.md", copy); } catch (IOException e) { new DialogBuilder() .setMessage("Cannot copy template to destination file!") .setType(DialogType.ERROR) .build(); e.printStackTrace(); } try { FileUtils.replace(copy, "%project_name%", project.getName()); FileUtils.replace(copy, "%brief_description%", project.getBriefDescription()); FileUtils.replace(copy, "%description%", project.getDescription()); FileUtils.replace(copy, "%aim%", project.getAim()); } catch (IOException e) { e.printStackTrace(); } try { generateIndex(project.getDataFolder(), copy); } catch (IOException e) { new DialogBuilder() .setMessage("Cannot generate index section!") .setType(DialogType.ERROR) .build(); e.printStackTrace(); } try { generateUsage(copy, project); } catch (URISyntaxException | IOException e) { new DialogBuilder() .setMessage("Cannot generate usage section!") .setType(DialogType.ERROR) .build(); e.printStackTrace(); } try { generateScreenshots(copy, project); } catch (IOException e) { new DialogBuilder() .setMessage("Cannot generate screenshots section!") .setType(DialogType.ERROR) .build(); e.printStackTrace(); } new DialogBuilder() .setMessage("Your README.md file has been generated successfully!") .setType(DialogType.SUCCESS) .onExit(() -> { pane.getChildren().clear(); UIUtil.load("open") .ifPresent(pane1 -> pane.getChildren().add(pane1)); }) .build(); } public void generateIndex(@NonNull File dataFolder, @NonNull File readme) throws IOException { int index = FileUtils.getIndex(readme, "%index_header%"); int contentIndex = FileUtils.getIndex(readme, "%index%"); FileUtils.replace(readme, "%index_header%", "`@root`\n"); walkDirectory(dataFolder, dataFolder, readme, index, contentIndex, 1); FileUtils.replace(readme, "%index%", "\n"); } private void walkFile(@NonNull File dataFolder, @NonNull File root, @NonNull File readme, @NonNull int contentIndex) throws IOException { Files.walk(root.toPath(), 1) .filter(s -> !root.toPath().equals(s)) .filter(path -> !path.toFile().isDirectory()) .forEach(s -> { try { FileUtils.getFunctions(s.toFile()) .forEach(s1 -> { try { FileUtils.insertLine(readme, contentIndex, String.format("* `%s` - %s.", s1, "A rly cool functions")); } catch (IOException e) { e.printStackTrace(); } }); FileUtils.insertLine(readme, contentIndex, String.format("\n`@%s`", FileUtils.formatPath(dataFolder, s))); } catch (IOException e) { e.printStackTrace(); } }); } private void walkDirectory(@NonNull File dataFolder, @NonNull File root, @NonNull File readme, @NonNull int index, @NonNull int contentIndex, @NonNull int depth) { FileUtils.walk(root) .forEach(file -> { try { FileUtils.insertLine(readme, index + 1, String.format("\t".repeat(depth - 1) + "* [**\uD83D\uDCC1 %s:**](%s/) A common folder.", file.getName(), FileUtils.formatPath(dataFolder, file.toPath()))); walkFile(dataFolder, file, readme, FileUtils.getIndex(readme, "%index%")); walkDirectory(dataFolder, file, readme, index + 1, contentIndex, depth + 1); } catch (IOException e) { e.printStackTrace(); } }); } private void generateUsage(@NonNull File readme, @NonNull Project project) throws URISyntaxException, IOException { File tmp = Files.createTempFile("hellstar", null).toFile(); tmp.createNewFile(); tmp.deleteOnExit(); FileUtils.copy("USAGE.md", tmp); if (Objects.isNull(project.getUsageCommand()) && Objects.isNull(project.getRequirements())) return; List<String> lines = Files.readAllLines(readme.toPath()); lines.addAll(Files.readAllLines(tmp.toPath())); Files.write(readme.toPath(), lines); FileUtils.replace(readme, "%project_name%", project.getName()); String usage = "Not set."; if (Objects.nonNull(project.getUsageCommand())) usage = project.getUsageCommand(); FileUtils.replace(readme, "%usage_command%", usage); String requirements = ""; if (Objects.nonNull(project.getRequirements())) requirements = project.getRequirements(); FileUtils.replace(readme, "%requirements%", requirements); } private void generateScreenshots(@NonNull File readme, @NonNull Project project) throws IOException { if (project.getScreenshots().size() == 0) return; File tmp = Files.createTempFile("hellstar", null).toFile(); tmp.createNewFile(); tmp.deleteOnExit(); FileUtils.copy("SCREENSHOTS.md", tmp); List<String> lines = Files.readAllLines(readme.toPath()); lines.addAll(Files.readAllLines(tmp.toPath())); Files.write(readme.toPath(), lines); int index = FileUtils.getIndex(readme, "%screenshots%"); project.getScreenshots() .forEach(path -> { String formattedRaw = FileUtils.formatPath(project.getDataFolder(), path); try { FileUtils.insertLine(readme, index, String.format("<img alt=\"%s\" src=\"%s\"/>", path.getFileName(), formattedRaw)); } catch (IOException e) { e.printStackTrace(); } }); FileUtils.replace(readme, "%screenshots%", "\n"); } }
42.335165
187
0.547437
28d678d3e2c5b84c41f4348d5eeaf08e86832f1f
1,546
/* * Copyright (c) 2012 - 2020 Arvato Systems GmbH * * 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.arvatosystems.t9t.schemaLoader.mavenPlugin.config; import java.util.List; import org.apache.maven.plugins.annotations.Parameter; import edu.emory.mathcs.backport.java.util.Collections; public class Migration { /** List of db object types to use for drop before migration (in provided order) */ @Parameter(alias = "pre-drops") private List<String> preDrops; /** List of db object types to use for creation after migration (in provided order) */ @Parameter(alias = "post-creates") private List<String> postCreates; public List<String> getPreDrops() { return preDrops==null?Collections.emptyList():preDrops; } public List<String> getPostCreates() { return postCreates==null?Collections.emptyList():postCreates; } @Override public String toString() { return "Migration [preDrops=" + preDrops + ", postCreates=" + postCreates + "]"; } }
30.92
90
0.710867
4df9b66816b396f70286c96149b1e902744deb21
664
import java.io.File; import java.nio.file.Paths; public class GGA { public GGA() { } public static void main(String[] args) { File file = new File (Paths.get(".").toAbsolutePath().normalize().toString() + "/src/data/input.txt"); //create inputData structure InputData inputData = new InputData(file); //Create a Genetic Algorithm object GeneticAlgorithm geneticAlgorithm = new GeneticAlgorithm(inputData); geneticAlgorithm.evolve(); geneticAlgorithm.displayBestPopulation(); Solution solution = new Solution(geneticAlgorithm); solution.printSolutionToFile(); } }
21.419355
110
0.656627
9dbe8f0b81f9f016f79789b87a0e855436a76041
1,744
/* * Copyright (c) 2018. * * 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.itfsw.mybatis.generator.plugins.utils.hook; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.dom.xml.Element; import org.mybatis.generator.api.dom.xml.XmlElement; import java.util.List; /** * --------------------------------------------------------------------------- * * --------------------------------------------------------------------------- * @author: hewei * @time:2018/4/28 17:50 * --------------------------------------------------------------------------- */ public interface IIncrementsPluginHook { /** * 生成增量操作节点 * @param introspectedColumn * @param prefix * @param hasComma * @return */ List<Element> incrementSetElementGenerated(IntrospectedColumn introspectedColumn, String prefix, boolean hasComma); /** * 生成增量操作节点(SelectiveEnhancedPlugin) * @param columns * @return */ List<XmlElement> incrementSetsWithSelectiveEnhancedPluginElementGenerated(List<IntrospectedColumn> columns); /** * 是否支持increment * @param column * @return */ boolean supportIncrement(IntrospectedColumn column); }
30.596491
119
0.616972
64baa70edcc6350d591b955a1bb09100a2f9f26d
1,025
/* * 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 Render; /** * This is an encapsulated class that holds HTML contents of table * * @author Thanura */ public class Table extends HTML { public Table() { super("table"); } /** * set Border to table * * @param x width of border */ public void setBorders(int x) { addAttribute("border", x + ""); } /** * this will crate a new row and return it. * * @return HTML row */ public HTML AddRow() { HTML tr = new HTML("tr"); addTags(tr); return tr; } /** * Generate HTML contents from table * * @return HTML content */ @Override public String toString() { updateInnerHTML(); return super.toString(); //To change body of generated methods, choose Tools | Templates. } }
20.098039
97
0.577561
9da4c93843bd6efebe20c6ee2fe83d1e00f63b07
260
package hybridObjects; public class simpleString { private String stringVariable = new String(); public String getStringVariable() { return stringVariable; } public void setStringVariable(String stringVariable) { this.stringVariable = stringVariable; } }
18.571429
54
0.796154
47b0b75b5d0f84adf80d995c0092e753758e5ee9
581
package com.xp.app.appfinance.dao.gen; import com.xp.app.appfinance.appobject.AccountBalanceSheetAO; import com.xp.app.appfinance.entity.gen.AccountBalanceSheetCriteria; import com.yuanxin.common.dao.base.BaseGeneratedMapper; /** * 自动生成的 AccountBalanceSheet 数据存取接口. * * <p> * 该类于 2016-12-05 10:07:54 生成,请勿手工修改! * </p> * * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @version 1.0.0.0, Dec 05, 2016 */ public interface AccountBalanceSheetGeneratedMapper extends BaseGeneratedMapper<AccountBalanceSheetAO, AccountBalanceSheetCriteria> { }
30.578947
134
0.748709
9b64d5a490e8a99ae4aaa8dd1d176093cbdad29f
448
package com.iwbfly.myhttp; import com.iwbfly.myhttp.register.MyhttpClientsRegister; import org.springframework.context.annotation.Import; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(MyhttpClientsRegister.class) public @interface EnableMyhttpClients { String[] value() default {}; String[] basePackages() default {}; Class<?> [] basePackageClasses() default {}; }
24.888889
56
0.767857
51b1c3fe5f8e4fbeb4a790a54dec372eab4c2e76
424
package uk.gov.digital.ho.hocs.client.workflow.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import java.util.Map; @NoArgsConstructor @AllArgsConstructor @Getter @EqualsAndHashCode public class AdvanceCaseDataRequest { @JsonProperty("data") private Map<String, String> data; }
21.2
53
0.813679
645c112f7ac92fb78150fd537d31d6d667336de3
76
/** * User module for hyperperform system */ package me.hyperperform.user;
19
38
0.736842
d15a73403d02c1c3aa7047f7deb5c7c17ecb866b
4,912
package com.barentine.totalconnect.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for VideoPIRConfigurationResults complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="VideoPIRConfigurationResults"> * &lt;complexContent> * &lt;extension base="{https://services.alarmnet.com/TC2/}WebMethodResults"> * &lt;sequence> * &lt;element name="DeviceName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="FeatureFlags" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SYSTEM_Data" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="VIDEO_Data" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="MOTION_Data" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EVENT_Data" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "VideoPIRConfigurationResults", propOrder = { "deviceName", "featureFlags", "systemData", "videoData", "motionData", "eventData" }) public class VideoPIRConfigurationResults extends WebMethodResults { @XmlElement(name = "DeviceName") protected String deviceName; @XmlElement(name = "FeatureFlags") protected String featureFlags; @XmlElement(name = "SYSTEM_Data") protected String systemData; @XmlElement(name = "VIDEO_Data") protected String videoData; @XmlElement(name = "MOTION_Data") protected String motionData; @XmlElement(name = "EVENT_Data") protected String eventData; /** * Gets the value of the deviceName property. * * @return * possible object is * {@link String } * */ public String getDeviceName() { return deviceName; } /** * Sets the value of the deviceName property. * * @param value * allowed object is * {@link String } * */ public void setDeviceName(String value) { this.deviceName = value; } /** * Gets the value of the featureFlags property. * * @return * possible object is * {@link String } * */ public String getFeatureFlags() { return featureFlags; } /** * Sets the value of the featureFlags property. * * @param value * allowed object is * {@link String } * */ public void setFeatureFlags(String value) { this.featureFlags = value; } /** * Gets the value of the systemData property. * * @return * possible object is * {@link String } * */ public String getSYSTEMData() { return systemData; } /** * Sets the value of the systemData property. * * @param value * allowed object is * {@link String } * */ public void setSYSTEMData(String value) { this.systemData = value; } /** * Gets the value of the videoData property. * * @return * possible object is * {@link String } * */ public String getVIDEOData() { return videoData; } /** * Sets the value of the videoData property. * * @param value * allowed object is * {@link String } * */ public void setVIDEOData(String value) { this.videoData = value; } /** * Gets the value of the motionData property. * * @return * possible object is * {@link String } * */ public String getMOTIONData() { return motionData; } /** * Sets the value of the motionData property. * * @param value * allowed object is * {@link String } * */ public void setMOTIONData(String value) { this.motionData = value; } /** * Gets the value of the eventData property. * * @return * possible object is * {@link String } * */ public String getEVENTData() { return eventData; } /** * Sets the value of the eventData property. * * @param value * allowed object is * {@link String } * */ public void setEVENTData(String value) { this.eventData = value; } }
23.960976
106
0.570847
436695feebc5d6e49f1e26278e5d89a6d7056309
1,185
package ru.i_novus.ms.rdm; import net.n2oapp.security.auth.common.User; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; public class SecurityContextUtils { public static final String DEFAULT_USER_ID = "UNKNOWN"; public static final String DEFAULT_USER_NAME = "UNKNOWN"; private SecurityContextUtils() { throw new UnsupportedOperationException(); } public static User getPrincipal() { Authentication authentication = getAuthentication(); if (authentication == null) return null; return (User) authentication.getPrincipal(); } private static Authentication getAuthentication() { SecurityContext context = SecurityContextHolder.getContext(); if (context == null) return null; Authentication authentication = context.getAuthentication(); return (authentication instanceof AnonymousAuthenticationToken) ? null : authentication; } }
32.027027
96
0.740928
3aa494c02aa81179e4d63a6e08801ce1901a2cf3
2,034
package MySecondGame; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class KoochikPlayer extends Player implements Draw{ private boolean playerHasTheDeffuser; private boolean createTheDefuser; private int halfSize; private boolean playerIsInThisWorld; private int playerHealth; // addd level spped KoochikPlayer(int level) { super(createThePlayerWidthHeight(level)); this.playerHasTheDeffuser = false; this.halfSize = super.getWidth()/2; this.createTheDefuser = false; this.playerIsInThisWorld = true; this.playerHealth = Size.Width; } public void playerGotTheDeffuser() { this.playerHasTheDeffuser = true; } public boolean playerHasTheDeffuser() { return this.playerHasTheDeffuser; } public void setHeightWidth(int hw) { this.setWidth(this.getWidth()+hw); this.setHeight(this.getHeight()+hw); } public boolean getCreateDefuser() { return this.createTheDefuser; } public void playerIsNotInThisWorld() { this.playerIsInThisWorld = false; } public void reducePlayerHealth(int h) { this.playerHealth-=h; } public int getHealth() { return this.playerHealth; } @Override public void draw(Graphics g) { if(!this.playerIsInThisWorld) { // g.setColor(Color.getHSBColor(0, 300, 100)); g.setColor(Color.green); g.fillRect(0, 0, this.playerHealth, Size.Height); super.draw(g); } if(this.playerIsInThisWorld) { super.draw(g); if(this.getWidth()<=this.halfSize) { g.setColor(Color.green); this.createTheDefuser = true; } else { g.setColor(Color.LIGHT_GRAY); this.createTheDefuser = false; } g.setFont(new Font("Serfi",Font.BOLD,100)); g.drawString(String.format("%d",super.getWidth()), Size.Width/2+120, Size.Height/2); g.drawString(String.format("%d", halfSize), Size.Width/2-290, Size.Height/2); g.setFont(new Font("Serfi",Font.PLAIN,50)); g.drawString("YOUR WIDTH", Size.Width/2,Size.Height/2+40); g.drawString("GOAL", Size.Width/2-300, Size.Height/2+40); } } }
21.1875
86
0.711898
9624af7834fd5ef123dacc422440b0f011548502
11,701
/* * * Copyright (C) 2020 iQIYI (www.iqiyi.com) * * 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.qiyi.lens.ui.devicepanel.blockInfos; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AbsListView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.qiyi.lens.ui.ActivityInfoPanel; import com.qiyi.lens.ui.FloatingPanel; import com.qiyi.lens.ui.FullScreenPanel; import com.qiyi.lens.ui.viewinfo.CurrentViewInfoPanel; import com.qiyi.lens.ui.viewinfo.SelectViewPanel; import com.qiyi.lens.ui.viewinfo.ViewInfoHolder; import com.qiyi.lens.ui.viewinfo.Widget; import com.qiyi.lens.ui.viewinfo.uicheck.UIUploadPanel; import com.qiyi.lens.utils.ApplicationLifecycle; import com.qiyi.lens.utils.DataPool; import com.qiyi.lens.utils.LensConfig; import com.qiyi.lens.utils.configs.ViewInfoConfig; import com.qiyi.lens.utils.event.DataCallBack; import com.qiyi.lens.utils.event.EventBus; import com.qiyi.lens.utils.iface.IViewInfoHandle; import com.qiyi.lens.utils.iface.ViewDebugActions; import com.qiyi.lens.utils.reflect.Info; import com.qiyi.lens.utils.reflect.ObjectFieldCollector; import com.qiyi.lens.utils.reflect.SpanableInfo; import com.qiyi.lenssdk.R; import java.lang.ref.WeakReference; import java.util.LinkedList; /** * to display activity info : such as witch activity; * how many views inside * view levels * 页面分析: * 新UI验收功能 : 当有选中视图的时候,使用选中的视图进行验收。没有选中的视图时候,使用当前界面的的根view 进行验收。 */ public class ActivityInfo extends AbsBlockInfo implements DataCallBack, ViewInfoHolder.WidgetSelectCallback, CompoundButton.OnCheckedChangeListener, FullScreenPanel.OnDismissListener { private TextView mActivityInfoTv; private Activity currentActivity; private TextView currentWidget; private CompoundButton selectWidget; private CheckBox showDistanceCheckbox; private CheckBox showSiblingCheckbox; private SelectViewPanel selectViewPanel; private View icBack; private View selectRowModel; private WeakReference<View> listRowRef; private ViewDebugActions mViewDebugActions; // 缓存当前被选中的视图。用于UI 验收 private WeakReference<View> currentSelectionView; public ActivityInfo(FloatingPanel panel) { super(panel); } @Override public View createView(ViewGroup parent) { View root = inflateView(parent, R.layout.lens_block_activity_info); mActivityInfoTv = root.findViewById(R.id.tv_activity_info); currentWidget = root.findViewById(R.id.currentWidget); selectWidget = root.findViewById(R.id.select); showDistanceCheckbox = root.findViewById(R.id.show_distance); showSiblingCheckbox = root.findViewById(R.id.show_sibling); icBack = root.findViewById(R.id.back_to_parent); selectRowModel = root.findViewById(R.id.up_to_row); // uiPost = root.findViewById(R.id.lens_activity_ui_post); root.findViewById(R.id.down_to_next).setOnClickListener(this); bindBlockClickEvent(parent); return root; } @Override protected void bindBlockClickEvent(View view) { currentWidget.setOnClickListener(this); selectWidget.setOnClickListener(this); showDistanceCheckbox.setOnCheckedChangeListener(this); showSiblingCheckbox.setOnCheckedChangeListener(this); icBack.setOnClickListener(this); mActivityInfoTv.setOnClickListener(this); selectRowModel.setOnClickListener(this); } @Override public void bind(View view) { currentActivity = (Activity) DataPool.obtain().getDataAsset(DataPool.DATA_TYPE_ACTIVITY, String.class); if (currentActivity == null) { currentActivity = ApplicationLifecycle.getInstance().getCurrentActivity(); } setData(); //[fix bug : 热启动时候,stampo util 存在值 但是数据却需要刷新的情况] EventBus.registerEvent(this, DataPool.DATA_TYPE_ACTIVITY); ViewInfoHolder.getInstant().setWidgetSelectCallback(this); } @Override public void unBind() { // mActivityInfoTv = null; currentActivity = null; EventBus.unRegisterEvent(this, DataPool.DATA_TYPE_ACTIVITY); ViewInfoHolder.getInstant().setWidgetSelectCallback(null); } @Override public void onDataArrived(Object data, int type) { if (data instanceof Activity) { currentActivity = (Activity) data; setData(); } } private void setData() { if (mActivityInfoTv != null && currentActivity != null) { String activityInfo = String.format( mActivityInfoTv.getContext().getString(R.string.lens_block_activity_info), getAppLabel(mActivityInfoTv.getContext()), currentActivity.getClass().getName()); mActivityInfoTv.setText(activityInfo); } } @Override public void onClick(View view) { super.onClick(view); int id = view.getId(); if (id == R.id.select) { if (selectViewPanel == null) { createSelectViewPanel(); toggleViewInfoWidget(true); } else { selectViewPanel.dismiss(); toggleViewInfoWidget(true); } } else if (id == R.id.currentWidget) { if (ViewInfoHolder.getInstant().getCurrentWidget() != null) { CurrentViewInfoPanel panel = new CurrentViewInfoPanel(getPanel()); panel.setDataView(ViewInfoHolder.getInstant() .getCurrentWidget().getView(), false); panel.show(); } } else if (id == R.id.back_to_parent) { if (selectViewPanel != null) { selectViewPanel.selectParent(); } } else if (id == R.id.tv_activity_info) { FloatingPanel basePanel = getPanel(); if (basePanel != null) { ActivityInfoPanel panel = new ActivityInfoPanel(basePanel); panel.show(); } } else if (id == R.id.up_to_row) { if (selectViewPanel != null && listRowRef.get() != null) { selectViewPanel.selectListRow(listRowRef.get()); } } else if (id == R.id.down_to_next) { if (selectViewPanel != null) { selectViewPanel.selectNext(); } } } public void exitViewSelectMode() { if (selectWidget != null) { selectWidget.performClick(); } } private void toggleViewInfoWidget(boolean visible) { if (visible) { icBack.setVisibility(View.VISIBLE); showDistanceCheckbox.setVisibility(View.VISIBLE); showSiblingCheckbox.setVisibility(View.VISIBLE); currentWidget.setVisibility(View.VISIBLE); } else { icBack.setVisibility(View.GONE); showDistanceCheckbox.setVisibility(View.GONE); showSiblingCheckbox.setVisibility(View.GONE); currentWidget.setVisibility(View.GONE); showDistanceCheckbox.setChecked(false); showSiblingCheckbox.setChecked(false); currentWidget.setText(null); } } private void createSelectViewPanel() { selectViewPanel = new SelectViewPanel(getPanel()); selectViewPanel.setOnDismissListener(this); selectViewPanel.show(); selectWidget.setChecked(true); mViewDebugActions = new ViewDebugActions(this, selectViewPanel); } private String getAppLabel(Context context) { PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = null; try { applicationInfo = packageManager.getApplicationInfo(context.getApplicationInfo() .packageName, 0); } catch (final PackageManager.NameNotFoundException ignored) { } return (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "Unknown"); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (selectViewPanel == null && isChecked) { createSelectViewPanel(); } if (selectViewPanel != null) { if (buttonView.getId() == R.id.show_distance) { selectViewPanel.showRelativePos(isChecked); } else if (buttonView.getId() == R.id.show_sibling) { selectViewPanel.showSibling(isChecked); } } } @Override public void onDismissListener(FullScreenPanel panel) { selectViewPanel = null; selectWidget.setChecked(false); currentSelectionView = null; toggleViewInfoWidget(false); ViewInfoHolder.getInstant().setCurrentWidget(null); } @Override public void onWidgetSelect(Widget widget) { if (widget == null) return; View selectView = widget.getView(); if (selectView != null) { currentSelectionView = new WeakReference<>(selectView); checkListRow(selectView); // new : support simple view debug onViewDebug(selectView); Info info = ObjectFieldCollector.create(selectView, null, null); info.setExpand(true); StringBuilder stringBuilder = new StringBuilder(); info.makeSpannable(stringBuilder, new LinkedList<SpanableInfo>()); currentWidget.setText(stringBuilder.toString()); } } private void onViewDebug(View mView) { Class<? extends IViewInfoHandle> handle = ViewInfoConfig.getInstance().getViewInfoHandle(); if (handle != null) { try { mViewDebugActions.dismiss(); IViewInfoHandle handler = handle.newInstance(); handler.onViewDebug(mViewDebugActions, mView); mViewDebugActions.show(); } catch (InstantiationException var10) { var10.printStackTrace(); } catch (IllegalAccessException var11) { var11.printStackTrace(); } } } private void checkListRow(View view) { boolean hasRowModel = false; View parent; while (view != null) { ViewParent viewParen = view.getParent(); if (viewParen instanceof View) { parent = (View) view.getParent(); if (parent instanceof AbsListView || parent instanceof RecyclerView) { hasRowModel = true; listRowRef = new WeakReference<>(view); break; } view = parent; } else { break; } } if (selectRowModel != null) { selectRowModel.setVisibility(hasRowModel ? View.VISIBLE : View.GONE); } } }
36.451713
116
0.649774
2532d3dd2f7d76a2fa8918659865f9f2a5cda8d4
507
package com.neusoft; public interface Livable { //静态方法的使用 public static void run(){ System.out.println("跑起来"); } //将func1和func2封装 //私有方法 private void func1(){ System.out.println("func1()"); } private void func2(){ System.out.println("func2()"); } public default void func(){ func1(); func2(); } // 抽象方法重名 public void show(); //默认方法重名 default void method(){ System.out.println("Livable"); } }
17.482759
38
0.538462
2a43b81004454623b0468e789f89da913ca1926b
2,612
package de.gothaer.PersonDemo.business; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import de.gothaer.PersonDemo.Persistence.PersonRepository; import de.gothaer.PersonDemo.Persistence.entities.Person; public class PersonServiceImpl implements PersonService { private final PersonRepository personRepository; private final List<String> antipathen; public PersonServiceImpl(final PersonRepository personRepository, final List<String> antipathen) { this.personRepository = personRepository; this.antipathen = antipathen; } /** * 1. Parameter darf nicht null sein * 2. Vorname darf nicht null sein * 3. Vorname muss min 2 Zeichen enthalten * 4. Nachname darf nicht null sein * 5. Nachname muss min 2 Zeichen haben * 6. Vorname darf kein Antipath sein... * 7. Person darf erst gespeichert werden wenn Bedingungen erfüllt sind * 8. Egal welcher technischer Fehler auftritt, es soll immer in eine PersonenServiceException gewandelt werden. */ @Override public void speichern(Person person) throws PersonServiceException { try { speichernImpl(person); } catch (RuntimeException e) { // ins logfile schreiben throw new PersonServiceException("Person konnte nicht gepeichert werden."); } } private void speichernImpl(Person person) throws PersonServiceException { checkPerson(person); person.setId(UUID.randomUUID().toString()); personRepository.save(person); } private void checkPerson(Person person) throws PersonServiceException { plausibilitaetsPruefung(person); vaidierung(person); } private void vaidierung(Person person) throws PersonServiceException { if(antipathen.contains(person.getVorname())) throw new PersonServiceException("Antipath."); } private void plausibilitaetsPruefung(Person person) throws PersonServiceException { if(person == null) throw new PersonServiceException("person must not be null"); if(person.getVorname() == null || person.getVorname().length() < 2) throw new PersonServiceException("firstname too short."); if(person.getNachname() == null || person.getNachname().length() < 2) throw new PersonServiceException("lastname too short."); } @Override public List<Person> findAllJohns() throws PersonServiceException { try { return personRepository.findAll().stream().filter(p->"John".equals(p.getVorname())).collect(Collectors.toList()); } catch (RuntimeException e) { throw new PersonServiceException("upps", e); } } }
28.086022
117
0.726263
6b371b9fd7928add1130dc300ffc4ea6dc15b9cb
4,818
/* * Copyright 2003 - 2016 The eFaps Team * * 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.efaps.update.schema.user; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.MultiValuedMap; import org.efaps.db.Instance; import org.efaps.update.AbstractUpdate; import org.efaps.update.Install.InstallFile; import org.efaps.update.LinkInstance; import org.efaps.util.EFapsException; /** * @author The eFaps Team */ public class RoleUpdate extends AbstractUpdate { /** * Set of all links used by commands. */ private static final Set<Link> ALLLINKS = new HashSet<>(); /** Link from UI object to role. */ private static final Link LINK2ACCESSCMD = new Link("Admin_UI_Access", "UserLink", "Admin_UI_Command", "UILink").setIncludeChildTypes(true); /** Link from AccessSet to roles. */ private static final Link LINK2ACCESSSET = new Link("Admin_Access_AccessSet2UserAbstract", "UserAbstractLink", "Admin_Access_AccessSet", "AccessSetLink"); static { RoleUpdate.ALLLINKS.add(RoleUpdate.LINK2ACCESSCMD); RoleUpdate.ALLLINKS.add(RoleUpdate.LINK2ACCESSSET); } /** * Global type or local. */ private boolean global = true; /** * Instantiates a new role update. * * @param _installFile the install file */ public RoleUpdate(final InstallFile _installFile) { super(_installFile, "temp", RoleUpdate.ALLLINKS); } @Override public String getDataModelTypeName() { return this.global ? "Admin_User_RoleGlobal" : "Admin_User_RoleLocal"; } /** * Creates new instance of class {@link RoleDefinition}. * * @return new definition instance * @see RoleDefinition */ @Override protected AbstractDefinition newDefinition() { return new RoleDefinition(); } /** * */ public class RoleDefinition extends AbstractDefinition { /** * Will the access be set or not. */ private boolean setAccess = false; @Override protected void readXML(final List<String> _tags, final Map<String, String> _attributes, final String _text) throws EFapsException { final String value = _tags.get(0); if ("status".equals(value)) { addValue("Status", _text); } else if ("global".equals(value)) { RoleUpdate.this.global = Boolean.valueOf(_text); } else if ("access".equals(value)) { this.setAccess = true; if (_tags.size() > 2) { final String subValue1 = _tags.get(1); if ("userinterface".equals(subValue1)) { final String subValue2 = _tags.get(2); if ("cmd".equals(subValue2)) { addLink(RoleUpdate.LINK2ACCESSCMD, new LinkInstance(_text)); } else { super.readXML(_tags, _attributes, _text); } } else if ("datamodel".equals(subValue1)) { final String subValue2 = _tags.get(2); if ("accessset".equals(subValue2)) { addLink(RoleUpdate.LINK2ACCESSSET, new LinkInstance(_text)); } } else { super.readXML(_tags, _attributes, _text); } } } else { super.readXML(_tags, _attributes, _text); } } @Override protected void setLinksInDB(final MultiValuedMap<String, String> _updateable, final Instance _instance, final Link _linktype, final Set<LinkInstance> _links) throws EFapsException { if (this.setAccess) { super.setLinksInDB(_updateable, _instance, _linktype, _links); } } } }
32.12
114
0.567248
8c05dd5dc911d5b289562562e600a166d072b846
1,790
package hr.fer.zemris.java.hw15.dao; import java.util.List; import hr.fer.zemris.java.hw15.model.BlogComment; import hr.fer.zemris.java.hw15.model.BlogEntry; import hr.fer.zemris.java.hw15.model.BlogUser; /** * <i>Data Acces Layer</i> interface used for manupilating with database data * <i>(i.e. retrieving/updating etc)</i>. * * @author dbrcina * */ public interface DAO { /** * Retrieves all blog entries from <i>bloe_entries</i> table as determined by * <code>user</code>. * * @param user user. * @return collection of blog entries. */ List<BlogEntry> getBlogEntries(BlogUser user); /** * Retrieves <i>blog-entry</i> as determined by <code>id</code>.<br> * If entry doesn't exist, <code>null</code> is returned. * * @param id entry key. * @return entry or <code>null</code> if entry doesn't exist. * @throws DAOException if error occurs while retrieving from database. */ BlogEntry getBlogEntry(Long id) throws DAOException; /** * Retrieves a collection of users from <i>blog_users</i> database table. * * @return collection of users. */ List<BlogUser> getUsers(); /** * Retrieves <i>blog-user</i> as determined by <code>nick</code>.<br> * If user doesn't exist, <code>null</code> is returned. * * @param nick nick. * @return blog user or <code>null</code>. */ BlogUser getUser(String nick); /** * Persists provided <code>user</code> to database. * * @param user user. */ void persistUser(BlogUser user); /** * Persists provided <code>blogEntry</code> to database. * * @param blogEntry blog entry. */ void persistBlog(BlogEntry blogEntry); /** * Persists provided <code>comment</code> to database. * * @param comment blog comment. */ void persistComment(BlogComment comment); }
24.189189
78
0.675419
f4817d6b49f6123304f2a3fecd20d224ba20b406
3,331
package com.thinkaurelius.titan.graphdb.query.condition; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.core.*; import com.thinkaurelius.titan.graphdb.internal.InternalElement; import com.thinkaurelius.titan.graphdb.internal.InternalRelationType; import com.thinkaurelius.titan.graphdb.query.TitanPredicate; import com.thinkaurelius.titan.graphdb.util.ElementHelper; import com.tinkerpop.blueprints.Direction; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.Iterator; /** * @author Matthias Broecheler (me@matthiasb.com) */ public class PredicateCondition<K, E extends TitanElement> extends Literal<E> { private final K key; private final TitanPredicate predicate; private final Object value; public PredicateCondition(K key, TitanPredicate predicate, Object value) { Preconditions.checkNotNull(key); Preconditions.checkArgument(key instanceof String || key instanceof RelationType); Preconditions.checkNotNull(predicate); this.key = key; this.predicate = predicate; this.value = value; } private boolean satisfiesCondition(Object value) { return predicate.evaluate(value, this.value); } @Override public boolean evaluate(E element) { RelationType type; if (key instanceof String) { type = ((InternalElement) element).tx().getRelationType((String) key); if (type == null) return satisfiesCondition(null); } else { type = (RelationType) key; } Preconditions.checkNotNull(type); if (type.isPropertyKey()) { Iterator<Object> iter = ElementHelper.getValues(element,(PropertyKey)type).iterator(); if (iter.hasNext()) { while (iter.hasNext()) { if (satisfiesCondition(iter.next())) return true; } return false; } return satisfiesCondition(null); } else { assert ((InternalRelationType)type).getMultiplicity().isUnique(Direction.OUT); return satisfiesCondition(((TitanRelation) element).getProperty((EdgeLabel) type)); } } public K getKey() { return key; } public TitanPredicate getPredicate() { return predicate; } public Object getValue() { return value; } @Override public int hashCode() { return new HashCodeBuilder().append(getType()).append(key).append(predicate).append(value).toHashCode(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || !getClass().isInstance(other)) return false; PredicateCondition oth = (PredicateCondition) other; return key.equals(oth.key) && predicate.equals(oth.predicate) && value.equals(oth.value); } @Override public String toString() { return key.toString() + " " + predicate.toString() + " " + String.valueOf(value); } public static <K, E extends TitanElement> PredicateCondition<K, E> of(K key, TitanPredicate titanPredicate, Object condition) { return new PredicateCondition<K, E>(key, titanPredicate, condition); } }
31.424528
131
0.646052
04f50c77efaae75f8e73b6baac75cb5cb38689bf
391
package com.leyou.item.dto; import com.leyou.item.pojo.Sku; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Transient; /** * @author meihewang * @date 2020/02/23 2:46 */ @Data @NoArgsConstructor @AllArgsConstructor public class SkuDto extends Sku { /** * 库存 */ @Transient private Integer stock; }
15.64
35
0.713555
bd7145ffa970949c03ee761ca57e9e0392584a55
247
//,temp,sample_5994.java,2,8,temp,sample_1980.java,2,9 //,3 public class xxx { public boolean rename(String src, String dst) throws IOException { checkNNStartup(); if(stateChangeLog.isDebugEnabled()) { log.info("dir namenode rename to"); } } };
19
66
0.732794
cdebbee5a77b3c2b11193075061175a42d0e8f66
153
package com.swws.marklang.prc_cardbook.utility.database; /** * Season ID of Kirato Prichan */ public enum SeasonID { SEASON_1ST, SEASON_2ND }
15.3
56
0.718954
6c679524505d0a9c7acd9264c62ffca43d740887
4,596
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.children; import org.apache.lucene.search.Filter; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.internal.ParentFieldMapper; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.aggregations.Aggregator; import org.elasticsearch.search.aggregations.AggregatorFactory; import org.elasticsearch.search.aggregations.support.FieldContext; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; import org.elasticsearch.search.internal.SearchContext; import java.io.IOException; /** * */ public class ChildrenParser implements Aggregator.Parser { @Override public String type() { return InternalChildren.TYPE.name(); } @Override public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { String childType = null; XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if ("type".equals(currentFieldName)) { childType = parser.text(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else { throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "]."); } } if (childType == null) { throw new SearchParseException(context, "Missing [child_type] field for children aggregation [" + aggregationName + "]"); } DocumentMapper childDocMapper = context.mapperService().documentMapper(childType); if (childDocMapper == null) { throw new SearchParseException(context, "[children] No mapping for for type [" + childType + "]"); } ParentFieldMapper parentFieldMapper = childDocMapper.parentFieldMapper(); if (!parentFieldMapper.active()) { throw new SearchParseException(context, "[children] _parent field not configured"); } String parentType = parentFieldMapper.type(); DocumentMapper parentDocMapper = context.mapperService().documentMapper(parentType); if (parentDocMapper == null) { throw new SearchParseException(context, "[children] Type [" + childType + "] points to a non existent parent type [" + parentType + "]"); } Filter parentFilter = context.filterCache().cache(parentDocMapper.typeFilter(), null, context.queryParserService().autoFilterCachePolicy()); Filter childFilter = context.filterCache().cache(childDocMapper.typeFilter(), null, context.queryParserService().autoFilterCachePolicy()); ParentChildIndexFieldData parentChildIndexFieldData = context.fieldData().getForField(parentFieldMapper); ValuesSourceConfig<ValuesSource.Bytes.WithOrdinals.ParentChild> config = new ValuesSourceConfig<>(ValuesSource.Bytes.WithOrdinals.ParentChild.class); config.fieldContext(new FieldContext(parentFieldMapper.names().indexName(), parentChildIndexFieldData, parentFieldMapper)); return new ParentToChildrenAggregator.Factory(aggregationName, config, parentType, parentFilter, childFilter); } }
48.893617
157
0.716928
b04cf4453246bf58eb0fd901dcf105c7d25f3d65
316
/* * 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 Archivos; /** * * @author Anahi SC */ public enum TSelva1 { ESCÁRCEGA, BALANCÁN, TENOSIQUE, PALENQUE }
17.555556
79
0.683544
c3c16661152de6d9a4fdd8deb3830540d93abbf8
2,184
/** * */ package misc; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author jbr * */ public class MPDefaultMethods { public static void modifyFolder(Path inputDir) throws IOException { Files.walk(inputDir) .filter(f -> f.toFile() .isFile() && f.toFile() .getName() .endsWith(".java")) .forEach(f -> modifyFile(f)); } public static void modifyFile(Path file) { String className = file.toFile() .getName() .replace(".java", ""); String content; try { content = new String(Files.readAllBytes(file)); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Could not read file: " + file, e); } Pattern pattern = Pattern.compile(className + " ([a-zA-Z]+)\\([^\\)]+\\);"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { if (!matcher.group(1) .startsWith("add")) { String newContent = "default " + matcher.group() .substring(0, matcher.group() .length() - 1) + " {\n" + " set" + capitalizeString(matcher.group(1)) + "(" + matcher.group(1) + ");\n" + " return this;\n" + " }"; content = content.substring(0, matcher.start()) + newContent + content.substring(matcher.end()); matcher = pattern.matcher(content); } } try { Files.write(file, content.getBytes()); } catch (IOException e) { throw new IllegalStateException("Could not write file: " + file, e); } } public static String capitalizeString(final String string) { return string.isEmpty() ? "" : Character.toUpperCase(string.charAt(0)) + string.substring(1); } }
32.597015
112
0.49359
a74b518c9921acdf283b134292061548d860e98d
102
package java.awt; public class Insets { public Insets(int top, int left, int bottom, int right); }
17
58
0.715686
c1c0c48bb91d469d5b1e39b0d9609b61dac7b2b5
2,565
package org.exparity.hamcrest.beans.testutils.types; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.exparity.dates.en.FluentDate.AUG; public class ObjectWithAllTypes { private List<SimpleTypeWithList> listOfObjects = new ArrayList<SimpleTypeWithList>(); private SimpleTypeWithList object = new SimpleTypeWithList(false, Arrays.asList(new SimpleType())); private String stringValue = "Oak"; private int intValue = 1; private long longValue = 20000L; private double doubleValue = 4.56; private BigDecimal decimalValue = new BigDecimal(10.98); private float floatValue = 2.34f; private Date dateValue = AUG(9, 1975); private boolean booleanValue = true; public String getStringValue() { return stringValue; } public void setStringValue(final String name) { this.stringValue = name; } public int getIntValue() { return intValue; } public void setIntValue(final int age) { this.intValue = age; } public long getLongValue() { return longValue; } public void setLongValue(final long numOfBranches) { this.longValue = numOfBranches; } public double getDoubleValue() { return doubleValue; } public void setDoubleValue(final double weight) { this.doubleValue = weight; } public BigDecimal getDecimalValue() { return decimalValue; } public void setDecimalValue(final BigDecimal height) { this.decimalValue = height; } public float getFloatValue() { return floatValue; } public void setFloatValue(final float girth) { this.floatValue = girth; } public Date getDateValue() { return dateValue; } public void setDateValue(final Date germinationDate) { this.dateValue = germinationDate; } public boolean getBooleanValue() { return booleanValue; } public void setBooleanValue(final boolean deciduous) { this.booleanValue = deciduous; } public List<SimpleTypeWithList> getObjects() { return listOfObjects; } public void setObjects(final List<SimpleTypeWithList> branches) { this.listOfObjects = branches; } public void addObject(final List<SimpleTypeWithList> branches) { this.listOfObjects.addAll(branches); } public void setObject(final SimpleTypeWithList mainBranch) { this.object = mainBranch; } public SimpleTypeWithList getObject() { return object; } @Override public String toString() { return "ObjectWithAllTypes [" + stringValue + "]"; } }
22.901786
101
0.717739
5584fda75c8aabc94815fe4e70ff064f15673123
395
package org.runestar.client.game.api; public final class ComponentClientCode { private ComponentClientCode() {} public static final int FPS = 1336; public static final int VIEWPORT = 1337; public static final int MINIMAP = 1338; public static final int COMPASS = 1339; public static final int WORLD_MAP = 1400; public static final int WORLD_MAP_OVERVIEW = 1401; }
28.214286
54
0.729114
c8a30397446ca5e21e3fd2db4cde51cbb57c1624
13,656
package sample; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import su.ugatu.moodle.is.credit_calc.*; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.List; /** * @return Этот класс контролируете все события и действия пользователя * {@link Controller} */ public class Controller { private CreditApplication application; private CreditOffer offer; //Коллекция данных о кредите private ObservableList<CreditData> creditData = FXCollections.observableArrayList(); //Коллекция типы данных о кредите private ObservableList<String> model = FXCollections.observableArrayList(); @FXML private Button btn_res; @FXML private GridPane grid_pan; @FXML private Label schema; @FXML private ImageView im_exit; // Текстура кнопки выхода @FXML private ImageView im_help; // Текстура кнопки справки @FXML private Text text_res; // Текст результата эффективный процентный ставки @FXML private ComboBox combo_type; // Элемент выбора схем погашения @FXML private TableView<CreditData> table; // Таблица результатов расчета @FXML private TableColumn<CreditData,Integer> num; // Колонка номер платежа @FXML private TableColumn<CreditData,String> paymentDateCol; // Колонка Дата платежа @FXML private TableColumn<CreditData,String> amountClo; // Колонка Сумма платежа @FXML private TableColumn<CreditData,String> principalCol; // Колонка Основной долг @FXML private TableColumn<CreditData,String> accruedInterestCol; // Колонка Начисленные проценты @FXML private TableColumn<CreditData,String> monthlyCommissionCol; // Колонка Ежемесячные комиссии @FXML private TableColumn<CreditData,String> balancePayableCol; // Колонка Остаток задолженности @FXML private TextField amount; // Текстовое поле Сумма кредита @FXML private TextField durationInMonths; // Текстовое поле Срок кредита @FXML private TextField interestRate; // Текстовое поле Процентная ставка @FXML private TextField onceCommissionAmount; // Текстовое поле Разовая комиссия (в деньгах) @FXML private TextField onceCommissionPercent; // Текстовое поле Разовая комиссия (в процентах) @FXML private TextField monthlyCommissionAmount; // Текстовое поле Ежемесячная комиссия (в деньгах) @FXML private TextField monthlyCommissionPercent; // Текстовое поле Ежемесячная комиссия (в процентах) @FXML private Label iab_one_pr;// Текст Разовая комиссия (в процентах) @FXML private Label lab_one_mny;// Текст Разовая комиссия (в деньгах) @FXML private Label lab_month_pr;// Текст Ежемесячная комиссия (в процентах) @FXML private Label lab_month_mny;// Текст Ежемесячная комиссия (в деньгах) /** * @return Метод для начальной инициализации данных {@link #initialize()} */ @FXML private void initialize() { // Инициализация текстур im_help.setImage(new Image("img/help.png")); im_exit.setImage(new Image("img/exit_def.png")); model.addAll("Аннуитетная", "Дифференцированная"); combo_type.setPrefSize(298, 28); combo_type.setItems(model); // Добавление данные схем погашения combo_type.getSelectionModel().select(0); // Начальная состояния "Аннуитетная" selectType(true); // ночальная положения компонентов combo_type.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String s, String s2) { if(s2.equals("Дифференцированная")){ selectType(false); } else { selectType(true); } } }); // Инициализация текста text_res.setText("Кредитный калькулятор позволяет\n" + "построить график погашения\n" + "произвольного кредита,а также\n" + "рассчитать эффективную процентную\n" + "ставку по кредиту."); // Устанавливаем тип и значение которое должно хранится в колонке num.setCellValueFactory(new PropertyValueFactory<CreditData, Integer>("num")); paymentDateCol.setCellValueFactory(new PropertyValueFactory<CreditData, String>("paymentDateCol")); amountClo.setCellValueFactory(new PropertyValueFactory<CreditData, String>("amountClo")); principalCol.setCellValueFactory(new PropertyValueFactory<CreditData, String>("principalCol")); accruedInterestCol.setCellValueFactory(new PropertyValueFactory<CreditData, String>("accruedInterestCol")); monthlyCommissionCol.setCellValueFactory(new PropertyValueFactory<CreditData, String>("monthlyCommissionCol")); balancePayableCol.setCellValueFactory(new PropertyValueFactory<CreditData, String>("balancePayableCol")); // Заполняем таблицу данными table.setPlaceholder(new Text("")); table.setItems(creditData); } /** * @return Метод выбора схему погашения */ private void initData() { if(combo_type.getSelectionModel().isSelected(1)){ application.setPaymentType(CreditPaymentType.DIFFERENTIAL); // Выбрана "Дифференцированная" CreditProposal proposal = offer.calculateProposal(application); printProposal(proposal); // Печать результата } else{ application.setPaymentType(CreditPaymentType.ANNUITY);// Выбрана "Аннуитетная" CreditProposal proposal = offer.calculateProposal(application); printProposal(proposal); // Печать результата } } /** * @return Событие расчёта данных и занесение их в таблицу */ @FXML public void onClickMethod(){ creditData.clear(); // Очистка таблицы if(control(amount) && control(durationInMonths) && control(interestRate)){ // Если все три поле числа то.. application = new CreditApplicationImpl(new BigDecimal(amount.getText())); // Возвращение текста сумма кредита в расчет application.setDurationInMonths(Integer.valueOf(durationInMonths.getText())); // Возвращение текста срок кредита в расчет offer = new CreditOfferImpl(); offer.setRate(new BigDecimal(interestRate.getText()).divide(new BigDecimal(100)));// Возвращение текста процентная савка в расчет // Проверки на числа комиссии if(control(onceCommissionAmount)) offer.setOnceCommissionAmount(new BigDecimal(onceCommissionAmount.getText())); else onceCommissionAmount.setText("0"); if(control(onceCommissionPercent)) offer.setOnceCommissionPercent(new BigDecimal(onceCommissionPercent.getText()).divide(new BigDecimal(100))); else onceCommissionPercent.setText("0"); if(control(monthlyCommissionPercent)) offer.setMonthlyCommissionPercent(new BigDecimal(monthlyCommissionPercent.getText()).divide(new BigDecimal(100))); else monthlyCommissionPercent.setText("0"); if(control(monthlyCommissionAmount)) offer.setMonthlyCommissionAmount(new BigDecimal(monthlyCommissionAmount.getText())); else monthlyCommissionAmount.setText("0"); initData(); // Метод выбора схему погашения } } /** * @return Метод выхода из программы */ @FXML public void onExit(){ System.exit(0); } /** * @return Метод вызова справки * @throws Exception */ @FXML public void onClickHelp() throws Exception { new HelpDialog(); // Объект окна справки } /** * @return Метод наведение курсора на кнопку выхода */ @FXML public void onHover(){ im_exit.setImage(new Image("img/exit.png")); im_help.setImage(new Image("img/help_exit.png")); } /** * @return Метод деактивированные курсора на кнопку выхода */ @FXML public void onHotHover(){ im_exit.setImage(new Image("img/exit_def.png")); im_help.setImage(new Image("img/help.png")); } /** * @return Метод наведение курсора на кнопку справки */ @FXML public void onHoverHelp(){ im_help.setImage(new Image("img/help_hover.png")); } /** * @return Метод деактивированные курсора на кнопку справки */ @FXML public void onHotHoverHelp(){ im_help.setImage(new Image("img/help.png")); } /** * @param tf входной параметр проверки * @return Метод проверки на число */ private boolean control(TextField tf){ double d; try { d = Double.parseDouble(tf.getText()); if(d < 0) tf.setText(""+Math.abs(d)); // Если введен отрицательный число то берется по модулю } catch (NumberFormatException e){ tf.setText(""); tf.setPromptText("Введите число"); return false; } return true; } /** * @return Метод печать результата * @param proposal - Заявка на получение кредита */ private void printProposal(CreditProposal proposal){ SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");// Форматирования даты DecimalFormat decimalFormat = new DecimalFormat("#.##"); // Форматирования числа List<CreditPayment> payments = proposal.getPayments(); text_res.setText("Всего: "+decimalFormat.format(proposal.getTotalPayment())+" денежных единиц\n" +"Эффективная процентная ставка: "+(decimalFormat.format(proposal.getEffectiveRate().doubleValue() * 100)) + "%\n" +"Комиссия: " + decimalFormat.format(proposal.getTotalCreditCommission())); int i = 1; // Вывод результатов на таблицу for (CreditPayment payment: payments) { creditData.add(new CreditData( (i++), "" + dateFormat.format(payment.getDate()), "" + decimalFormat.format(payment.getAmount()), "" + decimalFormat.format(payment.getDebt()), "" + decimalFormat.format(payment.getInterest()), "" + decimalFormat.format(payment.getCommission()), "" + decimalFormat.format(payment.getTotalLeft()))); } } /** * @return Метод расстановки компонентов в зависемости comboBox * @param select - индекатор расположения */ private void selectType(Boolean select){ // если выбрано Дифференцированная if(select){ // Установка видемости текставых полей lab_one_mny.setVisible(false); onceCommissionAmount.setVisible(false); onceCommissionAmount.setText(""); iab_one_pr.setVisible(false); onceCommissionPercent.setVisible(false); onceCommissionPercent.setText(""); lab_month_mny.setVisible(true); monthlyCommissionAmount.setVisible(true); monthlyCommissionAmount.setText(""); lab_month_pr.setVisible(false); monthlyCommissionPercent.setVisible(false); monthlyCommissionPercent.setText(""); // Перестановка мест компонентов grid_pan.getChildren().removeAll(monthlyCommissionAmount, lab_month_mny,schema,combo_type,btn_res,onceCommissionPercent, iab_one_pr,onceCommissionAmount,lab_one_mny,monthlyCommissionPercent, lab_month_pr); grid_pan.add(monthlyCommissionAmount,1,3); grid_pan.add(lab_month_mny,0,3); grid_pan.add(schema,0,4); grid_pan.add(combo_type,1,4); grid_pan.add(btn_res,1,5); } // если выбрано Аннуитетная else { // Установка видемости текставых полей lab_one_mny.setVisible(true); onceCommissionAmount.setVisible(true); iab_one_pr.setVisible(true); onceCommissionPercent.setVisible(true); lab_month_mny.setVisible(false); monthlyCommissionAmount.setVisible(false); monthlyCommissionAmount.setText(""); lab_month_pr.setVisible(true); monthlyCommissionPercent.setVisible(true); // Перестановка мест компонентов grid_pan.getChildren().removeAll(monthlyCommissionAmount, lab_month_mny,schema,combo_type,btn_res,onceCommissionPercent, iab_one_pr,onceCommissionAmount,lab_one_mny,monthlyCommissionPercent, lab_month_pr); grid_pan.add(onceCommissionPercent,1,3); grid_pan.add(iab_one_pr,0,3); grid_pan.add(onceCommissionAmount,1,4); grid_pan.add(lab_one_mny,0,4); grid_pan.add(monthlyCommissionPercent,1,5); grid_pan.add(lab_month_pr,0,5); grid_pan.add(schema,0,6); grid_pan.add(combo_type,1,6); grid_pan.add(btn_res,1,7); } } }
39.468208
141
0.653705