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 |
|---|---|---|---|---|---|
b1beb458f5a9b113d40c92aec16dbd6a8c35b152 | 1,491 | package mhfc.net.common.worldedit;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
public enum ClipboardFormats implements IClipboardFormat {
EXTENDED_FORGE_SCHEMATIC {
@Override
public ClipboardReader getReader(InputStream inputStream) throws IOException {
NBTInputStream nbtis = new NBTInputStream(new GZIPInputStream(inputStream));
return new PortableSchematicReader(nbtis, BlockIdMappingTable.createForgeMappingTable());
}
@Override
public ClipboardWriter getWriter(OutputStream outputStream) throws IOException {
NBTOutputStream nbtos = new NBTOutputStream(new GZIPOutputStream(outputStream));
return new PortableSchematicWriter(nbtos, BlockIdMappingTable.createForgeMappingTable());
}
},
NATIVE_SCHEMATIC {
@Override
public ClipboardReader getReader(InputStream inputStream) throws IOException {
return ClipboardFormat.SCHEMATIC.getReader(inputStream);
}
@Override
public ClipboardWriter getWriter(OutputStream outputStream) throws IOException {
return ClipboardFormat.SCHEMATIC.getWriter(outputStream);
}
};
}
| 36.365854 | 93 | 0.798793 |
2c187ebdb45158c8947bf9fddf2c590d57ab5e96 | 914 | package net.serenitybdd.screenplay.actions;
import net.serenitybdd.core.pages.PageObject;
/**
* Open the browser of an actor on a specified page or URL.
*/
public class Open {
public static OpenPage browserOn(PageObject targetPage) {
return new OpenPage(targetPage);
}
public static Open browserOn() {
return new Open();
}
public static OpenUrl url(String targetUrl) {
return new OpenUrl(targetUrl);
}
public static OpenAt relativeUrl(String targetUrl) {
return new OpenAt(targetUrl);
}
public OpenPage the(PageObject targetPage) {
return new OpenPage(targetPage);
}
public OpenPageWithName thePageNamed(String pageName) {
return new OpenPageWithName(pageName);
}
public OpenPageFromClass the(Class<? extends PageObject> targetPageClass) {
return new OpenPageFromClass(targetPageClass);
}
} | 24.052632 | 79 | 0.688184 |
563d293b6fb02cc7e7ba32a905714aeabb6fd616 | 5,250 | package com.fati.model;
import com.datastax.driver.mapping.annotations.Table;
import java.io.Serializable;
import java.util.Date;
/**
* author @ fati
* created @ 10.06.2021
*/
@Table(keyspace = "letterboxd", name = "twitteruser")
public class TwitterUser implements Serializable {
private static final long serialVersionUID = 5882477328310729699L;
private String id;
private String name;
private String screenName;
private String location;
private String url;
private String description;
private Boolean verified;
private Integer followersCount;
private Integer friendsCount;
private Integer listedCount;
private Integer favouritesCount;
private Integer statusesCount;
private Date createdAt;
private Boolean geoEnabled;
private String lang;
private Boolean contributorsEnabled;
private Boolean isTranslator;
private Boolean defaultProfile;
private Boolean defaultProfileImage;
private String profileBackgroundColor;
private Boolean profileBackgroundTiled;
private Boolean profileUseBackgroundImage;
private Boolean isVerified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public Integer getFollowersCount() {
return followersCount;
}
public void setFollowersCount(Integer followersCount) {
this.followersCount = followersCount;
}
public Integer getFriendsCount() {
return friendsCount;
}
public void setFriendsCount(Integer friendsCount) {
this.friendsCount = friendsCount;
}
public Integer getListedCount() {
return listedCount;
}
public void setListedCount(Integer listedCount) {
this.listedCount = listedCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public Integer getStatusesCount() {
return statusesCount;
}
public void setStatusesCount(Integer statusesCount) {
this.statusesCount = statusesCount;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Boolean getGeoEnabled() {
return geoEnabled;
}
public void setGeoEnabled(Boolean geoEnabled) {
this.geoEnabled = geoEnabled;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Boolean getContributorsEnabled() {
return contributorsEnabled;
}
public void setContributorsEnabled(Boolean contributorsEnabled) {
this.contributorsEnabled = contributorsEnabled;
}
public Boolean getIsTranslator() {
return isTranslator;
}
public void setIsTranslator(Boolean translator) {
isTranslator = translator;
}
public Boolean getDefaultProfile() {
return defaultProfile;
}
public void setDefaultProfile(Boolean defaultProfile) {
this.defaultProfile = defaultProfile;
}
public Boolean getDefaultProfileImage() {
return defaultProfileImage;
}
public void setDefaultProfileImage(Boolean defaultProfileImage) {
this.defaultProfileImage = defaultProfileImage;
}
public String getProfileBackgroundColor() {
return profileBackgroundColor;
}
public void setProfileBackgroundColor(String profileBackgroundColor) {
this.profileBackgroundColor = profileBackgroundColor;
}
public Boolean getProfileBackgroundTiled() {
return profileBackgroundTiled;
}
public void setProfileBackgroundTiled(Boolean profileBackgroundTiled) {
this.profileBackgroundTiled = profileBackgroundTiled;
}
public Boolean getProfileUseBackgroundImage() {
return profileUseBackgroundImage;
}
public void setProfileUseBackgroundImage(Boolean profileUseBackgroundImage) {
this.profileUseBackgroundImage = profileUseBackgroundImage;
}
public Boolean getIsVerified() {
return isVerified;
}
public void setIsVerified(Boolean isVerified) {
this.isVerified = isVerified;
}
}
| 23.230088 | 81 | 0.67619 |
a8c5acfb08229f02c8bb71730b7c235ee54bc7fc | 1,623 | /* Copyright 2021 Telstra Open Source
*
* 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.openkilda.northbound.dto.v1.switches;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonNaming(value = SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GroupInfoDto {
private Integer groupId;
private List<BucketDto> groupBuckets;
private List<BucketDto> missingGroupBuckets;
private List<BucketDto> excessGroupBuckets;
@Data
@AllArgsConstructor
@JsonNaming(value = SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class BucketDto implements Serializable {
private Integer port;
private Integer vlan;
private Integer vni;
}
}
| 32.46 | 79 | 0.763401 |
5ad4d4124f346a2245f246f9f1f790e78aaca648 | 2,305 | package org.pitest.coverage.execute;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.pitest.coverage.CoverageResult;
import org.pitest.functional.SideEffect1;
import org.pitest.testapi.Description;
import org.pitest.util.Id;
import org.pitest.util.SafeDataInputStream;
import sun.pitest.CodeCoverageStore;
// does this test add any value?
public class ReceiveTest {
private Receive testee;
private SideEffect1<CoverageResult> handler;
private CoverageResult result;
private Description description;
@Mock
private SafeDataInputStream is;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.handler = stubHandler();
this.testee = new Receive(this.handler);
this.description = new Description("foo", "bar");
}
private SideEffect1<CoverageResult> stubHandler() {
return new SideEffect1<CoverageResult>() {
@Override
public void apply(final CoverageResult a) {
ReceiveTest.this.result = a;
}
};
}
@Test
public void shouldReportNoCoverageWhenNoTestsRun() {
this.testee.apply(Id.DONE, this.is);
assertNull(this.result);
}
@Test
public void shouldReportWhenTestFails() {
recordTestCoverage(0, 0, 0, false);
assertEquals(false, this.result.isGreenTest());
}
@Test
public void shouldReportWhenTestPasses() {
recordTestCoverage(0, 0, 0, true);
assertEquals(true, this.result.isGreenTest());
}
private void recordTestCoverage(final int executionTime, final int classId,
final int probeNumber, final boolean testPassed) {
when(this.is.readInt()).thenReturn(classId, executionTime);
when(this.is.readString()).thenReturn("foo");
this.testee.apply(Id.CLAZZ, this.is);
when(this.is.read(Description.class)).thenReturn(this.description);
when(this.is.readInt()).thenReturn(1);
when(this.is.readLong()).thenReturn(1l,
CodeCoverageStore.encode(classId, probeNumber));
when(this.is.readBoolean()).thenReturn(testPassed);
this.testee.apply(Id.OUTCOME, this.is);
}
}
| 27.771084 | 77 | 0.712364 |
309130af1fb31046356786bf5a04a9202da049ca | 458 | package ru.kpfu.itis.tasks.task_I;
public class Cat extends Animal{
protected String color;
public Cat(int legs, int ears, int eyes,
String texture, boolean tail, String color){
super(legs, ears, eyes, texture, tail);
setColor(color);
}
public void setColor(String color){
if(color.length() >= 3){
this.color = color;
}
}
public String getColor(){
return color;
}
} | 21.809524 | 52 | 0.587336 |
e8be2468226ac820801e40111de02d2d6b607291 | 2,283 | https://practice.geeksforgeeks.org/problems/max-and-min-element-in-binary-tree
import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
import java.lang.Math;
class Node
{
int data;
Node left,right;
Node(int d) {data = d; left =right= null; }
}
public class GFG2
{
public static void inorder(Node root)
{
if(root==null)
return;
inorder(root.left);
System.out.print(root.data);
inorder(root.right);
}
/* Drier program to test above functions */
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
GFG2 llist=new GFG2();
Node root=null,parent=null;
HashMap<Integer, Node> m = new HashMap<>();
for(int i=0;i<n;i++)
{
int a=sc.nextInt();
int b=sc.nextInt();
char c=sc.next().charAt(0);
if(m.containsKey(a)==false)
{
parent=new Node(a);
m.put(a,parent);
if(root==null)
root=parent;
}
else
parent=m.get(a);
Node child=new Node(b);
if(c=='L')
parent.left=child;
else
parent.right=child;
m.put(b,child);
}
GFG obj = new GFG();
int Max=obj.findMax(root);
int Min=obj.findMin(root);
System.out.println(Max+" "+Min);
}
}
}// } Driver Code Ends
/*class Node
{
int data;
Node left,right;
Node(int d)
{
data=d;
left=right=null;
}
}*/
//Complete the findMax and findMin functions.
class GFG
{
public static int findMax(Node root)
{
if(root==null)
return Integer.MIN_VALUE;
return Math.max(root.data,Math.max(findMax(root.left),findMax(root.right)));
}
public static int findMin(Node root)
{
if(root==null)
return Integer.MAX_VALUE;
return Math.min(root.data,Math.min(findMin(root.left),findMin(root.right)));
}
} | 24.548387 | 82 | 0.494525 |
5d693055db8c00d99fc0aa7c91207d08d6657b95 | 1,509 | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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.github.zj.dreamly.tool.node;
import cn.hutool.json.JSONUtil;
import com.github.zj.dreamly.tool.api.ResponseEntity;
import java.util.ArrayList;
import java.util.List;
/**
* @author Chill
* @since 0.0.1
*/
public class NodeTest {
public static void main(String[] args) {
List<ForestNode> list = new ArrayList<>();
list.add(new ForestNode<>(1L, 0L, 1));
list.add(new ForestNode<>(2L, 0L, 2));
list.add(new ForestNode<>(3L, 1L,3));
list.add(new ForestNode<>(4L, 2L,4));
list.add(new ForestNode<>(5L, 3L, 5));
list.add(new ForestNode<>(6L, 4L, 6));
list.add(new ForestNode<>(7L, 3L, 7));
list.add(new ForestNode<>(8L, 5L, 8));
list.add(new ForestNode<>(9L, 6L, 9));
list.add(new ForestNode<>(10L, 9L, 10));
List<ForestNode> tns = ForestNodeMerger.merge(list);
tns.forEach(node ->
System.out.println(JSONUtil.toJsonStr(node))
);
}
}
| 30.795918 | 75 | 0.695162 |
ee2b131a4475e5b19867cb2241a3d93d6082dbe7 | 2,147 | package grafioschtrader.task;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import grafioschtrader.entities.Globalparameters;
import grafioschtrader.entities.TaskDataChange;
import grafioschtrader.entities.Tenant;
import grafioschtrader.repository.GlobalparametersJpaRepository;
import grafioschtrader.repository.TaskDataChangeJpaRepository;
import grafioschtrader.types.TaskDataExecPriority;
import grafioschtrader.types.TaskType;
/**
* Execute Job PRICE_AND_SPLIT_DIV_CALENDAR_UPDATE_THRU when it was not executed
* the day before or there is no existing
* {@link grafioschtrader.entities.TaskDataChange}.
*
* @author Hugo Graf
*
*/
@Component
public class ExecuteStartupTask implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private TaskDataChangeJpaRepository taskDataChangeJpaRepository;
@Autowired
private GlobalparametersJpaRepository globalparametersJpaRepository;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
Optional<Globalparameters> gpLastAppend = globalparametersJpaRepository
.findById(Globalparameters.GLOB_KEY_YOUNGES_SPLIT_APPEND_DATE);
if (gpLastAppend.isEmpty() || gpLastAppend.get().getPropertyDate().isBefore(LocalDate.now().minusDays(1L))) {
addDataUpdateTask();
} else if (taskDataChangeJpaRepository.count() == 0) {
addDataUpdateTask();
taskDataChangeJpaRepository.save(new TaskDataChange(TaskType.REBUILD_HOLDINGS_ALL_OR_SINGLE_TENANT,
TaskDataExecPriority.PRIO_NORMAL, LocalDateTime.now().plusMinutes(10), null, null));
}
}
private void addDataUpdateTask() {
TaskDataChange taskDataChange = new TaskDataChange(TaskType.PRICE_AND_SPLIT_DIV_CALENDAR_UPDATE_THRU,
TaskDataExecPriority.PRIO_HIGH, LocalDateTime.now().plusMinutes(5), null, null);
taskDataChangeJpaRepository.save(taskDataChange);
}
}
| 37.666667 | 113 | 0.814159 |
3898180fdc6609b844f58f25d30f882d52a1d263 | 761 | import static java.lang.System.out;
import java.util.Scanner;
import java.util.*;
import javax.swing.*;
public class LamdaExpressionDemo
{
public static void main(String... args)
{
String arr[] ={"The", "Quick", "Brown", "Fox", "Jumps", "Over", "To", "The", "Lazy", "Dog", "Tit", "For", "Tat"};
out.println("Before Sorting : ");
out.println(Arrays.toString(arr));
Arrays.sort(arr);
out.println("After Sorting : ");
out.println(Arrays.toString(arr));
// Sorting based on the string lenth
Arrays.sort(arr, (first, second) ->{ return first.length() - second.length(); });
out.println("After Sorting : ");
out.println(Arrays.toString(arr));
}
} | 30.44 | 121 | 0.574244 |
3b9d41483d2ed31036b7d53fe4b04ee20d0af592 | 2,072 | package largePriceFeed;
import com.ib.client.Contract;
import com.ib.client.EClientSocket;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class RequestPriceData {
final Contract cont;
final boolean snapshot;
private final EClientSocket socket;
private final WritePriceData writePriceData;
private final Connection sqlConnection;
private static int nextId = 1;
private final int myId;
List<Double> bidPrices = new ArrayList<>();
List<Double> askPrices = new ArrayList<>();
List<Double> lastPrices = new ArrayList<>();
List<Double> closePrices = new ArrayList<>();
double bidPrice = -1.0;
double askPrice = -1.0;
double lastPrice = -1.0;
double closePrice = -1.0;
public RequestPriceData(Contract cont, boolean snapshot,
EClientSocket socket, Connection sqlConnection) {
this.cont = cont;
this.snapshot = snapshot;
this.socket = socket;
this.sqlConnection = sqlConnection;
writePriceData = new WritePriceData(this, socket, sqlConnection);
myId = nextId++;
((RequestPriceWrapper) socket.requestPriceWrapper()).dataMap.put(myId, this);
reqData();
}
private void reqData() {
socket.reqMktData(myId, cont, "", snapshot, null);
}
// record bid price
public void dataRecdBid(double inputPrice) {
bidPrice = inputPrice;
bidPrices.add(inputPrice);
writePriceData.check();
}
// record ask price
public void dataRecdAsk(double inputPrice) {
askPrice = inputPrice;
askPrices.add(inputPrice);
writePriceData.check();
}
// record last price
public void dataRecdLast(double inputPrice) {
lastPrice = inputPrice;
lastPrices.add(inputPrice);
writePriceData.check();
}
// record close price
public void dataRecdClose(double inputPrice) {
closePrice = inputPrice;
closePrices.add(inputPrice);
writePriceData.check();
}
} | 28.383562 | 85 | 0.653475 |
52024ce490966e787732e7b127ab689079c526ca | 1,970 | package one.edee.darwin.model;
import one.edee.darwin.model.version.VersionComparator;
import one.edee.darwin.model.version.VersionDescriptor;
import one.edee.darwin.resources.DefaultResourceNameAnalyzer;
import one.edee.darwin.resources.ResourceNameAnalyzer;
import org.springframework.core.io.Resource;
import java.io.Serializable;
import java.util.Comparator;
import static java.util.Optional.ofNullable;
/**
* Can compare two Resource objects. If resources' file name contains valid patch version as defined in
* {@link VersionDescriptor} compares resources by {@link VersionComparator} implementation.
*
* @author Michal Kolesnac, FG Forrest a.s. (c) 2009
*/
public class ResourceVersionComparator implements Comparator<Resource>, Serializable {
private static final long serialVersionUID = -7943722730050082245L;
private final ResourceNameAnalyzer resourceNameAnalyzer = new DefaultResourceNameAnalyzer();
private final VersionComparator versionComparator = new VersionComparator();
@Override
public int compare(Resource o1, Resource o2) {
if (o1 == null || o2 == null) {
throw new IllegalArgumentException("Resources to be compared against cannot be null!");
}
final VersionDescriptor v1 = resourceNameAnalyzer.getVersionFromResource(o1);
final VersionDescriptor v2 = resourceNameAnalyzer.getVersionFromResource(o2);
if (v1 != null && v2 == null) {
return 1;
}
if (v2 != null) {
return versionComparator.compare(v1, v2);
}
final String aFileName = ofNullable(o1.getFilename()).map(String::toLowerCase).orElse("");
final String bFileName = ofNullable(o2.getFilename()).map(String::toLowerCase).orElse("");
int result = aFileName.compareToIgnoreCase(bFileName);
if (result > 0) {
return 1;
}
if (result < 0) {
return -1;
}
return result;
}
}
| 38.627451 | 103 | 0.701015 |
879868335542a705f9f940e9e419d09b988fd5dd | 507 | package org.kritikal.fabric.net.dns;
import java.util.HashMap;
/**
* Created by ben on 17/03/15.
*/
public class DnsResponseCompressionState {
public HashMap<String, Integer> map = new HashMap<>();
public int findResponse(String domainName) {
Integer i = map.get(domainName);
if (i == null) return 0;
return (i & 0b00111111111111111) ^ 0b1100000000000000;
}
public void storeResponse(int start, String domainName) {
map.put(domainName, start);
}
}
| 23.045455 | 62 | 0.66075 |
99830b566c2c573848005bc262cf9c8a385973b9 | 2,935 | /*
Copyright (c) 2013, Sony Mobile Communications AB
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Sony Mobile Communications AB nor the names
of its contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sonyericsson.extras.liveware.extension.util.control;
import com.sonyericsson.extras.liveware.aef.control.Control;
/**
* The control object click event class holds information about an object click
* event.
*/
public class ControlObjectClickEvent {
private final int mClickType;
private final long mTimeStamp;
private final int mLayoutReference;
/**
* Create click event.
*
* @see Control.Intents#CLICK_TYPE_SHORT
* @see Control.Intents#CLICK_TYPE_LONG
* @param clickType The click type.
* @param timeStamp The time when the event occurred.
* @param layoutReference Reference to view in the layout
*/
public ControlObjectClickEvent(final int clickType, final long timeStamp,
final int layoutReference) {
mClickType = clickType;
mTimeStamp = timeStamp;
mLayoutReference = layoutReference;
}
/**
* Get the click type.
*
* @return The click type.
*/
public int getClickType() {
return mClickType;
}
/**
* Get the touch event time stamp.
*
* @return The time stamp.
*/
public long getTimeStamp() {
return mTimeStamp;
}
/**
* Get the layout reference.
*
* @return Reference to view in the layout.
*/
public int getLayoutReference() {
return mLayoutReference;
}
}
| 32.977528 | 79 | 0.726405 |
9d142d1826565f67a00461fff895d4b1cf484403 | 393 | package com.xwheel.xmonitor.commons.utils;
import java.util.UUID;
/**
* @description: 全局标示符工具
* 保证同一时空所有机器唯一,由当前时间、日期、时钟序列、全局唯一的IEEE机器识别号
*/
public class GenerateUUIDUtils {
/**
* 获取全局唯一标识符
*
* @return 32位长度唯一主键
*/
public static String createUUID() {
String uuidStr = UUID.randomUUID().toString();
return uuidStr.replaceAll("-", "");
}
}
| 17.863636 | 54 | 0.628499 |
6b3750874bd6c3e5489c23ebf6e60cbe88f21a95 | 5,610 | package software.amazon.awssdk.regions;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* An Amazon Web Services region that hosts a set of Amazon services.
* <p>
* An instance of this class can be retrieved by referencing one of the static constants defined in this class (eg.
* {@link Region#US_EAST_1}) or by using the {@link Region#of(String)} method if the region you want is not included in
* this release of the SDK.
* </p>
* <p>
* Each AWS region corresponds to a separate geographical location where a set of Amazon services is deployed. These
* regions (except for the special {@link #AWS_GLOBAL} and {@link #AWS_CN_GLOBAL} regions) are separate from each other,
* with their own set of resources. This means a resource created in one region (eg. an SQS queue) is not available in
* another region.
* </p>
* <p>
* To programmatically determine whether a particular service is deployed to a region, you can use the
* {@code serviceMetadata} method on the service's client interface. Additional metadata about a region can be
* discovered using {@link RegionMetadata#of(Region)}.
* </p>
* <p>
* The {@link Region#id()} will be used as the signing region for all requests to AWS services unless an explicit region
* override is available in {@link RegionMetadata}. This id will also be used to construct the endpoint for accessing a
* service unless an explicit endpoint is available for that region in {@link RegionMetadata}.
* </p>
*/
@SdkPublicApi
@Generated("software.amazon.awssdk:codegen")
public final class Region {
public static final Region AP_SOUTH_1 = Region.of("ap-south-1");
public static final Region EU_WEST_3 = Region.of("eu-west-3");
public static final Region EU_WEST_2 = Region.of("eu-west-2");
public static final Region EU_WEST_1 = Region.of("eu-west-1");
public static final Region AP_NORTHEAST_3 = Region.of("ap-northeast-3");
public static final Region AP_NORTHEAST_2 = Region.of("ap-northeast-2");
public static final Region AP_NORTHEAST_1 = Region.of("ap-northeast-1");
public static final Region CA_CENTRAL_1 = Region.of("ca-central-1");
public static final Region SA_EAST_1 = Region.of("sa-east-1");
public static final Region CN_NORTH_1 = Region.of("cn-north-1");
public static final Region US_GOV_WEST_1 = Region.of("us-gov-west-1");
public static final Region AP_SOUTHEAST_1 = Region.of("ap-southeast-1");
public static final Region AP_SOUTHEAST_2 = Region.of("ap-southeast-2");
public static final Region EU_CENTRAL_1 = Region.of("eu-central-1");
public static final Region US_EAST_1 = Region.of("us-east-1");
public static final Region US_EAST_2 = Region.of("us-east-2");
public static final Region US_WEST_1 = Region.of("us-west-1");
public static final Region CN_NORTHWEST_1 = Region.of("cn-northwest-1");
public static final Region US_WEST_2 = Region.of("us-west-2");
public static final Region AWS_GLOBAL = Region.of("aws-global", true);
public static final Region AWS_CN_GLOBAL = Region.of("aws-cn-global", true);
public static final Region AWS_US_GOV_GLOBAL = Region.of("aws-us-gov-global", true);
public static final Region AWS_ISO_GLOBAL = Region.of("aws-iso-global", true);
public static final Region AWS_ISO_B_GLOBAL = Region.of("aws-iso-b-global", true);
private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(AP_SOUTH_1, EU_WEST_3, EU_WEST_2,
EU_WEST_1, AP_NORTHEAST_3, AP_NORTHEAST_2, AP_NORTHEAST_1, CA_CENTRAL_1, SA_EAST_1, CN_NORTH_1, US_GOV_WEST_1,
AP_SOUTHEAST_1, AP_SOUTHEAST_2, EU_CENTRAL_1, US_EAST_1, US_EAST_2, US_WEST_1, CN_NORTHWEST_1, US_WEST_2, AWS_GLOBAL,
AWS_CN_GLOBAL, AWS_US_GOV_GLOBAL, AWS_ISO_GLOBAL, AWS_ISO_B_GLOBAL));
private final boolean isGlobalRegion;
private final String id;
private Region(String id, boolean isGlobalRegion) {
this.id = id;
this.isGlobalRegion = isGlobalRegion;
}
public static Region of(String value) {
return of(value, false);
}
private static Region of(String value, boolean isGlobalRegion) {
Validate.paramNotBlank(value, "region");
String urlEncodedValue = SdkHttpUtils.urlEncode(value);
return RegionCache.put(urlEncodedValue, isGlobalRegion);
}
public static List<Region> regions() {
return REGIONS;
}
public String id() {
return this.id;
}
public RegionMetadata metadata() {
return RegionMetadata.of(this);
}
public boolean isGlobalRegion() {
return isGlobalRegion;
}
@Override
public String toString() {
return id;
}
private static class RegionCache {
private static final ConcurrentHashMap<String, Region> VALUES = new ConcurrentHashMap<>();
private RegionCache() {
}
private static Region put(String value, boolean isGlobalRegion) {
return VALUES.computeIfAbsent(value, v -> new Region(value, isGlobalRegion));
}
}
}
| 39.230769 | 208 | 0.686809 |
ce7e8e7a80c232204bd12b21563096bdbda9c274 | 634 | package com.kotorresearch.script.data;
/**
* @author Dmitry
*/
public class NwnVector {
public float x;
public float y;
public float z;
public NwnVector(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public NwnVector() {
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
}
| 13.782609 | 49 | 0.490536 |
ebae14f95831c07ad319f752290af7a28d511baa | 1,078 | package com.bolingcavalry.jacksondemo.annotation.fieldannotation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonPropertyDeserialization {
static class Test {
@JsonProperty(value = "json_field0")
private String field0;
private String field1;
@JsonProperty(value = "json_field1")
public void setField1(String field1) {
this.field1 = field1;
}
@Override
public String toString() {
return "Test{" +
"field0='" + field0 + '\'' +
", field1='" + field1 + '\'' +
'}';
}
}
public static void main(String[] args) throws Exception {
String jsonStr = "{\n" +
" \"json_field0\" : \"000\",\n" +
" \"json_field1\" : \"111\"\n" +
"}";
System.out.println(new ObjectMapper().readValue(jsonStr, Test.class));
}
}
| 27.641026 | 78 | 0.561224 |
cbdc577cc8b9eedd39586f611f9a56d438334cd1 | 905 | /**
*/
package br.ufes.inf.nemo.frameweb.model.frameweb.impl;
import br.ufes.inf.nemo.frameweb.model.frameweb.AttributeMapping;
import br.ufes.inf.nemo.frameweb.model.frameweb.FramewebPackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.uml2.uml.internal.impl.StereotypeImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Attribute Mapping</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("restriction")
public class AttributeMappingImpl extends StereotypeImpl implements AttributeMapping {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AttributeMappingImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return FramewebPackage.Literals.ATTRIBUTE_MAPPING;
}
} //AttributeMappingImpl
| 22.073171 | 86 | 0.687293 |
bbe64661fdb678242766d4d1003045bc3f9a6cd1 | 66 | package io.flutter.utils;
public class AndroidLocationProvider {}
| 22 | 39 | 0.833333 |
ede5f34a74d0bc0c6c52c025b46f25d223ee01e5 | 307 | package com.noturaun.posapp.repository;
import com.noturaun.posapp.entity.Product;
public interface ProductRepository {
Product[] getAll();
void add(Product product);
Product get(Integer productId);
void update(Integer productId, Product changes);
Boolean delete(Integer productId);
}
| 25.583333 | 52 | 0.752443 |
894e7e298f176228fec802af3a5c155e1d03f2e5 | 7,034 | package org.telegram.telegrambots.api.objects.inlinequery.result;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.telegram.telegrambots.api.objects.inlinequery.inputmessagecontent.InputMessageContent;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.exceptions.TelegramApiValidationException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Represents a venue. By default, the venue will be sent by the user. Alternatively, you can
* use input_message_content to send a message with the specified content instead of the venue.
* @note This will only work in Telegram versions released after 9 April, 2016. Older clients will
* ignore them.
* @date 10 of April of 2016
*/
public class InlineQueryResultVenue implements InlineQueryResult {
private static final String TYPE_FIELD = "type";
private static final String ID_FIELD = "id";
private static final String TITLE_FIELD = "title";
private static final String LATITUDE_FIELD = "latitude";
private static final String LONGITUDE_FIELD = "longitude";
private static final String ADDRESS_FIELD = "address";
private static final String FOURSQUARE_ID_FIELD = "foursquare_id";
private static final String REPLY_MARKUP_FIELD = "reply_markup";
private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content";
private static final String THUMBURL_FIELD = "thumb_url";
private static final String THUMBWIDTH_FIELD = "thumb_width";
private static final String THUMBHEIGHT_FIELD = "thumb_height";
@JsonProperty(TYPE_FIELD)
private final String type = "venue"; ///< Type of the result, must be "venue"
@JsonProperty(ID_FIELD)
private String id; ///< Unique identifier of this result, 1-64 bytes
@JsonProperty(TITLE_FIELD)
private String title; ///< Optional. Location title
@JsonProperty(LATITUDE_FIELD)
private Float latitude; ///< Venue latitude in degrees
@JsonProperty(LONGITUDE_FIELD)
private Float longitude; ///< Venue longitude in degrees
@JsonProperty(ADDRESS_FIELD)
private String address; ///< Address of the venue
@JsonProperty(FOURSQUARE_ID_FIELD)
private String foursquareId; ///< Optional. Foursquare identifier of the venue if known
@JsonProperty(REPLY_MARKUP_FIELD)
private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message
@JsonProperty(INPUTMESSAGECONTENT_FIELD)
private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent
@JsonProperty(THUMBURL_FIELD)
private String thumbUrl; ///< Optional. URL of the thumbnail (jpeg only) for the file
@JsonProperty(THUMBWIDTH_FIELD)
private Integer thumbWidth; ///< Optional. Thumbnail width
@JsonProperty(THUMBHEIGHT_FIELD)
private Integer thumbHeight; ///< Optional. Thumbnail height
public InlineQueryResultVenue() {
super();
}
public String getType() {
return type;
}
public String getId() {
return id;
}
public InlineQueryResultVenue setId(String id) {
this.id = id;
return this;
}
public String getTitle() {
return title;
}
public InlineQueryResultVenue setTitle(String title) {
this.title = title;
return this;
}
public Float getLatitude() {
return latitude;
}
public InlineQueryResultVenue setLatitude(Float latitude) {
this.latitude = latitude;
return this;
}
public Float getLongitude() {
return longitude;
}
public InlineQueryResultVenue setLongitude(Float longitude) {
this.longitude = longitude;
return this;
}
public String getAddress() {
return address;
}
public InlineQueryResultVenue setAddress(String address) {
this.address = address;
return this;
}
public String getFoursquareId() {
return foursquareId;
}
public InlineQueryResultVenue setFoursquareId(String foursquareId) {
this.foursquareId = foursquareId;
return this;
}
public InlineKeyboardMarkup getReplyMarkup() {
return replyMarkup;
}
public InlineQueryResultVenue setReplyMarkup(InlineKeyboardMarkup replyMarkup) {
this.replyMarkup = replyMarkup;
return this;
}
public InputMessageContent getInputMessageContent() {
return inputMessageContent;
}
public InlineQueryResultVenue setInputMessageContent(InputMessageContent inputMessageContent) {
this.inputMessageContent = inputMessageContent;
return this;
}
public String getThumbUrl() {
return thumbUrl;
}
public InlineQueryResultVenue setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
return this;
}
public Integer getThumbWidth() {
return thumbWidth;
}
public InlineQueryResultVenue setThumbWidth(Integer thumbWidth) {
this.thumbWidth = thumbWidth;
return this;
}
public Integer getThumbHeight() {
return thumbHeight;
}
public InlineQueryResultVenue setThumbHeight(Integer thumbHeight) {
this.thumbHeight = thumbHeight;
return this;
}
@Override
public void validate() throws TelegramApiValidationException {
if (id == null || id.isEmpty()) {
throw new TelegramApiValidationException("ID parameter can't be empty", this);
}
if (title == null || title.isEmpty()) {
throw new TelegramApiValidationException("Title parameter can't be empty", this);
}
if (latitude == null) {
throw new TelegramApiValidationException("Latitude parameter can't be empty", this);
}
if (longitude == null) {
throw new TelegramApiValidationException("Longitude parameter can't be empty", this);
}
if (address == null || address.isEmpty()) {
throw new TelegramApiValidationException("Longitude parameter can't be empty", this);
}
if (inputMessageContent != null) {
inputMessageContent.validate();
}
if (replyMarkup != null) {
replyMarkup.validate();
}
}
@Override
public String toString() {
return "InlineQueryResultVenue{" +
"type='" + type + '\'' +
", id='" + id + '\'' +
", mimeType='" + latitude + '\'' +
", documentUrl='" + longitude + '\'' +
", thumbHeight=" + thumbHeight +
", thumbWidth=" + thumbWidth +
", thumbUrl='" + thumbUrl + '\'' +
", title='" + title + '\'' +
", foursquareId='" + foursquareId + '\'' +
", address='" + address + '\'' +
", inputMessageContent='" + inputMessageContent + '\'' +
", replyMarkup='" + replyMarkup + '\'' +
'}';
}
}
| 33.655502 | 101 | 0.656668 |
64138ae8cb7dc454bd5cb63453f586b068a063ee | 4,980 | package com.ddphin.rabbitmq.scheduler;
import com.ddphin.rabbitmq.configuration.DdphinRabbitmqProperties;
import com.ddphin.rabbitmq.sender.RabbitmqCommonTxMessageMonitor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* RabbitmqRetryScheduler
*
* @Date 2019/7/24 下午6:12
* @Author ddphin
*/
@Slf4j
public class RabbitmqRetrySchedulerConfigurer implements SchedulingConfigurer {
private RabbitmqCommonTxMessageMonitor rabbitmqCommonTxMessageMonitor;
private AtomicInteger integer = new AtomicInteger(0);
private String retryCron = "0 0/1 * * * ?";
private String redoCron = "30 0/1 * * * ?";
private String clearCron = "0 0/1 * * * ?";
private Integer poolSize = 10;
private Boolean enableRetry = true;
private Boolean enableRedo = true;
private Boolean enableClear = true;
public RabbitmqRetrySchedulerConfigurer(
RabbitmqCommonTxMessageMonitor rabbitmqCommonTxMessageMonitor,
DdphinRabbitmqProperties ddphinRabbitmqProperties) {
this.rabbitmqCommonTxMessageMonitor = rabbitmqCommonTxMessageMonitor;
if (null != ddphinRabbitmqProperties.getRetryCron()) {
this.retryCron = ddphinRabbitmqProperties.getRetryCron();
}
if (null != ddphinRabbitmqProperties.getRedoCron()) {
this.redoCron = ddphinRabbitmqProperties.getRedoCron();
}
if (null != ddphinRabbitmqProperties.getClearCron()) {
this.clearCron = ddphinRabbitmqProperties.getClearCron();
}
if (null != ddphinRabbitmqProperties.getPoolSize()) {
this.poolSize = ddphinRabbitmqProperties.getPoolSize();
}
if (null != ddphinRabbitmqProperties.getEnableRetry()) {
this.enableRetry = ddphinRabbitmqProperties.getEnableRetry();
}
if (null != ddphinRabbitmqProperties.getEnableRedo()) {
this.enableRedo = ddphinRabbitmqProperties.getEnableRedo();
}
if (null != ddphinRabbitmqProperties.getEnableClear()) {
this.enableClear = ddphinRabbitmqProperties.getEnableClear();
}
}
public String getRetryCron() {
return this.retryCron;
}
public void setRetryCron(String retryCron) {
this.retryCron = retryCron;
}
public String getRedoCron() {
return this.redoCron;
}
public void setRedoCron(String redoCron) {
this.redoCron = redoCron;
}
public String getClearCron() {
return this.clearCron;
}
public void setClearCron(String clearCron) {
this.clearCron = clearCron;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
if (enableRetry || enableRedo || enableClear) {
scheduledTaskRegistrar.setScheduler(this.newExecutors());
}
if (enableRetry) {
scheduledTaskRegistrar.addTriggerTask(this::retry, triggerContext -> {
CronTrigger trigger = new CronTrigger(this.getRetryCron());
return trigger.nextExecutionTime(triggerContext);
});
}
if (enableRedo) {
scheduledTaskRegistrar.addTriggerTask(this::redo, triggerContext -> {
CronTrigger trigger = new CronTrigger(this.getRedoCron());
return trigger.nextExecutionTime(triggerContext);
});
}
if (enableClear) {
scheduledTaskRegistrar.addTriggerTask(this::clear, triggerContext -> {
CronTrigger trigger = new CronTrigger(this.getClearCron());
return trigger.nextExecutionTime(triggerContext);
});
}
}
private Executor newExecutors() {
return Executors.newScheduledThreadPool(this.poolSize, r -> new Thread(r, String.format("DDphin-Rabbitmq-%s", integer.incrementAndGet())));
}
private void retry() {
log.info("MQ message retry begin: CRON@{} - AT@{}", this.getRetryCron(), new Date());
rabbitmqCommonTxMessageMonitor.retry();
log.info("MQ message retry end: CRON@{} - AT@{}",this.getRetryCron(), new Date());
}
private void redo() {
log.info("MQ message redo begin: CRON@{} - AT@{}", this.getRedoCron(), new Date());
rabbitmqCommonTxMessageMonitor.redo();
log.info("MQ message redo end: CRON@{} - AT@{}",this.getRedoCron(), new Date());
}
private void clear() {
log.info("MQ message clear begin: CRON@{} - AT@{}", this.getRedoCron(), new Date());
rabbitmqCommonTxMessageMonitor.clear();
log.info("MQ message clear end: CRON@{} - AT@{}",this.getRedoCron(), new Date());
}
}
| 38.604651 | 147 | 0.666265 |
5274a7755880a5f3c910eb9bdf61b6554e4df13f | 37,395 | /*******************************************************************************
* ___ _ ____ ____
* / _ \ _ _ ___ ___| |_| _ \| __ )
* | | | | | | |/ _ \/ __| __| | | | _ \
* | |_| | |_| | __/\__ \ |_| |_| | |_) |
* \__\_\\__,_|\___||___/\__|____/|____/
*
* Copyright (c) 2014-2019 Appsicle
* Copyright (c) 2019-2022 QuestDB
*
* 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.questdb.griffin;
import io.questdb.cairo.CairoConfiguration;
import io.questdb.cairo.CairoEngine;
import io.questdb.cairo.CairoException;
import io.questdb.cairo.DefaultCairoConfiguration;
import io.questdb.cairo.security.CairoSecurityContextImpl;
import io.questdb.cairo.sql.InsertMethod;
import io.questdb.cairo.sql.InsertStatement;
import io.questdb.std.datetime.microtime.MicrosecondClockImpl;
import io.questdb.std.datetime.microtime.Timestamps;
import io.questdb.test.tools.TestUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
public class SecurityTest extends AbstractGriffinTest {
private static SqlExecutionContext readOnlyExecutionContext;
private static SqlCompiler memoryRestrictedCompiler;
private static CairoEngine memoryRestrictedEngine;
private static final AtomicInteger nCheckInterruptedCalls = new AtomicInteger();
private static long circuitBreakerCallLimit = Long.MAX_VALUE;
private static long circuitBreakerTimeoutDeadline = Long.MAX_VALUE;
@BeforeClass
public static void setUpReadOnlyExecutionContext() {
CairoConfiguration readOnlyConfiguration = new DefaultCairoConfiguration(root) {
@Override
public int getSqlMapPageSize() {
return 64;
}
@Override
public int getSqlMapMaxResizes() {
return 2;
}
@Override
public long getSqlSortKeyPageSize() {
return 64;
}
@Override
public int getSqlSortKeyMaxPages() {
return 2;
}
@Override
public int getSqlJoinMetadataPageSize() {
return 64;
}
@Override
public int getSqlJoinMetadataMaxResizes() {
return 10;
}
@Override
public long getSqlSortLightValuePageSize() {
return 1024;
}
@Override
public int getSqlSortLightValueMaxPages() {
return 11;
}
};
memoryRestrictedEngine = new CairoEngine(readOnlyConfiguration);
SqlExecutionCircuitBreaker dummyCircuitBreaker = new SqlExecutionCircuitBreaker() {
private long deadline;
@Override
public void test() {
int nCalls = nCheckInterruptedCalls.incrementAndGet();
long max = circuitBreakerCallLimit;
if (nCalls > max || MicrosecondClockImpl.INSTANCE.getTicks() > deadline) {
throw CairoException.instance(0).put("Interrupting SQL processing, max calls is ").put(max);
}
}
@Override
public void powerUp() {
deadline = circuitBreakerTimeoutDeadline;
}
};
readOnlyExecutionContext = new SqlExecutionContextImpl(
memoryRestrictedEngine, 1
)
.with(
new CairoSecurityContextImpl(
false),
bindVariableService,
null,
-1,
dummyCircuitBreaker);
memoryRestrictedCompiler = new SqlCompiler(memoryRestrictedEngine);
}
private static void setMaxCircuitBreakerChecks(long max) {
nCheckInterruptedCalls.set(0);
circuitBreakerCallLimit = max;
}
protected static void assertMemoryLeak(TestUtils.LeakProneCode code) throws Exception {
TestUtils.assertMemoryLeak(() -> {
try {
circuitBreakerCallLimit = Integer.MAX_VALUE;
nCheckInterruptedCalls.set(0);
code.run();
engine.releaseInactive();
Assert.assertEquals(0, engine.getBusyWriterCount());
Assert.assertEquals(0, engine.getBusyReaderCount());
memoryRestrictedEngine.releaseInactive();
Assert.assertEquals(0, memoryRestrictedEngine.getBusyWriterCount());
Assert.assertEquals(0, memoryRestrictedEngine.getBusyReaderCount());
} finally {
engine.clear();
memoryRestrictedEngine.clear();
}
});
}
@Test
public void testCreateTableDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
try {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
try {
assertQuery("count\n1\n", "select count() from balances", null);
Assert.fail();
} catch (SqlException ex) {
Assert.assertTrue(ex.toString().contains("table does not exist"));
}
});
}
@Test
public void testAlterTableDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", sqlExecutionContext);
CompiledQuery cq = compiler.compile("insert into balances values (1, 'EUR', 140.6)", sqlExecutionContext);
InsertStatement insertStatement = cq.getInsertStatement();
try (InsertMethod method = insertStatement.createMethod(sqlExecutionContext)) {
method.execute();
method.commit();
}
assertQuery("cust_id\tccy\tbalance\n1\tEUR\t140.6\n", "select * from balances", null, true, true);
try {
compile("alter table balances add column newcol int", readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
assertQueryPlain("cust_id\tccy\tbalance\n1\tEUR\t140.6\n", "select * from balances");
});
}
@Test
public void testDropTableDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", sqlExecutionContext);
try {
compiler.compile("drop table balances", readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
assertQuery("count\n0\n", "select count() from balances", null, false, true);
});
}
@Test
public void testInsertDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", sqlExecutionContext);
assertQuery("count\n0\n", "select count() from balances", null, false, true);
CompiledQuery cq = compiler.compile("insert into balances values (1, 'EUR', 140.6)", sqlExecutionContext);
InsertStatement insertStatement = cq.getInsertStatement();
try (InsertMethod method = insertStatement.createMethod(sqlExecutionContext)) {
method.execute();
method.commit();
}
assertQuery("count\n1\n", "select count() from balances", null, false, true);
try {
cq = compiler.compile("insert into balances values (2, 'ZAR', 140.6)", readOnlyExecutionContext);
insertStatement = cq.getInsertStatement();
try (InsertMethod method = insertStatement.createMethod(readOnlyExecutionContext)) {
method.execute();
method.commit();
}
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
assertQuery("count\n1\n", "select count() from balances", null, false, true);
});
}
@Test
public void testCircuitBreakerWithNonKeyedAgg() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(3,3,3,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10000)) timestamp(ts1)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sum\n" +
"165.6121723103405\n",
"select sum(d1) from tb1 where d1 < 0.2",
null,
false,
readOnlyExecutionContext,
true
);
Assert.assertTrue(nCheckInterruptedCalls.get() > 0);
try {
setMaxCircuitBreakerChecks(2);
assertQuery(
memoryRestrictedCompiler,
"sym1\nWCP\nICC\nUOJ\nFJG\nOZZ\nGHV\nWEK\nVDZ\nETJ\nUED\n",
"select sum(d1) from tb1 where d1 < 0.2",
null,
true,
readOnlyExecutionContext,
true
);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Interrupting SQL processing, max calls is 2"));
}
});
}
@Test
public void testBackupTableDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", sqlExecutionContext);
try {
compiler.compile("backup table balances", readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
});
}
@Test
public void testMemoryRestrictionsWithRandomAccessOrderBy() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(10)) timestamp(ts)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym\td\nVTJW\t0.1985581797355932\nVTJW\t0.21583224269349388\n",
"select sym, d from tb1 where d < 0.3 ORDER BY d",
null,
true, readOnlyExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym\td\nVTJW\t0.1985581797355932\nVTJW\t0.21583224269349388\nPEHN\t0.3288176907679504\n",
"select sym, d from tb1 where d < 0.5 ORDER BY d",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Maximum number of pages (2) breached"));
}
});
}
@Test
public void testMemoryRestrictionsWithoutRandomAccessOrderBy() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000001000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(3,3,3,20000) sym2," +
" rnd_double(2) d2," +
" timestamp_sequence(0, 1000000000) ts2" +
" from long_sequence(10)) timestamp(ts2)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 asof join tb2 where d1 < 0.3 ORDER BY d1",
null,
true, readOnlyExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\nPEHN\tRQQ\n",
"select sym1, sym2 from tb1 asof join tb2 where d1 < 0.9 ORDER BY d1",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Maximum number of pages (2) breached"));
}
});
}
@Test
public void testMemoryRestrictionsWithDistinct() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(20,4,4,20000) sym1," +
" rnd_symbol(20,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(20)) timestamp(ts)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nDEYY\tCXZO\nDEYY\tDSWU\nSXUX\tZSRY\n",
"select distinct sym1, sym2 from tb1 where d < 0.07",
null,
true, readOnlyExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nHYRX\tGPGW\nVTJW\tIBBT\nVTJW\tGPGW\n",
"select distinct sym1, sym2 from tb1",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithSampleByFillLinear() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_symbol(4,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(10000)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select ts, sum(d) from tb1 SAMPLE BY 5d FILL(linear)",
"ts",
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithSampleByFillNone() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(20,4,4,20000) sym1," +
" rnd_symbol(20,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(10000)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select sym1, sum(d) from tb1 SAMPLE BY 5d FILL(none)",
null,
false,
readOnlyExecutionContext
);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithSampleByFillPrev() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(20,4,4,20000) sym1," +
" rnd_symbol(4,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(10000)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select sym1, sum(d) from tb1 SAMPLE BY 5d FILL(prev)",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithSampleByFillValue() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(20,4,4,20000) sym1," +
" rnd_symbol(20,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 100000000000) ts" +
" from long_sequence(1000)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select sym1, sum(d) from tb1 SAMPLE BY 5d FILL(2.0)",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithSampleByFillNull() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(20,4,4,20000) sym1," +
" rnd_symbol(20,4,4,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(10000)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select sym1, sum(d) from tb1 SAMPLE BY 5d FILL(null)",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithLatestBy() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_symbol(4,4,4,20000) sym2," +
" rnd_long() d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(100)) timestamp(ts)", sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"TOO MUCH",
"select ts, d from tb1 LATEST BY d",
"ts",
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryResizesWithImplicitGroupBy() throws Exception {
SqlExecutionContext readOnlyExecutionContext = new SqlExecutionContextImpl(engine, 1)
.with(new CairoSecurityContextImpl(false),
bindVariableService,
null,
-1,
null);
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_symbol(2,2,2,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(1000)) timestamp(ts)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym2\td\nGZ\t0.006817672510656014\nGZ\t0.0014986299883373855\nGZ\t0.007868356216637062\nGZ\t0.007985454958725269\nGZ\t0.0011075361080621349\nRX\t4.016718301054212E-4\nRX\t0.006651203432318287\nRX\t6.503932953429992E-4\nRX\t0.0072398675350549\nRX\t0.0016532800623808575\n",
"select sym2, d from tb1 where d < 0.01 order by sym2",
null,
true, readOnlyExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"",
"select sym2, d from tb1 order by sym2",
null,
true, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Maximum number of pages (11) breached"));
}
});
}
@Test
public void testRenameTableDeniedOnNoWriteAccess() throws Exception {
assertMemoryLeak(() -> {
compiler.compile("create table balances(cust_id int, ccy symbol, balance double)", sqlExecutionContext);
try {
compiler.compile("rename table balances to newname", readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("permission denied"));
}
assertQuery("count\n0\n", "select count() from balances", null, false, true);
});
}
@Test
public void testMemoryRestrictionsWithUnion() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(3,3,3,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(20,3,3,20000) sym1," +
" rnd_double(2) d2," +
" timestamp_sequence(10000000000, 1000000000) ts2" +
" from long_sequence(100)) timestamp(ts2)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym1\nWCP\nICC\nUOJ\nFJG\nOZZ\nGHV\nWEK\nVDZ\nETJ\nUED\n",
"select sym1 from tb1 where d1 < 0.2 union select sym1 from tb2 where d2 < 0.1",
null,
false, readOnlyExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\td1\tts1\nVTJW\t0.1985581797355932\t1970-01-01T01:06:40.000000Z\nVTJW\t0.21583224269349388\t1970-01-01T01:40:00.000000Z\nRQQ\t0.5522494170511608\t1970-01-01T02:46:40.000000Z\n",
"select sym1 from tb1 where d1 < 0.2 union select sym1 from tb2",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testCircuitBreakerWithUnion() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(3,3,3,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(20,3,3,20000) sym1," +
" rnd_double(2) d2," +
" timestamp_sequence(10000000000, 1000000000) ts2" +
" from long_sequence(100)) timestamp(ts2)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym1\nWCP\nICC\nUOJ\nFJG\nOZZ\nGHV\nWEK\nVDZ\nETJ\nUED\n",
"select sym1 from tb1 where d1 < 0.2 union select sym1 from tb2 where d2 < 0.1",
null,
false, readOnlyExecutionContext);
Assert.assertTrue(nCheckInterruptedCalls.get() > 0);
try {
setMaxCircuitBreakerChecks(2);
assertQuery(
memoryRestrictedCompiler,
"sym1\nWCP\nICC\nUOJ\nFJG\nOZZ\nGHV\nWEK\nVDZ\nETJ\nUED\n",
"select sym1 from tb1 where d1 < 0.2 union select sym1 from tb2 where d2 < 0.1",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Interrupting SQL processing, max calls is 2"));
}
});
}
@Test
public void testCircuitBreakerTimeout() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tab as (select" +
" rnd_double(2) d" +
" from long_sequence(10000000))", sqlExecutionContext);
try {
setMaxCircuitBreakerChecks(Long.MAX_VALUE);
circuitBreakerTimeoutDeadline = MicrosecondClockImpl.INSTANCE.getTicks() + Timestamps.SECOND_MICROS;
TestUtils.printSql(
compiler,
readOnlyExecutionContext,
"tab order by d",
sink
);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Interrupting SQL processing"));
}
});
}
@Test
public void testTreeResizesWithImplicitGroupBy() throws Exception {
SqlExecutionContext readOnlyExecutionContext = new SqlExecutionContextImpl(engine, 1)
.with(new CairoSecurityContextImpl(false),
bindVariableService,
null,
-1,
null);
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_symbol(2,2,2,20000) sym2," +
" rnd_double(2) d," +
" timestamp_sequence(0, 1000000000) ts" +
" from long_sequence(2000)) timestamp(ts)", sqlExecutionContext);
assertQuery(
memoryRestrictedCompiler,
"sym2\tcount\nGZ\t1040\nRX\t960\n",
"select sym2, count() from tb1 order by sym2",
null,
true,
readOnlyExecutionContext,
true
);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tcount\nPEHN\t265\nCPSW\t231\nHYRX\t262\nVTJW\t242\n",
"select sym1, count() from tb1 order by sym1",
null,
readOnlyExecutionContext, true,
true,
true
);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("Maximum number of pages (2) breached"));
}
});
}
@Test
public void testMemoryRestrictionsWithInnerJoin() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(3,3,3,20000) sym2," +
" rnd_double(2) d2," +
" timestamp_sequence(0, 1000000000) ts2" +
" from long_sequence(10)) timestamp(ts2)", sqlExecutionContext);
assertQuery(
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 inner join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 inner join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithOuterJoin() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(3,3,3,20000) sym2," +
" rnd_double(2) d2," +
" timestamp_sequence(0, 1000000000) ts2" +
" from long_sequence(10)) timestamp(ts2)", sqlExecutionContext);
assertQuery(
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 outer join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 outer join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
});
}
@Test
public void testMemoryRestrictionsWithFullFatInnerJoin() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(3,3,3,20000) sym2," +
" rnd_double(2) d2," +
" timestamp_sequence(0, 1000000000) ts2" +
" from long_sequence(10)) timestamp(ts2)", sqlExecutionContext);
try {
compiler.setFullFatJoins(true);
assertQuery(
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 inner join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 inner join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
} finally {
compiler.setFullFatJoins(false);
}
});
}
@Test
public void testMemoryRstrictionsWithFullFatOuterJoin() throws Exception {
assertMemoryLeak(() -> {
sqlExecutionContext.getRandom().reset();
compiler.compile("create table tb1 as (select" +
" rnd_symbol(4,4,4,20000) sym1," +
" rnd_double(2) d1," +
" timestamp_sequence(0, 1000000000) ts1" +
" from long_sequence(10)) timestamp(ts1)", sqlExecutionContext);
compiler.compile("create table tb2 as (select" +
" rnd_symbol(3,3,3,20000) sym2," +
" rnd_double(2) d2," +
" timestamp_sequence(0, 1000000000) ts2" +
" from long_sequence(10)) timestamp(ts2)", sqlExecutionContext);
try {
compiler.setFullFatJoins(true);
assertQuery(
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 outer join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, sqlExecutionContext);
try {
assertQuery(
memoryRestrictedCompiler,
"sym1\tsym2\nVTJW\tFJG\nVTJW\tULO\n",
"select sym1, sym2 from tb1 outer join tb2 on tb2.ts2=tb1.ts1 where d1 < 0.3",
null,
false, readOnlyExecutionContext);
Assert.fail();
} catch (Exception ex) {
Assert.assertTrue(ex.toString().contains("limit of 2 resizes exceeded"));
}
} finally {
compiler.setFullFatJoins(false);
}
});
}
}
| 43.890845 | 293 | 0.51654 |
d641c30bfd3da986abae40aae65e32684ed9d2fd | 2,085 | /*
* 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.ingest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.script.TemplateScript;
import org.elasticsearch.script.mustache.MustacheScriptEngine;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
import java.util.Collections;
import java.util.Map;
import static org.elasticsearch.script.Script.DEFAULT_TEMPLATE_LANG;
public abstract class AbstractScriptTestCase extends ESTestCase {
protected ScriptService scriptService;
@Before
public void init() throws Exception {
MustacheScriptEngine engine = new MustacheScriptEngine();
Map<String, ScriptEngine> engines = Collections.singletonMap(engine.getType(), engine);
scriptService = new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS);
}
protected TemplateScript.Factory compile(String template) {
Script script = new Script(ScriptType.INLINE, DEFAULT_TEMPLATE_LANG, template, Collections.emptyMap());
return scriptService.compile(script, TemplateScript.CONTEXT);
}
}
| 38.611111 | 111 | 0.781775 |
7ca29e75dfecbf64af0fe079de81015c0ec5a24e | 2,273 | /**
* Copyright 2019 Pramati Prism, 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 io.hyscale.servicespec.commons.model.service;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Agent {
private String name;
private String image;
private Map<String,String> props;
private Secrets secrets;
private List<AgentVolume> volumes;
private String propsVolumePath;
private String secretsVolumePath;
private List<Port> ports;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<AgentVolume> getVolumes() {
return volumes;
}
public void setVolumes(List<AgentVolume> volumes) {
this.volumes = volumes;
}
public String getPropsVolumePath() {
return propsVolumePath;
}
public void setPropsVolumePath(String propsVolumePath) {
this.propsVolumePath = propsVolumePath;
}
public String getSecretsVolumePath() {
return secretsVolumePath;
}
public void setSecretsVolumePath(String secretsVolumePath) {
this.secretsVolumePath = secretsVolumePath;
}
public Secrets getSecrets() {
return secrets;
}
public void setSecrets(Secrets secrets) {
this.secrets = secrets;
}
public Map<String, String> getProps() {
return props;
}
public void setProps(Map<String, String> props) {
this.props = props;
}
public List<Port> getPorts() {
return ports;
}
public void setPorts(List<Port> ports) {
this.ports = ports;
}
}
| 22.50495 | 75 | 0.743511 |
65160e84ec3491fc731ddcd0000bd2210be4840e | 280 | package ex1;
/**
* Created by jomedjid on 14/11/2016.
*/
public interface MachineCafeState {
MachineCafeState give (int somme) throws MachineException;
MachineCafeState askCoffee() throws MachineException;
MachineCafeState askTea() throws MachineException;
}
| 21.538462 | 63 | 0.746429 |
31eb8551483e64d32dee65db587a3f87351c9b28 | 9,423 | /*
* Copyright (C) 2007 The Guava 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 com.google.common.eventbus;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.util.concurrent.MoreExecutors;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Dispatches events to listeners, and provides ways for listeners to register themselves.
*
* <p>The EventBus allows publish-subscribe-style communication between components without requiring
* the components to explicitly register with one another (and thus be aware of each other). It is
* designed exclusively to replace traditional Java in-process event distribution using explicit
* registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended
* for interprocess communication.
*
* <h2>Receiving Events</h2>
*
* <p>To receive events, an object should:
*
* <ol>
* <li>Expose a public method, known as the <i>event subscriber</i>, which accepts a single
* argument of the type of event desired;
* <li>Mark it with a {@link Subscribe} annotation;
* <li>Pass itself to an EventBus instance's {@link #register(Object)} method.
* </ol>
*
* <h2>Posting Events</h2>
*
* <p>To post an event, simply provide the event object to the {@link #post(Object)} method. The
* EventBus instance will determine the type of event and route it to all registered listeners.
*
* <p>Events are routed based on their type — an event will be delivered to any subscriber for
* any type to which the event is <em>assignable.</em> This includes implemented interfaces, all
* superclasses, and all interfaces implemented by superclasses.
*
* <p>When {@code post} is called, all registered subscribers for an event are run in sequence, so
* subscribers should be reasonably quick. If an event may trigger an extended process (such as a
* database load), spawn a thread or queue it for later. (For a convenient way to do this, use an
* {@link AsyncEventBus}.)
*
* <h2>Subscriber Methods</h2>
*
* <p>Event subscriber methods must accept only one argument: the event.
*
* <p>Subscribers should not, in general, throw. If they do, the EventBus will catch and log the
* exception. This is rarely the right solution for error handling and should not be relied upon; it
* is intended solely to help find problems during development.
*
* <p>The EventBus guarantees that it will not call a subscriber method from multiple threads
* simultaneously, unless the method explicitly allows it by bearing the {@link
* AllowConcurrentEvents} annotation. If this annotation is not present, subscriber methods need not
* worry about being reentrant, unless also called from outside the EventBus.
*
* <h2>Dead Events</h2>
*
* <p>If an event is posted, but no registered subscribers can accept it, it is considered "dead."
* To give the system a second chance to handle dead events, they are wrapped in an instance of
* {@link DeadEvent} and reposted.
*
* <p>If a subscriber for a supertype of all events (such as Object) is registered, no event will
* ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadEvent
* extends {@link Object}, a subscriber registered to receive any Object will never receive a
* DeadEvent.
*
* <p>This class is safe for concurrent use.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class EventBus {
private static final Logger logger = Logger.getLogger(EventBus.class.getName());
private final String identifier;
private final Executor executor;
private final SubscriberExceptionHandler exceptionHandler;
@SuppressWarnings("assignment.type.incompatible") // The SubscriberRegistry won't use the bus until it is full initialized
private final SubscriberRegistry subscribers = new SubscriberRegistry(this);
private final Dispatcher dispatcher;
/** Creates a new EventBus named "default". */
public EventBus() {
this("default");
}
/**
* Creates a new EventBus with the given {@code identifier}.
*
* @param identifier a brief name for this bus, for logging purposes. Should be a valid Java
* identifier.
*/
public EventBus(String identifier) {
this(
identifier,
MoreExecutors.directExecutor(),
Dispatcher.perThreadDispatchQueue(),
LoggingHandler.INSTANCE);
}
/**
* Creates a new EventBus with the given {@link SubscriberExceptionHandler}.
*
* @param exceptionHandler Handler for subscriber exceptions.
* @since 16.0
*/
public EventBus(SubscriberExceptionHandler exceptionHandler) {
this(
"default",
MoreExecutors.directExecutor(),
Dispatcher.perThreadDispatchQueue(),
exceptionHandler);
}
EventBus(
String identifier,
Executor executor,
Dispatcher dispatcher,
SubscriberExceptionHandler exceptionHandler) {
this.identifier = checkNotNull(identifier);
this.executor = checkNotNull(executor);
this.dispatcher = checkNotNull(dispatcher);
this.exceptionHandler = checkNotNull(exceptionHandler);
}
/**
* Returns the identifier for this event bus.
*
* @since 19.0
*/
public final String identifier() {
return identifier;
}
/** Returns the default executor this event bus uses for dispatching events to subscribers. */
final Executor executor() {
return executor;
}
/** Handles the given exception thrown by a subscriber with the given context. */
void handleSubscriberException(Throwable e, SubscriberExceptionContext context) {
checkNotNull(e);
checkNotNull(context);
try {
exceptionHandler.handleException(e, context);
} catch (Throwable e2) {
// if the handler threw an exception... well, just log it
logger.log(
Level.SEVERE,
String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, e),
e2);
}
}
/**
* Registers all subscriber methods on {@code object} to receive events.
*
* @param object object whose subscriber methods should be registered.
*/
public void register(Object object) {
subscribers.register(object);
}
/**
* Unregisters all subscriber methods on a registered {@code object}.
*
* @param object object whose subscriber methods should be unregistered.
* @throws IllegalArgumentException if the object was not previously registered.
*/
public void unregister(Object object) {
subscribers.unregister(object);
}
/**
* Posts an event to all registered subscribers. This method will return successfully after the
* event has been posted to all subscribers, and regardless of any exceptions thrown by
* subscribers.
*
* <p>If no subscribers have been subscribed for {@code event}'s class, and {@code event} is not
* already a {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted.
*
* @param event event to post.
*/
public void post(Object event) {
Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event);
if (eventSubscribers.hasNext()) {
dispatcher.dispatch(event, eventSubscribers);
} else if (!(event instanceof DeadEvent)) {
// the event had no subscribers and was not itself a DeadEvent
post(new DeadEvent(this, event));
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).addValue(identifier).toString();
}
/** Simple logging handler for subscriber exceptions. */
static final class LoggingHandler implements SubscriberExceptionHandler {
static final LoggingHandler INSTANCE = new LoggingHandler();
@Override
public void handleException(Throwable exception, SubscriberExceptionContext context) {
Logger logger = logger(context);
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE, message(context), exception);
}
}
private static Logger logger(SubscriberExceptionContext context) {
return Logger.getLogger(EventBus.class.getName() + "." + context.getEventBus().identifier());
}
private static String message(SubscriberExceptionContext context) {
Method method = context.getSubscriberMethod();
return "Exception thrown by subscriber method "
+ method.getName()
+ '('
+ method.getParameterTypes()[0].getName()
+ ')'
+ " on subscriber "
+ context.getSubscriber()
+ " when dispatching event: "
+ context.getEvent();
}
}
}
| 36.952941 | 124 | 0.715483 |
0039169395250aa13c4d76d3c5d42d775a2020c1 | 1,850 | package org.jrichardsz.tools.stressify.model;
import java.util.ArrayList;
public class Stress {
private String url;
private String method;
private ArrayList<HttpHeader> httpHeaders;
private String body;
private String assertScript;
private String reportFolderPath;
private String reportName;
private String csvDataPath;
private String mode;
private int threadNumber;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public ArrayList<HttpHeader> getHttpHeaders() {
return httpHeaders;
}
public void setHttpHeaders(ArrayList<HttpHeader> httpHeaders) {
this.httpHeaders = httpHeaders;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAssertScript() {
return assertScript;
}
public void setAssertScript(String assertScript) {
this.assertScript = assertScript;
}
public String getReportFolderPath() {
return reportFolderPath;
}
public void setReportFolderPath(String reportFolderPath) {
this.reportFolderPath = reportFolderPath;
}
public String getReportName() {
return reportName;
}
public void setReportName(String reportName) {
this.reportName = reportName;
}
public String getCsvDataPath() {
return csvDataPath;
}
public void setCsvDataPath(String csvDataPath) {
this.csvDataPath = csvDataPath;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public int getThreadNumber() {
return threadNumber;
}
public void setThreadNumber(int threadNumber) {
this.threadNumber = threadNumber;
}
}
| 18.877551 | 65 | 0.703784 |
7bb3f8420243199db9822bf5faf67a990b8cde48 | 3,551 | package br.com.alessanderleite.app.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component
@Entity
@Table(name = "DATA")
public class Data {
@Id
@Column(name = "ID", unique = true, nullable = false, precision = 38, scale = 0)
@SequenceGenerator(name = "ID_DATA_SEQ", sequenceName = "DATA_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_DATA_SEQ")
private Integer id;
private String ipv4;
private String continent_name;
private String country_name;
private String subdivision_1_name;
private String subdivision_2_name;
private String city_name;
private String latitude;
private String longitude;
@OneToMany(mappedBy = "data", fetch = FetchType.LAZY)
private Set<Localidade> localidades = new HashSet<Localidade>(0);
public Data() {}
public Data(Integer id, String ipv4, String continent_name, String country_name, String subdivision_1_name,
String subdivision_2_name, String city_name, String latitude, String longitude,
Set<Localidade> localidades) {
this.id = id;
this.ipv4 = ipv4;
this.continent_name = continent_name;
this.country_name = country_name;
this.subdivision_1_name = subdivision_1_name;
this.subdivision_2_name = subdivision_2_name;
this.city_name = city_name;
this.latitude = latitude;
this.longitude = longitude;
this.localidades = localidades;
}
public Data(String ipv4, String continent_name, String country_name, String city_name, String latitude,
String longitude) {
this.ipv4 = ipv4;
this.continent_name = continent_name;
this.country_name = country_name;
this.city_name = city_name;
this.latitude = latitude;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIpv4() {
return ipv4;
}
public void setIpv4(String ipv4) {
this.ipv4 = ipv4;
}
public String getContinent_name() {
return continent_name;
}
public void setContinent_name(String continent_name) {
this.continent_name = continent_name;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
public String getSubdivision_1_name() {
return subdivision_1_name;
}
public void setSubdivision_1_name(String subdivision_1_name) {
this.subdivision_1_name = subdivision_1_name;
}
public String getSubdivision_2_name() {
return subdivision_2_name;
}
public void setSubdivision_2_name(String subdivision_2_name) {
this.subdivision_2_name = subdivision_2_name;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public Set<Localidade> getLocalidades() {
return localidades;
}
public void setLocalidades(Set<Localidade> localidades) {
this.localidades = localidades;
}
}
| 22.909677 | 108 | 0.75866 |
d4ea38cb1c20dc47a69cd69f3905f08d072515c9 | 973 | package dev.xdark.ssvm.execution.asm;
import dev.xdark.ssvm.execution.ExecutionContext;
import dev.xdark.ssvm.execution.InstructionProcessor;
import dev.xdark.ssvm.execution.Result;
import dev.xdark.ssvm.execution.Stack;
import dev.xdark.ssvm.util.MathUtil;
import org.objectweb.asm.tree.AbstractInsnNode;
/**
* Compares two doubles.
* Pushes provided value if one of the values is NaN.
*
* @author xDark
*/
public final class DoubleCompareProcessor implements InstructionProcessor<AbstractInsnNode> {
private final int nan;
/**
* @param nan Value to be pushed to the stack
* if one of the doubles is {@code NaN}.
*/
public DoubleCompareProcessor(int nan) {
this.nan = nan;
}
@Override
public Result execute(AbstractInsnNode insn, ExecutionContext ctx) {
Stack stack = ctx.getStack();
double v2 = stack.popDouble();
double v1 = stack.popDouble();
stack.pushInt(MathUtil.compareDouble(v1, v2, nan));
return Result.CONTINUE;
}
}
| 26.297297 | 93 | 0.742035 |
763d7aecb8c03a60a0b419b5a829eff02193c2da | 422 | package com.packtpub.micronaut.config;
import io.micronaut.context.annotation.Value;
public class MongoConfiguration {
@Value("${mongodb.databaseName}")
private String databaseName;
@Value("${mongodb.collectionName}")
private String collectionName;
public String getDatabaseName() {
return databaseName;
}
public String getCollectionName() {
return collectionName;
}
}
| 21.1 | 45 | 0.703791 |
81a83f58498aa9513fe0db0080b1ab11f5fa6fdf | 3,696 | package be.rubus.angularwidgets.demo.widgets;
import be.rubus.web.testing.annotation.Grafaces;
import be.rubus.web.testing.widget.ButtonWidget;
import be.rubus.web.testing.widget.extension.angularwidgets.PuiGrowl;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.support.FindBy;
import static org.junit.Assert.assertEquals;
/**
*
*/
@RunWith(Arquillian.class)
public class GrowlTest extends AbstractWidgetTest {
@Grafaces
private PuiGrowl puiGrowl;
// For the default demo
@FindBy(id = "infoBtn")
private ButtonWidget infoButton;
@FindBy(id = "errorBtn")
private ButtonWidget errorButton;
@FindBy(id = "warnBtn")
private ButtonWidget warnButton;
@Override
protected int getWidgetIdx() {
return 5;
}
@Test
@RunAsClient
public void testOverview() {
testWidgetOverviewPage("puiGrowl", "puiGrowl", 3);
}
@Test
@RunAsClient
public void testDefault() {
showExample(1);
assertEquals("Default integration", contentArea.getExampleName());
assertEquals(VERSION_INITIAL, contentArea.getNewInVersionNumber());
assertEquals(0, puiGrowl.getNumberOfMessages());
infoButton.click();
assertEquals(1, puiGrowl.getNumberOfMessages());
assertEquals("Info message title", puiGrowl.getMessageTitle(0));
assertEquals("Info detail message", puiGrowl.getMessageText(0));
assertEquals(PuiGrowl.Severity.INFO, puiGrowl.getMessageSeverity(0));
puiGrowl.closeMessage(0);
waitForScreenUpdate(1000);
assertEquals(0, puiGrowl.getNumberOfMessages());
}
@Test
@RunAsClient
public void testDefaultWaitForClose() {
showExample(1);
assertEquals("Default integration", contentArea.getExampleName());
assertEquals(VERSION_INITIAL, contentArea.getNewInVersionNumber());
infoButton.click();
assertEquals(1, puiGrowl.getNumberOfMessages());
waitForScreenUpdate(3500);
assertEquals(0, puiGrowl.getNumberOfMessages());
}
@Test
@RunAsClient
public void testDefaultOtherSeverities() {
showExample(1);
assertEquals("Default integration", contentArea.getExampleName());
assertEquals(VERSION_INITIAL, contentArea.getNewInVersionNumber());
assertEquals(0, puiGrowl.getNumberOfMessages());
errorButton.click();
assertEquals(1, puiGrowl.getNumberOfMessages());
assertEquals("Error message title", puiGrowl.getMessageTitle(0));
assertEquals("Error detail message", puiGrowl.getMessageText(0));
assertEquals(PuiGrowl.Severity.ERROR, puiGrowl.getMessageSeverity(0));
warnButton.click();
assertEquals(2, puiGrowl.getNumberOfMessages());
assertEquals("Warn message title", puiGrowl.getMessageTitle(1));
assertEquals("Warn detail message", puiGrowl.getMessageText(1));
assertEquals(PuiGrowl.Severity.WARN, puiGrowl.getMessageSeverity(1));
}
@Test
@RunAsClient
public void testSticky() {
showExample(2);
assertEquals("Sticky message example", contentArea.getExampleName());
assertEquals(VERSION_INITIAL, contentArea.getNewInVersionNumber());
infoButton.click();
assertEquals(1, puiGrowl.getNumberOfMessages());
waitForScreenUpdate(3500);
assertEquals(1, puiGrowl.getNumberOfMessages());
puiGrowl.closeMessage(0);
waitForScreenUpdate(1000);
assertEquals(0, puiGrowl.getNumberOfMessages());
}
}
| 29.333333 | 78 | 0.695887 |
d832e7ba96dd9006f47155c9727dd8902925ce2b | 1,275 | package com.ddlab.rnd.cyclicbarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class TestCyclicBarrier1 {
public static void main(String[] args) throws Exception {
// Thread name has no impact in case of CyclicBarrier Runnable task.
String aadharResult = null;
String passportResult = null;
String panNoResult = null;
Thread endTask = new Thread(new EndTask(3, aadharResult, passportResult, panNoResult));
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, endTask);
// You can also write like this
// CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
Thread aadharThread =
new Thread(new AadharValidation(cyclicBarrier, 7, aadharResult), "Aadhar");
Thread passportThread =
new Thread(new PassportValidation(cyclicBarrier, 5, passportResult), "Passport");
Thread panNoThread = new Thread(new PanNoValidation(cyclicBarrier, 3, panNoResult), "PanNo");
aadharThread.start();
passportThread.start();
panNoThread.start();
aadharThread.join();
passportThread.join();
panNoThread.join();
System.out.println("All threads completed the tasks");
}
}
| 36.428571 | 98 | 0.712941 |
55dfad895760d92aec5dbc999c138b435f4f18a8 | 453 | package com.newrelic.app;
import com.newrelic.shared.OpenTelemetryConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
// Configure OpenTelemetry as early as possible
OpenTelemetryConfig.configureGlobal("otel-app");
SpringApplication.run(Application.class, args);
}
}
| 28.3125 | 68 | 0.801325 |
cb662b411f0233968cb2721f0cad0b97d12e3c93 | 85 | package socialnetwork.domain.posts;
public enum PostLikeType {
Berry, Unberry
}
| 14.166667 | 35 | 0.764706 |
f446cc3656b4a05b45e36a1b73838d82a86c47f2 | 76,285 | /* @(#)QuickTimeOutputStream.java
* Copyright © 2011 Werner Randelshofer, Switzerland.
* You may only use this software in accordance with the license terms.
*/
package ru.sbtqa.monte.media.quicktime;
import java.awt.image.ColorModel;
import ru.sbtqa.monte.media.Format;
import ru.sbtqa.monte.media.io.ImageOutputStreamAdapter;
import ru.sbtqa.monte.media.math.Rational;
import java.awt.image.IndexColorModel;
import java.io.*;
import java.nio.ByteOrder;
import java.util.Date;
import java.util.zip.DeflaterOutputStream;
import javax.imageio.stream.*;
import static java.lang.Math.*;
import static ru.sbtqa.monte.media.VideoFormatKeys.*;
import static ru.sbtqa.monte.media.AudioFormatKeys.*;
import ru.sbtqa.monte.media.io.IOStreams;
/**
* This class provides low-level support for writing already encoded audio and
* video samples into a QuickTime file.
*
* @author Werner Randelshofer
* @version 1.0 2011-08-19 Created.
*/
public class QuickTimeOutputStream extends AbstractQuickTimeStream {
/**
* Creates a new instance.
*
* @param file the output file
*/
public QuickTimeOutputStream(File file) throws IOException {
if (file.exists()) {
file.delete();
}
this.out = new FileImageOutputStream(file);
this.streamOffset = 0;
init();
}
/**
* Creates a new instance.
*
* @param out the output stream.
*/
public QuickTimeOutputStream(ImageOutputStream out) throws IOException {
this.out = out;
this.streamOffset = out.getStreamPosition();
init();
}
private void init() {
creationTime = new Date();
modificationTime = new Date();
}
/**
* Sets the time scale for this movie, that is, the number of time units
* that pass per second in its time coordinate system. The default value
* is 600.
*
* @param timeScale TODO
*/
public void setMovieTimeScale(long timeScale) {
if (timeScale < 1 || timeScale > (2L << 32)) {
throw new IllegalArgumentException("timeScale must be between 1 and 2^32:" + timeScale);
}
this.movieTimeScale = timeScale;
}
/**
* Returns the time scale of the movie.
*
* @return time scale
* @see #setMovieTimeScale(long)
*/
public long getMovieTimeScale() {
return movieTimeScale;
}
/**
* Returns the time scale of the media in a track.
*
* @param track Track index.
* @return time scale
* @see #setMovieTimeScale(long)
*/
public long getMediaTimeScale(int track) {
return tracks.get(track).mediaTimeScale;
}
/**
* Returns the media duration of a track in the media's time scale.
*
* @param track Track index.
* @return media duration
*/
public long getMediaDuration(int track) {
return tracks.get(track).mediaDuration;
}
/**
* Returns the track duration in the movie's time scale without taking the
* edit list into account. The returned value is the media duration of
* the track in the movies's time scale.
*
* @param track Track index.
* @return unedited track duration
*/
public long getUneditedTrackDuration(int track) {
Track t = tracks.get(track);
return t.mediaDuration * t.mediaTimeScale / movieTimeScale;
}
/**
* Returns the track duration in the movie's time scale. If the track
* has an edit-list, the track duration is the sum of all edit durations.
* If the track does not have an edit-list, then this method returns the
* media duration of the track in the movie's time scale.
*
* @param track Track index.
* @return track duration
*/
public long getTrackDuration(int track) {
return tracks.get(track).getTrackDuration(movieTimeScale);
}
/**
* Returns the total duration of the movie in the movie's time scale.
*
* @return media duration
*/
public long getMovieDuration() {
long duration = 0;
for (Track t : tracks) {
duration = Math.max(duration, t.getTrackDuration(movieTimeScale));
}
return duration;
}
/**
* Sets the color table for videos with indexed color models.
*
* @param track The track number.
* @param icm IndexColorModel. Specify null to use the standard Macintosh
* color table.
*/
public void setVideoColorTable(int track, ColorModel icm) {
if (icm instanceof IndexColorModel) {
VideoTrack t = (VideoTrack) tracks.get(track);
t.videoColorTable = (IndexColorModel) icm;
}
}
/**
* Gets the preferred color table for displaying the movie on devices that
* support only 256 colors.
*
* @param track The track number.
* @return The color table or null, if the video uses the standard Macintosh
* color table.
*/
public IndexColorModel getVideoColorTable(int track) {
VideoTrack t = (VideoTrack) tracks.get(track);
return t.videoColorTable;
}
/**
* Sets the edit list for the specified track. In the absence of an edit
* list, the presentation of the track starts immediately. An empty edit is
* used to offset the start time of a track.
*
* @throws IllegalArgumentException If the edit list ends with an empty
* edit.
*/
public void setEditList(int track, Edit[] editList) {
if (editList != null && editList.length > 0 && editList[editList.length - 1].mediaTime == -1) {
throw new IllegalArgumentException("Edit list must not end with empty edit.");
}
tracks.get(track).editList = editList;
}
/**
* Adds a video track.
*
* @param compressionType The QuickTime "image compression format"
* 4-Character code. A list of supported 4-Character codes is given in qtff,
* table 3-1, page 96.
* @param compressorName The QuickTime compressor name. Can be up to 32
* characters long.
* @param timeScale The media time scale between 1 and 2^32.
* @param width The width of a video frame.
* @param height The height of a video frame.
* @param depth The number of bits per pixel.
* @param syncInterval Interval for sync-samples. 0=automatic. 1=all frames
* are keyframes. Values larger than 1 specify that for every n-th frame is
* a keyframe. Apple's QuickTime will not work properly if there is not at
* least one keyframe every second.
*
* @return Returns the track index.
*
* @throws IllegalArgumentException if {@code width} or {@code height} is
* smaller than 1, if the length of {@code compressionType} is not equal to
* 4, if the length of the {@code compressorName} is not between 1 and 32,
* if the tiimeScale is not between 1 and 2^32.
*/
public int addVideoTrack(String compressionType, String compressorName, long timeScale, int width, int height, int depth, int syncInterval) throws IOException {
ensureStarted();
if (compressionType == null || compressionType.length() != 4) {
throw new IllegalArgumentException("compressionType must be 4 characters long:" + compressionType);
}
if (compressorName == null || compressorName.length() < 1 || compressorName.length() > 32) {
throw new IllegalArgumentException("compressorName must be between 1 and 32 characters long:" + (compressorName == null ? "null" : "\"" + compressorName + "\""));
}
if (timeScale < 1 || timeScale > (2L << 32)) {
throw new IllegalArgumentException("timeScale must be between 1 and 2^32:" + timeScale);
}
if (width < 1 || height < 1) {
throw new IllegalArgumentException("Width and height must be greater than 0, width:" + width + " height:" + height);
}
VideoTrack t = new VideoTrack();
t.mediaCompressionType = compressionType;
t.mediaCompressorName = compressorName;
t.mediaTimeScale = timeScale;
t.width = width;
t.height = height;
t.videoDepth = depth;
t.syncInterval = syncInterval;
t.format = new Format(
MediaTypeKey, MediaType.VIDEO,
MimeTypeKey, MIME_QUICKTIME,
EncodingKey, compressionType,
CompressorNameKey, compressorName,
DataClassKey, byte[].class,
WidthKey, width, HeightKey, height, DepthKey, depth,
FrameRateKey, new Rational(timeScale, 1));
tracks.add(t);
return tracks.size() - 1;
}
/**
* Adds an audio track.
*
* @param compressionType The QuickTime 4-character code. A list of
* supported 4-Character codes is given in qtff, table 3-7, page 113.
* @param timeScale The media time scale between 1 and 2^32.
* @param sampleRate The sample rate. The integer portion must match the
* {@code timeScale}.
* @param numberOfChannels The number of channels: 1 for mono, 2 for stereo.
* @param sampleSizeInBits The number of bits in a sample: 8 or 16.
* @param isCompressed Whether the sound is compressed.
* @param frameDuration The frame duration, expressed in the media’s
* timescale, where the timescale is equal to the sample rate. For
* uncompressed formats, this field is always 1.
* @param frameSize For uncompressed audio, the number of bytes in a sample
* for a single channel (sampleSize divided by 8). For compressed audio, the
* number of bytes in a frame.
*
* @throws IllegalArgumentException if the audioFormat is not 4 characters
* long, if the time scale is not between 1 and 2^32, if the integer portion
* of the sampleRate is not equal to the timeScale, if numberOfChannels is
* not 1 or 2.
* @return Returns the track index.
*/
public int addAudioTrack(String compressionType, //
long timeScale, double sampleRate, //
int numberOfChannels, int sampleSizeInBits, //
boolean isCompressed, //
int frameDuration, int frameSize, boolean signed, ByteOrder byteOrder) throws IOException {
ensureStarted();
if (compressionType == null || compressionType.length() != 4) {
throw new IllegalArgumentException("audioFormat must be 4 characters long:" + compressionType);
}
if (timeScale < 1 || timeScale > (2L << 32)) {
throw new IllegalArgumentException("timeScale must be between 1 and 2^32:" + timeScale);
}
if (timeScale != (int) Math.floor(sampleRate)) {
throw new IllegalArgumentException("timeScale: " + timeScale + " must match integer portion of sampleRate: " + sampleRate);
}
if (numberOfChannels != 1 && numberOfChannels != 2) {
throw new IllegalArgumentException("numberOfChannels must be 1 or 2: " + numberOfChannels);
}
if (sampleSizeInBits != 8 && sampleSizeInBits != 16) {
throw new IllegalArgumentException("sampleSize must be 8 or 16: " + numberOfChannels);
}
AudioTrack t = new AudioTrack();
t.mediaCompressionType = compressionType;
t.mediaTimeScale = timeScale;
t.soundSampleRate = sampleRate;
t.soundCompressionId = isCompressed ? -2 : -1;
t.soundNumberOfChannels = numberOfChannels;
t.soundSampleSize = sampleSizeInBits;
t.soundSamplesPerPacket = frameDuration;
if (isCompressed) {
t.soundBytesPerPacket = frameSize;
t.soundBytesPerFrame = frameSize * numberOfChannels;
} else {
t.soundBytesPerPacket = frameSize / numberOfChannels;
t.soundBytesPerFrame = frameSize;
}
t.soundBytesPerSample = sampleSizeInBits / 8;
t.format = new Format(
MediaTypeKey, MediaType.AUDIO,
MimeTypeKey, MIME_QUICKTIME,
EncodingKey, compressionType,
SampleRateKey, Rational.valueOf(sampleRate),
SampleSizeInBitsKey, sampleSizeInBits,
ChannelsKey, numberOfChannels,
FrameSizeKey, frameSize,
SampleRateKey, Rational.valueOf(sampleRate),
SignedKey, signed,
ByteOrderKey, byteOrder);
tracks.add(t);
return tracks.size() - 1;
}
/**
* Sets the compression quality of a track. A value of 0 stands for
* "high compression is important" a value of 1 for "high image quality is
* important". Changing this value affects the encoding of video frames
* which are subsequently written into the track. Frames which have already
* been written are not changed. This value has no effect on videos
* encoded with lossless encoders such as the PNG format. The default
* value is 0.97.
*
* @param newValue TODO
*/
public void setCompressionQuality(int track, float newValue) {
VideoTrack vt = (VideoTrack) tracks.get(track);
vt.videoQuality = newValue;
}
/**
* Returns the compression quality of a track.
*
* @return compression quality
*/
public float getCompressionQuality(int track) {
return ((VideoTrack) tracks.get(track)).videoQuality;
}
/**
* Sets the sync interval for the specified video track.
*
* @param track The track number.
* @param i Interval between sync samples (keyframes). 0 = automatic. 1 =
* write all samples as sync samples. n = sync every n-th sample.
*/
public void setSyncInterval(int track, int i) {
((VideoTrack) tracks.get(track)).syncInterval = i;
}
/**
* Gets the sync interval from the specified video track.
*/
public int getSyncInterval(int track) {
return ((VideoTrack) tracks.get(track)).syncInterval;
}
/**
* Sets the creation time of the movie.
*/
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
/**
* Gets the creation time of the movie.
*/
public Date getCreationTime() {
return creationTime;
}
/**
* Sets the modification time of the movie.
*/
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
/**
* Gets the modification time of the movie.
*/
public Date getModificationTime() {
return modificationTime;
}
/**
* Gets the preferred rate at which to play this movie. A value of 1.0
* indicates normal rate.
*/
public double getPreferredRate() {
return preferredRate;
}
/**
* Sets the preferred rate at which to play this movie. A value of 1.0
* indicates normal rate.
*/
public void setPreferredRate(double preferredRate) {
this.preferredRate = preferredRate;
}
/**
* Gets the preferred volume of this movie’s sound. A value of 1.0 indicates
* full volume.
*/
public double getPreferredVolume() {
return preferredVolume;
}
/**
* Sets the preferred volume of this movie’s sound. A value of 1.0 indicates
* full volume.
*/
public void setPreferredVolume(double preferredVolume) {
this.preferredVolume = preferredVolume;
}
/**
* Gets the time value for current time position within the movie.
*/
public long getCurrentTime() {
return currentTime;
}
/**
* Sets the time value for current time position within the movie.
*/
public void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
/**
* Gets the time value of the time of the movie poster.
*/
public long getPosterTime() {
return posterTime;
}
/**
* Sets the time value of the time of the movie poster.
*/
public void setPosterTime(long posterTime) {
this.posterTime = posterTime;
}
/**
* Gets the duration of the movie preview in movie time scale units.
*/
public long getPreviewDuration() {
return previewDuration;
}
/**
* Gets the duration of the movie preview in movie time scale units.
*/
public void setPreviewDuration(long previewDuration) {
this.previewDuration = previewDuration;
}
/**
* Gets the time value in the movie at which the preview begins.
*/
public long getPreviewTime() {
return previewTime;
}
/**
* The time value in the movie at which the preview begins.
*/
public void setPreviewTime(long previewTime) {
this.previewTime = previewTime;
}
/**
* The duration of the current selection in movie time scale units.
*/
public long getSelectionDuration() {
return selectionDuration;
}
/**
* The duration of the current selection in movie time scale units.
*/
public void setSelectionDuration(long selectionDuration) {
this.selectionDuration = selectionDuration;
}
/**
* The time value for the start time of the current selection.
*/
public long getSelectionTime() {
return selectionTime;
}
/**
* The time value for the start time of the current selection.
*/
public void setSelectionTime(long selectionTime) {
this.selectionTime = selectionTime;
}
/**
* Sets the transformation matrix of the entire movie.
*
* {a, b, u,
* c, d, v,
* tx,ty,w} // X- and Y-Translation
*
* [ a b u
* [x y 1] * c d v = [x' y' 1]
* tx ty w ]
*
*
* @param matrix The transformation matrix.
*/
public void setMovieTransformationMatrix(double[] matrix) {
if (matrix.length != 9) {
throw new IllegalArgumentException("matrix must have 9 elements, matrix.length=" + matrix.length);
}
System.arraycopy(matrix, 0, movieMatrix, 0, 9);
}
/**
* Gets the transformation matrix of the entire movie.
*
* @return The transformation matrix.
*/
public double[] getMovieTransformationMatrix() {
return movieMatrix.clone();
}
/**
* Sets the transformation matrix of the specified track.
*
* {a, b, u,
* c, d, v,
* tx,ty,w} // X- and Y-Translation
*
* [ a b u
* [x y 1] * c d v = [x' y' 1]
* tx ty w ]
*
*
* @param track The track number.
* @param matrix The transformation matrix.
*/
public void setTransformationMatrix(int track, double[] matrix) {
if (matrix.length != 9) {
throw new IllegalArgumentException("matrix must have 9 elements, matrix.length=" + matrix.length);
}
System.arraycopy(matrix, 0, tracks.get(track).matrix, 0, 9);
}
/**
* Gets the transformation matrix of the specified track.
*
* @param track The track number.
* @return The transformation matrix.
*/
public double[] getTransformationMatrix(int track) {
return tracks.get(track).matrix.clone();
}
/**
* Sets the state of the QuickTimeWriter to started. If the state is
* changed by this method, the prolog is written.
*/
protected void ensureStarted() throws IOException {
ensureOpen();
if (state == States.FINISHED) {
throw new IOException("Can not write into finished movie.");
}
if (state != States.STARTED) {
writeProlog();
mdatAtom = new WideDataAtom("mdat");
state = States.STARTED;
}
}
/**
* Writes an already encoded sample from a file into a track. This
* method does not inspect the contents of the samples. The contents has to
* match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param file The file which holds the encoded data sample.
* @param duration The duration of the sample in media time scale units.
* @param isSync whether the sample is a sync sample (key frame).
*
* @throws IndexOutofBoundsException if the track index is out of bounds.
* @throws IllegalArgumentException if the track does not support video, if
* the duration is less than 1, or if the dimension of the frame does not
* match the dimension of the video.
* @throws IOException if writing the sample data failed.
*/
public void writeSample(int track, File file, long duration, boolean isSync) throws IOException {
ensureStarted();
FileInputStream in = null;
try {
in = new FileInputStream(file);
writeSample(track, in, duration, isSync);
} finally {
if (in != null) {
in.close();
}
}
}
/**
* Writes an already encoded sample from an input stream into a track.
* This method does not inspect the contents of the samples. The contents
* has to match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param in The input stream which holds the encoded sample data.
* @param duration The duration of the video frame in media time scale
* units.
* @param isSync Whether the sample is a sync sample (keyframe).
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the sample data failed.
*/
public void writeSample(int track, InputStream in, long duration, boolean isSync) throws IOException {
ensureStarted();
if (duration <= 0) {
throw new IllegalArgumentException("duration must be greater 0");
}
Track t = tracks.get(track); // throws index out of bounds exception if illegal track index
ensureOpen();
ensureStarted();
long offset = getRelativeStreamPosition();
OutputStream mdatOut = mdatAtom.getOutputStream();
IOStreams.copy(in, mdatOut);
long length = getRelativeStreamPosition() - offset;
t.addSample(new Sample(duration, offset, length), 1, isSync);
}
/**
* Writes an already encoded sample from a byte array into a track. This
* method does not inspect the contents of the samples. The contents has to
* match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param data The encoded sample data.
* @param duration The duration of the sample in media time scale units.
* @param isSync Whether the sample is a sync sample.
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the sample data failed.
*/
public void writeSample(int track, byte[] data, long duration, boolean isSync) throws IOException {
writeSample(track, data, 0, data.length, duration, isSync);
}
/**
* Writes an already encoded sample from a byte array into a track. This
* method does not inspect the contents of the samples. The contents has to
* match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param data The encoded sample data.
* @param off The start offset in the data.
* @param len The number of bytes to write.
* @param duration The duration of the sample in media time scale units.
* @param isSync Whether the sample is a sync sample (keyframe).
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the sample data failed.
*/
public void writeSample(int track, byte[] data, int off, int len, long duration, boolean isSync) throws IOException {
ensureStarted();
if (duration <= 0) {
throw new IllegalArgumentException("duration must be greater 0");
}
Track t = tracks.get(track); // throws index out of bounds exception if illegal track index
ensureOpen();
ensureStarted();
long offset = getRelativeStreamPosition();
OutputStream mdatOut = mdatAtom.getOutputStream();
mdatOut.write(data, off, len);
t.addSample(new Sample(duration, offset, len), 1, isSync);
}
/**
* Writes multiple sync samples from a byte array into a track. This
* method does not inspect the contents of the samples. The contents has to
* match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param sampleCount The number of samples.
* @param data The encoded sample data. The length of data must be dividable
* by sampleCount.
* @param sampleDuration The duration of a sample. All samples must have the
* same duration.
*
* @throws IllegalArgumentException if {@code sampleDuration} is less than 1
* or if the length of {@code data} is not dividable by {@code sampleCount}.
* @throws IOException if writing the chunk failed.
*/
public void writeSamples(int track, int sampleCount, byte[] data, long sampleDuration, boolean isSync) throws IOException {
writeSamples(track, sampleCount, data, 0, data.length, sampleDuration, isSync);
}
/**
* Writes multiple sync samples from a byte array into a track. This
* method does not inspect the contents of the samples. The contents has to
* match the format and dimensions of the media in this track.
*
* @param track The track index.
* @param sampleCount The number of samples.
* @param data The encoded sample data.
* @param off The start offset in the data.
* @param len The number of bytes to write. Must be dividable by
* sampleCount.
* @param sampleDuration The duration of a sample. All samples must have the
* same duration.
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the sample data failed.
*/
public void writeSamples(int track, int sampleCount, byte[] data, int off, int len, long sampleDuration) throws IOException {
writeSamples(track, sampleCount, data, off, len, sampleDuration, true);
}
/**
* Writes multiple samples from a byte array into a track. This method
* does not inspect the contents of the data. The contents has to match the
* format and dimensions of the media in this track.
*
* @param track The track index.
* @param sampleCount The number of samples.
* @param data The encoded sample data.
* @param off The start offset in the data.
* @param len The number of bytes to write. Must be dividable by
* sampleCount.
* @param sampleDuration The duration of a sample. All samples must have the
* same duration.
* @param isSync Whether the samples are sync samples. All samples must
* either be sync samples or non-sync samples.
*
* @throws IllegalArgumentException if the duration is less than 1.
* @throws IOException if writing the sample data failed.
*/
public void writeSamples(int track, int sampleCount, byte[] data, int off, int len, long sampleDuration, boolean isSync) throws IOException {
ensureStarted();
if (sampleDuration <= 0) {
throw new IllegalArgumentException("sampleDuration must be greater 0, sampleDuration=" + sampleDuration + " track=" + track);
}
if (sampleCount <= 0) {
throw new IllegalArgumentException("sampleCount must be greater 0, sampleCount=" + sampleCount + " track=" + track);
}
if (len % sampleCount != 0) {
throw new IllegalArgumentException("len must be divisable by sampleCount len=" + len + " sampleCount=" + sampleCount + " track=" + track);
}
Track t = tracks.get(track); // throws index out of bounds exception if illegal track index
ensureOpen();
ensureStarted();
long offset = getRelativeStreamPosition();
OutputStream mdatOut = mdatAtom.getOutputStream();
mdatOut.write(data, off, len);
int sampleLength = len / sampleCount;
Sample first = new Sample(sampleDuration, offset, sampleLength);
Sample last = new Sample(sampleDuration, offset + sampleLength * (sampleCount - 1), sampleLength);
t.addChunk(new Chunk(first, last, sampleCount, 1), isSync);
}
/**
* Returns true if the limit for media samples has been reached. If this
* limit is reached, no more samples should be added to the movie.
* QuickTime files can be up to 64 TB long, but there are other values that
* may overflow before this size is reached. This method returns true when
* the files size exceeds 2^60 or when the media duration value of a track
* exceeds 2^61.
*/
public boolean isDataLimitReached() {
try {
long maxMediaDuration = 0;
for (Track t : tracks) {
maxMediaDuration = max(t.mediaDuration, maxMediaDuration);
}
return getRelativeStreamPosition() > (1L << 61) //
|| maxMediaDuration > 1L << 61;
} catch (IOException ex) {
return true;
}
}
/**
* Closes the movie file as well as the stream being filtered.
*
* @exception IOException if an I/O error has occurred
*/
public void close() throws IOException {
try {
if (state == States.STARTED) {
finish();
}
} finally {
if (state != States.CLOSED) {
out.close();
state = States.CLOSED;
}
}
}
/**
* Finishes writing the contents of the QuickTime output stream without
* closing the underlying stream. Use this method when applying multiple
* filters in succession to the same output stream.
*
* @exception IllegalStateException if the dimension of the video track has
* not been specified or determined yet.
* @exception IOException if an I/O exception has occurred
*/
public void finish() throws IOException {
ensureOpen();
if (state != States.FINISHED) {
for (int i = 0, n = tracks.size(); i < n; i++) {
}
mdatAtom.finish();
writeEpilog();
state = States.FINISHED;
/*
for (int i = 0, n = tracks.size(); i < n; i++) {
if (tracks.get(i) instanceof VideoTrack) {
VideoTrack t = (VideoTrack) tracks.get(i);
t.videoWidth = t.videoHeight = -1;
}
}*/
}
}
/**
* Check to make sure that this stream has not been closed
*/
protected void ensureOpen() throws IOException {
if (state == States.CLOSED) {
throw new IOException("Stream closed");
}
}
/**
* Writes the stream prolog.
*/
private void writeProlog() throws IOException {
/* File type atom
*
typedef struct {
magic brand;
bcd4 versionYear;
bcd2 versionMonth;
bcd2 versionMinor;
magic[4] compatibleBrands;
} ftypAtom;
*/
DataAtom ftypAtom = new DataAtom("ftyp");
DataAtomOutputStream d = ftypAtom.getOutputStream();
d.writeType("qt "); // brand
d.writeBCD4(2005); // versionYear
d.writeBCD2(3); // versionMonth
d.writeBCD2(0); // versionMinor
d.writeType("qt "); // compatibleBrands
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
d.writeInt(0); // compatibleBrands (0 is used to denote no value)
ftypAtom.finish();
}
private void writeEpilog() throws IOException {
long duration = getMovieDuration();
DataAtom leaf;
/* Movie Atom ========= */
moovAtom = new CompositeAtom("moov");
/* Movie Header Atom -------------
* The data contained in this atom defines characteristics of the entire
* QuickTime movie, such as time scale and duration. It has an atom type
* value of 'mvhd'.
*
* typedef struct {
byte version;
byte[3] flags;
mactimestamp creationTime;
mactimestamp modificationTime;
int timeScale;
int duration;
fixed16d16 preferredRate;
fixed8d8 preferredVolume;
byte[10] reserved;
fixed16d16 matrixA;
fixed16d16 matrixB;
fixed2d30 matrixU;
fixed16d16 matrixC;
fixed16d16 matrixD;
fixed2d30 matrixV;
fixed16d16 matrixX;
fixed16d16 matrixY;
fixed2d30 matrixW;
int previewTime;
int previewDuration;
int posterTime;
int selectionTime;
int selectionDuration;
int currentTime;
int nextTrackId;
} movieHeaderAtom;
*/
leaf = new DataAtom("mvhd");
moovAtom.add(leaf);
DataAtomOutputStream d = leaf.getOutputStream();
d.writeByte(0); // version
// A 1-byte specification of the version of this movie header atom.
d.writeByte(0); // flags[0]
d.writeByte(0); // flags[1]
d.writeByte(0); // flags[2]
// Three bytes of space for future movie header flags.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that specifies the calendar date and time (in
// seconds since midnight, January 1, 1904) when the movie atom was
// created. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that specifies the calendar date and time (in
// seconds since midnight, January 1, 1904) when the movie atom was
// changed. BooleanIt is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeUInt(movieTimeScale); // timeScale
// A time value that indicates the time scale for this movie—that is,
// the number of time units that pass per second in its time coordinate
// system. A time coordinate system that measures time in sixtieths of a
// second, for example, has a time scale of 60.
d.writeUInt(duration); // duration
// A time value that indicates the duration of the movie in time scale
// units. Note that this property is derived from the movie’s tracks.
// The value of this field corresponds to the duration of the longest
// track in the movie.
d.writeFixed16D16(preferredRate); // preferredRate
// A 32-bit fixed-point number that specifies the rate at which to play
// this movie. A value of 1.0 indicates normal rate.
d.writeFixed8D8(preferredVolume); // preferredVolume
// A 16-bit fixed-point number that specifies how loud to play this
// movie’s sound. A value of 1.0 indicates full volume.
d.write(new byte[10]); // reserved;
// Ten bytes reserved for use by Apple. Set to 0.
d.writeFixed16D16(movieMatrix[0]); // matrix[0]
d.writeFixed16D16(movieMatrix[1]); // matrix[1]
d.writeFixed2D30(movieMatrix[2]); // matrix[2]
d.writeFixed16D16(movieMatrix[3]); // matrix[3]
d.writeFixed16D16(movieMatrix[4]); // matrix[4]
d.writeFixed2D30(movieMatrix[5]); // matrix[5]
d.writeFixed16D16(movieMatrix[6]); // matrix[6]
d.writeFixed16D16(movieMatrix[7]); // matrix[7]
d.writeFixed2D30(movieMatrix[8]); // matrix[8]
// The matrix structure associated with this movie. A matrix shows how
// to map points from one coordinate space into another. See “Matrices”
// for a discussion of how display matrices are used in QuickTime:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_4.html#//apple_ref/doc/uid/TP40000939-CH206-18737
d.writeUInt(previewTime); // previewTime
// The time value in the movie at which the preview begins.
d.writeUInt(previewDuration); // previewDuration
// The duration of the movie preview in movie time scale units.
d.writeUInt(posterTime); // posterTime
// The time value of the time of the movie poster.
d.writeUInt(selectionTime); // selectionTime
// The time value for the start time of the current selection.
d.writeUInt(selectionDuration); // selectionDuration
// The duration of the current selection in movie time scale units.
d.writeUInt(currentTime); // currentTime;
// The time value for current time position within the movie.
d.writeUInt(tracks.size() + 1); // nextTrackId
// A 32-bit integer that indicates a value to use for the track ID
// number of the next track added to this movie. Note that 0 is not a
// valid track ID value.
for (int i = 0, n = tracks.size(); i < n; i++) {
/* Track Atom ======== */
writeTrackAtoms(i, moovAtom, modificationTime);
}
//
moovAtom.finish();
}
protected void writeTrackAtoms(int trackIndex, CompositeAtom moovAtom, Date modificationTime) throws IOException {
Track t = tracks.get(trackIndex);
DataAtom leaf;
DataAtomOutputStream d;
/* Track Atom ======== */
CompositeAtom trakAtom = new CompositeAtom("trak");
moovAtom.add(trakAtom);
/* Track Header Atom -----------
* The track header atom specifies the characteristics of a single track
* within a movie. A track header atom contains a size field that
* specifies the number of bytes and a type field that indicates the
* format of the data (defined by the atom type 'tkhd').
*
typedef struct {
byte version;
byte flag0;
byte flag1;
byte set TrackHeaderFlags flag2;
mactimestamp creationTime;
mactimestamp modificationTime;
int trackId;
byte[4] reserved;
int duration;
byte[8] reserved;
short layer;
short alternateGroup;
short volume;
byte[2] reserved;
int[9] matrix;
int trackWidth;
int trackHeight;
} trackHeaderAtom; */
leaf = new DataAtom("tkhd");
trakAtom.add(leaf);
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this track header.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(t.headerFlags); // flag[2]
// Three bytes that are reserved for the track header flags. These flags
// indicate how the track is used in the movie. The following flags are
// valid (all flags are enabled when set to 1):
//
// Track enabled
// Indicates that the track is enabled. Flag value is 0x0001.
// Track in movie
// Indicates that the track is used in the movie. Flag value is
// 0x0002.
// Track in preview
// Indicates that the track is used in the movie’s preview. Flag
// value is 0x0004.
// Track in poster
// Indicates that the track is used in the movie’s poster. Flag
// value is 0x0008.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that indicates the calendar date and time (expressed
// in seconds since midnight, January 1, 1904) when the track header was
// created. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that indicates the calendar date and time (expressed
// in seconds since midnight, January 1, 1904) when the track header was
// changed. It is strongly recommended that this value should be
// specified using coordinated universal time (UTC).
d.writeInt(trackIndex + 1); // trackId
// A 32-bit integer that uniquely identifies the track. The value 0
// cannot be used.
d.writeInt(0); // reserved;
// A 32-bit integer that is reserved for use by Apple. Set this field to 0.
d.writeUInt(t.getTrackDuration(movieTimeScale)); // duration
// A time value that indicates the duration of this track (in the
// movie’s time coordinate system). Note that this property is derived
// from the track’s edits. The value of this field is equal to the sum
// of the durations of all of the track’s edits. If there is no edit
// list, then the duration is the sum of the sample durations, converted
// into the movie timescale.
d.writeLong(0); // reserved
// An 8-byte value that is reserved for use by Apple. Set this field to 0.
d.writeShort(0); // layer;
// A 16-bit integer that indicates this track’s spatial priority in its
// movie. The QuickTime Movie Toolbox uses this value to determine how
// tracks overlay one another. Tracks with lower layer values are
// displayed in front of tracks with higher layer values.
d.writeShort(0); // alternate group
// A 16-bit integer that specifies a collection of movie tracks that
// contain alternate data for one another. QuickTime chooses one track
// from the group to be used when the movie is played. The choice may be
// based on such considerations as playback quality, language, or the
// capabilities of the computer.
d.writeFixed8D8(t.mediaType == MediaType.AUDIO ? 1 : 0); // volume
// A 16-bit fixed-point value that indicates how loudly this track’s
// sound is to be played. A value of 1.0 indicates normal volume.
d.writeShort(0); // reserved
// A 16-bit integer that is reserved for use by Apple. Set this field to 0.
double[] m = t.matrix;
d.writeFixed16D16(m[0]); // matrix[0]
d.writeFixed16D16(m[1]); // matrix[1]
d.writeFixed2D30(m[2]); // matrix[2]
d.writeFixed16D16(m[3]); // matrix[3]
d.writeFixed16D16(m[4]); // matrix[4]
d.writeFixed2D30(m[5]); // matrix[5]
d.writeFixed16D16(m[6]); // matrix[6]
d.writeFixed16D16(m[7]); // matrix[7]
d.writeFixed2D30(m[8]); // matrix[8]
// The matrix structure associated with this track.
// See Figure 2-8 for an illustration of a matrix structure:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_3.html#//apple_ref/doc/uid/TP40000939-CH204-32967
d.writeFixed16D16(t.mediaType == MediaType.VIDEO ? ((VideoTrack) t).width : 0); // width
// A 32-bit fixed-point number that specifies the width of this track in pixels.
d.writeFixed16D16(t.mediaType == MediaType.VIDEO ? ((VideoTrack) t).height : 0); // height
// A 32-bit fixed-point number that indicates the height of this track in pixels.
/* Edit Atom ========= */
CompositeAtom edtsAtom = new CompositeAtom("edts");
trakAtom.add(edtsAtom);
/* Edit List atom ------- */
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
editListTable editListTable[numberOfEntries];
} editListAtom;
typedef struct {
int trackDuration;
int mediaTime;
fixed16d16 mediaRate;
} editListTable;
*/
leaf = new DataAtom("elst");
edtsAtom.add(leaf);
d = leaf.getOutputStream();
d.write(0); // version
// One byte that specifies the version of this header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
Edit[] elist = t.editList;
if (elist == null || elist.length == 0) {
d.writeUInt(1); // numberOfEntries
d.writeUInt(t.getTrackDuration(movieTimeScale)); // trackDuration
d.writeUInt(0); // mediaTime
d.writeFixed16D16(1); // mediaRate
} else {
d.writeUInt(elist.length); // numberOfEntries
for (int i = 0; i < elist.length; ++i) {
d.writeUInt(elist[i].trackDuration); // trackDuration
d.writeUInt(elist[i].mediaTime); // mediaTime
d.writeUInt(elist[i].mediaRate); // mediaRate
}
}
/* Media Atom ========= */
CompositeAtom mdiaAtom = new CompositeAtom("mdia");
trakAtom.add(mdiaAtom);
/* Media Header atom -------
typedef struct {
byte version;
byte[3] flags;
mactimestamp creationTime;
mactimestamp modificationTime;
int timeScale;
int duration;
short language;
short quality;
} mediaHeaderAtom;*/
leaf = new DataAtom("mdhd");
mdiaAtom.add(leaf);
d = leaf.getOutputStream();
d.write(0); // version
// One byte that specifies the version of this header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// Three bytes of space for media header flags. Set this field to 0.
d.writeMacTimestamp(creationTime); // creationTime
// A 32-bit integer that specifies (in seconds since midnight, January
// 1, 1904) when the media atom was created. It is strongly recommended
// that this value should be specified using coordinated universal time
// (UTC).
d.writeMacTimestamp(modificationTime); // modificationTime
// A 32-bit integer that specifies (in seconds since midnight, January
// 1, 1904) when the media atom was changed. It is strongly recommended
// that this value should be specified using coordinated universal time
// (UTC).
d.writeUInt(t.mediaTimeScale); // timeScale
// A time value that indicates the time scale for this media—that is,
// the number of time units that pass per second in its time coordinate
// system.
d.writeUInt(t.mediaDuration); // duration
// The duration of this media in units of its time scale.
d.writeShort(0); // language;
// A 16-bit integer that specifies the language code for this media.
// See “Language Code Values” for valid language codes:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_2.html#//apple_ref/doc/uid/TP40000939-CH206-27005
d.writeShort(0); // quality
// A 16-bit integer that specifies the media’s playback quality—that is,
// its suitability for playback in a given environment.
/**
* Media Handler Reference Atom -------
*/
leaf = new DataAtom("hdlr");
mdiaAtom.add(leaf);
/*typedef struct {
byte version;
byte[3] flags;
magic componentType;
magic componentSubtype;
magic componentManufacturer;
int componentFlags;
int componentFlagsMask;
pstring componentName;
} handlerReferenceAtom;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this handler information.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for handler information flags. Set this field to 0.
d.writeType("mhlr"); // componentType
// A four-character code that identifies the type of the handler. Only
// two values are valid for this field: 'mhlr' for media handlers and
// 'dhlr' for data handlers.
d.writeType(t.mediaType == MediaType.VIDEO ? "vide" : "soun"); // componentSubtype
// A four-character code that identifies the type of the media handler
// or data handler. For media handlers, this field defines the type of
// data—for example, 'vide' for video data or 'soun' for sound data.
//
// For data handlers, this field defines the data reference type—for
// example, a component subtype value of 'alis' identifies a file alias.
if (t.mediaType == MediaType.AUDIO) {
d.writeType("appl");
} else {
d.writeUInt(0);
}
// componentManufacturer
// Reserved. Set to 0.
d.writeUInt(t.mediaType == MediaType.AUDIO ? 268435456L : 0); // componentFlags
// Reserved. Set to 0.
d.writeUInt(t.mediaType == MediaType.AUDIO ? 65941 : 0); // componentFlagsMask
// Reserved. Set to 0.
d.writePString(t.mediaType == MediaType.AUDIO ? "Apple Sound Media Handler" : ""); // componentName (empty string)
// A (counted) string that specifies the name of the component—that is,
// the media handler used when this media was created. This field may
// contain a zero-length (empty) string.
/* Media Information atom ========= */
writeMediaInformationAtoms(trackIndex, mdiaAtom);
}
protected void writeMediaInformationAtoms(int trackIndex, CompositeAtom mdiaAtom) throws IOException {
Track t = tracks.get(trackIndex);
DataAtom leaf;
DataAtomOutputStream d;
/* Media Information atom ========= */
CompositeAtom minfAtom = new CompositeAtom("minf");
mdiaAtom.add(minfAtom);
/* Video or Audio media information atom -------- */
switch (t.mediaType) {
case VIDEO:
writeVideoMediaInformationHeaderAtom(trackIndex,minfAtom);
break;
case AUDIO:
writeSoundMediaInformationHeaderAtom(trackIndex,minfAtom);
break;
default:
throw new UnsupportedOperationException("Media type "+t.mediaType+" not supported yet.");
}
/* Data Handler Reference Atom -------- */
// The handler reference atom specifies the media handler component that
// is to be used to interpret the media’s data. The handler reference
// atom has an atom type value of 'hdlr'.
leaf = new DataAtom("hdlr");
minfAtom.add(leaf);
/*typedef struct {
byte version;
byte[3] flags;
magic componentType;
magic componentSubtype;
magic componentManufacturer;
int componentFlags;
int componentFlagsMask;
pstring componentName;
ubyte[] extraData;
} handlerReferenceAtom;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this handler information.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for handler information flags. Set this field to 0.
d.writeType("dhlr"); // componentType
// A four-character code that identifies the type of the handler. Only
// two values are valid for this field: 'mhlr' for media handlers and
// 'dhlr' for data handlers.
d.writeType("alis"); // componentSubtype
// A four-character code that identifies the type of the media handler
// or data handler. For media handlers, this field defines the type of
// data—for example, 'vide' for video data or 'soun' for sound data.
// For data handlers, this field defines the data reference type—for
// example, a component subtype value of 'alis' identifies a file alias.
if (t.mediaType == MediaType.AUDIO) {
d.writeType("appl");
} else {
d.writeUInt(0);
}
// componentManufacturer
// Reserved. Set to 0.
d.writeUInt(t.mediaType == MediaType.AUDIO ? 268435457L : 0); // componentFlags
// Reserved. Set to 0.
d.writeInt(t.mediaType == MediaType.AUDIO ? 65967 : 0); // componentFlagsMask
// Reserved. Set to 0.
d.writePString("Apple Alias Data Handler"); // componentName (empty string)
// A (counted) string that specifies the name of the component—that is,
// the media handler used when this media was created. This field may
// contain a zero-length (empty) string.
/* Data information atom ===== */
CompositeAtom dinfAtom = new CompositeAtom("dinf");
minfAtom.add(dinfAtom);
/* Data reference atom ----- */
// Data reference atoms contain tabular data that instructs the data
// handler component how to access the media’s data.
leaf = new DataAtom("dref");
dinfAtom.add(leaf);
/*typedef struct {
ubyte version;
ubyte[3] flags;
int numberOfEntries;
dataReferenceEntry dataReference[numberOfEntries];
} dataReferenceAtom;
set {
dataRefSelfReference=1 // I am not shure if this is the correct value for this flag
} drefEntryFlags;
typedef struct {
int size;
magic type;
byte version;
ubyte flag1;
ubyte flag2;
ubyte set drefEntryFlags flag3;
byte[size - 12] data;
} dataReferenceEntry;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this data reference atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for data reference flags. Set this field to 0.
d.writeInt(1); // numberOfEntries
// A 32-bit integer containing the count of data references that follow.
d.writeInt(12); // dataReference.size
// A 32-bit integer that specifies the number of bytes in the data
// reference.
d.writeType("alis"); // dataReference.type
// A 32-bit integer that specifies the type of the data in the data
// reference. Table 2-4 lists valid type values:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_4.html#//apple_ref/doc/uid/TP40000939-CH204-38840
d.write(0); // dataReference.version
// A 1-byte specification of the version of the data reference.
d.write(0); // dataReference.flag1
d.write(0); // dataReference.flag2
d.write(0x1); // dataReference.flag3
// A 3-byte space for data reference flags. There is one defined flag.
//
// Self reference
// This flag indicates that the media’s data is in the same file as
// the movie atom. On the Macintosh, and other file systems with
// multifork files, set this flag to 1 even if the data resides in
// a different fork from the movie atom. This flag’s value is
// 0x0001.
/* Sample Table atom ========= */
writeSampleTableAtoms(trackIndex, minfAtom);
}
protected void writeVideoMediaInformationHeaderAtom(int trackIndex, CompositeAtom minfAtom) throws IOException {
DataAtom leaf;
DataAtomOutputStream d;
/* Video media information atom -------- */
leaf = new DataAtom("vmhd");
minfAtom.add(leaf);
/*typedef struct {
byte version;
byte flag1;
byte flag2;
byte set vmhdFlags flag3;
short graphicsMode;
ushort[3] opcolor;
} videoMediaInformationHeaderAtom;*/
d = leaf.getOutputStream();
d.write(0); // version
// One byte that specifies the version of this header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0x1); // flag[2]
// Three bytes of space for media header flags.
// This is a compatibility flag that allows QuickTime to distinguish
// between movies created with QuickTime 1.0 and newer movies. You
// should always set this flag to 1, unless you are creating a movie
// intended for playback using version 1.0 of QuickTime. This flag’s
// value is 0x0001.
d.writeShort(0x40); // graphicsMode (0x40 = DitherCopy)
// A 16-bit integer that specifies the transfer mode. The transfer mode
// specifies which Boolean operation QuickDraw should perform when
// drawing or transferring an image from one location to another.
// See “Graphics Modes” for a list of graphics modes supported by
// QuickTime:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/chapter_5_section_5.html#//apple_ref/doc/uid/TP40000939-CH206-18741
d.writeUShort(0); // opcolor[0]
d.writeUShort(0); // opcolor[1]
d.writeUShort(0); // opcolor[2]
// Three 16-bit values that specify the red, green, and blue colors for
// the transfer mode operation indicated in the graphics mode field.
}
protected void writeSoundMediaInformationHeaderAtom(int trackIndex,CompositeAtom minfAtom) throws IOException {
DataAtom leaf;
DataAtomOutputStream d;
/* Sound media information header atom -------- */
leaf = new DataAtom("smhd");
minfAtom.add(leaf);
/*typedef struct {
ubyte version;
ubyte[3] flags;
short balance;
short reserved;
} soundMediaInformationHeaderAtom;*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this sound media information header atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for sound media information flags. Set this field to 0.
d.writeFixed8D8(0); // balance
// A 16-bit integer that specifies the sound balance of this
// sound media. Sound balance is the setting that controls
// the mix of sound between the two speakers of a computer.
// This field is normally set to 0.
// Balance values are represented as 16-bit, fixed-point
// numbers that range from -1.0 to +1.0. The high-order 8
// bits contain the integer portion of the value; the
// low-order 8 bits contain the fractional part. Negative
// values weight the balance toward the left speaker;
// positive values emphasize the right channel. Setting the
// balance to 0 corresponds to a neutral setting.
d.writeUShort(0); // reserved
// Reserved for use by Apple. Set this field to 0.
}
protected void writeSampleTableAtoms(int trackIndex, CompositeAtom minfAtom) throws IOException {
Track t = tracks.get(trackIndex);
DataAtom leaf;
DataAtomOutputStream d;
/* Sample Table atom ========= */
CompositeAtom stblAtom = new CompositeAtom("stbl");
minfAtom.add(stblAtom);
/* Sample Description atom ------- */
t.writeSampleDescriptionAtom(stblAtom);
/* Time to Sample atom ---- */
// Time-to-sample atoms store duration information for a media’s
// samples, providing a mapping from a time in a media to the
// corresponding data sample. The time-to-sample atom has an atom type
// of 'stts'.
leaf = new DataAtom("stts");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
timeToSampleTable timeToSampleTable[numberOfEntries];
} timeToSampleAtom;
typedef struct {
int sampleCount;
int sampleDuration;
} timeToSampleTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(t.timeToSamples.size()); // numberOfEntries
// A 32-bit integer containing the count of entries in the
// time-to-sample table.
for (TimeToSampleGroup tts : t.timeToSamples) {
d.writeUInt(tts.getSampleCount()); // timeToSampleTable[0].sampleCount
// A 32-bit integer that specifies the number of consecutive
// samples that have the same duration.
d.writeUInt(tts.getSampleDuration()); // timeToSampleTable[0].sampleDuration
// A 32-bit integer that specifies the duration of each
// sample.
}
/* sample to chunk atom -------- */
// The sample-to-chunk atom contains a table that maps samples to chunks
// in the media data stream. By examining the sample-to-chunk atom, you
// can determine the chunk that contains a specific sample.
leaf = new DataAtom("stsc");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
sampleToChunkTable sampleToChunkTable[numberOfEntries];
} sampleToChunkAtom;
typedef struct {
int firstChunk;
int samplesPerChunk;
int sampleDescription;
} sampleToChunkTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
int entryCount = 0;
long previousSampleCount = -1;
long previousSampleDescriptionId = -1;
for (Chunk c : t.chunks) {
if (c.sampleCount != previousSampleCount//
|| c.sampleDescriptionId != previousSampleDescriptionId) {
previousSampleCount = c.sampleCount;
previousSampleDescriptionId = c.sampleDescriptionId;
entryCount++;
}
}
d.writeInt(entryCount); // number of entries
// A 32-bit integer containing the count of entries in the sample-to-chunk table.
int firstChunk = 1;
previousSampleCount = -1;
previousSampleDescriptionId = -1;
for (Chunk c : t.chunks) {
if (c.sampleCount != previousSampleCount//
|| c.sampleDescriptionId != previousSampleDescriptionId) {
previousSampleCount = c.sampleCount;
previousSampleDescriptionId = c.sampleDescriptionId;
d.writeUInt(firstChunk); // first chunk
// The first chunk number using this table entry.
d.writeUInt(c.sampleCount); // samples per chunk
// The number of samples in each chunk.
d.writeInt(c.sampleDescriptionId); // sample description
// The identification number associated with the sample description for
// the sample. For details on sample description atoms, see “Sample
// Description Atoms.”:
// http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap2/chapter_3_section_5.html#//apple_ref/doc/uid/TP40000939-CH204-25691
}
firstChunk++;
}
//
/* sync sample atom -------- */
if (t.syncSamples != null) {
leaf = new DataAtom("stss");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
syncSampleTable syncSampleTable[numberOfEntries];
} syncSampleAtom;
typedef struct {
int number;
} syncSampleTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(t.syncSamples.size());
// Number of entries
//A 32-bit integer containing the count of entries in the sync sample table.
for (Long number : t.syncSamples) {
d.writeUInt(number);
// Sync sample table A table of sample numbers; each sample
// number corresponds to a key frame.
}
}
/* sample size atom -------- */
// The sample size atom contains the sample count and a table giving the
// size of each sample. This allows the media data itself to be
// unframed. The total number of samples in the media is always
// indicated in the sample count. If the default size is indicated, then
// no table follows.
leaf = new DataAtom("stsz");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int sampleSize;
int numberOfEntries;
sampleSizeTable sampleSizeTable[numberOfEntries];
} sampleSizeAtom;
typedef struct {
int size;
} sampleSizeTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
int sampleUnit = t.mediaType == MediaType.AUDIO//
&& ((AudioTrack) t).soundCompressionId != -2 //
? ((AudioTrack) t).soundSampleSize / 8 * ((AudioTrack) t).soundNumberOfChannels//
: 1;
if (t.sampleSizes.size() == 1) {
d.writeUInt(t.sampleSizes.get(0).getSampleLength() / sampleUnit); // sample size
// A 32-bit integer specifying the sample size. If all the samples are
// the same size, this field contains that size value. If this field is
// set to 0, then the samples have different sizes, and those sizes are
// stored in the sample size table.
d.writeUInt(t.sampleSizes.get(0).getSampleCount()); // number of entries
// A 32-bit integer containing the count of entries in the sample size
// table.
} else {
d.writeUInt(0); // sample size
// A 32-bit integer specifying the sample size. If all the samples are
// the same size, this field contains that size value. If this field is
// set to 0, then the samples have different sizes, and those sizes are
// stored in the sample size table.
long count = 0;
for (SampleSizeGroup s : t.sampleSizes) {
count += s.sampleCount;
}
d.writeUInt(count); // number of entries
// A 32-bit integer containing the count of entries in the sample size
// table.
for (SampleSizeGroup s : t.sampleSizes) {
long sampleSize = s.getSampleLength() / sampleUnit;
for (int i = 0; i < s.sampleCount; i++) {
d.writeUInt(sampleSize); // sample size
// The size field contains the size, in bytes, of the sample in
// question. The table is indexed by sample number—the first entry
// corresponds to the first sample, the second entry is for the
// second sample, and so on.
}
}
}
//
/* chunk offset atom -------- */
// The chunk-offset table gives the index of each chunk into the
// QuickTime Stream. There are two variants, permitting the use of
// 32-bit or 64-bit offsets. The latter is useful when managing very
// large movies. Only one of these variants occurs in any single
// instance of a sample table atom.
if (t.chunks.isEmpty() || t.chunks.get(t.chunks.size() - 1).getChunkOffset() <= 0xffffffffL) {
/* 32-bit chunk offset atom -------- */
leaf = new DataAtom("stco");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
chunkOffsetTable chunkOffsetTable[numberOfEntries];
} chunkOffsetAtom;
typedef struct {
int offset;
} chunkOffsetTable;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(t.chunks.size()); // number of entries
// A 32-bit integer containing the count of entries in the chunk
// offset table.
for (Chunk c : t.chunks) {
d.writeUInt(c.getChunkOffset() + mdatOffset); // offset
// The offset contains the byte offset from the beginning of the
// data stream to the chunk. The table is indexed by chunk
// number—the first table entry corresponds to the first chunk,
// the second table entry is for the second chunk, and so on.
}
} else {
/* 64-bit chunk offset atom -------- */
leaf = new DataAtom("co64");
stblAtom.add(leaf);
/*
typedef struct {
byte version;
byte[3] flags;
int numberOfEntries;
chunkOffsetTable chunkOffset64Table[numberOfEntries];
} chunkOffset64Atom;
typedef struct {
long offset;
} chunkOffset64Table;
*/
d = leaf.getOutputStream();
d.write(0); // version
// A 1-byte specification of the version of this time-to-sample atom.
d.write(0); // flag[0]
d.write(0); // flag[1]
d.write(0); // flag[2]
// A 3-byte space for time-to-sample flags. Set this field to 0.
d.writeUInt(t.chunks.size()); // number of entries
// A 32-bit integer containing the count of entries in the chunk
// offset table.
for (Chunk c : t.chunks) {
d.writeLong(c.getChunkOffset()); // offset
// The offset contains the byte offset from the beginning of the
// data stream to the chunk. The table is indexed by chunk
// number—the first table entry corresponds to the first chunk,
// the second table entry is for the second chunk, and so on.
}
}
}
/**
* Writes a version of the movie which is optimized for the web into the
* specified output file. This method finishes the movie and then copies
* its content into the specified file. The web-optimized file starts with
* the movie header.
*
* @param outputFile The output file
* @param compressHeader Whether the movie header shall be compressed.
*/
public void toWebOptimizedMovie(File outputFile, boolean compressHeader) throws IOException {
finish();
long originalMdatOffset = mdatAtom.getOffset();
CompositeAtom originalMoovAtom = moovAtom;
mdatOffset = 0;
ImageOutputStream originalOut = out;
try {
out = null;
if (compressHeader) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int maxIteration = 5;
long compressionHeadersSize = 40 + 8;
long headerSize = 0;
long freeSize = 0;
while (true) {
mdatOffset = compressionHeadersSize + headerSize + freeSize;
buf.reset();
DeflaterOutputStream deflater = new DeflaterOutputStream(buf);
out = new MemoryCacheImageOutputStream(deflater);
writeEpilog();
out.close();
deflater.close();
if (buf.size() > headerSize + freeSize && --maxIteration > 0) {
if (headerSize != 0) {
freeSize = Math.max(freeSize, buf.size() - headerSize - freeSize);
}
headerSize = buf.size();
} else {
freeSize = headerSize + freeSize - buf.size();
headerSize = buf.size();
break;
}
}
if (maxIteration < 0 || buf.size() == 0) {
compressHeader = false;
System.err.println("WARNING QuickTimeWriter failed to compress header.");
} else {
out = new FileImageOutputStream(outputFile);
writeProlog();
// 40 bytes compression headers
DataAtomOutputStream daos = new DataAtomOutputStream(new ImageOutputStreamAdapter(out));
daos.writeUInt(headerSize + 40);
daos.writeType("moov");
daos.writeUInt(headerSize + 32);
daos.writeType("cmov");
daos.writeUInt(12);
daos.writeType("dcom");
daos.writeType("zlib");
daos.writeUInt(headerSize + 12);
daos.writeType("cmvd");
daos.writeUInt(originalMoovAtom.size());
daos.write(buf.toByteArray());
// 8 bytes "free" atom + free data
daos.writeUInt(freeSize + 8);
daos.writeType("free");
for (int i = 0; i < freeSize; i++) {
daos.write(0);
}
}
}
if (!compressHeader) {
out = new FileImageOutputStream(outputFile);
mdatOffset = moovAtom.size();
writeProlog();
writeEpilog();
}
byte[] buf = new byte[4096];
originalOut.seek((originalMdatOffset));
for (long count = 0, n = mdatAtom.size(); count < n;) {
int read = originalOut.read(buf, 0, (int) Math.min(buf.length, n - count));
out.write(buf, 0, read);
count += read;
}
out.close();
} finally {
mdatOffset = 0;
moovAtom = originalMoovAtom;
out = originalOut;
}
}
}
| 38.980583 | 174 | 0.597929 |
780959cb8a88e1147a27c83024c0583e5e8a5c02 | 1,042 | // =====================================================
// Project: authprovider
// (c) Heike Winkelvoß
// =====================================================
package de.egladil.web.authprovider.payload.profile;
import javax.validation.constraints.NotNull;
import de.egladil.web.commons_validation.annotations.UuidString;
import de.egladil.web.commons_validation.payload.OAuthClientCredentials;
/**
* ChangeProfilePasswordPayload
*/
public class ChangeProfilePasswordPayload {
@NotNull
private OAuthClientCredentials clientCredentials;
@NotNull
private ProfilePasswordPayload passwordPayload;
@NotNull
@UuidString
private String uuid;
public OAuthClientCredentials getClientCredentials() {
return clientCredentials;
}
public ProfilePasswordPayload getPasswordPayload() {
return passwordPayload;
}
public String getUuid() {
return uuid;
}
public void clean() {
if (clientCredentials != null) {
clientCredentials.clean();
}
if (passwordPayload != null) {
passwordPayload.clean();
}
}
}
| 18.607143 | 72 | 0.684261 |
7b5cc4d309807c8e6daa1f0c95ff18f8266d4edc | 700 | package com.github.yizzuide.milkomeda.light;
import java.lang.annotation.*;
/**
* LightCacheable
*
* @author yizzuide
* @since 2.0.0
* @version 3.5.0
* Create at 2019/12/18 14:35
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
public @interface LightCacheable {
/**
* 缓存实例名(不同的缓存类型应该设置不能的名字),支持EL表达式
* @return String
*/
String value();
/**
* 缓存key,支持EL表达式
* @return String
*/
String key();
/**
* 缓存key前辍,与属性方法 key() 合成完整的key
* @return String
*/
String keyPrefix() default "";
/**
* 缓存条件,需要使用EL表达式
* @return String
*/
String condition() default "";
}
| 16.666667 | 44 | 0.597143 |
22844a7c8b4f8e1e60d02b9bc40cb67290f07734 | 4,749 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.openide.awt;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import javax.swing.Icon;
import javax.swing.UIManager;
import org.openide.util.ImageUtilities;
import org.openide.util.Parameters;
import org.openide.util.VectorIcon;
/**
* An icon that paints a small arrow to the right of the provided icon.
*
* @author S. Aubrecht
* @since 6.11
*/
class IconWithArrow implements Icon {
private Icon orig;
private Icon arrow;
private boolean paintRollOver;
private static final int GAP = 6;
/** Creates a new instance of IconWithArrow */
public IconWithArrow( Icon orig, boolean paintRollOver, boolean disabledArrow ) {
Parameters.notNull("original icon", orig); //NOI18N
this.orig = orig;
this.paintRollOver = paintRollOver;
this.arrow = disabledArrow ? ArrowIcon.INSTANCE_DISABLED : ArrowIcon.INSTANCE_DEFAULT;
}
@Override
public void paintIcon( Component c, Graphics g, int x, int y ) {
int height = getIconHeight();
orig.paintIcon( c, g, x, y+(height-orig.getIconHeight())/2 );
arrow.paintIcon( c, g, x+GAP+orig.getIconWidth(), y+(height-arrow.getIconHeight())/2 );
if( paintRollOver ) {
Color brighter = UIManager.getColor( "controlHighlight" ); //NOI18N
Color darker = UIManager.getColor( "controlShadow" ); //NOI18N
if( null == brighter || null == darker ) {
brighter = c.getBackground().brighter();
darker = c.getBackground().darker();
}
if( null != brighter && null != darker ) {
g.setColor( brighter );
g.drawLine( x+orig.getIconWidth()+1, y,
x+orig.getIconWidth()+1, y+getIconHeight() );
g.setColor( darker );
g.drawLine( x+orig.getIconWidth()+2, y,
x+orig.getIconWidth()+2, y+getIconHeight() );
}
}
}
@Override
public int getIconWidth() {
return orig.getIconWidth() + GAP + arrow.getIconWidth();
}
@Override
public int getIconHeight() {
return Math.max( orig.getIconHeight(), arrow.getIconHeight() );
}
public static int getArrowAreaWidth() {
return GAP/2 + 5;
}
static class ArrowIcon extends VectorIcon {
public static final Icon INSTANCE_DEFAULT = new ArrowIcon(false);
public static final Icon INSTANCE_DISABLED = new ArrowIcon(true);
private final boolean disabled;
private ArrowIcon(boolean disabled) {
super(5, 4);
this.disabled = disabled;
}
@Override
protected void paintIcon(Component c, Graphics2D g, int width, int height, double scaling) {
final Color color;
if (UIManager.getBoolean("nb.dark.theme")) {
// Foreground brightness level taken from the combobox dropdown on Darcula.
color = disabled ? new Color(90, 90, 90, 255) : new Color(187, 187, 187, 255);
} else {
color = disabled ? new Color(201, 201, 201, 255) : new Color(86, 86, 86, 255);
}
g.setColor(color);
final double overshoot = 2.0 / scaling;
final double arrowWidth = width + overshoot * scaling;
final double arrowHeight = height - 0.2 * scaling;
final double arrowMidX = arrowWidth / 2.0 - (overshoot / 2.0) * scaling;
g.clipRect(0, 0, width, height);
Path2D.Double arrowPath = new Path2D.Double();
arrowPath.moveTo(arrowMidX - arrowWidth / 2.0, 0);
arrowPath.lineTo(arrowMidX, arrowHeight);
arrowPath.lineTo(arrowMidX + arrowWidth / 2.0, 0);
arrowPath.closePath();
g.fill(arrowPath);
}
}
}
| 37.393701 | 100 | 0.622447 |
a28d21fa1faa813be7c6e7ba9f08052c69eb01cb | 4,683 | package org.robolectric.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** @author christianw@google.com (Christian Williams) */
@RunWith(JUnit4.class)
public class RobolectricShadowTest {
private BugCheckerRefactoringTestHelper testHelper;
@Before
public void setUp() {
this.testHelper =
BugCheckerRefactoringTestHelper.newInstance(new RobolectricShadow(), getClass());
}
@Test
public void implMethodsShouldBeProtected() throws IOException {
testHelper
.addInputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.HiddenApi;",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(Object.class)",
"public class SomeShadow {",
" @Implementation public void publicMethod() {}",
" @Implementation @HiddenApi public void publicHiddenMethod() {}",
" @Implementation protected void protectedMethod() {}",
" @Implementation void packageMethod() {}",
" @Implementation private void privateMethod() {}",
"}")
.addOutputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.HiddenApi;",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(Object.class)",
"public class SomeShadow {",
" @Implementation protected void publicMethod() {}",
" @Implementation @HiddenApi public void publicHiddenMethod() {}",
" @Implementation protected void protectedMethod() {}",
" @Implementation protected void packageMethod() {}",
" @Implementation protected void privateMethod() {}",
"}")
.doTest();
}
@Test
public void implMethodsNotProtectedForClassesNotInAndroidSdk() throws IOException {
testHelper
.addInputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.HiddenApi;",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(value = Object.class, isInAndroidSdk = false)",
"public class SomeShadow {",
" @Implementation public void publicMethod() {}",
" @Implementation @HiddenApi public void publicHiddenMethod() {}",
" @Implementation protected void protectedMethod() {}",
" @Implementation void packageMethod() {}",
" @Implementation private void privateMethod() {}",
"}")
.addOutputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.HiddenApi;",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(value = Object.class, isInAndroidSdk = false)",
"public class SomeShadow {",
" @Implementation public void publicMethod() {}",
" @Implementation @HiddenApi public void publicHiddenMethod() {}",
" @Implementation protected void protectedMethod() {}",
" @Implementation void packageMethod() {}",
" @Implementation private void privateMethod() {}",
"}")
.doTest();
}
@Test
public void implMethodJavadocShouldBeMarkdown() throws Exception {
testHelper
.addInputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(Object.class)",
"public class SomeShadow {",
" /**",
" * <p>Should be markdown!</p>",
" */",
" @Implementation public void aMethod() {}",
"}")
.addOutputLines(
"in/SomeShadow.java",
"import org.robolectric.annotation.Implementation;",
"import org.robolectric.annotation.Implements;",
"",
"@Implements(Object.class)",
"public class SomeShadow {",
" /**",
" * Should be markdown!",
" */",
" @Implementation protected void aMethod() {}",
"}")
.doTest();
}
}
| 39.352941 | 89 | 0.586803 |
ddbd73318185657c6f8e00754b4f6b8192b3a0b0 | 13,479 | package com.alimama.mdrill.solr.hbaserealtime;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.core.SolrResourceLoader.PartionKey;
import com.alimama.mdrill.adhoc.TimeCacheMap;
import com.alimama.mdrill.adhoc.TimeCacheMap.CleanExecute;
import com.alimama.mdrill.editlog.AddOp;
import com.alimama.mdrill.editlog.FSEditLog;
import com.alimama.mdrill.editlog.defined.StorageDirectory;
import com.alimama.mdrill.editlog.read.EditLogInputStream;
import com.alimama.mdrill.hdfsDirectory.FileSystemDirectory;
import com.alimama.mdrill.solr.hbaserealtime.DirectoryInfo.DirTpe;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectorUtils;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectoryLock;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectoryParams;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectoryStatus;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectoryThread;
import com.alimama.mdrill.solr.hbaserealtime.realtime.RealTimeDirectoryData;
import com.alimama.mdrill.utils.UniqConfig;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class RealTimeDirectory implements MdrillDirectory,TimeCacheMap.ExpiredCallback<Integer, DirectoryInfo>{
public static Logger LOG = LoggerFactory.getLogger(RealTimeDirectory.class);
private RealTimeDirectoryData data;
private RealTimeDirectoryParams params=new RealTimeDirectoryParams();
private RealTimeDirectoryStatus status=new RealTimeDirectoryStatus();
private RealTimeDirectoryThread thread;
private FSEditLog editlog;
private final RealTimeDirectoryLock rlock=new RealTimeDirectoryLock();
private AtomicBoolean needFlushDfs=new AtomicBoolean(false);
private AtomicBoolean needRollLogs=new AtomicBoolean(false);
public RealTimeDirectory(File path,String hadoopConfDir,String hdfsPath,SolrCore core,PartionKey partion) throws IOException
{
LOG.info("##RealTimeDirectory init ##"+path.getAbsolutePath()+","+hdfsPath);
this.params.hadoopConfDir=hadoopConfDir;
this.params.baseDir=path.getAbsolutePath();
this.params.hdfsPath=hdfsPath;
this.params.Partion = partion;
this.params.core = core;
path.mkdirs();
status.isInit.set(this.params.checkSyncHdfs());
LOG.info("## RealTimeDirectory isinit##"+path.getAbsolutePath()+","+hdfsPath+",this.isInit="+String.valueOf(status.isInit));
Configuration conf=params.getConf();
FileSystem fs=FileSystem.get(conf);
if(!status.isInit.get())
{
fs.mkdirs(new Path(hdfsPath).getParent());
}
boolean isUsedHdfs=false;
if(!status.isInit.get())
{
isUsedHdfs=params.isUseHdfsIndex();
}
data=new RealTimeDirectoryData(params, status, this);
data.initDiskDirector(isUsedHdfs);
this.recoverFromEditlog(conf,isUsedHdfs);
thread=new RealTimeDirectoryThread(status,params,data,rlock,this);
thread.start();
if(isUsedHdfs)
{
status.allowsynchdfs.set(false);
thread.startSyncFromHdfs(new Runnable() {
@Override
public void run() {
status.allowsynchdfs.set(true);
}
});
}else{
status.allowsynchdfs.set(true);
}
if(!status.isInit.get())
{
this.params.markSyncHdfs();
}
}
public void setPartion(PartionKey partion) {
params.Partion = partion;
}
public CleanExecute<Integer, DirectoryInfo> getCleanLock()
{
return new TimeCacheMap.CleanExecuteWithLock<Integer, DirectoryInfo>(rlock.lock);
}
public void setCore(SolrCore core) {
params.core = core;
}
public void purger(boolean remakeLinks) throws IOException
{
List<Directory> copyDir=new ArrayList<Directory>();;
synchronized (rlock.lock) {
if(remakeLinks)
{
this.data.remakeIndexLinksFile();
}
copyDir=this.data.copyForSearch();
}
synchronized (rlock.searchLock) {
readList=copyDir;
SolrResourceLoader.SetCacheFlushKey(params.Partion,System.currentTimeMillis());
}
}
private List<Directory> readList=null;
public List<Directory> getForSearch()
{
List<Directory> rtn=null;
synchronized (rlock.searchLock) {
rtn=readList;
}
if(rtn==null)
{
List<Directory> copyDir=new ArrayList<Directory>();;
synchronized (rlock.lock) {
copyDir=this.data.copyForSearch();
}
synchronized (rlock.searchLock) {
readList=copyDir;
}
}
synchronized (rlock.searchLock) {
rtn=readList;
}
LOG.info("####getForSearch####"+String.valueOf(rtn));
return rtn;
}
public void commit(){
}
@Override
public void expire(Integer key, DirectoryInfo val) {
if (val.tp.equals(DirectoryInfo.DirTpe.buffer)) {
try {
this.data.mergerBuffer(val);
this.data.maybeMerger();
} catch (Throwable e) {
LOG.error("####expire buffer error ####", e);
}
return;
}
if (val.tp.equals(DirectoryInfo.DirTpe.ram)) {
try {
this.data.mergerRam(val);
this.data.maybeMerger();
} catch (Throwable e) {
LOG.error("####expire ram error ####", e);
}
return;
}
if (val.tp.equals(DirectoryInfo.DirTpe.delete)) {
try {
RealTimeDirectorUtils.deleteDirector(val,this.params.getConf());
} catch (Throwable e) {
LOG.error("deleteDirector", e);
}
return;
}
}
public void syncLocal()
{
synchronized (rlock.lock) {
this.data.flushToDisk();
}
}
public void mergerFinal()
{
synchronized (rlock.lock) {
this.data.flushToDisk();
boolean ismerger=this.data.maybeMergerFinal();
if(ismerger)
{
needFlushDfs.set(true);
}
}
}
public synchronized void syncHdfs()
{
if(!needFlushDfs.get())
{
return ;
}
long t1=System.currentTimeMillis();
while(!this.status.allowsynchdfs.get())
{
try {
Thread.sleep(10000);
LOG.error("syncHdfs wait");
} catch (InterruptedException e) {
}
long t2=System.currentTimeMillis();
if(t2-t1>1000l*3600*3)
{
LOG.error("syncHdfs wait timeout");
break;
}
}
needFlushDfs.set(false);
String tsstr="";
ConcurrentHashMap<String, DirectoryInfo> diskDirector_hdfs=new ConcurrentHashMap<String, DirectoryInfo>();
synchronized (rlock.lock) {
this.data.flushToDisk();
try {
tsstr=data.remakeIndexLinksFile();
diskDirector_hdfs=this.data.copyForSyncHdfs();;
} catch (Throwable e) {
LOG.error("syncHdfs",e);
}
}
try {
saveToHdfs(diskDirector_hdfs,tsstr);
} catch (Throwable e) {
LOG.error("syncHdfs",e);
}
}
private void saveToHdfs(ConcurrentHashMap<String, DirectoryInfo> buffer,String tsstr) throws IOException
{
Configuration conf=this.params.getConf();
FileSystem fs=FileSystem.get(conf);
Path tmpDir=new Path(params.hdfsPath,"realtime_tmp");
if(fs.exists(tmpDir))
{
fs.delete(tmpDir, true);
}
fs.mkdirs(tmpDir);
Path tsdst=new Path(tmpDir,"realtime_ts");
OutputStreamWriter fwriterTs= new OutputStreamWriter(fs.create(tsdst));
fwriterTs.write(tsstr);
fwriterTs.close();
LOG.info("####sync realtime_ts ####"+tsstr+","+tsdst.toString());
long txid=0;
for(Entry<String, DirectoryInfo> e:buffer.entrySet())
{
e.getValue().synctxid();
txid=Math.max(txid, e.getValue().readTxid());
Path local=new Path(e.getKey());
Path dst=new Path(tmpDir,local.getName());
LOG.info("####copyFromLocalFile####"+local.toString()+","+dst.toString());
fs.copyFromLocalFile(local,dst);
}
Path realtimefinal=new Path(params.hdfsPath,"realtime");
if(fs.exists(realtimefinal))
{
fs.delete(realtimefinal, true);
}
fs.rename(tmpDir, realtimefinal);
if(txid>0)
{
synchronized (editlog) {
editlog.purgeLogsOlderThan(txid-1);
}
}
LOG.info("####saveToHdfs####"+realtimefinal.toString()+",purgeLogsOlderThan txid="+txid);
}
public synchronized void addDocument(SolrInputDocument doc) throws CorruptIndexException, LockObtainFailedException, IOException
{
this.addDocument(doc,true);
}
private long editlogtime=System.currentTimeMillis();
private AtomicInteger addIntervel=new AtomicInteger(0);
public synchronized void addDocument(SolrInputDocument doc,boolean writelog) throws CorruptIndexException, LockObtainFailedException, IOException
{
if(RealTimeDirectorUtils.maybeReplication(doc))
{
return ;
}
this.status.lastAddDocumentTime.set(System.currentTimeMillis());
if(writelog)
{
try {
AddOp op=new AddOp();
op.setDoc(doc);
synchronized (editlog) {
if(!needRollLogs.get())
{
editlog.openForWrite();
needRollLogs.set(true);
}
editlog.logEdit(op);
long lasttid=editlog.getLastWrittenTxId();
doc.setTxid(lasttid);
if(lasttid%UniqConfig.logRollIntervel()==0)
{
long currenttime=System.currentTimeMillis();
if(currenttime-editlogtime>=UniqConfig.logRollTimelen())
{
editlogtime=currenttime;
editlog.rollEditLog();
}
}
}
} catch (Exception e) {
LOG.error("editlog_"+this.params.Partion.toString(),e);
editlog.openForWrite();
}
}
needFlushDfs.set(true);
synchronized (rlock.doclistBuffer_lock) {
this.data.AddDoc(doc);
}
if(addIntervel.incrementAndGet()>5000)
{
addIntervel.set(0);
int size=0;
synchronized (rlock.doclistBuffer_lock) {
size=this.data.doclistSize();
}
if(size>20000)
{
this.flushDocList();
}
}
}
public void flushDocList() throws CorruptIndexException,
LockObtainFailedException, IOException {
ArrayList<SolrInputDocument> flush = null;
synchronized (this.rlock.doclistBuffer_lock) {
flush = this.data.popDoclist();
addIntervel.set(0);
}
synchronized (this.rlock.lock) {
if (flush != null) {
this.data.flushDocList(flush);
}
}
}
private void recoverFromEditlog(Configuration conf,boolean isUsedHdfs) throws IOException
{
long t1=System.currentTimeMillis();
List<StorageDirectory> editsDirs = new ArrayList<StorageDirectory>();
if("hdfs".equals(SolrCore.getBinglogType()))
{
editsDirs.add(new StorageDirectory(FileSystem.get(conf), new Path(params.hdfsPath, "editlogs_v9")));
}else{
editsDirs.add(new StorageDirectory(FileSystem.getLocal(conf), new Path(params.baseDir, "editlogs_v9")));
}
LOG.info("recoverFromEditlog begin:"+this.params.getLogStr());
editlog = new FSEditLog(conf, editsDirs);
editlog.initJournalsForWrite();
editlog.recoverUnclosedStreams();
long savedTxid=this.data.getMaxTxidFromLocal();
if(isUsedHdfs)
{
Path realtimefinal=new Path(this.params.hdfsPath,"realtime");
FileSystem fs=FileSystem.get(conf);
FileStatus[] list=fs.listStatus(realtimefinal);
if(list!=null)
{
for(FileStatus s:list)
{
try{
DirectoryInfo info=new DirectoryInfo();
info.tp=DirTpe.hdfs;
info.d=new FileSystemDirectory(fs, s.getPath(), false, conf);
savedTxid=Math.max(savedTxid, info.readTxid());
}catch(Throwable e){
LOG.error("recoverFromEditlog error",e);
}
}
}
}
LOG.info("recoverFromEditlog savedTxid:"+savedTxid+","+this.params.getLogStr());
long lines=0;
long allrecord=0;
Collection<EditLogInputStream> streams=new ArrayList<EditLogInputStream>();
editlog.selectInputStreams(streams, savedTxid+1, true, true);
long lasttxid=savedTxid;
if(streams!=null&&streams.size()>0)
{
for(EditLogInputStream stream:streams)
{
while(true)
{
AddOp op=null;
try {
op = (AddOp) stream.readOp();
if (op == null) {
LOG.error("readOp end");
break;
}
if(op.getDoc()==null)
{
LOG.error("readOp doc null");
continue;
}
} catch (Throwable e) {
LOG.error("readOp", e);
break;
}
SolrInputDocument doc=op.getDoc();
doc.setTxid(op.getTransactionId());
if(lines<100000)
{
lines++;
if(lines%500==0)
{
LOG.info("##recover##"+doc.toString()+",savedTxid="+savedTxid+":"+this.params.getLogStr());
}
}
allrecord++;
if(allrecord%1000==0)
{
this.flushDocList();
}
this.addDocument(doc,false);
}
lasttxid=Math.max(stream.getLastTxId(), lasttxid);
}
FSEditLog.closeAllStreams(streams);
}
editlog.setNextTxId(lasttxid+1);
long t2=System.currentTimeMillis();
long timetaken=t2-t1;
LOG.info("##recovercount##count="+allrecord+",savedTxid="+savedTxid+",getLastTxId="+lasttxid+",timetaken="+timetaken+","+this.params.getLogStr());
}
public void close() {
try {
this.thread.close();
if(this.needRollLogs.get())
{
this.editlog.endCurrentLogSegment(true);
}
} catch (Throwable e) {
LOG.error("close",e);
}
}
}
| 26.377691 | 148 | 0.696491 |
bf3a4e479575f421a923eb5ad1e408545c4566e7 | 5,844 | /*
* Testerra
*
* (C) 2020, Peter Lehmann, T-Systems Multimedia Solutions GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license 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 eu.tsystems.mms.tic.testframework.pageobjects.internal.core;
import eu.tsystems.mms.tic.testframework.logging.LogLevel;
import eu.tsystems.mms.tic.testframework.pageobjects.GuiElement;
import eu.tsystems.mms.tic.testframework.pageobjects.POConfig;
import eu.tsystems.mms.tic.testframework.pageobjects.internal.TimerWrapper;
import eu.tsystems.mms.tic.testframework.pageobjects.internal.frames.FrameLogic;
import eu.tsystems.mms.tic.testframework.utils.StringUtils;
import java.util.WeakHashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GuiElementData {
public static final WeakHashMap<WebElement, GuiElement> WEBELEMENT_MAP = new WeakHashMap<>();
public final By by;
/**
* // TODO This will not @deprecated in Testerra 2
*/
@Deprecated // Evil, should never be used!!! <<< why, i need it?? pele 23.08.2019
public final GuiElement guiElement;
public final WebDriver webDriver;
public String name;
@Deprecated
public int timeoutInSeconds;
public final TimerWrapper timerWrapper;
public WebElement webElement;
public final FrameLogic frameLogic;
public final int timerSleepTimeInMs = 500;
public boolean sensibleData = false;
/**
* // TODO This will be @deprecated in Testerra 2
*/
@Deprecated
public GuiElementCore parent;
public final int index;
public LogLevel logLevel = LogLevel.DEBUG;
public LogLevel storedLogLevel = logLevel;
public String browser;
public boolean shadowRoot = false;
public GuiElementData(GuiElementData guiElementData, int index) {
this(
guiElementData.webDriver,
guiElementData.name,
guiElementData.frameLogic,
guiElementData.by,
guiElementData.guiElement,
index
);
parent = guiElementData.parent;
}
public GuiElementData(
WebDriver webDriver,
String name,
FrameLogic frameLogic,
By by,
GuiElement guiElement
) {
this(webDriver, name, frameLogic, by, guiElement, -1);
}
private GuiElementData(
WebDriver webDriver,
String name,
FrameLogic frameLogic,
By by,
GuiElement guiElement,
int index
) {
this.webDriver = webDriver;
this.name = name;
this.by = by;
this.guiElement = guiElement;
this.timeoutInSeconds = POConfig.getUiElementTimeoutInSeconds();
this.frameLogic = frameLogic;
// Central Timer Object which is used by all sequence executions
this.timerWrapper = new TimerWrapper(timerSleepTimeInMs, timeoutInSeconds, webDriver);
this.index = index;
}
public Logger getLogger() {
return LoggerFactory.getLogger("GuiElement" + (name == null ? "" : " " + name));
}
/**
* @deprecated See {@link GuiElement#getTimeoutInSeconds()} for description
*/
@Deprecated
public int getTimeoutInSeconds() {
return timeoutInSeconds;
}
/**
* @deprecated See {@link GuiElement#setTimeoutInSeconds(int)} for description
*/
@Deprecated
public void setTimeoutInSeconds(int timeoutInSeconds) {
this.timeoutInSeconds = timeoutInSeconds;
timerWrapper.setTimeoutInSeconds(timeoutInSeconds);
}
public boolean hasName() {
return !StringUtils.isEmpty(name);
}
@Override
public String toString() {
String toString = guiElement.getLocator().toString();
if (parent != null) {
toString += " child of " + parent;
}
if (hasName()) {
String realName = name;
if (index!=-1) {
realName += "_"+index;
}
toString = ">" + realName + "< (" + toString + ")";
}
if (hasFrameLogic()) {
String frameString = " inside Frames={";
if (frameLogic.hasFrames()) {
for (GuiElement frame : frameLogic.getFrames()) {
frameString += frame.toString() + ", ";
}
} else {
frameString += "autodetect, ";
}
frameString = frameString.substring(0, frameString.length() - 2);
toString = toString + frameString + "}";
}
return toString;
}
public boolean hasFrameLogic() {
return frameLogic != null;
}
public LogLevel getLogLevel() {
return logLevel;
}
public void setLogLevel(LogLevel logLevel) {
// store previous log level away
this.storedLogLevel = this.logLevel;
// set new log level
this.logLevel = logLevel;
}
public void resetLogLevel() {
this.logLevel = this.storedLogLevel;
}
}
| 31.934426 | 98 | 0.623717 |
ab9900fb591dd7982f76869d733b48403b3abe04 | 1,675 | package de.ellpeck.naturesaura.compat.patchouli;
import de.ellpeck.naturesaura.recipes.AltarRecipe;
import net.minecraft.item.crafting.Ingredient;
import vazkii.patchouli.api.IComponentProcessor;
import vazkii.patchouli.api.IVariable;
import vazkii.patchouli.api.IVariableProvider;
public class ProcessorAltar implements IComponentProcessor {
private AltarRecipe recipe;
@Override
public void setup(IVariableProvider provider) {
this.recipe = PatchouliCompat.getRecipe("altar", provider.get("recipe").asString());
}
@Override
public IVariable process(String key) {
if (this.recipe == null)
return null;
switch (key) {
case "input":
return PatchouliCompat.ingredientVariable(this.recipe.input);
case "output":
return IVariable.from(this.recipe.output);
case "catalyst":
if (this.recipe.catalyst != Ingredient.EMPTY)
return PatchouliCompat.ingredientVariable(this.recipe.catalyst);
else
return null;
case "type":
if (this.recipe.requiredType != null)
return IVariable.from(this.recipe.getDimensionBottle());
else
return null;
case "name":
return IVariable.wrap(this.recipe.output.getDisplayName().getString());
default:
return null;
}
}
@Override
public boolean allowRender(String group) {
return group.isEmpty() || group.equals(this.recipe.catalyst == Ingredient.EMPTY ? "altar" : "catalyst");
}
}
| 34.183673 | 112 | 0.615522 |
e1e0f1b808df906c23dd7760fa73189d7fb22b43 | 1,015 | package cn.cococode.cc150;
public class Joseph {
public int getResult1(int n, int m) {
if (n < 0 || m < 2) {
return 0;
}
if (n == 1) {
return 1;
}
ListNode head = new ListNode(0);
ListNode node = head;
for (int i = 1; i <=n; ++i){
node.next = new ListNode(i);
node = node.next;
}
node.next = head.next;
node = head.next;
while (node.next != node){
for (int i = 1; i < m-1; ++i){
node = node.next;
}
node.next = node.next.next;
node = node.next;
}
return node.val;
}
public int getResult(int n) {
if (n <= 1) {
return 1;
}
ListNode head = new ListNode(0);
ListNode node = head;
for (int i = 1; i <=n; ++i){
node.next = new ListNode(i);
node = node.next;
}
node.next = head.next;
node = head.next;
return 1;
}
}
| 20.3 | 41 | 0.431527 |
558ea3e77bb1b5ef36fff6dd5fc29ffd0594e5cb | 8,332 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.flink.source;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.config.TableConfigOptions;
import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;
import org.apache.iceberg.DataFile;
import org.apache.iceberg.Table;
import org.apache.iceberg.TestHelpers;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.data.GenericAppenderHelper;
import org.apache.iceberg.data.RandomGenericData;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.expressions.Expression;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.flink.FlinkTableOptions;
import org.apache.iceberg.flink.TableLoader;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
/**
* Test Flink SELECT SQLs.
*/
public class TestFlinkScanSql extends TestFlinkScan {
private volatile TableEnvironment tEnv;
public TestFlinkScanSql(String fileFormat) {
super(fileFormat);
}
@Override
public void before() throws IOException {
super.before();
sql("create catalog iceberg_catalog with ('type'='iceberg', 'catalog-type'='hadoop', 'warehouse'='%s')", warehouse);
sql("use catalog iceberg_catalog");
getTableEnv().getConfig().getConfiguration().set(TableConfigOptions.TABLE_DYNAMIC_TABLE_OPTIONS_ENABLED, true);
}
private TableEnvironment getTableEnv() {
if (tEnv == null) {
synchronized (this) {
if (tEnv == null) {
this.tEnv = TableEnvironment.create(EnvironmentSettings
.newInstance()
.useBlinkPlanner()
.inBatchMode().build());
}
}
}
return tEnv;
}
@Override
protected List<Row> run(FlinkSource.Builder formatBuilder, Map<String, String> sqlOptions, String sqlFilter,
String... sqlSelectedFields) {
String select = String.join(",", sqlSelectedFields);
StringBuilder builder = new StringBuilder();
sqlOptions.forEach((key, value) -> builder.append(optionToKv(key, value)).append(","));
String optionStr = builder.toString();
if (optionStr.endsWith(",")) {
optionStr = optionStr.substring(0, optionStr.length() - 1);
}
if (!optionStr.isEmpty()) {
optionStr = String.format("/*+ OPTIONS(%s)*/", optionStr);
}
return sql("select %s from t %s %s", select, optionStr, sqlFilter);
}
@Test
public void testResiduals() throws Exception {
Table table = catalog.createTable(TableIdentifier.of("default", "t"), SCHEMA, SPEC);
List<Record> writeRecords = RandomGenericData.generate(SCHEMA, 2, 0L);
writeRecords.get(0).set(1, 123L);
writeRecords.get(0).set(2, "2020-03-20");
writeRecords.get(1).set(1, 456L);
writeRecords.get(1).set(2, "2020-03-20");
GenericAppenderHelper helper = new GenericAppenderHelper(table, fileFormat, TEMPORARY_FOLDER);
List<Record> expectedRecords = Lists.newArrayList();
expectedRecords.add(writeRecords.get(0));
DataFile dataFile1 = helper.writeFile(TestHelpers.Row.of("2020-03-20", 0), writeRecords);
DataFile dataFile2 = helper.writeFile(TestHelpers.Row.of("2020-03-21", 0),
RandomGenericData.generate(SCHEMA, 2, 0L));
helper.appendToTable(dataFile1, dataFile2);
Expression filter = Expressions.and(Expressions.equal("dt", "2020-03-20"), Expressions.equal("id", 123));
assertRecords(runWithFilter(filter, "where dt='2020-03-20' and id=123"), expectedRecords, SCHEMA);
}
@Test
public void testInferedParallelism() throws IOException {
Table table = catalog.createTable(TableIdentifier.of("default", "t"), SCHEMA, SPEC);
TableLoader tableLoader = TableLoader.fromHadoopTable(table.location());
FlinkInputFormat flinkInputFormat = FlinkSource.forRowData().tableLoader(tableLoader).table(table).buildFormat();
ScanContext scanContext = ScanContext.builder().build();
// Empty table, infer parallelism should be at least 1
int parallelism = FlinkSource.forRowData().inferParallelism(flinkInputFormat, scanContext);
Assert.assertEquals("Should produce the expected parallelism.", 1, parallelism);
GenericAppenderHelper helper = new GenericAppenderHelper(table, fileFormat, TEMPORARY_FOLDER);
DataFile dataFile1 = helper.writeFile(TestHelpers.Row.of("2020-03-20", 0),
RandomGenericData.generate(SCHEMA, 2, 0L));
DataFile dataFile2 = helper.writeFile(TestHelpers.Row.of("2020-03-21", 0),
RandomGenericData.generate(SCHEMA, 2, 0L));
helper.appendToTable(dataFile1, dataFile2);
// Make sure to generate 2 CombinedScanTasks
long maxFileLen = Math.max(dataFile1.fileSizeInBytes(), dataFile2.fileSizeInBytes());
sql("ALTER TABLE t SET ('read.split.open-file-cost'='1', 'read.split.target-size'='%s')", maxFileLen);
// 2 splits (max infer is the default value 100 , max > splits num), the parallelism is splits num : 2
parallelism = FlinkSource.forRowData().inferParallelism(flinkInputFormat, scanContext);
Assert.assertEquals("Should produce the expected parallelism.", 2, parallelism);
// 2 splits and limit is 1 , max infer parallelism is default 100,
// which is greater than splits num and limit, the parallelism is the limit value : 1
parallelism = FlinkSource.forRowData().inferParallelism(flinkInputFormat, ScanContext.builder().limit(1).build());
Assert.assertEquals("Should produce the expected parallelism.", 1, parallelism);
// 2 splits and max infer parallelism is 1 (max < splits num), the parallelism is 1
Configuration configuration = new Configuration();
configuration.setInteger(FlinkTableOptions.TABLE_EXEC_ICEBERG_INFER_SOURCE_PARALLELISM_MAX, 1);
parallelism = FlinkSource.forRowData()
.flinkConf(configuration)
.inferParallelism(flinkInputFormat, ScanContext.builder().build());
Assert.assertEquals("Should produce the expected parallelism.", 1, parallelism);
// 2 splits, max infer parallelism is 1, limit is 3, the parallelism is max infer parallelism : 1
parallelism = FlinkSource.forRowData()
.flinkConf(configuration)
.inferParallelism(flinkInputFormat, ScanContext.builder().limit(3).build());
Assert.assertEquals("Should produce the expected parallelism.", 1, parallelism);
// 2 splits, infer parallelism is disabled, the parallelism is flink default parallelism 1
configuration.setBoolean(FlinkTableOptions.TABLE_EXEC_ICEBERG_INFER_SOURCE_PARALLELISM, false);
parallelism = FlinkSource.forRowData()
.flinkConf(configuration)
.inferParallelism(flinkInputFormat, ScanContext.builder().limit(3).build());
Assert.assertEquals("Should produce the expected parallelism.", 1, parallelism);
}
private List<Row> sql(String query, Object... args) {
TableResult tableResult = getTableEnv().executeSql(String.format(query, args));
try (CloseableIterator<Row> iter = tableResult.collect()) {
List<Row> results = Lists.newArrayList(iter);
return results;
} catch (Exception e) {
throw new RuntimeException("Failed to collect table result", e);
}
}
private String optionToKv(String key, Object value) {
return "'" + key + "'='" + value + "'";
}
}
| 43.170984 | 120 | 0.728157 |
2708662f47705a74e22a07acf42099ce3e817abd | 5,588 | package com.diviso.graeshoppe.client.product.model;
import java.util.Objects;
import com.diviso.graeshoppe.client.product.model.Product;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* Category
*/
@Validated
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2019-10-28T15:55:43.394+05:30[Asia/Kolkata]")
@Document(indexName = "category")
public class Category {
@JsonProperty("description")
private String description = null;
@JsonProperty("iDPcode")
private String iDPcode = null;
@JsonProperty("id")
private Long id = null;
@JsonProperty("image")
private byte[] image = null;
@JsonProperty("imageContentType")
private String imageContentType = null;
@JsonProperty("name")
private String name = null;
@JsonProperty("products")
@Valid
private List<Product> products = null;
public Category description(String description) {
this.description = description;
return this;
}
/**
* Get description
* @return description
**/
@ApiModelProperty(value = "")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Category iDPcode(String iDPcode) {
this.iDPcode = iDPcode;
return this;
}
/**
* Get iDPcode
* @return iDPcode
**/
@ApiModelProperty(value = "")
public String getIDPcode() {
return iDPcode;
}
public void setIDPcode(String iDPcode) {
this.iDPcode = iDPcode;
}
public Category id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Category image(byte[] image) {
this.image = image;
return this;
}
/**
* Get image
* @return image
**/
@ApiModelProperty(value = "")
@Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$")
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public Category imageContentType(String imageContentType) {
this.imageContentType = imageContentType;
return this;
}
/**
* Get imageContentType
* @return imageContentType
**/
@ApiModelProperty(value = "")
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public Category name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category products(List<Product> products) {
this.products = products;
return this;
}
public Category addProductsItem(Product productsItem) {
if (this.products == null) {
this.products = new ArrayList<Product>();
}
this.products.add(productsItem);
return this;
}
/**
* Get products
* @return products
**/
@ApiModelProperty(value = "")
@Valid
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(this.description, category.description) &&
Objects.equals(this.iDPcode, category.iDPcode) &&
Objects.equals(this.id, category.id) &&
Objects.equals(this.image, category.image) &&
Objects.equals(this.imageContentType, category.imageContentType) &&
Objects.equals(this.name, category.name) &&
Objects.equals(this.products, category.products);
}
@Override
public int hashCode() {
return Objects.hash(description, iDPcode, id, image, imageContentType, name, products);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" iDPcode: ").append(toIndentedString(iDPcode)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" image: ").append(toIndentedString(image)).append("\n");
sb.append(" imageContentType: ").append(toIndentedString(imageContentType)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" products: ").append(toIndentedString(products)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 22.623482 | 141 | 0.658912 |
17a4b1a29a1be5539c0c525cf17422b111e89cad | 3,788 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataprep.transformation.actions.delete;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.StringUtils.EMPTY;
import static org.talend.dataprep.api.type.Type.NUMERIC;
import static org.talend.dataprep.api.type.Type.STRING;
import static org.talend.dataprep.parameters.Parameter.parameter;
import static org.talend.dataprep.parameters.ParameterType.REGEX;
import static org.talend.dataprep.transformation.api.action.context.ActionContext.ActionStatus.OK;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import org.talend.dataprep.api.action.Action;
import org.talend.dataprep.api.dataset.ColumnMetadata;
import org.talend.dataprep.api.dataset.row.DataSetRow;
import org.talend.dataprep.api.type.Type;
import org.talend.dataprep.parameters.Parameter;
import org.talend.dataprep.transformation.actions.common.ActionsUtils;
import org.talend.dataprep.transformation.actions.common.ReplaceOnValueHelper;
import org.talend.dataprep.transformation.api.action.context.ActionContext;
/**
* Delete row on a given value.
*/
@Action(DeleteOnValue.DELETE_ON_VALUE_ACTION_NAME)
public class DeleteOnValue extends AbstractDelete {
/**
* The action name.
*/
public static final String DELETE_ON_VALUE_ACTION_NAME = "delete_on_value"; //$NON-NLS-1$
/**
* Name of the parameter needed.
*/
public static final String VALUE_PARAMETER = "value"; //$NON-NLS-1$
private static final boolean CREATE_NEW_COLUMN_DEFAULT = false;
@Override
public String getName() {
return DELETE_ON_VALUE_ACTION_NAME;
}
@Override
@Nonnull
public List<Parameter> getParameters(Locale locale) {
final List<Parameter> parameters = super.getParameters(locale);
parameters.add(parameter(locale).setName(VALUE_PARAMETER).setType(REGEX).setDefaultValue(EMPTY).build(this));
return parameters;
}
@Override
public boolean acceptField(ColumnMetadata column) {
return STRING.equals(Type.get(column.getType())) || NUMERIC.isAssignableFrom(Type.get(column.getType()));
}
@Override
public void compile(ActionContext actionContext) {
super.compile(actionContext);
if (ActionsUtils.doesCreateNewColumn(actionContext.getParameters(), CREATE_NEW_COLUMN_DEFAULT)) {
ActionsUtils.createNewColumn(actionContext, singletonList(ActionsUtils.additionalColumn()));
}
if (actionContext.getActionStatus() == OK) {
final Map<String, String> parameters = actionContext.getParameters();
final ReplaceOnValueHelper regexParametersHelper = new ReplaceOnValueHelper();
actionContext.get("replaceOnValue", p -> regexParametersHelper.build(parameters.get(VALUE_PARAMETER), true));
}
}
/**
* @see AbstractDelete#toDelete(DataSetRow, String, ActionContext)
*/
@Override
public boolean toDelete(DataSetRow dataSetRow, String columnId, ActionContext context) {
try {
final ReplaceOnValueHelper helper = context.get("replaceOnValue");
return helper.matches(dataSetRow.get(columnId));
} catch (IllegalArgumentException e) {
return false;
}
}
}
| 37.50495 | 121 | 0.704065 |
47b4789b15b43c541ec835aca646bab665b89bda | 2,234 | package jetbrains.mps.baseLanguage.javadoc.textGen;
/*Generated by MPS */
import jetbrains.mps.text.rt.TextGenDescriptorBase;
import jetbrains.mps.text.rt.TextGenContext;
import jetbrains.mps.text.impl.TextGenSupport;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SConcept;
public class ClassifierDocComment_TextGen extends TextGenDescriptorBase {
@Override
public void generateText(final TextGenContext ctx) {
final TextGenSupport tgs = new TextGenSupport(ctx);
DocCommentTextGen.docCommentStart(ctx.getPrimaryInput(), ctx);
for (SNode item : ListSequence.fromList(SLinkOperations.getChildren(ctx.getPrimaryInput(), LINKS.tags$stUD)).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return SNodeOperations.isInstanceOf(it, CONCEPTS.ParameterBlockDocTag$ie);
}
})) {
tgs.appendNode(item);
}
for (SNode item : SLinkOperations.getChildren(ctx.getPrimaryInput(), LINKS.param$Wb3e)) {
tgs.appendNode(item);
}
DocCommentTextGen.docCommentEnd(ctx.getPrimaryInput(), ctx);
tgs.appendAttributedNode();
}
private static final class LINKS {
/*package*/ static final SContainmentLink tags$stUD = MetaAdapterFactory.getContainmentLink(0xf280165065d5424eL, 0xbb1b463a8781b786L, 0x4a3c146b7fae70d3L, 0x4ab5c2019ddc99f3L, "tags");
/*package*/ static final SContainmentLink param$Wb3e = MetaAdapterFactory.getContainmentLink(0xf280165065d5424eL, 0xbb1b463a8781b786L, 0x1cb65d9fe66a764cL, 0x1cb65d9fe66a764eL, "param");
}
private static final class CONCEPTS {
/*package*/ static final SConcept ParameterBlockDocTag$ie = MetaAdapterFactory.getConcept(0xf280165065d5424eL, 0xbb1b463a8781b786L, 0x757ba20a4c905f8aL, "jetbrains.mps.baseLanguage.javadoc.structure.ParameterBlockDocTag");
}
}
| 47.531915 | 226 | 0.79812 |
aaca36ef2667b0f08ab5f134e1b562c9b3e81849 | 1,080 | package org.innovateuk.ifs.commons.exception;
import java.util.List;
import static java.util.Collections.emptyList;
public class ForbiddenActionException extends IFSRuntimeException {
public ForbiddenActionException() {
// no-arg constructor
}
public ForbiddenActionException(String message) {
super(message, emptyList());
}
public ForbiddenActionException(List<Object> arguments) {
super(arguments);
}
public ForbiddenActionException(String message, List<Object> arguments) {
super(message, arguments);
}
public ForbiddenActionException(String message, Throwable cause, List<Object> arguments) {
super(message, cause, arguments);
}
public ForbiddenActionException(Throwable cause, List<Object> arguments) {
super(cause, arguments);
}
public ForbiddenActionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, List<Object> arguments) {
super(message, cause, enableSuppression, writableStackTrace, arguments);
}
}
| 29.189189 | 149 | 0.725926 |
d971225dec728bddd7f9b1bcedb576a33f293305 | 904 | package com.komaxx.komaxx_gl.threading;
/**
* Everything that wants to be executed in an OnScreenHandlerThread
* needs to extend this class. <br>
* <b>NOTE</b>: When the bound activity is not in front, this AOnScreenRunnable
* will *not* be executed but discarded (you get a message, though).
*
* @author Matthias Schicker
*/
public abstract class AOnScreenRunnable implements Runnable {
private OnScreenHandlerThread handlerThread;
void setHandlerThread(OnScreenHandlerThread t){
handlerThread = t;
}
@Override
public final void run() {
if (handlerThread.isRunning()) doRun();
else discarded();
}
/**
* Called, when the bound activity is not in front when this runnable
* should be executed. Will NOT be rescheduled automatically.
*/
protected abstract void discarded();
/**
* Same as <code>run</code> in normal Runnables.
*/
protected abstract void doRun();
}
| 25.828571 | 79 | 0.725664 |
ac8680dca0559dcaa4866a523b0d8a5530d4e771 | 1,399 | /**
* Copyright (c) 2021 Hali Lev Ari or General Angels
* // TODO: add github
*/
package com.ga2230.Idan.base.messages.builtins.primitives;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.ga2230.Idan.base.messages.RosVariable;
/**
* Represents a short or int16
*/
public class Short16 extends RosVariable {
public short data;
/**
* Construct the Short16 variable
*
* @param data The short value
*/
public Short16(short data) {
this.data = data;
}
/**
* Construct the Short16 variable from bytes
*
* @param data serialized data
*/
public Short16(byte[] data) {
unpack(data);
}
/**
* Serializes the short
*
* @return The bytes array from the short
*/
@Override
public byte[] pack() {
ByteBuffer buff = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
buff.putShort(data);
return buff.array();
}
/**
* Deserializes the short
*
* @param serialized The serialized short
*/
@Override
public void unpack(byte[] serialized) {
this.data = ByteBuffer.wrap(serialized).order(ByteOrder.LITTLE_ENDIAN).getShort();
}
/**
* Returns the data
*
* @return The object stringified
*/
@Override
public String toString() {
return "" + data;
}
}
| 19.985714 | 90 | 0.59614 |
f173a9739d6d210b0effe36d096fbb823a26171b | 25,812 | package formal_testing.main;
import formal_testing.*;
import formal_testing.coverage.CoveragePoint;
import formal_testing.coverage.FlowCoveragePoint;
import formal_testing.coverage.FormulaCoveragePoint;
import formal_testing.enums.Language;
import formal_testing.formula.BinaryOperator;
import formal_testing.formula.LTLFormula;
import formal_testing.formula.UnaryOperator;
import formal_testing.generated.nusmv_ltlLexer;
import formal_testing.generated.nusmv_ltlParser;
import formal_testing.runner.Runner;
import formal_testing.runner.RunnerResult;
import formal_testing.value.BooleanValue;
import formal_testing.value.IntegerValue;
import formal_testing.value.Value;
import formal_testing.variable.BooleanVariable;
import formal_testing.variable.IntegerVariable;
import formal_testing.variable.SetVariable;
import formal_testing.variable.Variable;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
import org.apache.commons.lang3.tuple.Pair;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.BooleanOptionHandler;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
abstract class MainBase {
@Option(name = "--language", aliases = { "-l" }, usage = "PROMELA, NUSMV, NUXMV", metaVar = "<language>",
required = true)
private String language;
@Option(name = "--panO", usage = "optimization level to compile pan, default = 2", metaVar = "<number>")
private int panO = 2;
@Option(name = "--dynamic", handler = BooleanOptionHandler.class, usage = "enable NuSMV -dynamic")
private boolean dynamic;
@Option(name = "--coi", handler = BooleanOptionHandler.class, usage = "enable NuSMV -coi")
private boolean coi;
ProblemData data;
static void fillRandom(TestSuite ts, ProblemData data, Long seed, int length, int number) {
final Random random = seed == null ? new Random() : new Random(seed);
final List<List<? extends Value>> allValues = data.conf.nondetVars.stream()
.map(Variable::values).collect(Collectors.toList());
for (int i = 0; i < number; i++) {
final TestCase tc = new TestCase(data.conf, false);
for (int j = 0; j < length; j++) {
for (int k = 0; k < data.conf.nondetVars.size(); k++) {
final Variable<?> var = data.conf.nondetVars.get(k);
tc.addValue(var.indexedName(), allValues.get(k).get(random.nextInt(allValues.get(k).size())));
}
}
ts.add(tc);
}
}
private void setup() {
try {
Settings.LANGUAGE = Language.valueOf(language);
System.out.println("Language: " + Settings.LANGUAGE);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Unsupported language " + language);
}
Settings.PAN_OPTIMIZATION_LEVEL = panO;
Settings.NUSMV_DYNAMIC = dynamic;
Settings.NUSMV_COI = coi;
}
protected abstract void launcher() throws IOException, InterruptedException;
void run(String[] args) {
if (!parseArgs(args)) {
return;
}
setup();
try {
launcher();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
}
private boolean parseArgs(String[] args) {
final CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
return true;
} catch (CmdLineException e) {
System.out.print("Usage: java -jar <jar filename> ");
parser.printSingleLineUsage(System.out);
System.out.println();
parser.printUsage(System.out);
return false;
}
}
void loadData(String configurationFilename, String headerFilename, String plantModelFilename,
String controllerModelFilename, String specFilename) throws IOException {
final Configuration conf = Configuration.fromFile(configurationFilename);
System.out.println("Configuration:");
System.out.println(conf);
System.out.println();
data = new ProblemData(conf,
new String(Files.readAllBytes(Paths.get(headerFilename))),
new String(Files.readAllBytes(Paths.get(plantModelFilename))),
new String(Files.readAllBytes(Paths.get(controllerModelFilename))),
new String(Files.readAllBytes(Paths.get(specFilename)))
);
}
private List<String> propsFromCode(String code) {
return Settings.LANGUAGE == Language.PROMELA ? promelaPropsFromCode(code) : nuSMVPropsFromCode(code);
}
private List<String> promelaPropsFromCode(String code) {
return Arrays.stream(code.split("\n"))
.filter(s -> s.matches("ltl .*\\{.*\\}.*"))
.map(s -> s.replaceAll("^ltl ", "").replaceAll(" .*$", ""))
.collect(Collectors.toList());
}
private List<String> nuSMVPropsFromCode(String code) {
return Arrays.stream(code.split("\n")).filter(s -> s.matches("[A-Z]+SPEC .*")).collect(Collectors.toList());
}
private String nondetSelectionPromela() {
final StringBuilder sb = new StringBuilder();
for (Variable<?> var : data.conf.nondetVars) {
sb.append("if\n");
for (String value : var.stringValues()) {
sb.append(":: ").append(var.indexedName()).append(" = ").append(value).append(";\n");
}
sb.append("fi\n");
}
return sb.toString();
}
private List<FormulaCoveragePoint> specCoveragePoints(String nusmvSpecCoverage) {
final Set<LTLFormula> subformulas = new LinkedHashSet<>();
class MyRecognitionException extends RuntimeException {
MyRecognitionException(String message) {
super(message);
}
}
try (BufferedReader reader = new BufferedReader(new FileReader(new File(nusmvSpecCoverage)))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.replaceAll("--.*$", "").trim();
if (!line.startsWith("LTLSPEC ")) {
continue;
}
//System.out.println(line);
try (InputStream in = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8))) {
final nusmv_ltlLexer lexer = new nusmv_ltlLexer(CharStreams.fromStream(in, StandardCharsets.UTF_8));
final CommonTokenStream tokens = new CommonTokenStream(lexer);
final nusmv_ltlParser parser = new nusmv_ltlParser(tokens);
parser.addErrorListener(new ANTLRErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object o, int i, int i1, String s,
RecognitionException e) {
throw new MyRecognitionException("syntaxError");
}
@Override
public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean b, BitSet bitSet,
ATNConfigSet atnConfigSet) {
throw new MyRecognitionException("reportAmbiguity");
}
@Override
public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitSet,
ATNConfigSet atnConfigSet) {
throw new MyRecognitionException("reportAttemptingFullContext");
}
@Override
public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2,
ATNConfigSet atnConfigSet) {
throw new MyRecognitionException("reportContextSensitivity");
}
});
try {
final LTLFormula f = parser.formula().f;
f.allBooleanSubformulas(subformulas);
} catch (NullPointerException | RecognitionException e) {
e.printStackTrace();
} catch (MyRecognitionException e) {
System.err.println("LTL parse error: " + e.getMessage()
+ " (may be connected with support of a reduced subset of LTL)");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// add negations
subformulas.addAll(subformulas.stream().map(f -> f instanceof UnaryOperator
? ((UnaryOperator) f).argument : new UnaryOperator("!", f)).collect(Collectors.toList()));
return subformulas.stream().map(FormulaCoveragePoint::new).collect(Collectors.toList());
}
private List<CoveragePoint> coveragePoints(boolean includeInternal, boolean valuePairCoverage, int coverageClaims,
String nusmvSpecCoverage, int maxGoals) {
final List<Variable> variables = new ArrayList<>();
variables.addAll(data.conf.inputVars);
variables.addAll(data.conf.nondetVars);
variables.addAll(data.conf.outputVars);
if (includeInternal) {
variables.addAll(data.conf.plantInternalVars);
variables.addAll(data.conf.controllerInternalVars);
}
final List<FormulaCoveragePoint> formulas = new ArrayList<>();
if (valuePairCoverage && variables.size() > 1) {
for (int i = 0; i < variables.size(); i++) {
final Variable<?> varI = variables.get(i);
final List<LTLFormula> listI = oneVariableGoalFormulas(varI, maxGoals);
for (int j = i + 1; j < variables.size(); j++) {
final Variable<?> varJ = variables.get(j);
final List<LTLFormula> listJ = oneVariableGoalFormulas(varJ, maxGoals);
for (LTLFormula fI : listI) {
for (LTLFormula fJ : listJ) {
formulas.add(new FormulaCoveragePoint(new BinaryOperator("&", fI, fJ)));
}
}
}
}
// TODO add equivalence classes for pair coverage (if this is ever needed)
// TODO maybe remove pair coverage completely?
} else {
for (Variable<?> var : variables) {
final Set<CoveragePoint> cps = oneVariableGoalFormulas(var, maxGoals).stream()
.map(FormulaCoveragePoint::new).collect(Collectors.toCollection(LinkedHashSet::new));
for (CoveragePoint cp : cps) {
final FormulaCoveragePoint casted = (FormulaCoveragePoint) cp;
casted.setEquivalenceClass(cps);
formulas.add(casted);
}
}
}
if (nusmvSpecCoverage != null) {
formulas.addAll(specCoveragePoints(nusmvSpecCoverage));
}
// filter out equal FORMULA coverage points
final Map<String, FormulaCoveragePoint> unique = new LinkedHashMap<>();
for (FormulaCoveragePoint cp : formulas) {
final String key = cp.toString();
if (!unique.containsKey(key)) {
unique.put(key, cp);
}
}
final List<CoveragePoint> result = new ArrayList<>(unique.values());
for (int i = 0; i < coverageClaims; i++) {
result.add(new FlowCoveragePoint(i));
}
return result;
}
private List<LTLFormula> oneVariableGoalFormulas(Variable<?> var, int maxGoals) {
final List<? extends Value> values = var.values();
final List<LTLFormula> result = new ArrayList<>();
if (values.size() < maxGoals || !(var instanceof IntegerVariable)) {
values.forEach(value -> result.add(LTLFormula.equality(var, value)));
} else {
for (int i = 0; i < maxGoals; i++) {
final int fromIndex = i * values.size() / maxGoals;
final int toIndex = (i + 1) * values.size() / maxGoals - 1;
result.add(LTLFormula.between(var, values.get(fromIndex), values.get(toIndex)));
}
}
return result;
}
private String varFormat(String s, String indent) {
return s.isEmpty() ? "" : (indent + s + "\n");
}
private void printVars(StringBuilder sb, String indent, List<Variable<?>> variables, String text) {
if (!variables.isEmpty()) {
sb.append(indent).append(Settings.LANGUAGE.commentSymbol).append(" ").append(text).append("\n");
}
variables.forEach(v -> sb.append(varFormat(v.toLanguageString(), indent)));
}
private void printAllVars(StringBuilder sb, String indent) {
printVars(sb, indent, data.conf.inputVars, "Inputs");
printVars(sb, indent, data.conf.outputVars, "Outputs");
printVars(sb, indent, data.conf.nondetVars, "Nondeterministic variables");
printVars(sb, indent, data.conf.plantInternalVars, "Plant internal variables");
printVars(sb, indent, data.conf.controllerInternalVars, "Controller internal variables");
}
private Pair<String, Integer> promelaInstrument(String code, int firstClaimIndex) {
int nextClaimIndex = firstClaimIndex;
final Pattern p = Pattern.compile("::");
final Matcher m = p.matcher(code);
final StringBuilder transformed = new StringBuilder();
int lastPos = 0;
while (m.find()) {
transformed.append(code, lastPos, m.end());
int index = m.end();
int balance = 0;
while (index < code.length()) {
char cCur = code.charAt(index);
char cLast = code.charAt(index - 1);
balance += cCur == '(' ? 1 : cCur == ')' ? -1 : 0;
if (balance == 0 && cLast == '-' && cCur == '>') {
transformed.append(code, m.end(), index + 1).append(" _cover[")
.append(nextClaimIndex++).append("] = true; ");
break;
}
index++;
}
lastPos = index + 1;
}
transformed.append(code.substring(lastPos));
return Pair.of(transformed.toString(), nextClaimIndex);
}
String modelCode(boolean testing, boolean nondetSelection, boolean spec, String testHeader,
String testBody, boolean plantCodeCoverage, boolean controllerCodeCoverage,
CodeCoverageCounter counter, boolean includePrintf) {
return Settings.LANGUAGE == Language.PROMELA
? promelaModelCode(testing, nondetSelection, spec, testHeader, testBody, plantCodeCoverage,
controllerCodeCoverage, counter, includePrintf)
: nuSMVModelCode(testing, spec, testHeader, testBody);
}
private final BooleanVariable testingVar = new BooleanVariable("_test_passed", BooleanValue.FALSE);
private final Variable<?> testIndexVar = new IntegerVariable("_test_index", new IntegerValue(0), 0, 1, false, 1, 0);
private final Variable<?> testStepVar = new IntegerVariable("_test_step", new IntegerValue(0), 0, 1, false, 1, 0);
private String nuSMVModelCode(boolean testing, boolean spec, String testHeader, String testBody) {
final StringBuilder code = new StringBuilder();
// can contain e.g. some module declarations
if (!data.header.isEmpty()) {
code.append(data.header).append("\n");
}
final String nondetArgList = Util.argList(Arrays.asList(data.conf.nondetVars,
testBody != null ? Arrays.asList(testIndexVar, testStepVar) : Collections.emptyList(),
testing ? Collections.singletonList(testingVar) : Collections.emptyList()));
code.append("MODULE _NONDET_VAR_SELECTION").append(nondetArgList).append("\n");
if (testBody != null) {
code.append(testBody);
}
code.append("\n");
code.append("MODULE _PLANT").append(Util.argList(Arrays.asList(data.conf.inputVars, data.conf.nondetVars,
data.conf.plantInternalVars, data.conf.outputVars))).append("\n")
.append(Util.indent(data.plantModel)).append("\n\n");
code.append("MODULE _CONTROLLER").append(Util.argList(Arrays.asList(data.conf.inputVars,
data.conf.controllerInternalVars, data.conf.outputVars))).append("\n")
.append(Util.indent(data.controllerModel)).append("\n\n");
code.append("MODULE main\n").append("VAR\n");
printAllVars(code, " ");
code.append(" -- Misc\n");
if (testing) {
code.append(varFormat(testingVar.toNusmvString(), " "));
}
code.append(" _nondet_var_selection: _NONDET_VAR_SELECTION").append(nondetArgList).append(";\n");
code.append(" _plant: _PLANT").append(Util.argList(Arrays.asList(data.conf.inputVars, data.conf.nondetVars,
data.conf.plantInternalVars, data.conf.outputVars))).append(";\n");
code.append(" _controller: _CONTROLLER").append(Util.argList(Arrays.asList(data.conf.inputVars,
data.conf.controllerInternalVars, data.conf.outputVars))).append(";\n");
if (testHeader != null) {
code.append(testHeader).append("\n");
}
code.append("ASSIGN\n");
for (Variable<?> var : Util.merge(Arrays.asList(data.conf.inputVars, data.conf.nondetVars,
data.conf.controllerInternalVars, data.conf.plantInternalVars, data.conf.outputVars,
testing ? Collections.singletonList(testingVar) : Collections.emptyList()))) {
code.append(" init(").append(var.indexedName()).append(") := ")
.append(var.initialValue()).append(";\n");
}
if (spec) {
code.append("\n").append(data.spec);
}
if (testing) {
code.append("\nCTLSPEC AF _test_passed\n");
}
return code.toString();
}
private void promelaPrintf(StringBuilder sb, String indent) {
sb.append(indent).append("d_step {\n");
sb.append(indent).append(" printf(\"\\n -> New State <-\\n\");\n");
for (Variable<?> var : data.conf.allVariables()) {
final String symbol = var instanceof SetVariable ? "e" : "d";
sb.append(indent).append(" printf(\"").append(var.indexedName()).append(" = %").append(symbol)
.append("\\n\", ").append(var.indexedName()).append(");\n");
}
sb.append(indent).append("}\n");
}
private String promelaModelCode(boolean testing, boolean nondetSelection, boolean spec, String testHeader,
String testBody, boolean plantCodeCoverage, boolean controllerCodeCoverage,
CodeCoverageCounter counter, boolean includePrintf) {
final StringBuilder code = new StringBuilder();
final Set<String> mtypeValues = new LinkedHashSet<>();
Util.merge(Arrays.asList(data.conf.inputVars, data.conf.outputVars, data.conf.nondetVars,
data.conf.plantInternalVars, data.conf.controllerInternalVars)).stream()
.filter(v -> v instanceof SetVariable).forEach(v -> mtypeValues.addAll(v.stringValues()));
if (!mtypeValues.isEmpty()) {
code.append("mtype ").append(mtypeValues.toString().replace("[", "{").replace("]", "}")).append("\n");
}
printAllVars(code, "");
int coverageClaims = 0;
String plantCode = data.plantModel;
if (plantCodeCoverage) {
final Pair<String, Integer> p = promelaInstrument(plantCode, coverageClaims);
plantCode = p.getKey();
coverageClaims = p.getValue();
}
String controllerCode = data.controllerModel;
if (controllerCodeCoverage) {
final Pair<String, Integer> p = promelaInstrument(controllerCode, coverageClaims);
controllerCode = p.getKey();
coverageClaims = p.getValue();
}
if (coverageClaims > 0) {
code.append("\n").append("bool _cover[").append(coverageClaims).append("];\n");
}
if (testing) {
code.append("\n").append(varFormat(testingVar.toPromelaString(), ""));
}
code.append("\n").append(data.header);
if (testHeader != null) {
code.append("\n").append(testHeader);
}
code.append("\n").append("\n").append("init { do :: atomic {\n");
if (nondetSelection) {
code.append(Util.indent(nondetSelectionPromela())).append("\n");
}
if (testBody != null) {
code.append(Util.indent(testBody)).append("\n");
}
code.append("\n").append(Util.indent(plantCode)).append("\n\n")
.append(Util.indent(controllerCode)).append("\n");
if (includePrintf) {
promelaPrintf(code, " ");
}
code.append("} od }\n");
if (spec) {
code.append("\n").append(data.spec);
}
if (testing) {
code.append("\n").append("ltl test_passed { <>_test_passed }\n");
}
if (counter != null) {
counter.coverageClaims = coverageClaims;
}
return code.toString();
}
String usualModelCode(CodeCoverageCounter counter, boolean plantCodeCoverage, boolean controllerCodeCoverage) {
return modelCode(false, true, false, null, null, plantCodeCoverage, controllerCodeCoverage, counter, false);
}
int examineTestCase(TestCase tc, List<CoveragePoint> coveragePoints, Integer steps, boolean plantCodeCoverage,
boolean controllerCodeCoverage) throws IOException {
final List<CoveragePoint> uncovered = coveragePoints.stream().filter(cp -> !cp.covered())
.collect(Collectors.toList());
final String code = modelCode(false, false, false, tc.header(false), tc.body(false, data.conf),
plantCodeCoverage, controllerCodeCoverage, null, false);
int newCovered = 0;
try (final Runner runner = Runner.create(data, code, uncovered, steps)) {
System.out.println(runner.creationReport());
final String prefix = " (" + uncovered.size() + ") ";
System.out.print(prefix);
for (int i = 0; i < uncovered.size(); i++) {
final CoveragePoint cp = uncovered.get(i);
final RunnerResult result = runner.checkCoverage(cp);
if (i > 0 && i % 100 == 0) {
System.out.print("\n" + new String(new char[prefix.length()]).replace('\0', ' '));
}
if (result.outcomes().containsValue(false)) {
cp.cover();
newCovered++;
System.out.print("+");
} else {
System.out.print("-");
}
}
System.out.println();
}
return newCovered;
}
private static class CodeCoverageCounter {
int coverageClaims;
}
class CoverageInfo {
final List<CoveragePoint> coveragePoints;
final int totalPoints;
int coveredPoints = 0;
CoverageInfo(boolean plantCodeCoverage, boolean controllerCodeCoverage, boolean includeInternal,
boolean valuePairCoverage, String nusmvSpecCoverage, int maxGoals) {
final CodeCoverageCounter counter = new CodeCoverageCounter();
usualModelCode(counter, plantCodeCoverage, controllerCodeCoverage);
coveragePoints = coveragePoints(includeInternal, valuePairCoverage, counter.coverageClaims,
nusmvSpecCoverage, maxGoals);
totalPoints = coveragePoints.size();
}
void report() {
System.out.println(" Covered points: " + coveredPoints + " / " + totalPoints);
if (coveredPoints < totalPoints) {
System.out.println(" Not covered:");
coveragePoints.stream().filter(cp -> !cp.covered()).forEach(s -> System.out.println(" " + s));
}
}
boolean allCovered() {
return coveredPoints == totalPoints;
}
}
void verifyAll(String code, int timeout, boolean verbose, Integer nusmvBMCK, boolean inheritIO) throws IOException {
try (final Runner runner = Runner.create(data, code, Collections.emptyList(), null)) {
final RunnerResult result = runner.verify(timeout, false, nusmvBMCK, inheritIO);
for (Map.Entry<String, Boolean> outcome : result.outcomes().entrySet()) {
System.out.println("*** " + outcome.getKey() + " = " + outcome.getValue() + " ***");
}
if (verbose) {
result.log().forEach(System.out::println);
}
System.out.println(runner.totalResourceReport());
}
}
}
| 44.580311 | 120 | 0.585464 |
10a2f321f281f0464f67a715ba7bf5e0ceb73272 | 534 | package com.stylefeng.guns.modular.messageboard.service;
import com.stylefeng.guns.modular.system.model.MessageBoard;
import com.baomidou.mybatisplus.service.IService;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* 咨询留言表 服务类
* </p>
*
* @author stylefeng
* @since 2018-08-17
*/
public interface IMessageBoardService extends IService<MessageBoard> {
List<Map<String, Object>> list(@Param("condition") String condition, @Param("tipsNames")List<String> tipsNames);
}
| 23.217391 | 117 | 0.750936 |
fb5728dd54431b2d4ccfdfaa0c1a657c79ce872c | 1,297 | package com.gallagher.nzcovidpass;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import androidx.annotation.Nullable;
import org.apache.commons.codec.binary.Base16;
import org.junit.Assert;
import org.junit.Test;
// ref https://github.com/cbor/test-vectors/blob/master/appendix_a.json
public class Base32Tests {
@Test
public void testDecodeEmptyString() {
byte[] d = Base32.decode("");
assertEquals(0, d.length);
}
@Test
public void testDecodeString() {
byte[] d = Base32.decode("IRXWO===");
assertArrayEquals(new byte[]{ (byte)'D', (byte)'o', (byte)'g' }, d);
}
@Test
public void testDecodeBinary() {
// 1px transparent PNG file image from https://png-pixel.com/
byte[] referenceData = new Base16(true).decode("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63fcff9fa11e000782027f3dc848ef0000000049454e44ae426082");
// converted to base32 by https://cryptii.com/pipes/ (text->decodeBase64->encodeBase32->text)
byte[] d = Base32.decode("RFIE4RYNBINAUAAAAAGUSSCEKIAAAAABAAAAAAIIAYAAAAA7CXCISAAAAAGUSRCBKR4NUY7476P2CHQAA6BAE7Z5ZBEO6AAAAAAESRKOISXEEYEC");
assertArrayEquals(referenceData, d);
}
}
| 36.027778 | 199 | 0.728604 |
4ae9465c54fd4478ec409152a42c320c284ad309 | 1,111 | package team.fjut.cf.pojo.enums;
/**
* @author QAQ [2017/11/5]
*/
public enum CodeLanguage {
/**
*
*/
GPP(0, "G++"),
GCC(1, "GCC"),
JAVA(2, "JAVA"),
PYTHON2(3, "Python2"),
GPP11(4, "G++11"),
GCC11(5, "GCC11"),
V_CPP(6, "VC++"),
C_SHARP(7, "C#"),
GO_1_8(8, "GO 1.8"),
JS(9, "JavaScript"),
PASCAL(10, "Pascal");
private int code;
private String name;
CodeLanguage(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
public static String getNameByCode(int code) {
for (CodeLanguage l : CodeLanguage.values()) {
if (l.getCode() == code) {
return l.getName();
}
}
return null;
}
public static Integer getCodeByName(String name) {
for (CodeLanguage l : CodeLanguage.values()) {
if (name.equals(l.getName())) {
return l.getCode();
}
}
return null;
}
}
| 19.491228 | 54 | 0.489649 |
ce7efafc7c8adac57a90ff79865019ea92a0ab40 | 8,869 | package org.cloudfoundry.promregator.cfaccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.cloudfoundry.client.v2.Metadata;
import org.cloudfoundry.client.v2.applications.ApplicationEntity;
import org.cloudfoundry.client.v2.applications.ApplicationResource;
import org.cloudfoundry.client.v2.applications.ListApplicationsResponse;
import org.cloudfoundry.client.v2.info.GetInfoResponse;
import org.cloudfoundry.client.v2.organizations.ListOrganizationsResponse;
import org.cloudfoundry.client.v2.organizations.OrganizationEntity;
import org.cloudfoundry.client.v2.organizations.OrganizationResource;
import org.cloudfoundry.client.v2.spaces.GetSpaceSummaryResponse;
import org.cloudfoundry.client.v2.spaces.ListSpacesResponse;
import org.cloudfoundry.client.v2.spaces.SpaceApplicationSummary;
import org.cloudfoundry.client.v2.spaces.SpaceEntity;
import org.cloudfoundry.client.v2.spaces.SpaceResource;
import org.junit.jupiter.api.Assertions;
import reactor.core.publisher.Mono;
public class CFAccessorMock implements CFAccessor {
public static final String UNITTEST_ORG_UUID = "eb51aa9c-2fa3-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_SPACE_UUID = "db08be9a-2fa4-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_SPACE_UUID_DOESNOTEXIST = "db08be9a-2fa4-11e8-b467-0ed5f89f718b-doesnotexist";
public static final String UNITTEST_SPACE_UUID_EXCEPTION = "db08be9a-2fa4-11e8-b467-0ed5f89f718b-exception";
public static final String UNITTEST_APP1_UUID = "55820b2c-2fa5-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_APP2_UUID = "5a0ead6c-2fa5-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_APP1_ROUTE_UUID = "57ac2ada-2fa6-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_APP2_ROUTE_UUID = "5c5b464c-2fa6-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_APP1_HOST = "hostapp1";
public static final String UNITTEST_APP2_HOST = "hostapp2";
public static final String UNITTEST_SHARED_DOMAIN_UUID = "be9b8696-2fa6-11e8-b467-0ed5f89f718b";
public static final String UNITTEST_SHARED_DOMAIN = "shared.domain.example.org";
public static final String CREATED_AT_TIMESTAMP = "2014-11-24T19:32:49+00:00";
public static final String UPDATED_AT_TIMESTAMP = "2014-11-24T19:32:49+00:00";
@Override
public Mono<ListOrganizationsResponse> retrieveOrgId(String orgName) {
if ("unittestorg".equalsIgnoreCase(orgName)) {
OrganizationResource or = OrganizationResource.builder().entity(
OrganizationEntity.builder().name("unittestorg").build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_ORG_UUID).build()
// Note that UpdatedAt is not set here, as this can also happen in real life!
).build();
List<org.cloudfoundry.client.v2.organizations.OrganizationResource> list = new LinkedList<>();
list.add(or);
ListOrganizationsResponse resp = org.cloudfoundry.client.v2.organizations.ListOrganizationsResponse.builder().addAllResources(list).build();
return Mono.just(resp);
} else if ("doesnotexist".equals(orgName)) {
return Mono.just(org.cloudfoundry.client.v2.organizations.ListOrganizationsResponse.builder().resources(new ArrayList<>()).build());
} else if ("exception".equals(orgName)) {
return Mono.just(org.cloudfoundry.client.v2.organizations.ListOrganizationsResponse.builder().build())
.map(x -> {throw new Error("exception org name provided");});
}
Assertions.fail("Invalid OrgId request");
return null;
}
@Override
public Mono<ListSpacesResponse> retrieveSpaceId(String orgId, String spaceName) {
if (orgId.equals(UNITTEST_ORG_UUID)) {
if ( "unittestspace".equalsIgnoreCase(spaceName)) {
SpaceResource sr = SpaceResource.builder().entity(
SpaceEntity.builder().name("unittestspace").build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_SPACE_UUID).build()
).build();
List<SpaceResource> list = new LinkedList<>();
list.add(sr);
ListSpacesResponse resp = ListSpacesResponse.builder().addAllResources(list).build();
return Mono.just(resp);
} else if ( "unittestspace-summarydoesnotexist".equals(spaceName)) {
SpaceResource sr = SpaceResource.builder().entity(
SpaceEntity.builder().name(spaceName).build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_SPACE_UUID_DOESNOTEXIST).build()
).build();
List<SpaceResource> list = new LinkedList<>();
list.add(sr);
ListSpacesResponse resp = ListSpacesResponse.builder().addAllResources(list).build();
return Mono.just(resp);
} else if ( "unittestspace-summaryexception".equals(spaceName)) {
SpaceResource sr = SpaceResource.builder().entity(
SpaceEntity.builder().name(spaceName).build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_SPACE_UUID_EXCEPTION).build()
).build();
List<SpaceResource> list = new LinkedList<>();
list.add(sr);
ListSpacesResponse resp = ListSpacesResponse.builder().addAllResources(list).build();
return Mono.just(resp);
} else if ("doesnotexist".equals(spaceName)) {
return Mono.just(ListSpacesResponse.builder().resources(new ArrayList<>()).build());
} else if ("exception".equals(spaceName)) {
return Mono.just(ListSpacesResponse.builder().build()).map(x -> { throw new Error("exception space name provided"); });
}
}
Assertions.fail("Invalid SpaceId request");
return null;
}
@Override
public Mono<ListApplicationsResponse> retrieveAllApplicationIdsInSpace(String orgId, String spaceId) {
if (orgId.equals(UNITTEST_ORG_UUID) && spaceId.equals(UNITTEST_SPACE_UUID)) {
List<ApplicationResource> list = new LinkedList<>();
ApplicationResource ar = ApplicationResource.builder().entity(
ApplicationEntity.builder().name("testapp").state("STARTED").build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_APP1_UUID).build()
).build();
list.add(ar);
ar = ApplicationResource.builder().entity(
ApplicationEntity.builder().name("testapp2").state("STARTED").build()
).metadata(
Metadata.builder().createdAt(CREATED_AT_TIMESTAMP).id(UNITTEST_APP2_UUID).build()
).build();
list.add(ar);
ListApplicationsResponse resp = ListApplicationsResponse.builder().addAllResources(list).build();
return Mono.just(resp);
} else if (UNITTEST_SPACE_UUID_DOESNOTEXIST.equals(spaceId)) {
return Mono.just(ListApplicationsResponse.builder().build());
} else if (UNITTEST_SPACE_UUID_EXCEPTION.equals(spaceId)) {
return Mono.just(ListApplicationsResponse.builder().build()).map( x-> { throw new Error("exception on AllAppIdsInSpace"); });
}
Assertions.fail("Invalid process request");
return null;
}
@Override
public Mono<GetSpaceSummaryResponse> retrieveSpaceSummary(String spaceId) {
if (spaceId.equals(UNITTEST_SPACE_UUID)) {
List<SpaceApplicationSummary> list = new LinkedList<>();
final String[] urls1 = { UNITTEST_APP1_HOST + "." + UNITTEST_SHARED_DOMAIN };
SpaceApplicationSummary sas = SpaceApplicationSummary.builder()
.id(UNITTEST_APP1_UUID)
.name("testapp")
.addAllUrls(Arrays.asList(urls1))
.instances(2)
.build();
list.add(sas);
final String[] urls2 = { UNITTEST_APP2_HOST + "." + UNITTEST_SHARED_DOMAIN + "/additionalPath",
UNITTEST_APP2_HOST + ".additionalSubdomain." + UNITTEST_SHARED_DOMAIN + "/additionalPath" };
sas = SpaceApplicationSummary.builder()
.id(UNITTEST_APP2_UUID)
.name("testapp2")
.addAllUrls(Arrays.asList(urls2))
.instances(1)
.build();
list.add(sas);
GetSpaceSummaryResponse resp = GetSpaceSummaryResponse.builder().addAllApplications(list).build();
return Mono.just(resp);
} else if (spaceId.equals(UNITTEST_SPACE_UUID_DOESNOTEXIST)) {
return Mono.just(GetSpaceSummaryResponse.builder().build());
} else if (spaceId.equals(UNITTEST_SPACE_UUID_EXCEPTION)) {
return Mono.just(GetSpaceSummaryResponse.builder().build()).map( x-> { throw new Error("exception on application summary"); });
}
Assertions.fail("Invalid retrieveSpaceSummary request");
return null;
}
public Mono<ListOrganizationsResponse> retrieveAllOrgIds() {
return this.retrieveOrgId("unittestorg");
}
@Override
public Mono<ListSpacesResponse> retrieveSpaceIdsInOrg(String orgId) {
return this.retrieveSpaceId(UNITTEST_ORG_UUID, "unittestspace");
}
@Override
public Mono<GetInfoResponse> getInfo() {
GetInfoResponse data = GetInfoResponse.builder()
.description("CFAccessorMock")
.name("CFAccessorMock")
.version(1)
.build();
return Mono.just(data);
}
@Override
public void reset() {
// nothing to be done
}
}
| 42.845411 | 143 | 0.751494 |
4eb6c53e29301ee42aae105d0c29b2930aba6670 | 800 | package com.zerone.example;
import com.zerone.example.invaders.Assets;
import com.zerone.example.invaders.MainMenuScene;
import com.zerone.example.invaders.Settings;
import com.zerone.android.ZeroneActivity;
import com.zerone.core.Scene;
public class Invaders extends ZeroneActivity {
boolean firstTimeCreate = true;
public Scene getStartScene() {
return new MainMenuScene(this);
}
@Override
public void onInitialized() {
if (firstTimeCreate) {
Settings.load(getFileIO());
Assets.load(this);
firstTimeCreate = false;
} else {
Assets.reload();
}
}
@Override
public void onPause() {
super.onPause();
if (Settings.soundEnabled)
Assets.music.pause();
}
}
| 23.529412 | 49 | 0.6375 |
f67f1f5dacb9502a1f547a9cb573e7330380a3ea | 9,271 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.brooklyn.core.objs;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import org.apache.brooklyn.api.mgmt.ExecutionContext;
import org.apache.brooklyn.api.mgmt.Task;
import org.apache.brooklyn.api.objs.BrooklynObject;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.config.ConfigKey.HasConfigKey;
import org.apache.brooklyn.config.ConfigMap.ConfigMapWithInheritance;
import org.apache.brooklyn.core.config.MapConfigKey;
import org.apache.brooklyn.core.config.StructuredConfigKey;
import org.apache.brooklyn.core.config.SubElementConfigKey;
import org.apache.brooklyn.core.config.internal.AbstractConfigMapImpl;
import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
import org.apache.brooklyn.util.collections.MutableMap;
import org.apache.brooklyn.util.core.config.ConfigBag;
import org.apache.brooklyn.util.core.flags.TypeCoercions;
import org.apache.brooklyn.util.core.task.ImmediateSupplier.ImmediateUnsupportedException;
import org.apache.brooklyn.util.core.task.ImmediateSupplier.ImmediateValueNotAvailableException;
import org.apache.brooklyn.util.core.task.Tasks;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.exceptions.RuntimeInterruptedException;
import org.apache.brooklyn.util.guava.Maybe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Predicate;
public abstract class AbstractConfigurationSupportInternal implements BrooklynObjectInternal.ConfigurationSupportInternal {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(AbstractConfigurationSupportInternal.class);
@Override
public <T> T get(HasConfigKey<T> key) {
return get(key.getConfigKey());
}
@Override
public Maybe<Object> getLocalRaw(HasConfigKey<?> key) {
return getLocalRaw(key.getConfigKey());
}
@Override
public Maybe<Object> getRaw(HasConfigKey<?> key) {
return getRaw(key.getConfigKey());
}
@Override
public <T> Maybe<T> getNonBlocking(HasConfigKey<T> key) {
return getNonBlocking(key.getConfigKey());
}
@Override
public <T> Maybe<T> getNonBlocking(final ConfigKey<T> key) {
try {
if (key instanceof StructuredConfigKey || key instanceof SubElementConfigKey) {
return getNonBlockingResolvingStructuredKey(key);
} else {
return getNonBlockingResolvingSimple(key);
}
} catch (ImmediateValueNotAvailableException e) {
return Maybe.absent(e);
} catch (ImmediateUnsupportedException e) {
return Maybe.absent(e);
}
}
/**
* For resolving a {@link StructuredConfigKey}, such as a {@link MapConfigKey}. Here we need to
* execute the custom logic, as is done by {@link #get(ConfigKey)}, but non-blocking!
*/
protected <T> Maybe<T> getNonBlockingResolvingStructuredKey(final ConfigKey<T> key) {
Callable<T> job = new Callable<T>() {
@Override
public T call() {
try {
return get(key);
} catch (RuntimeInterruptedException e) {
throw Exceptions.propagate(e); // expected; return gracefully
}
}
};
Task<T> t = Tasks.<T>builder().dynamic(false).body(job)
.displayName("Resolving config "+key.getName())
.description("Internal non-blocking structured key resolution")
.tag(BrooklynTaskTags.TRANSIENT_TASK_TAG)
.build();
try {
return getContext().getImmediately(t);
} catch (ImmediateUnsupportedException e) {
return Maybe.absent();
}
}
/**
* For resolving a "simple" config key - i.e. where there's not custom logic inside a
* {@link StructuredConfigKey} such as a {@link MapConfigKey}. For those, we'd need to do the
* same as is in {@link #get(ConfigKey)}, but non-blocking!
* See {@link #getNonBlockingResolvingStructuredKey(ConfigKey)}.
*/
protected <T> Maybe<T> getNonBlockingResolvingSimple(ConfigKey<T> key) {
Object unresolved = getRaw(key).or(key.getDefaultValue());
Maybe<Object> resolved = Tasks.resolving(unresolved)
.as(Object.class)
.immediately(true)
.deep(true)
.context(getContext())
.description("Resolving raw value of simple config "+key)
.getMaybe();
if (resolved.isAbsent()) return Maybe.Absent.<T>castAbsent(resolved);
// likely we don't need this coercion if we set as(key.getType()) above,
// but that needs confirmation and quite a lot of testing
return TypeCoercions.tryCoerce(resolved.get(), key.getTypeToken());
}
@Override
public <T> T set(HasConfigKey<T> key, Task<T> val) {
return set(key.getConfigKey(), val);
}
@Override
public <T> T set(HasConfigKey<T> key, T val) {
return set(key.getConfigKey(), val);
}
protected abstract AbstractConfigMapImpl<? extends BrooklynObject> getConfigsInternal();
protected abstract <T> void assertValid(ConfigKey<T> key, T val);
protected abstract BrooklynObject getContainer();
protected abstract <T> void onConfigChanging(ConfigKey<T> key, Object val);
protected abstract <T> void onConfigChanged(ConfigKey<T> key, Object val);
@Override
public <T> T get(ConfigKey<T> key) {
return getConfigsInternal().getConfig(key);
}
@SuppressWarnings("unchecked")
protected <T> T setConfigInternal(ConfigKey<T> key, Object val) {
onConfigChanging(key, val);
T result = (T) getConfigsInternal().setConfig(key, val);
onConfigChanged(key, val);
return result;
}
@Override
public <T> T set(ConfigKey<T> key, T val) {
assertValid(key, val);
return setConfigInternal(key, val);
}
@Override
public <T> T set(ConfigKey<T> key, Task<T> val) {
return setConfigInternal(key, val);
}
@Override
public ConfigBag getLocalBag() {
return ConfigBag.newInstance(getConfigsInternal().getAllConfigLocalRaw());
}
@SuppressWarnings("unchecked")
@Override
public Maybe<Object> getRaw(ConfigKey<?> key) {
return (Maybe<Object>) getConfigsInternal().getConfigInheritedRaw(key).getWithoutError().asMaybe();
}
@Override
public Maybe<Object> getLocalRaw(ConfigKey<?> key) {
return getConfigsInternal().getConfigLocalRaw(key);
}
@Override
public void putAll(Map<?, ?> vals) {
getConfigsInternal().putAll(vals);
}
@Override @Deprecated
public void set(Map<?, ?> vals) {
putAll(vals);
}
@Override
public void removeKey(String key) {
getConfigsInternal().removeKey(key);
}
@Override
public void removeKey(ConfigKey<?> key) {
getConfigsInternal().removeKey(key);
}
@Override
public void removeAllLocalConfig() {
getConfigsInternal().setLocalConfig(MutableMap.<ConfigKey<?>,Object>of());
}
@Override @Deprecated
public Set<ConfigKey<?>> findKeys(Predicate<? super ConfigKey<?>> filter) {
return getConfigsInternal().findKeys(filter);
}
@Override
public Set<ConfigKey<?>> findKeysDeclared(Predicate<? super ConfigKey<?>> filter) {
return getConfigsInternal().findKeysDeclared(filter);
}
@Override
public Set<ConfigKey<?>> findKeysPresent(Predicate<? super ConfigKey<?>> filter) {
return getConfigsInternal().findKeysPresent(filter);
}
@Override
public ConfigMapWithInheritance<? extends BrooklynObject> getInternalConfigMap() {
return getConfigsInternal();
}
@Override
public Map<ConfigKey<?>,Object> getAllLocalRaw() {
return getConfigsInternal().getAllConfigLocalRaw();
}
@SuppressWarnings("deprecation")
@Override
// see super; we aspire to depreate this due to poor treatment of inheritance
public ConfigBag getBag() {
return getConfigsInternal().getAllConfigBag();
}
/**
* @return An execution context for use by {@link #getNonBlocking(ConfigKey)}
*/
@Nullable
protected abstract ExecutionContext getContext();
}
| 35.385496 | 123 | 0.675871 |
593abfc9acb89dbb6318e40632b4a66b2ed99e92 | 1,474 | package org.mycompany.myname.model.entity;
public class Coordinate {
final public static String COORDINATE_TABLE = "coordinate";
final public static String ID_NOTE = "id_note";
final public static String CORDINATE = "coordinate";
private Note note;
private double coordinate;
public Note getNote() throws Exception {
return note;
}
public void setNote(Note note) {
this.note = note;
}
public double getCoordinate() {
return coordinate;
}
public void setCoordinate(double coordinate) {
this.coordinate = coordinate;
}
@Override
public String toString() {
return "Coordinate{" +
"note=" + note +
", coordinate=" + coordinate +
'}';
}
// Coordinate Builder
public static final class CoordinateBuilder implements IBuilder<Coordinate>{
private Note note;
private double coordinate;
public CoordinateBuilder setNote(Note note) {
this.note = note;
return this;
}
public CoordinateBuilder setCoordinate(double coordinate){
this.coordinate = coordinate;
return this;
}
public Coordinate build(){
Coordinate coordinatePoint = new Coordinate();
coordinatePoint.setNote(note);
coordinatePoint.setCoordinate(coordinate);
return coordinatePoint;
}
}
}
| 24.983051 | 80 | 0.603799 |
2279224a5deb59b865d2432caa37e723a18103ae | 2,737 | package com.tukeping.leetcode.problems;
/*
* @lc app=leetcode.cn id=746 lang=java
*
* [746] 使用最小花费爬楼梯
*
* https://leetcode-cn.com/problems/min-cost-climbing-stairs/description/
*
* algorithms
* Easy (47.37%)
* Likes: 245
* Dislikes: 0
* Total Accepted: 26K
* Total Submissions: 54.8K
* Testcase Example: '[0,0,0,0]'
*
* 数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
*
* 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
*
* 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
*
* 示例 1:
*
*
* 输入: cost = [10, 15, 20]
* 输出: 15
* 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
*
*
* 示例 2:
*
*
* 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
* 输出: 6
* 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
*
*
* 注意:
*
*
* cost 的长度将会在 [2, 1000]。
* 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
*
*
*/
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* trie
*
* @author tukeping
* @date 2020/3/23
**/
public class LeetCode746 {
public int minCostClimbingStairsV2(int[] cost) {
int n = cost.length;
int[] dp = new int[n + 1];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i <= n; i++) {
int c = i == n ? 0 : cost[i];
dp[i] = Math.min(c + dp[i - 1], c + dp[i - 2]);
}
return Math.min(dp[n], dp[n - 1]);
}
public int minCostClimbingStairs(int[] cost) {
int f1 = 0, f2 = 0;
for (int i = cost.length - 1; i >= 0; --i) {
int f0 = cost[i] + Math.min(f1, f2);
f2 = f1;
f1 = f0;
}
return Math.min(f1, f2);
}
public int minCostClimbingStairs2(int[] cost) {
int len = cost.length;
if (len == 0) return 0;
if (len == 1) return cost[0];
if (len == 2) return Math.min(cost[0], cost[1]);
int[] dp = new int[len];
dp[0] = cost[0];
dp[1] = cost[1];
int min = Integer.MAX_VALUE;
for (int i = 2; i < len; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]);
min = Math.min(dp[i - 1], dp[i]);
}
return min;
}
/**
* 输入: cost = [10, 15, 20]
* 输出: 15
* 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
*/
@Test
public void test1() {
int n = minCostClimbingStairs(new int[]{10, 15, 20});
assertThat(n, is(15));
}
/**
* 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
* 输出: 6
* 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
*/
@Test
public void test2() {
int n = minCostClimbingStairs(new int[]{1, 100, 1, 1, 1, 100, 1, 1, 100, 1});
assertThat(n, is(6));
}
}
| 21.722222 | 85 | 0.510047 |
3e40aa850e39c6ad48f363a2eeec236ea4a42851 | 2,783 | /**
* blackduck-eclipse-integration-tests
*
* Copyright (C) 2018 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.integration.eclipse.test;
public class TestConstants {
public static final String TEST_MAVEN_GROUP = "com.blackducksoftware.integration.eclipse.test";
public static final String TEST_MAVEN_ARTIFACT = "just-a-maven-project";
public static final String TEST_MAVEN_COMPONENTS_ARTIFACT = "just-another-maven-project";
public static final String TEST_MAVEN_EMPTY_ARTIFACT = "just-a-third-maven-project";
public static final String TEST_GRADLE_PROJECT_NAME = "just-a-gradle-project";
public static final String TEST_NON_JAVA_PROJECT_NAME = "just-a-non-java-project";
public static final String TEST_MAVEN_COMPONENTS_ARTIFACT_POM_PATH = "resources/test-maven-components-artifact/pom.xml";
public static final String HUB_PREFERENCE_PAGE_NAME = "Black Duck Hub";
public static final String COMPONENT_INSPECTOR_PREFERENCE_PAGE_NAME = "Component Inspector Settings";
public static final String BLACK_DUCK_HUB_CATEGORY_NAME = "Black Duck Hub";
public static final String BLACK_DUCK_CATEGORY_NAME = "Black Duck";
public static final String COMPONENT_INSPECTOR_VIEW_NAME = "Component Inspector";
public static final String CONTEXT_MENU_INSPECT_PROJECT_ACTION = "Inspect Selected Project";
public static final String CONTEXT_MENU_OPEN_COMPONENT_INSPECTOR_ACTION = "Open Component Inspector";
public static final String CONTEXT_MENU_OPEN_HUB_SETTINGS_ACTION = "Hub Settings...";
public static final String CONTEXT_MENU_BLACK_DUCK_CATEGORY = "Black Duck";
public static final String HUB_URL_KEY = "hub.url";
public static final String HUB_USERNAME_KEY = "hub.username";
public static final String HUB_PASSWORD_KEY = "hub.password";
public static final String HUB_TIMEOUT_KEY = "hub.timeout";
public static final String INVALID_STRING = "INVALID";
}
| 53.519231 | 124 | 0.779375 |
ef83b1768e9a81eeb28d499965aba8b8f025e31c | 910 | /*
* Copyright (c) 2021 Tobias Briones. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* This file is part of Course Project at UNAH-MM545: Distributed Text File
* System.
*
* This source code is licensed under the BSD-3-Clause License found in the
* LICENSE file in the root directory of this source tree or at
* https://opensource.org/licenses/BSD-3-Clause.
*/
package com.github.tobiasbriones.cp.rmifilesystem.model.io;
/**
* @author Tobias Briones
*/
public record Directory(CommonPath path) implements CommonFile {
public static Directory of() {
return new Directory(CommonPath.of());
}
public static Directory of(CommonPath path) {
return new Directory(path);
}
public Directory(String path) {
this(new CommonPath(path));
}
public boolean isRoot() {
return path.value().equals(CommonPath.ROOT_PATH);
}
}
| 25.277778 | 75 | 0.687912 |
1da85acd8d3180c29240ad58eea588514b5865ee | 544 | package org.goblinframework.core.compression;
import org.goblinframework.api.core.GoblinException;
public class GoblinCompressionException extends GoblinException {
private static final long serialVersionUID = -1704098810351612906L;
public GoblinCompressionException() {
}
public GoblinCompressionException(String message) {
super(message);
}
public GoblinCompressionException(String message, Throwable cause) {
super(message, cause);
}
public GoblinCompressionException(Throwable cause) {
super(cause);
}
}
| 23.652174 | 70 | 0.779412 |
18dba406cb0f12fb1a06482552414cab28f0d671 | 4,061 | package com.webcheckers.ui.model.RuleSystemTests;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import com.webcheckers.model.GameBoard;
import com.webcheckers.model.Player;
import com.webcheckers.model.Position;
import com.webcheckers.model.GameBoard.cells;
import com.webcheckers.model.RuleSystem.RuleMaster;
/**
* JUnit tests for the RuleMaster model-tier class
*
* @author Michael Ambrose (ma8540@rit.edu)
*/
@Tag ("Model-tier")
public class RuleMasterTest {
//Object under test
private RuleMaster CuT;
//Friendly Objects
private Player user1 = new Player("User1"); //red player
private Player user2 = new Player("User2"); //white player
private GameBoard gameBoard;
private cells[][] fixedBoard;
private Position before_pos;
private Position after_pos;
//Board Cells
private static final cells X = cells.X;
private static final cells E = cells.E;
private static final cells W = cells.W;
private static final cells R = cells.R;
/**
* Instantiates CuT and other friendly objects before every test
*/
@BeforeEach
public void setup() {
gameBoard = new GameBoard(user1, user2);
CuT = new RuleMaster(gameBoard);
}
@Test
public void test_trigger_ruleset_move() {
//Makes a move
before_pos = new Position(5, 2);
after_pos = new Position(4, 3);
CuT.createBoardTransition(before_pos, after_pos, gameBoard.getActiveColor());
CuT.triggerRuleSet();
assertEquals(cells.E, gameBoard.getBoard()[5][2]);
assertEquals(cells.R, gameBoard.getBoard()[4][3]);
}
@Test
public void test_trigger_ruleset_jump() {
fixedBoard = new cells[][] {
{X, W, X, W, X, W, X, W},
{W, X, W, X, W, X, W, X},
{X, W, X, W, X, E, X, W},
{E, X, E, X, E, X, W, X},
{X, E, X, E, X, E, X, R},
{R, X, R, X, R, X, E, X},
{X, R, X, R, X, R, X, R},
{R, X, R, X, R, X, R, X}};
//Makes a jump
before_pos = new Position(4, 7);
after_pos = new Position(2, 5);
gameBoard.setBoard(fixedBoard);
CuT.createBoardTransition(before_pos, after_pos, gameBoard.getActiveColor());
assertTrue(CuT.triggerRuleSet());
assertEquals(cells.E, gameBoard.getBoard()[4][7]);
assertEquals(cells.E, gameBoard.getBoard()[3][6]);
assertEquals(cells.R, gameBoard.getBoard()[2][5]);
}
@Test
public void test_trigger_ruleset_invalid_jump() {
fixedBoard = new cells[][] {
{X, W, X, W, X, W, X, W},
{W, X, W, X, E, X, W, X},
{X, W, X, W, X, W, X, W},
{E, X, E, X, E, X, W, X},
{X, E, X, E, X, E, X, R},
{R, X, R, X, R, X, E, X},
{X, R, X, R, X, R, X, R},
{R, X, R, X, R, X, R, X}};
//Makes a jump
before_pos = new Position(4, 7);
after_pos = new Position(1, 4);
gameBoard.setBoard(fixedBoard);
CuT.createBoardTransition(before_pos, after_pos, gameBoard.getActiveColor());
assertFalse(CuT.triggerRuleSet());
}
/**
* Validates the win state is for red (user1)
*/
@Test
public void test_set_red_win() {
//user1 : red player
CuT.setWin("red player");
assertEquals(user1, CuT.getWinner());
}
/**
* Validates the win state is for white (user2)
*/
@Test
public void test_set_white_win() {
//user2 : white player
CuT.setWin("white player");
assertEquals(user2, CuT.getWinner());
}
@Test
public void test_set_game_over() {
//Game supposedly started, game is ongoing
assertFalse(CuT.getGameOver());
//Sets game condition to be over
CuT.setGameOver(true);
assertTrue(CuT.getGameOver());
}
}
| 28.598592 | 85 | 0.574735 |
222073bd010ac4f8252298cb89369bbc8de31909 | 267 | package app.bravo.zu.spiderx.core.parser.bean.annotation;
import java.lang.annotation.*;
/**
* json 对象
*/
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Element
public @interface JsonObject {
String path();
}
| 15.705882 | 57 | 0.737828 |
1b8a214bda2a644eeda4a691cce9d14f2dab7ec3 | 4,428 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.session;
import org.broad.igv.renderer.*;
/**
* Maps between renderer type name and renderer class. Used for saving and restoring sessions.
*
* @author eflakes
*/
public class RendererFactory {
static public enum RendererType {
BAR_CHART,
BASIC_FEATURE,
FEATURE_DENSITY,
GENE_TRACK,
GISTIC_TRACK,
HEATMAP,
MUTATION,
SCATTER_PLOT,
LINE_PLOT
}
static Class defaultRendererClass = BarChartRenderer.class;
static public Class getRendererClass(String rendererTypeName) {
String typeName = rendererTypeName.toUpperCase();
// Try know type names
if (typeName.equals(RendererType.BAR_CHART.name()) || typeName.equals("BAR")) {
return BarChartRenderer.class;
} else if (typeName.equals(RendererType.BASIC_FEATURE.name())) {
return IGVFeatureRenderer.class;
} else if (typeName.equals(RendererType.FEATURE_DENSITY.name())) {
return FeatureDensityRenderer.class;
} else if (typeName.equals(RendererType.GENE_TRACK.name())) {
return GeneTrackRenderer.class;
} else if (typeName.equals(RendererType.GISTIC_TRACK.name())) {
return GisticTrackRenderer.class;
} else if (typeName.equals(RendererType.HEATMAP.name())) {
return HeatmapRenderer.class;
} else if (typeName.equals(RendererType.MUTATION.name())) {
return MutationRenderer.class;
} else if (typeName.equals(RendererType.SCATTER_PLOT.name()) ||
typeName.toUpperCase().equals("POINTS")) {
return PointsRenderer.class;
} else if (typeName.equals(RendererType.LINE_PLOT.name()) ||
typeName.toUpperCase().equals("LINE")) {
return LineplotRenderer.class;
}
return null;
}
static public RendererType getRenderType(Renderer renderer) {
Class rendererClass = renderer.getClass();
RendererType rendererType = null;
if (rendererClass.equals(BarChartRenderer.class)) {
rendererType = RendererType.BAR_CHART;
} else if (rendererClass.equals(IGVFeatureRenderer.class)) {
rendererType = RendererType.BASIC_FEATURE;
} else if (rendererClass.equals(FeatureDensityRenderer.class)) {
rendererType = RendererType.FEATURE_DENSITY;
} else if (rendererClass.equals(GeneTrackRenderer.class)) {
rendererType = RendererType.GENE_TRACK;
} else if (rendererClass.equals(GisticTrackRenderer.class)) {
rendererType = RendererType.GISTIC_TRACK;
} else if (rendererClass.equals(HeatmapRenderer.class)) {
rendererType = RendererType.HEATMAP;
} else if (rendererClass.equals(MutationRenderer.class)) {
rendererType = RendererType.MUTATION;
} else if (rendererClass.equals(PointsRenderer.class)) {
rendererType = RendererType.SCATTER_PLOT;
} else if (rendererClass.equals(LineplotRenderer.class)) {
rendererType = RendererType.LINE_PLOT;
}
return rendererType;
}
}
| 38.504348 | 95 | 0.680217 |
9029ddc4f977f693dd0b78afa9952162575a7525 | 1,701 | package com.curisprofound.springplugincontainer;
import com.curisprofound.plugins.PluginInterface;
import org.pf4j.spring.SpringPluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.List;
@SpringBootApplication
public class SpringPluginContainerApplication {
private static Logger log = LoggerFactory.getLogger(SpringPluginContainerApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringPluginContainerApplication.class, args);
}
@Bean
public ApplicationRunner run() {
return new ApplicationRunner() {
@Autowired
private SpringPluginManager springPluginManager;
@Override
public void run(ApplicationArguments args) throws Exception {
List<PluginInterface> plugins = springPluginManager.getExtensions(PluginInterface.class);
log.info(String.format("Number of plugins found: %d", plugins.size()));
plugins.forEach(c -> log.info(c.getClass().getName() + ":" + c.identify()));
}
};
}
@Bean
public CommandLineRunner runner() {
return (args) -> {
log.info("Plugin installation folder path: {}", System.getProperty("pf4j.pluginsDir"));
};
}
}
| 34.714286 | 105 | 0.72134 |
5348dbde745934091ae7f3c438a2c5162ee43495 | 1,200 | package tech.crom.client.java.common;
import tech.crom.client.java.RepoDetails;
import tech.crom.client.java.common.internal.DefaultGitCromClient;
import tech.crom.client.java.scm.git.GitManager;
import tech.crom.client.java.scm.git.GitManagerBuilder;
import tech.crom.client.java.http.HttpConradClient;
import tech.crom.client.java.http.HttpConradClientBuilder;
import java.io.File;
import java.io.IOException;
public class ConradClientBuilder {
private RepoDetails repoDetails;
public ConradClientBuilder(RepoDetails repoDetails) {
this.repoDetails = repoDetails;
}
public ConradClientBuilder(String projectName, String repoName, String authToken) {
this(new RepoDetails(projectName, repoName, authToken));
}
public CromClient build(File projectDir) {
try {
GitManager gitManager = new GitManagerBuilder(projectDir).build();
HttpConradClient httpClient = new HttpConradClientBuilder(repoDetails).build();
return new DefaultGitCromClient(httpClient, gitManager);
} catch (IOException ioe) {
throw new RuntimeException("Only the git client is supported at this time.");
}
}
}
| 33.333333 | 91 | 0.736667 |
136d0eaca75bb1ce79e2a243fc73ac303f23d6d6 | 390 | package com.wangc.p22_decorator.test1;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wangchao on 2016/11/14.
*/
public class DBdate {
public static Map<String,Double> USER_DATA = new HashMap<String,Double>();
static {
USER_DATA.put("zhangsan",20000.0);
USER_DATA.put("lisi",10000.0);
USER_DATA.put("wangwu",30000.0);
}
}
| 20.526316 | 78 | 0.64359 |
991eb8384c7b4cd1604e0cb2a0f6d3d7ba595dbe | 1,817 | package org.dhwpcs.infinitum.chat.tag.inst;
import net.kyori.adventure.sound.Sound;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.dhwpcs.infinitum.chat.adventure.Translatable;
import org.dhwpcs.infinitum.chat.ChatContext;
import org.dhwpcs.infinitum.chat.tag.ChatTag;
import org.dhwpcs.infinitum.chat.tag.arguments.ArgumentPlayer;
import org.dhwpcs.infinitum.chat.tag.parse.TagFailedException;
import org.dhwpcs.infinitum.chat.tag.parse.argument.ArgumentTable;
import org.dhwpcs.infinitum.chat.tag.parse.argument.TagContext;
import java.util.List;
public class TagAt implements ChatTag<OfflinePlayer> {
@Override
public String name() {
return "At";
}
@Override
public String id() {
return "at";
}
@Override
public List<String> aliases() {
return List.of("@");
}
@Override
public ArgumentTable arguments() throws TagFailedException {
return ArgumentTable.table()
.with("id", ArgumentPlayer.player());
}
@Override
public Class<OfflinePlayer> type() {
return OfflinePlayer.class;
}
@Override
public OfflinePlayer parse(TagContext tag, ChatContext chat) throws TagFailedException {
return ArgumentPlayer.getPlayer("id", tag);
}
@Override
public Translatable parseComponent(OfflinePlayer result, ChatContext ctx) {
ctx.addAfterTask(() -> {
if(result.isOnline()) {
Player entity = result.getPlayer();
entity.playSound(Sound.sound(org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, Sound.Source.PLAYER, 1.0f, 0.0f));
}
});
return Translatable.wrapNugget(ctx.getInfinitum().getI18n().get("chat.at."+(result.isOnline() ? "online" : "offline")), result.getName());
}
}
| 30.283333 | 146 | 0.681893 |
26dc7c3b953e47a332b724200be5c12e3c5c3c44 | 1,267 | package com.sdoward.rxgooglemap;
import static org.mockito.Mockito.verify;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.PointOfInterest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import rx.observers.TestSubscriber;
@RunWith(PowerMockRunner.class)
@PrepareForTest(GoogleMap.class)
public class POIClickFuncTest {
@Mock
private GoogleMap googleMap;
@Captor
private ArgumentCaptor<GoogleMap.OnPoiClickListener> argumentCaptor;
@Test
public void shouldEmmitPolygon() throws Exception {
TestSubscriber<PointOfInterest> testSubscriber = new TestSubscriber<>();
new POIClickFunc().call(googleMap)
.subscribe(testSubscriber);
verify(googleMap).setOnPoiClickListener(argumentCaptor.capture());
argumentCaptor.getValue().onPoiClick(null);
testSubscriber.assertNoErrors();
testSubscriber.assertValueCount(1);
argumentCaptor.getValue().onPoiClick(null);
testSubscriber.assertValueCount(2);
}
}
| 33.342105 | 80 | 0.756117 |
f86ba21dce2684286c5d7487b2258f0fb6b6fd72 | 8,154 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.aws.s3;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.impl.ScheduledPollEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Defines the <a href="http://camel.apache.org/aws.html">AWS S3 Endpoint</a>.
*
*/
public class S3Endpoint extends ScheduledPollEndpoint {
protected final Logger log = LoggerFactory.getLogger(getClass());
private static final Logger LOG = LoggerFactory.getLogger(S3Endpoint.class);
private AmazonS3 s3Client;
private S3Configuration configuration;
private int maxMessagesPerPoll = 10;
@Deprecated
public S3Endpoint(String uri, CamelContext context, S3Configuration configuration) {
super(uri, context);
this.configuration = configuration;
}
public S3Endpoint(String uri, Component comp, S3Configuration configuration) {
super(uri, comp);
this.configuration = configuration;
}
public Consumer createConsumer(Processor processor) throws Exception {
S3Consumer s3Consumer = new S3Consumer(this, processor);
configureConsumer(s3Consumer);
s3Consumer.setMaxMessagesPerPoll(maxMessagesPerPoll);
return s3Consumer;
}
public Producer createProducer() throws Exception {
return new S3Producer(this);
}
public boolean isSingleton() {
return true;
}
@Override
public void doStart() throws Exception {
super.doStart();
s3Client = configuration.getAmazonS3Client() != null
? configuration.getAmazonS3Client() : createS3Client();
if (ObjectHelper.isNotEmpty(configuration.getAmazonS3Endpoint())) {
s3Client.setEndpoint(configuration.getAmazonS3Endpoint());
}
String fileName = getConfiguration().getFileName();
if (fileName != null) {
log.debug("File name [{}] requested, so skipping bucket check...", fileName);
return;
}
String bucketName = getConfiguration().getBucketName();
log.debug("Querying whether bucket [{}] already exists...", bucketName);
log.debug("S3 client key:{}, secret:{}", getConfiguration().getAccessKey(), getConfiguration().getSecretKey());
try {
s3Client.listObjects(new ListObjectsRequest(bucketName, getConfiguration().getPrefix(), getConfiguration().getMarker(), null, 0));
LOG.trace("Bucket [{}] already exists", bucketName);
return;
} catch (AmazonServiceException ase) {
/* 404 means the bucket doesn't exist */
if (ase.getStatusCode() != 404) {
throw ase;
}
}
LOG.trace("Bucket [{}] doesn't exist yet", bucketName);
// creates the new bucket because it doesn't exist yet
CreateBucketRequest createBucketRequest = new CreateBucketRequest(getConfiguration().getBucketName());
if (getConfiguration().getRegion() != null) {
createBucketRequest.setRegion(getConfiguration().getRegion());
}
LOG.trace("Creating bucket [{}] in region [{}] with request [{}]...", new Object[]{configuration.getBucketName(), configuration.getRegion(), createBucketRequest});
s3Client.createBucket(createBucketRequest);
LOG.trace("Bucket created");
if (configuration.getPolicy() != null) {
LOG.trace("Updating bucket [{}] with policy [{}]", bucketName, configuration.getPolicy());
s3Client.setBucketPolicy(bucketName, configuration.getPolicy());
LOG.trace("Bucket policy updated");
}
}
public Exchange createExchange(S3Object s3Object) {
return createExchange(getExchangePattern(), s3Object);
}
public Exchange createExchange(ExchangePattern pattern, S3Object s3Object) {
LOG.trace("Getting object with key [{}] from bucket [{}]...", s3Object.getKey(), s3Object.getBucketName());
ObjectMetadata objectMetadata = s3Object.getObjectMetadata();
LOG.trace("Got object [{}]", s3Object);
Exchange exchange = new DefaultExchange(this, pattern);
Message message = exchange.getIn();
message.setBody(s3Object.getObjectContent());
message.setHeader(S3Constants.KEY, s3Object.getKey());
message.setHeader(S3Constants.BUCKET_NAME, s3Object.getBucketName());
message.setHeader(S3Constants.E_TAG, objectMetadata.getETag());
message.setHeader(S3Constants.LAST_MODIFIED, objectMetadata.getLastModified());
message.setHeader(S3Constants.VERSION_ID, objectMetadata.getVersionId());
message.setHeader(S3Constants.CONTENT_TYPE, objectMetadata.getContentType());
message.setHeader(S3Constants.CONTENT_MD5, objectMetadata.getContentMD5());
message.setHeader(S3Constants.CONTENT_LENGTH, objectMetadata.getContentLength());
message.setHeader(S3Constants.CONTENT_ENCODING, objectMetadata.getContentEncoding());
message.setHeader(S3Constants.CONTENT_DISPOSITION, objectMetadata.getContentDisposition());
message.setHeader(S3Constants.CACHE_CONTROL, objectMetadata.getCacheControl());
return exchange;
}
public S3Configuration getConfiguration() {
return configuration;
}
public void setConfiguration(S3Configuration configuration) {
this.configuration = configuration;
}
public void setS3Client(AmazonS3 s3Client) {
this.s3Client = s3Client;
}
public AmazonS3 getS3Client() {
return s3Client;
}
/**
* Provide the possibility to override this method for an mock implementation
*
* @return AmazonS3Client
*/
AmazonS3 createS3Client() {
AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey());
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMaxConnections(configuration.getMaxConnections());
log.info("creating S3 client with the following config:{}", configuration);
AmazonS3 client = new AmazonS3Client(credentials, clientConfiguration);
return client;
}
public int getMaxMessagesPerPoll() {
return maxMessagesPerPoll;
}
public void setMaxMessagesPerPoll(int maxMessagesPerPoll) {
this.maxMessagesPerPoll = maxMessagesPerPoll;
}
} | 40.366337 | 171 | 0.696468 |
43c52e5cffd76fbce350bf7b19e1fd490c5d8eb4 | 5,132 | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 io.ballerina.stdlib.graphql.compiler;
import io.ballerina.compiler.api.symbols.ClassSymbol;
import io.ballerina.compiler.api.symbols.IntersectionTypeSymbol;
import io.ballerina.compiler.api.symbols.MethodSymbol;
import io.ballerina.compiler.api.symbols.Qualifier;
import io.ballerina.compiler.api.symbols.Symbol;
import io.ballerina.compiler.api.symbols.SymbolKind;
import io.ballerina.compiler.api.symbols.TypeDescKind;
import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol;
import io.ballerina.compiler.api.symbols.TypeSymbol;
import io.ballerina.compiler.api.symbols.UnionTypeSymbol;
import io.ballerina.tools.diagnostics.Location;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Util class for the compiler plugin.
*/
public final class Utils {
private Utils() {
}
// compiler plugin constants
public static final String PACKAGE_NAME = "graphql";
public static final String PACKAGE_ORG = "ballerina";
// resource function constants
public static final String LISTENER_IDENTIFIER = "Listener";
public static final String CONTEXT_IDENTIFIER = "Context";
public static final String FILE_UPLOAD_IDENTIFIER = "Upload";
public static boolean isGraphqlModuleSymbol(TypeSymbol typeSymbol) {
if (typeSymbol.getModule().isEmpty()) {
return false;
}
String moduleName = typeSymbol.getModule().get().id().moduleName();
String orgName = typeSymbol.getModule().get().id().orgName();
return PACKAGE_NAME.equals(moduleName) && PACKAGE_ORG.equals(orgName);
}
public static boolean isRemoteFunction(MethodSymbol methodSymbol) {
return methodSymbol.qualifiers().contains(Qualifier.REMOTE);
}
public static boolean isGraphqlListener(Symbol listenerSymbol) {
if (listenerSymbol.kind() != SymbolKind.TYPE) {
return false;
}
TypeSymbol typeSymbol = ((TypeReferenceTypeSymbol) listenerSymbol).typeDescriptor();
if (typeSymbol.typeKind() != TypeDescKind.OBJECT) {
return false;
}
if (!isGraphqlModuleSymbol(typeSymbol)) {
return false;
}
if (typeSymbol.getName().isEmpty()) {
return false;
}
return LISTENER_IDENTIFIER.equals(typeSymbol.getName().get());
}
public static boolean isIgnoreType(TypeSymbol typeSymbol) {
return typeSymbol.typeKind() == TypeDescKind.NIL || typeSymbol.typeKind() == TypeDescKind.ERROR;
}
public static List<TypeSymbol> getEffectiveTypes(UnionTypeSymbol unionTypeSymbol) {
List<TypeSymbol> effectiveTypes = new ArrayList<>();
for (TypeSymbol typeSymbol : unionTypeSymbol.memberTypeDescriptors()) {
if (!isIgnoreType(typeSymbol)) {
effectiveTypes.add(typeSymbol);
}
}
return effectiveTypes;
}
public static TypeSymbol getEffectiveType(IntersectionTypeSymbol intersectionTypeSymbol, Location location) {
List<TypeSymbol> effectiveTypes = new ArrayList<>();
for (TypeSymbol typeSymbol : intersectionTypeSymbol.memberTypeDescriptors()) {
if (typeSymbol.typeKind() == TypeDescKind.READONLY) {
continue;
}
effectiveTypes.add(typeSymbol);
}
if (effectiveTypes.size() == 1) {
return effectiveTypes.get(0);
}
return null;
}
public static boolean isPrimitiveType(TypeSymbol returnType) {
return returnType.typeKind().isStringType() ||
returnType.typeKind() == TypeDescKind.INT ||
returnType.typeKind() == TypeDescKind.FLOAT ||
returnType.typeKind() == TypeDescKind.BOOLEAN ||
returnType.typeKind() == TypeDescKind.DECIMAL;
}
public static boolean isDistinctServiceReference(TypeSymbol typeSymbol) {
if (typeSymbol.typeKind() != TypeDescKind.TYPE_REFERENCE) {
return false;
}
TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) typeSymbol;
Symbol typeDescriptor = typeReferenceTypeSymbol.typeDescriptor();
if (typeDescriptor.kind() != SymbolKind.CLASS) {
return false;
}
ClassSymbol classSymbol = (ClassSymbol) typeDescriptor;
return classSymbol.qualifiers().containsAll(Arrays.asList(Qualifier.SERVICE, Qualifier.DISTINCT));
}
}
| 38.586466 | 113 | 0.688815 |
54910709ebe517ded5e5e88542aa98d659ddc0f1 | 7,673 | package stolat.model;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AlbumTest {
@Test
void shouldCreateAlbumWhenTagsAreValid() {
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist");
}
@Test
void shouldCreateAlbumWithMultipleArtistsWhenTagsAreValid() {
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), List.of("Some Artist", "Some Other Artist"), "Some Artist & Some Other Artist");
}
@Test
void shouldNotCreateAlbumWhenAlbumMbidIsInvalid() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
"invalid UUID", "Some Album",
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenAlbumMbidIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
"", "Some Album",
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenAlbumMbidIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
null, "Some Album",
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenAlbumNameIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "",
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenAlbumNameIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), null,
List.of(UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistMbidIsInvalid() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of("invalid UUID"), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenOneOfArtistMbidIsInvalid() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString(), "invalid UUID"), List.of("Some Artist", "Some Other Artist"), "Some Artist & Some Other Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistMbidIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(""), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenOneOfArtistMbidIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of("", UUID.randomUUID().toString()), List.of("Some Artist", "Some Other Artist"), "Some Artist & Some Other Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistMbidIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
Collections.singletonList(null), List.of("Some Artist"), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenOneOfArtistMbidIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
Arrays.asList(UUID.randomUUID().toString(), null), List.of("Some Artist", "Some Other Artist"), "Some Artist & Some Other Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistNameIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString()), List.of(""), ""));
}
@Test
void shouldNotCreateAlbumWhenOneOfArtistNameIsEmpty() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), List.of("", "Some Other Artist"), "Some Other Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistNameIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString()), Collections.singletonList(null), "Some Other Artist"));
}
@Test
void shouldNotCreateAlbumWhenOneOfArtistNameIsNull() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), Arrays.asList("Some Artist", null), "Some Artist"));
}
@Test
void shouldNotCreateAlbumWhenArtistIDsAndNamesHaveDifferentSize() {
assertThrows(IllegalArgumentException.class, () ->
new Album(
UUID.randomUUID().toString(), "Some Album",
List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), List.of("Some Artist"), "Some Artist"
));
}
@Test
void shouldCreateAlbumWithArtistNameWhenArtistDisplayNameIsEmpty() {
Album actual = new Album(UUID.randomUUID().toString(), "Some Album", List.of(UUID.randomUUID().toString()), List.of("This Artist"), "");
assertEquals("This Artist", actual.getDisplayArtist());
}
@Test
void shouldCreateAlbumWithArtistNameWhenArtistDisplayNameIsNull() {
Album actual = new Album(UUID.randomUUID().toString(), "Some Album", List.of(UUID.randomUUID().toString()), List.of("This Artist"), null);
assertEquals("This Artist", actual.getDisplayArtist());
}
@Test
void shouldCreateAlbumWithMultipleArtistNamesWhenArtistDisplayNameIsEmpty() {
Album actual = new Album(UUID.randomUUID().toString(), "Some Album", List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), List.of("This Artist", "That Artist"), "");
assertEquals("This Artist, That Artist", actual.getDisplayArtist());
}
@Test
void shouldCreateAlbumWithMultipleArtistNamesWhenArtistDisplayNameIsNull() {
Album actual = new Album(UUID.randomUUID().toString(), "Some Album", List.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()), List.of("This Artist", "That Artist"), null);
assertEquals("This Artist, That Artist", actual.getDisplayArtist());
}
} | 42.392265 | 191 | 0.595986 |
2711a437f60e58c657e78060ca5518c337d467b9 | 477 | /*
* Copyright (C) 2013 Schlichtherle IT Services & Stimulus Software.
* All rights reserved. Use is subject to license terms.
*/
package net.java.trueupdate.installer.cargo;
/**
* Indicates an error when using the generic Cargo API.
*
* @author Christian Schlichtherle
*/
public class CargoException extends Exception {
private static final long serialVersionUID = 0L;
CargoException(String message, Throwable cause) {
super(message, cause);
}
}
| 23.85 | 68 | 0.721174 |
52e5b061f8bd11e7d50468937a316174484fda60 | 1,957 | package com.marianhello.bgloc.data;
import com.marianhello.utils.CloneHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by finch on 9.12.2017.
*/
public class HashMapLocationTemplate extends AbstractLocationTemplate implements Serializable {
private HashMap<?, String> mMap;
private static final long serialVersionUID = 1234L;
// copy constructor
public HashMapLocationTemplate(HashMapLocationTemplate tpl) {
if (tpl == null || tpl.mMap == null) {
return;
}
mMap = CloneHelper.deepCopy(tpl.mMap);
}
public HashMapLocationTemplate(HashMap map) {
this.mMap = map;
}
@Override
public Object locationToJson(BackgroundLocation location) throws JSONException {
return LocationMapper.map(location).withMap(mMap);
}
public Iterator iterator() {
return mMap.entrySet().iterator();
}
public boolean containsKey(String propName) {
return mMap.containsKey(propName);
}
public String get(String key) {
return mMap.get(key);
}
@Override
public boolean isEmpty() {
return mMap == null || mMap.isEmpty();
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof HashMapLocationTemplate)) return false;
return ((HashMapLocationTemplate) other).mMap.equals(this.mMap);
}
@Override
public String toString() {
if (mMap == null) {
return "null";
}
JSONObject jObject = new JSONObject(mMap);
return jObject.toString();
}
public Map toMap() {
return mMap;
}
@Override
public LocationTemplate clone() {
return new HashMapLocationTemplate(this);
}
}
| 23.578313 | 95 | 0.645376 |
0ca25735bab72a670024060e70f069908cf01cec | 354 | package net.kanjitomo.dictionary;
/**
* How is search string matched against target string
*/
public enum SearchMode {
/**
* Target string must match search string exactly
*/
EQUALS,
/**
* Target string must start with search string
*/
STARTS_WITH,
/**
* Target string must contain search string in any positions
*/
CONTAINS;
}
| 15.391304 | 61 | 0.686441 |
e9dd7ee12167e61067d447c04997acfa2a594620 | 821 | package com.example.myeatingmapdemo.ListView;
public class ListViewItem {
private String POIStr;
private String AddressStr;
private double POIlatitude;
private double POIlongitude;
public ListViewItem() {
POIStr = new String();
AddressStr = new String();
POIlatitude = 0;
POIlongitude = 0;
}
public String getPOIStr() { return POIStr; }
public String getAddressStr() { return AddressStr; }
public double getPOIlatitude() { return POIlatitude; }
public double getPOIlongitude() { return POIlongitude; }
public void setPOIStr(String POI) { POIStr = POI; }
public void setAddressStr(String address) { AddressStr = address; }
public void setPOIlatitude(double latitude) { POIlatitude = latitude; }
public void setPOIlongitude(double longitude) { POIlongitude = longitude; }
}
| 30.407407 | 77 | 0.732034 |
f5d5e3cd62623b7662fb7034753fdea52a4f387d | 4,060 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.adapters.authenticationplugins.gaianimpersonation;
import com.ibm.gaiandb.GaianAuthenticator;
import org.apache.derby.authentication.UserAuthenticator;
import java.sql.SQLException;
import java.util.Properties;
/**
* ProxyUserAuthenticator performs the user authentication for the user name using the proxy properties or the basic
* authentication if proxy properties or not set up.
*/
public class ProxyUserAuthenticator implements UserAuthenticator {
private static final com.ibm.gaiandb.Logger logger = new com.ibm.gaiandb.Logger("ProxyUserAuthenticator", 30);
private static final String PROXY_UID_KEY = "proxy-user";
private static final String PROXY_PWD_KEY = "proxy-pwd";
private static final GaianAuthenticator basAuth = new GaianAuthenticator();
/**
* Authenticate the user using proxy properties for the default ones
*
* @param userName the name of the user that should be authenticated
* @param passwordOrSid password to authenticate the user
* @param dbName database name
* @param info properties
* @return boolean if the authentication was successful or not
* @throws SQLException provides information on a database access error or other errors
*/
public boolean authenticateUser(String userName, String passwordOrSid, String dbName, Properties info) throws SQLException {
String userId = info.getProperty(PROXY_UID_KEY);
String password = info.getProperty(PROXY_PWD_KEY);
boolean isAuthenticated = performProxyAuthentication(userName, dbName, info, userId, password);
if (!isAuthenticated) {
isAuthenticated = performRegularAuthentication(userName, passwordOrSid, dbName, info);
}
if (isAuthenticated) {
logger.logDetail("authentication was successful");
} else {
logger.logDetail("authentication failed");
}
return isAuthenticated;
}
/**
* In case that the proxy authentication failed or the proxy user is not used,
* perform regular authentication for the user, no need to manipulate properties.
*
* @param userName the name of the user that should be authenticated
* @param passwordOrSid password to authenticate the user
* @param dbName database name
* @param info properties
* @return boolean true if the authentication was successful
* @throws SQLException provides information on a database access error or other errors
*/
private boolean performRegularAuthentication(String userName, String passwordOrSid, String dbName, Properties info) throws SQLException {
logger.logDetail("Performing regular authentication for user:" + userName);
return basAuth.authenticateUser(userName, passwordOrSid, dbName, info);
}
/**
* Authentication based on this proxy user and can assert identity amd force automatic creation of schema
* There are no additional checks to control if this user has privileges to perform escalation.
*
* @param userName the name of the user that should be authenticated
* @param dbName database name
* @param info properties
* @param userId user identifier
* @param password user password
* @return boolean true if the authentication was successful
* @throws SQLException provides information on a database access error or other errors
*/
private boolean performProxyAuthentication(String userName, String dbName, Properties info, String userId, String password) throws SQLException {
if (userId == null || password == null) {
return false;
}
logger.logDetail("Performing proxy authentication with user:" + userId + " on behalf of:" + userName);
info.setProperty("create", "true");
return basAuth.authenticateUser(userId, password, dbName, info);
}
} | 44.130435 | 149 | 0.714039 |
212b619e24b16ebce4e0f30e7a2bbfa7f4646069 | 7,571 | package gamePlay.boardGrid;
import State.GameState;
import javafx.collections.ObservableList;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import gamePlay.preGame.playerSelect;
import Objects.*;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class boardGrid {
// grid pane
protected static GridPane board = new GridPane();
private static int height = 10, width = 10;
private static boardScore currentScore;
private static turns currentTurn;
private static ArrayList<String> playerList;
private static final ArrayList<Color> colors = new ArrayList<>();
// load an arraylist to the grid
private static void loadGrid(Stage primaryStage, ArrayList<ArrayList<boardCell>> table){
/*
table:
[i] is width
[j] is height
*/
for (int i = 0; i < table.size(); i++){
for (int j = 0; j < table.get(i).size(); j++){
boardCell currentCell = table.get(i).get(j);
if (currentCell == null) { continue; } // empty cell element
board.add(table.get(i).get(j).
getCellObject(primaryStage, currentScore, currentTurn), // button or board element
i, // x coordinate
j // y coordinate
);
setDrag(table.get(i).get(j));
}
}
}
// convert possible stackPane table to boardCell table
// TODO: work with Binary-Brothers
private static ArrayList<ArrayList<boardCell>> stackToCell(ArrayList<ArrayList<StackPane>> stackTable){
ArrayList<ArrayList<boardCell>> cellTable = new ArrayList<>();
for (int i = 0; i < stackTable.size(); i++){
ArrayList<boardCell> currentRow = new ArrayList<>();
for (int j = 0; j < stackTable.get(i).size(); j++){
boardCell currentCell = new boardCell();
currentCell.setPosition(i, j);
if (stackTable.get(i).get(j) != null){ // load stack
currentCell.loadStack(stackTable.get(i).get(j));
currentRow.add(currentCell);
continue;
}
// if it's an empty stack pane, then create some default features
currentCell.loadCellImage(i % 2 == 0? "src/gamePlay/images/fish.jpeg": "src/gamePlay/images/marius.jpeg");
currentCell.setIndex(i + j * width + 1);
currentRow.add(currentCell);
}
cellTable.add(currentRow);
}
return cellTable;
}
protected static void updatePlayerScore(String name, int amount){
// TODO: checking winning or scoring condition
boolean condition = true;
if (condition){
currentScore.updateScore(name, amount);
}
}
public void updateCell(Stage primaryStage, boardCell cell, int x, int y, StackPane object){
// TODO: replace cell method
try{
board.getChildren().remove(x, y);
board.add(
cell.getCellObject(primaryStage, currentScore, currentTurn),
x,
y
);
}
catch (Exception ignored) {
board.add(
cell.getCellObject(primaryStage, currentScore, currentTurn),
x,
y
);
}
}
/*
Will move whatever is in the top of the stackpane to another location
*/
public static void movePiece(int origX, int origY, int destX, int destY){
StackPane origin = getBoardCell(origX, origY);
StackPane destination = getBoardCell(destX, destY);
destination.getChildren().addAll(origin.getChildren().get(1));
}
//Add initial pieces to the board
public static void addInitialPlayers(List<Player> players) {
for (int i = 0; i < 5; i++) {
colors.add(Color.ORANGE);
colors.add(Color.AQUA);
colors.add(Color.PINK);
colors.add(Color.GREEN);
colors.add(Color.MAGENTA);
colors.add(Color.WHITE);
}
for (int i = 0; i < players.size(); i++) {
Player player = players.get(i);
Tile tile = player.getTile();
StackPane destination = getBoardCell(tile.getX(), tile.getY());
Rectangle rect = new Rectangle(80,80);
rect.setFill(colors.get(i % 5));
destination.getChildren().addAll(rect);
}
}
/*
********************************
get cell based on the coordinate
*/
//TODO: This is the function that I need to call in order to do the stackpane animation for dragging
public static StackPane getBoardCell(int x, int y){
Node node = null;
ObservableList<Node> childerns = board.getChildren();
for (Node n : childerns){
if (board.getRowIndex(n) == x && board.getColumnIndex(n) == y){
node = n;
break;
}
}
return (node instanceof StackPane)? (StackPane) node : null;
}
// set drag motion for the cell
protected static void setDrag(boardCell cell){
/*
from Binary-Brother Branch
*/
cell.getStack().setCursor(Cursor.HAND);
// stack was pressed:
cell.getStack().setOnMousePressed((event -> {
int orgX = cell.getPosition()[0]; int orgY = cell.getPosition()[1];
StackPane current = cell.getStack();
current.toFront();
}));
// stack was dragged
cell.getStack().setOnMouseDragged((event -> {
}));
}
public static HBox createScore(){
return currentScore.scoreBox();
}
public static StackPane createTurns(){
return currentTurn.displayTurns();
}
public static GridPane createBoard(Stage primaryStage, ArrayList<String> players, ArrayList<ArrayList<StackPane>> cellTable){
width = cellTable.size();
height = cellTable.get(0).size();
int widthPercentage = 100 / width;
int heightPercentage = 100 / height;
playerList = new ArrayList<>();
if (players == null){
players = new ArrayList<>();
players.add(null);
}
playerList.addAll(players);
// create local score and turns objects
currentScore = new boardScore(playerList);
currentTurn = new turns(currentScore);
// column constraints
for (int i = 0; i < width; i++){
ColumnConstraints column = new ColumnConstraints();
column.setPercentWidth(widthPercentage);
board.getColumnConstraints().
add(column);
}
// row constraints
for (int j = 0; j < height; j++){
RowConstraints row = new RowConstraints();
row.setPercentHeight(heightPercentage);
board.getRowConstraints().
add(row);
}
loadGrid(primaryStage, stackToCell(cellTable)); // load from a 2d array
// testing update board cell
// StackPane a = getBoardCell(3, 3);
// a.getChildren().remove(0, 2);
// a.getChildren().addAll(getBoardCell(1, 0).getChildren());
//movePiece(3, 3, 4, 4);
return board;
}
}
| 32.080508 | 129 | 0.56439 |
e90481931d3836ec0224270263f46a85a172b1a2 | 10,713 | package com.lakeel.altla.vision.nearby.presentation.view.activity;
import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lakeel.altla.vision.nearby.R;
import com.lakeel.altla.vision.nearby.presentation.application.App;
import com.lakeel.altla.vision.nearby.presentation.di.component.ViewComponent;
import com.lakeel.altla.vision.nearby.presentation.presenter.ActivityPresenter;
import com.lakeel.altla.vision.nearby.presentation.presenter.model.ActivityModel;
import com.lakeel.altla.vision.nearby.presentation.service.AdvertiseService;
import com.lakeel.altla.vision.nearby.presentation.view.ActivityView;
import com.lakeel.altla.vision.nearby.presentation.view.fragment.FragmentController;
import com.lakeel.altla.vision.nearby.presentation.view.intent.IntentKey;
import com.lakeel.altla.vision.nearby.presentation.view.layout.DrawerHeaderLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ActivityView {
@Inject
ActivityPresenter presenter;
private static final Logger LOGGER = LoggerFactory.getLogger(MainActivity.class);
private static final int REQUEST_CODE_ENABLE_BLE = 1;
private static final int REQUEST_CODE_ACCESS_FINE_LOCATION = 2;
private DrawerHeaderLayout drawerHeaderLayout = new DrawerHeaderLayout();
private ViewComponent viewComponent;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private RelativeLayout mainLayout;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
// Memo:
// By the management of the memory by the Android OS, re-construction of Fragment is carried out automatically.
// But once you create an instance of the Dagger after super#onCreate(),
// it will be done token rebuild the Fragment in the processing of the super#onCreate.
// because the NullPointerException occurs, create an instance of the Dagger before super#onCreate().
// Dagger
viewComponent = App.getApplicationComponent(this).viewComponent();
viewComponent.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = ButterKnife.findById(this, R.id.fragmentPlaceholder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
drawerLayout.addDrawerListener(toggle);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
ButterKnife.bind(drawerHeaderLayout, headerView);
presenter.onCreateView(this);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
presenter.onStop();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (REQUEST_CODE_ENABLE_BLE == requestCode) {
if (RESULT_OK == resultCode) {
presenter.onBleEnabled();
} else {
LOGGER.error("Failed token enable BLE.");
showSnackBar(R.string.snackBar_error_not_enable_ble);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
presenter.onAccessFineLocationGranted();
} else {
presenter.onAccessFineLocationDenied();
LOGGER.warn("Access fine location permission is denied.");
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return toggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.favorites: {
FragmentController controller = new FragmentController(this);
controller.showFavoriteListFragment();
break;
}
case R.id.history: {
FragmentController controller = new FragmentController(this);
controller.showNearbyHistoryListFragment();
break;
}
case R.id.nearby: {
FragmentController controller = new FragmentController(this);
controller.showNearbyUserListFragment();
break;
}
case R.id.information: {
FragmentController controller = new FragmentController(this);
controller.showInformationListFragment();
break;
}
case R.id.settings: {
FragmentController controller = new FragmentController(this);
controller.showSettingsFragment();
break;
}
case R.id.signOut:
presenter.onSignOut(this);
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void showSignInFragment() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(false);
}
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
FragmentController fragmentController = new FragmentController(this);
fragmentController.showSignInFragment();
}
@Override
public void updateDrawerProfile(@NonNull ActivityModel model) {
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(model.imageUri, drawerHeaderLayout.userImageView);
drawerHeaderLayout.userNameTextView.setText(model.userName);
drawerHeaderLayout.emailTextView.setText(model.email);
}
@Override
public void showAdvertiseDisableConfirmDialog() {
MaterialDialog.Builder builder = new MaterialDialog.Builder(MainActivity.this);
builder.title(R.string.dialog_title_confirm);
builder.positiveText(R.string.dialog_button_positive);
builder.content(R.string.snackBar_message_advertise_disable);
builder.show();
}
@Override
public void showBleEnabledActivity() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_CODE_ENABLE_BLE);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void requestAccessFineLocationPermission() {
MainActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ACCESS_FINE_LOCATION);
}
@Override
public void startDetectBeaconsInBackground() {
App.startDetectBeaconsInBackground(this);
}
@Override
public void stopDetectBeaconsInBackground() {
App.stopDetectBeaconsInBackground(this);
}
@Override
public void startAdvertiseInBackground(@NonNull String beaconId) {
Intent intent = new Intent(getApplicationContext(), AdvertiseService.class);
intent.putExtra(IntentKey.BEACON_ID.name(), beaconId);
getApplicationContext().startService(intent);
}
@Override
public void finishActivity() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAndRemoveTask();
} else {
finish();
}
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
@Override
public void showFavoriteListFragment() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
FragmentController fragmentController = new FragmentController(this);
fragmentController.showFavoriteListFragment();
}
@Override
public void showSnackBar(int resId) {
Snackbar.make(mainLayout, resId, Snackbar.LENGTH_SHORT).show();
}
public static ViewComponent getUserComponent(@NonNull Fragment fragment) {
return ((MainActivity) fragment.getActivity()).viewComponent;
}
public void setDrawerIndicatorEnabled(boolean enabled) {
toggle.setDrawerIndicatorEnabled(enabled);
}
public void onSignedIn() {
presenter.onSignedIn();
}
}
| 35.829431 | 136 | 0.696537 |
d92d9561d4433de24fca9b9631883523c0a031d7 | 4,763 | package com.imagelab.operator.imagecontours;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import com.imagelab.operator.OpenCVOperator;
import com.imagelab.operator.basic.ReadImage;
import com.imagelab.operator.basic.WriteImage;
import com.imagelab.operator.drawing.DrawCircle;
import com.imagelab.operator.drawing.DrawLine;
import com.imagelab.operator.filtering.ApplyBoxFilter;
import com.imagelab.operator.filtering.ApplyErosion;
import com.imagelab.operator.filtering.ApplyImagePyramid;
import com.imagelab.operator.filtering.ApplyImagePyramidDown;
import com.imagelab.operator.geotransformation.ImageAffine;
import com.imagelab.operator.geotransformation.ImageReflection;
import com.imagelab.operator.geotransformation.RotateImage;
import com.imagelab.operator.imagebluring.ApplyBlurEffect;
import com.imagelab.operator.imagebluring.ApplyGaussianBlurEffect;
import com.imagelab.operator.imagebluring.ApplyMedianBlurEffect;
import com.imagelab.operator.imageconversion.ColoredImageToBinary;
import com.imagelab.operator.imageconversion.ConvertToGrayscale;
public class BoundingBoxesForContours extends OpenCVOperator {
/*
* Contours
*/
private ArrayList<MatOfPoint> contours;
/*
* Random value - colors
*/
private Random rng = new Random(12345);
@Override
public boolean validate(OpenCVOperator previous) {
if (previous == null || previous.getClass() != FindContours.class) {
return false;
}else if(previous.getClass() == FindContours.class) {
contours = FindContours.getContours();
}
return allowedOperators().contains(previous.getClass());
}
@Override
public Mat compute(Mat image) {
// TODO Auto-generated method stub
return boudingBoxContours(image,getContoursList());
}
private Mat boudingBoxContours(Mat drawing, ArrayList<MatOfPoint> contours) {
// TODO Auto-generated method stub
MatOfPoint2f[] contoursPoly = new MatOfPoint2f[contours.size()];
Rect[] boundRect = new Rect[contours.size()];
Point[] centers = new Point[contours.size()];
float[][] radius = new float[contours.size()][1];
/*
* For every found contour apply approximation to polygons with accuracy +-3
*/
for (int i = 0; i < contours.size(); i++) {
contoursPoly[i] = new MatOfPoint2f();
Imgproc.approxPolyDP(new MatOfPoint2f(contours.get(i).toArray()), contoursPoly[i], 3, true);
boundRect[i] = Imgproc.boundingRect(new MatOfPoint(contoursPoly[i].toArray()));
centers[i] = new Point();
Imgproc.minEnclosingCircle(contoursPoly[i], centers[i], radius[i]);
}
/*
* For every contour: pick a random color, draw the cotour by last operator and bounding box
*/
ArrayList<MatOfPoint> contoursPolyList = new ArrayList<>(contoursPoly.length);
for (MatOfPoint2f poly : contoursPoly) {
contoursPolyList.add(new MatOfPoint(poly.toArray()));
}
for (int i = 0; i < contours.size(); i++) {
Scalar color = new Scalar(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256));
/*
* No need to draw contours again. Since last operator find and draw the contours
*/
//Imgproc.drawContours(drawing, contoursPolyList, i, color);
Imgproc.rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2);
Imgproc.circle(drawing, centers[i], (int) radius[i][0], color, 2);
}
return drawing;
}
/**
* allowed operators can only have before applying the bounding boxes
*/
@Override
public Set<Class<?>> allowedOperators() {
Set<Class<?>> allowed = new HashSet<>();
allowed.add(ReadImage.class);
allowed.add(WriteImage.class);
allowed.add(FindContours.class);
return allowed;
}
public ArrayList<MatOfPoint> getContoursList() {
return this.contours;
}
public enum Information {
/**
* Operator information in string format.
*/
OPERATOR_INFO {
/**
* @return - Operator information and name
* of the operator.
*/
public String toString() {
return "Bounding Boxes for Contours\n\n"
+ "This operation will bound the identified contours for the given image. It uses cv.rectangle()"
+ "to draw the boxes."
;
}
}
}
}
| 36.083333 | 115 | 0.674995 |
6a768c607950a5a42745a80bd4c8b90faa7278d9 | 181 | package sol_engine.utils.mutable_primitives;
public class MVal<T> {
public T value;
public MVal() {
}
public MVal(T value) {
this.value = value;
}
}
| 12.928571 | 44 | 0.596685 |
e20d4d9407e112bd8f319626050d6b703154f72e | 2,244 | package org.practice.trees;
public class q428 {
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Codec {
// Encodes a tree to a single string.
public String serialize(Node root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
System.out.println(sb.toString());
return sb.toString();
}
// Decodes your encoded data to tree.
public Node deserialize(String data) {
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(",")));
return buildTree(nodes);
// return null;
}
public void buildString(Node node, StringBuilder sb) {
if(node == null) {
sb.append("n").append(",");
return;
}
else {
sb.append(node.val).append(",");
if(node.children.isEmpty()) {
buildString(null, sb);
}
else {
for(Node child: node.children) {
buildString(child, sb);
}
sb.append("x").append(",");
}
}
}
public Node buildTree(Deque<String> nodes) {
if(nodes.isEmpty()) return null;
String str = nodes.remove();
System.out.println(str);
if(str.equals("n")) {
return null;
}
else {
Node node = new Node(Integer.valueOf(str));
while(!nodes.peek().equals("x")) {
Node child = buildTree(nodes);
if(child != null) node.children.add(child);
}
nodes.remove();
return node;
}
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
}
| 26.714286 | 63 | 0.467023 |
989d1c50e0535e1169eb4d6cbfc7a2a295c4b3f0 | 1,943 | package aracket.linking.std;
import a10lib.compiler.syntax.Statement;
import aracket.core.RacketDictionary;
import aracket.core.RacketInterpreter;
import aracket.lang.RacketBaseFunction;
import aracket.lang.RacketFunction;
import aracket.lang.RacketList;
import aracket.lang.RacketObject;
/**
* A function that take function then use that function to utilize it with a
* list in some way
*
* @author Athensclub
*
*/
public class ListManipulationFunction extends RacketBaseFunction {
/**
* A class that use function and list to work
*
* @author Athensclub
*
*/
@FunctionalInterface
public interface ListManipulation {
/**
* Invoke this function
*/
public RacketObject apply(RacketDictionary scope, RacketList list, RacketFunction function);
}
private ListManipulation implementation;
private String name;
public ListManipulationFunction(RacketInterpreter interpreter, String name, ListManipulation implementation) {
super(interpreter);
this.implementation = implementation;
this.name = name;
}
@Override
public RacketObject invoke(RacketDictionary scope, Statement... args) {
if(args.length == 2) {
RacketObject first = getInterpreter().evaluate(args[0], scope);
if(first instanceof RacketBaseFunction) {
RacketObject second = getInterpreter().evaluate(args[1],scope);
if(second instanceof RacketList) {
return implementation.apply(scope, (RacketList)second, ((RacketBaseFunction) first).asRacketFunction());
}else {
throw new IllegalArgumentException(name + " expected second argument as list found: " + second);
}
}else {
throw new IllegalArgumentException(name + " expected first argument as procedure found: " + first);
}
}else {
throw new IllegalArgumentException(name + " expected 2 arguments found: " + args.length);
}
}
}
| 29.439394 | 115 | 0.703551 |
59ba59b9edcf34b23da759a852ed5b2e5d915f4a | 6,323 | package com.sparkystudios.traklibrary.game.service.client.impl;
import com.google.common.io.Files;
import com.sparkystudios.traklibrary.game.service.client.ImageClient;
import com.sparkystudios.traklibrary.game.service.exception.UploadFailedException;
import com.sparkystudios.traklibrary.security.AuthenticationService;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
@Slf4j
@RequiredArgsConstructor
@Component
public class ImageClientCircuitBreakerImpl implements ImageClient {
private static final String COMPANY_UPLOAD_FAILED_MESSAGE = "company-image.exception.upload-failed";
private static final String DOWNLOADABLE_CONTENT_UPLOAD_FAILED_MESSAGE = "downloadable-content-image.exception.upload-failed";
private static final String GAME_UPLOAD_FAILED_MESSAGE = "game-image.exception.upload-failed";
private static final String PLATFORM_UPLOAD_FAILED_MESSAGE = "platform-image.exception.upload-failed";
private final AuthenticationService authenticationService;
@SuppressWarnings("all")
private final CircuitBreakerFactory circuitBreakerFactory;
private final MessageSource messageSource;
private final RestTemplate restTemplate;
@Setter
private CircuitBreaker imageServerCircuitBreaker;
@PostConstruct
private void postConstruct() {
imageServerCircuitBreaker = circuitBreakerFactory.create("image-server-circuit-breaker");
}
@Override
public void uploadCompanyImage(MultipartFile multipartFile, long companyId) {
uploadImage(multipartFile, COMPANY_UPLOAD_FAILED_MESSAGE, companyId, "/companies");
}
@Override
public void uploadDownloadableContentImage(MultipartFile multipartFile, long downloadableContentId) {
uploadImage(multipartFile, DOWNLOADABLE_CONTENT_UPLOAD_FAILED_MESSAGE, downloadableContentId, "/dlc");
}
@Override
public void uploadGameImage(MultipartFile multipartFile, long gameId) {
uploadImage(multipartFile, GAME_UPLOAD_FAILED_MESSAGE, gameId, "");
}
@Override
public void uploadPlatformImage(MultipartFile multipartFile, long platformId) {
uploadImage(multipartFile, PLATFORM_UPLOAD_FAILED_MESSAGE, platformId, "/platforms");
}
private void uploadImage(MultipartFile multipartFile, String failureMessage, long id, String folder) {
// Create a temporary directory for the file to ensure the name doesn't clash with any other files.
@SuppressWarnings("UnstableApiUsage")
var file = new File(Files.createTempDir(), Objects.requireNonNull(multipartFile.getOriginalFilename()));
// Write the contents of the file to the new temporary file created.
try (var stream = new FileOutputStream(file)) {
stream.write(multipartFile.getBytes());
} catch (IOException e) {
String errorMessage = messageSource
.getMessage(failureMessage, new Object[] { id }, LocaleContextHolder.getLocale());
throw new UploadFailedException(errorMessage, e);
}
// Create the http headers with the multi-part file for the image service request.
var httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
httpHeaders.setBearerAuth(authenticationService.getToken());
// Jackson struggles to serialize MultipartFile objects, so it's sent up as a file system resource.
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(file));
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, httpHeaders);
// Send the request. We'll fail the call if the image can't be uploaded to keep the table
// and image provider in sync with one another.
imageServerCircuitBreaker.run(() ->
restTemplate.postForEntity("http://trak-image-server/games" + folder, requestEntity, Void.class), throwable -> {
String errorMessage = messageSource
.getMessage(failureMessage, new Object[] { id }, LocaleContextHolder.getLocale());
throw new UploadFailedException(errorMessage, throwable);
});
}
@Override
public byte[] downloadCompanyImage(String filename) {
return downloadImage("/companies", filename);
}
@Override
public byte[] downloadDownloadableContentImage(String filename) {
return downloadImage("/dlc", filename);
}
@Override
public byte[] downloadGameImage(String filename) {
return downloadImage("", filename);
}
@Override
public byte[] downloadPlatformImage(String filename) {
return downloadImage("/platforms", filename);
}
private byte[] downloadImage(String folder, String filename) {
return imageServerCircuitBreaker.run(() -> {
ByteArrayResource resource = restTemplate
.getForObject("http://trak-image-server/games" + folder + "/{filename}", ByteArrayResource.class, filename);
return resource != null ? resource.getByteArray() : new byte[0];
},
throwable -> {
log.error("Failed to retrieve image: " + folder + "/" + filename, throwable);
return new byte[0];
});
}
}
| 43.606897 | 136 | 0.729559 |
9f0d7fd5b54f2293462758c977b8cf9e9e891e63 | 1,309 | package commands.audio;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import commands.audio.managers.PlayerManager;
import commands.owner.Settings;
public class Queue extends Command {
public Queue() {
this.name = "queue";
this.aliases = new String[]{"queue", "q"};
this.arguments = "[0]Queue, [1]PageNumber";
this.help = "Provides a list of audio tracks queued.";
}
@Override
protected void execute(CommandEvent ce) {
Settings.deleteInvoke(ce);
String[] args = ce.getMessage().getContentRaw().split("\\s"); // Parse message for arguments
int arguments = args.length;
switch (arguments) {
case 1 -> { // First page
PlayerManager.getINSTANCE().getPlaybackManager(ce.getGuild()).audioScheduler.getQueue(ce, 0);
}
case 2 -> {
try { // Custom page
PlayerManager.getINSTANCE().getPlaybackManager(ce.getGuild())
.audioScheduler.getQueue(ce, Integer.parseInt(args[1]) - 1);
} catch (NumberFormatException error) { // Invalid argument
ce.getChannel().sendMessage("Page number must be a number.").queue();
}
} // Invalid arguments
default -> ce.getChannel().sendMessage("Invalid number of arguments.").queue();
}
}
} | 36.361111 | 101 | 0.664629 |
532976e50716a68b2f1f45a9d47f90639fde9c4a | 4,402 | package de.javagl.geom;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Integration test for the {@link CatmullRomSpline} class
*/
@SuppressWarnings({"javadoc"})
public class CatmullRomSplineTest{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new CatmullRomSplineTestPanel());
f.setSize(800, 800);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
@SuppressWarnings({"javadoc", "serial"})
class CatmullRomSplineTestPanel extends JPanel
implements MouseListener, MouseMotionListener{
private final List<Point2D> pointList;
private CatmullRomSpline spline;
private Point2D draggedPoint;
private int draggedPointIndex;
private JSlider slider;
public CatmullRomSplineTestPanel(){
this.pointList = new ArrayList<Point2D>();
pointList.add(new Point2D.Double(132, 532));
pointList.add(new Point2D.Double(275, 258));
pointList.add(new Point2D.Double(295, 267));
pointList.add(new Point2D.Double(433, 567));
pointList.add(new Point2D.Double(476, 635));
pointList.add(new Point2D.Double(350, 123));
pointList.add(new Point2D.Double(246, 512));
pointList.add(new Point2D.Double(93, 12));
spline = CatmullRomSpline.create(pointList, 20, 0.0);
slider = new JSlider(0, 100, 0);
slider.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
double alpha = slider.getValue() / 100.0;
spline.setInterpolation(alpha);
repaint();
}
});
add(slider);
final JCheckBox checkBox = new JCheckBox("Closed?");
checkBox.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
boolean closed = checkBox.isSelected();
spline = CatmullRomSpline.create(pointList, 20, 0.0, closed);
repaint();
}
});
add(checkBox);
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
protected void paintComponent(Graphics gr){
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
g.setColor(Color.RED);
for(Point2D p : pointList){
double r = 5;
g.draw(new Ellipse2D.Double(p.getX() - r, p.getY() - r, r + r, r + r));
}
g.setColor(Color.BLACK);
g.draw(Paths.fromPoints(spline.getInterpolatedPoints(), false));
}
@Override
public void mouseDragged(MouseEvent e){
if(draggedPoint != null){
draggedPoint.setLocation(e.getX(), e.getY());
spline.updateControlPoint(draggedPointIndex, draggedPoint);
repaint();
System.out.println("Points: ");
for(Point2D p : pointList){
System.out.println(" " + p);
}
}
}
@Override
public void mouseMoved(MouseEvent e){
// Nothing to do here
}
@Override
public void mouseClicked(MouseEvent e){
// Nothing to do here
}
@Override
public void mousePressed(MouseEvent e){
final double thresholdSquared = 10 * 10;
Point2D p = e.getPoint();
Point2D closestPoint = null;
double minDistanceSquared = Double.MAX_VALUE;
for(Point2D point : pointList){
double dd = point.distanceSq(p);
if(dd < thresholdSquared && dd < minDistanceSquared){
minDistanceSquared = dd;
closestPoint = point;
}
}
draggedPoint = closestPoint;
draggedPointIndex = pointList.indexOf(closestPoint);
}
@Override
public void mouseReleased(MouseEvent e){
draggedPoint = null;
}
@Override
public void mouseEntered(MouseEvent e){
// Nothing to do here
}
@Override
public void mouseExited(MouseEvent e){
// Nothing to do here
}
} | 25.011364 | 75 | 0.695139 |
ddf973eaed90e94ac65403db4f2fcb2ce26d10a9 | 8,924 | package io.github.luizgrp.sectionedrecyclerviewadapter.demo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection;
public class Example8Fragment extends Fragment {
private static final Random RANDOM = new Random();
private SectionedRecyclerViewAdapter sectionAdapter;
private RecyclerView recyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ex8, container, false);
sectionAdapter = new SectionedRecyclerViewAdapter();
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (sectionAdapter.getSectionItemViewType(position)) {
case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
return 2;
default:
return 1;
}
}
});
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);
addNewSectionToAdapter();
addNewSectionToAdapter();
view.findViewById(R.id.btnAdd).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addNewSectionToAdapter();
}
});
return view;
}
@Override
public void onResume() {
super.onResume();
if (getActivity() instanceof AppCompatActivity) {
AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity.getSupportActionBar() != null) {
activity.getSupportActionBar().setTitle(R.string.nav_example8);
}
}
}
private void addNewSectionToAdapter() {
String randomNumber = getRandomStringNumber();
String sectionTag = String.format("section%sTag", randomNumber);
NameSection section = new NameSection(sectionTag,
getString(R.string.group_title, randomNumber));
sectionAdapter.addSection(sectionTag, section);
int sectionPos = sectionAdapter.getSectionPosition(sectionTag);
sectionAdapter.notifyItemInserted(sectionPos);
recyclerView.smoothScrollToPosition(sectionPos);
}
@NonNull
private String getRandomStringNumber() {
return String.valueOf(RANDOM.nextInt(100000));
}
private Person getRandomName() {
String[] names = getResources().getStringArray(R.array.names);
String[] randomName = names[RANDOM.nextInt(names.length)].split("\\|");
return new Person(randomName[0], "ID #" + getRandomStringNumber());
}
private class NameSection extends StatelessSection {
final String TAG;
String title;
List<Person> list;
NameSection(String tag, String title) {
super(SectionParameters.builder()
.itemResourceId(R.layout.section_ex8_item)
.headerResourceId(R.layout.section_ex8_header)
.build());
this.TAG = tag;
this.title = title;
this.list = new ArrayList<>();
}
@Override
public int getContentItemsTotal() {
return list.size();
}
@Override
public RecyclerView.ViewHolder getItemViewHolder(View view, int viewType) {
return new ItemViewHolder(view);
}
@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
String name = list.get(position).getName();
String category = list.get(position).getId();
itemHolder.tvItem.setText(name);
itemHolder.tvSubItem.setText(category);
itemHolder.imgItem.setImageResource(name.hashCode() % 2 == 0 ? R.drawable.ic_face_black_48dp : R.drawable.ic_tag_faces_black_48dp);
itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int adapterPosition = itemHolder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
int positionInSection = sectionAdapter.getPositionInSection(adapterPosition);
list.remove(positionInSection);
sectionAdapter.notifyItemRemovedFromSection(TAG, positionInSection);
}
}
});
}
@Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
final HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
headerHolder.rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
final int adapterPosition = headerHolder.getAdapterPosition();
if (adapterPosition != RecyclerView.NO_POSITION) {
final int sectionItemsTotal = getSectionItemsTotal();
sectionAdapter.removeSection(TAG);
sectionAdapter.notifyItemRangeRemoved(adapterPosition, sectionItemsTotal);
}
}
});
headerHolder.btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int positionToInsertItemAt = 0;
list.add(positionToInsertItemAt, getRandomName());
sectionAdapter.notifyItemInsertedInSection(TAG, positionToInsertItemAt);
}
});
headerHolder.btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int contentItemsTotal = getContentItemsTotal();
list.clear();
sectionAdapter.notifyItemRangeRemovedFromSection(TAG, 0, contentItemsTotal);
}
});
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final TextView tvTitle;
private final Button btnAdd;
private final Button btnClear;
HeaderViewHolder(View view) {
super(view);
rootView = view;
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
btnAdd = (Button) view.findViewById(R.id.btnAdd);
btnClear = (Button) view.findViewById(R.id.btnClear);
}
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final ImageView imgItem;
private final TextView tvItem;
private final TextView tvSubItem;
ItemViewHolder(View view) {
super(view);
rootView = view;
imgItem = (ImageView) view.findViewById(R.id.imgItem);
tvItem = (TextView) view.findViewById(R.id.tvItem);
tvSubItem = (TextView) view.findViewById(R.id.tvSubItem);
}
}
private class Person {
String name;
String id;
Person(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
| 32.569343 | 143 | 0.617548 |
a31a7fe0f36f6bb01d2ca2a43fc933cfddbd9365 | 1,425 | package com.daolion.view.dialog;
/**
* Created by lixiaodaoaaa on 2016/11/2.
*/
/**
* dialog 的描述 类
*/
public class DialogDescription {
private String title;
private String dialogContent;
private String positiveText;
private String negativeText;
public DialogDescription(String title, String dialogContent, String positiveText, String negativeText) {
this.title = title;
this.dialogContent = dialogContent;
this.positiveText = positiveText;
this.negativeText = negativeText;
}
public DialogDescription(String title, String negativeText, String positiveText) {
this.title = title;
this.negativeText = negativeText;
this.positiveText = positiveText;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDialogContent() {
return dialogContent;
}
public void setDialogContent(String dialogContent) {
this.dialogContent = dialogContent;
}
public String getPositiveText() {
return positiveText;
}
public void setPositiveText(String positiveText) {
this.positiveText = positiveText;
}
public String getNegativeText() {
return negativeText;
}
public void setNegativeText(String negativeText) {
this.negativeText = negativeText;
}
}
| 22.619048 | 108 | 0.66386 |
413f148cc987c3427bcd42e61c88c26d1efd94f9 | 470 | package item41;
// This is supposed to show how overloading works. Don't do this!
final public class Car {
private Integer numberOfDoors;
private int numberOfSeats;
public void design(Integer numberOfDoors) {
this.numberOfDoors = numberOfDoors;
}
public void design(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public Integer getNumberOfDoors() {
return numberOfDoors;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
}
| 18.8 | 65 | 0.746809 |
f05da3d2210672cc788e3a8b5648120d04c430c2 | 2,955 | package org.jfree.ui;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Rectangle;
public final class OverlayLayout implements LayoutManager {
private boolean ignoreInvisible;
public OverlayLayout(boolean ignoreInvisible) {
this.ignoreInvisible = ignoreInvisible;
}
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets ins = parent.getInsets();
Rectangle bounds = parent.getBounds();
int width = (bounds.width - ins.left) - ins.right;
int height = (bounds.height - ins.top) - ins.bottom;
Component[] comps = parent.getComponents();
for (int i = 0; i < comps.length; i++) {
Component c = comps[i];
if (comps[i].isVisible() || !this.ignoreInvisible) {
c.setBounds(ins.left, ins.top, width, height);
}
}
}
}
public Dimension minimumLayoutSize(Container parent) {
Dimension dimension;
synchronized (parent.getTreeLock()) {
Insets ins = parent.getInsets();
Component[] comps = parent.getComponents();
int height = 0;
int width = 0;
for (int i = 0; i < comps.length; i++) {
if (comps[i].isVisible() || !this.ignoreInvisible) {
Dimension pref = comps[i].getMinimumSize();
if (pref.height > height) {
height = pref.height;
}
if (pref.width > width) {
width = pref.width;
}
}
}
dimension = new Dimension((ins.left + width) + ins.right, (ins.top + height) + ins.bottom);
}
return dimension;
}
public Dimension preferredLayoutSize(Container parent) {
Dimension dimension;
synchronized (parent.getTreeLock()) {
Insets ins = parent.getInsets();
Component[] comps = parent.getComponents();
int height = 0;
int width = 0;
for (int i = 0; i < comps.length; i++) {
if (comps[i].isVisible() || !this.ignoreInvisible) {
Dimension pref = comps[i].getPreferredSize();
if (pref.height > height) {
height = pref.height;
}
if (pref.width > width) {
width = pref.width;
}
}
}
dimension = new Dimension((ins.left + width) + ins.right, (ins.top + height) + ins.bottom);
}
return dimension;
}
}
| 34.764706 | 103 | 0.521151 |
9b63b6243a2b2c08db681e613eac6b19c4126ad7 | 1,022 | package chopchop.testutil;
import static chopchop.logic.parser.CliSyntax.PREFIX_EXPIRY;
import static chopchop.logic.parser.CliSyntax.PREFIX_QUANTITY;
import chopchop.logic.commands.AddIngredientCommand;
import chopchop.model.ingredient.Ingredient;
/**
* A utility class for Ingredient.
*/
public class IngredientUtil {
/**
* Returns an add command string for adding the {@code ingredient}.
*/
public static String getAddCommand(Ingredient ind) {
return AddIngredientCommand.COMMAND_WORD + " " + getIngredientDetails(ind);
}
/**
* Returns the part of command string for the given {@code ingredient}'s details.
*/
public static String getIngredientDetails(Ingredient ind) {
StringBuilder sb = new StringBuilder();
sb.append(ind.getName().fullName + " ");
sb.append(PREFIX_QUANTITY + Double.toString(ind.getQuantity().value) + " ");
sb.append(PREFIX_EXPIRY + ind.getExpiryDate().toString() + " ");
return sb.toString();
}
}
| 30.969697 | 85 | 0.695695 |
6dea53c2dbd023b340ad0c2e8a2340cef2710a0a | 6,391 | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.refactoring.contentassist;
import java.util.ArrayList;
import java.util.Arrays;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.contentassist.IContentAssistSubjectControl;
import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.CompletionProposalComparator;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal;
public class JavaPackageCompletionProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor {
private IPackageFragmentRoot fPackageFragmentRoot;
private CompletionProposalComparator fComparator;
private ILabelProvider fLabelProvider;
private char[] fProposalAutoActivationSet;
/**
* Creates a <code>JavaPackageCompletionProcessor</code>.
* The completion context must be set via {@link #setPackageFragmentRoot(IPackageFragmentRoot)}.
*/
public JavaPackageCompletionProcessor() {
this(new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_SMALL_ICONS));
}
/**
* Creates a <code>JavaPackageCompletionProcessor</code>.
* The Processor uses the given <code>ILabelProvider</code> to show text and icons for the
* possible completions.
* @param labelProvider Used for the popups.
*/
public JavaPackageCompletionProcessor(ILabelProvider labelProvider) {
fComparator= new CompletionProposalComparator();
fLabelProvider= labelProvider;
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
String triggers= preferenceStore.getString(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
fProposalAutoActivationSet = triggers.toCharArray();
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$
return null;
}
/*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return fProposalAutoActivationSet;
}
/*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
return null;
}
/*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
return null; //no context
}
/*
* @see ISubjectControlContentAssistProcessor#computeContextInformation(IContentAssistSubjectControl, int)
*/
public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubjectControl,
int documentOffset) {
return null;
}
/*
* @see ISubjectControlContentAssistProcessor#computeCompletionProposals(IContentAssistSubjectControl, int)
*/
public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) {
if (fPackageFragmentRoot == null)
return null;
String input= contentAssistSubjectControl.getDocument().get();
ICompletionProposal[] proposals= createPackagesProposals(documentOffset, input);
Arrays.sort(proposals, fComparator);
return proposals;
}
public void setPackageFragmentRoot(IPackageFragmentRoot packageFragmentRoot) {
fPackageFragmentRoot= packageFragmentRoot;
}
private ICompletionProposal[] createPackagesProposals(int documentOffset, String input) {
ArrayList proposals= new ArrayList();
String prefix= input.substring(0, documentOffset);
try {
IJavaElement[] packageFragments= fPackageFragmentRoot.getChildren();
for (int i= 0; i < packageFragments.length; i++) {
IPackageFragment pack= (IPackageFragment) packageFragments[i];
String packName= pack.getElementName();
if (packName.length() == 0 || ! packName.startsWith(prefix))
continue;
Image image= fLabelProvider.getImage(pack);
JavaCompletionProposal proposal= new JavaCompletionProposal(packName, 0, input.length(), image, fLabelProvider.getText(pack), 0);
proposals.add(proposal);
}
} catch (JavaModelException e) {
//fPackageFragmentRoot is not a proper root -> no proposals
}
return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
}
}
| 39.450617 | 137 | 0.779847 |
b3fead294f6405222e14e14afd374b9893eacb91 | 137 | package com.funbasetools.codecs;
@FunctionalInterface
public interface Decoder<SOURCE, TARGET> {
TARGET decode(final SOURCE src);
}
| 19.571429 | 42 | 0.781022 |
69b016b29b34eaa7d5523ee5c8e1c75fda27367d | 20,629 | package edu.gdei.gdeiassistant.Presenter;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import com.taobao.sophix.SophixManager;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;
import edu.gdei.gdeiassistant.Activity.LoginActivity;
import edu.gdei.gdeiassistant.Activity.MainActivity;
import edu.gdei.gdeiassistant.Application.GdeiAssistantApplication;
import edu.gdei.gdeiassistant.Constant.ActivityRequestCodeConstant;
import edu.gdei.gdeiassistant.Constant.MainTagConstant;
import edu.gdei.gdeiassistant.Constant.PermissionRequestCodeConstant;
import edu.gdei.gdeiassistant.Constant.RequestConstant;
import edu.gdei.gdeiassistant.Model.BitmapFileModel;
import edu.gdei.gdeiassistant.Model.MainModel;
import edu.gdei.gdeiassistant.Pojo.Entity.Access;
import edu.gdei.gdeiassistant.Pojo.Entity.Profile;
import edu.gdei.gdeiassistant.Service.UpgradeService;
import edu.gdei.gdeiassistant.Tools.TokenUtils;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class MainPresenter {
private BroadcastReceiver receiver;
private MainActivity mainActivity;
private MainActivityHandler mainActivityHandler;
private MainModel mainModel;
private String cachePath;
/**
* 移除所有的回调和消息,防止内存泄露
*/
public void RemoveCallBacksAndMessages() {
mainActivityHandler.removeCallbacksAndMessages(null);
}
/**
* 注销广播
*/
public void UnregisterReceiver() {
if (receiver != null) {
mainActivity.unregisterReceiver(receiver);
}
}
/**
* 下载新版本
*
* @param downloadURL
*/
public void DownLoadNewVersion(String downloadURL) {
//使用浏览器下载新版本应用,并接收返回结果
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(Uri.parse(downloadURL));
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
mainActivity.startActivityForResult(Intent.createChooser(intent, "请选择浏览器"), ActivityRequestCodeConstant.BROWSER_UPDATE_REQUEST_CODE);
}
/**
* 检查软件更新
*/
public void CheckUpgrade() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mainActivity.startForegroundService(new Intent(mainActivity, UpgradeService.class));
} else {
mainActivity.startService(new Intent(mainActivity, UpgradeService.class));
}
}
public static class MainActivityHandler extends Handler {
private MainActivity mainActivity;
MainActivityHandler(MainActivity mainActivity) {
this.mainActivity = new WeakReference<>(mainActivity).get();
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case RequestConstant.REQUEST_FAILURE:
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.GET_USER_ACCESS:
case MainTagConstant.GET_USER_PROFILE:
case MainTagConstant.UPLOAD_AVATAR:
mainActivity.ShowToast(msg.getData().getString("Message"));
break;
}
break;
case RequestConstant.REQUEST_SUCCESS:
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
//下载或上传头像成功
File file = new File(mainActivity.getApplicationContext().getCacheDir() + "/gdeiassistant/" + "avatar.jpg");
if (file.exists() && file.canRead()) {
Drawable drawable = Drawable.createFromPath(file.getPath());
mainActivity.SetAvatarImage(drawable);
} else {
mainActivity.ShowToast("获取头像失败,请检查是否正确开启存储权限");
}
break;
case MainTagConstant.GET_USER_PROFILE:
//获取用户资料
Profile profile = (Profile) msg.getData().getSerializable("Profile");
if (profile != null) {
mainActivity.UpdateMainNavigationWelcomeText(profile.getNickname());
}
break;
case MainTagConstant.GET_USER_ACCESS:
//加载用户权限并显示功能菜单
Access access = (Access) msg.getData().getSerializable("Access");
//缓存用户权限信息
((GdeiAssistantApplication) mainActivity.getApplication()).setAccess(access);
mainActivity.LoadAccessAndShowMenu(access);
break;
}
break;
case RequestConstant.REQUEST_TIMEOUT:
//网络连接异常
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
mainActivity.ShowToast("网络连接超时,请重试");
break;
case MainTagConstant.GET_USER_PROFILE:
break;
case MainTagConstant.GET_USER_ACCESS:
mainActivity.ShowToast("网络异常,加载功能菜单失败,请尝试重新登录");
break;
}
break;
case RequestConstant.SERVER_ERROR:
//服务器异常
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
mainActivity.ShowToast("服务暂不可用,请稍候再试");
break;
case MainTagConstant.GET_USER_PROFILE:
break;
case MainTagConstant.GET_USER_ACCESS:
mainActivity.ShowToast("服务器异常,加载功能菜单失败,请尝试重新登录");
break;
}
break;
case RequestConstant.EMPTY_RESULT:
//返回结果为空
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
//显示默认头像
break;
case MainTagConstant.GET_USER_PROFILE:
case MainTagConstant.GET_USER_ACCESS:
break;
}
break;
case RequestConstant.CLIENT_ERROR:
//加载头像失败
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
mainActivity.ShowToast("获取头像失败,请检查是否正确开启存储权限");
break;
case MainTagConstant.GET_USER_PROFILE:
case MainTagConstant.GET_USER_ACCESS:
break;
}
break;
case RequestConstant.UNKNOWN_ERROR:
//未知异常
switch (msg.getData().getInt("Tag")) {
case MainTagConstant.DOWNLOAD_AVATAR:
case MainTagConstant.UPLOAD_AVATAR:
mainActivity.ShowToast("解析头像出现错误");
break;
case MainTagConstant.GET_USER_PROFILE:
break;
case MainTagConstant.GET_USER_ACCESS:
mainActivity.ShowToast("加载功能菜单出现未知异常,请尝试重新登录");
break;
}
break;
}
}
}
public MainPresenter(final MainActivity mainActivity) {
this.mainActivity = mainActivity;
this.cachePath = mainActivity.getApplicationContext().getCacheDir() + "/gdeiassistant/";
this.mainModel = new MainModel();
this.mainActivityHandler = new MainActivityHandler(mainActivity);
Init();
}
private void Init() {
//注册监听广播
if (receiver == null) {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("edu.gdei.gdeiassistant.PATCH_RELAUNCH")) {
//显示补丁冷启动提示
mainActivity.ShowPatchRelaunchTip();
} else if (intent.getAction().equals("edu.gdei.gdeiassistant.CHECK_UPGRADE")) {
String versionCodeName = intent.getStringExtra("VersionCodeName");
String versionInfo = intent.getStringExtra("VersionInfo");
String downloadURL = intent.getStringExtra("DownloadURL");
String fileSize = intent.getStringExtra("FileSize");
//显示更新提示
mainActivity.ShowUpgradeTip(versionCodeName, versionInfo, downloadURL, fileSize);
}
}
}
};
//注册广播监听
mainActivity.registerReceiver(receiver, new IntentFilter("edu.gdei.gdeiassistant.PATCH_RELAUNCH"));
mainActivity.registerReceiver(receiver, new IntentFilter("edu.gdei.gdeiassistant.CHECK_UPGRADE"));
}
//加载用户权限列表信息
GetUserAccess();
}
/**
* 获取用户权限列表信息
*/
public void GetUserAccess() {
mainModel.GetUserAccess(mainActivityHandler, mainActivity.getApplicationContext());
}
/**
* 退出账号
*/
public void Logout() {
try {
final String accessToken = TokenUtils.GetUserAccessToken(mainActivity.getApplicationContext());
final String refreshToken = TokenUtils.GetUserRefreshToken(mainActivity.getApplicationContext());
//发送Token失效请求
new Thread() {
@Override
public void run() {
super.run();
try {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS).readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS).build();
RequestBody requestBody = new FormBody.Builder().add("token", accessToken).build();
Request request = new Request.Builder().post(requestBody).url("https://www.gdeiassistant.cn/rest/token/expire").build();
okHttpClient.newCall(request).execute();
} catch (Exception ignored) {
}
}
}.start();
new Thread() {
@Override
public void run() {
super.run();
try {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS).readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS).build();
RequestBody requestBody = new FormBody.Builder().add("token", refreshToken).build();
Request request = new Request.Builder().post(requestBody).url("https://www.gdeiassistant.cn/rest/token/expire").build();
okHttpClient.newCall(request).execute();
} catch (Exception ignored) {
}
}
}.start();
//清除SharedPreferences保存的令牌信息
TokenUtils.ClearUserToken(mainActivity.getApplicationContext());
//清除本地缓存的用户凭证
GdeiAssistantApplication application = (GdeiAssistantApplication) mainActivity.getApplication();
application.removeAllData();
//清除缓存头像信息
File avatarFile = new File(cachePath + "avatar.jpg");
if (avatarFile.exists() && avatarFile.canWrite()) {
avatarFile.delete();
}
mainActivity.startActivity(new Intent(mainActivity, LoginActivity.class));
mainActivity.finish();
} catch (Exception ignored) {
}
}
/**
* 结束应用程序使补丁生效
*/
public void PatchRelaunchAndStopProcess() {
SophixManager.getInstance().killProcessSafely();
}
/**
* 加载用户资料
*/
public void InitUserProfile() {
if (!CheckStoragePermission()) {
mainActivity.ShowRequestStoragePermissionDialog(PermissionRequestCodeConstant.LOAD_AVATAR);
return;
}
mainModel.DownloadAvatarToOSS(mainActivityHandler, mainActivity.getApplicationContext());
mainModel.GetUserProfile(mainActivityHandler, mainActivity.getApplicationContext());
}
/**
* 打开相册界面,从相册选择图片
*/
public void GetPhotoFromAlbum() {
if (!CheckStoragePermission()) {
//若没有访问存储的权限,则进行申请
mainActivity.ShowRequestStoragePermissionDialog(PermissionRequestCodeConstant.PERMISSION_ALBUM);
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
mainActivity.startActivityForResult(intent, ActivityRequestCodeConstant.RESULT_PHOTO_FROM_ALBUM);
}
/**
* 从相机拍照获取图片
*/
public void GetPhotoFromCamera() {
if (!CheckStoragePermission()) {
//若没有访问存储的权限,则进行申请
mainActivity.ShowRequestStoragePermissionDialog(PermissionRequestCodeConstant.PERMISSION_ALBUM);
return;
}
if (!CheckCameraPermission()) {
//若没有访问相机的权限,则进行申请
mainActivity.ShowRequestCameraPermissionDialog(PermissionRequestCodeConstant.PERMISSION_CAMERA);
return;
}
File avatarDirectory = new File(mainActivity.getCacheDir() + "/gdeiassistant/");
if (!avatarDirectory.exists()) {
avatarDirectory.mkdirs();
}
File file = new File(mainActivity.getCacheDir() + "/gdeiassistant/photo.jpg");
//删除原有的残留照片
if (file.exists()) {
file.delete();
}
Intent intent = new Intent();
intent.setAction("android.media.action.IMAGE_CAPTURE");
intent.addCategory("android.intent.category.DEFAULT");
//保存照片
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri uri = FileProvider.getUriForFile(mainActivity.getApplicationContext(), "edu.gdei.gdeiassistant.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
} else {
Uri uri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mainActivity.startActivityForResult(intent, ActivityRequestCodeConstant.RESULT_PHOTO_FROM_CAMERA);
}
/**
* 将得到的图片进行图片裁剪
*
* @param uri
*/
public void StartPhotoZoom(Uri uri) {
if (uri != null) {
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(uri, "image/*");
//crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
//aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
//outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
mainActivity.startActivityForResult(intent, ActivityRequestCodeConstant.RESULT_SAVE_PHOTO_TO_VIEW);
}
}
/**
* 从相机拍照得到照片,进行裁剪
*/
public void StartCamera(Context context) {
File tempFile = new File(cachePath + "photo.jpg");
if (tempFile.exists() && tempFile.canRead()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri uri = FileProvider.getUriForFile(context, "edu.gdei.gdeiassistant.fileprovider", tempFile);
StartPhotoZoom(uri);
} else {
StartPhotoZoom(Uri.fromFile(tempFile));
}
}
}
/**
* 保存图片到对象存储OSS和本地,同时更新头像图片
*
* @param data
*/
public void SaveAvatarAndSetPhotoToView(Intent data) {
if (data != null) {
File avatarDirectory = new File(mainActivity.getApplicationContext().getCacheDir() + "/gdeiassistant/");
if (!avatarDirectory.exists()) {
avatarDirectory.mkdirs();
}
//保存裁剪之后的照片
Bundle extras = data.getExtras();
if (extras != null) {
//取得SDCard图片路径做显示
Bitmap photo = extras.getParcelable("data");
String urlPath = BitmapFileModel.saveFile(mainActivity.getApplicationContext()
, mainActivity.getCacheDir() + "/gdeiassistant/"
, ((GdeiAssistantApplication) mainActivity.getApplication()).getUsername() + ".jpg", photo);
//删除拍照残留照片
File cameraFile = new File(mainActivity.getCacheDir() + "/gdeiassistant/photo.jpg");
if (cameraFile.exists() && cameraFile.canWrite()) {
cameraFile.delete();
}
File file = new File(urlPath);
if (file.exists() && file.canRead() && file.canWrite()) {
//上传头像文件到对象存储OSS
mainModel.UploadAvatarToOSS(mainActivityHandler, mainActivity.getApplicationContext(), file);
return;
}
}
mainActivity.ShowToast("保存头像失败,请检查是否正确开启存储权限");
}
}
/**
* 申请访问存储权限
*
* @param requestCode
*/
public void RequestStoragePermission(int requestCode) {
ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
}
/**
* 申请访问相机权限
*
* @param requestCode
*/
public void RequestCameraPermission(int requestCode) {
ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.CAMERA}, requestCode);
}
/**
* 检查是否已经获得访问存储权限
*
* @return
*/
private boolean CheckStoragePermission() {
if (ContextCompat.checkSelfPermission(mainActivity.getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return ContextCompat.checkSelfPermission(mainActivity.getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
return false;
}
/**
* 检查是否已经获得访问相机的权限
*
* @return
*/
private boolean CheckCameraPermission() {
return ContextCompat.checkSelfPermission(mainActivity.getApplicationContext(), Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
}
} | 39.368321 | 144 | 0.567114 |
14169ee5f9b1d60a39a48cf60e2d11925e45a761 | 2,153 | package com.pandawork.web.filter;
import com.pandawork.common.utils.WebConstants;
import com.pandawork.core.framework.web.filter.AbstractConstansFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 常量拦截器
*/
public class ConstantsFilter extends AbstractConstansFilter {
private String basePath;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getContextPath();
int port = httpRequest.getServerPort();
basePath = httpRequest.getScheme() + "://" + httpRequest.getServerName()
+ (port == 80 ? "" : (":" + port)) + path + "/";
//不要删除 下载的时候要用
request.setAttribute("tinyStaticWebsite", getTinyStaticWebsite());
request.setAttribute("uploadStaticWebsite", getUploadStaticWebsite());
//添加商城域名
super.doFilter(httpRequest, response, chain);
}
public String getTinyStaticWebsite() {
// return basePath + "resources/";
return WebConstants.staticWebsite;
}
public String getUploadStaticWebsite(){
return WebConstants.staticWebsite + "uploads/";
}
@Override
public String getStaticWebsite() {
// return basePath + "resources/";
return WebConstants.staticWebsite + "resources/";
}
@Override
public String getTinyWebSite() {
return WebConstants.staticWebsite + "uploads/";
}
@Override
public String getWebfullName() {
return WebConstants.webFullName;
}
@Override
public String getWebName() {
return WebConstants.webName;
}
@Override
public String getWebTitle() {
return WebConstants.webTitle;
}
@Override
public String getWebsite() {
return basePath;
}
@Override
public void destroy() {
//noop
}
}
| 25.939759 | 132 | 0.675801 |
7013660e622622d7262beae1ea0ee59a6583fd8d | 8,772 | /*
* Copyright 2014 Mario Guggenberger <mg@protyposis.net>
*
* 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 net.protyposis.android.spectaculumdemo;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import net.protyposis.android.spectaculum.SpectaculumView;
import net.protyposis.android.spectaculum.effects.BooleanParameter;
import net.protyposis.android.spectaculum.effects.EnumParameter;
import net.protyposis.android.spectaculum.effects.FloatParameter;
import net.protyposis.android.spectaculum.effects.IntegerParameter;
import net.protyposis.android.spectaculum.effects.Parameter;
/**
* Created by Mario on 06.09.2014.
*/
public class EffectParameterListAdapter extends BaseAdapter {
private Activity mActivity;
private SpectaculumView mSpectaculumView;
public List<Parameter> mParameters;
public EffectParameterListAdapter(Activity activity, SpectaculumView spectaculumView, List<Parameter> parameters) {
mActivity = activity;
mSpectaculumView = spectaculumView;
mParameters = new ArrayList<>(parameters);
}
@Override
public int getCount() {
return mParameters.size();
}
@Override
public Parameter getItem(int position) {
return mParameters.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Parameter parameter = getItem(position);
View view = convertView;
if(convertView == null || convertView.getTag() != parameter.getClass()) {
if(parameter instanceof EnumParameter) {
view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_spinner, parent, false);
} else if(parameter instanceof BooleanParameter) {
view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_checkbox, parent, false);
} else {
view = mActivity.getLayoutInflater().inflate(R.layout.list_item_parameter_seekbar, parent, false);
}
view.setTag(parameter.getClass());
}
TextView parameterName = (TextView) view.findViewById(R.id.name);
parameterName.setText(parameter.getName());
if(parameter.getDescription() != null) {
parameterName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mActivity, parameter.getDescription(), Toast.LENGTH_SHORT).show();
}
});
}
final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBar);
final Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
final CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);
final TextView valueView = (TextView) view.findViewById(R.id.value);
final Button resetButton = (Button) view.findViewById(R.id.reset);
if (parameter instanceof IntegerParameter) {
final IntegerParameter p = (IntegerParameter) parameter;
int interval = p.getMax() - p.getMin();
seekBar.setMax(interval);
seekBar.setProgress(p.getValue() - p.getMin());
SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
final int value = progress + p.getMin();
p.setValue(value);
valueView.setText(String.format("%d", value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
seekBar.setOnSeekBarChangeListener(changeListener);
changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBar.setProgress(p.getDefault() - p.getMin());
}
});
} else if (parameter instanceof FloatParameter) {
final int precision = 100; // 2 digits after comma
final FloatParameter p = (FloatParameter) parameter;
float interval = p.getMax() - p.getMin();
seekBar.setMax((int) (interval * precision));
seekBar.setProgress((int) ((p.getValue() - p.getMin()) * precision));
SeekBar.OnSeekBarChangeListener changeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) {
final float value = (progress / (float) precision) + p.getMin();
p.setValue(value);
valueView.setText(String.format("%.2f", value));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
seekBar.setOnSeekBarChangeListener(changeListener);
changeListener.onProgressChanged(seekBar, seekBar.getProgress(), false); // init value label
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBar.setProgress((int) ((p.getDefault() - p.getMin()) * precision));
}
});
} else if (parameter instanceof EnumParameter) {
final EnumParameter p = (EnumParameter) parameter;
final ArrayAdapter<Enum> adapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_spinner_item, p.getEnumValues());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getPosition(p.getValue()));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
p.setValue(p.getEnumValues()[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spinner.setSelection(adapter.getPosition(p.getDefault()));
}
});
} else if (parameter instanceof BooleanParameter) {
final BooleanParameter p = (BooleanParameter) parameter;
checkbox.setChecked(p.getValue());
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
p.setValue(isChecked);
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkbox.setChecked(p.getDefault());
}
});
}
return view;
}
public void clear() {
mParameters.clear();
notifyDataSetChanged();
}
} | 41.57346 | 134 | 0.627793 |
af39a80b5f3befcc03ef580f1f32a9cf9a050dff | 912 | public class PatternConsole {
public static void main(String [] args) {
int lines = 4;
int space = 0;
int i, j;
for(i = 0; i < lines; i++) {
for(j = 1; j <= space; j++) {
System.out.print(" ");
}
for(j = 1; j <= lines; j++) {
if(j <= (lines - i)) {
System.out.print(j);
}
else {
System.out.print("*");
}
}
j--;
while(j > 0) {
if(j > lines - i) {
System.out.print("*");
}
else {
System.out.print(j);
}
j--;
}
if((lines - i) > 9) {
space = space + 1;
}
System.out.println("");
}
}
} | 22.243902 | 45 | 0.281798 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.