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
|
---|---|---|---|---|---|
97038efc34b6d7259d0678c5fba4ce6aa87e38b2 | 6,678 | package edu.umass.cs.txn;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import edu.umass.cs.gigapaxos.interfaces.ExecutedCallback;
import edu.umass.cs.gigapaxos.interfaces.Request;
import edu.umass.cs.nio.interfaces.IntegerPacketType;
import edu.umass.cs.reconfiguration.AbstractReplicaCoordinator;
import edu.umass.cs.reconfiguration.ReconfigurationConfig;
import edu.umass.cs.reconfiguration.ReconfigurationConfig.RC;
import edu.umass.cs.reconfiguration.interfaces.ReconfigurableRequest;
import edu.umass.cs.reconfiguration.reconfigurationutils.RequestParseException;
import edu.umass.cs.txn.interfaces.TXInterface;
import edu.umass.cs.txn.txpackets.TXPacket;
import edu.umass.cs.txn.txpackets.TxOpRequest;
import edu.umass.cs.utils.Config;
import edu.umass.cs.utils.GCConcurrentHashMap;
/**
* @author arun
*
* @param <NodeIDType>
*/
public abstract class AbstractTransactor<NodeIDType> extends
AbstractReplicaCoordinator<NodeIDType> {
private final AbstractReplicaCoordinator<NodeIDType> coordinator;
protected AbstractTransactor(
AbstractReplicaCoordinator<NodeIDType> coordinator) {
super(coordinator);
this.coordinator = coordinator;
}
private static final IntegerPacketType[] txTypes = {
TXPacket.PacketType.ABORT_REQUEST,
TXPacket.PacketType.COMMIT_REQUEST,
TXPacket.PacketType.LOCK_REQUEST,
TXPacket.PacketType.TX_STATE_REQUEST,
TXPacket.PacketType.UNLOCK_REQUEST };
private static final boolean ENABLE_TRANSACTIONS = Config
.getGlobalBoolean(RC.ENABLE_TRANSACTIONS);
/* FIXME: how is a transaction's timeout decided? Any limit imposes a limit
* on the type of operations that can be done within a transaction.
* Databases don't impose such a timeout as they allow transactional
* operations to take arbitrarily long. So should we. */
private static final long DEFAULT_TX_TIMEOUT = Long.MAX_VALUE;
private static final long MAX_QUEUED_REQUESTS = 8000;
private GCConcurrentHashMap<Request, ExecutedCallback> callbacks = new GCConcurrentHashMap<Request, ExecutedCallback>(
DEFAULT_TX_TIMEOUT);
/* ********* Start of coordinator-related methods *************** */
private Set<IntegerPacketType> cachedRequestTypes = null;
@Override
public Set<IntegerPacketType> getRequestTypes() {
if (cachedRequestTypes != null)
return cachedRequestTypes;
Set<IntegerPacketType> types = new HashSet<IntegerPacketType>();
// underlying coordinator request (includes app types)
types.addAll(this.coordinator.getRequestTypes());
// tx types
if (ENABLE_TRANSACTIONS)
types.addAll(new HashSet<IntegerPacketType>(Arrays.asList(txTypes)));
return cachedRequestTypes = types;
}
// simply enqueue if room and call parent
@Override
public boolean coordinateRequest(Request request, ExecutedCallback callback)
throws IOException, RequestParseException {
if (!ENABLE_TRANSACTIONS || this.callbacks.size() < MAX_QUEUED_REQUESTS
&& this.callbacks.putIfAbsent(request, callback) == null)
return this.coordinator.coordinateRequest(request, callback);
// else
ReconfigurationConfig.getLogger().log(Level.WARNING,
"{0} dropping request {1} because queue size limit reached",
new Object[] { this, request.getSummary() });
return false;
}
@Override
public boolean execute(Request request, boolean noReplyToClient) {
if (!ENABLE_TRANSACTIONS || !isLocked(request.getServiceName()) ||
(request instanceof TxOpRequest && this.isOngoing(((TxOpRequest)request).getTxID())))
return this.coordinator.execute(request, noReplyToClient,
this.callbacks.remove(request.getServiceName()));
enqueue(request, noReplyToClient);
/* Need to return true here no matter what, otherwise paxos will be
* stuck. */
return true;
}
/**
* @param txID
* @return True if txID is an ongoing transaction.
*/
private boolean isOngoing(String txID) {
// TODO Auto-generated method stub
return false;
}
private TXInterface getTransaction(String serviceName) {
// TODO Auto-generated method stub
return null;
}
protected abstract void enqueue(Request request, boolean noReplyToClient);
protected abstract boolean isLocked(String serviceName);
@Override
public boolean execute(Request request) {
return this.execute(request, false);
}
@Override
public boolean createReplicaGroup(String serviceName, int epoch,
String state, Set<NodeIDType> nodes) {
return this.coordinator.createReplicaGroup(serviceName, epoch, state,
nodes);
}
@Override
public boolean deleteReplicaGroup(String serviceName, int epoch) {
return this.coordinator.deleteReplicaGroup(serviceName, epoch);
}
@Override
public Set<NodeIDType> getReplicaGroup(String serviceName) {
return this.coordinator.getReplicaGroup(serviceName);
}
/* ********* End of coordinator methods *************** */
/* ********* Start of Repliconfigurable methods *************** */
@Override
public ReconfigurableRequest getStopRequest(String name, int epoch) {
return this.coordinator.getStopRequest(name, epoch);
}
@Override
public String getFinalState(String name, int epoch) {
return this.coordinator.getFinalState(name, epoch);
}
@Override
public void putInitialState(String name, int epoch, String state) {
this.coordinator.putInitialState(name, epoch, state);
}
@Override
public boolean deleteFinalState(String name, int epoch) {
return this.coordinator.deleteFinalState(name, epoch);
}
@Override
public Integer getEpoch(String name) {
return this.coordinator.getEpoch(name);
}
@Override
public String checkpoint(String name) {
return this.coordinator.checkpoint(name);
}
@Override
public boolean restore(String name, String state) {
TXInterface request = this.decodeTX(state);
if (request == null)
return this.coordinator.restore(name, state);
else
return this.processTX((TXInterface) request);
}
private boolean processTX(TXInterface request) {
Set<NodeIDType> group = this.getReplicaGroup(request.getTXID());
SortedSet<String> sorted = new TreeSet<String>();
for (NodeIDType node : group)
sorted.add(node.toString());
if (this.getMyID().toString().equals(sorted.iterator().next())) {
// if first in list, actually do stuff
}
// else secondary
return spawnWaitPrimaryTask(request);
}
private boolean spawnWaitPrimaryTask(TXInterface request) {
// TODO Auto-generated method stub
return false;
}
private TXInterface decodeTX(String state) {
// TODO Auto-generated method stub
return null;
}
/* ********* End of Repliconfigurable methods *************** */
}
| 32.26087 | 119 | 0.758311 |
5dae838710f53294c25ddf5370c445c61cc09357 | 1,535 | package com.peter._2020._30.days.trail.june._12_Insert_Delete_GetRandom;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class RandomizedSet {
public static void main(String[] args) {
var a = new RandomizedSet();
a.insert(1);
a.insert(2);
a.remove(1);
a.insert(3);
a.remove(2);
System.out.println("a.getRandom() = " + a.getRandom());
}
private final Map<Integer, Integer> map = new HashMap<>();
private final List<Integer> list = new ArrayList<>();
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
*/
public boolean insert(int val) {
if (map.containsKey(val)) return false;
map.put(val, list.size());
list.add(val);
return true;
}
/**
* Removes a value from the set. Returns true if the set contained the specified element.
*/
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
Integer index = map.get(val);
int tail = list.size() - 1;
if (index != tail) {
Integer element = list.get(tail);
Collections.swap(list, index, tail);
map.put(element, index);
}
list.remove(tail);
map.remove(val);
return true;
}
/**
* Get a random element from the set.
*/
public int getRandom() {
return list.get(ThreadLocalRandom.current().nextInt(list.size()));
}
}
| 28.425926 | 105 | 0.584365 |
ca2cc302a1e371a5a88ef5ef67cefbf207597dc1 | 9,363 | /**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.User;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* Lets the user set pings on/off for a given friend.
*
* @date September 25, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class UserDetailsPingsActivity extends Activity {
private static final String TAG = "UserDetailsPingsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserDetailsPingsActivity.EXTRA_USER_PARCEL";
public static final String EXTRA_USER_RETURNED = Foursquared.PACKAGE_NAME
+ ".UserDetailsPingsActivity.EXTRA_USER_RETURNED";
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_details_pings_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().getExtras() != null) {
if (getIntent().hasExtra(EXTRA_USER_PARCEL)) {
User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL);
mStateHolder.setUser(user);
} else {
Log.e(TAG, TAG + " requires a user pareclable in its intent extras.");
finish();
return;
}
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
User user = mStateHolder.getUser();
TextView tv = (TextView)findViewById(R.id.userDetailsPingsActivityDescription);
Button btn = (Button)findViewById(R.id.userDetailsPingsActivityButton);
if (user.getSettings().getGetPings()) {
tv.setText(getString(R.string.user_details_pings_activity_description_on,
user.getFirstname()));
btn.setText(getString(R.string.user_details_pings_activity_pings_off,
user.getFirstname()));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStateHolder.startPingsTask(UserDetailsPingsActivity.this, false);
}
});
} else {
tv.setText(getString(R.string.user_details_pings_activity_description_off,
user.getFirstname()));
btn.setText(getString(R.string.user_details_pings_activity_pings_on,
user.getFirstname()));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStateHolder.startPingsTask(UserDetailsPingsActivity.this, true);
}
});
}
if (mStateHolder.getIsRunningTaskPings()) {
btn.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
} else {
btn.setEnabled(true);
setProgressBarIndeterminateVisibility(false);
}
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
private void prepareResultIntent() {
Intent intent = new Intent();
intent.putExtra(EXTRA_USER_RETURNED, mStateHolder.getUser());
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void onTaskPingsComplete(Settings settings, String userId, boolean on, Exception ex) {
mStateHolder.setIsRunningTaskPings(false);
// The api is returning pings = false for all cases, so manually overwrite,
// assume a non-null settings object is success.
if (settings != null) {
settings.setGetPings(on);
mStateHolder.setSettingsResult(settings);
prepareResultIntent();
} else {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
}
ensureUi();
}
private static class TaskPings extends AsyncTask<Void, Void, Settings> {
private UserDetailsPingsActivity mActivity;
private String mUserId;
private boolean mOn;
private Exception mReason;
public TaskPings(UserDetailsPingsActivity activity, String userId, boolean on) {
mActivity = activity;
mUserId = userId;
mOn = on;
}
public void setActivity(UserDetailsPingsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected Settings doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.setpings(mUserId, mOn);
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Settings settings) {
if (mActivity != null) {
mActivity.onTaskPingsComplete(settings, mUserId, mOn, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskPingsComplete(null, mUserId, mOn, new FoursquareException("Tip task cancelled."));
}
}
}
private static class StateHolder {
private User mUser;
private boolean mIsRunningTask;
private Intent mPreparedResult;
private TaskPings mTaskPings;
public StateHolder() {
mPreparedResult = null;
mIsRunningTask = false;
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
public void setSettingsResult(Settings settings) {
mUser.getSettings().setGetPings(settings.getGetPings());
}
public void startPingsTask(UserDetailsPingsActivity activity, boolean on) {
if (!mIsRunningTask) {
mIsRunningTask = true;
mTaskPings = new TaskPings(activity, mUser.getId(), on);
mTaskPings.execute();
}
}
public void setActivity(UserDetailsPingsActivity activity) {
if (mTaskPings != null) {
mTaskPings.setActivity(activity);
}
}
public void setIsRunningTaskPings(boolean isRunning) {
mIsRunningTask = isRunning;
}
public boolean getIsRunningTaskPings() {
return mIsRunningTask;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
}
}
| 33.439286 | 114 | 0.597244 |
4a80b0312afdf2a3b7fab6a17db128e2e03d57e1 | 3,145 | /*
* Copyright 2013 Dominic.
*
* 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.domsplace.CreditShops.Commands;
import com.domsplace.CreditShops.Bases.Base;
import com.domsplace.CreditShops.Bases.BukkitCommand;
import com.domsplace.CreditShops.Objects.DomsItem;
import com.domsplace.CreditShops.Objects.ItemPricer;
import com.domsplace.CreditShops.Objects.SubCommandOption;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
/**
* @author Dominic
* @since 30/10/2013
*/
public class SellCommand extends BukkitCommand {
public SellCommand() {
super("sell");
this.addSubCommandOption(SubCommandOption.ITEM_OPTION);
}
@Override
public boolean cmd(CommandSender sender, Command cmd, String label, String[] args) {
if(!isPlayer(sender)) return this.noPermission(sender, cmd, label, args);
DomsItem held = DomsItem.createItem(getPlayer(sender).getItemInHand());
if(held == null || held.isAir()) {
sendMessage(sender, ChatError + "You must be holding an item.");
return true;
}
if(!ItemPricer.isSellable(held)) {
sendMessage(sender, ChatError + "This item cannot be sold.");
return true;
}
int amount = getPlayer(sender).getItemInHand().getAmount();
if(args.length > 0) {
if(!isInt(args[0]) || getInt(args[0]) < 1) {
sendMessage(sender, ChatError + "Amount must be a number above 0");
return true;
}
amount = getInt(args[0]);
}
//determine worth
double sellWorth = ItemPricer.getPrice(held);
sellWorth = sellWorth * ((double) amount);
sellWorth = sellWorth * getConfig().getDouble("cost.command.sell.deflateprice", 1.00d);
String v = Base.formatEcon(sellWorth);
//Take Items
if(!DomsItem.hasItem(held, amount, getPlayer(sender).getInventory())) {
sendMessage(sender, ChatError + "You don't have these items.");
return true;
}
DomsItem.removeItem(held, amount, getPlayer(sender).getInventory());
if(Base.useEcon()) {
Base.chargePlayer(sender.getName(), -sellWorth);
}
sendMessage(sender,
"Sold " + ChatImportant +
Base.listToString(DomsItem.getHumanMessages(DomsItem.multiply(held, amount))).replaceAll(ChatDefault, ChatImportant)
+ ChatDefault + " for " + ChatImportant + v
);
return true;
}
}
| 36.149425 | 128 | 0.633704 |
2e7d1843856c4eb854cf981d2307667cc714b105 | 793 | package com.cm.usermanagement.user.transfer;
import java.io.Serializable;
public class ForgotPasswordRequest implements Serializable {
private static final long serialVersionUID = 1629672935573849314L;
private String email;
private String guid;
private String password;
private String password2;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}
| 16.520833 | 67 | 0.736444 |
b778b8dd74ff381ec33b309224067cb3fd3e57e4 | 857 | /**
*
*/
package com.cloderia.helion.client.shared.operation;
import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.Portable;
import com.cloderia.helion.client.shared.model.SubjectCategory;
/**
* @author adrian
*
*/
@Portable
public class SubjectCategoryOperation extends AbstractOperation {
private final SubjectCategory subjectCategory;
public SubjectCategoryOperation(final @MapsTo("subjectCategory") SubjectCategory subjectCategory,
final @MapsTo("sourceQueueSessionId") String sourceQueueSessionId) {
this.subjectCategory = subjectCategory;
this.sourceQueueSessionId = sourceQueueSessionId;
}
/**
* A {@link SubjectCategory} that has been created or updated.
*/
public SubjectCategory getData() {
return subjectCategory;
}
}
| 23.805556 | 101 | 0.749125 |
195fa4303e3eb2f34e85a8966530ab194deeff61 | 10,069 | /*
* 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.tuscany.sca.assembly.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.tuscany.sca.assembly.Base;
import org.apache.tuscany.sca.assembly.Binding;
import org.apache.tuscany.sca.assembly.Component;
import org.apache.tuscany.sca.assembly.ComponentService;
import org.apache.tuscany.sca.assembly.Endpoint;
import org.apache.tuscany.sca.assembly.EndpointReference;
import org.apache.tuscany.sca.assembly.builder.BuilderExtensionPoint;
import org.apache.tuscany.sca.assembly.builder.ContractBuilder;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.interfacedef.InterfaceContract;
import org.apache.tuscany.sca.policy.ExtensionType;
import org.apache.tuscany.sca.policy.Intent;
import org.apache.tuscany.sca.policy.PolicySet;
import org.apache.tuscany.sca.policy.PolicySubject;
/**
* The assembly model object for an endpoint.
*
* @version $Rev$ $Date$
*/
public class EndpointImpl implements Endpoint {
private static final long serialVersionUID = 7344399683703812593L;
protected transient ExtensionPointRegistry registry;
protected transient BuilderExtensionPoint builders;
protected transient ContractBuilder contractBuilder;
protected boolean unresolved;
protected String uri;
protected String deployedURI;
protected Component component;
protected ComponentService service;
protected Binding binding;
protected InterfaceContract interfaceContract;
protected List<EndpointReference> callbackEndpointReferences = new ArrayList<EndpointReference>();
protected List<PolicySet> policySets = new ArrayList<PolicySet>();
protected List<Intent> requiredIntents = new ArrayList<Intent>();
protected boolean remote = false;
protected String specVersion = Base.SCA11_NS;
protected EndpointImpl(ExtensionPointRegistry registry) {
this.registry = registry;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public boolean isUnresolved() {
return unresolved;
}
public void setUnresolved(boolean unresolved) {
this.unresolved = unresolved;
}
public Component getComponent() {
resolve();
return component;
}
public void setComponent(Component component) {
this.component = component;
reset();
}
public ComponentService getService() {
resolve();
return service;
}
public void setService(ComponentService service) {
this.service = service;
reset();
}
public Binding getBinding() {
resolve();
return binding;
}
public void setBinding(Binding binding) {
this.binding = binding;
reset();
}
public InterfaceContract getComponentServiceInterfaceContract() {
resolve();
if (interfaceContract == null && service != null) {
interfaceContract = service.getInterfaceContract();
}
return interfaceContract;
}
public void setInterfaceContract(InterfaceContract interfaceContract) {
this.interfaceContract = interfaceContract;
}
/**
* Get the services callbacl enpoint references that
* represent endpoint references from which callbacks
* originate
*
* @return callbackEndpoint the reference callback endpoint
*/
public List<EndpointReference> getCallbackEndpointReferences() {
resolve();
return callbackEndpointReferences;
}
public List<PolicySet> getPolicySets() {
resolve();
return policySets;
}
public List<Intent> getRequiredIntents() {
resolve();
return requiredIntents;
}
public ExtensionType getExtensionType() {
getBinding();
if (binding instanceof PolicySubject) {
return ((PolicySubject)binding).getExtensionType();
}
return null;
}
public void setExtensionType(ExtensionType type) {
throw new UnsupportedOperationException();
}
public String toStringWithoutHash() {
String output = "Endpoint: ";
if (getURI() != null) {
output += " URI = " + getURI();
}
if (unresolved) {
output += " [Unresolved]";
}
return output;
}
public String toString() {
return "(@" + this.hashCode() + ")" + toStringWithoutHash();
}
public String getURI() {
if (uri == null) {
if (component != null && service != null && binding != null) {
String bindingName = binding.getName();
if (bindingName == null) {
bindingName = service.getName();
}
uri = component.getURI() + "#service-binding(" + service.getName() + "/" + bindingName + ")";
} else if (component != null && service != null) {
uri = component.getURI() + "#service(" + service.getName() + ")";
} else if (component != null) {
uri = component.getURI();
}
}
return uri;
}
public void setURI(String uri) {
this.uri = uri;
}
protected void resolve() {
}
protected void reset() {
this.uri = null;
}
protected void setExtensionPointRegistry(ExtensionPointRegistry registry) {
this.registry = registry;
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remote) {
this.remote = remote;
}
public boolean matches(String serviceURI) {
String[] parts1 = parseServiceURI(serviceURI);
String[] parts2 = parseStructuralURI(getURI());
for (int i = 0; i < parts1.length; i++) {
if (parts1[i] == null || parts1[i].equals(parts2[i])) {
continue;
} else {
return false;
}
}
return true;
}
/**
* Parse the service URI into an array of names. The service URI is in one of the following formats:
* <ul>
* <li>componentName
* <li>componentName/serviceName
* <li>componentName/serviceName/bindingName
* </ul>
* @param serviceURI
* @return
*/
private static String[] parseServiceURI(String serviceURI) {
if (serviceURI.startsWith("/")) {
serviceURI = serviceURI.substring(1);
}
if (serviceURI.contains("#")) {
return parseStructuralURI(serviceURI);
}
String[] names = new String[3];
String[] segments = serviceURI.split("/");
for (int i = 0; i < names.length && i < segments.length; i++) {
names[i] = segments[i];
}
return names;
}
/**
* Parse the structural URI into an array of parts (componentURI, serviceName, bindingName)
* @param structuralURI
* @return [0]: componentURI [1]: serviceName [2]: bindingName
*/
private static String[] parseStructuralURI(String structuralURI) {
String[] names = new String[3];
int index = structuralURI.lastIndexOf('#');
if (index == -1) {
names[0] = structuralURI;
} else {
names[0] = structuralURI.substring(0, index);
String str = structuralURI.substring(index + 1);
if (str.startsWith("service-binding(") && str.endsWith(")")) {
str = str.substring("service-binding(".length(), str.length() - 1);
String[] parts = str.split("/");
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid service-binding URI: " + structuralURI);
}
names[1] = parts[0];
names[2] = parts[1];
} else if (str.startsWith("service(") && str.endsWith(")")) {
str = str.substring("service(".length(), str.length() - 1);
// [rfeng] Deal with empty service name
if (!"".equals(str)) {
names[1] = str;
}
} else {
throw new IllegalArgumentException("Invalid structural URI: " + structuralURI);
}
}
return names;
}
public boolean isAsyncInvocation() {
if (service != null && service.getName().endsWith("_asyncCallback")) {
// this is a response service at the reference component so don't create a
// response reference.
return false;
} // end if
for (Intent intent : getRequiredIntents()) {
if (intent.getName().getLocalPart().equals("asyncInvocation")) {
return true;
}
}
return false;
}
@Override
public String getDeployedURI() {
return deployedURI == null ? (binding == null ? null : binding.getURI()) : deployedURI;
}
@Override
public void setDeployedURI(String deployedURI) {
this.deployedURI = deployedURI;
}
@Override
public String getSpecVersion() {
return specVersion;
}
@Override
public void setSpecVersion(String specVersion){
this.specVersion = specVersion;
}
}
| 31.270186 | 109 | 0.615851 |
6a26c3689c0091bf7171506369fd88c203b98fa6 | 2,105 | /*
* Kimberly M. Praxel
* 11/06/16
* EUSalesTax.java
*/
package edu.greenriver.it.taxcalculators;
import java.util.*;
/**
* Creates sales tax for EU Customers
*
* @author kimberlypraxel
* @version 1.0
*/
public class EUSalesTax implements ISalesTax{
private String region;
/**
* creates a new EUSalesTax
*
* @param region - EU country
*/
public EUSalesTax(String region) {
this.region = region;
}
/**
* tax calculations based on country
*
* @param salesSubTotal
* @return calculated tax
*/
@Override
public double calculateTax(double salesSubTotal){
HashMap<String,Double> euTaxRates = new HashMap<String,Double>();
euTaxRates.put("austria", new Double(0.20));
euTaxRates.put("belgium", new Double(0.21));
euTaxRates.put("bulgaria", new Double(0.20));
euTaxRates.put("croatia", new Double(0.25));
euTaxRates.put("cyprus", new Double(0.19));
euTaxRates.put("czech republic", new Double(0.21));
euTaxRates.put("denmark", new Double(0.25));
euTaxRates.put("estonia", new Double(0.20));
euTaxRates.put("finland", new Double(0.24));
euTaxRates.put("france", new Double(0.20));
euTaxRates.put("germany", new Double(0.19));
euTaxRates.put("greece", new Double(0.24));
euTaxRates.put("hungary", new Double(0.27));
euTaxRates.put("ireland", new Double(0.23));
euTaxRates.put("italy", new Double(0.22));
euTaxRates.put("latvia", new Double(0.21));
euTaxRates.put("lithuania", new Double(0.21));
euTaxRates.put("luxembourg", new Double(0.17));
euTaxRates.put("malta", new Double(0.18));
euTaxRates.put("netherlands", new Double(0.21));
euTaxRates.put("poland", new Double(0.23));
euTaxRates.put("portugal", new Double(0.23));
euTaxRates.put("romania", new Double(0.20));
euTaxRates.put("slovakia", new Double(0.20));
euTaxRates.put("slovenia", new Double(0.22));
euTaxRates.put("spain", new Double(0.25));
euTaxRates.put("sweden", new Double(0.25));
euTaxRates.put("united kingdom", new Double(0.20));
double currentTaxRate = euTaxRates.get(region);
return salesSubTotal * currentTaxRate;
}
}
| 27.697368 | 68 | 0.682185 |
12b520fe0f8e81ce9cef52ccfedcaf8c24077ec7 | 796 | package com.alibaba.markovdemo.engine.stages;
import com.alibaba.fastjson.JSONObject;
public final class Utils {
public enum PrepareDataType {
Tair,
ScsIndex,
Tdbm,
KVfile,
TransMsg,
MetisData,
Imock,
Text,
ArtisMsg,
Mysql,
TreeIndex,
Conf,
Igraph,
IgraphDw,
//全量索引
Index,
//直通车sn需要
OrsMock,
//online
tt,
Swift,
IgraphOnline
}
public static String getValueOrEmptyString(JSONObject obj, String key){
String value = obj.getString(key);
return value == null? "":value;
}
public static boolean isEmptyStringOrNull(String str){
return str == null || str.isEmpty();
}
}
| 18.090909 | 75 | 0.542714 |
0894285d68208e7f5c1f8ae4ab2f6cf055ee6241 | 121 | package designPattern.memento;
/**
* @author Kevin
* @description
* @date 2017/2/23
*/
public interface Memento {
}
| 12.1 | 30 | 0.677686 |
77a7ea9ab259d0a83775f29f18259cfc6ddddbf7 | 1,189 | package dydeve.monitor.holder;
import dydeve.monitor.stat.MapStat;
import dydeve.monitor.stat.Tracer;
import org.springframework.core.NamedThreadLocal;
import java.util.Map;
import java.util.UUID;
/**
* threadLocal holder
* Created by dy on 2017/7/24.
*/
public class ThreadLocalHolder {
public static final ThreadLocal<Tracer<Map.Entry<String, Object>, String, MapStat>> TRACER = new NamedThreadLocal<Tracer<Map.Entry<String, Object>, String, MapStat>>("tracer threadLocal") {
@Override
protected Tracer<Map.Entry<String, Object>, String, MapStat> initialValue() {
return null;
}
};
/*@NotThreadSafe
public static final ThreadLocal<Stopwatch> STOP_WATCH = new NamedThreadLocal<Stopwatch>("stopWatch threadLocal") {
@Override
protected Stopwatch initialValue() {
return null;
}
};*/
//we don't return null because the interceptor may not in used
public static final ThreadLocal<String> TRACE_ID = new NamedThreadLocal<String>("traceId threadLocal") {
@Override
protected String initialValue() {
return UUID.randomUUID().toString();
}
};
}
| 29.725 | 193 | 0.679563 |
df9cc62934f6725e1f97b9fabdf4908f970015c4 | 636 | package com.sdut.threadtest;
//线程的强制执行,可以理解为找关系插队
public class ThreadTest10 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程VIP" + i);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadTest10 threadTest10 = new ThreadTest10();
Thread thread = new Thread(threadTest10);
thread.start();
//主线程,被插队
for (int i = 0; i < 500; i++) {
System.out.println("main" + i);
if ( i == 200){
thread.join();
}
}
}
}
| 24.461538 | 72 | 0.525157 |
8da15547fdd3c993dbe8ff3681242f586facf9fd | 1,996 | /*
* Copyright (c) 2020 TurnOnline.biz s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package biz.turnonline.ecosystem.widget.shared.rest.billing;
/**
* Identification of the bill (receipt) or invoice document settled by associated transaction. Valid invoice identification includes order identification too.
*/
public final class Bill
{
private Long id;
private Long invoice;
private Long order;
private Long receipt;
/**
* The unique identification of the bill within Billing Processor service.
*/
public Long getId()
{
return id;
}
public Bill setId( Long id )
{
this.id = id;
return this;
}
/**
* The invoice identification, unique only for specified order.
**/
public Long getInvoice()
{
return invoice;
}
public Bill setInvoice( Long invoice )
{
this.invoice = invoice;
return this;
}
/**
* The unique identification of the order associated with the invoice.
**/
public Long getOrder()
{
return order;
}
public Bill setOrder( Long order )
{
this.order = order;
return this;
}
/**
* The unique identification of the receipt within Product Billing service.
**/
public Long getReceipt()
{
return receipt;
}
public Bill setReceipt( Long receipt )
{
this.receipt = receipt;
return this;
}
}
| 22.426966 | 158 | 0.637776 |
5be243cef98adca46e3c2911e029136a15bd4914 | 918 | package cn.yueshutong.snowjenaticketserver.token;
import cn.yueshutong.commoon.entity.RateLimiterRule;
import cn.yueshutong.snowjenaticketserver.token.service.TokenService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TokenController {
@Autowired
private TokenService tokenService;
@RequestMapping(value = "/token",method = RequestMethod.POST)
public String token(@RequestParam("data") String rule){
RateLimiterRule rateLimiterRule = JSON.parseObject(rule, RateLimiterRule.class);
return JSON.toJSONString(tokenService.token(rateLimiterRule));
}
}
| 38.25 | 88 | 0.811547 |
03b0c2641996691657499baf30bcf78ea6a51733 | 1,542 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.v2016_09_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.appservice.v2016_09_01.implementation.ResourceMetricInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.appservice.v2016_09_01.implementation.AppServiceManager;
import org.joda.time.DateTime;
import java.util.List;
/**
* Type representing ServerfarmResourceMetric.
*/
public interface ServerfarmResourceMetric extends HasInner<ResourceMetricInner>, HasManager<AppServiceManager> {
/**
* @return the endTime value.
*/
DateTime endTime();
/**
* @return the id value.
*/
String id();
/**
* @return the metricValues value.
*/
List<ResourceMetricValue> metricValues();
/**
* @return the name value.
*/
ResourceMetricName name();
/**
* @return the properties value.
*/
List<ResourceMetricProperty> properties();
/**
* @return the resourceId value.
*/
String resourceId();
/**
* @return the startTime value.
*/
DateTime startTime();
/**
* @return the timeGrain value.
*/
String timeGrain();
/**
* @return the unit value.
*/
String unit();
}
| 22.676471 | 112 | 0.671855 |
d2e676a7ecbbb25e3fe5e2071e328658edf68964 | 10,590 | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.keyframes.model;
import android.graphics.Matrix;
import android.graphics.Paint;
import java.util.List;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedAnchorPoint;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedFillColor;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedOpacity;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedPath;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedStrokeColor;
import com.facebook.keyframes.model.keyframedmodels.KeyFramedStrokeWidth;
import com.facebook.keyframes.util.AnimationHelper;
import com.facebook.keyframes.util.ArgCheckUtil;
import com.facebook.keyframes.util.ListHelper;
/**
* An object which describes one feature layer to be drawn. This includes color, stroke, and
* animation information for just this feature. The shape is backed by a series of vector commands
* that describe how to draw the feature as a path.
*/
public class KFFeature {
/**
* The name of this feature, for ease of identification.
*/
public static final String NAME_JSON_FIELD = "name";
private final String mName;
/**
* The fill color to use for this feature.
*/
public static final String FILL_COLOR_JSON_FIELD = "fill_color";
private final int mFillColor;
/**
* The stroke color to use for this feature.
*/
public static final String STROKE_COLOR_JSON_FIELD = "stroke_color";
private final int mStrokeColor;
/**
* The width of the stroke used if tracing the path.
*/
public static final String STROKE_WIDTH_JSON_FIELD = "stroke_width";
private final float mStrokeWidth;
/**
* The frame that this feature stops showing up.
*/
public static final String FROM_FRAME_JSON_FIELD = "from_frame";
private final float mFromFrame;
/**
* The frame that this feature starts showing up.
*/
public static final String TO_FRAME_JSON_FIELD = "to_frame";
private final float mToFrame;
/**
* A list of {@link KFFeatureFrame}s which holds information about how the path of this
* feature changes throughout the duration of the animation.
*/
public static final String KEY_FRAMES_JSON_FIELD = "key_frames";
private final List<KFFeatureFrame> mKeyFrames;
/**
* Timing curves needed if mKeyFrames is present to describe how to animate between each key
* frame.
*/
public static final String TIMING_CURVES_JSON_FIELD = "timing_curves";
private final float[][][] mTimingCurves;
/**
* The animation layer that this feature belongs to. The final animation matrix of the group will
* be applied to this feature, and any animations belonging to the feature will be nested within
* this group.
*/
public static final String ANIMATION_GROUP_JSON_FIELD = "animation_group";
private final int mAnimationGroup;
/**
* The cap the use at the ends of stroke lines.
*/
public static final String STROKE_LINE_CAP_JSON_FIELD = "stroke_line_cap";
private final Paint.Cap mStrokeLineCap;
/**
* Masking layer that can be used for this feature.
*/
public static final String FEATURE_MASK_JSON_FIELD = "masking";
private final KFFeature mFeatureMask;
/**
* A list of animations to apply to just this feature layer.
*/
public static final String FEATURE_ANIMATIONS_JSON_FIELD = "feature_animations";
/**
* A KFAnimation just for the special cased stroke width animation. Package private for testing.
*/
final KFAnimation mStrokeWidthAnimation;
/**
* The remaining, matrix based animations from the feature_animations set.
* Package private for testing.
*/
final List<KFAnimation> mFeatureMatrixAnimations;
/**
* The anchor point for all animations in this feature.
*/
final KFAnimation mAnchorPoint;
/**
* The opacity for this feature.
*/
private final KFAnimation mOpacityAnimation;
/**
* A KFAnimation just for the special cased stroke color animation. Package private for testing.
*/
final KFAnimation mStrokeColorAnimation;
/**
* A KFAnimation just for the special cased fill color animation. Package private for testing.
*/
final KFAnimation mFillColorAnimation;
/**
* An optional effect that this feature layer can have.
* Currently, only a simple linear gradient is supported.
*/
public static final String EFFECT_JSON_FIELD = "effects";
private final KFFeatureEffect mEffect;
/**
* EXPERIMENTAL optional "backedImage" name used to refer the bitmap name backing the feature.
*/
public static final String BACKED_IMAGE_NAME_JSON_FIELD = "backed_image";
private final String mBackedImageName;
/**
* A post-processed object containing cached information for this path, if keyframed.
*/
private final KeyFramedPath mKeyFramedPath;
public static class Builder {
public String name;
public int fillColor;
public int strokeColor;
public float strokeWidth;
public float fromFrame = 0;
public float toFrame = Float.MAX_VALUE;
public List<KFFeatureFrame> keyFrames;
public float[][][] timingCurves;
public int animationGroup;
public Paint.Cap strokeLineCap = Paint.Cap.ROUND;
public KFFeature featureMask;
public List<KFAnimation> featureAnimations;
public float[] anchorPoint;
public KFFeatureEffect effect;
public String backedImageName;
public KFFeature build() {
return new KFFeature(
name,
fillColor,
strokeColor,
strokeWidth,
fromFrame,
toFrame,
keyFrames,
timingCurves,
animationGroup,
strokeLineCap,
featureMask,
featureAnimations,
anchorPoint,
effect,
backedImageName);
}
}
public KFFeature(
String name,
int fillColor,
int strokeColor,
float strokeWidth,
float fromFrame,
float toFrame,
List<KFFeatureFrame> keyFrames,
float[][][] timingCurves,
int animationGroup,
Paint.Cap strokeLineCap,
KFFeature featureMask,
List<KFAnimation> featureAnimations,
float[] anchorPoint,
KFFeatureEffect effect,
String backedImageName) {
mName = name;
mFillColor = fillColor;
mStrokeColor = strokeColor;
mStrokeWidth = strokeWidth;
mFromFrame = fromFrame;
mToFrame = toFrame;
mKeyFrames = ListHelper.immutableOrEmpty(keyFrames);
mTimingCurves = ArgCheckUtil.checkArg(
timingCurves,
ArgCheckUtil.checkTimingCurveObjectValidity(timingCurves, mKeyFrames.size()),
TIMING_CURVES_JSON_FIELD);
mAnimationGroup = animationGroup;
mStrokeLineCap = strokeLineCap;
mFeatureMask = featureMask;
mStrokeWidthAnimation = AnimationHelper.extractSpecialAnimationAnimationSet(
featureAnimations,
KFAnimation.PropertyType.STROKE_WIDTH);
mStrokeColorAnimation = AnimationHelper.extractSpecialAnimationAnimationSet(
featureAnimations,
KFAnimation.PropertyType.STROKE_COLOR);
mFillColorAnimation = AnimationHelper.extractSpecialAnimationAnimationSet(
featureAnimations,
KFAnimation.PropertyType.FILL_COLOR);
mAnchorPoint = AnimationHelper.extractSpecialAnimationAnimationSet(
featureAnimations,
KFAnimation.PropertyType.ANCHOR_POINT);
mOpacityAnimation = AnimationHelper.extractSpecialAnimationAnimationSet(
featureAnimations,
KFAnimation.PropertyType.OPACITY);
ListHelper.sort(featureAnimations, KFAnimation.ANIMATION_PROPERTY_COMPARATOR);
mFeatureMatrixAnimations = ListHelper.immutableOrEmpty(featureAnimations);
mEffect = effect;
mBackedImageName = backedImageName;
mKeyFramedPath = mKeyFrames.isEmpty() ? null : KeyFramedPath.fromFeature(this);
}
public String getName() {
return mName;
}
public int getFillColor() {
return mFillColor;
}
public int getStrokeColor() {
return mStrokeColor;
}
public float getFromFrame() {
return mFromFrame;
}
public float getToFrame() {
return mToFrame;
}
public List<KFFeatureFrame> getKeyFrames() {
return mKeyFrames;
}
public float[][][] getTimingCurves() {
return mTimingCurves;
}
public KeyFramedPath getPath() {
return mKeyFramedPath;
}
public int getAnimationGroup() {
return mAnimationGroup;
}
public Paint.Cap getStrokeLineCap() {
return mStrokeLineCap;
}
public KFFeature getFeatureMask() {
return mFeatureMask;
}
public void setStrokeWidth(
KeyFramedStrokeWidth.StrokeWidth strokeWidth,
float frameProgress) {
if (strokeWidth == null) {
return;
}
strokeWidth.setStrokeWidth(mStrokeWidth);
if (mStrokeWidthAnimation == null) {
return;
}
mStrokeWidthAnimation.getAnimation().apply(frameProgress, strokeWidth);
}
public void setStrokeColor(
KeyFramedStrokeColor.StrokeColor strokeColor,
float frameProgress) {
if (strokeColor == null || mStrokeColorAnimation == null) {
return;
}
mStrokeColorAnimation.getAnimation().apply(frameProgress, strokeColor);
}
public void setFillColor(
KeyFramedFillColor.FillColor fillColor,
float frameProgress) {
if (fillColor == null || mFillColorAnimation == null) {
return;
}
mFillColorAnimation.getAnimation().apply(frameProgress, fillColor);
}
public void setOpacity(
KeyFramedOpacity.Opacity opacity,
float frameProgress) {
if (opacity == null || mOpacityAnimation == null) {
return;
}
mOpacityAnimation.getAnimation().apply(frameProgress, opacity);
}
public void setAnimationMatrix(Matrix featureMatrix, float frameProgress) {
if (featureMatrix == null) {
return;
}
featureMatrix.reset();
if (mFeatureMatrixAnimations == null) {
return;
}
if (mAnchorPoint != null) {
mAnchorPoint.getAnimation().apply(frameProgress, featureMatrix);
}
for (int i = 0, len = mFeatureMatrixAnimations.size(); i < len; i++) {
mFeatureMatrixAnimations.get(i).getAnimation().apply(frameProgress, featureMatrix);
}
}
public KFFeatureEffect getEffect() {
return mEffect;
}
public String getBackedImageName() {
return mBackedImageName;
}
}
| 30.17094 | 100 | 0.715581 |
ea66e028338d4845379b3a43067a81c7f1ea6482 | 3,246 | package ganymede.server;
/*-
* ##########################################################################
* Ganymede
* %%
* Copyright (C) 2021 Allen D. Ball
* %%
* 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.
* ##########################################################################
*/
import java.math.BigInteger;
import java.util.stream.Stream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.zeromq.ZMQ;
/**
* HMAC message digester. See discussion in
* {@link.uri https://jupyter-client.readthedocs.io/en/latest/messaging.html#the-wire-protocol target=newtab The Wire Protocol}.
*
* {@bean.info}
*
* @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
*/
@Data @Log4j2
public class HMACDigester {
private final Mac mac;
/**
* Sole constructor.
*
* @param scheme The signature scheme.
* @param key See key.
*/
public HMACDigester(String scheme, String key) {
Mac mac = null;
if (key != null && (! key.isEmpty())) {
try {
mac = Mac.getInstance(scheme.replaceAll("-", ""));
mac.init(new SecretKeySpec(key.getBytes(ZMQ.CHARSET), scheme));
} catch (Exception exception) {
throw new ExceptionInInitializerError(exception);
}
}
this.mac = mac;
}
/**
* Method to calculate a digest for message frames. See
* {@link Mac#update(byte[])} and {@link Mac#doFinal()}.
*
* @param frames The {@code byte[]} frames of the message to
* digest.
*
* @return The digest {@link String}.
*/
public String digest(byte[]... frames) {
String digest = "";
if (mac != null) {
synchronized (mac) {
Stream.of(frames).forEach(mac::update);
var bytes = mac.doFinal();
digest = new BigInteger(1, bytes).toString(16);
}
var length = 2 * mac.getMacLength();
while (digest.length() < length) {
digest = "0" + digest;
}
}
return digest;
}
/**
* Method to verify a digest for message frames.
*
* @param digest The digest to verify.
* @param frames The {@code byte[]} frames of the message to
* digest.
*
* @return {@code true} if the argument digest matches the one
* calculated; {@code false} otherwise.
*/
public boolean verify(String digest, byte[]... frames) {
return digest.equals(digest(frames));
}
}
| 30.336449 | 128 | 0.550216 |
2225c2b39758c3db11aca912b1b3067f486b06d3 | 17,610 | package com.nedap.archie.flattener;
import com.nedap.archie.aom.*;
import com.nedap.archie.aom.utils.AOMUtils;
import com.nedap.archie.base.MultiplicityInterval;
import com.nedap.archie.paths.PathSegment;
import com.nedap.archie.paths.PathUtil;
import com.nedap.archie.query.AOMPathQuery;
import com.nedap.archie.query.APathQuery;
import com.nedap.archie.query.ComplexObjectProxyReplacement;
import com.nedap.archie.rminfo.RMAttributeInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Flattens attributes, taking sibling order into account.
*/
public class CAttributeFlattener {
private final IAttributeFlattenerSupport flattener;
public CAttributeFlattener(IAttributeFlattenerSupport flattener) {
this.flattener = flattener;
}
public void flattenSingleAttribute(CComplexObject newObject, CAttribute attribute) {
if(attribute.getDifferentialPath() != null) {
//this overrides a specific path
ArchetypeModelObject object = new AOMPathQuery(attribute.getDifferentialPath()).dontFindThroughCComplexObjectProxies().find(newObject);
if(object == null) {
//it is possible that the object points to a reference, in which case we need to clone the referenced node, then try again
//AOM spec paragraph 7.2: 'proxy reference targets are expanded inline if the child archetype overrides them.'
//also examples in ADL2 spec about internal references
//so find the internal references here!
//TODO: AOMUtils.pathAtSpecializationLevel(pathSegments.subList(0, pathSegments.size()-1), flatParent.specializationDepth());
CComplexObjectProxy internalReference = new AOMPathQuery(attribute.getDifferentialPath()).findAnyInternalReference(newObject);
if(internalReference != null) {
//in theory this can be a use node within a use node.
ComplexObjectProxyReplacement complexObjectProxyReplacement =
ComplexObjectProxyReplacement.getComplexObjectProxyReplacement(internalReference);
if(complexObjectProxyReplacement != null) {
complexObjectProxyReplacement.replace();
//and again!
flattenSingleAttribute(newObject, attribute);
} else {
throw new RuntimeException("cannot find target in CComplexObjectProxy");
}
} else {
//lookup the parent and try to add the last attribute if it does not exist
List<PathSegment> pathSegments = new APathQuery(attribute.getDifferentialPath()).getPathSegments();
String pathMinusLastNode = PathUtil.getPath(pathSegments.subList(0, pathSegments.size()-1));
CObject parentObject = newObject.itemAtPath(pathMinusLastNode);
if(parentObject != null && parentObject instanceof CComplexObject) {
//attribute does not exist, but does exist in RM (or it would not have passed the ArchetypeValidator, or the person using
//this flattener does not care
CAttribute realAttribute = new CAttribute(pathSegments.get(pathSegments.size()-1).getNodeName());
((CComplexObject) parentObject).addAttribute(realAttribute);
flattenAttribute(newObject, realAttribute, attribute);
}
}
}
else if(object instanceof CAttribute) {
CAttribute realAttribute = (CAttribute) object;
flattenAttribute(newObject, realAttribute, attribute);
} else if (object instanceof CObject) {
//TODO: what does this mean?
}
} else {
//this overrides the same path
flattenAttribute(newObject, newObject.getAttribute(attribute.getRmAttributeName()), attribute);
}
}
public CAttribute flattenAttribute(CComplexObject root, CAttribute attributeInParent, CAttribute attributeInSpecialization) {
if(attributeInParent == null) {
CAttribute childCloned = attributeInSpecialization.clone();
root.addAttribute(childCloned);
return childCloned;
} else {
attributeInParent.setExistence(FlattenerUtil.getPossiblyOverridenValue(attributeInParent.getExistence(), attributeInSpecialization.getExistence()));
attributeInParent.setCardinality(FlattenerUtil.getPossiblyOverridenValue(attributeInParent.getCardinality(), attributeInSpecialization.getCardinality()));
if (attributeInSpecialization.getChildren().size() > 0 && attributeInSpecialization.getChildren().get(0) instanceof CPrimitiveObject) {
//in case of a primitive object, just replace all nodes
attributeInParent.setChildren(attributeInSpecialization.getChildren());
} else {
//ordering the children correctly is tricky.
// First reorder parentCObjects if necessary, in the case that a sibling order refers to a redefined node
// in the attributeInSpecialization archetype
reorderSiblingOrdersReferringToSameLevel(attributeInSpecialization);
//Now maintain an insertion anchor
//for when a sibling node has been set somewhere.
// insert everything after/before the anchor if it is set,
// at the defined position from the spec if it is null
SiblingOrder anchor = null;
List<CObject> parentCObjects = attributeInParent.getChildren();
for (CObject specializedChildCObject : attributeInSpecialization.getChildren()) {
//find matching attributeInParent and create the child node with it
CObject matchingParentObject = findMatchingParentCObject(specializedChildCObject, parentCObjects);
if(specializedChildCObject.getSiblingOrder() != null) {
//new sibling order, update the anchor
anchor = specializedChildCObject.getSiblingOrder();
}
if (anchor != null) {
mergeObjectIntoAttribute(attributeInParent, specializedChildCObject, matchingParentObject, attributeInSpecialization.getChildren(), anchor);
anchor = nextAnchor(anchor, specializedChildCObject);
} else { //no sibling order, apply default rules
//add to end
CObject specializedObject = flattener.createSpecializeCObject(attributeInParent, matchingParentObject, specializedChildCObject);
if(matchingParentObject == null) {
//extension nodes should be added to the last position
attributeInParent.addChild(specializedObject);
} else {
attributeInParent.addChild(specializedObject, SiblingOrder.createAfter(findLastSpecializedChildDirectlyAfter(attributeInParent, matchingParentObject)));
if(shouldRemoveParent(specializedChildCObject, matchingParentObject, attributeInSpecialization.getChildren())) {
attributeInParent.removeChild(matchingParentObject.getNodeId());
}
}
}
}
}
return attributeInParent;
}
}
/**
* Given the last used siblingorder anchor and the last specialized object added, return the SiblingOrder where the
* next specialized object should be added - if that next object does not have a new sibling order
* @param lastAnchor
* @param lastSpecializedObject
* @return
*/
private SiblingOrder nextAnchor(SiblingOrder lastAnchor, CObject lastSpecializedObject) {
if(lastAnchor.isBefore()) {
return lastAnchor;
} else {
return SiblingOrder.createAfter(lastSpecializedObject.getNodeId());
}
}
/**
* Add the specializedChildObject to the parentAttribute at the given siblingOrder. This method automatically checks if the matchingParentObject should be removed, and removes it if necessary.
*
* @param parentAttribute the attribute to add the new object to
* @param specializedChildCObject the specialized object that should be merged into the parent object
* @param matchingParentObject the matching parent CObject for the given specializedChildObject
* @param allSpecializedChildren all the specialized children in the same container as specialedChildCObject
* @param siblingOrder the sibling order where to add the specializedChild to. Directly adds, no preprocessing or anchor support in this method, you must do that before.
*/
private void mergeObjectIntoAttribute(CAttribute parentAttribute, CObject specializedChildCObject, CObject matchingParentObject, List<CObject> allSpecializedChildren, SiblingOrder siblingOrder) {
CObject specializedObject = flattener.createSpecializeCObject(parentAttribute, matchingParentObject, specializedChildCObject);
if (shouldRemoveParent(specializedChildCObject, matchingParentObject, allSpecializedChildren)) {
parentAttribute.removeChild(matchingParentObject.getNodeId());
}
parentAttribute.addChild(specializedObject, siblingOrder);
}
/**
* If the following occurs:
*
* after[id3]
* ELEMENT[id2]
* ELEMENT[id3.1]
*
* Reorder it and remove sibling orders:
*
* ELEMENT[id3.1]
* ELEMENT[id2]
*
* If sibling order do not refer to specialized nodes at this level, leaves them alone
* @param parent the attribute to reorder the child nodes for
*/
private void reorderSiblingOrdersReferringToSameLevel(CAttribute parent) {
for(CObject cObject:new ArrayList<>(parent.getChildren())) {
if(cObject.getSiblingOrder() != null) {
String matchingNodeId = findCObjectMatchingSiblingOrder(cObject.getSiblingOrder(), parent.getChildren());
if(matchingNodeId != null) {
parent.removeChild(cObject.getNodeId());
SiblingOrder siblingOrder = new SiblingOrder();
siblingOrder.setSiblingNodeId(matchingNodeId);
siblingOrder.setBefore(cObject.getSiblingOrder().isBefore());
parent.addChild(cObject, siblingOrder);
cObject.setSiblingOrder(null);//unset sibling order, it has been processed already
}
}
}
}
/**
* Find the CObject in the given list of cObjects that matches with the given sibling order
* @param siblingOrder
* @param cObjectList
* @return
*/
private String findCObjectMatchingSiblingOrder(SiblingOrder siblingOrder, List<CObject> cObjectList) {
for(CObject object:cObjectList) {
if(AOMUtils.isOverriddenIdCode(object.getNodeId(), siblingOrder.getSiblingNodeId())) {
return object.getNodeId();
}
}
return null;
}
/**
* Give an attribute and a CObject that is a child of that attribute, find the node id of the last object that is
* in the list of nodes directly after the child attribute that specialize the matching parent. If the parent
* has not yet been specialized, returns the parent node id
*
* @param parent
* @param matchingParentObject
* @return
*/
private String findLastSpecializedChildDirectlyAfter(CAttribute parent, CObject matchingParentObject) {
int matchingIndex = parent.getIndexOfChildWithNodeId(matchingParentObject.getNodeId());
String result = matchingParentObject.getNodeId();
for(int i = matchingIndex+1; i < parent.getChildren().size(); i++) {
if(AOMUtils.isOverriddenIdCode(parent.getChildren().get(i).getNodeId(), matchingParentObject.getNodeId())) {
result = parent.getChildren().get(i).getNodeId();
}
}
return result;
}
/**
* For the given specialized CObject that is to be added to the archetype, specializing matchingParentObject, and given
* the list of all specialized children of the same container as the given specialized cobject, return if the parent
* should be removed from the resulting list of flattened CObjects after inserting the specialized check or not.
*
*
* @param specializedChildCObject the specialized child object that is to be added
* @param matchingParentObject the CObject that matches with the specializedChildObject. Can be null.
* @param allSpecializedChildren all specialized children under the specializing child container
* @return
*/
private boolean shouldRemoveParent(CObject specializedChildCObject, CObject matchingParentObject, List<CObject> allSpecializedChildren) {
if(matchingParentObject == null) {
return false;
}
List<CObject> allMatchingChildren = new ArrayList<>();
for (CObject specializedChild : allSpecializedChildren) {
if (AOMUtils.isOverridenCObject(specializedChild, matchingParentObject)) {
allMatchingChildren.add(specializedChild);
}
}
boolean hasSameNodeIdInMatchingChildren = allMatchingChildren.stream().anyMatch(c -> c.getNodeId().equals(matchingParentObject.getNodeId()));
if(hasSameNodeIdInMatchingChildren) {
//if parent contains id2, and child as well, replace the exact same node with the exact child. Otherwise,
//add children and replace the last child.
return specializedChildCObject.getNodeId().equalsIgnoreCase(matchingParentObject.getNodeId());
} else if(allMatchingChildren.get(allMatchingChildren.size()-1).getNodeId().equalsIgnoreCase(specializedChildCObject.getNodeId())) {
//the last matching child should possibly replace the parent, the rest should just add
//if there is just one child, that's fine, it should still work
return shouldReplaceSpecializedParent(matchingParentObject, allMatchingChildren);
}
return false;
}
private boolean shouldReplaceSpecializedParent(CObject parent, List<CObject> differentialNodes) {
MultiplicityInterval occurrences = parent.effectiveOccurrences(flattener.getMetaModels()::referenceModelPropMultiplicity);
//isSingle/isMultiple is tricky and not doable just in the parser. Don't use those
if(isSingle(parent.getParent())) {
return true;
} else if(occurrences != null && occurrences.upperIsOne()) {
//REFINE the parent node case 1, the parent has occurrences upper == 1
return true;
} else if (differentialNodes.size() == 1) {
MultiplicityInterval effectiveOccurrences;
//the differentialNode can have a differential path instead of an attribute name. In that case, we need to replace the rm type name
//of the parent with the actual typename in the parent archetype. Otherwise, it may fall back to the default type in the RM,
//and that can be an abstract type that does not have the attribute that we are trying to constrain. For example:
//diff archetype:
// /events[id6]/data/items matches {
//in the rm, data maps to an ITEM_STRUCTURE that does not have the attribute items.
//in the parent archetype, that is then an ITEM_TREE. We need to use ITEM_TREE here, which is what this code accomplishes.
if(parent.getParent() == null || parent.getParent().getParent() == null) {
effectiveOccurrences = differentialNodes.get(0).effectiveOccurrences(flattener.getMetaModels()::referenceModelPropMultiplicity);
} else {
effectiveOccurrences = differentialNodes.get(0).effectiveOccurrences((s, s2) -> flattener.getMetaModels().referenceModelPropMultiplicity(
parent.getParent().getParent().getRmTypeName(), parent.getParent().getRmAttributeName()));
}
if(effectiveOccurrences != null && effectiveOccurrences.upperIsOne()) {
//REFINE the parent node case 2, only one child with occurrences upper == 1
return true;
}
}
return false;
}
private boolean isSingle(CAttribute attribute) {
if(attribute != null && attribute.getParent() != null && attribute.getDifferentialPath() == null) {
return !flattener.getMetaModels().isMultiple(attribute.getParent().getRmTypeName(), attribute.getRmAttributeName());
}
return false;
}
/**
* Find the matching parent CObject given a specialized child. REturns null if not found.
* @param specializedChildCObject
* @param parentCObjects
* @return
*/
private CObject findMatchingParentCObject(CObject specializedChildCObject, List<CObject> parentCObjects) {
for (CObject parentCObject : parentCObjects) {
if (AOMUtils.isOverridenCObject(specializedChildCObject, parentCObject)) {
return parentCObject;
}
}
return null;
}
}
| 53.525836 | 199 | 0.662862 |
faf21af037296962cc26c25610b4f7be085cb9a3 | 8,034 | package com.intellij.jira.ui.dialog;
import com.intellij.jira.server.JiraServer;
import com.intellij.jira.server.JiraServerManager;
import com.intellij.jira.server.editor.JiraServerEditor;
import com.intellij.jira.tasks.RefreshIssuesTask;
import com.intellij.jira.ui.panels.JiraPanel;
import com.intellij.jira.util.JiraPanelUtil;
import com.intellij.jira.util.SimpleSelectableList;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.JBSplitter;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.ui.JBUI;
import icons.TasksCoreIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import static java.util.Objects.nonNull;
public class ConfigureJiraServersDialog extends DialogWrapper {
private static final JPanel EMPTY_PANEL = JiraPanelUtil.createPlaceHolderPanel("No server selected.").withMinimumWidth(450).withMinimumHeight(100);
private static final String EMPTY_PANEL_NAME = "empty.panel";
private final Project myProject;
private final JiraServerManager myManager;
private SimpleSelectableList<JiraServer> myServers;
private JBList<JiraServer> myServersList;
private List<JiraServerEditor> myEditors = new ArrayList<>();
private JPanel myJiraServerEditor;
private Splitter mySplitter;
private int count;
private final Map<JiraServer, String> myServerNames = ConcurrentFactoryMap.createMap(server -> Integer.toString(count++));
private BiConsumer<JiraServer, Boolean> myChangeListener;
private Consumer<JiraServer> myChangeUrlListener;
public ConfigureJiraServersDialog(@NotNull Project project) {
super(project, false);
this.myProject = project;
this.myManager = JiraServerManager.getInstance(project);
init();
}
@Override
protected void init() {
myJiraServerEditor = new JPanel(new CardLayout());
myJiraServerEditor.add(EMPTY_PANEL, EMPTY_PANEL_NAME);
myServers = new SimpleSelectableList<>();
CollectionListModel listModel = new CollectionListModel(new ArrayList());
for(JiraServer server : myManager.getJiraServers()){
JiraServer clone = server.clone();
listModel.add(clone);
myServers.add(clone);
}
myServers.selectItem(myManager.getSelectedJiraServerIndex());
this.myChangeListener = (server, selected) -> myServers.updateSelectedItem(server, selected);
this.myChangeUrlListener = (server) -> ((CollectionListModel)myServersList.getModel()).contentsChanged(server);
for(int i = 0; i < myServers.getItems().size(); i++){
addJiraServerEditor(myServers.getItems().get(i), i == myManager.getSelectedJiraServerIndex());
}
myServersList = new JBList();
myServersList.setEmptyText("No servers");
myServersList.setModel(listModel);
myServersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myServersList.addListSelectionListener(e -> {
JiraServer selectedServer = getSelectedServer();
if(nonNull(selectedServer)) {
String name = myServerNames.get(selectedServer);
updateEditorPanel(name);
}
});
myServersList.setCellRenderer(new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) {
JiraServer server = (JiraServer)value;
setIcon(TasksCoreIcons.Jira);
append(server.getPresentableName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
});
setTitle("Configure Servers");
super.init();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
mySplitter = new JBSplitter(true, 0.6f);
mySplitter.setFirstComponent(createServersPanel());
mySplitter.setSecondComponent(createDetailsServerPanel());
return mySplitter;
}
@NotNull
@Override
protected List<ValidationInfo> doValidateAll() {
List<ValidationInfo> validationInfos = new ArrayList<>();
for (JiraServerEditor editor : myEditors) {
ValidationInfo info = editor.validate();
if (Objects.nonNull(info)) {
validationInfos.add(info);
}
}
return validationInfos;
}
@Override
protected void doOKAction() {
myManager.setJiraServers(myServers);
updateIssues();
super.doOKAction();
}
private JComponent createServersPanel() {
if(myServers.hasSelectedItem()){
myServersList.setSelectedValue(myServers.getSelectedItem(), true);
}
JPanel myPanel = new JiraPanel(new BorderLayout());
myPanel.setMinimumSize(JBUI.size(-1, 200));
myPanel.add(ToolbarDecorator.createDecorator(myServersList)
.setAddAction(button -> {
addJiraServer();
})
.setRemoveAction(button -> {
if (Messages.showOkCancelDialog(myProject, "You are going to delete this server, are you sure?","Delete Server", Messages.getOkButton(), Messages.getCancelButton(), Messages.getQuestionIcon()) == Messages.OK) {
removeJiraServer();
}
})
.disableUpDownActions().createPanel(), BorderLayout.CENTER);
return myPanel;
}
private void addJiraServer(){
JiraServer server = new JiraServer();
myServers.add(server);
((CollectionListModel) myServersList.getModel()).add(server);
addJiraServerEditor(server, false);
myServersList.setSelectedIndex(myServersList.getModel().getSize() - 1);
}
private void addJiraServerEditor(JiraServer server, boolean selected){
JiraServerEditor editor = new JiraServerEditor(myProject, server, selected, myChangeListener, myChangeUrlListener);
myEditors.add(editor);
String name = myServerNames.get(server);
myJiraServerEditor.add(editor.getPanel(), name);
myJiraServerEditor.doLayout();
}
private void removeJiraServer(){
int selectedServer = myServersList.getSelectedIndex();
if(selectedServer > -1){
((CollectionListModel) myServersList.getModel()).remove(selectedServer);
myServers.remove(selectedServer);
myServersList.setSelectedIndex(myServers.getSelectedItemIndex());
}
if(myServers.isEmpty()){
updateEditorPanel(EMPTY_PANEL_NAME);
}
}
private void updateEditorPanel(String name){
((CardLayout) myJiraServerEditor.getLayout()).show(myJiraServerEditor, name);
mySplitter.doLayout();
mySplitter.repaint();
}
private void updateIssues(){
new RefreshIssuesTask(myProject).queue();
}
private JComponent createDetailsServerPanel() {
return myJiraServerEditor;
}
@Nullable
private JiraServer getSelectedServer(){
return myServersList.getSelectedValue();
}
}
| 34.930435 | 238 | 0.682848 |
292093c87043da903071c17bfd9bd20081140af6 | 2,505 | package com.gearservice.model.authorization;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Class User is model Entity, that store in database and consists user's data.
* Has many-to-many relationship with Authority entity.
*
* @version 1.1
* @author Dmitry
* @since 21.01.2016
*/
@Entity
public class User {
@Id private String username;
@JsonIgnore private String password;
@Transient @JsonProperty private String newPassword;
@Transient @JsonProperty private String adminPassword;
private boolean enabled;
private String fullname;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
@JoinTable(
name = "user_authorities",
joinColumns = @JoinColumn(name = "username"),
inverseJoinColumns = @JoinColumn(name = "authority"))
private Set<Authority> authorities = new HashSet<>();
public User() {}
public User(User user) {
super();
this.username = user.getUsername();
this.fullname = user.getFullname();
this.password = user.getPassword();
this.enabled = user.isEnabled();
this.authorities = user.getAuthorities();
}
public User(String username, String newPassword, boolean enabled, String fullname, Set<Authority> authorities) {
this.username = username;
this.newPassword = newPassword;
this.enabled = enabled;
this.fullname = fullname;
this.authorities = authorities;
}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
public String getNewPassword() {return newPassword;}
public void setNewPassword(String newPassword) {this.newPassword = newPassword;}
public boolean isEnabled() {return enabled;}
public void setEnabled(boolean enabled) {this.enabled = enabled;}
public String getFullname() {return fullname;}
public void setFullname(String fullname) {this.fullname = fullname;}
public Set<Authority> getAuthorities() {return authorities;}
public void setAuthorities(Set<Authority> authorities) {this.authorities = authorities;}
public String getAdminPassword() {return adminPassword;}
public void setAdminPassword(String adminPassword) {this.adminPassword = adminPassword;}
}
| 36.304348 | 116 | 0.705389 |
499da560d68328560640773c38e7908bd124721d | 6,212 | package com.nirvana.springreactorexample.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.nirvana.springreactorexample.model.Profile;
import com.nirvana.springreactorexample.repository.SalaryRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
import java.util.List;
import static com.nirvana.springreactorexample.service.ProfileServiceImpl.convertToQueryString;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EmployeeControllerIntegrationTest {
private WireMockServer server;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private WebTestClient webTestClient;
@Autowired
private SalaryRepository salaryRepository;
@BeforeEach
public void init() {
// Port 8181 is configured for profile service in application.properties for tests.
server = new WireMockServer(WireMockConfiguration.options().port(8181));
server.start();
}
@AfterEach
public void end() {
server.stop();
}
@Test
public void shouldReturnStatusOkForGetEmployeeById() throws Exception {
String employeeId = "1";
server.stubFor(WireMock.get("/profiles/" + employeeId)
.willReturn(WireMock.okJson(objectMapper.writeValueAsString(Profile.builder().id(employeeId).name("James")
.mobile("0987432").build()))));
webTestClient.get().uri("/employees/" + employeeId)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk();
}
@Test
public void shouldReturnEmployeeDetailsWithSalaryInResponseBodyForGetEmployeeById() throws Exception {
String employeeId = "1";
server.stubFor(WireMock.get("/profiles/" + employeeId)
.willReturn(WireMock.okJson(objectMapper.writeValueAsString(Profile.builder().id(employeeId).name("James")
.mobile("0987432").build()))));
webTestClient.get().uri("/employees/" + employeeId)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectBody()
.jsonPath("$.name").isEqualTo("James")
.jsonPath("$.id").isEqualTo(employeeId)
.jsonPath("$.salary").isEqualTo(20000.50);
}
@Test
public void shouldReturnStatusNotFoundProvidedSalaryNotFoundForEmployee() throws Exception {
String employeeId = "12345";
server.stubFor(WireMock.get("/profiles/" + employeeId)
.willReturn(WireMock.okJson(objectMapper.writeValueAsString(Profile.builder().id(employeeId).name("James")
.mobile("0987432").build()))));
webTestClient.get().uri("/employees/" + employeeId)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isNotFound();
}
@Test
public void shouldReturnStatusNotFoundProvidedProfileNotFoundForEmployee() throws Exception {
String employeeId = "1";
server.stubFor(WireMock.get("/profiles/" + employeeId)
.willReturn(WireMock.notFound()));
webTestClient.get().uri("/employees/" + employeeId)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isNotFound();
}
@Test
public void shouldReturnStatusOkForGetAllEmployees() throws Exception {
var employeeIds = List.of("1", "2", "3");
server.stubFor(WireMock.get("/profiles?" + convertToQueryString(employeeIds))
.willReturn(WireMock.okJson(objectMapper.writeValueAsString(List.of(
Profile.builder().id("1").name("James").mobile("0987432").build(),
Profile.builder().id("2").name("Pankaj").mobile("0987431").build(),
Profile.builder().id("3").name("Yadav").mobile("0987430").build()
)))));
webTestClient.get().uri("/employees?" + convertToQueryString(employeeIds))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk();
}
@Test
public void shouldReturnEmployeesDetailsWithSalaryInResponseBodyForGetAllEmployees() throws Exception {
var employeeIds = List.of("1", "2", "3");
server.stubFor(WireMock.get("/profiles?" + convertToQueryString(employeeIds))
.willReturn(WireMock.okJson(objectMapper.writeValueAsString(List.of(
Profile.builder().id("1").name("James").mobile("0987432").build(),
Profile.builder().id("2").name("Pankaj").mobile("0987431").build(),
Profile.builder().id("3").name("Yadav").mobile("0987430").build()
)))));
webTestClient.get().uri("/employees?" + convertToQueryString(employeeIds))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$[0].name").isEqualTo("James")
.jsonPath("$[1].name").isEqualTo("Pankaj")
.jsonPath("$[2].name").isEqualTo("Yadav")
.jsonPath("$[0].id").isEqualTo("1")
.jsonPath("$[1].id").isEqualTo("2")
.jsonPath("$[2].id").isEqualTo("3")
.jsonPath("$[0].salary").isEqualTo(20000.50)
.jsonPath("$[1].salary").isEqualTo(30000.50)
.jsonPath("$[2].salary").isEqualTo(40000.50);
}
}
| 42.258503 | 122 | 0.635705 |
f88211a8905cad94fa5a7f0d3ddcb9059e8af41c | 2,477 | package parsley.commands.core;
import parsley.commands.Command;
import parsley.lexing.*;
import parsley.model.*;
import parsley.runtime.*;
import parsley.values.*;
import java.util.*;
public class CallCommand extends Command {
protected String name;
protected Stack parameters;
protected Hashtable arguments;
public CallCommand(Tokens tokens) {
this();
initWithTokens(tokens);
}
public CallCommand() {
parameters = new Stack();
arguments = new Hashtable();
}
public Command initWithTokens(Tokens tokens) {
parameters.clear();
arguments.clear();
setName(tokens.nextToken());
setParameters(tokens);
return this;
}
protected void setName(String token) throws IllegalArgumentException {
if (isName(token)) {
name = new String(token);
} else {
throw new IllegalArgumentException(token);
}
}
protected void setParameters(Tokens tokens) {
String previous = null, current = null;
while (tokens.hasMoreTokens()) {
current = tokens.nextToken();
if (isParameter(current)) {
setParameter(current);
} else if (isParameter(previous)) {
setArgument(previous, current);
} else {
throw new IllegalArgumentException(current);
}
previous = current;
}
}
protected void setParameter(String token) throws IllegalArgumentException {
if (isParameter(token)) {
parameters.push(new Parameter(token));
} else {
throw new IllegalArgumentException(token);
}
}
protected void setArgument(String parameter, String argument) {
arguments.put(new Parameter(parameter), argument);
}
private Value valueForToken(Context context, String token) {
if (isSymbol(token)) {
return context.localValueForSymbol(symbolForToken(token));
} else if (isNumber(token)) {
return numberValueForToken(token);
} else if (isString(token)) {
return stringValueForToken(token);
} else if (isBoolean(token)) {
return booleanValueForToken(token);
} else {
throw new IllegalStateException(token);
}
}
public Signature signature() {
return new Signature(name, parameters);
}
public void execute(Context context) throws Exception {
Enumeration enumeration = arguments.keys();
Table table = Table.newTable();
while (enumeration.hasMoreElements()) {
Parameter parameter = (Parameter) enumeration.nextElement();
table.save(symbolForParameter(parameter), valueForToken(context, (String) arguments.get(parameter)));
}
context.onProcedureCall(signature(), table);
}
}
| 25.27551 | 105 | 0.720226 |
dcfccf73581bd762d76d8b190a67b403f318e811 | 8,965 | package com.ferreusveritas.dynamictrees.systems.genfeatures;
import com.ferreusveritas.dynamictrees.api.IFullGenFeature;
import com.ferreusveritas.dynamictrees.api.configurations.ConfigurationProperty;
import com.ferreusveritas.dynamictrees.systems.genfeatures.config.ConfiguredGenFeature;
import com.ferreusveritas.dynamictrees.trees.Species;
import com.ferreusveritas.dynamictrees.util.BlockBounds;
import com.ferreusveritas.dynamictrees.util.SafeChunkBounds;
import com.ferreusveritas.dynamictrees.util.SimpleVoxmap;
import com.google.common.collect.Iterables;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import java.util.Random;
import static net.minecraft.block.HugeMushroomBlock.*;
/**
* Generates a singular huge mushroom
*
* @author ferreusveritas
*/
public class HugeMushroomGenFeature extends GenFeature implements IFullGenFeature {
public static final ConfigurationProperty<Block> MUSHROOM_BLOCK = ConfigurationProperty.block("mushroom");
public static final ConfigurationProperty<Block> STEM_BLOCK = ConfigurationProperty.block("stem");
private int height = -1;
public HugeMushroomGenFeature(ResourceLocation registryName) {
super(registryName);
}
@Override
protected void registerProperties() {
this.register(MUSHROOM_BLOCK, STEM_BLOCK);
}
@Override
protected ConfiguredGenFeature<GenFeature> createDefaultConfiguration() {
return super.createDefaultConfiguration()
.with(MUSHROOM_BLOCK, Blocks.RED_MUSHROOM_BLOCK)
.with(STEM_BLOCK, Blocks.MUSHROOM_STEM);
}
static final SimpleVoxmap BROWN_CAP;
static final SimpleVoxmap BROWN_CAP_MEDIUM;
static final SimpleVoxmap BROWN_CAP_SMALL;
static final SimpleVoxmap RED_CAP;
static final SimpleVoxmap RED_CAP_SHORT;
static final SimpleVoxmap RED_CAP_SMALL;
static {
BROWN_CAP = new SimpleVoxmap(7, 1, 7, new byte[]{
0, 1, 2, 2, 2, 3, 0,
1, 5, 5, 5, 5, 5, 3,
4, 5, 5, 5, 5, 5, 6,
4, 5, 5, 5, 5, 5, 6,
4, 5, 5, 5, 5, 5, 6,
7, 5, 5, 5, 5, 5, 9,
0, 7, 8, 8, 8, 9, 0
}).setCenter(new BlockPos(3, 0, 3));
BROWN_CAP_MEDIUM = new SimpleVoxmap(5, 1, 5, new byte[]{
0, 1, 2, 3, 0,
1, 5, 5, 5, 3,
4, 5, 5, 5, 6,
7, 5, 5, 5, 9,
0, 7, 8, 9, 0
}).setCenter(new BlockPos(2, 0, 2));
BROWN_CAP_SMALL = new SimpleVoxmap(3, 1, 3, new byte[]{
1, 2, 3,
4, 5, 6,
7, 8, 9
}).setCenter(new BlockPos(1, 0, 1));
RED_CAP = new SimpleVoxmap(5, 4, 5, new byte[]{
0, 1, 2, 3, 0,
1, 0, 0, 0, 3,
4, 0, 10, 0, 6,
7, 0, 0, 0, 9,
0, 7, 8, 9, 0, // Bottom
0, 1, 2, 3, 0,
1, 0, 0, 0, 3,
4, 0, 10, 0, 6,
7, 0, 0, 0, 9,
0, 7, 8, 9, 0,
0, 1, 2, 3, 0,
1, 0, 0, 0, 3,
4, 0, 10, 0, 6,
7, 0, 0, 0, 9,
0, 7, 8, 9, 0,
0, 0, 0, 0, 0,
0, 1, 2, 3, 0,
0, 4, 5, 6, 0,
0, 7, 8, 9, 0,
0, 0, 0, 0, 0 // Top
}).setCenter(new BlockPos(2, 3, 2));
RED_CAP_SHORT = new SimpleVoxmap(5, 3, 5, new byte[]{
0, 1, 2, 3, 0,
1, 0, 0, 0, 3,
4, 0, 10, 0, 6,
7, 0, 0, 0, 9,
0, 7, 8, 9, 0, // Bottom
0, 1, 2, 3, 0,
1, 0, 0, 0, 3,
4, 0, 10, 0, 6,
7, 0, 0, 0, 9,
0, 7, 8, 9, 0,
0, 0, 0, 0, 0,
0, 1, 2, 3, 0,
0, 4, 5, 6, 0,
0, 7, 8, 9, 0,
0, 0, 0, 0, 0 // Top
}).setCenter(new BlockPos(2, 2, 2));
RED_CAP_SMALL = new SimpleVoxmap(3, 2, 3, new byte[]{
1, 2, 3,
4, 10, 6,
7, 8, 9, // Bottom
1, 2, 3,
4, 5, 6,
7, 8, 9 // Top
}).setCenter(new BlockPos(1, 1, 1));
}
public HugeMushroomGenFeature setHeight(int height) {
this.height = height;
return this;
}
/**
* Select the appropriate sized cap for a huge mushroom type
*
* @param mushroomBlock Red or Brown mushroom block
* @param height The height of the huge mushroom
* @return a voxmap of the cap to create
*/
protected SimpleVoxmap getCapForHeight(Block mushroomBlock, int height) {
// Brown Cap mushroom
if (mushroomBlock == Blocks.BROWN_MUSHROOM_BLOCK) {
switch (height) {
case 2:
case 3:
return BROWN_CAP_SMALL;
case 4:
case 5:
return BROWN_CAP_MEDIUM;
default:
return BROWN_CAP;
}
}
// Red Cap mushroom
switch (height) {
case 2:
return BROWN_CAP_SMALL;
case 3:
return RED_CAP_SMALL;
case 4:
return RED_CAP_SHORT;
default:
return RED_CAP;
}
}
//Override this for custom mushroom heights
protected int getMushroomHeight(IWorld world, BlockPos rootPos, Biome biome, Random random, int radius, SafeChunkBounds safeBounds) {
return this.height > 0 ? this.height : random.nextInt(9) + 2;
}
@Override
public boolean generate(ConfiguredGenFeature<?> configuredGenFeature, IWorld world, BlockPos rootPos, Species species, Biome biome, Random random, int radius, SafeChunkBounds safeBounds) {
final BlockPos genPos = rootPos.above();
final int height = this.getMushroomHeight(world, rootPos, biome, random, radius, safeBounds);
final BlockState soilState = world.getBlockState(rootPos);
if (species.isAcceptableSoilForWorldgen(world, rootPos, soilState)) {
Block mushroomBlock = configuredGenFeature.get(MUSHROOM_BLOCK);
if (mushroomBlock == null) {
mushroomBlock = random.nextBoolean() ? Blocks.BROWN_MUSHROOM_BLOCK : Blocks.RED_MUSHROOM_BLOCK;
}
final SimpleVoxmap capMap = this.getCapForHeight(mushroomBlock, height);
final BlockPos capPos = genPos.above(height - 1); // Determine the cap position(top block of mushroom cap)
final BlockBounds capBounds = capMap.getBounds().move(capPos); // Get a bounding box for the entire cap
if (safeBounds.inBounds(capBounds, true)) {//Check to see if the cap can be generated in safeBounds
// Check there's room for a mushroom cap and stem.
for (BlockPos mutPos : Iterables.concat(BlockPos.betweenClosed(BlockPos.ZERO.below(capMap.getLenY()), BlockPos.ZERO.below(height - 1)), capMap.getAllNonZero())) {
final BlockPos dPos = mutPos.offset(capPos);
final BlockState state = world.getBlockState(dPos);
if (!state.getMaterial().isReplaceable()) {
return false;
}
}
final BlockState stemState = configuredGenFeature.get(STEM_BLOCK).defaultBlockState();
// Construct the mushroom cap from the voxel map.
for (SimpleVoxmap.Cell cell : capMap.getAllNonZeroCells()) {
world.setBlock(capPos.offset(cell.getPos()), this.getMushroomStateForValue(mushroomBlock, stemState, cell.getValue(), cell.getPos().getY()), 2);
}
// Construct the stem.
final int stemLen = height - capMap.getLenY();
for (int y = 0; y < stemLen; y++) {
world.setBlock(genPos.above(y), stemState, 2);
}
return true;
}
}
return false;
}
// Whatever. It works.
protected BlockState getMushroomStateForValue(Block mushroomBlock, BlockState stemBlock, int value, int y) {
if (value == 10) {
return stemBlock;
}
return mushroomBlock.defaultBlockState()
.setValue(UP, y >= -1)
.setValue(DOWN, false)
.setValue(NORTH, value >= 1 && value <= 3)
.setValue(SOUTH, value >= 7 && value <= 9)
.setValue(WEST, value == 1 || value == 4 || value == 7)
.setValue(EAST, value % 3 == 0);
}
}
| 35.717131 | 192 | 0.544004 |
8340f0d5aa6d0c15bb0856848be8890c2a219fef | 2,614 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.hybrid.gateway.api.synchronizer.util;
/**
* Constants related to API synchronization
*/
public class APISynchronizationConstants {
public static final String EMPTY_STRING = "";
public static final String API_MEDIATION_POLICY_VIEW_SCOPE = "apim:mediation_policy_view";
public static final String API_VIEW_SCOPE = "apim:api_view";
public static final String API_PUBLISHER_URL_PROPERTY = "api.publisher.url";
public static final String API_VERSION_PROPERTY = "rest.api.version";
public static final String DEFAULT_API_PUBLISHER_URL = "https://localhost:9443";
public static final String DEFAULT_API_UPDATE_URL_PROPERTY = "api.lifecycle.event.publisher.url";
public static final String API_VIEW_PATH = "/api/am/publisher/{version}/apis";
public static final String API_VIEW_MEDIATION_POLICY_PATH = "/policies/mediation";
public static final String API_VIEW_GLOBAL_MEDIATION_POLICY_PATH = "/api/am/publisher/{version}/policies/mediation";
public static final String DEFAULT_API_UPDATE_SERVICE_URL = "https://localhost:9443/micro-gateway/v0.9/updated-apis";
public static final String API_NAME = "name";
public static final String API_SEQUENCE = "sequence";
public static final String API_VERSION_PARAM = "{version}";
public static final String API_DEFAULT_VERSION = "v0.15";
public static final String URL_PATH_SEPARATOR = "/";
public static final String CLOUD_API = "cloud";
public static final String QUESTION_MARK = "?";
public static final String OFFSET_PREFIX = "offset=";
public static final String API_SEARCH_LABEL_QUERY_PREFIX = "query=label:";
public static final String AMPERSAND = "&";
public static final String PAGINATION_LIMIT_PREFIX = "limit=";
public static final String PAGINATION_LIMIT = "500";
public static final String CHARSET_UTF8 = "UTF-8";
public static final String SEQUENCE_NAME = "name";
}
| 52.28 | 121 | 0.754399 |
24a2faceacd456a6c254000eb49df5c15fdb2aef | 1,084 | package org.firstinspires.ftc.teamcode.temp;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
/**
* Created by USER on 11/21/2017.
*/
@TeleOp(name="collector", group="Temp")
public class TestCollector extends TempOpMode {
@Override
public void runOpMode() throws InterruptedException {
initRobot();
waitForStart();
double power = -0.25;
while (opModeIsActive()) {
if (gamepad1.y)
power = gamepad1.left_stick_y;
if (gamepad1.a) {
leftFront.setPower(power);
rightFront.setPower(-power);
} else if (gamepad1.b) {
leftFront.setPower(-power);
rightFront.setPower(power);
} else if (gamepad1.x) {
leftFront.setPower(0);
rightFront.setPower(0);
} else {
leftFront.setPower(power);
rightFront.setPower(power);
}
telemetry.addData("power", "$.2f", power);
telemetry.update();
}
}
}
| 24.088889 | 57 | 0.535055 |
18a9ddef0e02e1e5f75f02e719d092c9ee8e139b | 395 | package org.springframework.security.web.server.authorization;
import reactor.core.publisher.Mono;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public interface ServerAccessDeniedHandler {
Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied);
}
| 23.235294 | 77 | 0.812658 |
b9e9c7efcd4e22b02937fdabf2fe78e239b5dda8 | 425 | package org.socraticgrid.hl7.services.orders.xmladapter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MessageTypeAdapter extends XmlAdapter<Object, Object> {
@Override
public Object unmarshal(Object v) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public Object marshal(Object v) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| 21.25 | 68 | 0.769412 |
4aee2d31ae6cd208a7126e11e6ad4a7fa9b30f56 | 3,115 | /*
* MIT License
*
* Copyright (c) 2018 Charalampos Savvidis
*
* 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.lowbudget.chess.front.app.controller.player;
import com.lowbudget.chess.front.app.Constants;
import com.lowbudget.chess.front.app.Player;
import com.lowbudget.common.ListenerList;
import com.lowbudget.chess.model.PlayerColor;
import com.lowbudget.chess.model.Move;
import java.util.Objects;
/**
* A base implementation for a {@link Player} that stores the player's name and color and provide the infrastructure to
* add and remove {@link com.lowbudget.chess.front.app.Player.PlayerListener}s.
*/
public abstract class AbstractPlayer implements Player {
private String name;
private final PlayerColor color;
final ListenerList<PlayerListener> playerListeners;
AbstractPlayer(PlayerColor color) {
this(Constants.UNKNOWN_NAME, color);
}
AbstractPlayer(String name, PlayerColor color) {
this.name = Objects.requireNonNull(name, "Player's name is required");
this.color = Objects.requireNonNull(color, "Player's color is required");
this.playerListeners = new ListenerList<>();
}
@Override
public String getName() {
return this.name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public PlayerColor getColor() {
return this.color;
}
@Override
public void addPlayerListener(PlayerListener playerListener) {
this.playerListeners.add(playerListener);
}
@Override
public void removePlayerListener(PlayerListener playerListener) {
playerListeners.remove(playerListener);
}
@Override
public boolean isEngine() {
return false;
}
@Override
public boolean isHuman() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void startThinking(String lastFenPosition, Move lastMove, long whiteRemainingTime, long blackRemainingTime) {}
@Override
public void handShake(Player opponent) {}
@Override
public void start() {}
@Override
public void stop() {}
@Override
public void pause() {}
@Override
public void resume() {}
}
| 27.086957 | 119 | 0.756661 |
34ba1770877581276e099c3a060564ef8b706ea2 | 3,007 | /*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* 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.hyracks.api.comm;
import java.nio.ByteBuffer;
public class FrameHelper {
public static int getTupleCountOffset(int frameSize) {
return frameSize - FrameConstants.SIZE_LEN;
}
/**
* The actual frameSize = frameCount * intitialFrameSize
* This method is used to put that frameCount into the first byte of the frame buffer.
* @param outputFrame
* @param numberOfMinFrame
*/
public static void serializeFrameSize(ByteBuffer outputFrame, byte numberOfMinFrame) {
serializeFrameSize(outputFrame, 0, numberOfMinFrame);
}
public static void serializeFrameSize(ByteBuffer outputFrame, int start, byte numberOfMinFrame) {
outputFrame.array()[start + FrameConstants.META_DATA_FRAME_COUNT_OFFSET] = (byte) (numberOfMinFrame & 0xff);
}
public static byte deserializeNumOfMinFrame(ByteBuffer frame) {
return deserializeNumOfMinFrame(frame, 0);
}
public static byte deserializeNumOfMinFrame(ByteBuffer buffer, int start) {
return (byte) (buffer.array()[start + FrameConstants.META_DATA_FRAME_COUNT_OFFSET] & 0xff);
}
/**
* Add one tuple requires
* 4bytes to store the tuple offset
* 4bytes * |fields| to store the relative offset of each field
* nbytes the actual data.
* If the tupleLength includes the field slot, please set the fieldCount = 0
*/
public static int calcSpaceInFrame(int fieldCount, int tupleLength) {
return 4 + fieldCount * 4 + tupleLength;
}
/**
* A faster way of calculating the ceiling
*
* @param fieldCount please set fieldCount to 0 if the tupleLength includes the fields' length
* @param tupleLength
* @param minFrameSize
* @return
*/
public static int calcAlignedFrameSizeToStore(int fieldCount, int tupleLength, int minFrameSize) {
assert fieldCount >= 0 && tupleLength >= 0 && minFrameSize > 0;
return (1 + (calcSpaceInFrame(fieldCount, tupleLength) + FrameConstants.META_DATA_LEN - 1) / minFrameSize)
* minFrameSize;
}
public static void clearRemainingFrame(ByteBuffer buffer, int position) {
buffer.array()[position] = 0;
}
public static boolean hasBeenCleared(ByteBuffer buffer, int position) {
return deserializeNumOfMinFrame(buffer, position) == 0;
}
}
| 38.063291 | 116 | 0.703026 |
5bfcfe324fc7640a9df1fcba748bb77da7205b7b | 868 | package nahabi4.supplement.sqlserver.jdbc;
import com.microsoft.sqlserver.jdbc.SQLServerException;
import nahabi4.supplement.java.sql.ColumnMetadata;
public class StringArraysBulkRecordSet extends ArraysBulkRecordSet {
protected StringToObjectTransformer transformer;
public StringArraysBulkRecordSet(String[][] data, ColumnMetadata[] columnMetadata, StringToObjectTransformer transformer) {
super(data, columnMetadata);
this.transformer = transformer;
}
@Override
public Object[] getRowData() throws SQLServerException {
String[] sourceData = (String[]) super.getRowData();
Object[] resultData = new Object[sourceData.length];
for(int i=0; i < sourceData.length; i++){
resultData[i] = transformer.transform(sourceData[i], columnMetadata[i]);
}
return resultData;
}
}
| 31 | 127 | 0.71659 |
8729b0c08831b6e58720be31c8cc71d10dab94d9 | 284 | package nl.uva.deepspike.events;
/**
* Created by peter on 2/24/16.
*/
public class SpikeEvent extends SignedSpikeEvent {
/* This exists purely to avoid accidently treating SignedSpikeEvents as SpikeEvents */
public SpikeEvent (int src){
super(src, false);
}
}
| 23.666667 | 90 | 0.697183 |
95bc8bb048ed8b55f00081cdc502d621b1db4359 | 609 | /*
* $Header: /usr/cvsroot/AntIDE/source/com/antsoft/ant/property/CompilerPanel.java,v 1.3 1999/07/22 03:42:03 multipia Exp $
* Ant ( JDK wrapper Java IDE )
* Version 1.0
* Copyright (c) 1998-1999 Antsoft Co. All rights reserved.
* This program and source file is protected by Korea and international
* Copyright laws.
*
* $Revision: 1.3 $
*/
package com.antsoft.ant.property;
import javax.swing.*;
import com.antsoft.ant.util.BorderList;
import java.awt.*;
public class CompilerPanel extends JPanel{
public CompilerPanel() {
setBorder(BorderList.emptyBorder5);
}
}
| 26.478261 | 124 | 0.697865 |
78fd17abe1289a20fda609257b76977c217f27bc | 1,244 | package com.bapocalypse.train.service;
import com.bapocalypse.train.dto.Exposer;
import com.bapocalypse.train.dto.TrickExecution;
import com.bapocalypse.train.exception.RepeatBuyException;
import com.bapocalypse.train.exception.TrickCloseException;
import com.bapocalypse.train.exception.TrickException;
import com.bapocalypse.train.po.Trick;
import java.sql.Date;
import java.util.List;
/**
* @package: com.bapocalypse.train.service
* @Author: 陈淼
* @Date: 2016/11/25
* @Description: 车票操作的服务接口
*/
public interface TrickService {
List<Trick> findAllTricksByUid(int uid);
/**
* @funtion exportBuyTrickUrl
* @Description 开始购票是输出购票接口地址,否则输出系统时间以及提示。
* @param tid 列车id
* @param date 日期
* @return 暴露购买车票地址DTO
*/
Exposer exportBuyTrickUrl(String tid, Date date);
/**
* @funtion executeBuyTrick
* @Description 执行购票业务
* @param trick 车票对象
* @param level 座位等级
* @param md5 md5加密方式
* @return 购买车票后的结果
* @throws TrickException 购票相关业务异常
* @throws RepeatBuyException 重复购买异常
* @throws TrickCloseException 购票关闭异常
*/
TrickExecution executeBuyTrick(Trick trick, String level, String md5) throws TrickException, RepeatBuyException, TrickCloseException;
}
| 28.930233 | 137 | 0.727492 |
31571c21931af74636802e5a812f3739e3cfac9c | 1,450 | /* Copyright (c) 2017 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.geotools.data.reader;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.annotation.Nullable;
import org.geotools.filter.visitor.DefaultFilterVisitor;
import org.opengis.filter.Filter;
import org.opengis.filter.expression.Literal;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
/**
*
*/
class ExtractBounds extends DefaultFilterVisitor {
private List<Envelope> bounds = new ArrayList<>(2);
@Override
public List<Envelope> visit(Literal literal, @Nullable Object data) {
Object value = literal.getValue();
if (value instanceof Geometry) {
Geometry geom = (Geometry) value;
Envelope literalEnvelope = geom.getEnvelopeInternal();
bounds.add(literalEnvelope);
}
return bounds;
}
@SuppressWarnings("unchecked")
public static List<Envelope> getBounds(Filter filterInNativeCrs) {
return (List<Envelope>) filterInNativeCrs.accept(new ExtractBounds(), null);
}
}
| 30.851064 | 84 | 0.728276 |
ba7506acf27546a6b26b31cf276a3038dee74640 | 3,521 | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.pocketEtl.core.consumer;
import com.amazon.pocketEtl.EtlTestBase;
import com.amazon.pocketEtl.Loader;
import com.amazon.pocketEtl.core.EtlStreamObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LoaderEtlConsumerTest extends EtlTestBase {
private static final String TEST_NAME = "TestName";
@Mock
private Loader<TestDTO> mockLoader;
@Mock
private EtlConsumer mockErrorEtlConsumer;
@Mock
private EtlStreamObject mockEtlStreamObject;
@Mock
private TestDTO mockTestDTO;
private LoaderEtlConsumer<TestDTO> loaderConsumer;
@Before
public void constructWorker() {
when(mockEtlStreamObject.get(any())).thenReturn(mockTestDTO);
loaderConsumer = new LoaderEtlConsumer<>(TEST_NAME, mockLoader, TestDTO.class, mockErrorEtlConsumer);
}
@Test
public void consumeLoadsASingleObject() {
loaderConsumer.open(mockMetrics);
loaderConsumer.consume(mockEtlStreamObject);
verify(mockLoader, times(1)).load(eq(mockTestDTO));
}
@Test
public void closeClosesLoader() throws Exception {
loaderConsumer.open(mockMetrics);
loaderConsumer.close();
verify(mockLoader).close();
}
@Test
public void closeClosesErrorConsumer() throws Exception {
loaderConsumer.open(mockMetrics);
loaderConsumer.close();
verify(mockErrorEtlConsumer).close();
}
@Test
public void closeClosesErrorConsumerEvenAfterARuntimeException() throws Exception {
doThrow(new RuntimeException("Test exception")).when(mockLoader).close();
loaderConsumer.open(mockMetrics);
loaderConsumer.close();
verify(mockErrorEtlConsumer).close();
}
@Test
public void openOpensLoader() throws Exception {
loaderConsumer.open(etlProfilingScope.getMetrics());
verify(mockLoader).open(eq(etlProfilingScope.getMetrics()));
}
@Test
public void openOpensErrorConsumer() throws Exception {
loaderConsumer.open(etlProfilingScope.getMetrics());
verify(mockErrorEtlConsumer).open(eq(etlProfilingScope.getMetrics()));
}
@Test
public void consumePassesToTheErrorConsumerOnRuntimeException() {
doThrow(new RuntimeException("test")).when(mockLoader).load(any(TestDTO.class));
loaderConsumer.open(mockMetrics);
loaderConsumer.consume(mockEtlStreamObject);
verify(mockErrorEtlConsumer).consume(mockEtlStreamObject);
}
}
| 30.617391 | 109 | 0.725362 |
22e8bc52ab2719cd0960423c61cd10e38c8faecb | 443 | package com.cloudycrew.cloudycar.roleselection;
/**
* Created by George on 2016-11-23.
*/
public interface IRoleSelectionView {
/**
* Callback for displaying the add car notification
*/
void displayAddCarDescription();
/**
* Callback for displaying driver summary
*/
void displayDriverSummary();
/**
* Callback for after a car description is added
*/
void onCarDescriptionAdded();
}
| 19.26087 | 55 | 0.656885 |
a97b726dc98e9e84e83619b6cd94242b1815f272 | 663 | //package com.nexuslink.wenavi.contract;
//
//import android.widget.EditText;
//
//import com.nexuslink.wenavi.base.BasePresenter;
//import com.nexuslink.wenavi.base.BaseView;
//
///**
// * Created by aplrye on 17-8-27.
// */
//
//public interface UserContract {
// interface Presenter extends BasePresenter {
// void register(EditText nameEditTx,EditText accountEditTx, EditText pwEditTx);
//
// void login(EditText accountEditTx, EditText pwEditTx);
// }
//
// interface View extends BaseView<Presenter> {
// void showHome();
//
// void showProgress(boolean bool);
//
// void showNotifyInfo(String text);
// }
//}
| 24.555556 | 87 | 0.665158 |
0425fd9ec84f59a5f423b46b2c98d9bcc5fc1caf | 2,911 | package controllers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import exceptions.CardapioInvalidoException;
import exceptions.CardapioOverflowException;
import exceptions.DadoIncompletoException;
import models.Alimento;
import models.Cardapio;
import models.Grupo;
import models.Refeicao;
public class MontagemCardapio {
List<Alimento> alimentosDiaAnterior;
List<Grupo> gruposDia;
List<Refeicao> refeicoesDia;
List<Alimento> alimentosDiaAtual;
Map<String, Integer> frequenciasAlimentos;
List<Alimento> alimentosRefeicao;
List<Alimento> alimentosGrupo;
List<Integer> indices;
Alimento alimentoSelecionado;
Integer valorParaIncrementar;
public MontagemCardapio() {
}
void computar(List<List<Grupo>> gruposInput) throws CardapioInvalidoException, CardapioOverflowException, DadoIncompletoException {
Cardapio.clearCardapioSemana();
alimentosDiaAnterior = new ArrayList<Alimento>();
for (int i = 0; i < Cardapio.DIAS_DA_SEMANA.size(); i++) {
gruposDia = gruposInput.get(i);
refeicoesDia = new ArrayList<Refeicao>();
alimentosDiaAtual = new ArrayList<Alimento>();
frequenciasAlimentos = new LinkedHashMap<String, Integer>();
for (int j = 0; j < CardapioController.NUM_REFEICOES_DIA; j++) {
alimentosRefeicao = new ArrayList<Alimento>();
for (Grupo g : gruposDia) {
alimentosGrupo = g.getAlimentos();
indices = new ArrayList<Integer>();
for (int w = 0; w < alimentosGrupo.size(); w++) {
indices.add(w);
}
Collections.shuffle(indices);
alimentoSelecionado = null;
for (Integer indiceAleatorio : indices) {
alimentoSelecionado = alimentosGrupo.get(indiceAleatorio);
if (frequenciasAlimentos.containsKey(alimentoSelecionado.getNome()) == false) {
frequenciasAlimentos.put(alimentoSelecionado.getNome(), 0);
}
if (alimentosDiaAnterior.contains(alimentoSelecionado) == false && frequenciasAlimentos.get(alimentoSelecionado.getNome()) < 2) {
break;
} else if(indices.indexOf(indiceAleatorio) == indices.size() - 1) {
throw new CardapioInvalidoException("Não foi possível montar o cardápio");
}
}
alimentosRefeicao.add(alimentoSelecionado);
alimentosDiaAtual.add(alimentoSelecionado);
valorParaIncrementar = frequenciasAlimentos.get(alimentoSelecionado.getNome());
valorParaIncrementar++;
frequenciasAlimentos.put(alimentoSelecionado.getNome(), valorParaIncrementar);
}
refeicoesDia.add(new Refeicao(Cardapio.REFEICOES.get(j), alimentosRefeicao));
}
alimentosDiaAnterior.clear();
alimentosDiaAnterior.addAll(alimentosDiaAtual);
Cardapio.addCardapioDia(new Cardapio(Cardapio.DIAS_DA_SEMANA.get(i), refeicoesDia));
}
}
}
| 30.010309 | 135 | 0.719684 |
d749dfd4fceddce2814c2786bf9c9be61dfcb82d | 20,053 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.runelite.mapping.Export
* net.runelite.mapping.Implements
* net.runelite.mapping.ObfuscatedGetter
* net.runelite.mapping.ObfuscatedName
* net.runelite.mapping.ObfuscatedSignature
*/
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName(value="ev")
@Implements(value="NPCDefinition")
public class NPCDefinition
extends DualNode {
@ObfuscatedName(value="ae")
@ObfuscatedSignature(descriptor="Lkc;")
static AbstractArchive field7157;
@ObfuscatedName(value="ai")
@ObfuscatedSignature(descriptor="Lga;")
@Export(value="NpcDefinition_cached")
static EvictingDualNodeHashTable NpcDefinition_cached;
@ObfuscatedName(value="ak")
@ObfuscatedSignature(descriptor="Lkc;")
@Export(value="NpcDefinition_archive")
static AbstractArchive NpcDefinition_archive;
@ObfuscatedName(value="ax")
@ObfuscatedSignature(descriptor="Lga;")
static EvictingDualNodeHashTable field7160;
@ObfuscatedName(value="aa")
int[] field7161;
@ObfuscatedName(value="ac")
@ObfuscatedGetter(intValue=-1961030239)
int field7163 = 128;
@ObfuscatedName(value="af")
@ObfuscatedGetter(intValue=-726340049)
public int field7165 = -1;
@ObfuscatedName(value="ag")
@ObfuscatedGetter(intValue=2118073827)
int field7166 = 128;
@ObfuscatedName(value="ah")
@ObfuscatedGetter(intValue=542931001)
@Export(value="id")
public int id;
@ObfuscatedName(value="aj")
@ObfuscatedGetter(intValue=-244130131)
public int field7168 = 1;
@ObfuscatedName(value="al")
int[] field7169;
@ObfuscatedName(value="am")
@ObfuscatedGetter(intValue=13434001)
public int field7170 = -1;
@ObfuscatedName(value="an")
@ObfuscatedGetter(intValue=2050696585)
public int field7171 = -1;
@ObfuscatedName(value="ao")
short[] field7172;
@ObfuscatedName(value="ap")
short[] field7173;
@ObfuscatedName(value="aq")
@ObfuscatedGetter(intValue=1452086197)
public int field7174 = -1;
@ObfuscatedName(value="ar")
short[] field7175;
@ObfuscatedName(value="as")
public String field7176 = Strings.field2765;
@ObfuscatedName(value="au")
public boolean field7178 = false;
@ObfuscatedName(value="aw")
@ObfuscatedGetter(intValue=-427780219)
public int field7180 = -1;
@ObfuscatedName(value="ay")
@ObfuscatedGetter(intValue=-2082584459)
public int field7181 = -1;
@ObfuscatedName(value="az")
short[] field7182;
@ObfuscatedName(value="bd")
public boolean field7184 = false;
@ObfuscatedName(value="bg")
@ObfuscatedGetter(intValue=537900383)
public int field7186 = -1;
@ObfuscatedName(value="bh")
@ObfuscatedGetter(intValue=-233849213)
int field7187 = -1;
@ObfuscatedName(value="bj")
public int[] field7189;
@ObfuscatedName(value="bp")
@ObfuscatedGetter(intValue=-267992369)
int field7191 = 0;
@ObfuscatedName(value="bq")
@ObfuscatedGetter(intValue=1030095631)
int field7192 = -1;
@ObfuscatedName(value="br")
public boolean field7193 = true;
@ObfuscatedName(value="ad")
@ObfuscatedGetter(intValue=577225751)
public int field7164 = -1;
@ObfuscatedName(value="at")
public String[] field7177 = new String[5];
@ObfuscatedName(value="av")
public boolean field7179 = true;
@ObfuscatedName(value="bc")
@ObfuscatedSignature(descriptor="Lpy;")
IterableNodeHashTable field7183;
@ObfuscatedName(value="bi")
@ObfuscatedGetter(intValue=-2042324995)
int field7188 = 0;
@ObfuscatedName(value="ab")
@ObfuscatedGetter(intValue=-1512059499)
public int field7162 = -1;
@ObfuscatedName(value="bf")
@ObfuscatedGetter(intValue=863132285)
public int field7185 = 32;
@ObfuscatedName(value="bk")
public boolean field7190 = true;
static {
NpcDefinition_cached = new EvictingDualNodeHashTable(64, null);
field7160 = new EvictingDualNodeHashTable(50, null);
}
NPCDefinition() {
}
@ObfuscatedName(value="aa")
public boolean method13355(byte by) {
if (this.field7189 != null) {
by = this.field7187 != -1 ? (byte)class285.method10473(this.field7187, -181913371) : (this.field7192 != -1 ? (byte)Varps.Varps_main[this.field7192] : (byte)-1);
if (by >= 0 && by < this.field7189.length) {
return this.field7189[by] != -1;
{
}
}
by = (byte)this.field7189[this.field7189.length - 1];
return by != -1;
}
return true;
}
/*
* Enabled aggressive block sorting
*/
@ObfuscatedName(value="ah")
@ObfuscatedSignature(descriptor="(Lmi;IB)V")
void method13361(Buffer buffer, int n, byte by) {
int n2;
block33: {
int n3;
block34: {
int n4;
block35: {
int n5;
block36: {
block38: {
block37: {
n3 = 0;
n4 = 0;
n5 = 0;
by = 0;
n2 = 0;
if (n == 1) break block33;
if (n == 2) {
this.field7176 = buffer.method11664(-2131282049);
return;
}
if (n == 12) {
this.field7168 = buffer.method11650(-1866239559);
return;
}
if (n == 13) {
this.field7162 = buffer.method11637(420803215);
return;
}
if (n == 14) {
this.field7170 = buffer.method11637(-1339842304);
return;
}
if (n == 15) {
this.field7165 = buffer.method11637(436776507);
return;
}
if (n == 16) {
this.field7174 = buffer.method11637(-1487769259);
return;
}
if (n == 17) {
this.field7170 = buffer.method11637(606938048);
this.field7171 = buffer.method11637(884878015);
this.field7181 = buffer.method11637(1382192670);
this.field7180 = buffer.method11637(-138090276);
return;
}
if (n >= 30 && n < 35) {
String[] arrstring = this.field7177;
arrstring[n -= 30] = buffer.method11664(-1892360931);
if (!this.field7177[n].equalsIgnoreCase(Strings.field2788)) return;
this.field7177[n] = null;
return;
}
if (n == 40) break block34;
if (n == 41) break block35;
if (n == 60) break block36;
if (n == 93) {
this.field7179 = false;
return;
}
if (n == 95) {
this.field7164 = buffer.method11637(59270871);
return;
}
if (n == 97) {
this.field7166 = buffer.method11637(85946715);
return;
}
if (n == 98) {
this.field7163 = buffer.method11637(-1565919237);
return;
}
if (n == 99) {
this.field7178 = true;
return;
}
if (n == 100) {
this.field7191 = buffer.method11636(1840504305);
return;
}
if (n == 101) {
this.field7188 = buffer.method11636(1609233902);
return;
}
if (n == 102) {
this.field7186 = buffer.method11637(152605669);
return;
}
if (n == 103) {
this.field7185 = buffer.method11637(1437020093);
return;
}
if (n != 106 && n != 118) {
if (n == 107) {
this.field7193 = false;
return;
}
if (n == 109) {
this.field7190 = false;
return;
}
if (n == 111) {
this.field7184 = true;
return;
}
if (n != 249) return;
this.field7183 = FontName.method6390(buffer, this.field7183, 1408256200);
return;
}
this.field7187 = buffer.method11637(1974472682);
if (this.field7187 == 65535) {
this.field7187 = -1;
}
this.field7192 = buffer.method11637(1036460288);
if (this.field7192 == 65535) {
this.field7192 = -1;
}
if (n != 118) break block37;
n = n2 = buffer.method11637(547410802);
if (n2 != 65535) break block38;
}
n = -1;
}
n2 = buffer.method11650(187268643);
this.field7189 = new int[n2 + 2];
while (true) {
if (by > n2) {
this.field7189[n2 + 1] = n;
return;
}
this.field7189[by] = buffer.method11637(43689559);
if (this.field7189[by] == 65535) {
this.field7189[by] = -1;
}
by = (byte)(by + 1);
}
}
by = (byte)buffer.method11650(-1382421803);
this.field7161 = new int[by];
n = n5;
while (n < by) {
this.field7161[n] = buffer.method11637(-162728084);
++n;
}
return;
}
by = (byte)buffer.method11650(1033257447);
this.field7172 = new short[by];
this.field7182 = new short[by];
n = n4;
while (n < by) {
this.field7172[n] = (short)buffer.method11637(87301852);
this.field7182[n] = (short)buffer.method11637(266348165);
++n;
}
return;
}
by = (byte)buffer.method11650(1014792194);
this.field7175 = new short[by];
this.field7173 = new short[by];
n = n3;
while (n < by) {
this.field7175[n] = (short)buffer.method11637(-389839992);
this.field7173[n] = (short)buffer.method11637(-7776136);
++n;
}
return;
}
by = (byte)buffer.method11650(-907234312);
this.field7169 = new int[by];
n = n2;
while (n < by) {
this.field7169[n] = buffer.method11637(119195297);
++n;
}
}
/*
* Enabled aggressive block sorting
*/
@ObfuscatedName(value="aj")
@ObfuscatedSignature(descriptor="(I)Lbk;")
public final ModelData method13363(int n) {
if (this.field7189 != null) {
NPCDefinition nPCDefinition = this.method13364(-944307993);
if (nPCDefinition != null) return nPCDefinition.method13363(2097411);
return null;
}
if (this.field7161 == null) {
return null;
}
int n2 = 0;
n = 0;
boolean bl = false;
while (true) {
block9: {
block10: {
block8: {
if (n >= this.field7161.length) break block8;
if (field7157.tryLoadFile(this.field7161[n], 0)) break block9;
break block10;
}
if (bl) {
return null;
}
Object object = new ModelData[this.field7161.length];
for (n = 0; n < this.field7161.length; ++n) {
object[n] = ModelData.ModelData_get(field7157, this.field7161[n], 0);
}
object = ((ModelData[])object).length == 1 ? object[0] : new ModelData((ModelData[])object, ((ModelData[])object).length);
if (this.field7175 != null) {
for (n = 0; n < this.field7175.length; ++n) {
((ModelData)object).recolor(this.field7175[n], this.field7173[n]);
}
}
if (this.field7172 == null) return object;
n = n2;
while (n < this.field7172.length) {
((ModelData)object).retexture(this.field7172[n], this.field7182[n]);
++n;
}
return object;
}
bl = true;
}
++n;
}
}
@ObfuscatedName(value="al")
@ObfuscatedSignature(descriptor="(I)Lev;")
public final NPCDefinition method13364(int n) {
n = this.field7187 != -1 ? class285.method10473(this.field7187, 1520700128) : (this.field7192 != -1 ? Varps.Varps_main[this.field7192] : -1);
n = n >= 0 && n < this.field7189.length - 1 ? this.field7189[n] : this.field7189[this.field7189.length - 1];
if (n == -1) {
return null;
}
NPCDefinition nPCDefinition = ItemContainer.getNpcDefinition(n);
return nPCDefinition;
}
/*
* Handled impossible loop by adding 'first' condition
* Enabled aggressive block sorting
*/
@ObfuscatedName(value="as")
@ObfuscatedSignature(descriptor="(Ldv;ILdv;IB)Lcp;")
public final Model method13365(SequenceDefinition dualNode, int n, SequenceDefinition sequenceDefinition, int n2, byte by) {
if (this.field7189 != null) {
NPCDefinition nPCDefinition = this.method13364(-944307993);
if (nPCDefinition == null) return null;
return nPCDefinition.method13365((SequenceDefinition)dualNode, n, sequenceDefinition, n2, (byte)1);
}
ModelData[] arrmodelData = (ModelData[])field7160.get(this.id);
Object object = arrmodelData;
boolean bl = true;
while (true) {
block12: {
boolean bl2;
block13: {
block10: {
block11: {
if (!bl || (bl = false)) continue;
if (arrmodelData != null) break block10;
byte by2 = 0;
by = 0;
bl2 = false;
if (by >= this.field7169.length) break block11;
if (field7157.tryLoadFile(this.field7169[by], 0)) break block12;
break block13;
}
if (bl2) {
return null;
}
object = new ModelData[this.field7169.length];
for (by = 0; by < this.field7169.length; by = (byte)(by + 1)) {
object[by] = ModelData.ModelData_get(field7157, this.field7169[by], 0);
}
object = ((ModelData[])object).length == 1 ? object[0] : new ModelData((ModelData[])object, ((ModelData[])object).length);
if (this.field7175 != null) {
for (by = 0; by < this.field7175.length; by = (byte)(by + 1)) {
((ModelData)object).recolor(this.field7175[by], this.field7173[by]);
}
}
if (this.field7172 != null) {
for (by = by2; by < this.field7172.length; by = (byte)(by + 1)) {
((ModelData)object).retexture(this.field7172[by], this.field7182[by]);
}
}
object = ((ModelData)object).toModel(this.field7191 + 64, this.field7188 * 5 + 850, -30, -50, -30);
field7160.put((DualNode)object, this.id);
}
dualNode = dualNode != null && sequenceDefinition != null ? ((SequenceDefinition)dualNode).method13167((Model)object, n, sequenceDefinition, n2, -193747437) : (dualNode != null ? ((SequenceDefinition)dualNode).method13178((Model)object, n) : (sequenceDefinition != null ? sequenceDefinition.method13178((Model)object, n2) : ((Model)object).toSharedSequenceModel(true)));
if (this.field7166 == 128 && this.field7163 == 128) return dualNode;
((Model)dualNode).scale(this.field7166, this.field7163, this.field7166);
return dualNode;
}
bl2 = true;
}
by = (byte)(by + 1);
}
}
@ObfuscatedName(value="ai")
@ObfuscatedSignature(descriptor="(I)V", garbageValue="479930846")
@Export(value="postDecode")
void postDecode() {
}
@ObfuscatedName(value="ax")
@ObfuscatedSignature(descriptor="(Lmi;I)V")
@Export(value="decodeNext")
void decodeNext(Buffer buffer, int n) {
while ((n = buffer.method11650(949964015)) != 0) {
this.method13361(buffer, n, (byte)43);
}
return;
}
}
| 42.485169 | 390 | 0.44532 |
22336a51d932c5d1ce0841fb6496d6abb2f0448f | 938 | /*
* 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 controller.util;
import javax.validation.ConstraintViolation;
import java.util.Set;
/**
*
* @author jGauravGupta
*/
public class ValidationUtil {
public static String getResponse(javax.mvc.binding.BindingResult validationResult, controller.util.ErrorBean error) {
final Set<ConstraintViolation<?>> set = validationResult.getAllViolations();
final ConstraintViolation<?> cv = set.iterator().next();
final String property = cv.getPropertyPath().toString();
error.setProperty(property.substring(property.lastIndexOf('.') + 1));
error.setValue(cv.getInvalidValue());
error.setMessage(cv.getMessage());
return "/webresources/common/error.jsp";
}
}
| 33.5 | 122 | 0.690832 |
0fda9721f11098d594ec7f20b9565a7849ed0096 | 246 | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/**
* Interceptors are used to do pre-processing and post-processing during invocation of Command.
*
* @author fulan.zjf
*/
package ${package}.interceptor; | 27.333333 | 95 | 0.666667 |
9b1dd2ae8d8aa0b02372224133c57116a31fe704 | 3,822 | package msifeed.misca.charsheet.cap;
import msifeed.misca.charsheet.ICharsheet;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import javax.annotation.Nullable;
import java.util.Map;
public class CharsheetStorage implements Capability.IStorage<ICharsheet> {
@Nullable
@Override
public NBTBase writeNBT(Capability<ICharsheet> capability, ICharsheet instance, EnumFacing side) {
final NBTTagCompound nbt = new NBTTagCompound();
nbt.setString(Tag.name, instance.getName());
nbt.setString(Tag.wikiPage, instance.getWikiPage());
instance.skills().writeNBT(Tag.skills, nbt);
instance.effortPools().writeNBT(Tag.effortPools, nbt);
instance.resources().writeNBT(Tag.resources, nbt);
instance.needsGain().writeNBT(Tag.needsRest, nbt);
instance.needsLost().writeNBT(Tag.needsLost, nbt);
final NBTTagCompound potionsNbt = new NBTTagCompound();
for (Map.Entry<Potion, Integer> entry : instance.potions().entrySet())
potionsNbt.setByte(entry.getKey().getRegistryName().toString(), entry.getValue().byteValue());
nbt.setTag(Tag.potions, potionsNbt);
final NBTTagCompound enchantsNbt = new NBTTagCompound();
for (Map.Entry<Enchantment, Integer> entry : instance.enchants().entrySet())
enchantsNbt.setByte(entry.getKey().getRegistryName().toString(), entry.getValue().byteValue());
nbt.setTag(Tag.enchants, enchantsNbt);
nbt.setLong(Tag.updated, instance.getLastUpdated());
return nbt;
}
@Override
public void readNBT(Capability<ICharsheet> capability, ICharsheet instance, EnumFacing side, NBTBase nbtBase) {
final NBTTagCompound nbt = (NBTTagCompound) nbtBase;
instance.setName(nbt.getString(Tag.name));
instance.setWikiPage(nbt.getString(Tag.wikiPage));
instance.skills().readNBT(nbt, Tag.skills);
instance.effortPools().readNBT(nbt, Tag.effortPools);
instance.resources().readNBT(nbt, Tag.resources);
instance.needsGain().readNBT(nbt, Tag.needsRest);
instance.needsLost().readNBT(nbt, Tag.needsLost);
instance.potions().clear();
final NBTTagCompound potionsNbt = nbt.getCompoundTag(Tag.potions);
for (String key : potionsNbt.getKeySet()) {
final Potion p = Potion.getPotionFromResourceLocation(key);
if (p != null) {
instance.potions().put(p, (int) potionsNbt.getByte(key));
}
}
instance.enchants().clear();
final NBTTagCompound enchantsNbt = nbt.getCompoundTag(Tag.enchants);
for (String key : enchantsNbt.getKeySet()) {
final Enchantment e = Enchantment.getEnchantmentByLocation(key);
if (e != null) {
instance.enchants().put(e, (int) enchantsNbt.getByte(key));
}
}
if (nbt.hasKey(Tag.updated)) {
instance.setLastUpdated(nbt.getLong(Tag.updated));
}
}
private static class Tag {
private static final String name = "name";
private static final String wikiPage = "wiki";
private static final String skills = "skills";
private static final String effortPools = "effortPools";
private static final String resources = "Resources";
private static final String needsRest = "needsRest";
private static final String needsLost = "needsLost";
private static final String potions = "potions";
private static final String enchants = "enchants";
private static final String updated = "updated";
}
}
| 42.466667 | 115 | 0.675039 |
6cc457c6f73e6bc093cd0c48dfdb2d29d42a4703 | 3,797 | package com.alibaba.alink.operator.common.tensorflow;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.ml.api.misc.param.Params;
import org.apache.flink.table.api.TableSchema;
import com.alibaba.alink.common.dl.plugin.TFPredictorClassLoaderFactory;
import com.alibaba.alink.common.mapper.Mapper;
import com.alibaba.alink.common.utils.TableUtil;
import com.alibaba.alink.params.tensorflow.savedmodel.HasInputNames;
import com.alibaba.alink.params.tensorflow.savedmodel.HasOutputNames;
import com.alibaba.alink.params.tensorflow.savedmodel.TFSavedModelPredictParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Arrays;
/**
* Predict mapper for SavedModel. Different from {@link BaseTFSavedModelPredictMapper}, `modelPath` can be oss links or
* http/https links.
* <p>
* This mapper needs to be compatible with previous behaviours: 1. outputTypes are by default all strings; 2. Input
* signature defs and output signature defs are by default equal to TF input columns and output columns accordingly.
*/
public class TFSavedModelPredictMapper extends Mapper implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(TFSavedModelPredictMapper.class);
private final BaseTFSavedModelPredictMapper mapper;
public TFSavedModelPredictMapper(TableSchema dataSchema, Params params) {
this(dataSchema, params, new TFPredictorClassLoaderFactory());
}
public TFSavedModelPredictMapper(TableSchema dataSchema, Params params, TFPredictorClassLoaderFactory factory) {
super(dataSchema, params);
Params mapperParams = params.clone();
// Compatible with previous behaviors, where selected columns are equal to input names.
if (params.contains(HasInputNames.INPUT_NAMES)) {
String[] inputNames = params.get(HasInputNames.INPUT_NAMES);
mapperParams.set(TFSavedModelPredictParams.SELECTED_COLS, inputNames);
}
// Compatible with previous behaviors, where output columns are equal to output names, and types are strings.
if (params.contains(HasOutputNames.OUTPUT_NAMES)) {
String[] outputNames = params.get(HasOutputNames.OUTPUT_NAMES);
TypeInformation <?>[] outputTypes = new TypeInformation[outputNames.length];
Arrays.fill(outputTypes, Types.STRING);
TableSchema outputSchema = new TableSchema(outputNames, outputTypes);
mapperParams.set(TFSavedModelPredictParams.OUTPUT_SCHEMA_STR, TableUtil.schema2SchemaStr(outputSchema));
}
mapper = new BaseTFSavedModelPredictMapper(dataSchema, mapperParams, factory);
}
@Override
protected Tuple4 <String[], String[], TypeInformation <?>[], String[]> prepareIoSchema(TableSchema dataSchema,
Params params) {
String[] tfInputCols = params.get(TFSavedModelPredictParams.SELECTED_COLS);
if (null == tfInputCols) {
tfInputCols = dataSchema.getFieldNames();
}
String tfOutputSchemaStr = params.get(TFSavedModelPredictParams.OUTPUT_SCHEMA_STR);
TableSchema tfOutputSchema = TableUtil.schemaStr2Schema(tfOutputSchemaStr);
String[] reservedCols = params.get(TFSavedModelPredictParams.RESERVED_COLS);
return Tuple4.of(tfInputCols,
tfOutputSchema.getFieldNames(),
tfOutputSchema.getFieldTypes(),
reservedCols);
}
@Override
protected void map(SlicedSelectedSample selection, SlicedResult result) throws Exception {
mapper.map(selection, result);
}
@Override
public void open() {
String modelPath = params.get(TFSavedModelPredictParams.MODEL_PATH);
String localModelPath = TFSavedModelUtils.downloadSavedModel(modelPath);
mapper.setModelPath(localModelPath);
mapper.open();
}
@Override
public void close() {
mapper.close();
}
}
| 39.968421 | 119 | 0.792731 |
74a8bed7e6a7f22e19e4df5bc041df8e430f3a12 | 1,919 | package org.jobjects.myws2.orm.user;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.jobjects.myws2.tools.AbstractFacade;
import org.jobjects.myws2.tools.AppConstants;
/**
* EJB de la gestion des User.
* @author Mickaël Patron
* @version 2016-05-08
*
*/
@Stateless
@Local({ UserFacade.class })
public class UserStaless extends AbstractFacade<User> implements UserFacade {
/**
* Constructeur pour passer en paramètre le nom de la classe.
*/
public UserStaless() {
super(User.class);
}
/**
* EntityManager de serveur J2EE.
*/
@PersistenceContext(unitName = AppConstants.PERSISTENCE_UNIT_NAME)
private EntityManager entityManager;
/**
* @param entityManager
* the entityManager to set
*/
public void setEntityManager(final EntityManager entityManager) {
this.entityManager = entityManager;
}
/*
* (non-Javadoc)
* @see org.jobjects.myws.orm.tools.AbstractFacade#getEntityManager()
*/
@Override
public EntityManager getEntityManager() {
return entityManager;
}
/*
* (non-Javadoc)
* @see
* org.jobjects.myws.orm.user.UserFacade#findByFirstName(java.lang.String)
*/
public List<User> findByFirstName(final String firstName) {
TypedQuery<User> query = getEntityManager().createNamedQuery(User.FIND_BY_FIRSTNAME, User.class);
return query.setParameter("firstName", firstName).getResultList();
}
/*
* (non-Javadoc)
* @see org.jobjects.myws.orm.user.UserFacade#findByEmail(java.lang.String)
*/
public User findByEmail(final String email) {
User returnValue = null;
List<User> users = findByNamedQuery(User.FIND_BY_EMAIL, email);
for (User user : users) {
returnValue = user;
break;
}
return returnValue;
}
}
| 25.586667 | 101 | 0.71235 |
28ba7227b3a0b47ab463e48f6d982d61aa41754f | 1,319 | package com.intrack.session;
import com.intrack.io.XMLConfigBuilder;
import com.intrack.session.defaults.DefaultSqlSessionFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;
/**
* @author intrack
*/
public class SqlSessionFactoryBuilder {
/**
* Build session factory according to configuration file
*/
public SqlSessionFactory build(String filename) throws FileNotFoundException {
return build(new FileInputStream(filename));
}
public SqlSessionFactory build(InputStream stream) {
return build(stream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
XMLConfigBuilder configBuilder = new XMLConfigBuilder(inputStream, environment, properties);
return build(configBuilder.parse());
}
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
return build(new Configuration());
}
public SqlSessionFactory build(Configuration configuration) {
return new DefaultSqlSessionFactory(configuration);
}
}
| 27.479167 | 104 | 0.738438 |
a8077794326fe1f46f1ddd1b759405d493477ae6 | 541 | package org.zalando.riptide.micrometer.tag;
import io.micrometer.core.instrument.Tag;
import org.apiguardian.api.API;
import org.zalando.riptide.RequestArguments;
import static java.util.Collections.singleton;
import static org.apiguardian.api.API.Status.EXPERIMENTAL;
@API(status = EXPERIMENTAL)
public final class HttpMethodTagGenerator implements TagGenerator {
@Override
public Iterable<Tag> onRequest(final RequestArguments arguments) {
return singleton(Tag.of("http.method", arguments.getMethod().name()));
}
}
| 30.055556 | 78 | 0.783734 |
86629927d5f4ea52ca2005f2750e2832fbb22620 | 5,105 | /**
* Copyright (c) 2022
* All rights reserved.
*
* 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.
*
* 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.webexcc.api.demo.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
private Boolean active;
private String agentProfileId;
private String ciUserId;
private Boolean contactCenterEnabled;
private Long createdTime;
private String deafultDialledNumber;
private String email;
private String externalIdentifier;
private String firstName;
private String id;
private Boolean imiUserCreated;
private String lastName;
private Long lastUpdatedTime;
private String mobile;
private String multimediaProfileId;
private String siteId;
private String subscriptionId;
private List<String> teamIds = null;
private String userProfileId;
private String workPhone;
private String xspVersion;
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getAgentProfileId() {
return agentProfileId;
}
public void setAgentProfileId(String agentProfileId) {
this.agentProfileId = agentProfileId;
}
public String getCiUserId() {
return ciUserId;
}
public void setCiUserId(String ciUserId) {
this.ciUserId = ciUserId;
}
public Boolean getContactCenterEnabled() {
return contactCenterEnabled;
}
public void setContactCenterEnabled(Boolean contactCenterEnabled) {
this.contactCenterEnabled = contactCenterEnabled;
}
public Long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Long createdTime) {
this.createdTime = createdTime;
}
public String getDeafultDialledNumber() {
return deafultDialledNumber;
}
public void setDeafultDialledNumber(String deafultDialledNumber) {
this.deafultDialledNumber = deafultDialledNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExternalIdentifier() {
return externalIdentifier;
}
public void setExternalIdentifier(String externalIdentifier) {
this.externalIdentifier = externalIdentifier;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Boolean getImiUserCreated() {
return imiUserCreated;
}
public void setImiUserCreated(Boolean imiUserCreated) {
this.imiUserCreated = imiUserCreated;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(Long lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMultimediaProfileId() {
return multimediaProfileId;
}
public void setMultimediaProfileId(String multimediaProfileId) {
this.multimediaProfileId = multimediaProfileId;
}
public String getSiteId() {
return siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public String getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
}
public List<String> getTeamIds() {
return teamIds;
}
public void setTeamIds(List<String> teamIds) {
this.teamIds = teamIds;
}
public String getUserProfileId() {
return userProfileId;
}
public void setUserProfileId(String userProfileId) {
this.userProfileId = userProfileId;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getXspVersion() {
return xspVersion;
}
public void setXspVersion(String xspVersion) {
this.xspVersion = xspVersion;
}
}
| 22.688889 | 73 | 0.753575 |
07f0ef1ccce6ec4709253ea828f5d604a082ce9d | 3,526 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.Subsystem;
import frc.robot.Constants;
import frc.robot.subsystems.PixyVisionSubsystem;
import frc.robot.subsystems.WestCoastDriveTrain;
public class TrackBallWithPixyCommand extends CommandBase {
// instance variables
private WestCoastDriveTrain westCoastDriveTrain;
private PixyVisionSubsystem pixy;
private int maxTime;
private PIDController anglePID;
private PIDController distancePID;
private Timer timer;
private int timeInTargetArea;
/** Creates a new TrackBallWithPixyCommand. */
public TrackBallWithPixyCommand(WestCoastDriveTrain westCoastDriveTrain, PixyVisionSubsystem pixy, int maxTime) {
this.westCoastDriveTrain = westCoastDriveTrain;
this.maxTime = maxTime;
this.pixy = pixy;
anglePID = new PIDController(Constants.TRACK_BALL_WITH_PIXY_COMMAND_ANGLE_KP, Constants.TRACK_BALL_WITH_PIXY_COMMAND_ANGLE_KI, Constants.TRACK_BALL_WITH_PIXY_COMMAND_ANGLE_KD);
distancePID = new PIDController(Constants.TRACK_BALL_WITH_PIXY_COMMAND_DISTANCE_KP, Constants.TRACK_BALL_WITH_PIXY_COMMAND_DISTANCE_KI, Constants.TRACK_BALL_WITH_PIXY_COMMAND_DISTANCE_KD);
timer = new Timer();
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(westCoastDriveTrain);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
timer.reset();
timer.start();
anglePID.reset();
anglePID.setSetpoint(Constants.TRACK_BALL_WITH_PIXY_COMMAND_TARGET_TX);
distancePID.reset();
distancePID.setSetpoint(Constants.TRACK_BALL_WITH_PIXY_COMMAND_TARGET_TY);
timeInTargetArea = 0;
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if(pixy.getFilteredX() == null){
// There is no current pixy target
westCoastDriveTrain.simpleArcadeDrive(0, Constants.SAFE_TURN_RATE, false);
timeInTargetArea = 0;
System.out.println("NO TARGET");
}
else{
System.out.println("TERGET FOUND");
// There is a current pixy target
double x = pixy.getFilteredX();
double y = pixy.getFilteredY();
double linearPower = distancePID.calculate(y);
double angularPower = anglePID.calculate(x);
westCoastDriveTrain.simpleArcadeDrive(linearPower, -angularPower, false);
// Update ball in target zone counter
if(Math.abs(distancePID.getPositionError()) < Constants.TRACK_BALL_WITH_PIXY_COMMAND_TARGET_TY_TOLERANCE &&
Math.abs(anglePID.getPositionError()) < Constants.TRACK_BALL_WITH_PIXY_COMMAND_TARGET_TX_TOLERANCE){
timeInTargetArea ++;
}
}
System.out.println("SUS");
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
westCoastDriveTrain.stopArcadeDrive();
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
// Timer exit condition
if(timer.get() > maxTime){
return true;
}
// Found ball exit condition
return timeInTargetArea > Constants.TRACK_BALL_WITH_PIXY_COMMAND_TARGET_TIME_IN_TARGET_AREA;
}
}
| 35.616162 | 192 | 0.756665 |
761019b0f004197bc581ef4af7d18f5e959d21a0 | 2,892 | import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class FastCollinearPoints {
private LineSegment lineSegments[];
public FastCollinearPoints(Point[] points) {
if (points == null) {
throw new IllegalArgumentException();
}
for (Point p : points) {
if (p == null) {
throw new IllegalArgumentException();
}
}
Point[] sortedPoints = points.clone();
Arrays.sort(sortedPoints);
for (int i = 0; i < sortedPoints.length - 1; i++) {
if (sortedPoints[i].compareTo(sortedPoints[i + 1]) == 0) {
throw new IllegalArgumentException();
}
}
final int N = points.length;
List<LineSegment> list = new LinkedList<LineSegment>();
for (int i = 0; i < N; i++) {
Point p = sortedPoints[i];
Point[] sortedPointsBySlope = sortedPoints.clone();
Arrays.sort(sortedPointsBySlope, p.slopeOrder());
int j = 1;
while (j < N) {
LinkedList<Point> candidates = new LinkedList<Point>();
final double slopeRef = p.slopeTo(sortedPointsBySlope[j]);
do {
candidates.add(sortedPointsBySlope[j]);
j++;
} while (j < N && p.slopeTo(sortedPointsBySlope[j]) == slopeRef);
if (candidates.size() >= 3 && p.compareTo(candidates.peek()) < 0) {
Point min = p;
Point max = candidates.removeLast();
list.add(new LineSegment(min, max));
}
}
}
lineSegments = list.toArray(new LineSegment[0]);
}
public int numberOfSegments() {
return lineSegments.length;
}
public LineSegment[] segments() {
return lineSegments.clone();
}
public static void main(String[] args) {
// read the n points from a file
In in = new In(args[0]);
int n = in.readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
}
// draw the points
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : points) {
p.draw();
}
StdDraw.show();
// print and draw the line segments
FastCollinearPoints collinear = new FastCollinearPoints(points);
for (LineSegment segment : collinear.segments()) {
StdOut.println(segment);
segment.draw();
}
StdDraw.show();
}
}
| 30.765957 | 83 | 0.527663 |
86cc4805df2cfa7f623fac5dca131aa16dc189dd | 1,688 | import static spark.Spark.*;
import java.util.HashMap;
import spark.ModelAndView;
// import spark.template.velocity.VelocityTemplateEngine;
public class App {
public static void main(String[] args) {}
public static String numberToWord(String userInput) {
char[] userInputArray = userInput.toCharArray();
String test = "";
HashMap<Character, String> ones = new HashMap();
ones.put('1',"one");
ones.put('2',"two");
ones.put('3',"three");
ones.put('4',"four");
ones.put('5',"five");
ones.put('6',"six");
ones.put('7',"seven");
ones.put('8',"eight");
ones.put('9',"nine");
HashMap<Character, String> teens = new HashMap();
teens.put('0',"ten");
teens.put('1',"eleven");
teens.put('2',"twelve");
teens.put('3',"thirteen");
teens.put('4',"fourteen");
teens.put('5',"fifteen");
teens.put('6',"sixteen");
teens.put('7',"seventeen");
teens.put('8',"eighteen");
teens.put('9',"nineteen");
HashMap<Character, String> tens = new HashMap();
tens.put('1',"ten");
tens.put('2',"twenty");
tens.put('3',"thirty");
tens.put('4',"fourty");
tens.put('5',"fifty");
tens.put('6',"sixty");
tens.put('7',"seventy");
tens.put('8',"eighty");
tens.put('9',"ninety");
if (userInputArray.length == 1) {
test = ones.get(userInputArray[0]);
} else if ((userInputArray.length == 2) && (userInputArray[0] == '1')) { test = teens.get(userInputArray[1]);
} else {
test = tens.get(userInputArray[0]) + ones.get(userInputArray[1]);
}
return test;
}
}
| 29.103448 | 118 | 0.552133 |
cb3ce8a5f708d845c878a126f9a6ffb2504f5fea | 5,806 | package example;
import com.google.cloud.texttospeech.v1beta1.SsmlVoiceGender;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import vocalcord.CommandChain;
import vocalcord.UserStream;
import vocalcord.VocalCord;
public class ExampleBot extends ListenerAdapter implements VocalCord.Callbacks {
private final VocalCord cord;
public ExampleBot() {
/*
* This code will create the bot, make sure to specify the absolute paths of the files you downloaded to native to ensure all libraries
* are loaded correctly. This is also where you can config VocalCord settings.
*/
// Windows
cord = VocalCord.newConfig(this).withWakeDetection("C:\\Users\\wdavi\\IdeaProjects\\VocalCord\\native\\windows\\libjni_porcupine.dll",
"C:\\Users\\wdavi\\IdeaProjects\\VocalCord\\native\\windows\\libpv_porcupine.dll", "C:\\Users\\wdavi\\IdeaProjects\\VocalCord\\native\\porcupine_params.pv",
0.5f, "C:\\Users\\wdavi\\IdeaProjects\\VocalCord\\phrases\\hey_cord.ppn").withTTS(SsmlVoiceGender.MALE, true).build();
// Linux (using WSL)
// cord = VocalCord.newConfig(this).withWakeDetection("/mnt/c/Users/wdavi/IdeaProjects/VocalCord/native/linux/libjni_porcupine.so",
// "/mnt/c/Users/wdavi/IdeaProjects/VocalCord/native/linux/libpv_porcupine.so", "/mnt/c/Users/wdavi/IdeaProjects/VocalCord/native/porcupine_params.pv",
// 0.5f, "/mnt/c/Users/wdavi/IdeaProjects/VocalCord/phrases/linux.ppn").withTTS(SsmlVoiceGender.MALE, true).build();
}
public static void main(String[] args) throws Exception {
// Creates a JDA Discord instance and makes your bot go online
JDA api = JDABuilder.createDefault(/* YOUR BOT TOKEN HERE */args[0]).build();
api.addEventListener(new ExampleBot());
}
/*
* This callback defines which users are allowed to access VocalCord.
* Note, you want to be restrictive on this, especially for large servers,
* running wake word detection on like 50+ users simultaneously is untested and
* may affect performance.
*/
@Override
public boolean canWakeBot(User user) {
return true;
}
/*
* This method is called when an authorized user (canWakeBot(..) returned true)
* woke up the bot, the keywordIndex defines which keyword woke the bot (this depends
* on the order you specified keywords to when setting up VocalCord) If you only have one
* keyword, this will be 0. This method is useful for giving the user some feedback that the
* bot is listening, here for example, the bot will say "Yes?" when it's woken up. Immediately after
* this call, VocalCord will start generating a voice transcript of what the user said. If you want to cancel
* voice recognition here, you can call userStream.sleep()
*/
@Override
public void onWake(UserStream userStream, int keywordIndex) {
cord.say("Yes?");
}
/*
* Note: There are two onTranscribed(..) methods, you should only use one of them (this one is better)
* This callback is where you'll store all your voice commands. Importantly, voice transcripts aren't always
* 100% accurate. If you hard code a list of commands, being off by just one word wouldn't register the command,
* or trying to use lots of String.contains(..) calls could easily intermix commands. This callback employs
* CommandChain, which will generate document vectors and a document term matrix in order to compute the cosine
* similarity between a candidate transcription. Essentially, CommandChain will automatically run an algorithm to
* determine which command was most likely said. This means that a user doesn't have to be 100% accurate on matching a command,
* and instead only needs to capture the meaning of a command.
*/
@Override
public CommandChain onTranscribed() {
return new CommandChain.Builder().addPhrase("hello world", (user, transcript, args) -> {
cord.say(user.getName()+" said something");
})
.addPhrase("knock knock", (user, transcript, args) -> {
cord.say("Who's there?");
}).withFallback(((user, transcript, args) -> {
cord.say("I'm sorry, I didn't get that");
})).withMinThreshold(0.5f).build();
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
// Don't process messages from other bots
if(event.getAuthor().isBot()) return;
Message message = event.getMessage();
String content = message.getContentRaw();
if(content.startsWith("!say")) {
cord.say(content.substring(5));
}
/*
* This is a basic summon command that will summon the bot to
* whatever voice channel the author is in, this is a really basic
* summon command, but you can develop more advanced scenarios where
* the bot follows you around or whatever.
*/
if(content.equals("!summon")) {
event.getMessage().getChannel().sendMessage("On my way!").queue();
try {
VoiceChannel authorVoiceChannel = event.getMember().getVoiceState().getChannel();
cord.connect(authorVoiceChannel);
} catch(Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onTTSCompleted() {
// If you want to do anything after the bot stops speaking
}
} | 47.203252 | 172 | 0.677747 |
3ad9162ab744929c3a2113ba06983e2a5877114d | 1,096 | package pl.czakanski.thesis.nanoservice.user.activation.controller.v1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.client.RestTemplate;
import pl.czakanski.thesis.common.helpers.NanoserviceConstant;
import pl.czakanski.thesis.common.request.ConstantRequest;
@Controller
@RequestMapping(value = ConstantRequest.USER)
public class UserActivingController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = ConstantRequest.USER_ACTIVATION, method = RequestMethod.GET)
public ResponseEntity activeUserAccount(@PathVariable(ConstantRequest.ID_PATH) final int userId) {
return restTemplate.getForEntity(NanoserviceConstant.USER_SERVICE + ConstantRequest.USER +"/" + userId + ConstantRequest.USER_ACTIVE, null);
}
}
| 42.153846 | 148 | 0.828467 |
c2d027fb4d994a7642bf6c54a54fa738d6fe6ba0 | 692 | package net.endhq.remoteentities.api.events;
import net.endhq.remoteentities.api.RemoteEntity;
import net.endhq.remoteentities.api.pathfinding.CancelReason;
import org.bukkit.event.HandlerList;
public class RemotePathCancelEvent extends RemoteEvent
{
private static final HandlerList handlers = new HandlerList();
private final CancelReason m_reason;
public RemotePathCancelEvent(RemoteEntity inEntity, CancelReason inReason)
{
super(inEntity);
this.m_reason = inReason;
}
public CancelReason getReason()
{
return this.m_reason;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
} | 20.352941 | 75 | 0.787572 |
f8d6894af0cfbf22cd50db41282852f47d8fc8b9 | 2,036 | import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.PredictionMode;
import java.lang.reflect.Method;
import java.util.List;
/*$PackageName*/import __PackageName__.*;/*PackageName$*/
public class Main {
public static void main(String[] args) {
try {
String fileName = "../../Text";
if (args.length > 0) {
fileName = args[0];
}
CharStream codeStream = CharStreams.fromFileName(fileName);
__TemplateLexerName__ lexer = new __TemplateLexerName__(codeStream);
List<? extends Token> tokens = lexer.getAllTokens();
/*$ParserPart*/
String rootRule = null;
String mode = "ll";
if (args.length > 1) {
rootRule = args[1];
if (args.length > 2) {
// TODO: process OnlyTokenize parameter
if (args.length > 3) {
mode = args[3].toLowerCase();
}
}
}
ListTokenSource tokensSource = new ListTokenSource(tokens);
CommonTokenStream tokensStream = new CommonTokenStream(tokensSource);
__TemplateParserName__ parser = new __TemplateParserName__(tokensStream);
PredictionMode predictionMode = mode.equals("sll")
? PredictionMode.SLL
: mode.equals("ll")
? PredictionMode.LL
: PredictionMode.LL_EXACT_AMBIG_DETECTION;
parser.getInterpreter().setPredictionMode(predictionMode);
String ruleName = rootRule == null ? __TemplateParserName__.ruleNames[0] : rootRule;
Method parseMethod = __TemplateParserName__.class.getDeclaredMethod(ruleName);
ParserRuleContext ast = (ParserRuleContext)parseMethod.invoke(parser);
String stringTree = ast.toStringTree(parser);
System.out.print("Tree " + stringTree);
/*ParserPart$*/
}
catch (Exception e) {
}
}
}
| 37.703704 | 96 | 0.576621 |
49a7e4ca47be74caf0b61fe6ea94899f593fdd30 | 379 | package io.shaka.some;
public class SomeValues {
public static <T> T some(SomeBuilder<T> builder) {
return builder.build();
}
public static SomeStringBuilder string = SomeStringBuilder.string;
public static SomeIntegerBuilder integer = SomeIntegerBuilder.integer;
public static SomeIntegerBuilder naturalNumber = SomeIntegerBuilder.naturalNumber;
}
| 31.583333 | 86 | 0.759894 |
19be4567cade9b8719bcd9d4239173b228d11e62 | 1,618 | /*
* PlanePane.java
*
* $Id: LeftPane.java,v 1.2 2008/02/27 15:00:16 marco Exp $
*
* 04/gen/08
*
* Copyright notice
*/
package org.mmarini.atc.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.mmarini.atc.sim.AtcHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author marco.marini@mmarini.org
* @version $Id: LeftPane.java,v 1.2 2008/02/27 15:00:16 marco Exp $
*/
public class LeftPane extends JPanel {
private static Logger log = LoggerFactory.getLogger(LeftPane.class);
/**
*
*/
private static final long serialVersionUID = 1L;
private PlanePane planePane;
private LogPane logPane;
/**
*
*/
public LeftPane() {
planePane = new PlanePane();
logPane = new LogPane();
createContent();
}
/**
*
*
*/
private void createContent() {
log.debug("init");
setPreferredSize(new Dimension(200, 10));
setLayout(new BorderLayout());
setBackground(Color.BLACK);
add(planePane, BorderLayout.CENTER);
JScrollPane scrollPane1 = new JScrollPane(logPane);
add(scrollPane1, BorderLayout.SOUTH);
}
/**
*
*/
public void init() {
logPane.clear();
}
/**
*
*/
public void refresh() {
planePane.refresh();
logPane.refresh();
}
/**
*
* @param atcHandler
*/
public void setAtcHandler(AtcHandler atcHandler) {
planePane.setAtcHandler(atcHandler);
logPane.setAtcHandler(atcHandler);
}
}
| 18.597701 | 70 | 0.629172 |
4c904108e0a0a03e195500c27f2d90c34f156a21 | 9,473 | package com.linkedin.platform;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.linkedin.platform.errors.LIAppErrorCode;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.internals.AppStore;
import com.linkedin.platform.internals.LIAppVersion;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;
import java.util.List;
/**
*
* LISessionManager manages the authorizations needed for an application
* to access LinkedIn data and to view LinkedIn profiles.
*
* A typical usage flow is:
*
* LISessionManager.init(activity, Scope.build(LIPermission.R_BASICPROFILE), callback, true);
*
* When callback.onAuthSuccess() is called, calls to {@link APIHelper}
* to retrieve LinkedIn data or calls to {@link DeepLinkHelper} can be
* made to view LinkedIn profiles.
* {@link LISession#isValid()} should be used to validate the session before
* making api calls or deeplink calls
*
*/
public class LISessionManager {
private static final String TAG = LISessionManager.class.getSimpleName();
private static final int LI_SDK_AUTH_REQUEST_CODE = 3672;
private static final String AUTH_TOKEN = "token";
private static final String AUTH_STATE = "state";
private static final String LI_APP_PACKAGE_NAME = "com.linkedin.android";
private static final String LI_APP_AUTH_CLASS_NAME = "com.linkedin.android.liauthlib.thirdparty.LiThirdPartyAuthorizeActivity";
private static final String SCOPE_DATA = "com.linkedin.thirdpartysdk.SCOPE_DATA";
private static final String LI_APP_ACTION_AUTHORIZE_APP = "com.linkedin.android.auth.AUTHORIZE_APP";
private static final String LI_APP_CATEGORY = "com.linkedin.android.auth.thirdparty.authorize";
private static final String LI_ERROR_INFO = "com.linkedin.thirdparty.authorize.RESULT_ACTION_ERROR_INFO";
private static final String LI_ERROR_DESCRIPTION = "com.linkedin.thirdparty.authorize.RESULT_ACTION_ERROR_DESCRIPTION";
private static LISessionManager sessionManager;
private Context ctx;
private LISessionImpl session;
private AuthListener authListener;
public static LISessionManager getInstance(@NonNull Context context) {
if (sessionManager == null) {
sessionManager = new LISessionManager();
}
if (context != null && sessionManager.ctx == null) {
sessionManager.ctx = context.getApplicationContext();
}
return sessionManager;
}
private LISessionManager() {
this.session = new LISessionImpl();
}
/**
* Initializes LISession using previously obtained AccessToken
* The passed in access token should be one that was obtained from the LinkedIn Mobile SDK.
*
* @param accessToken access token
*/
public void init(AccessToken accessToken) {
session.setAccessToken(accessToken);
}
/**
* Brings the user to an authorization screen which allows the user to authorize
* the application to access their LinkedIn data. When the user authorizes the application
* {@link AuthListener#onAuthSuccess()} is called.
* If the user has previously authorized the application, onAuthSuccess will be called without
* the authorization screen being shown.
*
* If there is no user logged into the LinkedIn application, the user will be prompted to login
* to LinkedIn, after which the authorization screen will be shown.
*
* Either this method or {@link LISessionManager#init(AccessToken)} must be
* called before the application can make API calls or DeepLink calls.
*
* @param activity activity to return to after initialization
* @param scope The type of LinkedIn data that for which access is requested.
* see {@link Scope}
* @param callback listener to execute on completion
* @param showGoToAppStoreDialog determines behaviour when the LinkedIn app is not installed
* if true, a dialog is shown which prompts the user to install
* the LinkedIn app via the app store. If false, the user is
* taken directly to the app store.
*
*/
public void init(Activity activity,
Scope scope, AuthListener callback, boolean showGoToAppStoreDialog) {
//check if LI
if (!LIAppVersion.isLIAppCurrent(ctx)) {
AppStore.goAppStore(activity, showGoToAppStoreDialog);
return;
}
authListener = callback;
Intent i = new Intent();
i.setClassName(LI_APP_PACKAGE_NAME, LI_APP_AUTH_CLASS_NAME);
i.putExtra(SCOPE_DATA, scope.createScope());
i.setAction(LI_APP_ACTION_AUTHORIZE_APP);
i.addCategory(LI_APP_CATEGORY);
try {
activity.startActivityForResult(i, LI_SDK_AUTH_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
Log.d(TAG, e.getMessage());
}
}
/**
* This method must be called in the calling Activity's onActivityResult in order to
* process the response to
* {@link LISessionManager#init(Activity, Scope, AuthListener, boolean)}
* @param activity
* @param requestCode
* @param resultCode
* @param data
*/
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
// set access token
if (authListener != null && requestCode == LI_SDK_AUTH_REQUEST_CODE) {
// got result
if (resultCode == Activity.RESULT_OK) {
String token = data.getStringExtra(AUTH_TOKEN);
long expiresOn = data.getLongExtra("expiresOn", 0L);
AccessToken accessToken = new AccessToken(token, expiresOn);
init(accessToken);
// call the callback with the
authListener.onAuthSuccess();
} else if (resultCode == Activity.RESULT_CANCELED) {
authListener.onAuthError(new LIAuthError(LIAppErrorCode.USER_CANCELLED, "user canceled"));
} else {
String errorInfo = data.getStringExtra(LI_ERROR_INFO);
String errorDesc = data.getStringExtra(LI_ERROR_DESCRIPTION);
authListener.onAuthError(new LIAuthError(errorInfo, errorDesc));
}
authListener = null;
}
}
/**
* @return the LISession
*/
public LISession getSession() {
return session;
}
/**
* Clears the session. Calls to retrieve LinkedIn data or to view profiles will no longer
* work.
*/
public void clearSession() {
session.setAccessToken(null);
}
/**
* Builds scope based on List of permissions.
*
* @param perms
* @return
*/
private static String createScope(List<String> perms) {
if (perms == null || perms.isEmpty()) {
return "";
}
return TextUtils.join(" ", perms);
}
/**
* private implementation of LISession
* takes are of saving and restoring session to/from shared preferences
*/
private static class LISessionImpl implements LISession {
private static final String LI_SDK_SHARED_PREF_STORE = "li_shared_pref_store";
private static final String SHARED_PREFERENCES_ACCESS_TOKEN = "li_sdk_access_token";
private AccessToken accessToken = null;
public LISessionImpl() {
}
@Override
public AccessToken getAccessToken() {
if (accessToken == null) {
recover();
}
return accessToken;
}
void setAccessToken(@Nullable AccessToken accessToken) {
this.accessToken = accessToken;
save();
}
/**
* @return true if a valid accessToken is present. Note that if the member revokes
* access to this application, this will still return true
*/
@Override
public boolean isValid() {
AccessToken at = getAccessToken();
return at != null && !at.isExpired();
}
/**
* clears session. (Kills it)
*/
public void clear() {
setAccessToken(null);
}
/**
* Storage
*/
private SharedPreferences getSharedPref() {
return LISessionManager.sessionManager.ctx.getSharedPreferences(LI_SDK_SHARED_PREF_STORE, Context.MODE_PRIVATE);
}
private void save() {
SharedPreferences.Editor edit = getSharedPref().edit();
edit.putString(SHARED_PREFERENCES_ACCESS_TOKEN, accessToken == null ? null : accessToken.toString());
edit.commit();
}
private void recover() {
SharedPreferences sharedPref = getSharedPref();
String accessTokenStr = sharedPref.getString(SHARED_PREFERENCES_ACCESS_TOKEN, null);
accessToken = accessTokenStr == null ? null : AccessToken.buildAccessToken(accessTokenStr);
}
}
}
| 37.59127 | 131 | 0.65597 |
4a78f9eb764057cd18d0820e66549160f122fd6e | 512 | package com.ygy.dao;
import com.ygy.model.User;
import com.ygy.model.UserFollow;
/**
* @author ygy
* @date 2018/5/30
* 将用户信息放在redis数据中
*/
public interface RedisDao {
/**
* 增加关注
*
* @param
* @param
*/
void add(UserFollow user);
/**
* 删除关注
*
* @param
*/
void delete(UserFollow user);
/**
* 注册用户
* @param user
*/
void addUser(User user);
/**
* 删除用户
* @param userid
*/
void deleteUser(long userid);
} | 13.473684 | 33 | 0.509766 |
b9d7765226620f0c0c9194e3c3b682e6d0f166a6 | 8,686 | /*
* The MIT License
*
* Copyright (c) 2019 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.util;
import htsjdk.samtools.SAMSequenceDictionaryCodec;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.samtools.util.SortingCollection;
import htsjdk.samtools.util.StringUtil;
import picard.PicardException;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Class with helper methods for generating and writing SequenceDictionary objects.
*/
public class SequenceDictionaryUtils {
static public class SamSequenceRecordsIterator implements Iterator<SAMSequenceRecord> {
final private boolean truncateNamesAtWhitespace;
final private ReferenceSequenceFile refSeqFile;
private String genomeAssembly;
private String uri;
public void setGenomeAssembly(final String genomeAssembly) {
this.genomeAssembly = genomeAssembly;
}
public void setUri(final String uri) {
this.uri = uri;
}
public void setSpecies(final String species) {
this.species = species;
}
private String species;
private ReferenceSequence nextRefSeq;
private final MessageDigest md5;
public SamSequenceRecordsIterator(File referenceSequence, boolean truncateNamesAtWhitespace) {
this.truncateNamesAtWhitespace = truncateNamesAtWhitespace;
this.refSeqFile = ReferenceSequenceFileFactory.
getReferenceSequenceFile(referenceSequence, truncateNamesAtWhitespace);
this.nextRefSeq = refSeqFile.nextSequence();
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new PicardException("MD5 algorithm not found", e);
}
}
private String md5Hash(final byte[] bytes) {
md5.reset();
md5.update(bytes);
String s = new BigInteger(1, md5.digest()).toString(16);
if (s.length() != 32) {
final String zeros = "00000000000000000000000000000000";
s = zeros.substring(0, 32 - s.length()) + s;
}
return s;
}
/**
* Create one SAMSequenceRecord from a single fasta sequence
*/
private SAMSequenceRecord makeSequenceRecord(final ReferenceSequence refSeq) {
final SAMSequenceRecord ret = new SAMSequenceRecord(refSeq.getName(), refSeq.length());
// Compute MD5 of upcased bases
final byte[] bases = refSeq.getBases();
for (int i = 0; i < bases.length; ++i) {
bases[i] = StringUtil.toUpperCase(bases[i]);
}
ret.setAttribute(SAMSequenceRecord.MD5_TAG, md5Hash(bases));
if (genomeAssembly != null) {
ret.setAttribute(SAMSequenceRecord.ASSEMBLY_TAG, genomeAssembly);
}
ret.setAttribute(SAMSequenceRecord.URI_TAG, uri);
if (species != null) {
ret.setAttribute(SAMSequenceRecord.SPECIES_TAG, species);
}
return ret;
}
@Override
public boolean hasNext() {
return nextRefSeq != null;
}
@Override
public SAMSequenceRecord next() {
if (!hasNext()) {
throw new NoSuchElementException("next() was called when hasNext() was false.");
}
final SAMSequenceRecord samSequenceRecord = makeSequenceRecord(nextRefSeq);
nextRefSeq = refSeqFile.nextSequence();
return samSequenceRecord;
}
}
/**
* Encodes a sequence dictionary
*
* @param writer a Buffered writer into which the dictionary will be written
* @param samSequenceRecordIterator an iterator that produces SAMSequenceRecords
* @throws IllegalArgumentException if the iterator produces two SAMSequenceRecord with the same name
*/
public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) {
final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer);
samDictCodec.encodeHeaderLine(false);
// SortingCollection is used to check uniqueness of sequence names
final SortingCollection<String> sequenceNames = makeSortingCollection();
// read reference sequence one by one and write its metadata
while (samSequenceRecordIterator.hasNext()) {
final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next();
samDictCodec.encodeSequenceRecord(samSequenceRecord);
sequenceNames.add(samSequenceRecord.getSequenceName());
}
// check uniqueness of sequences names
final CloseableIterator<String> iterator = sequenceNames.iterator();
if (!iterator.hasNext()) {
return;
}
String current = iterator.next();
while (iterator.hasNext()) {
final String next = iterator.next();
if (current.equals(next)) {
throw new PicardException("Sequence name " + current +
" appears more than once in reference file");
}
current = next;
}
}
public static SortingCollection<String> makeSortingCollection() {
final File tmpDir = IOUtil.createTempDir("SamDictionaryNames", null);
tmpDir.deleteOnExit();
// 256 byte for one name, and 1/10 part of all memory for this, rough estimate
long maxNamesInRam = Runtime.getRuntime().maxMemory() / 256 / 10;
return SortingCollection.newInstance(
String.class,
new StringCodec(),
String::compareTo,
(int) Math.min(maxNamesInRam, Integer.MAX_VALUE),
tmpDir.toPath()
);
}
private static class StringCodec implements SortingCollection.Codec<String> {
private DataInputStream dis;
private DataOutputStream dos;
public StringCodec clone() {
return new StringCodec();
}
public void setOutputStream(final OutputStream os) {
dos = new DataOutputStream(os);
}
public void setInputStream(final InputStream is) {
dis = new DataInputStream(is);
}
public void encode(final String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
public String decode() {
try {
return dis.readUTF();
} catch (EOFException e) {
return null;
} catch (IOException e) {
throw new PicardException("Exception reading sequence name from temporary file.", e);
}
}
}
}
| 37.765217 | 125 | 0.652084 |
e1f79745ce4a8fdd53315cbf5d72f21cc332b614 | 1,785 | package contest.usaco;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class USACO_2014_Reordering_The_Cows {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static boolean[] visited = new boolean[0];
public static void main(String[] args) throws IOException {
int n = readInt();
visited = new boolean[n];
int[] start = new int[n];
int[] end = new int[n];
int[] endLoc = new int[n];
for (int x = 0; x < n; x++)
start[x] = readInt();
for (int x = 0; x < n; x++) {
end[x] = readInt();
endLoc[end[x] - 1] = x;
}
int max = 0;
int count = 0;
for (int x = 0; x < n; x++) {
if (start[x] != end[x] && !visited[x]) {
max = Math.max(getCycle(x, endLoc, start), max);
count++;
}
}
System.out.println(count + " " + (max == 0 ? -1 : max));
}
public static int getCycle(int start, int[] endLoc, int[] startLoc) {
int count = 0;
int curr = start;
while (start != curr || count == 0) {
visited[curr] = true;
curr = endLoc[startLoc[curr] - 1];
count++;
}
return count;
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
| 25.5 | 82 | 0.602241 |
508f4bb1bce4cda5468715fd057a01c45478c797 | 6,471 | package net.kunmc.lab.commondestiny;
import com.destroystokyo.paper.event.server.ServerTickStartEvent;
import net.kunmc.lab.commondestiny.config.ConfigManager;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.util.HashMap;
import java.util.Map;
public class PairingListener implements Listener {
private final Map<Player, BukkitTask> differentWorldTimers = new HashMap<>();
private void startDifferentWorldTimer(Player player1, Player player2) {
ConfigManager configManager = CommonDestinyPlugin.getConfigManager();
long differentWorldTimer = configManager.getDifferentWorldTimer();
BukkitTask task = Bukkit.getScheduler().runTaskLater(CommonDestinyPlugin.getInstance(), () -> {
if (configManager.isEnabled() && !player1.isDead()) {
player1.setHealth(0);
}
stopDifferentWorldTimer(player1, player2);
}, differentWorldTimer);
differentWorldTimers.put(player1, task);
differentWorldTimers.put(player2, task);
}
private void stopDifferentWorldTimer(Player player1, Player player2) {
if (differentWorldTimers.containsKey(player1)) {
differentWorldTimers.get(player1).cancel();
}
if (differentWorldTimers.containsKey(player2)) {
differentWorldTimers.remove(player2).cancel();
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
PairingManager manager = CommonDestinyPlugin.getPairingManager();
Player player = event.getPlayer();
Player lastPartner = manager.getLastPartner(player);
if (lastPartner == null) {
return;
}
Player rev = manager.getLastPartner(lastPartner);
if (player.equals(rev)) {
manager.form(player, lastPartner, false);
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
PairingManager manager = CommonDestinyPlugin.getPairingManager();
Player player = event.getPlayer();
if (manager.hasPartner(player)) {
manager.dissolve(player, true);
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
ConfigManager configManager = CommonDestinyPlugin.getConfigManager();
PairingManager manager = CommonDestinyPlugin.getPairingManager();
if (!configManager.isEnabled()) {
return;
}
Player player = event.getEntity();
if (!manager.hasPartner(player)) {
return;
}
Player partner = manager.getPartner(player);
if (!partner.isDead()) {
partner.setHealth(0);
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
ConfigManager configManager = CommonDestinyPlugin.getConfigManager();
if (!configManager.isEnabled()) {
return;
}
PairingManager manager = CommonDestinyPlugin.getPairingManager();
Player player = event.getPlayer();
if (!manager.hasPartner(player)) {
return;
}
Player partner = manager.getPartner(player);
if (!partner.isDead()) {
event.setRespawnLocation(partner.getLocation());
}
}
@EventHandler
public void onPlayerChangeWorld(PlayerChangedWorldEvent event) {
ConfigManager configManager = CommonDestinyPlugin.getConfigManager();
if (!configManager.isEnabled()) {
return;
}
PairingManager manager = CommonDestinyPlugin.getPairingManager();
Player player = event.getPlayer();
if (!manager.hasPartner(player)) {
return;
}
Player partner = manager.getPartner(player);
if (!player.getWorld().equals(partner.getWorld())) {
startDifferentWorldTimer(player, partner);
} else {
stopDifferentWorldTimer(player, partner);
}
}
@EventHandler
public void onTick(ServerTickStartEvent event) {
ConfigManager configManager = CommonDestinyPlugin.getConfigManager();
PairingManager manager = CommonDestinyPlugin.getPairingManager();
if (!configManager.isEnabled()) {
return;
}
double range = configManager.getRange();
for (PairResult pair : manager.pairs()) {
if (pair.player1.isDead() || pair.player2.isDead()) {
continue;
}
if (!pair.player1.getWorld().equals(pair.player2.getWorld())) {
continue;
}
Location location1 = pair.player1.getEyeLocation().clone().add(pair.player1.getLocation()).multiply(0.5);
Location location2 = pair.player2.getEyeLocation().clone().add(pair.player2.getLocation()).multiply(0.5);
double distance = location1.distance(location2);
if (distance > range) {
pair.player1.setHealth(0);
continue;
}
Color color;
if (distance < range * 0.6) {
color = Color.WHITE;
} else if (distance < range * 0.8) {
color = Color.YELLOW;
} else {
color = Color.RED;
}
drawLine(location1, location2, color, event.getTickNumber() % 20);
drawLine(location2, location1, color, event.getTickNumber() % 20);
}
}
private void drawLine(Location loc1, Location loc2, Color color, int tick) {
double distance = loc1.distance(loc2);
loc1 = loc1.clone();
int numParticle = Math.max(3, (int)distance);
Vector vector = loc2.clone().subtract(loc1).toVector().multiply(1.0 / numParticle);
World world = loc1.getWorld();
loc1.add(vector.clone().multiply(tick / 20.0));
Particle.DustOptions dustOptions = new Particle.DustOptions(color, 1);
for (int i = 0; i < numParticle; i++) {
world.spawnParticle(Particle.REDSTONE, loc1, 0, dustOptions);
loc1.add(vector);
}
}
}
| 38.064706 | 117 | 0.633442 |
315543150192b8b627f0e61817683244e8ef3704 | 7,414 | /**
*
* Copyright (c) Microsoft and contributors. 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.
*
*/
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
package com.microsoft.windowsazure.management.websites.models;
import com.microsoft.windowsazure.core.LazyArrayList;
import java.util.ArrayList;
import java.util.Calendar;
/**
* A specific backup.
*/
public class BackupItem {
private String blobName;
/**
* Optional. The blob name where the backup is stored, e.g.
* mysite1_20140506.zip
* @return The BlobName value.
*/
public String getBlobName() {
return this.blobName;
}
/**
* Optional. The blob name where the backup is stored, e.g.
* mysite1_20140506.zip
* @param blobNameValue The BlobName value.
*/
public void setBlobName(final String blobNameValue) {
this.blobName = blobNameValue;
}
private String correlationId;
/**
* Optional. Internal correlation identifier - identifies a specific backup.
* @return The CorrelationId value.
*/
public String getCorrelationId() {
return this.correlationId;
}
/**
* Optional. Internal correlation identifier - identifies a specific backup.
* @param correlationIdValue The CorrelationId value.
*/
public void setCorrelationId(final String correlationIdValue) {
this.correlationId = correlationIdValue;
}
private Calendar created;
/**
* Optional. Timestamp when the backup has been created.
* @return The Created value.
*/
public Calendar getCreated() {
return this.created;
}
/**
* Optional. Timestamp when the backup has been created.
* @param createdValue The Created value.
*/
public void setCreated(final Calendar createdValue) {
this.created = createdValue;
}
private ArrayList<DatabaseBackupSetting> databases;
/**
* Optional. Database settings for backup.
* @return The Databases value.
*/
public ArrayList<DatabaseBackupSetting> getDatabases() {
return this.databases;
}
/**
* Optional. Database settings for backup.
* @param databasesValue The Databases value.
*/
public void setDatabases(final ArrayList<DatabaseBackupSetting> databasesValue) {
this.databases = databasesValue;
}
private Calendar finishedTimeStamp;
/**
* Optional. Timestamp when this backup has been finished and a zip file has
* been uploaded to a storage account.
* @return The FinishedTimeStamp value.
*/
public Calendar getFinishedTimeStamp() {
return this.finishedTimeStamp;
}
/**
* Optional. Timestamp when this backup has been finished and a zip file has
* been uploaded to a storage account.
* @param finishedTimeStampValue The FinishedTimeStamp value.
*/
public void setFinishedTimeStamp(final Calendar finishedTimeStampValue) {
this.finishedTimeStamp = finishedTimeStampValue;
}
private Calendar lastRestoreTimeStamp;
/**
* Optional. Timestamp when this backup has been used for a restore
* operation (empty if it wasn't).
* @return The LastRestoreTimeStamp value.
*/
public Calendar getLastRestoreTimeStamp() {
return this.lastRestoreTimeStamp;
}
/**
* Optional. Timestamp when this backup has been used for a restore
* operation (empty if it wasn't).
* @param lastRestoreTimeStampValue The LastRestoreTimeStamp value.
*/
public void setLastRestoreTimeStamp(final Calendar lastRestoreTimeStampValue) {
this.lastRestoreTimeStamp = lastRestoreTimeStampValue;
}
private String log;
/**
* Optional. Information about the backup, usually used only if there was an
* error.
* @return The Log value.
*/
public String getLog() {
return this.log;
}
/**
* Optional. Information about the backup, usually used only if there was an
* error.
* @param logValue The Log value.
*/
public void setLog(final String logValue) {
this.log = logValue;
}
private String name;
/**
* Optional. The name of this backup.
* @return The Name value.
*/
public String getName() {
return this.name;
}
/**
* Optional. The name of this backup.
* @param nameValue The Name value.
*/
public void setName(final String nameValue) {
this.name = nameValue;
}
private boolean scheduled;
/**
* Optional. True if this backup has been created as a part of a scheduled
* backup; false otherwise.
* @return The Scheduled value.
*/
public boolean isScheduled() {
return this.scheduled;
}
/**
* Optional. True if this backup has been created as a part of a scheduled
* backup; false otherwise.
* @param scheduledValue The Scheduled value.
*/
public void setScheduled(final boolean scheduledValue) {
this.scheduled = scheduledValue;
}
private long sizeInBytes;
/**
* Optional. Size of the backup zip file in bytes.
* @return The SizeInBytes value.
*/
public long getSizeInBytes() {
return this.sizeInBytes;
}
/**
* Optional. Size of the backup zip file in bytes.
* @param sizeInBytesValue The SizeInBytes value.
*/
public void setSizeInBytes(final long sizeInBytesValue) {
this.sizeInBytes = sizeInBytesValue;
}
private BackupItemStatus status;
/**
* Optional. The status of the backup - e.g. Succeeded or Failed
* @return The Status value.
*/
public BackupItemStatus getStatus() {
return this.status;
}
/**
* Optional. The status of the backup - e.g. Succeeded or Failed
* @param statusValue The Status value.
*/
public void setStatus(final BackupItemStatus statusValue) {
this.status = statusValue;
}
private String storageAccountUrl;
/**
* Optional. SAS URL for a container in a storage account.
* @return The StorageAccountUrl value.
*/
public String getStorageAccountUrl() {
return this.storageAccountUrl;
}
/**
* Optional. SAS URL for a container in a storage account.
* @param storageAccountUrlValue The StorageAccountUrl value.
*/
public void setStorageAccountUrl(final String storageAccountUrlValue) {
this.storageAccountUrl = storageAccountUrlValue;
}
/**
* Initializes a new instance of the BackupItem class.
*
*/
public BackupItem() {
this.setDatabases(new LazyArrayList<DatabaseBackupSetting>());
}
}
| 27.664179 | 85 | 0.654303 |
c5c95e9aedb0c02d6e49c70ab60e5f8016236637 | 1,355 | /**
*
* Copyright 2012 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* Original project:
*
* 2017 Rewrite in Kotlin by JonathanxD <https://github.com/JonathanxD>
*
* 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.github.jonathanxd.controlflowhelper.util;
import com.github.jonathanxd.iutils.opt.specialized.OptInt;
public final class LateInt {
private OptInt opt = OptInt.none();
public LateInt() {
}
public LateInt(int i) {
this.init(i);
}
public void init(int i) {
if (opt.isPresent())
throw new IllegalStateException("Already initialized");
this.opt = OptInt.optInt(i);
}
public int getValue() {
if (!opt.isPresent())
throw new IllegalStateException("Not initialized yet!");
return opt.getValue();
}
}
| 26.568627 | 76 | 0.676015 |
97392653fea81937bbc82eb72d8c771201a8ac76 | 456 | package studio.csuk.javabridge;
public class RunResult extends AbstractResult{
public RunResult(State state, String error, int lineNumber, String output) {
super(error, lineNumber, output);
this.state = state;
}
private State state;
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public enum State{
SUCCESS, FAIL;
};
}
| 17.538462 | 80 | 0.622807 |
f258cbd4741a7f0576fef86e8323ab8caf4efdc2 | 2,564 | package com.haoict.tiab.commands;
import com.haoict.tiab.Config;
import com.haoict.tiab.item.ItemTimeInABottle;
import com.haoict.tiab.utils.SendMessage;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.command.arguments.MessageArgument;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
public class TiabCommands {
public static void register(CommandDispatcher<CommandSource> dispatcher) {
LiteralArgumentBuilder<CommandSource> tiabCommands
= Commands.literal("tiab")
.requires((commandSource) -> commandSource.hasPermissionLevel(2))
.then(Commands.literal("addtime")
.then(Commands.argument("timeToAdd", MessageArgument.message())
.executes((ctx) -> {
ITextComponent messageValue = MessageArgument.getMessage(ctx, "timeToAdd");
CommandSource source = ctx.getSource();
ServerPlayerEntity player = source.asPlayer();
if (!messageValue.getString().isEmpty()) {
try {
int timeToAdd = Integer.parseInt(messageValue.getString());
if (timeToAdd > Config.MAX_STORED_TIME / 20) {
timeToAdd = Config.MAX_STORED_TIME / 20;
}
ItemStack currentItem = player.inventory.getCurrentItem();
if (currentItem.getItem() instanceof ItemTimeInABottle) {
ItemTimeInABottle.setStoredTime(currentItem, ItemTimeInABottle.getStoredTime(currentItem) + timeToAdd * Config.TICK_CONST);
SendMessage.sendMessage(player, "Added " + timeToAdd + " seconds");
} else {
SendMessage.sendMessage(player, "You need to hold Time in a bottle to use this command");
}
return 1;
} catch (NumberFormatException ex) {
SendMessage.sendMessage(player, "Invalid time parameter!");
}
} else {
SendMessage.sendMessage(player, "Empty time parameter!");
}
return 0;
})
));
dispatcher.register(tiabCommands);
}
}
| 45.785714 | 148 | 0.596724 |
75b77de43a645d3f2168ae7b2c7756449a82dbd5 | 1,939 | /*
* 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.aliyuncs.vod.transform.v20170321;
import com.aliyuncs.vod.model.v20170321.UpdateWatermarkResponse;
import com.aliyuncs.vod.model.v20170321.UpdateWatermarkResponse.WatermarkInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class UpdateWatermarkResponseUnmarshaller {
public static UpdateWatermarkResponse unmarshall(UpdateWatermarkResponse updateWatermarkResponse, UnmarshallerContext _ctx) {
updateWatermarkResponse.setRequestId(_ctx.stringValue("UpdateWatermarkResponse.RequestId"));
WatermarkInfo watermarkInfo = new WatermarkInfo();
watermarkInfo.setCreationTime(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.CreationTime"));
watermarkInfo.setType(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.Type"));
watermarkInfo.setIsDefault(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.IsDefault"));
watermarkInfo.setWatermarkId(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.WatermarkId"));
watermarkInfo.setName(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.Name"));
watermarkInfo.setFileUrl(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.FileUrl"));
watermarkInfo.setWatermarkConfig(_ctx.stringValue("UpdateWatermarkResponse.WatermarkInfo.WatermarkConfig"));
updateWatermarkResponse.setWatermarkInfo(watermarkInfo);
return updateWatermarkResponse;
}
} | 48.475 | 126 | 0.817432 |
4e9b4d3f6b2469e997f4416d0245efd4ada5db6c | 357 | package com.learning.daggertwo.casterio.dagger.Settings;
import dagger.Module;
import dagger.Provides;
/**
* Created by wahibulhaq on 03/04/16.
*/
@Module
public class SettingsModule {
// All settings screen dependencies go here
@Provides
public SettingsService provideSettingsService() {
return new SettingServiceImpl();
}
}
| 17.85 | 56 | 0.722689 |
810011565e4e215942d050cab2791307791d250b | 3,783 | package bf.io.openshop.UX.adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import bf.io.openshop.R;
import bf.io.openshop.entities.drawerMenu.DrawerItemCategory;
import bf.io.openshop.interfaces.DrawerSubmenuRecyclerInterface;
/**
* Adapter handling list of drawer sub-items.
*/
public class DrawerSubmenuRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final DrawerSubmenuRecyclerInterface drawerSubmenuRecyclerInterface;
private LayoutInflater layoutInflater;
private List<DrawerItemCategory> drawerItemCategoryList = new ArrayList<>();
/**
* Creates an adapter that handles a list of drawer sub-items.
*
* @param drawerSubmenuRecyclerInterface listener indicating events that occurred.
*/
public DrawerSubmenuRecyclerAdapter(DrawerSubmenuRecyclerInterface drawerSubmenuRecyclerInterface) {
this.drawerSubmenuRecyclerInterface = drawerSubmenuRecyclerInterface;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (layoutInflater == null)
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.list_item_drawer_category, parent, false);
return new ViewHolderItemCategory(view, drawerSubmenuRecyclerInterface);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ViewHolderItemCategory viewHolderItemCategory = (ViewHolderItemCategory) holder;
DrawerItemCategory drawerItemCategory = getDrawerItem(position);
viewHolderItemCategory.bindContent(drawerItemCategory);
viewHolderItemCategory.itemText.setText(drawerItemCategory.getName());
viewHolderItemCategory.subMenuIndicator.setVisibility(View.INVISIBLE);
}
// This method returns the number of items present in the list
@Override
public int getItemCount() {
return drawerItemCategoryList.size();
}
private DrawerItemCategory getDrawerItem(int position) {
return drawerItemCategoryList.get(position);
}
public void changeDrawerItems(List<DrawerItemCategory> children) {
drawerItemCategoryList.clear();
drawerItemCategoryList.addAll(children);
notifyDataSetChanged();
}
// Provide a reference to the views for each data item
public static class ViewHolderItemCategory extends RecyclerView.ViewHolder {
public TextView itemText;
public ImageView subMenuIndicator;
public LinearLayout layout;
private DrawerItemCategory drawerItemCategory;
public ViewHolderItemCategory(View itemView, final DrawerSubmenuRecyclerInterface drawerSubmenuRecyclerInterface) {
super(itemView);
itemText = itemView.findViewById(R.id.drawer_list_item_text);
subMenuIndicator = itemView.findViewById(R.id.drawer_list_item_indicator);
layout = itemView.findViewById(R.id.drawer_list_item_layout);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerSubmenuRecyclerInterface.onSubCategorySelected(v, drawerItemCategory);
}
});
}
public void bindContent(DrawerItemCategory drawerItemCategory) {
this.drawerItemCategory = drawerItemCategory;
}
}
}
| 37.088235 | 123 | 0.739096 |
08dc0c9bc73c8f9062094206b76a4f52c476cdd2 | 8,383 | /*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.pcepio.protocol.ver1;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.pcepio.exceptions.PcepParseException;
import org.onosproject.pcepio.protocol.PcepEndPointsObject;
import org.onosproject.pcepio.types.PcepObjectHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
/**
* Provides PCEP Endpoints Object.
*/
public class PcepEndPointsObjectVer1 implements PcepEndPointsObject {
/*
* RFC : 5440 , section : 7.6
* An End point is defined as follows:
END-POINTS Object-Class is 4.
END-POINTS Object-Type is 1 for IPv4 and 2 for IPv6.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Object-Class | OT |Res|P|I| Object Length (bytes) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source IPv4 address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination IPv4 address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
protected static final Logger log = LoggerFactory.getLogger(PcepEndPointsObjectVer1.class);
static final byte END_POINTS_OBJ_TYPE = 1;
static final byte END_POINTS_OBJ_CLASS = 4;
static final byte END_POINTS_OBJECT_VERSION = 1;
static final short END_POINTS_OBJ_MINIMUM_LENGTH = 12;
public static byte endPointObjType;
static final PcepObjectHeader DEFAULT_END_POINTS_OBJECT_HEADER = new PcepObjectHeader(END_POINTS_OBJ_CLASS,
END_POINTS_OBJ_TYPE, PcepObjectHeader.REQ_OBJ_OPTIONAL_PROCESS, PcepObjectHeader.RSP_OBJ_PROCESSED,
END_POINTS_OBJ_MINIMUM_LENGTH);
private PcepObjectHeader endPointsObjHeader;
public int sourceIpAddress;
public int destIpAddress;
/**
* Constructor to initialize all variables.
*
* @param endPointsObjHeader end points object header
* @param sourceIpAddress source IP address
* @param destIpAddress destination IP address
*/
public PcepEndPointsObjectVer1(PcepObjectHeader endPointsObjHeader, int sourceIpAddress, int destIpAddress) {
this.endPointsObjHeader = endPointsObjHeader;
this.sourceIpAddress = sourceIpAddress;
this.destIpAddress = destIpAddress;
}
/**
* Sets End Points Object Header.
*
* @param obj of PcepObjectHeader
*/
public void setEndPointsObjHeader(PcepObjectHeader obj) {
this.endPointsObjHeader = obj;
}
@Override
public void setSourceIpAddress(int sourceIpAddress) {
this.sourceIpAddress = sourceIpAddress;
}
@Override
public void setDestIpAddress(int destIpAddress) {
this.destIpAddress = destIpAddress;
}
@Override
public int getSourceIpAddress() {
return this.sourceIpAddress;
}
@Override
public int getDestIpAddress() {
return this.destIpAddress;
}
/**
* Reads from channel buffer and returns object of PcepEndPointsObject.
*
* @param cb of channel buffer
* @return object of PcepEndPointsObject
* @throws PcepParseException while parsing channel buffer
*/
public static PcepEndPointsObject read(ChannelBuffer cb) throws PcepParseException {
PcepObjectHeader endPointsObjHeader;
int sourceIpAddress;
int destIpAddress;
endPointsObjHeader = PcepObjectHeader.read(cb);
if (endPointsObjHeader.getObjType() == END_POINTS_OBJ_TYPE
&& endPointsObjHeader.getObjClass() == END_POINTS_OBJ_CLASS) {
sourceIpAddress = cb.readInt();
destIpAddress = cb.readInt();
} else {
throw new PcepParseException("Expected PcepEndPointsObject.");
}
return new PcepEndPointsObjectVer1(endPointsObjHeader, sourceIpAddress, destIpAddress);
}
@Override
public int write(ChannelBuffer cb) throws PcepParseException {
int objStartIndex = cb.writerIndex();
//write common header
int objLenIndex = endPointsObjHeader.write(cb);
//write source IPv4 IP
cb.writeInt(sourceIpAddress);
//write destination IPv4 IP
cb.writeInt(destIpAddress);
int length = cb.writerIndex() - objStartIndex;
//now write EndPoints Object Length
cb.setShort(objLenIndex, (short) length);
//will be helpful during print().
endPointsObjHeader.setObjLen((short) length);
return cb.writerIndex();
}
/**
* Builder class for PCEP end points objects.
*/
public static class Builder implements PcepEndPointsObject.Builder {
private boolean bIsHeaderSet = false;
private boolean bIsSourceIpAddressset = false;
private boolean bIsDestIpAddressset = false;
private PcepObjectHeader endpointsObjHeader;
private int sourceIpAddress;
private int destIpAddress;
private boolean bIsPFlagSet = false;
private boolean bPFlag;
private boolean bIsIFlagSet = false;
private boolean bIFlag;
@Override
public PcepEndPointsObject build() throws PcepParseException {
PcepObjectHeader endpointsObjHeader = this.bIsHeaderSet ? this.endpointsObjHeader
: DEFAULT_END_POINTS_OBJECT_HEADER;
if (bIsPFlagSet) {
endpointsObjHeader.setPFlag(bPFlag);
}
if (bIsIFlagSet) {
endpointsObjHeader.setIFlag(bIFlag);
}
if (!this.bIsSourceIpAddressset) {
throw new PcepParseException("SourceIpAddress not set while building EndPoints object");
}
if (!this.bIsDestIpAddressset) {
throw new PcepParseException("DestIpAddress not set while building EndPoints object");
}
return new PcepEndPointsObjectVer1(endpointsObjHeader, this.sourceIpAddress, this.destIpAddress);
}
@Override
public PcepObjectHeader getEndPointsObjHeader() {
return this.endpointsObjHeader;
}
@Override
public Builder setEndPointsObjHeader(PcepObjectHeader obj) {
this.endpointsObjHeader = obj;
this.bIsHeaderSet = true;
return this;
}
@Override
public int getSourceIpAddress() {
return this.sourceIpAddress;
}
@Override
public Builder setSourceIpAddress(int sourceIpAddress) {
this.sourceIpAddress = sourceIpAddress;
this.bIsSourceIpAddressset = true;
return this;
}
@Override
public int getDestIpAddress() {
return this.destIpAddress;
}
@Override
public Builder setDestIpAddress(int destIpAddress) {
this.destIpAddress = destIpAddress;
this.bIsDestIpAddressset = true;
return this;
}
@Override
public Builder setPFlag(boolean value) {
this.bPFlag = value;
this.bIsPFlagSet = true;
return this;
}
@Override
public Builder setIFlag(boolean value) {
this.bIFlag = value;
this.bIsIFlagSet = true;
return this;
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("sourceIpAddress", sourceIpAddress)
.add("destIpAddress", destIpAddress).toString();
}
}
| 32.618677 | 113 | 0.626148 |
d36ce80b76d86cac906cb54f97646314fc2e8ec7 | 1,362 | package de.tum.testextension;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import de.tum.localcampuslib.ShowPostFragment;
public class TestShowFragment extends ShowPostFragment {
private TestShowViewModel testShowViewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Possibly use Android ViewModels bound to the context
// ViewModelProviders.of ...
testShowViewModel = new TestShowViewModel(getDataProvider());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutInflater newInflator = inflater.cloneInContext(getContext());
View view = newInflator.inflate(R.layout.fragment_test, null, false);
ImageView img= (ImageView) view.findViewById(R.id.imageView);
img.setImageResource(R.drawable.ic_launcher_placeholder);
TextView textView = view.findViewById(R.id.fragmentText);
testShowViewModel.getText().observe(this, text -> {
textView.setText(text);
});
return view;
}
} | 30.266667 | 77 | 0.716593 |
8ad1a14b4782243ea445ec5d2df27609778068a5 | 893 | package outputModules.csv.exporters;
import cfg.nodes.CFGNode;
import outputModules.common.DOMExporter;
import cfg.nodes.ASTNodeContainer;
import databaseNodes.EdgeTypes;
import outputModules.common.Writer;
public class CSVDOMExporter extends DOMExporter
{
@Override
protected void addDomEdge(CFGNode vertex, CFGNode dominator)
{
long srcId = getId(dominator);
long dstId = getId(vertex);
Writer.addEdge(srcId, dstId, null, EdgeTypes.DOM);
}
@Override
protected void addPostDomEdge(CFGNode vertex, CFGNode postDominator)
{
long srcId = getId(postDominator);
long dstId = getId(vertex);
Writer.addEdge(srcId, dstId, null, EdgeTypes.POST_DOM);
}
private long getId(CFGNode node)
{
if (node instanceof ASTNodeContainer)
{
return Writer
.getIdForObject(((ASTNodeContainer) node).getASTNode());
}
else
{
return Writer.getIdForObject(node);
}
}
}
| 21.261905 | 69 | 0.7514 |
4be60f242ad8a2dbe8f46e57f491e3e30c147f89 | 4,594 | package net.MrBonono63.create.blocks.schematics;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.HorizontalFacingBlock;
import net.minecraft.block.ShapeContext;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.state.property.Property;
import net.minecraft.util.BlockMirror;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.util.shape.VoxelShapes;
import net.minecraft.world.BlockView;
import net.minecraft.world.WorldView;
public class SchematicTable extends HorizontalFacingBlock {
public static final DirectionProperty FACING;
public static final VoxelShape COLLISION_SHAPE_TOP;
public static final VoxelShape COLLISION_SHAPE;
public static final VoxelShape BOTTOM_SHAPE;
public static final VoxelShape BASE_SHAPE;
public static final VoxelShape MIDDLE_SHAPE;
public static final VoxelShape NORTH_SHAPE;
public static final VoxelShape SOUTH_SHAPE;
public static final VoxelShape EAST_SHAPE;
public static final VoxelShape WEST_SHAPE;
public SchematicTable(Settings settings) {
super(settings.nonOpaque());
this.setDefaultState(this.stateManager.getDefaultState().with(FACING, Direction.NORTH));
}
@Override
public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
switch ((Direction)state.get(FACING))
{
case NORTH:
return NORTH_SHAPE;
case SOUTH:
return SOUTH_SHAPE;
case EAST:
return EAST_SHAPE;
case WEST:
return WEST_SHAPE;
default:
return BASE_SHAPE;
}
}
public boolean hasSidedTransparency(BlockState state) {
return true;
}
public BlockState getPlacementState(ItemPlacementContext ctx) {
return (BlockState)this.getDefaultState().with(FACING, ctx.getPlayerFacing().getOpposite());
}
@Override
public VoxelShape getCollisionShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
return COLLISION_SHAPE;
}
@Override
public VoxelShape getCullingShape(BlockState state, BlockView view, BlockPos pos) {
return BASE_SHAPE;
}
@Override
public BlockState rotate(BlockState state, BlockRotation rotation) {
return state.with(FACING, rotation.rotate(state.get(FACING)));
}
@Override
public BlockState mirror(BlockState state, BlockMirror mirror) {
return state.rotate(mirror.getRotation(state.get(FACING)));
}
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(FACING);
}
@Override
public boolean canPlaceAt(BlockState state, WorldView world, BlockPos pos) {
return true;
}
static
{
BOTTOM_SHAPE = Block.createCuboidShape(4.0,0.0,4.0,12.0,2.0,12.0);
MIDDLE_SHAPE = Block.createCuboidShape(5.0,2.0,5.0,11.0,14,11.0);
BASE_SHAPE = VoxelShapes.union(BOTTOM_SHAPE,MIDDLE_SHAPE);
COLLISION_SHAPE_TOP = Block.createCuboidShape(0.0,15.0,0.0,16.0,15.0,16.0);
COLLISION_SHAPE = VoxelShapes.union(BASE_SHAPE, COLLISION_SHAPE_TOP);
WEST_SHAPE = VoxelShapes.union(Block.createCuboidShape(0.0D, 10.0D, 0.0D, 5D, 14.0D, 16.0D),new VoxelShape[]{Block.createCuboidShape(5D, 12.0D, 0.0D, 10D, 16.0D, 16.0D), Block.createCuboidShape(10D, 14.0D, 0.0D, 15.0D, 18.0D, 16.0D), BASE_SHAPE});
NORTH_SHAPE = VoxelShapes.union(Block.createCuboidShape(0.0D, 10.0D, 0.0D, 16.0D, 14.0D, 5D), new VoxelShape[]{Block.createCuboidShape(0.0D, 12.0D, 5D, 16.0D, 16.0D, 10D), Block.createCuboidShape(0.0D, 14.0D, 10D, 16.0D, 18.0D, 15.0D), BASE_SHAPE});
EAST_SHAPE = VoxelShapes.union(Block.createCuboidShape(16.0D, 10.0D, 0.0D, 11D, 14.0D, 16.0D), new VoxelShape[]{Block.createCuboidShape(11D, 12.0D, 0.0D, 6D, 16.0D, 16.0D), Block.createCuboidShape(6D, 14.0D, 0.0D, 1.0D, 18.0D, 16.0D), BASE_SHAPE});
SOUTH_SHAPE = VoxelShapes.union(Block.createCuboidShape(0.0D, 10.0D, 16.0D, 16.0D, 14.0D, 11D), new VoxelShape[]{Block.createCuboidShape(0.0D, 12.0D, 11D, 16.0D, 16.0D, 6D), Block.createCuboidShape(0.0D, 14.0D, 6D, 16.0D, 18.0D, 1.0D), BASE_SHAPE});
FACING = HorizontalFacingBlock.FACING;
}
}
| 42.934579 | 257 | 0.71071 |
d09fdeca7edeb318020feafdbe6996e683023ab1 | 23,433 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.dvi.layout.edge.rendering.connectors;
import gleem.linalg.Vec2f;
import gleem.linalg.Vec3f;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.media.opengl.GL2;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.core.util.color.Color;
import org.caleydo.core.view.opengl.camera.ViewFrustum;
import org.caleydo.core.view.opengl.canvas.PixelGLConverter;
import org.caleydo.core.view.opengl.util.spline.ConnectionBandRenderer;
import org.caleydo.view.dvi.GLDataViewIntegrator;
import org.caleydo.view.dvi.node.IDVINode;
public class BottomBundleConnector
extends ABundleConnector
{
public BottomBundleConnector(IDVINode node, PixelGLConverter pixelGLConverter,
ConnectionBandRenderer connectionBandRenderer,
List<TablePerspective> commonTablePerspectives, int minBandWidth, int maxBandWidth,
int maxDataAmount, IDVINode otherNode, ViewFrustum viewFrustum,
GLDataViewIntegrator view)
{
super(node, pixelGLConverter, connectionBandRenderer, commonTablePerspectives,
minBandWidth, maxBandWidth, maxDataAmount, otherNode, viewFrustum, view);
calcBundlingPoint();
calcBandConnectionPoint();
}
protected void calcBundlingPoint()
{
float bundlingPositionX = calcXPositionOfBundlingPoint(node, commonTablePerspectives);
float nodeBottomPositionY = (float) node.getBottomAnchorPoints().getFirst().getY();
float bundlingPositionY = nodeBottomPositionY
- pixelGLConverter.getGLHeightForPixelHeight(BUNDLING_POINT_NODE_DISTANCE_Y);
bundlingPoint = new Point2D.Float(bundlingPositionX, bundlingPositionY);
}
protected void calcBandConnectionPoint()
{
float bundlingPositionX = (float) bundlingPoint.getX();
float bundlingPositionXOtherNode = calcXPositionOfBundlingPoint(otherNode,
commonTablePerspectives);
float deltaX = bundlingPositionXOtherNode - bundlingPositionX;
float ratioX = deltaX / viewFrustum.getWidth();
float edgeAnchorX = bundlingPositionX + ratioX * node.getWidth() / 2.0f;
float edgeAnchorXOtherNode = bundlingPositionXOtherNode - ratioX
* otherNode.getWidth() / 2.0f;
float edgeAnchorY = (float) node.getBoundingBox().getMinY()
- pixelGLConverter
.getGLHeightForPixelHeight(BOUNDING_BOX_BAND_CONNECTIONPOINT_DISTANCE_Y);
float edgeAnchorYOtherNode = otherNode.isUpsideDown() ? ((float) otherNode
.getBoundingBox().getMaxY() + pixelGLConverter
.getGLHeightForPixelHeight(BOUNDING_BOX_BAND_CONNECTIONPOINT_DISTANCE_Y))
: (float) otherNode.getBoundingBox().getMinY()
- pixelGLConverter
.getGLHeightForPixelHeight(BOUNDING_BOX_BAND_CONNECTIONPOINT_DISTANCE_Y);
boolean hasEdgeNodeIntersection = doesLineIntersectWithNode(new Point2D.Float(
edgeAnchorX, edgeAnchorY), new Point2D.Float(edgeAnchorXOtherNode,
edgeAnchorYOtherNode));
float bundleDeltaX = (float) (edgeAnchorX - bundlingPoint.getX());
use4ControlPointsForBandBundleConnection = true;
float deltaXLimit = commonTablePerspectives.size() > 1 ? pixelGLConverter
.getGLWidthForPixelWidth(bandWidthPixels) : pixelGLConverter
.getGLWidthForPixelWidth(bandWidthPixels) / 2.0f;
if (hasEdgeNodeIntersection || (Math.abs(bundleDeltaX) < deltaXLimit)
|| (otherNode.getPosition().getY() > node.getPosition().getY())
|| (!otherNode.isUpsideDown() && node.getSpacingX(otherNode) < 0))
{
use4ControlPointsForBandBundleConnection = false;
edgeAnchorX = bundlingPositionX;
}
// float edgeAnchorY = (float) (nodeAnchorPoints.getFirst().getY() -
// Math.min(
// 0.2f * spacingY, pixelGLConverter
// .getGLHeightForPixelHeight(MAX_NODE_EDGE_ANCHOR_DISTANCE_PIXELS)));
bandConnectionPoint = new Point2D.Float(edgeAnchorX, edgeAnchorY);
}
@Override
public Point2D getBandConnectionPoint()
{
return bandConnectionPoint;
}
@Override
public Point2D getBandHelperPoint()
{
// float bundleDeltaX = (float) (bandConnectionPoint.getX() -
// bundlingPoint
// .getX());
// if (Math.abs(bundleDeltaX) != 0)
if (use4ControlPointsForBandBundleConnection)
return bundlingPoint;
return new Point2D.Float((float) bandConnectionPoint.getX(), (float) node
.getPosition().getY());
}
@Override
public void render(GL2 gl, List<Vec3f> bandPoints, boolean isEnd1, Color color)
{
// Point2D bandAnchorPoint1 = null;
// Point2D bandAnchorPoint2 = null;
calcBandAnchorPoints(isEnd1, bandPoints);
if (!isEnd1)
{
Point2D temp = bandAnchorPoint1;
bandAnchorPoint1 = bandAnchorPoint2;
bandAnchorPoint2 = temp;
}
float vecBandEndX = (float) (bandAnchorPoint2.getX() - bandAnchorPoint1.getX())
/ bandWidthPixels;
float vecBandEndY = (float) (bandAnchorPoint2.getY() - bandAnchorPoint1.getY())
/ bandWidthPixels;
// The direction of this vector is correct, since bandAnchorPoint1 is
// always the left point...
// float vecNormalX = -vecBandEndY;
// float vecNormalY = vecBandEndX;
Vec2f bandVec = new Vec2f(-vecBandEndY, vecBandEndX);
bandVec.normalize();
Vec2f bundleVec = new Vec2f(0, -1);
Point2D leftBandBundleConnectionPoint = null;
Point2D rightBandBundleConnectionPoint = null;
Point2D leftBandConnectionPointOffsetAnchor = null;
Point2D rightBandConnectionPointOffsetAnchor = null;
Point2D leftBundleConnectionPointOffsetAnchor = null;
Point2D rightBundleConnectionPointOffsetAnchor = null;
Point2D leftTablePerspectiveBundleConnectionPoint = null;
Point2D rightTablePerspectiveBundleConnectionPoint = null;
float bandWidth = pixelGLConverter.getGLWidthForPixelWidth(bandWidthPixels);
leftBandBundleConnectionPoint = new Point2D.Float((float) bundlingPoint.getX()
- bandWidth / 2.0f, (float) bundlingPoint.getY());
rightBandBundleConnectionPoint = new Point2D.Float((float) bundlingPoint.getX()
+ bandWidth / 2.0f, (float) bundlingPoint.getY());
if (!use4ControlPointsForBandBundleConnection)
{
if (bandAnchorPoint1.getY() > bandAnchorPoint2.getY())
{
leftBandBundleConnectionPoint = bandAnchorPoint1;
rightBandBundleConnectionPoint = new Point2D.Float(
(float) bandAnchorPoint1.getX() + bandWidth,
(float) bandAnchorPoint1.getY());
leftBandConnectionPointOffsetAnchor = leftBandBundleConnectionPoint;
float minY = (float) bandAnchorPoint2.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MAX_BAND_ANCHOR_OFFSET_DISTANCE_Y_2_CP);
float maxY = (float) rightBandBundleConnectionPoint.getY();
rightBandConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
bandAnchorPoint2, bandVec.x(), bandVec.y(),
(float) rightBandBundleConnectionPoint.getX(), minY, maxY, minY, maxY);
}
else
{
leftBandBundleConnectionPoint = new Point2D.Float(
(float) bandAnchorPoint2.getX() - bandWidth,
(float) bandAnchorPoint2.getY());
rightBandBundleConnectionPoint = bandAnchorPoint2;
float minY = (float) bandAnchorPoint1.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MAX_BAND_ANCHOR_OFFSET_DISTANCE_Y_2_CP);
float maxY = (float) leftBandBundleConnectionPoint.getY();
float fixedX = (float) (leftBandBundleConnectionPoint.getX());
leftBandConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
bandAnchorPoint1, bandVec.x(), bandVec.y(), fixedX, minY, maxY, minY,
maxY);
rightBandConnectionPointOffsetAnchor = rightBandBundleConnectionPoint;
}
leftTablePerspectiveBundleConnectionPoint = new Point2D.Float(
(float) leftBandBundleConnectionPoint.getX(), (float) bundlingPoint.getY());
rightTablePerspectiveBundleConnectionPoint = new Point2D.Float(
(float) rightBandBundleConnectionPoint.getX(),
(float) bundlingPoint.getY());
}
else
{
float dotProduct = bandVec.dot(bundleVec);
float distanceScaling = Math.max((1 + dotProduct) * 0.5f, 0.3f);
// if (!use4ControlPointsForBandBundleConnection)
// distanceScaling = 1;
// gl.glBegin(GL.GL_LINES);
// gl.glVertex2d(fixedX, 0);
// gl.glVertex2d(fixedX, 4);
// gl.glEnd();
float minY = (float) bandAnchorPoint2.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MAX_BAND_ANCHOR_OFFSET_DISTANCE_Y_4_CP);
float maxY = (float) rightBandBundleConnectionPoint.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MIN_BAND_ANCHOR_OFFSET_DISTANCE_Y_4_CP);
float fixedX = (float) (bandAnchorPoint2.getX() + (rightBandBundleConnectionPoint
.getX() - bandAnchorPoint2.getX()) * distanceScaling);
rightBandConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(bandAnchorPoint2,
bandVec.x(), bandVec.y(), fixedX, minY, maxY, minY, maxY);
minY = (float) bandAnchorPoint1.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MAX_BAND_ANCHOR_OFFSET_DISTANCE_Y_4_CP);
maxY = (float) leftBandBundleConnectionPoint.getY()
- pixelGLConverter
.getGLHeightForPixelHeight(MIN_BAND_ANCHOR_OFFSET_DISTANCE_Y_4_CP);
fixedX = (float) (bandAnchorPoint1.getX() + (leftBandBundleConnectionPoint.getX() - bandAnchorPoint1
.getX()) * distanceScaling);
leftBandConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(bandAnchorPoint1,
bandVec.x(), bandVec.y(), fixedX, minY, maxY, minY, maxY);
if (bandVec.x() == 0)
{
leftBandConnectionPointOffsetAnchor.setLocation(
bandAnchorPoint1.getX(),
bandAnchorPoint1.getY()
+ (leftBandBundleConnectionPoint.getY() - bandAnchorPoint1
.getY()) / 4);
rightBandConnectionPointOffsetAnchor.setLocation(
bandAnchorPoint2.getX(),
bandAnchorPoint2.getY()
+ (rightBandBundleConnectionPoint.getY() - bandAnchorPoint2
.getY()) / 4);
}
else
{
// Vec2f anchorVec = new Vec2f(
// (float) (leftBandBundleConnectionPoint.getX() -
// bandAnchorPoint1.getX()),
// (float) (leftBandBundleConnectionPoint.getY() -
// bandAnchorPoint1.getY()));
//
// if ((anchorVec.x() < 0 && bandVec.x() > 0)
// || (anchorVec.x() > 0 && bandVec.x() < 0)
// || (anchorVec.y() < 0 && bandVec.y() > 0)
// || (anchorVec.x() > 0 && bandVec.x() < 0)
// ||
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3d(0, maxY, 3);
// gl.glVertex3d(5, maxY, 3);
// gl.glEnd();
if ((float) leftBandConnectionPointOffsetAnchor.getY() >= maxY
- pixelGLConverter.getGLHeightForPixelHeight(1))
{
Vec2f miniVec = bandVec.times(pixelGLConverter
.getGLHeightForPixelHeight(2));
leftBandConnectionPointOffsetAnchor.setLocation(bandAnchorPoint1.getX()
+ miniVec.x(), bandAnchorPoint1.getY() + miniVec.y());
rightBandConnectionPointOffsetAnchor.setLocation(bandAnchorPoint2.getX()
+ miniVec.x(), bandAnchorPoint2.getY() + miniVec.y());
}
}
// float minX = (float) bandAnchorPoint1.getX();
// float maxX = (float) leftBandBundleConnectionPoint.getX();
float fixedY = (float) (rightBandBundleConnectionPoint.getY() - (leftBandBundleConnectionPoint
.getY() - bandAnchorPoint1.getY()) * 0.3f);
// leftBundleConnectionPointOffsetAnchor =
// calcPointOnLineWithFixedY(
// leftBandBundleConnectionPoint, 0, -1, fixedY, minX, maxY, minX,
// maxX);
leftBundleConnectionPointOffsetAnchor = new Point2D.Float(
(float) leftBandBundleConnectionPoint.getX(), fixedY);
fixedY = (float) (rightBandBundleConnectionPoint.getY() - (rightBandBundleConnectionPoint
.getY() - bandAnchorPoint2.getY()) * 0.3f);
rightBundleConnectionPointOffsetAnchor = new Point2D.Float(
(float) rightBandBundleConnectionPoint.getX(), fixedY);
leftTablePerspectiveBundleConnectionPoint = leftBandBundleConnectionPoint;
rightTablePerspectiveBundleConnectionPoint = rightBandBundleConnectionPoint;
}
// }
// gl.glPointSize(3);
// gl.glColor3f(1, 0, 0);
// gl.glBegin(GL2.GL_POINTS);
// gl.glVertex3d(bandAnchorPoint1.getX(), bandAnchorPoint1.getY(), 2);
// gl.glVertex3d(bandAnchorPoint2.getX(), bandAnchorPoint2.getY(), 2);
// gl.glColor3f(0, 0, 1);
// gl.glVertex3d(bandConnectionPoint.getX(), bandConnectionPoint.getY(),
// 2);
// gl.glEnd();
// //
// gl.glPointSize(3);
// gl.glColor3f(0, 1, 0);
// gl.glBegin(GL2.GL_POINTS);
// gl.glVertex3d(leftBandConnectionPointOffsetAnchor.getX(),
// leftBandConnectionPointOffsetAnchor.getY(), 3);
//
// gl.glVertex3d(rightBandConnectionPointOffsetAnchor.getX(),
// rightBandConnectionPointOffsetAnchor.getY(), 3);
// if (use4ControlPointsForBandBundleConnection)
// {
// gl.glVertex3d(leftBundleConnectionPointOffsetAnchor.getX(),
// leftBundleConnectionPointOffsetAnchor.getY(), 3);
// gl.glVertex3d(rightBundleConnectionPointOffsetAnchor.getX(),
// rightBundleConnectionPointOffsetAnchor.getY(), 3);
// }
// gl.glColor3f(0, 1, 1);
// gl.glVertex3d(leftTablePerspectiveBundleConnectionPoint.getX(),
// leftTablePerspectiveBundleConnectionPoint.getY(), 3);
// gl.glVertex3d(rightTablePerspectiveBundleConnectionPoint.getX(),
// rightTablePerspectiveBundleConnectionPoint.getY(), 3);
// gl.glEnd();
List<Pair<Point2D, Point2D>> anchorPoints = new ArrayList<Pair<Point2D, Point2D>>();
anchorPoints.add(new Pair<Point2D, Point2D>(bandAnchorPoint1, bandAnchorPoint2));
anchorPoints.add(new Pair<Point2D, Point2D>(leftBandConnectionPointOffsetAnchor,
rightBandConnectionPointOffsetAnchor));
if (use4ControlPointsForBandBundleConnection)
{
anchorPoints.add(new Pair<Point2D, Point2D>(leftBundleConnectionPointOffsetAnchor,
rightBundleConnectionPointOffsetAnchor));
}
anchorPoints.add(new Pair<Point2D, Point2D>(leftBandBundleConnectionPoint,
rightBandBundleConnectionPoint));
connectionBandRenderer.renderComplexBand(gl, anchorPoints, false, color.getRGB(),
(highlightBand) ? 1 : 0.5f);
if (!use4ControlPointsForBandBundleConnection)
{
connectionBandRenderer.renderStraightBand(gl, new float[] {
(float) rightTablePerspectiveBundleConnectionPoint.getX(),
(float) rightTablePerspectiveBundleConnectionPoint.getY() }, new float[] {
(float) leftTablePerspectiveBundleConnectionPoint.getX(),
(float) leftTablePerspectiveBundleConnectionPoint.getY() }, new float[] {
(float) rightBandBundleConnectionPoint.getX(),
(float) rightBandBundleConnectionPoint.getY() }, new float[] {
(float) leftBandBundleConnectionPoint.getX(),
(float) leftBandBundleConnectionPoint.getY() }, false, 0, color.getRGB(),
(highlightBand) ? 1 : 0.5f);
}
Point2D prevBandAnchorPoint = leftTablePerspectiveBundleConnectionPoint;
List<Pair<Double, TablePerspective>> sortedDimensionGroups = new ArrayList<Pair<Double, TablePerspective>>(
commonTablePerspectives.size());
for (TablePerspective tablePerspective : commonTablePerspectives)
{
sortedDimensionGroups.add(new Pair<Double, TablePerspective>(node
.getBottomObjectAnchorPoints(tablePerspective).getFirst().getX(),
tablePerspective));
}
Collections.sort(sortedDimensionGroups, Pair.<Double> compareFirst());
for (int i = 0; i < sortedDimensionGroups.size(); i++)
{
TablePerspective tablePerspective = sortedDimensionGroups.get(i).getSecond();
anchorPoints = new ArrayList<Pair<Point2D, Point2D>>();
Pair<Point2D, Point2D> dimensionGroupAnchorPoints = node
.getBottomObjectAnchorPoints(tablePerspective);
Pair<Point2D, Point2D> dimensionGroupAnchorOffsetPoints = new Pair<Point2D, Point2D>();
Pair<Point2D, Point2D> nodeBottomAnchorPoints = node.getBottomAnchorPoints();
float offsetPositionY = (float) (nodeBottomAnchorPoints.getFirst().getY() - pixelGLConverter
.getGLHeightForPixelHeight(TABLEPERSPECTIVE_OFFSET_Y));
dimensionGroupAnchorOffsetPoints.setFirst(new Point2D.Float(
(float) dimensionGroupAnchorPoints.getFirst().getX(), offsetPositionY));
dimensionGroupAnchorOffsetPoints.setSecond(new Point2D.Float(
(float) dimensionGroupAnchorPoints.getSecond().getX(), offsetPositionY));
int width = bandWidthMap.get(tablePerspective);
Point2D nextBandAnchorPoint = null;
if (i == commonTablePerspectives.size() - 1)
{
nextBandAnchorPoint = rightTablePerspectiveBundleConnectionPoint;
}
else
{
nextBandAnchorPoint = new Point2D.Float((float) prevBandAnchorPoint.getX()
+ pixelGLConverter.getGLWidthForPixelWidth(width),
(float) prevBandAnchorPoint.getY());
}
float bandOffsetPositionY = (float) nodeBottomAnchorPoints.getFirst().getY()
- pixelGLConverter
.getGLHeightForPixelHeight(TABLEPERSPECTIVE_TO_BUNDLE_OFFSET_Y);
Point2D bandOffsetPoint1 = new Point2D.Float((float) prevBandAnchorPoint.getX(),
bandOffsetPositionY);
Point2D bandOffsetPoint2 = new Point2D.Float((float) nextBandAnchorPoint.getX(),
bandOffsetPositionY);
anchorPoints.add(dimensionGroupAnchorPoints);
anchorPoints.add(dimensionGroupAnchorOffsetPoints);
anchorPoints.add(new Pair<Point2D, Point2D>(bandOffsetPoint1, bandOffsetPoint2));
anchorPoints.add(new Pair<Point2D, Point2D>(prevBandAnchorPoint,
nextBandAnchorPoint));
connectionBandRenderer.renderComplexBand(gl, anchorPoints, false, color.getRGB(),
(highlightBand) ? 1 : 0.5f);
prevBandAnchorPoint = nextBandAnchorPoint;
}
}
// @Override
// public void render(GL2 gl, List<Vec3f> bandPoints, boolean isEnd1,
// Color color) {
//
// // Point2D bandAnchorPoint1 = null;
// // Point2D bandAnchorPoint2 = null;
//
// calcBandAnchorPoints(isEnd1, bandPoints);
//
// if (!isEnd1) {
// Point2D temp = bandAnchorPoint1;
// bandAnchorPoint1 = bandAnchorPoint2;
// bandAnchorPoint2 = temp;
// }
//
// gl.glPointSize(3);
// gl.glColor3f(1, 0, 0);
// gl.glBegin(GL2.GL_POINTS);
// gl.glVertex3d(bandAnchorPoint1.getX(), bandAnchorPoint1.getY(), 2);
// gl.glVertex3d(bandAnchorPoint2.getX(), bandAnchorPoint2.getY(), 2);
// gl.glColor3f(0, 0, 1);
// gl.glVertex3d(bundlingPoint.getX(), bundlingPoint.getY(), 2);
// gl.glEnd();
//
// float vecBandEndX = (float) (bandAnchorPoint2.getX() - bandAnchorPoint1
// .getX()) / bandWidth;
// float vecBandEndY = (float) (bandAnchorPoint2.getY() - bandAnchorPoint1
// .getY()) / bandWidth;
//
// float vecNormalX = vecBandEndY;
// float vecNormalY = -vecBandEndX;
//
// Point2D leftBandBundleConnecionPoint = null;
// Point2D rightBandBundleConnecionPoint = null;
// Point2D leftBundleConnectionPointOffsetAnchor = null;
// Point2D rightBundleConnectionPointOffsetAnchor = null;
//
// if (bandAnchorPoint1.getY() > bandAnchorPoint2.getY()) {
// leftBandBundleConnecionPoint = bandAnchorPoint1;
// rightBandBundleConnecionPoint = new Point2D.Float(
// (float) bandAnchorPoint1.getX()
// + pixelGLConverter
// .getGLWidthForPixelWidth(bandWidth),
// (float) bandAnchorPoint1.getY());
// leftBundleConnectionPointOffsetAnchor = leftBandBundleConnecionPoint;
// float minY = (float) bandAnchorPoint2.getY() - 0.1f;
// float maxY = (float) rightBandBundleConnecionPoint.getY();
// rightBundleConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
// bandAnchorPoint2, vecNormalX, vecNormalY,
// (float) rightBandBundleConnecionPoint.getX(), minY, maxY,
// minY, maxY);
//
// } else {
// leftBandBundleConnecionPoint = new Point2D.Float(
// (float) bandAnchorPoint2.getX()
// - pixelGLConverter
// .getGLWidthForPixelWidth(bandWidth),
// (float) bandAnchorPoint2.getY());
// rightBandBundleConnecionPoint = bandAnchorPoint2;
//
// rightBundleConnectionPointOffsetAnchor = rightBandBundleConnecionPoint;
// float minY = (float) bandAnchorPoint1.getY() - 0.1f;
// float maxY = (float) leftBandBundleConnecionPoint.getY();
// leftBundleConnectionPointOffsetAnchor = calcPointOnLineWithFixedX(
// bandAnchorPoint1, vecNormalX, vecNormalY,
// (float) leftBandBundleConnecionPoint.getX(), minY, maxY,
// minY, maxY);
// }
//
// List<Pair<Point2D, Point2D>> anchorPoints = new ArrayList<Pair<Point2D,
// Point2D>>();
//
// anchorPoints.add(new Pair<Point2D, Point2D>(bandAnchorPoint1,
// bandAnchorPoint2));
// anchorPoints.add(new Pair<Point2D, Point2D>(
// leftBundleConnectionPointOffsetAnchor,
// rightBundleConnectionPointOffsetAnchor));
// anchorPoints.add(new Pair<Point2D, Point2D>(
// leftBandBundleConnecionPoint, rightBandBundleConnecionPoint));
//
// connectionBandRenderer.renderComplexBand(gl, anchorPoints, false,
// color.getRGB(), (highlightBand) ? 1 : 0.5f);
//
// Point2D prevBandAnchorPoint = leftBandBundleConnecionPoint;
//
// List<Pair<Double, TablePerspective>> sortedDimensionGroups = new
// ArrayList<Pair<Double, TablePerspective>>(
// commonTablePerspectives.size());
// for (TablePerspective tablePerspective : commonTablePerspectives) {
// sortedDimensionGroups.add(new Pair<Double, TablePerspective>(node
// .getBottomTablePerspectiveAnchorPoints(tablePerspective)
// .getFirst().getX(), tablePerspective));
// }
//
// Collections.sort(sortedDimensionGroups);
//
// for (int i = 0; i < sortedDimensionGroups.size(); i++) {
// TablePerspective tablePerspective = sortedDimensionGroups.get(i)
// .getSecond();
// anchorPoints = new ArrayList<Pair<Point2D, Point2D>>();
// Pair<Point2D, Point2D> dimensionGroupAnchorPoints = node
// .getBottomTablePerspectiveAnchorPoints(tablePerspective);
// Pair<Point2D, Point2D> dimensionGroupAnchorOffsetPoints = new
// Pair<Point2D, Point2D>();
// Pair<Point2D, Point2D> nodeBottomAnchorPoints = node
// .getBottomAnchorPoints();
// dimensionGroupAnchorOffsetPoints.setFirst(new Point2D.Float(
// (float) dimensionGroupAnchorPoints.getFirst().getX(),
// (float) nodeBottomAnchorPoints.getFirst().getY() - 0.1f));
//
// dimensionGroupAnchorOffsetPoints.setSecond(new Point2D.Float(
// (float) dimensionGroupAnchorPoints.getSecond().getX(),
// (float) nodeBottomAnchorPoints.getSecond().getY() - 0.1f));
//
// int width = bandWidthMap.get(tablePerspective);
//
// Point2D nextBandAnchorPoint = null;
//
// if (i == commonTablePerspectives.size() - 1) {
// nextBandAnchorPoint = rightBandBundleConnecionPoint;
// } else {
// nextBandAnchorPoint = new Point2D.Float(
// (float) prevBandAnchorPoint.getX()
// + pixelGLConverter
// .getGLWidthForPixelWidth(width),
// (float) prevBandAnchorPoint.getY());
// }
//
// Point2D bandOffsetPoint1 = new Point2D.Float(
// (float) prevBandAnchorPoint.getX(),
// (float) nodeBottomAnchorPoints.getFirst().getY() - 0.17f);
//
// Point2D bandOffsetPoint2 = new Point2D.Float(
// (float) nextBandAnchorPoint.getX(),
// (float) nodeBottomAnchorPoints.getSecond().getY() - 0.17f);
//
// anchorPoints.add(dimensionGroupAnchorPoints);
// anchorPoints.add(dimensionGroupAnchorOffsetPoints);
// anchorPoints.add(new Pair<Point2D, Point2D>(bandOffsetPoint1,
// bandOffsetPoint2));
// anchorPoints.add(new Pair<Point2D, Point2D>(prevBandAnchorPoint,
// nextBandAnchorPoint));
//
// connectionBandRenderer.renderComplexBand(gl, anchorPoints, false,
// color.getRGB(), (highlightBand) ? 1 : 0.5f);
//
// prevBandAnchorPoint = nextBandAnchorPoint;
// }
// }
}
| 38.925249 | 109 | 0.73708 |
adc926257edb2e42c34c8ac1040b0fdf2448c470 | 3,275 | package org.lagonette.app.app.widget.performer.impl;
import android.arch.lifecycle.ViewModelProviders;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.maps.android.clustering.Cluster;
import org.lagonette.app.R;
import org.lagonette.app.app.fragment.MapsFragment;
import org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel;
import org.lagonette.app.app.widget.coordinator.state.UiState;
import org.lagonette.app.app.widget.performer.base.ViewPerformer;
import org.lagonette.app.room.entity.statement.LocationItem;
import org.zxcv.functions.main.Consumer;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Action.NOTIFY_MAP_MOVEMENT;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.MOVE_TO_CLUSTER;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.MOVE_TO_FOOTPRINT;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.MOVE_TO_MY_LOCATION;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.MOVE_TO_SELECTED_LOCATION;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.STOP_MOVING;
import static org.lagonette.app.app.viewmodel.MainLiveEventBusViewModel.Map.UPDATE_MAP_LOCATION_UI;
public abstract class MapFragmentPerformer
implements ViewPerformer {
@NonNull
private final FragmentManager mFragmentManager;
@NonNull
public Consumer<UiState.MapMovement> onMapMovementChanged = Consumer::doNothing;
@NonNull
protected MainLiveEventBusViewModel mEventBus;
protected MapsFragment mFragment;
@NonNull
protected UiState.MapMovement mMapMovement;
public MapFragmentPerformer(@NonNull AppCompatActivity activity) {
mEventBus = ViewModelProviders.of(activity).get(MainLiveEventBusViewModel.class);
mFragmentManager = activity.getSupportFragmentManager();
mMapMovement = UiState.MapMovement.IDLE;
mEventBus.subscribe(
NOTIFY_MAP_MOVEMENT,
activity,
this::notifyMapMovement
);
}
public void loadFragment() {
mFragment = MapsFragment.newInstance();
mFragmentManager.beginTransaction()
.add(R.id.content, mFragment, MapsFragment.TAG)
.commit();
}
public void restoreFragment() {
mFragment = (MapsFragment) mFragmentManager.findFragmentByTag(MapsFragment.TAG);
}
@NonNull
public UiState.MapMovement getMapMovement() {
return mMapMovement;
}
private void notifyMapMovement(@NonNull UiState.MapMovement mapMovement) {
mMapMovement = mapMovement;
onMapMovementChanged.accept(mMapMovement);
}
public void moveToMyLocation(@Nullable Location location) {
mEventBus.publish(MOVE_TO_MY_LOCATION, location);
}
public boolean moveToFootprint() {
mEventBus.publish(MOVE_TO_FOOTPRINT);
return true;
}
public void moveToCluster(@NonNull Cluster<LocationItem> cluster) {
mEventBus.publish(MOVE_TO_CLUSTER, cluster);
}
public void moveToSelectedLocation() {
mEventBus.publish(MOVE_TO_SELECTED_LOCATION);
}
public void stopMoving() {
mEventBus.publish(STOP_MOVING);
}
public void updateLocationUI() {
mEventBus.publish(UPDATE_MAP_LOCATION_UI);
}
}
| 31.796117 | 102 | 0.818321 |
c008336d36eec284ed6cb1b79ece005343ea3577 | 6,153 | package fr.sma.zombifier.core;
import fr.sma.zombifier.resources.FireWeapon;
import fr.sma.zombifier.resources.Resource;
import fr.sma.zombifier.resources.Weapon;
import fr.sma.zombifier.utils.Constants;
import fr.sma.zombifier.utils.Globals;
import fr.sma.zombifier.world.World;
import java.util.List;
import junit.framework.TestCase;
/**
* Unit tests for Simulation class.
*
* @author Alexandre Rabérin - Adrien Pierreval
*/
public class SimulationTest extends TestCase
{
/**
* Constructor.
* @param testName Name of the test case.
*/
public SimulationTest(String testName)
{
super(testName);
Globals.HUMAN_CONFIG = Constants.HUMAN_CONFIG_TEST;
Globals.ZOMBIE_CONFIG = Constants.ZOMBIE_CONFIG_TEST;
Globals.SIMULATION_PROPERTIES = Constants.SIMULATION_PROPERTIES_TEST;
Globals.RESOURCES_CONFIG = Constants.RESOURCES_CONFIG_TEST;
}
/**
* Set up the test case context.
* @throws Exception Exception.
*/
@Override
protected void setUp() throws Exception
{
super.setUp();
}
/**
* Clean memory allocation for the test case context.
* @throws Exception Exception.
*/
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
/**
* Test of initSimultation method, of class Simulation.
*/
public void testInitSimultation()
{
Simulation instance = new Simulation();
instance.initSimultation();
World w = instance.getWorld();
assertNotNull(w);
// Check entities positions
Entity e;
Human h;
Zombie z;
// Check Humans
// Check entity 1
e = w.get(4).get(4).getEntity();
assertNotNull(e);
assertTrue(e instanceof Human);
h = (Human)e;
assertEquals((int)h.getDirection().getFirst(), 0);
assertEquals((int)h.getDirection().getSecond(), -1);
// Check entity 2
e = w.get(15).get(9).getEntity();
assertNotNull(e);
assertTrue(e instanceof Human);
h = (Human)e;
assertEquals((int)h.getDirection().getFirst(), 1);
assertEquals((int)h.getDirection().getSecond(), 0);
// Check entity 3
e = w.get(1).get(19).getEntity();
assertNotNull(e);
assertTrue(e instanceof Human);
h = (Human)e;
assertEquals((int)h.getDirection().getFirst(), 1);
assertEquals((int)h.getDirection().getSecond(), 0);
// Check entity 4
e = w.get(12).get(12).getEntity();
assertNotNull(e);
assertTrue(e instanceof Human);
h = (Human)e;
assertEquals((int)h.getDirection().getFirst(), 0);
assertEquals((int)h.getDirection().getSecond(), -1);
// Check entity 5
e = w.get(6).get(10).getEntity();
assertNotNull(e);
assertTrue(e instanceof Human);
h = (Human)e;
assertEquals((int)h.getDirection().getFirst(), -1);
assertEquals((int)h.getDirection().getSecond(), 0);
// Check Zombies
// Check entity 1
e = w.get(5).get(4).getEntity();
assertNotNull(e);
assertTrue(e instanceof Zombie);
z = (Zombie)e;
assertEquals((int)z.getDirection().getFirst(), 0);
assertEquals((int)z.getDirection().getSecond(), 1);
// Check entity 2
e = w.get(3).get(17).getEntity();
assertNotNull(e);
assertTrue(e instanceof Zombie);
z = (Zombie)e;
assertEquals((int)z.getDirection().getFirst(), -1);
assertEquals((int)z.getDirection().getSecond(), 0);
// Check entity 3
e = w.get(15).get(13).getEntity();
assertNotNull(e);
assertTrue(e instanceof Zombie);
z = (Zombie)e;
assertEquals((int)z.getDirection().getFirst(), 0);
assertEquals((int)z.getDirection().getSecond(), 1);
// Check the number of entities
assertEquals(w.getNbEntities(), 8);
// Check resources positions
Resource r;
Weapon we;
FireWeapon f;
// Check resource 1
r = w.get(6).get(5).getResource();
assertNotNull(r);
assertTrue(r instanceof FireWeapon);
f = (FireWeapon)r;
assertEquals(f.getBreakRate(), 0.1f);
assertEquals(f.getPower(), 10);
assertEquals(f.getAmmo(), 5);
assertEquals(f.getRange(), 5);
// Check resource 2
r = w.get(11).get(19).getResource();
assertNotNull(r);
assertTrue(r instanceof Weapon);
we = (Weapon)r;
assertEquals(we.getBreakRate(), 0.2f);
assertEquals(we.getPower(), 11);
// Check resource 3
r = w.get(19).get(11).getResource();
assertNotNull(r);
assertTrue(r instanceof Weapon);
we = (Weapon)r;
assertEquals(we.getBreakRate(), 0.4f);
assertEquals(we.getPower(), 13);
// Check nb resources
assertEquals(w.getNbResources(), 3);
}
/**
* Test of getWorld method, of class Simulation.
*/
public void testGetWorld()
{
Simulation instance = new Simulation();
World result = instance.getWorld();
assertNull(result);
instance.initSimultation();
result = instance.getWorld();
assertNotNull(result);
assertEquals(result.size(), Globals.WORLD_HEIGHT);
assertEquals(result.get(0).size(), Globals.WORLD_WIDTH);
}
/**
* Test of getEntities method, of class Simulation.
*/
public void testGetEntities()
{
Simulation instance = new Simulation();
List<Entity> result = instance.getEntities();
assertNull(result);
instance.initSimultation();
result = instance.getEntities();
assertNotNull(result);
// Check only 8 entities because there are dublons and incompatible positions in test config
assertEquals(8, result.size());
}
}
| 30.014634 | 100 | 0.58053 |
552368123548d8079f7616fd0a3ddbdfe9b53036 | 403 | package com.cjy.flb.event;
/**
* Created by Administrator on 2015/12/15 0015.
*/
public class MedicineInfoEvent {
private boolean isTrue;
public MedicineInfoEvent() {
}
public MedicineInfoEvent(boolean b) {
this.isTrue = b;
}
public boolean isTrue() {
return isTrue;
}
public void setIsTrue(boolean isTrue) {
this.isTrue = isTrue;
}
}
| 16.12 | 47 | 0.617866 |
9a2471de56ef03ba2903db5fd911a6625a30e364 | 670 | package core.framework.api.validate;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Digits can be used on numeric fields.
*
* @author chris
*/
@Target(FIELD)
@Retention(RUNTIME)
public @interface Digits {
int integer() default -1; // maximum number of integral digits accepted for this number
int fraction() default -1; // maximum number of fractional digits accepted for this number
String message() default "field out of bounds (<{integer} digits>.<{fraction} digits> expected), value={value}";
}
| 26.8 | 116 | 0.747761 |
0a99637ce986be7e55aa425570af37b02dec39cd | 780 | /*
Copyright (C) 2001, 2008 United States Government
as represented by the Administrator of the
National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.render.markers;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.render.DrawContext;
/**
* @author tag
* @version $Id: Marker.java 12576 2009-09-10 16:17:20Z jterhorst $
*/
public interface Marker
{
void render(DrawContext dc, Vec4 point, double radius, boolean isRelative);
void render(DrawContext dc, Vec4 point, double radius);
Position getPosition();
void setPosition(Position position);
MarkerAttributes getAttributes();
void setAttributes(MarkerAttributes attributes);
Angle getHeading();
void setHeading(Angle heading);
}
| 21.666667 | 79 | 0.744872 |
e1ff5474e054d573f9e5e28ed153fd4c40d67284 | 788 | package org.vivoweb.vivo.selenium;
import org.openqa.selenium.By;
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 final class SeleniumUtils {
private static String baseUrl = "http://localhost:8080/vivo";
public static void setBaseUrl(String baseUrl) {
SeleniumUtils.baseUrl = baseUrl;
}
public static String makeUrl(String urlPart) {
if (urlPart.startsWith("/")) {
return baseUrl + urlPart;
} else {
return baseUrl + "/" + urlPart;
}
}
public static void navigate(WebDriver driver, String urlPart) {
driver.navigate().to(makeUrl(urlPart));
}
}
| 28.142857 | 67 | 0.68401 |
8f8e2950fd69001ea25768ee6dcc839d651c5f61 | 3,609 | package org.coreasm.compiler.plugins.io.include;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.coreasm.engine.absstorage.Element;
import org.coreasm.engine.absstorage.Location;
import org.coreasm.engine.absstorage.Update;
import org.coreasm.engine.plugins.string.StringElement;
import CompilerRuntime.AggregationHelper;
import CompilerRuntime.AggregationHelper.Flag;
import CompilerRuntime.PluginCompositionAPI;
import CompilerRuntime.UpdateAggregator;
/**
* Aggregates IO operation updates
* @author Spellmaker
*
*/
public class IOAggregator implements UpdateAggregator {
@Override
public void aggregateUpdates(AggregationHelper pluginAgg) {
// all locations on which contain print actions
synchronized (this) {
Set<Location> locsToAggregate = pluginAgg.getLocsWithAnyAction(IOPlugin.PRINT_ACTION);
List<Element> contributingAgents = new ArrayList<Element>();
// for all locations to aggregate
for (Location l : locsToAggregate) {
if (l.equals(IOPlugin.PRINT_OUTPUT_FUNC_LOC)) {
String outputResult = "";
// if regular update affects this location
if (pluginAgg.regularUpdatesAffectsLoc(l)) {
pluginAgg.handleInconsistentAggregationOnLocation(l,this);
} else {
for (Update update: pluginAgg.getLocUpdates(l)) {
if (update.action.equals(IOPlugin.PRINT_ACTION)) {
outputResult += update.value.toString() + "\n";
// flag update aggregation as successful for this update
pluginAgg.flagUpdate(update, Flag.SUCCESSFUL, this);
contributingAgents.addAll(update.agents);
}
}
}
pluginAgg.addResultantUpdate(
new Update(
IOPlugin.PRINT_OUTPUT_FUNC_LOC,
new StringElement(outputResult),
Update.UPDATE_ACTION,
new HashSet<Element>(contributingAgents), null
),
this
);
}
}
}
}
@Override
public void compose(PluginCompositionAPI compAPI) {
synchronized (this) {
String outputResult1 = "";
String outputResult2 = "";
List<Element> contributingAgents = new ArrayList<Element>();
// First, add all the updates in the second set
for (Update u: compAPI.getLocUpdates(2, IOPlugin.PRINT_OUTPUT_FUNC_LOC)) {
if (u.action.equals(IOPlugin.PRINT_ACTION)) {
if (!outputResult2.isEmpty())
outputResult2 += '\n';
outputResult2 += u.value.toString();
contributingAgents.addAll(u.agents);
}
else
compAPI.addComposedUpdate(u, "IOPlugin");
}
// if the second set does not have a basic update,
// add all the updates from the first set as well
if (!compAPI.isLocUpdatedWithActions(2, IOPlugin.PRINT_OUTPUT_FUNC_LOC, Update.UPDATE_ACTION)) {
for (Update u: compAPI.getLocUpdates(1, IOPlugin.PRINT_OUTPUT_FUNC_LOC)) {
if (u.action.equals(IOPlugin.PRINT_ACTION)) {
if (!outputResult1.isEmpty())
outputResult1 += '\n';
outputResult1 += u.value.toString();
contributingAgents.addAll(u.agents);
}
else
compAPI.addComposedUpdate(u, "IOPlugin");
}
}
if (!outputResult1.isEmpty() || !outputResult2.isEmpty()) {
String outputResult = outputResult1;
if (outputResult.isEmpty())
outputResult = outputResult2;
else if (!outputResult2.isEmpty())
outputResult = outputResult1 + '\n' + outputResult2;
compAPI.addComposedUpdate(new Update(IOPlugin.PRINT_OUTPUT_FUNC_LOC,
new StringElement(outputResult),
IOPlugin.PRINT_ACTION, new HashSet<Element>(contributingAgents), null), "IOPlugin");
}
}
}
}
| 32.223214 | 99 | 0.702688 |
7056783d942bd5d57cc190fc156cf3ac23b37329 | 1,296 | package cucumber.runtime.model;
import cucumber.runtime.World;
import gherkin.formatter.model.Scenario;
import gherkin.formatter.model.Step;
import gherkin.formatter.model.Tag;
import java.util.*;
public class CucumberScenario {
private final List<Step> steps = new ArrayList<Step>();
private final Scenario scenario;
private final CucumberFeature cucumberFeature;
private final String uri;
private World world;
public CucumberScenario(CucumberFeature cucumberFeature, String uri, Scenario scenario) {
this.cucumberFeature = cucumberFeature;
this.uri = uri;
this.scenario = scenario;
}
public Scenario getScenario() {
return scenario;
}
public List<Step> getSteps() {
return steps;
}
public void step(Step step) {
steps.add(step);
}
public Set<String> tags() {
Set<String> tags = new HashSet<String>();
for (Tag tag : cucumberFeature.getFeature().getTags()) {
tags.add(tag.getName());
}
for (Tag tag : scenario.getTags()) {
tags.add(tag.getName());
}
return tags;
}
public String getUri() {
return uri;
}
public Locale getLocale() {
return cucumberFeature.getLocale();
}
}
| 23.563636 | 93 | 0.633488 |
c8ce4536c27e3f0b68d9a9578d7c7ee8cce429b3 | 202 | package com.run.sg.util;
/**
* Created by MBENBEN on 2017/6/15.
*/
public class CurrentPosition {
public static double mCurrentPointLat = 0.0;
public static double mCurrentPointLon = 0.0;
}
| 18.363636 | 48 | 0.70297 |
47dea7b87bc9efccba844c29adf53413a38ce1f2 | 1,861 | package com.adintellig.ella.model;
import java.sql.Timestamp;
public class RequestCount {
private long writeCount = 0l;
private long readCount = 0l;
private long totalCount = 0l;
private Timestamp updateTime = null;
private Timestamp insertTime = null;
private int writeTps = 0;
private int readTps = 0;
private int totalTps = 0;
public RequestCount() {
}
public RequestCount(long writeCount, long readCount, long totalCount,
Timestamp updateTime, Timestamp insertTime, int writeTps,
int readTps, int totalTps) {
super();
this.writeCount = writeCount;
this.readCount = readCount;
this.totalCount = totalCount;
this.updateTime = updateTime;
this.insertTime = insertTime;
this.writeTps = writeTps;
this.readTps = readTps;
this.totalTps = totalTps;
}
public long getWriteCount() {
return writeCount;
}
public void setWriteCount(long writeCount) {
this.writeCount = writeCount;
}
public long getReadCount() {
return readCount;
}
public void setReadCount(long readCount) {
this.readCount = readCount;
}
public long getTotalCount() {
return totalCount;
}
public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public Timestamp getInsertTime() {
return insertTime;
}
public void setInsertTime(Timestamp insertTime) {
this.insertTime = insertTime;
}
public int getWriteTps() {
return writeTps;
}
public void setWriteTps(int writeTps) {
this.writeTps = writeTps;
}
public int getReadTps() {
return readTps;
}
public void setReadTps(int readTps) {
this.readTps = readTps;
}
public int getTotalTps() {
return totalTps;
}
public void setTotalTps(int totalTps) {
this.totalTps = totalTps;
}
}
| 19.185567 | 70 | 0.726491 |
88242060e6eccf64488431506d68f7aa4201aaa4 | 1,630 | package com.udacity.jdnd.course3.critter.service;
import com.udacity.jdnd.course3.critter.data.entity.Customer;
import com.udacity.jdnd.course3.critter.data.entity.Pet;
import com.udacity.jdnd.course3.critter.data.repository.CustomerRepository;
import com.udacity.jdnd.course3.critter.data.repository.PetRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CustomerService {
private CustomerRepository customerRepository;
private PetRepository petRepository;
public CustomerService(CustomerRepository repo, PetRepository petRepository) {
customerRepository = repo;
this.petRepository = petRepository;
}
public Customer save(Customer customer) {
return customerRepository.save(customer);
}
public Customer getCustomer(long id) {
Optional<Customer> optionalCustomer = customerRepository.findById(id);
if (optionalCustomer.isPresent()) {
return optionalCustomer.get();
} else {
throw new ObjectNotFoundException("Cannot find customer with id: " + id);
}
}
public List<Customer> getAllCustomers() {
return customerRepository.findAll();
}
public Customer getByPetId(long petId) {
Optional<Pet> optionalPet = petRepository.findById(petId);
if (!optionalPet.isPresent()) {
throw new ObjectNotFoundException("Cannot find pet with id: " + petId);
}
return optionalPet.get().getOwner();
}
}
| 31.346154 | 85 | 0.720245 |
cf685e33c72774abf9f4d3e1c3d397707dfa2401 | 205 | package com.gmy.common.constant;
public class EsConstant {
/* product 在 es 的索引 */
public static final String PRODUCT_INDEX = "product";
public static final Integer PRODUCT_PAGE_SIZE = 16;
}
| 20.5 | 57 | 0.717073 |
aa6e832de58453e3ab345cfb44aeefb14178c6f8 | 417 | /*
* 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 ed.biodare2.backend.features.ppa;
import ed.biodare2.backend.features.jobcentre2.JC2ServiceParameters;
/**
*
* @author tzielins
*/
public class PPAServiceParameters extends JC2ServiceParameters {
}
| 24.529412 | 80 | 0.731415 |
7e649bb7328a1e75fe6a24887e2b43122d21caed | 8,681 | package jetbrains.mps.baseLanguage.regexp.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.openapi.editor.style.StyleRegistry;
import jetbrains.mps.nodeEditor.MPSColors;
import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.openapi.editor.cells.CellActionType;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSmart;
import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SEmptyContainmentSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo;
import jetbrains.mps.openapi.editor.menus.transformation.SNodeLocation;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
/*package*/ class InlineRegexpExpression_EditorBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public InlineRegexpExpression_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_0();
}
private EditorCell createCollection_0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_5rturt_a");
editorCell.setBig(true);
setCellContext(editorCell);
editorCell.addEditorCell(createConstant_0());
editorCell.addEditorCell(createRefNode_0());
editorCell.addEditorCell(createConstant_1());
if (nodeCondition_5rturt_a3a()) {
editorCell.addEditorCell(createConstant_2());
}
if (nodeCondition_5rturt_a4a()) {
editorCell.addEditorCell(createConstant_3());
}
if (nodeCondition_5rturt_a5a()) {
editorCell.addEditorCell(createConstant_4());
}
return editorCell;
}
private boolean nodeCondition_5rturt_a3a() {
return SPropertyOperations.getBoolean(myNode, PROPS.multiLine$$IgZ);
}
private boolean nodeCondition_5rturt_a4a() {
return SPropertyOperations.getBoolean(myNode, PROPS.dotAll$_Eew);
}
private boolean nodeCondition_5rturt_a5a() {
return SPropertyOperations.getBoolean(myNode, PROPS.caseInsensitive$j6L5);
}
private EditorCell createConstant_0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "/");
editorCell.setCellId("Constant_5rturt_a0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, StyleRegistry.getInstance().getSimpleColor(MPSColors.DARK_MAGENTA));
style.set(StyleAttributes.PUNCTUATION_RIGHT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_0() {
SingleRoleCellProvider provider = new regexpSingleRoleHandler_5rturt_b0(myNode, LINKS.regexp$XKbh, getEditorContext());
return provider.createCell();
}
private static class regexpSingleRoleHandler_5rturt_b0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public regexpSingleRoleHandler_5rturt_b0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), LINKS.regexp$XKbh, child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), LINKS.regexp$XKbh, child));
installCellInfo(child, editorCell, false);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell, boolean isEmpty) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo((isEmpty ? new SEmptyContainmentSubstituteInfo(editorCell) : new SChildSubstituteInfo(editorCell)));
}
if (editorCell.getSRole() == null) {
editorCell.setSRole(LINKS.regexp$XKbh);
}
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), LINKS.regexp$XKbh));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_regexp");
installCellInfo(null, editorCell, true);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no regexp>";
}
}
private EditorCell createConstant_1() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "/");
editorCell.setCellId("Constant_5rturt_c0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, StyleRegistry.getInstance().getSimpleColor(MPSColors.DARK_MAGENTA));
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_2() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "m");
editorCell.setCellId("Constant_5rturt_d0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, StyleRegistry.getInstance().getSimpleColor(MPSColors.DARK_MAGENTA));
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
editorCell.getStyle().putAll(style);
InlineRegexpExpression_removeM.setCellActions(editorCell, myNode, getEditorContext());
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_3() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "s");
editorCell.setCellId("Constant_5rturt_e0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, StyleRegistry.getInstance().getSimpleColor(MPSColors.DARK_MAGENTA));
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
editorCell.getStyle().putAll(style);
InlineRegexpExpression_removeS.setCellActions(editorCell, myNode, getEditorContext());
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_4() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "i");
editorCell.setCellId("Constant_5rturt_f0");
Style style = new StyleImpl();
style.set(StyleAttributes.TEXT_COLOR, StyleRegistry.getInstance().getSimpleColor(MPSColors.DARK_MAGENTA));
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
editorCell.getStyle().putAll(style);
InlineRegexpExpression_removeI.setCellActions(editorCell, myNode, getEditorContext());
editorCell.setDefaultText("");
return editorCell;
}
private static final class PROPS {
/*package*/ static final SProperty multiLine$$IgZ = MetaAdapterFactory.getProperty(0xdaafa647f1f74b0bL, 0xb09669cd7c8408c0L, 0x1117648961dL, 0x1119ceddfe3L, "multiLine");
/*package*/ static final SProperty dotAll$_Eew = MetaAdapterFactory.getProperty(0xdaafa647f1f74b0bL, 0xb09669cd7c8408c0L, 0x1117648961dL, 0x1119cedcf38L, "dotAll");
/*package*/ static final SProperty caseInsensitive$j6L5 = MetaAdapterFactory.getProperty(0xdaafa647f1f74b0bL, 0xb09669cd7c8408c0L, 0x1117648961dL, 0x1119cf15020L, "caseInsensitive");
}
private static final class LINKS {
/*package*/ static final SContainmentLink regexp$XKbh = MetaAdapterFactory.getContainmentLink(0xdaafa647f1f74b0bL, 0xb09669cd7c8408c0L, 0x1117648961dL, 0x11176490e08L, "regexp");
}
}
| 44.290816 | 186 | 0.769957 |
ac8204243f662f3936058124bb430739b2868d90 | 38 | class _lNP6WbU {
}
class K05pD {
}
| 4.75 | 16 | 0.605263 |
227d99de697f629fa85c0b81fd2338ebbc323a2c | 2,946 | package org.jcodec.algo;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture;
import org.jcodec.common.model.Plane;
import org.jcodec.common.model.Size;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* @author The JCodec project
*
*/
public class BilinearInterpolator2D implements Interpolator2D {
private static int ROUND = 1 << 15;
/**
* Interpolate input plane to fill the output plane
*
* @param in
* @param out
*/
public void interpolate(Plane in, Plane out) {
int stepX = (in.getSize().getWidth() << 8) / out.getSize().getWidth();
int stepY = (in.getSize().getHeight() << 8) / out.getSize().getHeight();
int[] data = in.getData();
int stride = in.getSize().getWidth();
int[] outData = out.getData();
int posY = 0, line = 0, outOff = 0;
for (int y = 0; y < out.getSize().getHeight() - 1; y++) {
interpolateLine(outData, outOff, out.getSize().getWidth(), data, line, line + stride, posY & 0xff, stepX);
outOff += out.getSize().getWidth();
posY += stepY;
line = (posY >> 8) * stride;
}
interpolateLine(outData, outOff, out.getSize().getWidth(), data, line, line, posY & 0xff, stepX);
}
private final void interpolateLine(int[] dst, int dstOff, int dstWidth, int[] src, int line, int nextLine,
int shiftY, int stepX) {
int posX = 0;
for (int x = 0; x < dstWidth - 1; x++) {
int ind = posX >> 8;
dst[dstOff++] = interpolateHV(shiftY, posX & 0xff, src[line + ind], src[line + ind + 1],
src[nextLine + ind], src[nextLine + ind + 1]);
posX += stepX;
}
int ind = posX >> 8;
dst[dstOff++] = interpolateHV(shiftY, posX & 0xff, src[line + ind], src[line + ind], src[nextLine + ind],
src[nextLine + ind]);
}
private final int interpolateHV(int shiftY, int shiftX, int s00, int s01, int s10, int s11) {
int s0 = (s00 << 8) + (s01 - s00) * shiftX;
int s1 = (s10 << 8) + (s11 - s10) * shiftX;
return ((s0 << 8) + (s1 - s0) * shiftY + ROUND) >> 16;
}
/**
* Interpolate an input picture to fill the output picture
*
* @param in
* @param out
*/
public void interpolate(Picture in, Picture out) {
int[][] data = in.getData();
ColorSpace inClr = in.getColor();
ColorSpace outClr = out.getColor();
for (int i = 0; i < data.length; i++) {
interpolate(new Plane(data[i], new Size(in.getWidth() * inClr.compWidth[i], in.getHeight()
* inClr.compHeight[i])),
new Plane(data[i], new Size(in.getWidth() * outClr.compWidth[i], in.getHeight()
* outClr.compHeight[i])));
}
}
}
| 35.493976 | 118 | 0.554311 |
54be8d2c0ec89d8ccfa8b445d5ff7d9ddd6f69dd | 5,695 | /*
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API generated from yang definitions
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.TapiPhotonicMediaLaserControlStatusType;
import io.swagger.model.TapiPhotonicMediaLaserType;
import javax.validation.constraints.*;
/**
* TapiPhotonicMediaLaserPropertiesPac
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2018-11-14T14:58:12.974+01:00")
public class TapiPhotonicMediaLaserPropertiesPac {
@JsonProperty("laser-application-type")
private TapiPhotonicMediaLaserType laserApplicationType = null;
@JsonProperty("laser-bias-current")
private String laserBiasCurrent = null;
@JsonProperty("laser-temperature")
private String laserTemperature = null;
@JsonProperty("laser-status")
private TapiPhotonicMediaLaserControlStatusType laserStatus = null;
public TapiPhotonicMediaLaserPropertiesPac laserApplicationType(TapiPhotonicMediaLaserType laserApplicationType) {
this.laserApplicationType = laserApplicationType;
return this;
}
/**
* The type of laser, its operational wavelengths, and its applications. String size 255.
* @return laserApplicationType
**/
@JsonProperty("laser-application-type")
@ApiModelProperty(value = "The type of laser, its operational wavelengths, and its applications. String size 255.")
public TapiPhotonicMediaLaserType getLaserApplicationType() {
return laserApplicationType;
}
public void setLaserApplicationType(TapiPhotonicMediaLaserType laserApplicationType) {
this.laserApplicationType = laserApplicationType;
}
public TapiPhotonicMediaLaserPropertiesPac laserBiasCurrent(String laserBiasCurrent) {
this.laserBiasCurrent = laserBiasCurrent;
return this;
}
/**
* The Bias current of the laser that is the medium polarization current of the laser.
* @return laserBiasCurrent
**/
@JsonProperty("laser-bias-current")
@ApiModelProperty(value = "The Bias current of the laser that is the medium polarization current of the laser.")
public String getLaserBiasCurrent() {
return laserBiasCurrent;
}
public void setLaserBiasCurrent(String laserBiasCurrent) {
this.laserBiasCurrent = laserBiasCurrent;
}
public TapiPhotonicMediaLaserPropertiesPac laserTemperature(String laserTemperature) {
this.laserTemperature = laserTemperature;
return this;
}
/**
* The temperature of the laser
* @return laserTemperature
**/
@JsonProperty("laser-temperature")
@ApiModelProperty(value = "The temperature of the laser")
public String getLaserTemperature() {
return laserTemperature;
}
public void setLaserTemperature(String laserTemperature) {
this.laserTemperature = laserTemperature;
}
public TapiPhotonicMediaLaserPropertiesPac laserStatus(TapiPhotonicMediaLaserControlStatusType laserStatus) {
this.laserStatus = laserStatus;
return this;
}
/**
* none
* @return laserStatus
**/
@JsonProperty("laser-status")
@ApiModelProperty(value = "none")
public TapiPhotonicMediaLaserControlStatusType getLaserStatus() {
return laserStatus;
}
public void setLaserStatus(TapiPhotonicMediaLaserControlStatusType laserStatus) {
this.laserStatus = laserStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TapiPhotonicMediaLaserPropertiesPac tapiPhotonicMediaLaserPropertiesPac = (TapiPhotonicMediaLaserPropertiesPac) o;
return Objects.equals(this.laserApplicationType, tapiPhotonicMediaLaserPropertiesPac.laserApplicationType) &&
Objects.equals(this.laserBiasCurrent, tapiPhotonicMediaLaserPropertiesPac.laserBiasCurrent) &&
Objects.equals(this.laserTemperature, tapiPhotonicMediaLaserPropertiesPac.laserTemperature) &&
Objects.equals(this.laserStatus, tapiPhotonicMediaLaserPropertiesPac.laserStatus);
}
@Override
public int hashCode() {
return Objects.hash(laserApplicationType, laserBiasCurrent, laserTemperature, laserStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TapiPhotonicMediaLaserPropertiesPac {\n");
sb.append(" laserApplicationType: ").append(toIndentedString(laserApplicationType)).append("\n");
sb.append(" laserBiasCurrent: ").append(toIndentedString(laserBiasCurrent)).append("\n");
sb.append(" laserTemperature: ").append(toIndentedString(laserTemperature)).append("\n");
sb.append(" laserStatus: ").append(toIndentedString(laserStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 34.515152 | 190 | 0.755048 |
4ed97178f667ab949a22560c359f790985d23266 | 10,008 | // Copyright 2010 Google, Inc. All rights reserved.
// Copyright 2009 John Kristian.
//
// 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.oacurl;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.oauth.OAuth;
import com.google.oacurl.oauth.OAuthAccessor;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import com.google.oacurl.options.LoginOptions;
/**
* Class that runs a Jetty server on a free port, waiting for OAuth to redirect
* to it with the one-time authorization token.
* <p>
* Initially derived from the oauth-example-desktop by John Kristian.
*
* @author phopkins@google.com
*/
public class LoginCallbackServer {
public enum TokenStatus {
MISSING,
VALID,
INVALID
}
private static final String DEMO_PATH = "/";
private static final String CALLBACK_PATH = "/OAuthCallback";
private final LoginOptions options;
private int port;
private String host;
private Server server;
private TokenStatus tokenStatus = TokenStatus.MISSING;
private String authorizationUrl;
private Map<String, String> verifierMap = new HashMap<String, String>();
public LoginCallbackServer(LoginOptions options) {
this.options = options;
}
public void start() {
if (server != null) {
throw new IllegalStateException("Server is already started");
}
try {
port = getUnusedPort();
host = options.getHost();
server = new Server(port);
for (Connector c : server.getConnectors()) {
c.setHost(host);
}
server.addHandler(new CallbackHandler());
server.addHandler(new DemoHandler());
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void stop() throws Exception {
if (server != null) {
server.stop();
server = null;
}
}
public void setTokenStatus(TokenStatus tokenStatus) {
this.tokenStatus = tokenStatus;
}
public void setAuthorizationUrl(String authorizationUrl) {
this.authorizationUrl = authorizationUrl;
}
public String getDemoUrl() throws IOException {
if (port == 0) {
throw new IllegalStateException("Server is not yet started");
}
return "http://" + host + ":" + port + DEMO_PATH;
}
public String getCallbackUrl() {
if (port == 0) {
throw new IllegalStateException("Server is not yet started");
}
return "http://" + host + ":" + port + CALLBACK_PATH;
}
private static int getUnusedPort() throws IOException {
Socket s = new Socket();
s.bind(null);
try {
return s.getLocalPort();
} finally {
s.close();
}
}
/**
* Call that blocks until the OAuth provider redirects back here with the
* verifier token.
*
* @param accessor Accessor whose request token we're waiting for a verifier
* token for.
* @param waitMillis Amount of time we're willing to wait, it millis.
* @return The verifier token, or null if there was a timeout.
*/
public String waitForVerifier(OAuthAccessor accessor, long waitMillis) {
long startTime = System.currentTimeMillis();
synchronized (verifierMap) {
while (!verifierMap.containsKey(accessor.requestToken)) {
try {
verifierMap.wait(3000);
} catch (InterruptedException e) {
return null;
}
if (waitMillis != -1 && System.currentTimeMillis() > startTime + waitMillis) {
return null;
}
}
return verifierMap.remove(accessor.requestToken);
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth
* provider and stashes it where
* {@link LoginCallbackServer#waitForVerifier} will find it.
*/
public class CallbackHandler extends AbstractHandler {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch)
throws IOException, ServletException {
if (!CALLBACK_PATH.equals(target)) {
return;
}
String requestTokenName;
String verifierName;
switch (options.getVersion()) {
case V1:
verifierName = OAuth.OAUTH_VERIFIER;
requestTokenName = OAuth.OAUTH_TOKEN;
break;
case V2:
verifierName = "code";
requestTokenName = "state";
break;
case WRAP:
verifierName = "wrap_verification_code";
requestTokenName = OAuth.OAUTH_TOKEN;
break;
default:
throw new AssertionError("Unknown version: " + options.getVersion());
}
String verifier = request.getParameter(verifierName);
String requestToken = request.getParameter(requestTokenName);
if (verifier != null) {
writeLandingHtml(response);
synchronized (verifierMap) {
verifierMap.put(requestToken, verifier);
verifierMap.notifyAll();
}
} else {
writeErrorHtml(request, response);
}
response.flushBuffer();
((Request) request).setHandled(true);
}
private void writeLandingHtml(HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println("<head><title>OAuth Authentication Token Recieved</title></head>");
doc.println("<body>");
doc.println("Received verifier token. Closing...");
doc.println("<script type='text/javascript'>");
// We open "" in the same window to trigger JS ownership of it, which lets
// us then close it via JS, at least in Chrome.
doc.println("window.setTimeout(function() {");
doc.println(" window.open('', '_self', ''); window.close(); }, 1000);");
doc.println("if (window.opener) { window.opener.checkToken(); }");
doc.println("</script>");
doc.println("</body>");
doc.println("</HTML>");
doc.flush();
}
private void writeErrorHtml(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println("<head><title>OAuth Authentication Token Not Recieved</title></head>");
doc.println("<body>");
doc.println("Did not receive verifier token. One of these parameters might be interesting:");
doc.println("<dl>");
@SuppressWarnings("unchecked")
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
doc.println("<dt>" + param.getKey() + "</dt>");
for (String value : param.getValue()) {
doc.println("<dd>" + value + "</dd>");
}
}
doc.println("</dl>");
doc.println("</body>");
doc.println("</HTML>");
doc.flush();
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth
* provider and stashes it where
* {@link LoginCallbackServer#waitForVerifier} will find it.
*/
public class DemoHandler extends AbstractHandler {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch)
throws IOException, ServletException {
if (!DEMO_PATH.equals(target)) {
return;
}
writeDemoHtml(LoginCallbackServer.this.authorizationUrl, response);
}
private void writeDemoHtml(String authorizationUrl,
HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println("<head><title>OACurl Demo App</title></head>");
doc.println("<body>");
doc.println("<script type='text/javascript'>");
doc.println("function launchAuth() {");
doc.println(" window.open('" + authorizationUrl + "', 'oauth', ");
doc.println(" 'width=640,height=450,toolbar=no,location=yes');");
doc.println("}");
doc.println("function checkToken() {");
// 1s delay for reload because we want to wait for the OAuth check to
// happen in the background. One would presumably make a nicer flow-of-
// control in a real app.
doc.println(" window.setTimeout(function() { window.location.reload(); }, 1000);");
doc.println("}");
doc.println("</script>");
doc.println("<h1>OACurl Demo App</h1>");
doc.println("<p>Current token status: <b>" + LoginCallbackServer.this.tokenStatus + "</b></p>");
doc.println("<button onclick='launchAuth()'>OAuth Login</button><br />");
doc.println("<h2>Recommended JavaScript for Authorization</h2>");
doc.println("<pre>");
doc.println("window.open('<i>http://...</i>',");
doc.println(" 'oauth', ");
doc.println(" 'width=640,height=450,toolbar=no,location=yes');");
doc.println("</pre>");
doc.println("</body>");
doc.println("</HTML>");
doc.flush();
}
}
}
| 31.670886 | 102 | 0.652678 |
52afd386bb4afd29403191416d6c16a84c2bc330 | 232 | package com.oc.hawk.api.constant;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class AccountHolder {
private Long id;
public AccountHolder(Long id) {
this.id = id;
}
}
| 14.5 | 35 | 0.702586 |
2fd62b618250d091cd7303fe8ac04985024b3cd9 | 1,051 | package com.clavardage.core.database.queries.inserts;
import com.clavardage.core.database.queries.QueryParameters;
import java.sql.SQLException;
import java.util.ArrayList;
public class NewConversationInsertQuery extends InsertQuery {
private static final String QUERY = "INSERT INTO chat_room (name, users_number) VALUES (?,?)";
private static final int NUMBER_OF_ARGUMENTS = 2;
public NewConversationInsertQuery() {
super(QUERY);
}
@Override
public void setParameters(QueryParameters parameters) {
ArrayList<Object> parametersList = parameters.getParam();
if (parametersList.size() != NUMBER_OF_ARGUMENTS) {
System.err.println(NUMBER_OF_ARGUMENTS + " arguments needed");
} else {
try {
this.statement.setString(1, (String) parametersList.get(0));
this.statement.setInt(2, (Integer) parametersList.get(1));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
| 33.903226 | 98 | 0.664129 |
4e61b8893734b1497ed1626dc0c6ed8a92529197 | 1,645 | /*
* Copyright 2012 JBoss 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.drools.guvnor.client.rpc;
import org.drools.ide.common.client.modeldriven.testing.Scenario;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.google.gwt.user.client.rpc.SerializationException;
@RemoteServiceRelativePath("testScenarioService")
public interface TestScenarioService
extends
RemoteService {
/**
* @param packageName
* The package name the scenario is to be run in.
* @param scenario
* The scenario to run.
* @return The scenario, with the results fields populated.
* @throws com.google.gwt.user.client.rpc.SerializationException
*/
public SingleScenarioResult runScenario(String packageName,
Scenario scenario) throws SerializationException;
/**
* This should be pretty obvious what it does !
*/
public BulkTestRunResult runScenariosInPackage(String packageUUID) throws SerializationException;
}
| 35 | 101 | 0.715502 |
b63964e009120835e366b0f9802e01a3e6e28368 | 987 | package com.mysite.core.services.impl;
import com.mysite.core.services.ConfigurationService;
import com.mysite.core.services.Student;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
import com.mysite.core.services.Configuration;
import java.util.List;
@Component(service=ConfigurationService.class)
@Designate(ocd=Configuration.class)
public class ConfigurationServiceImpl implements ConfigurationService {
private int allowedStudents;
private int passingMarks;
@Activate
protected void activate(Configuration config) {
allowedStudents = config.allowed_students();
passingMarks = config.passing_marks();
}
@Override
public boolean isClassLimitReached(List<Student> list) {
return list.size() < allowedStudents;
}
@Override
public int getPassingMarks() {
return passingMarks;
}
}
| 25.307692 | 71 | 0.758865 |
7114e1949256c3bb9f8fc4cbd4c618c544453cb6 | 605 | package com.michael.attackpoint.discussion;
import com.michael.attackpoint.discussion.data.DiscussionRepository;
import com.michael.attackpoint.discussion.data.DiscussionRepositoryImpl;
/**
* Created by michael on 5/5/16.
*/
public class DiscussionRepositories {
private DiscussionRepositories() {
// no instance
}
private static DiscussionRepository repository = null;
public synchronized static DiscussionRepository getRepoInstance() {
if (repository == null) {
repository = new DiscussionRepositoryImpl();
}
return repository;
}
}
| 25.208333 | 72 | 0.715702 |
b236000fb0ed2b293852a20b80414a0c9bfd6803 | 1,658 | /**
* created Jun 9, 2006
*
* @by Marc Woerlein (woerlein@informatik.uni-erlangen.de)
*
* Copyright 2006 Marc Woerlein
*
* This file is part of parsemis.
*
* Licence:
* LGPL: http://www.gnu.org/licenses/lgpl.html
* EPL: http://www.eclipse.org/org/documents/epl-v10.php
* See the LICENSE file in the project's top-level directory for details.
*/
package de.parsemis.miner.chain;
import java.util.Collection;
import de.parsemis.miner.general.HPEmbedding;
/**
* This class implements the general child generation based on stored
* embeddings.
*
* @author Marc Woerlein (woerlein@informatik.uni-erlangen.de)
*
* @param <NodeType>
* the type of the node labels (will be hashed and checked with
* .equals(..))
* @param <EdgeType>
* the type of the edge labels (will be hashed and checked with
* .equals(..))
*/
public class EmbeddingBasedGenerationStep<NodeType, EdgeType> extends
GenerationStep<NodeType, EdgeType> {
/**
* creates a new GenerationStep
*
* @param next
* the next step of the mining chain
*/
public EmbeddingBasedGenerationStep(
final MiningStep<NodeType, EdgeType> next) {
super(next);
}
/*
* (non-Javadoc)
*
* @see de.parsemis.miner.MiningStep#call(de.parsemis.miner.SearchLatticeNode,
* java.util.Collection)
*/
@Override
public void call(final SearchLatticeNode<NodeType, EdgeType> node,
final Collection<Extension<NodeType, EdgeType>> extensions) {
super.reset();
for (final HPEmbedding<NodeType, EdgeType> e : node.allEmbeddings()) {
super.call(node, e);
}
super.call(node, extensions);
}
}
| 25.507692 | 79 | 0.677925 |
b1eb1c40816265191e5e6866d39f3499c0ff48a8 | 94 | package wx.ds.graph.search.bfs;
/**
* Created by apple on 16/5/15.
*/
public class BFS {
}
| 11.75 | 31 | 0.638298 |
664482e8fab29d0de08a4b45f829690cde8fcc11 | 192 | package com.codewithmosh;
public class Main41java {
public static void main(String[] args) {
int result = (int)Math.round(Math.random()*100);
System.out. println(result);
}
} | 21.333333 | 53 | 0.671875 |
2e57fe151e1f844404eba1053a5cd8c760bbf98b | 29 | public class Problem{
}
| 7.25 | 21 | 0.62069 |