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 |
|---|---|---|---|---|---|
eb7c4cb577d0e36be40716300bab598abfb69f5c | 1,829 | /*******************************************************************************
* Copyright (c) 2015, 2016 David Green.
*
* 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.greensopinion.finance.services.persistence;
import static com.google.common.base.Preconditions.checkNotNull;
import com.greensopinion.finance.services.domain.EntityEventSupport;
public class ConfigurationService<T> {
private final PersistenceService<T> persistenceService;
private final EntityEventSupport eventSupport;
private final Object dataLock = new Object();
private T data;
public ConfigurationService(PersistenceService<T> persistenceService, EntityEventSupport eventSupport) {
this.persistenceService = checkNotNull(persistenceService);
this.eventSupport = checkNotNull(eventSupport);
}
public T retrieve() {
synchronized (dataLock) {
if (data == null) {
data = load();
}
return data;
}
}
protected void clearState() {
synchronized (dataLock) {
data = null;
}
}
public void update(T value) {
checkNotNull(value);
synchronized (dataLock) {
persistenceService.save(value);
data = value;
}
eventSupport.updated(value);
}
protected T load() {
return persistenceService.load();
}
}
| 29.5 | 105 | 0.677966 |
933718157b7e6899509f20ed1c5e8f80121f5d51 | 700 | package com.mistraltech.bogen.utils;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.project.Project;
public class ActionUtils {
public static void runAction(Runnable action) {
ApplicationManager.getApplication().runWriteAction(action);
}
public static void runActionAsCommand(final Runnable action, final Project project) {
CommandProcessor.getInstance().executeCommand(project, () -> runAction(action), "", "");
}
public static void runActionLater(final Runnable action) {
ApplicationManager.getApplication().invokeLater(() -> runAction(action));
}
}
| 33.333333 | 96 | 0.748571 |
23c55f68eaebf6c6f97f636fd321e70cb68e2e30 | 1,217 | package leetcode.page1.p148;
import leetcode.ListNode;
/**
* 148.排序链表
*/
public class Solution {
public ListNode sortList(ListNode head) {
return head == null ? null : mergeSort(head);
}
private ListNode mergeSort(ListNode head) {
if (head.next == null) return head;
ListNode fast = head, slow = head, pre = null;
while (fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
pre.next = null;
ListNode right = mergeSort(slow);
ListNode left = mergeSort(head);
return merge(left, right);
}
private ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (left != null && right != null) {
if (left.val < right.val) {
head.next = left;
left = left.next;
} else {
head.next = right;
right = right.next;
}
head = head.next;
}
if (left != null) head.next = left;
if (right != null) head.next = right;
return dummy.next;
}
}
| 26.456522 | 59 | 0.512736 |
0de81f11876bd2b1a83aea25e144d137c8a35b18 | 691 | package com.sakhatech;
import javax.annotation.PreDestroy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.sakhatech.util.MongoOperationClient;
/**
*
* @author Naveen
* @createdDate 6-Jun-2017
* @modifiedDate 6-Jun-2017
*/
@SpringBootApplication
public class MongoDbOperationsApplication {
public static void main(String[] args) {
SpringApplication.run(MongoDbOperationsApplication.class, args);
}
/**
*
* @author Naveen
* @createdDate 6-Jun-2017
* @modifiedDate 6-Jun-2017
*
*/
@PreDestroy
public void closeMongoConnecion(){
MongoOperationClient.closeMongoClient();
}
}
| 19.742857 | 68 | 0.756874 |
696bfdf43851e18a162bb787064f5a7a0b5b2184 | 2,958 | package net.ethobat.system0.api.zdroid;
import net.ethobat.system0.api.recipe.S0RecipeType;
import java.util.HashSet;
import java.util.Set;
public class ZeeAbilities {
private int replicationRate;
private int territoryRange;
private HashSet<S0RecipeType> recipeTypes;
private HashSet<ZeeWorldEffect> worldEffects;
public ZeeAbilities() {
this(0, 0, new HashSet<S0RecipeType>(), new HashSet<ZeeWorldEffect>());
}
public ZeeAbilities(int replicationRate, int territoryRange, HashSet<S0RecipeType> recipeTypes, HashSet<ZeeWorldEffect> effects) {
this.replicationRate = replicationRate;
this.territoryRange = territoryRange;
this.recipeTypes = recipeTypes;
this.worldEffects = effects;
}
// Used to generate a heterozygous gene's effects when both alleles are expressed (i.e. both dominant or both recessive).
// This is never called when the gene has a single dominant allele or is homozygous.
// Numerical values are the ceiling of the average.
// Recipe types and world effects are the intersection of the sets, i.e. both alleles must provide process/effect.
public ZeeAbilities getCombinedEffectsForGene(ZeeAbilities za) {
HashSet<S0RecipeType> newRecipeTypes = new HashSet<S0RecipeType>(this.getRecipeTypes());
newRecipeTypes.retainAll(za.getRecipeTypes());
HashSet<ZeeWorldEffect> newWorldEffects = new HashSet<ZeeWorldEffect>(this.getWorldEffects());
newWorldEffects.retainAll(za.getWorldEffects());
return new ZeeAbilities(
(int) Math.ceil((float) (this.getReplicationRate() + za.getReplicationRate()) / 2),
(int) Math.ceil((float) (this.getTerritoryRange() + za.getTerritoryRange()) / 2),
newRecipeTypes,
newWorldEffects
);
}
// Additively combines zee abilities - used to calculate a genome's ultimate phenotype.
// Numerical values are added, sets are unioned.
public ZeeAbilities getCombinedEffectsForPhenotype(ZeeAbilities za) {
HashSet<S0RecipeType> newRecipeTypes = new HashSet<S0RecipeType>(this.getRecipeTypes());
newRecipeTypes.addAll(za.getRecipeTypes());
HashSet<ZeeWorldEffect> newWorldEffects = new HashSet<ZeeWorldEffect>(this.getWorldEffects());
newWorldEffects.addAll(za.getWorldEffects());
return new ZeeAbilities(
this.getReplicationRate() + za.getReplicationRate(),
this.getTerritoryRange() + za.getTerritoryRange(),
newRecipeTypes,
newWorldEffects
);
}
public int getReplicationRate() {
return replicationRate;
}
public int getTerritoryRange() {
return territoryRange;
}
public Set<S0RecipeType> getRecipeTypes() {
return recipeTypes;
}
public Set<ZeeWorldEffect> getWorldEffects() {
return worldEffects;
}
}
| 36.975 | 134 | 0.687965 |
ce3d704fec956a1721e8f9f521ec71805de23f53 | 10,936 | /*
* 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.drill.exec.store.hive;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.apache.drill.exec.metastore.store.FileSystemMetadataProviderManager;
import org.apache.drill.exec.metastore.MetadataProviderManager;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.store.parquet.ParquetReaderConfig;
import org.apache.drill.metastore.metadata.LocationProvider;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.expression.ValueExpressions;
import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.base.SubScan;
import org.apache.drill.exec.proto.CoordinationProtos;
import org.apache.drill.exec.store.StoragePluginRegistry;
import org.apache.drill.exec.store.dfs.FileSelection;
import org.apache.drill.exec.store.dfs.ReadEntryWithPath;
import org.apache.drill.exec.store.hive.HiveMetadataProvider.LogicalInputSplit;
import org.apache.drill.exec.store.parquet.AbstractParquetGroupScan;
import org.apache.drill.exec.store.parquet.RowGroupReadEntry;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@JsonTypeName("hive-drill-native-parquet-scan")
public class HiveDrillNativeParquetScan extends AbstractParquetGroupScan {
private final HiveStoragePlugin hiveStoragePlugin;
private final HivePartitionHolder hivePartitionHolder;
private final Map<String, String> confProperties;
@JsonCreator
public HiveDrillNativeParquetScan(@JacksonInject StoragePluginRegistry engineRegistry,
@JsonProperty("userName") String userName,
@JsonProperty("hiveStoragePluginConfig") HiveStoragePluginConfig hiveStoragePluginConfig,
@JsonProperty("columns") List<SchemaPath> columns,
@JsonProperty("entries") List<ReadEntryWithPath> entries,
@JsonProperty("hivePartitionHolder") HivePartitionHolder hivePartitionHolder,
@JsonProperty("confProperties") Map<String, String> confProperties,
@JsonProperty("readerConfig") ParquetReaderConfig readerConfig,
@JsonProperty("filter") LogicalExpression filter,
@JsonProperty("schema") TupleMetadata schema) throws IOException {
super(ImpersonationUtil.resolveUserName(userName), columns, entries, readerConfig, filter);
this.hiveStoragePlugin = engineRegistry.resolve(hiveStoragePluginConfig, HiveStoragePlugin.class);
this.confProperties = confProperties;
HiveParquetTableMetadataProvider.Builder builder =
defaultTableMetadataProviderBuilder(new FileSystemMetadataProviderManager());
HiveParquetTableMetadataProvider metadataProvider = builder
.withEntries(entries)
.withHivePartitionHolder(hivePartitionHolder)
.withHiveStoragePlugin(hiveStoragePlugin)
.withReaderConfig(readerConfig)
.withSchema(schema)
.build();
this.metadataProvider = metadataProvider;
this.hivePartitionHolder = metadataProvider.getHivePartitionHolder();
this.fileSet = metadataProvider.getFileSet();
init();
}
public HiveDrillNativeParquetScan(String userName,
List<SchemaPath> columns,
HiveStoragePlugin hiveStoragePlugin,
List<LogicalInputSplit> logicalInputSplits,
Map<String, String> confProperties,
ParquetReaderConfig readerConfig) throws IOException {
this(userName, columns, hiveStoragePlugin, logicalInputSplits, confProperties, readerConfig, ValueExpressions.BooleanExpression.TRUE);
}
public HiveDrillNativeParquetScan(String userName,
List<SchemaPath> columns,
HiveStoragePlugin hiveStoragePlugin,
List<LogicalInputSplit> logicalInputSplits,
Map<String, String> confProperties,
ParquetReaderConfig readerConfig,
LogicalExpression filter) throws IOException {
super(userName, columns, new ArrayList<>(), readerConfig, filter);
this.hiveStoragePlugin = hiveStoragePlugin;
this.confProperties = confProperties;
HiveParquetTableMetadataProvider.Builder builder =
tableMetadataProviderBuilder(new FileSystemMetadataProviderManager());
HiveParquetTableMetadataProvider metadataProvider = builder
.withHiveStoragePlugin(hiveStoragePlugin)
.withLogicalInputSplits(logicalInputSplits)
.withReaderConfig(readerConfig)
.build();
this.metadataProvider = metadataProvider;
this.entries = metadataProvider.getEntries();
this.hivePartitionHolder = metadataProvider.getHivePartitionHolder();
this.fileSet = metadataProvider.getFileSet();
init();
}
/**
* Copy constructor for shallow partial cloning
* @param that old groupScan
*/
private HiveDrillNativeParquetScan(HiveDrillNativeParquetScan that) {
super(that);
this.hiveStoragePlugin = that.hiveStoragePlugin;
this.hivePartitionHolder = that.hivePartitionHolder;
this.confProperties = that.confProperties;
}
@JsonProperty
public HiveStoragePluginConfig getHiveStoragePluginConfig() {
return hiveStoragePlugin.getConfig();
}
@JsonProperty
public HivePartitionHolder getHivePartitionHolder() {
return hivePartitionHolder;
}
@JsonProperty
public Map<String, String> getConfProperties() {
return confProperties;
}
@Override
public SubScan getSpecificScan(int minorFragmentId) {
List<RowGroupReadEntry> readEntries = getReadEntries(minorFragmentId);
HivePartitionHolder subPartitionHolder = new HivePartitionHolder();
for (RowGroupReadEntry readEntry : readEntries) {
List<String> values = hivePartitionHolder.get(readEntry.getPath());
subPartitionHolder.add(readEntry.getPath(), values);
}
return new HiveDrillNativeParquetRowGroupScan(getUserName(), hiveStoragePlugin, readEntries, columns, subPartitionHolder,
confProperties, readerConfig, filter, getTableMetadata().getSchema());
}
@Override
public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
Preconditions.checkArgument(children.isEmpty());
return new HiveDrillNativeParquetScan(this);
}
@Override
public HiveDrillNativeParquetScan clone(FileSelection selection) throws IOException {
HiveDrillNativeParquetScan newScan = new HiveDrillNativeParquetScan(this);
newScan.modifyFileSelection(selection);
newScan.init();
return newScan;
}
@Override
public GroupScan clone(List<SchemaPath> columns) {
HiveDrillNativeParquetScan newScan = new HiveDrillNativeParquetScan(this);
newScan.columns = columns;
return newScan;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("HiveDrillNativeParquetScan [");
builder.append("entries=").append(entries);
builder.append(", numFiles=").append(getEntries().size());
builder.append(", numRowGroups=").append(getRowGroupsMetadata().size());
String filterString = getFilterString();
if (!filterString.isEmpty()) {
builder.append(", filter=").append(filterString);
}
builder.append(", columns=").append(columns);
builder.append("]");
return builder.toString();
}
@Override
protected RowGroupScanFilterer<?> getFilterer() {
return new HiveDrillNativeParquetScanFilterer(this);
}
@Override
protected Collection<CoordinationProtos.DrillbitEndpoint> getDrillbits() {
return hiveStoragePlugin.getContext().getBits();
}
@Override
protected AbstractParquetGroupScan cloneWithFileSelection(Collection<Path> filePaths) throws IOException {
FileSelection newSelection = new FileSelection(null, new ArrayList<>(filePaths), null, null, false);
return clone(newSelection);
}
@Override
protected boolean supportsFileImplicitColumns() {
// current group scan should populate directory partition values
return true;
}
@Override
protected List<String> getPartitionValues(LocationProvider locationProvider) {
return hivePartitionHolder.get(locationProvider.getPath());
}
@Override
protected HiveParquetTableMetadataProvider.Builder tableMetadataProviderBuilder(MetadataProviderManager source) {
return defaultTableMetadataProviderBuilder(source);
}
@Override
protected HiveParquetTableMetadataProvider.Builder defaultTableMetadataProviderBuilder(MetadataProviderManager source) {
return new HiveParquetTableMetadataProvider.Builder(source);
}
/**
* Implementation of RowGroupScanFilterer which uses {@link HiveDrillNativeParquetScanFilterer} as source and
* builds {@link HiveDrillNativeParquetScanFilterer} instance with filtered metadata.
*/
private static class HiveDrillNativeParquetScanFilterer extends RowGroupScanFilterer<HiveDrillNativeParquetScanFilterer> {
public HiveDrillNativeParquetScanFilterer(HiveDrillNativeParquetScan source) {
super(source);
}
@Override
protected AbstractParquetGroupScan getNewScan() {
return new HiveDrillNativeParquetScan((HiveDrillNativeParquetScan) source);
}
@Override
protected HiveDrillNativeParquetScanFilterer self() {
return this;
}
}
}
| 41.112782 | 138 | 0.736192 |
3db3f358980c27b24156606f4ab369944cbbdb86 | 2,205 | package com.bht.pim.mapper;
import java.util.List;
import java.util.stream.Collectors;
import org.mapstruct.CollectionMappingStrategy;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import org.springframework.stereotype.Component;
import com.bht.pim.entity.ProjectEntity;
import com.bht.pim.proto.projects.Project;
@Component
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE,
collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
uses = {CustomizedMapper.class, DateTimeMapper.class})
public interface ProjectMapper {
@Named("toProject")
@Mapping(source = "projectEntity", target = "projectInfo", qualifiedByName = "getProjectInfo")
@Mapping(source = "projectEntity.enrolledEmployees", target = "membersList", qualifiedByName = "getEmployeeInfo")
Project toProject(final ProjectEntity projectEntity);
@Named("toProjectIgnoreMembers")
@Mapping(source = "projectEntity", target = "projectInfo", qualifiedByName = "getProjectInfoIgnoreGroupLeader")
@Mapping(source = "projectEntity.enrolledEmployees", target = "membersList", ignore = true)
Project toProjectIgnoreMembers(final ProjectEntity projectEntity);
default List<Project> toProjectList(final List<ProjectEntity> projectEntities) {
return projectEntities.stream()
.map(this::toProjectIgnoreMembers)
.collect(Collectors.toList());
}
@Mapping(source = "project.projectInfo.id", target = "id")
@Mapping(source = "project.projectInfo.number", target = "number")
@Mapping(source = "project.projectInfo.name", target = "name")
@Mapping(source = "project.projectInfo.customer", target = "customer")
@Mapping(source = "project.projectInfo.status", target = "status")
@Mapping(source = "project.projectInfo.start", target = "start")
@Mapping(source = "project.projectInfo.end", target = "end")
@Mapping(source = "project.projectInfo.group", target = "group")
@Mapping(source = "project.membersList", target = "enrolledEmployees")
ProjectEntity toProjectEntity(final Project project);
} | 42.403846 | 117 | 0.741043 |
974220b29f71611200c84ae94deab5fc7ff72859 | 4,895 | package com.example.simplefirebaseapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class PersonalChatActivity extends AppCompatActivity {
private CollectionReference tweetsCollection;
@BindView(R.id.txt_tweets) TextView txtTweets;
@BindView(R.id.edt_sender) EditText edtSenderEmail;
@BindView(R.id.edt_tweet) EditText edtTweet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_chat);
ButterKnife.bind(this);
getDataOneTime();
}
private void getDataOneTime(){
tweetsCollection = FirebaseFirestore.getInstance().collection("personalTweets");
tweetsCollection.orderBy("timestamp", Query.Direction.ASCENDING).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
String allText = "";
List<DocumentSnapshot> myListOfDocuments = task.getResult().getDocuments();
for(DocumentSnapshot curr : myListOfDocuments)
{
Object textArray[] = curr.getData().values().toArray();
if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(textArray[1])) {
allText += convertString(textArray);
}
}
txtTweets.setText(allText);
}
}
});
}
private String convertString(Object[] textArray) {
Object timeSent= textArray[0].toString().substring(11,19); /* data full */
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Date:");
stringBuilder.append(timeSent);
stringBuilder.append("\nSend From: ");
stringBuilder.append(textArray[3]); /* send from*/
stringBuilder.append("\nMessage:\n");
stringBuilder.append(textArray[4]); /* Message */
stringBuilder.append("\n\n");
/*stringBuilder.append(textArray[1]); send to */
/*stringBuilder.append(textArray[5]); TimeStamp */
return stringBuilder.toString();
}
@OnClick(R.id.btn_send)
public void onTweetClicked(){
String user = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String tweetText = edtTweet.getText().toString();
String senderName = edtSenderEmail.getText().toString();
Map<String, Object> tweet = new HashMap<>();
tweet.put("sender",senderName);
tweet.put("content", tweetText);
tweet.put("type", "text");
tweet.put("user", user);
tweet.put("timestamp", System.currentTimeMillis());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
tweet.put("date", ZonedDateTime.now().toString());
}
tweetsCollection.add(tweet)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(PersonalChatActivity.this,"Send",Toast.LENGTH_SHORT).show();
}
});
getDataOneTime();
edtTweet.getText().clear();
edtSenderEmail.getText().clear();
Toast.makeText(PersonalChatActivity.this, "Message send successfully!",
Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.btn_al)
public void onPersonalClicked(){
startActivity(new Intent(PersonalChatActivity.this, MainActivity.class));
finish();
}
@OnClick(R.id.btn_logout)
public void onLogoutClicked() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(PersonalChatActivity.this, LoginActivity.class));
finish();
}
} | 39.475806 | 142 | 0.659244 |
52d4cecc8a409fc9a5ee64db9da1076477617e2e | 24,866 | /*
* Copyright 2015-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This is auto-generated file. Do not edit.
*/
package org.schema;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.annotation.*;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* The geographic shape of a place. A GeoShape can be described using several properties whose values are based on latitude/longitude pairs. Either whitespace or commas can be used to separate latitude and longitude; whitespace should be used when writing a list of several such points.Source: http://www.w3.org/wiki/WebSchemas/SchemaDotOrgSources#source_rNews
*/
public class GeoShape extends StructuredValue {
/**
* Physical address of the item.
*/
@JsonIgnore public PostalAddress getAddressPostalAddress() {
return (PostalAddress) getValue("address");
}
/**
* Physical address of the item.
*/
@JsonIgnore public Collection<PostalAddress> getAddressPostalAddresss() {
final Object current = myData.get("address");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<PostalAddress>) current;
}
return Arrays.asList((PostalAddress) current);
}
/**
* Physical address of the item.
*/
@JsonIgnore public String getAddressString() {
return (String) getValue("address");
}
/**
* Physical address of the item.
*/
@JsonIgnore public Collection<String> getAddressStrings() {
final Object current = myData.get("address");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@JsonIgnore public Country getAddressCountryCountry() {
return (Country) getValue("addressCountry");
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@JsonIgnore public Collection<Country> getAddressCountryCountrys() {
final Object current = myData.get("addressCountry");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<Country>) current;
}
return Arrays.asList((Country) current);
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@JsonIgnore public String getAddressCountryString() {
return (String) getValue("addressCountry");
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@JsonIgnore public Collection<String> getAddressCountryStrings() {
final Object current = myData.get("addressCountry");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* A box is the area enclosed by the rectangle formed by two points. The first point is the lower corner, the second point is the upper corner. A box is expressed as two points separated by a space character.
*/
@JsonIgnore public String getBox() {
return (String) getValue("box");
}
/**
* A box is the area enclosed by the rectangle formed by two points. The first point is the lower corner, the second point is the upper corner. A box is expressed as two points separated by a space character.
*/
@JsonIgnore public Collection<String> getBoxs() {
final Object current = myData.get("box");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* A circle is the circular region of a specified radius centered at a specified latitude and longitude. A circle is expressed as a pair followed by a radius in meters.
*/
@JsonIgnore public String getCircle() {
return (String) getValue("circle");
}
/**
* A circle is the circular region of a specified radius centered at a specified latitude and longitude. A circle is expressed as a pair followed by a radius in meters.
*/
@JsonIgnore public Collection<String> getCircles() {
final Object current = myData.get("circle");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Integer getElevationInteger() {
return (Integer) getValue("elevation");
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Collection<Integer> getElevationIntegers() {
final Object current = myData.get("elevation");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<Integer>) current;
}
return Arrays.asList((Integer) current);
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Long getElevationLong() {
return (Long) getValue("elevation");
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Collection<Long> getElevationLongs() {
final Object current = myData.get("elevation");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<Long>) current;
}
return Arrays.asList((Long) current);
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Float getElevationFloat() {
return (Float) getValue("elevation");
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Collection<Float> getElevationFloats() {
final Object current = myData.get("elevation");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<Float>) current;
}
return Arrays.asList((Float) current);
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Double getElevationDouble() {
return (Double) getValue("elevation");
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Collection<Double> getElevationDoubles() {
final Object current = myData.get("elevation");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<Double>) current;
}
return Arrays.asList((Double) current);
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public String getElevationString() {
return (String) getValue("elevation");
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@JsonIgnore public Collection<String> getElevationStrings() {
final Object current = myData.get("elevation");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* A line is a point-to-point path consisting of two or more points. A line is expressed as a series of two or more point objects separated by space.
*/
@JsonIgnore public String getLine() {
return (String) getValue("line");
}
/**
* A line is a point-to-point path consisting of two or more points. A line is expressed as a series of two or more point objects separated by space.
*/
@JsonIgnore public Collection<String> getLines() {
final Object current = myData.get("line");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* A polygon is the area enclosed by a point-to-point path for which the starting and ending points are the same. A polygon is expressed as a series of four or more space delimited points where the first and final points are identical.
*/
@JsonIgnore public String getPolygon() {
return (String) getValue("polygon");
}
/**
* A polygon is the area enclosed by a point-to-point path for which the starting and ending points are the same. A polygon is expressed as a series of four or more space delimited points where the first and final points are identical.
*/
@JsonIgnore public Collection<String> getPolygons() {
final Object current = myData.get("polygon");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
/**
* The postal code. For example, 94043.
*/
@JsonIgnore public String getPostalCode() {
return (String) getValue("postalCode");
}
/**
* The postal code. For example, 94043.
*/
@JsonIgnore public Collection<String> getPostalCodes() {
final Object current = myData.get("postalCode");
if (current == null) return Collections.emptyList();
if (current instanceof Collection) {
return (Collection<String>) current;
}
return Arrays.asList((String) current);
}
protected GeoShape(java.util.Map<String,Object> data) {
super(data);
}
/**
* Builder for {@link GeoShape}
*/
public static class Builder extends StructuredValue.Builder {
public Builder(@NotNull HashMap<String,Object> data) {
super(data);
}
@NotNull public GeoShape build() {
return new GeoShape(myData);
}
/**
* Physical address of the item.
*/
@NotNull public Builder address(@NotNull PostalAddress postalAddress) {
putValue("address", postalAddress);
return this;
}
/**
* Physical address of the item.
*/
@NotNull public Builder address(@NotNull PostalAddress.Builder postalAddress) {
putValue("address", postalAddress.build());
return this;
}
/**
* Physical address of the item.
*/
@NotNull public Builder address(@NotNull String address) {
putValue("address", address);
return this;
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@NotNull public Builder addressCountry(@NotNull Country country) {
putValue("addressCountry", country);
return this;
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@NotNull public Builder addressCountry(@NotNull Country.Builder country) {
putValue("addressCountry", country.build());
return this;
}
/**
* The country. For example, USA. You can also provide the two-letter [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1).
*/
@NotNull public Builder addressCountry(@NotNull String addressCountry) {
putValue("addressCountry", addressCountry);
return this;
}
/**
* A box is the area enclosed by the rectangle formed by two points. The first point is the lower corner, the second point is the upper corner. A box is expressed as two points separated by a space character.
*/
@NotNull public Builder box(@NotNull String box) {
putValue("box", box);
return this;
}
/**
* A circle is the circular region of a specified radius centered at a specified latitude and longitude. A circle is expressed as a pair followed by a radius in meters.
*/
@NotNull public Builder circle(@NotNull String circle) {
putValue("circle", circle);
return this;
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@NotNull public Builder elevation(@NotNull Integer integer) {
putValue("elevation", integer);
return this;
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@NotNull public Builder elevation(@NotNull Long elevation) {
putValue("elevation", elevation);
return this;
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@NotNull public Builder elevation(@NotNull Float elevation) {
putValue("elevation", elevation);
return this;
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@NotNull public Builder elevation(@NotNull Double elevation) {
putValue("elevation", elevation);
return this;
}
/**
* The elevation of a location ([WGS 84](https://en.wikipedia.org/wiki/World_Geodetic_System)). Values may be of the form 'NUMBER UNIT_OF_MEASUREMENT' (e.g., '1,000 m', '3,200 ft') while numbers alone should be assumed to be a value in meters.
*/
@NotNull public Builder elevation(@NotNull String elevation) {
putValue("elevation", elevation);
return this;
}
/**
* A line is a point-to-point path consisting of two or more points. A line is expressed as a series of two or more point objects separated by space.
*/
@NotNull public Builder line(@NotNull String line) {
putValue("line", line);
return this;
}
/**
* A polygon is the area enclosed by a point-to-point path for which the starting and ending points are the same. A polygon is expressed as a series of four or more space delimited points where the first and final points are identical.
*/
@NotNull public Builder polygon(@NotNull String polygon) {
putValue("polygon", polygon);
return this;
}
/**
* The postal code. For example, 94043.
*/
@NotNull public Builder postalCode(@NotNull String postalCode) {
putValue("postalCode", postalCode);
return this;
}
/**
* An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
*/
@NotNull public Builder additionalType(@NotNull String additionalType) {
putValue("additionalType", additionalType);
return this;
}
/**
* An alias for the item.
*/
@NotNull public Builder alternateName(@NotNull String alternateName) {
putValue("alternateName", alternateName);
return this;
}
/**
* A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
*/
@NotNull public Builder disambiguatingDescription(@NotNull String disambiguatingDescription) {
putValue("disambiguatingDescription", disambiguatingDescription);
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull CreativeWork creativeWork) {
putValue("mainEntityOfPage", creativeWork);
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull CreativeWork.Builder creativeWork) {
putValue("mainEntityOfPage", creativeWork.build());
return this;
}
/**
* Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See [background notes](/docs/datamodel.html#mainEntityBackground) for details.
*/
@NotNull public Builder mainEntityOfPage(@NotNull String mainEntityOfPage) {
putValue("mainEntityOfPage", mainEntityOfPage);
return this;
}
/**
* The name of the item.
*/
@NotNull public Builder name(@NotNull String name) {
putValue("name", name);
return this;
}
/**
* URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
*/
@NotNull public Builder sameAs(@NotNull String sameAs) {
putValue("sameAs", sameAs);
return this;
}
/**
* URL of the item.
*/
@NotNull public Builder url(@NotNull String url) {
putValue("url", url);
return this;
}
/**
* Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
*/
@NotNull public Builder potentialAction(@NotNull Action action) {
putValue("potentialAction", action);
return this;
}
/**
* Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
*/
@NotNull public Builder potentialAction(@NotNull Action.Builder action) {
putValue("potentialAction", action.build());
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull CreativeWork creativeWork) {
putValue("subjectOf", creativeWork);
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull CreativeWork.Builder creativeWork) {
putValue("subjectOf", creativeWork.build());
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull Event event) {
putValue("subjectOf", event);
return this;
}
/**
* A CreativeWork or Event about this Thing.
*/
@NotNull public Builder subjectOf(@NotNull Event.Builder event) {
putValue("subjectOf", event.build());
return this;
}
@NotNull public Builder id(@NotNull String id) {
myData.put("id", id);
return this;
}
public Builder id(long id) {
return id(Long.toString(id));
}
@Override protected void fromMap(String key, Object value) {
if ("address".equals(key) && value instanceof PostalAddress) { address((PostalAddress)value); return; }
if ("addresss".equals(key) && value instanceof PostalAddress) { address((PostalAddress)value); return; }
if ("address".equals(key) && value instanceof String) { address((String)value); return; }
if ("addresss".equals(key) && value instanceof String) { address((String)value); return; }
if ("addressCountry".equals(key) && value instanceof Country) { addressCountry((Country)value); return; }
if ("addressCountrys".equals(key) && value instanceof Country) { addressCountry((Country)value); return; }
if ("addressCountry".equals(key) && value instanceof String) { addressCountry((String)value); return; }
if ("addressCountrys".equals(key) && value instanceof String) { addressCountry((String)value); return; }
if ("box".equals(key) && value instanceof String) { box((String)value); return; }
if ("boxs".equals(key) && value instanceof String) { box((String)value); return; }
if ("circle".equals(key) && value instanceof String) { circle((String)value); return; }
if ("circles".equals(key) && value instanceof String) { circle((String)value); return; }
if ("elevation".equals(key) && value instanceof Integer) { elevation((Integer)value); return; }
if ("elevations".equals(key) && value instanceof Integer) { elevation((Integer)value); return; }
if ("elevation".equals(key) && value instanceof Long) { elevation((Long)value); return; }
if ("elevations".equals(key) && value instanceof Long) { elevation((Long)value); return; }
if ("elevation".equals(key) && value instanceof Float) { elevation((Float)value); return; }
if ("elevations".equals(key) && value instanceof Float) { elevation((Float)value); return; }
if ("elevation".equals(key) && value instanceof Double) { elevation((Double)value); return; }
if ("elevations".equals(key) && value instanceof Double) { elevation((Double)value); return; }
if ("elevation".equals(key) && value instanceof String) { elevation((String)value); return; }
if ("elevations".equals(key) && value instanceof String) { elevation((String)value); return; }
if ("line".equals(key) && value instanceof String) { line((String)value); return; }
if ("lines".equals(key) && value instanceof String) { line((String)value); return; }
if ("polygon".equals(key) && value instanceof String) { polygon((String)value); return; }
if ("polygons".equals(key) && value instanceof String) { polygon((String)value); return; }
if ("postalCode".equals(key) && value instanceof String) { postalCode((String)value); return; }
if ("postalCodes".equals(key) && value instanceof String) { postalCode((String)value); return; }
super.fromMap(key, value);
}
}
}
| 46.048148 | 422 | 0.684107 |
37db9a552b6986b574cf487693caf51613a31573 | 10,930 | package com.github.sanctum.clans.construct;
import com.github.sanctum.clans.ClansJavaPlugin;
import com.github.sanctum.clans.construct.api.Clan;
import com.github.sanctum.clans.construct.api.ClanCooldown;
import com.github.sanctum.clans.construct.api.ClansAPI;
import com.github.sanctum.clans.construct.extra.FancyLogoAppendage;
import com.github.sanctum.clans.construct.impl.Resident;
import com.github.sanctum.labyrinth.data.DataTable;
import com.github.sanctum.labyrinth.data.FileList;
import com.github.sanctum.labyrinth.data.FileManager;
import com.github.sanctum.labyrinth.data.LabyrinthDataTable;
import com.github.sanctum.labyrinth.formatting.FancyMessage;
import com.github.sanctum.labyrinth.library.Items;
import com.github.sanctum.labyrinth.library.StringUtils;
import com.github.sanctum.labyrinth.task.Schedule;
import com.github.sanctum.skulls.CustomHead;
import com.github.sanctum.skulls.CustomHeadLoader;
import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
public class DataManager {
public final Map<Player, String> ID_MODE = new HashMap<>();
private final Set<Player> CHAT_SPY = new HashSet<>();
private final Set<Resident> RESIDENTS = new HashSet<>();
private final Set<Player> INHABITANTS = new HashSet<>();
private final List<ClanCooldown> COOLDOWNS = new LinkedList<>();
private final DataTable resetTable = new LabyrinthDataTable();
public static class Side {
public static final int LEFT = 1;
public static final int RIGHT = 2;
}
void create(FileManager manager) {
if (!manager.getRoot().exists()) {
InputStream is = ClansAPI.getInstance().getPlugin().getResource(manager.getRoot().getName() + manager.getRoot().getType().getExtension());
if (is == null) throw new IllegalStateException("Unable to load Config.yml from the jar!");
FileList.copy(is, manager.getRoot().getParent());
manager.getRoot().reload();
}
}
public DataTable getResetTable() {
return this.resetTable;
}
public boolean isSpy(Player player) {
return CHAT_SPY.contains(player);
}
public boolean addSpy(Player spy) {
return CHAT_SPY.add(spy);
}
public boolean removeSpy(Player spy) {
return CHAT_SPY.remove(spy);
}
public Set<Player> getSpies() {
return Collections.unmodifiableSet(CHAT_SPY);
}
public List<ClanCooldown> getCooldowns() {
return Collections.unmodifiableList(COOLDOWNS);
}
public Set<Resident> getResidents() {
return Collections.unmodifiableSet(RESIDENTS);
}
public Resident getResident(Player p) {
return RESIDENTS.stream().filter(r -> r.getPlayer().getName().equals(p.getName())).findFirst().orElse(null);
}
public boolean isInWild(Player player) {
return INHABITANTS.contains(player);
}
public boolean removeWildernessInhabitant(Player player) {
return INHABITANTS.remove(player);
}
public boolean addWildernessInhabitant(Player player) {
return INHABITANTS.add(player);
}
public boolean addClaimResident(Resident resident) {
return RESIDENTS.add(resident);
}
public boolean removeClaimResident(Resident resident) {
return RESIDENTS.remove(resident);
}
public @NotNull FileManager getConfig() {
FileManager main = ClansAPI.getInstance().getFileList().get("Config", "Configuration");
create(main);
return main;
}
public @NotNull FileManager getMessages() {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main;
}
public @NotNull FileManager getClanFile(Clan c) {
return ClansAPI.getInstance().getFileList().get(c.getId().toString(), "Clans", JavaPlugin.getPlugin(ClansJavaPlugin.class).TYPE);
}
public String getConfigString(String path) {
return getConfig().getRoot().getString(path);
}
public boolean isTrue(String path) {
return getConfig().getRoot().getBoolean(path);
}
public String getMenuTitle(String menu) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main.getRoot().getString("menu-titles." + menu);
}
public String getMenuCategory(String menu) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main.getRoot().getString("menu-categories." + menu);
}
public String getMenuNavigation(String menu) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main.getRoot().getString("gui-navigation." + menu);
}
private ItemStack improvise(String value) {
Material mat = Items.findMaterial(value);
if (mat != null) {
return new ItemStack(mat);
} else {
if (value.length() < 26) {
return CustomHead.Manager.getHeads().stream().filter(h -> StringUtils.use(h.name()).containsIgnoreCase(value)).map(CustomHead::get).findFirst().orElse(null);
} else {
return CustomHeadLoader.provide(value);
}
}
}
public ItemStack getMenuItem(String object) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return improvise(Objects.requireNonNull(main.getRoot().getString("menu-items." + object)));
}
public Material getMenuMaterial(String object) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return Items.findMaterial(Objects.requireNonNull(main.getRoot().getString("menu-items." + object)));
}
public String getMessageString(String path) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main.getRoot().getString(path);
}
public int getConfigInt(String path) {
return getConfig().getRoot().getInt(path);
}
public String getMessageResponse(String path) {
FileManager main = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
create(main);
return main.getRoot().getString("Response." + path);
}
public FancyLogoAppendage appendStringsToLogo(List<String> logo, Consumer<FancyMessage> consumer) {
return new FancyLogoAppendage().append(logo, consumer);
}
public String[] appendStringsToLogo(List<String> logo, @MagicConstant(valuesFromClass = Side.class) int side, String... text) {
String[] ar = logo.toArray(new String[0]);
for (int i = 0; i < ar.length; i++) {
if (i > 0) {
if ((Math.max(0, i - 1)) <= text.length - 1) {
String m = text[Math.max(0, i - 1)];
switch (side) {
case 1:
ar[i] = "&r" + m + " &r" + ar[i];
break;
case 2:
ar[i] = ar[i] + " &r" + m;
break;
}
}
}
}
return ar;
}
public static boolean isTitlesAllowed() {
FileManager main = ClansAPI.getInstance().getFileList().get("Config", "Configuration");
return main.getRoot().getBoolean("Clans.land-claiming.send-titles");
}
public String formatDisplayTag(String color, String name) {
return MessageFormat.format(Objects.requireNonNull(getConfig().getRoot().getString("Formatting.nametag-prefix.text")), color, name);
}
public boolean isDisplayTagsAllowed() {
FileManager main = getConfig();
return main.getRoot().getBoolean("Formatting.nametag-prefix.use");
}
public boolean isUpdate() {
ClansAPI api = ClansAPI.getInstance();
FileList list = api.getFileList();
FileManager main = list.get("Config", "Configuration");
FileManager messages = list.get("Messages", "Configuration");
if (!ClansAPI.getInstance().getPlugin().getDescription().getVersion().equals(getConfig().getRoot().getString("Version"))) {
FileManager mainOld = list.get("config_old", "Configuration", com.github.sanctum.labyrinth.data.FileType.JSON);
FileManager messOld = list.get("messages_old", "Configuration", com.github.sanctum.labyrinth.data.FileType.JSON);
if (mainOld.getRoot().exists()) {
mainOld.getRoot().delete();
}
if (messOld.getRoot().exists()) {
messOld.getRoot().delete();
}
final String type = main.read(c -> c.getNode("Formatting").getNode("file-type").toPrimitive().getString());
main.toJSON("config_old", "Configuration");
messages.toJSON("messages_old", "Configuration");
Schedule.sync(() -> {
InputStream mainGrab;
if (type != null) {
if (type.equals("JSON")) {
mainGrab = api.getPlugin().getResource("Config_json.yml");
} else {
mainGrab = api.getPlugin().getResource("Config.yml");
}
} else {
mainGrab = api.getPlugin().getResource("Config.yml");
}
InputStream msgGrab;
msgGrab = api.getPlugin().getResource("Messages.yml");
if (mainGrab == null) throw new IllegalStateException("Unable to load Config.yml from the jar!");
if (msgGrab == null) throw new IllegalStateException("Unable to load Messages.yml from the jar!");
FileList.copy(mainGrab, main.getRoot().getParent());
FileList.copy(msgGrab, messages.getRoot().getParent());
messages.getRoot().reload();
main.getRoot().reload();
}).wait(1);
return true;
}
return false;
}
public void copyDefaults() {
FileManager main = ClansAPI.getInstance().getFileList().get("Config", "Configuration");
FileManager msg = ClansAPI.getInstance().getFileList().get("Messages", "Configuration");
if (!main.getRoot().exists()) {
InputStream mainGrab = ClansAPI.getInstance().getPlugin().getResource("Config.yml");
if (mainGrab == null) throw new IllegalStateException("Unable to load Config.yml from the jar!");
FileList.copy(mainGrab, main.getRoot().getParent());
}
if (!msg.getRoot().exists()) {
InputStream mainGrab = ClansAPI.getInstance().getPlugin().getResource("Messages.yml");
if (mainGrab == null) throw new IllegalStateException("Unable to load Messages.yml from the jar!");
FileList.copy(mainGrab, msg.getRoot().getParent());
}
}
public File getClanFolder() {
final File dir = new File(FileManager.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " "));
File d = new File(dir.getParentFile().getPath(), ClansAPI.getInstance().getPlugin().getDescription().getName() + "/" + "Clans" + "/");
if (!d.exists()) {
d.mkdirs();
}
return d;
}
public boolean addCooldown(ClanCooldown instance) {
return COOLDOWNS.add(instance);
}
public boolean removeCooldown(ClanCooldown instance) {
return COOLDOWNS.remove(instance);
}
public static class Security {
public static String getPermission(String command) {
return ClansAPI.getDataInstance().getMessageString("Commands." + command + ".permission");
}
}
}
| 34.588608 | 161 | 0.722415 |
f943bfb92fbfae435a73574219c57388f33f06c7 | 2,314 | package com.tiagobalduino.springhibernate.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tiagobalduino.springhibernate.bean.Customer;
import com.tiagobalduino.springhibernate.dao.CustomerDAO;
@RestController
public class CustomerRestController {
@Autowired
private CustomerDAO customerDAO;
@RequestMapping("/customers")
public List getCustomers() {
return customerDAO.list();
}
@RequestMapping(value = "/customers/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity getCustomer(@PathVariable("id") Long id) {
Customer customer = customerDAO.get(id);
if (customer == null) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customer, HttpStatus.OK);
}
@RequestMapping(value = "/customers", method = RequestMethod.POST, headers = "Accept=application/json" )
public ResponseEntity createCustomer(@RequestBody Customer customer) {
customerDAO.create(customer);
return new ResponseEntity(customer, HttpStatus.OK);
}
@RequestMapping(value = "/customers/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json" )
public ResponseEntity deleteCustomer(@PathVariable Long id) {
if (null == customerDAO.delete(id)) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(id, HttpStatus.OK);
}
@RequestMapping(value = "/customers/{id}", method = RequestMethod.PUT, headers = "Accept=application/json" )
public ResponseEntity updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
customer = customerDAO.update(id, customer);
if (null == customer) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customer, HttpStatus.OK);
}
} | 32.138889 | 112 | 0.77312 |
9d2046f024d1d8f20e1cbfe0eb8e7b5114a7ab8d | 542 | package com.lecast.smartchart.axis;
import com.lecast.smartchart.chart.CartesianChart;
/**
* @author vincent
*
*/
public interface IAxis
{
public void dataChanged();
public void update();
public String getTitle();
public String getDisplayName();
public void setDataProvider(Object dataProvider);
public Object getDataProvider();
public void setFontSize(int fontSize);
public int getTextAngle();
public AxisLabelSetting getAxisLabelSetting();
public void accept(CartesianChart chart);
}
| 16.9375 | 53 | 0.717712 |
c7cc987f7b37b38a010ff4d53421f0ff89ea0141 | 267 | package com.ruoyi.project.system.yx.mapper;
import java.util.Map;
import com.ruoyi.project.system.yx.domain.YxYue;
/**
* 牙星公司Mapper接口
*
* @author ruoyi
* @date 2020-04-07
*/
public interface tableYYMapper {
Map YxtableYY(YxYue YxYue);
}
| 15.705882 | 49 | 0.666667 |
821fccdfc3dc219cc2bfa2bc8933110a1d6bf358 | 1,315 | package de.ancash.sockets.async;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Executors;
import de.ancash.sockets.async.client.AbstractAsyncClient;
import de.ancash.sockets.async.client.AbstractAsyncClientFactory;
import de.ancash.sockets.async.server.AbstractAsyncServer;
public class AsyncChatClientFactory extends AbstractAsyncClientFactory{
@Override
public AbstractAsyncClient newInstance(AbstractAsyncServer asyncServer, AsynchronousSocketChannel socket, int queueSize, int readBufSize) {
throw new UnsupportedOperationException();
}
@Override
public AsyncChatClient newInstance(String address, int port, int queueSize, int readBufSize, int threads) throws IOException {
AsynchronousChannelGroup asyncChannelGroup = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(3));
AsynchronousSocketChannel asyncSocket = AsynchronousSocketChannel.open(asyncChannelGroup);
AsyncChatClient client = new AsyncChatClient(asyncSocket, asyncChannelGroup, queueSize, readBufSize, threads);
asyncSocket.connect(new InetSocketAddress(address, port), client, client.getAsyncConnectHandlerFactory().newInstance(client));
return client;
}
} | 46.964286 | 140 | 0.846388 |
45307eb14b4586fb635bb59f19d397ff640c286e | 3,290 | package nl.hsleiden.tags;
import javax.servlet.http.HttpServletRequest;
import org.hippoecm.hst.configuration.hosting.Mount;
import org.hippoecm.hst.configuration.site.HstSite;
import org.hippoecm.hst.configuration.sitemenu.HstSiteMenuConfiguration;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.request.HstRequestContext;
import org.hippoecm.hst.core.sitemenu.CommonMenu;
import org.hippoecm.hst.core.sitemenu.CommonMenuItem;
import org.hippoecm.hst.core.sitemenu.HstSiteMenuImpl;
import com.tdclighthouse.prototype.utils.NavigationUtils;
public class MenuFunctions {
private MenuFunctions() {
}
public static CommonMenuItem getTopMenuItem(CommonMenu menu, Integer level) {
CommonMenuItem result = null;
if (menu != null) {
result = getTopMenuItemOfNotNullMenu(menu, level);
}
return result;
}
// just for making sonar happy :)
private static CommonMenuItem getTopMenuItemOfNotNullMenu(CommonMenu menu, Integer level) {
CommonMenuItem result = null;
Integer depthLevel = level;
for (CommonMenuItem menuItem : NavigationUtils.getMenuItems(menu)) {
if (menuItem != null && menuItem.isExpanded()) {
while (depthLevel != 0) {
depthLevel--;
menuItem = recurseMenuItems(menuItem);
}
result = menuItem;
}
}
return result;
}
private static CommonMenuItem recurseMenuItems(CommonMenuItem menuItem) {
CommonMenuItem result = null;
if (menuItem != null) {
for (CommonMenuItem child : NavigationUtils.getSubmenuItems(menuItem)) {
if (child.isExpanded()) {
result = child;
}
}
}
if (result == null) {
result = menuItem;
}
return result;
}
public static CommonMenuItem getMenuItem(HttpServletRequest req, CommonMenuItem originalMenuItem) {
CommonMenuItem result = originalMenuItem;
String sitemenuConfigParameter = ParametersFunctions.getSitemenuConfigParameter(originalMenuItem,
"useMainMenuConfig");
if (sitemenuConfigParameter != null && "true".equalsIgnoreCase(sitemenuConfigParameter)) {
HstRequest request = (HstRequest) req;
CommonMenu mainMenu = getSiteMainMenu(request);
String originalMenuItemName = originalMenuItem.getName();
for (CommonMenuItem menuItem : NavigationUtils.getMenuItems(mainMenu)) {
if (originalMenuItemName.equals(menuItem.getName())) {
result = menuItem;
break;
}
}
}
return result;
}
private static CommonMenu getSiteMainMenu(HstRequest request) {
HstRequestContext requestContext = request.getRequestContext();
Mount mount = requestContext.getMount("hsl");
HstSite hstSite = mount.getHstSite();
HstSiteMenuConfiguration siteMenuConfiguration = hstSite.getSiteMenusConfiguration().getSiteMenuConfiguration(
"main");
return new HstSiteMenuImpl(null, siteMenuConfiguration, requestContext);
}
}
| 35 | 118 | 0.649848 |
5e3766b65fb4a1ed953fe3e7a464fdd0d87c9db1 | 5,454 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.app;
import android.os.RemoteException;
// Referenced classes of package android.support.v4.app:
// NotificationManagerCompat, INotificationSideChannel
private static class NotificationManagerCompat$CancelTask
implements NotificationManagerCompat.Task
{
public void send(INotificationSideChannel inotificationsidechannel)
throws RemoteException
{
if(all)
//* 0 0:aload_0
//* 1 1:getfield #29 <Field boolean all>
//* 2 4:ifeq 18
{
inotificationsidechannel.cancelAll(packageName);
// 3 7:aload_1
// 4 8:aload_0
// 5 9:getfield #23 <Field String packageName>
// 6 12:invokeinterface #40 <Method void INotificationSideChannel.cancelAll(String)>
return;
// 7 17:return
} else
{
inotificationsidechannel.cancel(packageName, id, tag);
// 8 18:aload_1
// 9 19:aload_0
// 10 20:getfield #23 <Field String packageName>
// 11 23:aload_0
// 12 24:getfield #25 <Field int id>
// 13 27:aload_0
// 14 28:getfield #27 <Field String tag>
// 15 31:invokeinterface #43 <Method void INotificationSideChannel.cancel(String, int, String)>
return;
// 16 36:return
}
}
public String toString()
{
StringBuilder stringbuilder = new StringBuilder("CancelTask[");
// 0 0:new #48 <Class StringBuilder>
// 1 3:dup
// 2 4:ldc1 #50 <String "CancelTask[">
// 3 6:invokespecial #52 <Method void StringBuilder(String)>
// 4 9:astore_1
stringbuilder.append("packageName:").append(packageName);
// 5 10:aload_1
// 6 11:ldc1 #54 <String "packageName:">
// 7 13:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 8 16:aload_0
// 9 17:getfield #23 <Field String packageName>
// 10 20:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 11 23:pop
stringbuilder.append(", id:").append(id);
// 12 24:aload_1
// 13 25:ldc1 #60 <String ", id:">
// 14 27:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 15 30:aload_0
// 16 31:getfield #25 <Field int id>
// 17 34:invokevirtual #63 <Method StringBuilder StringBuilder.append(int)>
// 18 37:pop
stringbuilder.append(", tag:").append(tag);
// 19 38:aload_1
// 20 39:ldc1 #65 <String ", tag:">
// 21 41:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 22 44:aload_0
// 23 45:getfield #27 <Field String tag>
// 24 48:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 25 51:pop
stringbuilder.append(", all:").append(all);
// 26 52:aload_1
// 27 53:ldc1 #67 <String ", all:">
// 28 55:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 29 58:aload_0
// 30 59:getfield #29 <Field boolean all>
// 31 62:invokevirtual #70 <Method StringBuilder StringBuilder.append(boolean)>
// 32 65:pop
stringbuilder.append("]");
// 33 66:aload_1
// 34 67:ldc1 #72 <String "]">
// 35 69:invokevirtual #58 <Method StringBuilder StringBuilder.append(String)>
// 36 72:pop
return stringbuilder.toString();
// 37 73:aload_1
// 38 74:invokevirtual #74 <Method String StringBuilder.toString()>
// 39 77:areturn
}
final boolean all;
final int id;
final String packageName;
final String tag;
NotificationManagerCompat$CancelTask(String s)
{
// 0 0:aload_0
// 1 1:invokespecial #21 <Method void Object()>
packageName = s;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #23 <Field String packageName>
id = 0;
// 5 9:aload_0
// 6 10:iconst_0
// 7 11:putfield #25 <Field int id>
tag = null;
// 8 14:aload_0
// 9 15:aconst_null
// 10 16:putfield #27 <Field String tag>
all = true;
// 11 19:aload_0
// 12 20:iconst_1
// 13 21:putfield #29 <Field boolean all>
// 14 24:return
}
NotificationManagerCompat$CancelTask(String s, int i, String s1)
{
// 0 0:aload_0
// 1 1:invokespecial #21 <Method void Object()>
packageName = s;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #23 <Field String packageName>
id = i;
// 5 9:aload_0
// 6 10:iload_2
// 7 11:putfield #25 <Field int id>
tag = s1;
// 8 14:aload_0
// 9 15:aload_3
// 10 16:putfield #27 <Field String tag>
all = false;
// 11 19:aload_0
// 12 20:iconst_0
// 13 21:putfield #29 <Field boolean all>
// 14 24:return
}
}
| 36.604027 | 101 | 0.551705 |
15f433f2de10c8e20e4f046089025b1f1d76fcc1 | 1,685 | package io.snyk.snyk_maven_plugin.download;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import static io.snyk.snyk_maven_plugin.download.UpdatePolicy.shouldUpdate;
public class ExecutableDownloader {
private static final String SNYK_RELEASES_LATEST = "https://static.snyk.io/cli/%s/%s";
@SuppressWarnings("ResultOfMethodCallIgnored")
public static File download(URL url, File destination, String updatePolicy) {
try {
if (destination.exists() && !shouldUpdate(
updatePolicy,
destination.lastModified(),
System.currentTimeMillis()
)) {
return destination;
}
destination.getParentFile().mkdirs();
try (
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(destination);
) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
destination.setExecutable(true);
return destination;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static URL getDownloadUrl(Platform platform, String version) {
try {
return new URL(String.format(SNYK_RELEASES_LATEST, version, platform.snykExecutableFileName));
} catch (MalformedURLException e) {
throw new RuntimeException("Download URL is malformed", e);
}
}
}
| 34.387755 | 106 | 0.641543 |
4c56fcf2b81f7f6f16e2ee4096d1d7783df69cb3 | 1,896 | /*
* Copyright 2004 - 2012 Mirko Nasato and contributors
* 2016 - 2020 Simon Braconnier and contributors
*
* This file is part of JODConverter - Java OpenDocument Converter.
*
* 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.jodconverter.core.document;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Contains properties that will be applied when loading(opening) and storing(saving) document for a
* specific {@link DocumentFormat}.
*/
public class DocumentFormatProperties {
/** Properties applied when loading(opening) a document. */
private final Map<String, Object> load = new HashMap<>();
/** Properties applied when storing(saving) a document for each supported families. */
private final Map<DocumentFamily, Map<String, Object>> store = new HashMap<>();
/**
* Gets the properties applied when loading(opening) a document.
*
* @return A map containing the properties.
*/
@NonNull
public Map<@NonNull String, @NonNull Object> getLoad() {
return load;
}
/**
* Gets the properties applied when storing(saving) a document for each supported families.
*
* @return A map containing the properties.
*/
@NonNull
public Map<@NonNull DocumentFamily, @NonNull Map<@NonNull String, @NonNull Object>> getStore() {
return store;
}
}
| 32.135593 | 100 | 0.721519 |
5e259f8ee5a859fa2f734c43113a4d067c025630 | 1,194 | package test.api;
import framework.E2ESuiteBase;
import framework.UserTestBase;
import io.restassured.response.Response;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.google.common.truth.Truth.assertThat;
public class CreateUsers extends UserTestBase {
@BeforeClass
public void setupToken() {
setToken();
}
@Test(dataProvider = "userdata")
public void testCreateUser(String email, String firstName, String lastName, int age) {
Response resCreate = createUser(email, firstName, lastName, age, E2ESuiteBase.token);
checkApiSuccess(resCreate);
int id = resCreate.getBody().jsonPath().getInt("id");
Response resGet = getUser(id, E2ESuiteBase.token);
checkApiSuccess(resGet);
usersAvailable.put(email, id);
assertThat(resGet.getBody().jsonPath().getString("first_name")).isEqualTo(firstName);
assertThat(resGet.getBody().jsonPath().getString("last_name")).isEqualTo(lastName);
assertThat(resGet.getBody().jsonPath().getString("email")).isEqualTo(email);
assertThat(resGet.getBody().jsonPath().getInt("age")).isEqualTo(age);
}
}
| 34.114286 | 93 | 0.71273 |
9944ac75d002190f266130b452ce8cfd21246df5 | 2,441 | package xyz.cofe.collection.graph;
/**
* Базовый интервейс графа
* @author GoCha
* @param <N> Тип вершины
* @param <E> Тип дуги/ребра
*/
public interface Graph<N,E>
{
/**
* Проверяет наличае вершины
* @param node Вершина
* @return true -вершина содержиться в графе
*/
boolean contains(N node);
/**
* Добавляет вершину к графу
* @param node Вершина
*/
void add(N node);
/**
* Удаляет вершину из графа
* @param node Вершина
*/
void remove(N node);
/**
* Возвращает вершины графа
* @return вершины
*/
Iterable<N> getNodes();
/**
* Возвращает Ребра и вершины графа
* @return Ребра и вершины
*/
Iterable<Edge<N, E>> getEdges();
/**
* Возвращает ребра указанной вершины
* @param node Вершина
* @return ребра
*/
Iterable<Edge<N, E>> edgesOf(N node);
/**
* Возвращает ребра из вершины А
* @param nodeA Вершина А
* @return Ребра
*/
Iterable<Edge<N, E>> edgesOfNodeA(N nodeA);
/**
* Возвращает ребра из вершины Б
* @param nodeB Вершина Б
* @return Ребра
*/
Iterable<Edge<N, E>> edgesOfNodeB(N nodeB);
/**
* Удаляет все ребра
*/
void clearEdges();
/**
* Удалес все ребра и вершины
*/
void clearAll();
/**
* Проверка наличия ребра между вершинами
* @param a Вершина А
* @param b Вершина Б
* @return Флаг наличия ребра
*/
boolean hasEdge(N a, N b);
/**
* Удаление ребра
* @param a Вершина А
* @param b Вершина Б
*/
void removeEdge(N a, N b);
/**
* Возвращает ребро между вершинами
* @param a Вершина А
* @param b Вершина Б
* @return Ребро
*/
E getEdge(N a, N b);
/**
* Установка ребра между вершинами
* @param a Вершина А
* @param edge Ребро
* @param b Вершина Б
*/
void setEdge( N a, N b, E edge);
/**
* Возвращает ребра между вершинами
* @param a Вершина А
* @param b Вершина Б
* @return Ребра
*/
Iterable<E> getEdges(N a, N b);
/**
* Установка ребр между вершинами
* @param a Вершина А
* @param edges Ребра
* @param b Вершина Б
*/
void setEdges( N a, N b, Iterable<E> edges);
}
| 20.341667 | 49 | 0.521098 |
756d8c9b1099da8c6a13a2db06670d1548103c50 | 6,435 | package net.haesleinhuepf.clij2.plugins;
import ij.IJ;
import ij.ImagePlus;
import ij.plugin.Duplicator;
import ij.plugin.ImageCalculator;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.clearcl.ClearCLImage;
import net.haesleinhuepf.clij.test.TestUtilities;
import net.haesleinhuepf.clij2.CLIJ2;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class AddImagesWeightedTest {
@Test
public void addWeightedPixelwise3d() {
CLIJ2 clij2 = CLIJ2.getInstance();
ImagePlus testImp1 = TestUtilities.getRandomImage(100, 100, 3, 16, 0, 15);
ImagePlus testImp2 = TestUtilities.getRandomImage(100, 100, 3, 16, 0, 15);
float factor1 = 3f;
float factor2 = 2;
// do operation with ImageJ
ImagePlus testImp1copy = new Duplicator().run(testImp1);
ImagePlus testImp2copy = new Duplicator().run(testImp2);
IJ.run(testImp1copy,
"Multiply...",
"value=" + factor1 + " stack");
IJ.run(testImp2copy,
"Multiply...",
"value=" + factor2 + " stack");
ImageCalculator ic = new ImageCalculator();
ImagePlus
sumImp =
ic.run("Add create stack", testImp1copy, testImp2copy);
// do operation with ClearCL
ClearCLImage src = clij2.convert(testImp1, ClearCLImage.class);
ClearCLImage src1 = clij2.convert(testImp2, ClearCLImage.class);
ClearCLImage dst = clij2.convert(testImp1, ClearCLImage.class);
clij2.addImagesWeighted(
src,
src1,
dst,
factor1,
factor2);
ImagePlus sumImpFromCL = clij2.pull(dst);
assertTrue(TestUtilities.compareImages(sumImp, sumImpFromCL));
src.close();
src1.close();
dst.close();
IJ.exit();
clij2.clear();
}
@Test
public void addWeightedPixelwise3d_Buffers() {
CLIJ2 clij2 = CLIJ2.getInstance();
ImagePlus testImp1 = TestUtilities.getRandomImage(100, 100, 3, 16, 0, 15);
ImagePlus testImp2 = TestUtilities.getRandomImage(100, 100, 3, 16, 0, 15);
float factor1 = 3f;
float factor2 = 2;
// do operation with ImageJ
ImagePlus testImp1copy = new Duplicator().run(testImp1);
ImagePlus testImp2copy = new Duplicator().run(testImp2);
IJ.run(testImp1copy,
"Multiply...",
"value=" + factor1 + " stack");
IJ.run(testImp2copy,
"Multiply...",
"value=" + factor2 + " stack");
ImageCalculator ic = new ImageCalculator();
ImagePlus
sumImp =
ic.run("Add create stack", testImp1copy, testImp2copy);
// do operation with ClearCL
ClearCLBuffer src = clij2.convert(testImp1, ClearCLBuffer.class);
ClearCLBuffer src1 = clij2.convert(testImp2, ClearCLBuffer.class);
ClearCLBuffer dst = clij2.convert(testImp1, ClearCLBuffer.class);
clij2.addImagesWeighted(
src,
src1,
dst,
factor1,
factor2);
ImagePlus sumImpFromCL = clij2.convert(dst, ImagePlus.class);
assertTrue(TestUtilities.compareImages(sumImp, sumImpFromCL));
src.close();
src1.close();
dst.close();
IJ.exit();
clij2.clear();
}
@Test
public void addWeightedPixelwise2d() {
CLIJ2 clij2 = CLIJ2.getInstance();
ImagePlus testImp2D1 = TestUtilities.getRandomImage(100, 100, 1, 16, 0, 15);
ImagePlus testImp2D2 = TestUtilities.getRandomImage(100, 100, 1, 16, 0, 15);
float factor1 = 3f;
float factor2 = 2;
// do operation with ImageJ
ImagePlus testImp1copy = new Duplicator().run(testImp2D1);
ImagePlus testImp2copy = new Duplicator().run(testImp2D2);
IJ.run(testImp1copy, "Multiply...", "value=" + factor1 + " ");
IJ.run(testImp2copy, "Multiply...", "value=" + factor2 + " ");
ImageCalculator ic = new ImageCalculator();
ImagePlus
sumImp =
ic.run("Add create ", testImp1copy, testImp2copy);
// do operation with ClearCL
ClearCLImage src = clij2.convert(testImp2D1, ClearCLImage.class);
ClearCLImage src1 = clij2.convert(testImp2D2, ClearCLImage.class);
ClearCLImage dst = clij2.convert(testImp2D1, ClearCLImage.class);
clij2.addImagesWeighted(
src,
src1,
dst,
factor1,
factor2);
ImagePlus sumImpFromCL = clij2.convert(dst, ImagePlus.class);
assertTrue(TestUtilities.compareImages(sumImp, sumImpFromCL));
src.close();
src1.close();
dst.close();
IJ.exit();
clij2.clear();
}
@Test
public void addWeightedPixelwise2d_Buffers() {
CLIJ2 clij2 = CLIJ2.getInstance();
ImagePlus testImp2D1 = TestUtilities.getRandomImage(100, 100, 1, 16, 0, 15);
ImagePlus testImp2D2 = TestUtilities.getRandomImage(100, 100, 1, 16, 0, 15);
float factor1 = 3f;
float factor2 = 2;
// do operation with ImageJ
ImagePlus testImp1copy = new Duplicator().run(testImp2D1);
ImagePlus testImp2copy = new Duplicator().run(testImp2D2);
IJ.run(testImp1copy, "Multiply...", "value=" + factor1 + " ");
IJ.run(testImp2copy, "Multiply...", "value=" + factor2 + " ");
ImageCalculator ic = new ImageCalculator();
ImagePlus
sumImp =
ic.run("Add create ", testImp1copy, testImp2copy);
// do operation with ClearCL
ClearCLBuffer src = clij2.convert(testImp2D1, ClearCLBuffer.class);
ClearCLBuffer src1 = clij2.convert(testImp2D2, ClearCLBuffer.class);
ClearCLBuffer dst = clij2.convert(testImp2D1, ClearCLBuffer.class);
clij2.addImagesWeighted(
src,
src1,
dst,
factor1,
factor2);
ImagePlus sumImpFromCL = clij2.convert(dst, ImagePlus.class);
assertTrue(TestUtilities.compareImages(sumImp, sumImpFromCL));
src.close();
src1.close();
dst.close();
IJ.exit();
clij2.clear();
}
} | 33.170103 | 84 | 0.592385 |
ba7f2f03b079838879b391fc4423e5eb0286d76f | 730 | //,temp,TestReplicationScenariosAcrossInstances.java,1323,1335,temp,TestReplicationScenariosAcrossInstances.java,1286,1299
//,3
public class xxx {
@Override
public Boolean apply(CallerArguments args) {
injectionPathCalled = true;
if (!args.dbName.equalsIgnoreCase(replicatedDbName) || (args.constraintTblName != null)) {
LOG.warn("Verifier - DB: " + String.valueOf(args.dbName)
+ " Constraint Table: " + String.valueOf(args.constraintTblName));
return false;
}
if (args.tblName != null) {
LOG.warn("Verifier - Table: " + String.valueOf(args.tblName));
return args.tblName.equals("t1");
}
return true;
}
}; | 38.421053 | 122 | 0.627397 |
5542a57cb59d0d5eefee142da6516529ed1d3c66 | 643 | package com.jsite.common.beetl.fn;
import com.jsite.common.lang.StringUtils;
import org.beetl.core.Context;
import org.beetl.core.Function;
import java.util.List;
public class InArrayString implements Function {
@Override
public Object call(Object[] paras, Context ctx) {
String word = (String) paras[0];
List<String> arrString = (List<String>) paras[1];
if (StringUtils.isBlank(word) || arrString == null)
return false;
for (String s : arrString) {
if (word.equals(StringUtils.trim(s))) {
return true;
}
}
return false;
}
}
| 23.814815 | 59 | 0.609642 |
0e6a6b5dd56707b37155e26d31dab14887995989 | 18,053 | //
// Copyright (c) 2016 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
package com.couchbase.lite.multithreads;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.CouchbaseLiteRuntimeException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Emitter;
import com.couchbase.lite.LiteTestCaseWithDB;
import com.couchbase.lite.LiveQuery;
import com.couchbase.lite.Mapper;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.Reducer;
import com.couchbase.lite.View;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by hideki on 6/29/16.
*/
public class MultiThreadsTest extends LiteTestCaseWithDB {
private static final String TAG = MultiThreadsTest.class.getName();
@Override
protected void setUp() throws Exception {
if (!multithreadsTestsEnabled()) {
return;
}
super.setUp();
}
public void testInsertAndQueryThreads() {
if (!multithreadsTestsEnabled())
return;
// create view
final View view = createView(database);
final AtomicInteger count = new AtomicInteger();
Thread insertThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
String docID = String.format(Locale.ENGLISH, "docID-%08d", count.incrementAndGet());
Document doc = database.getDocument(docID);
Map<String, Object> props = new HashMap<String, Object>();
props.put("key", count.get());
try {
doc.putProperties(props);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Error in Document.putProperty(). ", e);
fail(e.getMessage());
}
}
}
});
Thread queryThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Query query = view.createQuery();
try {
for (QueryRow row : query.run()) {
Log.i(TAG, "row=%s", row.getDocumentId());
}
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Error in Query.run(). ", e);
fail(e.getMessage());
}
}
}
});
queryThread.start();
insertThread.start();
try {
insertThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in insertThread. ", e);
}
try {
queryThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in insertThread. ", e);
}
}
public static View createView(Database db) {
return createView(db, "aview");
}
public static View createView(Database db, String name) {
View view = db.getView(name);
if (view != null) {
view.setMapReduce(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
if (document.get("key") != null)
emitter.emit(document.get("key"), null);
}
}, null, "1");
}
return view;
}
/**
* https://github.com/couchbase/couchbase-lite-java-core/issues/1437
*/
public void testUpdateDocsAndReadRevHistory() throws Exception {
if (!multithreadsTestsEnabled())
return;
// Insert docs
Thread insertThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
String docID = String.format(Locale.ENGLISH, "docID-%08d", i);
Document doc = database.getDocument(docID);
Map<String, Object> props = new HashMap<String, Object>();
props.put("key", i);
try {
doc.putProperties(props);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Error in Document.putProperty(). ", e);
fail(e.getMessage());
}
}
}
});
insertThread.start();
try {
insertThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in insertThread. ", e);
}
// Thread1: read docs
Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 20; j++) {
for (int i = 0; i < 100; i++) {
String docID = String.format(Locale.ENGLISH, "docID-%08d", i);
Document doc = database.getDocument(docID);
String revID = doc.getCurrentRevisionId();
//RevisionInternal rev = new RevisionInternal(doc.getId(), revID, false);
RevisionInternal rev = new RevisionInternal(doc.getId(), doc.getCurrentRevisionId(), false);
//RevisionInternal rev = new RevisionInternal(doc.getId(), null, false);
List<RevisionInternal> revs = database.getRevisionHistory(rev);
//Log.e(TAG, "readThread docID=[%s] revID=[%s]", docID, revID);
assertNotNull(revs);
}
}
}
});
// Thread2: update docs
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
String docID = String.format(Locale.ENGLISH, "docID-%08d", i);
Log.e(TAG, "updateThread docID=%s", docID);
for (int j = 0; j < 20; j++) {
Document doc = database.getDocument(docID);
Map<String, Object> props = new HashMap<String, Object>();
props.putAll(doc.getProperties());
props.put("index", j);
try {
doc.putProperties(props);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Error in Document.putProperty(). ThreadName=[%s]", e, Thread.currentThread().getName());
fail(e.getMessage());
}
}
}
}
});
// run read thread and update thread in parallel
readThread.start();
updateThread.start();
// wait read thread finish
try {
readThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in readThread. ", e);
}
// wait update thread finish
try {
updateThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in updateThread. ", e);
}
}
/**
* ported from .NET - TestMultipleQueriesOnSameView()
* https://github.com/couchbase/couchbase-lite-net/blob/master/src/Couchbase.Lite.Tests.Shared/ViewsTest.cs#L2136
*/
public void testMultipleQueriesOnSameView() throws CouchbaseLiteException {
if (!multithreadsTestsEnabled())
return;
View view = database.getView("view1");
view.setMapReduce(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
emitter.emit(document.get("jim"), document.get("_id"));
}
}, new Reducer() {
@Override
public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) {
return keys.size();
}
}, "1.0");
LiveQuery query1 = view.createQuery().toLiveQuery();
LiveQuery query2 = view.createQuery().toLiveQuery();
try {
query1.start();
query2.start();
long timestamp = System.currentTimeMillis();
for (int i = 0; i < 50; i++) {
String docID = String.format(Locale.ENGLISH, "doc%d-%d", i, timestamp);
Document doc = database.getDocument(docID);
Map<String, Object> props = new HashMap<String, Object>();
props.put("jim", "borden");
doc.putProperties(props);
}
sleep(5 * 1000);
assertEquals(50, view.getTotalRows());
assertEquals(50, view.getLastSequenceIndexed());
query1.stop();
for (int i = 50; i < 60; i++) {
String docID = String.format(Locale.ENGLISH, "doc%d-%d", i, timestamp);
Document doc = database.getDocument(docID);
Map<String, Object> props = new HashMap<String, Object>();
props.put("jim", "borden");
doc.putProperties(props);
if (i == 55) {
query1.start();
}
}
sleep(5 * 1000);
assertEquals(60, view.getTotalRows());
assertEquals(60, view.getLastSequenceIndexed());
} finally {
query1.stop();
query2.stop();
}
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.e(TAG, "Error in Thread.sleep() - %d ms", e, millis);
}
}
/**
* parallel view/query without prefix
*/
public void testParallelViewQueries() throws CouchbaseLiteException {
_testParallelViewQueries("");
}
/**
* parallel view/query with prefix
*/
public void testParallelViewQueriesWithPrefix() throws CouchbaseLiteException {
_testParallelViewQueries("prefix/");
}
/**
* ported from .NET - TestParallelViewQueries()
* https://github.com/couchbase/couchbase-lite-net/blob/master/src/Couchbase.Lite.Tests.Shared/ViewsTest.cs#L399
*/
private void _testParallelViewQueries(String prefix) throws CouchbaseLiteException {
if (!multithreadsTestsEnabled())
return;
int[] data = new int[]{42, 184, 256, Integer.MAX_VALUE, 412};
final String viewName = prefix + "vu";
View vu = database.getView(viewName);
vu.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", document.get("sequence"));
emitter.emit(key, null);
}
}, "1.0");
final String viewNameFake = prefix + "vuFake";
View vuFake = database.getView(viewNameFake);
vuFake.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", "FAKE");
emitter.emit(key, null);
}
}, "1.0");
createDocuments(database, 500);
int expectCount = 1;
parallelQuery(data, expectCount, viewName, viewNameFake);
createDocuments(database, 500);
expectCount = 2;
parallelQuery(data, expectCount, viewName, viewNameFake);
vu.delete();
vu = database.getView(viewName);
vu.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", document.get("sequence"));
emitter.emit(key, null);
}
}, "1.0");
expectCount = 2;
parallelQuery(data, expectCount, viewName, viewNameFake);
vuFake.delete();
vuFake = database.getView(viewNameFake);
vuFake.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", "FAKE");
emitter.emit(key, null);
}
}, "1.0");
expectCount = 2;
parallelQuery(data, expectCount, viewName, viewNameFake);
}
private void parallelQuery(int[] numbers, final int expectCount, final String viewName1, final String viewName2) {
Thread[] threads = new Thread[numbers.length];
for (int i = 0; i < numbers.length; i++) {
final int num = numbers[i];
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try {
if (num == Integer.MAX_VALUE)
queryAction2(expectCount, viewName2);
else
queryAction(num, expectCount, viewName1);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
});
}
for (int i = 0; i < numbers.length; i++) {
threads[i].start();
}
for (int i = 0; i < numbers.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void queryAction(int x, int expectCount, String viewName) throws CouchbaseLiteException {
Database db = manager.getDatabase(database.getName());
View gotVu = db.getView(viewName);
Query query = gotVu.createQuery();
List<Object> keys = new ArrayList<Object>();
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", x);
keys.add(key);
query.setKeys(keys);
QueryEnumerator rows = query.run();
assertEquals(expectCount * 500, gotVu.getLastSequenceIndexed());
assertEquals(expectCount, rows.getCount());
}
private void queryAction2(int expectCount, String viewName) throws CouchbaseLiteException {
Database db = manager.getDatabase(database.getName());
View gotVu = db.getView(viewName);
Query query = gotVu.createQuery();
List<Object> keys = new ArrayList<Object>();
Map<String, Object> key = new HashMap<String, Object>();
key.put("sequence", "FAKE");
keys.add(key);
query.setKeys(keys);
QueryEnumerator rows = query.run();
assertEquals(expectCount * 500, gotVu.getLastSequenceIndexed());
assertEquals(expectCount * 500, rows.getCount());
}
public void testCloseDBDuringInsertions() throws CouchbaseLiteException {
if (!multithreadsTestsEnabled())
return;
final Database db = manager.getDatabase("multi-thread-close-db");
final CountDownLatch latch = new CountDownLatch(50);
Thread insertThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
store(i);
latch.countDown();
}
}
});
Thread closeThread = new Thread(new Runnable() {
@Override
public void run() {
try {
assertTrue(latch.await(30, TimeUnit.SECONDS));
} catch (InterruptedException e) {
fail(e.toString());
}
db.close();
}
});
closeThread.start();
insertThread.start();
try {
closeThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in closeThread. ", e);
}
try {
insertThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Error in insertThread. ", e);
}
db.delete();
}
private void store(int i) {
try {
Database db = manager.getDatabase("multi-thread-close-db");
String id = String.format(Locale.ENGLISH, "ID_%05d", i);
Document doc = db.getDocument(id);
Map<String, Object> props = new HashMap<String, Object>();
props.put("value", i);
doc.putProperties(props);
} catch (CouchbaseLiteRuntimeException re) {
Log.e(TAG, "Error in store(): %s", re.getMessage());
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Error in store()", e);
fail("Error in store()");
}
}
}
| 35.537402 | 128 | 0.528666 |
478b3937290b5d701de0d9f5c04aa17e6828542b | 2,543 | public class Alarm extends SubstituteStrategic {
private static final boolean synX244boolean = false;
private static final boolean synX243boolean = true;
private static final boolean synX242boolean = false;
private static final int synX241int = 0;
private static final boolean synX240boolean = false;
private static final int synX239int = 0;
private static final double synX238double = 0.08476015478247001;
private static final int synX237int = 0;
private static final int synX236int = 30;
private static final int synX235int = 1127055936;
private static final int synX234int = 0;
private static final double synX233double = 0.10778275568730522;
private static final int synX232int = 30;
private static final int synX231int = 0;
private static final int synX230int = 29;
private static final double synX229double = 0.6533080417752668;
private int present = 0;
public static final double depressShackled = 0.4028078523947658;
public synchronized boolean isComplete() {
double chained;
chained = synX229double;
return Tires[synX230int] != null;
}
public Alarm() {
present = synX231int;
this.Tires = new Annexes[synX232int];
}
private Annexes[] Tires = null;
protected synchronized void enhanceFront(Annexes addendum, Operation prevalentMethod) {
double kesThings;
kesThings = synX233double;
if (Tires[present] == null) {
Tires[present] = addendum;
this.propelPoint();
return;
}
while (Tires[present].conveyUnlockFormalities() != prevalentMethod.catchIbid()
&& Tires[present].findBar() == synX234int) {
if (Tires[present].conveyUnlockFormalities() == prevalentMethod.catchIbid()) {
Tires[present].echelonUndercut();
}
propelPoint();
}
Tires[present] = addendum;
propelPoint();
}
private synchronized void propelPoint() {
int matt;
matt = synX235int;
present++;
if (present == synX236int) present = synX237int;
}
public synchronized boolean tabAsked(Operation previousProceeding) {
double critical;
critical = synX238double;
if (Tires[synX239int] == null) {
return synX240boolean;
}
for (int i = synX241int; i < Tires.length; i++) {
if (Tires[i] == null) return synX242boolean;
if (Tires[i].conveyUnlockFormalities() == previousProceeding.catchIbid()
&& previousProceeding.haveDemands().peek().equals(Tires[i].makeDimidiate())) {
return synX243boolean;
}
}
return synX244boolean;
}
}
| 29.917647 | 89 | 0.697601 |
9cd5049767009c3cec430f34a1bdc781312c0449 | 8,266 | package com.kickstarter.viewmodels;
import com.kickstarter.libs.ActivityViewModel;
import com.kickstarter.libs.CurrentUserType;
import com.kickstarter.libs.Environment;
import com.kickstarter.libs.rx.transformers.Transformers;
import com.kickstarter.services.ApiClientType;
import com.kickstarter.services.apiresponses.AccessTokenEnvelope;
import com.kickstarter.services.apiresponses.ErrorEnvelope;
import com.kickstarter.ui.IntentKey;
import com.kickstarter.ui.activities.TwoFactorActivity;
import androidx.annotation.NonNull;
import rx.Observable;
import rx.subjects.PublishSubject;
public interface TwoFactorViewModel {
interface Inputs {
/** Call when the 2FA code has been submitted. */
void code(String __);
/** Call when the log in button has been clicked. */
void loginClick();
/** Call when the resend button has been clicked. */
void resendClick();
}
interface Outputs {
/** Emits when submitting TFA code errored for an unknown reason. */
Observable<Void> genericTfaError();
/** Emits when TFA code was submitted. */
Observable<Boolean> formSubmitting();
/** Emits when TFA code submission has completed. */
Observable<Boolean> formIsValid();
/** Emits when resend code confirmation should be shown. */
Observable<Void> showResendCodeConfirmation();
/** Emits when a submitted TFA code does not match. */
Observable<Void> tfaCodeMismatchError();
/** Emits when submitting TFA code was successful. */
Observable<Void> tfaSuccess();
}
final class ViewModel extends ActivityViewModel<TwoFactorActivity> implements Inputs, Outputs{
private final ApiClientType client;
private final CurrentUserType currentUser;
public ViewModel(final @NonNull Environment environment) {
super(environment);
this.currentUser = environment.currentUser();
this.client = environment.apiClient();
final Observable<String> email = intent()
.map(i -> i.getStringExtra(IntentKey.EMAIL));
final Observable<String> fbAccessToken = intent()
.map(i -> i.getStringExtra(IntentKey.FACEBOOK_TOKEN));
final Observable<Boolean> isFacebookLogin = intent()
.map(i -> i.getBooleanExtra(IntentKey.FACEBOOK_LOGIN, false));
final Observable<String> password = intent()
.map(i -> i.getStringExtra(IntentKey.PASSWORD));
final Observable<TfaData> tfaData = Observable.combineLatest(
email, fbAccessToken, isFacebookLogin, password, TfaData::new
);
this.code
.map(TwoFactorViewModel.ViewModel::isCodeValid)
.compose(bindToLifecycle())
.subscribe(this.formIsValid);
this.code
.compose(Transformers.combineLatestPair(tfaData))
.compose(Transformers.takeWhen(this.loginClick))
.filter(cd -> !cd.second.isFacebookLogin)
.switchMap(cd -> this.login(cd.first, cd.second.email, cd.second.password))
.compose(bindToLifecycle())
.subscribe(this::success);
this.code
.compose(Transformers.combineLatestPair(tfaData))
.compose(Transformers.takeWhen(this.loginClick))
.filter(cd -> cd.second.isFacebookLogin)
.switchMap(cd -> this.loginWithFacebook(cd.first, cd.second.fbAccessToken))
.compose(bindToLifecycle())
.subscribe(this::success);
tfaData
.compose(Transformers.takeWhen(this.resendClick))
.filter(d -> !d.isFacebookLogin)
.flatMap(d -> resendCode(d.email, d.password))
.compose(bindToLifecycle())
.subscribe();
tfaData
.compose(Transformers.takeWhen(this.resendClick))
.filter(d -> d.isFacebookLogin)
.flatMap(d -> resendCodeWithFacebook(d.fbAccessToken))
.compose(bindToLifecycle())
.subscribe();
this.tfaSuccess
.compose(bindToLifecycle())
.subscribe(__ -> this.koala.trackLoginSuccess());
this.resendClick
.compose(bindToLifecycle())
.subscribe(__ -> this.koala.trackTwoFactorResendCode());
this.tfaError
.compose(bindToLifecycle())
.subscribe(__ -> this.koala.trackLoginError());
this.koala.trackTwoFactorAuthView();
}
private void success(final @NonNull AccessTokenEnvelope envelope) {
this.currentUser.login(envelope.user(), envelope.accessToken());
this.tfaSuccess.onNext(null);
}
private @NonNull Observable<AccessTokenEnvelope> login(final @NonNull String code, final @NonNull String email,
final @NonNull String password) {
return this.client.login(email, password, code)
.compose(Transformers.pipeApiErrorsTo(this.tfaError))
.compose(Transformers.neverError())
.doOnSubscribe(() -> this.formSubmitting.onNext(true))
.doAfterTerminate(() -> this.formSubmitting.onNext(false));
}
private @NonNull Observable<AccessTokenEnvelope> loginWithFacebook(final @NonNull String code, final @NonNull String fbAccessToken) {
return this.client.loginWithFacebook(fbAccessToken, code)
.compose(Transformers.pipeApiErrorsTo(this.tfaError))
.compose(Transformers.neverError())
.doOnSubscribe(() -> this.formSubmitting.onNext(true))
.doAfterTerminate(() -> this.formSubmitting.onNext(false));
}
private @NonNull Observable<AccessTokenEnvelope> resendCode(final @NonNull String email, final @NonNull String password) {
return this.client.login(email, password)
.compose(Transformers.neverError())
.doOnSubscribe(() -> this.showResendCodeConfirmation.onNext(null));
}
private @NonNull Observable<AccessTokenEnvelope> resendCodeWithFacebook(final @NonNull String fbAccessToken) {
return this.client.loginWithFacebook(fbAccessToken)
.compose(Transformers.neverError())
.doOnSubscribe(() -> this.showResendCodeConfirmation.onNext(null));
}
private static boolean isCodeValid(final String code) {
return code != null && code.length() > 0;
}
private final PublishSubject<String> code = PublishSubject.create();
private final PublishSubject<Void> loginClick = PublishSubject.create();
private final PublishSubject<Void> resendClick = PublishSubject.create();
private final PublishSubject<Boolean> formIsValid = PublishSubject.create();
private final PublishSubject<Boolean> formSubmitting = PublishSubject.create();
private final PublishSubject<Void> showResendCodeConfirmation = PublishSubject.create();
private final PublishSubject<ErrorEnvelope> tfaError = PublishSubject.create();
private final PublishSubject<Void> tfaSuccess = PublishSubject.create();
public final Inputs inputs = this;
public final Outputs outputs = this;
@Override public Observable<Boolean> formIsValid() {
return this.formIsValid;
}
@Override public Observable<Boolean> formSubmitting() {
return this.formSubmitting;
}
@Override public Observable<Void> genericTfaError() {
return this.tfaError
.filter(env -> !env.isTfaFailedError())
.map(__ -> null);
}
@Override public Observable<Void> showResendCodeConfirmation() {
return this.showResendCodeConfirmation;
}
@Override public Observable<Void> tfaCodeMismatchError() {
return this.tfaError
.filter(ErrorEnvelope::isTfaFailedError)
.map(__ -> null);
}
@Override public Observable<Void> tfaSuccess() {
return this.tfaSuccess;
}
@Override public void code(final @NonNull String s) {
this.code.onNext(s);
}
@Override public void loginClick() {
this.loginClick.onNext(null);
}
@Override public void resendClick() {
this.resendClick.onNext(null);
}
protected final class TfaData {
final @NonNull String email;
final @NonNull String fbAccessToken;
final boolean isFacebookLogin;
final @NonNull String password;
protected TfaData(final @NonNull String email, final @NonNull String fbAccessToken, final boolean isFacebookLogin,
final @NonNull String password) {
this.email = email;
this.fbAccessToken = fbAccessToken;
this.isFacebookLogin = isFacebookLogin;
this.password = password;
}
}
}
}
| 37.067265 | 137 | 0.69925 |
9af22b913c03eba3ca9cc18b1ebb3e7f069f523e | 1,408 | package quina.test.route;
import quina.component.restful.RESTfulGetSync;
import quina.exception.QuinaException;
import quina.http.Params;
import quina.http.Request;
import quina.http.server.response.SyncResponse;
import quina.jdbc.QuinaConnection;
import quina.jdbc.QuinaDataSource;
import quina.jdbc.QuinaJDBCService;
import quina.jdbc.io.QueryStatement;
import quina.json.JsonList;
import quina.route.annotation.Route;
@Route("/json/jdbc/testTable")
public class TestDBJsonGet implements RESTfulGetSync {
@Override
public Object get(Request req, SyncResponse res, Params params) {
QueryStatement qe;
QuinaDataSource ds = QuinaJDBCService.dataSource("testdb");
try(QuinaConnection conn = ds.getConnection()) {
JsonList ret = new JsonList();
// id=1001を取得.
qe = conn.queryStatement();
//qe.sql("select id, name, grade from TestTable")
//qe.selectSQL("TestTable", "id", "name", "grade")
// .sql("where id=?")
// .params(1001)
// .executeQuery()
// .getList(ret);
qe.selectRow(ret, "TestTable",
"id", 1001);
// id=2001を取得.
//qe.sql("select id, name, grade from TestTable")
//qe.selectSQL("TestTable", "id", "name", "grade")
// .sql("where id=?")
// .params(2001)
// .executeQuery()
// .getList(ret);
qe.selectRow(ret, "TestTable",
"id", 2001);
return ret;
} catch(Exception e) {
throw new QuinaException(e);
}
}
}
| 27.076923 | 66 | 0.68821 |
c970be398a609fce55060f4aa9ba5005fb87f22d | 1,587 | package com.lukinhasssss.proposta.dto.request;
import com.lukinhasssss.proposta.config.validation.Document;
import com.lukinhasssss.proposta.config.validation.UniqueValue;
import com.lukinhasssss.proposta.entities.Proposta;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import javax.validation.constraints.*;
import java.math.BigDecimal;
public class PropostaRequest {
@NotBlank @NotEmpty
private String nome;
@NotBlank @NotEmpty
@Email
private String email;
@NotBlank @NotEmpty
@Document
@UniqueValue(domainClass = Proposta.class, fieldName = "documento", message = "Já existe uma proposta associada a este CPF/CNPJ")
private String documento;
@NotBlank @NotEmpty
private String endereco;
@NotNull @PositiveOrZero
private BigDecimal salario;
public PropostaRequest(String nome, String email, String documento, String endereco, BigDecimal salario) {
this.nome = nome;
this.email = email;
this.documento = documento;
this.endereco = endereco;
this.salario = salario;
}
public String getNome() {
return nome;
}
public String getEmail() {
return email;
}
public String getDocumento() {
return documento;
}
public String getEndereco() {
return endereco;
}
public BigDecimal getSalario() {
return salario;
}
public Proposta converterParaEntidade(TextEncryptor encriptor) {
return new Proposta(nome, email, encriptor.encrypt(documento), endereco, salario);
}
}
| 24.796875 | 133 | 0.696912 |
554be28bc635bfa78f78e19b36d96231ea97d47c | 2,936 | /*
* Copyright 2018-present Open Networking Foundation
*
* 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.onosproject.net.flowobjective;
import org.onosproject.net.flow.TrafficTreatment;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Represents a next action specified by traffic treatment and weight.
*/
public final class DefaultNextTreatment implements NextTreatment {
private final TrafficTreatment treatment;
private final int weight;
private DefaultNextTreatment(TrafficTreatment treatment, int weight) {
this.treatment = treatment;
this.weight = weight;
}
/**
* Returns traffic treatment.
*
* @return traffic treatment.
*/
public TrafficTreatment treatment() {
return treatment;
}
/**
* Returns an instance of DefaultNextTreatment with given traffic treatment.
*
* @param treatment traffic treatment
* @return an instance of DefaultNextTreatment
*/
public static DefaultNextTreatment of(TrafficTreatment treatment) {
return new DefaultNextTreatment(treatment, DEFAULT_WEIGHT);
}
/**
* Returns an instance of DefaultNextTreatment with given traffic treatment and weight.
*
* @param treatment traffic treatment
* @param weight the weight of next treatment
* @return an instance of DefaultNextTreatment
*/
public static DefaultNextTreatment of(TrafficTreatment treatment, int weight) {
return new DefaultNextTreatment(treatment, weight);
}
@Override
public int weight() {
return weight;
}
@Override
public Type type() {
return Type.TREATMENT;
}
@Override
public int hashCode() {
return Objects.hash(treatment, weight);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultNextTreatment) {
final DefaultNextTreatment other = (DefaultNextTreatment) obj;
return Objects.equals(this.treatment, other.treatment) && Objects.equals(this.weight, other.weight);
}
return false;
}
@Override
public String toString() {
return toStringHelper(this)
.add("treatment", treatment)
.add("weight", weight)
.toString();
}
}
| 29.069307 | 112 | 0.672684 |
2cff9194d37fb4c654265f8ede5de48068ed4a38 | 348 | package Exceptions;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by mrc on 25/03/16.
*/
public class ExpiredSessionException extends Throwable {
public ExpiredSessionException(InputStream errorStream) throws IOException {
super(IOUtils.toString(errorStream));
}
}
| 21.75 | 80 | 0.755747 |
75ec089bd49761f9bdbb0bd4004c45fc4dc15c86 | 1,961 | package eventcenter.leveldb;
import eventcenter.api.*;
import eventcenter.api.async.QueueEventContainer;
import eventcenter.api.support.DefaultEventCenter;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class TestLevelDBEventContainerFactory {
DefaultEventCenter eventCenter;
@Ignore
@Test
public void test() throws Exception {
eventCenter = new DefaultEventCenter();
eventCenter.startup();
EventCenterConfig config = new EventCenterConfig();
List<EventListener> listeners = new ArrayList<EventListener>();
listeners.add(new TestListener());
CommonEventListenerConfig listenerConfig = new CommonEventListenerConfig();
listenerConfig.getListeners().put("test", listeners );
config.loadCommonEventListenerConfig(listenerConfig);
LevelDBContainerFactory factory = new LevelDBContainerFactory();
factory.setCorePoolSize(1);
factory.setMaximumPoolSize(1);
QueueEventContainer container = factory.createContainer(config);
container.startup();
Assert.assertEquals(true, container.isIdle());
container.send(new CommonEventSource(this, UUID.randomUUID().toString(), "test", null, null, null));
Thread.sleep(200);
Assert.assertEquals(false, container.isIdle());
container.send(new CommonEventSource(this, UUID.randomUUID().toString(), "test", null, null, null));
Thread.sleep(500);
Assert.assertEquals(false, container.isIdle());
Thread.sleep(1500);
Assert.assertEquals(true, container.isIdle());
container.shutdown();
eventCenter.shutdown();
}
class TestListener implements EventListener {
@Override
public void onObserved(CommonEventSource source) {
try {
System.out.println("begin consuming:" + source.getEventId());
Thread.sleep(1000);
System.out.println("consumed:" + source.getEventId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 30.169231 | 102 | 0.756757 |
f366e76192fb0d2234248e97fbf267cadb7b245b | 205 | package name.pkrause.blueprint.interfaceadapters.exceptions;
public class CatNotFoundException extends RuntimeException {
public CatNotFoundException(String message) {
super(message);
}
}
| 25.625 | 60 | 0.77561 |
054037f79ffdff661af04da9965d39fedc02ab2b | 1,824 | /*===========================================================================
Copyright (C) 2010 by the Okapi Framework contributors
-----------------------------------------------------------------------------
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.sf.okapi.common.filters;
/**
* Interface to edit a list of filter configurations at once.
*/
public interface IFilterConfigurationListEditor {
/**
* Displays a list of all available configurations in a given {@link FilterConfigurationMapper} and allow to edit them.
* @param fcMapper the {@link IFilterConfigurationMapper} to use.
*/
public void editConfigurations (IFilterConfigurationMapper fcMapper);
/**
* Displays a list of all available configurations in a given {@link FilterConfigurationMapper}, allow to edit them
* and to select one.
* @param fcMapper the {@link IFilterConfigurationMapper} to use.
* @param configId the configuration id to start with (can be null or empty).
* @return the configuration ID selected or null if none was selected. If the dialog
* is terminated with a Cancel or Close rather than a Select action, the return is null.
*/
public String editConfigurations (IFilterConfigurationMapper fcMapper, String configId);
}
| 44.487805 | 120 | 0.669408 |
670da2c995cbd5be29de2623dfdb5f5b0fb1652a | 3,791 | package org.kunze.diansh.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.kunze.diansh.controller.vo.HomeShopVo;
import org.kunze.diansh.entity.HomeShop;
import org.kunze.diansh.mapper.HomeShopMapper;
import org.kunze.diansh.service.IHomeShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
@Service
public class HomeShopServiceImpl extends ServiceImpl<HomeShopMapper, HomeShop> implements IHomeShopService {
@Autowired
private HomeShopMapper homeShopMapper;
/**
* 超市查询分类专区
*
* @param shopId
* @param homegName
* @return
*/
@Override
public PageInfo<HomeShopVo> queryHomeShop(String shopId, String homegName,Integer pageNo,Integer pageSize) {
Page page = PageHelper.startPage(pageNo,pageSize);
if(StringUtils.isEmpty(shopId)){
return null;
}
HomeShop homeShop = new HomeShop();
homeShop.setShopId(shopId);
List<HomeShopVo> homeShopVoList = homeShopMapper.queryHomeShop(homeShop,homegName);
PageInfo<HomeShopVo> pageInfo = new PageInfo<HomeShopVo>(homeShopVoList);
pageInfo.setTotal(page.getTotal());
return pageInfo;
}
/**
* 超市添加分类专区
*
* @param homeShop
* @return
*/
@Override
public Boolean saveHomeShop(HomeShop homeShop) {
Boolean isFlag = false;
homeShop.setId(UUID.randomUUID().toString().replace("-",""));
int result = homeShopMapper.saveHomeShop(homeShop);
if(result>0){
isFlag = true;
}
return isFlag;
}
/**
* 超市修改分类专区
*
* @param homeShop
* @return
*/
@Override
public Boolean editHomeShop(HomeShop homeShop) {
Boolean isFlag = false;
if(!StringUtils.isEmpty(homeShop.getId())){
int result = homeShopMapper.editHomeShop(homeShop);
if(result>0){
isFlag = true;
}
}
return isFlag;
}
/**
* 超市删除分类专区
*
* @param ids
* @return
*/
@Override
public Boolean delHomeShop(String ids) {
Boolean isFlag = false;
if(ids != null && !ids.equals("")){
char a = ids.charAt(ids.length()-1);
if(a == ','){
ids = ids.substring(0,ids.length()-1);
}
if(ids == null || ids.equals("")){
return false;
}
List<String> stringList = new ArrayList<String>();
if(ids.contains(",")){
stringList = new ArrayList<String>(Arrays.asList(ids.split(",")));
}else {
stringList.add(ids);
}
int result = homeShopMapper.delHomeShop(stringList);
if(result>0){
isFlag = true;
}
}
return isFlag;
}
/**
* 检索当前超市下是否存在相同的专区
*
* @param homePageId
* @param shopId
* @return
*/
@Override
public Boolean queryNotHomeShop(String homePageId, String shopId) {
Boolean isFlag = false;
int result = homeShopMapper.queryNotHomeShop(homePageId,shopId);
if(result>0){
isFlag = true;
}
return isFlag;
}
/**
* 前台获取首页菜单数据
* @param shopId
* @return
*/
public List<Map<String,Object>> qryHomeMenu(String shopId){
return homeShopMapper.qryHomeMenu(shopId);
}
}
| 27.273381 | 112 | 0.598523 |
864042c6074b5d9f49332f3926be093bf4ccd52d | 807 | /*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.link.process;
import org.dspace.app.rest.RestResourceController;
import org.dspace.app.rest.link.HalLinkFactory;
/**
* This abstract class offers an easily extendable HalLinkFactory class to use methods on the RestResourceController
* and make it more easy to read or define which methods should be found in the getMethodOn methods when building links
* @param <T> This parameter should be of type {@link org.dspace.app.rest.model.hateoas.HALResource}
*/
public abstract class ProcessHalLinkFactory<T> extends HalLinkFactory<T, RestResourceController> {
} | 42.473684 | 119 | 0.780669 |
8aeaca9793e6185f77ff5cb56bd78f6de0e0657a | 1,292 | package org.mage.test.cards.continuous;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* @author magenoxx_at_gmail.com
*/
public class EvernightShadeTest extends CardTestPlayerBase {
/**
* Tests boost disappeared after creature died
*/
@Test
public void testBoostWithUndying() {
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 3);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1);
// Evernight Shade Creature - Shade 1/1 {3}{B}
// {B}: Evernight Shade gets +1/+1 until end of turn.
// Undying (When this creature dies, if it had no +1/+1 counters on it, return it to the battlefield under its owner's control with a +1/+1 counter on it.)
addCard(Zone.BATTLEFIELD, playerA, "Evernight Shade");
addCard(Zone.HAND, playerA, "Lightning Bolt");
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{B}");
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{B}");
castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, "Lightning Bolt", "Evernight Shade");
setStopAt(1, PhaseStep.END_TURN);
execute();
assertPowerToughness(playerA, "Evernight Shade", 2, 2);
}
}
| 34.918919 | 163 | 0.674923 |
9338ae128083fa90ba903cb7e13681be23b5441b | 301 | package novemberizing.rx;
/**
*
* @author novemberizing, me@novemberizing.net
* @since 2017. 1. 17.
*/
public interface Observer<T> {
Scheduler observeOn();
void onNext(T o);
void onError(Throwable e);
void onComplete();
void subscribe(boolean v);
boolean subscribed();
}
| 18.8125 | 46 | 0.657807 |
d2f1d597a01b2a036167aa44e49019529448c6a1 | 3,464 | package org.apache.lucene.search.grouping.function;
/*
* 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.
*/
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.grouping.AbstractSecondPassGroupingCollector;
import org.apache.lucene.search.grouping.SearchGroup;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.search.grouping.TopGroups; //javadoc
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
* Concrete implementation of {@link AbstractSecondPassGroupingCollector} that groups based on
* {@link ValueSource} instances.
*
* @lucene.experimental
*/
public class FunctionSecondPassGroupingCollector extends AbstractSecondPassGroupingCollector<MutableValue> {
private final ValueSource groupByVS;
private final Map<?, ?> vsContext;
private FunctionValues.ValueFiller filler;
private MutableValue mval;
/**
* Constructs a {@link FunctionSecondPassGroupingCollector} instance.
*
* @param searchGroups The {@link SearchGroup} instances collected during the first phase.
* @param groupSort The group sort
* @param withinGroupSort The sort inside a group
* @param maxDocsPerGroup The maximum number of documents to collect inside a group
* @param getScores Whether to include the scores
* @param getMaxScores Whether to include the maximum score
* @param fillSortFields Whether to fill the sort values in {@link TopGroups#withinGroupSort}
* @param groupByVS The {@link ValueSource} to group by
* @param vsContext The value source context
* @throws IOException IOException When I/O related errors occur
*/
public FunctionSecondPassGroupingCollector(Collection<SearchGroup<MutableValue>> searchGroups, Sort groupSort, Sort withinGroupSort, int maxDocsPerGroup, boolean getScores, boolean getMaxScores, boolean fillSortFields, ValueSource groupByVS, Map<?, ?> vsContext) throws IOException {
super(searchGroups, groupSort, withinGroupSort, maxDocsPerGroup, getScores, getMaxScores, fillSortFields);
this.groupByVS = groupByVS;
this.vsContext = vsContext;
}
@Override
protected SearchGroupDocs<MutableValue> retrieveGroup(int doc) throws IOException {
filler.fillValue(doc);
return groupMap.get(mval);
}
@Override
public void setNextReader(AtomicReaderContext readerContext) throws IOException {
super.setNextReader(readerContext);
FunctionValues values = groupByVS.getValues(vsContext, readerContext);
filler = values.getValueFiller();
mval = filler.getValue();
}
}
| 42.243902 | 285 | 0.779734 |
717d21e33e8b26c2f1e175dc93e03106c0072720 | 19,426 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.facebook.share.model;
import android.net.Uri;
import android.os.Parcel;
// Referenced classes of package com.facebook.share.model:
// ShareMessengerActionButton, ShareModel, ShareModelBuilder
public final class ShareMessengerURLActionButton extends ShareMessengerActionButton
{
public static final class Builder extends ShareMessengerActionButton.Builder
{
public ShareMessengerURLActionButton build()
{
return new ShareMessengerURLActionButton(this);
// 0 0:new #7 <Class ShareMessengerURLActionButton>
// 1 3:dup
// 2 4:aload_0
// 3 5:aconst_null
// 4 6:invokespecial #44 <Method void ShareMessengerURLActionButton(ShareMessengerURLActionButton$Builder, ShareMessengerURLActionButton$1)>
// 5 9:areturn
}
public volatile Object build()
{
return ((Object) (build()));
// 0 0:aload_0
// 1 1:invokevirtual #47 <Method ShareMessengerURLActionButton build()>
// 2 4:areturn
}
public volatile ShareMessengerActionButton.Builder readFrom(ShareMessengerActionButton sharemessengeractionbutton)
{
return ((ShareMessengerActionButton.Builder) (readFrom((ShareMessengerURLActionButton)sharemessengeractionbutton)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:checkcast #7 <Class ShareMessengerURLActionButton>
// 3 5:invokevirtual #52 <Method ShareMessengerURLActionButton$Builder readFrom(ShareMessengerURLActionButton)>
// 4 8:areturn
}
public Builder readFrom(ShareMessengerURLActionButton sharemessengerurlactionbutton)
{
if(sharemessengerurlactionbutton == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 6
return this;
// 2 4:aload_0
// 3 5:areturn
else
return setUrl(sharemessengerurlactionbutton.getUrl()).setIsMessengerExtensionURL(sharemessengerurlactionbutton.getIsMessengerExtensionURL()).setFallbackUrl(sharemessengerurlactionbutton.getFallbackUrl()).setWebviewHeightRatio(sharemessengerurlactionbutton.getWebviewHeightRatio()).setShouldHideWebviewShareButton(sharemessengerurlactionbutton.getShouldHideWebviewShareButton());
// 4 6:aload_0
// 5 7:aload_1
// 6 8:invokevirtual #56 <Method Uri ShareMessengerURLActionButton.getUrl()>
// 7 11:invokevirtual #60 <Method ShareMessengerURLActionButton$Builder setUrl(Uri)>
// 8 14:aload_1
// 9 15:invokevirtual #64 <Method boolean ShareMessengerURLActionButton.getIsMessengerExtensionURL()>
// 10 18:invokevirtual #68 <Method ShareMessengerURLActionButton$Builder setIsMessengerExtensionURL(boolean)>
// 11 21:aload_1
// 12 22:invokevirtual #71 <Method Uri ShareMessengerURLActionButton.getFallbackUrl()>
// 13 25:invokevirtual #74 <Method ShareMessengerURLActionButton$Builder setFallbackUrl(Uri)>
// 14 28:aload_1
// 15 29:invokevirtual #78 <Method ShareMessengerURLActionButton$WebviewHeightRatio ShareMessengerURLActionButton.getWebviewHeightRatio()>
// 16 32:invokevirtual #82 <Method ShareMessengerURLActionButton$Builder setWebviewHeightRatio(ShareMessengerURLActionButton$WebviewHeightRatio)>
// 17 35:aload_1
// 18 36:invokevirtual #85 <Method boolean ShareMessengerURLActionButton.getShouldHideWebviewShareButton()>
// 19 39:invokevirtual #88 <Method ShareMessengerURLActionButton$Builder setShouldHideWebviewShareButton(boolean)>
// 20 42:areturn
}
public volatile ShareModelBuilder readFrom(ShareModel sharemodel)
{
return ((ShareModelBuilder) (readFrom((ShareMessengerURLActionButton)sharemodel)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:checkcast #7 <Class ShareMessengerURLActionButton>
// 3 5:invokevirtual #52 <Method ShareMessengerURLActionButton$Builder readFrom(ShareMessengerURLActionButton)>
// 4 8:areturn
}
public Builder setFallbackUrl(Uri uri)
{
fallbackUrl = uri;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #32 <Field Uri fallbackUrl>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public Builder setIsMessengerExtensionURL(boolean flag)
{
isMessengerExtensionURL = flag;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #29 <Field boolean isMessengerExtensionURL>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public Builder setShouldHideWebviewShareButton(boolean flag)
{
shouldHideWebviewShareButton = flag;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #39 <Field boolean shouldHideWebviewShareButton>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public Builder setUrl(Uri uri)
{
url = uri;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #25 <Field Uri url>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public Builder setWebviewHeightRatio(WebviewHeightRatio webviewheightratio)
{
webviewHeightRatio = webviewheightratio;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #36 <Field ShareMessengerURLActionButton$WebviewHeightRatio webviewHeightRatio>
return this;
// 3 5:aload_0
// 4 6:areturn
}
private Uri fallbackUrl;
private boolean isMessengerExtensionURL;
private boolean shouldHideWebviewShareButton;
private Uri url;
private WebviewHeightRatio webviewHeightRatio;
/*
static Uri access$000(Builder builder)
{
return builder.url;
// 0 0:aload_0
// 1 1:getfield #25 <Field Uri url>
// 2 4:areturn
}
*/
/*
static boolean access$100(Builder builder)
{
return builder.isMessengerExtensionURL;
// 0 0:aload_0
// 1 1:getfield #29 <Field boolean isMessengerExtensionURL>
// 2 4:ireturn
}
*/
/*
static Uri access$200(Builder builder)
{
return builder.fallbackUrl;
// 0 0:aload_0
// 1 1:getfield #32 <Field Uri fallbackUrl>
// 2 4:areturn
}
*/
/*
static WebviewHeightRatio access$300(Builder builder)
{
return builder.webviewHeightRatio;
// 0 0:aload_0
// 1 1:getfield #36 <Field ShareMessengerURLActionButton$WebviewHeightRatio webviewHeightRatio>
// 2 4:areturn
}
*/
/*
static boolean access$400(Builder builder)
{
return builder.shouldHideWebviewShareButton;
// 0 0:aload_0
// 1 1:getfield #39 <Field boolean shouldHideWebviewShareButton>
// 2 4:ireturn
}
*/
public Builder()
{
// 0 0:aload_0
// 1 1:invokespecial #20 <Method void ShareMessengerActionButton$Builder()>
// 2 4:return
}
}
public static final class WebviewHeightRatio extends Enum
{
public static WebviewHeightRatio valueOf(String s)
{
return (WebviewHeightRatio)Enum.valueOf(com/facebook/share/model/ShareMessengerURLActionButton$WebviewHeightRatio, s);
// 0 0:ldc1 #2 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 1 2:aload_0
// 2 3:invokestatic #39 <Method Enum Enum.valueOf(Class, String)>
// 3 6:checkcast #2 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 4 9:areturn
}
public static WebviewHeightRatio[] values()
{
return (WebviewHeightRatio[])((WebviewHeightRatio []) ($VALUES)).clone();
// 0 0:getstatic #31 <Field ShareMessengerURLActionButton$WebviewHeightRatio[] $VALUES>
// 1 3:invokevirtual #46 <Method Object _5B_Lcom.facebook.share.model.ShareMessengerURLActionButton$WebviewHeightRatio_3B_.clone()>
// 2 6:checkcast #42 <Class ShareMessengerURLActionButton$WebviewHeightRatio[]>
// 3 9:areturn
}
private static final WebviewHeightRatio $VALUES[];
public static final WebviewHeightRatio WebviewHeightRatioCompact;
public static final WebviewHeightRatio WebviewHeightRatioFull;
public static final WebviewHeightRatio WebviewHeightRatioTall;
static
{
WebviewHeightRatioFull = new WebviewHeightRatio("WebviewHeightRatioFull", 0);
// 0 0:new #2 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 1 3:dup
// 2 4:ldc1 #17 <String "WebviewHeightRatioFull">
// 3 6:iconst_0
// 4 7:invokespecial #21 <Method void ShareMessengerURLActionButton$WebviewHeightRatio(String, int)>
// 5 10:putstatic #23 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioFull>
WebviewHeightRatioTall = new WebviewHeightRatio("WebviewHeightRatioTall", 1);
// 6 13:new #2 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 7 16:dup
// 8 17:ldc1 #24 <String "WebviewHeightRatioTall">
// 9 19:iconst_1
// 10 20:invokespecial #21 <Method void ShareMessengerURLActionButton$WebviewHeightRatio(String, int)>
// 11 23:putstatic #26 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioTall>
WebviewHeightRatioCompact = new WebviewHeightRatio("WebviewHeightRatioCompact", 2);
// 12 26:new #2 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 13 29:dup
// 14 30:ldc1 #27 <String "WebviewHeightRatioCompact">
// 15 32:iconst_2
// 16 33:invokespecial #21 <Method void ShareMessengerURLActionButton$WebviewHeightRatio(String, int)>
// 17 36:putstatic #29 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioCompact>
$VALUES = (new WebviewHeightRatio[] {
WebviewHeightRatioFull, WebviewHeightRatioTall, WebviewHeightRatioCompact
});
// 18 39:iconst_3
// 19 40:anewarray WebviewHeightRatio[]
// 20 43:dup
// 21 44:iconst_0
// 22 45:getstatic #23 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioFull>
// 23 48:aastore
// 24 49:dup
// 25 50:iconst_1
// 26 51:getstatic #26 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioTall>
// 27 54:aastore
// 28 55:dup
// 29 56:iconst_2
// 30 57:getstatic #29 <Field ShareMessengerURLActionButton$WebviewHeightRatio WebviewHeightRatioCompact>
// 31 60:aastore
// 32 61:putstatic #31 <Field ShareMessengerURLActionButton$WebviewHeightRatio[] $VALUES>
//* 33 64:return
}
private WebviewHeightRatio(String s, int i)
{
super(s, i);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:iload_2
// 3 3:invokespecial #33 <Method void Enum(String, int)>
// 4 6:return
}
}
ShareMessengerURLActionButton(Parcel parcel)
{
super(parcel);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #34 <Method void ShareMessengerActionButton(Parcel)>
url = (Uri)parcel.readParcelable(((Class) (android/net/Uri)).getClassLoader());
// 3 5:aload_0
// 4 6:aload_1
// 5 7:ldc1 #36 <Class Uri>
// 6 9:invokevirtual #42 <Method ClassLoader Class.getClassLoader()>
// 7 12:invokevirtual #48 <Method android.os.Parcelable Parcel.readParcelable(ClassLoader)>
// 8 15:checkcast #36 <Class Uri>
// 9 18:putfield #50 <Field Uri url>
byte byte0 = parcel.readByte();
// 10 21:aload_1
// 11 22:invokevirtual #54 <Method byte Parcel.readByte()>
// 12 25:istore_2
boolean flag1 = true;
// 13 26:iconst_1
// 14 27:istore 4
boolean flag;
if(byte0 != 0)
//* 15 29:iload_2
//* 16 30:ifeq 38
flag = true;
// 17 33:iconst_1
// 18 34:istore_3
else
//* 19 35:goto 40
flag = false;
// 20 38:iconst_0
// 21 39:istore_3
isMessengerExtensionURL = flag;
// 22 40:aload_0
// 23 41:iload_3
// 24 42:putfield #56 <Field boolean isMessengerExtensionURL>
fallbackUrl = (Uri)parcel.readParcelable(((Class) (android/net/Uri)).getClassLoader());
// 25 45:aload_0
// 26 46:aload_1
// 27 47:ldc1 #36 <Class Uri>
// 28 49:invokevirtual #42 <Method ClassLoader Class.getClassLoader()>
// 29 52:invokevirtual #48 <Method android.os.Parcelable Parcel.readParcelable(ClassLoader)>
// 30 55:checkcast #36 <Class Uri>
// 31 58:putfield #58 <Field Uri fallbackUrl>
webviewHeightRatio = (WebviewHeightRatio)parcel.readSerializable();
// 32 61:aload_0
// 33 62:aload_1
// 34 63:invokevirtual #62 <Method java.io.Serializable Parcel.readSerializable()>
// 35 66:checkcast #11 <Class ShareMessengerURLActionButton$WebviewHeightRatio>
// 36 69:putfield #64 <Field ShareMessengerURLActionButton$WebviewHeightRatio webviewHeightRatio>
if(parcel.readByte() != 0)
//* 37 72:aload_1
//* 38 73:invokevirtual #54 <Method byte Parcel.readByte()>
//* 39 76:ifeq 85
flag = flag1;
// 40 79:iload 4
// 41 81:istore_3
else
//* 42 82:goto 87
flag = false;
// 43 85:iconst_0
// 44 86:istore_3
shouldHideWebviewShareButton = flag;
// 45 87:aload_0
// 46 88:iload_3
// 47 89:putfield #66 <Field boolean shouldHideWebviewShareButton>
// 48 92:return
}
private ShareMessengerURLActionButton(Builder builder)
{
super(((ShareMessengerActionButton.Builder) (builder)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #70 <Method void ShareMessengerActionButton(ShareMessengerActionButton$Builder)>
url = builder.url;
// 3 5:aload_0
// 4 6:aload_1
// 5 7:invokestatic #74 <Method Uri ShareMessengerURLActionButton$Builder.access$000(ShareMessengerURLActionButton$Builder)>
// 6 10:putfield #50 <Field Uri url>
isMessengerExtensionURL = builder.isMessengerExtensionURL;
// 7 13:aload_0
// 8 14:aload_1
// 9 15:invokestatic #78 <Method boolean ShareMessengerURLActionButton$Builder.access$100(ShareMessengerURLActionButton$Builder)>
// 10 18:putfield #56 <Field boolean isMessengerExtensionURL>
fallbackUrl = builder.fallbackUrl;
// 11 21:aload_0
// 12 22:aload_1
// 13 23:invokestatic #81 <Method Uri ShareMessengerURLActionButton$Builder.access$200(ShareMessengerURLActionButton$Builder)>
// 14 26:putfield #58 <Field Uri fallbackUrl>
webviewHeightRatio = builder.webviewHeightRatio;
// 15 29:aload_0
// 16 30:aload_1
// 17 31:invokestatic #85 <Method ShareMessengerURLActionButton$WebviewHeightRatio ShareMessengerURLActionButton$Builder.access$300(ShareMessengerURLActionButton$Builder)>
// 18 34:putfield #64 <Field ShareMessengerURLActionButton$WebviewHeightRatio webviewHeightRatio>
shouldHideWebviewShareButton = builder.shouldHideWebviewShareButton;
// 19 37:aload_0
// 20 38:aload_1
// 21 39:invokestatic #88 <Method boolean ShareMessengerURLActionButton$Builder.access$400(ShareMessengerURLActionButton$Builder)>
// 22 42:putfield #66 <Field boolean shouldHideWebviewShareButton>
// 23 45:return
}
public Uri getFallbackUrl()
{
return fallbackUrl;
// 0 0:aload_0
// 1 1:getfield #58 <Field Uri fallbackUrl>
// 2 4:areturn
}
public boolean getIsMessengerExtensionURL()
{
return isMessengerExtensionURL;
// 0 0:aload_0
// 1 1:getfield #56 <Field boolean isMessengerExtensionURL>
// 2 4:ireturn
}
public boolean getShouldHideWebviewShareButton()
{
return shouldHideWebviewShareButton;
// 0 0:aload_0
// 1 1:getfield #66 <Field boolean shouldHideWebviewShareButton>
// 2 4:ireturn
}
public Uri getUrl()
{
return url;
// 0 0:aload_0
// 1 1:getfield #50 <Field Uri url>
// 2 4:areturn
}
public WebviewHeightRatio getWebviewHeightRatio()
{
return webviewHeightRatio;
// 0 0:aload_0
// 1 1:getfield #64 <Field ShareMessengerURLActionButton$WebviewHeightRatio webviewHeightRatio>
// 2 4:areturn
}
public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() {
public ShareMessengerURLActionButton createFromParcel(Parcel parcel)
{
return new ShareMessengerURLActionButton(parcel);
// 0 0:new #9 <Class ShareMessengerURLActionButton>
// 1 3:dup
// 2 4:aload_1
// 3 5:invokespecial #19 <Method void ShareMessengerURLActionButton(Parcel)>
// 4 8:areturn
}
public volatile Object createFromParcel(Parcel parcel)
{
return ((Object) (createFromParcel(parcel)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokevirtual #22 <Method ShareMessengerURLActionButton createFromParcel(Parcel)>
// 3 5:areturn
}
public ShareMessengerURLActionButton[] newArray(int i)
{
return new ShareMessengerURLActionButton[i];
// 0 0:iload_1
// 1 1:anewarray ShareMessengerURLActionButton[]
// 2 4:areturn
}
public volatile Object[] newArray(int i)
{
return ((Object []) (newArray(i)));
// 0 0:aload_0
// 1 1:iload_1
// 2 2:invokevirtual #27 <Method ShareMessengerURLActionButton[] newArray(int)>
// 3 5:areturn
}
}
;
private final Uri fallbackUrl;
private final boolean isMessengerExtensionURL;
private final boolean shouldHideWebviewShareButton;
private final Uri url;
private final WebviewHeightRatio webviewHeightRatio;
static
{
// 0 0:new #6 <Class ShareMessengerURLActionButton$1>
// 1 3:dup
// 2 4:invokespecial #28 <Method void ShareMessengerURLActionButton$1()>
// 3 7:putstatic #30 <Field android.os.Parcelable$Creator CREATOR>
//* 4 10:return
}
}
| 39.008032 | 382 | 0.623958 |
4cb580c4f9db97f3b49f9df808041fc1d736b871 | 3,080 | /*
* (C) Copyright 2017 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.storage.dbs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
public class TestDBSInvalidations {
@Test
public void testSerialization() throws IOException {
DBSInvalidations invals;
@SuppressWarnings("resource")
ByteArrayOutputStream baout = new ByteArrayOutputStream();
String ser;
invals = new DBSInvalidations();
invals.serialize(baout);
ser = new String(baout.toByteArray());
assertEquals("", ser);
invals = new DBSInvalidations();
invals.add("foo");
baout.reset();
invals.serialize(baout);
ser = new String(baout.toByteArray());
assertEquals(",foo", ser);
invals.add("bar");
baout.reset();
invals.serialize(baout);
ser = new String(baout.toByteArray());
assertTrue(ser, Arrays.asList(",foo,bar", ",bar,foo").contains(ser)); // non-deterministic order
invals = new DBSInvalidations();
invals.setAll();
baout.reset();
invals.serialize(baout);
ser = new String(baout.toByteArray());
assertEquals("A", ser);
}
@Test
public void testDeserialization() throws IOException {
DBSInvalidations invals;
ByteArrayInputStream bain;
bain = new ByteArrayInputStream("".getBytes());
invals = DBSInvalidations.deserialize(bain);
assertNull(invals);
bain = new ByteArrayInputStream("x".getBytes());
invals = DBSInvalidations.deserialize(bain);
assertNull(invals);
bain = new ByteArrayInputStream("A".getBytes());
invals = DBSInvalidations.deserialize(bain);
assertTrue(invals.all);
bain = new ByteArrayInputStream(",foo".getBytes());
invals = DBSInvalidations.deserialize(bain);
assertEquals(Collections.singleton("foo"), invals.ids);
bain = new ByteArrayInputStream(",foo,bar".getBytes());
invals = DBSInvalidations.deserialize(bain);
assertEquals(new HashSet<>(Arrays.asList("foo", "bar")), invals.ids);
}
}
| 32.083333 | 104 | 0.669481 |
4911fee32a11ad3ce8603fb013c74fb0cb22be9e | 1,862 | package com.zjp.mine.activity;
import android.content.Context;
import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.zjp.base.activity.BaseActivity;
import com.zjp.common.ui.WebViewActivity;
import com.zjp.mine.R;
import com.zjp.mine.adapter.OpenSourceProjAdapter;
import com.zjp.mine.bean.OpenSourceProj;
import com.zjp.mine.databinding.ActivityOpensourceProjBinding;
import com.zjp.mine.util.DataUtils;
import com.zjp.mine.viewmodel.MineViewModel;
/**
* Created by zjp on 2020/7/14 22:44.
*/
public class OpenSourceProjActivity extends BaseActivity<ActivityOpensourceProjBinding, MineViewModel> {
private OpenSourceProjAdapter openSourceProjAdapter;
public static void start(Context context) {
context.startActivity(new Intent(context, OpenSourceProjActivity.class));
}
@Override
protected void initImmersionBar() {
super.initImmersionBar();
mImmersionBar
.statusBarDarkFont(true)
.init();
}
@Override
protected int getLayoutId() {
return R.layout.activity_opensource_proj;
}
@Override
protected void initView() {
super.initView();
mViewDataBinding.titleview.setTitle("开源项目");
mViewDataBinding.recy.setLayoutManager(new LinearLayoutManager(this));
mViewDataBinding.recy.setAdapter(openSourceProjAdapter = new OpenSourceProjAdapter());
openSourceProjAdapter.setList(DataUtils.getData());
openSourceProjAdapter.setOnItemClickListener((adapter, view, position) -> {
OpenSourceProj openSourceProj = openSourceProjAdapter.getItem(position);
if (openSourceProj != null) {
WebViewActivity.start(OpenSourceProjActivity.this, openSourceProj.getAuthor(), openSourceProj.getLink());
}
});
}
}
| 32.103448 | 121 | 0.721805 |
46cfe3361c24edf94950caa2a47ed3e1ef8c4fe3 | 1,499 | package site.hearen.thread.dump.analyzer.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import site.hearen.thread.dump.analyzer.entity.ThreadDo;
import site.hearen.thread.dump.analyzer.dao.ThreadDoRepository;
import site.hearen.thread.dump.analyzer.enums.StateEnum;
@Service
@Slf4j
public class ThreadInfoService {
@Autowired
private ThreadDoRepository threadDoRepository;
public ThreadDo getInfo(Long infoId) {
return threadDoRepository.getOne(infoId);
}
public List<ThreadDo> getStateInfoList(Long dumpId, String state) {
return threadDoRepository.findAllByDumpDo_IdAndStateEnum(dumpId, StateEnum.valueOf(state));
}
public List<ThreadDo> getGroupInfoList(Long dumpId, String groupName) {
return threadDoRepository.findAllByDumpDo_IdAndNameStartsWith(dumpId, groupName);
}
public List<ThreadDo> getDeamonOrNondaemon(Long dumpId, boolean isDaemon) {
return threadDoRepository.findAllByDumpDo_IdAndDaemon(dumpId, isDaemon);
}
public List<ThreadDo> getLockHolders(Long dumpId, String lock) {
List<ThreadDo> dos = threadDoRepository.findAllByDumpDoIdAndLocksHeldContains(dumpId, lock);
return dos;
}
public List<ThreadDo> getLockWaiters(Long dumpId, String lock) {
return threadDoRepository.findAllByDumpDoIdAndLocksWaitingContains(dumpId, lock);
}
}
| 34.068182 | 100 | 0.772515 |
900bd5b5178306a354dc07a60ae8b49fad38efe3 | 1,139 | package com.penghuang.springboot_mybatis.dao;
import com.penghuang.springboot_mybatis.entity.UserT;
import java.util.List;
public interface UserTMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_t
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_t
*
* @mbggenerated
*/
int insert(UserT record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_t
*
* @mbggenerated
*/
UserT selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_t
*
* @mbggenerated
*/
List<UserT> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_t
*
* @mbggenerated
*/
int updateByPrimaryKey(UserT record);
} | 24.76087 | 59 | 0.656716 |
04c7a6fcc7344b4093bfef6d310024af29e91e98 | 3,818 | package com.khayyamapp.juveiran.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.khayyamapp.juveiran.R;
import com.khayyamapp.juveiran.adapters.ArticleRvAdapter;
import com.khayyamapp.juveiran.api_service.ApiService;
import com.khayyamapp.juveiran.data_model.Article;
import com.khayyamapp.juveiran.database.ArticleDatabaseOpenHelper;
import com.khayyamapp.juveiran.globals.Globals;
import java.util.ArrayList;
import java.util.Collections;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ArticlesFragment extends Fragment {
RecyclerView rvArticles;
Context c;
ArrayList<Article> arrayList;
ArticleRvAdapter adapter;
SwipeRefreshLayout swipeRefreshLayout;
ArticleDatabaseOpenHelper databaseOpenHelper;
public ArticlesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_articles, container, false);
c = getContext();
databaseOpenHelper = new ArticleDatabaseOpenHelper(getContext());
rvArticles = v.findViewById(R.id.rv_Farticles_newsList);
swipeRefreshLayout = v.findViewById(R.id.srl_Farticles_swipeLayout);
loadApi();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadApi();
}
});
swipeRefreshLayout.setRefreshing(true);
loadApi();
return v;
}
private void loadApi() {
swipeRefreshLayout.setRefreshing(true);
ApiService.getApi().getArticles().enqueue(new Callback<ArrayList<Article>>() {
@Override
public void onResponse(Call<ArrayList<Article>> call, Response<ArrayList<Article>> response) {
if (response.isSuccessful() && response.body() != null) {
arrayList = response.body();
adapter = new ArticleRvAdapter(arrayList, c);
rvArticles.setAdapter(adapter);
rvArticles.setLayoutManager(new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false));
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
//insert data to database
//databaseOpenHelper.addPosts(response.body(), Globals.CATEGORY_ID_HOME);
}
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(Call<ArrayList<Article>> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(c, R.string.api_error_respons, Toast.LENGTH_SHORT).show();
}
});
}
//read data from sqlite
private void loadArticles() {
arrayList = databaseOpenHelper.getAllPosts(Globals.CATEGORY_ID_HOME);
adapter = new ArticleRvAdapter(arrayList, c);
Collections.reverse(arrayList);
rvArticles.setAdapter(adapter);
rvArticles.setLayoutManager(new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false));
adapter.notifyDataSetChanged();
}
}
| 34.089286 | 113 | 0.680199 |
9f8fde107ec89b437ab9870a452d05c0942dc030 | 5,665 | package net.fewald.jfeedreader;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.concurrent.Semaphore;
import java.util.logging.Logger;
/**
* Class to perform asynchronous requests and read the RSS/Atom feed
* One instance per feed.
*/
public class FeedReader implements Runnable {
/**
* The feed which is processed by this FeedReader instance.
*/
private Feed feed;
/**
* Logger
*/
private Logger logger;
/**
* The connection to the database.
*/
public IDatabaseConnector database;
private Semaphore semaphore;
private HashSet<String> stopWords;
public FeedReader(Feed feed, IDatabaseConnector database) {
this.feed = feed;
this.database = database;
// Initialize the logger.
logger = Logger.getLogger("FeedReader");
}
public FeedReader(Semaphore semaphore, Feed feed, IDatabaseConnector database, HashSet<String> stopWords) {
this(feed, database);
this.semaphore = semaphore;
this.stopWords = stopWords;
}
private void read() throws FeedReadException, ConnectionException {
Queue<Article> articles = new ArrayDeque<Article>();
HashSet<String> articleHeadlinesCurrentRunHashSet = new HashSet<String>();
SyndFeedInput input = new SyndFeedInput();
SyndFeed syndFeed = null;
try {
syndFeed = input.build(new XmlReader(this.feed.getUrl()));
}
catch (IOException exception) {
throw new FeedReadException(exception.getMessage());
}
catch (FeedException exception) {
throw new FeedReadException(exception.getMessage());
}
// Initialize headline formatter with stop words
HeadlineFormatter headlineFormatter = new HeadlineFormatter(this.stopWords);
for (SyndEntry entry : syndFeed.getEntries ()) {
// Convert the Date object to LocalDateTimeObject
LocalDateTime publishedDateTime = null;
if (entry.getPublishedDate() != null) {
publishedDateTime = entry.getPublishedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
else {
logger.severe("published data is missing, cannot add this entry to the list.");
continue;
}
// Create a new article object and set the values
Article article = new Article(entry.getTitle(), publishedDateTime);
// Copy over the feed name for later evaluation.
article.feedName = feed.getName();
if (article.getHeadlineOriginal() != null) {
String cleanedHeadline = headlineFormatter.getCleanString(article.getHeadlineOriginal());
article.setHeadline(cleanedHeadline);
}
article.author = entry.getAuthor();
if (entry.getUpdatedDate() != null) {
article.updatedDateTime = entry.getUpdatedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
// Try to build the url and write null otherwise after informing the user.
URL url = null;
try {
String link = entry.getLink();
if (link != null && link.length() > 0 && link.startsWith("http:")) {
url = new URL(entry.getLink());
}
}
catch (MalformedURLException exception) {
logger.info("Could not format URL for article " + article.getHeadlineOriginal());
}
article.url = url;
article.content = ContentFormatter.cleanHtml(entry.getDescription().getValue());
// Check, if the article is in the current list of articles already.
// If this is the case, don't add it to the database because this would
// be a duplicate.
if (!feed.getCurrentArticles().contains(article.getHeadline())) {
// Add the article to the queue, if it is not the latest one.
articles.add(article);
}
// Add the headline to the current processed headlines.
articleHeadlinesCurrentRunHashSet.add(article.getHeadline());
}
// Update the last update to now
feed.setLastUpdate(LocalDateTime.now());
// Remove all but the last element from the queue.
while (articles.size() > 0) {
Article a = articles.remove();
database.addArticle(a);
}
// Clean up the current articles
feed.setCurrentArticles(articleHeadlinesCurrentRunHashSet);
// Clear the temporary hash set
articleHeadlinesCurrentRunHashSet = null;
}
/**
* Fetches the feed in a different thread.
*/
public void run() {
// Run the fetch
try {
this.read();
} catch (FeedReadException e) {
logger.severe(e.getMessage());
e.printStackTrace();
} catch (ConnectionException e) {
logger.severe(e.getMessage());
e.printStackTrace();
}
finally {
// Release the semaphore
semaphore.release();
}
}
}
| 34.754601 | 126 | 0.614122 |
31795f7b01637126c53afb2fe874af3fe2fdb4c3 | 6,928 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.Post;
import com.microsoft.graph.models.extensions.SingleValueLegacyExtendedProperty;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseCollectionRequest;
import com.microsoft.graph.concurrency.IExecutors;
import com.microsoft.graph.requests.extensions.ISingleValueLegacyExtendedPropertyCollectionPage;
import com.microsoft.graph.requests.extensions.SingleValueLegacyExtendedPropertyCollectionResponse;
import com.microsoft.graph.requests.extensions.ISingleValueLegacyExtendedPropertyCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.ISingleValueLegacyExtendedPropertyCollectionRequest;
import com.microsoft.graph.requests.extensions.SingleValueLegacyExtendedPropertyCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Single Value Legacy Extended Property Collection Request.
*/
public class SingleValueLegacyExtendedPropertyCollectionRequest extends BaseCollectionRequest<SingleValueLegacyExtendedPropertyCollectionResponse, ISingleValueLegacyExtendedPropertyCollectionPage> implements ISingleValueLegacyExtendedPropertyCollectionRequest {
/**
* The request builder for this collection of SingleValueLegacyExtendedProperty
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public SingleValueLegacyExtendedPropertyCollectionRequest(final String requestUrl, IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, SingleValueLegacyExtendedPropertyCollectionResponse.class, ISingleValueLegacyExtendedPropertyCollectionPage.class);
}
public void get(final ICallback<ISingleValueLegacyExtendedPropertyCollectionPage> callback) {
final IExecutors executors = getBaseRequest().getClient().getExecutors();
executors.performOnBackground(new Runnable() {
@Override
public void run() {
try {
executors.performOnForeground(get(), callback);
} catch (final ClientException e) {
executors.performOnForeground(e, callback);
}
}
});
}
public ISingleValueLegacyExtendedPropertyCollectionPage get() throws ClientException {
final SingleValueLegacyExtendedPropertyCollectionResponse response = send();
return buildFromResponse(response);
}
public void post(final SingleValueLegacyExtendedProperty newSingleValueLegacyExtendedProperty, final ICallback<SingleValueLegacyExtendedProperty> callback) {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
new SingleValueLegacyExtendedPropertyRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.post(newSingleValueLegacyExtendedProperty, callback);
}
public SingleValueLegacyExtendedProperty post(final SingleValueLegacyExtendedProperty newSingleValueLegacyExtendedProperty) throws ClientException {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
return new SingleValueLegacyExtendedPropertyRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.post(newSingleValueLegacyExtendedProperty);
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
public ISingleValueLegacyExtendedPropertyCollectionRequest expand(final String value) {
addQueryOption(new com.microsoft.graph.options.QueryOption("$expand", value));
return (SingleValueLegacyExtendedPropertyCollectionRequest)this;
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
public ISingleValueLegacyExtendedPropertyCollectionRequest select(final String value) {
addQueryOption(new com.microsoft.graph.options.QueryOption("$select", value));
return (SingleValueLegacyExtendedPropertyCollectionRequest)this;
}
/**
* Sets the top value for the request
*
* @param value the max number of items to return
* @return the updated request
*/
public ISingleValueLegacyExtendedPropertyCollectionRequest top(final int value) {
addQueryOption(new com.microsoft.graph.options.QueryOption("$top", value + ""));
return (SingleValueLegacyExtendedPropertyCollectionRequest)this;
}
/**
* Sets the skip value for the request
*
* @param value of the number of items to skip
* @return the updated request
*/
public ISingleValueLegacyExtendedPropertyCollectionRequest skip(final int value) {
addQueryOption(new com.microsoft.graph.options.QueryOption("$skip", value + ""));
return (SingleValueLegacyExtendedPropertyCollectionRequest)this;
}
/**
* Add Skip token for pagination
* @param skipToken - Token for pagination
* @return the updated request
*/
public ISingleValueLegacyExtendedPropertyCollectionRequest skipToken(final String skipToken) {
addQueryOption(new QueryOption("$skiptoken", skipToken));
return (ISingleValueLegacyExtendedPropertyCollectionRequest)this;
}
public ISingleValueLegacyExtendedPropertyCollectionPage buildFromResponse(final SingleValueLegacyExtendedPropertyCollectionResponse response) {
final ISingleValueLegacyExtendedPropertyCollectionRequestBuilder builder;
if (response.nextLink != null) {
builder = new SingleValueLegacyExtendedPropertyCollectionRequestBuilder(response.nextLink, getBaseRequest().getClient(), /* options */ null);
} else {
builder = null;
}
final SingleValueLegacyExtendedPropertyCollectionPage page = new SingleValueLegacyExtendedPropertyCollectionPage(response, builder);
page.setRawObject(response.getSerializer(), response.getRawObject());
return page;
}
}
| 48.788732 | 261 | 0.736143 |
524f319b627a017aa3ba37e9adeb78f7c0efb50c | 4,536 | package com.thowv.javafxgridgameboard;
import java.io.Serializable;
import java.util.ArrayList;
public class GameBoardBehavior implements Serializable {
private GameBoard gameBoardControl;
private int gameBoardSize;
private GameBoardTile[][] gameBoardTiles;
public GameBoardBehavior(GameBoard gameBoardControl, int gameBoardSize) {
this.gameBoardControl = gameBoardControl;
this.gameBoardSize = gameBoardSize;
}
// region Behavior
public void resetGameBoardTiles() {
gameBoardTiles = gameBoardControl.getGameBoardSkin().createGameBoardTiles(gameBoardSize);
}
public void clearDecoratedGameBoardTiles() {
ArrayList<GameBoardTile> matchedGameBoardTiles = getGameBoardTilesByTypes(
new GameBoardTileType[] { GameBoardTileType.VISIBLE, GameBoardTileType.INTERACTABLE });
// Hide all type matched game board tiles
for (GameBoardTile gameBoardTile : matchedGameBoardTiles) {
gameBoardTile.setGameBoardTileType(GameBoardTileType.HIDDEN);
}
}
public int countTilesByType(GameBoardTileType gameBoardTileType) {
int tileCount = 0;
for (GameBoardTile[] gameBoardTilesX : gameBoardTiles) {
for (GameBoardTile gameBoardTile : gameBoardTilesX) {
if (gameBoardTile.getGameBoardTileType() == gameBoardTileType)
tileCount++;
}
}
return tileCount;
}
// endregion
// region Getters and setters
public int getGameBoardSize() {
return gameBoardSize;
}
public void copyGameBoardTiles(GameBoardTile[][] gameBoardTiles) {
for (GameBoardTile[] gameBoardTileArray : gameBoardTiles) {
for (GameBoardTile gameBoardTile : gameBoardTileArray) {
int xCord = gameBoardTile.getXCord();
int yCord = gameBoardTile.getYCord();
GameBoardTileType tileType = gameBoardTile.getGameBoardTileType();
this.gameBoardTiles[xCord][yCord].setGameBoardTileType(tileType);
}
}
}
public void copyGameBoardTiles(ArrayList<GameBoardTile> gameBoardTiles) {
for (GameBoardTile gameBoardTile : gameBoardTiles) {
int xCord = gameBoardTile.getXCord();
int yCord = gameBoardTile.getYCord();
GameBoardTileType tileType = gameBoardTile.getGameBoardTileType();
this.gameBoardTiles[xCord][yCord].setGameBoardTileType(tileType);
}
}
public void setGameBoardTileType(int xCord, int yCord, GameBoardTileType gameBoardTileType) {
gameBoardTiles[xCord][yCord].setGameBoardTileType(gameBoardTileType);
}
public void setGameBoardTileTypes(ArrayList<GameBoardTile> gameBoardTiles, GameBoardTileType forcedType) {
for (GameBoardTile gameBoardTile : gameBoardTiles) {
gameBoardTile.setGameBoardTileType(forcedType);
}
}
public GameBoardTile[][] getAllGameBoardTiles() {
return gameBoardTiles;
}
public GameBoardTile[][] getAllGameBoardTilesCopy() {
GameBoardTile[][] gameBoardTileCopies = new GameBoardTile[gameBoardSize][gameBoardSize];
for (int i = 0; i < gameBoardSize; i++) {
for (int j = 0; j < gameBoardSize; j++) {
gameBoardTileCopies[i][j] = new GameBoardTile(gameBoardTiles[i][j]);
}
}
return gameBoardTileCopies;
}
public void setGameBoardTiles(GameBoardTile[][] gameBoardTiles) {
this.gameBoardTiles = gameBoardTiles;
}
public GameBoardTile getGameBoardTile(int xCord, int yCord) {
return gameBoardTiles[xCord][yCord];
}
public ArrayList<GameBoardTile> getGameBoardTilesByType(GameBoardTileType gameBoardTileType) {
return getGameBoardTilesByTypes(new GameBoardTileType[] { gameBoardTileType });
}
public ArrayList<GameBoardTile> getGameBoardTilesByTypes(GameBoardTileType[] gameBoardTileTypes) {
ArrayList<GameBoardTile> typeMatchedBoardTiles = new ArrayList<>();
for (GameBoardTile[] gameBoardTilesX : gameBoardTiles) {
for (GameBoardTile gameBoardTile : gameBoardTilesX) {
for (GameBoardTileType gameBoardTileType : gameBoardTileTypes) {
if (gameBoardTile.getGameBoardTileType() == gameBoardTileType)
typeMatchedBoardTiles.add(gameBoardTile);
}
}
}
return typeMatchedBoardTiles;
}
// endregion
}
| 36 | 110 | 0.67306 |
63af3645c22601f0504b989f1cefbc8fa973f5c8 | 3,202 | package com.example.appmuseu;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.List;
import java.util.Locale;
public class Cafe extends AppCompatActivity implements OnSuccessListener<Location>, OnFailureListener {
public final static int LOCATION_CODE = 1;
TextView txtlocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafe);
txtlocation = findViewById(R.id.txtlocation);
if(ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_CODE);
Toast toast = Toast.makeText(this, "A permissão não foi concedida", Toast.LENGTH_SHORT);
toast.show();
} else {
final FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this);
fusedLocationProviderClient.getLastLocation().addOnFailureListener(this);
}
}
@Override
public void onFailure(@NonNull Exception e){
Log.e("Location not detected", "errors", e);}
@Override
public void onSuccess(Location location){
if(location != null){
double latitude1 = location.getLatitude();
double longitude1 = location.getLongitude();
Geocoder geocoder = new Geocoder(Cafe.this, Locale.getDefault());
try{
List<Address> locales = geocoder.getFromLocation(40.7844, -73.9582, 1);
if(locales.size() == 0){
return;
}
Address local = locales.get(0);
double latitude2 = local.getLatitude();
double longitude2 = local.getLongitude();
float[] results = new float[1];
Location.distanceBetween(latitude1, longitude1, latitude2, longitude2, results);
float results2 = results[0] / 1000;
txtlocation.setText(String.valueOf("Por mais que você esteja a " + results2 + " km de distância de nós. Por que não passar para tomar um cafezinho?"));
} catch (Exception e){
Log.e("Exception", "errors", e);
}
}
else{
txtlocation.setText(String.valueOf("Parece que alguém esta perdido 🙄"));
}
}
} | 39.530864 | 167 | 0.679575 |
c9849f16fe44b09e340596249841617a5f1c7851 | 1,537 | package _47b3n.yseldar.engine.game.entity;
import java.awt.Graphics;
import java.awt.Rectangle;
import _47b3n.yseldar.engine.gamestate.gamestates.InGame;
public abstract class Entity {
protected float velX = 0.0F;
protected float velY = 0.0F;
protected float width, height;
protected boolean falling = true;
protected boolean jumping = false;
protected int facing = 1;
protected float x;
protected float y;
protected EntityID id;
protected InGame inGame;
public Entity(float x, float y, EntityID id, InGame inGame) {
this.x = x;
this.y = y;
this.id = id;
this.inGame = inGame;
}
public abstract void tick();
public abstract void render(Graphics g);
public abstract Rectangle getBounds();
public boolean isFalling() {
return falling;
}
public void setFalling(boolean falling) {
this.falling = falling;
}
public boolean isJumping() {
return jumping;
}
public void setJumping(boolean jumping) {
this.jumping = jumping;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public float getVelX() {
return velX;
}
public float getVelY() {
return velY;
}
public void setVelX(float velX) {
this.velX = velX;
}
public void setVelY(float velY) {
this.velY = velY;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public int getFacing() {
return facing;
}
public EntityID getID() {
return id;
}
}
| 15.845361 | 62 | 0.686402 |
23454448680fbd4c847950d5fec126255eb9a693 | 272 | package javadoc.test010;
public class Test {
int val;
/**
* {@link java.util.Vector#Vector()}
* @param name {@link java.lang.String inline tag}
* @see Object {@link java.lang.String inline tag} leading comment
*/
public void gee(String name) {
}
}
| 18.133333 | 66 | 0.643382 |
a9198bae22264795c20066934fe537c860881d80 | 489 | package com.tct.positionApp.dao;
import com.tct.positionApp.domain.Parents;
import com.tct.positionApp.domain.Status;
import com.tct.positionApp.domain.Students;
import org.apache.ibatis.annotations.*;
@Mapper
public interface StatusDao {
@Select("SELECT * FROM status WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "statusName", column = "status_name"),
})
Status findStatusById(@Param("id") int id);
}
| 28.764706 | 69 | 0.678937 |
0cc25c06f1ab351b668699b48ff47948f799036e | 4,343 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.protocol.servlet5.arq514hack.descriptors.impl.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.arquillian.protocol.servlet5.arq514hack.descriptors.api.web.ServletDef;
import org.jboss.arquillian.protocol.servlet5.arq514hack.descriptors.api.web.ServletMappingDef;
import org.jboss.shrinkwrap.descriptor.spi.node.Node;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public class ServletDefImpl extends WebAppDescriptorImpl implements ServletDef {
private final Node servlet;
public ServletDefImpl(String descriptorName, Node webApp, Node servlet) {
super(descriptorName, webApp);
this.servlet = servlet;
}
@Override
public ServletDef name(String name) {
servlet.getOrCreate("servlet-name").text(name);
return this;
}
@Override
public ServletDef asyncSupported(boolean value) {
servlet.getOrCreate("async-supported").text(value);
return this;
}
@Override
public ServletDef initParam(String name, Object value) {
InitParamDefImpl param = new InitParamDefImpl(getDescriptorName(), getRootNode(), servlet);
param.initParam(name, value == null ? null : value.toString());
return this;
}
@Override
public ServletDef loadOnStartup(int order) {
servlet.getOrCreate("load-on-startup").text(order);
return this;
}
@Override
public ServletMappingDef mapping() {
Node mappingNode = getRootNode().createChild("servlet-mapping");
ServletMappingDef mapping = new ServletMappingDefImpl(getDescriptorName(), getRootNode(), servlet, mappingNode);
mapping.servletName(getName());
return mapping;
}
@Override
public ServletDef servletClass(Class<?> clazz) {
return servletClass(clazz.getName());
}
@Override
public ServletDef servletClass(String clazz) {
servlet.getOrCreate("servlet-class").text(clazz);
return this;
}
@Override
public String getServletClass() {
if (servlet.getSingle("servlet-class") != null) {
return servlet.getSingle("servlet-class").getText();
}
return null;
}
@Override
public String getName() {
return servlet.getTextValueForPatternName("servlet-name");
}
@Override
public String getInitParam(String name) {
Map<String, String> params = getInitParams();
for (Entry<String, String> e : params.entrySet()) {
if (e.getKey() != null && e.getKey().equals(name)) {
return e.getValue();
}
}
return null;
}
@Override
public Map<String, String> getInitParams() {
Map<String, String> result = new HashMap<String, String>();
List<Node> params = servlet.get("init-param");
for (Node node : params) {
result.put(node.getTextValueForPatternName("param-name"), node.getTextValueForPatternName("param-value"));
}
return result;
}
@Override
public boolean isAsyncSupported() {
return Strings.isTrue(servlet.getTextValueForPatternName("async-supported"));
}
@Override
public int getLoadOnStartup() throws NumberFormatException {
String tex = servlet.getTextValueForPatternName("load-on-startup");
return tex == null ? null : Integer.valueOf(tex);
}
public Node getNode() {
return servlet;
}
}
| 33.152672 | 120 | 0.677412 |
1e1b615d1b652548ce43d1afe402ab4ce820e71d | 6,144 | /*
Copyright (C) 2016 Migeran
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.moe.maven;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
/**
* @goal setupSDK
*/
public class SetupSDKTask extends GradleTask {
public static final String MOE_SDK_CORE_JAR = "moe.sdk.coreJar";
public static final String MOE_SDK_PLATFORM_JAR = "moe.sdk.platformJar";
public static final String MOE_SDK_JUNIT_JAR = "moe.sdk.junitJar";
public static final String MOE_SDK_JAVA8SUPPORT_JAR = "moe.sdk.java8support";
public static final String MOE_SDK_HOME = "moe.sdk.home";
/**
* Used to look up Artifacts in the remote repository.
*
* @parameter expression=
* "${component.org.apache.maven.artifact.factory.ArtifactFactory}"
* @required
* @readonly
*/
protected ArtifactFactory factory;
/**
* @parameter
*/
protected String moeSdkLocalbuild;
private String coreJarPath;
private String platformJarPath;
private String junitJarPath;
private String moeSDKPath;
@SuppressWarnings("unchecked")
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
super.execute();
if (project != null) {
Artifact moe_ios = factory.createArtifact("moe.sdk", MOE_SDK_PLATFORM_JAR, "1.0", "system", "jar");
moe_ios.setFile(new File(platformJarPath));
try {
artifactResolver.resolve(moe_ios, remoteRepositories, localRepository);
} catch (ArtifactResolutionException e) {
getLog().error(e);
} catch (ArtifactNotFoundException e) {
getLog().error(e);
}
Artifact moe_core = factory.createArtifact("moe.sdk", MOE_SDK_CORE_JAR, "1.0", "system", "jar");
moe_core.setFile(new File(coreJarPath));
try {
artifactResolver.resolve(moe_core, remoteRepositories, localRepository);
} catch (ArtifactResolutionException e) {
getLog().error(e);
} catch (ArtifactNotFoundException e) {
getLog().error(e);
}
Artifact moe_junit = factory.createArtifact("moe.sdk", MOE_SDK_JUNIT_JAR, "1.0", "system", "jar");
File junitJar = new File(junitJarPath);
moe_junit.setFile(junitJar);
MOESdk.setJunitJar(junitJar);
try {
artifactResolver.resolve(moe_junit, remoteRepositories, localRepository);
} catch (ArtifactResolutionException e) {
getLog().error(e);
} catch (ArtifactNotFoundException e) {
getLog().error(e);
}
Artifact moe_java8support = factory.createArtifact("moe.sdk", MOE_SDK_JAVA8SUPPORT_JAR, "1.0", "system", "jar");
String java8supportPath = moeSDKPath + File.separator + "tools" + File.separator + "java8support.jar";
File java8supportJAR = new File(java8supportPath);
moe_java8support.setFile(java8supportJAR);
try {
artifactResolver.resolve(moe_java8support, remoteRepositories, localRepository);
} catch (ArtifactResolutionException e) {
getLog().error(e);
} catch (ArtifactNotFoundException e) {
getLog().error(e);
}
Set<Artifact> projectDependencies = new HashSet<Artifact>();
projectDependencies.addAll(project.getDependencyArtifacts());
projectDependencies.add(moe_ios);
projectDependencies.add(moe_core);
projectDependencies.add(moe_junit);
projectDependencies.add(moe_java8support);
project.setDependencyArtifacts(projectDependencies);
} else {
getLog().error("PROJECT NULL");
}
}
@Override
protected String[] tasks() {
return new String[] { "moeSDKProperties" };
}
@Override
protected void readOutput(ByteArrayOutputStream baos) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith(MOE_SDK_PLATFORM_JAR)) {
platformJarPath = getValue(line);
} else if (line.startsWith(MOE_SDK_CORE_JAR)) {
coreJarPath = getValue(line);
} else if (line.startsWith(MOE_SDK_JUNIT_JAR)) {
junitJarPath = getValue(line);
} else if (line.startsWith(MOE_SDK_HOME)) {
moeSDKPath = getValue(line);
}
}
} catch (IOException e) {
getLog().error("Unable read SDK properties", e);
;
}
}
private String getValue(String line) {
String[] keyValue = line.split("=");
if (keyValue.length > 1) {
return keyValue[1];
}
return "";
}
}
| 34.711864 | 124 | 0.634603 |
9b12c2ada2e52b26c17b666add18f7af766e76a0 | 7,460 | package ru.geekbrains.homeworks.hw02.task1;
import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Slf4j
public class MainTest {
@Rule
public TestWatcher watchman = new TestWatcher() {
@Override
protected void starting(Description description) {
log.info("[ " + description + " ]");
}
@Override
protected void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("[ NOK ] failed!");
if (e != null) {
builder.append(' ').append(e);
}
log.info(builder.toString());
log.info("");
}
@Override
protected void succeeded(Description description) {
log.info("[ OK ] succeeded!");
log.info("");
}
};
@BeforeClass
public static void setUpBeforeClass() {
log.info("All unit tests were started...");
log.info("");
}
@AfterClass
public static void tearDownAfterClass() {
log.info("All unit tests were finished!\n");
}
/* ************************************************** ******* ************************************************* */
/* *************************************************** -TESTS- ************************************************** */
/* ************************************************** ******* ************************************************* */
/* checkIfSumBelongsToInterval */
@Test
public void when_BordersAreIncorrect_Expect_Exception() {
int a = 12, b = 122, leftBorder = 100, rightBorder = 1;
assertThatThrownBy(() -> {
log.info("Checking for exception:");
Main.checkIfSumBelongsToInterval(a, b, leftBorder, rightBorder);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Interval boundaries are incorrect!");
}
@Test
public void when_SumBelongsToInterval_Expect_True() {
int a = 12, b = 122, leftBorder = 1, rightBorder = 200;
String expectedResult = "true";
log.info("Checking that the sum belongs to the interval:");
assertThat(Main.checkIfSumBelongsToInterval(a, b, leftBorder, rightBorder)).isEqualTo(expectedResult);
}
@Test
public void when_SumNotBelongsToInterval_Expect_False() {
int a = 12, b = 122, leftBorder = 1, rightBorder = 100;
String expectedResult = "false";
log.info("Checking that the sum doesn't belong to the interval:");
assertThat(Main.checkIfSumBelongsToInterval(a, b, leftBorder, rightBorder)).isEqualTo(expectedResult);
}
/* checkNumberSign */
@Test
public void checkNumberSign_NumberSignPositive_Equal() {
int number = 12;
String expectedResult = "positive";
log.info("Checking for positive sign:");
assertThat(Main.checkNumberSign(number)).isEqualTo(expectedResult);
}
@Test
public void checkNumberSign_NumberSignNegative_Equal() {
int number = -12;
String expectedResult = "negative";
log.info("Checking for negative sign:");
assertThat(Main.checkNumberSign(number)).isEqualTo(expectedResult);
}
@Test
public void checkNumberSign_NumberSignAbsent_Equal() {
int number = 0;
String expectedResult = "zero";
log.info("Checking for zero:");
assertThat(Main.checkNumberSign(number)).isEqualTo(expectedResult);
}
/* isNumberNegative */
@Test
public void isNumberNegative_NumberSignNegative_Equal() {
int number = -10;
String expectedResult = "true";
log.info("Checking for negative:");
assertThat(Main.isNumberNegative(number)).isEqualTo(expectedResult);
}
@Test
public void isNumberNegative_NumberSignPositive_Equal() {
int number = 10;
String expectedResult = "false";
log.info("Checking for positive:");
assertThat(Main.isNumberNegative(number)).isEqualTo(expectedResult);
}
/* repeatNumberTimes */
@Test
public void when_NumberOfRepetitionsAreIncorrect_Expect_Exception() {
String str = "test";
int number = 0;
assertThatThrownBy(() -> {
log.info("Checking for exception:");
Main.repeatNumberTimes(str, number);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Number of repetitions is incorrect!");
}
@Test
public void repeatNumberTimes_Repeat4Times_Equal() {
String str = "Test";
int number = 4;
String expectedResult = "TestTestTestTest";
log.info("Checking for equality:");
assertThat(Main.repeatNumberTimes(str, number)).isEqualTo(expectedResult);
}
@Test
public void repeatNumberTimes_Repeat4Times_NotEqual() {
String str = "Test";
int number = 4;
String expectedResult = "TestTestTest";
log.info("Checking for equality:");
assertThat(Main.repeatNumberTimes(str, number)).isNotEqualTo(expectedResult);
}
/* isLeapYear */
@Test
public void when_YearIsIncorrect_Expect_Exception() {
int year = 0;
assertThatThrownBy(() -> {
log.info("Checking for exception:");
Main.isLeapYear(year);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Year is incorrect!");
}
@Test
public void isLeapYear_YearNotMultipleOf4_Equal() {
int year = 1;
String expectedResult = "не високосный";
log.info("Checking for a non-leap year:");
assertThat(Main.isLeapYear(year)).isEqualTo(expectedResult);
}
@Test
public void isLeapYear_YearMultipleOf4_Equal() {
int year = 2004;
String expectedResult = "високосный";
log.info("Checking for a leap year:");
assertThat(Main.isLeapYear(year)).isEqualTo(expectedResult);
}
@Test
public void isLeapYear_YearMultipleOf100_Equal() {
int year = 1900;
String expectedResult = "не високосный";
log.info("Checking for a non-leap year:");
assertThat(Main.isLeapYear(year)).isEqualTo(expectedResult);
}
@Test
public void isLeapYear_YearMultipleOf400_Equal() {
int year = 2000;
String expectedResult = "високосный";
log.info("Checking for a leap year:");
assertThat(Main.isLeapYear(year)).isEqualTo(expectedResult);
}
/* ************************************************** ******* ************************************************* */
/* *************************************************** /TESTS/ ************************************************** */
/* ************************************************** ******* ************************************************* */
}
| 32.719298 | 120 | 0.55 |
3766ad0c5fc779d5a1fdd63fa84183541fa19bb1 | 229 | package com.mwd.training.section1.lazy;
public class SecondBean {
public SecondBean() {
System.out.println("Inside SecondBean Constuctor");
}
public void test() {
System.out.println("Method of SecondBean Class");
}
}
| 17.615385 | 53 | 0.720524 |
5e05b2a05c63c705662dbb1241aca0c6cf9e5767 | 14,021 | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.groundstation;
import javax.annotation.Generated;
import com.amazonaws.services.groundstation.model.*;
/**
* Abstract implementation of {@code AWSGroundStationAsync}. Convenient method forms pass through to the corresponding
* overload that takes a request object and an {@code AsyncHandler}, which throws an
* {@code UnsupportedOperationException}.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAWSGroundStationAsync extends AbstractAWSGroundStation implements AWSGroundStationAsync {
protected AbstractAWSGroundStationAsync() {
}
@Override
public java.util.concurrent.Future<CancelContactResult> cancelContactAsync(CancelContactRequest request) {
return cancelContactAsync(request, null);
}
@Override
public java.util.concurrent.Future<CancelContactResult> cancelContactAsync(CancelContactRequest request,
com.amazonaws.handlers.AsyncHandler<CancelContactRequest, CancelContactResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateConfigResult> createConfigAsync(CreateConfigRequest request) {
return createConfigAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateConfigResult> createConfigAsync(CreateConfigRequest request,
com.amazonaws.handlers.AsyncHandler<CreateConfigRequest, CreateConfigResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateDataflowEndpointGroupResult> createDataflowEndpointGroupAsync(CreateDataflowEndpointGroupRequest request) {
return createDataflowEndpointGroupAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateDataflowEndpointGroupResult> createDataflowEndpointGroupAsync(CreateDataflowEndpointGroupRequest request,
com.amazonaws.handlers.AsyncHandler<CreateDataflowEndpointGroupRequest, CreateDataflowEndpointGroupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<CreateMissionProfileResult> createMissionProfileAsync(CreateMissionProfileRequest request) {
return createMissionProfileAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateMissionProfileResult> createMissionProfileAsync(CreateMissionProfileRequest request,
com.amazonaws.handlers.AsyncHandler<CreateMissionProfileRequest, CreateMissionProfileResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteConfigResult> deleteConfigAsync(DeleteConfigRequest request) {
return deleteConfigAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteConfigResult> deleteConfigAsync(DeleteConfigRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteConfigRequest, DeleteConfigResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteDataflowEndpointGroupResult> deleteDataflowEndpointGroupAsync(DeleteDataflowEndpointGroupRequest request) {
return deleteDataflowEndpointGroupAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteDataflowEndpointGroupResult> deleteDataflowEndpointGroupAsync(DeleteDataflowEndpointGroupRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteDataflowEndpointGroupRequest, DeleteDataflowEndpointGroupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DeleteMissionProfileResult> deleteMissionProfileAsync(DeleteMissionProfileRequest request) {
return deleteMissionProfileAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteMissionProfileResult> deleteMissionProfileAsync(DeleteMissionProfileRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteMissionProfileRequest, DeleteMissionProfileResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeContactResult> describeContactAsync(DescribeContactRequest request) {
return describeContactAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeContactResult> describeContactAsync(DescribeContactRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeContactRequest, DescribeContactResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetConfigResult> getConfigAsync(GetConfigRequest request) {
return getConfigAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetConfigResult> getConfigAsync(GetConfigRequest request,
com.amazonaws.handlers.AsyncHandler<GetConfigRequest, GetConfigResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetDataflowEndpointGroupResult> getDataflowEndpointGroupAsync(GetDataflowEndpointGroupRequest request) {
return getDataflowEndpointGroupAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetDataflowEndpointGroupResult> getDataflowEndpointGroupAsync(GetDataflowEndpointGroupRequest request,
com.amazonaws.handlers.AsyncHandler<GetDataflowEndpointGroupRequest, GetDataflowEndpointGroupResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetMinuteUsageResult> getMinuteUsageAsync(GetMinuteUsageRequest request) {
return getMinuteUsageAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetMinuteUsageResult> getMinuteUsageAsync(GetMinuteUsageRequest request,
com.amazonaws.handlers.AsyncHandler<GetMinuteUsageRequest, GetMinuteUsageResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetMissionProfileResult> getMissionProfileAsync(GetMissionProfileRequest request) {
return getMissionProfileAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetMissionProfileResult> getMissionProfileAsync(GetMissionProfileRequest request,
com.amazonaws.handlers.AsyncHandler<GetMissionProfileRequest, GetMissionProfileResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetSatelliteResult> getSatelliteAsync(GetSatelliteRequest request) {
return getSatelliteAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetSatelliteResult> getSatelliteAsync(GetSatelliteRequest request,
com.amazonaws.handlers.AsyncHandler<GetSatelliteRequest, GetSatelliteResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListConfigsResult> listConfigsAsync(ListConfigsRequest request) {
return listConfigsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListConfigsResult> listConfigsAsync(ListConfigsRequest request,
com.amazonaws.handlers.AsyncHandler<ListConfigsRequest, ListConfigsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListContactsResult> listContactsAsync(ListContactsRequest request) {
return listContactsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListContactsResult> listContactsAsync(ListContactsRequest request,
com.amazonaws.handlers.AsyncHandler<ListContactsRequest, ListContactsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListDataflowEndpointGroupsResult> listDataflowEndpointGroupsAsync(ListDataflowEndpointGroupsRequest request) {
return listDataflowEndpointGroupsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListDataflowEndpointGroupsResult> listDataflowEndpointGroupsAsync(ListDataflowEndpointGroupsRequest request,
com.amazonaws.handlers.AsyncHandler<ListDataflowEndpointGroupsRequest, ListDataflowEndpointGroupsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListGroundStationsResult> listGroundStationsAsync(ListGroundStationsRequest request) {
return listGroundStationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListGroundStationsResult> listGroundStationsAsync(ListGroundStationsRequest request,
com.amazonaws.handlers.AsyncHandler<ListGroundStationsRequest, ListGroundStationsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListMissionProfilesResult> listMissionProfilesAsync(ListMissionProfilesRequest request) {
return listMissionProfilesAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListMissionProfilesResult> listMissionProfilesAsync(ListMissionProfilesRequest request,
com.amazonaws.handlers.AsyncHandler<ListMissionProfilesRequest, ListMissionProfilesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListSatellitesResult> listSatellitesAsync(ListSatellitesRequest request) {
return listSatellitesAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListSatellitesResult> listSatellitesAsync(ListSatellitesRequest request,
com.amazonaws.handlers.AsyncHandler<ListSatellitesRequest, ListSatellitesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) {
return listTagsForResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request,
com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ReserveContactResult> reserveContactAsync(ReserveContactRequest request) {
return reserveContactAsync(request, null);
}
@Override
public java.util.concurrent.Future<ReserveContactResult> reserveContactAsync(ReserveContactRequest request,
com.amazonaws.handlers.AsyncHandler<ReserveContactRequest, ReserveContactResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) {
return tagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request,
com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) {
return untagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request,
com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateConfigResult> updateConfigAsync(UpdateConfigRequest request) {
return updateConfigAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateConfigResult> updateConfigAsync(UpdateConfigRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateConfigRequest, UpdateConfigResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<UpdateMissionProfileResult> updateMissionProfileAsync(UpdateMissionProfileRequest request) {
return updateMissionProfileAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateMissionProfileResult> updateMissionProfileAsync(UpdateMissionProfileRequest request,
com.amazonaws.handlers.AsyncHandler<UpdateMissionProfileRequest, UpdateMissionProfileResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
}
| 39.384831 | 152 | 0.77548 |
611098c498f28143411907cfb4b6f3e633c1e535 | 3,975 | /*
* Copyright 2015 Kevin Herron
*
* 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.digitalpetri.opcua.stack.core.types.structured;
import com.digitalpetri.opcua.stack.core.Identifiers;
import com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry;
import com.digitalpetri.opcua.stack.core.serialization.UaDecoder;
import com.digitalpetri.opcua.stack.core.serialization.UaEncoder;
import com.digitalpetri.opcua.stack.core.serialization.UaRequestMessage;
import com.digitalpetri.opcua.stack.core.types.UaDataType;
import com.digitalpetri.opcua.stack.core.types.builtin.NodeId;
import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UInteger;
@UaDataType("TransferSubscriptionsRequest")
public class TransferSubscriptionsRequest implements UaRequestMessage {
public static final NodeId TypeId = Identifiers.TransferSubscriptionsRequest;
public static final NodeId BinaryEncodingId = Identifiers.TransferSubscriptionsRequest_Encoding_DefaultBinary;
public static final NodeId XmlEncodingId = Identifiers.TransferSubscriptionsRequest_Encoding_DefaultXml;
protected final RequestHeader _requestHeader;
protected final UInteger[] _subscriptionIds;
protected final Boolean _sendInitialValues;
public TransferSubscriptionsRequest() {
this._requestHeader = null;
this._subscriptionIds = null;
this._sendInitialValues = null;
}
public TransferSubscriptionsRequest(RequestHeader _requestHeader, UInteger[] _subscriptionIds, Boolean _sendInitialValues) {
this._requestHeader = _requestHeader;
this._subscriptionIds = _subscriptionIds;
this._sendInitialValues = _sendInitialValues;
}
public RequestHeader getRequestHeader() { return _requestHeader; }
public UInteger[] getSubscriptionIds() { return _subscriptionIds; }
public Boolean getSendInitialValues() { return _sendInitialValues; }
@Override
public NodeId getTypeId() { return TypeId; }
@Override
public NodeId getBinaryEncodingId() { return BinaryEncodingId; }
@Override
public NodeId getXmlEncodingId() { return XmlEncodingId; }
public static void encode(TransferSubscriptionsRequest transferSubscriptionsRequest, UaEncoder encoder) {
encoder.encodeSerializable("RequestHeader", transferSubscriptionsRequest._requestHeader != null ? transferSubscriptionsRequest._requestHeader : new RequestHeader());
encoder.encodeArray("SubscriptionIds", transferSubscriptionsRequest._subscriptionIds, encoder::encodeUInt32);
encoder.encodeBoolean("SendInitialValues", transferSubscriptionsRequest._sendInitialValues);
}
public static TransferSubscriptionsRequest decode(UaDecoder decoder) {
RequestHeader _requestHeader = decoder.decodeSerializable("RequestHeader", RequestHeader.class);
UInteger[] _subscriptionIds = decoder.decodeArray("SubscriptionIds", decoder::decodeUInt32, UInteger.class);
Boolean _sendInitialValues = decoder.decodeBoolean("SendInitialValues");
return new TransferSubscriptionsRequest(_requestHeader, _subscriptionIds, _sendInitialValues);
}
static {
DelegateRegistry.registerEncoder(TransferSubscriptionsRequest::encode, TransferSubscriptionsRequest.class, BinaryEncodingId, XmlEncodingId);
DelegateRegistry.registerDecoder(TransferSubscriptionsRequest::decode, TransferSubscriptionsRequest.class, BinaryEncodingId, XmlEncodingId);
}
}
| 45.689655 | 173 | 0.788176 |
6637a85a92ff5961032555813940c37598c5cf68 | 234 | package com.africastalking.models.payment.checkout;
public final class CheckoutValidateRequest {
public transient CheckoutRequest.TYPE type = CheckoutRequest.TYPE.CARD;
public String transactionId;
public String token;
}
| 29.25 | 75 | 0.799145 |
10c037707d5104ac0862eb24e2d138c28802699b | 1,644 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.tools.transfer.stream;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.tools.transfer.IDataTransferConsumer;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProcessor;
import java.io.InputStream;
import java.util.List;
/**
* IStreamDataImporter
*/
public interface IStreamDataImporter extends IDataTransferProcessor {
void init(@NotNull IStreamDataImporterSite site) throws DBException;
@NotNull
List<StreamDataImporterColumnInfo> readColumnsInfo(StreamEntityMapping entityMapping, @NotNull InputStream inputStream) throws DBException;
void runImport(
@NotNull DBRProgressMonitor monitor,
@NotNull DBPDataSource streamDataSource,
@NotNull InputStream inputStream,
@NotNull IDataTransferConsumer consumer) throws DBException;
void dispose();
}
| 33.55102 | 143 | 0.773723 |
d8580a2eccb009a0df2401aa0f03229130b49b47 | 1,368 | package UnitTest.DataStructureTest.arrayANDlistTest.listTest;
import DataStructure.arrayANDlist.list.listRealize.SinglyLinkedList;
import org.junit.Test;
/**
* @author liujun
* @version 1.0
* @date 2020/11/10
* @author—Email liujunfirst@outlook.com
* @blogURL https://blog.csdn.net/ljfirst
* @description 单链表 测试案例
*/
public class SinglyLinkedListTest extends ListljTest {
@Test
public void test_insert() {
super.test_insert(new SinglyLinkedList());
}
/**
* @return 在索引位置插入元素
*/
@Test
public void test_insert_index() {
super.test_insert_index(new SinglyLinkedList());
}
/**
* @return 删除指定元素
*/
@Test
public void test_delete_value() {
super.test_delete_value(new SinglyLinkedList());
}
/**
* @return 删除索引位元素
*/
@Test
public void test_delete_index() {
super.test_delete_index(new SinglyLinkedList());
}
/**
* @return 查找指定元素,返回该元素的索引位置
*/
@Test
public void test_search_value() {
super.test_search_value(new SinglyLinkedList());
}
/**
* @return 查找索引位元素,返回该索引位置的元素
*/
@Test
public void test_search_index() {
super.test_search_index(new SinglyLinkedList());
}
@Test
public void test_listequals() {
super.testlistequals(new SinglyLinkedList());
}
}
| 20.41791 | 68 | 0.635234 |
3a2bcbd8945ec6996283a417e31ce42866765809 | 964 | package gordbilyi.com.navigator.main;
import android.support.annotation.NonNull;
/**
* Created by gordbilyi on 15/08/17.
*/
public interface MainContract {
interface View extends gordbilyi.com.navigator.Presenter.View {
void start();
}
interface Presenter extends gordbilyi.com.navigator.Presenter<View> {
void setNavigator(@NonNull MainContract.Navigator navigator);
void selectSpacesTab();
void selectSharingTab();
void selectSettingsTab();
boolean selectPreviousTab();
void selectTabByIndex(int tabIndex);
void selectTabById(int tabId);
}
interface Navigator {
void selectSpacesTab();
void selectSharingTab();
void selectSettingsTab();
boolean selectPreviousTab();
void selectTabByIndex(int tabIndex);
void selectTabById(int tabId);
}
interface NavigatorProvider {
Navigator getNavigator();
}
}
| 22.418605 | 73 | 0.665975 |
064ef1015181c5c82d3e90753253be90432a04f3 | 2,499 | /* Annot8 (annot8.io) - Licensed under Apache-2.0. */
package io.annot8.testing.testimpl.content;
import io.annot8.api.data.Content;
import io.annot8.api.data.Item;
import io.annot8.api.properties.ImmutableProperties;
import io.annot8.common.data.content.Table;
import io.annot8.common.data.content.TableContent;
import io.annot8.implementations.support.content.AbstractContentBuilder;
import io.annot8.implementations.support.content.AbstractContentBuilderFactory;
import io.annot8.implementations.support.stores.AnnotationStoreFactory;
import io.annot8.testing.testimpl.AbstractTestContent;
import java.util.function.Supplier;
public class TestTableContent extends AbstractTestContent<Table> implements TableContent {
public TestTableContent() {
this(null);
}
public TestTableContent(Item item) {
super(item, Table.class);
}
public TestTableContent(Item item, String description) {
super(item, Table.class, description);
}
public TestTableContent(
Item item,
Class<Table> dataClass,
String id,
String description,
ImmutableProperties properties) {
super(item, Table.class, id, description, properties);
}
public TestTableContent(
Item item,
String id,
String description,
ImmutableProperties properties,
Supplier<Table> data) {
super(item, Table.class, id, description, properties, data);
}
public TestTableContent(
Item item,
AnnotationStoreFactory annotationStoreFactory,
String id,
String description,
ImmutableProperties properties,
Supplier<Table> data) {
super(item, Table.class, annotationStoreFactory, id, description, properties, data);
}
@Override
public Class<? extends Content<Table>> getContentClass() {
return TableContent.class;
}
public static class Builder extends AbstractContentBuilder<Table, TableContent> {
public Builder(Item item) {
super(item);
}
@Override
protected TableContent create(
String id, String description, ImmutableProperties properties, Supplier<Table> data) {
return new TestTableContent(getItem(), id, description, properties, data);
}
}
public static class BuilderFactory extends AbstractContentBuilderFactory<Table, TableContent> {
public BuilderFactory() {
super(Table.class, TableContent.class);
}
@Override
public Content.Builder<TableContent, Table> create(Item item) {
return new Builder(item);
}
}
}
| 28.724138 | 97 | 0.730692 |
7e62516fdcbaba0a8ab739d816edbe62f33464c0 | 10,247 | /* GROOVE: GRaphs for Object Oriented VErification
* Copyright 2003--2011 University of Twente
*
* 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.
*
* $Id: ExploreConfigDialog.java 5815 2016-10-27 10:58:04Z rensink $
*/
package groove.gui.dialog;
import static groove.io.FileType.PROPERTY;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.EnumMap;
import java.util.Map;
import java.util.Properties;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import com.itextpdf.text.Font;
import groove.explore.ExploreConfig;
import groove.explore.config.ExploreKey;
import groove.explore.config.Setting;
import groove.explore.config.SettingKey;
import groove.gui.Options;
import groove.gui.action.Refreshable;
import groove.gui.dialog.config.EditorFactory;
import groove.gui.dialog.config.SettingEditor;
import groove.gui.dialog.config.SettingsPanel;
import groove.util.parse.FormatException;
/**
* Dialog to manage exploration configurations.
* @author Arend Rensink
* @version $Revision $
*/
public class ExploreConfigDialog extends ConfigDialog<ExploreConfig> {
/** Constructs a new dialog, and attempts to load it from the property files in {@link #CONFIG_DIR}. */
public ExploreConfigDialog() {
File configDir = new File(CONFIG_DIR);
if (!configDir.exists()) {
configDir.mkdirs();
}
if (configDir.isDirectory()) {
this.storing = false;
for (File file : configDir.listFiles(PROPERTY.getFilter())) {
try (InputStream in = new FileInputStream(file)) {
Properties props = new Properties();
props.load(in);
addConfig(PROPERTY.stripExtension(file.getName()), new ExploreConfig(props));
} catch (IOException exc) {
// skip this file
}
}
this.storing = true;
}
}
@Override
protected void selectConfig(String name) {
super.selectConfig(name);
boolean wasListening = resetDirtListening();
ExploreConfig config = getSelectedConfig();
if (config != null) {
for (SettingEditor editor : getEditorMap().values()) {
editor.setSetting(config.get(editor.getKey()));
}
}
setDirtListening(wasListening);
}
@Override
protected ExploreConfig createConfig() {
return new ExploreConfig();
}
@Override
protected JComponent createMainPanel() {
JPanel result = new JPanel(new BorderLayout());
result.add(createTabsPanel(), BorderLayout.CENTER);
result.add(createCommandLinePanel(), BorderLayout.SOUTH);
return result;
}
private JComponent createTabsPanel() {
JTabbedPane result = new JTabbedPane();
result.setPreferredSize(new Dimension(500, 100));
// panel with basic settings
SettingsPanel searchPanel = new SettingsPanel(this, "Search");
addEditor(searchPanel, ExploreKey.TRAVERSE);
addEditor(searchPanel, ExploreKey.RANDOM);
addEditor(searchPanel, ExploreKey.ACCEPTOR);
addEditor(searchPanel, ExploreKey.COUNT);
addTab(result, searchPanel);
// panel with basic settings
SettingsPanel checkingPanel = new SettingsPanel(this, "Model Checking");
addEditor(checkingPanel, ExploreKey.CHECKING);
addTab(result, checkingPanel);
// panel with advanced settings
SettingsPanel advancedPanel = new SettingsPanel(this, "Advanced");
addEditor(advancedPanel, ExploreKey.ALGEBRA);
addEditor(advancedPanel, ExploreKey.ISO);
addEditor(advancedPanel, ExploreKey.MATCHER);
addTab(result, advancedPanel);
return result;
}
/** Adds the editor for a given exploration key to a given settings panel. */
private void addEditor(SettingsPanel panel, ExploreKey key) {
SettingsPanel oldPanel = this.panelMap.put(key, panel);
assert oldPanel == null;
panel.add(getEditorMap().get(key));
}
private final Map<ExploreKey,SettingsPanel> panelMap = new EnumMap<>(ExploreKey.class);
private Map<ExploreKey,SettingEditor> getEditorMap() {
if (this.editorMap == null) {
EditorFactory factory = new EditorFactory(this);
this.editorMap = new EnumMap<>(ExploreKey.class);
for (ExploreKey key : ExploreKey.values()) {
this.editorMap.put(key, factory.createEditor(key));
}
}
return this.editorMap;
}
private Map<ExploreKey,SettingEditor> editorMap;
/** Adds a given settings panel as tab to the tabbed pane of the main panel. */
private void addTab(JTabbedPane pane, SettingsPanel panel) {
panel.addGlue();
pane.add(panel, panel.getName());
}
private JPanel createCommandLinePanel() {
JPanel result = new JPanel(new BorderLayout());
result.setBorder(BorderFactory.createEmptyBorder(6, 5, 0, 5));
result.add(new JLabel("Command: "), BorderLayout.WEST);
result.add(getCommandLineField(), BorderLayout.CENTER);
return result;
}
private CommandLineField getCommandLineField() {
if (this.commandLineField == null) {
this.commandLineField = new CommandLineField();
}
return this.commandLineField;
}
private CommandLineField commandLineField;
private class CommandLineField extends JTextField implements Refreshable {
/**
* Constructs an initially empty command line field.
*/
CommandLineField() {
addRefreshable(this);
setEditable(false);
setBackground(Color.WHITE);
}
@Override
public void refresh() {
ExploreConfig config = extractConfig();
String commandLine = config.toCommandLine();
if (commandLine.isEmpty()) {
setForeground(Color.GRAY);
setFont(getFont().deriveFont(Font.ITALIC));
setText("No parameters");
setEnabled(false);
} else {
setForeground(Color.BLACK);
setFont(getFont().deriveFont(Font.NORMAL));
setText(commandLine);
setEnabled(true);
}
}
}
@Override
protected boolean testDirty() {
boolean result = false;
ExploreConfig config = getSelectedConfig();
if (config != null) {
for (SettingEditor editor : getEditorMap().values()) {
try {
Setting<?,?> selectedValue = config.get(editor.getKey());
Setting<?,?> editedValue = editor.getSetting();
result = selectedValue == null ? editedValue != null
: !selectedValue.equals(editedValue);
} catch (FormatException exc) {
// there is an error in a setting, so the state must be dirty
result = true;
}
if (result) {
break;
}
}
}
return result;
}
@Override
protected ExploreConfig extractConfig() {
ExploreConfig result = createConfig();
for (SettingEditor editor : getEditorMap().values()) {
try {
Setting<?,?> editedValue = editor.getSetting();
if (editedValue != null) {
result.put(editor.getKey(), editedValue);
}
} catch (FormatException exc) {
// do nothing
}
}
return result;
}
@Override
void addConfig(String newName, ExploreConfig newConfig) {
super.addConfig(newName, newConfig);
store(newName, newConfig);
}
@Override
void saveConfig() {
String currentName = getSelectedName();
String newName = getEditedName();
if (!currentName.equals(newName)) {
getFile(currentName).delete();
}
super.saveConfig();
store(getSelectedName(), getSelectedConfig());
}
@Override
void deleteConfig() {
getFile(getSelectedName()).delete();
super.deleteConfig();
}
private void store(String name, ExploreConfig config) {
if (!this.storing) {
return;
}
try (OutputStream out = new FileOutputStream(getFile(name))) {
config.getProperties()
.store(out, "Exploration configuration '" + name + "'");
} catch (IOException exc) {
// give up
}
}
private boolean storing;
private File getFile(String name) {
return new File(CONFIG_DIR, PROPERTY.addExtension(name));
}
/** Sets the help panel for a given combination of exploration key and setting kind. */
public void setHelp(ExploreKey key, SettingKey kind) {
SettingsPanel panel = this.panelMap.get(key);
if (panel != null) {
panel.setHelp(key, kind);
}
}
/** Name of the configuration directory. */
public static final String CONFIG_DIR = ".config";
/** Main method, for testing purposes. */
public static void main(String[] args) {
Options.initLookAndFeel();
new ExploreConfigDialog().getConfiguration();
}
}
| 34.156667 | 107 | 0.621645 |
207f54f29da90c8ea3e8cff5afd3f28c5e70181e | 512 | package academy.pocu.comp2500.lab5;
public class Pet {
private final String name;
private final int str;
public Pet(String name, int str) {
this.name = name;
this.str = str;
}
public int getStr() {
return str;
}
public boolean isSame(Pet other) {
boolean answer = false;
if (name.equals(other.name)) {
answer = true;
}
if (str == other.str) {
answer = true;
}
return answer;
}
}
| 18.285714 | 38 | 0.519531 |
e235c74ff0a3e41d89785ff7dff5422279bfb017 | 13,354 | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.db.raw;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.cache.OLevel1RecordCache;
import com.orientechnologies.orient.core.cache.OLevel2RecordCache;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener;
import com.orientechnologies.orient.core.db.ODatabaseListener;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.fetch.OFetchHelper;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.intent.OIntent;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.OStorage;
/**
* Lower level ODatabase implementation. It's extended or wrapped by all the others.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
@SuppressWarnings("unchecked")
public class ODatabaseRaw implements ODatabase {
protected String url;
protected OStorage storage;
protected STATUS status;
protected OIntent currentIntent;
private ODatabaseRecord databaseOwner;
private final Map<String, Object> properties = new HashMap<String, Object>();
private final List<ODatabaseListener> listeners = new ArrayList<ODatabaseListener>();
public ODatabaseRaw(final String iURL) {
try {
url = iURL.replace('\\', '/');
status = STATUS.CLOSED;
// SET DEFAULT PROPERTIES
setProperty("fetch-max", 50);
} catch (Throwable t) {
throw new ODatabaseException("Error on opening database '" + iURL + "'", t);
}
}
public <DB extends ODatabase> DB open(final String iUserName, final String iUserPassword) {
try {
if (status == STATUS.OPEN)
throw new IllegalStateException("Database " + getName() + " is already open");
if (storage == null)
storage = Orient.instance().loadStorage(url);
storage.open(iUserName, iUserPassword, properties);
// WAKE UP DB LIFECYCLE LISTENER
for (ODatabaseLifecycleListener it : Orient.instance().getDbLifecycleListeners())
it.onOpen(getDatabaseOwner());
// WAKE UP LISTENERS
for (ODatabaseListener listener : listeners)
try {
listener.onOpen(this);
} catch (Throwable t) {
}
status = STATUS.OPEN;
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Exception e) {
throw new ODatabaseException("Can't open database", e);
}
return (DB) this;
}
public <DB extends ODatabase> DB create() {
try {
if (status == STATUS.OPEN)
throw new IllegalStateException("Database " + getName() + " is already open");
if (storage == null)
storage = Orient.instance().loadStorage(url);
storage.create(properties);
// WAKE UP DB LIFECYCLE LISTENER
for (ODatabaseLifecycleListener it : Orient.instance().getDbLifecycleListeners())
it.onOpen(getDatabaseOwner());
// WAKE UP LISTENERS
for (ODatabaseListener listener : listeners)
try {
listener.onCreate(this);
} catch (Throwable t) {
}
status = STATUS.OPEN;
} catch (Exception e) {
throw new ODatabaseException("Can't create database", e);
}
return (DB) this;
}
public void delete() {
final List<ODatabaseListener> tmpListeners = new ArrayList<ODatabaseListener>(listeners);
close();
try {
if (storage == null)
storage = Orient.instance().loadStorage(url);
storage.delete();
storage = null;
// WAKE UP LISTENERS
for (ODatabaseListener listener : tmpListeners)
try {
listener.onDelete(this);
} catch (Throwable t) {
}
status = STATUS.CLOSED;
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Exception e) {
throw new ODatabaseException("Can't delete database", e);
}
}
public void reload() {
storage.reload();
}
public STATUS getStatus() {
return status;
}
public <DB extends ODatabase> DB setStatus(final STATUS status) {
this.status = status;
return (DB) this;
}
public boolean exists() {
if (status == STATUS.OPEN)
return true;
if (storage == null)
storage = Orient.instance().loadStorage(url);
return storage.exists();
}
public long countClusterElements(final String iClusterName) {
final int clusterId = getClusterIdByName(iClusterName);
if (clusterId < 0)
throw new IllegalArgumentException("Cluster '" + iClusterName + "' was not found");
return storage.count(clusterId);
}
public long countClusterElements(final int iClusterId) {
return storage.count(iClusterId);
}
public long countClusterElements(final int[] iClusterIds) {
return storage.count(iClusterIds);
}
public ORawBuffer read(final ORecordId iRid, final String iFetchPlan) {
if (!iRid.isValid())
return null;
OFetchHelper.checkFetchPlanValid(iFetchPlan);
try {
return storage.readRecord(databaseOwner, iRid, iFetchPlan);
} catch (Throwable t) {
if (iRid.isTemporary())
throw new ODatabaseException("Error on retrieving record using temporary RecordId: " + iRid, t);
else
throw new ODatabaseException("Error on retrieving record " + iRid + " (cluster: "
+ storage.getPhysicalClusterNameById(iRid.clusterId) + ")", t);
}
}
public long save(final ORecordId iRid, final byte[] iContent, final int iVersion, final byte iRecordType) {
// CHECK IF RECORD TYPE IS SUPPORTED
Orient.instance().getRecordFactoryManager().getRecordTypeClass(iRecordType);
try {
if (iRid.clusterPosition < 0) {
// CREATE
return storage.createRecord(iRid, iContent, iRecordType);
} else {
// UPDATE
return storage.updateRecord(iRid, iContent, iVersion, iRecordType);
}
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Throwable t) {
throw new ODatabaseException("Error on saving record " + iRid, t);
}
}
public void delete(final ORecordId iRid, final int iVersion) {
try {
if (!storage.deleteRecord(iRid, iVersion))
throw new ORecordNotFoundException("The record with id " + iRid + " was not found");
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Exception e) {
OLogManager.instance().exception("Error on deleting record " + iRid, e, ODatabaseException.class);
}
}
public OStorage getStorage() {
return storage;
}
public boolean isClosed() {
return status == STATUS.CLOSED;
}
public String getName() {
return storage != null ? storage.getName() : "<no-name>";
}
public String getURL() {
return url != null ? url : storage.getURL();
}
@Override
public void finalize() {
close();
}
public int getClusters() {
return storage.getClusters();
}
public String getClusterType(final String iClusterName) {
return storage.getClusterTypeByName(iClusterName);
}
public int getClusterIdByName(final String iClusterName) {
return storage.getClusterIdByName(iClusterName);
}
public String getClusterNameById(final int iClusterId) {
if (iClusterId == -1)
return null;
// PHIYSICAL CLUSTER
return storage.getPhysicalClusterNameById(iClusterId);
}
public long getClusterRecordSizeById(final int iClusterId) {
try {
return storage.getClusterById(iClusterId).getRecordsSize();
} catch (Exception e) {
OLogManager.instance().exception("Error on reading records size for cluster with id '" + iClusterId + "'", e,
ODatabaseException.class);
}
return 0l;
}
public long getClusterRecordSizeByName(final String iClusterName) {
try {
return storage.getClusterById(getClusterIdByName(iClusterName)).getRecordsSize();
} catch (Exception e) {
OLogManager.instance().exception("Error on reading records size for cluster '" + iClusterName + "'", e,
ODatabaseException.class);
}
return 0l;
}
public int addCluster(final String iClusterName, final OStorage.CLUSTER_TYPE iType) {
return storage.addCluster(iClusterName, iType);
}
public int addLogicalCluster(final String iClusterName, final int iPhyClusterContainerId) {
return storage.addCluster(iClusterName, OStorage.CLUSTER_TYPE.LOGICAL, iPhyClusterContainerId);
}
public int addPhysicalCluster(final String iClusterName, final String iClusterFileName, final int iStartSize) {
return storage.addCluster(iClusterName, OStorage.CLUSTER_TYPE.PHYSICAL, iClusterFileName, iStartSize);
}
public boolean dropCluster(final String iClusterName) {
return storage.dropCluster(iClusterName);
}
public boolean dropCluster(int iClusterId) {
return storage.dropCluster(iClusterId);
}
public int addDataSegment(final String iSegmentName, final String iSegmentFileName) {
return storage.addDataSegment(iSegmentName, iSegmentFileName);
}
public Collection<String> getClusterNames() {
return storage.getClusterNames();
}
/**
* Returns always null
*
* @return
*/
public OLevel1RecordCache getLevel1Cache() {
return null;
}
public int getDefaultClusterId() {
return storage.getDefaultClusterId();
}
public boolean declareIntent(final OIntent iIntent) {
if (currentIntent != null) {
if (iIntent != null && iIntent.getClass().equals(currentIntent.getClass()))
// SAME INTENT: JUMP IT
return false;
// END CURRENT INTENT
currentIntent.end(this);
}
currentIntent = iIntent;
if (iIntent != null)
iIntent.begin(this);
return true;
}
public ODatabaseRecord getDatabaseOwner() {
return databaseOwner;
}
public ODatabaseRaw setOwner(final ODatabaseRecord iOwner) {
databaseOwner = iOwner;
return this;
}
public Object setProperty(final String iName, final Object iValue) {
if (iValue == null)
return properties.remove(iName.toLowerCase());
else
return properties.put(iName.toLowerCase(), iValue);
}
public Object getProperty(final String iName) {
return properties.get(iName.toLowerCase());
}
public Iterator<Entry<String, Object>> getProperties() {
return properties.entrySet().iterator();
}
public void registerListener(final ODatabaseListener iListener) {
listeners.add(iListener);
}
public void unregisterListener(final ODatabaseListener iListener) {
for (int i = 0; i < listeners.size(); ++i)
if (listeners.get(i) == iListener) {
listeners.remove(i);
break;
}
}
public List<ODatabaseListener> getListeners() {
return listeners;
}
public OLevel2RecordCache getLevel2Cache() {
return storage.getLevel2Cache();
}
public void close() {
if (status != STATUS.OPEN)
return;
callOnCloseListeners();
listeners.clear();
if (storage != null)
storage.close();
storage = null;
status = STATUS.CLOSED;
}
@Override
public String toString() {
return "OrientDB[" + (getStorage() != null ? getStorage().getURL() : "?") + "]";
}
public Object get(final ATTRIBUTES iAttribute) {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
switch (iAttribute) {
case STATUS:
return getStatus();
}
return null;
}
public <DB extends ODatabase> DB set(final ATTRIBUTES iAttribute, final Object iValue) {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = iValue != null ? iValue.toString() : null;
switch (iAttribute) {
case STATUS:
setStatus(STATUS.valueOf(stringValue.toUpperCase(Locale.ENGLISH)));
break;
}
return (DB) this;
}
public void callOnCloseListeners() {
// WAKE UP DB LIFECYCLE LISTENER
for (ODatabaseLifecycleListener it : Orient.instance().getDbLifecycleListeners())
it.onClose(getDatabaseOwner());
// WAKE UP LISTENERS
for (ODatabaseListener listener : listeners)
try {
listener.onClose(getDatabaseOwner());
} catch (Throwable t) {
t.printStackTrace();
}
}
protected boolean isClusterBoundedToClass(int iClusterId) {
return false;
}
}
| 28.054622 | 113 | 0.693425 |
0b9ef29c45e294b7aaa756b4c6a11663cfe94825 | 741 | import java.util.Scanner;
public class EstimatingTheAreaOfACircle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = in.nextLine();
while (!line.equalsIgnoreCase("0 0 0")) {
String[] splitLine = line.split("\\s");
double radius = Double.parseDouble(splitLine[0]);
double trueArea = radius*radius*Math.PI;
double totalDots = Double.parseDouble(splitLine[1]);
double circleDots = Double.parseDouble(splitLine[2]);
double estimateArea = (circleDots/totalDots)*((radius*2)*(radius*2));
System.out.println(trueArea + " " + estimateArea);
line = in.nextLine();
}
}
}
| 39 | 81 | 0.60054 |
44c947eafa55448ff9443fdc70661e5ec7089c32 | 2,156 | package com.julioromano.batchimporterspringboot.controllers;
import com.julioromano.batchimporterspringboot.batch.BatchAnalyzer;
import com.julioromano.batchimporterspringboot.processing.ProcessType;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping(value = "/batch-processing")
public class BatchProcessingController {
private final BatchAnalyzer fileBatchAnalyzer;
@Value("${application.sales-data-in-dir}")
private String salesDataInDir;
public BatchProcessingController(@Qualifier("FileBatchAnalyzer") BatchAnalyzer fileBatchAnalyzer) {
this.fileBatchAnalyzer = fileBatchAnalyzer;
}
@RequestMapping(path = "/{processTypeValue}", method = RequestMethod.POST)
public ResponseEntity<String> process(@PathVariable String processTypeValue) {
try {
ProcessType processType = ProcessType.valueOf(processTypeValue.toUpperCase());
String inDir = getInDir(processType);
if (inDir == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
CompletableFuture<String> report = fileBatchAnalyzer.analyzeFiles(inDir, processType);
return ResponseEntity.ok(report.get());
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
private String getInDir(ProcessType processType) {
String inDir = null;
if (processType == ProcessType.SALES) {
inDir = salesDataInDir;
}
return inDir;
}
}
| 38.5 | 103 | 0.742115 |
93464886d254d87645fc38aa4ad52657cbccdffd | 629 | class goO4M51tlS3VhG {
public static void klVa (String[] iXISM) throws e {
return new void[ true.eonO8_TEu].iVLK79zjr58();
boolean[][] Nb5NwYqsYtC = !!-!--null[ -mHjiYT8hwbi.ytB] = ( ( new dsEb7Abc()._7xd0i7AcwBali()).eLb()).q();
}
public boolean B () throws Ki4W0aIY3C {
while ( !false.wrqDxhHb()) {
boolean[] y6EMBGfKvi;
}
int[] w = -QvNJdMo[ null.mhTvK()];
return;
true.cYeZDSKJ();
while ( Rrz0XJB5GN[ --true.px4v]) {
boolean[][] EX;
}
UQNrlX pg72U19 = -088804124[ true[ false[ null.ULqPchWK]]];
}
}
| 33.105263 | 116 | 0.535771 |
9847aa00a531e40312ebea958689bff3515a9d3a | 1,636 | package org.redischool.fall2018project.usecases.shoppingcart;
import com.google.common.collect.ImmutableList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
public class ShoppingCart {
private final Map<Product, Item> items = new LinkedHashMap<>();
public List<Item> items() {
return ImmutableList.copyOf(items.values());
}
ShoppingCart add(Product product, int quantity) {
if (!items.containsKey(product)) {
items.put(product, new Item(product, quantity));
} else {
Item existingItem = items.get(product);
items.put(product, existingItem.plus(quantity));
}
return this;
}
static class Item {
private final Product product;
private final int quantity;
public Item(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Item) {
Item other = (Item) obj;
return Objects.equals(product, other.product) && quantity == other.quantity;
} else {
return false;
}
}
@Override
public String toString() {
return toStringHelper(this).add("product", product).add("quantity", quantity).toString();
}
private Item plus(int quantity) {
return new Item(product, this.quantity + quantity);
}
}
}
| 28.206897 | 101 | 0.605134 |
1e141a76eca55a56b9384720a8a7ed08c820a8f0 | 1,221 |
/*
ID: helena.6
LANG: JAVA
TASK: skidesign
*/
import java.io.*;
import java.util.Arrays;
public class skidesign {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("skidesign.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("skidesign.out")));
int n = Integer.parseInt(f.readLine());
int[] elevation = new int[n];
for (int i = 0; i < n; i++) {
elevation[i] = Integer.parseInt(f.readLine());
}
Arrays.sort(elevation);
int min = elevation[0];
int max = elevation[n - 1];
if (max-min > 17) {
int minCost = Integer.MAX_VALUE;
int cost = 0;
for (int i = min; i <= max - 17; i++) { //i represents the smallest number
for (int k = 0; k < n; k++) {
if (elevation[k] < i) {
cost = cost + (i-elevation[k])*(i-elevation[k]);
}
if (elevation[k] > i + 17) {
cost = cost + (elevation[k] - i - 17)*(elevation[k] - i - 17); // distribute (elevation[k] - (i + 17))
}
}
if (cost < minCost)
minCost = cost;
cost = 0;
}
out.println(minCost);
} else {
out.println(0);
}
out.close();
}
} | 24.42 | 109 | 0.559378 |
dccf0f1154110d9800be7ad1b71326207f5bdb73 | 1,029 | package io.github.bootsrc.im.server.core;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.channel.ChannelHandlerContext;
/**
* 客户端连接管理
* @author yinjihuan
*
*/
public class ConnectionPool {
private static Map<String, ChannelHandlerContext> pool = new ConcurrentHashMap<String, ChannelHandlerContext>();
public static ChannelHandlerContext getChannel(String clientId) {
if (clientId == null) {
return null;
}
return pool.get(clientId);
}
public static ChannelHandlerContext putChannel(String clientId, ChannelHandlerContext channel) {
return pool.put(clientId, channel);
}
public static Set<String> getClients() {
return pool.keySet();
}
public static List<ChannelHandlerContext> getChannels() {
List<ChannelHandlerContext> channels = new ArrayList<>();
Set<String> keys = pool.keySet();
for (String key : keys) {
channels.add(pool.get(key));
}
return channels;
}
}
| 22.866667 | 113 | 0.739553 |
1e8b9c3898a4c754c3810fca382148d14d7d3b59 | 2,816 | package com.common.util.count.aspect;
import com.common.util.ip.HttpRequestUtil;
import com.common.util.count.annotation.RequestLimit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author
* @Description: 文件描述
* @date
**/
@Component
@Aspect
public class RequestLimitAspect {
/**
* logger
*/
private final Logger logger = LoggerFactory.getLogger(getClass());
private AtomicLong countAto = new AtomicLong(0L);
@Before("execution(* com.common.util.count.controller.*.*(..)) && @annotation(limit)")
public void requestLimit(JoinPoint joinpoint, RequestLimit limit) {
Object[] args = joinpoint.getArgs();
Object target = joinpoint.getTarget();
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ip = HttpRequestUtil.getIpAddr(request);
String url = request.getRequestURL().toString();
String key = "req_limit_".concat(url).concat(ip);
// 加1后看看值
long curCountV = countAto.getAndIncrement();
System.out.println(curCountV + " --- " + countAto.incrementAndGet() + " --- " + limit.count());
if (curCountV > limit.count()) {
logger.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
throw new RuntimeException("超出访问次数限制");
}
}
@After("execution(* com.common.util.count.controller.*.*(..)) && @annotation(com.common.util.count.annotation.RequestLimit)")
public void requestLimitAfter(JoinPoint joinpoint) {
Object[] args = joinpoint.getArgs();
Object target = joinpoint.getTarget();
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ip = HttpRequestUtil.getIpAddr(request);
String url = request.getRequestURL().toString();
String key = "req_limit_".concat(url).concat(ip);
// 加1后看看值
long curCountV = countAto.getAndIncrement();
if (curCountV > 5) {
logger.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + 5 + "]");
throw new RuntimeException("超出访问次数限制");
}
}
} | 40.228571 | 129 | 0.682528 |
570a37ed60d5a93dd03e96820bf2eb44bdf8f693 | 2,254 | package com.stylefeng.gunSelf.modular.system.model;
import com.baomidou.mybatisplus.enums.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import org.springframework.format.annotation.DateTimeFormat;
import cn.afterturn.easypoi.excel.annotation.Excel;
/**
* <p>
*
* </p>
*
* @author stylezhang123
* @since 2019-05-12
*/
@TableName("blog_board")
public class BlogBoard extends Model<BlogBoard> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
@Excel(name="主键")
private Integer id;
/**
* 留言内容
*/
@Excel(name="留言内容")
private String content;
/**
* 用户名
*/
@Excel(name="用户名")
private String account;
/**
* 所属博客账户
*/
@Excel(name="所属博客账户")
private String blogAccount;
/**
* 发表时间
*/
@Excel(name="发表时间",format="yyyy-MM-dd HH:mm:ss",width=20.0)
private Date creatTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getBlogAccount() {
return blogAccount;
}
public void setBlogAccount(String blogAccount) {
this.blogAccount = blogAccount;
}
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCreatTime() {
return creatTime;
}
public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "BlogBoard{" +
"id=" + id +
", content=" + content +
", account=" + account +
", blogAccount=" + blogAccount +
", creatTime=" + creatTime +
"}";
}
}
| 21.264151 | 63 | 0.60559 |
53cf92be1658d29499e30d60f5ffd7d332984727 | 3,318 | package org.adorsys.adpharma.client.jpa.loader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.control.Label;
import javax.inject.Inject;
import org.adorsys.adpharma.client.jpa.productfamily.ProductFamily;
import org.adorsys.adpharma.client.jpa.productfamily.ProductFamilyParentFamily;
import org.adorsys.adpharma.client.jpa.productfamily.ProductFamilySearchInput;
import org.adorsys.adpharma.client.jpa.productfamily.ProductFamilySearchResult;
import org.adorsys.adpharma.client.jpa.productfamily.ProductFamilyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ProductFamilyLoader extends Service<List<ProductFamily>> {
@Inject
private ProductFamilyService remoteService;
private HSSFWorkbook workbook;
public ProductFamilyLoader setWorkbook(HSSFWorkbook workbook) {
this.workbook = workbook;
return this;
}
private String progressText;
private Label progressLabel;
public ProductFamilyLoader setProgressText(String progressText) {
this.progressText = progressText;
return this;
}
public ProductFamilyLoader setProgressLabel(Label progressLabel) {
this.progressLabel = progressLabel;
return this;
}
private List<ProductFamily> load() {
List<ProductFamily> result = new ArrayList<ProductFamily>();
result.addAll(remoteService.listAll().getResultList());
HSSFSheet sheet = workbook.getSheet("ProductFamily");
if(sheet==null){
return result;
}
Platform.runLater(new Runnable(){@Override public void run() {progressLabel.setText(progressText);}});
Iterator<Row> rowIterator = sheet.rowIterator();
rowIterator.next();
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
ProductFamily entity = new ProductFamily();
Cell cell = row.getCell(0);
if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue()))
entity.setName(cell.getStringCellValue().trim());
if (StringUtils.isBlank(entity.getName()))
continue;
ProductFamilySearchInput searchInput = new ProductFamilySearchInput();
searchInput.setEntity(entity);
searchInput.setFieldNames(Arrays.asList("name"));
ProductFamilySearchResult found = remoteService.findBy(searchInput);
if (!found.getResultList().isEmpty()){
result.add(found.getResultList().iterator().next());
continue;
}
cell = row.getCell(1);
if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())){
String parentFamilyName = cell.getStringCellValue().trim();
for (ProductFamily parentFamily : result) {
if(parentFamilyName.equalsIgnoreCase(parentFamily.getName())){
entity.setParentFamily(new ProductFamilyParentFamily(parentFamily));
}
}
}
result.add(remoteService.create(entity));
}
return result;
}
@Override
protected Task<List<ProductFamily>> createTask() {
return new Task<List<ProductFamily>>() {
@Override
protected List<ProductFamily> call() throws Exception {
return load();
}
};
}
}
| 31.009346 | 104 | 0.761905 |
f95646a75d6e015eb13cfbd44dcf428c63b011ef | 10,748 | /*
* 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.netbeans.modules.html.editor.api.actions;
import java.awt.Dialog;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.Action;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.csl.api.DataLoadersBridge;
import org.netbeans.modules.css.model.api.Body;
import org.netbeans.modules.css.model.api.Declarations;
import org.netbeans.modules.css.model.api.ElementFactory;
import org.netbeans.modules.css.model.api.Media;
import org.netbeans.modules.css.model.api.Model;
import org.netbeans.modules.css.model.api.Rule;
import org.netbeans.modules.css.model.api.Selector;
import org.netbeans.modules.css.model.api.SelectorsGroup;
import org.netbeans.modules.css.model.api.StyleSheet;
import org.netbeans.modules.html.editor.Utils;
import org.netbeans.modules.html.editor.lib.api.elements.Attribute;
import org.netbeans.modules.html.editor.lib.api.elements.OpenTag;
import org.netbeans.modules.html.editor.ui.ModifyElementRulesPanel;
import org.netbeans.modules.parsing.api.Snapshot;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.modules.parsing.spi.ParseException;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
/**
* Opens a UI which allows to edit css rules associated to the selected element.
*
* TODO replace the ugly manual document update by something more elegant I
* already have for the html/css refactoring.
*
* @author marekfukala
*/
@NbBundle.Messages({
"action.name_modify.rules=Modify Rules"
})
public class ModifyElementRulesAction extends AbstractSourceElementAction {
private int pos; //last change offset
private int diff; //aggregated document modifications diff
public ModifyElementRulesAction(FileObject file, String elementPath) {
super(file, elementPath);
putValue(Action.NAME, Bundle.action_name_modify_rules());
}
@Override
public void actionPerformed(ActionEvent e) {
try {
final SourceElementHandle handle = createSourceElementHandle();
if (!handle.isResolved()) {
return;
}
final ModifyElementRulesPanel panel = new ModifyElementRulesPanel(handle);
DialogDescriptor descriptor = new DialogDescriptor(
panel,
Bundle.action_name_modify_rules(),
true,
DialogDescriptor.OK_CANCEL_OPTION,
DialogDescriptor.OK_OPTION,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(DialogDescriptor.OK_OPTION)) {
if(!panel.isModified()) {
return ;
}
if(panel.isPanelContentValid()) {
applyChanges(panel, handle);
} else {
Toolkit.getDefaultToolkit().beep();
}
}
}
});
Dialog dialog = DialogDisplayer.getDefault().createDialog(descriptor);
dialog.setVisible(true);
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
private void applyChanges(final ModifyElementRulesPanel panel, final SourceElementHandle handle) {
final BaseDocument doc = (BaseDocument) Utils.getDocument(file);
final AtomicBoolean success = new AtomicBoolean();
pos = Integer.MAX_VALUE;
diff = -1;
doc.runAtomicAsUser(new Runnable() {
@Override
public void run() {
try {
updateAttribute(handle, doc, panel.getOriginalClassAttribute(), panel.getNewClassAttributeValue(), "class");
updateAttribute(handle, doc, panel.getOriginalIdAttribute(), panel.getNewIdAttributeValue(), "id");
success.set(true); //better not to do the save from within the atomic modification task
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
});
//possibly save the document if not opened in editor
if (success.get()) {
try {
Utils.saveDocumentIfNotOpened(doc);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
applyChangesToStyleSheets(panel, handle);
}
}
private void applyChangesToStyleSheets(final ModifyElementRulesPanel panel, SourceElementHandle handle) {
try {
if (panel.getSelectedStyleSheet() == null) {
return;
}
final Model model = Utils.createCssSourceModel(Source.create(panel.getSelectedStyleSheet()));
final ElementFactory factory = model.getElementFactory();
model.runWriteTask(new Model.ModelTask() {
@Override
public void run(StyleSheet styleSheet) {
try {
//add to the body
Body body = styleSheet.getBody();
if (body == null) {
//create body if empty file
body = factory.createBody();
styleSheet.setBody(body);
}
//workaround: the current ModifyElementRulesPanel cannot handle
//multiple classes being specified in one class attribute.
//so if such situation happen the modified/created class selectors
//won't be created in the stylesheet/s!
String[] classes = panel.getNewClasses();
if(classes != null && classes.length == 1) {
String justOne = classes[0];
if (!panel.classExistsInSelectedStyleSheet(justOne)) {
Rule rule = createRule(factory, "." + justOne);
styleSheet.getBody().addRule(rule);
}
}
if (!panel.idExistsInSelectedStyleSheet()) {
Rule rule = createRule(factory, "#" + panel.getNewIdAttributeValue());
styleSheet.getBody().addRule(rule);
}
//apply && save
model.applyChanges();
} catch ( IOException | BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
});
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
private Rule createRule(ElementFactory factory, String selector) {
Selector s = factory.createSelector(selector);
SelectorsGroup sg = factory.createSelectorsGroup(s);
Declarations ds = factory.createDeclarations();
return factory.createRule(sg, ds);
}
private void updateAttribute(SourceElementHandle handle, Document doc, Attribute a, String value, String name) throws BadLocationException {
OpenTag ot = handle.getOpenTag();
Snapshot snap = handle.getSnapshot();
if (a == null && value == null) {
return; //no change
}
if (a == null && value != null) {
//insert whole new attribute
int insertPos = snap.getOriginalOffset(ot.from() + 1 + ot.name().length());
StringBuilder sb = new StringBuilder();
sb.append(' ');
sb.append(name);
sb.append('=');
sb.append('"');
sb.append(value);
sb.append('"');
doc.insertString(insertPos, sb.toString(), null);
pos = insertPos;
diff = sb.length();
} else if (a != null && value == null) {
//remove
int removeFrom = a.from() - 1; //include the WS before attribute name
int removeTo = a.to();
int rfdoc = snap.getOriginalOffset(removeFrom);
int rtdoc = snap.getOriginalOffset(removeTo);
if (rfdoc >= pos) {
rfdoc += diff;
rtdoc += diff;
}
doc.remove(rfdoc, rtdoc - rfdoc);
pos = removeFrom;
diff = rfdoc - rtdoc;
} else {
//change
int removeFrom = a.from();
int removeTo = a.to();
int rfdoc = snap.getOriginalOffset(removeFrom);
int rtdoc = snap.getOriginalOffset(removeTo);
if (rfdoc >= pos) {
rfdoc += diff;
rtdoc += diff;
}
doc.remove(rfdoc, rtdoc - rfdoc);
int insertPos = rfdoc;
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append('=');
sb.append('"');
sb.append(value);
sb.append('"');
doc.insertString(insertPos, sb.toString(), null);
pos = insertPos;
diff = rfdoc - rtdoc + sb.length();
}
}
}
| 38.942029 | 144 | 0.564942 |
4d2475b22a1fb627db8c0fcf22a0193ea9b143ba | 5,944 | package org.yinwang.rubysonar.types;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yinwang.rubysonar.Analyzer;
import org.yinwang.rubysonar.State;
import org.yinwang.rubysonar.TypeStack;
import org.yinwang.rubysonar.ast.Function;
import java.util.*;
public class FunType extends Type {
@NotNull
public Map<Type, Type> arrows = new HashMap<>();
public Function func;
@Nullable
public ClassType cls = null;
public State env;
@Nullable
public Type selfType; // self's type for calls
public List<Type> defaultTypes; // types for default parameters (evaluated at def time)
public boolean isClassMethod = false;
public FunType() {
}
public FunType(Function func, State env) {
this.func = func;
this.env = env;
}
public FunType(Type from, Type to) {
addMapping(from, to);
}
public void addMapping(Type from, Type to) {
if (arrows.size() < 5) {
arrows.put(from, to);
Map<Type, Type> oldArrows = arrows;
arrows = compressArrows(arrows);
if (toString().length() > 900) {
arrows = oldArrows;
}
}
}
@Nullable
public Type getMapping(@NotNull Type from) {
return arrows.get(from);
}
public Type getReturnType() {
if (!arrows.isEmpty()) {
return arrows.values().iterator().next();
} else {
return Type.UNKNOWN;
}
}
public void setCls(ClassType cls) {
this.cls = cls;
}
public void setSelfType(Type selfType) {
this.selfType = selfType;
}
public void setDefaultTypes(List<Type> defaultTypes) {
this.defaultTypes = defaultTypes;
}
public void setClassMethod(boolean isClassMethod) {
this.isClassMethod = isClassMethod;
}
@Override
public boolean equals(Object other) {
if (other instanceof FunType) {
return func.equals(((FunType) other).func);
} else {
return false;
}
}
@Override
public int hashCode() {
return func.hashCode();
}
private boolean subsumed(Type type1, Type type2) {
return subsumedInner(type1, type2, new TypeStack());
}
private boolean subsumedInner(Type type1, Type type2, TypeStack typeStack) {
if (typeStack.contains(type1, type2)) {
return true;
}
if (type1.isUnknownType() || type1 == Type.NIL || type1.equals(type2)) {
return true;
}
if (type1 instanceof TupleType && type2 instanceof TupleType) {
List<Type> elems1 = ((TupleType) type1).eltTypes;
List<Type> elems2 = ((TupleType) type2).eltTypes;
if (elems1.size() == elems2.size()) {
typeStack.push(type1, type2);
for (int i = 0; i < elems1.size(); i++) {
if (!subsumedInner(elems1.get(i), elems2.get(i), typeStack)) {
typeStack.pop(type1, type2);
return false;
}
}
}
return true;
}
if (type1 instanceof ListType && type2 instanceof ListType) {
return subsumedInner(((ListType) type1).toTupleType(), ((ListType) type2).toTupleType(), typeStack);
}
return false;
}
private Map<Type, Type> compressArrows(Map<Type, Type> arrows) {
Map<Type, Type> ret = new HashMap<>();
for (Map.Entry<Type, Type> e1 : arrows.entrySet()) {
boolean subsumed = false;
for (Map.Entry<Type, Type> e2 : arrows.entrySet()) {
if (e1 != e2 && subsumed(e1.getKey(), e2.getKey())) {
subsumed = true;
break;
}
}
if (!subsumed) {
ret.put(e1.getKey(), e1.getValue());
}
}
return ret;
}
// If the self type is set, use the self type in the display
// This is for display purpose only, it may not be logically
// correct wrt some pathological programs
private TupleType simplifySelf(TupleType from) {
TupleType simplified = new TupleType();
if (from.eltTypes.size() > 0) {
if (cls != null) {
simplified.add(cls.getCanon());
} else {
simplified.add(from.get(0));
}
}
for (int i = 1; i < from.eltTypes.size(); i++) {
simplified.add(from.get(i));
}
return simplified;
}
@Override
protected String printType(@NotNull CyclicTypeRecorder ctr) {
if (arrows.isEmpty()) {
return "? -> ?";
}
StringBuilder sb = new StringBuilder();
Integer num = ctr.visit(this);
if (num != null) {
sb.append("#").append(num);
} else {
int newNum = ctr.push(this);
int i = 0;
Set<String> seen = new HashSet<>();
for (Map.Entry<Type, Type> e : arrows.entrySet()) {
Type from = e.getKey();
String as = from.printType(ctr) + " -> " + e.getValue().printType(ctr);
if (!seen.contains(as)) {
if (i != 0) {
if (Analyzer.self.multilineFunType) {
sb.append("\n| ");
} else {
sb.append(" | ");
}
}
sb.append(as);
seen.add(as);
}
i++;
}
if (ctr.isUsed(this)) {
sb.append("=#").append(newNum).append(": ");
}
ctr.pop(this);
}
return sb.toString();
}
}
| 25.51073 | 112 | 0.509421 |
e32c126d6f19c59ddac2a3568f2aa5cb84beaa3e | 4,730 | package org.innovateuk.ifs;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.invite.constant.InviteStatus;
import org.innovateuk.ifs.invite.resource.ApplicationInviteResource;
import org.innovateuk.ifs.invite.resource.InviteOrganisationResource;
import org.innovateuk.ifs.invite.service.InviteOrganisationRestService;
import org.innovateuk.ifs.invite.service.InviteRestService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.mockito.Mock;
import java.util.Arrays;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.rest.RestResult.restFailure;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
public abstract class AbstractInviteMockMVCTest<ControllerType> extends BaseControllerMockMVCTest<ControllerType> {
protected Long competitionId = 1L;
@Mock
protected InviteRestService inviteRestService;
@Mock
private InviteOrganisationRestService inviteOrganisationRestService;
public ApplicationInviteResource invite;
public ApplicationInviteResource acceptedInvite;
public ApplicationInviteResource existingUserInvite;
public static final String INVITE_HASH = "b157879c18511630f220325b7a64cf3eb782759326d3cbb85e546e0d03e663ec711ec7ca65827a96";
public static final String INVITE_HASH_EXISTING_USER = "cccccccccc630f220325b7a64cf3eb782759326d3cbb85e546e0d03e663ec711ec7ca65827a96";
public static final String INVALID_INVITE_HASH = "aaaaaaa7a64cf3eb782759326d3cbb85e546e0d03e663ec711ec7ca65827a96";
public static final String ACCEPTED_INVITE_HASH = "BBBBBBBBB7a64cf3eb782759326d3cbb85e546e0d03e663ec711ec7ca65827a96";
public void setupInvites() {
when(inviteRestService.getInvitesByApplication(isA(Long.class))).thenReturn(restSuccess(emptyList()));
InviteOrganisationResource inviteOrganisation = new InviteOrganisationResource(2L, "Invited Organisation Ltd", "Org type", null, null);
invite = new ApplicationInviteResource();
invite.setStatus(InviteStatus.SENT);
invite.setApplication(1L);
invite.setName("Some Invitee");
invite.setHash(INVITE_HASH);
String email = "invited@email.com";
invite.setEmail(email);
invite.setInviteOrganisation(inviteOrganisation.getId());
invite.setCompetitionId(competitionId);
inviteOrganisation.setInviteResources(Arrays.asList(invite));
when(inviteRestService.getInviteByHash(eq(INVITE_HASH))).thenReturn(restSuccess(invite));
when(inviteOrganisationRestService.getByIdForAnonymousUserFlow(eq(invite.getInviteOrganisation()))).thenReturn(restSuccess(inviteOrganisation));
when(inviteOrganisationRestService.put(any())).thenReturn(restSuccess());
when(inviteRestService.checkExistingUser(eq(INVITE_HASH))).thenReturn(restSuccess(false));
when(inviteRestService.checkExistingUser(eq(INVALID_INVITE_HASH))).thenReturn(restFailure(notFoundError(UserResource.class, email)));
when(inviteRestService.getInviteByHash(eq(INVALID_INVITE_HASH))).thenReturn(restFailure(notFoundError(ApplicationResource.class, INVALID_INVITE_HASH)));
when(inviteRestService.getInviteOrganisationByHash(INVITE_HASH)).thenReturn(restSuccess(new InviteOrganisationResource()));
acceptedInvite = new ApplicationInviteResource();
acceptedInvite.setStatus(InviteStatus.OPENED);
acceptedInvite.setApplication(1L);
acceptedInvite.setName("Some Invitee");
acceptedInvite.setHash(ACCEPTED_INVITE_HASH);
acceptedInvite.setEmail(email);
when(inviteRestService.getInviteByHash(eq(ACCEPTED_INVITE_HASH))).thenReturn(restSuccess(acceptedInvite));
existingUserInvite = new ApplicationInviteResource();
existingUserInvite.setStatus(InviteStatus.SENT);
existingUserInvite.setApplication(1L);
existingUserInvite.setName("Some Invitee");
existingUserInvite.setHash(INVITE_HASH_EXISTING_USER);
existingUserInvite.setEmail("existing@email.com");
when(inviteRestService.checkExistingUser(eq(INVITE_HASH_EXISTING_USER))).thenReturn(restSuccess(true));
when(inviteRestService.getInviteByHash(eq(INVITE_HASH_EXISTING_USER))).thenReturn(restSuccess(existingUserInvite));
when(inviteRestService.getInvitesByApplication(isA(Long.class))).thenReturn(restSuccess(emptyList()));
when(inviteRestService.getInviteOrganisationByHash(INVITE_HASH_EXISTING_USER)).thenReturn(restSuccess(new InviteOrganisationResource()));
}
} | 57.682927 | 160 | 0.798943 |
58090dc1b209c05caf240f89647edd424e08b6fc | 94 | package il.co.topq.fixture;
public class FixtureResponse {
public Object response;
}
| 9.4 | 30 | 0.723404 |
013610cc7fb433342ff9577ddb01498a81273256 | 3,664 | package opencv.android;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import com.facebook.react.bridge.ReadableMap;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Size;
import org.opencv.face.FaceRecognizer;
import org.opencv.face.LBPHFaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.CLAHE;
import org.opencv.imgproc.Imgproc;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static org.opencv.objdetect.Objdetect.CASCADE_SCALE_IMAGE;
/**
* Created by Assem Abozaid on 8/3/2018.
*/
public class ReactMethods {
private static ReactMethods instance;
private CLAHE clahe;
private MatOfPoint2f points;
private ReactMethods() {
clahe = Imgproc.createCLAHE();
}
static ReactMethods getInstance() {
if(instance == null)
instance = new ReactMethods();
return instance;
}
public int checkDetection(final MatOfRect faces, final Mat grayImage) {
if(!faces.empty()) {
if(isBlurImage(grayImage))
return 1;
else {
if(faces.toArray().length > 1)
return 2;
else
return 3;
}
} else
return 0;
}
private boolean isBlurImage(final Mat grayImage) {
int l = CvType.CV_8UC1; //8-bit grey scale image
Mat dst2 = new Mat();
Imgproc.cvtColor(grayImage, dst2, Imgproc.COLOR_GRAY2RGB);
Mat laplacianImage = new Mat();
dst2.convertTo(laplacianImage, l);
Imgproc.Laplacian(grayImage, laplacianImage, CvType.CV_8U);
Mat laplacianImage8bit = new Mat();
laplacianImage.convertTo(laplacianImage8bit, l);
Bitmap bmp = Bitmap.createBitmap(laplacianImage8bit.cols(), laplacianImage8bit.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(laplacianImage8bit, bmp);
int[] pixels = new int[bmp.getHeight() * bmp.getWidth()];
bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
int maxLap = -16777216; // 16m
for (int pixel : pixels) {
if (pixel > maxLap)
maxLap = pixel;
}
// int soglia = -6118750;
int soglia = -8118750;
if (maxLap <= soglia) {
return true;
}
return false;
}
public Mat improvements(final Mat image) {
Mat improve = new Mat();
clahe.setClipLimit(4);
clahe.apply(image, improve);
Imgproc.equalizeHist(improve, improve);
return improve;
}
public Mat cropImage(final MatOfRect faces, final Mat image) {
if(!faces.empty()) {
Rect rect_crop = null;
points = new MatOfPoint2f();
ArrayList<Point> rectPoints = new ArrayList<>();
for (Rect face : faces.toArray()) {
rect_crop = new Rect(face.x, face.y, face.width, face.height);
rectPoints.add(new Point(face.tl().x, face.br().y));
}
points.fromList(rectPoints);
Mat cropedFace = new Mat(image, rect_crop);
return cropedFace;
}
return image;
}
}
| 30.280992 | 120 | 0.628275 |
362bed1bd69b99a9e94eb9ac201bd5fd6b3d54a2 | 2,568 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.app.Dialog;
import android.content.Context;
import android.preference.EditTextPreference;
import android.text.method.DigitsKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
/**
* TODO: Add a soft dialpad for PIN entry.
*/
class EditPinPreference extends EditTextPreference {
interface OnPinEnteredListener {
void onPinEntered(EditPinPreference preference, boolean positiveResult);
}
private OnPinEnteredListener mPinListener;
public EditPinPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditPinPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnPinEnteredListener(OnPinEnteredListener listener) {
mPinListener = listener;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
final EditText editText = (EditText) view.findViewById(android.R.id.edit);
if (editText != null) {
editText.setSingleLine(true);
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
editText.setKeyListener(DigitsKeyListener.getInstance());
}
}
public boolean isDialogOpen() {
Dialog dialog = getDialog();
return dialog != null && dialog.isShowing();
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (mPinListener != null) {
mPinListener.onPinEntered(this, positiveResult);
}
}
public void showPinDialog() {
Dialog dialog = getDialog();
if (dialog == null || !dialog.isShowing()) {
showDialog(null);
}
}
}
| 30.571429 | 89 | 0.69704 |
021b89b7f923d184e04fbad7dcb1cd4d4f58867e | 848 | package org.example.bucket;
import org.example.ArrayCreation;
import org.example.ReportSorting;
import java.util.ResourceBundle;
/**
* Created on 29.07.2021 14:15.
*
* @author Aleks Sidorenko (e-mail: alek.sidorenko@gmail.com).
* @version Id$.
* @since 0.1.
*/
public class StartBucketSort {
public static void main(String[] args) {
init();
}
public static void init() {
ReportSorting reportSorting = new ReportSorting();
ResourceBundle resource = ResourceBundle.getBundle("messages");
int nubOfItems = 100_000;
int[] arr = new ArrayCreation().array(nubOfItems);
int[] arrSortBucket = new BucketSort().sort(arr);
reportSorting.writeReport(
nubOfItems,
resource.getString("bucket.sort"),
arrSortBucket
);
}
}
| 24.228571 | 71 | 0.629717 |
cb5954e216fa5e8f9c75e21ba299f2b3d0129eb4 | 3,118 | package org.rcsb.cif.schema.mm;
import org.rcsb.cif.model.*;
import org.rcsb.cif.schema.*;
import javax.annotation.Generated;
/**
* Data items in the PDBX_STRUCT_REF_SEQ_INSERTION category
* annotate deletions in the sequence of the entity described
* in the referenced database entry.
*/
@Generated("org.rcsb.cif.schema.generator.SchemaGenerator")
public class PdbxStructRefSeqDeletion extends DelegatingCategory {
public PdbxStructRefSeqDeletion(Category delegate) {
super(delegate);
}
@Override
protected Column createDelegate(String columnName, Column column) {
switch (columnName) {
case "id":
return getId();
case "details":
return getDetails();
case "asym_id":
return getAsymId();
case "comp_id":
return getCompId();
case "db_seq_id":
return getDbSeqId();
case "db_code":
return getDbCode();
case "db_name":
return getDbName();
default:
return new DelegatingColumn(column);
}
}
/**
* The value of _pdbx_struct_ref_seq_deletion.id must
* uniquely identify a record in the PDBX_STRUCT_REF_SEQ_DELETION list.
* @return StrColumn
*/
public StrColumn getId() {
return delegate.getColumn("id", DelegatingStrColumn::new);
}
/**
* A description of any special aspects of the deletion
* @return StrColumn
*/
public StrColumn getDetails() {
return delegate.getColumn("details", DelegatingStrColumn::new);
}
/**
* Identifies the polymer entity instance in this entry corresponding
* to the reference sequence in which the deletion is specified.
*
* This data item is a pointer to _pdbx_poly_seq_scheme.asym_id in the
* PDBX_POLY_SEQ_SCHEME category.
* @return StrColumn
*/
public StrColumn getAsymId() {
return delegate.getColumn("asym_id", DelegatingStrColumn::new);
}
/**
* The monomer name found at this position in the referenced
* database entry.
* @return StrColumn
*/
public StrColumn getCompId() {
return delegate.getColumn("comp_id", DelegatingStrColumn::new);
}
/**
* This data item is the database sequence numbering of the deleted
* residue
* @return IntColumn
*/
public IntColumn getDbSeqId() {
return delegate.getColumn("db_seq_id", DelegatingIntColumn::new);
}
/**
* The code for this entity or biological unit or for a closely
* related entity or biological unit in the named database.
* @return StrColumn
*/
public StrColumn getDbCode() {
return delegate.getColumn("db_code", DelegatingStrColumn::new);
}
/**
* The name of the database containing reference information about
* this entity or biological unit.
* @return StrColumn
*/
public StrColumn getDbName() {
return delegate.getColumn("db_name", DelegatingStrColumn::new);
}
} | 29.415094 | 75 | 0.630212 |
4a8dcb811a288ba4553eb89ee4d22bd9f5e7eea5 | 986 | package org.hisrc.jsonix.compilation.mapping.typeinfo.builtin;
import javax.xml.namespace.QName;
import org.hisrc.jscm.codemodel.JSCodeModel;
import org.hisrc.jscm.codemodel.expression.JSAssignmentExpression;
import org.hisrc.jsonix.compilation.mapping.MappingCompiler;
import org.hisrc.jsonix.compilation.mapping.typeinfo.BuiltinLeafInfoCompiler;
public class DecimalTypeInfoCompiler<T, C extends T, O> extends BuiltinLeafInfoCompiler<T, C, O> {
public DecimalTypeInfoCompiler(String name, QName qualifiedName) {
super(name, qualifiedName);
}
@Override
public JSAssignmentExpression createValue(MappingCompiler<T, C> mappingCompiler, String item) {
final JSCodeModel codeModel = mappingCompiler.getCodeModel();
// Hack to make -INF an INF work
if ("-INF".equals(item)) {
return codeModel.globalVariable("Infinity").negative();
} else if ("INF".equals(item)) {
return codeModel.globalVariable("Infinity");
} else {
return codeModel.decimal(item);
}
}
}
| 34 | 98 | 0.77789 |
c986ffbe2df6879a40f3770e3bc537e2548807dc | 1,094 | package io.avaje.jex.jetty;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import java.io.*;
class ContextUtil {
private static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
private static final int BUFFER_MAX = 65536;
static byte[] readBody(HttpServletRequest req) {
try {
final ServletInputStream inputStream = req.getInputStream();
int bufferSize = inputStream.available();
if (bufferSize < DEFAULT_BUFFER_SIZE) {
bufferSize = DEFAULT_BUFFER_SIZE;
} else if (bufferSize > BUFFER_MAX) {
bufferSize = BUFFER_MAX;
}
ByteArrayOutputStream os = new ByteArrayOutputStream(bufferSize);
copy(inputStream, os, bufferSize);
return os.toByteArray();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
static void copy(InputStream in, OutputStream out, int bufferSize) throws IOException {
byte[] buffer = new byte[bufferSize];
int len;
while ((len = in.read(buffer, 0, bufferSize)) > 0) {
out.write(buffer, 0, len);
}
}
}
| 26.047619 | 89 | 0.682815 |
67b51b062ff855e50edcf8710d3fb1eecc8515fd | 942 | package io.t2l.mc.matrix.test.mcserver;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum Server {
CRAFTBUKKIT("CraftBukkit", new MCVersion[]{
MCVersion.V1_13_2,
MCVersion.V1_13_1,
MCVersion.V1_13,
MCVersion.V1_12_2
}),
SPIGOT("Spigot", new MCVersion[]{
MCVersion.V1_13_2,
MCVersion.V1_13_1,
MCVersion.V1_13,
MCVersion.V1_12_2
}),
PAPER("Paperclip", new MCVersion[]{
MCVersion.V1_13_2,
MCVersion.V1_12_2
}),
GLOWSTONE("Glowstone", new MCVersion[]{
MCVersion.V1_12_2
}),
;
public final String serverName;
public final List<MCVersion> versions;
Server(String serverName, MCVersion[] versions) {
this.serverName = serverName;
this.versions = Collections.unmodifiableList(Arrays.asList(versions));
}
}
| 25.459459 | 78 | 0.613588 |
e0680ad67404c36550d83b4d9700ba78c50dad09 | 4,164 | package com.scausum.demo.widget;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ProgressBar;
import com.scausum.ptrlayout.PtrLayout;
import com.scausum.ptrlayout.RefreshView;
/**
* Created by sum on 8/6/16.
*/
public class ProgressRefreshView extends ProgressBar implements RefreshView {
private int height;
private static final int EXIT_ANIM_DURATION = 600;
private DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
private PtrLayout ptrLayout;
private View targetView;
public ProgressRefreshView(Context context) {
super(context);
}
public ProgressRefreshView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProgressRefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (height == 0) {
height = MeasureSpec.getSize(heightMeasureSpec);
ptrLayout = (PtrLayout) getParent();
targetView = ptrLayout.getContentView();
}
}
@Override
public void onPullingDown(float offset) {
// calculate the target view's translationY.
offset = Math.min(height, offset);
offset = Math.max(0, offset);
int translationY = (int) (decelerateInterpolator.getInterpolation(offset / height) * offset);
// move down target view.
targetView.setTranslationY(translationY);
// move down myself
setTranslationY(translationY);
}
@Override
public void onRelease() {
if ((int) getTranslationY() < height) {
startExitAnimation();
} else {
startRefreshingAnimation();
}
}
private void startRefreshingAnimation() {
ptrLayout.notifyRefreshAnimationStart();
}
private void startExitAnimation() {
float crrTranslationY = getTranslationY();
ValueAnimator exitAnimator = ValueAnimator.ofFloat(crrTranslationY, 0);
exitAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// calculate the target view's translationY.
float targetTranslationY = (float) animation.getAnimatedValue();
float ratio = decelerateInterpolator.getInterpolation(targetTranslationY / height);
targetTranslationY = ratio * targetTranslationY;
// move up target view.
targetView.setTranslationY(targetTranslationY);
// move up myself.
setTranslationY(targetTranslationY);
if (targetTranslationY <= 0) {
// notify ptrLayout the refresh animation finished.
ptrLayout.notifyRefreshAnimationStop();
}
}
});
exitAnimator.setDuration(EXIT_ANIM_DURATION * (int) (crrTranslationY) / height);
exitAnimator.start();
}
@Override
public void onRefreshFinished() {
startExitAnimation();
}
@Override
public void autoRefresh() {
ValueAnimator startAnimator = ValueAnimator.ofFloat(0, height);
startAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
private boolean isRelease;
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float offset = (float) animation.getAnimatedValue();
// simulate pulling down
onPullingDown(offset);
if (offset >= height && !isRelease) {
isRelease = true;
onRelease();
}
}
});
startAnimator.setDuration(EXIT_ANIM_DURATION);
startAnimator.start();
}
}
| 33.312 | 101 | 0.64049 |
f0bb517d441ab21f5ce7a2febe3fcad864b54bfb | 1,132 | package com.tiny.socket.socketio.message.base;
import com.tiny.socket.socketio.header.HeaderBase;
public abstract class MessageBase<T> {
protected HeaderBase header;
protected T buffer;
protected MessageBase() {
}
protected MessageBase(HeaderBase header, T buffer) {
this.header = header;
this.buffer = buffer;
}
@Override
public String toString() {
return header.toString();
}
public abstract boolean release();
@SuppressWarnings("rawtypes")
public abstract MessageBase clone();
@SuppressWarnings({"rawtypes", "hiding"})
public <T extends MessageBase> T clone(Class<T> clazz) {
return clazz.cast(clone());
}
@SuppressWarnings("hiding")
public <T extends HeaderBase> T getHeader(Class<T> clazz) {
return clazz.cast(header);
}
public HeaderBase getHeader() {
return header;
}
public void setHeader(HeaderBase header) {
this.header = header;
}
public T getBuffer() {
return buffer;
}
public void setBuffer(T buffer) {
this.buffer = buffer;
}
}
| 20.962963 | 63 | 0.633392 |
f196268fb5ff96c77e7f6b5659f32a8ca6aab61b | 10,395 | // Start of user code Copyright
/*
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Simple
*
* This file is generated by Lyo Designer (https://www.eclipse.org/lyo/)
*/
// End of user code
package org.oasis.oslcop.sysml;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;
import org.eclipse.lyo.oslc4j.core.OSLC4JUtils;
import org.eclipse.lyo.oslc4j.core.exception.OslcCoreApplicationException;
import org.eclipse.lyo.oslc4j.core.annotation.OslcAllowedValue;
import org.eclipse.lyo.oslc4j.core.annotation.OslcDescription;
import org.eclipse.lyo.oslc4j.core.annotation.OslcMemberProperty;
import org.eclipse.lyo.oslc4j.core.annotation.OslcName;
import org.eclipse.lyo.oslc4j.core.annotation.OslcNamespace;
import org.eclipse.lyo.oslc4j.core.annotation.OslcOccurs;
import org.eclipse.lyo.oslc4j.core.annotation.OslcPropertyDefinition;
import org.eclipse.lyo.oslc4j.core.annotation.OslcRdfCollectionType;
import org.eclipse.lyo.oslc4j.core.annotation.OslcRange;
import org.eclipse.lyo.oslc4j.core.annotation.OslcReadOnly;
import org.eclipse.lyo.oslc4j.core.annotation.OslcRepresentation;
import org.eclipse.lyo.oslc4j.core.annotation.OslcResourceShape;
import org.eclipse.lyo.oslc4j.core.annotation.OslcTitle;
import org.eclipse.lyo.oslc4j.core.annotation.OslcValueType;
import org.eclipse.lyo.oslc4j.core.model.AbstractResource;
import org.eclipse.lyo.oslc4j.core.model.Link;
import org.eclipse.lyo.oslc4j.core.model.Occurs;
import org.eclipse.lyo.oslc4j.core.model.OslcConstants;
import org.eclipse.lyo.oslc4j.core.model.Representation;
import org.eclipse.lyo.oslc4j.core.model.ValueType;
import org.eclipse.lyo.oslc4j.core.model.ResourceShape;
import org.eclipse.lyo.oslc4j.core.model.ResourceShapeFactory;
import org.oasis.oslcop.sysml.SysmlDomainConstants;
import org.oasis.oslcop.sysml.Feature;
import org.oasis.oslcop.sysml.IAnnotatingElement;
import org.oasis.oslcop.sysml.SysmlDomainConstants;
import org.oasis.oslcop.sysml.Annotation;
import org.oasis.oslcop.sysml.Comment;
import org.oasis.oslcop.sysml.Conjugation;
import org.oasis.oslcop.sysml.DataType;
import org.oasis.oslcop.sysml.Documentation;
import org.oasis.oslcop.sysml.Element;
import org.oasis.oslcop.sysml.Feature;
import org.oasis.oslcop.sysml.FeatureMembership;
import org.oasis.oslcop.sysml.FeatureTyping;
import org.oasis.oslcop.sysml.Generalization;
import org.oasis.oslcop.sysml.SysmlImport;
import org.oasis.oslcop.sysml.Membership;
import org.oasis.oslcop.sysml.MetadataFeature;
import org.oasis.oslcop.sysml.Multiplicity;
import org.oasis.oslcop.sysml.Namespace;
import org.eclipse.lyo.oslc.domains.Person;
import org.oasis.oslcop.sysml.Redefinition;
import org.oasis.oslcop.sysml.Relationship;
import org.oasis.oslcop.sysml.Subsetting;
import org.oasis.oslcop.sysml.TextualRepresentation;
import org.oasis.oslcop.sysml.Type;
import org.oasis.oslcop.sysml.TypeFeaturing;
// Start of user code imports
// End of user code
// Start of user code preClassCode
// End of user code
// Start of user code classAnnotations
// End of user code
@OslcNamespace(SysmlDomainConstants.ANNOTATINGFEATURE_NAMESPACE)
@OslcName(SysmlDomainConstants.ANNOTATINGFEATURE_LOCALNAME)
@OslcResourceShape(title = "AnnotatingFeature Resource Shape", describes = SysmlDomainConstants.ANNOTATINGFEATURE_TYPE)
public class AnnotatingFeature
extends Feature
implements IAnnotatingFeature, IAnnotatingElement
{
// Start of user code attributeAnnotation:metadataType
// End of user code
private Link metadataType;
// Start of user code attributeAnnotation:ownedMetadata
// End of user code
private Set<Link> ownedMetadata = new HashSet<Link>();
// Start of user code attributeAnnotation:annotatedElement
// End of user code
private Set<Link> annotatedElement = new HashSet<Link>();
// Start of user code attributeAnnotation:annotation
// End of user code
private Set<Link> annotation = new HashSet<Link>();
// Start of user code classAttributes
// End of user code
// Start of user code classMethods
// End of user code
public AnnotatingFeature()
{
super();
// Start of user code constructor1
// End of user code
}
public AnnotatingFeature(final URI about)
{
super(about);
// Start of user code constructor2
// End of user code
}
public static ResourceShape createResourceShape() throws OslcCoreApplicationException, URISyntaxException {
return ResourceShapeFactory.createResourceShape(OSLC4JUtils.getServletURI(),
OslcConstants.PATH_RESOURCE_SHAPES,
SysmlDomainConstants.ANNOTATINGFEATURE_PATH,
AnnotatingFeature.class);
}
public String toString()
{
return toString(false);
}
public String toString(boolean asLocalResource)
{
String result = "";
// Start of user code toString_init
// End of user code
if (asLocalResource) {
result = result + "{a Local AnnotatingFeature Resource} - update AnnotatingFeature.toString() to present resource as desired.";
// Start of user code toString_bodyForLocalResource
// End of user code
}
else {
result = String.valueOf(getAbout());
}
// Start of user code toString_finalize
result = getShortTitle();
// End of user code
return result;
}
public void addOwnedMetadata(final Link ownedMetadata)
{
this.ownedMetadata.add(ownedMetadata);
}
public void addAnnotatedElement(final Link annotatedElement)
{
this.annotatedElement.add(annotatedElement);
}
public void addAnnotation(final Link annotation)
{
this.annotation.add(annotation);
}
// Start of user code getterAnnotation:metadataType
// End of user code
@OslcName("metadataType")
@OslcPropertyDefinition(SysmlDomainConstants.SYSML_NAMSPACE + "metadataType")
@OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.Resource)
@OslcRange({SysmlDomainConstants.DATATYPE_TYPE})
@OslcReadOnly(false)
public Link getMetadataType()
{
// Start of user code getterInit:metadataType
// End of user code
return metadataType;
}
// Start of user code getterAnnotation:ownedMetadata
// End of user code
@OslcName("ownedMetadata")
@OslcPropertyDefinition(SysmlDomainConstants.SYSML_NAMSPACE + "ownedMetadata")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcRange({SysmlDomainConstants.METADATAFEATURE_TYPE})
@OslcReadOnly(false)
public Set<Link> getOwnedMetadata()
{
// Start of user code getterInit:ownedMetadata
// End of user code
return ownedMetadata;
}
// Start of user code getterAnnotation:annotatedElement
// End of user code
@OslcName("annotatedElement")
@OslcPropertyDefinition(SysmlDomainConstants.SYSML_NAMSPACE + "annotatedElement")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcRange({SysmlDomainConstants.ELEMENT_TYPE})
@OslcReadOnly(false)
public Set<Link> getAnnotatedElement()
{
// Start of user code getterInit:annotatedElement
// End of user code
return annotatedElement;
}
// Start of user code getterAnnotation:annotation
// End of user code
@OslcName("annotation")
@OslcPropertyDefinition(SysmlDomainConstants.SYSML_NAMSPACE + "annotation")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcRange({SysmlDomainConstants.ANNOTATION_TYPE})
@OslcReadOnly(false)
public Set<Link> getAnnotation()
{
// Start of user code getterInit:annotation
// End of user code
return annotation;
}
// Start of user code setterAnnotation:metadataType
// End of user code
public void setMetadataType(final Link metadataType )
{
// Start of user code setterInit:metadataType
// End of user code
this.metadataType = metadataType;
// Start of user code setterFinalize:metadataType
// End of user code
}
// Start of user code setterAnnotation:ownedMetadata
// End of user code
public void setOwnedMetadata(final Set<Link> ownedMetadata )
{
// Start of user code setterInit:ownedMetadata
// End of user code
this.ownedMetadata.clear();
if (ownedMetadata != null)
{
this.ownedMetadata.addAll(ownedMetadata);
}
// Start of user code setterFinalize:ownedMetadata
// End of user code
}
// Start of user code setterAnnotation:annotatedElement
// End of user code
public void setAnnotatedElement(final Set<Link> annotatedElement )
{
// Start of user code setterInit:annotatedElement
// End of user code
this.annotatedElement.clear();
if (annotatedElement != null)
{
this.annotatedElement.addAll(annotatedElement);
}
// Start of user code setterFinalize:annotatedElement
// End of user code
}
// Start of user code setterAnnotation:annotation
// End of user code
public void setAnnotation(final Set<Link> annotation )
{
// Start of user code setterInit:annotation
// End of user code
this.annotation.clear();
if (annotation != null)
{
this.annotation.addAll(annotation);
}
// Start of user code setterFinalize:annotation
// End of user code
}
}
| 33.75 | 139 | 0.71342 |
d98c85ae52edc5266cc9d81b1f09cf2926b02746 | 315 | package com.xwc1125.droidui.recyclerview.listener;
import android.view.View;
/**
* item点击事件
* <p>
* Created by xwc1125 on 2017/4/27.
*/
public interface DroidItemClickListener {
/**
* item点击事件
*
* @param view
* @param postion 位置
*/
void onItemClick(View view, int postion);
}
| 16.578947 | 50 | 0.634921 |
68be966a154dc89118ebba889667a63f73f3d01b | 641 | package neo.repository;
import neo.domain.OtherThing;
import neo.domain.Thing;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface ThingRepository extends Neo4jRepository<Thing, Long> {
@Query("MATCH (thing:Thing)-[r:SOME_RELATIONSHIP]-(otherThing:OtherThing) WHERE thing.name={name} RETURN thing, otherThing, r")
Thing findByName(@Param("name") String name);
@Query("MATCH (n) DETACH DELETE n")
void deleteAll();
}
| 33.736842 | 131 | 0.784711 |
072e785ed12a425d5ee30cb9ac4e7fff328c8c9b | 912 | package easy.array.plusone;
/**
* PlusOne
*
* @author john 2020/4/25
*/
public class PlusOne {
class Solution {
public int[] plusOne(int[] digits) {
if (needNewArr(digits)) {
int[] newArr = new int[digits.length + 1];
newArr[0] = 1;
return newArr;
} else {
return carrying(digits, digits.length - 1);
}
}
private boolean needNewArr(int[] digits) {
for (int digit : digits) {
if (digit != 9) {
return false;
}
}
return true;
}
private int[] carrying(int[] digits, int idx) {
digits[idx] += 1;
if (digits[idx] == 10) {
digits[idx] = 0;
carrying(digits, --idx);
}
return digits;
}
}
} | 24 | 59 | 0.416667 |
ef88cdc8ec1a007c154619c71015c4bf90579aa6 | 4,412 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.io.FileSystemUtil;
import com.intellij.util.io.FileAccessorCache;
import com.intellij.util.io.ResourceHandle;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipFile;
public class ZipHandler extends ZipHandlerBase {
private volatile String myCanonicalPathToZip;
private volatile long myFileStamp;
private volatile long myFileLength;
public ZipHandler(@NotNull String path) {
super(path);
}
private static final FileAccessorCache<ZipHandler, ZipFile> ourZipFileFileAccessorCache = new FileAccessorCache<ZipHandler, ZipFile>(20, 10) {
@NotNull
@Override
protected ZipFile createAccessor(ZipHandler handler) throws IOException {
final String canonicalPathToZip = handler.getCanonicalPathToZip();
setFileAttributes(handler, canonicalPathToZip);
return new ZipFile(canonicalPathToZip);
}
@Override
protected void disposeAccessor(@NotNull final ZipFile fileAccessor) throws IOException {
// todo: ZipFile isn't disposable for Java6, replace the code below with 'disposeCloseable(fileAccessor);'
fileAccessor.close();
}
@Override
public boolean isEqual(ZipHandler val1, ZipHandler val2) {
return val1 == val2; // reference equality to handle different jars for different ZipHandlers on the same path
}
};
protected static synchronized void setFileAttributes(@NotNull ZipHandler zipHandler, @NotNull String pathToZip) {
FileAttributes attributes = FileSystemUtil.getAttributes(pathToZip);
zipHandler.myFileStamp = attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP;
zipHandler.myFileLength = attributes != null ? attributes.length : DEFAULT_LENGTH;
}
private static synchronized boolean isSameFileAttributes(@NotNull ZipHandler zipHandler, @NotNull FileAttributes attributes) {
return attributes.lastModified == zipHandler.myFileStamp && attributes.length == zipHandler.myFileLength;
}
@NotNull
private String getCanonicalPathToZip() throws IOException {
String value = myCanonicalPathToZip;
if (value == null) {
myCanonicalPathToZip = value = getFileToUse().getCanonicalPath();
}
return value;
}
@Contract("true -> !null")
protected FileAccessorCache.Handle<ZipFile> getCachedZipFileHandle(boolean createIfNeeded) throws IOException {
try {
FileAccessorCache.Handle<ZipFile> handle = createIfNeeded ? ourZipFileFileAccessorCache.get(this) : ourZipFileFileAccessorCache.getIfCached(this);
// check handle is valid
if (handle != null && getFile() == getFileToUse()) { // files are canonicalized
// IDEA-148458, http://bugs.java.com/view_bug.do?bug_id=4425695, JVM crashes on use of opened ZipFile after it was updated
// Reopen file if the file has been changed
FileAttributes attributes = FileSystemUtil.getAttributes(getCanonicalPathToZip());
if (attributes == null) {
throw new FileNotFoundException(getCanonicalPathToZip());
}
if (isSameFileAttributes(this, attributes)) return handle;
// Note that zip_util.c#ZIP_Get_From_Cache will allow us to have duplicated ZipFile instances without a problem
clearCaches();
handle.release();
handle = ourZipFileFileAccessorCache.get(this);
}
return handle;
}
catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) throw (IOException)cause;
throw e;
}
}
@Override
protected void clearCaches() {
ourZipFileFileAccessorCache.remove(this);
super.clearCaches();
}
@NotNull
protected File getFileToUse() {
return getFile();
}
@Override
protected long getEntryFileStamp() {
return myFileStamp;
}
@Override
@NotNull
protected ResourceHandle<ZipFile> acquireZipHandle() throws IOException {
return getCachedZipFileHandle(true);
}
// also used in Kotlin
public static void clearFileAccessorCache() {
ourZipFileFileAccessorCache.clear();
}
} | 35.580645 | 152 | 0.738214 |
6517ae5d7418e2d8b252c5aa8365d746903792ca | 8,038 | /*
* Copyright 2015 herd contributors
*
* 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.finra.herd.service.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.finra.herd.model.api.xml.BusinessObjectDataKey;
import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitKey;
import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitStatusUpdateRequest;
import org.finra.herd.model.api.xml.BusinessObjectDataStorageUnitStatusUpdateResponse;
import org.finra.herd.model.jpa.StorageUnitEntity;
import org.finra.herd.model.jpa.StorageUnitStatusEntity;
import org.finra.herd.service.AbstractServiceTest;
import org.finra.herd.service.helper.BusinessObjectDataHelper;
import org.finra.herd.service.helper.StorageUnitDaoHelper;
import org.finra.herd.service.helper.StorageUnitHelper;
import org.finra.herd.service.helper.StorageUnitStatusDaoHelper;
/**
* This class tests functionality within the business object data storage unit status service implementation.
*/
public class BusinessObjectDataStorageUnitStatusServiceImplTest extends AbstractServiceTest
{
@Mock
private BusinessObjectDataHelper businessObjectDataHelper;
@InjectMocks
private BusinessObjectDataStorageUnitStatusServiceImpl businessObjectDataStorageUnitStatusServiceImpl;
@Mock
private StorageUnitDaoHelper storageUnitDaoHelper;
@Mock
private StorageUnitHelper storageUnitHelper;
@Mock
private StorageUnitStatusDaoHelper storageUnitStatusDaoHelper;
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
}
@Test
public void testUpdateBusinessObjectDataStorageUnitStatus()
{
// Create a business object data key.
BusinessObjectDataKey businessObjectDataKey =
new BusinessObjectDataKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE, SUBPARTITION_VALUES,
DATA_VERSION);
// Create a business object data storage unit key.
BusinessObjectDataStorageUnitKey businessObjectDataStorageUnitKey =
new BusinessObjectDataStorageUnitKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
SUBPARTITION_VALUES, DATA_VERSION, STORAGE_NAME);
// Create a storage unit entity.
StorageUnitEntity storageUnitEntity = storageUnitDaoTestHelper.createStorageUnitEntity(businessObjectDataStorageUnitKey, STORAGE_UNIT_STATUS);
// Create a storage unit status entity.
StorageUnitStatusEntity storageUnitStatusEntity = storageUnitStatusDaoTestHelper.createStorageUnitStatusEntity(STORAGE_UNIT_STATUS_2);
// Create a business object data storage unit status update request.
BusinessObjectDataStorageUnitStatusUpdateRequest request = new BusinessObjectDataStorageUnitStatusUpdateRequest(STORAGE_UNIT_STATUS_2);
// Create a business object data storage unit status update response.
BusinessObjectDataStorageUnitStatusUpdateResponse expectedResponse =
new BusinessObjectDataStorageUnitStatusUpdateResponse(businessObjectDataStorageUnitKey, STORAGE_UNIT_STATUS_2, STORAGE_UNIT_STATUS);
// Mock the external calls.
when(storageUnitDaoHelper.getStorageUnitEntityByKey(businessObjectDataStorageUnitKey)).thenReturn(storageUnitEntity);
when(storageUnitStatusDaoHelper.getStorageUnitStatusEntity(STORAGE_UNIT_STATUS_2)).thenReturn(storageUnitStatusEntity);
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
// Get the storage unit entity parameter.
StorageUnitEntity storageUnitEntity = (StorageUnitEntity) invocation.getArguments()[0];
StorageUnitStatusEntity storageUnitStatusEntity = (StorageUnitStatusEntity) invocation.getArguments()[1];
// Update storage unit status.
storageUnitEntity.setStatus(storageUnitStatusEntity);
return null;
}
}).when(storageUnitDaoHelper).updateStorageUnitStatus(storageUnitEntity, storageUnitStatusEntity, STORAGE_UNIT_STATUS_2);
when(businessObjectDataHelper.createBusinessObjectDataKeyFromEntity(storageUnitEntity.getBusinessObjectData())).thenReturn(businessObjectDataKey);
when(storageUnitHelper.createBusinessObjectDataStorageUnitKey(businessObjectDataKey, STORAGE_NAME)).thenReturn(businessObjectDataStorageUnitKey);
// Call the method under test.
BusinessObjectDataStorageUnitStatusUpdateResponse result =
businessObjectDataStorageUnitStatusServiceImpl.updateBusinessObjectDataStorageUnitStatus(businessObjectDataStorageUnitKey, request);
// Verify the external calls.
verify(storageUnitHelper).validateBusinessObjectDataStorageUnitKey(businessObjectDataStorageUnitKey);
verify(storageUnitDaoHelper).getStorageUnitEntityByKey(businessObjectDataStorageUnitKey);
verify(storageUnitStatusDaoHelper).getStorageUnitStatusEntity(STORAGE_UNIT_STATUS_2);
verify(storageUnitDaoHelper).updateStorageUnitStatus(storageUnitEntity, storageUnitStatusEntity, STORAGE_UNIT_STATUS_2);
verify(businessObjectDataHelper).createBusinessObjectDataKeyFromEntity(storageUnitEntity.getBusinessObjectData());
verify(storageUnitHelper).createBusinessObjectDataStorageUnitKey(businessObjectDataKey, STORAGE_NAME);
verifyNoMoreInteractionsHelper();
// Validate the results.
assertEquals(expectedResponse, result);
}
@Test
public void testUpdateBusinessObjectDataStorageUnitStatusImplMissingStorageUnitStatus()
{
// Create a business object data storage unit key.
BusinessObjectDataStorageUnitKey businessObjectDataStorageUnitKey =
new BusinessObjectDataStorageUnitKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
SUBPARTITION_VALUES, DATA_VERSION, STORAGE_NAME);
// Try to call the method under test when update request has a blank business object data storage unit status.
try
{
businessObjectDataStorageUnitStatusServiceImpl.updateBusinessObjectDataStorageUnitStatusImpl(businessObjectDataStorageUnitKey,
new BusinessObjectDataStorageUnitStatusUpdateRequest(BLANK_TEXT));
fail();
}
catch (IllegalArgumentException e)
{
assertEquals("A business object data storage unit status must be specified.", e.getMessage());
}
// Verify the external calls.
verify(storageUnitHelper).validateBusinessObjectDataStorageUnitKey(businessObjectDataStorageUnitKey);
verifyNoMoreInteractionsHelper();
}
/**
* Checks if any of the mocks has any interaction.
*/
private void verifyNoMoreInteractionsHelper()
{
verifyNoMoreInteractions(businessObjectDataHelper, storageUnitDaoHelper, storageUnitHelper, storageUnitStatusDaoHelper);
}
}
| 48.421687 | 160 | 0.778427 |
ada2f3cb5ed022e4332905c17071d46cd2556b74 | 2,607 | package net.config;
import net.domain.EmailConfig;
import net.repository.EmailConfigJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class EmailDataSource extends JavaMailSenderImpl {
@Autowired
private EmailConfigJPA emailRepository;
@Autowired
private JavaMailSender mailSender;
// public String DEFAULT_PROJECT = "gvsun";
private static EmailDataSource emailDataSource = null;
private EmailDataSource(){};
private EmailDataSource getInstance(){
if (emailDataSource==null) {
synchronized (EmailDataSource.class){
if (emailDataSource==null){
emailDataSource = new EmailDataSource();
}
}
}
return emailDataSource;
}
/**
* 首次加载初始化emailDataSource对象
*/
@PostConstruct
public void init() {
emailDataSource = this;
emailDataSource.mailSender = this.mailSender;
emailDataSource.emailRepository = this.emailRepository;
}
/**
* @Description: 修改邮件端配置项
* @Author: 徐明杭
* @CreateDate: 2019/5/7 12:04
*/
public void changeDataSource(String project){
try {
EmailConfig email = emailRepository.findByProjectName(project);
emailDataSource.setHost(email.getHost());
emailDataSource.setPassword(email.getPassword());
emailDataSource.setUsername(email.getUsername());
emailDataSource.setPort(email.getPort());
emailDataSource.setDefaultEncoding("utf8");
this.mailSender = emailDataSource;
}catch (NullPointerException e){
System.out.println("=======邮箱参数错误,发送失败============");
}catch (Exception e){
e.printStackTrace();
}
}
public void changeemailDatsource(String host,String password,String username,Integer port){
try {
emailDataSource.setHost(host);
emailDataSource.setPassword(password);
emailDataSource.setUsername(username);
emailDataSource.setPort(port);
emailDataSource.setDefaultEncoding("utf8");
this.mailSender = emailDataSource;
}catch (NullPointerException e){
System.out.println("=======邮箱参数错误,发送失败============");
}catch (Exception e){
e.printStackTrace();
}
}
}
| 30.313953 | 95 | 0.641734 |
affd8bf9dc58f4f1e944638d108c64a46bade8b5 | 1,403 | package model.component.character;
import api.IComponent;
import javafx.beans.property.SimpleObjectProperty;
import utility.SingleProperty;
import java.util.List;
/**
* The class for Attack. Contains a single double property.
*
* @author Roxanne Baker, Rhondu Smithwick
*/
@SuppressWarnings("serial")
public class Attack implements IComponent {
private final SingleProperty<Double> singleProperty = new SingleProperty<>("Attack", 0.0);
/**
* Empty constructor. Has attack at 0.
*/
public Attack () {
}
/**
* Construct with an initial value.
*
* @param attack the initial value
*/
public Attack (double attack) {
setAttack(attack);
}
/**
* Get the attack as a property.
*
* @return the attack property
*/
public SimpleObjectProperty<Double> attackProperty () {
return singleProperty.property1();
}
public double getAttack () {
return attackProperty().get();
}
public void setAttack (double attack) {
attackProperty().set(attack);
}
@Override
public String toString () {
return String.format("Attack: %s", getAttack());
}
@Override
public List<SimpleObjectProperty<?>> getProperties () {
return singleProperty.getProperties();
}
@Override
public void update () {
setAttack(getAttack());
}
} | 21.257576 | 94 | 0.632217 |
61f24962ec30702300abe4766f6f206d8b36df4b | 2,021 | /* file: Parameter.java */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* @ingroup univariate_outlier_detection
* @{
*/
package com.intel.daal.algorithms.univariate_outlier_detection;
import com.intel.daal.utils.*;
import com.intel.daal.services.DaalContext;
/**
* <a name="DAAL-CLASS-ALGORITHMS__UNIVARIATE_OUTLIER_DETECTION__PARAMETER"></a>
* @brief Parameters of the univariate outlier detection algorithm @DAAL_DEPRECATED
*/
@Deprecated
public class Parameter extends com.intel.daal.algorithms.Parameter {
/** @private */
static {
LibUtils.loadLibrary();
}
public Parameter(DaalContext context, long cParameter) {
super(context);
}
/**
* Set initialization procedure for specifying initial parameters of the univariate outlier detection algorithm
* @param initializationProcedure Initialization procedure
*/
public void setInitializationProcedure(InitializationProcedureIface initializationProcedure) {}
/**
* Gets the initialization procedure for setting the initial parameters of the univariate outlier detection algorithm
* @return Initialization procedure
*/
public Object getInitializationProcedure() {
return _initializationProcedure;
}
private Object _initializationProcedure;
}
/** @} */
| 34.254237 | 121 | 0.683325 |
4b4a260c6c1e0c70fa5be13e18f218cce0d522f1 | 711 | package de.cotto.lndmanagej.model.warnings;
public class NodeWarningFixtures {
public static final NodeOnlinePercentageWarning NODE_ONLINE_PERCENTAGE_WARNING =
new NodeOnlinePercentageWarning(51, 14);
public static final NodeOnlinePercentageWarning NODE_ONLINE_PERCENTAGE_WARNING_2 =
new NodeOnlinePercentageWarning(1, 21);
public static final NodeOnlineChangesWarning NODE_ONLINE_CHANGES_WARNING =
new NodeOnlineChangesWarning(123, 7);
public static final NodeOnlineChangesWarning NODE_ONLINE_CHANGES_WARNING_2 =
new NodeOnlineChangesWarning(99, 14);
public static final NodeNoFlowWarning NODE_NO_FLOW_WARNING = new NodeNoFlowWarning(16);
}
| 50.785714 | 91 | 0.787623 |
35777ca8df210d5518f4cd8a89b4b50178a18ff2 | 9,901 | package org.sagebionetworks.bridge.services.backfill;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.longThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.mockito.ArgumentMatcher;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sagebionetworks.bridge.dao.BackfillDao;
import org.sagebionetworks.bridge.dao.DistributedLockDao;
import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException;
import org.sagebionetworks.bridge.models.backfill.BackfillRecord;
import org.sagebionetworks.bridge.models.backfill.BackfillStatus;
import org.sagebionetworks.bridge.models.backfill.BackfillTask;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class AsyncBackfillTemplateTest {
private static final Logger LOG = LoggerFactory.getLogger(AsyncBackfillTemplateTest.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
public void test() throws Exception {
final AsyncBackfillTemplate backfillTemplate = new TestBackfillService();
// Mock lock
final Class<TestBackfillService> lockClazz = TestBackfillService.class;
final String lockObject = TestBackfillService.class.getSimpleName();
final String lock = "lock";
final DistributedLockDao lockDao = mock(DistributedLockDao.class);
when(lockDao.acquireLock(lockClazz, lockObject, TestBackfillService.EXPIRE)).thenReturn(lock);
backfillTemplate.setDistributedLockDao(lockDao);
// Mock task and backfill dao
final String taskName = "taskName";
final String user = "user";
final long timestamp = DateTime.now(DateTimeZone.UTC).getMillis();
final String taskId = "taskId";
final BackfillTask backfillTask = createBackfillTask(taskName, user, timestamp, taskId, BackfillStatus.SUBMITTED);
BackfillDao backfillDao = mock(BackfillDao.class);
when(backfillDao.createTask(taskName, user)).thenReturn(backfillTask);
backfillTemplate.setBackfillDao(backfillDao);
// Mock callback
BackfillCallback callback = mock(BackfillCallback.class);
backfillTemplate.backfill(user, taskName, callback);
Thread.sleep(200L);
// Verify callback
verify(callback, times(1)).start(backfillTask);
verify(callback, times(2)).newRecords(any(BackfillRecord.class));
verify(callback, times(1)).done();
// Verify lock
verify(lockDao, times(1)).acquireLock(lockClazz, lockObject, TestBackfillService.EXPIRE);
verify(lockDao, times(1)).releaseLock(lockClazz, lockObject, lock);
// Verify backfill dao
verify(backfillDao, times(1)).createTask(taskName, user);
verify(backfillDao, times(1)).updateTaskStatus(taskId, BackfillStatus.IN_PROCESS);
verify(backfillDao, times(1)).updateTaskStatus(taskId, BackfillStatus.COMPLETED);
}
@Test
public void testWithConcurrentModificationException() throws Exception {
final AsyncBackfillTemplate backfillTemplate = new TestBackfillService();
// Mock lock
final Class<TestBackfillService> lockClazz = TestBackfillService.class;
final String lockObject = TestBackfillService.class.getSimpleName();
final DistributedLockDao lockDao = mock(DistributedLockDao.class);
when(lockDao.acquireLock(lockClazz, lockObject, TestBackfillService.EXPIRE))
.thenThrow(ConcurrentModificationException.class);
backfillTemplate.setDistributedLockDao(lockDao);
// Mock task and backfill dao
final String taskName = "taskName";
final String user = "user";
final long timestamp = DateTime.now(DateTimeZone.UTC).getMillis();
final String taskId1 = "taskId1";
final BackfillTask task1 = createBackfillTask(taskName, user, timestamp, taskId1, BackfillStatus.COMPLETED);
final String taskId2 = "taskId2";
final BackfillTask task2 = createBackfillTask(taskName, user, timestamp, taskId2, BackfillStatus.IN_PROCESS);
BackfillDao backfillDao = mock(BackfillDao.class);
Answer<List<BackfillTask>> tasks = new Answer<List<BackfillTask>>() {
@Override
public List<BackfillTask> answer(InvocationOnMock invocation) throws Throwable {
return Arrays.asList(task1, task2);
}
};
when(backfillDao.getTasks(eq(taskName), anyLong())).thenAnswer(tasks);
backfillTemplate.setBackfillDao(backfillDao);
// Mock
BackfillRecordFactory recordFactory = mock(BackfillRecordFactory.class);
BackfillRecord record = new BackfillRecord() {
@Override
public String getTaskId() {
return taskId2;
}
@Override
public long getTimestamp() {
return task2.getTimestamp();
}
@Override
public JsonNode toJsonNode() {
return MAPPER.createObjectNode();
}
};
when(recordFactory.createOnly(any(BackfillTask.class), any(String.class))).thenReturn(record);
backfillTemplate.setBackfillRecordFactory(recordFactory);
// Do backfill
final long beforeBackfill = DateTime.now(DateTimeZone.UTC).getMillis();
BackfillCallback callback = mock(BackfillCallback.class);
backfillTemplate.backfill(user, taskName, callback);
Thread.sleep(200L);
final long afterBackfill = DateTime.now(DateTimeZone.UTC).getMillis();
// Verify lock
verify(lockDao, times(1)).acquireLock(lockClazz, lockObject, TestBackfillService.EXPIRE);
// Verify backfill dao
ArgumentMatcher<Long> sinceMatcher = new ArgumentMatcher<Long>() {
@Override
public boolean matches(Long since) {
long expireInMillis = TestBackfillService.EXPIRE * 1000L;
// Make sure the time point after which we look for the list of backfill tasks
// goes back for the duration of lock expiration
long lower = beforeBackfill - expireInMillis;
long upper = afterBackfill - expireInMillis;
if (lower <= since && since <= upper) {
return true;
} else {
LOG.error("getTasks() expected to be called with a time between " + lower + " and " + upper +
", actual=" + since);
return false;
}
}
};
verify(backfillDao, times(1)).getTasks(eq(taskName), longThat(sinceMatcher));
verify(backfillDao, times(1)).getRecordCount(taskId2);
// Verify callback
verify(callback, times(1)).newRecords(record);
}
@Test
public void testFailure() throws Exception {
final AsyncBackfillTemplate testBackfillService = new TestBackfillService();
final AsyncBackfillTemplate backfillTemplate = spy(testBackfillService);
when(backfillTemplate.getLockExpireInSeconds()).thenReturn(TestBackfillService.EXPIRE);
// Mock lock
final Class<TestBackfillService> lockClazz = TestBackfillService.class;
final String lockObject = TestBackfillService.class.getSimpleName();
final String lock = "lock";
final DistributedLockDao lockDao = mock(DistributedLockDao.class);
when(lockDao.acquireLock(lockClazz, lockObject, TestBackfillService.EXPIRE)).thenReturn(lock);
backfillTemplate.setDistributedLockDao(lockDao);
// Mock task and backfill dao
final String taskName = "taskName";
final String user = "user";
final long timestamp = DateTime.now(DateTimeZone.UTC).getMillis();
final String taskId = "taskId";
final BackfillTask backfillTask = createBackfillTask(taskName, user, timestamp, taskId, BackfillStatus.SUBMITTED);
BackfillDao backfillDao = mock(BackfillDao.class);
when(backfillDao.createTask(taskName, user)).thenReturn(backfillTask);
backfillTemplate.setBackfillDao(backfillDao);
// Mock a failure
BackfillCallback callback = mock(BackfillCallback.class);
doThrow(RuntimeException.class).when(backfillTemplate).doBackfill(
any(BackfillTask.class), any(BackfillCallback.class));
backfillTemplate.backfill(user, taskName, callback);
Thread.sleep(200L);
// Verify
verify(backfillDao, times(1)).updateTaskStatus(taskId, BackfillStatus.FAILED);
}
private BackfillTask createBackfillTask(final String taskName, final String user, final long timestamp,
final String taskId, final BackfillStatus status) {
return new BackfillTask() {
@Override
public String getId() {
return taskId;
}
@Override
public long getTimestamp() {
return timestamp;
}
@Override
public String getName() {
return taskName;
}
@Override
public String getUser() {
return user;
}
@Override
public String getStatus() {
return status.name();
}
};
}
}
| 42.861472 | 122 | 0.674578 |
a30443ca56de77b540e428d5fdd5baedc54c9a54 | 704 | package com.packtpub.book.ch05.springsecurity.model;
import lombok.*;
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Movie {
private Long id;
private String title;
private String genre;
public Movie(Long id, String title, String genre) {
super();
this.id = id;
this.title = title;
this.genre = genre;
}
public Movie( ) {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}
| 13.283019 | 52 | 0.670455 |
ff8eb532f9fe3e0bca416143d0b8a292c3be95e2 | 11,298 | package ssangyong.dclass.seoulexploration.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kakao.kakaolink.KakaoLink;
import com.kakao.kakaolink.KakaoTalkLinkMessageBuilder;
import java.util.ArrayList;
import ssangyong.dclass.seoulexploration.R;
import ssangyong.dclass.seoulexploration.data.ServerGetImage;
import ssangyong.dclass.seoulexploration.data.TreasureDAO;
import ssangyong.dclass.seoulexploration.data.TreasureDTO;
import ssangyong.dclass.seoulexploration.temp.IconBadge;
/***********************************
* * 작성자 : 김훈영
* * 기 능 : 보물리스트
* * 수정내용 : 카카오톡연동추가헸습니다. -보현-
* * 버 전 :
* **********************************/
public class TreasureListActivity extends AppCompatActivity implements View.OnClickListener {
boolean isPageOpen = false;
Animation translateLeftAnim;
Animation translateRightAnim;
//슬라이딩으로 보여줄 페이지
LinearLayout slidingMenuPage;
Button backBtn;
TextView kakaoShareBtn;
ArrayList<TreasureDTO> list;
GridView gridView;
String note,name,num;
Context context;
String medalUrl = "";
int mainMedal = 0;
Integer[] ImageID={R.drawable.g1j, R.drawable.g2j, R.drawable.g3j, R.drawable.g4j, R.drawable.g5j, R.drawable.g6j, R.drawable.g7j, R.drawable.g8j, R.drawable.g9j, R.drawable.g10j,
R.drawable.g11j, R.drawable.g12j, R.drawable.g13j, R.drawable.g14j, R.drawable.g15j, R.drawable.g16j, R.drawable.g17j, R.drawable.g18j, R.drawable.g19j, R.drawable.g20j,
R.drawable.g21j, R.drawable.g22j, R.drawable.g23j, R.drawable.g24j, R.drawable.g25j, R.drawable.g26j, R.drawable.g27j, R.drawable.g28j, R.drawable.g29j, R.drawable.g30j,
R.drawable.g31j, R.drawable.g32j, R.drawable.g33j, R.drawable.g34j, R.drawable.g35j, R.drawable.g36j, R.drawable.g37j, R.drawable.g38j, R.drawable.g39j, R.drawable.g40j,
R.drawable.g41j, R.drawable.g42j, R.drawable.g43j, R.drawable.g44j, R.drawable.g45j, R.drawable.g46j, R.drawable.g47j, R.drawable.g48j, R.drawable.g49j, R.drawable.g50j,
R.drawable.g51j, R.drawable.g52j, R.drawable.g53j, R.drawable.g54j, R.drawable.g55j, R.drawable.g56j, R.drawable.g57j, R.drawable.g58j, R.drawable.g59j, R.drawable.g60j,
R.drawable.g61j, R.drawable.g62j, R.drawable.g63j, R.drawable.g64j, R.drawable.g65j, R.drawable.g66j, R.drawable.g67j, R.drawable.g68j, R.drawable.g69j, R.drawable.g70j,
R.drawable.g71j, R.drawable.g72j, R.drawable.g73j, R.drawable.g74j, R.drawable.g75j, R.drawable.g76j, R.drawable.g77j, R.drawable.g78j, R.drawable.g79j, R.drawable.g80j,
R.drawable.g81j, R.drawable.g82j, R.drawable.g83j, R.drawable.g84j, R.drawable.g85j, R.drawable.g86j, R.drawable.g87j, R.drawable.g88j, R.drawable.g89j, R.drawable.g90j,
R.drawable.g91j, R.drawable.g92j, R.drawable.g93j, R.drawable.g94j, R.drawable.g95j, R.drawable.g96j, R.drawable.g97j, R.drawable.g98j, R.drawable.g99j, R.drawable.g100j,
R.drawable.g101j, R.drawable.g102j, R.drawable.g103j, R.drawable.g104j, R.drawable.g105j, R.drawable.g106j, R.drawable.g107j, R.drawable.g108j, R.drawable.g109j, R.drawable.g110j,
R.drawable.g111j, R.drawable.g112j, R.drawable.g113j, R.drawable.g114j, R.drawable.g115j};
@Override
public void onClick(View v) {
//카카오톡 연동
if (v == kakaoShareBtn) {
try {
final KakaoLink kakaoLink = KakaoLink.getKakaoLink(this);
final KakaoTalkLinkMessageBuilder builder = kakaoLink.createKakaoTalkLinkMessageBuilder();
builder.addAppButton("같이 탐험하러 가기");
builder.addText("[서울 유적 탐험가]\n\n나 우리나라 보물 "+ list.size()+"개 있다~!!\n부럽지??!! 너도 할 수 있는데 같이 할래?!");
builder.addImage(medalUrl, 300, 330);
kakaoLink.sendMessage(builder, this);
}catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IconBadge.updateIconBadge(this, 0);
//홈버튼 보여주기
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menuicon);
//슬라이드메뉴 res 왼쪽 오른쪽 값 애니메이션 객체에 넣어주기
translateLeftAnim = AnimationUtils.loadAnimation(this, R.anim.menu_left);
translateRightAnim = AnimationUtils.loadAnimation(this, R.anim.menu_right);
//슬라이드메뉴페이지
slidingMenuPage = (LinearLayout) findViewById(R.id.slidingMenuPage);
backBtn = (Button) findViewById(R.id.backBtn);
TreasureDAO dao = new TreasureDAO(this);
list = dao.selectGain();
if(list.size()==0) {
Toast.makeText(this, "획득한 보물이 없습니다. ", Toast.LENGTH_SHORT).show();
}
setContentView(R.layout.activity_treasure_list);
gridView = (GridView) findViewById((R.id.gridView1));
TreasueAdapter gAdapter = new TreasueAdapter(this);
for(int i=0;i<list.size();i++) {
gAdapter.addItem(list.get(i));
}
gridView.setAdapter(gAdapter);
// 감사패 가져오기
TreasureDAO treasureDAO = new TreasureDAO(this);
list=treasureDAO.selectGain();
mainMedal=list.size();
//감사패 조건
if(mainMedal<2){
// 브론즈
medalUrl = "http://xml.namoolab.com/image/class/medal_tree.png";
}
else if(mainMedal>=2 && mainMedal<4){
// 실버
medalUrl = "http://xml.namoolab.com/image/class/medal_stone.png";
}
else if(mainMedal>=4 && mainMedal<6){
// 골드
medalUrl = "http://xml.namoolab.com/image/class/medal_bronze.png";
}
else if(mainMedal>=6 && mainMedal<8){
// 다이아몬드
medalUrl = "http://xml.namoolab.com/image/class/medal_silver.png";
}
else if(mainMedal>=8){
// 마스터
medalUrl = "http://xml.namoolab.com/image/class/medal_gold.png";
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem actionViewItem = menu.findItem(R.id.talkShareActionBtn);
View v = MenuItemCompat.getActionView(actionViewItem);
kakaoShareBtn = (TextView) v.findViewById(R.id.kakaoShareBtn);
kakaoShareBtn.setOnClickListener(this);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.treasure_list, menu);
return true;
}
public class TreasueAdapter extends BaseAdapter {
Context context;
public TreasueAdapter(Context context) {
this.context = context;
}
ArrayList<TreasureDTO> items = new ArrayList<>();
public void addItem(TreasureDTO item) {
items.add(item);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ImageView imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(400,400));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(ImageID[position]);
//그리드뷰에 띄울 이미지
final View dialogView = View.inflate(TreasureListActivity.this, R.layout.activity_treasure_list_dialog, null);
final ImageView ivPoster = (ImageView) dialogView.findViewById(R.id.ivPoster);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TreasureDTO curItem = items.get(position);
note = curItem.getNote();
name = curItem.getName();
num= curItem.getNumber();
View dialogView = View.inflate(TreasureListActivity.this, R.layout.activity_treasure_list_dialog, null);
AlertDialog.Builder dlg = new AlertDialog.Builder(TreasureListActivity.this);
ImageView ivPoster = (ImageView) dialogView.findViewById(R.id.ivPoster);
ivPoster.setImageResource(ImageID[position]);
TextView textView=(TextView) dialogView.findViewById(R.id.textView);
textView.setText(note);
dlg.setTitle(name);
dlg.setIcon(R.drawable.logo);
dlg.setView(dialogView);
dlg.setNegativeButton("닫기", null);
dlg.show();
}
});
return imageView;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//홈버튼을 선택하면
if(id == android.R.id.home){
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.startAnimation(translateLeftAnim);
slidingMenuPage.setVisibility(View.INVISIBLE);
backBtn.setVisibility(View.INVISIBLE);
}
else{ //페이지가 닫혀있으면
isPageOpen = true;
slidingMenuPage.startAnimation(translateRightAnim);
slidingMenuPage.setVisibility(View.VISIBLE);
backBtn.setVisibility(View.VISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
public void onClickTourInfoBtn(View v) { //관광 안내소 버튼
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.setVisibility(View.INVISIBLE);
}
Intent intent = new Intent(getApplicationContext(),TourInfoActivity.class);
startActivity(intent);
}
public void onClickInfoBtn(View v) { //출처 안내 버튼
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.setVisibility(View.INVISIBLE);
}
Intent intent = new Intent(getApplicationContext(),InfoActivity.class);
startActivity(intent);
}
public void onClickBack(View v){ //다른 곳 눌러도 닫히게
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.startAnimation(translateLeftAnim);
slidingMenuPage.setVisibility(View.INVISIBLE);
backBtn.setVisibility(View.INVISIBLE);
}
}
} | 36.095847 | 191 | 0.635157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.