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 |
|---|---|---|---|---|---|
b69c863d81b077ac2e2e196f8e8c3a382a38f887 | 7,403 | /*
* Copyright 2016 Ecole des Mines de Saint-Etienne.
*
* 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.thesmartenergy.sparql.generate.jena.iterator.library;
import com.github.filosganga.geogson.gson.GeometryAdapterFactory;
import com.github.filosganga.geogson.model.Feature;
import com.github.filosganga.geogson.model.FeatureCollection;
import com.github.filosganga.geogson.model.Geometry;
import com.github.thesmartenergy.sparql.generate.jena.SPARQLGenerate;
import com.github.thesmartenergy.sparql.generate.jena.iterator.IteratorFunctionBase1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.expr.nodevalue.NodeValueNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Iterator function
* <a href="http://w3id.org/sparql-generate/iter/GeoJSONFeatures">iter:GeoJSONFeatures</a>
* takes as input a <a href="https://tools.ietf.org/html/rfc7946">GeoJSON</a> document, decodes it,
* and extracts a list of sub-JSON <a href="https://tools.ietf.org/html/rfc7946#page-11">Features</a> contained in the <a href="https://tools.ietf.org/html/rfc7946#page-12">FeatureCollection</a> object.
*
* <ul>
* <li>Param 1: (json): a GeoJSON object with the type FeatureCollection.</li>
* </ul>
*
* <b>Example: </b>
*
* Iterating over this GeoJSON document (as <tt>?source</tt>)<br>
* <pre>
* {
* "type":"FeatureCollection",
* "metadata":{
* "generated":1528963592000,
* "url":"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson",
* "title":"USGS Magnitude 2.5+ Earthquakes, Past Month"
* },
* "features":[
* {
* "type":"Feature",
* "properties":{
* "place":"1km SSE of Volcano, Hawaii",
* "time":1528975443520,
* "updated":1528975662950,
* "url":"https://earthquake.usgs.gov/earthquakes/eventpage/hv70265061",
* "detail":"https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/hv70265061.geojson",
* "type":"earthquake"
* },
* "geometry":{
* "type":"Point",
* "coordinates":[
* -155.2333374,
* 19.4148331,
* -1.07
* ]
* },
* "id":"hv70265061"
* },
* {
* "type":"Feature",
* "properties":{
* "place":"5km SSW of Volcano, Hawaii",
* "time":1528974963260,
* "updated":1528975327080,
* "url":"https://earthquake.usgs.gov/earthquakes/eventpage/hv70265026",
* "detail":"https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/hv70265026.geojson",
* "type":"earthquake"
* },
* "geometry":{
* "type":"Polygon",
* "coordinates":[
* [
* [
* 30,
* 10
* ],
* [
* 40,
* 40
* ],
* [
* 20,
* 40
* ],
* [
* 10,
* 20
* ],
* [
* 30,
* 10
* ]
* ]
* ]
* },
* "id":"hv70265026"
* }
* ]
* }
* </pre>
* with ITERATOR <tt>iter:GeoJSONFeatures(?source) AS ?earthquake</tt> return (in each iteration):<br>
* <pre>
* ?earthquake => { "type":"Feature", "properties":{ "place":"5km SSW of Volcano, Hawaii", "time":1528974963260, "updated":1528975327080, "url":"https://earthquake.usgs.gov/earthquakes/eventpage/hv70265026", "detail":"https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/hv70265026.geojson", "type":"earthquake" }, "geometry":{ "type":"Polygon", "coordinates":[ [ [ 30, 10 ], [ 40, 40 ], [ 20, 40 ], [ 10, 20 ], [ 30, 10 ] ] ] }, "id":"hv70265026" }
* ?earchquake => { "type":"Feature", "properties":{ "place":"1km SSE of Volcano, Hawaii", "time":1528975443520, "updated":1528975662950, "url":"https://earthquake.usgs.gov/earthquakes/eventpage/hv70265061", "detail":"https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/hv70265061.geojson", "type":"earthquake" }, "geometry":{ "type":"Point", "coordinates":[ -155.2333374, 19.4148331, -1.07 ] }, "id":"hv70265061" }
* </pre>
*
* @author El Mehdi Khalfi <el-mehdi.khalfi at emse.fr>
* @since 2018-09-04
*/
public class ITER_GeoJSONFeatures extends IteratorFunctionBase1 {
/**
* The logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(ITER_GeoJSONFeatures.class);
/**
* The SPARQL function URI.
*/
public static final String URI = SPARQLGenerate.ITER + "GeoJSONFeatures";
private static final String datatypeUri = "http://www.iana.org/assignments/media-types/application/geo+json";
/**
* Registering the GeometryAdapterFactory.
* Gson TypeAdapterFactory is responsible fpr serializing/de-serializing all the {@link Geometry}, {@link Feature}
* and {@link FeatureCollection} instances.
*/
private static Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new GeometryAdapterFactory())
.create();
@Override
public List<List<NodeValue>> exec(NodeValue json) {
if (json.getDatatypeURI() != null
&& !json.getDatatypeURI().equals(datatypeUri)
&& !json.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
LOG.debug("The URI of NodeValue1 MUST be"
+ " <" + datatypeUri + "> or"
+ " <http://www.w3.org/2001/XMLSchema#string>. Got "
+ json.getDatatypeURI());
}
FeatureCollection featureCollection = gson.fromJson(json.asString(), FeatureCollection.class);
List<NodeValue> nodeValues = new ArrayList<>();
for (Feature feature : featureCollection.features()) {
String featureJsonString = gson.toJson(feature);
Node node = NodeFactory.createLiteral(featureJsonString, XSDDatatype.XSDstring);
NodeValue nodeValue = new NodeValueNode(node);
nodeValues.add(nodeValue);
}
return new ArrayList<>(Collections.singletonList(nodeValues));
}
}
| 42.0625 | 454 | 0.58044 |
034fb2f36a9100e00057bf0028201090780c93d4 | 2,572 | package de.gerrygames.the5zig.clientviaversion.viaversion;
import us.myles.ViaVersion.api.ViaVersionConfig;
import java.util.Collections;
import java.util.List;
public class CustomViaConfig implements ViaVersionConfig {
@Override
public boolean isCheckForUpdates() {
return false;
}
@Override
public boolean isPreventCollision() {
return false;
}
@Override
public boolean isNewEffectIndicator() {
return true;
}
@Override
public boolean isShowNewDeathMessages() {
return false;
}
@Override
public boolean isSuppressMetadataErrors() {
return true;
}
@Override
public boolean isShieldBlocking() {return false;}
@Override
public boolean isHologramPatch() {
return false;
}
@Override
public boolean isPistonAnimationPatch() {
return false;
}
@Override
public boolean isBossbarPatch() {
return true;
}
@Override
public boolean isBossbarAntiflicker() {
return false;
}
@Override
public boolean isUnknownEntitiesSuppressed() {
return true;
}
@Override
public double getHologramYOffset() {
return 0;
}
@Override
public boolean isAutoTeam() {return false;}
@Override
public boolean isBlockBreakPatch() {
return false;
}
@Override
public int getMaxPPS() {
return -1;
}
@Override
public String getMaxPPSKickMessage() {
return null;
}
@Override
public int getTrackingPeriod() {
return -1;
}
@Override
public int getWarningPPS() {
return -1;
}
@Override
public int getMaxWarnings() {
return -1;
}
@Override
public String getMaxWarningsKickMessage() {
return null;
}
@Override
public boolean isAntiXRay() {
return false;
}
@Override
public boolean isSendSupportedVersions() {
return false;
}
@Override
public boolean isStimulatePlayerTick() {
return true;
}
@Override
public boolean isItemCache() {
return false;
}
@Override
public boolean isNMSPlayerTicking() {
return false;
}
@Override
public boolean isReplacePistons() {
return false;
}
@Override
public int getPistonReplacementId() {
return -1;
}
@Override
public boolean isForceJsonTransform() {
return true;
}
@Override
public boolean is1_12NBTArrayFix() {
return true;
}
@Override
public boolean is1_13TeamColourFix() {
return true;
}
@Override
public boolean is1_12QuickMoveActionFix() {
return true;
}
@Override
public List<Integer> getBlockedProtocols() {
return Collections.emptyList();
}
@Override
public String getBlockedDisconnectMsg() {
return null;
}
@Override
public String getReloadDisconnectMsg() {
return null;
}
}
| 14.697143 | 58 | 0.722006 |
906dc40c9e569d723c2d90d602000e808e4180dd | 500 | package com.tyrfing.games.id17.networking;
import com.tyrfing.games.id17.intrigue.actions.Maraude;
import com.tyrlib2.networking.Connection;
public class MaraudingArmy extends NetworkMessage {
/**
*
*/
private static final long serialVersionUID = 3376894262954246781L;
public final short armyID;
public MaraudingArmy(short armyID) {
this.armyID = armyID;
}
@Override
public void process(Connection c) {
Maraude.createMaraudeSubFaction(armyID);
}
}
| 20 | 68 | 0.724 |
a0ba50c3847c18e666dafc62b361428d826c6bb0 | 1,529 | package com.wangzhe.ui;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import org.apache.log4j.Logger;
/**
*
* @author ocq
*/
public class SettingTabpaneController_1 implements Initializable {
private Logger log = Logger.getLogger(SettingTabpaneController.class.getName());
@FXML
public TabPane tp_SettingPane;
@FXML
private Tab tab_changeIp;//换ip
@FXML
private Tab tab_system;//系统设置
@FXML
private Tab tab_other;//其他
/**
* Initializes the controller class.
*
* @param url 描述
* @param rb 描述
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
tp_SettingPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
@Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
switch (newValue.getText()) {
case "换IP设置":
// tab_changeIp.setContent(Util.getParent("SettingPanel.fxml"));
break;
case "系统设置":
break;
case "其他设置":
break;
}
}
});
tp_SettingPane.getSelectionModel().select(0);
}
}
| 25.483333 | 105 | 0.608241 |
3ab50ef0fbc282773cfb2ef3574b14684e464429 | 1,165 | package org.kanishka.onclinicwebbackend.model;
import java.util.Arrays;
import java.util.List;
public class Demographics {
private String race;
private String religion;
private List<String> languages= Arrays.asList("");;
private String occupation;
public Demographics() {
}
public Demographics(String race, String religion, List<String> languages, String occupation) {
this.race = race;
this.religion = religion;
this.languages = languages;
this.occupation = occupation;
}
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
public String getReligion() {
return religion;
}
public void setReligion(String religion) {
this.religion = religion;
}
public List<String> getLanguages() {
return languages;
}
public void setLanguages(List<String> languages) {
this.languages = languages;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
}
| 21.574074 | 98 | 0.638627 |
3af206ac4560878f0c23f1694804f5fa7f739410 | 863 | package com.workflowfm.composer.processes;
import com.workflowfm.composer.prover.Prover;
import com.workflowfm.composer.utils.validate.ValidationException;
import com.workflowfm.composer.utils.validate.Validator;
public class ProcessPortValidator implements Validator<ProcessPort> {
private Validator<String> channelValidator;
private Validator<CllTerm> termValidator;
public ProcessPortValidator(Prover prover) {
this(prover.getChannelValidator(),new CllTermValidator(prover));
}
public ProcessPortValidator(Validator<String> channelValidator, Validator<CllTerm> termValidator) {
this.channelValidator = channelValidator;
this.termValidator = termValidator;
}
@Override
public void validate(ProcessPort field) throws ValidationException {
channelValidator.validate(field.getChannel());
termValidator.validate(field.getCllTerm());
}
}
| 30.821429 | 100 | 0.816918 |
47aaea4b9a24849a9bb5941298ba9e8c602b2fe9 | 1,090 | package com.obsidiandynamics.meteor;
import java.io.*;
import java.util.*;
import com.hazelcast.core.*;
import com.obsidiandynamics.func.*;
public final class HeapRingbufferStore implements RingbufferStore<Object> {
public static final class Factory implements RingbufferStoreFactory<Object>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public HeapRingbufferStore newRingbufferStore(String name, Properties properties) {
return new HeapRingbufferStore();
}
}
private final List<byte[]> stored = new ArrayList<>();
private HeapRingbufferStore() {}
@Override
public void store(long sequence, Object data) {
stored.add(Classes.cast(data));
}
@Override
public void storeAll(long firstItemSequence, Object[] items) {
long sequence = firstItemSequence;
for (Object item : items) {
store(sequence++, item);
}
}
@Override
public byte[] load(long sequence) {
return stored.get((int) sequence);
}
@Override
public long getLargestSequence() {
return stored.size() - 1;
}
}
| 23.695652 | 93 | 0.707339 |
48f0413561774532598334161139f36eb2be93ed | 8,287 | /* (C) Copyright 2009-2013 CNRS (Centre National de la Recherche Scientifique).
Licensed to the CNRS under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The CNRS 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.
*/
/* Contributors:
Luc Hogie (CNRS, I3S laboratory, University of Nice-Sophia Antipolis)
*/
package xycharter;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.image.ImageObserver;
import xycharter.Dimension.Orientation;
/**
* <p>
* A space is the abstract thing that defines the dimension X and Y. This models
* the mathematical concept of space.
* </p>
*
* <p>
* A space is made of:
* <ul>
* <li>2 dimensions (X and Y),
* <li>an origin point with coordinates (0, 0),
* <li>a scale that calculates the position on a Java Graphics2D of a logic
* coordinate.
* </ul>
* </p>
*
* <p>
* The space features also a legend that will be drawn on top of the graphics
* representation.
* </p>
*
* @author Luc Hogie.
*/
public class Space extends GraphicalElement {
private Legend legend = new Legend("Ultimate Plotter");
private Dimension xDimension;
private Dimension yDimension;
private Point2D originPoint = new Point2D.Double(0, 0);
private Graphics2D figureGraphics;
/*
* the imageObserver is the object that will render the image on its pane. it
* can be a SwingPlotter
*/
private ImageObserver imageObserver;
private Color backgroundColor = Color.white;
public Space() {
Dimension xDimension = new Dimension(Orientation.X);
setXDimension(xDimension);
Dimension yDimension = new Dimension(Orientation.Y);
setYDimension(yDimension);
legend.setFont(new Font(null, Font.PLAIN, 20));
getXDimension().getLowerBoundAxis().setVisible(false);
getXDimension().getUpperBoundAxis().setVisible(false);
getYDimension().getLowerBoundAxis().setVisible(false);
getYDimension().getUpperBoundAxis().setVisible(false);
}
/**
* Sets the X dimension of the space.
*
* @param xDimension
*/
public void setXDimension(Dimension xDimension) {
if (xDimension == null)
throw new IllegalArgumentException("X dimension cannot be set to null");
this.xDimension = xDimension;
xDimension.setParent(this);
}
/**
* Gets the X dimension of the space.
*
* @return Dimension
*/
public Dimension getXDimension() {
return xDimension;
}
/**
* Sets the Y dimension of the space.
*
* @param yDimension
*/
public void setYDimension(Dimension yDimension) {
if (yDimension == null)
throw new IllegalArgumentException("Y dimension cannot be set to null");
this.yDimension = yDimension;
yDimension.setParent(this);
}
/**
* Gets the X dimension of the space.
*
* @return Dimension
*/
public Dimension getYDimension() {
return yDimension;
}
/**
* Gets the origin point (the point with (0, 0) coordinates) of the space.
* Obviously, the real position (on the Graphics2D) of this point is not (0, 0).
*
* @return Point2D
*/
public Point2D getOriginPoint() {
return originPoint;
}
/**
* Sets the range of the space. This is a facility method: this can be done
* directly manipulating the dimensions of the space.
*
* Warning! This is a convenience method. The Dimension, Graduation and AxisLine
* classes allow you to have a better control.
*
* @param xmin
* @param xmax
* @param xstep
* @param ymin
* @param ymax
* @param ystep
*/
public void setRange(double xmin, double xmax, double ymin, double ymax) {
xDimension.setMin(xmin, true);
xDimension.setMax(xmax, true);
yDimension.setMin(ymin, true);
yDimension.setMax(ymax, true);
}
/**
* Sets the visibility of the grid.
*
* Warning! This is a facade method. The grid class feature many methods that
* allow a better control.
*
* @param gridTracing
*/
public void setGridVisible(boolean gridTracing) {
getXDimension().getGrid().setVisible(gridTracing);
getYDimension().getGrid().setVisible(gridTracing);
}
public void setArrowsVisible(boolean b) {
getXDimension().getLowerBoundAxis().getLine().getArrow().setVisible(b);
getXDimension().getOriginAxis().getLine().getArrow().setVisible(b);
getXDimension().getUpperBoundAxis().getLine().getArrow().setVisible(b);
getYDimension().getLowerBoundAxis().getLine().getArrow().setVisible(b);
getYDimension().getOriginAxis().getLine().getArrow().setVisible(b);
getYDimension().getUpperBoundAxis().getLine().getArrow().setVisible(b);
}
public enum MODE {
MATHS, PHYSICS
}
public void setMode(MODE mode) {
getXDimension().getLegend().setFont(new Font(null, Font.PLAIN, 12));
getYDimension().getLegend().setFont(new Font(null, Font.PLAIN, 12));
if (mode == MODE.MATHS) {
setBackgroundColor(Color.white);
setColor(Color.black);
getXDimension().getLowerBoundAxis().setVisible(false);
getXDimension().getOriginAxis().setVisible(true);
getXDimension().getUpperBoundAxis().setVisible(false);
getYDimension().getLowerBoundAxis().setVisible(false);
getYDimension().getOriginAxis().setVisible(true);
getYDimension().getUpperBoundAxis().setVisible(false);
} else if (mode == MODE.PHYSICS) {
setBackgroundColor(Color.black);
setColor(Color.white);
getXDimension().getLowerBoundAxis().setVisible(true);
getXDimension().getOriginAxis().setVisible(false);
getXDimension().getUpperBoundAxis().setVisible(true);
getYDimension().getLowerBoundAxis().setVisible(true);
getYDimension().getOriginAxis().setVisible(false);
getYDimension().getUpperBoundAxis().setVisible(true);
getXDimension().getLowerBoundAxis().getLine().getArrow().setVisible(false);
getXDimension().getUpperBoundAxis().getLine().getArrow().setVisible(false);
getYDimension().getLowerBoundAxis().getLine().getArrow().setVisible(false);
getYDimension().getUpperBoundAxis().getLine().getArrow().setVisible(false);
}
}
public void draw(Graphics2D spaceGraphics, Graphics2D figureGraphics) {
if (isVisible()) {
// the first thing to do is to initialize the graduations and draw
// the grids
xDimension.getGrid().draw(figureGraphics);
yDimension.getGrid().draw(figureGraphics);
// then the rest can be drawn
xDimension.draw(spaceGraphics, figureGraphics);
yDimension.draw(spaceGraphics, figureGraphics);
}
}
/**
* Returns the imageObserver.
*
* @return ImageObserver
*/
public ImageObserver getImageObserver() {
return imageObserver;
}
/**
* Sets the imageObserver.
*
* @param imageObserver The imageObserver to set
*/
public void setImageObserver(ImageObserver imageObserver) {
this.imageObserver = imageObserver;
}
public Legend getLegend() {
return legend;
}
public void setLegend(Legend newLegend) {
if (newLegend == null)
throw new IllegalArgumentException("the legend cannot be set to null");
this.legend = newLegend;
legend.setParent(this);
}
/**
* Returns the backgroundColor.
*
* @return Color
*/
public Color getBackgroundColor() {
return backgroundColor;
}
/**
* Sets the backgroundColor.
*
* @param backgroundColor The backgroundColor to set
*/
public void setBackgroundColor(Color backgroundColor) {
if (backgroundColor == null)
throw new IllegalArgumentException("backgroundColor cannot be set to null");
this.backgroundColor = backgroundColor;
}
public String toString() {
return "Space";
}
public Graphics2D getFigureGraphics() {
return figureGraphics;
}
public void setFigureGraphics(Graphics2D graphics2D) {
figureGraphics = graphics2D;
}
public void setAutoBounds(boolean b) {
getXDimension().setAutoBounds(b);
getYDimension().setAutoBounds(b);
}
} | 26.993485 | 81 | 0.723543 |
8a3e1c0d504d53765e58d6ffc5c6d267944357a0 | 3,502 | package gov.va.med.lom.avs.client.model;
import java.util.List;
import java.io.Serializable;
public class AvsJson implements Serializable {
private String content;
private String instructions;
private String fontClass;
private String language;
private String labDateRange;
private String sections;
private boolean printAllServiceDescriptions;
private String selectedServiceDescriptions;
private String charts;
private boolean locked;
private boolean userIsProvider;
private String lastRefreshed;
private boolean contentEdited;
private List<MedicationJson> remoteVaMeds;
private List<MedicationJson> remoteNonVaMeds;
private String diagnosisCodes;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getFontClass() {
return fontClass;
}
public void setFontClass(String fontClass) {
this.fontClass = fontClass;
}
public String getLabDateRange() {
return labDateRange;
}
public void setLabDateRange(String labDateRange) {
this.labDateRange = labDateRange;
}
public String getSections() {
return sections;
}
public void setSections(String sections) {
this.sections = sections;
}
public boolean getPrintAllServiceDescriptions() {
return printAllServiceDescriptions;
}
public void setPrintAllServiceDescriptions(boolean printAllServiceDescriptions) {
this.printAllServiceDescriptions = printAllServiceDescriptions;
}
public String getCharts() {
return charts;
}
public void setCharts(String charts) {
this.charts = charts;
}
public boolean getLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public String getLastRefreshed() {
return lastRefreshed;
}
public void setLastRefreshed(String lastRefreshed) {
this.lastRefreshed = lastRefreshed;
}
public boolean getUserIsProvider() {
return userIsProvider;
}
public void setUserIsProvider(boolean userIsProvider) {
this.userIsProvider = userIsProvider;
}
public boolean isContentEdited() {
return contentEdited;
}
public void setContentEdited(boolean contentEdited) {
this.contentEdited = contentEdited;
}
public String getSelectedServiceDescriptions() {
return selectedServiceDescriptions;
}
public void setSelectedServiceDescriptions(String selectedServiceDescriptions) {
this.selectedServiceDescriptions = selectedServiceDescriptions;
}
public List<MedicationJson> getRemoteVaMeds() {
return remoteVaMeds;
}
public void setRemoteVaMeds(List<MedicationJson> remoteVaMeds) {
this.remoteVaMeds = remoteVaMeds;
}
public List<MedicationJson> getRemoteNonVaMeds() {
return remoteNonVaMeds;
}
public void setRemoteNonVaMeds(List<MedicationJson> remoteNonVaMeds) {
this.remoteNonVaMeds = remoteNonVaMeds;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getDiagnosisCodes() {
return diagnosisCodes;
}
public void setDiagnosisCodes(String diagnosisCodes) {
this.diagnosisCodes = diagnosisCodes;
}
}
| 28.471545 | 84 | 0.722444 |
d8bde18ee8abf05f91c1eb16e92adc6b709125cb | 23,877 | package com.github.aloomaio.androidsdk.aloomametrics;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import com.github.aloomaio.androidsdk.util.Base64Coder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Manage communication of events with the internal database and the Mixpanel servers.
*
* <p>This class straddles the thread boundary between user threads and
* a logical Mixpanel thread.
*/
/* package */ class AnalyticsMessages {
public void forceSSL(boolean mForceSSL) {
mSchema = mForceSSL? "https" : "http";
}
/**
* Do not call directly. You should call AnalyticsMessages.getInstance()
*/
/* package */ AnalyticsMessages(final Context context) {
this(context, null, false);
}
/**
* Do not call directly. You should call AnalyticsMessages.getInstance()
*/
/* package */ AnalyticsMessages(final Context context, String aloomaHost, boolean forceSSL) {
mContext = context;
mAloomaHost = (null == aloomaHost) ? DEFAULT_ALOOMA_HOST : aloomaHost;
forceSSL(forceSSL);
mConfig = getConfig(context);
mWorker = new Worker();
}
public static AnalyticsMessages getInstance(final Context messageContext) {
return getInstance(messageContext, null, true);
}
public static AnalyticsMessages getInstance(final Context messageContext, String aloomaHost) {
return getInstance(messageContext, aloomaHost, true);
}
/**
* Returns an AnalyticsMessages instance with configurable forceSSL attribute
*/
public static AnalyticsMessages getInstance(final Context messageContext,
String aloomaHost,
boolean forceSSL) {
synchronized (sInstances) {
final Context appContext = messageContext.getApplicationContext();
AnalyticsMessages ret;
if (! sInstances.containsKey(appContext)) {
ret = new AnalyticsMessages(appContext, aloomaHost, forceSSL);
sInstances.put(appContext, ret);
}
else {
ret = sInstances.get(appContext);
}
return ret;
}
}
public void eventsMessage(final EventDescription eventDescription) {
final Message m = Message.obtain();
m.what = ENQUEUE_EVENTS;
m.obj = eventDescription;
mWorker.runMessage(m);
}
// Must be thread safe.
public void peopleMessage(final JSONObject peopleJson) {
final Message m = Message.obtain();
m.what = ENQUEUE_PEOPLE;
m.obj = peopleJson;
mWorker.runMessage(m);
}
public void postToServer() {
final Message m = Message.obtain();
m.what = FLUSH_QUEUE;
mWorker.runMessage(m);
}
public void installDecideCheck(final DecideMessages check) {
final Message m = Message.obtain();
m.what = INSTALL_DECIDE_CHECK;
m.obj = check;
mWorker.runMessage(m);
}
public void registerForGCM(final String senderID) {
final Message m = Message.obtain();
m.what = REGISTER_FOR_GCM;
m.obj = senderID;
mWorker.runMessage(m);
}
public void hardKill() {
final Message m = Message.obtain();
m.what = KILL_WORKER;
mWorker.runMessage(m);
}
/////////////////////////////////////////////////////////
// For testing, to allow for Mocking.
/* package */ boolean isDead() {
return mWorker.isDead();
}
protected ADbAdapter makeDbAdapter(Context context) {
return new ADbAdapter(context);
}
protected AConfig getConfig(Context context) {
return AConfig.getInstance(context);
}
protected ServerMessage getPoster() {
return new ServerMessage();
}
////////////////////////////////////////////////////
static class EventDescription {
public EventDescription(String eventName, JSONObject properties, String token) {
this.eventName = eventName;
this.properties = properties;
this.token = token;
}
public String getEventName() {
return eventName;
}
public JSONObject getProperties() {
return properties;
}
public String getToken() {
return token;
}
private final String eventName;
private final JSONObject properties;
private final String token;
}
// Sends a message if and only if we are running with alooma Message log enabled.
// Will be called from the alooma thread.
private void logAboutMessageToAlooma(String message) {
if (AConfig.DEBUG) {
Log.v(LOGTAG, message + " (Thread " + Thread.currentThread().getId() + ")");
}
}
private void logAboutMessageToAlooma(String message, Throwable e) {
if (AConfig.DEBUG) {
Log.v(LOGTAG, message + " (Thread " + Thread.currentThread().getId() + ")", e);
}
}
// Worker will manage the (at most single) IO thread associated with
// this AnalyticsMessages instance.
// XXX: Worker class is unnecessary, should be just a subclass of HandlerThread
private class Worker {
public Worker() {
mHandler = restartWorkerThread();
}
public boolean isDead() {
synchronized(mHandlerLock) {
return mHandler == null;
}
}
public void runMessage(Message msg) {
synchronized(mHandlerLock) {
if (mHandler == null) {
// We died under suspicious circumstances. Don't try to send any more events.
logAboutMessageToAlooma("Dead alooma worker dropping a message: " + msg.what);
} else {
mHandler.sendMessage(msg);
}
}
}
// NOTE that the returned worker will run FOREVER, unless you send a hard kill
// (which you really shouldn't)
private Handler restartWorkerThread() {
final HandlerThread thread = new HandlerThread("com.alooma.android.AnalyticsWorker", Thread.MIN_PRIORITY);
thread.start();
final Handler ret = new AnalyticsMessageHandler(thread.getLooper());
return ret;
}
private class AnalyticsMessageHandler extends Handler {
public AnalyticsMessageHandler(Looper looper) {
super(looper);
mDbAdapter = null;
mDecideChecker = new DecideChecker(mContext, mConfig);
mDisableFallback = mConfig.getDisableFallback();
mFlushInterval = mConfig.getFlushInterval();
mSystemInformation = new SystemInformation(mContext);
}
@Override
public void handleMessage(Message msg) {
if (mDbAdapter == null) {
mDbAdapter = makeDbAdapter(mContext);
mDbAdapter.cleanupEvents(System.currentTimeMillis() - mConfig.getDataExpiration(), ADbAdapter.Table.EVENTS);
mDbAdapter.cleanupEvents(System.currentTimeMillis() - mConfig.getDataExpiration(), ADbAdapter.Table.PEOPLE);
}
try {
int queueDepth = -1;
if (msg.what == ENQUEUE_PEOPLE) {
final JSONObject message = (JSONObject) msg.obj;
logAboutMessageToAlooma("Queuing people record for sending later");
logAboutMessageToAlooma(" " + message.toString());
queueDepth = mDbAdapter.addJSON(message, ADbAdapter.Table.PEOPLE);
}
else if (msg.what == ENQUEUE_EVENTS) {
final EventDescription eventDescription = (EventDescription) msg.obj;
try {
final JSONObject message = prepareEventObject(eventDescription);
logAboutMessageToAlooma("Queuing event for sending later");
logAboutMessageToAlooma(" " + message.toString());
queueDepth = mDbAdapter.addJSON(message, ADbAdapter.Table.EVENTS);
} catch (final JSONException e) {
Log.e(LOGTAG, "Exception tracking event " + eventDescription.getEventName(), e);
}
}
else if (msg.what == FLUSH_QUEUE) {
logAboutMessageToAlooma("Flushing queue due to scheduled or forced flush");
updateFlushFrequency();
sendAllData(mDbAdapter);
mDecideChecker.runDecideChecks(getPoster());
}
else if (msg.what == INSTALL_DECIDE_CHECK) {
logAboutMessageToAlooma("Installing a check for surveys and in app notifications");
final DecideMessages check = (DecideMessages) msg.obj;
mDecideChecker.addDecideCheck(check);
mDecideChecker.runDecideChecks(getPoster());
}
else if (msg.what == KILL_WORKER) {
Log.w(LOGTAG, "Worker received a hard kill. Dumping all events and force-killing. Thread id " + Thread.currentThread().getId());
synchronized(mHandlerLock) {
mDbAdapter.deleteDB();
mHandler = null;
Looper.myLooper().quit();
}
} else {
Log.e(LOGTAG, "Unexpected message received by Alooma worker: " + msg);
}
///////////////////////////
if (queueDepth >= mConfig.getBulkUploadLimit()) {
logAboutMessageToAlooma("Flushing queue due to bulk upload limit");
updateFlushFrequency();
sendAllData(mDbAdapter);
mDecideChecker.runDecideChecks(getPoster());
} else if (queueDepth > 0 && !hasMessages(FLUSH_QUEUE)) {
// The !hasMessages(FLUSH_QUEUE) check is a courtesy for the common case
// of delayed flushes already enqueued from inside of this thread.
// Callers outside of this thread can still send
// a flush right here, so we may end up with two flushes
// in our queue, but we're OK with that.
logAboutMessageToAlooma("Queue depth " + queueDepth + " - Adding flush in " + mFlushInterval);
if (mFlushInterval >= 0) {
sendEmptyMessageDelayed(FLUSH_QUEUE, mFlushInterval);
}
}
} catch (final RuntimeException e) {
Log.e(LOGTAG, "Worker threw an unhandled exception", e);
synchronized (mHandlerLock) {
mHandler = null;
try {
Looper.myLooper().quit();
Log.e(LOGTAG, "Alooma will not process any more analytics messages", e);
} catch (final Exception tooLate) {
Log.e(LOGTAG, "Could not halt looper", tooLate);
}
}
}
}// handleMessage
private void sendAllData(ADbAdapter dbAdapter) {
final ServerMessage poster = getPoster();
if (! poster.isOnline(mContext)) {
logAboutMessageToAlooma("Not flushing data to alooma because the device is not connected to the internet.");
return;
}
logAboutMessageToAlooma("Sending records to alooma");
sendData(dbAdapter, ADbAdapter.Table.EVENTS, new String[]{ mSchema + "://" + mAloomaHost + "/track?ip=1" });
}
private void sendData(ADbAdapter dbAdapter, ADbAdapter.Table table, String[] urls) {
final ServerMessage poster = getPoster();
final String[] eventsData = dbAdapter.generateDataString(table);
if (eventsData != null) {
final String lastId = eventsData[0];
final String rawMessage = eventsData[1];
final String encodedData = Base64Coder.encodeString(rawMessage);
final List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("data", encodedData));
if (AConfig.DEBUG) {
params.add(new BasicNameValuePair("verbose", "1"));
}
boolean deleteEvents = true;
byte[] response;
for (String url : urls) {
try {
response = poster.performRequest(url, params);
deleteEvents = true; // Delete events on any successful post, regardless of 1 or 0 response
if (null == response) {
logAboutMessageToAlooma("Response was null, unexpected failure posting to " + url + ".");
} else {
String parsedResponse;
try {
parsedResponse = new String(response, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF not supported on this platform?", e);
}
logAboutMessageToAlooma("Successfully posted to " + url + ": \n" + rawMessage);
logAboutMessageToAlooma("Response was " + parsedResponse);
}
break;
} catch (final OutOfMemoryError e) {
Log.e(LOGTAG, "Out of memory when posting to " + url + ".", e);
break;
} catch (final MalformedURLException e) {
Log.e(LOGTAG, "Cannot interpret " + url + " as a URL.", e);
break;
} catch (final IOException e) {
logAboutMessageToAlooma("Cannot post message to " + url + ".", e);
deleteEvents = false;
}
}
if (deleteEvents) {
logAboutMessageToAlooma("Not retrying this batch of events, deleting them from DB.");
dbAdapter.cleanupEvents(lastId, table);
} else {
logAboutMessageToAlooma("Retrying this batch of events.");
if (!hasMessages(FLUSH_QUEUE)) {
sendEmptyMessageDelayed(FLUSH_QUEUE, mFlushInterval);
}
}
}
}
private JSONObject getDefaultEventProperties()
throws JSONException {
final JSONObject ret = new JSONObject();
ret.put("alooma_sdk", "android");
ret.put("$lib_version", AConfig.VERSION);
// For querying together with data from other libraries
ret.put("$os", "Android");
ret.put("$os_version", Build.VERSION.RELEASE == null ? "UNKNOWN" : Build.VERSION.RELEASE);
ret.put("$manufacturer", Build.MANUFACTURER == null ? "UNKNOWN" : Build.MANUFACTURER);
ret.put("$brand", Build.BRAND == null ? "UNKNOWN" : Build.BRAND);
ret.put("$model", Build.MODEL == null ? "UNKNOWN" : Build.MODEL);
try {
try {
final int servicesAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
switch (servicesAvailable) {
case ConnectionResult.SUCCESS:
ret.put("$google_play_services", "available");
break;
case ConnectionResult.SERVICE_MISSING:
ret.put("$google_play_services", "missing");
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
ret.put("$google_play_services", "out of date");
break;
case ConnectionResult.SERVICE_DISABLED:
ret.put("$google_play_services", "disabled");
break;
case ConnectionResult.SERVICE_INVALID:
ret.put("$google_play_services", "invalid");
break;
}
} catch (RuntimeException e) {
// Turns out even checking for the service will cause explosions
// unless we've set up meta-data
ret.put("$google_play_services", "not configured");
}
} catch (NoClassDefFoundError e) {
ret.put("$google_play_services", "not included");
}
final DisplayMetrics displayMetrics = mSystemInformation.getDisplayMetrics();
ret.put("$screen_dpi", displayMetrics.densityDpi);
ret.put("$screen_height", displayMetrics.heightPixels);
ret.put("$screen_width", displayMetrics.widthPixels);
final String applicationVersionName = mSystemInformation.getAppVersionName();
if (null != applicationVersionName)
ret.put("$app_version", applicationVersionName);
final Boolean hasNFC = mSystemInformation.hasNFC();
if (null != hasNFC)
ret.put("$has_nfc", hasNFC.booleanValue());
final Boolean hasTelephony = mSystemInformation.hasTelephony();
if (null != hasTelephony)
ret.put("$has_telephone", hasTelephony.booleanValue());
final String carrier = mSystemInformation.getCurrentNetworkOperator();
if (null != carrier)
ret.put("$carrier", carrier);
final Boolean isWifi = mSystemInformation.isWifiConnected();
if (null != isWifi)
ret.put("$wifi", isWifi.booleanValue());
final Boolean isBluetoothEnabled = mSystemInformation.isBluetoothEnabled();
if (isBluetoothEnabled != null)
ret.put("$bluetooth_enabled", isBluetoothEnabled);
final String bluetoothVersion = mSystemInformation.getBluetoothVersion();
if (bluetoothVersion != null)
ret.put("$bluetooth_version", bluetoothVersion);
return ret;
}
private JSONObject prepareEventObject(EventDescription eventDescription) throws JSONException {
final JSONObject eventObj = new JSONObject();
final JSONObject eventProperties = eventDescription.getProperties();
final JSONObject sendProperties = getDefaultEventProperties();
if (eventProperties != null) {
for (final Iterator<?> iter = eventProperties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
sendProperties.put(key, eventProperties.get(key));
}
}
JSONObject props;
try {
props = eventObj.getJSONObject("properties");
} catch (JSONException ex) {
props = new JSONObject();
}
props.put("token", eventDescription.getToken());
for (final Iterator<?> iter = sendProperties.keys(); iter.hasNext();) {
final String key = (String) iter.next();
eventObj.put(key, sendProperties.get(key));
}
eventObj.put("event", eventDescription.getEventName());
eventObj.put("properties", props);
return eventObj;
}
private ADbAdapter mDbAdapter;
private final DecideChecker mDecideChecker;
private final long mFlushInterval;
private final boolean mDisableFallback;
}// AnalyticsMessageHandler
private void updateFlushFrequency() {
final long now = System.currentTimeMillis();
final long newFlushCount = mFlushCount + 1;
if (mLastFlushTime > 0) {
final long flushInterval = now - mLastFlushTime;
final long totalFlushTime = flushInterval + (mAveFlushFrequency * mFlushCount);
mAveFlushFrequency = totalFlushTime / newFlushCount;
final long seconds = mAveFlushFrequency / 1000;
logAboutMessageToAlooma("Average send frequency approximately " + seconds + " seconds.");
}
mLastFlushTime = now;
mFlushCount = newFlushCount;
}
private final Object mHandlerLock = new Object();
private Handler mHandler;
private long mFlushCount = 0;
private long mAveFlushFrequency = 0;
private long mLastFlushTime = -1;
private SystemInformation mSystemInformation;
}
/////////////////////////////////////////////////////////
// Used across thread boundaries
private final Worker mWorker;
private final Context mContext;
private final AConfig mConfig;
private final String mAloomaHost;
private String mSchema;
// Messages for our thread
private static int ENQUEUE_PEOPLE = 0; // submit events and people data
private static int ENQUEUE_EVENTS = 1; // push given JSON message to people DB
private static int FLUSH_QUEUE = 2; // push given JSON message to events DB
private static int KILL_WORKER = 5; // Hard-kill the worker thread, discarding all events on the event queue. This is for testing, or disasters.
private static int INSTALL_DECIDE_CHECK = 12; // Run this DecideCheck at intervals until it isDestroyed()
private static int REGISTER_FOR_GCM = 13; // Register for GCM using Google Play Services
private static final String LOGTAG = "AloomaAPI.AnalyticsMessages";
private static final Map<Context, AnalyticsMessages> sInstances = new HashMap<Context, AnalyticsMessages>();
private final String DEFAULT_ALOOMA_HOST = "inputs.alooma.com";
}
| 42.790323 | 152 | 0.545713 |
930f280b862fe448cb9726cf13ad946446ab188f | 1,399 | package org.cloudfoundry.autoscaler.servicebroker.data.storeservice;
import java.util.List;
import org.cloudfoundry.autoscaler.servicebroker.data.entity.ApplicationInstance;
import org.cloudfoundry.autoscaler.servicebroker.data.entity.ServiceInstance;
public interface IDataStoreService {
public ServiceInstance createService(String serviceId, String serverUrl, String orgId, String spaceId);
public ApplicationInstance bindApplication(String appId, String serviceId, String bindingId);
public void unbindApplication(String bindingId);
public void deleteService(String serviceId);
//service url => multiple service instances
public List<String> getServiceInstanceIdByServerURL(String serverUrl);
// service url => the number of service instances
public int getWorkloadSummaryByServerURL(String serverUrl);
//service id => multiple bound app
public List<String> getBoundAppIdByServiceId(String serviceId);
//app id => it is possible to have more binding record per app. But in current implementation, we only allow one app binding one service instance
public List<ApplicationInstance> getBoundAppByAppId(String appId);
//service id => unique id for a service instance
public ServiceInstance getServiceInstanceByServiceId(String serviceId);
//binding id => unique id for a binding
public ApplicationInstance getBoundAppByBindingId(String bindingId);
}
| 35.871795 | 147 | 0.808435 |
1005b8c42949beb954ecef4c42c83f7ad60fb1b9 | 2,368 | package com.badlogic.androidgames.framework.math;
import android.util.FloatMath;
public class Vector2 {
public static float TO_RADIANS = (1 / 180.0f) * (float) Math.PI;
public static float TO_DEGREES = (1 / (float) Math.PI) * 180;
public float x, y;
public Vector2() {
}
public Vector2(float x, float y) {
this.x = x;
this.y = y;
}
public Vector2(Vector2 other) {
this.x = other.x;
this.y = other.y;
}
public Vector2 cpy() {
return new Vector2(x, y);
}
public Vector2 set(float x, float y) {
this.x = x;
this.y = y;
return this;
}
public Vector2 set(Vector2 other) {
this.x = other.x;
this.y = other.y;
return this;
}
public Vector2 add(float x, float y) {
this.x += x;
this.y += y;
return this;
}
public Vector2 add(Vector2 other) {
this.x += other.x;
this.y += other.y;
return this;
}
public Vector2 sub(float x, float y) {
this.x -= x;
this.y -= y;
return this;
}
public Vector2 sub(Vector2 other) {
this.x -= other.x;
this.y -= other.y;
return this;
}
public Vector2 mul(float scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
}
public float len() {
return FloatMath.sqrt(x * x + y * y);
}
public Vector2 nor() {
float len = len();
if (len != 0) {
this.x /= len;
this.y /= len;
}
return this;
}
public float angle() {
float angle = (float) Math.atan2(y, x) * TO_DEGREES;
if (angle < 0)
angle += 360;
return angle;
}
public Vector2 rotate(float angle) {
float rad = angle * TO_RADIANS;
float cos = FloatMath.cos(rad);
float sin = FloatMath.sin(rad);
float newX = this.x * cos - this.y * sin;
float newY = this.x * sin + this.y * cos;
this.x = newX;
this.y = newY;
return this;
}
public float dist(Vector2 other) {
float distX = this.x - other.x;
float distY = this.y - other.y;
return FloatMath.sqrt(distX * distX + distY * distY);
}
public float dist(float x, float y) {
float distX = this.x - x;
float distY = this.y - y;
return FloatMath.sqrt(distX * distX + distY * distY);
}
public float distSquared(Vector2 other) {
float distX = this.x - other.x;
float distY = this.y - other.y;
return distX*distX + distY*distY;
}
public float distSquared(float x, float y) {
float distX = this.x - x;
float distY = this.y - y;
return distX * distX + distY * distY;
}
}
| 18.645669 | 65 | 0.615287 |
55ca45eb8394d5ce020eaeec5fa9eae1ac9f5021 | 4,617 | package com.alibaba.dcm.internal;
import sun.net.InetAddressCachePolicy;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Util class to manipulate dns cache.
*
* @author Jerry Lee (oldratlee at gmail dot com)
* @since 1.6.0
*/
public class InetAddressCacheUtilCommons {
public static final long NEVER_EXPIRATION = Long.MAX_VALUE;
static InetAddress[] toInetAddressArray(String host, String[] ips) throws UnknownHostException {
InetAddress[] addresses = new InetAddress[ips.length];
for (int i = 0; i < addresses.length; i++) {
addresses[i] = InetAddress.getByAddress(host, IpParserUtil.ip2ByteArray(ips[i]));
}
return addresses;
}
/**
* Set JVM DNS cache policy
*
* @param cacheSeconds set default dns cache time. Special input case:
* <ul>
* <li> {@code -1} means never expired.(In effect, all negative value)</li>
* <li> {@code 0} never cached.</li>
* </ul>
* @see InetAddressCachePolicy
* @see InetAddressCachePolicy#cachePolicy
*/
public static void setDnsCachePolicy(int cacheSeconds)
throws NoSuchFieldException, IllegalAccessException {
setCachePolicy0(false, cacheSeconds);
}
public static int getDnsCachePolicy() {
return InetAddressCachePolicy.get();
}
/**
* Set JVM DNS negative cache policy
*
* @param negativeCacheSeconds set default dns cache time. Special input case:
* <ul>
* <li> {@code -1} means never expired.(In effect, all negative value)</li>
* <li> {@code 0} never cached.</li>
* </ul>
* @see InetAddressCachePolicy
* @see InetAddressCachePolicy#negativeCachePolicy
*/
public static void setDnsNegativeCachePolicy(int negativeCacheSeconds)
throws NoSuchFieldException, IllegalAccessException {
setCachePolicy0(true, negativeCacheSeconds);
}
public static int getDnsNegativeCachePolicy() {
return InetAddressCachePolicy.getNegative();
}
private static volatile Field setFiled$InetAddressCachePolicy = null;
private static volatile Field negativeSet$InetAddressCachePolicy = null;
@SuppressWarnings("JavaReflectionMemberAccess")
private static void setCachePolicy0(boolean isNegative, int seconds)
throws NoSuchFieldException, IllegalAccessException {
if (seconds < 0) {
seconds = -1;
}
final Class<?> clazz = InetAddressCachePolicy.class;
final Field cachePolicyFiled = clazz.getDeclaredField(
isNegative ? "negativeCachePolicy" : "cachePolicy");
cachePolicyFiled.setAccessible(true);
final Field setField;
if (isNegative) {
if (negativeSet$InetAddressCachePolicy == null) {
synchronized (InetAddressCacheUtilForJdk8Minus.class) {
if (negativeSet$InetAddressCachePolicy == null) {
try {
negativeSet$InetAddressCachePolicy = clazz.getDeclaredField("propertyNegativeSet");
} catch (NoSuchFieldException e) {
negativeSet$InetAddressCachePolicy = clazz.getDeclaredField("negativeSet");
}
negativeSet$InetAddressCachePolicy.setAccessible(true);
}
}
}
setField = negativeSet$InetAddressCachePolicy;
} else {
if (setFiled$InetAddressCachePolicy == null) {
synchronized (InetAddressCacheUtilForJdk8Minus.class) {
if (setFiled$InetAddressCachePolicy == null) {
try {
setFiled$InetAddressCachePolicy = clazz.getDeclaredField("propertySet");
} catch (NoSuchFieldException e) {
setFiled$InetAddressCachePolicy = clazz.getDeclaredField("set");
}
setFiled$InetAddressCachePolicy.setAccessible(true);
}
}
}
setField = setFiled$InetAddressCachePolicy;
}
synchronized (InetAddressCachePolicy.class) { // static synchronized method!
cachePolicyFiled.set(null, seconds);
setField.set(null, true);
}
}
}
| 38.798319 | 111 | 0.591943 |
3941473148509cef7b8356b181f04468b4e8d012 | 4,597 | package net.i2p.itoopie.gui;
import java.awt.BorderLayout;
import java.io.File;
import javax.security.cert.X509Certificate;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import net.i2p.itoopie.i18n.Transl;
import net.i2p.itoopie.security.CertificateHelper;
import net.i2p.itoopie.security.CertificateManager;
public class CertificateGUI {
/*
public static void main(String[] args){
System.out.println("Save new cert: " + saveNewCert(null,null));
System.out.println("Overwrite cert: " + overwriteCert(null,null));
}
*/
public static synchronized boolean saveNewCert(Main main, CertificateManager certificateManager, String hostname, X509Certificate cert){
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JButton bt = new JButton();
bt.setText("text");
frame.add(bt, BorderLayout.NORTH);
String title = Transl._t("New remote host detected");
String hostString = Transl._t("Would you like permanently trust the certificate from the remote host {0}?", hostname);
String certName = "N/A";
String certAlgo = "N/A";
String certSerial = "N/A";
String certThumb = "N/A";
if (cert != null){
certName = cert.getSubjectDN().getName();
String certString = cert.getPublicKey().toString();
certAlgo = certString.substring(0,certString.indexOf("\n"));
certSerial = String.valueOf(cert.getPublicKey().serialVersionUID);
certThumb = CertificateHelper.getThumbPrint(cert);
}
String certInfo = "<html>"+Transl._t("Certificate info") + "<br><br>" +
Transl._t("Name: ") + certName + "<br>" +
Transl._t("Algorithm: ") + certAlgo + "<br>" +
Transl._t("Serial: ") + certSerial + "<br>" +
Transl._t("SHA-1 ID-hash: ") + certThumb;
String textContent = certInfo + "<br><br>" + hostString;
int n = JOptionPane.showConfirmDialog(
frame,
textContent,
title,
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (n == JOptionPane.YES_OPTION){
certificateManager.forcePutServerCert(hostname, CertificateHelper.convert(cert));
updateUI(main);
return true;
} else {
return false;
}
}
public static boolean overwriteCert(Main main, CertificateManager certificateManager, String hostname, X509Certificate cert){
JFrame frame = new JFrame();
String title = Transl._t("Warning, new remote host detected");
String hostString = Transl._t("The certificate of {0} has changed!", hostname) + "<br>" +
Transl._t("Are you sure you want to permanently trust the new certificate from the remote host?");
String certName = "N/A";
String certAlgo = "N/A";
String certSerial = "N/A";
String certThumb = "N/A";
if (cert != null){
certName = cert.getSubjectDN().getName();
String certString = cert.getPublicKey().toString();
certAlgo = certString.substring(0,certString.indexOf("\n"));
certSerial = String.valueOf(cert.getPublicKey().serialVersionUID);
certThumb = CertificateHelper.getThumbPrint(cert);
}
String certInfo = "<html>"+Transl._t("Certificate info") + "<br><br>" +
Transl._t("Name: ") + certName + "<br>" +
Transl._t("Algorithm: ") + certAlgo + "<br>" +
Transl._t("Serial: ") + certSerial + "<br>" +
Transl._t("SHA-1 ID-hash: ") + certThumb;
String textContent = certInfo + "<br><br>" + hostString;
int n = JOptionPane.showConfirmDialog(
frame,
textContent,
title,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (n == JOptionPane.YES_OPTION){
n = JOptionPane.showConfirmDialog(
frame,
Transl._t("Are you sure that you trust the new certificate?"),
Transl._t("Is that your final answer?"),
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
if (n == JOptionPane.YES_OPTION){
certificateManager.forcePutServerCert(hostname, CertificateHelper.convert(cert));
updateUI(main);
return true; // Confirmation positive
} else {
return false; // Confirmation negative
}
} else {
return false; // No
}
}
/**
* Upon new cert accepted it is probable a good idea to show it by updating the GUI.
*/
private static void updateUI(final Main main) {
// Sleep before updating.
(new Thread(){
@Override
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
main.fireNewChange();
}
});
}
}).start();
}
}
| 31.486301 | 137 | 0.677616 |
085b41f3d473252bc8bf477af81b85cc133239d6 | 3,399 | package org.tuxdevelop.spring_data_demo.rest;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.tuxdevelop.spring_data_demo.jpa.domain.*;
import org.tuxdevelop.spring_data_demo.jpa.util.CommunicationFactory;
import org.tuxdevelop.spring_data_demo.jpa.util.ContactFactory;
import org.tuxdevelop.spring_data_demo.jpa.util.CustomerFactory;
import org.tuxdevelop.spring_data_demo.rest.repository.CommunicationRepository;
import org.tuxdevelop.spring_data_demo.rest.repository.ContactRepository;
import org.tuxdevelop.spring_data_demo.rest.repository.CustomerRepository;
import java.util.Collection;
import java.util.LinkedList;
@EnableAutoConfiguration
@EntityScan(value = "org.tuxdevelop.spring_data_demo.jpa.domain")
@ComponentScan(basePackages = "org.tuxdevelop.spring_data_demo.rest")
public class SpringDataRestApplication {
public static void main(final String[] args) {
SpringApplication.run(SpringDataRestApplication.class, args);
}
@Bean
public InitializingBean populateStaticDate(final CustomerRepository customerRepository, final ContactRepository
contactRepository, final CommunicationRepository communicationRepository) {
return new InitializingBean() {
@Override
public void afterPropertiesSet() throws Exception {
final Communication emailCommunication = CommunicationFactory.createEmailCommunication(
CommunicationClassifier.STANDARD);
communicationRepository.save(emailCommunication);
final Communication phoneCommunication = CommunicationFactory.createPhoneCommunication(
CommunicationClassifier.STANDARD);
communicationRepository.save(phoneCommunication);
final Contact contact = ContactFactory.createContact(ContactClassifier.STANDARD);
contactRepository.save(contact);
emailCommunication.setContact(contact);
phoneCommunication.setContact(contact);
communicationRepository.save(emailCommunication);
communicationRepository.save(phoneCommunication);
Collection<Communication> emailCommunications = new LinkedList<>();
Collection<Communication> phoneCommunications = new LinkedList<>();
emailCommunications.add(emailCommunication);
phoneCommunications.add(phoneCommunication);
contact.setEmailCommunications(emailCommunications);
contact.setPhoneCommunications(phoneCommunications);
contactRepository.save(contact);
final Customer customer = CustomerFactory.createCustomer();
customerRepository.save(customer);
contact.setCustomer(customer);
contactRepository.save(contact);
final Collection<Contact> contacts = new LinkedList<>();
contacts.add(contact);
customer.setContacts(contacts);
customerRepository.save(customer);
}
};
}
}
| 50.731343 | 115 | 0.724625 |
a6ed236ae485c6ccba01fd344d53b0d5925ddb2c | 7,477 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.TouchSensor;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
/*
This is TeleOpMode
-When this OpMode is run, the drivers can control the robot via controllers
-In it, we assign controls and designate functions
*/
@TeleOp(name="TeleOpMode", group="Iterative Opmode")
public class TeleOpMode extends OpMode implements Constants {
//This is where we declare the motors and hardware we use. We declare them here so we can use them later
private ElapsedTime runtime = new ElapsedTime(); //This is the time that has gone by so far in the match. We can use this to say: "Do this at this time in the match"
//Drivetrain Motors - These are the motors used for driving the robot
private DcMotor leftFrontDrive = null;
private DcMotor rightFrontDrive = null;
private DcMotor leftBackDrive = null;
private DcMotor rightBackDrive = null;
//Gamepiece Motors
private DcMotor stretch = null; //This is responsible for opening and closing the intake mechanism
private DcMotor elevator = null; //This controls the elevator up and down motion, yes
private DcMotor intakeA = null; //This is the left set of intake wheels
private DcMotor intakeB = null; //This is the right set of intake wheels
//Servos
private Servo elevatorTilt = null; //This is called a LINEAR ACTUATOR. It's essentially a motor that can only push and pull forward and backward. We use it to push the elevator/INTAKE mechanism up and down
private Servo clampA = null; //This is the left servo in the back of the bot. It's used for clamping onto the foundation
private Servo clampB = null; //This is the right servo in the back of the bot. It's used for clamping onto the foundation
//Sensors
private TouchSensor lowerLimit = null; //When it's true, the elevator has hit it. We programmed it to stop the elevator when it hits this so it doesn't go too low and break
@Override
public void init() {
//Initialization- Motors
leftFrontDrive = hardwareMap.get(DcMotor.class, "leftFrontDrive"); //The things in quotes are what we named it on the phone configuration
rightFrontDrive = hardwareMap.get(DcMotor.class, "rightFrontDrive");
leftBackDrive = hardwareMap.get(DcMotor.class, "leftBackDrive");
rightBackDrive = hardwareMap.get(DcMotor.class, "rightBackDrive");
stretch = hardwareMap.get(DcMotor.class, "stretch");
elevator = hardwareMap.get(DcMotor.class, "elevator");
intakeA = hardwareMap.get(DcMotor.class, "intakeA");
intakeB = hardwareMap.get(DcMotor.class, "intakeB");
//Initialization - Servos
elevatorTilt = hardwareMap.get(Servo.class , "elevatorTilt");
clampA = hardwareMap.get(Servo.class , "clampA");
clampB = hardwareMap.get(Servo.class , "clampB");
//Initialization - Sensors
lowerLimit = hardwareMap.get(TouchSensor.class, "lowerLimit");
leftFrontDrive.setDirection(DcMotor.Direction.FORWARD);
rightFrontDrive.setDirection(DcMotor.Direction.REVERSE);
leftBackDrive.setDirection(DcMotor.Direction.FORWARD);
rightBackDrive.setDirection(DcMotor.Direction.REVERSE);
// Tell the driver that initialization is complete.
telemetry.addData("Status", "Initialized");
telemetry.update();
}
@Override
public void init_loop() {
//public void raiseElevator (double power) {
// elevator.setPower(power);
//}
}
@Override
public void start() {
runtime.reset();
}
@Override
public void loop() { //Everything in this bracket loops in the TeleOp period
//Driving
double rightOutput;
double leftOutput;
double drive = gamepad1.left_stick_y * .9;
double turn = -gamepad1.right_stick_x * .5;
telemetry.addData("Time Elapsed", getRuntime() );
telemetry.update();
//Clamping Foundation
if (gamepad1.x) { //If the X button on gamepad 1 (driver) is hit, the platform is clamped...)
clampPlatform();
}
if (gamepad1.y) {
releasePlatform();
}
//Driving
if (gamepad1.left_trigger > .1) {
strafeLeft(.8);
}
else if (gamepad1.right_trigger > .1) {
strafeRight(.8);
}
else {
leftOutput = Range.clip(drive + turn, -.95, .95);
rightOutput = Range.clip(drive - turn, -.95, .95);
leftFrontDrive.setPower(leftOutput);
rightFrontDrive.setPower(rightOutput);
leftBackDrive.setPower(leftOutput);
rightBackDrive.setPower(rightOutput);
}
if (gamepad1.a) {
drive(.85);
}
if (gamepad1.y) {
drive(-.85);
}
//Intake
if (gamepad2.left_trigger > .1) {
intakeA.setPower(Constants.SHOOT_SPEED * -1);
intakeB.setPower(Constants.SHOOT_SPEED);
}
else if (gamepad2.right_trigger > .1) {
intakeA.setPower(Constants.INTAKE_SPEED * -1);
intakeB.setPower(Constants.INTAKE_SPEED);
}
else {
intakeA.setPower(0);
intakeB.setPower(0);
}
if (gamepad2.x) {
openIntake();
}
if (gamepad2.y) {
closeIntake();
}
//Elevator
if (lowerLimit.isPressed()) {
moveElevator(gamepad2.right_stick_y * -1 * Constants.SLOWED_ELEVATOR_GAIN);
}
else {
moveElevator(gamepad2.right_stick_y * -1 * Constants.ELEVATOR_GAIN);
}
tiltElevator(Range.clip(gamepad2.left_stick_y * -1, 0, 1));
}
@Override
public void stop() {
}
private void strafeRight(double strafeSpeed) {
leftFrontDrive.setPower(-strafeSpeed);
leftBackDrive.setPower(strafeSpeed);
rightFrontDrive.setPower(strafeSpeed);
rightBackDrive.setPower(-strafeSpeed);
}
private void strafeLeft(double strafeSpeed) {
leftFrontDrive.setPower(strafeSpeed);
leftBackDrive.setPower(-strafeSpeed);
rightFrontDrive.setPower(-strafeSpeed);
rightBackDrive.setPower(strafeSpeed);
}
private void drive (double power) {
leftFrontDrive.setPower(power);
rightFrontDrive.setPower(power);
leftBackDrive.setPower(power);
rightBackDrive.setPower(power);
}
private void openIntake() {
stretch.setPower(.9);
}
private void closeIntake() {
stretch.setPower(-.9);
}
private void moveElevator(double power) {
elevator.setPower(power);
}
private void tiltElevator(double position) {
elevatorTilt.setPosition(position);
}
private void clampPlatform() {
clampA.setPosition(-1);
clampB.setPosition(-1);
}
private void releasePlatform() {
clampA.setPosition(0);
clampB.setPosition(0);
}//I'll go over the functions (orange) in the auto classes but this is pretty much it for TeleOP
} //We're gonna go to auto now bois Red or Blue first? | 34.298165 | 209 | 0.648388 |
09d35bed9bd74b4a33c0a8e0bdcb9fc679e70c10 | 3,522 | /*
* Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clarkparsia.empire.impl;
import com.clarkparsia.empire.ds.DataSourceException;
import com.clarkparsia.empire.ds.SupportsTransactions;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
/**
* <p>Implementation of the JPA EntityTransaction interface for an RDF data source.</p>
*
* @author Michael Grove
* @since 0.1
* @version 0.1
* @see EntityManagerImpl
*/
public final class DataSourceEntityTransaction implements EntityTransaction {
/**
* Whether or not the transaction is currently active
*/
private boolean mIsActive;
/**
* Sets whether or not the transaction can only be rolled back
*/
private boolean mRollbackOnly = false;
/**
* The data source the transaction is being performed on
*/
private SupportsTransactions mDataSource;
/**
* Create (but not open) a transaction for the specified data source
* @param theDataSource the data source that will have the transaction
*/
public DataSourceEntityTransaction(final SupportsTransactions theDataSource) {
mDataSource = theDataSource;
}
/**
* @inheritDoc
*/
public void begin() {
assertInactive();
mIsActive = true;
try {
mDataSource.begin();
}
catch (DataSourceException e) {
throw new PersistenceException(e);
}
}
/**
* @inheritDoc
*/
public void commit() {
assertActive();
if (getRollbackOnly()) {
throw new RollbackException("Transaction cannot be committed, it is marked as rollback only.");
}
try {
mDataSource.commit();
mIsActive = false;
}
catch (DataSourceException e) {
throw new RollbackException(e);
}
}
/**
* @inheritDoc
*/
public void rollback() {
assertActive();
try {
mDataSource.rollback();
}
catch (DataSourceException e) {
throw new PersistenceException(e);
}
finally {
mIsActive = false;
}
}
/**
* @inheritDoc
*/
public void setRollbackOnly() {
assertActive();
mRollbackOnly = true;
}
/**
* @inheritDoc
*/
public boolean getRollbackOnly() {
assertActive();
return mRollbackOnly;
}
/**
* @inheritDoc
*/
public boolean isActive() {
return mIsActive;
}
/**
* Force there to be no active transaction. If one is active, an IllegalStateException is thrown
* @throws IllegalStateException if there is an active transaction
*/
private void assertInactive() {
if (isActive()) {
throw new IllegalStateException("Transaction must be inactive in order to perform this operation.");
}
}
/**
* Force there to be an active transaction. If one is not active, an IllegalStateException is thrown
* @throws IllegalStateException if there is not an active transaction
*/
private void assertActive() {
if (!isActive()) {
throw new IllegalStateException("Transaction must be active in order to perform this operation.");
}
}
}
| 22.87013 | 103 | 0.710392 |
64190b82aa538289f3eb07f76bcc56ddecfa5314 | 3,245 | /*
* 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 edu.usc.irds.sparkler.model;
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class FetchedData implements Serializable {
private Resource resource;
private byte[] content;
private String contentType;
private Integer contentLength;
private Map<String, List<String>> headers = Collections.emptyMap();
private Date fetchedAt;
private MultiMap<String, String> metadata = new MultiMap<>();
private int responseCode;
private long responseTime = -1;
public FetchedData() {
}
public FetchedData(byte[] content, String contentType, int responseCode) {
super();
this.content = content;
this.contentLength = content.length;
this.contentType = contentType;
this.responseCode = responseCode;
this.fetchedAt = new Date();
}
public String getContentType() {
return contentType == null ? "" : contentType;
}
public int getResponseCode() {
return responseCode;
}
public Resource getResource() { return resource; }
public byte[] getContent() {
return content;
}
public Integer getContentLength() {
return contentLength;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
public Date getFetchedAt() {
return fetchedAt;
}
public MultiMap<String, String> getMetadata() {
return metadata;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void setContentLength(Integer contentLength) {
this.contentLength = contentLength;
}
public void setContent(byte[] content) {
this.content = content;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setFetchedAt(Date fetchedAt) {
this.fetchedAt = fetchedAt;
}
public void setMetadata(MultiMap<String, String> metadata) {
this.metadata = metadata;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
public Long getResponseTime(){return this.responseTime;}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
}
| 26.818182 | 78 | 0.684746 |
812a5187b06d2de616a34c21b8bd38116083b5f2 | 3,322 | package Autonomous.OpModes.Tests;
import android.graphics.Bitmap;
import android.util.Log;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import java.util.ArrayList;
import Autonomous.ImageProcessing.CryptoBoxColumnImageProcessor;
import Autonomous.VuforiaHelper;
/**
* Created by root on 11/20/17.
*/
/*
An opmode to test saving images using vuforia
*/
@Autonomous(name="Capture Test", group="Testers") // @Autonomous(...) is the other common choice
@Disabled
public class VuforiaImageCaptureTest extends LinearOpMode {
CryptoBoxColumnImageProcessor cryptoFinder;
@Override
public void runOpMode() throws InterruptedException {
int imageTaken = 0;
CryptoBoxColumnImageProcessor.CRYPTOBOX_COLOR color = CryptoBoxColumnImageProcessor.CRYPTOBOX_COLOR.BLUE;
/*To access the image: you need to iterate through the images of the frame object:*/
VuforiaHelper vuforia = new VuforiaHelper(hardwareMap);
//wait for the op mode to start, this is the time to change teams
while (!opModeIsActive()) {
if (gamepad1.start) {
if(color == CryptoBoxColumnImageProcessor.CRYPTOBOX_COLOR.BLUE) color = CryptoBoxColumnImageProcessor.CRYPTOBOX_COLOR.RED;
else color = CryptoBoxColumnImageProcessor.CRYPTOBOX_COLOR.BLUE;
while (gamepad1.start) ;
}
telemetry.addData("Color", color);
telemetry.update();
}
//initialize the image processor
cryptoFinder = new CryptoBoxColumnImageProcessor(CryptoBoxColumnImageProcessor.DESIRED_HEIGHT, CryptoBoxColumnImageProcessor.DESIRED_WIDTH,.1,1, color);
telemetry.addData("Status","Initialized");
waitForStart();
//storage variables
Bitmap bmp;
ArrayList<Integer> columnLocations = new ArrayList<Integer>();
while(opModeIsActive()){
long timeStart = System.currentTimeMillis();
//get an image
bmp = vuforia.getImage(CryptoBoxColumnImageProcessor.DESIRED_WIDTH, CryptoBoxColumnImageProcessor.DESIRED_HEIGHT);
if(bmp != null){
long algorithmStart = System.currentTimeMillis();
//find the columns
columnLocations = cryptoFinder.findColumns(bmp,true);
telemetry.addData("Algorithm Time", "" + (System.currentTimeMillis() - algorithmStart));
//for every column seen, print its location
if(columnLocations != null){
for(int i = 0; i < columnLocations.size(); i ++){
telemetry.addData("Column " + i, " " + columnLocations.get(i).intValue());
}
}
//save every tenth image
if(imageTaken == 50) {
vuforia.saveBMP(bmp); // save edited image
imageTaken = 0;
}
imageTaken++;
telemetry.addData("Loop Time", "" + (System.currentTimeMillis() - timeStart));
telemetry.update();
}
else{
Log.d("BMP","NULL!");
}
}
}
}
| 40.024096 | 160 | 0.627333 |
7c3cb076308d89a834d874d6e26e2b5dac90fcd3 | 13,000 | package application.controller.page;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import application.controller.MainController;
import application.controller.add.AjoutCommandeController;
import application.controller.detail.DetailCommandeController;
import application.controller.edit.EditCommandeController;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import modele.Client;
import modele.Commande;
import modele.LigneCommande;
import modele.Produit;
public class PageCommandeController implements Initializable {
@FXML private TableView<Commande> tabCommande;
@FXML private TableColumn<Commande, Integer> idCommande = new TableColumn<Commande, Integer>("Identifiant");
@FXML private TableColumn<Commande, LocalDate> dateCommande = new TableColumn<Commande, LocalDate>("Date Commande");
@FXML private TableColumn<Commande, String> clientCommande = new TableColumn<Commande, String>("Client Concerne");
@FXML private Button addCommande;
@FXML private Button deleteCommande;
@FXML private Button editCommande;
@FXML private Button detailCommande;
@FXML Button actualiser;
@FXML HBox rechercheCl;
@FXML HBox rechercheProd;
@FXML private ChoiceBox<Produit> searchProduit;
@FXML private TextField searchClient;
@SuppressWarnings("unused")
private MainController main;
private Commande commande;
private Client client=null;
public void actualiser() {
try {
this.tabCommande.getItems().setAll(MainController.commandeDAO.findAll());
ObservableList<Produit> listeProduit = FXCollections.observableArrayList();
for (Produit produit : MainController.produitDAO.findAll()) {
listeProduit.add(produit);
}
listeProduit.add(null);
this.searchProduit.setItems(listeProduit);
} catch (Exception e) {
e.printStackTrace();
}
}
public void initData(Client selectedClient) {
client = selectedClient;
if (client!=null) {
try {
for (Commande commande : MainController.commandeDAO.findAll()) {
if (commande.getIdClient() != client.getId()) this.tabCommande.getItems().remove(commande);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList<Produit> listeProduit = FXCollections.observableArrayList();
try {
for (Produit produit : MainController.produitDAO.findAll()) {
listeProduit.add(produit);
}
listeProduit.add(null);
this.searchProduit.setItems(listeProduit);
} catch (Exception e1) {
e1.printStackTrace();
}
searchProduit.getSelectionModel().selectedItemProperty().addListener(
(observale, odlValue, newValue) -> {
filtrerProduit();
});
this.idCommande.setCellValueFactory(new PropertyValueFactory<>("id"));
this.dateCommande.setCellValueFactory(new PropertyValueFactory<>("date"));
this.clientCommande.setCellValueFactory(new Callback<CellDataFeatures<Commande, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<Commande, String> p) {
try {
return new ReadOnlyStringWrapper(MainController.clientDAO.getById(p.getValue().getIdClient()).getNom());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
this.tabCommande.getItems().addAll(MainController.commandeDAO.findAll());
if (client!=null) {
for (Commande commande : MainController.commandeDAO.findAll()) {
if (commande.getIdClient() != client.getId()) this.tabCommande.getItems().remove(commande);
}
}
} catch (Exception e) {
e.printStackTrace();
}
this.tabCommande.getSelectionModel().selectedItemProperty().addListener(
(observale, odlValue, newValue) -> {
this.commande = tabCommande.getSelectionModel().getSelectedItem();
this.addCommande.setDisable(newValue != null);
this.deleteCommande.setDisable(newValue == null);
this.editCommande.setDisable(newValue == null);
this.detailCommande.setDisable(newValue == null);
});
//event qui annule la selection actuelle de la tableView si on selectionne une ligne vide
this.tabCommande.addEventFilter(MouseEvent.MOUSE_CLICKED, evt -> {
Node source = evt.getPickResult().getIntersectedNode();
// move up through the node hierarchy until a TableRow or scene root is found
while (source != null && !(source instanceof TableRow)) {
source = source.getParent();
}
// clear selection on click anywhere but on a filled row
if (source == null || (source instanceof TableRow && ((TableRow<?>) source).isEmpty())) {
tabCommande.getSelectionModel().clearSelection();
}
});
this.deleteCommande.setDisable(true);
this.editCommande.setDisable(true);
this.detailCommande.setDisable(true);
}
public void init(MainController mainController) {
main = mainController;
}
//Charge la page AJoutCommande et recupere les donnees pour les ajouter dans le tableau
public void ajoutCommande() {
Stage nStage = new Stage();
try {
//On charge l'url de la page AjoutCommande.fxml
URL fxmlURL=getClass().getResource("/fxml/add/AjoutCommande.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
Node root = fxmlLoader.load();
//On recupere le controleur de la page AjoutCommande.fxml
AjoutCommandeController controller = fxmlLoader.getController();
//On affiche la fenetre AjoutCommande
Scene scene = new Scene((AnchorPane) root, 600, 350);
nStage.setScene(scene);
nStage.setResizable(false);
nStage.setTitle("Creer une commande");
nStage.initModality(Modality.APPLICATION_MODAL);
nStage.showAndWait();
if (controller.getCommandeAjout() != null)
tabCommande.getItems().add(controller.getCommandeAjout());
}
catch (Exception e) {
e.printStackTrace();
}
}
//Charge la page DetailCommmande qui affiche les lignes de commande d'une commande
public void detailCommande() {
Stage nStage = new Stage();
try {
//On charge l'url de la page DztailCommande.fxml
URL fxmlURL=getClass().getResource("/fxml/detail/DetailCommande.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
Node root = fxmlLoader.load();
//On recupere le controleur de la page DetailCommande.fxml
DetailCommandeController controller = fxmlLoader.getController();
//On charge les donnees de la ligne selectionnee dans la classe controleur DetailCommandeController
controller.initData(tabCommande.getSelectionModel().getSelectedItem().getId());
//On affiche la fenetre DetailCommande
Scene scene = new Scene((AnchorPane) root, 600, 400);
nStage.setScene(scene);
nStage.setResizable(false);
nStage.setTitle("Detail d'une commande");
nStage.initModality(Modality.APPLICATION_MODAL);
nStage.showAndWait();
try {
for(Commande commande : tabCommande.getItems()) {
if (!MainController.commandeDAO.findAll().contains(commande)) tabCommande.getItems().remove(commande);
}
} catch(ConcurrentModificationException e) {
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public TableView<Commande> getTabCommande() {
return tabCommande;
}
public void setTabCommande(TableView<Commande> tabCommande) {
this.tabCommande = tabCommande;
}
//Charge la page ModifCommande et recupere les donnees pour les modifier dans le tableau
public void modifCommande() {
Stage nStage = new Stage();
try {
//On charge l'url de la page ModifCommande.fxml
URL fxmlURL=getClass().getResource("/fxml/edit/ModifCommande.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
Node root = fxmlLoader.load();
//On recupere le controleur de la page ModifCommande.fxml
EditCommandeController controller = fxmlLoader.getController();
//On charge les donnees de la ligne selectionnee dans la classe controleur EditCommandeController
controller.initData(tabCommande.getSelectionModel().getSelectedItem());
//On affiche la fenetre ModifCommande
Scene scene = new Scene((AnchorPane) root, 600, 400);
nStage.setScene(scene);
nStage.setResizable(false);
nStage.setTitle("Modififer une commande");
nStage.initModality(Modality.APPLICATION_MODAL);
nStage.showAndWait();
//On modifie l'objet dans le tableau
tabCommande.getItems().set(
tabCommande.getItems().indexOf(controller.getSelectedItem()),
controller.getSelectedItem());
}
catch (Exception e) {
e.printStackTrace();
}
}
//Supprime la valeur dans le tableau et dans la dao
@SuppressWarnings("rawtypes")
public void supprCommande() {
//Ouvre une fenetre d'alerte pour confirmer la suppression
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Alerte suppression");
alert.setContentText("Etes vouloir supprimer cette commande qui est composée d'un ou plusieurs produits ?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
try {
for (Map.Entry mapentry : commande.getLigneCommande().entrySet()) {
MainController.ligneCommandeDAO.delete((LigneCommande) mapentry.getValue());
}
MainController.commandeDAO.delete(commande);
tabCommande.getItems().remove(commande);
tabCommande.getSelectionModel().clearSelection();
}
catch(Exception e) {
e.printStackTrace();
}
}
else {
tabCommande.getSelectionModel().clearSelection();
}
}
//Renvoie une liste des commandes qui possedent un produit correspondant a la demande
public ArrayList<Commande> filtrerProduit() {
searchClient.setText("");
ArrayList<Commande> listeCommande = new ArrayList<Commande>();
Produit produit = searchProduit.getSelectionModel().getSelectedItem();
String nom = searchClient.getText().trim().toLowerCase();
try {
if ((produit!=null) && (nom.equals(""))) {
for (Commande commande : MainController.commandeDAO.findAll()) {
for (Map.Entry<Produit, LigneCommande> mapentry : commande.getLigneCommande().entrySet()) {
if (mapentry.getKey().equals(produit))
listeCommande.add(commande);
}
}
}
else {
listeCommande.addAll(MainController.commandeDAO.findAll());
}
tabCommande.getItems().clear();
tabCommande.getItems().addAll(listeCommande);
} catch (Exception e) {
e.printStackTrace();
}
return listeCommande;
}
//Renvoie une liste des clients qui possedent un nom correspondant a la demande
public ArrayList<Commande> filtrerClient() {
searchProduit.setValue(null);
String nom = searchClient.getText().trim().toLowerCase();
ArrayList<Commande> listeCommande= new ArrayList<Commande>();
try {
if (nom.equals("")) {
listeCommande.addAll(MainController.commandeDAO.findAll());
}
else {
for (Commande commande : MainController.commandeDAO.findAll()) {
if (MainController.clientDAO.getById(commande.getIdClient()).getNom().toLowerCase().contains(nom)) {
listeCommande.add(commande);
}
}
}
tabCommande.getItems().clear();
tabCommande.getItems().addAll(listeCommande);
} catch (Exception e) {
e.printStackTrace();
}
return listeCommande;
}
public Button getActualiser() {
return actualiser;
}
public HBox getRechercheCl() {
return rechercheCl;
}
public HBox getRechercheProd() {
return rechercheProd;
}
public Button getAddCommande() {
return addCommande;
}
}
| 33.07888 | 120 | 0.702692 |
6b08ac7b52bb1b23f2660daeb25a8b7ac066328c | 1,575 | package com.premar.muvi.utils;
import com.premar.muvi.model.Movie;
import com.premar.muvi.model.search.Search;
import java.util.ArrayList;
import java.util.List;
public class SearchToMovie {
private ArrayList<Search> searches;
private ArrayList<Movie> movies;
public SearchToMovie(ArrayList<Search> searches) {
this.searches=searches;
movies=new ArrayList<>(searches.size());
}
public ArrayList<Movie> getMovies()
{
for(int i=0;i<searches.size();i++)
{
movies.add(new Movie());
movies.get(i).setTitle(searches.get(i).getTitle());
movies.get(i).setAdult(searches.get(i).getAdult());
movies.get(i).setBackdropPath((String)searches.get(i).getBackdropPath());
movies.get(i).setPopularity(searches.get(i).getPopularity());
movies.get(i).setId(searches.get(i).getId());
movies.get(i).setOriginalLanguage(searches.get(i).getOriginalLanguage());
movies.get(i).setOriginalTitle(searches.get(i).getOriginalTitle());
movies.get(i).setOverview(searches.get(i).getOverview());
movies.get(i).setPosterPath(searches.get(i).getPosterPath());
movies.get(i).setReleaseDate(searches.get(i).getReleaseDate());
movies.get(i).setVideo(searches.get(i).getVideo());
movies.get(i).setVoteAverage(searches.get(i).getVoteAverage());
movies.get(i).setVoteCount(searches.get(i).getVoteCount());
}
return movies;
}
}
| 39.375 | 86 | 0.627302 |
300c4c8534b1dc6b19c5234bc96f36ff315fcb2b | 9,594 | /*
* Copyright 2010-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.springfaces.mvc.navigation.requestmapped;
import java.lang.reflect.Method;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.springfaces.mvc.bind.ReverseDataBinder;
import org.springframework.springfaces.mvc.servlet.view.BookmarkableRedirectView;
import org.springframework.springfaces.mvc.servlet.view.BookmarkableView;
import org.springframework.springfaces.mvc.servlet.view.FacesRenderedView;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.FacesWebRequest;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.view.AbstractView;
import org.springframework.web.util.UriTemplate;
/**
* A {@link BookmarkableView} that redirects to a URL built dynamically from {@link RequestMapping} annotated
* {@link Controller} methods. URLs are built by inspecting values of the {@link RequestMapping} annotation along with
* any method parameters.
* <p>
* For example, given the following controller:
*
* <pre>
* @RequestMapping('/hotel')
* public class HotelsController {
* @RequestMapping('/search')
* public void search(String s) {
* //...
* }
* }
* </pre>
*
* A <tt>RequestMappedRedirectView</tt> for the <tt>search</tt> method would create the URL
* <tt>/springdispatch/hotel/search?s=spring+jsf</tt>.
* <p>
* Method parameters are resolved against the <tt>model</tt>, in the example above the model contains the entry
* <tt>s="spring jsf"</tt>. As well as simple data types, method parameters can also reference any object that
* {@link DataBinder} supports. The model will also be referenced when resolving URI path template variables (for
* example <tt>/show/{id}</tt>).
* <p>
* There are several limitations to the types of methods that can be used with this view, namely:
* <ul>
* <li>The {@link RequestMapping} must contain only a single <tt>value</tt></li>
* <li>Paths should not contain wildcards (<tt>"*"</tt>, <tt>"?"</tt>, etc)</li>
* <li>Custom {@link InitBinder} annotationed methods of the controller will not be called</li>
* </ul>
*
* @author Phillip Webb
* @see RequestMappedRedirectDestinationViewResolver
* @see RequestMappedRedirectViewContext
* @see ReverseDataBinder
*/
public class RequestMappedRedirectView implements BookmarkableView, FacesRenderedView {
/**
* Context for the view
*/
private RequestMappedRedirectViewContext context;
/**
* The MVC handler being referenced
*/
private Object handler;
/**
* The MVC handler method being referenced
*/
private Method handlerMethod;
/**
* The model builder.
*/
private RequestMappedRedirectViewModelBuilder modelBuilder;
/**
* Create a new {@link RequestMappedRedirectView}.
* @param context the context for redirect view
* @param handler the MVC handler
* @param handlerMethod the MVC handler method that should be used to generate the redirect URL
*/
public RequestMappedRedirectView(RequestMappedRedirectViewContext context, Object handler, Method handlerMethod) {
Assert.notNull(context, "Context must not be null");
Assert.notNull(handler, "Handler must not be null");
Assert.notNull(handlerMethod, "HandlerMethod must not be null");
this.context = context;
this.handler = handler;
this.handlerMethod = BridgeMethodResolver.findBridgedMethod(handlerMethod);
this.modelBuilder = new RequestMappedRedirectViewModelBuilder(context, handlerMethod);
}
public String getContentType() {
return AbstractView.DEFAULT_CONTENT_TYPE;
}
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
NativeWebRequest webRequest = new FacesWebRequest(FacesContext.getCurrentInstance());
String url = buildRedirectUrl(request);
Map<String, ?> relevantModel = getRelevantModel(webRequest, url, model);
createDelegateRedirector(url).render(relevantModel, request, response);
}
public void render(Map<String, ?> model, FacesContext facesContext) throws Exception {
HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
NativeWebRequest webRequest = new FacesWebRequest(facesContext);
String url = buildRedirectUrl(request);
Map<String, ?> relevantModel = getRelevantModel(webRequest, url, model);
BookmarkableView delegate = createDelegateRedirector(url);
if (delegate instanceof FacesRenderedView) {
((FacesRenderedView) delegate).render(relevantModel, facesContext);
} else {
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
delegate.render(relevantModel, request, response);
}
}
public String getBookmarkUrl(Map<String, ?> model, HttpServletRequest request) throws Exception {
NativeWebRequest webRequest = new FacesWebRequest(FacesContext.getCurrentInstance());
String url = buildRedirectUrl(request);
Map<String, ?> relevantModel = getRelevantModel(webRequest, url, model);
return createDelegateRedirector(url).getBookmarkUrl(relevantModel, request);
}
/**
* Build the redirect URL
* @param request the HTTP servlet request
* @return a redirect URL
*/
private String buildRedirectUrl(HttpServletRequest request) {
RequestMapping methodRequestMapping = AnnotationUtils.findAnnotation(this.handlerMethod, RequestMapping.class);
RequestMapping typeLevelRequestMapping = AnnotationUtils.findAnnotation(this.handler.getClass(),
RequestMapping.class);
Assert.state(methodRequestMapping != null, "The handler method must declare @RequestMapping annotation");
Assert.state(methodRequestMapping.value().length == 1,
"@RequestMapping must have a single value to be mapped to a URL");
Assert.state(typeLevelRequestMapping == null || typeLevelRequestMapping.value().length == 1,
"@RequestMapping on handler class must have a single value to be mapped to a URL");
String url = this.context.getDispatcherServletPath();
if (url == null) {
url = request.getServletPath();
}
if (typeLevelRequestMapping != null) {
url += typeLevelRequestMapping.value()[0];
}
PathMatcher pathMatcher = this.context.getPathMatcher();
if (pathMatcher == null) {
pathMatcher = new AntPathMatcher();
}
url = pathMatcher.combine(url, methodRequestMapping.value()[0]);
if (!url.startsWith("/")) {
url = "/" + url;
}
return url;
}
/**
* Factory method that creates a {@link BookmarkableView} used as a delegate to perform the actual
* bookmark/redirect. The default implementation returns a {@link BookmarkableRedirectView}.
* @param url the URL that should be redirected to.
* @return a {@link BookmarkableView} that will be used to perform the actual bookmark/redirect
*/
protected BookmarkableView createDelegateRedirector(String url) {
return new BookmarkableRedirectView(url, true);
}
/**
* Extract the relevant items from the source model. The default implementation delegates to
* {@link RequestMappedRedirectViewModelBuilder}.
* @param request the current request
* @param url the URL
* @param sourceModel the source model
* @return relevant model items
*/
protected Map<String, ?> getRelevantModel(NativeWebRequest request, String url, Map<String, ?> sourceModel) {
Map<String, Object> model = buildModel(request, url, sourceModel);
addUriTemplateParameters(model, url, sourceModel);
return model;
}
private Map<String, Object> buildModel(NativeWebRequest request, String url, Map<String, ?> sourceModel) {
try {
return this.modelBuilder.build(request, sourceModel);
} catch (RuntimeException e) {
throw new IllegalStateException("Unable to build model for URL '" + url, e);
}
}
/**
* Add to the model any URI template variable that have not been covered by {@link PathVariable} annotated method
* parameters.
* @param model the model to add item into
* @param url the URL
* @param sourceModel the source model
*/
private void addUriTemplateParameters(Map<String, Object> model, String url, Map<String, ?> sourceModel) {
UriTemplate uriTemplate = new UriTemplate(url);
for (String name : uriTemplate.getVariableNames()) {
if (!model.containsKey(name)) {
Assert.state(sourceModel.containsKey(name), "Unable to find URL template variable '" + name
+ "' in source model");
model.put(name, sourceModel.get(name));
}
}
}
}
| 41 | 118 | 0.75985 |
7aa35308a26f2fc0b3f9f11ee3c332c6be8cf49b | 3,563 | package farmsim.entities.predators;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
/**
* A class used for loading in the config file for predators
* @author r-portas
*/
public class PredatorConfigLoader {
private HashMap<String, HashMap<String, String>> predators;
/**
* Intialises the PredatorConfigLoader class
*/
public PredatorConfigLoader() {
predators = new HashMap<String, HashMap<String, String>>();
}
/**
* Loads a config file into the object
* @param filename A string representing the filename of the config file
*/
public void loadFile(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = new String();
line = reader.readLine();
String predatorName = new String();
HashMap<String, String> tempPred = new HashMap<String, String>();
while (line != null) {
if (line.length() > 0) {
if (line.charAt(0) == '[' && line.charAt(line.length() - 1) == ']') {
if (!predatorName.isEmpty()) {
predators.put(predatorName, tempPred);
}
predatorName = line.replace("[", "");
predatorName = predatorName.replace("]", "");
tempPred = new HashMap<String, String>();
} else if (line.contains("=")) {
String[] sep = line.split("=");
if (sep.length == 2) {
tempPred.put(sep[0], sep[1]);
}
}
}
line = reader.readLine();
}
reader.close();
if (!predatorName.isEmpty()) {
predators.put(predatorName, tempPred);
}
} catch (Exception e){
//System.out.println(e.toString()); @Todo -> user logger!!!!
// For now, do nothing
// If this occurs the predator manager will
// revert to it's backup values
}
}
/**
* Returns the string representation of the stored data
* @return String representation of PredatorConfigLoader
*/
public String toString() {
return predators.toString();
}
/**
* Returns the number of predators loaded in by the config loader
* @return The count of animals loaded
*/
public int getLoadedCount() {
return predators.size();
}
/**
* Gets all entries relating to the given predator
* @param predator A string name representing the predator
* @return Returns a hashmap of data if the predator is found, else returns null
*/
public HashMap<String, String> getPredator(String predator) {
return predators.get(predator);
}
/**
* Gets the given predator attribute
* @param predator The name of the predator
* @param attr The name of the attribute
* @return A string containing the requested attribute
*/
public String getPredatorAttribute(String predator, String attr) {
return predators.get(predator).get(attr);
}
/**
* Gets everything stored inside the config loader
* @return A hashmap containing the predators with corresponding key value pairs
*/
public HashMap<String, HashMap<String, String>> getConfig() {
return predators;
}
}
| 32.099099 | 89 | 0.558518 |
76ac4faa98c9c6c5c794dd5728d531126cab0f95 | 9,949 | package org.swiftboot.web.result;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swiftboot.data.model.entity.BaseEntity;
import org.swiftboot.data.model.entity.IdPersistable;
import org.swiftboot.util.BeanUtils;
import org.swiftboot.web.Info;
import org.swiftboot.web.R;
import org.swiftboot.web.annotation.PopulateIgnore;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
/**
* 提供将入实体类的属性值填入返回值的方法。如果 Result 存在的属性名称在实体类中不存在的话,则抛出异常。
* <code>populateByEntity(E entity)</code> 方法将实体类的属性填充到当前对象实例中。
* 静态方法<code>populateByEntity(E entity, BasePopulateResult<E> result)</code>将指定实体类属性值填充至指定的 Result 实例中。
* 填充方法支持将实体类的 <code>@OneToOne</code> 和 </code>@OneToMany</code> 的属性填充到 Result 实例中,前提是 Result 实例中对应的属性类型必须也是继承自 BasePopulateResult 的类。
* 注意:一对一关系如果需要填充,则必须使用 fetch = FetchType.LAZY 来标注,否则将无法通过反射获取到带有属性值的子类。
* 标记 {@link JsonIgnore} 注解的 Result 类属性不会被处理。
* 如果希望某个实体类中不存在的属性也能出现在 Result 类中,那么可以用 {@link PopulateIgnore} 来标注这个属性。
*
* @author swiftech
**/
public abstract class BasePopulateResult<E extends IdPersistable> implements Result {
/**
* 按照返回值类型创建返回值对象,并从实体类填充返回值
*
* @param resultClass 返回对象类型
* @param entity 实体类
* @param <T>
* @return
*/
public static <T extends BasePopulateResult> T createResult(
Class<T> resultClass,
IdPersistable entity) {
if (resultClass == null || entity == null) {
throw new IllegalArgumentException(Info.get(BasePopulateResult.class, R.REQUIRE_PARAMS));
}
T ret;
Constructor<T> constructor;
try {
constructor = resultClass.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new RuntimeException(Info.get(BasePopulateResult.class, R.REQUIRE_NO_PARAM_CONSTRUCTOR1, resultClass.getName()));
}
try {
ret = constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(Info.get(BasePopulateResult.class, R.CONSTRUCT_FAIL2, resultClass.getName(), BasePopulateResult.class));
}
ret.populateByEntity(entity);
return ret;
}
/**
* 从实体类填充当前返回值对象,如果属性值是其他对象的集合,那么也会自动从实体类中获取对应名字的集合来填充返回值的集合
*
* @param entity
* @return
*/
public BasePopulateResult<E> populateByEntity(E entity) {
return BasePopulateResult.populateByEntity(entity, this);
}
/**
* 从实体类填充属性至返回值对象,如果属性值是其他对象的集合,那么也会自动从实体类中获取对应名字的集合来填充返回值的集合
*
* @param entity
* @param result
* @return
*/
public static <E extends IdPersistable> BasePopulateResult<E> populateByEntity(E entity, BasePopulateResult<E> result) {
if (entity == null) {
throw new RuntimeException(Info.get(BasePopulateResult.class, R.REQUIRE_ENTITY));
}
Logger log = LoggerFactory.getLogger(BasePopulateResult.class);
log.trace(Info.get(BasePopulateResult.class, R.POPULATE_FROM_ENTITY1, entity));
/*
* 先处理一对多关联(保证ID属性先被处理,后续处理时略过这些字段)
*/
List<String> ignoredFieldNameList = new LinkedList<>();// 需要忽略的目标属性名称
List<Field> fieldsByType = BeanUtils.getDeclaredFieldsByType(entity, BaseEntity.class);
for (Field srcField : fieldsByType) {
String relationFiledNameInResultClass = srcField.getName() + "Id";
try {
Field targetField = result.getClass().getDeclaredField(relationFiledNameInResultClass);
if (targetField.getAnnotation(JsonIgnore.class) != null
|| targetField.getAnnotation(PopulateIgnore.class) != null) {
continue;
}
BaseEntity parentEntity = (BaseEntity) BeanUtils.forceGetProperty(entity, srcField);
if (parentEntity != null) {
BeanUtils.forceSetProperty(result, relationFiledNameInResultClass, parentEntity.getId());
ignoredFieldNameList.add(relationFiledNameInResultClass); // 记录目标属性名称
}
} catch (Exception e) {
// 忽略处理
continue;
}
}
/*
* 处理(一对一)关联的 Result 对象
*/
List<Field> fieldsOne2One = BeanUtils.getDeclaredFieldsByTypeIgnore(result, BasePopulateResult.class, JsonIgnore.class, PopulateIgnore.class);
for (Field targetField : fieldsOne2One) {
ignoredFieldNameList.add(targetField.getName());
Field srcField;
try {
srcField = BeanUtils.getDeclaredField(entity, targetField.getName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new RuntimeException(Info.get(R.class, R.FIELD_REQUIRED_FOR_ENTITY2, entity.getClass(), targetField.getName()));
}
// String getterNameInEntity = "get" + Character.toUpperCase(srcField.getName().charAt(0)) + srcField.getName().substring(1);
// Object subEntity = null;
// try {
// subEntity = BeanUtils.forceInvokeMethod(entity, getterNameInEntity);
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// throw new RuntimeException(String.format("实体类 %s 缺少参数必要的属性的 Getter: %s", entity.getClass(), targetField.getName()));
// }
Object subEntity = BeanUtils.forceGetProperty(entity, srcField);
if (subEntity instanceof IdPersistable) {
Class subResultClass = (Class) targetField.getGenericType();
if (subResultClass != null) {
BasePopulateResult<E> subResult = createResult(subResultClass, (IdPersistable) subEntity);
BeanUtils.forceSetProperty(result, targetField, subResult);
}
}
}
/*
* 接着处理所有除外键属性之外的所有可用属性
*/
Collection<Field> targetFields = BeanUtils.getFieldsIgnore(result.getClass(), JsonIgnore.class, PopulateIgnore.class);
for (Field targetField : targetFields) {
if (ignoredFieldNameList.contains(targetField.getName())) {
continue;
}
Field srcField;
try {
srcField = BeanUtils.getDeclaredField(entity, targetField.getName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new RuntimeException(Info.get(R.class, R.FIELD_REQUIRED_FOR_ENTITY2, entity.getClass(), targetField.getName()));
}
// unlock
boolean accessible = targetField.isAccessible();
targetField.setAccessible(true);
// 处理集合类属性
if (Collection.class.isAssignableFrom(srcField.getType())
&& Collection.class.isAssignableFrom(targetField.getType())) {
try {
Type[] actualTypeArguments = ((ParameterizedType) targetField.getGenericType()).getActualTypeArguments();
if (actualTypeArguments.length > 0) {
Collection srcCollection = (Collection) BeanUtils.forceGetProperty(entity, srcField.getName());
if (srcCollection != null && !srcCollection.isEmpty()) {
Collection targetCollection = (Collection) BeanUtils.forceGetProperty(result, targetField.getName());
Class elementClass = (Class) actualTypeArguments[0];
if (targetCollection == null) {
if (Set.class.isAssignableFrom(targetField.getType())) {
// 如果集合为 TreeSet 并且其中的元素的类型实现了 Comparable 接口,那么返回 TreeSet
if (TreeSet.class.isAssignableFrom(targetField.getType())
&& Comparable.class.isAssignableFrom((Class<?>) elementClass)) {
targetCollection = new TreeSet<>();
}
else {
targetCollection = new HashSet<>();
}
}
else if (List.class.isAssignableFrom(targetField.getType())) {
targetCollection = new LinkedList<>();
}
targetField.set(result, targetCollection);
}
for (Object subEntity : srcCollection) {
if (subEntity instanceof IdPersistable) {
BasePopulateResult<E> subResult = createResult(elementClass, (IdPersistable) subEntity);
targetCollection.add(subResult);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(Info.get(BasePopulateResult.class, R.POPULATE_COLLECTION_FAIL1, srcField.getName()));
}
}
else {
try {
Object value = BeanUtils.forceGetProperty(entity, srcField.getName());
targetField.set(result, value);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(Info.get(R.class, R.POPULATE_FIELD_FAIL1, srcField.getName()));
}
}
targetField.setAccessible(accessible);
}
return result;
}
}
| 45.429224 | 150 | 0.581365 |
fc1bac5ec987118e76b5493f7e517f3f5d03e054 | 375 | package com.challenge.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.math.BigDecimal;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class SubmissionDTO {
private Long challengeId;
private String userId;
private BigDecimal score;
private String createdAt;
}
| 17.045455 | 33 | 0.792 |
903008db51a91c3cfd8fc7766adeccee3bcafe22 | 2,150 | package fr.vergne.parsing.layer.util;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import fr.vergne.parsing.layer.exception.ParsingException;
public class IntNumberTest {
@Test
public void testSetGetContentPositiveOnly() {
IntNumber integer = new IntNumber(false);
for (String num : Arrays.asList("0", "90", "2094")) {
integer.setContent(num);
assertEquals(num, integer.getContent());
}
}
@Test
public void testSetGetContentPositiveOrNegative() {
IntNumber integer = new IntNumber(true);
for (String sign : Arrays.asList("", "+", "-")) {
for (String num : Arrays.asList("0", "90", "2094")) {
String content = sign + num;
integer.setContent(content);
assertEquals(content, integer.getContent());
}
}
}
@Test
public void testNoSignForPositiveOnly() {
IntNumber integer = new IntNumber(false);
for (String sign : Arrays.asList("", "+", "-")) {
for (String num : Arrays.asList("0", "90", "2094")) {
String content = sign + num;
if (sign.isEmpty()) {
integer.setContent(content);
assertEquals(content, integer.getContent());
} else {
try {
integer.setContent(content);
fail(content + " accepted as positive-only integer.");
} catch (ParsingException e) {
}
}
}
}
}
@Test
public void testNoExcessiveZeros() {
IntNumber integer = new IntNumber(true);
for (String sign : Arrays.asList("", "+", "-")) {
for (String num : Arrays.asList("00", "090", "002094")) {
String content = sign + num;
try {
integer.setContent(content);
fail(content
+ " accepted as integer while has excessive zeros.");
} catch (ParsingException e) {
}
}
}
}
@Test
public void testNofractionalPart() {
IntNumber integer = new IntNumber(true);
for (String sign : Arrays.asList("", "+", "-")) {
for (String num : Arrays.asList("0.", "0.0", "90.1", "2094.321")) {
String content = sign + num;
try {
integer.setContent(content);
fail(content
+ " accepted as integer while has fractional part.");
} catch (ParsingException e) {
}
}
}
}
}
| 24.712644 | 70 | 0.628837 |
a606bef9d2b34ac2a0040b8a4fb5b0e5a7868241 | 333 | package io.github.nemesismate.spring.ws.tunnel;
import io.github.nemesismate.spring.ws.tunnel.tunnel.TunnelConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(TunnelConfiguration.class)
public class WsTunnelAutoConfiguration {
}
| 27.75 | 73 | 0.852853 |
0905054754c4b7d9bc36f17b4f20338d7721bf74 | 5,511 | package org.dspace.submit.step;
import org.dspace.app.util.SubmissionInfo;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.core.Context;
import org.dspace.handle.HandleManager;
import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.IdentifierService;
import org.dspace.submit.AbstractProcessingStep;
import org.dspace.utils.DSpace;
import org.dspace.workflow.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.usagelogging.EventLogger;
/**
* User: kevin (kevin at atmire.com)
* Date: 13-apr-2010
* Time: 18:01:18
*
* The last step in the submission process for a data file
*/
public class CompletedDatastep extends AbstractProcessingStep {
@Override
public int doProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException {
Item completedDataset = subInfo.getSubmissionItem().getItem();
Item publication = DryadWorkflowUtils.getDataPackage(context, subInfo.getSubmissionItem().getItem());
if(completedDataset.getHandle() == null){
//Since we are done we need to create a handle for this
//Create a handle & make sure our publication is aware of this (if it is still in the workflow)!
IdentifierService service = new DSpace().getSingletonService(IdentifierService.class);
try {
service.reserve(context, completedDataset);
} catch (IdentifierException e) {
throw new ServletException(e);
}
if(!publication.isArchived()){
String id;
DCValue[] doiIdentifiers = completedDataset.getMetadata(MetadataSchema.DC_SCHEMA, "identifier", null, Item.ANY);
if(0 < doiIdentifiers.length)
id = doiIdentifiers[0].value;
else
id = HandleManager.resolveToURL(context, completedDataset.getHandle());
publication.addMetadata(MetadataSchema.DC_SCHEMA, "relation", "haspart", null, id);
publication.update();
}
}
String redirectUrl = null;
DCValue[] redirToWorkflowVals = completedDataset.getMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, "submit", "toworkflow", Item.ANY);
if(0 < redirToWorkflowVals.length && Boolean.valueOf(redirToWorkflowVals[0].value)){
//Clear the metadata from the workflow
completedDataset.clearMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, "submit", "toworkflow", Item.ANY);
//Send our item to the workflow
try {
WorkflowItem workflowItem = WorkflowManager.start(context, (WorkspaceItem) subInfo.getSubmissionItem());
WorkflowItem datasetWf = WorkflowItem.findByItemId(context, publication.getID());
ClaimedTask task = ClaimedTask.findByWorkflowIdAndEPerson(context, datasetWf.getID(), context.getCurrentUser().getID());
//Redir us to our overview
redirectUrl = request.getContextPath() + "/handle/" + workflowItem.getCollection().getHandle() + "/workflow?workflowID=" + datasetWf.getID() + "&stepID=" + task.getStepID() + "&actionID=" + task.getActionID();
} catch (Exception e) {
throw new ServletException(e);
}
} else {
if(subInfo.getSubmissionItem() instanceof WorkspaceItem){
//We have a workspace item
//Don't forget to set submitted to true for the item that is just through the workflow !
if(0 == completedDataset.getMetadata("internal", "workflow", "submitted", Item.ANY).length)
completedDataset.addMetadata("internal", "workflow", "submitted", null, Boolean.TRUE.toString());
redirectUrl = request.getContextPath() + "/submit-overview?workspaceID=" + subInfo.getSubmissionItem().getID();
}else{
redirectUrl = request.getContextPath() + "/submit-overview?workflowID=" + subInfo.getSubmissionItem().getID();
}
}
if(completedDataset.getMetadata(MetadataSchema.DC_SCHEMA, "type", null, Item.ANY).length == 0)
completedDataset.addMetadata(MetadataSchema.DC_SCHEMA, "type", null, Item.ANY, "Dataset");
completedDataset.update();
//Commit our changes before redirect
context.commit();
EventLogger.log(context, "submission-completed-dataset", "status=complete,redirectUrl=" + redirectUrl);
//Redirect us to an overview page of our completed dataset !
response.sendRedirect(redirectUrl);
//Find out if we need to add another dataset
return STATUS_COMPLETE;
}
@Override
public int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException {
return 1;
}
@Override
public boolean isStepShownInProgressBar() {
return false;
}
// @Override
// public boolean isStepAccessible(Context context, Item item) {
// Only show this step if we are submitting a new item, if our item already has a handle there is no need to show this page
// return item.getHandle() == null;
//
// }
}
| 45.545455 | 225 | 0.671022 |
6c81d8d5e61fae79f60b7176063110ff57a5b17d | 11,965 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2011 ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.control;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.TreeMap;
import java.util.Vector;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.help.HelpSetException;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.Extension;
import org.parosproxy.paros.extension.ExtensionLoader;
import org.zaproxy.zap.extension.help.ExtensionHelp;
public class ExtensionFactory {
private static Logger log = Logger.getLogger(ExtensionFactory.class);
private static Vector<Extension> listAllExtension = new Vector<>();
private static TreeMap<String, Extension> mapAllExtension = new TreeMap<>();
private static TreeMap<Integer, Extension> mapOrderToExtension = new TreeMap<>();
private static List<Extension> unorderedExtensions = new ArrayList<>();
private static AddOnLoader addOnLoader = null;
/**
*
*/
public ExtensionFactory() {
super();
}
public static AddOnLoader getAddOnLoader() {
if (addOnLoader == null) {
addOnLoader = new AddOnLoader(new File[] {
new File(Constant.FOLDER_PLUGIN),
new File(Constant.getZapHome(), Constant.FOLDER_PLUGIN)});
}
return addOnLoader;
}
public static synchronized void loadAllExtension(ExtensionLoader extensionLoader, Configuration config) {
List<Extension> listExts = getAddOnLoader().getImplementors("org.zaproxy.zap.extension", Extension.class);
listExts.addAll(getAddOnLoader().getImplementors("org.parosproxy.paros.extension", Extension.class));
synchronized (mapAllExtension) {
mapAllExtension.clear();
for (int i=0; i<listExts.size(); i++) {
Extension extension = listExts.get(i);
if (mapAllExtension.containsKey(extension.getName())) {
if (mapAllExtension.get(extension.getName()).getClass().equals(extension.getClass())) {
// Same name, same class so ignore
log.error("Duplicate extension: " + extension.getName() + " " +
extension.getClass().getCanonicalName());
continue;
} else {
// Same name but different class, log but still load it
log.error("Duplicate extension name: " + extension.getName() + " " +
extension.getClass().getCanonicalName() +
" " + mapAllExtension.get(extension.getName()).getClass().getCanonicalName());
}
}
if (extension.isDepreciated()) {
log.debug("Depreciated extension " + extension.getName());
continue;
}
extension.setEnabled(config.getBoolean("ext." + extension.getName(), true));
listAllExtension.add(extension);
mapAllExtension.put(extension.getName(), extension);
int order = extension.getOrder();
if (order == 0) {
unorderedExtensions.add(extension);
} else if (mapOrderToExtension.containsKey(order)) {
log.error("Duplicate order " + order + " " +
mapOrderToExtension.get(order).getName() + "/" + mapOrderToExtension.get(order).getClass().getCanonicalName() +
" already registered, " +
extension.getName() + "/" +extension.getClass().getCanonicalName() +
" will be added as an unordered extension");
unorderedExtensions.add(extension);
} else {
mapOrderToExtension.put(order, extension);
}
}
// Add the ordered extensions
Iterator<Integer> iter = mapOrderToExtension.keySet().iterator();
while (iter.hasNext()) {
Integer order = iter.next();
Extension ext = mapOrderToExtension.get(order);
if (ext.isEnabled()) {
log.debug("Ordered extension " + order + " " + ext.getName());
extensionLoader.addExtension(ext);
loadMessages(ext);
intitializeHelpSet(ext);
}
}
// And then the unordered ones
for (Extension ext : unorderedExtensions) {
if (ext.isEnabled()) {
log.debug("Unordered extension " + ext.getName());
extensionLoader.addExtension(ext);
loadMessages(ext);
intitializeHelpSet(ext);
}
}
}
}
public static synchronized List<Extension> loadAddOnExtensions(ExtensionLoader extensionLoader, Configuration config, AddOn addOn) {
List<Extension> listExts = getAddOnLoader().getImplementors(addOn, "org.zaproxy.zap.extension", Extension.class);
listExts.addAll(getAddOnLoader().getImplementors(addOn, "org.parosproxy.paros.extension", Extension.class));
synchronized (mapAllExtension) {
for (Extension extension : listExts) {
if (mapAllExtension.containsKey(extension.getName())) {
if (mapAllExtension.get(extension.getName()).getClass().equals(extension.getClass())) {
// Same name, same class cant currently replace exts already loaded
log.debug("Duplicate extension: " + extension.getName() + " " +
extension.getClass().getCanonicalName());
extension.setEnabled(false);
continue;
} else {
// Same name but different class, log but still load it
log.error("Duplicate extension name: " + extension.getName() + " " +
extension.getClass().getCanonicalName() +
" " + mapAllExtension.get(extension.getName()).getClass().getCanonicalName());
}
}
if (extension.isDepreciated()) {
log.debug("Depreciated extension " + extension.getName());
continue;
}
extension.setEnabled(config.getBoolean("ext." + extension.getName(), true));
listAllExtension.add(extension);
mapAllExtension.put(extension.getName(), extension);
// Order actually irrelevant when adding an addon;)
int order = extension.getOrder();
if (order == 0) {
unorderedExtensions.add(extension);
} else if (mapOrderToExtension.containsKey(order)) {
log.error("Duplicate order " + order + " " +
mapOrderToExtension.get(order).getName() + "/" + mapOrderToExtension.get(order).getClass().getCanonicalName() +
" already registered, " +
extension.getName() + "/" +extension.getClass().getCanonicalName() +
" will be added as an unordered extension");
unorderedExtensions.add(extension);
} else {
mapOrderToExtension.put(order, extension);
}
}
for (Extension ext : listExts) {
if (ext.isEnabled()) {
log.debug("Adding new extension " + ext.getName());
extensionLoader.addExtension(ext);
loadMessages(ext);
intitializeHelpSet(ext);
}
}
}
return listExts;
}
private static void loadMessages(Extension ext) {
// Try to load a message bundle in the same package as the extension
String name = ext.getClass().getPackage().getName() + "." + Constant.MESSAGES_PREFIX;
try {
ResourceBundle msg = ResourceBundle.getBundle(name, Constant.getLocale(), ext.getClass().getClassLoader());
ext.setMessages(msg);
Constant.messages.addMessageBundle(ext.getI18nPrefix(), ext.getMessages());
} catch (Exception e) {
// Ignore - it will be using the standard message bundle
}
}
/**
* If there are help files within the extension, they are loaded and merged
* with existing help files.
*/
private static void intitializeHelpSet(Extension ext) {
URL helpSetUrl = getExtensionHelpSetUrl(ext);
if (helpSetUrl != null) {
try {
log.debug("Load help files for extension '" + ext.getName() + "' and merge with core help.");
HelpSet extHs = new HelpSet(ext.getClass().getClassLoader(), helpSetUrl);
HelpBroker hb = ExtensionHelp.getHelpBroker();
hb.getHelpSet().add(extHs);
} catch (HelpSetException e) {
log.error("An error occured while adding help file of extension '" + ext.getName() + "': " + e.getMessage(), e);
}
}
}
private static URL getExtensionHelpSetUrl(Extension extension) {
String helpSetLocation = extension.getClass().getPackage().getName().replaceAll("\\.", "/") + "/resource/help/helpset.hs";
return HelpSet.findHelpSet(extension.getClass().getClassLoader(), helpSetLocation);
}
public static List<Extension> getAllExtensions() {
return listAllExtension;
}
public static Extension getExtension(String name) {
Extension test = mapAllExtension.get(name);
return test;
}
public static void unloadAddOnExtension(Extension extension) {
synchronized (mapAllExtension) {
unloadMessages(extension);
unloadHelpSet(extension);
mapAllExtension.remove(extension.getName());
listAllExtension.remove(extension);
boolean isUnordered = true;
for (Iterator<Extension> it = mapOrderToExtension.values().iterator(); it.hasNext();) {
if (it.next() == extension) {
it.remove();
isUnordered = false;
break;
}
}
if (isUnordered) {
unorderedExtensions.remove(extension);
}
}
}
private static void unloadMessages(Extension extension) {
ResourceBundle msg = extension.getMessages();
if (msg != null) {
Constant.messages.removeMessageBundle(extension.getI18nPrefix());
}
}
private static void unloadHelpSet(Extension ext) {
URL helpSetUrl = getExtensionHelpSetUrl(ext);
if (helpSetUrl != null) {
HelpSet baseHelpSet = ExtensionHelp.getHelpBroker().getHelpSet();
Enumeration<?> helpSets = baseHelpSet.getHelpSets();
while (helpSets.hasMoreElements()) {
HelpSet extensionHelpSet = (HelpSet) helpSets.nextElement();
if (helpSetUrl.equals(extensionHelpSet.getHelpSetURL())) {
baseHelpSet.remove(extensionHelpSet);
break;
}
}
}
}
}
| 41.982456 | 136 | 0.59415 |
9d410f64dc2022b51c04cb645e7fd51d2d948001 | 4,155 | package com.bitwaffle.guts.physics;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
import com.bitwaffle.guts.entity.Entity;
/**
* Handles keeping track of which entities to render and handles
* updating all entities
*
* @author TranquilMarmot
*/
public class Entities {
@SuppressWarnings("serial")
public class EntityHashMap extends HashMap<Integer, Entity>{};
/** Request to add entity to world */
public static class EntityAddRequest{
/** Entity being added */
public Entity ent;
/** Hash to add entity with */
public int hash;
public EntityAddRequest(Entity ent, int hash){
this.ent = ent;
this.hash = hash;
ent.setHashCode(hash);
}
}
/** Request to remove entity from world */
public static class EntityRemoveRequest{
/** Layer to remove entity from */
public int layer;
/** Hash of entity being removed */
public int hash;
public EntityRemoveRequest(int layer, int hash){
this.layer = layer;
this.hash = hash;
}
}
/** Number of layers of entities we have */
public static final int NUM_LAYERS = 10;
/** List of lists to keep track of everything */
public EntityHashMap[] layers;
/** Used when adding entities to avoid ConcurrentModificationException */
private Stack<EntityAddRequest> toAdd2D;
/** Used when removing entities to avoid ConcurrentModificationException */
private Stack<EntityRemoveRequest> toRemove2D;
public Entities(){
layers = new EntityHashMap[NUM_LAYERS];
for(int i = 0; i < layers.length; i++)
layers[i] = new EntityHashMap();
toAdd2D = new Stack<EntityAddRequest>();
toRemove2D = new Stack<EntityRemoveRequest>();
}
/** Add an entity to be rendered/updated */
public void addEntity(Entity ent){
addEntity(ent, ent.hashCode());
}
/**
* Add an entity with a specific hash value
* @param ent Entity to add
* @param hash Hash to add entity with
*/
public void addEntity(Entity ent, int hash){
toAdd2D.add(new EntityAddRequest(ent, hash));
}
/** Remove an entity from being rendered/updated */
public void removeEntity(Entity ent){
removeEntity(ent, ent.hashCode());
}
/** Remove an entity with a specific hash value */
public void removeEntity(Entity ent, int hash){
toRemove2D.add(new EntityRemoveRequest(ent.getLayer(), hash));
}
/**
* Update every entity
* @param timeStep Amount of time passed since last update, in seconds
*/
public void update(float timeStep){
// check for any entities to be added
while(!toAdd2D.isEmpty())
handleAddRequest(toAdd2D.pop());
// update all entities
for(EntityHashMap list : layers)
updateLayer(list, timeStep);
// check for any entities to be removed
while(!toRemove2D.isEmpty())
handleRemoveRequest(toRemove2D.pop());
}
/** Add a request to remove an entity from the world */
private void handleRemoveRequest(EntityRemoveRequest req){
Entity ent = layers[req.layer].get(req.hash);
if(ent != null){
ent.cleanup();
layers[req.layer].remove(ent.hashCode());
ent = null;
}
}
/** Add an entity to be rendered */
private void handleAddRequest(EntityAddRequest req){
int layer = req.ent.getLayer();
if(layer > NUM_LAYERS)
layer = NUM_LAYERS;
layers[layer].put(req.hash, req.ent);
}
/**
* Update a list of entities
* @param timeStep Time passed since last update, in seconds
*/
private void updateLayer(EntityHashMap list, float timeStep){
for(Entity ent : list.values())
if(ent != null)
ent.update(timeStep);
}
/** Clear every entity from this list */
public void clear(){
for(EntityHashMap l : layers){
l.clear();
}
}
/** @return Total number of entities */
public int numEntities(){
int count = 0;
for(EntityHashMap l : layers){
count += l.size();
}
return count;
}
/** @return An array containing an iterator for each layer */
public Iterator<Entity>[] getAll2DIterators(){
@SuppressWarnings("unchecked") //can't have a generic array
Iterator<Entity>[] its = new Iterator[NUM_LAYERS];
for(int i = 0; i < NUM_LAYERS; i++)
its[i] = layers[i].values().iterator();
return its;
}
}
| 24.88024 | 76 | 0.687846 |
ac604a79b0d981b34b203b46d3f4682c7a168eb1 | 3,999 | package info.u_team.u_team_core.ingredient;
import java.util.Arrays;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.tags.SetTag;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.IIngredientSerializer;
public class ItemIngredient extends Ingredient {
private final int amount;
public static ItemIngredient fromItems(int amount, ItemLike... items) {
return new ItemIngredient(amount, Arrays.stream(items).map((item) -> new ItemValue(new ItemStack(item))));
}
public static ItemIngredient fromStacks(int amount, ItemStack... stacks) {
return new ItemIngredient(amount, Arrays.stream(stacks).map((stack) -> new ItemValue(stack)));
}
public static ItemIngredient fromTag(int amount, SetTag<Item> tag) {
return new ItemIngredient(amount, Stream.of(new Ingredient.TagValue(tag)));
}
protected ItemIngredient(int amount, Stream<? extends Value> stream) {
super(stream);
this.amount = amount;
}
@Override
public boolean test(ItemStack stack) {
if (stack == null) {
return false;
} else if (values.length == 0) {
return stack.isEmpty();
} else {
dissolve();
for (final ItemStack itemstack : itemStacks) {
if (itemstack.getItem() == stack.getItem()) {
return stack.getCount() >= amount;
}
}
return false;
}
}
public int getAmount() {
return amount;
}
@Override
public IIngredientSerializer<? extends Ingredient> getSerializer() {
return Serializer.INSTANCE;
}
@Override
public JsonElement toJson() {
final var jsonObject = new JsonObject();
jsonObject.addProperty("type", CraftingHelper.getID(Serializer.INSTANCE).toString());
jsonObject.addProperty("amount", amount);
jsonObject.add("items", super.toJson());
return jsonObject;
}
public static class Serializer implements IIngredientSerializer<ItemIngredient> {
public static final Serializer INSTANCE = new Serializer();
@Override
public ItemIngredient parse(JsonObject jsonObject) {
if (!jsonObject.has("amount") || !jsonObject.has("items")) {
throw new JsonSyntaxException("Expected amount and items");
}
final var amount = GsonHelper.getAsInt(jsonObject, "amount");
final var ingredientJsonElement = jsonObject.get("items");
if (ingredientJsonElement.isJsonObject()) {
return new ItemIngredient(amount, Stream.of(valueFromJson(ingredientJsonElement.getAsJsonObject())));
} else if (ingredientJsonElement.isJsonArray()) {
final var jsonArray = ingredientJsonElement.getAsJsonArray();
if (jsonArray.size() == 0) {
throw new JsonSyntaxException("Item array cannot be empty, at least one item must be defined");
} else {
return new ItemIngredient(amount, StreamSupport.stream(jsonArray.spliterator(), false).map((jsonArrayElement) -> {
return valueFromJson(GsonHelper.convertToJsonObject(jsonArrayElement, "item"));
}));
}
} else {
throw new JsonSyntaxException("Expected item to be object or array of objects");
}
}
@Override
public ItemIngredient parse(FriendlyByteBuf buffer) {
final var amount = buffer.readInt();
final var length = buffer.readVarInt();
return new ItemIngredient(amount, Stream.generate(() -> new ItemValue(buffer.readItem())).limit(length));
}
@Override
public void write(FriendlyByteBuf buffer, ItemIngredient ingredient) {
final var items = ingredient.getItems();
buffer.writeInt(ingredient.amount);
buffer.writeVarInt(items.length);
for (final ItemStack stack : items) {
buffer.writeItem(stack);
}
}
}
}
| 31.738095 | 119 | 0.732933 |
024329f0f1d773478ee056d4d8e8e75db96eff68 | 942 | package br.com.caelum.stella.gateway.visa;
import br.com.caelum.stella.gateway.core.ProblematicTransactionException;
/**
* Responsável por verificar o retorno dado pelos componentes.
* @author Alberto Pc
*
*/
public class VISAComponentReturnHandler {
private VISAIntegrationReturn retornoIntegracao;
public VISAComponentReturnHandler(
VISAIntegrationReturn resultadoIntegracao) {
super();
this.retornoIntegracao = resultadoIntegracao;
}
/**
* Verifica se a resposta de determinado componente para a solicitação indica
* sucesso ou não.
* @throws ProblematicTransactionException caso o retorno indique problema
*/
public VISAIntegrationReturn check(){
if (retornoIntegracao.getLr()!=0 && retornoIntegracao.getLr()!=11) {
throw new ProblematicTransactionException(retornoIntegracao.getArs(),retornoIntegracao);
}
return retornoIntegracao;
}
}
| 22.428571 | 92 | 0.730361 |
0d6f001849a9ed9251825efa428ae3a6afb1b510 | 5,127 | package frc.spartanlib.swerve.module;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import com.revrobotics.CANEncoder;
import com.revrobotics.CANPIDController;
import com.revrobotics.CANSparkMax;
import com.revrobotics.ControlType;
import com.revrobotics.CANSparkMax.IdleMode;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import frc.spartanlib.controllers.SpartanPID;
import frc.spartanlib.helpers.PIDConstants;
import frc.spartanlib.math.Vector2;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class TorqueModule extends SwerveModule<SpartanPID, WPI_TalonSRX, CANSparkMax> {
private final int ALIGNMENT_TIMEOUT = 1250; // Milliseconds until I start complaining
private final double ALIGNMENT_TOLERANCE = 2.5; // Tolerance in degrees
private double mLastUpdate = Double.NaN;
private double mLastGoodAlignment;
private CANPIDController mDriveController;
private CANEncoder mDriveEncoder;
public TorqueModule(int pID, int pAzimuthID, int pDriveID, int pEncoderID, double pEncoderZero, PIDConstants pAziConsts, PIDConstants pDriConsts) {
super(pID, pEncoderID, pEncoderZero);
mLastUpdate = System.currentTimeMillis();
mAzimuth = new WPI_TalonSRX(pAzimuthID);
invertAzimuth(true);
mDrive = new CANSparkMax(pDriveID, MotorType.kBrushless);
mDrive.restoreFactoryDefaults();
mDriveEncoder = mDrive.getEncoder();
mDriveController = mDrive.getPIDController();
mDriveEncoder.setPosition(0.0);
mDriveController.setOutputRange(-1, 1);
mDriveController.setP(pDriConsts.P);
mDriveController.setP(pDriConsts.I);
mDriveController.setP(pDriConsts.D);
mAzimuthController = new SpartanPID(pAziConsts);
mAzimuthController.setMinOutput(-1);
mAzimuthController.setMaxOutput(1);
}
@Override
protected void setAzimuthSpeed(double pSpeed) {
mAzimuth.set(ControlMode.PercentOutput, pSpeed);
}
@Override
public void setTargetAngle(double angle) {
super.setTargetAngle(angle);
mAzimuthController.reset();
mAzimuthController.setSetpoint(mTargetAngle);
}
@Override
protected void setDriveSpeed(double pSpeed) {
mDriveController.setIAccum(0.0);
mDriveController.setReference(pSpeed, ControlType.kDutyCycle);
}
@Override
public void invertDrive(boolean pA) {
mDrive.setInverted(pA);
}
@Override
public void invertDrive(boolean pA, boolean internal) {
mDrive.setInverted(pA);
driveInverted = pA;
}
@Override
public void invertAzimuth(boolean pA) {
mAzimuth.setInverted(pA);
}
public void setDriveBrakeMode(boolean pMode) {
if (pMode) mDrive.setIdleMode(IdleMode.kBrake);
else mDrive.setIdleMode(IdleMode.kCoast);
}
@Override
public void update() {
//mAzimuthController.setSetpoint(0.0);
double deltaT = 0.0;
double now = System.currentTimeMillis();
if (Double.isFinite(mLastUpdate)) deltaT = (now - mLastUpdate) * 1000;
mLastUpdate = now;
System.out.println("DeltaT: " + deltaT);
double adjustedTheta = getAngle();
while (adjustedTheta < mTargetAngle - 180) adjustedTheta += 360;
while (adjustedTheta >= mTargetAngle + 180) adjustedTheta -= 360;
double error = mTargetAngle - adjustedTheta;
SmartDashboard.putNumber("[" + mID + "] Module Error", error);
double output = mAzimuthController.WhatShouldIDo(adjustedTheta, deltaT);
SmartDashboard.putNumber("[" + mID + "] Module Spin Speed", output);
setAzimuthSpeed(output);
setDriveSpeed(getTargetSpeed() * mMaxSpeed);
}
@Override
public void updateSmartDashboard() {
SmartDashboard.putNumber("[" + mID + "] Module Encoder", getRawEncoder());
SmartDashboard.putNumber("[" + mID + "] Module Angle", getAngle());
SmartDashboard.putNumber("[" + mID + "] Module Target Angle", getTargetAngle());
SmartDashboard.putNumber("[" + mID + "] Module Target Speed", getTargetSpeed());
double target = getTargetAngle();
double actual = getAngle();
if (Math.abs(target - actual) <= ALIGNMENT_TOLERANCE) {
mLastGoodAlignment = System.currentTimeMillis();
SmartDashboard.putBoolean("[" + mID + "] Module Alignment Warning", true);
} else {
if (mLastGoodAlignment + ALIGNMENT_TIMEOUT < System.currentTimeMillis()) {
SmartDashboard.putBoolean("[" + mID + "] Module Alignment Warning", false);
}
}
}
@Override
public void updateAzimuthPID(double pP, double pI, double pD) {
mAzimuthController.setP(pP);
mAzimuthController.setI(pI);
mAzimuthController.setD(pD);
System.out.println(pD);
}
@Override
public double getDriveSpeed() {
return mDriveEncoder.getVelocity();
}
@Override
public Vector2 getSpeedVector() {
double speed = (getDriveSpeed() * (driveInverted ^ mDrive.getInverted() ? -1 : 1));
double x = speed * Math.sin((getAngle() * Math.PI) / 180);
double y = speed * Math.cos((getAngle() * Math.PI) / 180);
return new Vector2(x, y);
}
@Override
public void setDriveEncoder(double count) {
mDriveEncoder.setPosition(count);
}
}
| 31.648148 | 149 | 0.722645 |
86f2491f283014c1488cbd3e3921e321d0d59778 | 4,172 | /*
* 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.usergrid.persistence.graph.serialization.impl.shard.count;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.persistence.core.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.core.scope.ApplicationScope;
import org.apache.usergrid.persistence.core.test.ITRunner;
import org.apache.usergrid.persistence.core.test.UseModules;
import org.apache.usergrid.persistence.core.util.IdGenerator;
import org.apache.usergrid.persistence.graph.GraphFig;
import org.apache.usergrid.persistence.graph.guice.TestGraphModule;
import org.apache.usergrid.persistence.graph.serialization.EdgeSerialization;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.DirectedEdgeMeta;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.Shard;
import org.apache.usergrid.persistence.model.entity.Id;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import com.google.inject.Inject;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import static org.apache.usergrid.persistence.core.util.IdGenerator.createId;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(ITRunner.class)
@UseModules({ TestGraphModule.class })
public class NodeShardCounterSerializationTest {
private static final Logger log = LoggerFactory.getLogger( NodeShardCounterSerializationTest.class );
@Inject
@Rule
public MigrationManagerRule migrationManagerRule;
protected EdgeSerialization serialization;
@Inject
protected GraphFig graphFig;
@Inject
protected Keyspace keyspace;
@Inject
protected NodeShardCounterSerialization nodeShardCounterSerialization;
protected ApplicationScope scope;
@Before
public void setup() {
scope = mock( ApplicationScope.class );
Id orgId = mock( Id.class );
when( orgId.getType() ).thenReturn( "organization" );
when( orgId.getUuid() ).thenReturn( UUIDGenerator.newTimeUUID() );
when( scope.getApplication() ).thenReturn( orgId );
}
@Test
public void testWritesRead() throws ConnectionException {
final Id id = IdGenerator.createId( "test" );
ShardKey key1 = new ShardKey( scope, new Shard( 0, 0, false ), DirectedEdgeMeta.fromSourceNode( id, "type1" ) );
ShardKey key2 = new ShardKey( scope, new Shard( 0, 0, false ), DirectedEdgeMeta.fromSourceNode( id, "type2" ) );
ShardKey key3 = new ShardKey( scope, new Shard( 1, 0, false ), DirectedEdgeMeta.fromSourceNode( id, "type1" ) );
Counter counter = new Counter();
counter.add( key1, 1000 );
counter.add( key2, 2000 );
counter.add( key3, 3000 );
nodeShardCounterSerialization.flush( counter ).execute();
final long time1 = nodeShardCounterSerialization.getCount( key1 );
assertEquals( 1000, time1 );
final long time2 = nodeShardCounterSerialization.getCount( key2 );
assertEquals( 2000, time2 );
final long time3 = nodeShardCounterSerialization.getCount( key3 );
assertEquals( 3000, time3 );
}
}
| 33.376 | 120 | 0.746405 |
aa48caf596a76e5d48aba8c9a81e7a1c54c7726a | 4,983 | /*
* 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.devtools.j2objc.translate;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.ast.Assignment;
import com.google.devtools.j2objc.ast.Block;
import com.google.devtools.j2objc.ast.ExpressionStatement;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.SuperMethodInvocation;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.TypeDeclaration;
import com.google.devtools.j2objc.ast.VariableDeclaration;
import com.google.devtools.j2objc.types.GeneratedVariableBinding;
import com.google.devtools.j2objc.types.IOSMethod;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.NameTable;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Modifier;
import java.util.List;
/**
* Writes the copyAllFieldsTo method in order to support correct Java clone()
* behavior.
*
* @author Keith Stanger
*/
public class CopyAllFieldsWriter extends TreeVisitor {
private static final IOSMethod COPY_ALL_PROPERTIES =
IOSMethod.create("NSObject copyAllFieldsTo:(id)other");
private static final Function<VariableDeclaration, IVariableBinding> GET_VARIABLE_BINDING_FUNC =
new Function<VariableDeclaration, IVariableBinding>() {
public IVariableBinding apply(VariableDeclaration node) {
return node.getVariableBinding();
}
};
private static final Predicate<IBinding> IS_NON_STATIC_PRED = new Predicate<IBinding>() {
public boolean apply(IBinding binding) {
return !BindingUtil.isStatic(binding);
}
};
// Binding for the declaration of copyAllFieldsTo in NSObject.
private final IOSMethodBinding nsObjectCopyAll;
public CopyAllFieldsWriter() {
nsObjectCopyAll = IOSMethodBinding.newMethod(
COPY_ALL_PROPERTIES, Modifier.PUBLIC, Types.resolveJavaType("void"),
Types.resolveIOSType("NSObject"));
nsObjectCopyAll.addParameter(Types.resolveIOSType("id"));
}
@Override
public void endVisit(TypeDeclaration node) {
ITypeBinding type = node.getTypeBinding();
List<IVariableBinding> fields = getNonStaticFields(node);
if (fields.isEmpty()) {
return;
}
String typeName = NameTable.getFullName(type);
IOSMethod iosMethod = IOSMethod.create(
String.format("%s copyAllFieldsTo:(%s *)other", typeName, typeName));
int modifiers = Modifier.PUBLIC | BindingUtil.ACC_SYNTHETIC;
IOSMethodBinding methodBinding = IOSMethodBinding.newMethod(
iosMethod, modifiers, Types.resolveJavaType("void"), type);
methodBinding.addParameter(type);
GeneratedVariableBinding copyParamBinding = new GeneratedVariableBinding(
"other", 0, type, false, true, null, methodBinding);
MethodDeclaration declaration = new MethodDeclaration(methodBinding);
node.getBodyDeclarations().add(declaration);
SingleVariableDeclaration copyParam = new SingleVariableDeclaration(copyParamBinding);
declaration.getParameters().add(copyParam);
Block body = new Block();
declaration.setBody(body);
List<Statement> statements = body.getStatements();
SuperMethodInvocation superCall = new SuperMethodInvocation(nsObjectCopyAll);
superCall.getArguments().add(new SimpleName(copyParamBinding));
statements.add(new ExpressionStatement(superCall));
for (IVariableBinding field : fields) {
statements.add(new ExpressionStatement(new Assignment(
new FieldAccess(field, new SimpleName(copyParamBinding)),
new SimpleName(field))));
}
}
private static List<IVariableBinding> getNonStaticFields(TypeDeclaration node) {
return Lists.newArrayList(Iterables.filter(
Iterables.transform(TreeUtil.getAllFields(node), GET_VARIABLE_BINDING_FUNC),
IS_NON_STATIC_PRED));
}
}
| 39.23622 | 98 | 0.770821 |
61b35bcdc044394297e4bb8aace067a9cef9ed70 | 1,029 | package com.learn.java.leetcode.lc0040;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
List<Integer> levelList = new ArrayList<>();
dfs(candidates, target,result,levelList, 0, 0);
return result;
}
private void dfs(int[] candidates, int target,List<List<Integer>> result,List<Integer> levelList,int sum,int level){
for(int i = level;i<candidates.length;i++){
if(i>level&&candidates[i]==candidates[i-1]){
continue;
}
if(sum+candidates[i]>target){
continue;
}
sum+=candidates[i];
levelList.add(candidates[i]);
if(sum==target){
result.add(new ArrayList(levelList));
}
dfs(candidates, target,result,levelList, sum, i+1);
sum-=candidates[i];
levelList.remove(levelList.size()-1);
}
}
}
| 24.5 | 117 | 0.6793 |
60887543b918619a7db90b91d8330da6c902b917 | 356 | import javax.swing.JFrame;
public class ShowAFrame {
public static void main(String args[]) {
JFrame myFrame = new JFrame();
String myTitle = "Blank Frame";
myFrame.setTitle(myTitle);
myFrame.setSize(300, 200);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
| 23.733333 | 63 | 0.648876 |
4086da46f7a0292e01533523175f22d49e6bc785 | 4,918 | package components.DatabaseHandler;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.google.gson.Gson;
import components.Location.LocationValues;
public class LocationSimpleDatabase {
String name;
static SQLiteDatabase myDatabase;
Context mContext;
static String locationTableName;
LinkedList<LinkedHashMap<String, String>> listOfMaps;
public LocationSimpleDatabase(String databaseName,
String locationTableName_, Context ctx) {
this.name = databaseName;
locationTableName = locationTableName_;
this.mContext = ctx;
myDatabase = mContext.openOrCreateDatabase(name, Context.MODE_PRIVATE,
null);
listOfMaps = new LinkedList<LinkedHashMap<String, String>>();
listOfMaps.add(LocationValues.getAllElements());
myDatabase.execSQL(utilities.GetInfo.generateSqlStatement(
locationTableName, listOfMaps));
}
public boolean insertLocationIntoDb(LocationValues eL) {
ContentValues newValues = new ContentValues();
for (Field f : LocationValues.class.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
String value;
try {
value = f.get(eL).toString();
newValues.put(name, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
}
}
myDatabase.insert(locationTableName, null, newValues);
newValues.clear();
return false;
}
public static LinkedList<LocationValues> getAllLocationsFromDatabase() {
int numberOfElements = LocationValues.class.getDeclaredFields().length;
String[] arrayOfFields = new String[numberOfElements];
int i = 0;
for (Field f : LocationValues.class.getDeclaredFields()) {
f.setAccessible(true);
arrayOfFields[i] = f.getName();
i++;
}
Cursor cursor = myDatabase.query(locationTableName, arrayOfFields,
null, null, null, null, null);
LinkedList<LocationValues> locationList = new LinkedList<LocationValues>();
while (cursor.moveToNext()) {
/*
* LocationValues specific part
*/
long time_ = cursor.getLong(cursor.getColumnIndex("time_"));
int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
double lat_ = cursor.getDouble(cursor.getColumnIndex("lat_"));
double lon_ = cursor.getDouble(cursor.getColumnIndex("lon_"));
double speed_ = cursor.getDouble(cursor.getColumnIndex("speed_"));
double altitude_ = cursor.getDouble(cursor
.getColumnIndex("altitude_"));
double bearing_ = cursor.getDouble(cursor
.getColumnIndex("bearing_"));
double accuracy_ = cursor.getDouble(cursor
.getColumnIndex("accuracy_"));
int satellites_ = cursor.getInt(cursor
.getColumnIndex("satellites_"));
LocationValues lV = new LocationValues(user_id, lat_, lon_, speed_,
altitude_, bearing_, accuracy_, satellites_, time_);
locationList.add(lV);
}
return locationList;
}
public static LinkedList<LocationValues> getLocationsForUploadFromDatabase() {
int numberOfElements = LocationValues.class.getDeclaredFields().length;
String[] arrayOfFields = new String[numberOfElements];
int i = 0;
for (Field f : LocationValues.class.getDeclaredFields()) {
f.setAccessible(true);
arrayOfFields[i] = f.getName();
i++;
}
Cursor cursor = myDatabase.query(locationTableName, arrayOfFields,
"upload=?", new String[] { "FALSE" }, null, null, null);
LinkedList<LocationValues> locationList = new LinkedList<LocationValues>();
while (cursor.moveToNext()) {
/*
* LocationValues specific part
*/
long time_ = cursor.getLong(cursor.getColumnIndex("time_"));
int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
double lat_ = cursor.getDouble(cursor.getColumnIndex("lat_"));
double lon_ = cursor.getDouble(cursor.getColumnIndex("lon_"));
double speed_ = cursor.getDouble(cursor.getColumnIndex("speed_"));
double altitude_ = cursor.getDouble(cursor
.getColumnIndex("altitude_"));
double bearing_ = cursor.getDouble(cursor
.getColumnIndex("bearing_"));
double accuracy_ = cursor.getDouble(cursor
.getColumnIndex("accuracy_"));
int satellites_ = cursor.getInt(cursor
.getColumnIndex("satellites_"));
LocationValues lV = new LocationValues(user_id, lat_, lon_, speed_,
altitude_, bearing_, accuracy_, satellites_, time_);
locationList.add(lV);
}
return locationList;
}
public String getJSONFromLocationsForUploadFromDatabase() {
Gson json = new Gson();
return json.toJson(getLocationsForUploadFromDatabase());
}
public void setUploadToTrue() {
ContentValues values = new ContentValues();
values.put("upload", "TRUE");
myDatabase.update(locationTableName, values, null, null);
}
}
| 31.126582 | 79 | 0.736478 |
3898ea79664084ab495e7faeaf9f9b0deb52fc9a | 3,821 | /*
* This file is part of LanternServer, licensed under the MIT License (MIT).
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.lanternpowered.server.world.rules;
import static com.google.common.base.Preconditions.checkNotNull;
import org.lanternpowered.api.cause.CauseStack;
import org.lanternpowered.server.world.LanternWorld;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.world.ChangeWorldGameRuleEvent;
import java.util.Optional;
import javax.annotation.Nullable;
public final class Rule<T> {
private final RuleType<T> ruleType;
private final Rules rules;
private T value;
Rule(Rules rules, RuleType<T> ruleType) {
this.value = ruleType.getDefaultValue();
this.ruleType = ruleType;
this.rules = rules;
}
/**
* Sets the raw value of this rule, the value will be automatically parsed
* as the required type.
*
* @param value The raw value
* @throws IllegalArgumentException if the parsing failed
*/
public void setRawValue(String value) throws IllegalArgumentException {
setValue0(this.ruleType.getDataType().parse(checkNotNull(value, "value")), value);
}
/**
* Gets the raw value of this rule.
*
* @return The raw value
*/
public String getRawValue() {
return this.ruleType.getDataType().serialize(this.value);
}
/**
* Sets the value of this rule.
*
* @param value The value
*/
public void setValue(T value) {
setValue0(checkNotNull(value, "value"), null);
}
/**
* Gets the value of this rule.
*
* @return The value
*/
public T getValue() {
return this.value;
}
private void setValue0(T newValue, @Nullable String newRawValue) {
final Optional<LanternWorld> optWorld = this.rules.getWorld();
if (optWorld.isPresent() && !newValue.equals(this.value)) {
final LanternWorld world = optWorld.get();
if (newRawValue == null) {
newRawValue = this.ruleType.getDataType().serialize(newValue);
}
final Cause cause = CauseStack.current().getCurrentCause();
final ChangeWorldGameRuleEvent event = SpongeEventFactory.createChangeWorldGameRuleEvent(
cause, getRawValue(), newRawValue, this.ruleType.getName(), world);
if (Sponge.getEventManager().post(event)) {
return;
}
}
this.value = newValue;
}
}
| 35.37963 | 101 | 0.686993 |
164a7c049f3c918c1f9c9f882f17e9d63ec1ff16 | 6,274 | package mams.model.appeal;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import mams.testutil.TypicalAppeals;
public class AppealTest {
@Test
public void isSameAppeal() {
Appeal appealTest1 = TypicalAppeals.APPEAL1;
// same object -> returns true
Assertions.assertTrue(appealTest1.isSameAppeal(appealTest1));
//null -> returns false
Assertions.assertFalse(appealTest1.isSameAppeal(null));
// approved appeal -> returns false
Appeal approveAppeal = new Appeal(appealTest1.getAppealId(),
appealTest1.getAppealType(),
appealTest1.getStudentId(),
appealTest1.getAcademicYear(),
appealTest1.getStudentWorkload(),
appealTest1.getAppealDescription(),
appealTest1.getPreviousModule(),
appealTest1.getNewModule(),
appealTest1.getModuleToAdd(),
appealTest1.getModuleToDrop(),
true,
"approved",
"");
assertFalse(appealTest1.isSameAppeal(approveAppeal));
// rejected appeal -> returns false
Appeal rejectedAppeal = new Appeal(appealTest1.getAppealId(),
appealTest1.getAppealType(),
appealTest1.getStudentId(),
appealTest1.getAcademicYear(),
appealTest1.getStudentWorkload(),
appealTest1.getAppealDescription(),
appealTest1.getPreviousModule(),
appealTest1.getNewModule(),
appealTest1.getModuleToAdd(),
appealTest1.getModuleToDrop(),
true,
"rejected",
"");
assertFalse(appealTest1.isSameAppeal(rejectedAppeal));
}
@Test
public void equals() {
Appeal appealToTest = TypicalAppeals.APPEAL1;
// same object -> returns true
assertTrue(appealToTest.equals(appealToTest));
// null -> returns false
assertFalse(appealToTest.equals(null));
// different type -> return false
assertFalse(appealToTest.equals(5));
// different appeal -> return false
Appeal anotherAppeal = TypicalAppeals.APPEAL2;
assertFalse(appealToTest.equals(anotherAppeal));
// different appealID -> return false
Appeal appealwithDifferentId = new Appeal(TypicalAppeals.APPEAL3.getAppealId(),
appealToTest.getAppealType(),
appealToTest.getStudentId(),
appealToTest.getAcademicYear(),
appealToTest.getStudentWorkload(),
appealToTest.getAppealDescription(),
appealToTest.getPreviousModule(),
appealToTest.getNewModule(),
appealToTest.getModuleToAdd(),
appealToTest.getModuleToDrop(),
false,
"",
"");
assertFalse(appealToTest.equals(appealwithDifferentId));
// different appeal type -> returns false
Appeal appealOfAnotherType = new Appeal(appealToTest.getAppealId(),
TypicalAppeals.APPEAL2.getAppealType(),
appealToTest.getStudentId(),
appealToTest.getAcademicYear(),
appealToTest.getStudentWorkload(),
appealToTest.getAppealDescription(),
appealToTest.getPreviousModule(),
appealToTest.getNewModule(),
appealToTest.getModuleToAdd(),
appealToTest.getModuleToDrop(),
false,
"",
"");
assertFalse(appealToTest.equals(appealOfAnotherType));
// different studentID -> returns false
Appeal appealWithAnotherStudent = new Appeal(appealToTest.getAppealId(),
appealToTest.getAppealType(),
TypicalAppeals.APPEAL3.getStudentId(),
appealToTest.getAcademicYear(),
appealToTest.getStudentWorkload(),
appealToTest.getAppealDescription(),
appealToTest.getPreviousModule(),
appealToTest.getNewModule(),
appealToTest.getModuleToAdd(),
appealToTest.getModuleToDrop(),
false,
"",
"");
assertFalse(appealToTest.equals(appealWithAnotherStudent));
}
@Test void isValidAppealId() {
//invalid code
assertFalse(Appeal.isValidAppealId("")); // empty string
assertFalse(Appeal.isValidAppealId("CS")); // C with another letter only
assertFalse(Appeal.isValidAppealId("C23")); // less than 6 numbers
assertFalse(Appeal.isValidAppealId("C1233333314")); // more than 6 numbers
//valid code
assertTrue(Appeal.isValidAppealId("C000002"));
assertTrue(Appeal.isValidAppealId("C123456"));
assertTrue(Appeal.isValidAppealId("C123232"));
}
@Test void isValidAppealType() {
//invalid code
assertFalse(Appeal.isValidAppealType("")); // empty string
assertFalse(Appeal.isValidAppealType("addmodule")); // no spaces
assertFalse(Appeal.isValidAppealType("drop module")); // more than 1 space
assertFalse(Appeal.isValidAppealType("increase workload2")); // with numbers
//valid code
assertTrue(Appeal.isValidAppealType("add MOdule"));
assertTrue(Appeal.isValidAppealType("DroP mOdUle"));
assertTrue(Appeal.isValidAppealType("INCREASE WORKLOAD"));
}
@Test
public void isEqual() {
assertFalse(Appeal.isValidAppealType("")); // empty string
assertFalse(Appeal.isValidAppealType("addmodule")); // no spaces
assertFalse(Appeal.isValidAppealType("drop module")); // more than 1 space
assertFalse(Appeal.isValidAppealType("increase workload2")); // with numbers
//valid code
assertTrue(Appeal.isValidAppealType("add MOdule"));
assertTrue(Appeal.isValidAppealType("DroP mOdUle"));
assertTrue(Appeal.isValidAppealType("INCREASE WORKLOAD"));
}
}
| 38.256098 | 87 | 0.613165 |
9f290655cad7d3ce649f333812efa4a33bf81332 | 2,238 | package com.spotinst.sdkjava.model.api.mrScaler.aws;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
public class ApiMrScalerAwsEbsConfiguration {
//region Members
@JsonIgnore
private Set<String> isSet;
private Boolean ebsOptimized;
private List<ApiMrScalerAwsEbsBlockDeviceConfig> ebsBlockDeviceConfigs;
// endregion
//region Constructor
public ApiMrScalerAwsEbsConfiguration() {
isSet = new HashSet<>();
}
// endregion
// region methods
// region ebsOptimized
public Boolean getEbsOptimized() { return ebsOptimized; }
public void setEbsOptimized(Boolean ebsOptimized) {
isSet.add("ebsOptimized");
this.ebsOptimized = ebsOptimized;
}
public Boolean isEbsOptimizedSet() { return isSet.contains("ebsOptimized"); }
// endregion
// region ebsBlockDeviceConfigs
public List<ApiMrScalerAwsEbsBlockDeviceConfig> getEbsBlockDeviceConfigs() { return ebsBlockDeviceConfigs; }
public void setEbsBlockDeviceConfigs(List<ApiMrScalerAwsEbsBlockDeviceConfig> ebsBlockDeviceConfigs) {
isSet.add("ebsBlockDeviceConfigs");
this.ebsBlockDeviceConfigs = ebsBlockDeviceConfigs;
}
public Boolean isEbsBlockDeviceConfigsSet() { return isSet.contains("ebsBlockDeviceConfigs"); }
// endregion
// endregion
public static class Builder {
private ApiMrScalerAwsEbsConfiguration ebsConfiguration;
private Builder(){ this.ebsConfiguration = new ApiMrScalerAwsEbsConfiguration(); }
public static Builder get(){
return new Builder();
}
// region build methods
public Builder setEbsOptimized(final Boolean ebsOptimized){
ebsConfiguration.setEbsOptimized(ebsOptimized);
return this;
}
public Builder setEbsBlockDeviceConfigs(final List<ApiMrScalerAwsEbsBlockDeviceConfig> ebsBlockDeviceConfigs){
ebsConfiguration.setEbsBlockDeviceConfigs(ebsBlockDeviceConfigs);
return this;
}
public ApiMrScalerAwsEbsConfiguration build(){
return ebsConfiguration;
}
// endregion
}
}
| 30.657534 | 118 | 0.707328 |
44ce83c51bce3b8ea20ef601f11f4a7b7bd3b282 | 2,324 | package de.keeyzar.tenancyfixer.namespace;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.informers.ResourceEventHandler;
import io.fabric8.kubernetes.client.informers.SharedIndexInformer;
import io.fabric8.kubernetes.client.informers.SharedInformerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.function.Consumer;
/**
* watches namespace creation
*/
@ApplicationScoped
public class NamespaceWatcher {
private static final Logger log = LoggerFactory.getLogger(IstioController.class);
private final KubernetesClient kubernetesClient;
@Inject
public NamespaceWatcher(KubernetesClient kubernetesClient) {
this.kubernetesClient = kubernetesClient;
}
public void registerNamespaceListener(Type operationType, Consumer<Namespace> listener){
SharedInformerFactory informers = kubernetesClient.informers();
SharedIndexInformer<Namespace> namespaceSharedIndexInformer =
informers.sharedIndexInformerFor(Namespace.class, NamespaceList.class, 1000);
namespaceSharedIndexInformer.addEventHandler(new ResourceEventHandler<>() {
@Override
public void onAdd(Namespace addedNamespace) {
log.info("new namespace: {} registered operation: {}", addedNamespace.getMetadata().getName(), operationType);
if(Type.CREATE == operationType)
listener.accept(addedNamespace);
}
@Override
public void onUpdate(Namespace oldObj, Namespace newObj) {
//don't do anything
}
@Override
public void onDelete(Namespace deletedNamespace, boolean deletedFinalStateUnknown) {
log.info("deleted namespace: {} registered operation: {}", deletedNamespace.getMetadata().getName(), operationType);
if(Type.DELETE == operationType)
listener.accept(deletedNamespace);
}
});
informers.startAllRegisteredInformers();
}
public enum Type{
CREATE,
DELETE
}
}
| 37.483871 | 132 | 0.703528 |
f8be7e5757dce7d44b837f7019579174cf2de71a | 5,734 | package frontend.pascal.parsers;
import frontend.EofToken;
import frontend.Token;
import frontend.TokenType;
import frontend.pascal.PascalErrorCode;
import frontend.pascal.PascalParserTD;
import frontend.pascal.PascalTokenType;
import intermediate.Definition;
import intermediate.ICodeFactory;
import intermediate.ICodeNode;
import intermediate.SymbolTableEntry;
import intermediate.symtabimpl.DefinitionImpl;
import java.util.EnumSet;
import static frontend.pascal.PascalErrorCode.MISSING_SEMICOLON;
import static frontend.pascal.PascalErrorCode.UNEXPECTED_TOKEN;
import static frontend.pascal.PascalTokenType.*;
import static intermediate.icodeimpl.ICodeKeyImpl.LINE;
import static intermediate.icodeimpl.ICodeNodeTypeImpl.NO_OP;
import static intermediate.symtabimpl.DefinitionImpl.UNDEFINED;
public class StatementParser extends PascalParserTD {
// Synchronization set for starting a statement.
protected static final EnumSet<PascalTokenType> STMT_START_SET =
EnumSet.of(BEGIN, CASE, FOR, PascalTokenType.IF, REPEAT, WHILE,
IDENTIFIER, SEMICOLON);
// Synchronization set for following a statement.
protected static final EnumSet<PascalTokenType> STMT_FOLLOW_SET = EnumSet.of(SEMICOLON, END, ELSE, UNTIL, DOT);
public StatementParser(PascalParserTD parent) {
super(parent);
}
public ICodeNode parse(Token token) throws Exception {
ICodeNode statementNode = null;
switch ((PascalTokenType) token.getType()) {
case BEGIN: {
CompoundStatementParser compoundParser = new CompoundStatementParser(this);
statementNode = compoundParser.parse(token);
break;
}
case IDENTIFIER: {
String name = token.getText().toLowerCase();
SymbolTableEntry id = symbolTableStack.lookup(name);
Definition idDefinition = id != null
? id.getDefinition()
: UNDEFINED;
// Assignment statement or procedure call
switch ((DefinitionImpl) idDefinition) {
case VARIABLE:
case VALUE_PARM:
case VAR_PARM:
case UNDEFINED: {
AssignmentStatementParser assignmentParser = new AssignmentStatementParser(this);
statementNode = assignmentParser.parse(token);
break;
}
case FUNCTION: {
AssignmentStatementParser assignmentParser = new AssignmentStatementParser(this);
statementNode = assignmentParser.parseFunctionNameAssignment(token);
break;
}
case PROCEDURE: {
CallParser callParser = new CallParser(this);
statementNode = callParser.parse(token);
break;
}
default: {
errorHandler.flag(token, UNEXPECTED_TOKEN, this);
// consume identifier
token = nextToken();
}
}
break;
}
case REPEAT: {
RepeatStatementParser repeatParser = new RepeatStatementParser(this);
statementNode = repeatParser.parse(token);
break;
}
case WHILE: {
WhileStatementParser whileParser = new WhileStatementParser(this);
statementNode = whileParser.parse(token);
break;
}
case FOR: {
ForStatementParser forParser = new ForStatementParser(this);
statementNode = forParser.parse(token);
break;
}
case IF: {
IfStatementParser ifParser = new IfStatementParser(this);
statementNode = ifParser.parse(token);
break;
}
case CASE: {
CaseStatementParser caseParser = new CaseStatementParser(this);
statementNode = caseParser.parse(token);
break;
}
default: {
statementNode = ICodeFactory.createICodeNode(NO_OP);
break;
}
}
setLineNumber(statementNode, token);
return statementNode;
}
protected void parseList(Token token, ICodeNode parentNode,
PascalTokenType terminator, PascalErrorCode errorCode)
throws Exception {
EnumSet<PascalTokenType> terminatorSet = STMT_START_SET.clone();
terminatorSet.add(terminator);
while (!(token instanceof EofToken)
&& (token.getType() != terminator)) {
ICodeNode statementNode = parse(token);
parentNode.addChild(statementNode);
token = currentToken();
TokenType tokenType = token.getType();
if(tokenType == SEMICOLON) {
token = nextToken();
}
else if(STMT_START_SET.contains(tokenType)) {
errorHandler.flag(token, MISSING_SEMICOLON, this);
}
token = synchronize(terminatorSet);
}
if(token.getType() == terminator) {
token = nextToken();
}else {
errorHandler.flag(token, errorCode, this);
}
}
protected void setLineNumber(ICodeNode node, Token token) {
if (node != null) {
node.setAttribute(LINE, token.getLineNumber());
}
}
}
| 36.75641 | 115 | 0.573945 |
095678fdd21a11fce7b3b296c77d4e23c60630b2 | 1,468 | package org.stagemonitor.eum;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.stagemonitor.web.servlet.util.ServletContainerInitializerUtil;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@SpringBootApplication
@Configuration
public class EumApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(EumApplication.class);
}
@Component
public static class StagemonitorInitializer implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// necessary for spring boot 2.0.0.M2 until stagemonitor supports it natively
ServletContainerInitializerUtil.registerStagemonitorServletContainerInitializers(servletContext);
}
}
}
| 34.952381 | 100 | 0.848774 |
c91f828c2e5a4f7300bef08b61d12aa5fe537dbf | 244 | package com.couplingfire.publisher;
import com.couplingfire.event.MicroModuleEvent;
public interface MicroModuleEventPublisher {
void publishEvent(MicroModuleEvent e);
void publishEvent(String microModuleName, MicroModuleEvent e);
}
| 24.4 | 66 | 0.819672 |
e9886356d2a13122bd580e5072f833bc4e4367ec | 3,558 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.model.validation.validators;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.pattern.UriPattern;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.traits.HttpTrait;
import software.amazon.smithy.model.traits.Trait;
import software.amazon.smithy.model.validation.AbstractValidator;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.utils.OptionalUtils;
import software.amazon.smithy.utils.Pair;
/**
* Validates that no two URIs in a service conflict with each other.
*/
public final class HttpUriConflictValidator extends AbstractValidator {
@Override
public List<ValidationEvent> validate(Model model) {
TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class);
return model.getShapeIndex().shapes(ServiceShape.class)
.flatMap(shape -> validateService(topDownIndex, shape).stream())
.collect(Collectors.toList());
}
private List<ValidationEvent> validateService(TopDownIndex topDownIndex, ServiceShape service) {
List<OperationShape> operations = topDownIndex.getContainedOperations(service)
.stream()
.filter(shape -> shape.getTrait(HttpTrait.class).isPresent())
.collect(Collectors.toList());
return operations.stream()
.flatMap(shape -> Trait.flatMapStream(shape, HttpTrait.class))
.flatMap(pair -> OptionalUtils.stream(checkConflicts(pair, operations)))
.collect(Collectors.toList());
}
private Optional<ValidationEvent> checkConflicts(
Pair<OperationShape, HttpTrait> pair,
List<OperationShape> operations
) {
OperationShape operation = pair.getLeft();
String method = pair.getRight().getMethod();
UriPattern pattern = pair.getRight().getUri();
String conflicts = operations.stream()
.filter(shape -> shape != operation)
.flatMap(shape -> Trait.flatMapStream(shape, HttpTrait.class))
.filter(other -> other.getRight().getMethod().equals(method))
.filter(other -> other.getRight().getUri().conflictsWith(pattern))
.map(other -> String.format("`%s` (%s)", other.getLeft().getId(), other.getRight().getUri()))
.sorted()
.collect(Collectors.joining(", "));
if (conflicts.isEmpty()) {
return Optional.empty();
}
return Optional.of(error(operation, String.format(
"Operation URI, `%s`, conflicts with other operation URIs in the same service: [%s]",
pattern, conflicts)));
}
}
| 43.390244 | 109 | 0.685779 |
90642e5debfc392075e60dd1a267e87daf60793c | 2,021 | package eas.com.model;
import eas.com.exception.QuickMartException;
import java.util.HashMap;
import java.util.Map;
/**
* Class for simulating the inventory of item
*
* Created by eduardo on 12/12/2016.
*/
public class Inventory {
/**
* Key: Name of Item
* Value: Relation Item-Quantity @see {@link ItemQuantity}
*/
private Map<String, ItemQuantity> inventoryItemMap;
public Inventory() {
this.inventoryItemMap = new HashMap<>();
}
/**
* Remove a quantity of item from inventory
*
* @param nameItem name of item
* @param quantity count of items
* @return ItemQuantity
* @throws QuickMartException if do not exist the item or the quantity is not enough
*/
public ItemQuantity removeItemQuantity(String nameItem, int quantity) throws QuickMartException {
ItemQuantity inventoryItem;
if ((inventoryItem = this.inventoryItemMap.get(nameItem)) == null) {
throw new QuickMartException("There is not the item: " + nameItem + " in the inventory");
}
ItemQuantity itemQuantityDecrement = inventoryItem.decrease(quantity);
if (inventoryItem.isItemSoldOut())
this.inventoryItemMap.remove(nameItem);
return itemQuantityDecrement;
}
/**
* Add item quantity
*
* @param itemQuantity to save in the inventory
*/
public void addItemQuantity(ItemQuantity itemQuantity) {
if (this.inventoryItemMap.containsKey(itemQuantity.getItem().getName())) {
this.inventoryItemMap.get(itemQuantity.getItem().getName()).increase(itemQuantity);
} else {
this.inventoryItemMap.put(itemQuantity.getItem().getName(), itemQuantity);
}
}
/**
* @return true is the inventory is empty, false otherwise
*/
public boolean isEmpty() {
return this.inventoryItemMap.isEmpty();
}
public Map<String, ItemQuantity> getInventoryItemMap() {
return inventoryItemMap;
}
}
| 28.069444 | 101 | 0.656111 |
6d3e1e780c4c6f9330cd86b34e811109f465609b | 23,503 | package org.checkerframework.qualframework.base;
import org.checkerframework.framework.qual.SubtypeOf;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedUnionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.framework.util.AnnotationBuilder;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedArrayType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedDeclaredType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedExecutableType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedIntersectionType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedNoType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedNullType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedParameterDeclaration;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedPrimitiveType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedTypeDeclaration;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedTypeVariable;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedUnionType;
import org.checkerframework.qualframework.base.QualifiedTypeMirror.QualifiedWildcardType;
import org.checkerframework.qualframework.util.WrappedAnnotatedTypeMirror;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeKind;
/**
* Helper class used by adapters to convert between {@link QualifiedTypeMirror}
* and {@link AnnotatedTypeMirror}.
*
* Only adapters should ever have a reference to this class. All adapters for
* a single type system must use the same {@link TypeMirrorConverter} instance,
* since converting from {@link QualifiedTypeMirror} to {@link
* AnnotatedTypeMirror} and back will fail if the two conversion steps are
* performed with different instances.
*/
/* This class uses a lookup table and a special annotation '@Key' to encode
* qualifiers as annotations. Each '@Key' annotation contains a single index,
* which is a key into the lookup table indicating a particular qualifier.
*/
public class TypeMirrorConverter<Q> {
/** The checker adapter, used for lazy initialization of {@link
* typeFactory}. */
private final CheckerAdapter<Q> checkerAdapter;
/** Annotation processing environment, used to construct new {@link Key}
* {@link AnnotationMirror}s. */
private final ProcessingEnvironment processingEnv;
/** The {@link Element} corresponding to the {@link Key#index()} field. */
private final ExecutableElement indexElement;
/** A {@link Key} annotation with no <code>index</code> set. */
private final AnnotationMirror blankKey;
/** The type factory adapter, used to construct {@link
* AnnotatedTypeMirror}s. */
private QualifiedTypeFactoryAdapter<Q> typeFactory;
/** The next unused index in the lookup table. */
private int nextIndex = 0;
/** The qualifier-to-index half of the lookup table. This lets us ensure
* that the same qualifier maps to the same <code>@Key</code> annotation.
*/
private final HashMap<Q, Integer> qualToIndex;
/** The index-to-qualifier half of the lookup table. This is used for
* annotated-to-qualified conversions. */
private final HashMap<Integer, Q> indexToQual;
/** Cache @Key annotation mirrors so they are not to be recreated on every conversion */
public LinkedHashMap<Integer, AnnotationMirror> keyToAnnoCache =
new LinkedHashMap<Integer, AnnotationMirror>(10, .75f, true) {
private static final long serialVersionUID = 1L;
private static final int MAX_SIZE = 1000;
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, AnnotationMirror> eldest) {
return size() > MAX_SIZE;
}
};
@SubtypeOf({})
public static @interface Key {
/** An index into the lookup table. */
int index() default -1;
/** A string representation of the qualifier this {@link Key}
* represents. This lets us have slightly nicer error messages. */
String desc() default "";
}
public TypeMirrorConverter(
ProcessingEnvironment processingEnv, CheckerAdapter<Q> checkerAdapter) {
this.checkerAdapter = checkerAdapter;
this.processingEnv = processingEnv;
this.indexElement =
TreeUtils.getMethod(Key.class.getCanonicalName(), "index", 0, processingEnv);
this.blankKey = AnnotationUtils.fromClass(processingEnv.getElementUtils(), Key.class);
// typeFactory will be lazily initialized, to break a circular
// dependency between this class and QualifiedTypeFactoryAdapter.
this.typeFactory = null;
this.qualToIndex = new HashMap<>();
this.indexToQual = new HashMap<>();
}
/** Returns the type factory to use for building {@link
* AnnotatedTypeMirror}s, running lazy initialization if necessary. */
private QualifiedTypeFactoryAdapter<Q> getTypeFactory() {
if (typeFactory == null) {
typeFactory = checkerAdapter.getTypeFactory();
}
return typeFactory;
}
/** Constructs a new {@link Key} annotation with the provided index, using
* <code>desc.toString()</code> to set the {@link Key#desc()} field. */
private AnnotationMirror createKey(int index, Object desc) {
if (keyToAnnoCache.containsKey(index)) {
return keyToAnnoCache.get(index);
} else {
AnnotationBuilder builder =
new AnnotationBuilder(processingEnv, Key.class.getCanonicalName());
builder.setValue("index", index);
builder.setValue("desc", "" + desc);
AnnotationMirror result = builder.build();
keyToAnnoCache.put(index, result);
return result;
}
}
/** Returns the index that represents <code>qual</code>. If
* <code>qual</code> has not been assigned an index yet, a new index will
* be generated and assigned to it.
*/
private int getIndexForQualifier(Q qual) {
if (qualToIndex.containsKey(qual)) {
return qualToIndex.get(qual);
} else {
int index = nextIndex++;
qualToIndex.put(qual, index);
indexToQual.put(index, qual);
return index;
}
}
/** Returns the <code>index</code> field of a {@link Key} {@link
* AnnotationMirror}. */
private int getIndex(AnnotationMirror anno) {
return getAnnotationField(anno, indexElement);
}
/** Helper function to obtain an integer field value from an {@link
* AnnotationMirror}. */
private int getAnnotationField(AnnotationMirror anno, ExecutableElement element) {
AnnotationValue value = anno.getElementValues().get(element);
if (value == null) {
throw new IllegalArgumentException("@Key annotation contains no " + element);
}
assert (value.getValue() instanceof Integer);
Integer index = (Integer) value.getValue();
return index;
}
/* QTM -> ATM conversion functions */
/** Given a QualifiedTypeMirror and an AnnotatedTypeMirror with the same
* underlying TypeMirror, recursively update annotations on the
* AnnotatedTypeMirror to match the qualifiers present on the
* QualifiedTypeMirror. After running applyQualifiers, calling
* getQualifiedType on the AnnotatedTypeMirror should produce a
* QualifiedTypeMirror which is identical to the one initially passed to
* applyQualifiers.
*/
public void applyQualifiers(QualifiedTypeMirror<Q> qtm, AnnotatedTypeMirror atm) {
if (qtm == null && atm == null) {
return;
}
assert qtm != null && atm != null;
atm.clearAnnotations();
// Only add the qualifier if it is not null,
// and the original underlying ATV had a primary annotation.
if (qtm.getQualifier() != null
&& (qtm.getKind() != TypeKind.TYPEVAR
|| ((QualifiedTypeVariable<Q>) qtm).isPrimaryQualifierValid())) {
// Apply the qualifier for this QTM-ATM pair.
int index = getIndexForQualifier(qtm.getQualifier());
AnnotationMirror key = createKey(index, qtm.getQualifier());
atm.addAnnotation(key);
}
// Recursively create entries for all component QTM-ATM pairs.
APPLY_COMPONENT_QUALIFIERS_VISITOR.visit(qtm, atm);
}
/** Given a QualifiedTypeMirror, produce an AnnotatedTypeMirror with the
* same underlying TypeMirror and with annotations corresponding to the
* qualifiers on the input QualifiedTypeMirror. As with applyQualifiers,
* calling getQualifiedType on the resulting AnnotatedTypeMirror should
* produce a QualifiedTypeMirror that is identical to the one passed as
* input.
*/
public AnnotatedTypeMirror getAnnotatedType(QualifiedTypeMirror<Q> qtm) {
if (qtm == null) {
return null;
}
AnnotatedTypeMirror atm;
if (qtm.getUnderlyingType() instanceof WrappedAnnotatedTypeMirror) {
atm = ((WrappedAnnotatedTypeMirror) qtm.getUnderlyingType()).unwrap().deepCopy();
} else {
atm =
AnnotatedTypeMirror.createType(
qtm.getUnderlyingType().getOriginalType(),
getTypeFactory(),
qtm.getUnderlyingType().isDeclaration());
}
applyQualifiers(qtm, atm);
return atm;
}
public List<AnnotatedTypeMirror> getAnnotatedTypeList(
List<? extends QualifiedTypeMirror<Q>> qtms) {
if (qtms == null) {
return null;
}
List<AnnotatedTypeMirror> atms = new ArrayList<AnnotatedTypeMirror>();
for (QualifiedTypeMirror<Q> qtm : qtms) {
atms.add(getAnnotatedType(qtm));
}
return atms;
}
/** applyQualifiers lifted to operate on lists of augmented TypeMirrors.
*/
private void applyQualifiersToLists(
List<? extends QualifiedTypeMirror<Q>> qtms, List<? extends AnnotatedTypeMirror> atms) {
assert (qtms.size() == atms.size());
for (int i = 0; i < qtms.size(); ++i) {
applyQualifiers(qtms.get(i), atms.get(i));
}
}
/** A visitor to recursively applyQualifiers to components of the
* TypeMirrors.
*
* This also has some special handling for ExecutableTypes. Both
* AnnotatedTypeMirror and ExtendedTypeMirror (the underlying types used by
* QualifiedTypeMirror) track the corresponding ExecutableElement (unlike
* raw javac TypeMirrors), and this visitor updates that element if
* necessary to make the augmented TypeMirrors correspond.
*/
private final SimpleQualifiedTypeVisitor<Q, Void, AnnotatedTypeMirror>
APPLY_COMPONENT_QUALIFIERS_VISITOR =
new SimpleQualifiedTypeVisitor<Q, Void, AnnotatedTypeMirror>() {
private final IdentityHashMap<AnnotatedTypeMirror, Void> seenATVs =
new IdentityHashMap<>();
@Override
public Void visitArray(
QualifiedArrayType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedArrayType atm = (AnnotatedArrayType) rawAtm;
applyQualifiers(qtm.getComponentType(), atm.getComponentType());
return null;
}
@Override
public Void visitDeclared(
QualifiedDeclaredType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedDeclaredType atm = (AnnotatedDeclaredType) rawAtm;
applyQualifiersToLists(qtm.getTypeArguments(), atm.getTypeArguments());
return null;
}
@Override
public Void visitExecutable(
QualifiedExecutableType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedExecutableType atm = (AnnotatedExecutableType) rawAtm;
// Update the ExecutableElement if necessary. This should
// happen before the recursive applyQualifiers calls, since it
// may cause the receiver and return types of the ATM to become
// non-null.
ExecutableElement elt = qtm.getUnderlyingType().asElement();
if (atm.getElement() != elt) {
assert elt != null;
atm.setElement(elt);
}
applyQualifiersToLists(
qtm.getParameterTypes(), atm.getParameterTypes());
applyQualifiers(qtm.getReceiverType(), atm.getReceiverType());
applyQualifiers(qtm.getReturnType(), atm.getReturnType());
applyQualifiersToLists(qtm.getThrownTypes(), atm.getThrownTypes());
applyQualifiersToLists(qtm.getTypeParameters(), atm.getTypeVariables());
return null;
}
@Override
public Void visitIntersection(
QualifiedIntersectionType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedIntersectionType atm = (AnnotatedIntersectionType) rawAtm;
applyQualifiersToLists(qtm.getBounds(), atm.directSuperTypes());
return null;
}
@Override
public Void visitNoType(
QualifiedNoType<Q> qtm, AnnotatedTypeMirror rawAtm) {
// NoType has no components.
return null;
}
@Override
public Void visitNull(
QualifiedNullType<Q> qtm, AnnotatedTypeMirror rawAtm) {
// NullType has no components.
return null;
}
@Override
public Void visitPrimitive(
QualifiedPrimitiveType<Q> qtm, AnnotatedTypeMirror rawAtm) {
// PrimitiveType has no components.
return null;
}
@Override
public Void visitTypeVariable(
QualifiedTypeVariable<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedTypeVariable atm = (AnnotatedTypeVariable) rawAtm;
typeVariableHelper(qtm.getDeclaration(), atm);
return null;
}
@Override
public Void visitUnion(
QualifiedUnionType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedUnionType atm = (AnnotatedUnionType) rawAtm;
applyQualifiersToLists(qtm.getAlternatives(), atm.getAlternatives());
return null;
}
@Override
public Void visitWildcard(
QualifiedWildcardType<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedWildcardType atm = (AnnotatedWildcardType) rawAtm;
applyQualifiers(qtm.getExtendsBound(), atm.getExtendsBound());
applyQualifiers(qtm.getSuperBound(), atm.getSuperBound());
return null;
}
private void typeVariableHelper(
QualifiedParameterDeclaration<Q> qtm, AnnotatedTypeVariable atm) {
if (!seenATVs.containsKey(atm)) {
seenATVs.put(atm, null);
QualifiedTypeParameterBounds<Q> bounds =
getTypeFactory()
.getUnderlying()
.getQualifiedTypeParameterBounds(
qtm.getUnderlyingType());
try {
applyQualifiers(bounds.getUpperBound(), atm.getUpperBound());
applyQualifiers(bounds.getLowerBound(), atm.getLowerBound());
} finally {
seenATVs.remove(atm);
}
}
}
@Override
public Void visitParameterDeclaration(
QualifiedParameterDeclaration<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedTypeVariable atm = (AnnotatedTypeVariable) rawAtm;
typeVariableHelper(qtm, atm);
return null;
}
@Override
public Void visitTypeDeclaration(
QualifiedTypeDeclaration<Q> qtm, AnnotatedTypeMirror rawAtm) {
AnnotatedDeclaredType atm = (AnnotatedDeclaredType) rawAtm;
applyQualifiersToLists(qtm.getTypeParameters(), atm.getTypeArguments());
return null;
}
};
/* ATM -> QTM conversion functions */
/** Given an AnnotatedTypeMirror, construct a QualifiedTypeMirror with the
* same underlying type with the qualifiers extracted from the
* AnnotatedTypeMirror's @Key annotations.
*/
public QualifiedTypeMirror<Q> getQualifiedType(AnnotatedTypeMirror atm) {
if (atm == null) {
return null;
}
return getQualifiedTypeFromWrapped(WrappedAnnotatedTypeMirror.wrap(atm));
}
public List<QualifiedTypeMirror<Q>> getQualifiedTypeList(
List<? extends AnnotatedTypeMirror> atms) {
if (atms == null) {
return null;
}
List<QualifiedTypeMirror<Q>> qtms = new ArrayList<>();
for (AnnotatedTypeMirror atm : atms) {
qtms.add(getQualifiedType(atm));
}
return qtms;
}
private QualifiedTypeMirror<Q> getQualifiedTypeFromWrapped(WrappedAnnotatedTypeMirror watm) {
if (watm == null) {
return null;
}
// FIXME: This is a total hack to work around a particularly nasty
// aspect of the framework's AnnotatedTypeVariable handling.
//
// Consider:
// class C<T> {
// class D<U extends T> { }
// }
//
// When processing the declaration of `U`, the underlying
// AnnotatedTypeMirror initially has no @Key annotations. During
// processing, TypeMirrorConverter will request the qualified
// bounds of `U`. This leads to a call chain: ATV.getLowerBound ->
// fixupBoundAnnotations -> getUpperBound().getEffectiveAnnotations() ->
// getEffectiveUpperBound(). This results in calling substitute (and
// therefore postTypeVarSubstitution) on the upper bound, which
// currently has no annotations. So the ATM -> QTM conversion fails
// ("can't create QTM with null qualifier"). Using TypeAnnotator
// instead of UPDATED_QTM_BUILDER is not a great solution (since we end
// up running TypeAnnotator on the same type more than once) but it does
// work around this issue.
//
// TODO: This also works around the problem of capture-converted
// wildcards starting out with no top-level annotation. This is another
// one we should fix properly instead of hacking around.
DefaultQualifiedTypeFactory<Q> defaultFactory =
(DefaultQualifiedTypeFactory<Q>) getTypeFactory().getUnderlying();
return watm.accept(defaultFactory.getTypeAnnotator(), null);
// UPDATED_QTM_BUILDER was deleted in the same commit that added the
// workaround.
// return watm.accept(UPDATED_QTM_BUILDER, getQualifier(watm.unwrap()));
}
/* Conversion functions between qualifiers and @Key AnnotationMirrors */
/** Get the qualifier corresponding to a Key annotation.
*/
public Q getQualifier(AnnotationMirror anno) {
if (anno == null) {
return null;
}
int index = getIndex(anno);
return indexToQual.get(index);
}
/** Get the qualifier corresponding to the Key annotation present on an
* AnnotatedTypeMirror, or null if no such annotation exists.
*/
public Q getQualifier(AnnotatedTypeMirror atm) {
return getQualifier(atm.getAnnotation(Key.class));
}
/** Get an AnnotationMirror for a Key annotation encoding the specified
* qualifier.
*/
public AnnotationMirror getAnnotation(Q qual) {
return createKey(getIndexForQualifier(qual), qual);
}
/* Miscellaneous utility functions */
/** Check if an AnnotationMirror is a valid Key annotation.
*/
public boolean isKey(AnnotationMirror anno) {
// TODO: This should probably also check that 'anno' has a value in its
// 'index' field.
return anno != null && blankKey.getAnnotationType().equals(anno.getAnnotationType());
}
/** Get a Key annotation containing no index.
*/
public AnnotationMirror getBlankKeyAnnotation() {
return blankKey;
}
}
| 46.265748 | 100 | 0.609071 |
c2e08aa26e2385ec4f788bea51c4176a0396f6a0 | 2,785 | /*
* Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. 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, 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 io.hops.hopsworks.apiV2.users;
import io.hops.hopsworks.apiV2.filter.AllowedProjectRoles;
import io.hops.hopsworks.common.dao.user.UserFacade;
import io.hops.hopsworks.common.dao.user.Users;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.util.ArrayList;
import java.util.List;
@Path("/users")
@RolesAllowed({"HOPS_ADMIN", "HOPS_USER"})
@Api(value = "Users", description = "Users Resource")
@Stateless
@TransactionAttribute(TransactionAttributeType.NEVER)
public class UsersResource {
@EJB
private UserFacade userBean;
@ApiOperation("Get a list of users in the cluster")
@GET
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({AllowedProjectRoles.ANYONE})
public Response findAll(@Context SecurityContext sc) {
List<Users> users = userBean.findAllUsers();
List<UserView> userViews = new ArrayList<>();
for (Users user : users) {
UserView userView = new UserView(user);
userViews.add(userView);
}
GenericEntity<List<UserView>> result = new GenericEntity<List<UserView>>(userViews) {};
return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build();
}
}
| 39.785714 | 98 | 0.766248 |
aafd4f7c4f7902308ebbfbce8457cdcf359f83f2 | 5,946 | package com.bx.philosopher.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bx.philosopher.R;
import com.bx.philosopher.base.activity.BaseActivity;
import com.bx.philosopher.base.activity.BaseContract;
import com.bx.philosopher.base.adapter.BaseListAdapter;
import com.bx.philosopher.model.bean.response.BaseResponse;
import com.bx.philosopher.model.bean.response.SubscribeBean;
import com.bx.philosopher.net.BaseObserver;
import com.bx.philosopher.net.HttpUtil;
import com.bx.philosopher.net.RxScheduler;
import com.bx.philosopher.ui.adapter.BookCatalogAdapter;
import com.bx.philosopher.utils.ToastUtils;
import com.bx.philosopher.utils.login.LoginUtil;
import java.util.List;
import butterknife.BindView;
public class BookCatalogActivity extends BaseActivity implements BaseContract.BaseView {
@BindView(R.id.book_catalog_list)
RecyclerView book_catalog_lis;
@BindView(R.id.container)
LinearLayout container;
private BookCatalogAdapter bookCatalogAdapter;
private int bookId;
private String from_type;
private String bookName;
private boolean hadPay;
private SubscribeBean subscribeBean;
@Override
protected int getContentId() {
return R.layout.activity_book_catalog;
}
@Override
protected void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
bookId = getIntent().getIntExtra("bookId", -1);
from_type = getIntent().getStringExtra("from_type");
bookName = getIntent().getStringExtra("bookName");
}
public static void startActivity(Context context, int bookId, String from_type, String bookName) {
Intent intent = new Intent(context, BookCatalogActivity.class);
intent.putExtra("bookId", bookId);
intent.putExtra("from_type", from_type);
intent.putExtra("bookName", bookName);
context.startActivity(intent);
}
@Override
protected void initWidget() {
super.initWidget();
book_catalog_lis.setLayoutManager(new LinearLayoutManager(this));
bookCatalogAdapter = new BookCatalogAdapter();
book_catalog_lis.setAdapter(bookCatalogAdapter);
getData();
bookCatalogAdapter.setOnItemClickListener((view, pos) -> {
if (from_type.equals(BookDetailActivity.TYPE_EXPLORE)) {
if (hadPay) {
ReadingActivity.startActivity(BookCatalogActivity.this, bookId, from_type, bookName, bookCatalogAdapter.getItem(pos));
} else {
ToastUtils.show("Please buy this book first");
}
} else {
if (subscribeBean != null) {
if (subscribeBean.getVip_status() == 1) {
ToastUtils.show("Please buy this book first");
} else {
ReadingActivity.startActivity(BookCatalogActivity.this, bookId, from_type, bookName, bookCatalogAdapter.getItem(pos));
}
}
}
});
}
private void getData() {
if (bookId != -1) {
switch (from_type) {
case BookDetailActivity.TYPE_EXPLORE:
HttpUtil.getInstance().getRequestApi().getExploreBookDetailCatalog(LoginUtil.getUserId(),bookId)
.compose(RxScheduler.Obs_io_main())
.subscribe(new BaseObserver<BaseResponse<List<String>>>(this) {
@Override
public void onSuccess(BaseResponse<List<String>> o) {
List<String> catalogs = o.getData().subList(2, o.getData().size() - 1);
hadPay = o.getData().get(o.getData().size() - 1).equals("1");
bookCatalogAdapter.addItems(catalogs);
}
@Override
public void onError(String msg) {
}
});
break;
case BookDetailActivity.TYPE_LIBRARY:
getSubscribeInfo();
HttpUtil.getInstance().getRequestApi().getLibraryBookCatelog(bookId)
.compose(RxScheduler.Obs_io_main())
.subscribe(new BaseObserver<BaseResponse<List<String>>>(this) {
@Override
public void onSuccess(BaseResponse<List<String>> o) {
List<String> catalogs = o.getData().subList(2, o.getData().size());
bookCatalogAdapter.addItems(catalogs);
}
@Override
public void onError(String msg) {
}
});
break;
}
}
}
@Override
public void showError(String msg) {
}
@Override
public void complete() {
}
private void getSubscribeInfo() {
HttpUtil.getInstance().getRequestApi().getSubscribeInfo(LoginUtil.getUserId())
.compose(RxScheduler.Obs_io_main())
.subscribe(new BaseObserver<BaseResponse<SubscribeBean>>(this) {
@Override
public void onSuccess(BaseResponse<SubscribeBean> o) {
subscribeBean = o.getData();
}
@Override
public void onError(String msg) {
}
});
}
}
| 36.036364 | 142 | 0.574504 |
9637967e888255908dc379e2bb9c009f36536f88 | 1,103 | package co.s4n.corrientazos.domain.route;
import co.s4n.corrientazos.domain.drone.IDrone;
import java.util.HashMap;
import java.util.Map;
public enum RouteStep {
AHEAD("A") {
@Override
public void executeStep(IDrone drone) {
drone.continueAHead();
}
}, LEFT("I") {
@Override
public void executeStep(IDrone drone) {
drone.turnLeft();
}
}, RIGHT("D") {
@Override
public void executeStep(IDrone drone) {
drone.turnRight();
}
}, NONE("NONE") {
@Override
public void executeStep(IDrone drone) {
}
};
private static final Map<String, RouteStep> BY_LABEL = new HashMap<>();
static {
for (RouteStep e: values()) {
BY_LABEL.put(e.value, e);
}
}
private String value;
private RouteStep(String value) {
this.value = value;
}
public abstract void executeStep(IDrone drone);
public static RouteStep valueOfLabel(String label) {
return BY_LABEL.getOrDefault(label, NONE);
}
}
| 22.06 | 75 | 0.577516 |
117ea6bf8e7b104b7364404978c0cd6647a6ae63 | 6,476 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.j2cl.java.io.string;
import org.junit.jupiter.api.Test;
import walkingkooka.collect.list.Lists;
import walkingkooka.reflect.JavaVisibility;
import walkingkooka.reflect.PublicStaticHelperTesting;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
public final class StringDataInputDataOutputTest implements PublicStaticHelperTesting<StringDataInputDataOutput> {
@Test
public void testWriteByteReadByte() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<Byte> written = Lists.array();
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
final byte v = (byte) i;
out.writeByte(v);
written.add(v);
}
final List<Byte> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
read.add(input.readByte());
}
this.checkEquals(written, read);
}
@Test
public void testWriteShortReadShort() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<Short> written = Lists.array();
for (int i = Short.MIN_VALUE; i <= Short.MAX_VALUE; i++) {
final short v = (short) i;
out.writeShort(v);
written.add(v);
}
final List<Short> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (int i = Short.MIN_VALUE; i <= Short.MAX_VALUE; i++) {
read.add(input.readShort());
}
this.checkEquals(written, read);
}
@Test
public void testWriteIntReadInt() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<Integer> written = Lists.array();
for (long i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i+= Short.MAX_VALUE) {
final int v = (int)i;
out.writeInt(v);
written.add(v);
}
final List<Integer> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (long i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i+= Short.MAX_VALUE) {
read.add(input.readInt());
}
this.checkEquals(written, read);
}
@Test
public void testWriteCharReadChar() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<Character> written = Lists.array();
for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++) {
final char v = (char) i;
out.writeChar(v);
written.add(v);
}
final List<Character> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++) {
read.add(input.readChar());
}
this.checkEquals(written, read);
}
@Test
public void testWriteStringReadString() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<String> written = Lists.array();
for (int i = 'a'; i <= 'z'; i++) {
final String s = Character.valueOf((char) i).toString();
out.writeUTF(s);
written.add(s);
}
final List<String> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (int i = 'a'; i <= 'z'; i++) {
read.add(input.readUTF());
}
this.checkEquals(written.toString(), read.toString());
}
@Test
public void testWriteStringReadString2() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
final List<String> written = Lists.array();
for (int i = Character.MIN_VALUE; i <= 'z'; i++) {
final String s = Character.valueOf((char) i).toString();
out.writeUTF(s);
written.add(s);
}
final List<String> read = Lists.array();
final StringDataInput input = StringDataInput.with(b.toString());
for (int i = Character.MIN_VALUE; i <= 'z'; i++) {
read.add(input.readUTF());
}
this.checkEquals(written.toString(), read.toString());
}
@Test
public void testWriteBooleanCharIntStringRountrip() throws IOException {
final StringBuilder b = new StringBuilder();
final StringDataOutput out = StringDataOutput.with(b::append);
for(int i = 0; i < 3; i++) {
out.writeBoolean(true);
out.writeChar('A');
out.writeInt(123);
out.writeUTF("XYZ");
}
final StringDataInput input = StringDataInput.with(b.toString());
for(int i = 0; i < 3; i++) {
this.checkEquals(true, input.readBoolean());
this.checkEquals('A', input.readChar());
this.checkEquals(123, input.readInt());
this.checkEquals("XYZ", input.readUTF());
}
}
@Override
public Class<StringDataInputDataOutput> type() {
return StringDataInputDataOutput.class;
}
@Override
public JavaVisibility typeVisibility() {
return JavaVisibility.PUBLIC;
}
@Override
public boolean canHavePublicTypes(final Method method) {
return false;
}
}
| 32.38 | 114 | 0.615195 |
27e369ecae36291bdb1d283619eaa156a318b533 | 547 | package com.learning.spring.debug.design.chain;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Father extends Handler{
private static final Logger logger = LogManager.getLogger(Father.class);
public Father() {
super(1);
}
@Override
public void response(People people) {
logger.info("--------------------------------------------");
logger.info("女儿的请示:{}, {}", people.getRequest(), people.getType());
logger.info("父亲的答复:{}\n", "同意");
}
}
| 26.047619 | 76 | 0.601463 |
c21a523519598fc57bafb3baf95c0d51dc3f2c14 | 158 | package at.ciit.products.states;
public enum ProductState {
ORDERED,
SOLD,
MANUFACTURED,
IN_TRANSPORT,
IN_BRANCH,
SUBMITTED,
AFTER_GARANCY_PERIOD
}
| 13.166667 | 32 | 0.772152 |
211266737b5e4fa685eded6eaa33a98bcf32d812 | 861 | package ru.job4j.calculate;
/**
* Calculator.
*
* @author Maksym Mateiuk (maxymmateuk@gmail.com)
*/
public class Calculator {
/**
* Add numbers.
* @param first double
* @param second double
* @return result
*/
public double add(double first, double second) {
return first + second;
}
/**
* Substract numbers.
* @param first double
* @param second double
* @return result
*/
public double subsctract(double first, double second) {
return first - second;
}
/**
* Multiple numbers.
* @param first double
* @param second double
* @return result
*/
public double multiple(double first, double second) {
return first * second;
}
/**
* Divide numbers.
* @param first double
* @param second double
* @return result
*/
public double divide(double first, double second) {
return first / second;
}
}
| 16.882353 | 56 | 0.651568 |
d0df5c8f825e4189d250e4393a3fe0ad087c677e | 3,243 | package edu.rice.cs.hpctraceviewer.ui.depth;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import edu.rice.cs.hpctraceviewer.data.SpaceTimeDataController;
import edu.rice.cs.hpctraceviewer.ui.base.AbstractBaseItem;
import edu.rice.cs.hpctraceviewer.ui.base.ITracePart;
import edu.rice.cs.hpctraceviewer.ui.main.HPCTraceView;
/*****************************************************
*
* Depth view
*
*****************************************************/
public class HPCDepthView extends AbstractBaseItem
{
private static final int VIEW_HEIGHT_HINT = 40;
/** Paints and displays the detail view. */
private DepthTimeCanvas depthCanvas;
public HPCDepthView(CTabFolder parent, int style) {
super(parent, style);
}
@Override
public void createContent(ITracePart parentPart,
IEclipseContext context,
IEventBroker broker,
Composite master)
{
final Composite plotArea = new Composite(master, SWT.NONE);
/*************************************************************************
* Padding Canvas
*************************************************************************/
final Canvas axisCanvas = new Canvas(plotArea, SWT.NONE);
GridDataFactory.fillDefaults().grab(false, true).
hint(HPCTraceView.Y_AXIS_WIDTH, VIEW_HEIGHT_HINT).applyTo(axisCanvas);
/*************************************************************************
* Depth View Canvas
*************************************************************************/
depthCanvas = new DepthTimeCanvas(parentPart, plotArea);
GridDataFactory.fillDefaults().grab(true, true).
hint(500, VIEW_HEIGHT_HINT).applyTo(depthCanvas);
/*************************************************************************
* Master Composite
*************************************************************************/
GridDataFactory.fillDefaults().grab(true, true).applyTo(plotArea);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(plotArea);
setToolTipText("The view to show for a given process, its virtual time along the horizontal axis, and a call path" +
" along the vertical axis, where `main' is at the top and leaves (samples) are at the bottom.");
}
@Override
public void setInput(Object input) {
depthCanvas.updateView((SpaceTimeDataController) input);
depthCanvas.refresh();
}
/****
* Zoom out the depth: increase the depth so users can see more
*/
public void zoomOut() {
depthCanvas.zoomOut();
}
/****
* Zoom in the depth: decrease the depth so user can see more pixels
*/
public void zoomIn() {
depthCanvas.zoomIn();
}
/****
* check if we can zoom out
* @return true if it's feasible
*/
public boolean canZoomOut() {
return depthCanvas.canZoomOut();
}
/****
* check if can zoom in
* @return true if it's possible
*/
public boolean canZoomIn() {
return depthCanvas.canZoomIn();
}
}
| 28.447368 | 118 | 0.599137 |
15f31dadf9d08412f746027378641bcecfb51de4 | 1,500 | package org.wustrive.java.dao.jdbc;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("all")
public class SqlParameter implements Map {
private Map source;
public SqlParameter(){
this.source = new HashMap();
}
public SqlParameter(Object key,Object value){
this.source = new HashMap();
this.source.put(key, value);
}
public Map getSource() {
return source;
}
public SqlParameter setSource(Map source) {
this.source = source;
return this;
}
public void clear() {
this.source.clear();
}
public boolean containsKey(Object key) {
return this.source.containsKey(key);
}
public boolean containsValue(Object value) {
return this.source.containsValue(value);
}
public Set entrySet() {
return this.source.entrySet();
}
public Object get(Object key) {
return this.source.get(key);
}
public boolean isEmpty() {
return this.source.isEmpty();
}
public Set keySet() {
return this.source.keySet();
}
public SqlParameter addValue(Object key, Object value) {
this.source.put(key, value);
return this;
}
public void putAll(Map m) {
this.source.putAll(m);
}
public SqlParameter remove(Object key) {
this.source.remove(key);
return this;
}
public int size() {
return this.source.size();
}
public Collection values() {
return this.source.values();
}
public SqlParameter put(Object key, Object value) {
this.source.put(key, value);
return this;
}
}
| 17.045455 | 57 | 0.696 |
9c9ae2faa682df3682ff5666433f8d388f43b90b | 534 | package net.nocturne.game.player.dialogues.impl.dominionTower;
import net.nocturne.game.player.dialogues.Dialogue;
public class DTSpectateReq extends Dialogue {
@Override
public void start() {
sendDialogue(
"You don't have the requirements to play this content, but you can",
"spectate some of the matches taking place if you would like.");
}
@Override
public void run(int interfaceId, int componentId, int slotId) {
player.getDominionTower().openSpectate();
end();
}
@Override
public void finish() {
}
}
| 19.777778 | 70 | 0.734082 |
4584d58b606c0059326a4da6e5e144f8092efa0e | 13,208 | package game;
import interfaces.Player;
import interfaces.PlayerNotificatior;
import javafx.application.Platform;
import javafx.scene.paint.Color;
import player.HumanPlayer;
import player.HumanPlayer.State;
import java.util.ArrayList;
import java.util.List;
public class Board {
private Figure[] remaining;
private Figure[] board;
private Player p1;
private Player p2;
private Player onTurn;
private int round;
private boolean inRound;
private Figure selectedFigure;
private boolean firstRound = true;
private PlayerNotificatior notifier;
public boolean gameRunning = true;
public Board(Player p1, Player p2, PlayerNotificatior not) {
this.board = new Figure[16];
this.remaining = new Figure[16];
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(gameRunning) {
if(isOver()) {
gameRunning = false;
handleEnd(onTurn);
}
}
}
});
//t.setDaemon(true);
//t.start();
this.p1 = p1;
this.p2 = p2;
this.notifier = not;
this.onTurn = Math.random() > 0.5 ? this.p1 : this.p2;
for (int i = 0; i < this.remaining.length; i++) {
this.remaining[i] = new Figure((byte) i);
}
}
public void handleFieldClick(int index) {
if(this.onTurn instanceof HumanPlayer) {
((HumanPlayer)this.onTurn).handleFieldClick(index);
}
}
public void handleFigureClick(int index) {
if(this.onTurn instanceof HumanPlayer) {
((HumanPlayer)this.onTurn).handleFigureClick(index);
}
}
private List<Figure> getRemainingFigures() {
List<Figure> temp = new ArrayList<Figure>();
for (Figure figure : this.remaining) {
if (figure != null)
temp.add(figure.clone());
}
return temp;
}
private boolean win() {
boolean winns = false;
// diagnoals
winns |= Figure.hasGeneInCommon(this.board[0], this.board[5], this.board[10], this.board[15]);
winns |= Figure.hasGeneInCommon(this.board[3], this.board[6], this.board[9], this.board[12]);
if (winns)
return true;
// rows and columns
for (int i = 0; i < 4; i++) {
winns |= Figure.hasGeneInCommon(this.board[(i * 4)], this.board[(i * 4) + 1], this.board[(i * 4) + 2], this.board[(i * 4) + 3]);
winns |= Figure.hasGeneInCommon(this.board[i], this.board[i + 4], this.board[i + 8], this.board[i + 12]);
if (winns)
return true;
}
// squares
for (int i = 0; i < 3; i++) {
winns |= Figure.hasGeneInCommon(this.board[i], this.board[i + 1], this.board[i + 4], this.board[i + 5]);
winns |= Figure.hasGeneInCommon(this.board[i + 4], this.board[i + 5], this.board[i + 8], this.board[i + 9]);
winns |= Figure.hasGeneInCommon(this.board[i + 8], this.board[i + 9], this.board[i + 12], this.board[i + 13]);
if (winns)
return true;
}
return false;
}
public Figure[][] get2DBoard() {
Figure[][] f = new Figure[4][4];
for (int i = 0; i < 4; i++) {
if(this.board[i] != null) f[0][i] = this.board[i].clone();
if(this.board[i + 4] != null) f[1][i] = this.board[i + 4].clone();
if(this.board[i + 8] != null) f[2][i] = this.board[i + 8].clone();
if(this.board[i + 12] != null) f[3][i] = this.board[i + 12].clone();
}
return f;
}
private Figure[] get1DBoard() {
Figure[] fs = new Figure[this.board.length];
for(int i = 0; i < fs.length; i++) {
fs[i] = (board[i] == null) ? null : board[i].clone();
}
return fs;
}
public Figure[] getRemainingFiguresArray() {
return this.remaining;
}
public Figure[] getField() {
return this.board;
}
public Figure getSelectedFigure() {
return this.selectedFigure;
}
public void nextRound() {
if(!this.gameRunning) return;
if(firstRound) {
if(this.onTurn instanceof HumanPlayer) {
HumanPlayer hp = (HumanPlayer) this.onTurn;
switch (hp.playerState) {
case NONE:
//let the player know to selekt a figure
this.notifier.setPlayer(this.onTurn.getName());
this.notifier.notifyPlayer("Bitte wähle eine Figur!");
hp.playerState = HumanPlayer.State.FIGURE_SELECTED;
return;
default:
this.selectFigure(hp.selectFigure(this.getRemainingFigures(), this.get1DBoard()));
this.notifier.resetNotification();
this.firstRound = false;
this.round++;
this.notifier.updateView();
if(this.isOver())
handleEnd(this.onTurn);
else
this.nextRound();
return;
}
} else {
this.selectFigure(this.onTurn.selectFigure(this.getRemainingFigures(), this.get1DBoard()));
this.round++;
this.firstRound = false;
this.notifier.updateView();
if(this.isOver())
handleEnd(this.onTurn);
else
this.nextRound();
return;
}
}
if(inRound && (this.onTurn instanceof HumanPlayer)) {
HumanPlayer hp = (HumanPlayer)this.onTurn;
switch (hp.playerState) {
case NONE:
this.placeFigure(this.selectedFigure, hp.placeFigure(this.selectedFigure, this.get1DBoard(), this.getRemainingFigures()));
//this.placeFigure(this.selectedFigure, this.onTurn);
this.selectedFigure = null;
this.notifier.updateView();
//let the user know to select a fugure
if(this.isOver()) {
this.handleEnd(this.onTurn);
return;
}
this.notifier.setPlayer(this.onTurn.getName());
this.notifier.notifyPlayer(onTurn.getName() + " Bitte wähle eine Figur!");
hp.playerState = State.PLACED_FIGURE;
return;
case PLACED_FIGURE:
this.selectFigure(hp.selectFigure(this.getRemainingFigures(), this.get1DBoard()));
//round over
this.notifier.resetNotification();
this.inRound = false;
this.notifier.updateView();
if(this.isOver())
handleEnd(this.onTurn);
else
this.nextRound();
return;
default:
return;
}
} else {
/*
if(this.round % 2 == 0) {
this.onTurn = p1;
} else {
this.onTurn = p2;
}
*/
this.swapPlayer();
this.round++;
if(!(this.onTurn instanceof HumanPlayer)) {
this.placeFigure(this.selectedFigure, this.onTurn.placeFigure(this.selectedFigure, this.get1DBoard(), this.getRemainingFigures()));
//this.placeFigure(this.selectedFigure, this.onTurn);
this.selectFigure(this.onTurn.selectFigure(this.getRemainingFigures(), this.get1DBoard()));
this.notifier.updateView();
if(this.isOver())
handleEnd(this.onTurn);
else
this.nextRound();
} else {
((HumanPlayer)this.onTurn).playerState = HumanPlayer.State.NONE;
this.notifier.setPlayer(this.onTurn.getName());
this.notifier.notifyPlayer("Wähle ein Feld für diese Figur");
//let the user knot to place place the figure and press the accept button
this.notifier.updateView();
this.inRound = true;
//return;
}
}
}
private void swapPlayer() {
if(this.p1 == this.onTurn) {
this.onTurn = this.p2;
} else {
this.onTurn = this.p1;
}
}
private void selectFigure(Figure f) {
if(getRemainingFigures().contains(f)) {
this.remaining[f.getGenome()] = null;
this.selectedFigure = f;
}
}
private void placeFigure(Figure f, int index) {
if(this.board[index] == null) {
this.board[index] = f;
}
}
private void placeFigure(Figure f, Player p) {
Figure[] board = this.get1DBoard();
List<Figure> fs = this.getRemainingFigures();
int index = p.placeFigure(f, board, fs);
while(index < 0 || this.board[index] != null) {
index = p.placeFigure(f, board, fs);
}
this.board[index] = f;
}
public Player getP1() {
return this.p1;
}
public Player getP2() {
return this.p2;
}
public Player getLastPlayer() {
return this.onTurn;
}
private int[] getWinningSituation() {
if(Figure.hasGeneInCommon(this.board[0], this.board[5], this.board[10], this.board[15]))
return new int[] {0, 5, 10, 15};
if(Figure.hasGeneInCommon(this.board[3], this.board[6], this.board[9], this.board[12]))
return new int[] {3, 6, 9, 12};
// rows and columns
for (int i = 0; i < 4; i++) {
if(Figure.hasGeneInCommon(this.board[(i * 4)], this.board[(i * 4) + 1], this.board[(i * 4) + 2], this.board[(i * 4) + 3]))
return new int[]{(i * 4), (i * 4) + 1, (i * 4) + 2, (i * 4) + 3};
if(Figure.hasGeneInCommon(this.board[i], this.board[i + 4], this.board[i + 8], this.board[i + 12]))
return new int[] {i, i + 4, i + 8, i + 12};
}
// squares
for (int i = 0; i < 3; i++) {
if(Figure.hasGeneInCommon(this.board[i], this.board[i + 1], this.board[i + 4], this.board[i + 5]))
return new int[] {i, i + 1, i + 4, i + 5};
if(Figure.hasGeneInCommon(this.board[i + 4], this.board[i + 5], this.board[i + 8], this.board[i + 9]))
return new int[] {i + 4, i + 5, i + 8, i + 9};
if(Figure.hasGeneInCommon(this.board[i + 8], this.board[i + 9], this.board[i + 12], this.board[i + 13]))
return new int[] {i + 8, i + 9, i + 12, i + 13};
}
return null;
}
public Player getHumanPlayer() {
if (this.p1 instanceof HumanPlayer)
return this.p1;
else if(this.p2 instanceof HumanPlayer)
return this.p2;
else
return null;
}
public boolean is101() {
return this.p1 instanceof HumanPlayer && this.p2 instanceof HumanPlayer;
}
public Player getNotOnTurn() {
if(this.p2.equals(this.onTurn))
return p1;
else
return p2;
}
public void setP1(Player p) {
if(this.onTurn.equals(p1))
this.onTurn = p;
this.p1 = p;
}
public void setP2(Player p) {
if(this.onTurn.equals(p))
this.onTurn = p;
this.p2 = p;
}
private boolean simpleDraw() {
int counter = 0;
for(Figure f : this.board) {
if(f == null)
counter++;
}
return counter == 0 && !this.win();
}
private boolean draw() {
int counter = 0;
for(Figure f : this.board) {
if(f == null)
counter++;
}
return counter == 0;
}
private boolean isOver() {
return this.draw() || this.win();
}
private void handleEnd(Player lastMove) {
if(this.win()) {
this.gameRunning = false;
Platform.runLater(() -> this.notifier.setStyle(Color.RED));
Platform.runLater(() -> this.notifier.setPlayer(lastMove.getName() + " hat gewonnen."));
Platform.runLater(() -> this.notifier.notifyPlayer("Klicke auf das Feld um neu zu beginnen."));
System.out.println(lastMove.getName() + " hat gewonnen");
//System.out.println(Arrays.toString(this.getWinningSituation()));
Platform.runLater(() -> this.notifier.showWin(this.getWinningSituation()));
} else if(this.simpleDraw()) {
this.gameRunning = false;
Platform.runLater(() -> this.notifier.setStyle(Color.YELLOW));
Platform.runLater(() -> this.notifier.setPlayer("Unentschieden..."));
Platform.runLater(() -> this.notifier.notifyPlayer("Klicke auf das Feld um neu zu beginnen."));
}
}
}
| 33.866667 | 147 | 0.511054 |
5ae0172e1c63347d456d6c7e9c1205fa04641de8 | 1,376 | package me.ycdev.android.demo.lollipopdemo.usage.apps;
import java.text.Collator;
import java.util.Comparator;
public class AppsUsageItem {
public String pkgName;
public String appName;
public long lastStartup;
public String lastStartupStr;
public long fgTime;
public String fgTimeStr;
public static class AppNameComparator implements Comparator<AppsUsageItem> {
private Collator mCollator = Collator.getInstance();
@Override
public int compare(AppsUsageItem lhs, AppsUsageItem rhs) {
return mCollator.compare(lhs.appName, rhs.appName);
}
}
public static class LastStartupComparator implements Comparator<AppsUsageItem> {
@Override
public int compare(AppsUsageItem lhs, AppsUsageItem rhs) {
if (lhs.lastStartup < rhs.lastStartup) {
return 1;
} else if (lhs.lastStartup > rhs.lastStartup) {
return -1;
}
return 0;
}
}
public static class FgTimeComparator implements Comparator<AppsUsageItem> {
@Override
public int compare(AppsUsageItem lhs, AppsUsageItem rhs) {
if (lhs.fgTime < rhs.fgTime) {
return 1;
} else if (lhs.fgTime > rhs.fgTime) {
return -1;
}
return 0;
}
}
}
| 29.276596 | 84 | 0.614099 |
73665a35fb6cfb4989acff3594e9b149128358d5 | 2,228 |
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.data.document;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.eclipse.birt.data.engine.core.security.FileSecurity;
/**
*
*/
public class SimpleRandomAccessObject implements IRandomAccessObject
{
RandomAccessFile randomAccessFile = null;
public SimpleRandomAccessObject( File file, String mode ) throws FileNotFoundException
{
this.randomAccessFile = FileSecurity.createRandomAccessFile( file, mode );
}
public void close( ) throws IOException
{
randomAccessFile.close( );
}
public FileDescriptor getFD( ) throws IOException
{
return randomAccessFile.getFD( );
}
public long getFilePointer( ) throws IOException
{
return randomAccessFile.getFilePointer( );
}
public long length( ) throws IOException
{
return randomAccessFile.length( );
}
public int read( byte[] b, int off, int len ) throws IOException
{
return randomAccessFile.read( );
}
public int read( byte[] b ) throws IOException
{
return randomAccessFile.read( b );
}
public void seek( long pos ) throws IOException
{
randomAccessFile.seek( pos );
}
public void setLength( long newLength ) throws IOException
{
randomAccessFile.setLength( newLength );
}
public void write( byte[] b, int off, int len ) throws IOException
{
randomAccessFile.write( b, off, len );
}
public void flush( ) throws IOException
{
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.data.document.IRandomAccessObject#read()
*/
public int read() throws IOException
{
return randomAccessFile.read( );
}
}
| 23.452632 | 87 | 0.686266 |
80a2775d99020924b55c4c5cb20f6df8dcd2881c | 652 | package org.hyperledger.indy.sdk.payment;
import org.hyperledger.indy.sdk.payments.Payments;
import org.hyperledger.indy.sdk.payments.UnknownPaymentMethodException;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import static org.hamcrest.CoreMatchers.isA;
public class ParseGetTxnFeesResponseTest extends PaymentIntegrationTest {
@Test
public void testParseGetTxnFeesResponseResponseTestWorksForUnknownPaymentMethod() throws Exception {
thrown.expect(ExecutionException.class);
thrown.expectCause(isA(UnknownPaymentMethodException.class));
Payments.parseGetTxnFeesResponse(paymentMethod, emptyObject).get();
}
}
| 31.047619 | 101 | 0.843558 |
1b9b576e3008c6d7033edfdffb80464690f20d7b | 5,975 | package com.skillw.rpglib.manager.script;
import com.skillw.rpglib.RPGLib;
import com.skillw.rpglib.api.manager.script.CompiledScriptManager;
import com.skillw.rpglib.util.FileUtils;
import com.skillw.rpglib.util.MessageUtils;
import jdk.internal.dynalink.beans.StaticClass;
import org.bukkit.configuration.ConfigurationSection;
import javax.script.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static com.skillw.rpglib.script.ScriptTool.staticClass;
public class CompiledScriptManagerImpl extends CompiledScriptManager {
private final Set<File> files = new HashSet<>();
private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
private final String jdkVersion = System.getProperty("java.specification.version");
private final ScriptEngine scriptEngine;
public CompiledScriptManagerImpl() {
this.scriptEngine = this.scriptEngineManager.getEngineByName("JavaScript");
if (this.scriptEngine == null) {
MessageUtils.sendWrong("尚未支持&6Jdk " + this.jdkVersion);
return;
}
this.load();
}
@Override
public void reload() {
this.map.clear();
this.files.forEach(
folder -> FileUtils.listFiles(folder)
.forEach(file -> this.map.put(file, Objects.requireNonNull(this.compileScript(file))))
);
}
@Override
public String getJdkVersion() {
return this.jdkVersion;
}
@Override
public ScriptEngine getScriptEngine() {
return this.scriptEngine;
}
@Override
public ScriptEngineManager getScriptEngineManager() {
return this.scriptEngineManager;
}
public void load() {
File scriptsFile = new File(RPGLib.getInstance().getPlugin().getDataFolder(), "scripts");
this.files.add(scriptsFile);
if (!scriptsFile.exists()) {
scriptsFile.mkdirs();
}
this.reload();
}
@Override
public CompiledScript compileScript(File file) {
try {
return ((Compilable) this.scriptEngine).compile(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
} catch (ScriptException | FileNotFoundException e) {
MessageUtils.sendWrong("脚本文件 &6" + file.getPath() + " &c编译失败! 请检查.");
e.printStackTrace();
}
return null;
}
@Override
public CompiledScript compileScript(String filePath) {
File file = new File(RPGLib.getConfigManager().getServer(), filePath);
return this.compileScript(file);
}
@Override
public Optional<Map.Entry<File, CompiledScript>> searchScript(String filePath) {
Optional<Map.Entry<File, CompiledScript>> optional = this.map
.entrySet()
.stream()
.filter(fileCompiledScriptEntry ->
fileCompiledScriptEntry.getKey().getAbsolutePath().replace("\\\\", "/").endsWith(filePath))
.findFirst();
if (!optional.isPresent()) {
CompiledScript compiledScript = this.compileScript(filePath);
if (compiledScript != null) {
File file = new File(RPGLib.getConfigManager().getServer(), filePath);
this.map.put(file, compiledScript);
return this.map.entrySet().stream()
.filter(fileCompiledScriptEntry ->
fileCompiledScriptEntry.getKey().equals(file))
.findFirst();
} else {
MessageUtils.sendWrong("未发现脚本文件 &6" + filePath + " &c! 请检查.");
}
}
return optional;
}
@Override
public Set<File> getFiles() {
return this.files;
}
@Override
public Object invoke(String filePath, Map<String, Object> variables, Object... args) {
return this.invoke(filePath, variables, "main", args);
}
@Override
public Object invokePathWithFunction(String filePathWithFunction, Map<String, Object> variables, Object... args) {
String[] strings = filePathWithFunction.split("::");
return this.invoke(strings[0], variables, strings[1], args);
}
@Override
public Object invoke(String filePath, Map<String, Object> variables, String function, Object... args) {
Optional<Map.Entry<File, CompiledScript>> optional = RPGLib.getCompiledScriptManager().searchScript(filePath);
if (optional.isPresent()) {
Map.Entry<File, CompiledScript> entry = optional.get();
CompiledScript compiledScript = entry.getValue();
ScriptEngine scriptEngine = compiledScript.getEngine();
variables.forEach(scriptEngine::put);
RPGLib.getConfigManager().getStaticMap().forEach(scriptEngine::put);
try {
compiledScript.eval(scriptEngine.getContext());
} catch (ScriptException e) {
MessageUtils.sendWrong("执行脚本文件 &6" + filePath + " &c中的函数 &d" + function + " &c时发生了错误 !");
e.printStackTrace();
}
Invocable invocable = (Invocable) scriptEngine;
try {
return invocable.invokeFunction(function, args);
} catch (ScriptException e) {
MessageUtils.sendWrong("执行脚本文件 &6" + filePath + " &c中的函数 &d" + function + " &c时发生了错误(或不存在此函数)!");
e.printStackTrace();
} catch (NoSuchMethodException e) {
MessageUtils.sendWrong("执行脚本文件 &6" + filePath + " &c中的函数 &d" + function + " &c时发生了错误!");
e.printStackTrace();
}
}
return null;
}
}
| 38.548387 | 135 | 0.607197 |
4dea3fe8007d50811884974a4ed8c435fc70989b | 5,883 | /*
* Copyright 2014 - 2022 Blazebit.
*
* 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.blazebit.persistence.impl.query;
import com.blazebit.persistence.ReturningResult;
import com.blazebit.persistence.impl.ParameterValueTransformer;
import com.blazebit.persistence.impl.ValuesParameterBinder;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.PersistenceException;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.ParameterExpression;
import java.util.*;
import java.util.stream.Stream;
/**
* @author Christian Beikov
* @since 1.2.0
*/
public class CustomReturningSQLTypedQuery<T> extends AbstractCustomQuery<ReturningResult<T>> implements TypedQuery<ReturningResult<T>> {
private final TypedQuery<?> delegate;
public CustomReturningSQLTypedQuery(QuerySpecification<ReturningResult<T>> querySpecification, TypedQuery<?> delegate, Map<ParameterExpression<?>, String> criteriaNameMapping, Map<String, ParameterValueTransformer> transformers, Map<String, String> valuesParameters, Map<String, ValuesParameterBinder> valuesBinders) {
super(querySpecification, criteriaNameMapping, transformers, valuesParameters, valuesBinders);
this.delegate = delegate;
}
@Override
@SuppressWarnings("unchecked")
public List<ReturningResult<T>> getResultList() {
bindParameters();
return querySpecification.createSelectPlan(firstResult, maxResults).getResultList();
}
@Override
@SuppressWarnings("unchecked")
public ReturningResult<T> getSingleResult() {
bindParameters();
return querySpecification.createSelectPlan(firstResult, maxResults).getSingleResult();
}
@Override
public int executeUpdate() {
bindParameters();
return querySpecification.createModificationPlan(firstResult, maxResults).executeUpdate();
}
@Override
public TypedQuery<ReturningResult<T>> setHint(String hintName, Object value) {
delegate.setHint(hintName, value);
return this;
}
@Override
public Map<String, Object> getHints() {
return delegate.getHints();
}
@Override
public TypedQuery<ReturningResult<T>> setFlushMode(FlushModeType flushMode) {
delegate.setFlushMode(flushMode);
return this;
}
@Override
public FlushModeType getFlushMode() {
return delegate.getFlushMode();
}
@Override
public TypedQuery<ReturningResult<T>> setLockMode(LockModeType lockMode) {
delegate.setLockMode(lockMode);
return this;
}
@Override
public LockModeType getLockMode() {
return delegate.getLockMode();
}
@Override
public <T> T unwrap(Class<T> cls) {
if (getParticipatingQueries().size() > 1) {
throw new PersistenceException("Unsupported unwrap: " + cls.getName());
}
return delegate.unwrap(cls);
}
/* Covariant override */
@Override
public TypedQuery<ReturningResult<T>> setMaxResults(int maxResults) {
super.setMaxResults(maxResults);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setFirstResult(int startPosition) {
super.setFirstResult(startPosition);
return this;
}
@Override
public <X> TypedQuery<ReturningResult<T>> setParameter(Parameter<X> param, X value) {
super.setParameter(param, value);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType) {
super.setParameter(param, value, temporalType);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(Parameter<Date> param, Date value, TemporalType temporalType) {
super.setParameter(param, value, temporalType);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(String name, Object value) {
super.setParameter(name, value);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(String name, Calendar value, TemporalType temporalType) {
super.setParameter(name, value, temporalType);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(String name, Date value, TemporalType temporalType) {
super.setParameter(name, value, temporalType);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(int position, Object value) {
super.setParameter(position, value);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(int position, Calendar value, TemporalType temporalType) {
super.setParameter(position, value, temporalType);
return this;
}
@Override
public TypedQuery<ReturningResult<T>> setParameter(int position, Date value, TemporalType temporalType) {
super.setParameter(position, value, temporalType);
return this;
}
public Stream<ReturningResult<T>> getResultStream() {
bindParameters();
return querySpecification.createSelectPlan(firstResult, maxResults).getResultStream();
}
}
| 32.502762 | 322 | 0.710862 |
56a9aff13747f36ef21dfe4eb8221bbefa399d47 | 3,342 | /* SPDX-License-Identifier: Apache 2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.samples.applications.hrim.properties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Person
{
private String pnum = null;
private String firstName = null;
private String lastName = null;
private EmployeeStatus employeeStatus = null;
private int jobLevel = 0;
private String departmentCode = null;
private String role = null;
private int locationCode = 0;
private int taxStatus = 1;
public Person()
{
}
public String getPnum()
{
return pnum;
}
public void setPnum(String pnum)
{
this.pnum = pnum;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public EmployeeStatus getEmployeeStatus()
{
return employeeStatus;
}
public void setEmployeeStatus(EmployeeStatus employeeStatus)
{
this.employeeStatus = employeeStatus;
}
public int getJobLevel()
{
return jobLevel;
}
public void setJobLevel(int jobLevel)
{
this.jobLevel = jobLevel;
}
public String getDepartmentCode()
{
return departmentCode;
}
public void setDepartmentCode(String departmentCode)
{
this.departmentCode = departmentCode;
}
public String getRole()
{
return role;
}
public void setRole(String role)
{
this.role = role;
}
public int getLocationCode()
{
return locationCode;
}
public void setLocationCode(int locationCode)
{
this.locationCode = locationCode;
}
public int getTaxStatus()
{
return taxStatus;
}
public void setTaxStatus(int taxStatus)
{
this.taxStatus = taxStatus;
}
@Override
public String toString()
{
return "Person{" +
"pnum='" + pnum + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", employeeStatus=" + employeeStatus +
", jobLevel=" + jobLevel +
", departmentCode='" + departmentCode + '\'' +
", role='" + role + '\'' +
", locationCode=" + locationCode +
", taxStatus=" + taxStatus +
'}';
}
}
| 21.286624 | 97 | 0.577798 |
f139651d0c94ae5578dc69bd33fc4834fa2421ae | 1,054 | package com.zhengjianting.zookeeper.impl;
import com.zhengjianting.dto.RpcRequest;
import com.zhengjianting.zookeeper.ServiceDiscovery;
import com.zhengjianting.zookeeper.util.CuratorUtils;
import org.apache.curator.framework.CuratorFramework;
import java.net.InetSocketAddress;
import java.util.List;
public class ServiceDiscoveryImpl implements ServiceDiscovery {
@Override
public InetSocketAddress lookupService(RpcRequest rpcRequest) {
String rpcServiceName = rpcRequest.getRpcServiceName();
CuratorFramework zkClient = CuratorUtils.getZkClient();
List<String> addresses = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
if (addresses == null || addresses.size() == 0) {
throw new RuntimeException("No server implementing this service was found.");
}
// default select the first address
String host = addresses.get(0).split(":")[0];
int port = Integer.parseInt(addresses.get(0).split(":")[1]);
return new InetSocketAddress(host, port);
}
}
| 37.642857 | 89 | 0.728653 |
42752db77e3bb888311e266846804065808c6025 | 4,551 | /**
* Copyright 2016 LinkedIn Corp. 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.
*/
package com.github.ambry.utils;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BloomFilterTest {
public IFilter bf;
public BloomFilterTest() {
bf = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE);
}
public static IFilter testSerialize(IFilter f) throws IOException {
f.add(ByteBuffer.wrap("a".getBytes()));
ByteBuffer output = ByteBuffer.allocate(100000);
DataOutputStream out = new DataOutputStream(new ByteBufferOutputStream(output));
FilterFactory.serialize(f, out);
output.flip();
DataInputStream input = new DataInputStream(new ByteBufferInputStream(output));
IFilter f2 = FilterFactory.deserialize(input);
assert f2.isPresent(ByteBuffer.wrap("a".getBytes()));
assert !f2.isPresent(ByteBuffer.wrap("b".getBytes()));
return f2;
}
@Before
public void clear() {
bf.clear();
}
@Test(expected = UnsupportedOperationException.class)
public void testBloomLimits1() {
int maxBuckets = BloomCalculations.probs.length - 1;
int maxK = BloomCalculations.probs[maxBuckets].length - 1;
// possible
BloomCalculations.computeBloomSpec(maxBuckets, BloomCalculations.probs[maxBuckets][maxK]);
// impossible, throws
BloomCalculations.computeBloomSpec(maxBuckets, BloomCalculations.probs[maxBuckets][maxK] / 2);
}
@Test
public void testOne() {
bf.add(ByteBuffer.wrap("a".getBytes()));
assert bf.isPresent(ByteBuffer.wrap("a".getBytes()));
assert !bf.isPresent(ByteBuffer.wrap("b".getBytes()));
}
@Test
public void testFalsePositivesInt() {
FilterTestHelper.testFalsePositives(bf, FilterTestHelper.intKeys(), FilterTestHelper.randomKeys2());
}
@Test
public void testFalsePositivesRandom() {
FilterTestHelper.testFalsePositives(bf, FilterTestHelper.randomKeys(), FilterTestHelper.randomKeys2());
}
@Test
public void testWords() {
if (KeyGenerator.WordGenerator.WORDS == 0) {
return;
}
IFilter bf2 = FilterFactory.getFilter(KeyGenerator.WordGenerator.WORDS / 2, FilterTestHelper.MAX_FAILURE_RATE);
int skipEven = KeyGenerator.WordGenerator.WORDS % 2 == 0 ? 0 : 2;
FilterTestHelper.testFalsePositives(bf2, new KeyGenerator.WordGenerator(skipEven, 2),
new KeyGenerator.WordGenerator(1, 2));
}
@Test
public void testSerialize() throws IOException {
BloomFilterTest.testSerialize(bf);
}
public void testManyHashes(Iterator<ByteBuffer> keys) {
int MAX_HASH_COUNT = 128;
Set<Long> hashes = new HashSet<Long>();
long collisions = 0;
while (keys.hasNext()) {
hashes.clear();
ByteBuffer buf = keys.next();
BloomFilter bf = (BloomFilter) FilterFactory.getFilter(10, 1);
for (long hashIndex : bf.getHashBuckets(buf, MAX_HASH_COUNT, 1024 * 1024)) {
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
}
assert collisions <= 100;
}
@Test
public void testManyRandom() {
testManyHashes(FilterTestHelper.randomKeys());
}
@Test
public void testHugeBFSerialization() throws IOException {
ByteBuffer test = ByteBuffer.wrap(new byte[]{0, 1});
File f = File.createTempFile("bloomFilterTest-", ".dat");
f.deleteOnExit();
BloomFilter filter = (BloomFilter) FilterFactory.getFilter(((long) 100000 / 8) + 1, 0.01d);
filter.add(test);
DataOutputStream out = new DataOutputStream(new FileOutputStream(f));
FilterFactory.serialize(filter, out);
filter.bitset.serialize(out);
out.close();
DataInputStream in = new DataInputStream(new FileInputStream(f));
BloomFilter filter2 = (BloomFilter) FilterFactory.deserialize(in);
Assert.assertTrue(filter2.isPresent(test));
in.close();
}
}
| 31.604167 | 115 | 0.716985 |
da5f61c265cbbc8b8d905111db75407b3307bc5d | 3,345 | package com.inconspicuousy.pattern.mediator;
// 中介者模式: 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间耦合松散,且可以独立的改变他们之间的交互。
// 中介者模式又叫调停模式
// 简单来说, 多个对象之间的相互交互, 交给中间人去传话处理,实现多个对象之间的解耦,直接交互变为间接交互。
// 独立改变:当交流的规则发生改变时, 我们只需要修改中间人传话规则就行。
// 我们就以买房子为例。
// 角色分为 房客、房东、中介
// 这里房客和房东借用 中介 这个中间人实现消息传递。
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
// 抽象同事接口,因为同事类需要与中介者交互,所以需要与中介者建立依赖关系
// 提供将消息发送给中介者的方法
// 提供处理接收到其他消息的方法
@Getter
@Setter
@AllArgsConstructor
abstract class Collegua {
// 与中介者建立依赖, 并可以设置处理的中介者
private Mediator mediator;
// 发送消息给中介者
public abstract void send(String message);
// 接收中介者的消息
public abstract void receive(String message);
}
// 卖家
class Seller extends Collegua {
public Seller(Mediator mediator) {
super(mediator);
}
@Override
public void send(String message) {
// 将消息传递给中介进行转发
this.getMediator().relay(this, message);
}
@Override
public void receive(String message) {
// 处理接收到的消息
System.out.println("卖家收到消息: " + message);
}
}
// 买家
class Buyer extends Collegua {
public Buyer(Mediator mediator) {
super(mediator);
}
@Override
public void send(String message) {
// 将消息传递给中介进行转发
this.getMediator().relay(this, message);
}
@Override
public void receive(String message) {
System.out.println("买家收到消息: " + message);
}
}
// 定义抽象中介者
// 因为涉及到多个对象之间的交互,所以需要提供管理对象的注册功能。
// 定义多个对象相互交互的抽象方法。
interface Mediator {
void register(Collegua collegua);
// 注意, 相互交互的话, 我们要知道交互的双方是谁以及交互的内容
// collegua是话题发起人, message是传递的内容
void relay(Collegua collegua, String message);
}
// 具体的中介
class ConcreteMediator implements Mediator {
// 一般中介者只有只会有一个, 我们采用单例模式进行创建
private static final ConcreteMediator CONCRETE_MEDIATOR = new ConcreteMediator();
private ConcreteMediator() {
}
public static ConcreteMediator getInstance () {
return CONCRETE_MEDIATOR;
}
// 中介一般会将买房的人信息和卖房的人分开管理
// 卖房子
private final List<Collegua> sellers = new ArrayList<>();
// 买房子
private final List<Collegua> buyers = new ArrayList<>();
@Override
public void register(Collegua collegua) {
if (collegua instanceof Seller) {
sellers.add(collegua);
} else {
buyers.add(collegua);
}
}
@Override
public void relay(Collegua collegua, String message) {
if (collegua instanceof Seller) {
buyers.forEach(buyer -> buyer.receive(message));
} else {
// 找到任意一个卖房的人
sellers.stream().findAny().ifPresent(seller -> seller.receive(message));
}
}
}
/**
* 中介者模式代码测试
* @author peng.yi
*/
public class MediatorTest {
public static void main(String[] args) {
ConcreteMediator concreteMediator = ConcreteMediator.getInstance();
Seller seller = new Seller(concreteMediator);
// 获取到两个买房的人
Buyer buyer = new Buyer(concreteMediator);
Buyer buyer1 = new Buyer(concreteMediator);
// 将买房的人和卖房的人的信息注册到系统
concreteMediator.register(seller);
concreteMediator.register(buyer);
concreteMediator.register(buyer1);
seller.send("我的房子又大又好又便宜,快来租");
buyer.send("我要我要~");
}
}
| 23.391608 | 85 | 0.660688 |
962b39cca2f6ebe6a78a575ea761e1765c5cb2e6 | 733 | package com.anybbo.api;
import com.anybbo.api.sender.Sender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig(classes = RabbitMQApplication.class)
public class RabbitMQApplicationTests {
@Resource
private Sender sender;
@Test
public void contextLoads() {
sender.send();
}
}
| 26.178571 | 72 | 0.803547 |
2e0f782709976ac8f7d08129615118055524a8d6 | 1,170 | package br.com.observer.teste;
import java.math.BigDecimal;
import org.junit.Test;
import br.com.observer.eventos.Argumentos;
import br.com.observer.observadores.ContaCorrente;
import br.com.observer.observadores.Investimento;
import br.com.observer.observadores.Poupanca;
import br.com.observer.sujeitos.OrdemJudicial;
public class PrincipalTest {
@Test
public void test() {
OrdemJudicial ordemJudicial = OrdemJudicial.getInstancia();
ordemJudicial.notificarTodos(new Argumentos("012.345.678-90", BigDecimal.ONE));
ContaCorrente contaCorrente = ContaCorrente.getInstancia();
Poupanca poupanca = Poupanca.getInstancia();
Investimento investimento = Investimento.getInstancia();
ordemJudicial.registrar(contaCorrente);
ordemJudicial.registrar(poupanca);
ordemJudicial.notificarTodos(new Argumentos("012.345.678-90", BigDecimal.TEN));
ordemJudicial.registrar(investimento);
ordemJudicial.notificarTodos(new Argumentos("012.345.678-90", BigDecimal.ONE));
ordemJudicial.cancelar(poupanca);
ordemJudicial.notificarTodos(new Argumentos("184.176.049-87", BigDecimal.TEN));
}
}
| 28.536585 | 82 | 0.752991 |
e947a8a3e018979ce6bf210af7d8cc86a272eeab | 6,055 |
package trywithkids.gui;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import trywithkids.domain.Experiment;
import trywithkids.domain.TryWithKids;
/**
* search GUI
* @author satu
*/
public class GUIsearch {
private TryWithKids tryWithKids;
/**
*
* @param tryWithKids sets the trywithkids application logic to the view
*/
public GUIsearch(TryWithKids tryWithKids) {
this.tryWithKids = tryWithKids;
}
/**
* returns view
* @return view of search
*/
public Parent getView() {
BorderPane setting = new BorderPane();
VBox head = new VBox();
head.setSpacing(10);
head.setPadding(new Insets(10, 10, 10, 10));
Label headline = new Label("SEARCH THE DATABASE");
Label guide = new Label("You can search by subject, by maximum wanted duration or with both");
// Create a togglegroup of buttons for subject
Label bySubject = new Label("Select the subject");
ToggleButton biology = new ToggleButton("Biology");
ToggleButton physics = new ToggleButton("Physics");
ToggleButton chemistry = new ToggleButton("Chemistry");
ToggleGroup toggleGroup1 = new ToggleGroup();
physics.setToggleGroup(toggleGroup1);
chemistry.setToggleGroup(toggleGroup1);
biology.setToggleGroup(toggleGroup1);
HBox subject = new HBox(physics, chemistry, biology);
subject.setSpacing(10);
// create a togglegroup of buttons for duration
Label byDuration = new Label("Select the maximum duration you want");
ToggleButton five = new ToggleButton("5min");
ToggleButton ten = new ToggleButton("10min");
ToggleButton fiveteen = new ToggleButton("15min");
ToggleButton twenty = new ToggleButton("20min");
ToggleButton thirty = new ToggleButton("30min");
ToggleButton fourty = new ToggleButton("40min");
ToggleButton fifty = new ToggleButton("50min");
ToggleButton sixty = new ToggleButton("60min");
ToggleGroup toggleGroup2 = new ToggleGroup();
five.setToggleGroup(toggleGroup2);
ten.setToggleGroup(toggleGroup2);
fiveteen.setToggleGroup(toggleGroup2);
twenty.setToggleGroup(toggleGroup2);
thirty.setToggleGroup(toggleGroup2);
fourty.setToggleGroup(toggleGroup2);
fifty.setToggleGroup(toggleGroup2);
sixty.setToggleGroup(toggleGroup2);
HBox duration = new HBox(five, ten, fiveteen, twenty, thirty, fourty, fifty, sixty);
duration.setSpacing(10);
Button search = new Button("SEARCH");
head.getChildren().addAll(headline, guide, bySubject, subject, byDuration, duration, search);
setting.setTop(head);
search.setOnAction((event) -> {
// getting the toggled subject
ToggleButton selected = (ToggleButton) toggleGroup1.getSelectedToggle();
String subjectToggle = "empty";
if (selected == null) {
subjectToggle = "empty";
} else if (selected.equals(biology)) {
subjectToggle = "Biology";
} else if (selected.equals(physics)) {
subjectToggle = "Physics";
} else if (selected.equals(chemistry)) {
subjectToggle = "Chemistry";
}
// getting the toggled value of duration
ToggleButton selected2 = (ToggleButton) toggleGroup2.getSelectedToggle();
int durationToggle = 0;
if (selected2 == null) {
durationToggle = 0;
} else if (selected2.equals(five)) {
durationToggle = 5;
} else if (selected2.equals(ten)) {
durationToggle = 10;
} else if (selected2.equals(fiveteen)) {
durationToggle = 15;
} else if (selected2.equals(twenty)) {
durationToggle = 20;
} else if (selected2.equals(thirty)) {
durationToggle = 30;
} else if (selected2.equals(fourty)) {
durationToggle = 40;
} else if (selected2.equals(fifty)) {
durationToggle = 50;
} else if (selected2.equals(sixty)) {
durationToggle = 60;
}
List<Experiment> resultsList = new ArrayList<>();
if (!subjectToggle.contains("empty") || durationToggle != 0) {
resultsList = this.tryWithKids.search(subjectToggle, durationToggle);
} else {
System.out.println("durationToggle = " + durationToggle);
System.out.println(selected2);
System.out.println("subjectToggle = " + subjectToggle);
System.out.println(selected);
}
ScrollPane results = new ScrollPane();
results.setFitToHeight(true);
results.setFitToWidth(true);
results.setMaxHeight(300);
ListView<Experiment> listView = new ListView();
ObservableList<Experiment> observableExperiment = FXCollections.observableList(resultsList);
listView.setItems(observableExperiment);
results.setContent(new Label("Experiments in database matching search criteria"));
results.setContent(listView);
setting.setBottom(results);
});
return setting;
}
}
| 38.566879 | 104 | 0.611561 |
71e22381e4d29a4306a6fedfd71f1f591601fc34 | 1,062 | package com.moon.office.excel.core;
import com.moon.util.compute.RunnerUtil;
/**
* @author benshaoye
*/
class VarSetterEq implements VarSetter {
private final String[] keys;
private final String expression;
public VarSetterEq(String[] keys, String expression) {
this.keys = keys;
this.expression = expression;
}
/**
* value, key, index, size, first, last
*/
private final static Object[] objects = {null, 0, 0, 1, true, true, null};
private static final WorkCenterMap setVar(WorkCenterMap centerMap, String[] keys, Object data) {
Object[] values = objects;
centerMap.put(keys[0], data);
for (int i = 1, len = keys.length; i < len; i++) {
centerMap.put(keys[i], values[i]);
}
return centerMap;
}
@Override
public boolean isEq() {
return true;
}
@Override
public void beforeSetAndRender(WorkCenterMap centerMap, CenterRenderer target) {
setVar(centerMap, keys, RunnerUtil.run(expression, centerMap));
}
}
| 25.902439 | 100 | 0.627119 |
cd4f43c46f0eaffd6112ff5f608a0d0fe77d888c | 1,441 | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class VariableLengthQuantity {
private long sevenBitsMask = 0x7f;
private long eightBitsMask = 0x80;
List<String> encodeSingleNumber(long number) {
List<String> bytes = new ArrayList<String>();
bytes.add("0x" + Long.toHexString(number & sevenBitsMask));
number >>= 7;
while (number > 0) {
bytes.add("0x" + Long.toHexString(number & sevenBitsMask | eightBitsMask));
number >>= 7;
}
Collections.reverse(bytes);
return bytes;
}
List<String> encode(List<Long> numbers) {
List<String> bytes = new ArrayList<String>();
for (long number : numbers) {
bytes.addAll(encodeSingleNumber(number));
}
return bytes;
}
List<String> decode(List<Long> bytes) {
List<String> numbers = new ArrayList<String>();
int i = 0;
long number = 0;
for (long b : bytes) {
number <<= 7;
number += b & sevenBitsMask;
if ((b & eightBitsMask) == 0) {
numbers.add("0x" + Long.toHexString(number));
number = 0;
i++;
} else if (i == bytes.size() - 1) {
throw new IllegalArgumentException("Invalid variable-length quantity encoding");
}
}
return numbers;
}
}
| 26.685185 | 96 | 0.546842 |
3601790e2e1b2d9c31891e5c1efb9377a744ae63 | 2,424 | package com.github.badpop.jcoinbase.service.account.dto;
import com.github.badpop.jcoinbase.model.ResourceType;
import com.github.badpop.jcoinbase.model.account.Account;
import com.github.badpop.jcoinbase.model.account.AccountType;
import com.github.badpop.jcoinbase.model.account.Rewards;
import com.github.badpop.jcoinbase.service.utils.DateAndTimeUtils;
import lombok.val;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;
class AccountDtoTest {
@Test
void should_map_to_Account() {
val currency =
new AccountCurrencyDto(
"BTC",
"Bitcoin",
"yellow",
1,
8,
"crypto",
"regex",
"assetId",
"bitcoin",
"destTagName",
"destTagRegex");
val balance = new AccountBalanceDto(BigDecimal.valueOf(10), "BTC");
val dto =
new AccountDto(
"id",
"name",
false,
"type",
currency,
balance,
Instant.ofEpochSecond(192362328),
Instant.ofEpochSecond(192362328),
"resource",
"resourcePath",
true,
true,
"2.00%",
new RewardsDto("0.02", "2,00%", "2,00% APY"));
val actual = dto.toAccount();
assertThat(actual)
.isInstanceOf(Account.class)
.usingRecursiveComparison()
.isEqualTo(
Account.builder()
.id("id")
.name("name")
.primary(false)
.type(AccountType.UNKNOWN)
.currency(currency.toAccountCurrency())
.balance(balance.toAccountBalance())
.creationDate(
DateAndTimeUtils.fromInstant(Instant.ofEpochSecond(192362328)).getOrNull())
.lastUpdateDate(
DateAndTimeUtils.fromInstant(Instant.ofEpochSecond(192362328)).getOrNull())
.resourceType(ResourceType.UNKNOWN)
.resourcePath("resourcePath")
.allowDeposits(true)
.allowWithdrawals(true)
.rewardsApy("2.00%")
.rewards(
Rewards.builder().apy("0.02").formattedApy("2,00%").label("2,00% APY").build())
.build());
}
}
| 30.3 | 99 | 0.554043 |
f68f02d751a6b7a88614c4aefc12aa7615c63704 | 7,442 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.common.stats;
import android.app.Service;
import android.content.*;
import android.util.Log;
import com.google.android.gms.common.util.ClientLibraryUtils;
import java.util.Collections;
import java.util.List;
public class ConnectionTracker
{
private ConnectionTracker()
{
// 0 0:aload_0
// 1 1:invokespecial #22 <Method void Object()>
zzyi = Collections.EMPTY_LIST;
// 2 4:aload_0
// 3 5:getstatic #32 <Field List Collections.EMPTY_LIST>
// 4 8:putfield #34 <Field List zzyi>
zzyj = Collections.EMPTY_LIST;
// 5 11:aload_0
// 6 12:getstatic #32 <Field List Collections.EMPTY_LIST>
// 7 15:putfield #36 <Field List zzyj>
zzyk = Collections.EMPTY_LIST;
// 8 18:aload_0
// 9 19:getstatic #32 <Field List Collections.EMPTY_LIST>
// 10 22:putfield #38 <Field List zzyk>
zzyl = Collections.EMPTY_LIST;
// 11 25:aload_0
// 12 26:getstatic #32 <Field List Collections.EMPTY_LIST>
// 13 29:putfield #40 <Field List zzyl>
// 14 32:return
}
public static ConnectionTracker getInstance()
{
if(zzyg == null)
//* 0 0:getstatic #44 <Field ConnectionTracker zzyg>
//* 1 3:ifnonnull 38
synchronized(zztm)
//* 2 6:getstatic #24 <Field Object zztm>
//* 3 9:astore_0
//* 4 10:aload_0
//* 5 11:monitorenter
{
if(zzyg == null)
//* 6 12:getstatic #44 <Field ConnectionTracker zzyg>
//* 7 15:ifnonnull 28
zzyg = new ConnectionTracker();
// 8 18:new #2 <Class ConnectionTracker>
// 9 21:dup
// 10 22:invokespecial #45 <Method void ConnectionTracker()>
// 11 25:putstatic #44 <Field ConnectionTracker zzyg>
}
// 12 28:aload_0
// 13 29:monitorexit
break MISSING_BLOCK_LABEL_38;
// 14 30:goto 38
exception;
// 15 33:astore_1
obj;
// 16 34:aload_0
JVM INSTR monitorexit ;
// 17 35:monitorexit
throw exception;
// 18 36:aload_1
// 19 37:athrow
return zzyg;
// 20 38:getstatic #44 <Field ConnectionTracker zzyg>
// 21 41:areturn
}
private static boolean zza(Context context, String s, Intent intent, ServiceConnection serviceconnection, int i, boolean flag)
{
if(flag)
//* 0 0:iload 5
//* 1 2:ifeq 45
{
s = ((String) (intent.getComponent()));
// 2 5:aload_2
// 3 6:invokevirtual #56 <Method ComponentName Intent.getComponent()>
// 4 9:astore_1
if(s == null)
//* 5 10:aload_1
//* 6 11:ifnonnull 20
flag = false;
// 7 14:iconst_0
// 8 15:istore 5
else
//* 9 17:goto 30
flag = ClientLibraryUtils.isPackageStopped(context, ((ComponentName) (s)).getPackageName());
// 10 20:aload_0
// 11 21:aload_1
// 12 22:invokevirtual #62 <Method String ComponentName.getPackageName()>
// 13 25:invokestatic #68 <Method boolean ClientLibraryUtils.isPackageStopped(Context, String)>
// 14 28:istore 5
if(flag)
//* 15 30:iload 5
//* 16 32:ifeq 45
{
Log.w("ConnectionTracker", "Attempted to bind to a service in a STOPPED package.");
// 17 35:ldc1 #70 <String "ConnectionTracker">
// 18 37:ldc1 #72 <String "Attempted to bind to a service in a STOPPED package.">
// 19 39:invokestatic #78 <Method int Log.w(String, String)>
// 20 42:pop
return false;
// 21 43:iconst_0
// 22 44:ireturn
}
}
return context.bindService(intent, serviceconnection, i);
// 23 45:aload_0
// 24 46:aload_2
// 25 47:aload_3
// 26 48:iload 4
// 27 50:invokevirtual #84 <Method boolean Context.bindService(Intent, ServiceConnection, int)>
// 28 53:ireturn
}
public boolean bindService(Context context, Intent intent, ServiceConnection serviceconnection, int i)
{
return bindService(context, ((Object) (context)).getClass().getName(), intent, serviceconnection, i);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_1
// 3 3:invokevirtual #90 <Method Class Object.getClass()>
// 4 6:invokevirtual #95 <Method String Class.getName()>
// 5 9:aload_2
// 6 10:aload_3
// 7 11:iload 4
// 8 13:invokevirtual #98 <Method boolean bindService(Context, String, Intent, ServiceConnection, int)>
// 9 16:ireturn
}
public boolean bindService(Context context, String s, Intent intent, ServiceConnection serviceconnection, int i)
{
return zza(context, s, intent, serviceconnection, i, true);
// 0 0:aload_1
// 1 1:aload_2
// 2 2:aload_3
// 3 3:aload 4
// 4 5:iload 5
// 5 7:iconst_1
// 6 8:invokestatic #100 <Method boolean zza(Context, String, Intent, ServiceConnection, int, boolean)>
// 7 11:ireturn
}
public boolean bindServiceAllowStoppedPackages(Context context, String s, Intent intent, ServiceConnection serviceconnection, int i)
{
return zza(context, s, intent, serviceconnection, i, false);
// 0 0:aload_1
// 1 1:aload_2
// 2 2:aload_3
// 3 3:aload 4
// 4 5:iload 5
// 5 7:iconst_0
// 6 8:invokestatic #100 <Method boolean zza(Context, String, Intent, ServiceConnection, int, boolean)>
// 7 11:ireturn
}
public void logConnectService(Context context, ServiceConnection serviceconnection, String s, Intent intent)
{
// 0 0:return
}
public void logDisconnectService(Context context, ServiceConnection serviceconnection)
{
// 0 0:return
}
public void logStartService(Service service, int i)
{
// 0 0:return
}
public void logStopService(Service service, int i)
{
// 0 0:return
}
public void unbindService(Context context, ServiceConnection serviceconnection)
{
context.unbindService(serviceconnection);
// 0 0:aload_1
// 1 1:aload_2
// 2 2:invokevirtual #112 <Method void Context.unbindService(ServiceConnection)>
// 3 5:return
}
private static final Object zztm = new Object();
private static volatile ConnectionTracker zzyg;
private static boolean zzyh = false;
private final List zzyi;
private final List zzyj;
private final List zzyk;
private final List zzyl;
static
{
// 0 0:new #4 <Class Object>
// 1 3:dup
// 2 4:invokespecial #22 <Method void Object()>
// 3 7:putstatic #24 <Field Object zztm>
// 4 10:iconst_0
// 5 11:putstatic #26 <Field boolean zzyh>
//* 6 14:return
}
}
| 34.775701 | 133 | 0.569605 |
72bfbdf924186d8895cf230a35a6a11dce5735a1 | 503 | package solutions;
import org.junit.Assert;
import org.junit.Test;
public class MovingAverageFromDataStreamTests {
@Test
public void testExample1() {
var solution = new MovingAverageFromDataStream(3);
Assert.assertEquals(1.0, solution.next(1), 0.01);
Assert.assertEquals((1 + 10) / 2.0, solution.next(10), 0.01);
Assert.assertEquals((1 + 10 + 3) / 3.0, solution.next(3), 0.01);
Assert.assertEquals((10 + 3 + 5) / 3.0, solution.next(5), 0.01);
}
}
| 27.944444 | 72 | 0.638171 |
7fd5d7f300b9fe4bc790db8e251a9f9315879361 | 1,988 | /* */ package listener;
/* */
/* */ import java.util.HashMap;
/* */ import main.Main;
/* */ import net.md_5.bungee.api.chat.BaseComponent;
/* */ import net.md_5.bungee.api.chat.TextComponent;
/* */ import net.md_5.bungee.api.connection.ProxiedPlayer;
/* */ import net.md_5.bungee.api.event.ChatEvent;
/* */ import net.md_5.bungee.api.plugin.Listener;
/* */ import net.md_5.bungee.event.EventHandler;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class ChatListener
/* */ implements Listener
/* */ {
/* 22 */ HashMap<ProxiedPlayer, Long> spam = new HashMap<>();
/* */
/* */ @EventHandler
/* */ public void onChat(ChatEvent e) {
/* 26 */ ProxiedPlayer p = (ProxiedPlayer)e.getSender();
/* 27 */ String msg = e.getMessage().replaceAll("%", "%%");
/* */
/* 29 */ if (p.hasPermission("admin.bypass")) {
/* 30 */ if (this.spam.containsKey(p)) {
/* 31 */ if (((Long)this.spam.get(p)).longValue() > System.currentTimeMillis()) {
/* 32 */ e.setCancelled(true);
/* */ } else {
/* */
/* 35 */ this.spam.put(p, Long.valueOf(System.currentTimeMillis() + 0L));
/* */ }
/* */ } else {
/* 38 */ this.spam.put(p, Long.valueOf(System.currentTimeMillis() + 0L));
/* */ }
/* */
/* */ }
/* 42 */ else if (this.spam.containsKey(p)) {
/* 43 */ if (((Long)this.spam.get(p)).longValue() > System.currentTimeMillis()) {
/* 44 */ e.setCancelled(true);
/* 45 */ p.sendMessage((BaseComponent)new TextComponent(Main.prefix + "&bDu darfst auf diesem Netzwerk §fnicht §bSpammen!"));
/* */ } else {
/* 47 */ this.spam.put(p, Long.valueOf(System.currentTimeMillis() + 3000L));
/* */ }
/* */ } else {
/* 50 */ this.spam.put(p, Long.valueOf(System.currentTimeMillis() + 3000L));
/* */ }
/* */ }
/* */ }
| 36.814815 | 133 | 0.507545 |
b496e7d77954d0207c19f4573df7551968a71f39 | 2,816 | package toughasnails.temperature.modifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable;
import toughasnails.api.temperature.IModifierMonitor;
import toughasnails.api.temperature.ITemperatureModifier;
import toughasnails.api.temperature.Temperature;
public abstract class TemperatureModifier implements ITemperatureModifier
{
private final String id;
public TemperatureModifier(String id)
{
this.id = id;
}
@Override
public Temperature applyEnvironmentModifiers(World world, BlockPos pos, Temperature initialTemperature, IModifierMonitor monitor)
{
return initialTemperature;
}
@Override
public Temperature applyPlayerModifiers(EntityPlayer player, Temperature initialTemperature, IModifierMonitor monitor)
{
return initialTemperature;
}
@Override
public abstract boolean isPlayerSpecific();
@Override
public String getId()
{
return this.id;
}
public static class ExternalModifier implements INBTSerializable<NBTTagCompound>
{
private String name;
private int amount;
private int rate;
private int endTime;
public ExternalModifier() {}
public ExternalModifier(String name, int amount, int rate, int endTime)
{
this.name = name;
this.amount = amount;
this.rate = rate;
this.endTime = endTime;
}
public String getName()
{
return this.name;
}
public int getAmount()
{
return this.amount;
}
public int getRate()
{
return this.rate;
}
public int getEndTime()
{
return this.endTime;
}
public void setEndTime(int time)
{
this.endTime = time;
}
@Override
public NBTTagCompound serializeNBT()
{
NBTTagCompound compound = new NBTTagCompound();
compound.setString("Name", this.name);
compound.setInteger("Amount", this.amount);
compound.setInteger("Rate", this.rate);
compound.setInteger("EndTime", this.endTime);
return compound;
}
@Override
public void deserializeNBT(NBTTagCompound nbt)
{
this.name = nbt.getString("Name");
this.amount = nbt.getInteger("Amount");
this.rate = nbt.getInteger("Rate");
this.endTime = nbt.getInteger("EndTime");
}
}
}
| 26.317757 | 133 | 0.602273 |
937f166e076ae1d2b10ea25a6f4bed59b763a8ad | 3,512 | package id.xaxxis.myintenapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnMoveActivity, btnMoveWithData, btnMoveWithObject, btnDialPhone, btnMoveForResult;
TextView tvResult;
private int REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMoveActivity = findViewById(R.id.btn_move_acivity);
btnMoveActivity.setOnClickListener(this);
btnMoveWithData = findViewById(R.id.btn_move_with_data);
btnMoveWithData.setOnClickListener(this);
btnMoveWithObject = findViewById(R.id.btn_move_activity_object);
btnMoveWithObject.setOnClickListener(this);
btnDialPhone = findViewById(R.id.btn_dial_number);
btnDialPhone.setOnClickListener(this);
btnMoveForResult = findViewById(R.id.btn_move_with_result);
btnMoveForResult.setOnClickListener(this);
tvResult = findViewById(R.id.tv_result);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_move_acivity:
Intent moveIntent = new Intent(MainActivity.this, MoveActivity.class);
startActivity(moveIntent);
break;
case R.id.btn_move_with_data:
Intent moveWithDataIntent = new Intent(MainActivity.this, MoveWithDataActivity.class);
moveWithDataIntent.putExtra(MoveWithDataActivity.EXTRA_NAME, "DicodingAcademy Boy");
moveWithDataIntent.putExtra(MoveWithDataActivity.EXTRA_AGE, 5);
startActivity(moveWithDataIntent);
break;
case R.id.btn_move_activity_object:
Person person = new Person();
person.setName("DicodingAcademy");
person.setAge(5);
person.setEmail("academy@dicoding.com");
person.setCity("Jakarta");
Intent moveWithObject = new Intent(MainActivity.this, MoveWithObjectActivity.class);
moveWithObject.putExtra(MoveWithObjectActivity.EXTRA_PERSON, person);
startActivity(moveWithObject);
break;
case R.id.btn_dial_number:
String number = "+6287782227767";
Intent dialPhoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" +number));
startActivity(dialPhoneIntent);
break;
case R.id.btn_move_with_result:
Intent moveActivityForReslut = new Intent(MainActivity.this, MoveForResultActivity.class);
startActivityForResult(moveActivityForReslut, REQUEST_CODE);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE){
if(resultCode == MoveForResultActivity.RESULT_CODE){
int selectedValue = data.getIntExtra(MoveForResultActivity.EXTRA_SELECTED_VALUE,0);
tvResult.setText(String.format("Hasil : %s", selectedValue));
}
}
}
}
| 39.022222 | 106 | 0.664009 |
86eb6cfa18895f1b7f9058409fd52dd0eafdcd8d | 22,179 | /*
* Copyright 2011 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.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.drools.guvnor.client.rpc.AdminArchivedPageRow;
import org.drools.guvnor.client.rpc.Asset;
import org.drools.guvnor.client.rpc.AssetPageRequest;
import org.drools.guvnor.client.rpc.AssetPageRow;
import org.drools.guvnor.client.rpc.AssetService;
import org.drools.guvnor.client.rpc.BuilderResult;
import org.drools.guvnor.client.rpc.ConversionResult;
import org.drools.guvnor.client.rpc.DetailedSerializationException;
import org.drools.guvnor.client.rpc.DiscussionRecord;
import org.drools.guvnor.client.rpc.PageRequest;
import org.drools.guvnor.client.rpc.PageResponse;
import org.drools.guvnor.client.rpc.PushResponse;
import org.drools.guvnor.client.rpc.QueryPageRequest;
import org.drools.guvnor.client.rpc.QueryPageRow;
import org.drools.guvnor.client.rpc.TableDataResult;
import org.drools.guvnor.server.cache.RuleBaseCache;
import org.drools.guvnor.server.contenthandler.ContentHandler;
import org.drools.guvnor.server.contenthandler.ContentManager;
import org.drools.guvnor.server.contenthandler.ICanHasAttachment;
import org.drools.guvnor.server.converters.ConversionService;
import org.drools.guvnor.server.repository.Preferred;
import org.drools.guvnor.server.repository.UserInbox;
import org.drools.guvnor.server.util.AssetPopulator;
import org.drools.guvnor.server.util.Discussion;
import org.drools.guvnor.server.util.LoggingHelper;
import org.drools.repository.AssetItem;
import org.drools.repository.ModuleItem;
import org.drools.repository.RulesRepository;
import org.drools.repository.RulesRepositoryException;
import org.drools.repository.VersionableItem;
import com.google.gwt.user.client.rpc.SerializationException;
import org.drools.guvnor.client.rpc.Path;
import org.drools.guvnor.client.rpc.PathImpl;
import org.jboss.solder.core.Veto;
import org.uberfire.security.annotations.Roles;
@ApplicationScoped
//@Named("org.drools.guvnor.client.rpc.AssetService")
//@Veto
public class RepositoryAssetService
implements
AssetService {
private static final long serialVersionUID = 90111;
private static final LoggingHelper log = LoggingHelper.getLogger( RepositoryAssetService.class );
@Inject @Preferred
protected RulesRepository rulesRepository;
@Inject
protected RepositoryAssetOperations repositoryAssetOperations;
@Inject
protected Backchannel backchannel;
@Inject
private ConversionService conversionService;
public RulesRepository getRulesRepository() {
return rulesRepository;
}
/**
* This actually does the hard work of loading up an asset based on its
* format.
* <p/>
* Role-based Authorization check: This method can be accessed if user has
* following permissions: 1. The user has a ANALYST_READ role or higher
* (i.e., ANALYST) and this role has permission to access the category which
* the asset belongs to. Or. 2. The user has a package.readonly role or
* higher (i.e., package.admin, package.developer) and this role has
* permission to access the package which the asset belongs to.
*/
public Asset loadRuleAsset(Path assetPath) throws SerializationException {
long time = System.currentTimeMillis();
AssetItem item = rulesRepository.loadAssetByUUID( assetPath.getUUID() );
Asset asset = new AssetPopulator().populateFrom( item );
asset.setMetaData( repositoryAssetOperations.populateMetaData( item ) );
ModuleItem pkgItem = handlePackageItem( item,
asset );
log.debug( "Package: " + pkgItem.getName() + ", asset: " + item.getName() + ". Load time taken for asset: " + (System.currentTimeMillis() - time) );
UserInbox.recordOpeningEvent( item );
return asset;
}
private ModuleItem handlePackageItem(AssetItem item,
Asset asset) throws SerializationException {
ModuleItem packageItem = item.getModule();
ContentHandler handler = ContentManager.getHandler( asset.getFormat() );
handler.retrieveAssetContent( asset,
item );
asset.setReadonly( asset.getMetaData().isHasSucceedingVersion() || asset.isArchived() );
if ( packageItem.isSnapshot() ) {
asset.setReadonly( true );
}
return packageItem;
}
public Asset[] loadRuleAssets(Path[] assetPaths) throws SerializationException {
return loadRuleAssets( Arrays.asList( assetPaths ) );
}
public String checkinVersion(Asset asset) throws SerializationException {
log.info( "USER:" + getCurrentUserName() + " CHECKING IN asset: [" + asset.getName() + "] UUID: [" + asset.getUuid() + "] " );
return repositoryAssetOperations.checkinVersion( asset );
}
public void restoreVersion(Path versionPath,
Path assetPath,
String comment) {
repositoryAssetOperations.restoreVersion( versionPath,
assetPath,
comment );
}
public TableDataResult loadItemHistory(Path path) throws SerializationException {
//VersionableItem assetItem = rulesRepository.loadAssetByUUID( uuid );
VersionableItem assetItem = rulesRepository.loadItemByUUID( path.getUUID() );
//serviceSecurity.checkSecurityAssetPackagePackageReadOnly( assetItem );
return repositoryAssetOperations.loadItemHistory( assetItem );
}
/**
* @deprecated in favour of {@link #loadArchivedAssets(PageRequest)}
*/
public TableDataResult loadAssetHistory(String packageUUID,
String assetName) throws SerializationException {
ModuleItem pi = rulesRepository.loadModuleByUUID( packageUUID );
AssetItem assetItem = pi.loadAsset( assetName );
return repositoryAssetOperations.loadItemHistory( assetItem );
}
@Deprecated
public TableDataResult loadArchivedAssets(int skip,
int numRows) throws SerializationException {
return repositoryAssetOperations.loadArchivedAssets( skip,
numRows );
}
public PageResponse<AdminArchivedPageRow> loadArchivedAssets(PageRequest request) throws SerializationException {
if ( request == null ) {
throw new IllegalArgumentException( "request cannot be null" );
}
if ( request.getPageSize() != null && request.getPageSize() < 0 ) {
throw new IllegalArgumentException( "pageSize cannot be less than zero." );
}
return repositoryAssetOperations.loadArchivedAssets( request );
}
/**
* @deprecated in favour of {@link #findAssetPage(AssetPageRequest)}
*/
public TableDataResult listAssets(Path modulePath,
String formats[],
int skip,
int numRows,
String tableConfig) throws SerializationException {
log.debug( "Loading asset list for [" + modulePath + "]" );
if ( numRows == 0 ) {
throw new DetailedSerializationException( "Unable to return zero results (bug)",
"probably have the parameters around the wrong way, sigh..." );
}
return repositoryAssetOperations.listAssets( modulePath,
formats,
skip,
numRows,
tableConfig );
}
public Path copyAsset(Path assetPath,
String newPackage,
String newName) {
log.info( "USER:" + getCurrentUserName() + " COPYING asset: [" + assetPath + "] to [" + newName + "] in PACKAGE [" + newPackage + "]" );
String copiedAssetUUID = rulesRepository.copyAsset( assetPath.getUUID(),
newPackage,
newName );
Path path = new PathImpl();
path.setUUID(copiedAssetUUID);
return path;
}
public void changeAssetPackage(Path assetPath,
String newPackage,
String comment) {
AssetItem item = rulesRepository.loadAssetByUUID( assetPath.getUUID() );
//Perform house-keeping for when an Asset is removed from a package
attachmentRemoved( item );
log.info( "USER:" + getCurrentUserName() + " CHANGING PACKAGE OF asset: [" + assetPath + "] to [" + newPackage + "]" );
rulesRepository.moveRuleItemModule( newPackage,
assetPath.getUUID(),
comment );
//Perform house-keeping for when an Asset is added to a package
attachmentAdded( item );
}
public void promoteAssetToGlobalArea(Path assetPath) {
AssetItem item = rulesRepository.loadAssetByUUID( assetPath.getUUID() );
//Perform house-keeping for when an Asset is removed from a module
attachmentRemoved( item );
log.info( "USER:" + getCurrentUserName() + " CHANGING MODULE OF asset: [" + assetPath + "] to [ globalArea ]" );
rulesRepository.moveRuleItemModule( RulesRepository.GLOBAL_AREA,
assetPath.getUUID(),
"promote asset to globalArea" );
//Perform house-keeping for when an Asset is added to a module
attachmentAdded( item );
}
public String buildAssetSource(Asset asset) throws SerializationException {
return repositoryAssetOperations.buildAssetSource( asset );
}
public Path renameAsset(Path uuid,
String newName) {
AssetItem item = rulesRepository.loadAssetByUUID( uuid.getUUID() );
return repositoryAssetOperations.renameAsset( uuid,
newName );
}
public void archiveAsset(Path path) {
archiveOrUnarchiveAsset( path,
true );
}
public BuilderResult validateAsset(Asset asset) throws SerializationException {
return repositoryAssetOperations.validateAsset( asset );
}
public void unArchiveAsset(Path path) {
archiveOrUnarchiveAsset( path,
false );
}
public void archiveAssets(Path[] paths,
boolean value) {
for ( Path uuid : paths ) {
archiveOrUnarchiveAsset( uuid,
value );
}
}
public void removeAsset(Path path) {
try {
AssetItem item = rulesRepository.loadAssetByUUID( path.getUUID() );
item.remove();
rulesRepository.save();
} catch ( RulesRepositoryException e ) {
log.error( "Unable to remove asset.",
e );
throw e;
}
}
public void removeAssets(Path[] paths) {
for ( Path path : paths ) {
removeAsset( path );
}
}
public PageResponse<AssetPageRow> findAssetPage(AssetPageRequest request) throws SerializationException {
if ( request == null ) {
throw new IllegalArgumentException( "request cannot be null" );
}
if ( request.getPageSize() != null && request.getPageSize() < 0 ) {
throw new IllegalArgumentException( "pageSize cannot be less than zero." );
}
return repositoryAssetOperations.findAssetPage( request );
}
public PageResponse<QueryPageRow> quickFindAsset(QueryPageRequest request) throws SerializationException {
if ( request == null ) {
throw new IllegalArgumentException( "request cannot be null" );
}
if ( request.getPageSize() != null && request.getPageSize() < 0 ) {
throw new IllegalArgumentException( "pageSize cannot be less than zero." );
}
return repositoryAssetOperations.quickFindAsset( request );
}
/**
* @deprecated in favour of {@link #quickFindAsset(QueryPageRequest)}
*/
public TableDataResult quickFindAsset(String searchText,
boolean searchArchived,
int skip,
int numRows) throws SerializationException {
return repositoryAssetOperations.quickFindAsset( searchText,
searchArchived,
skip,
numRows );
}
/*
* (non-Javadoc)
* @see
* org.drools.guvnor.client.rpc.RepositoryService#lockAsset(java.lang.String
* )
*/
public void lockAsset(Path assetPath) {
repositoryAssetOperations.lockAsset( assetPath );
}
/*
* (non-Javadoc)
* @see
* org.drools.guvnor.client.rpc.RepositoryService#unLockAsset(java.lang.
* String)
*/
public void unLockAsset(Path assetPath) {
repositoryAssetOperations.unLockAsset( assetPath );
}
/**
* @deprecated in favour of
* {@link ServiceImplementation#queryFullText(QueryPageRequest)}
*/
public TableDataResult queryFullText(String text,
boolean seekArchived,
int skip,
int numRows) throws SerializationException {
if ( numRows == 0 ) {
throw new DetailedSerializationException( "Unable to return zero results (bug)",
"probably have the parameters around the wrong way, sigh..." );
}
return repositoryAssetOperations.queryFullText( text,
seekArchived,
skip,
numRows );
}
Asset[] loadRuleAssets(Collection<Path> paths) throws SerializationException {
if ( paths == null ) {
return null;
}
Collection<Asset> assets = new HashSet<Asset>();
for ( Path path : paths ) {
assets.add( loadRuleAsset( path ) );
}
return assets.toArray( new Asset[assets.size()] );
}
private void archiveOrUnarchiveAsset(Path path,
boolean archive) {
AssetItem item = rulesRepository.loadAssetByUUID( path.getUUID() );
if ( item.getModule().isArchived() ) {
throw new RulesRepositoryException( "The package [" + item.getModuleName() + "] that asset [" + item.getName() + "] belongs to is archived. You need to unarchive it first." );
}
log.info( "USER:" + getCurrentUserName() + " ARCHIVING asset: [" + item.getName() + "] UUID: [" + item.getUUID() + "] " );
try {
ContentHandler handler = getContentHandler( item );
if ( handler instanceof ICanHasAttachment ) {
((ICanHasAttachment) handler).onAttachmentRemoved( item );
}
} catch ( IOException e ) {
log.error( "Unable to remove asset attachment",
e );
}
item.archiveItem( archive );
ModuleItem pkg = item.getModule();
pkg.updateBinaryUpToDate( false );
RuleBaseCache.getInstance().remove( pkg.getUUID() );
if ( archive ) {
item.checkin( "archived" );
} else {
item.checkin( "unarchived" );
}
push( "packageChange",
pkg.getName() );
}
public List<DiscussionRecord> addToDiscussionForAsset(Path assetId,
String comment) {
return repositoryAssetOperations.addToDiscussionForAsset( assetId,
comment );
}
@Roles({"ADMIN"})
public void clearAllDiscussionsForAsset(final Path assetId) {
repositoryAssetOperations.clearAllDiscussionsForAsset( assetId );
}
public List<DiscussionRecord> loadDiscussionForAsset(Path assetPath) {
return new Discussion().fromString( rulesRepository.loadAssetByUUID( assetPath.getUUID() ).getStringProperty( Discussion.DISCUSSION_PROPERTY_KEY ) );
}
/**
* Role-based Authorization check: This method can be accessed if user has
* following permissions: 1. The user has a Analyst role and this role has
* permission to access the category which the asset belongs to. Or. 2. The
* user has a package.developer role or higher (i.e., package.admin) and
* this role has permission to access the package which the asset belongs
* to.
*/
public void changeState(Path assetPath,
String newState) {
AssetItem asset = rulesRepository.loadAssetByUUID( assetPath.getUUID() );
log.info( "USER:" + getCurrentUserName() + " CHANGING ASSET STATUS. Asset name, uuid: " + "[" + asset.getName() + ", " + asset.getUUID() + "]" + " to [" + newState + "]" );
String oldState = asset.getStateDescription();
asset.updateState( newState );
push( "statusChange",
oldState );
push( "statusChange",
newState );
Path path = new PathImpl();
path.setUUID(asset.getUUID());
addToDiscussionForAsset( path,
oldState + " -> " + newState );
rulesRepository.save();
}
public void changePackageState(String uuid,
String newState) {
ModuleItem pkg = rulesRepository.loadModuleByUUID( uuid );
log.info( "USER:" + getCurrentUserName() + " CHANGING Package STATUS. Asset name, uuid: " + "[" + pkg.getName() + ", " + pkg.getUUID() + "]" + " to [" + newState + "]" );
pkg.changeStatus( newState );
rulesRepository.save();
}
/*
* (non-Javadoc)
* @see
* org.drools.guvnor.client.rpc.RepositoryService#getAssetLockerUserName
* (java.lang.String)
*/
public String getAssetLockerUserName(Path assetPath) {
return repositoryAssetOperations.getAssetLockerUserName( assetPath );
}
public long getAssetCount(AssetPageRequest request) throws SerializationException {
if ( request == null ) {
throw new IllegalArgumentException( "request cannot be null" );
}
return repositoryAssetOperations.getAssetCount( request );
}
private void push(String messageType,
String message) {
backchannel.publish( new PushResponse( messageType,
message ) );
}
private ContentHandler getContentHandler(AssetItem repoAsset) {
return ContentManager.getHandler( repoAsset.getFormat() );
}
private String getCurrentUserName() {
return rulesRepository.getSession().getUserID();
}
//The Asset is being effectively deleted from the source package so treat as though the Content is being deleted
private void attachmentRemoved(AssetItem item) {
ICanHasAttachment attachmentHandler = null;
ContentHandler contentHandler = ContentManager.getHandler( item.getFormat() );
if ( contentHandler instanceof ICanHasAttachment ) {
attachmentHandler = (ICanHasAttachment) contentHandler;
try {
attachmentHandler.onAttachmentRemoved( item );
} catch ( IOException ioe ) {
log.error( "Unable to remove asset attachment",
ioe );
}
}
}
//The Asset is being effectively added to the target package so treat as though the Content is being added
private void attachmentAdded(AssetItem item) {
ICanHasAttachment attachmentHandler = null;
ContentHandler contentHandler = ContentManager.getHandler( item.getFormat() );
if ( contentHandler instanceof ICanHasAttachment ) {
attachmentHandler = (ICanHasAttachment) contentHandler;
try {
attachmentHandler.onAttachmentAdded( item );
} catch ( IOException ioe ) {
log.error( "Unable to remove asset attachment",
ioe );
}
}
}
public ConversionResult convertAsset(Path convertAsset,
String targetFormat) throws SerializationException {
AssetItem item = rulesRepository.loadAssetByUUID( convertAsset.getUUID() );
return conversionService.convert( item,
targetFormat );
}
}
| 40.472628 | 187 | 0.600703 |
d4eecf1740c476d3d440d91efba362d731139694 | 3,646 | package com.riiablo;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.riiablo.graphics.BlendMode;
import com.riiablo.codec.FontTBL;
import com.riiablo.loader.BitmapFontLoader;
public class Fonts {
public final BitmapFont consolas12;
public final BitmapFont consolas16;
public final FontTBL.BitmapFont font6;
public final FontTBL.BitmapFont font8;
public final FontTBL.BitmapFont font16;
public final FontTBL.BitmapFont font24;
public final FontTBL.BitmapFont font30;
public final FontTBL.BitmapFont font42;
public final FontTBL.BitmapFont fontformal10;
public final FontTBL.BitmapFont fontformal11;
public final FontTBL.BitmapFont fontformal12;
public final FontTBL.BitmapFont fontexocet10;
public final FontTBL.BitmapFont fontridiculous;
public final FontTBL.BitmapFont ReallyTheLastSucker;
public Fonts(AssetManager assets) {
consolas12 = loadEx(assets, "consolas12.fnt");
consolas16 = loadEx(assets, "consolas16.fnt");
font6 = load(assets, "font6", BlendMode.LUMINOSITY_TINT);
font8 = load(assets, "font8", BlendMode.LUMINOSITY_TINT);
font16 = load(assets, "font16", BlendMode.LUMINOSITY_TINT);
font24 = load(assets, "font24", BlendMode.ID);
font30 = load(assets, "font30", BlendMode.ID);
font42 = load(assets, "font42", BlendMode.ID);
fontformal10 = load(assets, "fontformal10", BlendMode.LUMINOSITY_TINT);
fontformal11 = load(assets, "fontformal11", BlendMode.LUMINOSITY_TINT);
fontformal12 = load(assets, "fontformal12", BlendMode.LUMINOSITY_TINT);
fontexocet10 = load(assets, "fontexocet10", BlendMode.TINT_BLACKS);
fontridiculous = load(assets, "fontridiculous", BlendMode.TINT_BLACKS);
ReallyTheLastSucker = load(assets, "ReallyTheLastSucker", BlendMode.ID);
BitmapFont.BitmapFontData data;
data = font8.getData();
data.lineHeight = data.xHeight = data.capHeight = 12;
data.ascent = 16;
data.down = -12;
data = font16.getData();
data.lineHeight = data.xHeight = data.capHeight = 14;
data.ascent = 17;
data.down = -16;
data = font42.getData();
data.lineHeight = data.xHeight = data.capHeight = 31;
data.ascent = 48;
data.down = -31;
data = fontformal10.getData();
data.lineHeight = data.xHeight = data.capHeight = 14;
data.ascent = 17;
data.down = -14;
data = fontformal11.getData();
data.lineHeight = data.xHeight = data.capHeight = 18;
data.ascent = 18;
data.down = -18;
data = fontformal12.getData();
data.lineHeight = data.xHeight = data.capHeight = 16;
data.ascent = 42;
data.down = -20;
data = ReallyTheLastSucker.getData();
data.lineHeight = data.xHeight = data.capHeight = 8;
data.ascent = 11;
data.down = -8;
}
private BitmapFont loadEx(AssetManager assets, String fontName) {
assets.load(fontName, BitmapFont.class);
assets.finishLoadingAsset(fontName);
return assets.get(fontName);
}
private FontTBL.BitmapFont load(AssetManager assets, String fontName, int blendMode) {
AssetDescriptor<FontTBL.BitmapFont> descriptor = getDescriptor(fontName, blendMode);
assets.load(descriptor);
assets.finishLoadingAsset(descriptor);
return assets.get(descriptor);
}
private static AssetDescriptor<FontTBL.BitmapFont> getDescriptor(String fontName, int blendMode) {
return new AssetDescriptor<>("data\\local\\font\\latin\\" + fontName + ".TBL", FontTBL.BitmapFont.class, BitmapFontLoader.Params.of(blendMode));
}
}
| 37.587629 | 148 | 0.715579 |
b5f9f3477e88270e0efce4e11cb9bd0f3868357d | 292 | static void dfs1(int start, int par, int d) {
D[start] = d;
L[start][0] = par;
for (int i = 1; i < ln; i++) {
L[start][i] = L[L[start][i - 1]][i - 1];
}
for (int u : graph[start]) {
if (u == par)
continue;
dfs1(u, start, d + 1);
}
} | 24.333333 | 48 | 0.417808 |
e9d9b27527a6c66d82a1a3ed10847c9169d325c7 | 263 | package com.liu.service;
import com.liu.controller.student.vo.UncheckedVO;
import com.liu.util.PageQueryUtils;
import com.liu.util.PageResult;
import java.util.List;
public interface UncheckedService {
PageResult getUncheckedPage(PageQueryUtils utils);
}
| 20.230769 | 54 | 0.806084 |
70aac16597ac7dd875646e458c56bf805e194dda | 20,494 | package org.puretemplate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.puretemplate.error.RuntimeMessage;
import org.puretemplate.exception.NoSuchPropertyException;
import org.puretemplate.misc.ErrorBufferAllErrors;
import com.google.common.collect.ImmutableMap;
@Slf4j
class TestCoreBasics2 extends BaseTest
{
@Test
void testNullAttr()
{
assertNoArgRenderingResult("hi !", "hi <name>!");
}
@Test
void testAttr()
{
Context context = makeTemplateContext("hi <name>!").add("name", "Ter");
assertRenderingResult("hi Ter!", context);
}
@Test
void testChainAttr()
{
Context context = makeTemplateContext("<x>:<names>!").add("names", "Ter")
.add("names", "Tom")
.add("x", 1);
assertRenderingResult("1:TerTom!", context);
}
@Test
void testSetUnknownAttr()
{
String templates = "t() ::= <<hi <name>!>>\n";
Context context = loadGroupFromString(templates).getTemplate("t")
.createContext();
String result = null;
try
{
context.add("name", "Ter");
}
catch (IllegalArgumentException iae)
{
result = iae.getMessage();
}
String expected = "no such attribute: name";
assertEquals(expected, result);
}
@Test
void testMultiAttr()
{
Context context = makeTemplateContext("hi <name>!").add("name", "Ter")
.add("name", "Tom");
assertRenderingResult("hi TerTom!", context);
}
@Test
void testAttrIsList()
{
Context context = makeTemplateContext("hi <name>!");
List<String> names = List.of("Ter", "Tom");
context.add("name", names);
context.add("name", "Sumana");
assertRenderingResult("hi TerTomSumana!", context);
assertEquals(2, names.size()); // my names list is still just 2
}
@Test
void testAttrIsArray()
{
Context context = makeTemplateContext("hi <name>!");
String[] names = new String[]{ "Ter", "Tom" };
context.add("name", names);
context.add("name", "Sumana");
assertRenderingResult("hi TerTomSumana!", context);
}
@Test
void testProp()
{
String template = "<u.id>: <u.name>"; // checks field and method getter
Context context = makeTemplateContext(template).add("u", new User(1, "parrt"));
assertRenderingResult("1: parrt", context);
}
@Test
void testPropWithNoAttr()
{
Context context = makeTemplateContext("<foo.a>: <ick>").add("foo", Map.of("a", "b"));
assertRenderingResult("b: ", context);
}
@Test
void testMapAcrossDictionaryUsesKeys()
{
String template = "<foo:{f | <f>}>"; // checks field and method getter
Context context = makeTemplateContext(template).add("foo", ImmutableMap.of("a", "b", "c", "d"));
assertRenderingResult("ac", context);
}
@Test
void testSTProp()
{
String template = "<t.x>"; // get x attr of template context t
Context t = makeTemplateContext("<x>").add("x", "Ter");
Context context = makeTemplateContext(template).add("t", t);
assertRenderingResult("Ter", context);
}
@Test
void testBooleanISProp()
{
String template = "<t.manager>"; // call isManager
Context context = makeTemplateContext(template).add("t", new User(32, "Ter"));
assertRenderingResult("true", context);
}
@Test
void testBooleanHASProp()
{
String template = "<t.parkingSpot>"; // call hasParkingSpot
Context context = makeTemplateContext(template).add("t", new User(32, "Ter"));
assertRenderingResult("true", context);
}
@Test
void testNullAttrProp()
{
assertNoArgRenderingResult(": ", "<u.id>: <u.name>");
}
@Test
void testNoSuchProp() throws IOException
{
ErrorBufferAllErrors errors = new ErrorBufferAllErrors();
String template = "<u.qqq>";
STGroup group = new LegacyBareStGroup();
group.setListener(errors);
ST st = new ST(group, template);
st.add("u", new User(1, "parrt"));
assertRenderingResult("", st);
RuntimeMessage msg = (RuntimeMessage) errors.getErrors()
.get(0);
NoSuchPropertyException e = (NoSuchPropertyException) msg.getCause();
assertEquals("org.puretemplate.BaseTest$User.qqq", e.getPropertyName());
}
@Test
void testNullIndirectProp() throws IOException
{
ErrorBufferAllErrors errors = new ErrorBufferAllErrors();
STGroup group = new LegacyBareStGroup();
group.setListener(errors);
String template = "<u.(qqq)>";
ST st = new ST(group, template);
st.add("u", new User(1, "parrt"));
st.add("qqq", null);
assertRenderingResult("", st);
RuntimeMessage msg = (RuntimeMessage) errors.getErrors()
.get(0);
NoSuchPropertyException e = (NoSuchPropertyException) msg.getCause();
assertEquals("org.puretemplate.BaseTest$User.null", e.getPropertyName());
}
@Test
void testPropConvertsToString() throws IOException
{
ErrorBufferAllErrors errors = new ErrorBufferAllErrors();
STGroup group = new LegacyBareStGroup();
group.setListener(errors);
String template = "<u.(name)>";
ST st = new ST(group, template);
st.add("u", new User(1, "parrt"));
st.add("name", 100);
assertRenderingResult("", st);
RuntimeMessage msg = (RuntimeMessage) errors.getErrors()
.get(0);
NoSuchPropertyException e = (NoSuchPropertyException) msg.getCause();
assertEquals("org.puretemplate.BaseTest$User.100", e.getPropertyName());
}
@Test
void testInclude() throws IOException
{
String template = "load <box()>;";
ST st = new ST(template);
st.getImpl().nativeGroup.defineTemplate("box", "kewl" + NEWLINE + "daddy");
assertRenderingResult("load kewl" + NEWLINE + "daddy;", st);
}
@Test
void testIncludeWithArg() throws IOException
{
String template = "load <box(\"arg\")>;";
ST st = new ST(template);
st.getImpl().nativeGroup.defineTemplate("box", "x", "kewl <x> daddy");
dump(log, st.getImpl());
st.add("name", "Ter");
assertRenderingResult("load kewl arg daddy;", st);
}
@Test
void testIncludeWithEmptySubtemplateArg() throws IOException
{
String template = "load <box({})>;";
ST st = new ST(template);
st.getImpl().nativeGroup.defineTemplate("box", "x", "kewl <x> daddy");
dump(log, st.getImpl());
st.add("name", "Ter");
assertRenderingResult("load kewl daddy;", st);
}
@Test
void testIncludeWithArg2() throws IOException
{
String template = "load <box(\"arg\", foo())>;";
ST st = new ST(template);
st.getImpl().nativeGroup.defineTemplate("box", "x,y", "kewl <x> <y> daddy");
st.getImpl().nativeGroup.defineTemplate("foo", "blech");
st.add("name", "Ter");
assertRenderingResult("load kewl arg blech daddy;", st);
}
@Test
void testIncludeWithNestedArgs() throws IOException
{
String template = "load <box(foo(\"arg\"))>;";
ST st = new ST(template);
st.getImpl().nativeGroup.defineTemplate("box", "y", "kewl <y> daddy");
st.getImpl().nativeGroup.defineTemplate("foo", "x", "blech <x>");
st.add("name", "Ter");
assertRenderingResult("load kewl blech arg daddy;", st);
}
@Test
void testDefineTemplate() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("inc", "x", "<x>+1");
group.defineTemplate("test", "name", "hi <name>!");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", "Sumana");
assertRenderingResult("hi TerTomSumana!", st);
}
@Test
void testMap() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("inc", "x", "[<x>]");
group.defineTemplate("test", "name", "hi <name:inc()>!");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", "Sumana");
assertRenderingResult("hi [Ter][Tom][Sumana]!", st);
}
@Test
void testIndirectMap() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("inc", "x", "[<x>]");
group.defineTemplate("test", "t,name", "<name:(t)()>!");
ST st = group.getInstanceOf("test");
st.add("t", "inc");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", "Sumana");
assertRenderingResult("[Ter][Tom][Sumana]!", st);
}
@Test
void testParallelMap() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names,phones", "hi <names,phones:{n,p | <n>:<p>;}>");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", "Tom");
st.add("names", "Sumana");
st.add("phones", "x5001");
st.add("phones", "x5002");
st.add("phones", "x5003");
assertRenderingResult("hi Ter:x5001;Tom:x5002;Sumana:x5003;", st);
}
@Test
void testParallelMapWith3Versus2Elements() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names,phones", "hi <names,phones:{n,p | <n>:<p>;}>");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", "Tom");
st.add("names", "Sumana");
st.add("phones", "x5001");
st.add("phones", "x5002");
assertRenderingResult("hi Ter:x5001;Tom:x5002;Sumana:;", st);
}
@Test
void testParallelMapThenMap() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("bold", "x", "[<x>]");
group.defineTemplate("test", "names,phones", "hi <names,phones:{n,p | <n>:<p>;}:bold()>");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", "Tom");
st.add("names", "Sumana");
st.add("phones", "x5001");
st.add("phones", "x5002");
assertRenderingResult("hi [Ter:x5001;][Tom:x5002;][Sumana:;]", st);
}
@Test
void testMapThenParallelMap() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("bold", "x", "[<x>]");
group.defineTemplate("test", "names,phones", "hi <[names:bold()],phones:{n,p | <n>:<p>;}>");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", "Tom");
st.add("names", "Sumana");
st.add("phones", "x5001");
st.add("phones", "x5002");
assertRenderingResult("hi [Ter]:x5001;[Tom]:x5002;[Sumana]:;", st);
}
@Test
void testMapIndexes() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("inc", "x,i", "<i>:<x>");
group.defineTemplate("test", "name", "<name:{n|<inc(n,i)>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", null); // don't count this one
st.add("name", "Sumana");
assertRenderingResult("1:Ter, 2:Tom, 3:Sumana", st);
}
@Test
void testMapIndexes2() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "name", "<name:{n | <i>:<n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", null); // don't count this one. still can't apply subtemplate to null value
st.add("name", "Sumana");
assertRenderingResult("1:Ter, 2:Tom, 3:Sumana", st);
}
@Test
void testMapSingleValue() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("a", "x", "[<x>]");
group.defineTemplate("test", "name", "hi <name:a()>!");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
assertRenderingResult("hi [Ter]!", st);
}
@Test
void testMapNullValue() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("a", "x", "[<x>]");
group.defineTemplate("test", "name", "hi <name:a()>!");
ST st = group.getInstanceOf("test");
assertRenderingResult("hi !", st);
}
@Test
void testMapNullValueInList() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "name", "<name; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", "Tom");
st.add("name", null); // don't print this one
st.add("name", "Sumana");
assertRenderingResult("Ter, Tom, Sumana", st);
}
static Arguments[] mapTestData()
{
return new Arguments[]{
args("RepeatedMap", "hi <name:a():b()>!", "Tom", "hi ([Ter])([Tom])([Sumana])!"),
args("RepeatedMapWithNullValue", "hi <name:a():b()>!", null, "hi ([Ter])([Sumana])!"),
args("RepeatedMapWithNullValueAndNullOption",
"hi <name:a():b(); null={x}>!",
null,
"hi ([Ter])x([Sumana])!"),
args("RoundRobinMap", "hi <name:a(),b()>!", "Tom", "hi [Ter](Tom)[Sumana]!")
};
}
@ParameterizedTest(name = "[{index}] {0}")
@MethodSource("mapTestData")
void testMap(
@SuppressWarnings("unused") String testName,
String templateSource,
String middleAttributeValue,
String expectedResult) throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("a", "x", "[<x>]");
group.defineTemplate("b", "x", "(<x>)");
group.defineTemplate("test", "name", templateSource);
ST st = group.getInstanceOf("test");
st.add("name", "Ter");
st.add("name", middleAttributeValue);
st.add("name", "Sumana");
assertRenderingResult(expectedResult, st);
}
@Test
void testCharLiterals()
{
ST st = new ST("Foo <\\n><\\n><\\t> bar\n");
StringWriter sw = new StringWriter();
st.write(new AutoIndentWriter(sw, "\n")); // force \n as newline
String result = sw.toString();
String expecting = "Foo \n\n\t bar\n"; // expect \n in output
assertEquals(expecting, result);
st = new ST("Foo <\\n><\\t> bar" + NEWLINE);
sw = new StringWriter();
st.write(new AutoIndentWriter(sw, "\n")); // force \n as newline
expecting = "Foo \n\t bar\n"; // expect \n in output
result = sw.toString();
assertEquals(expecting, result);
st = new ST("Foo<\\ >bar<\\n>");
sw = new StringWriter();
st.write(new AutoIndentWriter(sw, "\n")); // force \n as newline
result = sw.toString();
expecting = "Foo bar\n"; // forced \n
assertEquals(expecting, result);
}
@Test
void testSeparator() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", "Tom");
assertRenderingResult("case Ter, case Tom", st);
}
@Test
void testSeparatorInList() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", List.of("Ter", "Tom"));
assertRenderingResult("case Ter, case Tom", st);
}
@Test
void testSeparatorInList2() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", List.of("Tom", "Sriram"));
assertRenderingResult("case Ter, case Tom, case Sriram", st);
}
@Test
void testSeparatorInArray() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", new String[]{ "Ter", "Tom" });
assertRenderingResult("case Ter, case Tom", st);
}
@Test
void testSeparatorInArray2() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", "Ter");
st.add("names", new String[]{ "Tom", "Sriram" });
assertRenderingResult("case Ter, case Tom, case Sriram", st);
}
@Test
void testSeparatorInPrimitiveArray() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", new int[]{ 0, 1 });
assertRenderingResult("case 0, case 1", st);
}
@Test
void testSeparatorInPrimitiveArray2() throws IOException
{
STGroup group = new LegacyBareStGroup();
group.defineTemplate("test", "names", "<names:{n | case <n>}; separator=\", \">");
ST st = group.getInstanceOf("test");
st.add("names", 0);
st.add("names", new int[]{ 1, 2 });
assertRenderingResult("case 0, case 1, case 2", st);
}
/**
* (...) forces early eval to string. early eval {@code <(x)>} using new STWriter derived from type of current
* STWriter. e.g., AutoIndentWriter.
*/
@Test
void testEarlyEvalIndent()
{
String templates = "t() ::= << abc>>\n" + "main() ::= <<\n" + "<t()>\n" + "<(t())>\n" +
// early eval ignores indents; mostly for simply strings
" <t()>\n" + " <(t())>\n" + ">>\n";
writeFile(tmpdir, "t.stg", templates);
STGroup group = STGroupFilePath.createWithDefaults(tmpdir + "/" + "t.stg");
ST st = group.getInstanceOf("main");
String result = st.render();
String expected = " abc" + NEWLINE + " abc" + NEWLINE + " abc" + NEWLINE + " abc";
assertEquals(expected, result);
}
@Test
void testEarlyEvalNoIndent()
{
String templates = "t() ::= << abc>>\n" + "main() ::= <<\n" + "<t()>\n" + "<(t())>\n" +
// early eval ignores indents; mostly for simply strings
" <t()>\n" + " <(t())>\n" + ">>\n";
writeFile(tmpdir, "t.stg", templates);
STGroup group = STGroupFilePath.createWithDefaults(tmpdir + "/" + "t.stg");
ST st = group.getInstanceOf("main");
StringWriter sw = new StringWriter();
NoIndentWriter w = new NoIndentWriter(sw);
st.write(w);
String result = sw.toString();
String expected = "abc" + NEWLINE + "abc" + NEWLINE + "abc" + NEWLINE + "abc";
assertEquals(expected, result);
}
@Test
void testPrototype() throws IOException
{
ST prototype = new ST("simple template");
ST st = new ST(prototype);
st.add("arg1", "value");
assertRenderingResult("simple template", st);
ST st2 = new ST(prototype);
st2.add("arg1", "value");
assertRenderingResult("simple template", st2);
}
}
| 34.043189 | 114 | 0.567922 |
4f21806207e8baa213718bf9695274379c64c8b2 | 134 | package bddController;
import alives.NPC;
public class NPCReader {
public static NPC getNPC(int id){
//TODO
return null;
}
}
| 11.166667 | 34 | 0.708955 |
f7aa208d3b3fe57b59daec0e011419ccc88df956 | 1,324 | package com.example.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by IntelliJ IDEA.
* Spring boot方式
* EnableTransactionManagement 自动管理事务
* Configuration 配置类注解
* @author : cchu
* Date: 2022/1/6 11:14
*/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* Mybatis Plus 分页
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//默认数据库类型
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE_12C));
//乐观锁
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分页配置
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
| 33.1 | 91 | 0.780211 |
a3a6c8dac2859121fbc3534df8ea36fc81046f05 | 3,120 | //- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved.
//- Limelight and all included source files are distributed under terms of the MIT License.
package limelight.styles.values;
import limelight.ui.MockGraphics;
import limelight.util.Box;
import limelight.styles.HorizontalAlignment;
import limelight.styles.VerticalAlignment;
import java.awt.*;
public class RepeatFillStrategyValueTest extends FillStrategyValueTest
{
private RepeatFillStrategyValue attribute;
private MockGraphics graphics;
private Box clip;
public void setUp() throws Exception
{
attribute = new RepeatFillStrategyValue();
graphics = new MockGraphics();
clip = new Box(0, 0, 60, 60);
graphics.clip = clip;
}
public void testName() throws Exception
{
assertEquals("repeat", attribute.toString());
}
public void testFill() throws Exception
{
Image image = new MockImage(20, 20);
attribute.fill(graphics, image, new StaticXCoordinateValue(0), new StaticYCoordinateValue(0));
assertEquals(9, graphics.drawnImages.size());
checkImage(graphics.drawnImages.get(0), image, 0, 0);
checkImage(graphics.drawnImages.get(1), image, 20, 0);
checkImage(graphics.drawnImages.get(2), image, 40, 0);
checkImage(graphics.drawnImages.get(3), image, 0, 20);
checkImage(graphics.drawnImages.get(4), image, 20, 20);
checkImage(graphics.drawnImages.get(5), image, 40, 20);
checkImage(graphics.drawnImages.get(6), image, 0, 40);
checkImage(graphics.drawnImages.get(7), image, 20, 40);
checkImage(graphics.drawnImages.get(8), image, 40, 40);
}
public void testFillNonZero() throws Exception
{
Image image = new MockImage(20, 20);
attribute.fill(graphics, image, new StaticXCoordinateValue(20), new StaticYCoordinateValue(20));
assertEquals(4, graphics.drawnImages.size());
checkImage(graphics.drawnImages.get(0), image, 20, 20);
checkImage(graphics.drawnImages.get(1), image, 40, 20);
checkImage(graphics.drawnImages.get(2), image, 20, 40);
checkImage(graphics.drawnImages.get(3), image, 40, 40);
}
public void testFillUneven() throws Exception
{
Image image = new MockImage(30, 30);
attribute.fill(graphics, image, new StaticXCoordinateValue(20), new StaticYCoordinateValue(20));
assertEquals(4, graphics.drawnImages.size());
checkImage(graphics.drawnImages.get(0), image, 20, 20);
checkImage(graphics.drawnImages.get(1), image, 50, 20);
checkImage(graphics.drawnImages.get(2), image, 20, 50);
checkImage(graphics.drawnImages.get(3), image, 50, 50);
}
public void testFillAligned() throws Exception
{
Image image = new MockImage(35, 35);
attribute.fill(graphics, image, new AlignedXCoordinateValue(HorizontalAlignment.CENTER), new AlignedYCoordinateValue(VerticalAlignment.CENTER));
assertEquals(4, graphics.drawnImages.size());
checkImage(graphics.drawnImages.get(0), image, -5, -5);
checkImage(graphics.drawnImages.get(1), image, 30, -5);
checkImage(graphics.drawnImages.get(2), image, -5, 30);
checkImage(graphics.drawnImages.get(3), image, 30, 30);
}
}
| 36.705882 | 148 | 0.723718 |
ca5a99743ce0367985abfa79fbea547708faecfa | 1,092 | package org.manuel.mysportfolio.model.dtos.usernotification;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import io.github.manuelarte.mysportfolio.model.dtos.team.TeamDto;
import javax.validation.constraints.NotNull;
import org.manuel.mysportfolio.model.entities.usernotification.UserNotificationStatus;
@JsonDeserialize(builder = TeamAddUserNotificationDto.TeamAddUserNotificationDtoBuilder.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@lombok.AllArgsConstructor
@lombok.Value
@lombok.Builder(toBuilder = true)
public class TeamAddUserNotificationDto implements UserNotificationDto {
@NotNull
private final String id;
@NotNull
private final Long version;
@NotNull
private final String from;
@NotNull
private final String to;
@NotNull
private final TeamDto team;
private final UserNotificationStatus status;
@JsonPOJOBuilder(withPrefix = "")
public static final class TeamAddUserNotificationDtoBuilder {
}
}
| 27.3 | 94 | 0.825092 |
34f3346a7bcf3f01e85966f00d0122c0efd639aa | 5,778 | package com.eilikce.osm.core.bo.transformable;
import java.io.Serializable;
import java.sql.Timestamp;
import com.eilikce.osm.core.bo.EntityTransBo;
import com.eilikce.osm.entity.consumer.CommodityPo;
public class Commodity extends EntityTransBo<CommodityPo> implements Serializable {
private static final long serialVersionUID = 1L;
private String commodityId;
private Integer groupId;
private Integer itemId;
private Integer barcode;
private String commodityName;
private String commodityDetail;
private String imgRule;
private Integer number;
private Float original;
private Float price;
private String unit;
private String source;
private String detail;
private Integer salesVolume;
private Integer shelves;
private Timestamp createDate;
public Commodity() {
super();
// TODO Auto-generated constructor stub
}
public Commodity(String commodityId, Integer groupId, Integer itemId, Integer barcode,
String commodityName, String commodityDetail, String imgRule, Integer number, Float original, Float price,
String unit, String source, String detail, Integer salesVolume, Integer shelves, Timestamp createDate) {
super();
this.commodityId = commodityId;
this.groupId = groupId;
this.itemId = itemId;
this.barcode = barcode;
this.commodityName = commodityName;
this.commodityDetail = commodityDetail;
this.imgRule = imgRule;
this.number = number;
this.original = original;
this.price = price;
this.unit = unit;
this.source = source;
this.detail = detail;
this.salesVolume = salesVolume;
this.shelves = shelves;
this.createDate = createDate;
}
/**
* 不包含id和createDate的构造
*/
public Commodity(String commodityId, Integer groupId, Integer itemId, Integer barcode, String commodityName,
String commodityDetail, String imgRule, Integer number, Float original, Float price, String unit,
String source, String detail, Integer salesVolume, Integer shelves) {
super();
this.commodityId = commodityId;
this.groupId = groupId;
this.itemId = itemId;
this.barcode = barcode;
this.commodityName = commodityName;
this.commodityDetail = commodityDetail;
this.imgRule = imgRule;
this.number = number;
this.original = original;
this.price = price;
this.unit = unit;
this.source = source;
this.detail = detail;
this.salesVolume = salesVolume;
this.shelves = shelves;
}
public Commodity(CommodityPo commodityPo) {
super();
this.commodityId = commodityPo.getCommodityId();
this.groupId = commodityPo.getGroupId();
this.itemId = commodityPo.getItemId();
this.barcode = commodityPo.getBarcode();
this.commodityName = commodityPo.getCommodityName();
this.commodityDetail = commodityPo.getCommodityDetail();
this.imgRule = commodityPo.getImgRule();
this.number = commodityPo.getNumber();
this.original = commodityPo.getOriginal();
this.price = commodityPo.getOriginal();
this.unit = commodityPo.getUnit();
this.source = commodityPo.getSource();
this.detail = commodityPo.getDetail();
this.salesVolume = commodityPo.getSalesVolume();
this.shelves = commodityPo.getShelves();
this.createDate = commodityPo.getCreateDate();
}
public String getCommodityId() {
return commodityId;
}
public void setCommodityId(String commodityId) {
this.commodityId = commodityId;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public Integer getBarcode() {
return barcode;
}
public void setBarcode(Integer barcode) {
this.barcode = barcode;
}
public String getCommodityName() {
return commodityName;
}
public void setCommodityName(String commodityName) {
this.commodityName = commodityName;
}
public String getCommodityDetail() {
return commodityDetail;
}
public void setCommodityDetail(String commodityDetail) {
this.commodityDetail = commodityDetail;
}
public String getImgRule() {
return imgRule;
}
public void setImgRule(String imgRule) {
this.imgRule = imgRule;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Float getOriginal() {
return original;
}
public void setOriginal(Float original) {
this.original = original;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Integer getSalesVolume() {
return salesVolume;
}
public void setSalesVolume(Integer salesVolume) {
this.salesVolume = salesVolume;
}
public Integer getShelves() {
return shelves;
}
public void setShelves(Integer shelves) {
this.shelves = shelves;
}
public Timestamp getCreateDate() {
return createDate;
}
public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "CommodityPo [commodityId=" + commodityId + ", groupId=" + groupId + ", itemId=" + itemId + ", barcode="
+ barcode + ", commodityName=" + commodityName + ", commodityDetail=" + commodityDetail + ", imgRule="
+ imgRule + ", number=" + number + ", original=" + original + ", price=" + price + ", unit=" + unit
+ ", source=" + source + ", detail=" + detail + ", salesVolume=" + salesVolume + ", shelves=" + shelves
+ ", createDate=" + createDate + "]";
}
}
| 23.975104 | 113 | 0.724472 |
78d3c88a2268e38b8a570b86a322dba825c70db3 | 1,733 | package com.patience.klondike.resource;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.patience.domain.model.event.EventStore;
import com.patience.domain.model.event.StoredEvent;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers=NotificationResource.class, secure=false)
public class NotficationResourceTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private EventStore eventStore;
@Test
public void retrieveNotifications() throws Exception {
List<StoredEvent> events = new ArrayList<>();
events.add(new StoredEvent("com.klondike.test-event", DateTime.now(), "{\"foo\":\"bar\"}"));
when(eventStore.unprocessedEvents()).thenReturn(events);
mockMvc.perform(get("/notifications").accept("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].eventType", equalTo("com.klondike.test-event")))
.andExpect(jsonPath("$[0].eventBody", equalTo("{\"foo\":\"bar\"}")));
}
}
| 36.87234 | 97 | 0.77438 |
c0fa37cb119de35619fa3012d399fad9e0dfd751 | 227 | package org.bukkit.craftbukkit.scheduler;
public class ObjectContainer<T> {
T object;
public void setObject(T object) {
this.object = object;
}
public T getObject() {
return object;
}
}
| 14.1875 | 41 | 0.61674 |
b1334082ff65e1fafd8c8d1c66b10320f9d9c454 | 4,075 | package org.tpc.expplus.common.block;
import org.tpc.expplus.common.tile.TileExpPlus;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public abstract class BlockExpPlus extends BlockContainer {
public BlockExpPlus() {
super(Material.ROCK);
setCreativeTab(CreativeTabs.REDSTONE);
setSoundType(SoundType.STONE);
setHardness(10.0F);
}
@Override
public boolean canEntityDestroy(IBlockState state, IBlockAccess world, BlockPos pos, Entity entity) {
if (!(entity instanceof EntityPlayer))
return false;
EntityPlayer player = ((EntityPlayer) entity);
TileEntity tile = world.getTileEntity(pos);
if (!(tile instanceof TileExpPlus))
return false;
return ((TileExpPlus) tile).isOwner(player);
}
@Override
public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player,
boolean willHarvest) {
if (world.isRemote)
return true;
TileEntity tile = world.getTileEntity(pos);
if (!(tile instanceof TileExpPlus))
return super.removedByPlayer(state, world, pos, player, willHarvest);
TileExpPlus tileExpPlus = (TileExpPlus) tile;
if (tileExpPlus.isOwner(player)) {
super.removedByPlayer(state, world, pos, player, willHarvest);
return true;
}
return false;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer,
ItemStack stack) {
if (!(placer instanceof EntityPlayer))
return;
TileEntity tile = worldIn.getTileEntity(pos);
if ((tile == null) || !(tile instanceof TileExpPlus))
return;
((TileExpPlus) tile).setOwner(((EntityPlayer) placer).getUniqueID());
tile.markDirty();
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
if (worldIn.isRemote)
return true;
// Drop through if the player is sneaking
return !playerIn.isSneaking();
}
@Override
public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, IBlockState state) {
if (worldIn.isRemote)
return;
TileEntity tile = worldIn.getTileEntity(pos);
if ((tile == null) || !(tile instanceof TileExpPlus))
return;
TileExpPlus tileExpPlus = (TileExpPlus) tile;
IInventory inventory = tileExpPlus.getInventory();
for (int index = inventory.getFieldCount(); index >= 0; index--) {
ItemStack stack = inventory.getStackInSlot(index);
if ((stack == null) || (stack.getItem() == Item.getItemFromBlock(Blocks.AIR)))
continue;
spawnAsEntity(worldIn, pos, stack);
}
super.onBlockDestroyedByPlayer(worldIn, pos, state);
}
@Override
protected boolean canSilkHarvest() {
return false;
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;
}
@Override
public boolean isBlockNormalCube(IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public float getExplosionResistance(Entity exploder) {
return 2000.0F;
}
} | 28.697183 | 104 | 0.731043 |
a8dd5229ad17f108b836e9efa4c82c042c4b55c3 | 884 | package com.github.nieldw.knapsack;
import com.github.nieldw.knapsack.constraints.Constraint;
import java.util.Collections;
import java.util.List;
import static java.util.Optional.ofNullable;
/**
* Abstract class that provides support for checking {@link KnapsackProblem} {@link Constraint}s.
*/
public abstract class KnapsackProblemConstraintSupport {
private List<Constraint> constraints;
/**
* Constructs a new {@link KnapsackProblemConstraintSupport}.
*
* @param constraints The {@link Constraint}s applied to problems by this object
*/
protected KnapsackProblemConstraintSupport(List<Constraint> constraints) {
this.constraints = ofNullable(constraints).orElse(Collections.emptyList());
}
public void checkConstraints(KnapsackProblem problem) {
constraints.forEach(constraint -> constraint.check(problem));
}
}
| 30.482759 | 97 | 0.746606 |
0a6af150b5a51515423c817fc08c76a8ca9b2bf9 | 16,843 | package gov.nasa.pds.web.ui.utils;
import java.io.UnsupportedEncodingException;
public class BinaryConversionUtils {
/**
*
* Converts an array of bytes into an int. The array of bytes may be of
* length 1, 2, 3, or 4, in big-endian order. That is, b[0] holds the most
* significant bits, b[n-1] the least. The bytes are assumed to be signed.
*
* @param b
* the array of bytes, in big-endian order
* @param n
* the number of bytes to convert in the array, from 1 to the
* size of an int
* @return the signed int value represented by the bytes
*/
public static int convertMSBSigned(byte[] b, int n) {
// Integer.size is The number of bits used to represent an <tt>int</tt>
// value in two's complement binary form.
// static final int SIZE = 32;
// so assert n(number of bytes in array) is between 1 and 8*n is less
// than 32)
assert (1 <= n && 8 * n <= Integer.SIZE);
int value = 0;
// From least- to most-significant byte, put each byte
// into the accumulating value, in the most significant
// byte position, shifting the prior value 8 bits to
// the right. That way the most significant byte will
// be the last byte we put in, setting the sign bit.
for (int i = n - 1; i >= 0; --i) {
value = (value >>> 8) | (b[i] << (Integer.SIZE - 8));
}
// Pad with the sign bit on the left, if we used fewer bytes
// than the size of an int.
if (n < 4) {
value = value >> (Integer.SIZE - 8 * n);
}
return value;
}
/**
*
* Converts an array of bytes into an int. The array of bytes may be of
* length 1, 2, 3, or 4, in little-endian order. That is, b[n-1] holds the
* most significant bits, b[n-1] the least. The bytes are assumed to be
* signed.
*
* @param b
* the array of bytes, in little-endian order
* @param n
* the number of bytes to convert in the array, from 1 to the
* size of an int
* @return the signed int value represented by the bytes
*/
public static int convertLSBSigned(byte[] b, int n) {
assert (1 <= n && 8 * n <= Integer.SIZE);
int value = 0;
// From least- to most-significant byte, put each byte
// into the accumulating value, in the most significant
// byte position, shifting the prior value 8 bits to
// the right. That way the most significant byte will
// be the last byte we put in, setting the sign bit.
for (int i = 0; i < n; i++) {
value = (value >>> 8) | (b[i] << (Integer.SIZE - 8));
}
// TODO should this pad on the right?
// Pad with the sign bit on the left, if we used fewer bytes
// than the size of an int.
if (n < 4) {
value = value >> (Integer.SIZE - 8 * n);
}
return value;
}
/**
*
* Converts an array of bytes into a long, permitting unsigned bytes. The
* array of bytes may be of length 1, 2, 3, or 4, in big-endian order. That
* is, b[0] holds the most significant bits, b[n-1] the least.
*
* @param b
* the array of bytes, in big-endian order
* @param n
* the number of bytes to convert in the array, from 1 to the
* size of an int
* @return the signed int value represented by the bytes
*/
@SuppressWarnings("cast")
public static long convertMSBUnsigned(int[] b, int n) {
// MSB_UNSIGNED_INTEGER 1-, 2-, and 4-byte unsigned integers
long anUnsignedInt = 0;
if (n == 1) {
anUnsignedInt = (long) (0xFF & ((int) b[0]));
}
if (n == 2) {
anUnsignedInt = (long) ((0xFF & ((int) b[0])) << 8 | (0xFF & ((int) b[1])));
}
if (n == 3) {
anUnsignedInt = ((long) ((0xFF & ((int) b[0])) << 16
| (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[2])))) & 0xFFFFFFFFL;
}
if (n == 4) {
anUnsignedInt = ((long) ((0xFF & ((int) b[0])) << 24
| (0xFF & ((int) b[1])) << 16 | (0xFF & ((int) b[2])) << 8 | (0xFF & ((int) b[3])))) & 0xFFFFFFFFL;
}
return anUnsignedInt;
}
/**
*
* Converts an array of bytes into a long, permitting unsigned bytes. The
* array of bytes may be of length 1, 2, 3, or 4, in big-endian order. That
* is, b[0] holds the most significant bits, b[n-1] the least.
*
* @param b
* the array of bytes, in big-endian order
* @param n
* the number of bytes to convert in the array, from 1 to the
* size of an int
* @return the signed int value represented by the bytes
*/
@SuppressWarnings("cast")
public static long convertMSBUnsigned(byte[] b, int n) {
// MSB_UNSIGNED_INTEGER 1-, 2-, and 4-byte unsigned integers
long anUnsignedInt = 0;
if (n == 1) {
anUnsignedInt = (long) (0xFF & ((int) b[0]));
}
if (n == 2) {
anUnsignedInt = (long) ((0xFF & ((int) b[0])) << 8 | (0xFF & ((int) b[1])));
}
if (n == 3) {
anUnsignedInt = ((long) ((0xFF & ((int) b[0])) << 16
| (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[2])))) & 0xFFFFFFFFL;
}
if (n == 4) {
anUnsignedInt = ((long) ((0xFF & ((int) b[0])) << 24
| (0xFF & ((int) b[1])) << 16 | (0xFF & ((int) b[2])) << 8 | (0xFF & ((int) b[3])))) & 0xFFFFFFFFL;
}
return anUnsignedInt;
}
@SuppressWarnings("cast")
public static long convertLSBUnsigned(int[] b, int n) {
long anUnsignedInt = 0;
if (n == 1) {
anUnsignedInt = (long) (0xFF & ((int) b[n - 1]));
}
if (n == 2) {
anUnsignedInt = (long) ((0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])));
}
if (n == 3) {
anUnsignedInt = ((long) ((0xFF & ((int) b[2])) << 16
| (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])))) & 0xFFFFFFFFL;
}
if (n == 4) {
anUnsignedInt = ((long) ((0xFF & ((int) b[3])) << 24
| (0xFF & ((int) b[2])) << 16 | (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])))) & 0xFFFFFFFFL;
}
return anUnsignedInt;
}
@SuppressWarnings("cast")
public static long convertLSBUnsigned(byte[] b, int n) {
long anUnsignedInt = 0;
if (n == 1) {
anUnsignedInt = (long) (0xFF & ((int) b[n - 1]));
}
if (n == 2) {
anUnsignedInt = (long) ((0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])));
}
if (n == 3) {
anUnsignedInt = ((long) ((0xFF & ((int) b[2])) << 16
| (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])))) & 0xFFFFFFFFL;
}
if (n == 4) {
anUnsignedInt = ((long) ((0xFF & ((int) b[3])) << 24
| (0xFF & ((int) b[2])) << 16 | (0xFF & ((int) b[1])) << 8 | (0xFF & ((int) b[0])))) & 0xFFFFFFFFL;
}
return anUnsignedInt;
}
/**
* convert MSB byte array (of size 4) to float
*
* @param test
* @return
*/
public static float MSBByteArrayToFloat(byte bytes[]) {
final int MASK = 0xff;
int bits = 0;
int i = 0;
for (int shifter = 3; shifter >= 0; shifter--) {
bits |= (bytes[i] & MASK) << (shifter * 8);
i++;
}
return Float.intBitsToFloat(bits);
}
/**
* convert LSB byte array (of size 4) to float
*
* @param test
* @return
*/
// LAB l5/30/10 not used yet
public static float LSBByteArrayToFloat(byte bytes[]) {
final int MASK = 0xff;
int bits = 0;
int i = 0;
for (int shifter = 0; shifter < 3; shifter++) {
bits |= (bytes[i] & MASK) << (shifter * 8);
i++;
}
return Float.intBitsToFloat(bits);
}
/**
* Convert byte array to String. Use the correct encoding, ASCII (7-bit) or EBCDIC (8-bit)
* In the case it is not able to use the correct encoding, display the bytes in decimal format
* as follows: [87,87,....]
*
* @param byteArray
* @return
*/
@SuppressWarnings("nls")
public static String byteArrayToString(byte[] byteArray, String encoding) {
StringBuilder sb = new StringBuilder("");
String text = null;
if (byteArray == null) {
throw new IllegalArgumentException("byteArray must not be null");
}
try {
text = new String(byteArray, 0, byteArray.length, encoding);
sb.append(text);
} catch(UnsupportedEncodingException e) {
int arrayLen = byteArray.length;
sb.append("[");
for (int i = 0; i < arrayLen; i++) {
sb.append(byteArray[i]);
if (i == arrayLen - 1) {
sb.append("]");
} else {
sb.append(", ");
}
}
}
return sb.toString();
}
/**
* Appends a logical 1 or 0 to the existing string based on the value of the bit
* Used to convert a byte array to string.
*/
@SuppressWarnings("nls")
public static void bitToString(StringBuilder byteValue, boolean bit) {
if(bit)
byteValue.append(1);
else
byteValue.append(0);
}
/**
* Convert a byte array of size 8 bytes to type long
* @param b: byte array of size 8 bytes
* @return long representation of the byte array
*
* Note: Need to type cast to type long since cannot shift pass 31 bits
*/
public static long convertByteArrayToLong(byte[] b) {
assert (b.length == 8);
long aSignedLong = 0;
aSignedLong = ((long)(0xFF & b[0]) << 56) |
((long)(0xFF & b[1]) << 48) |
((long)(0xFF & b[2]) << 40) |
((long)(0xFF & b[3]) << 32) |
((long)(0xFF & b[4]) << 24) |
((long)(0xFF & b[5]) << 16) |
((long)(0xFF & b[6]) << 8) |
((long)(0xFF & b[7]));
return aSignedLong;
}
/**
* Convert a byte array of size 4 bytes to type int
* @param b: byte array if size 4 bytes
* @return int representation of the byte array
*/
public static int convertByteArrayToInt(byte[] b) {
assert (b.length == 4);
int aSignedInt = 0;
aSignedInt = ((int)(0xFF & b[0]) << 24) |
((int)(0xFF & b[1]) << 16) |
((int)(0xFF & b[2]) << 8) |
((int)(0xFF & b[3]));
return aSignedInt;
}
/**
* Convert from VAX F-type 4-byte to IEEE single precision
*
* @param b - byte array of size 4 bytes
* @return Byte array in integer format with all the bits
* ordered in IEEE-754 4 byte format
*/
public static int vaxFTypeToIEEESingle(byte[] b) {
assert (b.length == 4);
//Extract the arrangement of bytes in VAX format and arrange
//them to IEEE format
int iEEESingleFormat = 0;
int sign = ((int)b[1] & 0x00000080) << 24;
int e1 = ((int)b[1] & 0x0000007F) << 1;
int e0 = ((int)b[0] & 0x00000080) >>> 7;
//Subtract 2 due to VAX bias being 129 instead of 127 for IEEE
//Then shift to right position in IEEE format
int e = ( (e1 | e0) - 0x00000002) << 23;
//Mantissa extraction
int m0 = ((int)b[0] & 0x0000007F) << 16;
int m1 = ((int)b[3] & 0x000000FF) << 8;
int m2 = ((int)b[2] & 0x000000FF);
//Piece together the different IEEE Float format components
iEEESingleFormat = sign | e | m0 | m1 | m2;
return iEEESingleFormat;
}
/**
* Convert from VAX D-type to IEEE double precision. For compatibility,
* the mantissa is truncated from 55 bits to 52 bits
*
* @param b - byte array of size 8 bytes
* @return Byte array in long format with all the bits
* ordered in IEEE-754 8 byte format
*/
public static long vaxDTypeToIEEEDouble(byte[] b) {
assert (b.length == 8);
//Extract the arrangement of bytes in VAX format and arrange
//them to IEEE format
long iEEEDoubleFormat = 0;
long sign = (long)b[1] & (0x0000000000000080L) << 56;
long e1 = ((long)b[1] & 0x000000000000007FL) << 1;
long e0 = ((long)b[0] & 0x0000000000000080L) >>> 7;
//VAX D-Type has a bias of 129. However, IEEE Double has a bias
//of 1023. Therefore adding 894 due to VAX bias being 1025 instead
//of 129 and -2 due to IEEE bias being 1023 = 0x37E
//Shifting left to conform to IEEE format
long e = ( (e1 | e0) + 0x000000000000037EL) << 52;
//Mantissa extraction and shifting to correct location
//in IEEE mantissa format
long m0 = ((long)b[0] & 0x000000000000007FL) << 48;
long m1 = ((long)b[3] & 0x00000000000000FFL) << 40;
long m2 = ((long)b[2] & 0x00000000000000FFL) << 32;
long m3 = ((long)b[5] & 0x00000000000000FFL) << 24;
long m4 = ((long)b[4] & 0x00000000000000FFL) << 16;
long m5 = ((long)b[7] & 0x00000000000000FFL) << 8;
long m6 = ((long)b[6] & 0x00000000000000FFL);
//VAX 8-byte D-type has a longer mantissa (55bits) than (52bits) as in
//IEEE 8-byte (Double Precision). Therefore, the mantissa is truncated
//from 55 bits to 52 bits in order to do the conversion
long m = (m0 | m1 | m2 | m3 | m4 | m5 | m6) >>> 3;
//Piece together the different IEEE Float format components
iEEEDoubleFormat = sign | e | m;
return iEEEDoubleFormat;
}
/**
* Convert from VAX G-type to IEEE 8-byte double precision
*
* @param b - byte array of size 8 bytes
* @return Byte array in long format with all the bits
* ordered in IEEE-754 8 byte format
*/
public static long vaxGTypeToIEEEDouble(byte[] b) {
assert (b.length == 8);
//Extract the arrangement of bytes in VAX format and arrange
//them to IEEE format
long iEEEDoubleFormat = 0;
long sign = (long)b[1] & (0x0000000000000080L) << 56;
long e1 = ((long)b[1] & 0x000000000000007FL) << 4;
long e0 = ((long)b[0] & 0x00000000000000F0L) >>> 4;
//Subtract 2 due to VAX bias being 1025 instead of 1023 as for IEEE
//Then shift to right position to conform to IEEE format
long e = ( (e1 | e0) - 0x0000000000000002L) << 52;
//Mantissa extraction
long m0 = ((long)b[0] & 0x000000000000000FL) << 48;
long m1 = ((long)b[3] & 0x00000000000000FFL) << 40;
long m2 = ((long)b[2] & 0x00000000000000FFL) << 32;
long m3 = ((long)b[5] & 0x00000000000000FFL) << 24;
long m4 = ((long)b[4] & 0x00000000000000FFL) << 16;
long m5 = ((long)b[7] & 0x00000000000000FFL) << 8;
long m6 = ((long)b[6] & 0x00000000000000FFL);
//Piece together the different IEEE Float format components
iEEEDoubleFormat = sign | e | m0 | m1 | m2 | m3 | m4 | m5 | m6;
return iEEEDoubleFormat;
}
/**
* Convert from PC_REAL type to IEEE single precision
* @param b - byte array of size 4 bytes
* @return The byte array in integer format
*/
public static int pcReal4BTypeToIEEESingle(byte[] b) {
assert (b.length == 4);
//Extract the arrangement of bytes in PC_REAL format and arrange
//them to IEEE format
int iEEESingleFormat = 0;
int sign = ((int)b[3] & 0x00000080) << 24;
int e1 = ((int)b[3] & 0x0000007F) << 1;
int e0 = ((int)b[2] & 0x00000080) >>> 7;
//Add 2 due to PC_REAL bias being 129 instead of 127 for IEEE
//Then shift to right position in IEEE format
int e = ( (e1 | e0) - 0x00000002) << 23;
//Mantissa extraction
int m0 = ((int)b[2] & 0x0000007F) << 16;
int m1 = ((int)b[1] & 0x000000FF) << 8;
int m2 = ((int)b[0] & 0x000000FF);
//Piece together the different IEEE Float format components
iEEESingleFormat = sign | e | m0 | m1 | m2;
return iEEESingleFormat;
}
/**
* Convert from PC_REAL 8 Byte type to IEEE double precision
*
* @param b - byte array of size 8 bytes
* @return Byte array in long type
*/
public static long pcReal8BTypeToIEEEDouble(byte[] b) {
assert (b.length == 8);
//Extract the arrangement of bytes in PC_REAL format and arrange
//them to IEEE format
long iEEEDoubleFormat = 0;
long sign = (long)b[7] & (0x0000000000000080L) << 56;
long e1 = ((long)b[7] & 0x000000000000007FL) << 4;
long e0 = ((long)b[6] & 0x00000000000000F0L) >>> 4;
//Add 2 due to PC_REAL bias being 1025 instead of 1023 as for IEEE
//Then shift to right position to conform to IEEE format
long e = ( (e1 | e0) - 0x0000000000000002L) << 52;
//Mantissa extraction
long m0 = ((long)b[6] & 0x000000000000000FL) << 48;
long m1 = ((long)b[5] & 0x00000000000000FFL) << 40;
long m2 = ((long)b[4] & 0x00000000000000FFL) << 32;
long m3 = ((long)b[3] & 0x00000000000000FFL) << 24;
long m4 = ((long)b[2] & 0x00000000000000FFL) << 16;
long m5 = ((long)b[1] & 0x00000000000000FFL) << 8;
long m6 = ((long)b[0] & 0x00000000000000FFL);
//Piece together the different IEEE Float format components
iEEEDoubleFormat = sign | e | m0 | m1 | m2 | m3 | m4 | m5 | m6;
return iEEEDoubleFormat;
}
}
| 31.839319 | 104 | 0.564804 |
daf227dcc2c1509699556ca8c3b41c8279eb4229 | 107 | package edu.mum.dao;
import edu.mum.domain.Order;
public interface OrderDao extends GenericDao<Order>{
}
| 15.285714 | 52 | 0.785047 |
ee428948cb83386ab1e2567aa99f6ca050cbaa16 | 1,519 | /*************************************************************************************
* Copyright (c) 2011, 2012, 2013 James Talbut.
* jim-emitters@spudsoft.co.uk
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* James Talbut - Initial implementation.
************************************************************************************/
package uk.co.spudsoft.birt.emitters.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
/**
* XlsEmitter is the leaf class for implementing the ExcelEmitter with HSSFWorkbook.
* @author Jim Talbut
*
*/
public class XlsEmitter extends ExcelEmitter {
/**
*/
public XlsEmitter() {
super(StyleManagerHUtils.getFactory());
log.debug("Constructed XlsEmitter");
}
public String getOutputFormat() {
return "xls";
}
protected Workbook createWorkbook() {
return new HSSFWorkbook();
}
protected Workbook openWorkbook( File templateFile ) throws IOException {
InputStream stream = new FileInputStream( templateFile );
try {
return new HSSFWorkbook( stream );
} finally {
stream.close();
}
}
}
| 27.125 | 87 | 0.62212 |
42537a26affd741dfcefe022b41acc78e49173fe | 5,445 | package controller_msgs.msg.dds;
import us.ihmc.communication.packets.Packet;
import us.ihmc.euclid.interfaces.Settable;
import us.ihmc.euclid.interfaces.EpsilonComparable;
import java.util.function.Supplier;
import us.ihmc.pubsub.TopicDataType;
/**
* This message is part of the IHMC whole-body controller API.
* This message commands the controller to move the head in both taskspace and jointspace
* to the desired orientation and joint angles while going through the specified trajectory points.
*/
public class HeadHybridJointspaceTaskspaceTrajectoryMessage extends Packet<HeadHybridJointspaceTaskspaceTrajectoryMessage> implements Settable<HeadHybridJointspaceTaskspaceTrajectoryMessage>, EpsilonComparable<HeadHybridJointspaceTaskspaceTrajectoryMessage>
{
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long sequence_id_;
/**
* The taskspace trajectory information.
*/
public controller_msgs.msg.dds.SO3TrajectoryMessage taskspace_trajectory_message_;
/**
* The jointspace trajectory information.
* The indexing for the joints goes increasingly from the joint the closest to the chest to the joint the closest to the head.
*/
public controller_msgs.msg.dds.JointspaceTrajectoryMessage jointspace_trajectory_message_;
public HeadHybridJointspaceTaskspaceTrajectoryMessage()
{
taskspace_trajectory_message_ = new controller_msgs.msg.dds.SO3TrajectoryMessage();
jointspace_trajectory_message_ = new controller_msgs.msg.dds.JointspaceTrajectoryMessage();
}
public HeadHybridJointspaceTaskspaceTrajectoryMessage(HeadHybridJointspaceTaskspaceTrajectoryMessage other)
{
this();
set(other);
}
public void set(HeadHybridJointspaceTaskspaceTrajectoryMessage other)
{
sequence_id_ = other.sequence_id_;
controller_msgs.msg.dds.SO3TrajectoryMessagePubSubType.staticCopy(other.taskspace_trajectory_message_, taskspace_trajectory_message_);
controller_msgs.msg.dds.JointspaceTrajectoryMessagePubSubType.staticCopy(other.jointspace_trajectory_message_, jointspace_trajectory_message_);
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public void setSequenceId(long sequence_id)
{
sequence_id_ = sequence_id;
}
/**
* Unique ID used to identify this message, should preferably be consecutively increasing.
*/
public long getSequenceId()
{
return sequence_id_;
}
/**
* The taskspace trajectory information.
*/
public controller_msgs.msg.dds.SO3TrajectoryMessage getTaskspaceTrajectoryMessage()
{
return taskspace_trajectory_message_;
}
/**
* The jointspace trajectory information.
* The indexing for the joints goes increasingly from the joint the closest to the chest to the joint the closest to the head.
*/
public controller_msgs.msg.dds.JointspaceTrajectoryMessage getJointspaceTrajectoryMessage()
{
return jointspace_trajectory_message_;
}
public static Supplier<HeadHybridJointspaceTaskspaceTrajectoryMessagePubSubType> getPubSubType()
{
return HeadHybridJointspaceTaskspaceTrajectoryMessagePubSubType::new;
}
@Override
public Supplier<TopicDataType> getPubSubTypePacket()
{
return HeadHybridJointspaceTaskspaceTrajectoryMessagePubSubType::new;
}
@Override
public boolean epsilonEquals(HeadHybridJointspaceTaskspaceTrajectoryMessage other, double epsilon)
{
if(other == null) return false;
if(other == this) return true;
if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sequence_id_, other.sequence_id_, epsilon)) return false;
if (!this.taskspace_trajectory_message_.epsilonEquals(other.taskspace_trajectory_message_, epsilon)) return false;
if (!this.jointspace_trajectory_message_.epsilonEquals(other.jointspace_trajectory_message_, epsilon)) return false;
return true;
}
@Override
public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof HeadHybridJointspaceTaskspaceTrajectoryMessage)) return false;
HeadHybridJointspaceTaskspaceTrajectoryMessage otherMyClass = (HeadHybridJointspaceTaskspaceTrajectoryMessage) other;
if(this.sequence_id_ != otherMyClass.sequence_id_) return false;
if (!this.taskspace_trajectory_message_.equals(otherMyClass.taskspace_trajectory_message_)) return false;
if (!this.jointspace_trajectory_message_.equals(otherMyClass.jointspace_trajectory_message_)) return false;
return true;
}
@Override
public java.lang.String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("HeadHybridJointspaceTaskspaceTrajectoryMessage {");
builder.append("sequence_id=");
builder.append(this.sequence_id_); builder.append(", ");
builder.append("taskspace_trajectory_message=");
builder.append(this.taskspace_trajectory_message_); builder.append(", ");
builder.append("jointspace_trajectory_message=");
builder.append(this.jointspace_trajectory_message_);
builder.append("}");
return builder.toString();
}
}
| 38.076923 | 257 | 0.743618 |
614b4114c163f38aa44034bcb5add4e2975780e9 | 813 | package jaskell.parsec;
import java.io.EOFException;
import java.util.List;
import java.util.Set;
import static java.util.stream.Collectors.joining;
/**
* Created by Mars Liu on 2016-01-03.
* NoneOf 即 none of ,它期待得到的信息项与给定的任何项都不匹配,否则返回错误.
*/
public class NoneOf<E> implements Parsec<E, E> {
private Set<E> items;
@Override
public <Status, Tran, S extends State<E, Status, Tran>> E parse(S s) throws EOFException, ParsecException {
E re = s.next();
if(items.contains(re)) {
String message = String.format("expect a item not in [%s] but got %s",
this.items.stream().map(E::toString).collect(joining()), re);
throw s.trap(message);
}
return re;
}
public NoneOf(Set<E> items){
this.items = items;
}
}
| 26.225806 | 111 | 0.621156 |
6c3ade4f1b678659d6c22570763fcecebcab4e3b | 5,175 | package com.example.broadcast.broadcast;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.util.Log;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class BroadcastManager {
/**
* One thing the thread pool framework does not handle is the Android
* activity lifecycle. If you want your thread pool to survive the
* activity lifecycle and reconnect to your activity after it is re-created
* (E.g. after an orientation change), it needs to be created and maintained outside the activity.
*/
private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
/**
* If the pool currently has more than corePoolSize threads,
* excess threads will be terminated if they have been idle for more than the keepAliveTime.
* This provides a means of reducing resource consumption when the pool is not being actively used.
*/
private static final int KEEP_ALIVE_TIME = 1;
/**
* Any BlockingQueue may be used to transfer and hold submitted tasks.
*/
private final BlockingQueue<Runnable> mTaskQueue;
/**
* New threads are created using a ThreadFactory
*/
private BackgroundThreadFactory backgroundThreadFactory;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT;
//The reference is later used to communicate with the UI thread
private WeakReference<UiThreadCallback> uiThreadCallbackWeakReference;
//an interface which extends Executor interface. It is used to manage threads in the threads pool.
private final ExecutorService mExecutorService;
private List<Future> mRunningTaskList;
private static BroadcastManager mBroadcastManager = null;
// The class is used as a singleton
static {
KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
mBroadcastManager = new BroadcastManager();
}
private BroadcastManager(){
// initialize a queue for the thread pool. New tasks will be added to this queue
mTaskQueue = new LinkedBlockingQueue<Runnable>();
mRunningTaskList = new ArrayList<>();
backgroundThreadFactory = new BackgroundThreadFactory();
mExecutorService = new ThreadPoolExecutor(NUMBER_OF_CORES,
NUMBER_OF_CORES*2,
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
mTaskQueue,
backgroundThreadFactory);
}
public static BroadcastManager getInstance(){
return mBroadcastManager;
}
/**
* New threads are created using a ThreadFactory
*/
private static class BackgroundThreadFactory implements ThreadFactory {
private static int sTag = 1;
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName("CustomThread" + sTag);
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
// A exception handler is created to log the exception from threads
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("TPE", thread.getName() + " encountered an error: " + ex.getMessage());
}
});
return thread;
}
}
// Add a callable to the queue, which will be executed by the next available thread in the pool
public void addCallable(Callable callable){
Future future = mExecutorService.submit(callable);
mRunningTaskList.add(future);
}
/* Remove all tasks in the queue and stop all running threads
* Notify UI thread about the cancellation
*/
/*public void cancelAllTasks() {
synchronized (this) {
mTaskQueue.clear();
for (Future task : mRunningTaskList) {
if (!task.isDone()) {
task.cancel(true);
}
}
mRunningTaskList.clear();
}
sendMessageToUiThread(Util.createMessage(Util.MESSAGE_ID, "All tasks in the thread pool are cancelled"));
}*/
// Keep a weak reference to the UI thread, so we can send messages to the UI thread
public void setUiThreadCallback(UiThreadCallback uiThreadCallback) {
this.uiThreadCallbackWeakReference = new WeakReference<UiThreadCallback>(uiThreadCallback);
}
// Pass the message to the UI thread
public void sendMessageToUiThread(Message message){
if(uiThreadCallbackWeakReference != null && uiThreadCallbackWeakReference.get() != null) {
uiThreadCallbackWeakReference.get().publishToUiThread(message);
}
}
}
| 34.046053 | 113 | 0.684444 |
d2e421e79d44fda127a88b0d428b0a56b6838316 | 1,904 | package io.github.fatihbozik.ch3.workingwithgenerics.example7;
import java.util.ArrayList;
import java.util.List;
public class UpperBoundedWildcard {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>();
integerList.add(5);
integerList.add(2);
System.out.println("Total of integer number: " + total(integerList));
List<Float> floatList = new ArrayList<>();
floatList.add(7f);
floatList.add(10f);
System.out.println("Total of float numbers: " + total(floatList));
}
public static long total(List<? extends Number> list) { // public static long total(List list) {
long count = 0; // long count = 0;
//
for (Number number : list) { // for(Object obj: list) {
count += number.longValue(); // Number number = (Number) obj;
} // count += number.longValue();
// }
return count; // return count;
} // }
public static <N extends Number> long total2(List<N> list) { // public static long total(List list) {
long count = 0; // long count = 0;
//
for (Number number : list) { // for(Object obj: list) {
count += number.longValue(); // Number number = (Number) obj;
} // count += number.longValue();
// }
return count; // return count;
} // }
}
| 47.6 | 105 | 0.421218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.