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
|
---|---|---|---|---|---|
69d4d85dab608c6dcc595d400e18054274671901 | 980 | /*
* Copyright (c) 2008-2013 Haulmont. All rights reserved.
* Use is subject to license terms, see http://www.cuba-platform.com/license for details.
*/
package com.haulmont.workflow.core.app;
import com.haulmont.workflow.core.entity.SendingSms;
import java.util.List;
/**
* @author novikov
* @version $Id$
*/
public interface SmsSenderAPI {
String NAME = "workflow_SmsSender";
SendingSms sendSmsSync(SendingSms sendingSms);
void scheduledSendSms(SendingSms sendingSms);
SendingSms sendSmsAsync(String phone, String addressee, String message);
SendingSms sendSmsAsync(SendingSms sendingSms);
List<SendingSms> sendSmsAsync(List<SendingSms> sendingSmsList);
SendingSms checkStatus(SendingSms sendingSms);
void scheduledCheckStatusSms(SendingSms sendingSms);
SmsProvider getSmsProvider();
void setSmsProviderClassName(String value);
void setUseDefaultSmsSending(boolean value);
}
| 24.5 | 90 | 0.726531 |
dca493112da40cab740b70735144147f022de611 | 5,905 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* 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.guvnor.asset.management.client.editors.release;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import org.guvnor.asset.management.client.i18n.Constants;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.FormGroup;
import org.gwtbootstrap3.client.ui.Input;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.workbench.events.NotificationEvent;
@Dependent
public class ReleaseConfigurationViewImpl extends Composite implements ReleaseConfigurationPresenter.ReleaseConfigurationView {
interface Binder
extends UiBinder<Widget, ReleaseConfigurationViewImpl> {
}
private static Binder uiBinder = GWT.create( Binder.class );
@Inject
private PlaceManager placeManager;
private ReleaseConfigurationPresenter presenter;
@UiField
public ListBox chooseRepositoryBox;
@UiField
public ListBox chooseBranchBox;
@UiField
public Button releaseButton;
@UiField
public TextBox userNameText;
@UiField
public Input passwordText;
@UiField
public TextBox serverURLText;
@UiField
public CheckBox deployToRuntimeCheck;
@UiField
public TextBox versionText;
@UiField
public TextBox currentVersionText;
@UiField
public FormGroup deployToRuntimeRow;
@UiField
public FormGroup usernameRow;
@UiField
public FormGroup passwordRow;
@UiField
public FormGroup serverURLRow;
@Inject
private Event<NotificationEvent> notification;
private Constants constants = GWT.create( Constants.class );
public ReleaseConfigurationViewImpl() {
initWidget( uiBinder.createAndBindUi( this ) );
}
@Override
public void init( final ReleaseConfigurationPresenter presenter ) {
this.presenter = presenter;
currentVersionText.setReadOnly( true );
presenter.loadServerSetting();
chooseRepositoryBox.addChangeHandler( new ChangeHandler() {
@Override
public void onChange( ChangeEvent event ) {
String value = chooseRepositoryBox.getSelectedValue();
presenter.loadBranches( value );
presenter.loadRepositoryStructure( value );
}
} );
presenter.loadRepositories();
}
public void showHideDeployToRuntimeSection( boolean show ) {
if ( show ) {
deployToRuntimeRow.setVisible( true );
usernameRow.setVisible( true );
passwordRow.setVisible( true );
serverURLRow.setVisible( true );
// by default deploy to runtime inputs are disabled
userNameText.setEnabled( false );
passwordText.setEnabled( false );
serverURLText.setEnabled( false );
deployToRuntimeCheck.addValueChangeHandler( new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange( ValueChangeEvent<Boolean> event ) {
if ( event.getValue() ) {
userNameText.setEnabled( true );
passwordText.setEnabled( true );
serverURLText.setEnabled( true );
} else {
userNameText.setEnabled( false );
passwordText.setEnabled( false );
serverURLText.setEnabled( false );
}
}
} );
} else {
deployToRuntimeRow.setVisible( false );
usernameRow.setVisible( false );
passwordRow.setVisible( false );
serverURLRow.setVisible( false );
}
}
@UiHandler("releaseButton")
public void releaseButton( ClickEvent e ) {
presenter.releaseProject( chooseRepositoryBox.getSelectedValue(), chooseBranchBox.getSelectedValue(),
userNameText.getText(), passwordText.getText(), serverURLText.getText(), deployToRuntimeCheck.getValue(), versionText.getText() );
}
@Override
public void displayNotification( String text ) {
notification.fire( new NotificationEvent( text ) );
}
public ListBox getChooseBranchBox() {
return chooseBranchBox;
}
@Override
public ListBox getChooseRepositoryBox() {
return chooseRepositoryBox;
}
@Override
public TextBox getCurrentVersionText() {
return currentVersionText;
}
@Override
public TextBox getVersionText() {
return versionText;
}
}
| 30.595855 | 146 | 0.679763 |
ada20e99d87d175fef71e0a98126e7c3b553baf1 | 26 | public class Version55 {
} | 13 | 24 | 0.769231 |
45674e825530ae82a473c24f42bab023df645de5 | 2,405 | package net.powermatcher.api;
import net.powermatcher.api.data.Bid;
import net.powermatcher.api.data.Price;
import net.powermatcher.api.messages.PriceUpdate;
/**
* {@link AgentEndpoint} defines the interface for classes that can receive a {@link PriceUpdate} and send a {@link Bid}
* , based on the {@link Price} of that {@link PriceUpdate}. An {@link AgentEndpoint} can be linked with zero or one
* {@link MatcherEndpoint} instances. These are linked by a {@link Session}.
*
* @author FAN
* @version 2.1
*/
public interface AgentEndpoint
extends Agent {
/**
* The {@link Status} object describes the current status and configuration of an {@link AgentEndpoint}. This status
* can be queried through the {@link AgentEndpoint#getStatus()} method and will give a snapshot of the state at that
* time.
*/
interface Status
extends Agent.Status {
/**
* @return the current {@link Session} for the connection from this {@link AgentEndpoint} to the
* {@link MatcherEndpoint}.
* @throws IllegalStateException
* when the agent is not connected (see {@link #isConnected()})
*/
Session getSession();
}
/**
* @return the id of the desired parent {@link Agent}.
*/
String getDesiredParentId();
@Override
Status getStatus();
/**
* Connects this {@link AgentEndpoint} instance to a {@link MatcherEndpoint}.
*
* @param session
* the {@link Session} that will link this {@link AgentEndpoint} with a {@link MatcherEndpoint}.
*/
void connectToMatcher(Session session);
/**
* Notifies the {@link Agent} that this {@link AgentEndpoint} instance is disconnected from the
* {@link MatcherEndpoint}.
*
* @param session
* the {@link Session} that used to link the {@link MatcherEndpoint} with this {@link AgentEndpoint}.
*/
void matcherEndpointDisconnected(Session session);
/**
* Called by {@link MatcherEndpoint} via the {@link Session} to update the {@link Price} used by this
* {@link AgentEndpoint} instance.
*
* @param priceUpdate
* The new {@link Price}, wrapped in a {@link PriceUpdate}, along with the id of the {@link Bid} it was
* based on.
*/
void handlePriceUpdate(PriceUpdate priceUpdate);
}
| 34.855072 | 120 | 0.640333 |
9c200fd7c07c3c450e026d34572bfea66bbeaf2f | 338 | package annotations.ex1;
/**
* Simple test of a Car.
*/
public class CarTest {
public static void main(String... args) throws Exception {
Car car = new Car("1234");
if (car.initEngine())
System.out.println(">>> COOL! It started!");
else
System.out.println(">>> " + car);
}
}
| 17.789474 | 62 | 0.54142 |
dd52fb3a2a95d8c6e380c330768592f3f9f418af | 4,098 | /*
* Copyright (C) 2014 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.internal.codegen.binding;
import static dagger.internal.codegen.base.Suppliers.memoize;
import static dagger.internal.codegen.xprocessing.XElements.isAbstract;
import static dagger.internal.codegen.xprocessing.XElements.isStatic;
import dagger.internal.codegen.collect.ImmutableSet;
import dagger.internal.codegen.collect.Sets;
import dagger.spi.model.BindingKind;
import dagger.spi.model.DependencyRequest;
import dagger.spi.model.Scope;
import java.util.Optional;
import java.util.function.Supplier;
/**
* An abstract type for classes representing a Dagger binding. Particularly, contains the element
* that generated the binding and the {@code DependencyRequest} instances that are required to
* satisfy the binding, but leaves the specifics of the <i>mechanism</i> of the binding to the
* subtypes.
*/
public abstract class Binding extends BindingDeclaration {
/**
* Returns {@code true} if using this binding requires an instance of the {@code
* #contributingModule()}.
*/
public boolean requiresModuleInstance() {
return contributingModule().isPresent()
&& bindingElement().isPresent()
&& !isAbstract(bindingElement().get())
&& !isStatic(bindingElement().get());
}
/**
* Returns {@code true} if this binding may provide {@code null} instead of an instance of {@code
* #key()}. Nullable bindings cannot be requested from {@code DependencyRequest#isNullable()
* non-nullable dependency requests}.
*/
public abstract boolean isNullable();
/** The kind of binding this instance represents. */
public abstract BindingKind kind();
/** The {@code BindingType} of this binding. */
public abstract BindingType bindingType();
/** The {@code FrameworkType} of this binding. */
public final FrameworkType frameworkType() {
return FrameworkType.forBindingType(bindingType());
}
/**
* The explicit set of {@code DependencyRequest dependencies} required to satisfy this binding as
* defined by the user-defined injection sites.
*/
public abstract ImmutableSet<DependencyRequest> explicitDependencies();
/**
* The set of {@code DependencyRequest dependencies} that are added by the framework rather than a
* user-defined injection site. This returns an unmodifiable set.
*/
public ImmutableSet<DependencyRequest> implicitDependencies() {
return ImmutableSet.of();
}
private final Supplier<ImmutableSet<DependencyRequest>> dependencies =
memoize(
() -> {
ImmutableSet<DependencyRequest> implicitDependencies = implicitDependencies();
return ImmutableSet.copyOf(
implicitDependencies.isEmpty()
? explicitDependencies()
: Sets.union(implicitDependencies, explicitDependencies()));
});
/**
* The set of {@code DependencyRequest dependencies} required to satisfy this binding. This is the
* union of {@code #explicitDependencies()} and {@code #implicitDependencies()}. This returns an
* unmodifiable set.
*/
public final ImmutableSet<DependencyRequest> dependencies() {
return dependencies.get();
}
/**
* If this binding's key's type parameters are different from those of the {@code
* #bindingTypeElement()}, this is the binding for the {@code #bindingTypeElement()}'s unresolved
* type.
*/
public abstract Optional<? extends Binding> unresolved();
public Optional<Scope> scope() {
return Optional.empty();
}
}
| 36.589286 | 100 | 0.719863 |
c2a4badff3a998fcd18c0d547de60bd133f76709 | 2,694 | package us.ihmc.robotics.stateMachine.old.conditionBasedStateMachine;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import us.ihmc.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.robotics.stateMachine.old.conditionBasedStateMachine.SimpleState;
import us.ihmc.robotics.stateMachine.old.conditionBasedStateMachine.StateMachine;
import us.ihmc.robotics.trajectories.providers.SettableDoubleProvider;
public class SimpleStateTest
{
@ContinuousIntegrationTest(estimatedDuration = 0.0)
@Test(timeout = 30000)
public void testSimpleStateMachine()
{
SettableDoubleProvider timeProvider = new SettableDoubleProvider();
YoVariableRegistry registry = new YoVariableRegistry("SimpleStateMachine");
StateMachine<StateList> stateMachine = new StateMachine<StateList>("SimpleStateMachine", "switchTime", StateList.class, timeProvider, registry);
SimpleState<StateList> stateStart = new SimpleState<StateList>(StateList.START, StateList.ONE)
{
@Override
public void doAction()
{
if (getTimeInCurrentState() > 1.0)
this.transitionToDefaultNextState();
}
};
stateMachine.addState(stateStart);
SimpleState<StateList> stateOne = new SimpleState<StateList>(StateList.ONE, StateList.TWO)
{
@Override
public void doAction()
{
if (getTimeInCurrentState() > 2.0)
this.transitionToDefaultNextState();
}
};
stateMachine.addState(stateOne);
SimpleState<StateList> stateTwo = new SimpleState<StateList>(StateList.TWO, StateList.END)
{
@Override
public void doAction()
{
if (getTimeInCurrentState() > 3.0)
this.transitionToDefaultNextState();
}
};
stateMachine.addState(stateTwo);
SimpleState<StateList> stateEnd = new SimpleState<StateList>(StateList.END)
{
@Override
public void doAction()
{
}
};
stateMachine.addState(stateEnd);
assertEquals(stateStart, stateMachine.getCurrentState());
stateMachine.setCurrentState(StateList.START);
assertEquals(stateMachine.getCurrentState(), stateStart);
while (timeProvider.getValue() < 10.0)
{
stateMachine.doAction();
stateMachine.checkTransitionConditions();
timeProvider.add(0.01);
}
assertEquals(stateMachine.getCurrentState(), stateEnd);
}
private enum StateList
{
START, ONE, TWO, END;
}
}
| 29.282609 | 150 | 0.679287 |
faab8e9d9e44a74598629014ee334bd895f2f71e | 7,137 | package com.rest;
/*
* #%L
* Gateway
* %%
* Copyright (C) 2015 Powered by Sergey
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.dto.GroupRequestDto;
import com.dto.InvitationRequestDto;
import com.dto.ProjectRequestDto;
import com.entity.*;
import com.repository.*;
import com.utils.SecurityContextReader;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
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 javax.validation.Valid;
/**
* Created by aautushk on 9/13/2015.
*/
@Component
@RestController
@RequestMapping("/gateway")
public class ProjectRest {
private ModelMapper modelMapper = new ModelMapper(); //read more at http://modelmapper.org/user-manual/
@Autowired
public IProjectRepository projectRepository;
@Autowired
public IProjectUserRepository projectUserRepository;
@Autowired
public IAuthorityRepository authorityRepository;
@Autowired
public ITranslationRepository translationRepository;
@Autowired
public IGroupRepository groupRepository;
@Autowired
public IProjectGroupRepository projectGroupRepository;
@Autowired
public IInvitationRepository invitationRepository;
@Autowired
public IInvitationGroupRepository invitationGroupRepository;
public SecurityContextReader securityContextReader = new SecurityContextReader();
@RequestMapping(value = "/createProject", method = RequestMethod.POST)
@Transactional
public ResponseEntity createProject(@Valid @RequestBody ProjectRequestDto projectRequestDto) {
ProjectEntity project = new ProjectEntity();
projectRepository.save(project);//project is created
TranslationEntity translationEntity = new TranslationEntity();
translationEntity.setParentGuid(project.getProjectGuid());
translationEntity.setParentEntity("Project");
translationEntity.setField("description");
translationEntity.setLanguage(LocaleContextHolder.getLocale().getDisplayLanguage());
translationEntity.setContent(projectRequestDto.getDescription());
translationRepository.save(translationEntity);//project description translation is created
ProjectUserEntity projectUserEntity = new ProjectUserEntity();
projectUserEntity.setUsername(securityContextReader.getUsername());
projectUserRepository.save(projectUserEntity);//project is assigned to its author
AuthorityEntity authorityEntity = new AuthorityEntity();
authorityEntity.setUsername(securityContextReader.getUsername());
authorityEntity.setAuthority(project.getProjectGuid() + "_admin");
authorityRepository.save(authorityEntity);//admin role is assigned to the project author
for(GroupRequestDto groupRequestDto : projectRequestDto.getGroups()){
GroupEntity groupEntity = new GroupEntity();
groupEntity.setGroupName(groupRequestDto.getGroupName());
if(groupRequestDto.getGroupGuid() != ""){
groupEntity.setGroupGuid(groupRequestDto.getGroupGuid());
}
groupRepository.save(groupEntity);//group is created
ProjectGroupEntity projectGroupEntity = new ProjectGroupEntity();
projectGroupEntity.setProjectGuid(project.getProjectGuid());
projectGroupEntity.setGroupGuid(groupEntity.getGroupGuid());
projectGroupRepository.save(projectGroupEntity);//group is assigned to the project
}
for(InvitationRequestDto invitation : projectRequestDto.getInvitations()){
InvitationEntity invitationEntity = new InvitationEntity();
invitationEntity.setRecipientEmail(invitation.getRecipientEmail());
invitationEntity.setProjectGuid(project.getProjectGuid());
invitationEntity.setAuthority(invitation.getAuthority());
invitationEntity.setIsInvitationAccepted(false);
invitationRepository.save(invitationEntity);//invitation is created
for(GroupRequestDto groupRequestDto : invitation.getGroups()){
InvitationGroupEntity invitationGroupEntity = new InvitationGroupEntity();
invitationGroupEntity.setInvitationGuid(invitationEntity.getInvitationGuid());
invitationGroupEntity.setGroupGuid(groupRequestDto.getGroupGuid());
invitationGroupRepository.save(invitationGroupEntity);//group is assigned to the invitation
}
}
return new ResponseEntity(HttpStatus.OK);
}
// private ProjectResponseDto convertToResponseDto(ProjectEntity project) {
// ProjectResponseDto projectResponseDto = modelMapper.map(project, ProjectResponseDto.class);
// TranslationEntity translationEntity = translationRepository.findByParentGuidAndFieldAndLanguage(projectResponseDto.getProjectGuid(), "description", LocaleContextHolder.getLocale().getDisplayLanguage());
//
// if(translationEntity != null){
// projectResponseDto.setDescription(translationEntity.getContent());
// }else{
// projectResponseDto.setDescription("");
// }
//
// return projectResponseDto;
// }
//
// @RequestMapping(value = "/getProjects", method = RequestMethod.GET)
// public Page<ProjectResponseDto> getProjects(Pageable pageable) {
// int totalElements = 0;
// List<ProjectResponseDto> projectsResponseDto = new ArrayList<ProjectResponseDto>();
// Page<ProjectEntity> projects = projectRepository.findAll(pageable);
//
// if(projects != null){
// totalElements = projects.getNumberOfElements();
// for(ProjectEntity project : projects){
// ProjectResponseDto projectResponseDto = this.convertToResponseDto(project);
// projectsResponseDto.add(projectResponseDto);
// }
// }
//
// return new PageImpl<>(projectsResponseDto, pageable, totalElements);
// }
}
| 41.736842 | 213 | 0.71949 |
c393b66a8c2eec89e1246c6022806422ac4e7a34 | 1,875 | /*
* Copyright 2019 Ivan Pekov (MrIvanPlays)
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
package com.github.mrivanplays.poll.storage.serializers;
import com.github.mrivanplays.poll.util.Voter;
import com.google.gson.JsonObject;
import java.util.UUID;
public class VoterSerializer {
public static Voter deserialize(JsonObject object) {
if (!object.has("uuid") || !object.has("answered")) {
throw new RuntimeException("Invalid json parsed");
}
return new Voter(UUID.fromString(object.get("uuid").getAsString()), object.get("answered").getAsString());
}
public static JsonObject serialize(Voter src) {
JsonObject object = new JsonObject();
object.addProperty("uuid", src.getUuid().toString());
object.addProperty("answered", src.getAnswered());
return object;
}
}
| 43.604651 | 114 | 0.733333 |
464aff5dc35b7339bc6a40b98f0017df323636ad | 1,228 | package com.example.ZMTCSD.entity;
import java.io.Serializable;
import java.util.List;
/**
* 中信保的投保详情 和 中信保的限额详情 一样
*/
public class CompanyInsureEntity implements Serializable {
@Override
public String toString() {
return "CompanyInsureEntity{" +
"lcId=" + lcId +
", propertyGroupInfos=" + propertyGroupInfos +
", fileInfos=" + fileInfos +
'}';
}
/**
* "lcId": 4001409,
* "propertyGroupInfos":
* "fileInfos": null
*/
private int lcId;
private List<PropertyGroupsEntity> propertyGroupInfos;
private List<FileInfoEntity> fileInfos;
public int getLcId() {
return lcId;
}
public void setLcId(int lcId) {
this.lcId = lcId;
}
public List<PropertyGroupsEntity> getPropertyGroupInfos() {
return propertyGroupInfos;
}
public void setPropertyGroupInfos(List<PropertyGroupsEntity> propertyGroupInfos) {
this.propertyGroupInfos = propertyGroupInfos;
}
public List<FileInfoEntity> getFileInfos() {
return fileInfos;
}
public void setFileInfos(List<FileInfoEntity> fileInfos) {
this.fileInfos = fileInfos;
}
}
| 21.928571 | 86 | 0.625407 |
b092c341cc697455bebf8ef5b714090d45290157 | 575 | package com.kuxhausen.huemore.net.dev;
import android.support.v4.util.Pair;
import com.kuxhausen.huemore.net.NetworkBulb;
import java.util.ArrayList;
/**
* For encapsulating connectivity data associated with devices
*/
public class ConnectivityMessage {
ArrayList<Pair<Long, NetworkBulb.ConnectivityState>> mData = new ArrayList<>();
public void addDevice(long id, NetworkBulb.ConnectivityState connectivity) {
mData.add(Pair.create(id, connectivity));
}
public ArrayList<Pair<Long, NetworkBulb.ConnectivityState>> getMessage() {
return mData;
}
}
| 23.958333 | 81 | 0.761739 |
462c3179cdc7fb5b6ee6da4d508faa5c2f743d2e | 20,107 | /*
* Copyright (C) 2014 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.example.android.sunshine.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.WindowInsets;
import com.example.android.sunshine.app.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with
* low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode.
*/
public class SunshineWatchFaceService extends CanvasWatchFaceService {
private static final Typeface NORMAL_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF
, Typeface.NORMAL);
/**
* Update rate in milliseconds for interactive mode. We update once a second since seconds are
* displayed in interactive mode.
*/
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
final String TAG = SunshineWatchFaceService.class.getSimpleName();
/**
* Handler message id for updating the time periodically in interactive mode.
*/
private static final int MSG_UPDATE_TIME = 0;
GoogleApiClient mGoogleApiClient;
@Override
public Engine onCreateEngine() {
return new Engine();
}
private static class EngineHandler extends Handler {
private final WeakReference<SunshineWatchFaceService.Engine> mWeakReference;
public EngineHandler(SunshineWatchFaceService.Engine reference) {
mWeakReference = new WeakReference<>(reference);
}
@Override
public void handleMessage(Message msg) {
SunshineWatchFaceService.Engine engine = mWeakReference.get();
if (engine != null) {
switch (msg.what) {
case MSG_UPDATE_TIME:
engine.handleUpdateTimeMessage();
break;
}
}
}
}
private class Engine extends CanvasWatchFaceService.Engine implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
DataApi.DataListener, OnLoadBitmapListener{
final Handler mUpdateTimeHandler = new EngineHandler(this);
boolean mRegisteredTimeZoneReceiver = false;
Paint mBackgroundPaint;
Paint mTextPaint;
Paint mDateTextPaint;
Paint mLinePaint;
Paint mTempPaint;
boolean mAmbient;
Time mTime;
final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mTime.clear(intent.getStringExtra("time-zone"));
mTime.setToNow();
}
};
int mTapCount;
float mXOffset;
float mYOffset;
//Date offsets
float mDateXOffset;
float mDateYOffset;
//Line Offsets
float mLineXStart;
float mLineXEnd;
float mLineY;
float mTempYOffset;
float mHighTempXOffset;
float mLowTempXOffset;
//High and Low temps
String mHighTemp = "";
String mLowTemp = "";
//Weather Image
Bitmap mPhotoImage;
float mPhotoXOffset;
float mPhotoYOffset;
//Keys to the data sent from the phone
private static final String TEMP_PATH = "/temp";
private static final String HIGH_TEMP_KEY = "hightemp";
private static final String LOW_TEMP_KEY = "lowtemp";
private static final String IMAGE_KEY = "forecast_icon";
private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
boolean mLowBitAmbient;
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
Log.e(TAG,"---- onCreate() ----");
setWatchFaceStyle(new WatchFaceStyle.Builder(SunshineWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.setAcceptsTapEvents(true)
.build());
//Get offsets from dimensions
Resources resources = SunshineWatchFaceService.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mDateYOffset = resources.getDimension(R.dimen.date_y_offset);
mTempYOffset = resources.getDimension(R.dimen.temp_y_offset);
mLineXStart = resources.getDimension(R.dimen.line_x_start);
mLineXEnd = resources.getDimension(R.dimen.line_x_end);
mLineY = resources.getDimension(R.dimen.line_y);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(resources.getColor(R.color.background));
mTextPaint = new Paint();
mTextPaint = createTextPaint(resources.getColor(R.color.digital_text));
//Create paint for date
mDateTextPaint = new Paint();
mDateTextPaint = createTextPaint(resources.getColor(R.color.digital_text_grey));
//Create paint for divider line
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.divider_line));
mLinePaint.setStrokeWidth(1f);
mLinePaint.setStyle(Paint.Style.STROKE);
//Create high/low temperature paint
mTempPaint = new Paint();
mTempPaint = createTextPaint(resources.getColor(R.color.digital_text));
mTime = new Time();
//Connect to Google Play Services to receive data from the phone
mGoogleApiClient = new GoogleApiClient.Builder(SunshineWatchFaceService.this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
@Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
private Paint createTextPaint(int textColor) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setTypeface(NORMAL_TYPEFACE);
paint.setAntiAlias(true);
return paint;
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
registerReceiver();
// Update time zone in case it changed while we weren't visible.
mTime.clear(TimeZone.getDefault().getID());
mTime.setToNow();
} else {
unregisterReceiver();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
private void registerReceiver() {
if (mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
SunshineWatchFaceService.this.registerReceiver(mTimeZoneReceiver, filter);
}
private void unregisterReceiver() {
if (!mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = false;
SunshineWatchFaceService.this.unregisterReceiver(mTimeZoneReceiver);
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
// Load resources that have alternate values for round watches.
Resources resources = SunshineWatchFaceService.this.getResources();
boolean isRound = insets.isRound();
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
float textSize = resources.getDimension(isRound
? R.dimen.digital_text_size_round : R.dimen.digital_text_size);
mTextPaint.setTextSize(textSize);
//Set Date offsets
mDateXOffset = resources.getDimension(isRound
? R.dimen.date_x_offset_round : R.dimen.date_x_offset);
float dateTextSize = resources.getDimension(isRound
? R.dimen.date_text_size_round : R.dimen.date_text_size);
mDateTextPaint.setTextSize(dateTextSize);
//Set Temperature offsets
mHighTempXOffset = resources.getDimension(isRound
? R.dimen.high_temp_x_offset_round : R.dimen.high_temp_x_offset);
mLowTempXOffset = resources.getDimension(isRound
? R.dimen.low_temp_x_offset_round : R.dimen.low_temp_x_offset);
float tempTextSize = resources.getDimension(isRound
? R.dimen.temp_text_size_round : R.dimen.temp_text_size);
//Set Photo offsets
mPhotoXOffset = resources.getDimension(isRound
? R.dimen.icon_x_offset_round : R.dimen.icon_x_offset);
mPhotoYOffset = resources.getDimension(isRound
? R.dimen.icon_y_offset_round : R.dimen.icon_y_offset);
mTempPaint.setTextSize(tempTextSize);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (mAmbient != inAmbientMode) {
mAmbient = inAmbientMode;
if (mLowBitAmbient) {
mTextPaint.setAntiAlias(!inAmbientMode);
mDateTextPaint.setAntiAlias(!inAmbientMode);
}
invalidate();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
/**
* Captures tap event (and tap type) and toggles the background color if the user finishes
* a tap.
*/
@Override
public void onTapCommand(int tapType, int x, int y, long eventTime) {
Resources resources = SunshineWatchFaceService.this.getResources();
switch (tapType) {
case TAP_TYPE_TOUCH:
// The user has started touching the screen.
break;
case TAP_TYPE_TOUCH_CANCEL:
// The user has started a different gesture or otherwise cancelled the tap.
break;
case TAP_TYPE_TAP:
// The user has completed the tap gesture.
mTapCount++;
mBackgroundPaint.setColor(resources.getColor(mTapCount % 2 == 0 ?
R.color.background : R.color.background2));
break;
}
invalidate();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
// Draw the background.
if (isInAmbientMode()) {
canvas.drawColor(Color.BLACK);
} else {
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint);
}
// Draw H:MM in ambient mode or H:MM:SS in interactive mode.
mTime.setToNow();
String text = String.format("%02d:%02d", mTime.hour, mTime.minute);
canvas.drawText(text, mXOffset, mYOffset, mTextPaint);
Date currentDate = new Date();
String strCurrentDate = new SimpleDateFormat("MMM d, yyyy").format(currentDate);
canvas.drawText(strCurrentDate,mDateXOffset,mDateYOffset,mDateTextPaint);
float centerX = bounds.width() / 2f;
canvas.drawLine(centerX - 30,mLineY,centerX + 30,mLineY,mLinePaint);
canvas.drawText(mHighTemp,mHighTempXOffset,mTempYOffset,mTempPaint);
canvas.drawText(mLowTemp, mLowTempXOffset, mTempYOffset, mTempPaint);
if(mPhotoImage != null)
canvas.drawBitmap(mPhotoImage,mPhotoXOffset,mPhotoYOffset,null);
}
/**
* Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
/**
* Handle updating the time periodically in interactive mode.
*/
private void handleUpdateTimeMessage() {
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs = INTERACTIVE_UPDATE_RATE_MS
- (timeMs % INTERACTIVE_UPDATE_RATE_MS);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
}
@Override
public void onConnected(Bundle bundle) {
Log.e(TAG,"onConnected()");
Wearable.DataApi.addListener(mGoogleApiClient, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.e(TAG, "onDataChanged in watchface: " + dataEvents);
// Loop through the events and send a message back to the node that created the data item.
for (DataEvent event : dataEvents) {
Uri uri = event.getDataItem().getUri();
String path = uri.getPath();
Log.e(TAG,"Path to data = " + path);
if (TEMP_PATH.equals(path)) {
// Get the node id of the node that created the data item from the host portion of
// the uri.
String nodeId = uri.getHost();
// Set the data of the message to be the bytes of the Uri.
byte[] payload = uri.toString().getBytes();
Log.e(TAG,"Pull datamap");
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
Log.e(TAG, "High temp = " + dataMap.getString(HIGH_TEMP_KEY));
Log.e(TAG, "Low temp = " + dataMap.getString(LOW_TEMP_KEY));
mHighTemp = dataMap.getString(HIGH_TEMP_KEY);
mLowTemp = dataMap.getString(LOW_TEMP_KEY);
final Asset photoAsset = dataMap.getAsset(IMAGE_KEY);
// Send the rpc
Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH,
payload);
new AssetToBitimapAsyncTask(this).execute(photoAsset);
}
}
}
@Override
public void onLoadBitmapFinished(Bitmap bitmap) {
Log.e(TAG, "onLoadBitmapFinished()! invalidate and redraw");
if(bitmap != null) {
Log.e(TAG, "Bitmap not null! horray!");
mPhotoImage = bitmap;
}
invalidate();
}
}
/**
* Task to change Asset from the phone into a Bitmap
*/
private class AssetToBitimapAsyncTask extends AsyncTask<Asset, Void, Bitmap> {
private OnLoadBitmapListener listener;
public AssetToBitimapAsyncTask(OnLoadBitmapListener listener) {
this.listener = listener;
}
@Override
protected Bitmap doInBackground(Asset... params) {
if(params.length > 0) {
Asset asset = params[0];
InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
mGoogleApiClient, asset).await().getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
return BitmapFactory.decodeStream(assetInputStream);
} else {
Log.e(TAG, "Asset must be non-null");
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null) {
Log.e(TAG, "Created Bitmap!..");
listener.onLoadBitmapFinished(bitmap);
//redraw watch face
// SunshineWatchFaceService.Engine.this.invalidate();
}
}
}
/**
* Interface used to call back from AsyncTask to let the outer class know the Bitmap is done
*/
interface OnLoadBitmapListener {
void onLoadBitmapFinished(Bitmap bitmap);
}
}
| 36.098743 | 102 | 0.61128 |
ad09bf890778fe54786ec28d885c335af4eba867 | 2,648 | package remotefndload;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogSshKeys extends JDialog {
private JToolBar toolBar = new JToolBar();
private BorderLayout borderLayout1 = new BorderLayout();
private JScrollPane scrollPane = new JScrollPane();
private JTable table = new JTable();
private JButton buttonAdd = new JButton();
private JButton buttonRemove = new JButton();
public DialogSshKeys() {
this(null, "Keys", false);
}
public DialogSshKeys(Frame parent, String title, boolean modal) {
super(parent, title, modal);
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void jbInit() throws Exception {
this.setSize( new Dimension( 400, 300 ) );
this.getContentPane().setLayout(borderLayout1);
this.setModal(true);
buttonAdd.setText("Add");
buttonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonAdd_actionPerformed(e);
}
});
buttonRemove.setText("Remove");
buttonRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonDelete_actionPerformed(e);
}
});
toolBar.add(buttonAdd, null);
toolBar.add(buttonRemove, null);
this.getContentPane().add(toolBar, BorderLayout.NORTH);
scrollPane.getViewport().add(table, null);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
void setSshKeys(SshKeys sshKeys) {
TableModelSshKeys model = new TableModelSshKeys(sshKeys);
table.setModel(model);
table.getColumnModel().getColumn(1).setCellRenderer(new PasswordRenderer());
}
private void buttonAdd_actionPerformed(ActionEvent e) {
TableModelSshKeys model = (TableModelSshKeys)table.getModel();
model.addRow();
model.fireTableDataChanged();
}
private void buttonDelete_actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row != -1) {
TableModelSshKeys model = (TableModelSshKeys)table.getModel();
row = table.convertRowIndexToModel(row);
model.removeRow(row);
model.fireTableDataChanged();
}
}
}
| 34.38961 | 85 | 0.615181 |
8fafe006c7ff11053c74d44b71ace674ea260d4e | 1,046 | package com.example.demo.entities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CategoryService {
@Autowired
private CategoryRepository catRep;
public Page<Category> findAll (Pageable page){
Page<Category> cat=catRep.findAll(PageRequest.of(0,10));
return catRep.findAll(page);
}
public Optional<Category> findOne(long id){
return catRep.findById(id);
}
public List<Category> findAll(){
return catRep.findAll();
}
public List<Category> findByName(String name){
return catRep.findByNameCategory(name);
}
public void saveCategory(Category category){
catRep.save(category);
}
public void deleteCategory(long id){
catRep.deleteById(id);
}
}
| 24.325581 | 64 | 0.711281 |
6435d3792ea7c56bd9cbb78292f4e14898b2da95 | 7,024 | /*
* 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.cassandra.io.tries;
import org.apache.cassandra.io.util.Rebufferer;
import org.apache.cassandra.utils.ByteComparable;
import org.apache.cassandra.utils.ByteSource;
/**
* Thread-unsafe value iterator for on-disk tries. Uses the assumptions of Walker.
*/
public class ValueIterator<Concrete extends ValueIterator<Concrete>> extends Walker<Concrete>
{
private final ByteSource limit;
private IterationPosition stack;
private long next;
static class IterationPosition
{
long node;
int childIndex;
int limit;
IterationPosition prev;
IterationPosition(long node, int childIndex, int limit, IterationPosition prev)
{
super();
this.node = node;
this.childIndex = childIndex;
this.limit = limit;
this.prev = prev;
}
@Override
public String toString()
{
return String.format("[Node %d, child %d, limit %d]", node, childIndex, limit);
}
}
protected ValueIterator(Rebufferer source, long root)
{
super(source, root);
limit = null;
initializeNoLeftBound(root, 256);
}
protected ValueIterator(Rebufferer source, long root, ByteComparable start, ByteComparable end, boolean admitPrefix)
{
super(source, root);
limit = end != null ? end.asComparableBytes(BYTE_COMPARABLE_VERSION) : null;
if (start != null)
initializeWithLeftBound(root, start.asComparableBytes(BYTE_COMPARABLE_VERSION), admitPrefix, limit != null);
else
initializeNoLeftBound(root, limit != null ? limit.next() : 256);
}
private void initializeWithLeftBound(long root, ByteSource startStream, boolean admitPrefix, boolean atLimit)
{
IterationPosition prev = null;
int childIndex;
int limitByte;
long payloadedNode = -1;
try
{
// Follow start position while we still have a prefix, stacking path and saving prefixes.
go(root);
while (true)
{
int s = startStream.next();
childIndex = search(s);
// For a separator trie the latest payload met along the prefix is a potential match for start
if (admitPrefix)
if (childIndex == 0 || childIndex == -1)
{
if (payloadFlags() != 0)
payloadedNode = position;
}
else
payloadedNode = -1;
limitByte = 256;
if (atLimit)
{
limitByte = limit.next();
if (s < limitByte)
atLimit = false;
}
if (childIndex < 0)
break;
prev = new IterationPosition(position, childIndex, limitByte, prev);
go(transition(childIndex));
}
childIndex = -1 - childIndex - 1;
stack = new IterationPosition(position, childIndex, limitByte, prev);
// Advancing now gives us first match if we didn't find one already.
if (payloadedNode != -1)
next = payloadedNode;
else
next = advanceNode();
}
catch (Throwable t)
{
super.close();
throw t;
}
}
private void initializeNoLeftBound(long root, int limitByte)
{
stack = new IterationPosition(root, -1, limitByte, null);
try
{
go(root);
if (payloadFlags() != 0)
next = root;
else
next = advanceNode();
}
catch (Throwable t)
{
super.close();
throw t;
}
}
/**
* Returns the payload node position.
*
* This method must be async-read-safe, see {@link #advanceNode()}.
*/
protected long nextPayloadedNode()
{
long toReturn = next;
if (next != -1)
next = advanceNode();
return toReturn;
}
/**
* This method must be async-read-safe. Every read from new buffering position (the go() calls) can
* trigger NotInCacheException, and iteration must be able to redo the work that was interrupted during the next
* call. Hence the mutable state must be fully ready before all go() calls (i.e. they must either be the
* last step in the loop or the state must be unchanged until that call has succeeded).
*/
private long advanceNode()
{
long child;
int transitionByte;
go(stack.node); // can throw NotInCacheException, OK no state modified yet
while (true)
{
// advance position in node but don't change the stack just yet due to NotInCacheExceptions
int childIndex = stack.childIndex + 1;
transitionByte = transitionByte(childIndex);
if (transitionByte > stack.limit)
{
// ascend
stack = stack.prev;
if (stack == null) // exhausted whole trie
return -1;
go(stack.node); // can throw NotInCacheException, OK - stack ready to re-enter loop with parent
continue;
}
child = transition(childIndex);
if (child != -1)
{
assert child >= 0 : String.format("Expected value >= 0 but got %d - %s", child, this);
// descend
go(child); // can throw NotInCacheException, OK - stack not yet changed, limit not yet incremented
int l = 256;
if (transitionByte == stack.limit)
l = limit.next();
stack.childIndex = childIndex;
stack = new IterationPosition(child, -1, l, stack);
if (payloadFlags() != 0)
return child;
}
else
{
stack.childIndex = childIndex;
}
}
}
}
| 32.368664 | 120 | 0.557802 |
89ca672eb871e6aaaf1d13277681922598cf0d7f | 7,890 | // Screen.java
// Represents the screen of the ATM
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
public class Screen extends JFrame
{
public JFrame Mainframe;
public static JTextField Inputfield1;
public static JTextField Inputfield2;
public static JTextField Inputfield3;
public static JTextField Inputfield4;
public JLabel messageJLabel;
public JLabel messageJLabel2; // displays message of game status
public JLabel messageJLabel3;
public JLabel messageJLabel4;
public JLabel messageJLabel5;
public JLabel messageJLabel8;
public JLabel messageJLabel9;
public JLabel messageJLabel10;
public JButton loginbutton; // creates new game
public JButton button1;
public JButton button2;
public JButton button3;
public JButton button4;
public JButton button5;
public JButton Exit;
public int accnum = 0;
public int PIN = 0;
public JLabel messageJLabel6;
public JLabel messageJLabel7;
// displays a message without a carriage return
public void displayMessage(String message)
{
System.out.print(message);
} // end method displayMessage
// display a message with a carriage return
public void displayMessageLine(String message)
{
System.out.println(message);
} // end method displayMessageLine
// display a dollar amount
public void displayDollarAmount(double amount)
{
System.out.printf("$%,.2f", amount);
} // end method displayDollarAmount
//create the login GUI
public void createlogin() {
Mainframe = new JFrame("ATM");
messageJLabel4 = new JLabel("Insert your credit/debit card then ");
messageJLabel = new JLabel(" Enter your PIN number: ");
Inputfield1 = new JTextField( 10 );
messageJLabel2 = new JLabel(" ");
Inputfield2 = new JTextField( 10 );
loginbutton = new JButton("Login");
messageJLabel3 = new JLabel("");
Mainframe.setLayout( new FlowLayout() ); // set layout
Mainframe.add(messageJLabel4);
Mainframe.add( messageJLabel ); // add first prompt
Mainframe.add( Inputfield2 );
Mainframe.add( messageJLabel2 );
//Mainframe.add(loginbutton);
// add message label
Mainframe.add(messageJLabel3);
Inputfield2.setEditable(false);
Mainframe.repaint();
}
//create the main menu GUI
public void createmenu(){
Mainframe.getContentPane().removeAll();
messageJLabel = new JLabel("Welcome");
messageJLabel2 = new JLabel("1 - Balance");
messageJLabel3 = new JLabel("2 - Withdrawal");
messageJLabel4 = new JLabel("3 - Deposit");
messageJLabel5 = new JLabel("4 - Exit");
Mainframe.setLayout( new FlowLayout() ); // set layout
Mainframe.add(messageJLabel);
Mainframe.add( messageJLabel2 ); // add first prompt
Mainframe.add( messageJLabel3 ); // add second prompt
Mainframe.add( messageJLabel4 ); // add message label
Mainframe.add( messageJLabel5 );
Mainframe.repaint();
}
//create the Balance GUI
public void creatBalanceGUI(){
Mainframe.getContentPane().removeAll();
messageJLabel = new JLabel("Balance Information: ");
messageJLabel2 = new JLabel("Avaliable Balance:");
messageJLabel3 = new JLabel("Total Balance:");
Exit = new JButton("Back");
Mainframe.setLayout( new FlowLayout() );
Mainframe.add(messageJLabel);
Mainframe.add(messageJLabel2);
Mainframe.add(messageJLabel3);
Mainframe.add(Exit);
Mainframe.repaint();
}
//Create the withdraw GUI
public void createWithdrawGUI(){
Mainframe.getContentPane().removeAll();
Mainframe.revalidate();
messageJLabel = new JLabel("Withdraw Menu: ");
messageJLabel2 = new JLabel("1 - $20 ");
messageJLabel3 = new JLabel("2 - $40 ");
messageJLabel4 = new JLabel("3 - $60 ");
messageJLabel5 = new JLabel("4 - $100 ");
messageJLabel6 = new JLabel("5 - $200 ");
messageJLabel7 = new JLabel(" Choose an amount to withdraw");
Exit = new JButton("Cancel");
Mainframe.setLayout( new FlowLayout() );
Mainframe.add(messageJLabel);
Mainframe.add(messageJLabel2);
Mainframe.add(messageJLabel3);
Mainframe.add(messageJLabel4);
Mainframe.add(messageJLabel5);
Mainframe.add(messageJLabel6);
Mainframe.add(Exit);
Mainframe.add(messageJLabel7);
Mainframe.repaint();
}
//Create the Deposit GUI
public void CreateDepositGUI(){
Mainframe.getContentPane().removeAll();
messageJLabel2 = new JLabel("Please enter a deposit amount in CENTS");
messageJLabel3 = new JLabel("");
Inputfield2 = new JTextField(10);
Inputfield2.setEditable(false);
button1 = new JButton("Deposit");
Exit = new JButton("Cancel");
Mainframe.add(messageJLabel2);
Mainframe.add(messageJLabel3);
Mainframe.add(Inputfield2);
Mainframe.add(Exit);
Mainframe.repaint();
}
public void setGUI(){
repaint();
}
//Create the admin page GUI
public void createAdminpage(){
messageJLabel = new JLabel("View Users:");
messageJLabel2 = new JLabel("Account number:");
messageJLabel3 = new JLabel("Avaliable Balance:");
messageJLabel4 = new JLabel("Total Balance:");
messageJLabel5 = new JLabel("________________________________________________");
button1 = new JButton("Next");
button4 = new JButton("Previous");
Exit = new JButton("Back");
Inputfield1 = new JTextField(10);
Inputfield2 = new JTextField(10);
Inputfield3 = new JTextField(10);
Inputfield4 = new JTextField(10);
Mainframe.setLayout( new FlowLayout() );
messageJLabel6 = new JLabel("Add Account: ");
messageJLabel7 = new JLabel("User name: ");
Mainframe.add(messageJLabel);
messageJLabel8 = new JLabel(" Account number: ");
Mainframe.add(messageJLabel2);
messageJLabel10 = new JLabel(" PIN: ");
messageJLabel9 = new JLabel(" Balance number: ");
button2 = new JButton("Add");
button3 = new JButton("Delete");
Mainframe.add(messageJLabel3);
Mainframe.add(messageJLabel4);
Mainframe.add(button4);
Mainframe.add(button1);
Mainframe.add(button3);
Mainframe.add(messageJLabel5);
Mainframe.add(messageJLabel6);
Mainframe.add(messageJLabel7);
Mainframe.add(Inputfield1);
Mainframe.add(messageJLabel8);
Mainframe.add(Inputfield2);
Mainframe.add(messageJLabel10);
Mainframe.add(Inputfield4);
Mainframe.add(messageJLabel9);
Mainframe.add(Inputfield3);
Mainframe.add(button2);
Mainframe.add(Exit);
Mainframe.repaint();
}
} // end class Screen
/**************************************************************************
* (C) Copyright 1992-2014 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/ | 33.717949 | 100 | 0.669962 |
992915051788e0de1e87e60fcf7ffacf9925e900 | 641 | package org.ovirt.engine.core.common.action;
import org.ovirt.engine.core.compat.Guid;
public class DetachUserFromVmFromPoolParameters extends VmPoolUserParameters {
private static final long serialVersionUID = 2255305819152411560L;
private boolean restoreStateless;
public DetachUserFromVmFromPoolParameters(Guid vmPoolId, Guid userId, Guid vmId, boolean restoreStateless) {
super(vmPoolId, userId, vmId);
this.restoreStateless = restoreStateless;
}
DetachUserFromVmFromPoolParameters() {
super();
}
public boolean getIsRestoreStateless() {
return restoreStateless;
}
}
| 27.869565 | 112 | 0.74571 |
2261665535fa055e417eca7fbdecd9cf1e831cfa | 2,772 | package com.github.eirslett.maven.plugins.frontend.mojo;
import com.github.eirslett.maven.plugins.frontend.lib.FrontendException;
import com.github.eirslett.maven.plugins.frontend.lib.FrontendPluginFactory;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Map;
public abstract class AbstractFrontendMojo extends AbstractMojo {
@Component
protected MojoExecution execution;
/**
* Whether you should skip while running in the test phase (default is false)
*/
@Parameter(property = "skipTests", required = false, defaultValue = "false")
protected Boolean skipTests;
/**
* The base directory for running all Node commands. (Usually the directory that contains package.json)
*/
@Parameter(defaultValue = "${basedir}", property = "workingDirectory", required = false)
protected File workingDirectory;
/**
* The base directory for installing node and npm.
*/
@Parameter(property = "installDirectory", required = false)
protected File installDirectory;
/**
* Additional environment variables to pass to the build.
*/
@Parameter
protected Map<String, String> environmentVariables;
/**
* Determines if this execution should be skipped.
*/
private boolean skipTestPhase() {
return skipTests && isTestingPhase();
}
/**
* Determines if the current execution is during a testing phase (e.g., "test" or "integration-test").
*/
private boolean isTestingPhase() {
String phase = execution.getLifecyclePhase();
return phase!=null && (phase.equals("test") || phase.equals("integration-test"));
}
protected abstract void execute(FrontendPluginFactory factory) throws FrontendException;
/**
* Implemented by children to determine if this execution should be skipped.
*/
protected abstract boolean skipExecution();
@Override
public void execute() throws MojoFailureException {
if (!(skipTestPhase() || skipExecution())) {
if (installDirectory == null) {
installDirectory = workingDirectory;
}
try {
execute(new FrontendPluginFactory(workingDirectory, installDirectory));
} catch (TaskRunnerException e) {
throw new MojoFailureException("Failed to run task", e);
} catch (FrontendException e) {
throw MojoUtils.toMojoFailureException(e);
}
} else {
LoggerFactory.getLogger(AbstractFrontendMojo.class).info("Skipping test phase.");
}
}
}
| 32.232558 | 105 | 0.728355 |
4900fd5f58264a5bc4d0768bb545a2e705ff0fdb | 13,132 | package jesse843.simplecalculator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "jesse843.simplecalculator.MESSAGE";
private String previous;
private TextView displayTextView;
private boolean multiply;
private boolean divide;
private boolean add;
private boolean subtract;
private boolean showingAnswer = false;
private boolean alreadyClear = false;
private TextView multiplyTextView;
private TextView divideTextView;
private TextView addTextView;
private TextView subtractTextView;
private ScrollView scrollview;
private String history;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing variables
previous = "0";
displayTextView = (TextView) findViewById(R.id.displayTextView);
multiply = false;
divide = false;
add = false;
subtract = false;
showingAnswer = false;
alreadyClear = false;
multiplyTextView = (TextView) findViewById(R.id.multiply_button);
divideTextView = (TextView) findViewById(R.id.divide_button);
addTextView = (TextView) findViewById(R.id.add_button);
subtractTextView = (TextView) findViewById(R.id.subtract_button);
scrollview = ((ScrollView) findViewById(R.id.scrollView));
history = "";
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.history_icon) {
Intent intent = new Intent(this, HistoryActivity.class);
intent.putExtra(EXTRA_MESSAGE, history);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void digitOne(View v) {
digitAdd("1");
}
public void digitTwo(View v) {
digitAdd("2");
}
public void digitThree(View v) {
digitAdd("3");
}
public void digitFour(View v) {
digitAdd("4");
}
public void digitFive(View v) {
digitAdd("5");
}
public void digitSix(View v) {
digitAdd("6");
}
public void digitSeven(View v) {
digitAdd("7");
}
public void digitEight(View v) {
digitAdd("8");
}
public void digitNine(View v) {
digitAdd("9");
}
public void digitZero(View v) {
digitAdd("0");
}
public void digitAdd(String digit) {
if ((multiply || divide || add || subtract) && !alreadyClear) {
displayTextView.setText("0");
}
alreadyClear = true;
if (showingAnswer) {
displayTextView.setText("0");
}
showingAnswer = false;
displayTextView.setTextColor(Color.WHITE);
if (displayTextView.getText().toString().contains(".")) {
displayTextView.setText("" + displayTextView.getText().toString() + digit);
} else {
BigInteger displayNum = new BigInteger(displayTextView.getText().toString());
displayNum = displayNum.multiply(new BigInteger("10"));
displayNum = displayNum.add(new BigInteger(digit));
displayTextView.setText("" + displayNum);
}
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public void addDecimal(View v) {
if ((multiply || divide || add || subtract) && !alreadyClear) {
displayTextView.setText("0");
alreadyClear = true;
}
if (showingAnswer) {
displayTextView.setText("0");
}
showingAnswer = false;
displayTextView.setTextColor(Color.WHITE);
if (!displayTextView.getText().toString().contains(".")) {
displayTextView.setText(displayTextView.getText().toString() + ".");
}
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public void clearDisplay(View v) {
displayTextView.setText("0");
if (multiply) {
multiplyTextView.setTextColor(Color.BLACK);
multiply = false;
} else if (divide) {
divideTextView.setTextColor(Color.BLACK);
divide = false;
} else if (add) {
addTextView.setTextColor(Color.BLACK);
add = false;
} else if (subtract) {
subtractTextView.setTextColor(Color.BLACK);
subtract = false;
}
showingAnswer = false;
displayTextView.setTextColor(Color.WHITE);
alreadyClear = false;
previous = "0";
}
public void backspace(View v) {
if (!showingAnswer) {
if (displayTextView.getText().toString().length() > 1)
displayTextView.setText(displayTextView.getText().toString().substring(0, displayTextView.getText().toString().length() - 1));
else {
displayTextView.setText("0");
}
}
}
public void negate(View v) {
if (!showingAnswer) {
if (displayTextView.getText().toString().contains(".")) {
BigDecimal displayNum = new BigDecimal(displayTextView.getText().toString());
displayNum = displayNum.negate();
displayTextView.setText("" + displayNum);
Log.v("LALALALLALALALLALALAL", "BigDecimal");
} else {
BigInteger displayNum = new BigInteger(displayTextView.getText().toString());
displayNum = displayNum.negate();
displayTextView.setText("" + displayNum);
Log.v("LALALALLALALALLALALAL", "BigInteger");
}
}
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public void multiply(View v) {
if (!multiply && !divide && !add && !subtract) {
previous = displayTextView.getText().toString();
multiply = true;
multiplyTextView.setTextColor(Color.RED);
alreadyClear = false;
} else if (alreadyClear) {
equals(null);
previous = displayTextView.getText().toString().substring(1, displayTextView.getText().toString().length());
multiply = true;
multiplyTextView.setTextColor(Color.RED);
displayTextView.setTextColor(Color.WHITE);
alreadyClear = false;
}
}
public void divide(View v) {
if (!divide && !multiply && !add && !subtract && !displayTextView.getText().toString().equals("0")) {
previous = displayTextView.getText().toString();
divide = true;
divideTextView.setTextColor(Color.RED);
alreadyClear = false;
} else if (alreadyClear) {
equals(null);
previous = displayTextView.getText().toString().substring(1, displayTextView.getText().toString().length());
divide = true;
divideTextView.setTextColor(Color.RED);
displayTextView.setTextColor(Color.WHITE);
alreadyClear = false;
}
}
public void add(View v) {
if (!add && !divide && !multiply && !subtract) {
previous = displayTextView.getText().toString();
add = true;
addTextView.setTextColor(Color.RED);
alreadyClear = false;
} else if (alreadyClear) {
equals(null);
previous = displayTextView.getText().toString().substring(1, displayTextView.getText().toString().length());
add = true;
addTextView.setTextColor(Color.RED);
displayTextView.setTextColor(Color.WHITE);
alreadyClear = false;
}
}
public void subtract(View v) {
if (!subtract && !divide && !add && !multiply) {
previous = displayTextView.getText().toString();
subtract = true;
subtractTextView.setTextColor(Color.RED);
alreadyClear = false;
} else if (alreadyClear) {
equals(null);
previous = displayTextView.getText().toString().substring(1, displayTextView.getText().toString().length());
subtract = true;
subtractTextView.setTextColor(Color.RED);
displayTextView.setTextColor(Color.WHITE);
alreadyClear = false;
}
}
public void equals(View v) {
if (multiply || divide || add || subtract) {
BigDecimal result = new BigDecimal("0");
if (previous.charAt(0) == '=') {
previous = previous.substring(1, previous.length());
}
if (multiply) {
result = new BigDecimal(previous);
result = result.multiply(new BigDecimal(displayTextView.getText().toString()));
multiply = false;
multiplyTextView.setTextColor(Color.BLACK);
history += previous + " x " + displayTextView.getText().toString();
history += "\n";
history += "=" + result + "\n";
} else if (divide) {
if (displayTextView.getText().toString().equals(("0"))) {
return;
}
result = new BigDecimal(previous);
result = result.divide(new BigDecimal(displayTextView.getText().toString()), 5, RoundingMode.HALF_UP);
divide = false;
String tooLong = result.toString();
while (tooLong.charAt(tooLong.length() - 1) == '0' && tooLong.length() > 1) {
tooLong = tooLong.substring(0, tooLong.length() - 1);
}
result = new BigDecimal(tooLong);
divideTextView.setTextColor(Color.BLACK);
history += previous + " ÷ " + displayTextView.getText().toString();
history += "\n";
history += "=" + result + "\n";
} else if (add) {
result = new BigDecimal(previous);
result = result.add(new BigDecimal(displayTextView.getText().toString()));
add = false;
addTextView.setTextColor(Color.BLACK);
history += previous + " + " + displayTextView.getText().toString();
history += "\n";
history += "=" + result + "\n";
} else if (subtract) {
result = new BigDecimal(previous);
result = result.subtract(new BigDecimal(displayTextView.getText().toString()));
subtract = false;
subtractTextView.setTextColor(Color.BLACK);
history += previous + " - " + displayTextView.getText().toString();
history += "\n";
history += "=" + result + "\n";
}
displayTextView.setText("=" + result);
showingAnswer = true;
alreadyClear = true;
displayTextView.setTextColor(Color.YELLOW);
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
}
}
| 34.832891 | 142 | 0.574398 |
a03bba6631af4617f79d048c3cb408fb7596232c | 2,467 | package io.choerodon.test.manager.api.controller.v1;
import java.util.Optional;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Sort;
import io.choerodon.core.enums.ResourceType;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.iam.InitRoleCode;
import org.springframework.data.domain.Pageable;
import io.choerodon.core.annotation.Permission;
import org.springframework.data.web.SortDefault;
import io.choerodon.test.manager.api.vo.TestCycleCaseHistoryVO;
import io.choerodon.test.manager.app.service.TestCycleCaseHistoryService;
/**
* Created by [email protected] on 6/28/18.
*/
@RestController
@RequestMapping(value = "/v1/projects/{project_id}/cycle/case/history/{cycleCaseId}")
public class TestCycleCaseHistoryController {
@Autowired
TestCycleCaseHistoryService testCycleCaseHistoryService;
@Permission(type = ResourceType.PROJECT, roles = {InitRoleCode.PROJECT_MEMBER, InitRoleCode.PROJECT_OWNER})
@ApiOperation("查询循环历史")
@GetMapping
public ResponseEntity<PageInfo<TestCycleCaseHistoryVO>> query(@PathVariable(name = "project_id") Long projectId,
@ApiIgnore
@ApiParam(value = "分页信息", required = true)
@SortDefault(value = "id", direction = Sort.Direction.DESC)
Pageable pageable,
@PathVariable(name = "cycleCaseId") Long cycleCaseId) {
return Optional.ofNullable(testCycleCaseHistoryService.query(cycleCaseId, pageable))
.map(result -> new ResponseEntity<>(result, HttpStatus.OK))
.orElseThrow(() -> new CommonException("error.history.query"));
}
}
| 46.54717 | 125 | 0.689096 |
4d379ed7b2bcd51997976b9c07fbb50e02548c2c | 349 | /**
* @author Almas Baimagambetov ([email protected])
*/
module com.almasb.fxgl.media {
requires com.almasb.fxgl.core;
requires javafx.media;
exports com.almasb.fxgl.audio;
exports com.almasb.fxgl.texture;
exports com.almasb.fxgl.audio.impl to com.almasb.fxgl.all;
opens com.almasb.fxgl.audio to com.almasb.fxgl.core;
} | 24.928571 | 62 | 0.713467 |
a7aec1dc80dd7d3ff4ea080b5d144bfa6a87f8cc | 2,359 | package com.ruoyi.web.controller.fc;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.module.domain.Prize;
import com.ruoyi.module.service.IPrizeService;
import com.ruoyi.web.core.base.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 奖品列 信息操作处理
*
* @author ruoyi
* @date 2018-10-27
*/
@Controller
@RequestMapping("/fc/prize")
public class PrizeController extends BaseController
{
private String prefix = "fc/prize";
@Autowired
private IPrizeService prizeService;
@RequiresPermissions("fc:prize:view")
@GetMapping()
public String prize()
{
return prefix + "/prize";
}
/**
* 查询奖品列列表
*/
@RequiresPermissions("fc:prize:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(Prize prize)
{
startPage();
List<Prize> list = prizeService.selectPrizeList(prize);
return getDataTable(list);
}
/**
* 新增奖品列
*/
@GetMapping("/add")
public String add()
{
return prefix + "/add";
}
/**
* 新增保存奖品列
*/
@RequiresPermissions("fc:prize:add")
@Log(title = "奖品列", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(Prize prize)
{
return toAjax(prizeService.insertPrize(prize));
}
/**
* 修改奖品列
*/
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Integer id, ModelMap mmap)
{
Prize prize = prizeService.selectPrizeById(id);
mmap.put("prize", prize);
return prefix + "/edit";
}
/**
* 修改保存奖品列
*/
@RequiresPermissions("fc:prize:edit")
@Log(title = "奖品列", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(Prize prize)
{
return toAjax(prizeService.updatePrize(prize));
}
/**
* 删除奖品列
*/
@RequiresPermissions("fc:prize:remove")
@Log(title = "奖品列", businessType = BusinessType.DELETE)
@PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids)
{
return toAjax(prizeService.deletePrizeByIds(ids));
}
}
| 21.445455 | 66 | 0.714286 |
ff1d3fde130f45a65f71f05de097b49dd50586bd | 2,905 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.springframework.samples.petclinic.owner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hibernate.internal.util.collections.CollectionHelper.arrayList;
import org.springframework.samples.petclinic.appointment.Appointment;
import org.springframework.samples.petclinic.appointment.UserHelping;
import org.springframework.security.crypto.password.PasswordEncoder;
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 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
/**
*
* @author donaldoherr
*/
@RestController
public class OwnerRestController {
OwnerRestRepository owners;
private PasswordEncoder pass;
public OwnerRestController(OwnerRestRepository owners){
this.owners = owners;
}
@RequestMapping(method = RequestMethod.GET, path = "/api/owner/{userID}")
public Map getCita(@PathVariable("userID") String userID) {
HashMap<String, String> map = new HashMap<>();
OwnerRest owner = this.owners.getOwnerByIdUser(userID);
map.put("owner",String.valueOf(owner.getId()));
return map;
}
@RequestMapping(method = RequestMethod.POST, path = "/api/owners/login")
public Map login(@RequestBody UserHelping userHelping) {
String email = userHelping.getEmail();
String password = userHelping.getPassword();
ArrayList<UserHelping> userData = this.owners.getByEmailUser(email);
String pass = null;
Integer id = null;
String name = null;
for(UserHelping user : userData){
pass = user.getPassword();
id = user.getId();
name = user.getFirstName();
}
String [] strPass = pass.split("}");
BCryptPasswordEncoder b = new BCryptPasswordEncoder();
HashMap<String, String> map = new HashMap<>();
if(b.matches(password, strPass[1]) == false){
map.put("response", "0");
return map;
}else{
map.put("response","1");
map.put("name",name);
map.put("userId",""+id);
return map;
}
}
/*@RequestMapping(method = RequestMethod.GET, path = "/api/owners/{owner}")
public Appointment getCita(@PathVariable("citaID") int citaID) {
}*/
}
| 35 | 81 | 0.683993 |
2779cbb1f44c8f4450a758ee8615afaea0dda5a7 | 7,344 | package pt.fccn.sobre.arquivo.pages;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SearchPage {
WebDriver driver;
private final String dir = "sobreTestsFiles";
List< String > topicsPT;
List< String > topicsEN;
private final int timeout = 50;
public SearchPage( WebDriver driver ) throws FileNotFoundException{
this.driver = driver;
topicsPT = new ArrayList< String >( );
topicsEN = new ArrayList< String >( );
if( !loadTopics( "SearchLinksPT.txt" , "pt" ) )
throw new FileNotFoundException( );
if( !loadTopics( "SearchLinksEN.txt" , "en" ) )
throw new FileNotFoundException( );
}
public boolean checkSearch( String language ) {
System.out.println( "[checkSearch]" );
//String xpathResults = "//*[@id=\"search-4\"]/form/label/input"; //get search links
String xpathResults = "//*[@id=\"gsc-i-id1\"]";
//String xpathButton = "//*[@id=\"wp_editor_widget-17\"]/div/div[2]/div/span/a";
String xpathButton = "//*[@id=\"___gcse_0\"]/div/form/table/tbody/tr/td[2]/button";
try{
if( language.equals( "EN" ) )
if( searchEN( xpathResults , xpathButton ) )
return true;
else
return false;
else
if( searchPT( xpathResults , xpathButton ) )
return true;
else
return false;
}catch( NoSuchElementException e ){
System.out.println( "Error in checkOPSite" );
e.printStackTrace( );
return false;
}
}
private boolean checkResults( String topic ) {
System.out.println( "[checkResults]" );
try{
String text = driver.findElement( By.cssSelector("b") ).getText( );
System.out.println( "Text = " + text );
Charset.forName( "UTF-8" ).encode( text );
System.out.println( "[checkResults] text["+text+"] equals topic["+topic+"]" );
return ( text.toLowerCase( ).equals( topic.toLowerCase( ) ) );
} catch( NoSuchElementException e ){
System.out.println( "Error in checkOPSite" );
e.printStackTrace( );
return false;
}
}
/*private boolean checkResults( String topic ) {
System.out.println( "[checkResults]" );
String xpathResults = "//*[@id=\"___gcse_0\"]/div/div/div/div[5]/div[2]/div/div/div[3]"; //get search links
String xpathText = "//div/div/div/table/tbody/tr/td/div[@class=\"gs-bidi-start-align gs-snippet\"]/b[1]";
String teste = "//div/div/div/table/tbody/tr/td/div[@class=\"gs-bidi-start-align gs-snippet\"]";
// //*[@id="___gcse_0"]/div/div/div/div[5]/div[2]/div/div/div[3]/div[1]/div[1]/table/tbody/tr/td[2]/div[3]
try{sleepThread( )
WebElement divElem = ( new WebDriverWait( driver, timeout + 40 ) )
.until( ExpectedConditions
.presenceOfElementLocated(
By.xpath( xpathResults )
)
);
//System.out.println( "[checkSearch] results size = " + divElem.getAttribute( "innerHTML" ) );
System.out.println( "HTML => " + divElem.getAttribute( "innerHTML" ));
List< WebElement > results = divElem.findElements( By.xpath( xpathText ) );
WebElement test = divElem.findElement( By.xpath( xpathText ) );
System.out.println( "HTML TESTE ===> " + test.getText( ) );
System.out.println( "Number of results = " + results.size( ) );
for( WebElement elem : results ) {
String text = elem.getText( );
Charset.forName( "UTF-8" ).encode( text );
if( elem.getText( ) == null || elem.getText( ).equals( "" ) )
continue;
if( !text.toLowerCase( ).equals( topic.toLowerCase( ) ) ){
System.out.println( "Failed text["+text+"] not contains topic["+topic+"]" );
return true;
}
System.out.println( "Success text["+text+"] equals topic["+topic+"]" );
}
return true;
} catch( NoSuchElementException e ){
System.out.println( "Error in checkOPSite" );
e.printStackTrace( );
return false;
}
}*/
private boolean searchEN( String xpathResults , String xpathButton ) {
System.out.println( "[searchEN]" );
for( String topic : topicsEN ) {
WebElement emailElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath( xpathResults ) ) );
emailElement.clear( );
emailElement.sendKeys( topic );
IndexSobrePage.sleepThread( );
WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath( xpathButton ) ) );
btnSubmitElement.click( );
sleepThread( );
if( !checkResults( topic ) )
return false;
}
return true;
}
private boolean searchPT( String xpathResults , String xpathSendButton ) {
System.out.println( "[searchPT]" );
for( String topic : topicsPT ) {
System.out.println( "Search for " + topic );
WebElement emailElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath( xpathResults ) ) );
emailElement.clear( );
emailElement.sendKeys( topic );
IndexSobrePage.sleepThread( );
WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath( xpathSendButton ) ) );
btnSubmitElement.click( );
sleepThread( );
if( !checkResults( topic ) )
return false;
//break; //TODO debug break - REMOVE !!!!
}
return true;
}
private boolean loadTopics( String filename , String language ) {
try {
String line;
InputStreamReader isr = new InputStreamReader( ClassLoader.getSystemResourceAsStream ( dir.concat( File.separator ).concat( filename ) ), Charset.forName( "UTF-8" ) );
BufferedReader br = new BufferedReader(isr);
while ( ( line = br.readLine( ) ) != null ) {
if( language.equals( "pt" ) )
topicsPT.add( line );
else
topicsEN.add( line );
}
br.close( );
isr.close( );
//printQuestions( ); Info Debug
return true;
} catch ( FileNotFoundException exFile ) {
exFile.printStackTrace( );
return false;
} catch ( IOException exIo ) {
exIo.printStackTrace( );
return false;
}
}
private void sleepThread( ) {
try {
Thread.sleep( 6000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 33.381818 | 173 | 0.618192 |
4cbfff5c8cc2a5f88ed652928cfece1a5cc791fe | 1,371 | package com.microsoft.bingads.v11.api.test.entities.budget.write;
import com.microsoft.bingads.v11.api.test.entities.budget.BulkBudgetTest;
import com.microsoft.bingads.v11.bulk.entities.BulkBudget;
import com.microsoft.bingads.v11.campaignmanagement.BudgetLimitType;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
public class BulkBudgetWriteToRowValuesBudgetTypeTest extends BulkBudgetTest {
@Parameter(value = 1)
public BudgetLimitType propertyValue;
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"DailyBudgetAccelerated", BudgetLimitType.DAILY_BUDGET_ACCELERATED},
{"DailyBudgetStandard", BudgetLimitType.DAILY_BUDGET_STANDARD},
{null, null}
});
}
@Test
public void testWrite() {
this.<BudgetLimitType>testWriteProperty("Budget Type", this.datum, this.propertyValue, new BiConsumer<BulkBudget, BudgetLimitType>() {
@Override
public void accept(BulkBudget c, BudgetLimitType v) {
c.getBudget().setBudgetType(v);;
}
});
}
}
| 36.078947 | 143 | 0.702407 |
c2370951cbd7ae904f44e69b2dd3b3dae1370857 | 1,684 | package com.github.pmoerenhout.atcommander.module.v250.exceptions;
public class RegistrationFailedException extends EquipmentException {
private static final long serialVersionUID = -2075761022117894075L;
/**
* Default constructor.
*/
public RegistrationFailedException() {
super();
}
/**
* Construct with specified message and cause.
*
* @param error is the error.
* @param networkRejectError is the error.
* @param message is the detail message.
* @param cause is the parent cause.
*/
public RegistrationFailedException(int error, int networkRejectError, String message, Throwable cause) {
super(error, networkRejectError, message, cause);
}
/**
* Construct with specified message and cause.
*
* @param message is the detail message.
* @param cause is the parent cause.
*/
public RegistrationFailedException(String message, Throwable cause) {
super(message, cause);
}
/**
* Construct with specified message.
*
* @param error is the error.
* @param networkRejectError is the error.
* @param message is the detail message.
*/
public RegistrationFailedException(int error, int networkRejectError, String message) {
super(error, networkRejectError, message);
}
/**
* Construct with specified message.
*
* @param message is the detail message.
*/
public RegistrationFailedException(String message) {
super(message);
}
/**
* Construct with specified cause.
*
* @param cause is the parent cause.
*/
public RegistrationFailedException(Throwable cause) {
super(cause);
}
}
| 25.515152 | 106 | 0.670428 |
896bed871d09ce2d84cd4d8d321fe7afb2cd472e | 690 | package com.ray.study.smaple.cas.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* CAS的配置参数
* @author ChengLi
*/
@Component
@Data
public class CasProperties {
@Value("${cas.server.url}")
private String casServerUrl;
@Value("${cas.server.login_url}")
private String casServerLoginUrl;
@Value("${cas.server.logout_url}")
private String casServerLogoutUrl;
@Value("${app.server.url}")
private String appServerUrl;
@Value("${app.server.login_url}")
private String appLoginUrl;
@Value("${app.server.logout_url}")
private String appLogoutUrl;
} | 20.909091 | 58 | 0.708696 |
546adfc27a0c6e2f32a12f66fcbe5324eecd291c | 623 | package com.tencent.mm.sdk.b;
import android.os.Handler;
import android.os.Looper;
import com.tencent.mm.sdk.b.b.a;
final class c implements a {
private Handler handler;
c() {
this.handler = new Handler(Looper.getMainLooper());
}
public final void f(String str, String str2) {
b.level;
}
public final void g(String str, String str2) {
b.level;
}
public final int getLogLevel() {
return b.level;
}
public final void h(String str, String str2) {
b.level;
}
public final void i(String str, String str2) {
b.level;
}
}
| 18.323529 | 59 | 0.601926 |
802253e9b6682859068dc6fad5fd847a8c0290e2 | 2,361 | package org.innovateuk.ifs.commons.service;
import org.innovateuk.ifs.commons.error.ErrorHolder;
import org.innovateuk.ifs.util.ExceptionThrowingConsumer;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* An interface that represents a result of some process that can either fail or succeed. Additionally, it can then be chained with
* other functions to produce results in the event of successes or failures by "mapping" over this object with the "andOnSuccess()" and
* handleSuccessOrFailure() methods
*/
public interface FailingOrSucceedingResult<SuccessType, FailureType> extends ErrorHolder {
SuccessType getSuccess();
boolean isSuccess();
boolean isFailure();
FailureType getFailure();
<R> FailingOrSucceedingResult<R, FailureType> andOnSuccess(ExceptionThrowingFunction<? super SuccessType, FailingOrSucceedingResult<R, FailureType>> successHandler);
<R> FailingOrSucceedingResult<R, FailureType> andOnSuccess(Runnable successHandler);
FailingOrSucceedingResult<SuccessType, FailureType> andOnSuccessDo(Consumer<SuccessType> successHandler);
FailingOrSucceedingResult<Void, FailureType> andOnSuccessReturnVoid(Runnable successHandler);
<R> FailingOrSucceedingResult<R, FailureType> andOnSuccess(Supplier<? extends FailingOrSucceedingResult<R, FailureType>> successHandler);
<R> FailingOrSucceedingResult<R, FailureType> andOnSuccessReturn(Supplier<R> successHandler);
<R> FailingOrSucceedingResult<R, FailureType> andOnSuccessReturn(ExceptionThrowingFunction<? super SuccessType, R> successHandler);
<R> FailingOrSucceedingResult<R, FailureType> andOnFailure(Supplier<FailingOrSucceedingResult<R, FailureType>> failureHandler);
<R> R handleSuccessOrFailure(ExceptionThrowingFunction<? super FailureType, ? extends R> failureHandler, ExceptionThrowingFunction<? super SuccessType, ? extends R> successHandler);
FailingOrSucceedingResult<SuccessType, FailureType> handleSuccessOrFailureNoReturn(ExceptionThrowingConsumer<? super FailureType> failureHandler, ExceptionThrowingConsumer<? super SuccessType> successHandler);
Optional<SuccessType> getOptionalSuccessObject();
SuccessType getOrElse(ExceptionThrowingFunction<FailureType, SuccessType> failureHandler);
SuccessType getOrElse(SuccessType orElse);
}
| 46.294118 | 213 | 0.811097 |
31b72685717aad5cf0ad34a7970ae2fa08a58eec | 4,943 | package org.mozilla.javascript.commonjs.module.provider;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.mozilla.javascript.Scriptable;
/**
* Implemented by objects that can provide the source text for the script. The
* design of the interface supports cache revalidation.
* @version $Id: ModuleSourceProvider.java,v 1.3 2011/04/07 20:26:12 hannes%helma.at Exp $
*/
public interface ModuleSourceProvider
{
/**
* A special return value for {@link #loadSource(String, Scriptable,
* Object)} and {@link #loadSource(URI, Object)} that signifies that the
* cached representation is still valid according to the passed validator.
*/
public static final ModuleSource NOT_MODIFIED = new ModuleSource(null,
null, null, null, null);
/**
* Returns the script source of the requested module. More specifically, it
* resolves the module ID to a resource. If it can not resolve it, null is
* returned. If the caller passes a non-null validator, and the source
* provider recognizes it, and the validator applies to the same resource
* that the provider would use to load the source, and the validator
* validates the current cached representation of the resource (using
* whatever semantics for validation that this source provider implements),
* then {@link #NOT_MODIFIED} should be returned. Otherwise, it should
* return a {@link ModuleSource} object with the actual source text of the
* module, preferrably a validator for it, and a security domain, where
* applicable.
* @param moduleId the ID of the module. An implementation must only accept
* an absolute ID, starting with a term.
* @param paths the value of the require() function's "paths" attribute. If
* the require() function is sandboxed, it will be null, otherwise it will
* be a JavaScript Array object. It is up to the provider implementation
* whether and how it wants to honor the contents of the array.
* @param validator a validator for an existing loaded and cached module.
* This will either be null, or an object that this source provider
* returned earlier as part of a {@link ModuleSource}. It can be used to
* validate the existing cached module and avoid reloading it.
* @return a script representing the code of the module. Null should be
* returned if the script is not found. {@link #NOT_MODIFIED} should be
* returned if the passed validator validates the current representation of
* the module (the currently cached module script).
* @throws IOException if there was an I/O problem reading the script
* @throws URISyntaxException if the final URI could not be constructed.
* @throws IllegalArgumentException if the module ID is syntactically not a
* valid absolute module identifier.
*/
public ModuleSource loadSource(String moduleId, Scriptable paths, Object validator)
throws IOException, URISyntaxException;
/**
* Returns the script source of the requested module from the given URI.
* The URI is absolute but does not contain a file name extension such as
* ".js", which may be specific to the ModuleSourceProvider implementation.
* <p>
* If the resource is not found, null is returned. If the caller passes a
* non-null validator, and the source provider recognizes it, and the
* validator applies to the same resource that the provider would use to
* load the source, and the validator validates the current cached
* representation of the resource (using whatever semantics for validation
* that this source provider implements), then {@link #NOT_MODIFIED}
* should be returned. Otherwise, it should return a {@link ModuleSource}
* object with the actual source text of the module, preferrably a
* validator for it, and a security domain, where applicable.
* @param uri the absolute URI from which to load the module source, but
* without an extension such as ".js".
* @param validator a validator for an existing loaded and cached module.
* This will either be null, or an object that this source provider
* returned earlier as part of a {@link ModuleSource}. It can be used to
* validate the existing cached module and avoid reloading it.
* @return a script representing the code of the module. Null should be
* returned if the script is not found. {@link #NOT_MODIFIED} should be
* returned if the passed validator validates the current representation of
* the module (the currently cached module script).
* @throws IOException if there was an I/O problem reading the script
* @throws URISyntaxException if the final URI could not be constructed
*/
public ModuleSource loadSource(URI uri, Object validator)
throws IOException, URISyntaxException;
} | 56.816092 | 90 | 0.724054 |
2a37829d8dd2efbe09b881f165daa5cff72caa45 | 749 | package util;
/**
*
* desc:需求订单状态的枚举。
* 若需求订单状态有改变时,需要修改该枚举类。
* 修改时先行全局搜索类名
* @author L
* time:2018年5月15日
*/
public enum RequirementOrderStatus {
UNCONFIRM("待确认", 0),
DOING("进行中", 1),
CPMPLETE("已完成", 2),
PICKING_UP_GOODS("取货中", 3),
UN_CHECK_GOODS("待验货", 4),
DELIVERY_GOODS("送货中", 5),
EVALUATE("已评价", 6),
UNRECEIPT("待接单", 7);
private String name ;
private int id ;
private RequirementOrderStatus( String name , int id ){
this.name = name ;
this.id = id ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 17.022727 | 57 | 0.578104 |
960da05dfb1afde9dd34ab7d55a1e886e934c6a1 | 2,841 | package org.springframework.samples.petclinic.service;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.validation.ConstraintViolationException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.samples.petclinic.model.Propietario;
import org.springframework.samples.petclinic.repository.PropietarioRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class))
public class PropietarioServiceTests {
@Autowired
private PropietarioService propietarioService;
@Autowired
protected PropietarioRepository propietarioRepository;
@Test
public void testCountWithInitialData() {
int count= propietarioService.count();
assertEquals(count,1);
}
@Test
@Transactional
void shouldFindPropietario() {
java.util.Optional<Propietario> propietario = this.propietarioService.findById(1);
Propietario p= propietario.get();
assertThat(p.getName().equals("Abdel"));
assertThat(p.getApellido().equals("Ch"));
assertThat(p.getGmail().equals("[email protected]"));
assertThat(p.getTelefono().equals("602354622"));
assertThat(p.getContrasena().equals("12345"));
}
@Test
@Transactional
void shouldInsertPropietario() {
Propietario p = new Propietario();
p.setName("abdel");
p.setApellido("Chell");
p.setGmail("[email protected]");
p.setContrasena("1234567");
p.setTelefono("602343454");
this.propietarioRepository.save(p);
assertThat(p.getId()).isNotNull();
}
@Test
@Transactional
void shouldNotInsertPropietarioithWrongEmail() {
Propietario p = new Propietario();
p.setName("abdel");
p.setApellido("Ch");
p.setGmail("abdel");
p.setContrasena("1234567");
p.setTelefono("602343454");
assertThrows(ConstraintViolationException.class, () -> {
this.propietarioRepository.save(p);
});
}
@Test
@Transactional
void shouldNotInsertPropietarioWithWrongcontraseña() {
Propietario p = new Propietario();
p.setName("abdel");
p.setApellido("Ch");
p.setGmail("abdel");
p.setContrasena("1");
p.setTelefono("602343454");
assertThrows(ConstraintViolationException.class, () -> {
this.propietarioRepository.save(p);
});
}
@Test
@Transactional
void shouldUpdateNombre() {
Propietario p = new Propietario();
String nombre = p.getName();
String n =nombre +"abi";
p.setName(n);
this.propietarioRepository.save(p);
assertThat(p.getName()).isEqualTo(n);
}
}
| 27.317308 | 84 | 0.750088 |
2276e69601f3b6ba3bf1dd05beef37d259a82d24 | 926 | package com.concurnas.compiler.visitors.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PermutorWithCache {
private static HashMap<Integer, List<Boolean[]>> cache = new HashMap<Integer, List<Boolean[]>>();
/**
* Provide permutations whilst ignoring skipping null case (i.e. binary representation of 0)
*/
public static List<Boolean[]> permutationsWithoutNullCase(int n) {
List<Boolean[]> got = cache.get(n);
if(got == null){
got = new ArrayList<Boolean[]>();
for (int i = 1; i < (Math.pow(2, n)); i++) {
Boolean[] itm = new Boolean[n];
String bString = Integer.toBinaryString(i);
while(bString.length() < n){
bString = "0" + bString;
}
for(int m=0; m < bString.length(); m++){
if(bString.charAt(m)=='1'){
itm[m]=true;
}
}
got.add(itm);
}
cache.put(n, got);
}
return got;
}
}
| 22.047619 | 98 | 0.614471 |
9007fb6cf68f32782316adde3b8ff3c018144114 | 4,649 | package com.ofg.infrastructure.web.resttemplate.fluent;
import java.util.concurrent.Callable;
import org.springframework.web.client.RestOperations;
import com.nurkiewicz.asyncretry.AsyncRetryExecutor;
import com.nurkiewicz.asyncretry.RetryExecutor;
import com.nurkiewicz.asyncretry.SyncRetryExecutor;
import com.ofg.infrastructure.web.resttemplate.fluent.common.response.receive.PredefinedHttpHeaders;
import com.ofg.infrastructure.web.resttemplate.fluent.delete.DeleteMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.delete.DeleteMethodBuilder;
import com.ofg.infrastructure.web.resttemplate.fluent.get.GetMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.get.GetMethodBuilder;
import com.ofg.infrastructure.web.resttemplate.fluent.head.HeadMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.head.HeadMethodBuilder;
import com.ofg.infrastructure.web.resttemplate.fluent.options.OptionsMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.options.OptionsMethodBuilder;
import com.ofg.infrastructure.web.resttemplate.fluent.post.PostMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.post.PostMethodBuilder;
import com.ofg.infrastructure.web.resttemplate.fluent.put.PutMethod;
import com.ofg.infrastructure.web.resttemplate.fluent.put.PutMethodBuilder;
/**
* Point of entry of the fluent API over {@link RestOperations}.
* This class gives methods for each of the HttpMethods and delegates to the root of
* the fluent API of that method.
*
* @see DeleteMethod
* @see GetMethod
* @see HeadMethod
* @see OptionsMethod
* @see PostMethod
* @see PutMethod
*/
public class HttpMethodBuilder {
/**
* URL of an external URL or a service retrieved via service discovery
*/
private final Callable<String> serviceUrl;
private final RestOperations restOperations;
private final PredefinedHttpHeaders predefinedHeaders;
private final TracingInfo tracingInfo;
private RetryExecutor retryExecutor = SyncRetryExecutor.INSTANCE;
public HttpMethodBuilder(RestOperations restOperations, TracingInfo tracingInfo) {
this(new Callable<String>() {
@Override
public String call() throws Exception {
return "";
}
}, restOperations, PredefinedHttpHeaders.NO_PREDEFINED_HEADERS, tracingInfo);
}
public HttpMethodBuilder(Callable<String> serviceUrl, RestOperations restOperations,
PredefinedHttpHeaders predefinedHeaders, TracingInfo tracingInfo) {
this.predefinedHeaders = predefinedHeaders;
this.restOperations = restOperations;
this.serviceUrl = serviceUrl;
this.tracingInfo = tracingInfo;
}
/**
* Attaches pre-configured {@link RetryExecutor} to this request in order to retry in case of failure.
* The easiest way to add retry to your requests is to inject built-in {@link AsyncRetryExecutor}
* and customize it, e.g. to retry 3 times after failure with 500 millisecond delays between attempts:
* <p/>
* <pre>
* {@code
*
* @param retryExecutor
* @Autowired AsyncRetryExecutor executor
* <p/>
* //...
* <p/>
* .retryUsing(executor.withMaxRetries(3).withFixedBackoff(500))
* }
* </pre>
* @see <a href="https://github.com/nurkiewicz/async-retry">github.com/nurkiewicz/async-retry</a>
*/
public HttpMethodBuilder retryUsing(RetryExecutor retryExecutor) {
this.retryExecutor = retryExecutor;
return this;
}
public DeleteMethod delete() {
return new DeleteMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public GetMethod get() {
return new GetMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public HeadMethod head() {
return new HeadMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public OptionsMethod options() {
return new OptionsMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public PostMethod post() {
return new PostMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public PutMethod put() {
return new PutMethodBuilder(serviceUrl, restOperations, predefinedHeaders, retryExecutor, tracingInfo);
}
public static final Callable<String> EMPTY_HOST = new Callable<String>() {
@Override
public String call() throws Exception {
return "";
}
};
}
| 39.067227 | 115 | 0.736287 |
ee82224256c9e59524bec268c7e1efe7dfad914e | 732 | package com.ubalube.scifiaddon.util.Player.util;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTPrimitive;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.Capability.IStorage;
public class LoadoutStorage implements IStorage<ILoadout> {
@Override
public NBTBase writeNBT(Capability<ILoadout> capability, ILoadout instance, EnumFacing side)
{
return new NBTTagInt(instance.getLoadoutID());
}
@Override
public void readNBT(Capability<ILoadout> capability, ILoadout instance, EnumFacing side, NBTBase nbt)
{
instance.setLoadoutID(((NBTPrimitive) nbt).getInt());
}
}
| 30.5 | 103 | 0.797814 |
d87e86186fb681c973bbc52fb251d2ceaee0b484 | 3,395 | /*
* #%L
* de.metas.manufacturing
* %%
* Copyright (C) 2021 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package org.eevolution.productioncandidate.service;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import de.metas.material.event.pporder.MaterialDispoGroupId;
import de.metas.material.planning.ProductPlanningId;
import de.metas.order.OrderLineId;
import de.metas.organization.ClientAndOrgId;
import de.metas.product.ProductId;
import de.metas.product.ResourceId;
import de.metas.quantity.Quantity;
import de.metas.util.Check;
import lombok.Builder;
import lombok.NonNull;
import lombok.Value;
import org.adempiere.mm.attributes.AttributeSetInstanceId;
import org.adempiere.warehouse.WarehouseId;
import org.eevolution.api.PPOrderCreateRequest;
import de.metas.inout.ShipmentScheduleId;
import javax.annotation.Nullable;
import java.time.Instant;
@Value
@JsonDeserialize(builder = PPOrderCreateRequest.PPOrderCreateRequestBuilder.class)
public class PPOrderCandidateCreateRequest
{
ClientAndOrgId clientAndOrgId;
ProductPlanningId productPlanningId;
MaterialDispoGroupId materialDispoGroupId;
ResourceId plantId;
WarehouseId warehouseId;
ProductId productId;
AttributeSetInstanceId attributeSetInstanceId;
Quantity qtyRequired;
Instant datePromised;
Instant dateStartSchedule;
OrderLineId salesOrderLineId;
ShipmentScheduleId shipmentScheduleId;
@Builder
public PPOrderCandidateCreateRequest(
@NonNull final ClientAndOrgId clientAndOrgId,
@Nullable final ProductPlanningId productPlanningId,
@Nullable final MaterialDispoGroupId materialDispoGroupId,
@NonNull final ResourceId plantId,
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final AttributeSetInstanceId attributeSetInstanceId,
@NonNull final Quantity qtyRequired,
@NonNull final Instant datePromised,
@NonNull final Instant dateStartSchedule,
@Nullable final OrderLineId salesOrderLineId,
@Nullable final ShipmentScheduleId shipmentScheduleId)
{
Check.assume(!qtyRequired.isZero(), "qtyRequired shall not be zero");
this.clientAndOrgId = clientAndOrgId;
this.productPlanningId = productPlanningId;
this.materialDispoGroupId = materialDispoGroupId;
this.plantId = plantId;
this.warehouseId = warehouseId;
this.productId = productId;
this.attributeSetInstanceId = attributeSetInstanceId;
this.qtyRequired = qtyRequired;
this.datePromised = datePromised;
this.dateStartSchedule = dateStartSchedule;
this.salesOrderLineId = salesOrderLineId;
this.shipmentScheduleId = shipmentScheduleId;
}
@JsonPOJOBuilder(withPrefix = "")
public static class PPOrderCreateRequestBuilder
{
}
} | 34.642857 | 82 | 0.805596 |
92df4feb475b04382a093118c88a3c3b59c7b154 | 314 | package com.helospark.tactview.core.timeline.effect.interpolation;
public class ValueProviderError {
private String errorMessage;
public ValueProviderError(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
| 20.933333 | 66 | 0.72293 |
5cc9592c28fc5f5a3deea60c58ecb54ddd4b5035 | 309 | package com.jdc.book.root.dto;
import lombok.Data;
@Data
public class Category {
private int id;
private String name;
public Category() {
}
public Category(String name) {
super();
this.name = name;
}
public Category(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
| 11.884615 | 39 | 0.650485 |
5ebac6f174852b8f401fb232f7f0addc9f50476f | 326 | package es.ipo.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class bibliotecaController {
@GetMapping(value= {"/biblioteca"})
public String serveBiblio(Model model) {
return "biblioteca";
}
}
| 20.375 | 58 | 0.785276 |
fc8c69bb1891bf4e4c57f693fea495df5aeb60a9 | 6,238 | package cc.eguid.cv.videoRecorder.manager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import cc.eguid.cv.videoRecorder.entity.RecordTask;
import cc.eguid.cv.videoRecorder.recorder.JavaCVRecord;
import cc.eguid.cv.videoRecorder.recorder.Recorder;
/**
* 默认任务管理(内置对象池管理)
*
* @author eguid
*
*/
public class DefaultTasksManager implements TasksManager {
public static final int START_STATUS = 1;
public static final int PAUSE_STATUS = -1;
public static final int STOP_STATUS = 2;
protected static volatile int task_id_index = 0;// id累加
protected volatile int maxSize = -1;// 最大任务限制,如果小于0则无限大
private String record_dir;//文件存储目录
private String play_url;//播放地址
public String getRecordDir() {
return record_dir;
}
public String getPlay_url() {
return play_url;
}
@Override
public TasksManager setPlayUrl(String play_url) {
this.play_url = play_url;
return this;
}
@Override
public TasksManager setRecordDir(String recordDir) {
this.record_dir = recordDir;
return this;
}
// 对象池操作
// 当前任务池大小
protected volatile int pool_size = 0;
// 当前任务池中数量
protected volatile int work_size = 0;
// 当前空闲任务数量
protected volatile int idle_size = 0;
/** 工作任务池 */
protected Queue<RecordTask> workpool = null;
/** 空闲任务池 */
protected Stack<RecordTask> idlepool = null;
/**
* 初始化
* @param maxSize -最大工作任务大小
* @param historyStorage -历史任务存储
* @throws Exception
*/
public DefaultTasksManager(int maxSize) throws Exception {
super();
if (maxSize < 1) {
throw new Exception("maxSize不能空不能小于1");
}
this.maxSize = maxSize;
this.workpool = new ConcurrentLinkedQueue<>();
this.idlepool = new Stack<>();
}
@Override
public synchronized RecordTask createRcorder(String src, String out) throws Exception {
RecordTask task = null;
Recorder recorder=null;
int id = getId();
// System.out.println("创建时,当前池数量:"+pool_size+",空闲数量:"+idle_size+",工作数量:"+work_size);
// 限制任务线程数量,先看有无空闲,再创建新的
String playurl=(play_url==null?out:play_url+out);
out =(record_dir==null?out:record_dir+out);
if (idle_size > 0) {// 如果有空闲任务,先从空闲任务池中获取
idle_size--;//空闲池数量减少
task=idlepool.pop();
task.setId(id);
task.setOut(out);
task.setSrc(src);
task.setPlayurl(playurl);
saveTaskAndinitRecorder(task);
return task;
}else if (pool_size <maxSize) {// 池中总数量未超出,则新建,若超出,不创建
recorder = new JavaCVRecord(src, out);
task = new RecordTask(id, src, out, recorder);
task.setPlayurl(playurl);
saveTaskAndinitRecorder(task);
pool_size++;// 池中活动数量增加
return task;
}
//池中数量已满,且空闲池以空,返回null
// 超出限制数量,返回空
return null;
}
@Override
public boolean start(RecordTask task) {
if(task!=null) {
Recorder recorder = task.getRecorder();
task.setstarttime(now());// 设置开始时间
task.setStatus(START_STATUS);// 状态设为开始
recorder.start();
return true;
}
return false;
}
@Override
public boolean pause(RecordTask task) {
if(task!=null) {
task.setEndtime(now());
task.setStatus(PAUSE_STATUS);// 状态设为暂停
task.getRecorder().pause();
}
return false;
}
@Override
public boolean carryon(RecordTask task) {
if(task!=null) {
task.getRecorder().carryon();
task.setStatus(START_STATUS);// 状态设为开始
}
return false;
}
@Override
public boolean stop(RecordTask task) {
if (task!=null) {
task.getRecorder().stop();// 停止录制
return recycleTask(task);
}
return false;
}
/**
* 回收对象
* @return
*/
private boolean recycleTask(RecordTask task) {
if (task!=null&&pool_size > 0 && work_size > 0 ) {
task.setEndtime(now());
task.setStatus(STOP_STATUS);
// 工作池中有没有
if (!workpool.contains(task)) {
return false;
}
// 从工作池中删除,存入空闲池
if (idlepool.add(task)) {
idle_size++;
if (workpool.remove(task)) {
work_size--;
// System.out.println("归还后,当前池数量:"+pool_size+",空闲数量:"+idle_size+",工作数量:"+work_size);
return true;
}
}
}
return false;
}
@Override
public List<RecordTask> list() {
List<RecordTask> list=new ArrayList<>();
Iterator<RecordTask> itor=workpool.iterator();
for(;itor.hasNext();) {
list.add(itor.next());
}
return list;
}
@Override
public RecordTask getRcorderTask(Integer id) {
Iterator<RecordTask> itor=workpool.iterator();
for(;itor.hasNext();) {
RecordTask task=itor.next();
if(task.getId()==id) {
return task;
}
}
return null;
}
/*
* 保存任务并初始化录制器
* @param task
* @throws CloneNotSupportedException
* @throws IOException
*/
private void saveTaskAndinitRecorder(RecordTask task) throws CloneNotSupportedException, IOException {
Recorder recorder=task.getRecorder();
recorder.from(task.getSrc()).to(task.getOut());//重新设置视频源和输出
workpool.add(task);
//由于使用的是池中的引用,所以使用克隆用于保存副本
work_size++;//工作池数量增加
}
/*
* 获取当前时间
*
* @return
*/
private Date now() {
return new Date();
}
/*
* 获取自增id
* @return
*/
private int getId() {
return ++task_id_index;
}
/**
* 线程保活和销毁定时器
* @author eguid
*
*/
class WorkerThreadTimer{
private Timer timer=null;
private int period=60*1000;
public WorkerThreadTimer(int period){
this.period=period;
timer=new Timer("录像线程池保活定时器",false);
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public void start() {
timer.schedule(new TimerTask() {
@Override
public void run() {
for(RecordTask rt:idlepool) {
Recorder r=rt.getRecorder();
if(r!=null&&r.alive()) {
//如果线程已经停止,回收该线程到空闲池
int status=r.status();
if(status==2) {
recycleTask(rt);
}
}
}
}
},period, period);
}
}
@Override
public boolean exist(String src, String out) {
// System.err.println("检查本地服务是否在工作的录像任务:"+src+","+out);
int index=-1;
for(RecordTask rt:workpool) {
// System.err.println("循环中:"+rt);
if(src.equals(rt.getSrc())&&rt.getOut().contains(out)) {
index++;
break;
}
}
// System.err.println("检查本地服务是否在工作的录像任务结果:"+index);
return index>=0;
}
}
| 21.290102 | 103 | 0.67185 |
af526d3d3263ecb54d2f5a2ec42dabcd08f36f57 | 925 | package com.aliyun.openservices.log.response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.aliyun.openservices.log.common.Machine;
public class ListMachinesResponse extends Response {
/**
*
*/
private static final long serialVersionUID = 4626637425501553843L;
protected int total = 0;
protected int count = 0;
protected List<Machine> machines = new ArrayList<Machine>();
public ListMachinesResponse(Map<String, String> headers, int count, int total, List<Machine> machines) {
super(headers);
this.total = total;
this.count = count;
SetMachines(machines);
}
public int GetTotal() {
return total;
}
public int GetCount() {
return count;
}
public List<Machine> GetMachines() {
return machines;
}
private void SetMachines(List<Machine> machines) {
this.machines = new ArrayList<Machine>(machines);
}
}
| 22.02381 | 106 | 0.699459 |
3955eae72f7fcfa4055300b651c2f79382c392f6 | 597 | import java.util.Random;
import com.allmycode.dummiesframe.DummiesFrame;
public class GuessingGameFrame {
public static void main(String args[]) {
DummiesFrame frame = new DummiesFrame("Guess the number game");
frame.addRow("Input number 1 to 10");
frame.setButtonText("Click this button");
frame.go();
}
public static String calculate(int inputNumber) {
Random random = new Random();
int randomNumber = random.nextInt(10) + 1;
if (inputNumber == randomNumber) {
return "You won";
} else {
return "You lose. We thought the random number " + randomNumber + ".";
}
}
}
| 27.136364 | 73 | 0.703518 |
ca6bbbd883626f176d606c14cb857d5d41a801c4 | 8,062 | package com.ntk.ehcrawler.activities;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.ntk.R;
import com.ntk.ehcrawler.EHConstants;
import com.ntk.ehcrawler.adapters.ThumbAdapter;
import com.ntk.ehcrawler.database.BookProvider;
import com.ntk.ehcrawler.model.BookConstants;
import com.ntk.ehcrawler.model.PageConstants;
import com.ntk.ehcrawler.services.DatabaseService;
import com.ntk.ehcrawler.services.DownloadService;
public class GalleryActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
private String mURL;
private RecyclerView mThumbView;
private ThumbAdapter mAdapter;
private String mId;
private int mCurrentPosition;
private boolean mNeedScroll;
private View mLoading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Intent intent = getIntent();
mURL = intent.getStringExtra(BookConstants.URL);
mId = intent.getStringExtra(BookConstants._ID);
int bookSize = intent.getIntExtra(BookConstants.FILE_COUNT, 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mThumbView = (RecyclerView) findViewById(R.id.gallery_thumbnails_rv);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
mThumbView.setLayoutManager(layoutManager);
mAdapter = new ThumbAdapter(this, bookSize);
mThumbView.setAdapter(mAdapter);
mLoading = findViewById(R.id.loading);
getSupportLoaderManager().initLoader(BookProvider.BOOK_INFO_LOADER, null, this);
getSupportLoaderManager().initLoader(BookProvider.PAGE_INFO_LOADER, null, this);
getSupportLoaderManager().initLoader(BookProvider.BOOK_STATUS_LOADER, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Context context = this;
Uri uri = null;
String[] projection = null;
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
switch (id){
case BookProvider.BOOK_INFO_LOADER:
uri = Uri.withAppendedPath(BookProvider.BOOKS_CONTENT_URI, mId);
projection = BookConstants.PROJECTION;
selection = BookConstants.URL.concat("=?");
selectionArgs = new String[]{mURL};
break;
case BookProvider.BOOK_STATUS_LOADER:
uri = BookProvider.BOOK_STATUS_CONTENT_URI;
projection = BookConstants.BOOK_STATUS_PROJECTION;
selection = BookConstants.URL.concat("=?");
selectionArgs = new String[]{mURL};
break;
case BookProvider.PAGE_INFO_LOADER:
uri = BookProvider.PAGES_CONTENT_URI;
projection = PageConstants.PROJECTION;
selection = PageConstants.BOOK_URL.concat("=?");
selectionArgs = new String[]{mURL};
break;
}
return new CursorLoader(context, uri, projection, selection, selectionArgs, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
switch (loader.getId()){
case BookProvider.BOOK_INFO_LOADER:
setInfoForBook(data);
break;
case BookProvider.BOOK_STATUS_LOADER:
setReadStatus(data);
mNeedScroll = true;
break;
case BookProvider.PAGE_INFO_LOADER:
setPagesInfo(data);
break;
}
if(mNeedScroll){
mThumbView.scrollToPosition(mCurrentPosition);
/* in case data is cleared, page data need to reload step by step
* we cannot need to call load new data, util it scrolls to position */
mNeedScroll = data.getCount() < mCurrentPosition;
}
}
private void setPagesInfo(Cursor data) {
if(data.getCount()<1){
getBookDetail();
}else {
mAdapter.changeCursor(data);
}
}
private void setReadStatus(Cursor data) {
if(!data.moveToFirst()) return;
mCurrentPosition = data.getInt(BookConstants.CURRENT_POSITION_INDEX);
}
private void setInfoForBook(Cursor data) {
if(!data.moveToFirst()) return;
mId = data.getString(0);
final String url = data.getString(BookConstants.URL_INDEX);
final int fileCount = data.getInt(BookConstants.FILE_COUNT_INDEX);
final String title = data.getString(BookConstants.TITLE_INDEX);
final String detail = data.getString(BookConstants.DETAIL_INDEX);
final String tags = data.getString(BookConstants.TAGS_INDEX);
final Boolean isFavorite = data.getInt(BookConstants.IS_FAVORITE_INDEX)==1;
if (!TextUtils.isEmpty(detail)) {
final TextView mTitle = (TextView) findViewById(R.id.title_tv);
final TextView mDetail = (TextView) findViewById(R.id.details_tv);
final TextView mTags = (TextView) findViewById(R.id.tags_tv);
final FloatingActionButton fabFavorite = (FloatingActionButton) findViewById(R.id.fab_favorite);
final FloatingActionButton fabDownload = (FloatingActionButton) findViewById(R.id.fab_download);
final FloatingActionButton fabPlay = (FloatingActionButton) findViewById(R.id.fab_play);
fabFavorite.setOnClickListener( new View.OnClickListener(){
@Override
public void onClick(View view) {
DatabaseService.startFavoriteBook(GalleryActivity.this, mId, !isFavorite);
fabFavorite.setImageResource(!isFavorite ? R.drawable.ic_favorite : R.drawable.ic_not_favorite);
}
});
fabFavorite.setVisibility(View.VISIBLE);
fabFavorite.setImageResource(isFavorite ? R.drawable.ic_favorite : R.drawable.ic_not_favorite);
fabDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DownloadService.startDownloadBook(GalleryActivity.this, mURL);
fabDownload.setVisibility(View.GONE);
}
});
fabDownload.setVisibility(View.VISIBLE);
fabPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GalleryActivity.this, FullscreenActivity.class);
intent.putExtra(BookConstants.URL, url);
intent.putExtra(BookConstants.FILE_COUNT, fileCount);
intent.putExtra(EHConstants.POSITION, mCurrentPosition);
startActivity(intent);
}
});
fabPlay.setVisibility(View.VISIBLE);
mTitle.setText(title);
mDetail.setText(detail);
mTags.setText(tags);
mLoading.setVisibility(View.GONE);
}
}
private void getBookDetail() {
mLoading.setVisibility(View.VISIBLE);
DatabaseService.startGetBookDetail(this, mId, mURL, 0);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| 41.556701 | 117 | 0.655172 |
db70cfb560673060caef9c20b13195785e6a8594 | 763 | package com.taobao.tddl.optimizer.costbased.after;
import java.util.Map;
import com.taobao.tddl.common.jdbc.ParameterContext;
import com.taobao.tddl.optimizer.core.plan.IDataNodeExecutor;
import com.taobao.tddl.optimizer.exceptions.QueryException;
/**
* <pre>
* 对执行计划树的优化,包含以下几个步骤:
* s8.为执行计划的每个节点选择执行的GroupNode
* 这一步是根据TDDL的规则进行分库 在Join,Merge的执行节点选择上,遵循的原则是尽量减少网络传输
*
* s9.调整分库后的Join节点
* 由于分库后,一个Query节点可能会变成一个Merge节点,需要对包含这样子节点的Join节点进行调整,详细见splitJoinAfterChooseDataNode的注释
* </pre>
*
* @since 5.0.0
*/
public interface QueryPlanOptimizer {
IDataNodeExecutor optimize(IDataNodeExecutor dne, Map<Integer, ParameterContext> parameterSettings,
Map<String, Object> extraCmd) throws QueryException;
}
| 29.346154 | 103 | 0.756225 |
ffc9d53906ef5bbe9150963df9fa578471a01d29 | 439 | package fr.openwide.maven.artifact.notifier.core.business.search.service;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.ArtifactVersion;
public interface IMavenCentralSearchUrlService {
String getGroupUrl(String groupId);
String getArtifactUrl(String groupId, String artifactId);
String getVersionUrl(String groupId, String artifactId, String version);
String getVersionUrl(ArtifactVersion version);
}
| 29.266667 | 88 | 0.831435 |
0d0b15f354e27e28d30669db048c01888a8601f7 | 4,156 | /*
* 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.openjpa.jdbc.meta.strats;
import java.lang.reflect.Method;
import org.apache.openjpa.jdbc.identifier.DBIdentifier;
import org.apache.openjpa.jdbc.kernel.JDBCStore;
import org.apache.openjpa.jdbc.meta.ValueMapping;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.ColumnIO;
import org.apache.openjpa.jdbc.sql.DBDictionary;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.meta.JavaTypes;
import org.apache.openjpa.util.Exceptions;
import org.apache.openjpa.util.MetaDataException;
/**
* Value handler for JDK1.5 enum field types.
*
*/
public class EnumValueHandler extends AbstractValueHandler {
private static final long serialVersionUID = 1L;
private Enum<?>[] _vals = null;
private boolean _ordinal = false;
private static final Localizer _loc = Localizer.forPackage(EnumValueHandler.class);
/**
* Whether to store the enum value as its ordinal.
*/
public boolean getStoreOrdinal() {
return _ordinal;
}
/**
* Whether to store the enum value as its ordinal.
*/
public void setStoreOrdinal(boolean ordinal) {
_ordinal = ordinal;
}
/**
* @deprecated
*/
@Deprecated
@Override
public Column[] map(ValueMapping vm, String name, ColumnIO io,
boolean adapt) {
DBDictionary dict = vm.getMappingRepository().getDBDictionary();
DBIdentifier colName = DBIdentifier.newColumn(name, dict != null ? dict.delimitAll() : false);
return map(vm, colName, io, adapt);
}
public Column[] map(ValueMapping vm, DBIdentifier name, ColumnIO io,
boolean adapt) {
// all enum classes have a static method called 'values()'
// that returns an array of all the enum values
try {
Method m = vm.getType().getMethod("values", (Class[]) null);
_vals = (Enum[]) m.invoke(null, (Object[]) null);
} catch (Exception e) {
throw new MetaDataException(_loc.get("not-enum-field",
vm.getFieldMapping().getFullName(true), Exceptions.toClassName(vm.getType()))).setCause(e);
}
Column col = new Column();
col.setIdentifier(name);
if (_ordinal)
col.setJavaType(JavaTypes.SHORT);
else {
// look for the longest enum value name; use 20 as min length to
// leave room for future long names
int len = 20;
for (int i = 0; i < _vals.length; i++)
len = Math.max(_vals[i].name().length(), len);
col.setJavaType(JavaTypes.STRING);
col.setSize(len);
}
return new Column[]{ col };
}
@Override
public boolean isVersionable(ValueMapping vm) {
return true;
}
@Override
public Object toDataStoreValue(ValueMapping vm, Object val, JDBCStore store) {
if (val == null)
return null;
if (_ordinal)
return Integer.valueOf(((Enum) val).ordinal());
return ((Enum) val).name();
}
@Override
public Object toObjectValue(ValueMapping vm, Object val) {
if (val == null)
return null;
if (_ordinal)
return _vals[((Number) val).intValue()];
return Enum.valueOf(vm.getType(), (String) val);
}
}
| 33.788618 | 111 | 0.652069 |
ed6fd94ebca701437c735c842ffd67876806c407 | 164 | package com.designpattern.creational.factorymethod;
public class CombustionCar implements Car {
public String getEnergy() {
return "Gasoline";
}
}
| 20.5 | 51 | 0.719512 |
3a7dc1534ad5961bebc1eb3c146ac3fa919c6b01 | 343 | package com.knyaz.testtask.base.mvp;
public class State {
public static final int CREATE = 0;
public static final int START = 1;
public static final int RESUME = 2;
public static final int PAUSE = 3;
public static final int STOP = 4;
public static final int DESTROY_VIEW = 5;
public static final int DESTROY = 6;
} | 31.181818 | 45 | 0.693878 |
5e9b774a380c71fb2c4c5b8cbcef5cf707d1171a | 1,186 | package com.swak.swing.support;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 基础的页面
*
* @author lifeng
* @date 2020年5月21日 上午10:35:04
*/
public abstract class AbstractPage {
protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractPage.class);
protected CompletableFuture<Void> initFuture = new CompletableFuture<>();
protected CompletableFuture<Void> closeFuture = new CompletableFuture<>();
/**
* 初始化
*/
public AbstractPage() {
this.initialize();
}
/**
* 顶层初始化
*/
public void initialize() {
this.initFuture.complete(null);
}
/**
* 界面显示
*/
public abstract void show();
/**
* 界面关闭
*/
public abstract void close();
/**
* 等待页面关闭
*/
public CompletableFuture<Void> waitClose() {
if (!closeFuture.isDone()) {
closeFuture.complete(null);
}
return initFuture.thenCompose((v) -> {
return closeFuture;
});
}
/**
* 当初始化之后需要处理
*
* @return
*/
public CompletableFuture<Void> whenInited() {
return this.initFuture;
}
/**
* 当结束之后需要处理
*
* @return
*/
public CompletableFuture<Void> whenClosed() {
return this.closeFuture;
}
}
| 15.813333 | 84 | 0.666105 |
ce6432135c0c3dd903a75cc16e1c52dae1e5ce92 | 33,166 | /*
* Copyright 2015 Goldman Sachs.
*
* 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.gs.collections.impl.list.mutable;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.RandomAccess;
import java.util.concurrent.ExecutorService;
import com.gs.collections.api.block.HashingStrategy;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.Function3;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.list.ParallelListIterable;
import com.gs.collections.api.list.primitive.MutableBooleanList;
import com.gs.collections.api.list.primitive.MutableByteList;
import com.gs.collections.api.list.primitive.MutableCharList;
import com.gs.collections.api.list.primitive.MutableDoubleList;
import com.gs.collections.api.list.primitive.MutableFloatList;
import com.gs.collections.api.list.primitive.MutableIntList;
import com.gs.collections.api.list.primitive.MutableLongList;
import com.gs.collections.api.list.primitive.MutableShortList;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.ordered.OrderedIterable;
import com.gs.collections.api.partition.list.PartitionMutableList;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.stack.MutableStack;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.Twin;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.HashingStrategies;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.collection.mutable.AbstractMutableCollection;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.factory.Stacks;
import com.gs.collections.impl.lazy.ReverseIterable;
import com.gs.collections.impl.lazy.parallel.list.ListIterableParallelIterable;
import com.gs.collections.impl.multimap.list.FastListMultimap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import com.gs.collections.impl.stack.mutable.ArrayStack;
import com.gs.collections.impl.utility.Iterate;
import com.gs.collections.impl.utility.ListIterate;
import com.gs.collections.impl.utility.OrderedIterate;
public abstract class AbstractMutableList<T>
extends AbstractMutableCollection<T>
implements MutableList<T>
{
private static final IntObjectToIntFunction<?> HASH_CODE_FUNCTION = new IntObjectToIntFunction<Object>()
{
public int intValueOf(int hashCode, Object item)
{
return 31 * hashCode + (item == null ? 0 : item.hashCode());
}
};
@Override
public MutableList<T> clone()
{
try
{
return (MutableList<T>) super.clone();
}
catch (CloneNotSupportedException e)
{
throw new AssertionError(e);
}
}
@Override
public boolean equals(Object that)
{
return this == that || (that instanceof List && ListIterate.equals(this, (List<?>) that));
}
@Override
public int hashCode()
{
// Optimize injectInto in subclasses if necessary
return this.injectInto(1, (IntObjectToIntFunction<T>) HASH_CODE_FUNCTION);
}
public void each(Procedure<? super T> procedure)
{
ListIterate.forEach(this, procedure);
}
public void reverseForEach(Procedure<? super T> procedure)
{
if (this.notEmpty())
{
this.forEach(this.size() - 1, 0, procedure);
}
}
@Override
public void forEachWithIndex(ObjectIntProcedure<? super T> objectIntProcedure)
{
ListIterate.forEachWithIndex(this, objectIntProcedure);
}
@Override
public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter)
{
ListIterate.forEachWith(this, procedure, parameter);
}
@Override
public <S, R extends Collection<Pair<T, S>>> R zip(Iterable<S> that, R target)
{
return ListIterate.zip(this, that, target);
}
@Override
public <R extends Collection<Pair<T, Integer>>> R zipWithIndex(R target)
{
return ListIterate.zipWithIndex(this, target);
}
public void forEachWithIndex(int fromIndex, int toIndex, ObjectIntProcedure<? super T> objectIntProcedure)
{
ListIterate.forEachWithIndex(this, fromIndex, toIndex, objectIntProcedure);
}
public MutableList<T> select(Predicate<? super T> predicate)
{
return this.select(predicate, this.newEmpty());
}
@Override
public <R extends Collection<T>> R select(Predicate<? super T> predicate, R target)
{
return ListIterate.select(this, predicate, target);
}
public <P> MutableList<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return this.selectWith(predicate, parameter, this.newEmpty());
}
@Override
public <P, R extends Collection<T>> R selectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R target)
{
return ListIterate.selectWith(this, predicate, parameter, target);
}
public MutableList<T> reject(Predicate<? super T> predicate)
{
return this.reject(predicate, this.newEmpty());
}
@Override
public <R extends Collection<T>> R reject(Predicate<? super T> predicate, R target)
{
return ListIterate.reject(this, predicate, target);
}
public <P> MutableList<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return this.rejectWith(predicate, parameter, this.newEmpty());
}
@Override
public <P, R extends Collection<T>> R rejectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R target)
{
return ListIterate.rejectWith(this, predicate, parameter, target);
}
@Override
public <P> Twin<MutableList<T>> selectAndRejectWith(
Predicate2<? super T, ? super P> predicate,
P parameter)
{
return ListIterate.selectAndRejectWith(this, predicate, parameter);
}
public PartitionMutableList<T> partition(Predicate<? super T> predicate)
{
return ListIterate.partition(this, predicate);
}
public <P> PartitionMutableList<T> partitionWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.partitionWith(this, predicate, parameter);
}
public <S> MutableList<S> selectInstancesOf(Class<S> clazz)
{
return ListIterate.selectInstancesOf(this, clazz);
}
@Override
public boolean removeIf(Predicate<? super T> predicate)
{
return ListIterate.removeIf(this, predicate);
}
@Override
public <P> boolean removeIfWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.removeIfWith(this, predicate, parameter);
}
public <V> MutableList<V> collect(Function<? super T, ? extends V> function)
{
return this.collect(function, FastList.<V>newList());
}
public MutableBooleanList collectBoolean(BooleanFunction<? super T> booleanFunction)
{
return ListIterate.collectBoolean(this, booleanFunction);
}
public MutableByteList collectByte(ByteFunction<? super T> byteFunction)
{
return ListIterate.collectByte(this, byteFunction);
}
public MutableCharList collectChar(CharFunction<? super T> charFunction)
{
return ListIterate.collectChar(this, charFunction);
}
public MutableDoubleList collectDouble(DoubleFunction<? super T> doubleFunction)
{
return ListIterate.collectDouble(this, doubleFunction);
}
public MutableFloatList collectFloat(FloatFunction<? super T> floatFunction)
{
return ListIterate.collectFloat(this, floatFunction);
}
public MutableIntList collectInt(IntFunction<? super T> intFunction)
{
return ListIterate.collectInt(this, intFunction);
}
public MutableLongList collectLong(LongFunction<? super T> longFunction)
{
return ListIterate.collectLong(this, longFunction);
}
public MutableShortList collectShort(ShortFunction<? super T> shortFunction)
{
return ListIterate.collectShort(this, shortFunction);
}
@Override
public <V, R extends Collection<V>> R collect(Function<? super T, ? extends V> function, R target)
{
return ListIterate.collect(this, function, target);
}
public <V> MutableList<V> flatCollect(Function<? super T, ? extends Iterable<V>> function)
{
return this.flatCollect(function, FastList.<V>newList());
}
@Override
public <V, R extends Collection<V>> R flatCollect(
Function<? super T, ? extends Iterable<V>> function, R target)
{
return ListIterate.flatCollect(this, function, target);
}
public <P, V> MutableList<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter)
{
return this.collectWith(function, parameter, FastList.<V>newList());
}
@Override
public <P, A, R extends Collection<A>> R collectWith(
Function2<? super T, ? super P, ? extends A> function, P parameter, R target)
{
return ListIterate.collectWith(this, function, parameter, target);
}
public <V> MutableList<V> collectIf(
Predicate<? super T> predicate, Function<? super T, ? extends V> function)
{
return this.collectIf(predicate, function, FastList.<V>newList());
}
@Override
public <V, R extends Collection<V>> R collectIf(
Predicate<? super T> predicate,
Function<? super T, ? extends V> function,
R target)
{
return ListIterate.collectIf(this, predicate, function, target);
}
@Override
public T detect(Predicate<? super T> predicate)
{
return ListIterate.detect(this, predicate);
}
@Override
public T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function)
{
T result = this.detect(predicate);
return result == null ? function.value() : result;
}
public int detectIndex(Predicate<? super T> predicate)
{
return ListIterate.detectIndex(this, predicate);
}
public int detectLastIndex(Predicate<? super T> predicate)
{
return ListIterate.detectLastIndex(this, predicate);
}
@Override
public T min(Comparator<? super T> comparator)
{
return ListIterate.min(this, comparator);
}
@Override
public T max(Comparator<? super T> comparator)
{
return ListIterate.max(this, comparator);
}
@Override
public T min()
{
return ListIterate.min(this);
}
@Override
public T max()
{
return ListIterate.max(this);
}
@Override
public <V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function)
{
return ListIterate.minBy(this, function);
}
@Override
public <V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function)
{
return ListIterate.maxBy(this, function);
}
@Override
public <P> T detectWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.detectWith(this, predicate, parameter);
}
@Override
public <P> T detectWithIfNone(
Predicate2<? super T, ? super P> predicate,
P parameter,
Function0<? extends T> function)
{
T result = ListIterate.detectWith(this, predicate, parameter);
return result == null ? function.value() : result;
}
@Override
public int count(Predicate<? super T> predicate)
{
return ListIterate.count(this, predicate);
}
@Override
public <P> int countWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.countWith(this, predicate, parameter);
}
public <S> boolean corresponds(OrderedIterable<S> other, Predicate2<? super T, ? super S> predicate)
{
return OrderedIterate.corresponds(this, other, predicate);
}
@Override
public boolean anySatisfy(Predicate<? super T> predicate)
{
return ListIterate.anySatisfy(this, predicate);
}
@Override
public <P> boolean anySatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.anySatisfyWith(this, predicate, parameter);
}
@Override
public boolean allSatisfy(Predicate<? super T> predicate)
{
return ListIterate.allSatisfy(this, predicate);
}
@Override
public <P> boolean allSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.allSatisfyWith(this, predicate, parameter);
}
@Override
public boolean noneSatisfy(Predicate<? super T> predicate)
{
return ListIterate.noneSatisfy(this, predicate);
}
@Override
public <P> boolean noneSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
{
return ListIterate.noneSatisfyWith(this, predicate, parameter);
}
@Override
public <IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super T, ? extends IV> function)
{
return ListIterate.injectInto(injectedValue, this, function);
}
@Override
public int injectInto(int injectedValue, IntObjectToIntFunction<? super T> function)
{
return ListIterate.injectInto(injectedValue, this, function);
}
@Override
public float injectInto(float injectedValue, FloatObjectToFloatFunction<? super T> function)
{
return ListIterate.injectInto(injectedValue, this, function);
}
public MutableList<T> distinct()
{
return ListIterate.distinct(this);
}
public MutableList<T> distinct(HashingStrategy<? super T> hashingStrategy)
{
return ListIterate.distinct(this, hashingStrategy);
}
@Override
public long sumOfInt(IntFunction<? super T> function)
{
return ListIterate.sumOfInt(this, function);
}
@Override
public long sumOfLong(LongFunction<? super T> function)
{
return ListIterate.sumOfLong(this, function);
}
@Override
public double sumOfFloat(FloatFunction<? super T> function)
{
return ListIterate.sumOfFloat(this, function);
}
@Override
public double sumOfDouble(DoubleFunction<? super T> function)
{
return ListIterate.sumOfDouble(this, function);
}
@Override
public long injectInto(long injectedValue, LongObjectToLongFunction<? super T> function)
{
return ListIterate.injectInto(injectedValue, this, function);
}
@Override
public <IV, P> IV injectIntoWith(
IV injectValue, Function3<? super IV, ? super T, ? super P, ? extends IV> function, P parameter)
{
return ListIterate.injectIntoWith(injectValue, this, function, parameter);
}
@Override
public MutableList<T> toList()
{
return FastList.newList(this);
}
@Override
public MutableList<T> toSortedList()
{
return this.toSortedList(Comparators.naturalOrder());
}
@Override
public MutableList<T> toSortedList(Comparator<? super T> comparator)
{
return this.toList().sortThis(comparator);
}
@Override
public MutableSet<T> toSet()
{
return UnifiedSet.newSet(this);
}
public MutableStack<T> toStack()
{
return Stacks.mutable.withAll(this);
}
public MutableList<T> asUnmodifiable()
{
return UnmodifiableMutableList.of(this);
}
public ImmutableList<T> toImmutable()
{
return Lists.immutable.withAll(this);
}
public MutableList<T> asSynchronized()
{
return SynchronizedMutableList.of(this);
}
public MutableList<T> sortThis(Comparator<? super T> comparator)
{
if (this.size() < 10)
{
if (comparator == null)
{
this.insertionSort();
}
else
{
this.insertionSort(comparator);
}
}
else
{
this.defaultSort(comparator);
}
return this;
}
/**
* Override in subclasses where it can be optimized.
*/
protected void defaultSort(Comparator<? super T> comparator)
{
Collections.sort(this, comparator);
}
private void insertionSort(Comparator<? super T> comparator)
{
for (int i = 0; i < this.size(); i++)
{
for (int j = i; j > 0 && comparator.compare(this.get(j - 1), this.get(j)) > 0; j--)
{
Collections.swap(this, j, j - 1);
}
}
}
private void insertionSort()
{
for (int i = 0; i < this.size(); i++)
{
for (int j = i; j > 0 && ((Comparable<T>) this.get(j - 1)).compareTo(this.get(j)) > 0; j--)
{
Collections.swap(this, j, j - 1);
}
}
}
public MutableList<T> sortThis()
{
return this.sortThis(Comparators.naturalOrder());
}
public <V extends Comparable<? super V>> MutableList<T> sortThisBy(Function<? super T, ? extends V> function)
{
return this.sortThis(Comparators.byFunction(function));
}
public MutableList<T> sortThisByInt(IntFunction<? super T> function)
{
return this.sortThis(Functions.toIntComparator(function));
}
public MutableList<T> sortThisByBoolean(BooleanFunction<? super T> function)
{
return this.sortThis(Functions.toBooleanComparator(function));
}
public MutableList<T> sortThisByChar(CharFunction<? super T> function)
{
return this.sortThis(Functions.toCharComparator(function));
}
public MutableList<T> sortThisByByte(ByteFunction<? super T> function)
{
return this.sortThis(Functions.toByteComparator(function));
}
public MutableList<T> sortThisByShort(ShortFunction<? super T> function)
{
return this.sortThis(Functions.toShortComparator(function));
}
public MutableList<T> sortThisByFloat(FloatFunction<? super T> function)
{
return this.sortThis(Functions.toFloatComparator(function));
}
public MutableList<T> sortThisByLong(LongFunction<? super T> function)
{
return this.sortThis(Functions.toLongComparator(function));
}
public MutableList<T> sortThisByDouble(DoubleFunction<? super T> function)
{
return this.sortThis(Functions.toDoubleComparator(function));
}
public MutableList<T> newEmpty()
{
return Lists.mutable.empty();
}
public MutableList<T> tap(Procedure<? super T> procedure)
{
this.forEach(procedure);
return this;
}
public void forEach(int from, int to, Procedure<? super T> procedure)
{
ListIterate.forEach(this, from, to, procedure);
}
public int indexOf(Object object)
{
for (int i = 0; i < this.size(); i++)
{
if (Comparators.nullSafeEquals(this.get(i), object))
{
return i;
}
}
return -1;
}
public int lastIndexOf(Object object)
{
for (int i = this.size() - 1; i >= 0; i--)
{
if (Comparators.nullSafeEquals(this.get(i), object))
{
return i;
}
}
return -1;
}
public Iterator<T> iterator()
{
return new MutableIterator<T>(this);
}
public ListIterator<T> listIterator()
{
return this.listIterator(0);
}
public ListIterator<T> listIterator(int index)
{
if (index < 0 || index > this.size())
{
throw new IndexOutOfBoundsException("Index: " + index);
}
return new MutableListIterator<T>(this, index);
}
public MutableList<T> toReversed()
{
return FastList.newList(this).reverseThis();
}
public MutableList<T> reverseThis()
{
Collections.reverse(this);
return this;
}
public MutableList<T> shuffleThis()
{
Collections.shuffle(this);
return this;
}
public MutableList<T> shuffleThis(Random rnd)
{
Collections.shuffle(this, rnd);
return this;
}
public MutableList<T> subList(int fromIndex, int toIndex)
{
return new SubList<T>(this, fromIndex, toIndex);
}
protected static class SubList<T>
extends AbstractMutableList<T>
implements Serializable, RandomAccess
{
// Not important since it uses writeReplace()
private static final long serialVersionUID = 1L;
private final MutableList<T> original;
private final int offset;
private int size;
protected SubList(AbstractMutableList<T> list, int fromIndex, int toIndex)
{
if (fromIndex < 0)
{
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
}
if (toIndex > list.size())
{
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
}
if (fromIndex > toIndex)
{
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ')');
}
this.original = list;
this.offset = fromIndex;
this.size = toIndex - fromIndex;
}
@Override
public MutableList<T> toReversed()
{
return FastList.newList(this).reverseThis();
}
protected Object writeReplace()
{
return FastList.newList(this);
}
@Override
public boolean add(T o)
{
this.original.add(this.offset + this.size, o);
this.size++;
return true;
}
public T set(int index, T element)
{
this.checkIfOutOfBounds(index);
return this.original.set(index + this.offset, element);
}
public T get(int index)
{
this.checkIfOutOfBounds(index);
return this.original.get(index + this.offset);
}
public int size()
{
return this.size;
}
public void add(int index, T element)
{
this.checkIfOutOfBounds(index);
this.original.add(index + this.offset, element);
this.size++;
}
public T remove(int index)
{
this.checkIfOutOfBounds(index);
T result = this.original.remove(index + this.offset);
this.size--;
return result;
}
public void clear()
{
for (Iterator<T> iterator = this.iterator(); iterator.hasNext(); )
{
iterator.next();
iterator.remove();
}
}
@Override
public boolean addAll(Collection<? extends T> collection)
{
return this.addAll(this.size, collection);
}
public boolean addAll(int index, Collection<? extends T> collection)
{
if (index < 0 || index > this.size)
{
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + this.size);
}
int cSize = collection.size();
if (cSize == 0)
{
return false;
}
this.original.addAll(this.offset + index, collection);
this.size += cSize;
return true;
}
@Override
public Iterator<T> iterator()
{
return this.listIterator();
}
@Override
public ListIterator<T> listIterator(final int index)
{
if (index < 0 || index > this.size)
{
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + this.size);
}
return new ListIterator<T>()
{
private final ListIterator<T> listIterator = SubList.this.original.listIterator(index + SubList.this.offset);
public boolean hasNext()
{
return this.nextIndex() < SubList.this.size;
}
public T next()
{
if (this.hasNext())
{
return this.listIterator.next();
}
throw new NoSuchElementException();
}
public boolean hasPrevious()
{
return this.previousIndex() >= 0;
}
public T previous()
{
if (this.hasPrevious())
{
return this.listIterator.previous();
}
throw new NoSuchElementException();
}
public int nextIndex()
{
return this.listIterator.nextIndex() - SubList.this.offset;
}
public int previousIndex()
{
return this.listIterator.previousIndex() - SubList.this.offset;
}
public void remove()
{
this.listIterator.remove();
SubList.this.size--;
}
public void set(T o)
{
this.listIterator.set(o);
}
public void add(T o)
{
this.listIterator.add(o);
SubList.this.size++;
}
};
}
@Override
public MutableList<T> subList(int fromIndex, int toIndex)
{
return new SubList<T>(this, fromIndex, toIndex);
}
private void checkIfOutOfBounds(int index)
{
if (index >= this.size || index < 0)
{
throw new IndexOutOfBoundsException("Index: " + index + " Size: " + this.size);
}
}
// Weird implementation of clone() is ok on final classes
@Override
public MutableList<T> clone()
{
return new FastList<T>(this);
}
@Override
public T getFirst()
{
return this.isEmpty() ? null : this.original.get(this.offset);
}
@Override
public T getLast()
{
return this.isEmpty() ? null : this.original.get(this.offset + this.size - 1);
}
@Override
public MutableStack<T> toStack()
{
return ArrayStack.newStack(this);
}
@Override
public void forEachWithIndex(ObjectIntProcedure<? super T> objectIntProcedure)
{
ListIterate.forEachWithIndex(this, objectIntProcedure);
}
@Override
public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter)
{
ListIterate.forEachWith(this, procedure, parameter);
}
}
@Override
public boolean contains(Object object)
{
return this.indexOf(object) > -1;
}
@Override
public boolean containsAll(Collection<?> source)
{
return Iterate.allSatisfyWith(source, Predicates2.in(), this);
}
@Override
public boolean removeAll(Collection<?> collection)
{
int currentSize = this.size();
this.removeIfWith(Predicates2.in(), collection);
return currentSize != this.size();
}
@Override
public boolean retainAll(Collection<?> collection)
{
int currentSize = this.size();
this.removeIfWith(Predicates2.notIn(), collection);
return currentSize != this.size();
}
public T getFirst()
{
return ListIterate.getFirst(this);
}
public T getLast()
{
return ListIterate.getLast(this);
}
@Override
public void appendString(Appendable appendable, String separator)
{
this.appendString(appendable, "", separator, "");
}
@Override
public void appendString(Appendable appendable, String start, String separator, String end)
{
ListIterate.appendString(this, appendable, start, separator, end);
}
public <V> FastListMultimap<V, T> groupBy(Function<? super T, ? extends V> function)
{
return ListIterate.groupBy(this, function);
}
public <V> FastListMultimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function)
{
return ListIterate.groupByEach(this, function);
}
@Override
public <K> MutableMap<K, T> groupByUniqueKey(Function<? super T, ? extends K> function)
{
return ListIterate.groupByUniqueKey(this, function);
}
public <S> MutableList<Pair<T, S>> zip(Iterable<S> that)
{
return ListIterate.zip(this, that);
}
public MutableList<Pair<T, Integer>> zipWithIndex()
{
return ListIterate.zipWithIndex(this);
}
public MutableList<T> with(T element)
{
this.add(element);
return this;
}
public MutableList<T> without(T element)
{
this.remove(element);
return this;
}
public MutableList<T> withAll(Iterable<? extends T> elements)
{
this.addAllIterable(elements);
return this;
}
public MutableList<T> withoutAll(Iterable<? extends T> elements)
{
this.removeAllIterable(elements);
return this;
}
public ReverseIterable<T> asReversed()
{
return ReverseIterable.adapt(this);
}
public ParallelListIterable<T> asParallel(ExecutorService executorService, int batchSize)
{
return new ListIterableParallelIterable<T>(this, executorService, batchSize);
}
public int binarySearch(T key, Comparator<? super T> comparator)
{
return Collections.binarySearch(this, key, comparator);
}
public int binarySearch(T key)
{
return Collections.binarySearch((List<? extends Comparable<? super T>>) this, key);
}
public MutableList<T> take(int count)
{
return ListIterate.take(this, count);
}
public MutableList<T> takeWhile(Predicate<? super T> predicate)
{
return ListIterate.takeWhile(this, predicate);
}
public MutableList<T> drop(int count)
{
return ListIterate.drop(this, count);
}
public MutableList<T> dropWhile(Predicate<? super T> predicate)
{
return ListIterate.dropWhile(this, predicate);
}
public PartitionMutableList<T> partitionWhile(Predicate<? super T> predicate)
{
return ListIterate.partitionWhile(this, predicate);
}
}
| 28.814944 | 125 | 0.619038 |
9e54b16806ead2a24408427adcf220fe310db681 | 1,503 |
package org.springframework.core.type;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Abstract base class for testing implementations of
* {@link ClassMetadata#getMemberClassNames()}.
* @since 3.1
*/
public abstract class AbstractClassMetadataMemberClassTests {
public abstract ClassMetadata getClassMetadataFor(Class<?> clazz);
@Test
public void withNoMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_a.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{}));
}
public static class L0_a {
}
@Test
public void withPublicMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_b.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{L0_b.L1.class.getName()}));
}
public static class L0_b {
public static class L1 { }
}
@Test
public void withNonPublicMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_c.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{L0_c.L1.class.getName()}));
}
public static class L0_c {
private static class L1 { }
}
@Test
public void againstMemberClass() {
ClassMetadata metadata = getClassMetadataFor(L0_b.L1.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{}));
}
}
| 24.241935 | 76 | 0.751164 |
4f52061caf7cd934ac7ff4da9a16c9d594d8e2ea | 7,392 | package com.firedome.ravello.model;
import com.firedome.ravello.Resource;
import com.firedome.ravello.model.common.vm.RavelloMemorySize;
import com.firedome.ravello.model.common.vm.harddrive.RavelloHardDrive;
import com.firedome.ravello.model.common.vm.networkconnection.RavelloNetworkConnection;
import java.util.ArrayList;
import java.util.List;
/**
* Describes Ravello Image model
* @see <a href="URL#https://www.ravellosystems.com/ravello-api-doc/#vm-properties></a>
*/
public class RavelloImage extends Resource {
private Long id;
private String name;
private Long creationTime;
private RavelloMemorySize memorySize;
private Integer numCpus;
private String platform;
private String os;
private Double rcu;
private Boolean supportsCloudInit;
private Boolean requiresKeypair;
private Boolean useCdn;
private Boolean privateCloudImage;
private Boolean legacyMode;
private String loadingStatus;
private Integer loadingPercentage;
private Long baseVmId;
private Boolean allowNested;
private List<RavelloNetworkConnection> networkConnections = new ArrayList<>();
private List<RavelloHardDrive> hardDrives = new ArrayList<>();
private Object busStructure;
private List<String> bootOrder = new ArrayList<>();
private Boolean powerOffOnStopTimeOut;
private Boolean usingNewNetwork;
private String bootType;
private Boolean importedByUser;
private Boolean isPublic;
private String owner;
private RavelloOwnerDetails ownerDetails;
private Long peerToPeerShares;
private Long communityShares;
private Long copies;
private Boolean hasDocumentation;
private Boolean requiresHvm;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreationTime() {
return creationTime;
}
public void setCreationTime(Long creationTime) {
this.creationTime = creationTime;
}
public RavelloMemorySize getMemorySize() {
return memorySize;
}
public void setMemorySize(RavelloMemorySize memorySize) {
this.memorySize = memorySize;
}
public Integer getNumCpus() {
return numCpus;
}
public void setNumCpus(Integer numCpus) {
this.numCpus = numCpus;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public Double getRcu() {
return rcu;
}
public void setRcu(Double rcu) {
this.rcu = rcu;
}
public Boolean getSupportsCloudInit() {
return supportsCloudInit;
}
public void setSupportsCloudInit(Boolean supportsCloudInit) {
this.supportsCloudInit = supportsCloudInit;
}
public Boolean getRequiresKeypair() {
return requiresKeypair;
}
public void setRequiresKeypair(Boolean requiresKeypair) {
this.requiresKeypair = requiresKeypair;
}
public Boolean getUseCdn() {
return useCdn;
}
public void setUseCdn(Boolean useCdn) {
this.useCdn = useCdn;
}
public Boolean getPrivateCloudImage() {
return privateCloudImage;
}
public void setPrivateCloudImage(Boolean privateCloudImage) {
this.privateCloudImage = privateCloudImage;
}
public Boolean getLegacyMode() {
return legacyMode;
}
public void setLegacyMode(Boolean legacyMode) {
this.legacyMode = legacyMode;
}
public String getLoadingStatus() {
return loadingStatus;
}
public void setLoadingStatus(String loadingStatus) {
this.loadingStatus = loadingStatus;
}
public Integer getLoadingPercentage() {
return loadingPercentage;
}
public void setLoadingPercentage(Integer loadingPercentage) {
this.loadingPercentage = loadingPercentage;
}
public Long getBaseVmId() {
return baseVmId;
}
public void setBaseVmId(Long baseVmId) {
this.baseVmId = baseVmId;
}
public Boolean getAllowNested() {
return allowNested;
}
public void setAllowNested(Boolean allowNested) {
this.allowNested = allowNested;
}
public List<RavelloNetworkConnection> getNetworkConnections() {
return networkConnections;
}
public void setNetworkConnections(List<RavelloNetworkConnection> networkConnections) {
this.networkConnections = networkConnections;
}
public List<RavelloHardDrive> getHardDrives() {
return hardDrives;
}
public void setHardDrives(List<RavelloHardDrive> hardDrives) {
this.hardDrives = hardDrives;
}
public Object getBusStructure() {
return busStructure;
}
public void setBusStructure(Object busStructure) {
this.busStructure = busStructure;
}
public List<String> getBootOrder() {
return bootOrder;
}
public Boolean getPowerOffOnStopTimeOut() {
return powerOffOnStopTimeOut;
}
public void setPowerOffOnStopTimeOut(Boolean powerOffOnStopTimeOut) {
this.powerOffOnStopTimeOut = powerOffOnStopTimeOut;
}
public Boolean getUsingNewNetwork() {
return usingNewNetwork;
}
public void setUsingNewNetwork(Boolean usingNewNetwork) {
this.usingNewNetwork = usingNewNetwork;
}
public Boolean getImportedByUser() {
return importedByUser;
}
public void setImportedByUser(Boolean importedByUser) {
this.importedByUser = importedByUser;
}
public Boolean getPublic() {
return isPublic;
}
public void setPublic(Boolean aPublic) {
isPublic = aPublic;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public RavelloOwnerDetails getOwnerDetails() {
return ownerDetails;
}
public void setOwnerDetails(RavelloOwnerDetails ownerDetails) {
this.ownerDetails = ownerDetails;
}
public Long getPeerToPeerShares() {
return peerToPeerShares;
}
public void setPeerToPeerShares(Long peerToPeerShares) {
this.peerToPeerShares = peerToPeerShares;
}
public Long getCommunityShares() {
return communityShares;
}
public void setCommunityShares(Long communityShares) {
this.communityShares = communityShares;
}
public Long getCopies() {
return copies;
}
public void setCopies(Long copies) {
this.copies = copies;
}
public Boolean getHasDocumentation() {
return hasDocumentation;
}
public void setHasDocumentation(Boolean hasDocumentation) {
this.hasDocumentation = hasDocumentation;
}
public Boolean getRequiresHvm() {
return requiresHvm;
}
public void setRequiresHvm(Boolean requiresHvm) {
this.requiresHvm = requiresHvm;
}
public String getBootType() {
return bootType;
}
public void setBootType(String bootType) {
this.bootType = bootType;
}
}
| 23.768489 | 90 | 0.672484 |
a740bb16d9acf037aeb02f979d2a2b49e58a3a6e | 826 | package com.github.theniles.archery.mixin;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.PersistentProjectileEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.List;
@Mixin(PersistentProjectileEntity.class)
public interface PersistentProjectileEntityMixin {
@Accessor("punch")
public int getPunch();
@Accessor("piercedEntities")
public IntOpenHashSet getPiercedEntities();
@Accessor("piercedEntities")
public void setPiercedEntities(IntOpenHashSet set);
@Accessor("piercingKilledEntities")
public List<Entity> getPiercedKilledEntities();
@Accessor("piercingKilledEntities")
public void setPiercedKilledEntities(List<Entity> list);
}
| 27.533333 | 66 | 0.788136 |
c2b5d88c1dd49a7ffea52227ca5facceb2a1ed99 | 5,131 | /*-
* <<
* UAVStack
* ==
* Copyright (C) 2016 - 2017 UAVStack
* ==
* 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.creditease.monitor.captureframework.spi;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.creditease.monitor.captureframework.StandardMonitor;
import com.creditease.monitor.captureframework.spi.Monitor.CapturePhase;
public class MonitorFactory {
private static MonitorFactory instance = new MonitorFactory();
public static MonitorFactory instance() {
return instance;
}
private Map<String, Monitor> monitors = new ConcurrentHashMap<String, Monitor>();
private Map<String, Map<String, Monitor>> serverCapPointBindMonitors = new ConcurrentHashMap<String, Map<String, Monitor>>();
/**
* build default monitor
*
* @param configFile
* @return
*/
public Monitor buildDefaultMonitor(String configFile) {
return buildMonitor(CaptureConstants.MONITOR_SERVER, configFile);
}
/**
* build application monitor
*
* @param monitorId
* @param configFile
* TODO: configFile is not used yet, only API avaiable
* @return
*/
public Monitor buildMonitor(String monitorId, String configFile) {
if (monitorId == null)
return null;
if (monitors.containsKey(monitorId)) {
monitors.get(monitorId).destroy();
}
Monitor mInst = new StandardMonitor(monitorId, configFile);
monitors.put(monitorId, mInst);
return mInst;
}
/**
* get default monitor
*
* @return
*/
public Monitor getDefaultMonitor() {
return getMonitor(CaptureConstants.MONITOR_SERVER);
}
/**
* get application monitor
*
* @param id
* @return
*/
public Monitor getMonitor(String id) {
if (!monitors.containsKey(id))
return null;
return monitors.get(id);
}
/**
* destroy default monitor
*/
public void destroyDefaultMonitor() {
destroyMonitor(CaptureConstants.MONITOR_SERVER);
}
/**
* destroy monitor
*
* @param id
*/
public void destroyMonitor(String id) {
if (id == null)
return;
Monitor m = getMonitor(id);
if (m != null) {
m.destroy();
}
monitors.remove(id);
}
/**
* bind monitor instance to Server Capture Point
*
* @param captureId
* @param monitor
* @param capturePhase
*/
public void bindMonitorToServerCapPoint(String captureId, Monitor monitor, CapturePhase capturePhase) {
if (captureId == null || "".equals(captureId) || monitor == null)
return;
String capKey = getCapKey(captureId, capturePhase);
Map<String, Monitor> bindMonitors = serverCapPointBindMonitors.get(capKey);
if (bindMonitors == null) {
synchronized (serverCapPointBindMonitors) {
bindMonitors = serverCapPointBindMonitors.get(capKey);
if (bindMonitors == null) {
bindMonitors = new ConcurrentHashMap<String, Monitor>();
serverCapPointBindMonitors.put(capKey, bindMonitors);
}
}
}
bindMonitors.put(monitor.getId(), monitor);
}
private String getCapKey(String captureId, CapturePhase capturePhase) {
// capkey is captureId + capture phase
String capKey = captureId + "." + capturePhase;
return capKey;
}
/**
* get Server Capture Point bind monitors
*
* @param captureId
* @param phase
* @return
*/
public Monitor[] getServerCapPointBindMonitors(String captureId, CapturePhase phase) {
if (captureId == null || "".equals(captureId))
return new Monitor[0];
String capKey = getCapKey(captureId, phase);
Map<String, Monitor> bindMonitors = serverCapPointBindMonitors.get(capKey);
if (bindMonitors != null && bindMonitors.size() > 0) {
Monitor[] monitorArray = new Monitor[bindMonitors.size()];
return bindMonitors.values().toArray(monitorArray);
}
return new Monitor[0];
}
/**
* get all monitors
*
* @return
*/
public Monitor[] getMonitors() {
if (monitors.size() > 0) {
Monitor[] monitorsArray = new Monitor[monitors.size()];
return monitors.values().toArray(monitorsArray);
}
return new Monitor[0];
}
}
| 25.655 | 129 | 0.613526 |
0ddc4203eeaf78e780b5b828e1b29c31d4383549 | 17,343 | package us.ihmc.footstepPlanning.ui.components;
import us.ihmc.footstepPlanning.graphSearch.parameters.FootstepPlannerParameters;
public class SettableFootstepPlannerParameters implements FootstepPlannerParameters
{
private double idealFootstepWidth;
private double idealFootstepLength;
private double wiggleInsideDelta;
private boolean wiggleIntoConvexHullOfPlanarRegions;
private boolean rejectIfCannotFullyWiggleInside;
private double maximumXYWiggleDistance;
private double maximumYawWiggle;
private double maxStepReach;
private double maxStepYaw;
private double minStepWidth;
private double minStepLength;
private double minStepYaw;
private double maxStepZ;
private double minFootholdPercent;
private double minSurfaceIncline;
private double maxStepWidth;
private double minXClearanceFromStance;
private double minYClearanceFromStance;
private double maximumStepReachWhenSteppingUp;
private double maximumStepZWhenSteppingUp;
private double maximumStepXWhenForwardAndDown;
private double maximumStepZWhenForwardAndDown;
private double maximumZPenetrationOnValleyRegions;
private double cliffHeightToAvoid;
private double minimumDistanceFromCliffBottoms;
private boolean returnBestEffortPlan;
private int minimumStepsForBestEffortPlan;
private double bodyGroundClearance;
private boolean checkForBodyBoxCollisions;
private boolean performHeuristicSearchPolicies;
private double bodyBoxWidth;
private double bodyBoxHeight;
private double bodyBoxDepth;
private double bodyBoxBaseX;
private double bodyBoxBaseY;
private double bodyBoxBaseZ;
private final SettableFootstepPlannerCostParameters costParameters;
public SettableFootstepPlannerParameters(FootstepPlannerParameters footstepPlannerParameters)
{
this.costParameters = new SettableFootstepPlannerCostParameters(footstepPlannerParameters.getCostParameters());
set(footstepPlannerParameters);
}
public void set(FootstepPlannerParameters footstepPlannerParameters)
{
this.idealFootstepWidth = footstepPlannerParameters.getIdealFootstepWidth();
this.idealFootstepLength = footstepPlannerParameters.getIdealFootstepLength();
this.wiggleInsideDelta = footstepPlannerParameters.getWiggleInsideDelta();
this.wiggleIntoConvexHullOfPlanarRegions = footstepPlannerParameters.getWiggleIntoConvexHullOfPlanarRegions();
this.rejectIfCannotFullyWiggleInside = footstepPlannerParameters.getRejectIfCannotFullyWiggleInside();
this.maximumXYWiggleDistance = footstepPlannerParameters.getMaximumXYWiggleDistance();
this.maximumYawWiggle = footstepPlannerParameters.getMaximumYawWiggle();
this.maxStepReach = footstepPlannerParameters.getMaximumStepReach();
this.maxStepYaw = footstepPlannerParameters.getMaximumStepYaw();
this.minStepWidth = footstepPlannerParameters.getMinimumStepWidth();
this.minStepLength = footstepPlannerParameters.getMinimumStepLength();
this.minStepYaw = footstepPlannerParameters.getMinimumStepYaw();
this.maxStepZ = footstepPlannerParameters.getMaximumStepZ();
this.maxStepWidth = footstepPlannerParameters.getMaximumStepWidth();
this.minFootholdPercent = footstepPlannerParameters.getMinimumFootholdPercent();
this.minSurfaceIncline = footstepPlannerParameters.getMinimumSurfaceInclineRadians();
this.minXClearanceFromStance = footstepPlannerParameters.getMinXClearanceFromStance();
this.minYClearanceFromStance = footstepPlannerParameters.getMinYClearanceFromStance();
this.maximumStepReachWhenSteppingUp = footstepPlannerParameters.getMaximumStepReachWhenSteppingUp();
this.maximumStepZWhenSteppingUp = footstepPlannerParameters.getMaximumStepZWhenSteppingUp();
this.maximumStepXWhenForwardAndDown = footstepPlannerParameters.getMaximumStepXWhenForwardAndDown();
this.maximumStepZWhenForwardAndDown = footstepPlannerParameters.getMaximumStepZWhenForwardAndDown();
this.maximumZPenetrationOnValleyRegions = footstepPlannerParameters.getMaximumZPenetrationOnValleyRegions();
this.cliffHeightToAvoid = footstepPlannerParameters.getCliffHeightToAvoid();
this.minimumDistanceFromCliffBottoms = footstepPlannerParameters.getMinimumDistanceFromCliffBottoms();
this.returnBestEffortPlan = footstepPlannerParameters.getReturnBestEffortPlan();
this.minimumStepsForBestEffortPlan = footstepPlannerParameters.getMinimumStepsForBestEffortPlan();
this.bodyGroundClearance = footstepPlannerParameters.getBodyGroundClearance();
this.checkForBodyBoxCollisions = footstepPlannerParameters.checkForBodyBoxCollisions();
this.performHeuristicSearchPolicies = footstepPlannerParameters.performHeuristicSearchPolicies();
this.bodyBoxHeight = footstepPlannerParameters.getBodyBoxHeight();
this.bodyBoxWidth = footstepPlannerParameters.getBodyBoxWidth();
this.bodyBoxDepth = footstepPlannerParameters.getBodyBoxDepth();
this.bodyBoxBaseX = footstepPlannerParameters.getBodyBoxBaseX();
this.bodyBoxBaseY = footstepPlannerParameters.getBodyBoxBaseY();
this.bodyBoxBaseZ = footstepPlannerParameters.getBodyBoxBaseZ();
this.costParameters.set(footstepPlannerParameters.getCostParameters());
}
public void setIdealFootstepWidth(double idealFootstepWidth)
{
this.idealFootstepWidth = idealFootstepWidth;
}
public void setIdealFootstepLength(double idealFootstepLength)
{
this.idealFootstepLength = idealFootstepLength;
}
public void setWiggleInsideDelta(double wiggleInsideDelta)
{
this.wiggleInsideDelta = wiggleInsideDelta;
}
public void setWiggleIntoConvexHullOfPlanarRegions(boolean wiggleIntoConvexHullOfPlanarRegions)
{
this.wiggleIntoConvexHullOfPlanarRegions = wiggleIntoConvexHullOfPlanarRegions;
}
public void setRejectIfCannotFullyWiggleInside(boolean rejectIfCannotFullyWiggleInside)
{
this.rejectIfCannotFullyWiggleInside = rejectIfCannotFullyWiggleInside;
}
public void setMaximumXYWiggleDistance(double maximumXYWiggleDistance)
{
this.maximumXYWiggleDistance = maximumXYWiggleDistance;
}
public void setMaximumYawWiggle(double maximumYawWiggle)
{
this.maximumYawWiggle = maximumYawWiggle;
}
public void setMaximumStepReach(double maxStepReach)
{
this.maxStepReach = maxStepReach;
}
public void setMaximumStepYaw(double maxStepYaw)
{
this.maxStepYaw = maxStepYaw;
}
public void setMinimumStepWidth(double minStepWidth)
{
this.minStepWidth = minStepWidth;
}
public void setMinimumStepLength(double minStepLength)
{
this.minStepLength = minStepLength;
}
public void setMinimumStepYaw(double minStepYaw)
{
this.minStepYaw = minStepYaw;
}
public void setMaximumStepZ(double maxStepZ)
{
this.maxStepZ = maxStepZ;
}
public void setMaximumStepWidth(double maxStepWidth)
{
this.maxStepWidth = maxStepWidth;
}
public void setMinimumFootholdPercent(double minFootholdPercent)
{
this.minFootholdPercent = minFootholdPercent;
}
public void setMinimumSurfaceInclineRadians(double minSurfaceIncline)
{
this.minSurfaceIncline = minSurfaceIncline;
}
public void setMaximumStepReachWhenSteppingUp(double maximumStepReachWhenSteppingUp)
{
this.maximumStepReachWhenSteppingUp = maximumStepReachWhenSteppingUp;
}
public void setMaximumStepZWhenSteppingUp(double maximumStepZWhenSteppingUp)
{
this.maximumStepZWhenSteppingUp = maximumStepZWhenSteppingUp;
}
public void setMaximumStepXWhenForwardAndDown(double maximumStepXWhenForwardAndDown)
{
this.maximumStepXWhenForwardAndDown = maximumStepXWhenForwardAndDown;
}
public void setMaximumStepZWhenForwardAndDown(double maximumStepZWhenForwardAndDown)
{
this.maximumStepZWhenForwardAndDown = maximumStepZWhenForwardAndDown;
}
public void setMinXClearanceFromStance(double minXClearanceFromStance)
{
this.minXClearanceFromStance = minXClearanceFromStance;
}
public void setMinYClearanceFromStance(double minYClearanceFromStance)
{
this.minYClearanceFromStance = minYClearanceFromStance;
}
public void setMaximumZPenetrationOnValleyRegions(double maximumZPenetrationOnValleyRegions)
{
this.maximumZPenetrationOnValleyRegions = maximumZPenetrationOnValleyRegions;
}
public void setCliffHeightToAvoid(double cliffHeightToAvoid)
{
this.cliffHeightToAvoid = cliffHeightToAvoid;
}
public void setMinimumDistanceFromCliffBottoms(double minimumDistanceFromCliffBottoms)
{
this.minimumDistanceFromCliffBottoms = minimumDistanceFromCliffBottoms;
}
public void setReturnBestEffortPlan(boolean returnBestEffortPlan)
{
this.returnBestEffortPlan = returnBestEffortPlan;
}
public void setMinimumStepsForBestEffortPlan(int minimumStepsForBestEffortPlan)
{
this.minimumStepsForBestEffortPlan = minimumStepsForBestEffortPlan;
}
public void setYawWeight(double yawWeight)
{
costParameters.setYawWeight(yawWeight);
}
public void setPitchWeight(double pitchWeight)
{
costParameters.setPitchWeight(pitchWeight);
}
public void setRollWeight(double rollWeight)
{
costParameters.setRollWeight(rollWeight);
}
public void setForwardWeight(double forwardWeight)
{
costParameters.setForwardWeight(forwardWeight);
}
public void setLateralWeight(double lateralWeight)
{
costParameters.setLateralWeight(lateralWeight);
}
public void setStepUpWeight(double stepUpWeight)
{
costParameters.setStepUpWeight(stepUpWeight);
}
public void setStepDownWeight(double stepDownWeight)
{
costParameters.setStepDownWeight(stepDownWeight);
}
public void setUseQuadraticDistanceCost(boolean useQuadraticDistanceCost)
{
costParameters.setUseQuadraticDistanceCost(useQuadraticDistanceCost);
}
public void setUseQuadraticHeightCost(boolean useQuadraticHeightCost)
{
costParameters.setUseQuadraticHeightCost(useQuadraticHeightCost);
}
public void setCostPerStep(double costPerStep)
{
costParameters.setCostPerStep(costPerStep);
}
public void setAStarHeuristicsWeight(double heuristicsWeight)
{
costParameters.setAStarHeuristicsWeight(heuristicsWeight);
}
public void setVisGraphWithAStarHeuristicsWeight(double heuristicsWeight)
{
costParameters.setVisGraphWithAStarHeuristicsWeight(heuristicsWeight);
}
public void setDepthFirstHeuristicsWeight(double heuristicsWeight)
{
costParameters.setDepthFirstHeuristicsWeight(heuristicsWeight);
}
public void setBodyPathBasedHeuristicsWeight(double heuristicsWeight)
{
costParameters.setBodyPathBasedHeuristicsWeight(heuristicsWeight);
}
public void setBodyGroundClearance(double bodyGroundClearance)
{
this.bodyGroundClearance = bodyGroundClearance;
}
public void setCheckForBodyBoxCollisions(boolean checkForBodyBoxCollisions)
{
this.checkForBodyBoxCollisions = checkForBodyBoxCollisions;
}
public void setPerformHeuristicSearchPolicies(boolean performHeuristicSearchPolicies)
{
this.performHeuristicSearchPolicies = performHeuristicSearchPolicies;
}
public void setBodyBoxWidth(double bodyBoxWidth)
{
this.bodyBoxWidth = bodyBoxWidth;
}
public void setBodyBoxHeight(double bodyBoxHeight)
{
this.bodyBoxHeight = bodyBoxHeight;
}
public void setBodyBoxDepth(double bodyBoxDepth)
{
this.bodyBoxDepth = bodyBoxDepth;
}
public void setBodyBoxBaseX(double bodyBoxBaseX)
{
this.bodyBoxBaseX = bodyBoxBaseX;
}
public void setBodyBoxBaseY(double bodyBoxBaseY)
{
this.bodyBoxBaseY = bodyBoxBaseY;
}
public void setBodyBoxBaseZ(double bodyBoxBaseZ)
{
this.bodyBoxBaseZ = bodyBoxBaseZ;
}
@Override
public double getIdealFootstepWidth()
{
return idealFootstepWidth;
}
@Override
public double getIdealFootstepLength()
{
return idealFootstepLength;
}
@Override
public double getWiggleInsideDelta()
{
return wiggleInsideDelta;
}
@Override
public boolean getWiggleIntoConvexHullOfPlanarRegions()
{
return wiggleIntoConvexHullOfPlanarRegions;
}
@Override
public boolean getRejectIfCannotFullyWiggleInside()
{
return rejectIfCannotFullyWiggleInside;
}
@Override
public double getMaximumXYWiggleDistance()
{
return maximumXYWiggleDistance;
}
@Override
public double getMaximumYawWiggle()
{
return maximumYawWiggle;
}
@Override
public double getMaximumStepReach()
{
return maxStepReach;
}
@Override
public double getMaximumStepYaw()
{
return maxStepYaw;
}
@Override
public double getMinimumStepWidth()
{
return minStepWidth;
}
@Override
public double getMinimumStepLength()
{
return minStepLength;
}
@Override
public double getMinimumStepYaw()
{
return minStepYaw;
}
@Override
public double getMaximumStepZ()
{
return maxStepZ;
}
@Override
public double getMaximumStepWidth()
{
return maxStepWidth;
}
@Override
public double getMaximumStepReachWhenSteppingUp()
{
return maximumStepReachWhenSteppingUp;
}
@Override
public double getMaximumStepZWhenSteppingUp()
{
return maximumStepZWhenSteppingUp;
}
@Override
public double getMaximumStepXWhenForwardAndDown()
{
return maximumStepXWhenForwardAndDown;
}
@Override
public double getMaximumStepZWhenForwardAndDown()
{
return maximumStepZWhenForwardAndDown;
}
@Override
public double getMinXClearanceFromStance()
{
return minXClearanceFromStance;
}
@Override
public double getMinYClearanceFromStance()
{
return minYClearanceFromStance;
}
@Override
public double getMinimumFootholdPercent()
{
return minFootholdPercent;
}
@Override
public double getMinimumSurfaceInclineRadians()
{
return minSurfaceIncline;
}
@Override
public double getMaximumZPenetrationOnValleyRegions()
{
return maximumZPenetrationOnValleyRegions;
}
@Override
public double getCliffHeightToAvoid()
{
return cliffHeightToAvoid;
}
@Override
public double getMinimumDistanceFromCliffBottoms()
{
return minimumDistanceFromCliffBottoms;
}
@Override
public boolean getReturnBestEffortPlan()
{
return returnBestEffortPlan;
}
@Override
public int getMinimumStepsForBestEffortPlan()
{
return minimumStepsForBestEffortPlan;
}
@Override
public double getBodyGroundClearance()
{
return bodyGroundClearance;
}
@Override
public boolean checkForBodyBoxCollisions()
{
return checkForBodyBoxCollisions;
}
@Override
public boolean performHeuristicSearchPolicies()
{
return performHeuristicSearchPolicies;
}
@Override
public double getBodyBoxHeight()
{
return bodyBoxHeight;
}
@Override
public double getBodyBoxWidth()
{
return bodyBoxWidth;
}
@Override
public double getBodyBoxDepth()
{
return bodyBoxDepth;
}
@Override
public double getBodyBoxBaseX()
{
return bodyBoxBaseX;
}
@Override
public double getBodyBoxBaseY()
{
return bodyBoxBaseY;
}
@Override
public double getBodyBoxBaseZ()
{
return bodyBoxBaseZ;
}
public boolean useQuadraticDistanceCost()
{
return costParameters.useQuadraticDistanceCost();
}
public boolean useQuadraticHeightCost()
{
return costParameters.useQuadraticHeightCost();
}
public double getYawWeight()
{
return costParameters.getYawWeight();
}
public double getPitchWeight()
{
return costParameters.getPitchWeight();
}
public double getRollWeight()
{
return costParameters.getRollWeight();
}
public double getForwardWeight()
{
return costParameters.getForwardWeight();
}
public double getLateralWeight()
{
return costParameters.getLateralWeight();
}
public double getStepUpWeight()
{
return costParameters.getStepUpWeight();
}
public double getStepDownWeight()
{
return costParameters.getStepDownWeight();
}
public double getCostPerStep()
{
return costParameters.getCostPerStep();
}
public double getAStarHeuristicsWeight()
{
return costParameters.getAStarHeuristicsWeight().getValue();
}
public double getVisGraphWithAStarHeuristicsWeight()
{
return costParameters.getVisGraphWithAStarHeuristicsWeight().getValue();
}
public double getDepthFirstHeuristicsWeight()
{
return costParameters.getDepthFirstHeuristicsWeight().getValue();
}
public double getBodyPathBasedHeuristicsWeight()
{
return costParameters.getBodyPathBasedHeuristicsWeight().getValue();
}
@Override
public SettableFootstepPlannerCostParameters getCostParameters()
{
return costParameters;
}
}
| 26.805255 | 117 | 0.759327 |
01b677f25b9d6d156436ca61e55fa850c1c8a842 | 3,205 | package com.gpc.meinvxiupro.utils;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.gpc.meinvxiupro.MeinvxiuApplication;
import com.gpc.meinvxiupro.R;
/**
* Created by pcgu on 16-4-12.
*/
public class ToastUtils {
public static void showShortToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
public static void showShortToast(Context context, int resId) {
Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
}
public static void showLongToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
public static void showLongToast(Context context, int resId) {
Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
}
public static void showShortSnakeBar(View parentView, String toast) {
Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_SHORT);
snackbar.show();
}
public static void showShortSnakeBar(View parentView, String toast, int backgroundColor, int textColor) {
Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_SHORT);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(backgroundColor);
TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(textColor);
snackbar.show();
}
public static void showShortSnakeBar(View parentView, String toast, String actionName) {
final Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_SHORT);
snackbar.setAction(actionName, new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
snackbar.show();
}
public static void showLongSnakeBar(View parentView, String toast) {
Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_LONG);
snackbar.show();
}
public static void showLongSnakeBar(View parentView, String toast, int backgroundColor) {
Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(backgroundColor);
TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(ContextCompat.getColor(MeinvxiuApplication.getInstance().getApplicationContext(), R.color.rgb_ffffff));
snackbar.show();
}
public static void showLongSnakeBar(View parentView, String toast, String actionName) {
final Snackbar snackbar = Snackbar.make(parentView, toast, Snackbar.LENGTH_LONG);
snackbar.setAction(actionName, new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
snackbar.show();
}
}
| 38.154762 | 133 | 0.697036 |
514c53334344773139c0ca1ad65bab4e0318ce74 | 4,493 | package com.qinyou.apiserver.sys.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinyou.apiserver.core.base.RequestException;
import com.qinyou.apiserver.core.base.ResultEnum;
import com.qinyou.apiserver.core.utils.WebUtils;
import com.qinyou.apiserver.sys.entity.User;
import com.qinyou.apiserver.sys.entity.UserRole;
import com.qinyou.apiserver.sys.mapper.UserMapper;
import com.qinyou.apiserver.sys.service.IUserRoleService;
import com.qinyou.apiserver.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Optional;
/**
* <p>
* 系统用户表 服务实现类
* </p>
*
* @author chuang
* @since 2019-10-19
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Value("${app.user-default-password}")
String userDefaultPwd;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
IUserRoleService userRoleService;
@Override
public void add(User user) {
if (StrUtil.isNotBlank(user.getPhone()) && checkExist(null, user.getPhone(), null)) {
throw RequestException.fail(ResultEnum.PHONE_EXIST);
}
if (StrUtil.isNotBlank(user.getEmail()) && checkExist(null, null, user.getEmail())) {
throw RequestException.fail(ResultEnum.EMAIL_EXIST);
}
user.setPassword(passwordEncoder.encode(userDefaultPwd))
.setCreater(WebUtils.getSecurityUsername())
.setCreateTime(LocalDateTime.now());
this.save(user);
}
@Override
public void update(User user) {
// 验证手机号邮箱是否存在
if (StrUtil.isNotBlank(user.getPhone()) && checkExist(user.getId(), user.getPhone(), null)) {
throw RequestException.fail(ResultEnum.PHONE_EXIST);
}
if (StrUtil.isNotBlank(user.getEmail()) && checkExist(user.getId(), null, user.getEmail())) {
throw RequestException.fail(ResultEnum.EMAIL_EXIST);
}
user.setUpdateTime(LocalDateTime.now())
.setUpdater(WebUtils.getSecurityUsername());
this.updateById(user);
}
@Transactional
@Override
public void remove(String id) {
User user = Optional.of(this.getById(id)).get();
this.removeById(id);
userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", id));
}
@Override
public void toggleState(String id) {
User user = Optional.of(this.getById(id)).get();
String state = "0".equals(user.getState()) ? "1" : "0";
this.update(
new UpdateWrapper<User>().set("state", state)
.set("updater", WebUtils.getSecurityUsername())
.set("update_time", LocalDateTime.now())
.eq("id", id)
);
}
/**
* 重置密码
*
* @param id
*/
@Override
public void resetPwd(String id) {
User user = Optional.of(this.getById(id)).get();
user.setPassword(passwordEncoder.encode(userDefaultPwd))
.setUpdater(WebUtils.getSecurityUsername())
.setUpdateTime(LocalDateTime.now());
this.updateById(user);
}
/**
* 手机号或邮箱否存在
* 参数 username 不为 null时, 排除此用户名判断
*
* @param username
* @param phone
* @param email
* @return
*/
@Override
public boolean checkExist(String username, String phone, String email) {
if ((phone == null && email == null) || (phone != null && email != null)) {
log.debug("email: {}, phone: {}", email, phone);
throw new IllegalArgumentException("参数 phone 、email 必须 一个 为 null, 一个 不为 null");
}
QueryWrapper<User> query = new QueryWrapper<>();
query.ne(username != null, "username", username)
.eq(phone != null, "phone", phone)
.eq(email != null, "email", email);
int count = this.count(query);
return count != 0;
}
}
| 34.29771 | 101 | 0.648787 |
db281bd51e32aa8d7fe1fc3d769d22eeebde6784 | 1,352 | package marubinotto.piggydb.model.filters;
import static org.junit.Assert.*;
import marubinotto.piggydb.model.Filter;
import marubinotto.piggydb.model.FilterRepository;
import marubinotto.piggydb.model.auth.User;
import marubinotto.util.time.DateTime;
import org.junit.Test;
public class DefaultTest extends FilterRepositoryTestBase {
public DefaultTest(RepositoryFactory<FilterRepository> factory) {
super(factory);
}
@Test
public void newInstance() throws Exception {
User user = getPlainUser();
Filter filter = this.object.newInstance(user);
assertTrue(filter.isAnd());
assertEquals(user.getName(), filter.getCreator());
assertNull(filter.getUpdater());
}
@Test
public void registerFilter() throws Exception {
// Given
DateTime registerDateTime = new DateTime(2008, 1, 1);
DateTime.setCurrentTimeForTest(registerDateTime);
// When
Filter filter = this.object.newInstance(getPlainUser());
filter.setNameByUser("new-filter", getPlainUser());
long filterId = this.object.register(filter);
// Then
assertEquals(filterId, filter.getId().longValue());
assertEquals(registerDateTime, filter.getCreationDatetime());
assertEquals(registerDateTime, filter.getUpdateDatetime());
// The post conditions for the repository is described by OneFilterTest
}
}
| 29.391304 | 74 | 0.741124 |
81447b04afceee61e6c439cac299c97f9e8f0b57 | 521 | /*
* Copyright (c) 2017, GoMint, BlackyPaw and geNAZt
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.world;
/**
* @author BlackyPaw
* @version 1.0
*/
public enum WeatherType {
/**
* Specifies entirely clear sky and sunshine!
*/
CLEAR,
/**
* Rain or (snow) will fall in the respective biomes
*/
DOWNFALL,
/**
* A thunderstorm will take place
*/
THUNDERSTORM;
}
| 16.28125 | 59 | 0.614203 |
e4e319fbdf68140af3135d4032aa3ec8cc3de8b8 | 10,621 | /**
* Copyright © 2016-2019 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.service.rpc;
import com.datastax.driver.core.utils.UUIDs;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.thingsboard.rule.engine.api.RpcError;
import org.thingsboard.rule.engine.api.msg.ToDeviceActorNotificationMsg;
import org.thingsboard.server.actors.service.ActorService;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.UUIDConverter;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgDataType;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.cluster.SendToClusterMsg;
import org.thingsboard.server.common.msg.cluster.ServerAddress;
import org.thingsboard.server.common.msg.core.ToServerRpcResponseMsg;
import org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest;
import org.thingsboard.server.common.msg.system.ServiceToRuleEngineMsg;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.gen.cluster.ClusterAPIProtos;
import org.thingsboard.server.service.cluster.routing.ClusterRoutingService;
import org.thingsboard.server.service.cluster.rpc.ClusterRpcService;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Created by ashvayka on 27.03.18.
*/
@Service
@Slf4j
public class DefaultDeviceRpcService implements DeviceRpcService {
private static final ObjectMapper json = new ObjectMapper();
@Autowired
private ClusterRoutingService routingService;
@Autowired
private ClusterRpcService rpcService;
@Autowired
private DeviceService deviceService;
@Autowired
@Lazy
private ActorService actorService;
private ScheduledExecutorService rpcCallBackExecutor;
private final ConcurrentMap<UUID, Consumer<FromDeviceRpcResponse>> localToRuleEngineRpcRequests = new ConcurrentHashMap<>();
private final ConcurrentMap<UUID, Consumer<FromDeviceRpcResponse>> localToDeviceRpcRequests = new ConcurrentHashMap<>();
@PostConstruct
public void initExecutor() {
rpcCallBackExecutor = Executors.newSingleThreadScheduledExecutor();
}
@PreDestroy
public void shutdownExecutor() {
if (rpcCallBackExecutor != null) {
rpcCallBackExecutor.shutdownNow();
}
}
@Override
public void processRestAPIRpcRequestToRuleEngine(ToDeviceRpcRequest request, Consumer<FromDeviceRpcResponse> responseConsumer) {
log.trace("[{}][{}] Processing REST API call to rule engine [{}]", request.getTenantId(), request.getId(), request.getDeviceId());
UUID requestId = request.getId();
localToRuleEngineRpcRequests.put(requestId, responseConsumer);
sendRpcRequestToRuleEngine(request);
scheduleTimeout(request, requestId, localToRuleEngineRpcRequests);
}
@Override
public void processResponseToServerSideRPCRequestFromRuleEngine(ServerAddress requestOriginAddress, FromDeviceRpcResponse response) {
log.trace("[{}] Received response to server-side RPC request from rule engine: [{}]", response.getId(), requestOriginAddress);
if (routingService.getCurrentServer().equals(requestOriginAddress)) {
UUID requestId = response.getId();
Consumer<FromDeviceRpcResponse> consumer = localToRuleEngineRpcRequests.remove(requestId);
if (consumer != null) {
consumer.accept(response);
} else {
log.trace("[{}] Unknown or stale rpc response received [{}]", requestId, response);
}
} else {
ClusterAPIProtos.FromDeviceRPCResponseProto.Builder builder = ClusterAPIProtos.FromDeviceRPCResponseProto.newBuilder();
builder.setRequestIdMSB(response.getId().getMostSignificantBits());
builder.setRequestIdLSB(response.getId().getLeastSignificantBits());
response.getResponse().ifPresent(builder::setResponse);
if (response.getError().isPresent()) {
builder.setError(response.getError().get().ordinal());
} else {
builder.setError(-1);
}
rpcService.tell(requestOriginAddress, ClusterAPIProtos.MessageType.CLUSTER_RPC_FROM_DEVICE_RESPONSE_MESSAGE, builder.build().toByteArray());
}
}
@Override
public void forwardServerSideRPCRequestToDeviceActor(ToDeviceRpcRequest request, Consumer<FromDeviceRpcResponse> responseConsumer) {
log.trace("[{}][{}] Processing local rpc call to device actor [{}]", request.getTenantId(), request.getId(), request.getDeviceId());
UUID requestId = request.getId();
localToDeviceRpcRequests.put(requestId, responseConsumer);
sendRpcRequestToDevice(request);
scheduleTimeout(request, requestId, localToDeviceRpcRequests);
}
@Override
public void processResponseToServerSideRPCRequestFromDeviceActor(FromDeviceRpcResponse response) {
log.trace("[{}] Received response to server-side RPC request from device actor.", response.getId());
UUID requestId = response.getId();
Consumer<FromDeviceRpcResponse> consumer = localToDeviceRpcRequests.remove(requestId);
if (consumer != null) {
consumer.accept(response);
} else {
log.trace("[{}] Unknown or stale rpc response received [{}]", requestId, response);
}
}
@Override
public void processResponseToServerSideRPCRequestFromRemoteServer(ServerAddress serverAddress, byte[] data) {
ClusterAPIProtos.FromDeviceRPCResponseProto proto;
try {
proto = ClusterAPIProtos.FromDeviceRPCResponseProto.parseFrom(data);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
RpcError error = proto.getError() > 0 ? RpcError.values()[proto.getError()] : null;
FromDeviceRpcResponse response = new FromDeviceRpcResponse(new UUID(proto.getRequestIdMSB(), proto.getRequestIdLSB()), proto.getResponse(), error);
processResponseToServerSideRPCRequestFromRuleEngine(routingService.getCurrentServer(), response);
}
@Override
public void sendReplyToRpcCallFromDevice(TenantId tenantId, DeviceId deviceId, int requestId, String body) {
ToServerRpcResponseActorMsg rpcMsg = new ToServerRpcResponseActorMsg(tenantId, deviceId, new ToServerRpcResponseMsg(requestId, body));
forward(deviceId, rpcMsg);
}
private void sendRpcRequestToRuleEngine(ToDeviceRpcRequest msg) {
ObjectNode entityNode = json.createObjectNode();
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("requestUUID", msg.getId().toString());
metaData.putValue("originHost", routingService.getCurrentServer().getHost());
metaData.putValue("originPort", Integer.toString(routingService.getCurrentServer().getPort()));
metaData.putValue("expirationTime", Long.toString(msg.getExpirationTime()));
metaData.putValue("oneway", Boolean.toString(msg.isOneway()));
Device device = deviceService.findDeviceById(msg.getTenantId(), msg.getDeviceId());
if (device != null) {
metaData.putValue("deviceName", device.getName());
metaData.putValue("deviceType", UUIDConverter.fromTimeUUID(device.getTypeId().getId()));
}
entityNode.put("method", msg.getBody().getMethod());
entityNode.put("params", msg.getBody().getParams());
try {
TbMsg tbMsg = new TbMsg(UUIDs.timeBased(), DataConstants.RPC_CALL_FROM_SERVER_TO_DEVICE, msg.getDeviceId(), metaData, TbMsgDataType.JSON
, json.writeValueAsString(entityNode)
, null, null, 0L);
actorService.onMsg(new SendToClusterMsg(msg.getDeviceId(), new ServiceToRuleEngineMsg(msg.getTenantId(), tbMsg)));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private void sendRpcRequestToDevice(ToDeviceRpcRequest msg) {
ToDeviceRpcRequestActorMsg rpcMsg = new ToDeviceRpcRequestActorMsg(routingService.getCurrentServer(), msg);
log.trace("[{}] Forwarding msg {} to device actor!", msg.getDeviceId(), msg);
forward(msg.getDeviceId(), rpcMsg);
}
private <T extends ToDeviceActorNotificationMsg> void forward(DeviceId deviceId, T msg) {
actorService.onMsg(new SendToClusterMsg(deviceId, msg));
}
private void scheduleTimeout(ToDeviceRpcRequest request, UUID requestId, ConcurrentMap<UUID, Consumer<FromDeviceRpcResponse>> requestsMap) {
long timeout = Math.max(0, request.getExpirationTime() - System.currentTimeMillis());
log.trace("[{}] processing the request: [{}]", this.hashCode(), requestId);
rpcCallBackExecutor.schedule(() -> {
log.trace("[{}] timeout the request: [{}]", this.hashCode(), requestId);
Consumer<FromDeviceRpcResponse> consumer = requestsMap.remove(requestId);
if (consumer != null) {
consumer.accept(new FromDeviceRpcResponse(requestId, null, RpcError.TIMEOUT));
}
}, timeout, TimeUnit.MILLISECONDS);
}
}
| 47.627803 | 155 | 0.727992 |
d48fe0564a782edc241093b00904b46fa6879344 | 636 | /**
* This package contains case matching functionality where the object/value to match on is
* known on definition time of the cases. To start matching, use on of the static methods
* defined in class {@link de.boereck.matcher.eager.EagerMatcher EagerMatcher}. The implementation
* is optimized to create as few objects (and therefore garbage) as possible, while still
* being immutable. Cases are evaluated directly when they are called, if a match is found
* further cases will not evaluate their checks (e.g. instanceof checks, predicates, to optional functions).
*
* @author Max Bureck
*/
package de.boereck.matcher.eager; | 57.818182 | 108 | 0.773585 |
4e9fbe8b21b31be7d67e93bd73ab2cb92da22dc3 | 5,333 | /*
* Copyright 2013 Robert von Burg <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.utils.helper;
import static li.strolch.utils.helper.BaseDecodingTest.PROP_RUN_PERF_TESTS;
import static li.strolch.utils.helper.BaseDecodingTest.isSkipPerfTests;
import static li.strolch.utils.helper.BaseEncoding.*;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <[email protected]>
*/
@SuppressWarnings("nls")
public class BaseEncodingTest {
private static final Logger logger = LoggerFactory.getLogger(BaseEncodingTest.class);
@Test
public void testBase64() {
assertEquals("", toBase64(""));
assertEquals("Zg==", toBase64("f"));
assertEquals("Zm8=", toBase64("fo"));
assertEquals("Zm9v", toBase64("foo"));
assertEquals("Zm9vYg==", toBase64("foob"));
assertEquals("Zm9vYmE=", toBase64("fooba"));
assertEquals("Zm9vYmFy", toBase64("foobar"));
}
@Test
public void testBase32() {
assertEquals("", toBase32(""));
assertEquals("MY======", toBase32("f"));
assertEquals("MZXQ====", toBase32("fo"));
assertEquals("MZXW6===", toBase32("foo"));
assertEquals("MZXW6YQ=", toBase32("foob"));
assertEquals("MZXW6YTB", toBase32("fooba"));
assertEquals("MZXW6YTBOI======", toBase32("foobar"));
}
@Test
public void testBase32Hex() {
assertEquals("", toBase32Hex(""));
assertEquals("CO======", toBase32Hex("f"));
assertEquals("CPNG====", toBase32Hex("fo"));
assertEquals("CPNMU===", toBase32Hex("foo"));
assertEquals("CPNMUOG=", toBase32Hex("foob"));
assertEquals("CPNMUOJ1", toBase32Hex("fooba"));
assertEquals("CPNMUOJ1E8======", toBase32Hex("foobar"));
}
@Test
public void testBase32Dmedia() {
assertEquals("", toBase32Dmedia(""));
assertEquals("FCNPVRELI7J9FUUI", toBase32Dmedia("binary foo"));
assertEquals("FR======", toBase32Dmedia("f"));
assertEquals("FSQJ====", toBase32Dmedia("fo"));
assertEquals("FSQPX===", toBase32Dmedia("foo"));
assertEquals("FSQPXRJ=", toBase32Dmedia("foob"));
assertEquals("FSQPXRM4", toBase32Dmedia("fooba"));
assertEquals("FSQPXRM4HB======", toBase32Dmedia("foobar"));
}
@Test
public void testBase16() {
assertEquals("", toBase16(""));
assertEquals("66", toBase16("f"));
assertEquals("666F", toBase16("fo"));
assertEquals("666F6F", toBase16("foo"));
assertEquals("666F6F62", toBase16("foob"));
assertEquals("666F6F6261", toBase16("fooba"));
assertEquals("666F6F626172", toBase16("foobar"));
}
@Test
public void testBase64Perf() {
if (isSkipPerfTests()) {
logger.info("Not running performance tests as not enabled by system property " + PROP_RUN_PERF_TESTS);
return;
}
long start = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
for (int i = 0; i < 200; i++) {
toBase64(bytes);
}
long end = System.nanoTime();
logger.info("Encoding 200MB Base64 took " + StringHelper.formatNanoDuration(end - start));
}
@Test
public void testBase32Perf() {
if (isSkipPerfTests()) {
logger.info("Not running performance tests as not enabled by system property " + PROP_RUN_PERF_TESTS);
return;
}
long start = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
for (int i = 0; i < 200; i++) {
toBase32(bytes);
}
long end = System.nanoTime();
logger.info("Encoding 200MB Base32 took " + StringHelper.formatNanoDuration(end - start));
}
@Test
public void testBase32HexPerf() {
if (isSkipPerfTests()) {
logger.info("Not running performance tests as not enabled by system property " + PROP_RUN_PERF_TESTS);
return;
}
long start = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
for (int i = 0; i < 200; i++) {
toBase32Hex(bytes);
}
long end = System.nanoTime();
logger.info("Encoding 200MB Base32Hex took " + StringHelper.formatNanoDuration(end - start));
}
@Test
public void testBase32DmediaPerf() {
if (isSkipPerfTests()) {
logger.info("Not running performance tests as not enabled by system property " + PROP_RUN_PERF_TESTS);
return;
}
long start = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
for (int i = 0; i < 200; i++) {
toBase32Hex(bytes);
}
long end = System.nanoTime();
logger.info("Encoding 200MB Base32Dmedia took " + StringHelper.formatNanoDuration(end - start));
}
@Test
public void testBase16Perf() {
if (isSkipPerfTests()) {
logger.info("Not running performance tests as not enabled by system property " + PROP_RUN_PERF_TESTS);
return;
}
long start = System.nanoTime();
byte[] bytes = new byte[1024 * 1024];
for (int i = 0; i < 200; i++) {
toBase16(bytes);
}
long end = System.nanoTime();
logger.info("Encoding 200MB Base16 took " + StringHelper.formatNanoDuration(end - start));
}
}
| 31.187135 | 105 | 0.68723 |
3404c59e4d720b47bd58f5f0df35e00647a3390f | 1,200 | package com.example.vendingmachine.model;
import java.util.HashMap;
import java.util.Map;
public class Inventory<T> {
private Map<T, Integer> inventory = new HashMap<>();
public int getQuantity(T item) {
Integer value = inventory.get(item);
return value == null ? 0 : value;
}
public void add(T item) {
int count = inventory.get(item);
inventory.put(item, count + 1);
}
public void deduct(T item) {
if (hasItem(item)) {
int count = inventory.get(item);
inventory.put(item, count - 1);
}
}
public boolean hasItem(T item) {
return getQuantity(item) > 0;
}
public void clear() {
inventory.clear();
}
public void put(T item, int quantity) {
inventory.put(item, quantity);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (Map.Entry<T, Integer> entry : inventory.entrySet()) {
result.append(entry.getKey());
result.append(" : ");
result.append(entry.getValue());
result.append("\n");
}
return result.toString();
}
}
| 23.076923 | 66 | 0.563333 |
4a95396a1d6830d292aa5985b40e07b2910d7fb3 | 1,982 | /**
* NOTE: This class is auto generated by the swagger code generator program (3.0.32).
* https://github.com/swagger-api/swagger-codegen Do not edit the class manually.
*/
package de.skuld.web.api;
import de.skuld.web.model.RandomnessQuery;
import de.skuld.web.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import javax.annotation.processing.Generated;
import javax.validation.Valid;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2022-01-24T09:48:19.864Z[GMT]")
@Validated
public interface RandomnessApi {
@Operation(summary = "analyzes randomness", description = "Randomness submitted to this endpoint will be analyzed. Statistical tests will be performed and we will try to solve for a PRNG and seed combination", tags = {
"Public API"})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "analysis results", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Result.class)))})
@PostMapping(value = "/randomness",
produces = {MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<Result> analyzeRandomness(
@Parameter(in = ParameterIn.DEFAULT, description = "randomness to be analyzed", required = true, schema = @Schema()) @Valid @RequestBody RandomnessQuery body);
}
| 49.55 | 220 | 0.783047 |
021fb9284dedcb89fd56a1a028d1e5badc5a94c4 | 1,471 | package de.feli490.feliutils.items;
import org.bukkit.inventory.ItemStack;
public enum DefaultSkulls {
RED_CROSS("5ecfabf0-5253-47b0-a44d-9a0c924081b9", "RED_CROSS",
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmViNTg4YjIxYTZmOThhZDFmZjRlMDg1YzU1MmRjYjA1MGVmYzljYWI0MjdmNDYwNDhmMThmYzgwMzQ3NWY3In19fQ=="),
GREEN_CHECKMARK("034a0e9e-8745-4fc6-8639-84abc48e9f72", "GREEN_CHECKMARK",
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTkyZTMxZmZiNTljOTBhYjA4ZmM5ZGMxZmUyNjgwMjAzNWEzYTQ3YzQyZmVlNjM0MjNiY2RiNDI2MmVjYjliNiJ9fX0="),
OPEN_CHEST("6cea9d9c-a908-4eec-a16e-0fdb0ce11fb8", "OPEN_CHEST",
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjZhY2ZjNjQzZjYwOGUxNmRlMTkzMzVkZGNhNzFhODI4ZGZiOGRhY2E1NzkzZWI1YmJjYjBjN2QxNTU5MjQ5In19fQ=="),
QUESTION_MARK("0929b983-8469-409a-82c0-b1b28ff3af47", "QUESTION_MARK",
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmMyNzEwNTI3MTllZjY0MDc5ZWU4YzE0OTg5NTEyMzhhNzRkYWM0YzI3Yjk1NjQwZGI2ZmJkZGMyZDZiNWI2ZSJ9fX0=");
private ItemStack head;
DefaultSkulls(String ownerUUIDString, String ownerName, String texturesProperty) {
head = SkullItemUtils.createHead(ownerUUIDString, ownerName, texturesProperty);
}
public ItemStack getItemStack() {
return head.clone();
}
}
| 56.576923 | 196 | 0.831407 |
c62c5dd7e891844eb41fd0a66344b02124539f02 | 11,944 | package com.pichs.filechooser;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.StringDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 调用系统分享的工具类
* 适配了一些手机
* FileShare.with(context)
* .setTitle("标题")
* .setTextContent("内容")
* .setContentType(FileShare.UriType.IMAGE)
* .addShareFileUri(uri)
* .setOnActivityResult(120)
* .build()
* .share();
*/
@SuppressWarnings("ALL")
public class FileShare {
private static final String TAG = "FileShare";
/**
* ShareContentType 选择分享的类型
* Support Share Content Types.
* 两种: 文本类型,文件类型(包含图片视频等))
*/
@StringDef({ContentType.FILE,
ContentType.IMAGE,
ContentType.TEXT})
@Retention(RetentionPolicy.SOURCE)
public @interface UriType {
}
/**
* Current activity
*/
private Activity activity;
/**
* Share content type
*/
private @UriType
String contentType;
/**
* Share title
*/
private String title;
/**
* Share file Uri
*/
private Set<Uri> shareFileUriList;
/**
* Share content text
*/
private String contentText;
/**
* Share to special component PackageName
*/
private String componentPackageName;
/**
* Share to special component ClassName
*/
private String componentClassName;
/**
* Share to special component ClassName
*/
private String targetPackage;
/**
* Share complete onActivityResult requestCode
*/
private int requestCode;
/**
* Forced Use System Chooser
*/
private boolean forcedUseSystemChooser;
private FileShare(@NonNull Builder builder) {
this.activity = builder.activity;
this.contentType = builder.contentType;
this.title = builder.title;
this.shareFileUriList = builder.shareFileUriList;
this.contentText = builder.textContent;
this.componentPackageName = builder.componentPackageName;
this.componentClassName = builder.componentClassName;
this.requestCode = builder.requestCode;
this.forcedUseSystemChooser = builder.forcedUseSystemChooser;
this.targetPackage = builder.targetPackage;
}
/**
* share
*/
public void share() {
if (checkShareParam()) {
Intent shareIntent = createShareIntent();
if (shareIntent == null) {
Log.e(TAG, "share failed! share Intent is null");
return;
}
if (title == null) {
title = "";
}
if (forcedUseSystemChooser) {
shareIntent = Intent.createChooser(shareIntent, title);
}
if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
try {
if (requestCode != -1) {
activity.startActivityForResult(shareIntent, requestCode);
} else {
activity.startActivity(shareIntent);
}
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
}
}
}
private Intent createShareIntent() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addCategory("android.intent.category.DEFAULT");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 优先使用ComponentName没有再考虑packageName
if (!TextUtils.isEmpty(this.componentPackageName) && !TextUtils.isEmpty(componentClassName)) {
ComponentName comp = new ComponentName(componentPackageName, componentClassName);
shareIntent.setComponent(comp);
} else if (!TextUtils.isEmpty(this.targetPackage)) {
shareIntent.setPackage(this.targetPackage);
}
switch (contentType) {
case ContentType.TEXT:
shareIntent.putExtra(Intent.EXTRA_TEXT, contentText);
shareIntent.setType(contentType);
break;
case ContentType.FILE:
case ContentType.IMAGE:
if (shareFileUriList == null || shareFileUriList.isEmpty()) {
// 没数据分享个屁
Log.e(TAG, "shareFileUriList is null");
return null;
}
shareIntent.setType(contentType);
if (!TextUtils.isEmpty(contentText)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, contentText);
}
if (shareFileUriList.size() == 1) {
shareIntent.putExtra(Intent.EXTRA_STREAM, shareFileUriList.iterator().next());
} else {
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, new ArrayList<>(shareFileUriList));
}
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(shareIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
for (Uri uri : shareFileUriList) {
activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
}
break;
default:
Log.e(TAG, contentType + " is not support share type.");
shareIntent = null;
break;
}
return shareIntent;
}
private boolean checkShareParam() {
if (this.activity == null) {
Log.e(TAG, "activity is null.");
return false;
}
if (ContentType.TEXT.equals(contentType)) {
if (TextUtils.isEmpty(contentText)) {
Log.e(TAG, "Share text context is empty.");
return false;
}
} else {
if (this.shareFileUriList == null || shareFileUriList.isEmpty()) {
Log.e(TAG, "Share file path is null.");
return false;
}
}
return true;
}
public static Builder with(Activity activity) {
return new Builder(activity);
}
public static class Builder {
private Activity activity;
@UriType
private String contentType = ContentType.FILE;
private String title;
// 指定app的界面 优先
private String componentPackageName;
private String componentClassName;
// 指定app分享 次之
private String targetPackage;
private Set<Uri> shareFileUriList;
private String textContent;
private int requestCode = -1;
private boolean forcedUseSystemChooser = true;
public Builder(Activity activity) {
this.activity = activity;
}
/**
* Set Content Type
*
* @param contentType {@link ContentType}
* @return Builder
*/
public Builder setContentType(@UriType String contentType) {
this.contentType = contentType;
return this;
}
/**
* Set Title
*
* @param title title
* @return Builder
*/
public Builder setTitle(@NonNull String title) {
this.title = title;
return this;
}
/**
* Set share file path uri, ,分享图片时使用,分享文字时调用无效
* 添加一个uri
*
* @param shareUri shareFileUri
* @return Builder
*/
public Builder addShareFileUri(Uri shareUri) {
if (shareUri == null) {
return this;
}
if (shareFileUriList == null) {
shareFileUriList = new HashSet<>();
}
this.shareFileUriList.add(shareUri);
return this;
}
/**
* Set share file path uri, ,分享图片时使用,分享文字时调用无效
* 添加一个uri
*
* @param shareUris shareFileUri
* @return Builder
*/
public Builder addShareFileUri(Uri... shareUris) {
if (shareUris == null || shareUris.length == 0) {
return this;
}
if (shareUris.length == 1) {
addShareFileUri(shareUris[0]);
return this;
}
if (this.shareFileUriList == null) {
this.shareFileUriList = new HashSet<>();
}
this.shareFileUriList.addAll(Arrays.asList(shareUris));
return this;
}
/**
* 批量添加uri ,分享图片时使用,分享文字时调用无效
*
* @param shareUriList Collection<Uri>
* @return
*/
public Builder addShareFileUri(Collection<Uri> shareUriList) {
if (shareUriList == null) {
return this;
}
if (this.shareFileUriList == null) {
this.shareFileUriList = new HashSet<>();
}
this.shareFileUriList.addAll(shareUriList);
return this;
}
public Builder clearShareFileUri() {
if (this.shareFileUriList != null) {
this.shareFileUriList.clear();
}
return this;
}
/**
* Set text content ,分享文字时使用,分享图片时调用无效
*
* @param textContent textContent
* @return Builder
*/
public Builder setTextContent(@NonNull String textContent) {
this.textContent = textContent;
return this;
}
/**
* Set Share To Component,可指定app 页面、包名分享
*
* @param componentPackageName componentPackageName
* @param componentClassName componentPackageName
* @return Builder
*/
public Builder setShareToComponent(String componentPackageName, String componentClassName) {
this.componentPackageName = componentPackageName;
this.componentClassName = componentClassName;
return this;
}
/**
* 设置分享至app的package name
*
* @param targetPackage 目标app的包名
* @return Builder
*/
public Builder setTargetPackage(String targetPackage) {
this.targetPackage = targetPackage;
return this;
}
/**
* Set onActivityResult requestCode, default value is -1
*
* @param requestCode requestCode
* @return Builder
*/
public Builder setOnActivityResult(int requestCode) {
this.requestCode = requestCode;
return this;
}
/**
* Forced Use System Chooser To Share
*
* @param enable default is true
* @return Builder
*/
public Builder forcedUseSystemChooser(boolean enable) {
this.forcedUseSystemChooser = enable;
return this;
}
/**
* build
*
* @return Share2
*/
public FileShare build() {
return new FileShare(this);
}
}
}
| 29.27451 | 151 | 0.557351 |
4d7443fc8af64fc033beda55729ba047587fdc18 | 24,639 | /*
* Copyright 2018 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.protean.arc.processor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.spi.DefinitionException;
import javax.enterprise.inject.spi.DeploymentException;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationTarget.Kind;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.ClassInfo.NestingType;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.jboss.protean.arc.processor.BeanDeploymentValidator.ValidationContext;
import org.jboss.protean.arc.processor.BeanProcessor.BuildContextImpl;
import org.jboss.protean.arc.processor.BeanRegistrar.RegistrationContext;
import org.jboss.protean.arc.processor.BuildExtension.BuildContext;
import org.jboss.protean.arc.processor.BuildExtension.Key;
/**
*
* @author Martin Kouba
*/
public class BeanDeployment {
private static final Logger LOGGER = Logger.getLogger(BeanDeployment.class);
private final IndexView index;
private final Map<DotName, ClassInfo> qualifiers;
private final Map<DotName, ClassInfo> interceptorBindings;
private final Map<DotName, StereotypeInfo> stereotypes;
private final List<BeanInfo> beans;
private final List<InterceptorInfo> interceptors;
private final List<ObserverInfo> observers;
private final BeanResolver beanResolver;
private final InterceptorResolver interceptorResolver;
private final AnnotationStore annotationStore;
private final Set<DotName> resourceAnnotations;
BeanDeployment(IndexView index, Collection<BeanDefiningAnnotation> additionalBeanDefiningAnnotations, List<AnnotationsTransformer> annotationTransformers) {
this(index, additionalBeanDefiningAnnotations, annotationTransformers, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
}
BeanDeployment(IndexView index, Collection<BeanDefiningAnnotation> additionalBeanDefiningAnnotations, List<AnnotationsTransformer> annotationTransformers,
Collection<DotName> resourceAnnotations, List<BeanRegistrar> beanRegistrars, List<BeanDeploymentValidator> validators,
BuildContextImpl buildContext) {
long start = System.currentTimeMillis();
this.resourceAnnotations = new HashSet<>(resourceAnnotations);
this.index = index;
this.annotationStore = new AnnotationStore(annotationTransformers, buildContext);
if (buildContext != null) {
buildContext.putInternal(Key.ANNOTATION_STORE.asString(), annotationStore);
}
this.qualifiers = findQualifiers(index);
// TODO interceptor bindings are transitive!!!
this.interceptorBindings = findInterceptorBindings(index);
this.stereotypes = findStereotypes(index, interceptorBindings, additionalBeanDefiningAnnotations);
this.interceptors = findInterceptors();
this.beanResolver = new BeanResolver(this);
List<ObserverInfo> observers = new ArrayList<>();
List<InjectionPointInfo> injectionPoints = new ArrayList<>();
this.beans = findBeans(initBeanDefiningAnnotations(additionalBeanDefiningAnnotations, stereotypes.keySet()), observers, injectionPoints);
if (buildContext != null) {
buildContext.putInternal(Key.INJECTION_POINTS.asString(), Collections.unmodifiableList(injectionPoints));
buildContext.putInternal(Key.OBSERVERS.asString(), Collections.unmodifiableList(observers));
buildContext.putInternal(Key.BEANS.asString(), Collections.unmodifiableList(beans));
}
// Register synthetic beans
if (!beanRegistrars.isEmpty()) {
RegistrationContext registrationContext = new RegistrationContext() {
@Override
public <T> BeanConfigurator<T> configure(Class<?> beanClass) {
return new BeanConfigurator<T>(beanClass, BeanDeployment.this, beans::add);
}
@Override
public <V> V get(Key<V> key) {
return buildContext.get(key);
}
@Override
public <V> V put(Key<V> key, V value) {
return buildContext.put(key, value);
}
};
for (BeanRegistrar registrar : beanRegistrars) {
registrar.register(registrationContext);
}
}
// Validate the bean deployment
List<Throwable> errors = new ArrayList<>();
validateBeanNames(errors);
ValidationContextImpl validationContext = new ValidationContextImpl(buildContext);
for (BeanDeploymentValidator validator : validators) {
validator.validate(validationContext);
}
errors.addAll(validationContext.getErrors());
if (!errors.isEmpty()) {
if (errors.size() == 1) {
Throwable error = errors.get(0);
if (error instanceof DeploymentException) {
throw (DeploymentException) error;
} else {
throw new DeploymentException(errors.get(0));
}
} else {
DeploymentException deploymentException = new DeploymentException("Multiple deployment problems occured: " + errors.stream()
.map(e -> e.getMessage())
.collect(Collectors.toList())
.toString());
for (Throwable error : errors) {
deploymentException.addSuppressed(error);
}
throw deploymentException;
}
}
this.observers = observers;
this.interceptorResolver = new InterceptorResolver(this);
LOGGER.infof("Bean deployment created in %s ms", System.currentTimeMillis() - start);
}
private void validateBeanNames(List<Throwable> errors) {
Map<String, List<BeanInfo>> namedBeans = new HashMap<>();
for (BeanInfo bean : beans) {
if (bean.getName() != null) {
List<BeanInfo> named = namedBeans.get(bean.getName());
if (named == null) {
named = new ArrayList<>();
namedBeans.put(bean.getName(), named);
}
named.add(bean);
}
}
if (!namedBeans.isEmpty()) {
for (Entry<String, List<BeanInfo>> entry : namedBeans.entrySet()) {
if (entry.getValue()
.size() > 1) {
if (Beans.resolveAmbiguity(entry.getValue()) == null) {
errors.add(new DeploymentException("Unresolvable ambiguous bean name detected: " + entry.getKey() + "\nBeans:\n" + entry.getValue()
.stream()
.map(Object::toString)
.collect(Collectors.joining("\n"))));
}
}
}
}
}
public Collection<BeanInfo> getBeans() {
return beans;
}
Collection<ObserverInfo> getObservers() {
return observers;
}
Collection<InterceptorInfo> getInterceptors() {
return interceptors;
}
IndexView getIndex() {
return index;
}
BeanResolver getBeanResolver() {
return beanResolver;
}
InterceptorResolver getInterceptorResolver() {
return interceptorResolver;
}
ClassInfo getQualifier(DotName name) {
return qualifiers.get(name);
}
ClassInfo getInterceptorBinding(DotName name) {
return interceptorBindings.get(name);
}
StereotypeInfo getStereotype(DotName name) {
return stereotypes.get(name);
}
Set<DotName> getResourceAnnotations() {
return resourceAnnotations;
}
AnnotationStore getAnnotationStore() {
return annotationStore;
}
Collection<AnnotationInstance> getAnnotations(AnnotationTarget target) {
return annotationStore.getAnnotations(target);
}
AnnotationInstance getAnnotation(AnnotationTarget target, DotName name) {
return annotationStore.getAnnotation(target, name);
}
boolean hasAnnotation(AnnotationTarget target, DotName name) {
return annotationStore.hasAnnotation(target, name);
}
void init() {
long start = System.currentTimeMillis();
for (BeanInfo bean : beans) {
bean.init();
}
for (InterceptorInfo interceptor : interceptors) {
interceptor.init();
}
LOGGER.infof("Bean deployment initialized in %s ms", System.currentTimeMillis() - start);
}
static Map<DotName, ClassInfo> findQualifiers(IndexView index) {
Map<DotName, ClassInfo> qualifiers = new HashMap<>();
for (AnnotationInstance qualifier : index.getAnnotations(DotNames.QUALIFIER)) {
qualifiers.put(qualifier.target().asClass().name(), qualifier.target().asClass());
}
return qualifiers;
}
static Map<DotName, ClassInfo> findInterceptorBindings(IndexView index) {
Map<DotName, ClassInfo> bindings = new HashMap<>();
for (AnnotationInstance binding : index.getAnnotations(DotNames.INTERCEPTOR_BINDING)) {
bindings.put(binding.target().asClass().name(), binding.target().asClass());
}
return bindings;
}
static Map<DotName, StereotypeInfo> findStereotypes(IndexView index, Map<DotName, ClassInfo> interceptorBindings, Collection<BeanDefiningAnnotation> additionalBeanDefiningAnnotations) {
Map<DotName, StereotypeInfo> stereotypes = new HashMap<>();
for (AnnotationInstance stereotype : index.getAnnotations(DotNames.STEREOTYPE)) {
ClassInfo stereotypeClass = index.getClassByName(stereotype.target().asClass().name());
if (stereotypeClass != null) {
boolean isAlternative = false;
ScopeInfo scope = null;
List<AnnotationInstance> bindings = new ArrayList<>();
boolean isNamed = false;
for (AnnotationInstance annotation : stereotypeClass.classAnnotations()) {
if (DotNames.ALTERNATIVE.equals(annotation.name())) {
isAlternative = true;
} else if (interceptorBindings.containsKey(annotation.name())) {
bindings.add(annotation);
} else if (DotNames.NAMED.equals(annotation.name())) {
if (annotation.value() != null && !annotation.value()
.asString()
.isEmpty()) {
throw new DefinitionException("Stereotype must not declare @Named with a non-empty value: " + stereotypeClass);
}
isNamed = true;
} else if (scope == null) {
scope = ScopeInfo.from(annotation.name());
}
}
stereotypes.put(stereotype.target().asClass().name(), new StereotypeInfo(scope, bindings, isAlternative, isNamed, stereotypeClass));
}
}
//if an additional bean defining annotation has a default scope we register it as a stereotype
if(additionalBeanDefiningAnnotations != null) {
for (BeanDefiningAnnotation i : additionalBeanDefiningAnnotations) {
if (i.getDefaultScope() != null) {
stereotypes.put(i.getAnnotation(), new StereotypeInfo(ScopeInfo.from(i.getDefaultScope()), Collections.emptyList(), false, false, index.getClassByName(i.getAnnotation())));
}
}
}
return stereotypes;
}
private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, List<ObserverInfo> observers, List<InjectionPointInfo> injectionPoints) {
Set<ClassInfo> beanClasses = new HashSet<>();
Set<MethodInfo> producerMethods = new HashSet<>();
Set<MethodInfo> disposerMethods = new HashSet<>();
Set<FieldInfo> producerFields = new HashSet<>();
Set<MethodInfo> syncObserverMethods = new HashSet<>();
Set<MethodInfo> asyncObserverMethods = new HashSet<>();
for (ClassInfo beanClass : index.getKnownClasses()) {
if (Modifier.isInterface(beanClass.flags()) || DotNames.ENUM.equals(beanClass.superName())) {
// Skip interfaces, annotations and enums
continue;
}
if (beanClass.nestingType().equals(NestingType.ANONYMOUS) || beanClass.nestingType().equals(NestingType.LOCAL)
|| (beanClass.nestingType().equals(NestingType.INNER) && !Modifier.isStatic(beanClass.flags()))) {
// Skip annonymous, local and inner classes
continue;
}
if (!beanClass.hasNoArgsConstructor()
&& beanClass.methods().stream().noneMatch(m -> m.name().equals("<init>") && m.hasAnnotation(DotNames.INJECT))) {
// Must have a constructor with no parameters or declare a constructor annotated with @Inject
continue;
}
if (annotationStore.hasAnnotation(beanClass, DotNames.VETOED)) {
// Skip vetoed bean classes
continue;
}
if (annotationStore.hasAnnotation(beanClass, DotNames.INTERCEPTOR)) {
// Skip interceptors
continue;
}
if (beanClass.interfaceNames().contains(DotNames.EXTENSION)) {
// Skip portable extensions
continue;
}
boolean hasBeanDefiningAnnotation = false;
if (annotationStore.hasAnyAnnotation(beanClass, beanDefiningAnnotations)) {
hasBeanDefiningAnnotation = true;
beanClasses.add(beanClass);
}
for (MethodInfo method : beanClass.methods()) {
if (annotationStore.getAnnotations(method).isEmpty()) {
continue;
}
if (annotationStore.hasAnnotation(method, DotNames.PRODUCES)) {
// Producers are not inherited
producerMethods.add(method);
if (!hasBeanDefiningAnnotation) {
LOGGER.infof("Producer method found but %s has no bean defining annotation - using @Dependent", beanClass);
beanClasses.add(beanClass);
}
} else if (annotationStore.hasAnnotation(method, DotNames.DISPOSES)) {
// Disposers are not inherited
disposerMethods.add(method);
} else if (annotationStore.hasAnnotation(method, DotNames.OBSERVES)) {
// TODO observers are inherited
syncObserverMethods.add(method);
if (!hasBeanDefiningAnnotation) {
LOGGER.infof("Observer method found but %s has no bean defining annotation - using @Dependent", beanClass);
beanClasses.add(beanClass);
}
} else if (annotationStore.hasAnnotation(method, DotNames.OBSERVES_ASYNC)) {
// TODO observers are inherited
asyncObserverMethods.add(method);
if (!hasBeanDefiningAnnotation) {
LOGGER.infof("Observer method found but %s has no bean defining annotation - using @Dependent", beanClass);
beanClasses.add(beanClass);
}
}
}
for (FieldInfo field : beanClass.fields()) {
if (annotationStore.hasAnnotation(field, DotNames.PRODUCES)) {
// Producer fields are not inherited
producerFields.add(field);
if (!hasBeanDefiningAnnotation) {
LOGGER.infof("Producer field found but %s has no bean defining annotation - using @Dependent", beanClass);
beanClasses.add(beanClass);
}
}
}
}
// Build metadata for typesafe resolution
List<BeanInfo> beans = new ArrayList<>();
Map<ClassInfo, BeanInfo> beanClassToBean = new HashMap<>();
for (ClassInfo beanClass : beanClasses) {
BeanInfo classBean = Beans.createClassBean(beanClass, this);
beans.add(classBean);
beanClassToBean.put(beanClass, classBean);
injectionPoints.addAll(classBean.getAllInjectionPoints());
}
List<DisposerInfo> disposers = new ArrayList<>();
for (MethodInfo disposerMethod : disposerMethods) {
BeanInfo declaringBean = beanClassToBean.get(disposerMethod.declaringClass());
if (declaringBean != null) {
Injection injection = Injection.forDisposer(disposerMethod, this);
disposers.add(new DisposerInfo(declaringBean, disposerMethod, injection));
injectionPoints.addAll(injection.injectionPoints);
}
}
for (MethodInfo producerMethod : producerMethods) {
BeanInfo declaringBean = beanClassToBean.get(producerMethod.declaringClass());
if (declaringBean != null) {
BeanInfo producerMethodBean = Beans.createProducerMethod(producerMethod, declaringBean, this,
findDisposer(declaringBean, producerMethod, disposers));
beans.add(producerMethodBean);
injectionPoints.addAll(producerMethodBean.getAllInjectionPoints());
}
}
for (FieldInfo producerField : producerFields) {
BeanInfo declaringBean = beanClassToBean.get(producerField.declaringClass());
if (declaringBean != null) {
beans.add(Beans.createProducerField(producerField, declaringBean, this, findDisposer(declaringBean, producerField, disposers)));
}
}
for (MethodInfo observerMethod : syncObserverMethods) {
BeanInfo declaringBean = beanClassToBean.get(observerMethod.declaringClass());
if (declaringBean != null) {
Injection injection = Injection.forObserver(observerMethod, this);
observers.add(new ObserverInfo(declaringBean, observerMethod, injection, false));
injectionPoints.addAll(injection.injectionPoints);
}
}
for (MethodInfo observerMethod : asyncObserverMethods) {
BeanInfo declaringBean = beanClassToBean.get(observerMethod.declaringClass());
if (declaringBean != null) {
Injection injection = Injection.forObserver(observerMethod, this);
observers.add(new ObserverInfo(declaringBean, observerMethod, injection, true));
injectionPoints.addAll(injection.injectionPoints);
}
}
if (LOGGER.isDebugEnabled()) {
for (BeanInfo bean : beans) {
LOGGER.logf(Level.DEBUG, "Created %s", bean);
}
}
return beans;
}
private DisposerInfo findDisposer(BeanInfo declaringBean, AnnotationTarget annotationTarget, List<DisposerInfo> disposers) {
List<DisposerInfo> found = new ArrayList<>();
Type beanType;
Set<AnnotationInstance> qualifiers;
if (Kind.FIELD.equals(annotationTarget.kind())) {
beanType = annotationTarget.asField().type();
qualifiers = annotationTarget.asField().annotations().stream().filter(a -> getQualifier(a.name()) != null).collect(Collectors.toSet());
} else if (Kind.METHOD.equals(annotationTarget.kind())) {
beanType = annotationTarget.asMethod().returnType();
qualifiers = annotationTarget.asMethod().annotations().stream().filter(a -> Kind.METHOD.equals(a.target().kind()) && getQualifier(a.name()) != null)
.collect(Collectors.toSet());
} else {
throw new RuntimeException("Unsupported annotation target: " + annotationTarget);
}
for (DisposerInfo disposer : disposers) {
if (disposer.getDeclaringBean().equals(declaringBean)) {
boolean hasQualifier = true;
for (AnnotationInstance qualifier : qualifiers) {
if (!Beans.hasQualifier(getQualifier(qualifier.name()), qualifier, null)) {
hasQualifier = false;
}
}
if (hasQualifier && beanResolver.matches(beanType, disposer.getDisposerMethod().parameters().get(disposer.getDisposedParameter().position()))) {
found.add(disposer);
}
}
}
if (found.size() > 1) {
throw new DefinitionException("Multiple disposer methods found for " + annotationTarget);
}
return found.isEmpty() ? null : found.get(0);
}
private List<InterceptorInfo> findInterceptors() {
Set<ClassInfo> interceptorClasses = new HashSet<>();
for (AnnotationInstance annotation : index.getAnnotations(DotNames.INTERCEPTOR)) {
if (Kind.CLASS.equals(annotation.target().kind())) {
interceptorClasses.add(annotation.target().asClass());
}
}
List<InterceptorInfo> interceptors = new ArrayList<>();
for (ClassInfo interceptorClass : interceptorClasses) {
interceptors.add(Interceptors.createInterceptor(interceptorClass, this));
}
if (LOGGER.isDebugEnabled()) {
for (InterceptorInfo interceptor : interceptors) {
LOGGER.logf(Level.DEBUG, "Created %s", interceptor);
}
}
return interceptors;
}
public static Set<DotName> initBeanDefiningAnnotations(Collection<BeanDefiningAnnotation> additionalBeanDefiningAnnotations, Set<DotName> stereotypes) {
Set<DotName> beanDefiningAnnotations = new HashSet<>();
for (ScopeInfo scope : ScopeInfo.values()) {
beanDefiningAnnotations.add(scope.getDotName());
}
if (additionalBeanDefiningAnnotations != null) {
beanDefiningAnnotations.addAll(additionalBeanDefiningAnnotations.stream().map(BeanDefiningAnnotation::getAnnotation).collect(Collectors.toSet()));
}
beanDefiningAnnotations.addAll(stereotypes);
beanDefiningAnnotations.add(DotNames.create(Model.class));
return beanDefiningAnnotations;
}
static class ValidationContextImpl implements ValidationContext {
private final BuildContext buildContext;
private final List<Throwable> errors;
public ValidationContextImpl(BuildContext buildContext) {
this.buildContext = buildContext;
this.errors = new ArrayList<Throwable>();
}
@Override
public <V> V get(Key<V> key) {
return buildContext.get(key);
}
@Override
public <V> V put(Key<V> key, V value) {
return buildContext.put(key, value);
}
@Override
public void addDeploymentProblem(Throwable problem) {
errors.add(problem);
}
List<Throwable> getErrors() {
return errors;
}
}
}
| 42.481034 | 192 | 0.61841 |
9586da5e024ac5cde2e8a1b5740728b31d7d604d | 1,002 | package com.aman.log4j2;
/* ################### */
/* Author : AMAN VERMA */
/* ################### */
public class CircleRect {
private int rectangleLength;
private int rectangleBreadth;
private float circleRadius;
public CircleRect(int rectangleLength, int rectangleBreadth) {
this.rectangleLength = rectangleLength;
this.rectangleBreadth = rectangleBreadth;
}
public CircleRect(float circleRadius) {
this.circleRadius = circleRadius;
}
// Circle Area Calculator Method
public float calculateCircleArea() {
return (float) (3.14 * circleRadius * circleRadius);
}
// Circle Circumference Calculator Method
public float calculateCircleCircumference() {
return (float) (2 * 3.14 * circleRadius);
}
// Rectangle Area Calculator Method
public int calculateRectangleArea() {
return rectangleLength * rectangleBreadth;
}
// Rectangle Circumference Calculator Method
public int calculateRectangleCircumference() {
return 2 * (rectangleLength + rectangleBreadth);
}
}
| 23.857143 | 63 | 0.721557 |
ac69382b930298837d1a0b35494a1b1148acf77a | 6,523 | /**
* "Visual Paradigm: DO NOT MODIFY THIS FILE!"
*
* This is an automatic generated file. It will be regenerated every time
* you generate persistence class.
*
* Modifying its content may cause the program not work, or your work may lost.
*/
/**
* Licensee: Kiyingi Simon Peter
* License Type: Purchased
*/
package entityclasses;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.orm.PersistentSession;
import org.orm.criteria.*;
public class Leave_transactionDetachedCriteria extends AbstractORMDetachedCriteria {
public final IntegerExpression leave_transaction_id;
public final IntegerExpression staffId;
public final AssociationExpression staff;
public final IntegerExpression days_taken;
public final DateExpression start_date;
public final DateExpression end_date;
public final IntegerExpression leave_year;
public final StringExpression leave_quarter;
public final StringExpression ticket_issue_by;
public final StringExpression paid_leave;
public final IntegerExpression approved_byId;
public final AssociationExpression approved_by;
public final StringExpression comment;
public final IntegerExpression leave_typeId;
public final AssociationExpression leave_type;
public final TimestampExpression add_date;
public final IntegerExpression add_userId;
public final AssociationExpression add_user;
public final TimestampExpression edit_date;
public final IntegerExpression edit_userId;
public final AssociationExpression edit_user;
public Leave_transactionDetachedCriteria() {
super(entityclasses.Leave_transaction.class, entityclasses.Leave_transactionCriteria.class);
leave_transaction_id = new IntegerExpression("leave_transaction_id", this.getDetachedCriteria());
staffId = new IntegerExpression("staff.staff_id", this.getDetachedCriteria());
staff = new AssociationExpression("staff", this.getDetachedCriteria());
days_taken = new IntegerExpression("days_taken", this.getDetachedCriteria());
start_date = new DateExpression("start_date", this.getDetachedCriteria());
end_date = new DateExpression("end_date", this.getDetachedCriteria());
leave_year = new IntegerExpression("leave_year", this.getDetachedCriteria());
leave_quarter = new StringExpression("leave_quarter", this.getDetachedCriteria());
ticket_issue_by = new StringExpression("ticket_issue_by", this.getDetachedCriteria());
paid_leave = new StringExpression("paid_leave", this.getDetachedCriteria());
approved_byId = new IntegerExpression("approved_by.staff_id", this.getDetachedCriteria());
approved_by = new AssociationExpression("approved_by", this.getDetachedCriteria());
comment = new StringExpression("comment", this.getDetachedCriteria());
leave_typeId = new IntegerExpression("leave_type.leave_type_id", this.getDetachedCriteria());
leave_type = new AssociationExpression("leave_type", this.getDetachedCriteria());
add_date = new TimestampExpression("add_date", this.getDetachedCriteria());
add_userId = new IntegerExpression("add_user.user_detail_id", this.getDetachedCriteria());
add_user = new AssociationExpression("add_user", this.getDetachedCriteria());
edit_date = new TimestampExpression("edit_date", this.getDetachedCriteria());
edit_userId = new IntegerExpression("edit_user.user_detail_id", this.getDetachedCriteria());
edit_user = new AssociationExpression("edit_user", this.getDetachedCriteria());
}
public Leave_transactionDetachedCriteria(DetachedCriteria aDetachedCriteria) {
super(aDetachedCriteria, entityclasses.Leave_transactionCriteria.class);
leave_transaction_id = new IntegerExpression("leave_transaction_id", this.getDetachedCriteria());
staffId = new IntegerExpression("staff.staff_id", this.getDetachedCriteria());
staff = new AssociationExpression("staff", this.getDetachedCriteria());
days_taken = new IntegerExpression("days_taken", this.getDetachedCriteria());
start_date = new DateExpression("start_date", this.getDetachedCriteria());
end_date = new DateExpression("end_date", this.getDetachedCriteria());
leave_year = new IntegerExpression("leave_year", this.getDetachedCriteria());
leave_quarter = new StringExpression("leave_quarter", this.getDetachedCriteria());
ticket_issue_by = new StringExpression("ticket_issue_by", this.getDetachedCriteria());
paid_leave = new StringExpression("paid_leave", this.getDetachedCriteria());
approved_byId = new IntegerExpression("approved_by.staff_id", this.getDetachedCriteria());
approved_by = new AssociationExpression("approved_by", this.getDetachedCriteria());
comment = new StringExpression("comment", this.getDetachedCriteria());
leave_typeId = new IntegerExpression("leave_type.leave_type_id", this.getDetachedCriteria());
leave_type = new AssociationExpression("leave_type", this.getDetachedCriteria());
add_date = new TimestampExpression("add_date", this.getDetachedCriteria());
add_userId = new IntegerExpression("add_user.user_detail_id", this.getDetachedCriteria());
add_user = new AssociationExpression("add_user", this.getDetachedCriteria());
edit_date = new TimestampExpression("edit_date", this.getDetachedCriteria());
edit_userId = new IntegerExpression("edit_user.user_detail_id", this.getDetachedCriteria());
edit_user = new AssociationExpression("edit_user", this.getDetachedCriteria());
}
public StaffDetachedCriteria createStaffCriteria() {
return new StaffDetachedCriteria(createCriteria("staff"));
}
public StaffDetachedCriteria createApproved_byCriteria() {
return new StaffDetachedCriteria(createCriteria("approved_by"));
}
public Leave_typeDetachedCriteria createLeave_typeCriteria() {
return new Leave_typeDetachedCriteria(createCriteria("leave_type"));
}
public User_detailDetachedCriteria createAdd_userCriteria() {
return new User_detailDetachedCriteria(createCriteria("add_user"));
}
public User_detailDetachedCriteria createEdit_userCriteria() {
return new User_detailDetachedCriteria(createCriteria("edit_user"));
}
public Leave_transaction uniqueLeave_transaction(PersistentSession session) {
return (Leave_transaction) super.createExecutableCriteria(session).uniqueResult();
}
public Leave_transaction[] listLeave_transaction(PersistentSession session) {
List list = super.createExecutableCriteria(session).list();
return (Leave_transaction[]) list.toArray(new Leave_transaction[list.size()]);
}
}
| 52.604839 | 100 | 0.791814 |
6fca9fc00d6345bb804ba5a7df4eb3747459a17d | 2,519 | package pl.polsl.workflow.manager.server.mapper;
import org.springframework.stereotype.Component;
import pl.polsl.workflow.manager.server.model.Task;
import pl.polsl.workflow.manager.server.view.TaskPost;
import pl.polsl.workflow.manager.server.view.TaskView;
import pl.polsl.workflow.manager.server.view.TaskWorkerReportPost;
@Component
public class TaskMapperImpl implements TaskMapper {
private final TaskManagerReportMapper taskManagerReportMapper;
private final TaskWorkerReportMapper taskWorkerReportMapper;
public TaskMapperImpl(TaskManagerReportMapper taskManagerReportMapper, TaskWorkerReportMapper taskWorkerReportMapper) {
this.taskManagerReportMapper = taskManagerReportMapper;
this.taskWorkerReportMapper = taskWorkerReportMapper;
}
@Override
public TaskView map(Task task) {
TaskView taskView = new TaskView();
taskView.setId(task.getId());
taskView.setIsSubTask(task.getIsSubtask());
taskView.setAssignDate(task.getAssignDate());
taskView.setCreateDate(task.getCreateDate());
taskView.setGroupId(task.getGroup().getId());
taskView.setStartDate(task.getStartDate());
taskView.setDeadline(task.getDeadline());
taskView.setDescription(task.getDescription());
taskView.setSharedTaskId(task.getSharedTaskId());
taskView.setName(task.getName());
taskView.setLocalizationId(task.getLocalization().getId());
taskView.setEstimatedExecutionTimeInMillis(task.getEstimatedExecutionTimeInMillis());
if (task.getAssignedWorker() != null)
taskView.setWorkerId(task.getAssignedWorker().getId());
if (task.getManagerReport() != null)
taskView.setTaskManagerReportView(taskManagerReportMapper.map(task.getManagerReport()));
if (task.getWorkerReport() != null)
taskView.setTaskWorkerReportView(taskWorkerReportMapper.map(task.getWorkerReport()));
return taskView;
}
@Override
public Task map(TaskPost taskPost) {
Task task = new Task();
task.setDeadline(taskPost.getDeadline());
task.setName(taskPost.getName());
task.setDescription(taskPost.getDescription());
task.setEstimatedExecutionTimeInMillis(taskPost.getEstimatedExecutionTimeInMillis());
return task;
}
@Override
public void map(TaskWorkerReportPost taskWorkerReportPost, Task task) {
task.setWorkerReport(taskWorkerReportMapper.map(taskWorkerReportPost));
}
}
| 42.694915 | 123 | 0.734418 |
b2201b1ae891a9d30ebabcae63605a21f8134717 | 1,779 | package com.davidbracewell.apollo.ml.clustering.topic;
import com.davidbracewell.apollo.Optimum;
import com.davidbracewell.apollo.linear.NDArray;
import com.davidbracewell.apollo.ml.Instance;
import com.davidbracewell.apollo.ml.clustering.Clusterer;
import com.davidbracewell.apollo.ml.clustering.flat.FlatClustering;
import com.davidbracewell.apollo.stat.measure.Measure;
import com.davidbracewell.collection.counter.Counter;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
/**
* @author David B. Bracewell
*/
public abstract class TopicModel extends FlatClustering {
private static final long serialVersionUID = 1L;
@Getter
@Setter
protected int K;
public TopicModel(TopicModel other) {
super(other);
this.K = other.K;
}
public TopicModel(Clusterer<?> clusterer, Measure measure, int k) {
super(clusterer, measure);
K = k;
}
/**
* Gets the distribution across topics for a given feature.
*
* @param feature the feature (word) whose topic distribution is desired
* @return the distribution across topics for the given feature
*/
public abstract double[] getTopicDistribution(String feature);
/**
* Gets topic vector.
*
* @param topic the topic
* @return the topic vector
*/
public abstract NDArray getTopicVector(int topic);
/**
* Gets the words and their probabilities for a given topic
*
* @param topic the topic
* @return the topic words
*/
public abstract Counter<String> getTopicWords(int topic);
@Override
public int hardCluster(@NonNull Instance instance) {
return Optimum.MAXIMUM.optimumIndex(softCluster(instance));
}
@Override
public int size() {
return K;
}
}// END OF TopicModel
| 26.161765 | 75 | 0.711636 |
2a13ac34f71653d3d6683b51ac889a569d718850 | 1,485 | package de.shiirroo.islands.command.subcommands.islandscommands;
import de.shiirroo.islands.IslandsPlugin;
import de.shiirroo.islands.command.CommandBuilder;
import de.shiirroo.islands.command.SubCommand;
import org.bukkit.*;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
public class SpawnTeleporter extends SubCommand {
@Override
public String getName() {
return "SpawnTeleporter";
}
@Override
public String getDescription() {
return "Spawn Teleporter";
}
@Override
public String getSyntax() {
return "/"+ IslandsPlugin.getPlugin().getName() + " SpawnTeleporter";
}
@Override
public Boolean getNeedOp() {
return true;
}
@Override
public CommandBuilder getSubCommandsArgs(String[] arg, Player player) {
return null;
}
@Override
public void perform(Player player, String[] args) {
Villager villager = (Villager) player.getWorld().spawnEntity(player.getLocation(), EntityType.VILLAGER);
villager.setAdult();
villager.setAI(false);
villager.setAgeLock(true);
villager.setCanPickupItems(false);
villager.setInvulnerable(true);
villager.setCollidable(false);
villager.setCustomName(ChatColor.GOLD + "Teleport to "+ IslandsPlugin.getPlugin().getName() + " World");
villager.setCustomNameVisible(true);
villager.setSilent(true);
}
}
| 29.7 | 113 | 0.688215 |
6412105321c6bb65dd882f1747cf347cc2cd14fc | 5,388 | /*-
* #%L
* anchor-io-input
* %%
* Copyright (C) 2010 - 2021 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package org.anchoranalysis.io.input;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Optional;
import java.util.function.Function;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.experimental.Accessors;
import org.anchoranalysis.core.exception.OperationFailedException;
import org.anchoranalysis.core.functional.FunctionalList;
import org.anchoranalysis.core.functional.checked.CheckedFunction;
import org.anchoranalysis.io.input.file.NamedFile;
/**
* All inputs for an experiment, together with any parent directory which is specified as a parent
* for these inputs.
*
* <p>All inputs must be contained in this directory or one of its sub-direcotries.
*
* @author Owen Feehan
* @param <T> input-type
*/
@Value
@AllArgsConstructor
@Accessors(fluent = true)
public class InputsWithDirectory<T extends InputFromManager> {
/** The inputs. */
private List<T> inputs;
/** The directory associated with the inputs. */
private Optional<Path> directory;
/**
* Creates without any parent directory.
*
* @param inputs the inputs.
*/
public InputsWithDirectory(List<T> inputs) {
this(inputs, Optional.empty());
}
/**
* Creates a new {@link InputsWithDirectory} which is the result of mapping the existing inputs.
*
* <p>This is an <i>immutable</i> operation.
*
* @param <S> the type of inputs that are mapped to.
* @param mapFunction the function that transforms and existing input into a new input.
* @return a newly created input-manager with the mapped inputs, but an identical directory.
*/
public <S extends InputFromManager> InputsWithDirectory<S> map(Function<T, S> mapFunction) {
return new InputsWithDirectory<>(FunctionalList.mapToList(inputs, mapFunction), directory);
}
/**
* Creates a new {@link InputsWithDirectory} which is the result of mapping the existing inputs.
*
* <p>This is an <i>immutable</i> operation.
*
* @param <S> the type of inputs that are mapped to.
* @param <E> an exception that may be thrown by {@code mapFunction}.
* @param mapFunction the function that transforms and existing input into a new input.
* @return a newly created input-manager with the mapped inputs, but an identical directory.
* @throws E if thrown by {@code mapFunction}.
*/
public <S extends InputFromManager, E extends Exception> InputsWithDirectory<S> map(
CheckedFunction<T, S, E> mapFunction, Class<? extends E> throwableClass) throws E {
return new InputsWithDirectory<>(
FunctionalList.mapToList(inputs, throwableClass, mapFunction), directory);
}
/**
* Changes the inputs, but preserves the directory.
*
* <p>This is an <i>immutable</i> operation.
*
* @param inputsToAssign inputs to assign
* @param <S> type of inputs to assign
* @return a newly created input-manager with <code>inputsToAssign</code>, but an unchanged
* directory.
*/
public <S extends InputFromManager> InputsWithDirectory<S> withInputs(List<S> inputsToAssign) {
return new InputsWithDirectory<>(inputsToAssign, directory);
}
/**
* Find all files in the input directory are not used as inputs.
*
* @return the files, with an identifier derived relative to the input-directory
* @throws OperationFailedException if directory isn't defined
*/
public Collection<NamedFile> findAllNonInputFiles() throws OperationFailedException {
if (directory.isPresent()) {
return FindNonInputFiles.from(directory.get(), inputs);
} else {
throw new OperationFailedException(
"A directory is not defined, so this operation is not possible.");
}
}
public boolean isEmpty() {
return inputs.isEmpty();
}
public Iterator<T> iterator() {
return inputs.iterator();
}
public ListIterator<T> listIterator() {
return inputs.listIterator();
}
}
| 37.678322 | 100 | 0.70026 |
708fa46eb43d39ae5c41c50c236e2b94c364b8a5 | 131 | package lab6.organizaton;
public class Doctor extends OperationsStaff
{
public String[] specialty;
public String[] locations;
}
| 16.375 | 43 | 0.78626 |
acf6adf402bf5619c211bdbfc6d2818cf5569a2e | 319 | package com.sflpro.notifier.externalclients.push.firebase;
/**
* Created by Hayk Mkrtchyan.
* Date: 7/5/19
* Time: 3:43 PM
*/
final class MessageSendingFaildException extends RuntimeException {
MessageSendingFaildException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 22.785714 | 79 | 0.730408 |
abd141656a310fbb944258ab01978247a63f60fc | 8,601 | package com.young.mall.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.pagehelper.PageHelper;
import com.young.db.dao.YoungOrderGoodsMapper;
import com.young.db.dao.YoungOrderMapper;
import com.young.db.dao.YoungUserMapper;
import com.young.db.entity.*;
import com.young.mall.service.CommonOrderService;
import com.young.mall.common.ResBean;
import com.young.mall.domain.dto.MailDto;
import com.young.mall.domain.dto.RefundVo;
import com.young.mall.domain.dto.UserVo;
import com.young.mall.exception.Asserts;
import com.young.mall.notify.NotifyService;
import com.young.mall.service.GoodsProductService;
import com.young.mall.service.OrderService;
import com.young.mall.domain.enums.AdminResponseCode;
import com.young.mall.util.OrderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* @Description: 订单数量实现类
* @Author: yqz
* @CreateDate: 2020/10/29 15:53
*/
@Service
public class OrderServiceImpl implements OrderService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private YoungOrderMapper youngOrderMapper;
@Autowired
private YoungOrderGoodsMapper goodsMapper;
@Autowired
private YoungUserMapper userMapper;
@Autowired
private CommonOrderService commonOrderService;
@Autowired
private GoodsProductService goodsProductService;
@Autowired
private NotifyService notifyService;
@Override
public Optional<Integer> count(Integer userId) {
YoungOrderExample example = new YoungOrderExample();
example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
long count = youngOrderMapper.countByExample(example);
return Optional.ofNullable(((int) count));
}
@Override
public Optional<Integer> count() {
YoungOrderExample example = new YoungOrderExample();
example.createCriteria().andDeletedEqualTo(false);
long count = youngOrderMapper.countByExample(example);
return Optional.ofNullable(((int) count));
}
@Override
public Optional<List<YoungOrder>> list(Integer userId, String orderSn,
List<Short> orderStatusArray,
Integer page, Integer size,
String sort, String order) {
YoungOrderExample example = new YoungOrderExample();
YoungOrderExample.Criteria criteria = example.createCriteria();
if (userId != null) {
criteria.andUserIdEqualTo(userId);
}
if (StrUtil.isNotBlank(orderSn)) {
criteria.andOrderSnEqualTo(orderSn);
}
if (CollectionUtil.isNotEmpty(orderStatusArray)) {
criteria.andOrderStatusIn(orderStatusArray);
}
criteria.andDeletedEqualTo(false);
if (!StrUtil.isNotBlank(sort) && !StrUtil.isNotBlank(order)) {
example.setOrderByClause(sort + " " + order);
}
PageHelper.startPage(page, size);
List<YoungOrder> youngOrders = youngOrderMapper.selectByExample(example);
return Optional.ofNullable(youngOrders);
}
@Override
public Optional<Map<String, Object>> detail(Integer id) {
YoungOrder order = youngOrderMapper.selectByPrimaryKey(id);
List<YoungOrderGoods> goodsList = queryByOid(id);
YoungUser youngUser = userMapper.selectByPrimaryKey(id);
UserVo userVo = new UserVo();
BeanUtil.copyProperties(youngUser, userVo);
Map<String, Object> map = new HashMap<>(5);
map.put("order", order);
map.put("orderGoods", goodsList);
map.put("user", userVo);
return Optional.ofNullable(map);
}
private List<YoungOrderGoods> queryByOid(Integer id) {
YoungOrderGoodsExample example = new YoungOrderGoodsExample();
example.createCriteria().andOrderIdEqualTo(id).andDeletedEqualTo(false);
List<YoungOrderGoods> goodsList = goodsMapper.selectByExample(example);
return goodsList;
}
@Transactional
@Override
public ResBean refund(RefundVo refundVo) {
YoungOrder youngOrder = youngOrderMapper.selectByPrimaryKey(refundVo.getOrderId());
if (BeanUtil.isEmpty(youngOrder)) {
logger.error("退款查无此订单:{}", refundVo.getOrderId());
return ResBean.validateFailed("查无此订单");
}
if (youngOrder.getActualPrice().compareTo(new BigDecimal(refundVo.getRefundMoney())) != 0) {
logger.error("退款金额与订单金额不一致:{}", youngOrder.getActualPrice());
return ResBean.validateFailed("退款金额与订单金额不一致");
}
//判断订单状态
if (!youngOrder.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) {
logger.error("商场管理->订单管理->订单退款失败:{}", AdminResponseCode.ORDER_REFUND_FAILED.desc());
return ResBean.failed(AdminResponseCode.ORDER_REFUND_FAILED.code(), AdminResponseCode.ORDER_REFUND_FAILED.desc());
}
//微信退款
WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
wxPayRefundRequest.setOutTradeNo(youngOrder.getOrderSn());
wxPayRefundRequest.setOutRefundNo("refund_" + youngOrder.getOrderStatus());
//元 转 分
int totalFee = youngOrder.getActualPrice().multiply(new BigDecimal(100)).intValue();
wxPayRefundRequest.setTotalFee(totalFee);
wxPayRefundRequest.setRefundFee(totalFee);
//为了账号安全,暂时屏蔽api退款
/*WxPayRefundResult wxPayRefundResult = null;
try {
wxPayRefundResult = wxPayService.refund(wxPayRefundRequest);
} catch (WxPayException e) {
e.printStackTrace();
return ResBean.failed(AdminResponseCode.ORDER_REFUND_FAILED.code(), "订单退款失败");
}
if (!wxPayRefundResult.getReturnCode().equals("SUCCESS")) {
logger.warn("refund fail:" + wxPayRefundResult.getReturnMsg());
return ResBean.failed(AdminResponseCode.ORDER_REFUND_FAILED.code(), "订单退款失败");
}
if (!wxPayRefundResult.getResultCode().equals("SUCCESS")) {
logger.warn("refund fail:" + wxPayRefundResult.getReturnMsg());
return ResBean.failed(AdminResponseCode.ORDER_REFUND_FAILED.code(), "订单退款失败");
}*/
//设置订单取消状态
youngOrder.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM);
if (!commonOrderService.updateWithOptimisticLocker(youngOrder).isPresent()) {
logger.error("商场管理->订单管理->订单退款失败:{}", "更新数据已失效");
Asserts.fail("更新数据失败");
}
//商品货品数量增加
List<YoungOrderGoods> goodsList = queryByOid(refundVo.getOrderId());
for (YoungOrderGoods orderGoods : goodsList) {
Integer productId = orderGoods.getProductId();
Short number = orderGoods.getNumber();
Optional<Integer> optional = goodsProductService.addStock(productId, number);
if (!optional.isPresent()) {
logger.error("商场管理->订单管理->订单退款失败:{}", "商品货品库存增加失败");
Asserts.fail("商品库存增加失败");
}
}
// TODO 发送邮件和短信通知,这里采用异步发送
// 退款成功通知用户, 例如“您申请的订单退款 [ 单号:{1} ] 已成功,请耐心等待到账。”
// 注意订单号只发后6位
//由于个人用户只能申请aliyun的验证码短信功能,腾讯无法个人申请,所以这里使用aliyun的短信
/*String substring = youngOrder.getOrderSn().substring(8, 14);
Map<String, Object> map = new HashMap<>(2);
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",substring);
map.put("params", jsonObject);
notifyService.notifySmsTemplate(youngOrder.getMobile(),
NotifyType.REFUND, map);*/
//退款邮件通知
MailDto mailDto = MailDto.builder()
.title("退款通知")
.content(youngOrder.getConsignee() + "退款申请已通过" + "订单ID" + youngOrder.getOrderSn())
//临时将订单ID为20190619518874的Message字段添加邮箱,用于测试邮箱功能
.to(youngOrder.getMessage())
.build();
notifyService.notifySslMailWithTo(mailDto);
logger.error("订单管理,订单退款成功:{}", JSONUtil.toJsonStr(youngOrder));
return ResBean.success(youngOrder);
}
}
| 37.395652 | 126 | 0.67155 |
33dd8511cb72ff123a3cce1e23b22280a45fdff2 | 653 | package io.quarkus.it.artemis;
import java.util.Random;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;
import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;
public interface ArtemisHelper {
default String createBody() {
return Integer.toString(new Random().nextInt(Integer.MAX_VALUE), 16);
}
default Session createSession() throws JMSException {
Connection connection = new ActiveMQJMSConnectionFactory("tcp://localhost:61616").createConnection();
connection.start();
return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
}
| 28.391304 | 109 | 0.750383 |
dcddaacbc42ef3f166486cb4a66098295d7229ec | 6,786 | /**
* Copyright 2019 Association for the promotion of open-source insurance software and for the establishment of open interface standards in the insurance industry (Verein zur Förderung quelloffener Versicherungssoftware und Etablierung offener Schnittstellenstandards in der Versicherungsbranche)
*
* 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.aposin.licensescout.maven.utils;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.building.DefaultSettingsBuilderFactory;
import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuilder;
import org.apache.maven.settings.building.SettingsBuildingException;
import org.apache.maven.settings.building.SettingsBuildingResult;
import org.aposin.licensescout.configuration.ExecutionDatabaseConfiguration;
import org.aposin.licensescout.configuration.ExecutionOutput;
import org.aposin.licensescout.configuration.OutputFileType;
import org.aposin.licensescout.core.test.util.TestUtil;
import org.aposin.licensescout.util.ILSLog;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link ConfigurationHelper}.
*
*/
public class ConfigurationHelperTest {
/**
* Test case for the method {@link ConfigurationHelper#getExecutionDatabaseConfiguration(DatabaseConfiguration, Settings, ILSLog)}.
* @throws Exception
*/
@Test
public void testGetExecutionDatabaseConfigurationSuccess() throws Exception {
final Settings settings = createSettings();
final DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration("jdbcUrl", "serverId");
final ExecutionDatabaseConfiguration executionDatabaseConfiguration = ConfigurationHelper
.getExecutionDatabaseConfiguration(databaseConfiguration, settings, TestUtil.createTestLog());
Assert.assertEquals("jdbcUrl", "jdbcUrl", executionDatabaseConfiguration.getJdbcUrl());
Assert.assertEquals("username", "serverIdusername", executionDatabaseConfiguration.getUsername());
Assert.assertEquals("password", "serverIdpassword", executionDatabaseConfiguration.getPassword());
}
/**
* Test case for the method {@link ConfigurationHelper#getExecutionDatabaseConfiguration(DatabaseConfiguration, Settings, ILSLog)}.
* @throws Exception
*/
@Test
public void testGetExecutionDatabaseConfigurationNull() throws Exception {
final Settings settings = createSettings();
final DatabaseConfiguration databaseConfiguration = null;
final ExecutionDatabaseConfiguration executionDatabaseConfiguration = ConfigurationHelper
.getExecutionDatabaseConfiguration(databaseConfiguration, settings, TestUtil.createTestLog());
Assert.assertNull("result ExecutionDatabaseConfiguration", executionDatabaseConfiguration);
}
/**
* Test case for the method {@link ConfigurationHelper#getExecutionDatabaseConfiguration(DatabaseConfiguration, Settings, ILSLog)}.
* @throws Exception
*/
@Test(expected = MojoExecutionException.class)
public void testGetExecutionDatabaseConfigurationServerIdNotFound() throws Exception {
final Settings settings = createSettings();
final DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration("jdbcUrl", "serverId_noexisting");
ConfigurationHelper.getExecutionDatabaseConfiguration(databaseConfiguration, settings,
TestUtil.createTestLog());
}
/**
* Creates a settings instance for testing.
* @return a settings instance
* @throws SettingsBuildingException
*/
private Settings createSettings() throws SettingsBuildingException {
DefaultSettingsBuilderFactory settingsBuilderFactory = new DefaultSettingsBuilderFactory();
SettingsBuilder settingsBuilder = settingsBuilderFactory.newInstance();
DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
final File userSettingsFile = new File("src/test/resources/ConfigurationHelperTest/settings.xml");
request.setUserSettingsFile(userSettingsFile);
SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(request);
return settingsBuildingResult.getEffectiveSettings();
}
/**
* Test case for the method {@link ConfigurationHelper#getExecutionOutputs(List, String, LSArtifact)}.
*
*/
@Test
public void testGetExecutionOutputsCustomUrl() {
final Output output = new Output(OutputFileType.CSV, "filename", "url", new File("template"), "templatEncoding",
"outputEncoding");
final String expectedUrl = "url";
assertGetExecutionOutputs(output, expectedUrl);
}
/**
* Test case for the method {@link ConfigurationHelper#getExecutionOutputs(List, String, LSArtifact)}.
*
*/
@Test
public void testGetExecutionOutputsDefaultUrl() {
final Output output = new Output(OutputFileType.CSV, "filename", null, new File("template"), "templatEncoding",
"outputEncoding");
final String expectedUrl = "http://server/repo/group/id/artifactId/version/artifactId-version.csv";
assertGetExecutionOutputs(output, expectedUrl);
}
/**
* @param output
* @param expectedUrl
*/
private void assertGetExecutionOutputs(final Output output, final String expectedUrl) {
final List<Output> outputs = Arrays.asList(output);
final String artifactBaseUrl = "http://server/repo/";
final LSArtifact artifact = new LSArtifact("group.id", "artifactId", "version", "");
final List<ExecutionOutput> executionOutputs = ConfigurationHelper.getExecutionOutputs(outputs, artifactBaseUrl,
artifact);
Assert.assertEquals("resulting output count", 1, executionOutputs.size());
final ExecutionOutput executionOutput = executionOutputs.get(0);
Assert.assertEquals("outputFileType", OutputFileType.CSV, executionOutput.getType());
Assert.assertEquals("url", expectedUrl, executionOutput.getUrl());
}
}
| 49.173913 | 295 | 0.749926 |
44dc603b2a5b4b8b7a144eea3bfcb0b1a2425264 | 4,929 | /*
* MIT License
*
* Copyright (c) 2020 TerraForged
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.terraforged.mod.biome.provider;
import com.electronwill.nightconfig.core.CommentedConfig;
import com.terraforged.mod.Log;
import com.terraforged.mod.biome.context.TFBiomeContext;
import com.terraforged.mod.biome.provider.analyser.BiomeAnalyser;
import com.terraforged.mod.config.ConfigManager;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.common.BiomeManager;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.IntUnaryOperator;
public class BiomeWeights implements IntUnaryOperator {
private final int standardWeight;
private final int forestWeight;
private final int rareWeight;
private final TFBiomeContext context;
private final Object2IntMap<String> biomes = new Object2IntOpenHashMap<>();
public BiomeWeights(TFBiomeContext context) {
this(10, 5, 2, context);
}
public BiomeWeights(int standard, int forest, int rare, TFBiomeContext context) {
this.standardWeight = standard;
this.forestWeight = forest;
this.rareWeight = rare;
this.context = context;
Set<String> validBiomes = BiomeAnalyser.getOverworldBiomesSet(context, context.biomes::getName);
// Get biome weights from Forge
for (BiomeManager.BiomeType type : BiomeManager.BiomeType.values()) {
List<BiomeManager.BiomeEntry> entries = BiomeManager.getBiomes(type);
if (entries == null) {
continue;
}
for (BiomeManager.BiomeEntry entry : entries) {
Biome biome = context.biomes.get(entry.getKey());
String name = context.biomes.getName(biome);
if (validBiomes.contains(name)) {
biomes.put(name.toString(), entry.itemWeight);
}
}
}
// TF config gets final say
readWeights(validBiomes);
}
@Override
public int applyAsInt(int biome) {
return getWeight(biome);
}
public int getWeight(int biome) {
String name = context.getName(biome);
Integer value = biomes.get(name);
if (value != null) {
return value;
}
if (BiomeDictionary.getTypes(context.getValue(biome)).contains(BiomeDictionary.Type.RARE)) {
return rareWeight;
}
if (context.biomes.get(biome).getCategory() == Biome.Category.FOREST) {
return forestWeight;
}
return standardWeight;
}
public void forEachEntry(BiConsumer<String, Integer> consumer) {
biomes.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> consumer.accept(e.getKey(), e.getValue()));
}
public void forEachUnregistered(BiConsumer<String, Integer> consumer) {
for (Biome biome : context.biomes) {
int id = context.biomes.getId(biome);
String name = context.getName(id);
if (!biomes.containsKey(name)) {
int weight = getWeight(id);
consumer.accept(name, weight);
}
}
}
private void readWeights(Set<String> validBiomes) {
CommentedConfig config = ConfigManager.BIOME_WEIGHTS.get();
for (String key : config.valueMap().keySet()) {
if (!validBiomes.contains(key)) {
continue;
}
int weight = Math.max(0, config.getInt(key));
biomes.put(key, weight);
Log.debug("Loaded custom biome weight: {}={}", key, weight);
}
}
}
| 36.242647 | 104 | 0.663421 |
2ff183443cf10fdaf60e16767a2d2800d541938a | 1,781 | import com.launchdarkly.sdk.LDUser;
import com.launchdarkly.sdk.LDValue;
import com.launchdarkly.sdk.server.LDClient;
import java.io.IOException;
public class Hello {
// Set SDK_KEY to your LaunchDarkly SDK key before compiling
static final String SDK_KEY = "sdk-dd6dc077-97f0-4aa5-a366-81855423818e";
// Set FEATURE_FLAG_KEY to the feature flag key you want to evaluate
static final String FEATURE_FLAG_KEY = "example-flag";
public static void main(String... args) throws IOException {
if (SDK_KEY.equals("")) {
System.out.println("Please edit Hello.java to set SDK_KEY to your LaunchDarkly SDK key first");
System.exit(1);
}
// Set up the user properties. This user should appear on your LaunchDarkly users dashboard
// soon after you run the demo.
LDUser user = new LDUser.Builder("[email protected]")
.firstName("Bob")
.lastName("Loblaw")
.custom("groups", LDValue.buildArray().add("beta_testers").build())
.build();
LDClient client = new LDClient(SDK_KEY);
boolean showFeature = client.boolVariation("example-flag", user, false);
System.out.println("Feature flag '" + FEATURE_FLAG_KEY + "' is " + showFeature + " for this user");
// Calling client.close() ensures that the SDK shuts down cleanly before the program exits.
// Unless you do this, the SDK may not have a chance to deliver analytics events to LaunchDarkly,
// so the user properties and the flag usage statistics may not appear on your dashboard. In a
// normal long-running application, events would be delivered automatically in the background
// and you would not need to close the client.
client.close();
}
}
| 41.418605 | 103 | 0.679394 |
1e37a424ccd1de4e3a41cfddcf1fc4619c75666e | 13,359 | /*
* 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.ignite.internal.raft;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.ignite.internal.manager.IgniteComponent;
import org.apache.ignite.internal.raft.server.RaftServer;
import org.apache.ignite.internal.raft.server.impl.JraftServerImpl;
import org.apache.ignite.internal.thread.NamedThreadFactory;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.lang.IgniteInternalException;
import org.apache.ignite.lang.IgniteStringFormatter;
import org.apache.ignite.lang.NodeStoppingException;
import org.apache.ignite.network.ClusterNode;
import org.apache.ignite.network.ClusterService;
import org.apache.ignite.raft.client.Peer;
import org.apache.ignite.raft.client.service.RaftGroupListener;
import org.apache.ignite.raft.client.service.RaftGroupService;
import org.apache.ignite.raft.jraft.RaftMessagesFactory;
import org.apache.ignite.raft.jraft.rpc.impl.RaftGroupServiceImpl;
import org.apache.ignite.raft.jraft.util.Utils;
import org.jetbrains.annotations.ApiStatus.Experimental;
import org.jetbrains.annotations.TestOnly;
/**
* Best raft manager ever since 1982.
*/
public class Loza implements IgniteComponent {
/** Factory. */
private static final RaftMessagesFactory FACTORY = new RaftMessagesFactory();
/** Raft client pool name. */
public static final String CLIENT_POOL_NAME = "Raft-Group-Client";
/** Raft client pool size. Size was taken from jraft's TimeManager. */
private static final int CLIENT_POOL_SIZE = Math.min(Utils.cpus() * 3, 20);
/** Timeout. */
private static final int RETRY_TIMEOUT = 10000;
/** Network timeout. */
private static final int RPC_TIMEOUT = 3000;
/** Retry delay. */
private static final int DELAY = 200;
/** Cluster network service. */
private final ClusterService clusterNetSvc;
/** Raft server. */
private final RaftServer raftServer;
/** Executor for raft group services. */
private final ScheduledExecutorService executor;
/** Busy lock to stop synchronously. */
private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
/** Prevents double stopping the component. */
private final AtomicBoolean stopGuard = new AtomicBoolean();
/**
* The constructor.
*
* @param clusterNetSvc Cluster network service.
* @param dataPath Data path.
*/
public Loza(ClusterService clusterNetSvc, Path dataPath) {
this.clusterNetSvc = clusterNetSvc;
this.raftServer = new JraftServerImpl(clusterNetSvc, dataPath);
this.executor = new ScheduledThreadPoolExecutor(CLIENT_POOL_SIZE,
new NamedThreadFactory(NamedThreadFactory.threadPrefix(clusterNetSvc.localConfiguration().getName(),
CLIENT_POOL_NAME)
)
);
}
/**
* The constructor. Used for testing purposes.
*
* @param srv Pre-started raft server.
*/
@TestOnly
public Loza(JraftServerImpl srv) {
this.clusterNetSvc = srv.clusterService();
this.raftServer = srv;
this.executor = new ScheduledThreadPoolExecutor(CLIENT_POOL_SIZE,
new NamedThreadFactory(NamedThreadFactory.threadPrefix(clusterNetSvc.localConfiguration().getName(),
CLIENT_POOL_NAME)
)
);
}
/** {@inheritDoc} */
@Override
public void start() {
raftServer.start();
}
/** {@inheritDoc} */
@Override
public void stop() throws Exception {
if (!stopGuard.compareAndSet(false, true)) {
return;
}
busyLock.block();
IgniteUtils.shutdownAndAwaitTermination(executor, 10, TimeUnit.SECONDS);
raftServer.stop();
}
/**
* Creates a raft group service providing operations on a raft group. If {@code nodes} contains the current node, then raft group starts
* on the current node.
*
* <p>IMPORTANT: DON'T USE. This method should be used only for long running changePeers requests - until IGNITE-14209 will be fixed
* with stable solution.
*
* @param groupId Raft group id.
* @param nodes Raft group nodes.
* @param lsnrSupplier Raft group listener supplier.
* @return Future representing pending completion of the operation.
* @throws NodeStoppingException If node stopping intention was detected.
*/
@Experimental
public CompletableFuture<RaftGroupService> prepareRaftGroup(
String groupId,
List<ClusterNode> nodes,
Supplier<RaftGroupListener> lsnrSupplier
) throws NodeStoppingException {
if (!busyLock.enterBusy()) {
throw new NodeStoppingException();
}
try {
return prepareRaftGroupInternal(groupId, nodes, lsnrSupplier);
} finally {
busyLock.leaveBusy();
}
}
/**
* Internal method to a raft group creation.
*
* @param groupId Raft group id.
* @param nodes Raft group nodes.
* @param lsnrSupplier Raft group listener supplier.
* @return Future representing pending completion of the operation.
*/
private CompletableFuture<RaftGroupService> prepareRaftGroupInternal(String groupId, List<ClusterNode> nodes,
Supplier<RaftGroupListener> lsnrSupplier) {
assert !nodes.isEmpty();
List<Peer> peers = nodes.stream().map(n -> new Peer(n.address())).collect(Collectors.toList());
String locNodeName = clusterNetSvc.topologyService().localMember().name();
boolean hasLocalRaft = nodes.stream().anyMatch(n -> locNodeName.equals(n.name()));
if (hasLocalRaft) {
if (!raftServer.startRaftGroup(groupId, lsnrSupplier.get(), peers)) {
throw new IgniteInternalException(IgniteStringFormatter.format(
"Raft group on the node is already started [node={}, raftGrp={}]",
locNodeName,
groupId
));
}
}
return RaftGroupServiceImpl.start(
groupId,
clusterNetSvc,
FACTORY,
RETRY_TIMEOUT,
RPC_TIMEOUT,
peers,
true,
DELAY,
executor
);
}
/**
* Creates a raft group service providing operations on a raft group. If {@code deltaNodes} contains the current node, then raft group
* starts on the current node.
*
* @param groupId Raft group id.
* @param nodes Full set of raft group nodes.
* @param deltaNodes New raft group nodes.
* @param lsnrSupplier Raft group listener supplier.
* @return Future representing pending completion of the operation.
* @throws NodeStoppingException If node stopping intention was detected.
*/
@Experimental
public CompletableFuture<RaftGroupService> updateRaftGroup(
String groupId,
Collection<ClusterNode> nodes,
Collection<ClusterNode> deltaNodes,
Supplier<RaftGroupListener> lsnrSupplier
) throws NodeStoppingException {
if (!busyLock.enterBusy()) {
throw new NodeStoppingException();
}
try {
return updateRaftGroupInternal(groupId, nodes, deltaNodes, lsnrSupplier);
} finally {
busyLock.leaveBusy();
}
}
/**
* Internal method for updating a raft group.
*
* @param groupId Raft group id.
* @param nodes Full set of raft group nodes.
* @param deltaNodes New raft group nodes.
* @param lsnrSupplier Raft group listener supplier.
* @return Future representing pending completion of the operation.
*/
private CompletableFuture<RaftGroupService> updateRaftGroupInternal(String groupId, Collection<ClusterNode> nodes,
Collection<ClusterNode> deltaNodes, Supplier<RaftGroupListener> lsnrSupplier) {
assert !nodes.isEmpty();
List<Peer> peers = nodes.stream().map(n -> new Peer(n.address())).collect(Collectors.toList());
String locNodeName = clusterNetSvc.topologyService().localMember().name();
if (deltaNodes.stream().anyMatch(n -> locNodeName.equals(n.name()))) {
if (!raftServer.startRaftGroup(groupId, lsnrSupplier.get(), peers)) {
throw new IgniteInternalException(IgniteStringFormatter.format(
"Raft group on the node is already started [node={}, raftGrp={}]",
locNodeName,
groupId
));
}
}
return RaftGroupServiceImpl.start(
groupId,
clusterNetSvc,
FACTORY,
RETRY_TIMEOUT,
RPC_TIMEOUT,
peers,
true,
DELAY,
executor
);
}
/**
* Changes peers for a group from {@code expectedNodes} to {@code changedNodes}.
*
* @param groupId Raft group id.
* @param expectedNodes List of nodes that contains the raft group peers.
* @param changedNodes List of nodes that will contain the raft group peers after.
* @return Future which will complete when peers change.
* @throws NodeStoppingException If node stopping intention was detected.
*/
public CompletableFuture<Void> changePeers(
String groupId,
List<ClusterNode> expectedNodes,
List<ClusterNode> changedNodes
) throws NodeStoppingException {
if (!busyLock.enterBusy()) {
throw new NodeStoppingException();
}
try {
return changePeersInternal(groupId, expectedNodes, changedNodes);
} finally {
busyLock.leaveBusy();
}
}
/**
* Internal method for changing peers for a RAFT group.
*
* @param groupId Raft group id.
* @param expectedNodes List of nodes that contains the raft group peers.
* @param changedNodes List of nodes that will contain the raft group peers after.
* @return Future which will complete when peers change.
*/
private CompletableFuture<Void> changePeersInternal(String groupId, List<ClusterNode> expectedNodes, List<ClusterNode> changedNodes) {
List<Peer> expectedPeers = expectedNodes.stream().map(n -> new Peer(n.address())).collect(Collectors.toList());
List<Peer> changedPeers = changedNodes.stream().map(n -> new Peer(n.address())).collect(Collectors.toList());
return RaftGroupServiceImpl.start(
groupId,
clusterNetSvc,
FACTORY,
10 * RETRY_TIMEOUT,
10 * RPC_TIMEOUT,
expectedPeers,
true,
DELAY,
executor
).thenCompose(srvc -> srvc.changePeers(changedPeers)
.thenRun(() -> srvc.shutdown()));
}
/**
* Stops a raft group on the current node.
*
* @param groupId Raft group id.
* @throws NodeStoppingException If node stopping intention was detected.
*/
public void stopRaftGroup(String groupId) throws NodeStoppingException {
if (!busyLock.enterBusy()) {
throw new NodeStoppingException();
}
try {
raftServer.stopRaftGroup(groupId);
} finally {
busyLock.leaveBusy();
}
}
/**
* Returns a cluster service.
*
* @return An underlying network service.
*/
@TestOnly
public ClusterService service() {
return clusterNetSvc;
}
/**
* Returns a raft server.
*
* @return An underlying raft server.
*/
@TestOnly
public RaftServer server() {
return raftServer;
}
/**
* Returns started groups.
*
* @return Started groups.
*/
@TestOnly
public Set<String> startedGroups() {
return raftServer.startedGroups();
}
}
| 34.879896 | 140 | 0.642189 |
8c24a950b62adc4a8915bc83dc6693f8ceefefec | 3,791 | /**
* Copyright 2012-2020 Solace Corporation. All rights reserved.
*
* http://www.solace.com
*
* This source is distributed under the terms and conditions
* of any contract or contracts between Solace and you or
* your company. If there are no contracts in place use of
* this source is not authorized. No support is provided and
* no distribution, sharing with others or re-use of this
* source is authorized unless specifically stated in the
* contracts referred to above.
*
* SolJMSHelloWorldQueuePub
*
* This sample shows the basics of creating session, connecting a session,
* looking up a queue, and publishing a guaranteed message to the queue.
* This is meant to be a very basic example for demonstration purposes.
*/
package com.solacesystems.jms.samples.intro;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.solacesystems.jms.SupportedProperty;
public class SolJMSHelloWorldQueuePub {
public static void main(String... args) throws JMSException, NamingException {
// Check command line arguments
if (args.length < 5) {
System.out.println("Usage: SolJMSHelloWorldPub <jndi-provider-url> <vpn> <client-username> <connection-factory> <jndi-queue>");
System.out.println();
System.out.println(" Note: the client-username provided must have adequate permissions in its client");
System.out.println(" profile to send and receive guaranteed messages, and to create endpoints.");
System.out.println(" Also, the message-spool for the VPN must be configured with >0 capacity.");
System.exit(-1);
}
System.out.println("SolJMSHelloWorldQueuePub initializing...");
// The client needs to specify all of the following properties:
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.solacesystems.jndi.SolJNDIInitialContextFactory");
env.put(InitialContext.PROVIDER_URL, (String)args[0]);
env.put(SupportedProperty.SOLACE_JMS_VPN, (String)args[1]);
env.put(Context.SECURITY_PRINCIPAL, (String)args[2]);
// InitialContext is used to lookup the JMS administered objects.
InitialContext initialContext = new InitialContext(env);
// Lookup ConnectionFactory.
QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup((String)args[3]);
// JMS Connection
QueueConnection connection = cf.createQueueConnection();
// Create a non-transacted, Auto Ack session.
Session session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
// Lookup Queue.
Queue queue = (Queue)initialContext.lookup((String)args[4]);
// From the session, create a producer for the destination.
// Use the default delivery mode as set in the connection factory
MessageProducer producer = session.createProducer(queue);
// Create a text message.
TextMessage testMessage = session.createTextMessage("Hello world!");
System.out.printf("Connected. About to send message '%s' to queue '%s'...%n", testMessage.getText(), queue.toString());
producer.send(testMessage);
System.out.println("Message sent. Exiting.");
connection.close();
initialContext.close();
}
}
| 42.595506 | 140 | 0.691902 |
94f7e897421b238a58da7e38bbc7fc63733eae96 | 634 | /*
* Copyright (c) 2019 Gili Tzabari
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
package org.bitbucket.cowwoc.requirements.java.internal.secrets;
import org.bitbucket.cowwoc.requirements.java.JavaRequirements;
import org.bitbucket.cowwoc.requirements.java.internal.scope.ApplicationScope;
/**
* @see JavaSecrets
*/
public interface SecretRequirements
{
/**
* Creates a new {@code JavaRequirements}.
*
* @param scope the application configuration
* @return a new {@code JavaRequirements}
*/
JavaRequirements create(ApplicationScope scope);
}
| 27.565217 | 94 | 0.733438 |
c157e837007fad5a14e0e165a5917367b3f5c375 | 795 | package container;
/**
* An interface of table that provides ordering the keys in ascending order.
*
*/
public interface SortedTable <K extends Comparable<K>, V> extends Table<K, V> {
/**
* Get the minimal key in the table.
* @return The minimal key in the table.
*/
abstract public K minKey();
/**
* Get the maximal key in the table.
* @return The maximal key in the table.
*/
abstract public K maxKey();
/**
* Return the rank of the key.
* @param key The specific key.
* @return Number of keys less than the specific key.
*/
abstract public int rank(K key);
/**
* Retrive the ith key in the table.
* @param i rank i.
* @return key of rank i.
*/
abstract public K select(int i);
} | 20.921053 | 79 | 0.597484 |
a2c9a6e3190fd9b093b0d909156bbc11549587e8 | 451 | package com.github.elic0de.spigotcommandlib.invocation;
public class CommandInvocationException extends Exception {
public CommandInvocationException() {
}
public CommandInvocationException(String message) {
super(message);
}
public CommandInvocationException(String message, Throwable cause) {
super(message, cause);
}
public CommandInvocationException(Throwable cause) {
super(cause);
}
}
| 23.736842 | 72 | 0.716186 |
ca7effb4bbd78d7a11e8133fe72cf2533b9c729c | 8,531 | package com.example.bluetooth.le;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;
import com.xtremeprog.sdk.ble.BleGattCharacteristic;
import com.xtremeprog.sdk.ble.BleService;
import com.xtremeprog.sdk.ble.IBle;
public class WeightActivity extends Activity implements View.OnClickListener {
private int index = 0;
private String mDeviceAddress;
private IBle mBle;
private BleGattCharacteristic mCharacteristicWgt;
private TextView txtWgt;
private Button btnSave;
private ListView listData;
private MyAdapter adapter;
private Timer pTimer;
protected static final String TAG = "weight";
private final class ReadWgtTimer extends TimerTask {
public void run() {
if(mBle.hasConnected(mDeviceAddress))
{
mBle.requestReadCharacteristic(mDeviceAddress, mCharacteristicWgt);
}
else
{
mBle.requestConnect(mDeviceAddress);
}
}
}
private class WeightData {
public String sid;
public String stime;
public String skg;
public WeightData(int id, String kg) {
sid = String.valueOf(id);
long time = System.currentTimeMillis();
stime = getCurrentTime(time);
skg = kg + "kg";
}
};
public static String getCurrentTime(long date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = format.format(new Date(date));
return str;
}
private final BroadcastReceiver mBleReceiver = new BroadcastReceiver() {
private int weight;
private boolean mNotifyStarted;
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (!mDeviceAddress.equals(extras.getString(BleService.EXTRA_ADDR))) {
return;
}
String uuid = extras.getString(BleService.EXTRA_UUID);
if (uuid != null
&& !mCharacteristicWgt.getUuid().toString().equals(uuid)) {
return;
}
String action = intent.getAction();
Log.e(TAG, action);
if (BleService.BLE_GATT_DISCONNECTED.equals(action)) {
Toast.makeText(WeightActivity.this, "Device disconnected...",
Toast.LENGTH_SHORT).show();
finish();
} else if (BleService.BLE_CHARACTERISTIC_READ.equals(action)
|| BleService.BLE_CHARACTERISTIC_CHANGED.equals(action)) {
byte[] val = extras.getByteArray(BleService.EXTRA_VALUE);
weight = Utils.bytesToInt(val);
runOnUiThread(new Runnable() {
@Override
public void run() {
txtWgt.setText(String.valueOf(weight));
}
});
} else if (BleService.BLE_CHARACTERISTIC_NOTIFICATION
.equals(action)) {
Toast.makeText(WeightActivity.this,
"Notification state changed!", Toast.LENGTH_SHORT)
.show();
mNotifyStarted = extras.getBoolean(BleService.EXTRA_VALUE);
if (mNotifyStarted) {
} else {
}
} else if (BleService.BLE_CHARACTERISTIC_INDICATION.equals(action)) {
Toast.makeText(WeightActivity.this,
"Indication state changed!", Toast.LENGTH_SHORT).show();
} else if (BleService.BLE_CHARACTERISTIC_WRITE.equals(action)) {
Toast.makeText(WeightActivity.this, "Write success!",
Toast.LENGTH_SHORT).show();
} else if (BleService.BLE_GATT_CONNECTED.equals(action)) {
Config.getInstance(WeightActivity.this).setDevAddress(mDeviceAddress);
Toast.makeText(
WeightActivity.this,
"Connect ok!" + extras.getString(BleService.EXTRA_ADDR),
Toast.LENGTH_SHORT).show();
} else if (BleService.BLE_GATT_DISCONNECTED.equals(action)) {
Toast.makeText(
WeightActivity.this,
"Disconnect!" + extras.getString(BleService.EXTRA_ADDR),
Toast.LENGTH_SHORT).show();
finish();
} else if (BleService.BLE_SERVICE_DISCOVERED.equals(action)) {
Toast.makeText(
WeightActivity.this,
"service discovery!"
+ extras.getString(BleService.EXTRA_ADDR),
Toast.LENGTH_SHORT).show();
} else if (BleService.BLE_REQUEST_FAILED.equals(action)) {
Toast.makeText(
WeightActivity.this,
"request failed"
+ extras.getString(BleService.EXTRA_ADDR),
Toast.LENGTH_SHORT).show();
finish();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight);
initResource();
btnSave.setOnClickListener(this);
mDeviceAddress = getIntent().getStringExtra("address");
BleApplication app = (BleApplication) getApplication();
mBle = app.getIBle();
if (mBle != null) {
}
mCharacteristicWgt = mBle.getService(mDeviceAddress,
UUID.fromString(Utils.UUID_SRV)).getCharacteristic(
UUID.fromString(Utils.UUID_WGT));
if (mCharacteristicWgt == null) {
return;
}
pTimer = new Timer();
pTimer.schedule(new ReadWgtTimer(), 0, 1000);
// mNotifyStarted = true;
// mBle.requestCharacteristicNotification(mDeviceAddress,
// mCharacteristic);
}
private void initResource() {
// TODO Auto-generated method stub
txtWgt = (TextView) findViewById(R.id.txtWgt);
listData = (ListView) findViewById(R.id.list);
adapter = new MyAdapter(this);
listData.setAdapter(adapter);
btnSave = (Button) findViewById(R.id.btn_save);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.weight, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.device_settings) {
Intent intent = new Intent(WeightActivity.this, CalibActivity.class);
intent.putExtra("address", mDeviceAddress);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mBleReceiver, BleService.getIntentFilter());
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e(TAG, "onStop");
unregisterReceiver(mBleReceiver);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pTimer.cancel();
mBle.disconnect(mDeviceAddress);
Log.e(TAG, "OnDestory");
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ArrayList<WeightData> arr;
public MyAdapter(Context context) {
super();
inflater = LayoutInflater.from(context);
arr = new ArrayList<WeightData>();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(final int position, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
if (view == null) {
view = inflater.inflate(R.layout.listview_item, null);
}
final TextView edit = (TextView) view.findViewById(R.id.index);
edit.setText(arr.get(position).sid);
final TextView time = (TextView) view.findViewById(R.id.time);
time.setText(arr.get(position).stime);
final TextView kg = (TextView) view.findViewById(R.id.kg);
kg.setText(arr.get(position).skg);
return view;
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_save:
saveWeight();
break;
default:
break;
}
}
private void saveWeight() {
// TODO Auto-generated method stub
String kgs = txtWgt.getText().toString();
WeightData data = new WeightData(index++, kgs);
adapter.arr.add(data);
adapter.notifyDataSetChanged();
}
}
| 25.773414 | 78 | 0.716446 |
e30b4faa04b70fbbc602a407b1ae302c69ba333f | 1,300 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.jube.model;
import java.io.IOException;
/**
* Represents an in memory representation of entities which is kept in sync
* via watching ZK
*/
public interface EntityModel<T> {
/**
* Returns the String ID for the entity
*/
String getId(T entity);
/**
* Invoked when the entity is deleted
*/
T deleteEntity(String id);
/**
* Invoked when the entity has been updated in ZK
*
* @return the newly marshalled data
*/
T updateEntity(String id, byte[] data) throws IOException;
String marshal(T entity) throws IOException;
T unmarshal(byte[] data) throws IOException;
}
| 27.659574 | 75 | 0.686154 |
5912336073877aec6c103edce3b6a9a96fbc7998 | 369 | package com.shangguan.product.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.shangguan.product.entity.ProductCategory;
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer>{
List<ProductCategory> findByCategoryTypeIn(List<Integer> CategoryTypeList);
}
| 28.384615 | 92 | 0.818428 |
9e61cea4b1d8fffbff526cb18786b317428ceec1 | 441 | package com.atlassian.clover.recorder;
/**
* Helper class which keeps result of the per-test recording.
*/
public final class RecordingResult {
public final LivePerTestRecording recording;
public final ActivePerTestRecorderAny recorders;
public RecordingResult(LivePerTestRecording recording, ActivePerTestRecorderAny recorders) {
this.recording = recording;
this.recorders = recorders;
}
}
| 29.4 | 97 | 0.732426 |
ef1554a521897fc5fcbf2ea7b9f97ea11dc921fc | 6,155 | package org.elastos.hive;
import org.elastos.hive.exception.HiveException;
import org.elastos.hive.network.response.VaultInfoResponseBody;
import org.elastos.hive.payment.Order;
import org.elastos.hive.payment.PricingPlan;
import org.elastos.hive.payment.Receipt;
import org.elastos.hive.service.PaymentService;
import org.elastos.hive.service.SubscriptionService;
import org.elastos.hive.vault.HttpExceptionHandler;
import org.elastos.hive.vault.PaymentServiceRender;
import org.elastos.hive.vault.SubscriptionServiceRender;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class BackupSubscription extends ServiceEndpoint implements SubscriptionService<BackupSubscription.BackupInfo>, PaymentService, HttpExceptionHandler {
private SubscriptionServiceRender subscriptionService;
private PaymentServiceRender paymentService;
public BackupSubscription(AppContext context, String providerAddress) throws HiveException {
super(context, providerAddress);
this.paymentService = new PaymentServiceRender(this);
this.subscriptionService = new SubscriptionServiceRender(this);
}
@Override
public CompletableFuture<BackupInfo> subscribe(String pricingPlan) {
return CompletableFuture.runAsync(() -> {
try {
this.subscriptionService.subscribeBackup();
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
}).thenApplyAsync(result -> {
try {
return getBackupInfoByResponseBody(this.subscriptionService.getBackupVaultInfo());
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
private BackupInfo getBackupInfoByResponseBody(VaultInfoResponseBody body) {
return new BackupInfo().setDid(body.getDid())
.setMaxStorage(body.getMaxStorage())
.setFileUseStorage(body.getFileUseStorage())
.setDbUseStorage(body.getDbUseStorage())
.setModifyTime(body.getModifyTimeStr())
.setStartTime(body.getStartTimeStr())
.setEndTime(body.getEndTimeStr())
.setPricingUsing(body.getPricingUsing())
.setIsExisting(body.isExisting());
}
@Override
public CompletableFuture<Void> unsubscribe() {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<Void> activate() {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<Void> deactivate() {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<BackupInfo> checkSubscription() {
return CompletableFuture.supplyAsync(()-> {
try {
return getBackupInfoByResponseBody(this.subscriptionService.getBackupVaultInfo());
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
public class BackupInfo {
private String did;
private long maxStorage;
private long fileUseStorage;
private long dbUseStorage;
private String modifyTime;
private String startTime;
private String endTime;
private String pricingUsing;
private boolean isExisting;
public String getDid() {
return did;
}
public BackupInfo setDid(String did) {
this.did = did;
return this;
}
public long getMaxStorage() {
return maxStorage;
}
public BackupInfo setMaxStorage(long maxStorage) {
this.maxStorage = maxStorage;
return this;
}
public long getFileUseStorage() {
return fileUseStorage;
}
public BackupInfo setFileUseStorage(long fileUseStorage) {
this.fileUseStorage = fileUseStorage;
return this;
}
public long getDbUseStorage() {
return dbUseStorage;
}
public BackupInfo setDbUseStorage(long dbUseStorage) {
this.dbUseStorage = dbUseStorage;
return this;
}
public String getModifyTime() {
return modifyTime;
}
public BackupInfo setModifyTime(String modifyTime) {
this.modifyTime = modifyTime;
return this;
}
public String getStartTime() {
return startTime;
}
public BackupInfo setStartTime(String startTime) {
this.startTime = startTime;
return this;
}
public String getEndTime() {
return endTime;
}
public BackupInfo setEndTime(String endTime) {
this.endTime = endTime;
return this;
}
public String getPricingUsing() {
return pricingUsing;
}
public BackupInfo setPricingUsing(String pricingUsing) {
this.pricingUsing = pricingUsing;
return this;
}
public boolean getIsExisting() {
return isExisting;
}
public BackupInfo setIsExisting(boolean isExisting) {
this.isExisting = isExisting;
return this;
}
}
@Override
public CompletableFuture<List<PricingPlan>> getPricingPlanList() {
return CompletableFuture.supplyAsync(()-> {
try {
return paymentService.getBackupPlanList();
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
@Override
public CompletableFuture<PricingPlan> getPricingPlan(String planName) {
return CompletableFuture.supplyAsync(()-> {
try {
return paymentService.getBackupPlan(planName);
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
@Override
public CompletableFuture<Order> placeOrder(String planName) {
return CompletableFuture.supplyAsync(()-> {
try {
return paymentService.getOrderInfo(paymentService.createBackupOrder(planName));
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
@Override
public CompletableFuture<Order> getOrder(String orderId) {
return CompletableFuture.supplyAsync(()-> {
try {
return paymentService.getOrderInfo(orderId);
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
@Override
public CompletableFuture<Receipt> payOrder(String orderId, List<String> transIds) {
return CompletableFuture.supplyAsync(()-> {
try {
paymentService.payOrder(orderId, transIds);
//TODO:
return null;
} catch (Exception e) {
throw new CompletionException(convertException(e));
}
});
}
@Override
public CompletableFuture<Receipt> getReceipt(String receiptId) {
throw new UnsupportedOperationException();
}
}
| 25.753138 | 157 | 0.747035 |
e21a8d11c23f644772c7e5e8b3b4f4af834d526c | 10,637 | package us.myles.ViaVersion.protocols.protocol1_16to1_15_2.packets;
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.github.steveice10.opennbt.tag.builtin.IntArrayTag;
import com.github.steveice10.opennbt.tag.builtin.StringTag;
import com.github.steveice10.opennbt.tag.builtin.Tag;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.rewriters.ItemRewriter;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.api.type.types.UUIDIntArrayType;
import us.myles.ViaVersion.protocols.protocol1_15to1_14_4.ClientboundPackets1_15;
import us.myles.ViaVersion.protocols.protocol1_16to1_15_2.ServerboundPackets1_16;
import us.myles.ViaVersion.protocols.protocol1_16to1_15_2.data.MappingData;
import java.util.UUID;
public class InventoryPackets {
public static void register(Protocol protocol) {
ItemRewriter itemRewriter = new ItemRewriter(protocol, InventoryPackets::toClient, InventoryPackets::toServer);
protocol.registerOutgoing(ClientboundPackets1_15.OPEN_WINDOW, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT);
map(Type.VAR_INT);
map(Type.COMPONENT);
handler(wrapper -> {
int windowType = wrapper.get(Type.VAR_INT, 1);
if (windowType >= 20) { // smithing added with id 20
wrapper.set(Type.VAR_INT, 1, ++windowType);
}
});
}
});
protocol.registerOutgoing(ClientboundPackets1_15.WINDOW_PROPERTY, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.UNSIGNED_BYTE); // Window id
map(Type.SHORT); // Property
map(Type.SHORT); // Value
handler(wrapper -> {
short property = wrapper.get(Type.SHORT, 0);
if (property >= 4 && property <= 6) { // Enchantment id
short enchantmentId = wrapper.get(Type.SHORT, 1);
if (enchantmentId >= 11) { // soul_speed added with id 11
wrapper.set(Type.SHORT, 1, ++enchantmentId);
}
}
});
}
});
itemRewriter.registerSetCooldown(ClientboundPackets1_15.COOLDOWN, InventoryPackets::getNewItemId);
itemRewriter.registerWindowItems(ClientboundPackets1_15.WINDOW_ITEMS, Type.FLAT_VAR_INT_ITEM_ARRAY);
protocol.registerOutgoing(ClientboundPackets1_15.TRADE_LIST, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> {
wrapper.passthrough(Type.VAR_INT);
int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
for (int i = 0; i < size; i++) {
Item input = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM);
toClient(input);
Item output = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM);
toClient(output);
if (wrapper.passthrough(Type.BOOLEAN)) { // Has second item
// Second Item
toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM));
}
wrapper.passthrough(Type.BOOLEAN); // Trade disabled
wrapper.passthrough(Type.INT); // Number of tools uses
wrapper.passthrough(Type.INT); // Maximum number of trade uses
wrapper.passthrough(Type.INT);
wrapper.passthrough(Type.INT);
wrapper.passthrough(Type.FLOAT);
wrapper.passthrough(Type.INT);
}
wrapper.passthrough(Type.VAR_INT);
wrapper.passthrough(Type.VAR_INT);
wrapper.passthrough(Type.BOOLEAN);
});
}
});
itemRewriter.registerSetSlot(ClientboundPackets1_15.SET_SLOT, Type.FLAT_VAR_INT_ITEM);
protocol.registerOutgoing(ClientboundPackets1_15.ENTITY_EQUIPMENT, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT); // 0 - Entity ID
handler(wrapper -> {
int slot = wrapper.read(Type.VAR_INT);
wrapper.write(Type.BYTE, (byte) slot);
InventoryPackets.toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM));
});
}
});
protocol.registerOutgoing(ClientboundPackets1_15.DECLARE_RECIPES, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> {
int size = wrapper.passthrough(Type.VAR_INT);
for (int i = 0; i < size; i++) {
String type = wrapper.passthrough(Type.STRING).replace("minecraft:", "");
String id = wrapper.passthrough(Type.STRING);
switch (type) {
case "crafting_shapeless": {
wrapper.passthrough(Type.STRING); // Group
int ingredientsNo = wrapper.passthrough(Type.VAR_INT);
for (int j = 0; j < ingredientsNo; j++) {
Item[] items = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT); // Ingredients
for (Item item : items) toClient(item);
}
toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM)); // Result
break;
}
case "crafting_shaped": {
int ingredientsNo = wrapper.passthrough(Type.VAR_INT) * wrapper.passthrough(Type.VAR_INT);
wrapper.passthrough(Type.STRING); // Group
for (int j = 0; j < ingredientsNo; j++) {
Item[] items = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT); // Ingredients
for (Item item : items) toClient(item);
}
toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM)); // Result
break;
}
case "blasting":
case "smoking":
case "campfire_cooking":
case "smelting": {
wrapper.passthrough(Type.STRING); // Group
Item[] items = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT); // Ingredients
for (Item item : items) toClient(item);
toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM));
wrapper.passthrough(Type.FLOAT); // EXP
wrapper.passthrough(Type.VAR_INT); // Cooking time
break;
}
case "stonecutting": {
wrapper.passthrough(Type.STRING);
Item[] items = wrapper.passthrough(Type.FLAT_VAR_INT_ITEM_ARRAY_VAR_INT); // Ingredients
for (Item item : items) toClient(item);
toClient(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM));
break;
}
}
}
});
}
});
itemRewriter.registerClickWindow(ServerboundPackets1_16.CLICK_WINDOW, Type.FLAT_VAR_INT_ITEM);
itemRewriter.registerCreativeInvAction(ServerboundPackets1_16.CREATIVE_INVENTORY_ACTION, Type.FLAT_VAR_INT_ITEM);
protocol.registerIncoming(ServerboundPackets1_16.EDIT_BOOK, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> InventoryPackets.toServer(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM)));
}
});
}
public static void toClient(Item item) {
if (item == null) return;
if (item.getIdentifier() == 771 && item.getTag() != null) {
CompoundTag tag = item.getTag();
Tag ownerTag = tag.get("SkullOwner");
if (ownerTag instanceof CompoundTag) {
CompoundTag ownerCompundTag = (CompoundTag) ownerTag;
Tag idTag = ownerCompundTag.get("Id");
if (idTag instanceof StringTag) {
UUID id = UUID.fromString((String) idTag.getValue());
ownerCompundTag.put(new IntArrayTag("Id", UUIDIntArrayType.uuidToIntArray(id)));
}
}
}
item.setIdentifier(getNewItemId(item.getIdentifier()));
}
public static void toServer(Item item) {
if (item == null) return;
item.setIdentifier(getOldItemId(item.getIdentifier()));
if (item.getIdentifier() == 771 && item.getTag() != null) {
CompoundTag tag = item.getTag();
Tag ownerTag = tag.get("SkullOwner");
if (ownerTag instanceof CompoundTag) {
CompoundTag ownerCompundTag = (CompoundTag) ownerTag;
Tag idTag = ownerCompundTag.get("Id");
if (idTag instanceof IntArrayTag) {
UUID id = UUIDIntArrayType.uuidFromIntArray((int[]) idTag.getValue());
ownerCompundTag.put(new StringTag("Id", id.toString()));
}
}
}
}
public static int getNewItemId(int id) {
int newId = MappingData.oldToNewItems.get(id);
if (newId == -1) {
Via.getPlatform().getLogger().warning("Missing 1.16 item for 1.15.2 item " + id);
return 1;
}
return newId;
}
public static int getOldItemId(int id) {
int oldId = MappingData.oldToNewItems.inverse().get(id);
return oldId != -1 ? oldId : 1;
}
}
| 45.457265 | 124 | 0.531917 |
9f50c9dc69c22290ff0d80dd2c6e1b77ea664aff | 1,086 | /**
* Brute force solution
*/
public class LPS {
public int findLPSLength(String input){
if(input == null || input.length() == 0) return 0;
return findLPSLengthRecursive(input, 0, input.length() - 1);
}
private int findLPSLengthRecursive(String input, int startIndex, int endIndex){
if (startIndex > endIndex) {
return 0;
}
if(startIndex == endIndex){
return 1;
}
if(input.charAt(startIndex) == input.charAt(endIndex)){
return 2 + findLPSLengthRecursive(input, startIndex + 1, endIndex - 1);
}
int skipBeginning = findLPSLengthRecursive(input, startIndex + 1, endIndex);
int skipEnding = findLPSLengthRecursive(input, startIndex, endIndex - 1);
return Math.max(skipBeginning, skipEnding);
}
public static void main(String[] args) {
LPS lps = new LPS();
System.out.println(lps.findLPSLength("abdbca"));
System.out.println(lps.findLPSLength("cddpd"));
System.out.println(lps.findLPSLength("pqr"));
}
}
| 29.351351 | 84 | 0.61418 |
51f5e5f355516a02dccddf14a265e1eb31bbd389 | 2,730 | package cn.yescallop.googletrans4j;
import cn.yescallop.googletrans4j.internal.TransRequestBuilderImpl;
import java.util.Set;
/**
* A <i>Google Translate</i> request.
*
* @author Scallop Ye
*/
public interface TransRequest {
/**
* Creates a new {@code TransRequest} builder.
*
* @return a new builder.
*/
static Builder newBuilder() {
return new TransRequestBuilderImpl();
}
/**
* Creates a new {@code TransRequest} builder with the given text.
*
* @param text the text.
* @return a new builder.
*/
static Builder newBuilder(String text) {
return newBuilder().text(text);
}
/**
* Creates a new {@code TransRequest} for detecting the language of the given text.
*
* @param text the text.
* @return a new request.
*/
static TransRequest langDetecting(String text) {
return newBuilder(text)
.parameters()
.build();
}
/**
* A builder of {@code TransRequest}.
*/
interface Builder {
/**
* Sets the source language.
* <p>
* If not invoked, "auto" will be used.
*
* @param lang the source language.
* @return this builder.
*/
Builder sourceLang(String lang);
/**
* Sets the target language.
* <p>
* If not invoked, this value will remain empty.
*
* @param lang the target language.
* @return this builder.
*/
Builder targetLang(String lang);
/**
* Sets the text of the request.
*
* @param text the text.
* @return this builder.
*/
Builder text(String text);
/**
* Sets the parameters of the request.
* <p>
* If not invoked, {@link TransParameter#TRANSLATION} will be used.
*
* @param params the parameters.
* @return this builder.
*/
Builder parameters(TransParameter... params);
/**
* Builds the request.
*
* @return the new request.
*/
TransRequest build();
}
/**
* Returns the source language of this request.
*
* @return the source language.
*/
String sourceLang();
/**
* Returns the target language of this request.
*
* @return the target language.
*/
String targetLang();
/**
* Returns the text of this request.
*
* @return the text.
*/
String text();
/**
* Returns the parameters of this request.
*
* @return the parameters.
*/
Set<TransParameter> parameters();
}
| 22.016129 | 87 | 0.531868 |
a3b6c638f065d2f39e30c66f77e3900e7269ae45 | 1,507 | /*
* Copyright (c) 2017 by Gerrit Grunwald
*
* 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 eu.hansolo.tilesfx.colors;
import javafx.scene.paint.Color;
/**
* Created by hansolo on 25.12.16.
*/
public class Wan implements TileColor {
public static Color RED = Color.web("#d57565");
public static Color ORANGE_RED = Color.web("#d59a65");
public static Color ORANGE = Color.web("#d5b065");
public static Color YELLOW_ORANGE = Color.web("#d5c765");
public static Color YELLOW = Color.web("#cad163");
public static Color GREEN_YELLOW = Color.web("#8fc65e");
public static Color GREEN = Color.web("#5bbf83");
public static Color BLUE_GREEN = Color.web("#5b9abf");
public static Color BLUE = Color.web("#5b6fbf");
public static Color PURPLE_BLUE = Color.web("#7d5bbf");
public static Color PURPLE = Color.web("#ba5bbf");
public static Color RED_PURPLE = Color.web("#c85f7e");
}
| 38.641026 | 75 | 0.681486 |
762689bdf21c5adda8bd6bd8bed31dbb6a165e1f | 2,199 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences.datareduction;
import android.content.Context;
import android.text.format.Formatter;
/**
* Stores the data used and saved by a hostname.
*/
public class DataReductionDataUseItem {
private String mHostname;
private long mDataUsed;
private long mOriginalSize;
/**
* Constructor for a DataReductionDataUseItem which associates a hostname with its data usage
* and savings.
*
* @param hostname The hostname associated with this data usage.
* @param dataUsed The amount of data used by the host.
* @param originalSize The original size of the data.
*/
public DataReductionDataUseItem(String hostname, long dataUsed, long originalSize) {
mHostname = hostname;
mDataUsed = dataUsed;
mOriginalSize = originalSize;
}
/**
* Returns the hostname for this data use item.
* @return The hostname.
*/
public String getHostname() {
return mHostname;
}
/**
* Returns the amount of data used by the associated hostname.
* @return The data used.
*/
public long getDataUsed() {
return mDataUsed;
}
/**
* Returns the amount of data saved by the associated hostname.
* @return The data saved.
*/
public long getDataSaved() {
return mOriginalSize - mDataUsed;
}
/**
* Returns a formatted String of the data used by the associated hostname.
* @param context An Android context.
* @return A formatted string of the data used.
*/
public String getFormattedDataUsed(Context context) {
return Formatter.formatFileSize(context, mDataUsed);
}
/**
* Returns a formatted String of the data saved by the associated hostname.
* @param context An Android context.
* @return A formatted string of the data saved.
*/
public String getFormattedDataSaved(Context context) {
return Formatter.formatFileSize(context, mOriginalSize - mDataUsed);
}
} | 30.123288 | 97 | 0.673943 |
59be29452c0ffd8d3216bfbfbbace39e26afbee2 | 4,112 | // Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.adaptor;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Date;
import java.util.logging.Logger;
/** Serves class' resources like dashboard's html and jquery js. */
class DashboardHandler implements HttpHandler {
private static final Logger log
= Logger.getLogger(DashboardHandler.class.getName());
/** Subpackage to look for static resources within. */
private static final String STATIC_PACKAGE = "resources";
@Override
public void handle(HttpExchange ex) throws IOException {
String requestMethod = ex.getRequestMethod();
if ("GET".equals(requestMethod)) {
URI req = HttpExchanges.getRequestUri(ex);
final String basePath = ex.getHttpContext().getPath();
final String pathPrefix = basePath + "/";
if (basePath.equals(req.getPath())) {
URI redirect;
try {
redirect = new URI(req.getScheme(), req.getAuthority(),
pathPrefix, req.getQuery(),
req.getFragment());
} catch (java.net.URISyntaxException e) {
throw new IllegalStateException(e);
}
ex.getResponseHeaders().set("Location", redirect.toString());
HttpExchanges.respond(
ex, HttpURLConnection.HTTP_MOVED_PERM, null, null);
return;
}
String path = req.getPath();
path = path.substring(pathPrefix.length());
if ("".equals(path)) {
path = "index.html";
}
path = STATIC_PACKAGE + "/" + path;
java.net.URL url = DashboardHandler.class.getResource(path);
if (url == null) {
HttpExchanges.cannedRespond(ex, HttpURLConnection.HTTP_NOT_FOUND,
Translation.HTTP_NOT_FOUND);
return;
}
Date lastModified = new Date(url.openConnection().getLastModified());
if (lastModified.getTime() == 0) {
log.info("Resource didn't have a lastModified time");
} else {
Date since = HttpExchanges.getIfModifiedSince(ex);
if (since != null && !lastModified.after(since)) {
HttpExchanges.respond(
ex, HttpURLConnection.HTTP_NOT_MODIFIED, null, null);
return;
}
HttpExchanges.setLastModified(ex, lastModified);
}
byte contents[] = loadPage(path);
String contentType = "application/octet-stream";
if (path.endsWith(".html")) {
contentType = "text/html";
} else if (path.endsWith(".css")) {
contentType = "text/css";
} else if (path.endsWith(".js")) {
contentType = "text/javascript";
}
HttpExchanges.enableCompressionIfSupported(ex);
HttpExchanges.respond(
ex, HttpURLConnection.HTTP_OK, contentType, contents);
} else {
HttpExchanges.cannedRespond(ex, HttpURLConnection.HTTP_BAD_METHOD,
Translation.HTTP_BAD_METHOD);
}
}
/**
* Provides static files that are resources.
*/
private byte[] loadPage(String path) throws IOException {
InputStream in = DashboardHandler.class.getResourceAsStream(path);
if (null == in) {
throw new FileNotFoundException(path);
} else {
try {
byte page[] = IOHelper.readInputStreamToByteArray(in);
return page;
} finally {
in.close();
}
}
}
}
| 35.756522 | 75 | 0.652967 |
4a220daa364e7a934b1556a2c14cefa160fa46c1 | 541 | // Generated by esidl 0.4.0.
package org.w3c.dom.typedarray;
import org.w3c.dom.LongArray;
public interface Int32Array_Constructor
{
// Constructor
public Int32Array createInstance(int length);
public Int32Array createInstance(ArrayBufferView array);
public Int32Array createInstance(LongArray array);
public Int32Array createInstance(ArrayBuffer buffer);
public Int32Array createInstance(ArrayBuffer buffer, int byteOffset);
public Int32Array createInstance(ArrayBuffer buffer, int byteOffset, int length);
}
| 31.823529 | 85 | 0.787431 |
5eb87acd478c9b9511895b46b2cc71b40c58bfe2 | 3,521 | package com.checkout.hybris.facades.payment.converters.populators;
import com.checkout.hybris.core.merchant.services.CheckoutComMerchantConfigurationService;
import com.checkout.hybris.core.model.CheckoutComCreditCardPaymentInfoModel;
import com.checkout.hybris.core.payment.resolvers.CheckoutComPaymentTypeResolver;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class CheckoutComCCPaymentInfoReversePopulatorTest {
private static final String TOKEN = "token";
private static final String CARD_BIN = "123456";
@InjectMocks
private CheckoutComCCPaymentInfoReversePopulator testObj;
@Mock
private CheckoutComPaymentTypeResolver checkoutComPaymentTypeResolverMock;
@Mock
private CheckoutComMerchantConfigurationService checkoutComMerchantConfigurationServiceMock;
private CheckoutComCreditCardPaymentInfoModel target = new CheckoutComCreditCardPaymentInfoModel();
@Before
public void setUp() {
when(checkoutComMerchantConfigurationServiceMock.isAutoCapture()).thenReturn(false);
when(checkoutComPaymentTypeResolverMock.isMadaCard(CARD_BIN)).thenReturn(false);
}
@Test(expected = IllegalArgumentException.class)
public void populate_WithNullSource_ShouldThrowException() {
testObj.populate(null, target);
}
@Test(expected = IllegalArgumentException.class)
public void populate_WithNullTarget_ShouldThrowException() {
final CCPaymentInfoData source = new CCPaymentInfoData();
source.setPaymentToken(TOKEN);
testObj.populate(source, null);
}
@Test
public void populate_WhenCardMarkedToSave_ShouldPopulateEverythingCorrectly() {
final CCPaymentInfoData source = createSource(true);
testObj.populate(source, target);
assertEquals(TOKEN, target.getCardToken());
assertTrue(target.getMarkToSave());
assertFalse(target.isSaved());
assertEquals(CARD_BIN, target.getCardBin());
assertFalse(target.getAutoCapture());
}
@Test
public void populate_WhenMadaCardMarkedToSave_ShouldPopulateEverythingCorrectly() {
when(checkoutComPaymentTypeResolverMock.isMadaCard(CARD_BIN)).thenReturn(true);
final CCPaymentInfoData source = createSource(true);
testObj.populate(source, target);
assertEquals(TOKEN, target.getCardToken());
assertTrue(target.getMarkToSave());
assertEquals(CARD_BIN, target.getCardBin());
assertTrue(target.getAutoCapture());
}
@Test
public void populate_WhenCardNotMarkedToSave_ShouldPopulateEverythingCorrectly() {
final CCPaymentInfoData source = createSource(false);
testObj.populate(source, target);
assertEquals(TOKEN, target.getCardToken());
assertFalse(target.getMarkToSave());
assertEquals(CARD_BIN, target.getCardBin());
}
private CCPaymentInfoData createSource(final boolean isSaved) {
final CCPaymentInfoData source = new CCPaymentInfoData();
source.setPaymentToken(TOKEN);
source.setSaved(isSaved);
source.setCardBin(CARD_BIN);
return source;
}
}
| 35.565657 | 103 | 0.756035 |
6cb14f66d1c804f97bfd3ea59edcbc213adaea4d | 1,169 | package au.com.manthey.devtest;
import spark.Spark;
import static au.com.manthey.devtest.PANValidator.validate;
import static spark.Spark.get;
import static spark.Spark.port;
public class RestApp {
public static final String SERVER = "localhost";
public static final int PORT = 8080;
public static final String HOST = SERVER + ":" + PORT;
public static final String USAGE_HINT = String.format("Usage: <a href='http://%s/1234567890123456'>http://%s/1234567890123456</a>", HOST, HOST);
public static void main(String[] args) {
port(PORT);
get("/", (req,res) -> USAGE_HINT);
get("/:cc", (req,res)-> validate(req.params(":cc")));
}
/**
* This was introduced to solve the Integration tests conflicting
*/
public static void stopServer() {
try {
Spark.stop();
while (true) {
try {
Spark.port();
Thread.sleep(500);
} catch (final IllegalStateException ignored) {
break;
}
}
} catch (final Exception ex) {
// Ignore
}
}
} | 29.225 | 148 | 0.560308 |
e6d90de403c7a01661758b3483870ff0bdeadc72 | 4,019 | package com.github.NervousOrange.dao;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.sql.*;
public class H2JdbcDAO implements CrawlerDAO {
Connection connection;
static final String databaseURL = "jdbc:h2:file:C:/Users/zch69/recipes/Multi-Threaded-Crawler/CrawlerDatabase";
public H2JdbcDAO() {
connectDatabase();
}
@SuppressFBWarnings("DMI_CONSTANT_DB_PASSWORD")
public void connectDatabase() {
try {
connection = DriverManager.getConnection(databaseURL, "root", "root");
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public synchronized String loadLinkFromDatabaseAndDelete() {
ResultSet resultSet = null;
String linkToBeProcessed = null;
try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT LINK FROM LINKS_TO_BE_PROCESSED LIMIT 1")) {
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
linkToBeProcessed = (resultSet.getString(1));
deleteLinkInDatabase(linkToBeProcessed);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return linkToBeProcessed;
}
@Override
public void insertLinkInLinkToBeProcessed(String link) {
try (PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO LINKS_TO_BE_PROCESSED (link) values (?)")) {
preparedStatement.setString(1, link);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void insertLinkInLinkAlreadyProcessed(String link) {
try (PreparedStatement preparedStatement = connection.prepareStatement("insert into LINKS_ALREADY_PROCESSED (link) values(?)")) {
preparedStatement.setString(1, link);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deleteLinkInDatabase(String link) {
try (PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM LINKS_TO_BE_PROCESSED WHERE LINK = ?")) {
preparedStatement.setString(1, link);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void writeNewsPagesIntoDatabase(String title, String content, String URL) {
try (PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO NEWS (TITLE, CONTENT, URL, CREATED_AT, MODIFIED_AT) VALUES (?, ?, ?, now(), now())")) {
preparedStatement.setString(1, title);
preparedStatement.setString(2, content);
preparedStatement.setString(3, URL);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean isLinkInDatabase(String link) {
ResultSet resultSet = null;
try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT LINK FROM LINKS_ALREADY_PROCESSED WHERE LINK = ?")) {
preparedStatement.setString(1, link);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
}
| 35.254386 | 179 | 0.602389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.