hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1ab6266c868b23b11a5978957e7b4d455b025f | 2,276 | java | Java | web/shared-beans/src/main/java/io/deephaven/web/shared/ast/MakeExpressionsNullSafe.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 55 | 2021-05-11T16:01:59.000Z | 2022-03-30T14:30:33.000Z | web/shared-beans/src/main/java/io/deephaven/web/shared/ast/MakeExpressionsNullSafe.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 943 | 2021-05-10T14:00:02.000Z | 2022-03-31T21:28:15.000Z | web/shared-beans/src/main/java/io/deephaven/web/shared/ast/MakeExpressionsNullSafe.java | mattrunyon/deephaven-core | 80e3567e4647ab76a81e483d0a8ab542f9aadace | [
"MIT"
] | 29 | 2021-05-10T11:33:16.000Z | 2022-03-30T21:01:54.000Z | 40.642857 | 115 | 0.676186 | 11,342 | package io.deephaven.web.shared.ast;
import io.deephaven.web.shared.data.FilterDescriptor;
import io.deephaven.web.shared.data.FilterDescriptor.FilterOperation;
/**
* Rewrites logical expressions into an actual version that does what would be expected. Right now this is just
* equalsIgnoreCase and its negation, to support null values.
*/
public class MakeExpressionsNullSafe extends ReplacingVisitor {
public static FilterDescriptor execute(FilterDescriptor descriptor) {
return new MakeExpressionsNullSafe().visit(descriptor);
}
@Override
public FilterDescriptor onEqualIgnoreCase(FilterDescriptor descriptor) {
return rewriteEqualIgnoreCaseExpression(descriptor);
}
@Override
public FilterDescriptor onNotEqualIgnoreCase(FilterDescriptor descriptor) {
return rewriteEqualIgnoreCaseExpression(descriptor).not();
}
private FilterDescriptor rewriteEqualIgnoreCaseExpression(FilterDescriptor descriptor) {
// rewriting A (is-equal-ignore-case) B
// to A == null ? B == null : A.equalsIgnoreCase(B)
// without the ternary, this is:
// (A == null && B == null) || (A != null && A.equalsIgnoreCase(B))
FilterDescriptor lhs = descriptor.getChildren()[0];
FilterDescriptor rhs = descriptor.getChildren()[1];
return node(
FilterOperation.OR,
node(FilterOperation.AND,
node(FilterOperation.IS_NULL, lhs),
node(FilterOperation.IS_NULL, rhs)),
node(FilterOperation.AND,
node(FilterOperation.NOT,
node(FilterOperation.IS_NULL, lhs)),
nodeEqIgnoreCase(FilterOperation.INVOKE, lhs, rhs)));
}
private FilterDescriptor nodeEqIgnoreCase(FilterOperation invoke, FilterDescriptor lhs, FilterDescriptor rhs) {
FilterDescriptor node = node(invoke, lhs, rhs);
node.setValue("equalsIgnoreCase");// note that this would fail validation
return node;
}
private FilterDescriptor node(FilterOperation op, FilterDescriptor... children) {
FilterDescriptor descriptor = new FilterDescriptor(op, null, null, children);
return descriptor;
}
}
|
3e1ab6e3fc345c7094e7e27306b599e37b01dc96 | 10,915 | java | Java | appinventor/components/src/com/google/appinventor/components/runtime/Polygon.java | Qiuyue-Liu/appinventor-sources | 3b2af9538971e710cdbfb25dafdc4fe7563060fc | [
"Apache-2.0"
] | 2 | 2019-10-04T17:51:46.000Z | 2020-06-12T23:56:25.000Z | appinventor/components/src/com/google/appinventor/components/runtime/Polygon.java | Qiuyue-Liu/appinventor-sources | 3b2af9538971e710cdbfb25dafdc4fe7563060fc | [
"Apache-2.0"
] | 3 | 2018-04-27T19:50:25.000Z | 2018-05-04T19:10:05.000Z | appinventor/components/src/com/google/appinventor/components/runtime/Polygon.java | Qiuyue-Liu/appinventor-sources | 3b2af9538971e710cdbfb25dafdc4fe7563060fc | [
"Apache-2.0"
] | 2 | 2020-01-15T08:33:07.000Z | 2020-07-29T06:00:00.000Z | 38.298246 | 120 | 0.71388 | 11,343 | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright © 2016-2017 Massachusetts Institute of Technology, All rights reserved.
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime;
import android.text.TextUtils;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.errors.DispatchableError;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import com.google.appinventor.components.runtime.util.GeometryUtil;
import com.google.appinventor.components.runtime.util.MapFactory;
import com.google.appinventor.components.runtime.util.MapFactory.MapCircle;
import com.google.appinventor.components.runtime.util.MapFactory.MapFeatureVisitor;
import com.google.appinventor.components.runtime.util.MapFactory.MapLineString;
import com.google.appinventor.components.runtime.util.MapFactory.MapMarker;
import com.google.appinventor.components.runtime.util.MapFactory.MapPolygon;
import com.google.appinventor.components.runtime.util.MapFactory.MapRectangle;
import com.google.appinventor.components.runtime.util.YailList;
import org.json.JSONArray;
import org.json.JSONException;
import org.locationtech.jts.geom.Geometry;
import org.osmdroid.util.GeoPoint;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@DesignerComponent(version = YaVersion.POLYGON_COMPONENT_VERSION,
category = ComponentCategory.MAPS,
description = "Polygon")
@SimpleObject
public class Polygon extends PolygonBase implements MapPolygon {
private static final String TAG = Polygon.class.getSimpleName();
private List<List<GeoPoint>> points = new ArrayList<List<GeoPoint>>();
private List<List<List<GeoPoint>>> holePoints = new ArrayList<List<List<GeoPoint>>>();
private boolean multipolygon = false;
private static final MapFeatureVisitor<Double> distanceComputation = new MapFeatureVisitor<Double>() {
@Override
public Double visit(MapMarker marker, Object... arguments) {
if ((Boolean) arguments[1]) {
return GeometryUtil.distanceBetweenCentroids(marker, (Polygon) arguments[0]);
} else {
return GeometryUtil.distanceBetweenEdges(marker, (Polygon) arguments[0]);
}
}
@Override
public Double visit(MapLineString lineString, Object... arguments) {
if ((Boolean) arguments[1]) {
return GeometryUtil.distanceBetweenCentroids(lineString, (Polygon) arguments[0]);
} else {
return GeometryUtil.distanceBetweenEdges(lineString, (Polygon) arguments[0]);
}
}
@Override
public Double visit(MapPolygon polygon, Object... arguments) {
if ((Boolean) arguments[1]) {
return GeometryUtil.distanceBetweenCentroids(polygon, (Polygon) arguments[0]);
} else {
return GeometryUtil.distanceBetweenEdges(polygon, (Polygon) arguments[0]);
}
}
@Override
public Double visit(MapCircle circle, Object... arguments) {
if ((Boolean) arguments[1]) {
return GeometryUtil.distanceBetweenCentroids((Polygon) arguments[0], circle);
} else {
return GeometryUtil.distanceBetweenEdges((Polygon) arguments[0], circle);
}
}
@Override
public Double visit(MapRectangle rectangle, Object... arguments) {
if ((Boolean) arguments[1]) {
return GeometryUtil.distanceBetweenCentroids((Polygon) arguments[0], rectangle);
} else {
return GeometryUtil.distanceBetweenEdges((Polygon) arguments[0], rectangle);
}
}
};
public Polygon(MapFactory.MapFeatureContainer container) {
super(container, distanceComputation);
container.addFeature(this);
}
@Override
@SimpleProperty(category = PropertyCategory.BEHAVIOR,
description = "The type of the feature. For polygons, this returns the text \"Polygon\".")
public String Type() {
return MapFactory.MapFeatureType.TYPE_POLYGON;
}
@Override
@SimpleProperty(category = PropertyCategory.BEHAVIOR,
description = "Gets or sets the sequence of points used to draw the polygon.")
public YailList Points() {
if (points.isEmpty()) {
return YailList.makeEmptyList();
} else if (multipolygon) {
// Return a 2-deep list of points for multipolygons
List<YailList> result = new LinkedList<YailList>();
for (List<GeoPoint> part : points) {
result.add(GeometryUtil.pointsListToYailList(part));
}
return YailList.makeList(result);
} else {
// Return a 1-deep list of points for simple polygons
return GeometryUtil.pointsListToYailList(points.get(0));
}
}
@Override
@SimpleProperty
public void Points(YailList points) {
try {
if (GeometryUtil.isPolygon(points)) {
multipolygon = false;
this.points.clear();
this.points.add(GeometryUtil.pointsFromYailList(points));
} else if (GeometryUtil.isMultiPolygon(points)) {
multipolygon = true;
this.points = GeometryUtil.multiPolygonFromYailList(points);
} else {
throw new DispatchableError(ErrorMessages.ERROR_POLYGON_PARSE_ERROR,
"Unable to determine the structure of the points argument.");
}
clearGeometry();
} catch(DispatchableError e) {
container.$form().dispatchErrorOccurredEvent(this, "Points", e.getErrorCode(), e.getArguments());
}
}
@SuppressWarnings("squid:S00100")
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING)
@SimpleProperty(description = "Constructs a polygon from the given list of coordinates.")
public void PointsFromString(String pointString) {
if (TextUtils.isEmpty(pointString)) {
points = new ArrayList<List<GeoPoint>>(); // create a new list in case the user has saved a reference
map.getController().updateFeaturePosition(this);
return;
}
try {
JSONArray content = new JSONArray(pointString);
if (content.length() == 0) {
points = new ArrayList<List<GeoPoint>>(); // create a new list in case the user has saved a reference
multipolygon = false;
map.getController().updateFeaturePosition(this);
return;
}
points = GeometryUtil.multiPolygonToList(content);
multipolygon = points.size() > 1;
clearGeometry();
map.getController().updateFeaturePosition(this);
} catch(JSONException e) {
container.$form().dispatchErrorOccurredEvent(this, "PointsFromString",
ErrorMessages.ERROR_POLYGON_PARSE_ERROR, e.getMessage());
} catch(DispatchableError e) {
getDispatchDelegate().dispatchErrorOccurredEvent(this, "PointsFromString",
e.getErrorCode(), e.getArguments());
}
}
@Override
@SimpleProperty
public YailList HolePoints() {
if (holePoints.isEmpty()) {
return YailList.makeEmptyList();
} else if (multipolygon) {
List<YailList> result = new LinkedList<YailList>();
for (List<List<GeoPoint>> polyholes : holePoints) {
result.add(GeometryUtil.multiPolygonToYailList(polyholes));
}
return YailList.makeList(result);
} else {
return GeometryUtil.multiPolygonToYailList(holePoints.get(0));
}
}
@Override
@SimpleProperty
public void HolePoints(YailList points) {
try {
if (points.size() == 0) {
holePoints = new ArrayList<List<List<GeoPoint>>>();
} else if (multipolygon) {
this.holePoints = GeometryUtil.multiPolygonHolesFromYailList(points);
} else if (GeometryUtil.isMultiPolygon(points)) {
List<List<List<GeoPoint>>> holes = new ArrayList<List<List<GeoPoint>>>();
holes.add(GeometryUtil.multiPolygonFromYailList(points));
this.holePoints = holes;
} else {
throw new DispatchableError(ErrorMessages.ERROR_POLYGON_PARSE_ERROR,
"Unable to determine the structure of the points argument.");
}
clearGeometry();
map.getController().updateFeaturePosition(this);
} catch(DispatchableError e) {
container.$form().dispatchErrorOccurredEvent(this, "HolePoints",
e.getErrorCode(), e.getArguments());
}
}
@SuppressWarnings("squid:S00100")
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING)
@SimpleProperty(description = "Constructs holes in a polygon from a given list of coordinates per hole.")
public void HolePointsFromString(String pointString) {
if (TextUtils.isEmpty(pointString)) {
holePoints = new ArrayList<List<List<GeoPoint>>>(); // create a new list in case the user has saved a reference
map.getController().updateFeaturePosition(this);
return;
}
try {
JSONArray content = new JSONArray(pointString);
if (content.length() == 0) {
holePoints = new ArrayList<List<List<GeoPoint>>>(); // create a new list in case the user has saved a reference
map.getController().updateFeaturePosition(this);
return;
}
holePoints = GeometryUtil.multiPolygonHolesToList(content);
map.getController().updateFeaturePosition(this);
Log.d(TAG, "Points: " + points);
} catch(JSONException e) {
Log.e(TAG, "Unable to parse point string", e);
container.$form().dispatchErrorOccurredEvent(this, "HolePointsFromString",
ErrorMessages.ERROR_POLYGON_PARSE_ERROR, e.getMessage());
}
}
@Override
@SimpleFunction(description = "Returns the centroid of the Polygon as a (latitude, longitude) pair.")
public YailList Centroid() {
return super.Centroid();
}
@Override
public List<List<GeoPoint>> getPoints() {
return points;
}
@Override
public List<List<List<GeoPoint>>> getHolePoints() {
return holePoints;
}
@Override
public <T> T accept(MapFeatureVisitor<T> visitor, Object... arguments) {
return visitor.visit(this, arguments);
}
@Override
protected Geometry computeGeometry() {
return GeometryUtil.createGeometry(points, holePoints);
}
@Override
public void updatePoints(List<List<GeoPoint>> points) {
this.points.clear();
this.points.addAll(points);
clearGeometry();
}
@Override
public void updateHolePoints(List<List<List<GeoPoint>>> points) {
this.holePoints.clear();
this.holePoints.addAll(points);
clearGeometry();
}
}
|
3e1ab732f6b9661adc2c9e28ff0a222afb144d9f | 541 | java | Java | StrategyPatternTshirt/src/models/Color.java | AnastAnton/Assignment_3_Strategy_Patterns_Bootcamp | cb84efeaf4bd0e48e3ca26d3aa1a240cef7ad6b7 | [
"Unlicense"
] | null | null | null | StrategyPatternTshirt/src/models/Color.java | AnastAnton/Assignment_3_Strategy_Patterns_Bootcamp | cb84efeaf4bd0e48e3ca26d3aa1a240cef7ad6b7 | [
"Unlicense"
] | null | null | null | StrategyPatternTshirt/src/models/Color.java | AnastAnton/Assignment_3_Strategy_Patterns_Bootcamp | cb84efeaf4bd0e48e3ca26d3aa1a240cef7ad6b7 | [
"Unlicense"
] | null | null | null | 20.807692 | 79 | 0.643253 | 11,344 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package models;
/**
*
* @author AnastAnton
*/
public enum Color {
RED(3f), ORANGE(3.2f), YELLOW(3.4f), GREEN(3.6f),
BLUE(3.8f), INDIGO(4f), VIOLET(4.2f);
private final float unitPrice;
private Color(float unitPrice) {
this.unitPrice = unitPrice;
}
public float getUnitPrice() {
return unitPrice;
}
}
|
3e1ab7655f6acbd916e5f2e75630d48c4e0c99b4 | 9,975 | java | Java | komet/application/src/main/java/sh/komet/fx/stage/NativeExportTemplate.java | HappyFacade/komet | 772483695fe1c78a62373bd930f6c04bfa14ab6c | [
"Apache-2.0"
] | 7 | 2015-12-01T21:53:06.000Z | 2019-09-19T19:32:18.000Z | komet/application/src/main/java/sh/komet/fx/stage/NativeExportTemplate.java | HappyFacade/komet | 772483695fe1c78a62373bd930f6c04bfa14ab6c | [
"Apache-2.0"
] | 14 | 2020-03-04T22:07:21.000Z | 2022-01-21T23:19:45.000Z | komet/application/src/main/java/sh/komet/fx/stage/NativeExportTemplate.java | HappyFacade/komet | 772483695fe1c78a62373bd930f6c04bfa14ab6c | [
"Apache-2.0"
] | 8 | 2016-07-06T18:21:25.000Z | 2020-02-10T16:37:04.000Z | 45.547945 | 142 | 0.561504 | 11,345 | /*
* Copyright 2018 ISAAC's KOMET Collaborators.
*
* 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 sh.komet.fx.stage;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import sh.isaac.api.Get;
import sh.isaac.api.TaxonomyService;
import sh.isaac.api.bootstrap.TermAux;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.commit.Stamp;
import sh.isaac.api.commit.StampService;
import sh.isaac.api.externalizable.IsaacObjectType;
import static sh.isaac.api.externalizable.IsaacObjectType.UNKNOWN;
import sh.isaac.api.task.TimedTaskWithProgressTracker;
import sh.isaac.model.ChronologyImpl;
import sh.komet.gui.util.FxGet;
/**
*
* @author kec
*/
public class NativeExportTemplate extends TimedTaskWithProgressTracker<Integer> {
final File exportFile;
int identifierCount = 0;
int exportCount = 0;
TreeSet<int[]> assemlageNidTypeTokenVersionTokenSet = new TreeSet((Comparator<int[]>) (int[] o1, int[] o2) -> {
int compare = Integer.compare(o1[0], o2[0]);
if (compare != 0) {
return compare;
}
compare = Integer.compare(o1[1], o2[1]);
if (compare != 0) {
return compare;
}
return Integer.compare(o1[2], o2[2]);
});
public NativeExportTemplate(File exportFile) {
this.exportFile = exportFile;
updateTitle("Native export to " + exportFile.getName());
Get.activeTasks().add(this);
}
@Override
protected Integer call() throws Exception {
try {
updateMessage("Counting identifiers...");
int[] assemblageNids = Get.identifierService().getAssemblageNids();
for (int assemblageNid: assemblageNids) {
Get.identifierService().getNidsForAssemblage(assemblageNid, false).forEach((nid) -> {
identifierCount++;
});
}
addToTotalWork(2*identifierCount);
updateMessage("Exporting identifiers...");
LOG.info("Identifier count: " + identifierCount);
try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(exportFile), StandardCharsets.UTF_8)) {
DataOutputStream dos = new DataOutputStream( zipOut );
ZipEntry identifierEntry = new ZipEntry("identifiers");
zipOut.putNextEntry(identifierEntry);
dos.writeInt(identifierCount);
for (int assemblageNid: assemblageNids) {
VersionType versionType = Get.assemblageService().getVersionTypeForAssemblage(assemblageNid);
Get.identifierService().getNidsForAssemblage(assemblageNid, false).forEach((nid) -> {
try {
dos.writeInt(nid);
UUID[] uuids = Get.identifierService().getUuidArrayForNid(nid);
dos.writeInt(uuids.length);
for (UUID uuid: uuids) {
dos.writeLong(uuid.getMostSignificantBits());
dos.writeLong(uuid.getLeastSignificantBits());
}
IsaacObjectType objectType = Get.identifierService().getObjectTypeForComponent(nid);
dos.writeByte(objectType.getToken());
dos.writeByte(versionType.getVersionTypeToken());
int[] assemlageNidTypeTokenVersionToken = new int[] {nid, objectType.getToken(), versionType.getVersionTypeToken()};
assemlageNidTypeTokenVersionTokenSet.add(assemlageNidTypeTokenVersionToken);
completedUnitOfWork();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
}
zipOut.closeEntry();
DataOutputStream typeOS = new DataOutputStream( zipOut );
ZipEntry typeEntry = new ZipEntry("types");
zipOut.putNextEntry(typeEntry);
typeOS.writeInt(assemlageNidTypeTokenVersionTokenSet.size());
assemlageNidTypeTokenVersionTokenSet.forEach((int[] types) -> {
try {
typeOS.writeInt(types[0]);
typeOS.writeInt(types[1]);
typeOS.writeInt(types[2]);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
zipOut.closeEntry();
updateMessage("Exporting STAMPs...");
ZipEntry stampEntry = new ZipEntry("stamp");
zipOut.putNextEntry(stampEntry);
StampService stampService = Get.stampService();
int[] stampSequences = stampService.getStampSequences().toArray();
dos.writeInt(stampSequences.length);
for (int stampSequence: stampSequences) {
try {
dos.writeInt(stampSequence);
Stamp stamp = stampService.getStamp(stampSequence);
dos.writeUTF(stamp.getStatus().name());
dos.writeLong(stamp.getTime());
dos.writeInt(stamp.getAuthorNid());
dos.writeInt(stamp.getModuleNid());
dos.writeInt(stamp.getPathNid());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
zipOut.closeEntry();
updateMessage("Exporting Taxonomy...");
ZipEntry taxonomy = new ZipEntry("taxonomy");
zipOut.putNextEntry(taxonomy);
TaxonomyService taxonomyService = Get.taxonomyService();
long count = Get.identifierService().getNidsForAssemblage(TermAux.SOLOR_CONCEPT_ASSEMBLAGE, true).count();
int[] conceptNids = new int[(int) count];
dos.writeInt(conceptNids.length);
addToTotalWork(conceptNids.length);
AtomicInteger taxonomyCount = new AtomicInteger();
Get.identifierService().getNidsForAssemblage(TermAux.SOLOR_CONCEPT_ASSEMBLAGE, false).forEach((int nid)-> {
try {
taxonomyCount.incrementAndGet();
dos.writeInt(nid);
int[] taxonomyData = taxonomyService.getTaxonomyData(TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid(), nid);
dos.writeInt(taxonomyData.length);
for (int i = 0; i < taxonomyData.length; i++) {
dos.writeInt(taxonomyData[i]);
}
completedUnitOfWork();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
zipOut.closeEntry();
if (count != taxonomyCount.longValue()) {
throw new IllegalStateException("Count: " + count + " TaxonomyCount: " + taxonomyCount.get());
}
updateMessage("Exporting objects...");
ZipEntry ibdfEntry = new ZipEntry("ibdf");
zipOut.putNextEntry(ibdfEntry);
for (int assemblageNid: assemblageNids) {
Get.identifierService().getNidsForAssemblage(assemblageNid, false).forEach((nid) -> {
Optional<? extends Chronology> chronologyOptional = Get.identifiedObjectService().getChronology(nid);
if (chronologyOptional.isPresent()) {
exportCount++;
try {
ChronologyImpl chronology = (ChronologyImpl) chronologyOptional.get();
dos.writeByte(chronology.getIsaacObjectType().getToken());
List<byte[]> dataToWrite = ChronologyImpl.getDataList(chronology);
dos.writeInt(dataToWrite.size());
for (byte[] data: dataToWrite) {
dos.writeInt(data.length);
dos.write(data);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
completedUnitOfWork();
});
}
dos.writeByte(UNKNOWN.getToken());
zipOut.closeEntry();
} catch (IOException ex) {
FxGet.dialogs().showErrorDialog("Failure during native export to zip file.", ex);
}
LOG.info("Export count: " + exportCount);
return identifierCount;
} finally {
Get.activeTasks().remove(this);
}
}
}
|
3e1ab8a01d0e1951a45669081923ab9300a087f4 | 12,427 | java | Java | Andromeda's Compiler/simple/src/com/google/devtools/simple/classfiles/ClassFile.java | mkeshita/Andromeda-Project | 544c9eabae1243a8ded3b6b381a48518516bd9bc | [
"MIT"
] | 6 | 2017-03-02T12:44:56.000Z | 2021-11-21T07:16:11.000Z | Andromeda's Compiler/simple/src/com/google/devtools/simple/classfiles/ClassFile.java | mkeshita/Andromeda-Project | 544c9eabae1243a8ded3b6b381a48518516bd9bc | [
"MIT"
] | 7 | 2018-11-12T11:58:15.000Z | 2018-11-12T12:18:09.000Z | Andromeda's Compiler/simple/src/com/google/devtools/simple/classfiles/ClassFile.java | mkeshita/Andromeda-Project | 544c9eabae1243a8ded3b6b381a48518516bd9bc | [
"MIT"
] | 3 | 2020-04-26T23:03:39.000Z | 2022-03-29T15:36:20.000Z | 30.089588 | 589 | 0.702824 | 11,346 | /*
* Copyright 2009 Google 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 com.google.devtools.simple.classfiles;
import com.google.devtools.simple.util.Preconditions;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a Java class file.
*
* <p>For more information about Java class files see the Java VM
* specification.
*
* @author Herbert Czymontek
*/
public final class ClassFile {
/*
* Represents an inner class attribute as defined by the Java VM specification.
*/
private class InnerClassAttribute {
// Indices into the constant pool
private final short innerclassIndex;
private final short outerclassIndex;
private final short nameIndex;
private final short innerFlags;
/*
* Creates a new inner class attribute.
*/
InnerClassAttribute(short innerclassIndex, short outerclassIndex, short nameIndex,
short innerFlags) {
this.innerclassIndex = innerclassIndex;
this.outerclassIndex = outerclassIndex;
this.nameIndex = nameIndex;
this.innerFlags = innerFlags;
}
/*
* Writes the inner class attribute into the classes byte buffer.
*/
void generate() {
generate16(innerclassIndex);
generate16(outerclassIndex);
generate16(nameIndex);
generate16(innerFlags);
}
}
/**
* Class access flags.
*/
public static final short ACC_PUBLIC = 0x0001;
public static final short ACC_FINAL = 0x0010;
public static final short ACC_SUPER = 0x0020;
public static final short ACC_INTERFACE = 0x0200;
public static final short ACC_ABSTRACT = 0x0400;
public static final short ACC_SYNTHETIC = 0x1000;
public static final short ACC_ANNOTATION = 0x2000;
public static final short ACC_ENUM = 0x4000;
// Mask containing all valid class access flags
private static final short ALLOWED_ACC_FLAGS = ACC_PUBLIC | ACC_FINAL | ACC_SUPER |
ACC_INTERFACE | ACC_ABSTRACT | ACC_SYNTHETIC | ACC_ANNOTATION | ACC_ENUM;
// Byte buffer holding the binary representation of the class
private Buffer buffer;
// Internal name of class
private final String internalName;
// Class constant pool
protected final ConstantPool constantpool;
// Access flags
private final short flags;
// Constant pool index of this class
private final short thisclass;
// Constant pool index of superclass
private final short superclass;
// List of constant pool indices of implemented interfaces by the class
private final List<Short> interfaces;
// List of fields defined by this class
private final List<Field> fields;
// List of methods defined by this class
private final List<Method> methods;
// List of required inner class attributes
private final List<InnerClassAttribute> innerclasses;
// Runtime visible annotations
private AnnotationsAttribute runtimeVisibleAnnotationsAttribute;
// Constant pool index of source file
private short sourceFileIndex;
// Class file attribute count
private short attributeCount;
// Constant pool index of InnerClasses attribute name (initialized lazily)
private short innerClassesAttributeIndex;
// Constant pool index of SourceFile attribute name (initialized lazily)
private short sourceFileAttributeIndex;
// Constant pool index of LocalVariableTable attribute name (initialized lazily)
private short localVariableTableAttributeIndex;
/**
* Creates a new instance of ClassFile.
*
* @param flags class access flags
* @param internalName internal name of class
* @param superclassInternalName internal name of superclass
*/
public ClassFile(short flags, String internalName, String superclassInternalName) {
constantpool = new ConstantPool();
interfaces = new ArrayList<Short>();
fields = new ArrayList<Field>();
methods = new ArrayList<Method>();
innerclasses = new ArrayList<InnerClassAttribute>();
Preconditions.checkArgument((flags & ALLOWED_ACC_FLAGS) == flags);
this.flags = flags;
this.internalName = internalName;
thisclass = constantpool.newConstantClass(internalName);
superclass = constantpool.newConstantClass(superclassInternalName);
}
/**
* Returns the internal name of the class.
*
* @return internal name
*/
public String getInternalName() {
return internalName;
}
/**
* Returns the name of the class.
*
* @return name
*/
public String getName() {
return internalName.replace('/', '.');
}
/**
* Adds the given internal class name to the list of interfaces implemented
* by this class.
*
* @param internalInterfaceName class name in internal format
*/
public void addInterfaceImplementation(String internalInterfaceName) {
interfaces.add(Short.valueOf(constantpool.newConstantClass(internalInterfaceName)));
}
/**
* Adds a new method defined by this class.
*
* @param access method access flags
* @param name method name
* @param signature method signature
* @return {@link Method} object for generating class file data for the
* method
*/
public Method newMethod(short access, String name, String signature) {
Method method = new Method(this, access, name, signature);
methods.add(method);
return method;
}
/**
* Adds a new field defined by this class.
*
* @param access field access flags
* @param name field name
* @param signature field signature
* @return {@link Field} object for generating class file data for the
* field
*/
public Field newField(short access, String name, String signature) {
Field field = new Field(this, access, name, signature);
fields.add(field);
return field;
}
/**
* Adds a new inner class defined by this class.
*
* @param access inner class access flags
* @param name inner class names
* @param innerInternalname name of inner class in internal format
*/
public void addInnerClass(short access, String name, String innerInternalname) {
createInnerClassesAttributeIndex();
short innerclassIndex = constantpool.newConstantClass(innerInternalname);
short nameIndex = name == null ? (short) 0 : constantpool.newConstantUtf8(name);
innerclasses.add(new InnerClassAttribute(innerclassIndex, thisclass, nameIndex, access));
}
/**
* Declares a class as the outer class of this class.
*
* @param access outer class access flags
* @param name outer class names
* @param outerInternalname name of outer class in internal format
*/
public void addOuterClass(short access, String name, String outerInternalname) {
createInnerClassesAttributeIndex();
short outerclassIndex = constantpool.newConstantClass(outerInternalname);
short nameIndex = name == null ? (short) 0 : constantpool.newConstantUtf8(name);
innerclasses.add(new InnerClassAttribute(thisclass, outerclassIndex, nameIndex, access));
}
/**
* Returns runtime visible annotations attribute.
*
* @return runtime visible annotations attribute
*/
public AnnotationsAttribute getRuntimeVisibleAnnotationsAttribute() {
if (runtimeVisibleAnnotationsAttribute == null) {
runtimeVisibleAnnotationsAttribute =
new AnnotationsAttribute(this, "RuntimeVisibleAnnotations");
attributeCount++;
}
return runtimeVisibleAnnotationsAttribute;
}
/**
* Sets the name of the corresponding source file.
*
* @param filename filename of source file without any directory information
*/
public void setSourceFile(String filename) {
createSourceFileAttributeIndex();
sourceFileIndex = constantpool.newConstantUtf8(filename);
}
/**
* Generates the binary data for the class file. For detailed information
* about Java class files see the Java VM specification.
*
* @return byte array containing binary data for class file
*/
public byte[] generate() {
buffer = new Buffer();
// Generate magic number and classfile version information
generate32(0xCAFEBABE);
generate16((short) 0); // Minor version
generate16((short) (44 + 5)); // Major version - JDK 1.5 for now
// Generate constant pool
constantpool.generate(this);
// Generate class access flags
generate16(flags);
// Generate class hierarchy information
generate16(thisclass);
generate16(superclass);
// Generate attribute for implemented interfaces
generate16((short) interfaces.size());
for (Short s : interfaces) {
generate16(s);
}
// Generate field information
generate16((short) fields.size());
for (Field field : fields) {
field.generate();
}
// Generate method information
generate16((short) methods.size());
for (Method method : methods) {
method.generate();
}
// Generate attribute count
generate16(attributeCount);
// Generate InnerClasses attribute
if (innerclasses.size() != 0) {
generateInnerclassAttribute();
}
// Generate RuntimeVisibleAnnotations attribute
if (runtimeVisibleAnnotationsAttribute != null) {
runtimeVisibleAnnotationsAttribute.generate();
}
// Generate SourceFile attribute
if (sourceFileIndex != 0) {
generateSourceFileAttribute();
}
return buffer.toByteArray();
}
/**
* Generates a byte value into the class data buffer.
*
* @param b byte to generate
*/
protected void generate8(byte b) {
buffer.generate8(b);
}
/**
* Generates a short value into the class data buffer.
*
* @param s short to generate
*/
protected void generate16(short s) {
buffer.generate16(s);
}
/**
* Generates an int value into the class data buffer.
*
* @param i int to generate
*/
protected void generate32(int i) {
buffer.generate32(i);
}
/**
* Generates a long value into the class data buffer.
*
* @param l long to generate
*/
protected void generate64(long l) {
buffer.generate64(l);
}
/**
* Copies an array of bytes into the class data buffer.
*
* @param bytes bytes to copy
*/
protected void generateBytes(byte[] bytes) {
buffer.generateBytes(bytes);
}
/**
* Creates a constant pool index for the LocalVariableTable attribute name.
* Because this index is initialized lazily, it is important that
* methods creating LocalVariableTable attributes must call this method.
*/
protected void createLocalVariableTableAttributeIndex() {
if (localVariableTableAttributeIndex == 0) {
localVariableTableAttributeIndex = constantpool.newConstantUtf8("LocalVariableTable");
}
}
/*
* Creates a constant pool index for the InnerClasses attribute name.
*/
private void createInnerClassesAttributeIndex() {
if (innerClassesAttributeIndex == 0) {
innerClassesAttributeIndex = constantpool.newConstantUtf8("InnerClasses");
attributeCount++;
}
}
/*
* Creates a constant pool index for the SourceFile attribute name.
*/
private void createSourceFileAttributeIndex() {
if (sourceFileAttributeIndex == 0) {
sourceFileAttributeIndex = constantpool.newConstantUtf8("SourceFile");
attributeCount++;
}
}
/*
* Writes the binary data for the InnerClass attributes to the class data buffer.
*/
private void generateInnerclassAttribute() {
generate16(innerClassesAttributeIndex);
generate32(2 + (innerclasses.size() * (2 + 2 + 2 + 2)));
generate16((short) innerclasses.size());
for (InnerClassAttribute innerclass : innerclasses) {
innerclass.generate();
}
}
/*
* Writes the binary data for the SourceFile attribute to the class data buffer.
*/
private void generateSourceFileAttribute() {
generate16(sourceFileAttributeIndex);
generate32(2);
generate16(sourceFileIndex);
}
}
|
3e1aba18322f6a7b8b6b2e948845c7381b0617bb | 17,701 | java | Java | test/com/rcwang/seal/fetch/ClueWebSearcherTest.java | TeamCohen/SEAL | 0d105370a89772df537eb5024e2fd42b7b4b8ca8 | [
"Apache-2.0"
] | 21 | 2015-03-11T01:56:23.000Z | 2021-05-20T02:34:02.000Z | test/com/rcwang/seal/fetch/ClueWebSearcherTest.java | TeamCohen/SEAL | 0d105370a89772df537eb5024e2fd42b7b4b8ca8 | [
"Apache-2.0"
] | 1 | 2018-06-14T15:48:19.000Z | 2018-06-14T15:48:19.000Z | test/com/rcwang/seal/fetch/ClueWebSearcherTest.java | TeamCohen/SEAL | 0d105370a89772df537eb5024e2fd42b7b4b8ca8 | [
"Apache-2.0"
] | 5 | 2015-02-04T19:44:40.000Z | 2018-06-21T17:16:58.000Z | 41.261072 | 162 | 0.632111 | 11,347 | package com.rcwang.seal.fetch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.apache.commons.io.input.ReaderInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.rcwang.seal.expand.Entity;
import com.rcwang.seal.expand.EntityList;
import com.rcwang.seal.expand.Seal;
import com.rcwang.seal.expand.SetExpander;
import com.rcwang.seal.fetch.ClueWebSearcher;
import com.rcwang.seal.fetch.WebSearcher;
import com.rcwang.seal.rank.Graph;
import com.rcwang.seal.rank.GraphRanker;
import com.rcwang.seal.rank.Graph.Node;
import com.rcwang.seal.rank.Graph.NodeSet;
import com.rcwang.seal.rank.Ranker.Feature;
import com.rcwang.seal.util.GlobalVar;
import com.rcwang.seal.util.Helper;
import com.rcwang.seal.util.StringFactory;
import static org.junit.Assert.*;
public class ClueWebSearcherTest {
private static final Logger log = Logger.getLogger(ClueWebSearcherTest.class);
@BeforeClass
public static void setupLogging() throws FileNotFoundException, IOException {
Properties logging = new Properties();
logging.load(new FileInputStream(new File("config/log4j.properties")));
PropertyConfigurator.configure(logging);
Logger.getLogger(ClueWebSearcher.class).setLevel(Level.DEBUG);
log.setLevel(Level.DEBUG);
Logger.getLogger(ClueWebSearcher.class).debug("Testing debug log");
}
@Test
public void testNPE() throws FileNotFoundException, IOException {
GlobalVar gv = GlobalVar.getGlobalVar();
Properties prop = new Properties();
prop.load(new FileInputStream("../OntologyLearner/conf/seal.properties"));
gv.load(prop);
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TMP_DIR,"/tmp/");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_HEADER_TIMEOUT_MS,"20000");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TIMEOUT_REPORTING_MS,"5000");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TIMEOUT_NUMTRIALS,"10");
gv.setStopwordsList(new File("lib/stopwords.txt"));
gv.setClueWebKeepQueryFile(true);
gv.setClueWebKeepResponseFile(true);
Seal s = new Seal();
EntityList el = new EntityList();
String[] seeds = ("Gm, Bmw, KIA, TVR, kia, Benz, ACURA, Acura, DODGE, E-M-F, Lexus, VOLVO, Vashon, jaguar, suzuki, AvtoVAZ, AvtoVaz, HYUNDAI, PEUGEOT, "+
"Porsche, Renault, Sanchis, avtovaz, citroen, peugeot, CORVETTE, Motobloc, cadillac, motobloc, CHEVROLET, Land rover, volkswagen, mercedes clc, nissan motor,"+
" Austro Daimler, AMERICAN MOTORS, Mercedes SLR-Class, Mitsubishi Evolander, mercedes used canada, mercedes_benz_cars_usa, mitsubishi galant lambda, MITSUBISHI"+
" FTO Fan Clutch, Mitsubishi Motors Company, mercedes e class 2010 new, mercedes_benz_sprinter_3_t, Mercedes R63 AMG and ML63 AMG, mitsubishi fto petrol fuel"+
" tank, MITSUBISHI FTO Front Bumper Guard").split(", ");
for (String seed : seeds) { el.add(seed); }
s.expand(el);
}
@Test
public void testCachedOLRelations() throws FileNotFoundException, IOException {
GlobalVar gv = ontologyLearnerProperties();
ClueWebSearcher s = new ClueWebSearcher();
s.buildSnippets(new File("/tmp/clueweb-resp_30299.txt"));
EntityList el = new EntityList();
el.add(new Entity("Steelers","Pittsburgh"));
el.add(new Entity("Seahawks","Seattle"));
el.add(new Entity("Bears","Chicago"));
for (Feature f : Feature.values()) {
gv.setFeature(f);
Seal seal = new Seal();
seal.expand(el, s.getDocuments(0));
EntityList newEntities = seal.getEntityList();
if (seal.getRanker() instanceof GraphRanker)
ontologyLearnerScoring(newEntities, ((GraphRanker) seal.getRanker()).getGraph());
System.out.println(newEntities.toDetails(50));
assertTrue(f+" Nonrelational! :(",newEntities.iterator().next().isRelational());
}
System.out.println("Complete!");
}
public GlobalVar ontologyLearnerProperties() throws FileNotFoundException, IOException {
GlobalVar gv = GlobalVar.getGlobalVar();
Properties prop = new Properties();
prop.load(new FileInputStream("../OntologyLearner/conf/seal.properties"));
gv.load(prop);
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TMP_DIR,"/tmp/");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_HEADER_TIMEOUT_MS,"60000");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TIMEOUT_REPORTING_MS,"5000");
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TIMEOUT_NUMTRIALS,"10");
gv.setStopwordsList(new File("lib/stopwords.txt"));
gv.setClueWebKeepQueryFile(true);
gv.setClueWebKeepResponseFile(true);
return gv;
}
public void ontologyLearnerSeal(EntityList seeds) throws FileNotFoundException, IOException {
ontologyLearnerProperties();
Seal seal = new Seal();
seal.expand(seeds);
EntityList newEntities = seal.getEntityList();
Graph graph = ((GraphRanker) seal.getRanker()).getGraph();
ontologyLearnerScoring(newEntities,graph);
System.out.println(newEntities.toDetails(50));
System.out.println("Complete!");
}
public void ontologyLearnerScoring(EntityList newEntities, Graph graph) {
for (Entity en : newEntities) {
Node n = graph.getNode(StringFactory.toID(en.getName()));//content
if (n == null) {
continue;
}
for (String edgelabel : graph.getEdges(n)) {
NodeSet ds = graph.followEdge(n, edgelabel);
for (Node d : ds) {
if (!d.getType().equals(Graph.DOCUMENT_NODE_NAME)) continue;
System.out.print(".");
//System.out.println(en+": "+d.getName());
// Instance in = instanceFromEntity(
// entityInstances.get(en),
// en,
// d.getName(),
// 1.,
// "");
// if (!entityInstances.containsKey(en)) entityInstances.put(en,in);
}
}
}
}
@Test
public void testNPEAgain() throws FileNotFoundException, IOException {
EntityList el = new EntityList();
LineNumberReader reader = new LineNumberReader(new FileReader("../OntologyLearner/endless.troubleshooting/npe-query.txt"));
String line = "";
while (!line.startsWith("<text>")) assertNotNull(line = reader.readLine());
line = line.substring(7, line.length()-8);
String[] seeds = line.split("\\) #");
for (String seed : seeds) {
String s = seed.replaceAll("1\\(","");
log.debug(s);
el.add(s);
}
ontologyLearnerSeal(el);
}
@Test
public void testOLRelations() throws FileNotFoundException, IOException {
EntityList el = new EntityList();
el.add(new Entity("Steelers","Pittsburgh"));
el.add(new Entity("Seahawks","Seattle"));
el.add(new Entity("Bears","Chicago"));
ontologyLearnerSeal(el);
}
@Test
public void testPostTimeout() {
ArrayList<String> querySet = new ArrayList<String>();
querySet.add("#1(iguanas) #1(tortoises) #1(alligators)");
querySet.add("#1(scarves) #1(mittens) #1(ear muffs)");
querySet.add(" #1(Washington State University) #1(University of Oxford) #1(University of Pittsburgh)");
// querySet.add("#1(robin) #1(chickadee) #1(finch)");
// querySet.add("#1(red) #1(blue) #1(green)");
// querySet.add("#1(boston) #1(new york) #1(san francisco) #1(seattle)");
GlobalVar gv = GlobalVar.getGlobalVar();
gv.getProperties().setProperty("clueweb.headerTimeout", "11500");
ClueWebSearcher s = new ClueWebSearcher();
File resp = s.sendBatchQuery(querySet);
// resp = s.sendBatchQuery(querySet);
// resp = s.sendBatchQuery(querySet);
}
@Test @Ignore
public void testRun() throws FileNotFoundException, IOException {
ClueWebSearcher s = new ClueWebSearcher();
s.addQuery("birds");
s.run();
assertEquals(100,s.getSnippets().size());
}
@Test
public void testCachedSearch() throws FileNotFoundException, IOException {
ClueWebSearcher s = new ClueWebSearcher();
s.setFulltext(FULLTEXT_ON);
s.setDiskMode(true);
s.setMemoryManagement(true);
s.setKeepResponseFile(true);
s.setFormat(ClueWebSearcher.FORMAT_TREC_EVAL);
s.buildSnippets(new File("/tmp/clueweb-resp_30299.txt"));
File cachedQuery = new File("/tmp/clueweb-query_30298.txt");
// File cachedQuery = new File("../OntologyLearner/bostonPerformanceStudy/categoryQuery.txt");
List<EntityList> queryseeds = new ArrayList<EntityList>();
BufferedReader reader = new BufferedReader(new FileReader(cachedQuery));
for (String line; (line = reader.readLine()) != null;) {
if (line.startsWith("<text>")) {
String[] seeds = line.substring(6,line.length()-7).split(" ");
EntityList query = new EntityList();
for (String seed : seeds) { if (seed.length() < 4) continue;
query.add(new Entity(seed.substring(3,seed.length()-1)));
}
queryseeds.add(query);
}
} reader.close();
int i=0;
for (String q : s.getQueries()) {
Seal seal = new Seal();
DocumentSet ds = s.getDocuments(i);
assertTrue("DocuemntSet size "+ds.size()+"exceeds limit of 100",ds.size() <= 100);
seal.expand(queryseeds.get(i), ds);
i++;
}
System.out.println("Stopping for heap dump");
}
@Test
public void testBuildSnippets() throws FileNotFoundException, IOException {
ClueWebSearcher s = new ClueWebSearcher();
s.setFulltext(FULLTEXT_ON);
s.setMemoryManagement(true);
s.setKeepResponseFile(true);
s.setFormat(ClueWebSearcher.FORMAT_INDRI);
s.buildSnippets(new File("cluewebTestQueryResponse.txt"));
assertEquals(100,s.getSnippets().size());
}
@Test
public void testBuildSnippets_trec() throws FileNotFoundException, IOException {
ClueWebSearcher s = new ClueWebSearcher();
s.setFormat(ClueWebSearcher.FORMAT_TREC_EVAL);
s.setMemoryManagement(true);
// s.buildSnippets(new File("cluewebTestQueryResponse_trec.txt"));
// assertEquals(100,s.getSnippets().size());
s.buildSnippets(new File("/tmp/clueweb-resp_47622txt"));
assertEquals(7017,s.getSnippets().size());
}
@Test
public void investigate_skipped_documents() throws FileNotFoundException, IOException {
ClueWebSearcher s = new ClueWebSearcher();
s.setFormat(ClueWebSearcher.FORMAT_TREC_EVAL);
s.setMemoryManagement(true);
s.buildSnippets(new File("cluewebTestQueryResponse_trec_failure.txt"));
for (int i=0;i<97;i++) {
System.out.println("Analyzing query "+i);
DocumentSet q = s.getDocuments(i);
if (q.size() == 0) continue;
if (q.size() != 100) {
int[] ranks = new int[100];
for (int d=0;d<q.size();d++) { ranks[d] = q.get(d).getSnippet().getRank(); }
Arrays.sort(ranks);
int j=1;
for (int d=0;d<q.size() && j<ranks.length;d++) {
while (ranks[d] != j) {
System.out.println("\tMissing "+j+" (seeking "+ranks[d]+")");
j=ranks[d];
}
j++;
}
break;
}
assertEquals(100,q.size());
}
assertEquals(100,s.getSnippets().size());
}
@Test
public void testOnlineSeal() throws FileNotFoundException, IOException {
GlobalVar gv = GlobalVar.getGlobalVar();
Properties prop = new Properties();
prop.load(new FileInputStream("config/seal.properties.online"));
gv.load(prop);
gv.setUseEngine(8); gv.setFeature(Feature.GWW);
gv.setIsFetchFromWeb(false);
gv.setClueWebMemoryManagement(false);
gv.setClueWebKeepResponseFile(true);
gv.setClueWebKeepQueryFile(true);
gv.getProperties().setProperty(GlobalVar.CLUEWEB_TMP_DIR, "tmp");
SetExpander seal = new Seal();
EntityList seeds = new EntityList();
seeds.add("Steelers"); seeds.add("Ravens"); seeds.add("Patriots");
seal.expand(seeds);
List<Entity> results = seal.getEntities();
assertTrue("No results!",results.size() > 0);
System.out.println(seal.getEntityList().toDetails(10));
}
static final boolean FULLTEXT_ON=true;
static final boolean FULLTEXT_OFF=false;
@Test
public void testPiecewiseOnlineSeal() throws FileNotFoundException, IOException {
ArrayList<String[]> categories = new ArrayList<String[]>();
categories.add(new String[] {"Steelers","Ravens","Buccaneers"});
categories.add(new String[] {"bracelet","ring","necklace"});
categories.add(new String[] {"Pennsylvania","Virginia","Ohio"});
ClueWebSearcher s = runOnlineTest(categories, FULLTEXT_ON);
for (int i=0;i<categories.size();i++) {
assertTrue("Expected at least 1 document for query '"+s.getQuery(i)+"'",s.getDocuments(i).size()>0);
}
}
@Test
public void testPathologicalSeedsOnline() throws FileNotFoundException, IOException {
ArrayList<String[]> categories = new ArrayList<String[]>();
categories.add(new String[] {"Baccarat","Battleship","Blackjack","Blind Man ' s Bluff"});
categories.add(new String[] {"Avril Lavigne","Dan Aykroyd","Jim Carrey","Michael J . Fox","Bernardo O'Higgins"});
categories.add(new String[] {"pop","punk","r&b","rap","reggae"});
categories.add(new String[] {"U.S. Senate Majority Leader","U.S. Supreme Court Justice","Defence Secretary"});
categories.add(new String[] {"C++","COBOL","FORTRAN","LISP"});
categories.add(new String[] {"4th of July, Asbury Park","America the Beautiful","Being for the Benefit of Mr. Kite!"});
ClueWebSearcher s = runOnlineTest(categories, FULLTEXT_ON);
for (int i=0;i<categories.size();i++) {
assertTrue("Expected at least 1 document for query '"+s.getQuery(i)+"'",s.getDocuments(i).size()>0);
}
}
protected ClueWebSearcher runOnlineTest(List<String[]> categories, boolean usefulltext) throws FileNotFoundException, IOException {
GlobalVar gv = GlobalVar.getGlobalVar();
Properties prop = new Properties();
prop.load(new FileInputStream("config/seal.properties.online"));
gv.load(prop);
gv.setUseEngine(8);
gv.setIsFetchFromWeb(false);
long start = System.currentTimeMillis();
ClueWebSearcher searcher = new ClueWebSearcher(false);
searcher.setFulltext(usefulltext);
for (String[] cat : categories) {
searcher.addQuery(cat);
}
searcher.run();
long retrieve = System.currentTimeMillis();
System.out.println("Time: "+((double)(retrieve - start))/1000+"s");
for (int i=0; i<categories.size(); i++) {
String[] cat = categories.get(i);
EntityList seeds = new EntityList();
for (String s : cat) seeds.add(s);
Seal seal = new Seal();
seal.expand(seeds, searcher.getDocuments(i));
EntityList results = seal.getEntityList();
// assertTrue("No results for query "+searcher.getQueries().get(i),results.size() > 0);
System.out.println(results.toDetails(10));
}
long end = System.currentTimeMillis();
System.out.println("Retrieval: "+((double)(retrieve - start))/1000+"s");
System.out.println("Expansion: "+((double)(end - retrieve))/1000+"s");
System.out.println("Total: "+((double)(end - start))/1000+"s");
return searcher;
}
}
|
3e1abac2ed1634a63839ac8aad3c6ba8d93d421d | 875 | java | Java | hazelcast/src/test/java/usercodedeployment/blacklisted/BlacklistedEP.java | geva/hazelcast | cd5916c518bc2770f5914e13fd1e153646ec8860 | [
"Apache-2.0"
] | 2 | 2017-05-21T17:34:36.000Z | 2017-05-21T19:30:44.000Z | hazelcast/src/test/java/usercodedeployment/blacklisted/BlacklistedEP.java | geva/hazelcast | cd5916c518bc2770f5914e13fd1e153646ec8860 | [
"Apache-2.0"
] | null | null | null | hazelcast/src/test/java/usercodedeployment/blacklisted/BlacklistedEP.java | geva/hazelcast | cd5916c518bc2770f5914e13fd1e153646ec8860 | [
"Apache-2.0"
] | null | null | null | 33.653846 | 75 | 0.764571 | 11,348 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package usercodedeployment.blacklisted;
import usercodedeployment.IncrementingEntryProcessor;
/**
* Used in tests of User Code Deployment blacklisting and whitelisting.
*/
public final class BlacklistedEP extends IncrementingEntryProcessor {
}
|
3e1abb580183a806096a511f8571fb7f2bdaab64 | 719 | java | Java | src/main/java/ru/skornei/restserver/annotations/RestServer.java | skornei/restserver | 65d535236e3d2b888636c0c655d225af62c84654 | [
"Apache-2.0"
] | 19 | 2018-12-11T20:48:59.000Z | 2021-12-15T05:23:49.000Z | src/main/java/ru/skornei/restserver/annotations/RestServer.java | skornei/restserver | 65d535236e3d2b888636c0c655d225af62c84654 | [
"Apache-2.0"
] | null | null | null | src/main/java/ru/skornei/restserver/annotations/RestServer.java | skornei/restserver | 65d535236e3d2b888636c0c655d225af62c84654 | [
"Apache-2.0"
] | 10 | 2020-07-21T12:21:03.000Z | 2022-03-30T13:34:54.000Z | 19.972222 | 49 | 0.653686 | 11,349 | package ru.skornei.restserver.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RestServer {
/**
* Порт сервера
* @return порт
*/
int port();
/**
* Конвертер объектов
* @return класс конвертера
*/
Class<?> converter() default void.class;
/**
* Аунтификатор
* @return класс аунтификатор
*/
Class<?> authentication() default void.class;
/**
* Контроллеры сервера
* @return список классов
*/
Class<?>[] controllers();
}
|
3e1abb61dc4bac12c5066c64694ecda1f92f5014 | 300 | java | Java | src/main/java/joni/dep/Qualifier.java | victorblaga/joni-dep | 3b70684e838380a14203b0a77acf2ad94b347f4a | [
"Apache-2.0"
] | null | null | null | src/main/java/joni/dep/Qualifier.java | victorblaga/joni-dep | 3b70684e838380a14203b0a77acf2ad94b347f4a | [
"Apache-2.0"
] | 1 | 2018-03-01T22:07:19.000Z | 2018-03-01T22:07:19.000Z | src/main/java/joni/dep/Qualifier.java | victorblaga/joni-dep | 3b70684e838380a14203b0a77acf2ad94b347f4a | [
"Apache-2.0"
] | null | null | null | 23.076923 | 44 | 0.8 | 11,350 | package joni.dep;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //
public @interface Qualifier {
String value();
}
|
3e1abbc4f808dcad22d0759e086fa4b569a46b91 | 1,082 | java | Java | subprojects/diagnostics/src/main/java/org/gradle/api/tasks/diagnostics/DependencyReportTask.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 2 | 2020-04-01T18:40:33.000Z | 2021-04-23T12:06:15.000Z | subprojects/diagnostics/src/main/java/org/gradle/api/tasks/diagnostics/DependencyReportTask.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 12 | 2020-07-11T15:43:32.000Z | 2020-10-13T23:39:44.000Z | subprojects/diagnostics/src/main/java/org/gradle/api/tasks/diagnostics/DependencyReportTask.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 4 | 2016-12-30T06:18:52.000Z | 2021-01-13T10:39:29.000Z | 34.903226 | 88 | 0.750462 | 11,351 | /*
* Copyright 2008 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.gradle.api.tasks.diagnostics;
import org.gradle.api.artifacts.ConfigurationContainer;
/**
* Displays the dependency tree for a project. An instance of this type is used when you
* execute the {@code dependencies} task from the command-line.
*/
public class DependencyReportTask extends AbstractDependencyReportTask {
@Override
public ConfigurationContainer getTaskConfigurations() {
return getProject().getConfigurations();
}
}
|
3e1abbd8858e4712da2ed3523b93084bf58e400a | 1,963 | java | Java | dag/runtime/extension/trace/src/main/java/com/asakusafw/dag/extension/trace/TracingObjectCursor.java | asakusafw/asakusafw-compiler | f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e | [
"Apache-2.0"
] | 2 | 2015-07-08T17:32:50.000Z | 2020-06-14T02:26:14.000Z | dag/runtime/extension/trace/src/main/java/com/asakusafw/dag/extension/trace/TracingObjectCursor.java | asakusafw/asakusafw-compiler | f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e | [
"Apache-2.0"
] | 212 | 2015-06-30T09:16:35.000Z | 2022-02-09T22:31:09.000Z | dag/runtime/extension/trace/src/main/java/com/asakusafw/dag/extension/trace/TracingObjectCursor.java | asakusafw/asakusafw-compiler | f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e | [
"Apache-2.0"
] | 7 | 2015-06-25T02:37:40.000Z | 2020-06-18T03:27:40.000Z | 29.298507 | 111 | 0.6811 | 11,352 | /**
* Copyright 2011-2021 Asakusa Framework 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 com.asakusafw.dag.extension.trace;
import java.io.IOException;
import java.util.function.Consumer;
import com.asakusafw.dag.api.common.ObjectCursor;
import com.asakusafw.lang.utils.common.Arguments;
/**
* An implementation of {@link ObjectCursor} which can tracing all objects through {@link #getObject()} method.
* @since 0.4.0
*/
public class TracingObjectCursor implements ObjectCursor {
private final ObjectCursor delegate;
private final Consumer<Object> sink;
private boolean first = true;
/**
* Creates a new instance.
* @param delegate the delegate object
* @param sink the trace sink
*/
public TracingObjectCursor(ObjectCursor delegate, Consumer<Object> sink) {
Arguments.requireNonNull(delegate);
Arguments.requireNonNull(sink);
this.delegate = delegate;
this.sink = sink;
}
@Override
public boolean nextObject() throws IOException, InterruptedException {
if (delegate.nextObject()) {
first = true;
return true;
}
return false;
}
@Override
public Object getObject() throws IOException, InterruptedException {
Object result = delegate.getObject();
if (first) {
sink.accept(result);
first = false;
}
return result;
}
}
|
3e1abcd71cb561ed37b7de6b52f889cdbad5b031 | 664 | java | Java | src/main/java/com/huobi/api/client/domain/event/AccountTick.java | chengjk/huobi-java-api | ba4337e377d1bdea9014d3924a21e03b9db98b97 | [
"MIT"
] | 8 | 2018-09-12T04:37:43.000Z | 2020-09-19T07:31:33.000Z | src/main/java/com/huobi/api/client/domain/event/AccountTick.java | chengjk/huobi-java-api | ba4337e377d1bdea9014d3924a21e03b9db98b97 | [
"MIT"
] | 2 | 2020-04-13T09:57:42.000Z | 2021-08-14T03:30:23.000Z | src/main/java/com/huobi/api/client/domain/event/AccountTick.java | chengjk/huobi-java-api | ba4337e377d1bdea9014d3924a21e03b9db98b97 | [
"MIT"
] | 4 | 2018-08-01T02:18:35.000Z | 2021-02-01T13:30:13.000Z | 22.133333 | 42 | 0.611446 | 11,353 | package com.huobi.api.client.domain.event;
import com.huobi.api.client.domain.Asset;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* created by jacky. 2018/9/25 5:19 PM
*/
@Getter
@Setter
public class AccountTick {
/**
* <p>订单创建(order.place)</p>
* <p>订单成交(order.match)</p>
* <p>订单成交退款(order.refund)</p>
* <p>订单撤销(order.cancel)</p>
* <p>点卡抵扣交易手续费(order.fee-refund)</p>
* <p>杠杆账户划转(margin.transfer)</p>
* <p>借贷本金(margin.loan)</p>
* <p>借贷计息(margin.interest)</p>
* <p>归还借贷本金利息(margin.repay)</p>
* <p>其他资产变化(other)</p>
*/
private String event;
private List<Asset> list;
}
|
3e1abd80b0a962ec48312d52d3d8e41cebb6ccfc | 2,984 | java | Java | app/src/main/java/com/valtech/contactsync/Authenticator.java | valtech/valtech-contactsync-android | 33b3baf1a2ecae2d2a840ccf4acde4b7fd1175a7 | [
"MIT"
] | 6 | 2015-01-16T14:44:06.000Z | 2020-02-07T06:16:25.000Z | app/src/main/java/com/valtech/contactsync/Authenticator.java | valtech/valtech-contactsync-android | 33b3baf1a2ecae2d2a840ccf4acde4b7fd1175a7 | [
"MIT"
] | 1 | 2016-10-22T13:25:07.000Z | 2016-10-22T13:35:25.000Z | app/src/main/java/com/valtech/contactsync/Authenticator.java | valtech/valtech-contactsync-android | 33b3baf1a2ecae2d2a840ccf4acde4b7fd1175a7 | [
"MIT"
] | 4 | 2017-07-05T02:00:41.000Z | 2020-02-07T06:16:29.000Z | 34.697674 | 181 | 0.765751 | 11,354 | package com.valtech.contactsync;
import android.accounts.*;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.valtech.contactsync.api.ApiClient;
import com.valtech.contactsync.api.InvalidGrantException;
public class Authenticator extends AbstractAccountAuthenticator {
private static final String TAG = Authenticator.class.getSimpleName();
private final Context context;
private final ApiClient apiClient;
public Authenticator(Context context) {
super(context);
this.context = context;
this.apiClient = new ApiClient(context);
}
@Override
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
return null;
}
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
return startSignIn(response);
}
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
Log.i(TAG, "Fetching new access token.");
Bundle bundle = new Bundle();
try {
String refreshToken = AccountManager.get(context).getPassword(account);
String accessToken = apiClient.getAccessToken(refreshToken);
Log.i(TAG, "Got new access token.");
bundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, context.getString(R.string.account_type));
bundle.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
return bundle;
} catch (InvalidGrantException e) {
Log.i(TAG, "Refresh token invalid.");
return startSignIn(response);
} catch (Exception e) {
Log.e(TAG, "Unknown error when fetching access token.", e);
bundle.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_BAD_AUTHENTICATION);
return bundle;
}
}
@Override
public String getAuthTokenLabel(String authTokenType) {
return null;
}
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException {
return null;
}
private Bundle startSignIn(AccountAuthenticatorResponse response) {
Bundle result = new Bundle();
Intent i = new Intent(context, SignInActivity.class);
i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
result.putParcelable(AccountManager.KEY_INTENT, i);
return result;
}
}
|
3e1abf0ce7057164d9ca0623394d2662469117f7 | 2,301 | java | Java | src/minecraft/tech/lowspeccorgi/Quark/Elements/impl/CardElement.java | Illuminate-dev/creativeclient | 8061012ce7bd170af507745adc31eb17340a8ebe | [
"MIT"
] | 1 | 2022-03-01T20:26:09.000Z | 2022-03-01T20:26:09.000Z | src/minecraft/tech/lowspeccorgi/Quark/Elements/impl/CardElement.java | Illuminate-dev/creativeclient | 8061012ce7bd170af507745adc31eb17340a8ebe | [
"MIT"
] | 1 | 2022-02-12T21:00:01.000Z | 2022-02-12T21:00:01.000Z | src/minecraft/tech/lowspeccorgi/Quark/Elements/impl/CardElement.java | Illuminate-dev/creativeclient | 8061012ce7bd170af507745adc31eb17340a8ebe | [
"MIT"
] | null | null | null | 31.958333 | 161 | 0.619296 | 11,355 | package tech.lowspeccorgi.Quark.Elements.impl;
import tech.lowspeccorgi.Quark.Elements.Element;
import tech.lowspeccorgi.Quark.Style.Anchor;
import tech.lowspeccorgi.Quark.Style.RectStyle;
import tech.lowspeccorgi.Quark.Style.TextStyle;
public class CardElement extends Element
{
private TextStyle title;
private TextStyle description;
private RectStyle rectStyle;
private int padding;
private Anchor anchor;
public CardElement(String id, int x, int y, int width, int height, TextStyle title, TextStyle description, RectStyle rectStyle, int padding) {
super(id, x, y, width, height);
this.rectStyle = rectStyle;
this.title = title;
this.description = description;
this.padding = padding;
this.anchor = Anchor.Left;
}
public CardElement(String id, int x, int y, int width, int height, TextStyle title, TextStyle description, RectStyle rectStyle, int padding, Anchor anchor) {
super(id, x, y, width, height);
this.rectStyle = rectStyle;
this.title = title;
this.description = description;
this.padding = padding;
this.anchor = anchor;
}
@Override
public void onRender(int mouseX, int mouseY, float partialTicks)
{
this.rectStyle.render(this.x, this.y, this.width, this.height);
switch (this.anchor)
{
case Center:
this.title.render(this.x + this.padding + this.width / 2, this.y + this.padding);
this.description.render(this.x + this.padding + this.width / 2, this.y + this.height / 2);
break;
case Left:
this.title.render(this.x + this.padding, this.y + this.padding);
this.description.render(this.x + this.padding, this.y + this.height / 2);
break;
default:
this.title.render(this.x, this.y);
this.description.render(this.x, this.y + this.height / 2);
break;
}
}
public RectStyle getRectStyle() {
return rectStyle;
}
public int getPadding() {
return padding;
}
public TextStyle getDescription() {
return description;
}
public TextStyle getTitle() {
return title;
}
}
|
3e1ac2ef449fb6feaae155498e471a097dacc8a1 | 8,526 | java | Java | src/edu/isi/pegasus/planner/selector/site/RoundRobin.java | hariharan-devarajan/pegasus | d0641541f2eccc69dd6cc5a09b0b51303686d3ac | [
"Apache-2.0"
] | 127 | 2015-01-28T19:19:13.000Z | 2022-03-31T05:57:40.000Z | src/edu/isi/pegasus/planner/selector/site/RoundRobin.java | hariharan-devarajan/pegasus | d0641541f2eccc69dd6cc5a09b0b51303686d3ac | [
"Apache-2.0"
] | 14 | 2015-04-15T17:44:20.000Z | 2022-02-22T22:48:49.000Z | src/edu/isi/pegasus/planner/selector/site/RoundRobin.java | hariharan-devarajan/pegasus | d0641541f2eccc69dd6cc5a09b0b51303686d3ac | [
"Apache-2.0"
] | 70 | 2015-01-22T15:20:32.000Z | 2022-02-21T22:50:23.000Z | 33.699605 | 100 | 0.550551 | 11,356 | /**
* Copyright 2007-2008 University Of Southern California
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.isi.pegasus.planner.selector.site;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.classes.Job;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* This ends up scheduling the jobs in a round robin manner. In order to avoid starvation, the jobs
* are scheduled in a round robin manner per level, and the queue is initialised for each level.
*
* @author Karan Vahi
* @version $Revision$
*/
public class RoundRobin extends AbstractPerJob {
/**
* The current level in the abstract workflow. It is level that is designated by Chimera while
* constructing the graph bottom up.
*/
private int mCurrentLevel;
/**
* The list of pools that have been given by the user at run time or has been authenticated
* against. At present these are the same as the list of pools that is passed for site selection
* at each function.
*/
private java.util.LinkedList mExecPools;
/** The default constructor. Not to be used. */
public RoundRobin() {
mCurrentLevel = -1;
}
/**
* Returns a brief description of the site selection techinque implemented by this class.
*
* @return String
*/
public String description() {
String st = "Round Robin Scheduling per level of the workflow";
return st;
}
/**
* Maps a job in the workflow to an execution site.
*
* @param job the job to be mapped.
* @param sites the list of <code>String</code> objects representing the execution sites that
* can be used.
*/
public void mapJob(Job job, List sites) {
NameValue current;
NameValue next;
if (mExecPools == null) {
initialiseList(sites);
}
if (job.level != mCurrentLevel) {
// reinitialize stuff
System.out.println("Job " + job.getID() + " Change in level to " + job.level);
System.out.println("execution sites " + listToString(mExecPools));
mCurrentLevel = job.level;
for (ListIterator it = mExecPools.listIterator(); it.hasNext(); ) {
((NameValue) it.next()).setValue(0);
}
}
// go around the list and schedule it to the first one where it can
String mapping = null;
for (ListIterator it = mExecPools.listIterator(); it.hasNext(); ) {
// System.out.println( "List is " + listToString( mExecPools ) );
current = (NameValue) it.next();
// check if job can run on pool
if (mTCMapper.isSiteValid(
job.namespace, job.logicalName, job.version, current.getName())) {
mapping = current.getName();
// update the the number of times used and place it at the
// correct position in the list
current.increment();
// the current element stays at it's place if it is the only one
// in the list or it's value is less than the next one.
if (it.hasNext()) {
next = (NameValue) it.next();
if (current.getValue() <= next.getValue()) {
it.previous();
continue;
} else {
// current's value is now greater than the next
current = (NameValue) it.previous();
current = (NameValue) it.previous();
}
}
it.remove();
// System.out.println( "List after removal of " + current + " is " + listToString(
// mExecPools ) );
// now go thru the list and insert in the correct position
while (it.hasNext()) {
next = (NameValue) it.next();
if (current.getValue() <= next.getValue()) {
// current has to be inserted before next
next = (NameValue) it.previous();
break;
}
}
// current goes to the current position or the end of the list
it.add(current);
break;
} else {
mLogger.log(
"Job " + job.getName() + " cannot be mapped to site " + current,
LogManager.DEBUG_MESSAGE_LEVEL);
}
}
// means no pool has been found to which the job could be mapped to.
mLogger.log(
"[RoundRobin Site Selector] Mapped job " + job.getID() + " to site " + mapping,
LogManager.DEBUG_MESSAGE_LEVEL);
job.setSiteHandle(mapping);
}
/**
* It initialises the internal list. A node in the list corresponds to a pool that can be used,
* and has the value associated with it which is the number of jobs in the current level have
* been scheduled to it.
*
* @param pools List
*/
private void initialiseList(List pools) {
if (mExecPools == null) {
mExecPools = new java.util.LinkedList();
Iterator it = pools.iterator();
while (it.hasNext()) {
mExecPools.add(new NameValue((String) it.next(), 0));
}
}
}
private String listToString(List elements) {
StringBuilder sb = new StringBuilder();
sb.append("size -> ").append(elements.size()).append(" ");
for (Object element : elements) {
sb.append(element).append(",");
}
return sb.toString();
}
/**
* A inner name value class that associates a string with an int value. This is used to populate
* the round robin list that is used by this scheduler.
*/
class NameValue {
/** Stores the name of the pair (the left handside of the mapping). */
private String name;
/** Stores the corresponding value to the name in the pair. */
private int value;
/** The default constructor which initialises the class member variables. */
public NameValue() {
name = new String();
value = -1;
}
/**
* Initialises the class member variables to the values passed in the arguments.
*
* @param name corresponds to the name in the NameValue pair
* @param value corresponds to the value for the name in the NameValue pair
*/
public NameValue(String name, int value) {
this.name = name;
this.value = value;
}
/**
* The set method to set the value.
*
* @param value int
*/
public void setValue(int value) {
this.value = value;
}
/**
* Returns the value associated with this pair.
*
* @return int
*/
public int getValue() {
return this.value;
}
/**
* Returns the key of this pair, i.e the left hand side of the mapping.
*
* @return String
*/
public String getName() {
return this.name;
}
/** Increments the int value by one. */
public void increment() {
value += 1;
}
/**
* Returns a copy of this object.
*
* @return Object
*/
public Object clone() {
NameValue nv = new NameValue(this.name, this.value);
return nv;
}
/**
* Writes out the contents of the class to a String in form suitable for displaying.
*
* @return String
*/
public String toString() {
String str = name + "-->" + value;
return str;
}
}
}
|
3e1ac31bbd481c3c1e9d697c2b4abaad71e636f4 | 773 | java | Java | src/main/java/org/iecas/pda/io/db/Co2DbReader.java | gaufung/PDA | e2e3524a2ec48ff18b04a40afa110907a5230bde | [
"MIT"
] | 1 | 2018-10-06T23:50:53.000Z | 2018-10-06T23:50:53.000Z | PDA-Java/src/main/java/org/iecas/pda/io/db/Co2DbReader.java | wsgan001/CodeBase | 0292b06cfe002b3ad0299e43bb51192816a02c74 | [
"MIT"
] | null | null | null | PDA-Java/src/main/java/org/iecas/pda/io/db/Co2DbReader.java | wsgan001/CodeBase | 0292b06cfe002b3ad0299e43bb51192816a02c74 | [
"MIT"
] | 1 | 2018-10-06T23:50:50.000Z | 2018-10-06T23:50:50.000Z | 28.62963 | 109 | 0.690815 | 11,357 | package org.iecas.pda.io.db;
import org.hibernate.Session;
import org.iecas.pda.io.Co2Reader;
import org.iecas.pda.model.Co2;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by gaufung on 06/07/2017.
*/
public class Co2DbReader implements Co2Reader {
@Override
public List<Co2> read(String year) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Co2Db> co2s = session.createQuery("FROM Co2Db WHERE year=:year ORDER BY id ASC")
.setParameter("year",year).list();
session.getTransaction().commit();
return co2s.stream().map(db->new Co2(db.getProvince(),db.components())).collect(Collectors.toList());
}
}
|
3e1ac397f24b481f8463d2e7c0764b9cc023c7aa | 737 | java | Java | qr-code-login/src/main/java/com/study/boot/qrlogin/config/CorsConfigure.java | sunxingyuqaq/sa-token-study | 7f2a58c5d046be7aaa9024980ddbdb6d48dcaeff | [
"Apache-2.0"
] | null | null | null | qr-code-login/src/main/java/com/study/boot/qrlogin/config/CorsConfigure.java | sunxingyuqaq/sa-token-study | 7f2a58c5d046be7aaa9024980ddbdb6d48dcaeff | [
"Apache-2.0"
] | null | null | null | qr-code-login/src/main/java/com/study/boot/qrlogin/config/CorsConfigure.java | sunxingyuqaq/sa-token-study | 7f2a58c5d046be7aaa9024980ddbdb6d48dcaeff | [
"Apache-2.0"
] | null | null | null | 28.346154 | 82 | 0.663501 | 11,358 | package com.study.boot.qrlogin.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* describe:
*
* @author admin
* @date 2021/08/10 09:02
*/
@Configuration
public class CorsConfigure implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
|
3e1ac41c015cadf1d71673b3fe78dfe5540c099a | 11,909 | java | Java | sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/HostNameBinding.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/HostNameBinding.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 12 | 2019-07-17T16:18:54.000Z | 2019-07-17T21:30:02.000Z | sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/HostNameBinding.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 33.546479 | 383 | 0.606768 | 11,359 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.v2019_08_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.appservice.v2019_08_01.implementation.HostNameBindingInner;
import com.microsoft.azure.arm.model.Indexable;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.appservice.v2019_08_01.implementation.AppServiceManager;
/**
* Type representing HostNameBinding.
*/
public interface HostNameBinding extends HasInner<HostNameBindingInner>, Indexable, Refreshable<HostNameBinding>, Updatable<HostNameBinding.Update>, HasManager<AppServiceManager> {
/**
* @return the azureResourceName value.
*/
String azureResourceName();
/**
* @return the azureResourceType value.
*/
AzureResourceType azureResourceType();
/**
* @return the customHostNameDnsRecordType value.
*/
CustomHostNameDnsRecordType customHostNameDnsRecordType();
/**
* @return the domainId value.
*/
String domainId();
/**
* @return the hostNameType value.
*/
HostNameType hostNameType();
/**
* @return the id value.
*/
String id();
/**
* @return the kind value.
*/
String kind();
/**
* @return the name value.
*/
String name();
/**
* @return the siteName value.
*/
String siteName();
/**
* @return the sslState value.
*/
SslState sslState();
/**
* @return the thumbprint value.
*/
String thumbprint();
/**
* @return the type value.
*/
String type();
/**
* @return the virtualIP value.
*/
String virtualIP();
/**
* The entirety of the HostNameBinding definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithSite, DefinitionStages.WithCreate {
}
/**
* Grouping of HostNameBinding definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a HostNameBinding definition.
*/
interface Blank extends WithSite {
}
/**
* The stage of the hostnamebinding definition allowing to specify Site.
*/
interface WithSite {
/**
* Specifies resourceGroupName, name.
* @param resourceGroupName Name of the resource group to which the resource belongs
* @param name Name of the app
* @return the next definition stage
*/
WithCreate withExistingSite(String resourceGroupName, String name);
}
/**
* The stage of the hostnamebinding definition allowing to specify AzureResourceName.
*/
interface WithAzureResourceName {
/**
* Specifies azureResourceName.
* @param azureResourceName Azure resource name
* @return the next definition stage
*/
WithCreate withAzureResourceName(String azureResourceName);
}
/**
* The stage of the hostnamebinding definition allowing to specify AzureResourceType.
*/
interface WithAzureResourceType {
/**
* Specifies azureResourceType.
* @param azureResourceType Azure resource type. Possible values include: 'Website', 'TrafficManager'
* @return the next definition stage
*/
WithCreate withAzureResourceType(AzureResourceType azureResourceType);
}
/**
* The stage of the hostnamebinding definition allowing to specify CustomHostNameDnsRecordType.
*/
interface WithCustomHostNameDnsRecordType {
/**
* Specifies customHostNameDnsRecordType.
* @param customHostNameDnsRecordType Custom DNS record type. Possible values include: 'CName', 'A'
* @return the next definition stage
*/
WithCreate withCustomHostNameDnsRecordType(CustomHostNameDnsRecordType customHostNameDnsRecordType);
}
/**
* The stage of the hostnamebinding definition allowing to specify DomainId.
*/
interface WithDomainId {
/**
* Specifies domainId.
* @param domainId Fully qualified ARM domain resource URI
* @return the next definition stage
*/
WithCreate withDomainId(String domainId);
}
/**
* The stage of the hostnamebinding definition allowing to specify HostNameType.
*/
interface WithHostNameType {
/**
* Specifies hostNameType.
* @param hostNameType Hostname type. Possible values include: 'Verified', 'Managed'
* @return the next definition stage
*/
WithCreate withHostNameType(HostNameType hostNameType);
}
/**
* The stage of the hostnamebinding definition allowing to specify Kind.
*/
interface WithKind {
/**
* Specifies kind.
* @param kind Kind of resource
* @return the next definition stage
*/
WithCreate withKind(String kind);
}
/**
* The stage of the hostnamebinding definition allowing to specify SiteName.
*/
interface WithSiteName {
/**
* Specifies siteName.
* @param siteName App Service app name
* @return the next definition stage
*/
WithCreate withSiteName(String siteName);
}
/**
* The stage of the hostnamebinding definition allowing to specify SslState.
*/
interface WithSslState {
/**
* Specifies sslState.
* @param sslState SSL type. Possible values include: 'Disabled', 'SniEnabled', 'IpBasedEnabled'
* @return the next definition stage
*/
WithCreate withSslState(SslState sslState);
}
/**
* The stage of the hostnamebinding definition allowing to specify Thumbprint.
*/
interface WithThumbprint {
/**
* Specifies thumbprint.
* @param thumbprint SSL certificate thumbprint
* @return the next definition stage
*/
WithCreate withThumbprint(String thumbprint);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<HostNameBinding>, DefinitionStages.WithAzureResourceName, DefinitionStages.WithAzureResourceType, DefinitionStages.WithCustomHostNameDnsRecordType, DefinitionStages.WithDomainId, DefinitionStages.WithHostNameType, DefinitionStages.WithKind, DefinitionStages.WithSiteName, DefinitionStages.WithSslState, DefinitionStages.WithThumbprint {
}
}
/**
* The template for a HostNameBinding update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<HostNameBinding>, UpdateStages.WithAzureResourceName, UpdateStages.WithAzureResourceType, UpdateStages.WithCustomHostNameDnsRecordType, UpdateStages.WithDomainId, UpdateStages.WithHostNameType, UpdateStages.WithKind, UpdateStages.WithSiteName, UpdateStages.WithSslState, UpdateStages.WithThumbprint {
}
/**
* Grouping of HostNameBinding update stages.
*/
interface UpdateStages {
/**
* The stage of the hostnamebinding update allowing to specify AzureResourceName.
*/
interface WithAzureResourceName {
/**
* Specifies azureResourceName.
* @param azureResourceName Azure resource name
* @return the next update stage
*/
Update withAzureResourceName(String azureResourceName);
}
/**
* The stage of the hostnamebinding update allowing to specify AzureResourceType.
*/
interface WithAzureResourceType {
/**
* Specifies azureResourceType.
* @param azureResourceType Azure resource type. Possible values include: 'Website', 'TrafficManager'
* @return the next update stage
*/
Update withAzureResourceType(AzureResourceType azureResourceType);
}
/**
* The stage of the hostnamebinding update allowing to specify CustomHostNameDnsRecordType.
*/
interface WithCustomHostNameDnsRecordType {
/**
* Specifies customHostNameDnsRecordType.
* @param customHostNameDnsRecordType Custom DNS record type. Possible values include: 'CName', 'A'
* @return the next update stage
*/
Update withCustomHostNameDnsRecordType(CustomHostNameDnsRecordType customHostNameDnsRecordType);
}
/**
* The stage of the hostnamebinding update allowing to specify DomainId.
*/
interface WithDomainId {
/**
* Specifies domainId.
* @param domainId Fully qualified ARM domain resource URI
* @return the next update stage
*/
Update withDomainId(String domainId);
}
/**
* The stage of the hostnamebinding update allowing to specify HostNameType.
*/
interface WithHostNameType {
/**
* Specifies hostNameType.
* @param hostNameType Hostname type. Possible values include: 'Verified', 'Managed'
* @return the next update stage
*/
Update withHostNameType(HostNameType hostNameType);
}
/**
* The stage of the hostnamebinding update allowing to specify Kind.
*/
interface WithKind {
/**
* Specifies kind.
* @param kind Kind of resource
* @return the next update stage
*/
Update withKind(String kind);
}
/**
* The stage of the hostnamebinding update allowing to specify SiteName.
*/
interface WithSiteName {
/**
* Specifies siteName.
* @param siteName App Service app name
* @return the next update stage
*/
Update withSiteName(String siteName);
}
/**
* The stage of the hostnamebinding update allowing to specify SslState.
*/
interface WithSslState {
/**
* Specifies sslState.
* @param sslState SSL type. Possible values include: 'Disabled', 'SniEnabled', 'IpBasedEnabled'
* @return the next update stage
*/
Update withSslState(SslState sslState);
}
/**
* The stage of the hostnamebinding update allowing to specify Thumbprint.
*/
interface WithThumbprint {
/**
* Specifies thumbprint.
* @param thumbprint SSL certificate thumbprint
* @return the next update stage
*/
Update withThumbprint(String thumbprint);
}
}
}
|
3e1ac5564aa1510af71e6f7d0ca1db3b5cc2f33f | 7,153 | java | Java | collect_app/src/test/java/org/odk/collect/android/formmanagement/ServerFormsDetailsFetcherTest.java | VijayMain/collect | 6469437e39e32de31b1e2413be946c39fbae1ea9 | [
"Apache-2.0"
] | null | null | null | collect_app/src/test/java/org/odk/collect/android/formmanagement/ServerFormsDetailsFetcherTest.java | VijayMain/collect | 6469437e39e32de31b1e2413be946c39fbae1ea9 | [
"Apache-2.0"
] | null | null | null | collect_app/src/test/java/org/odk/collect/android/formmanagement/ServerFormsDetailsFetcherTest.java | VijayMain/collect | 6469437e39e32de31b1e2413be946c39fbae1ea9 | [
"Apache-2.0"
] | 1 | 2021-08-23T02:57:20.000Z | 2021-08-23T02:57:20.000Z | 37.450262 | 144 | 0.663358 | 11,360 | package org.odk.collect.android.formmanagement;
import org.junit.Before;
import org.junit.Test;
import org.odk.collect.android.forms.Form;
import org.odk.collect.android.forms.FormRepository;
import org.odk.collect.android.forms.MediaFileRepository;
import org.odk.collect.android.openrosa.api.FormListApi;
import org.odk.collect.android.openrosa.api.FormListItem;
import org.odk.collect.android.openrosa.api.ManifestFile;
import org.odk.collect.android.openrosa.api.MediaFile;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.odk.collect.android.utilities.FileUtils.getMd5Hash;
@SuppressWarnings("PMD.DoubleBraceInitialization")
public class ServerFormsDetailsFetcherTest {
private final List<FormListItem> formList = asList(
new FormListItem("http://example.com/form-1", "form-1", "server", "md5:form-1-hash", "Form 1", null),
new FormListItem("http://example.com/form-2", "form-2", "server", "md5:form-2-hash", "Form 2", "http://example.com/form-2-manifest")
);
private ServerFormsDetailsFetcher fetcher;
private FormRepository formRepository;
private MediaFileRepository mediaFileRepository;
@Before
public void setup() throws Exception {
formRepository = new InMemFormRepository();
mediaFileRepository = mock(MediaFileRepository.class);
FormListApi formListAPI = mock(FormListApi.class);
when(formListAPI.fetchFormList()).thenReturn(formList);
when(formListAPI.fetchManifest(formList.get(1).getManifestURL())).thenReturn(new ManifestFile("manifest-2-hash", asList(
new MediaFile("blah.txt", "md5:" + getMd5Hash(new ByteArrayInputStream("blah".getBytes())), "http://example.com/media-file")))
);
DiskFormsSynchronizer diskFormsSynchronizer = mock(DiskFormsSynchronizer.class);
fetcher = new ServerFormsDetailsFetcher(formRepository, mediaFileRepository, formListAPI, diskFormsSynchronizer);
}
@Test
public void whenNoFormsExist_isNew() throws Exception {
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(0).isNotOnDevice(), is(true));
assertThat(serverFormDetails.get(1).isNotOnDevice(), is(true));
}
@Test
public void whenAFormExists_andListContainsUpdatedVersion_isUpdated() throws Exception {
formRepository.save(new Form.Builder()
.id(2L)
.jrFormId("form-2")
.md5Hash("form-2-hash-old")
.build());
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(1).isUpdated(), is(true));
}
@Test
public void whenAFormExists_andHasNewMediaFileOnServer_isUpdated() throws Exception {
formRepository.save(new Form.Builder()
.id(2L)
.jrFormId("form-2")
.jrVersion("server")
.md5Hash("form-2-hash")
.build());
when(mediaFileRepository.getAll("form-2", "server")).thenReturn(emptyList());
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(1).isUpdated(), is(true));
}
@Test
public void whenAFormExists_andHasUpdatedMediaFileOnServer_isUpdated() throws Exception {
formRepository.save(new Form.Builder()
.id(2L)
.jrFormId("form-2")
.jrVersion("server")
.md5Hash("form-2-hash")
.build());
File oldMediaFile = File.createTempFile("blah", ".csv");
writeToFile(oldMediaFile, "blah before");
when(mediaFileRepository.getAll("form-2", "server")).thenReturn(asList(oldMediaFile));
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(1).isUpdated(), is(true));
}
@Test
public void whenAFormExists_andIsNotUpdatedOnServer_andDoesNotHaveAManifest_isNotNewOrUpdated() throws Exception {
formRepository.save(new Form.Builder()
.id(1L)
.jrFormId("form-1")
.jrVersion("server")
.md5Hash("form-1-hash")
.build());
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(0).isUpdated(), is(false));
assertThat(serverFormDetails.get(0).isNotOnDevice(), is(false));
}
@Test
public void whenFormExists_isNotNewOrUpdated() throws Exception {
formRepository.save(new Form.Builder()
.id(2L)
.jrFormId("form-2")
.jrVersion("server")
.md5Hash("form-2-hash")
.build());
File mediaFile = File.createTempFile("blah", ".csv");
writeToFile(mediaFile, "blah");
when(mediaFileRepository.getAll("form-2", "server")).thenReturn(asList(mediaFile));
List<ServerFormDetails> serverFormDetails = fetcher.fetchFormDetails();
assertThat(serverFormDetails.get(1).isUpdated(), is(false));
assertThat(serverFormDetails.get(1).isNotOnDevice(), is(false));
}
private void writeToFile(File mediaFile, String blah) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(mediaFile));
bw.write(blah);
bw.close();
}
private static class InMemFormRepository implements FormRepository {
private final List<Form> forms = new ArrayList<>();
@Override
public void save(Form form) {
forms.add(form);
}
@Override
public boolean contains(String jrFormID) {
return forms.stream().anyMatch(form -> form.getJrFormId().equals(jrFormID));
}
@Override
public List<Form> getAll() {
return new ArrayList<>(forms); // Avoid anything mutating the list externally
}
@Nullable
@Override
public Form getByMd5Hash(String hash) {
return forms.stream().filter(form -> form.getMD5Hash().equals(hash)).findFirst().orElse(null);
}
@Override
public void delete(Long id) {
forms.removeIf(form -> form.getId().equals(id));
}
}
private static class RecordingFormDownloader implements FormDownloader {
private final List<String> formsDownloaded = new ArrayList<>();
@Override
public void downloadForm(ServerFormDetails form) {
formsDownloaded.add(form.getFormId());
}
public List<String> getDownloadedForms() {
return formsDownloaded;
}
}
} |
3e1ac6e7bf25586202f0cebbb8cc007f1aae2a5a | 2,094 | java | Java | app/src/main/java/com/rance/chatui/ui/activity/SocreActivity.java | MichaelODs/chuya | d9a88bb57dac60fbc428609f1d356c13090c56b4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rance/chatui/ui/activity/SocreActivity.java | MichaelODs/chuya | d9a88bb57dac60fbc428609f1d356c13090c56b4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rance/chatui/ui/activity/SocreActivity.java | MichaelODs/chuya | d9a88bb57dac60fbc428609f1d356c13090c56b4 | [
"Apache-2.0"
] | null | null | null | 24.635294 | 93 | 0.589303 | 11,361 | package com.rance.chatui.ui.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.rance.chatui.R;
public class SocreActivity extends AppCompatActivity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socre);
btn1 = (Button) findViewById(R.id.button1_score);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SocreActivity.this, AnsActivity.class);
startActivity(intent);
finish();
}
});
btn2 = (Button) findViewById(R.id.button2_score);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SocreActivity.this, OldActivity.class);
startActivity(intent);
finish();
}
});
btn3 = (Button) findViewById(R.id.button3_score);
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast toast = Toast.makeText(SocreActivity.this, "收藏成功", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
finish();
}
});
btn4 = (Button) findViewById(R.id.button4_score);
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SocreActivity.this, MenuActivity.class);
startActivity(intent);
finish();
}
});
}
}
|
3e1ac8fbba85c5f6aba5d5deac417bc7a88988e2 | 4,443 | java | Java | code/src/test/java/sources/TestFindEnrolledStudent.java | CurrenWong/CourseDesign | 1974f202fd57069ca81acdbb694d2fef117cd0b5 | [
"MIT"
] | 2 | 2020-03-16T10:01:17.000Z | 2020-03-16T15:01:05.000Z | code/src/test/java/sources/TestFindEnrolledStudent.java | CurrenWong/CourseDesign | 1974f202fd57069ca81acdbb694d2fef117cd0b5 | [
"MIT"
] | 5 | 2020-05-19T19:21:09.000Z | 2020-08-13T10:13:35.000Z | code/src/test/java/sources/TestFindEnrolledStudent.java | CurrenWong/CourseDesign | 1974f202fd57069ca81acdbb694d2fef117cd0b5 | [
"MIT"
] | null | null | null | 32.195652 | 92 | 0.623453 | 11,362 | package sources;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.getCurrentArgument;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.courseDesign.servlet.findEnrolledStudent;
import org.easymock.EasyMockSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
//这是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner这个类提供Spring测试上下文。
public class TestFindEnrolledStudent extends EasyMockSupport {
private findEnrolledStudent servlet;
private HttpServletRequest request;
private HttpServletResponse response;
StringWriter out;
PrintWriter writer;
// 测试方法执行前
@Before
public void setUp() {
// 创建Servlet
servlet = new findEnrolledStudent();
// 创建字符输出流
out = new StringWriter();
writer = new PrintWriter(out);
// 创建mock对象
request = createMock(HttpServletRequest.class);
response = createMock(HttpServletResponse.class);
// 初始化
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
/* 星号表示所有的异域请求都可以接受, */
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
}
// 测试方法执行后
@After
public void tearDown() {
// 验证所有mock都被使用
verifyAll();
}
@Test
public void testValidInput() {
// 设置参数
expect(request.getParameter("universityId")).andReturn("1");
// 设置返回参数
try {
expect(response.getWriter()).andReturn(writer);
} catch (IOException e) {
e.printStackTrace();
}
// 切换到replay模式
replayAll();
// 发送post请求
try {
servlet.doPost(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
// 输出结果
System.out.println("TestFindEnrolledStudent Input: " + "{\"universityId\":\"1\"}");
System.out.println("TestFindEnrolledStudent Output: " + out.toString());
// 返回结果存储在JSONArray中
JSONArray jsArray = (JSONArray) JSONObject.parse(out.toString());
// 确认返回结果
// 返回对象
JSONObject js = (JSONObject) jsArray.get(0);
// 确认个人信息
assertEquals(1, js.get("id"));
assertEquals(19875426874625L, js.get("testId"));
assertEquals("王一", js.get("name"));
assertEquals("男", js.get("gender"));
assertEquals(5, js.get("regionId"));
assertEquals(698, js.get("totalScore"));
assertEquals(200, js.get("rank"));
// 确认专业
JSONArray majors = (JSONArray) js.get("majors");
JSONObject major = (JSONObject) majors.get(0);
assertEquals("经济与贸易类", major.get("nclass"));
assertEquals("国际经济与贸易、金融学、税收学、管理科学", major.get("nmajor"));
assertEquals(5, major.get("classId"));
assertEquals(5, major.get("regionId"));
assertEquals(1, major.get("kind"));
assertEquals(1, major.get("batch"));
}
@Test
public void testInvalidInput() {
// 设置参数
expect(request.getParameter("universityId")).andReturn("0");
// 设置返回参数
try {
response.sendError(403, "访问错误,请刷新后重试");
} catch (IOException e) {
e.printStackTrace();
}
// 切换到replay模式
replayAll();
// 发送post请求
try {
servlet.doPost(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
// 输出结果
System.out.println("TestFindEnrolledStudent Input: " + "{\"universityId\":\"0\"}");
System.out.println("TestFindEnrolledStudent Output: " + "{\"StatusCode\":\"403\"}");
}
}
|
3e1ac9079b86633019e31f45eb7f9f8f15de66c4 | 6,733 | java | Java | src/main/java/de/hunsicker/jalopy/language/CompositeFactory.java | Bryanx/jalopy | 858b4fb93b636b36c48133bda60968cd59a582f3 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/de/hunsicker/jalopy/language/CompositeFactory.java | Bryanx/jalopy | 858b4fb93b636b36c48133bda60968cd59a582f3 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/de/hunsicker/jalopy/language/CompositeFactory.java | Bryanx/jalopy | 858b4fb93b636b36c48133bda60968cd59a582f3 | [
"BSD-3-Clause"
] | null | null | null | 29.530702 | 94 | 0.557552 | 11,363 | package de.hunsicker.jalopy.language;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import de.hunsicker.jalopy.language.antlr.ExtendedToken;
import de.hunsicker.jalopy.language.antlr.JavaNodeFactory;
import de.hunsicker.jalopy.language.antlr.Node;
/**
* This class creates instances of all the Factories used to generate JavaNodes, Nodes, &
* Extended Tokens. It is also responsible for maintaining and clearing the cache for these
* factories
*/
public class CompositeFactory {
/**TODO DOCUMENT ME!*/
private ExtendedTokenFactory extendedTokenFactory = null;
/**TODO DOCUMENT ME!*/
private JavaNodeFactory javaNodeFactory = null;
/**TODO DOCUMENT ME!*/
private final Map cacheMap;
/**TODO DOCUMENT ME!*/
private final Map reuseMap;
/**TODO DOCUMENT ME!*/
private NodeFactory nodeFactory = null;
/**TODO DOCUMENT ME!*/
private Recognizer recognizer;
/**
* TODO DOCUMENT ME!
* @author Steve Heyns Mar, 2007
* @version 1.0
*/
public class ExtendedTokenFactory {
/**TODO DOCUMENT ME!*/
private final CompositeFactory compositeFactory;
/**
* TODO DOCUMENT ME!
* @author Steve Heyns Mar, 2007
* @version 1.0
*/
private class ExtendedTokenImpl extends ExtendedToken {
// Empty implementation
} // end ExtendedTokenImpl
/**
* TODO Creates a new ExtendedTokenFactory object.
*
* @param compositeFactory DOCUMENT ME!
*/
private ExtendedTokenFactory(CompositeFactory compositeFactory) {
this.compositeFactory = compositeFactory;
} // end ExtendedTokenFactory()
/**
* TODO DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ExtendedToken create() {
ExtendedToken cached = (ExtendedToken)compositeFactory.getCached(this.getClass());
if (cached == null) {
cached = new ExtendedTokenImpl();
compositeFactory.addCached(ExtendedTokenFactory.class, cached);
} // end if
return cached;
} // end create()
/**
* TODO DOCUMENT ME!
*
* @param type The type
* @param text The text
*
* @return Creates a new extended token
*/
public ExtendedToken create(int type,
String text) {
ExtendedToken token = create();
token.setType(type);
token.setText(text);
return token;
} // end create()
} // end ExtendedTokenFactory
/**
* A constructor to provide single instance attributes
*/
public CompositeFactory() {
this.cacheMap = new HashMap();
this.reuseMap = new HashMap();
this.extendedTokenFactory = new ExtendedTokenFactory(this);
this.javaNodeFactory = new JavaNodeFactory(this);
this.nodeFactory = new NodeFactory(this);
} // end CompositeFactory()
/**
* Added the object to the cache
*
* @param class1 The type of object
* @param cached The object
*/
public void addCached(Class class1,
Object cached) {
synchronized (cacheMap) {
List cache = (List)cacheMap.get(class1);
if (cache == null) {
cache = new Vector();
cacheMap.put(class1, cache);
reuseMap.put(class1, new Vector());
} // end if
cache.add(cached);
} // end synchronized
} // end addCached()
/**
* Clears all objects that were created in the factories
*/
public void clear() {
List cache = null;
// List reuseList = null;
Object item = null;
// For each of the types clear the contents
synchronized (cacheMap) {
for (Iterator i = cacheMap.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Entry)i.next();
// reuseList = (List) reuseMap.get(entry.getKey());
cache = (List)entry.getValue();
for (Iterator l = cache.iterator(); l.hasNext();) {
item = l.next();
if (item instanceof Node) {
((Node)item).clear();
} // end if
else if (item instanceof ExtendedToken) {
((ExtendedToken)item).clear();
} // end else if
// reuseList.add(item);
l.remove();
} // end for
} // end for
} // end synchronized
} // end clear()
/**
* A factory calls this method to return an object that was cached
*
* @param class1 The class used to index
*
* @return
*/
public Object getCached(Class class1) {
return null;
// Commented out, just allow the objects to be created by the factories and let
// the GC take care of removing them
// List cache = (List) reuseMap.get(class1);
// Object result= null;
// if (cache!=null && !cache.isEmpty()) {
// result = cache.remove(0);
// addCached(class1, result);
// }
//
// return result;
} // end getCached()
/**
* Returns the local copy of the token factory
*
* @return The local copy of the token factory
*/
public ExtendedTokenFactory getExtendedTokenFactory() {
return extendedTokenFactory;
} // end getExtendedTokenFactory()
/**
* Returns the local copy of the java node factory
*
* @return The local copy of the java node factory
*/
public JavaNodeFactory getJavaNodeFactory() {
return javaNodeFactory;
} // end getJavaNodeFactory()
/**
* Returns the local node factory
*
* @return The node factory
*/
public NodeFactory getNodeFactory() {
return nodeFactory;
} // end getNodeFactory()
/**
* Returns the Recognizer
*
* @return The Recognizer
*/
public Recognizer getRecognizer() {
return recognizer;
} // end getRecognizer()
/**
* Sets the java Recognizer
*
* @param recognizer The java Recognizer
*/
public void setJavadocRecognizer(Recognizer recognizer) {
this.recognizer = recognizer;
} // end setJavadocRecognizer()
} // end CompositeFactory
|
3e1ac9559ae6502b50f8b86ea0234721d1497d67 | 8,541 | java | Java | cat-home/src/main/java/com/dianping/cat/report/task/utilization/UtilizationReportBuilder.java | HanderLo/cat | 59979b6800c3842fd7620719751047a58c19f36f | [
"Apache-2.0"
] | 1 | 2018-01-10T02:41:55.000Z | 2018-01-10T02:41:55.000Z | cat-home/src/main/java/com/dianping/cat/report/task/utilization/UtilizationReportBuilder.java | HanderLo/cat | 59979b6800c3842fd7620719751047a58c19f36f | [
"Apache-2.0"
] | null | null | null | cat-home/src/main/java/com/dianping/cat/report/task/utilization/UtilizationReportBuilder.java | HanderLo/cat | 59979b6800c3842fd7620719751047a58c19f36f | [
"Apache-2.0"
] | null | null | null | 38.300448 | 114 | 0.761152 | 11,364 | package com.dianping.cat.report.task.utilization;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.Constants;
import com.dianping.cat.DomainManager;
import com.dianping.cat.ServerConfigManager;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.consumer.cross.model.entity.CrossReport;
import com.dianping.cat.consumer.heartbeat.model.entity.HeartbeatReport;
import com.dianping.cat.consumer.transaction.TransactionAnalyzer;
import com.dianping.cat.consumer.transaction.model.entity.TransactionReport;
import com.dianping.cat.core.dal.DailyReport;
import com.dianping.cat.core.dal.HourlyReport;
import com.dianping.cat.core.dal.MonthlyReport;
import com.dianping.cat.core.dal.WeeklyReport;
import com.dianping.cat.helper.TimeUtil;
import com.dianping.cat.home.utilization.entity.ApplicationState;
import com.dianping.cat.home.utilization.entity.Domain;
import com.dianping.cat.home.utilization.entity.UtilizationReport;
import com.dianping.cat.home.utilization.transform.DefaultNativeBuilder;
import com.dianping.cat.report.page.cross.display.ProjectInfo;
import com.dianping.cat.report.page.cross.display.TypeDetailInfo;
import com.dianping.cat.report.page.transaction.TransactionMergeManager;
import com.dianping.cat.report.service.ReportService;
import com.dianping.cat.report.task.TaskHelper;
import com.dianping.cat.report.task.spi.ReportTaskBuilder;
public class UtilizationReportBuilder implements ReportTaskBuilder {
@Inject
protected ReportService m_reportService;
@Inject
private TransactionMergeManager m_mergeManager;
@Inject
private ServerConfigManager m_configManger;
@Inject
private DomainManager m_domainManager;
@Override
public boolean buildDailyTask(String name, String domain, Date period) {
UtilizationReport utilizationReport = queryHourlyReportsByDuration(name, domain, period,
TaskHelper.tomorrowZero(period));
DailyReport report = new DailyReport();
report.setContent("");
report.setCreationDate(new Date());
report.setDomain(domain);
report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
report.setName(name);
report.setPeriod(period);
report.setType(1);
byte[] binaryContent = DefaultNativeBuilder.build(utilizationReport);
return m_reportService.insertDailyReport(report, binaryContent);
}
@Override
public boolean buildHourlyTask(String name, String domain, Date start) {
UtilizationReport utilizationReport = new UtilizationReport(Constants.CAT);
Date end = new Date(start.getTime() + TimeUtil.ONE_HOUR);
Set<String> domains = m_reportService.queryAllDomainNames(start, end, TransactionAnalyzer.ID);
TransactionReportVisitor transactionVisitor = new TransactionReportVisitor()
.setUtilizationReport(utilizationReport);
HeartbeatReportVisitor heartbeatVisitor = new HeartbeatReportVisitor().setUtilizationReport(utilizationReport);
for (String domainName : domains) {
if (m_configManger.validateDomain(domainName)) {
TransactionReport transactionReport = m_reportService.queryTransactionReport(domainName, start, end);
int size = transactionReport.getMachines().size();
utilizationReport.findOrCreateDomain(domainName).setMachineNumber(size);
transactionReport = m_mergeManager.mergerAllIp(transactionReport, Constants.ALL);
transactionVisitor.visitTransactionReport(transactionReport);
}
}
for (String domainName : domains) {
if (m_configManger.validateDomain(domainName)) {
HeartbeatReport heartbeatReport = m_reportService.queryHeartbeatReport(domainName, start, end);
heartbeatVisitor.visitHeartbeatReport(heartbeatReport);
}
}
for (String domainName : domains) {
if (m_configManger.validateDomain(domainName)) {
CrossReport crossReport = m_reportService.queryCrossReport(domainName, start, end);
ProjectInfo projectInfo = new ProjectInfo(TimeUtil.ONE_HOUR);
projectInfo.setDomainManager(m_domainManager);
projectInfo.setClientIp(Constants.ALL);
projectInfo.visitCrossReport(crossReport);
Collection<TypeDetailInfo> callInfos = projectInfo.getCallProjectsInfo();
for (TypeDetailInfo typeInfo : callInfos) {
String project = typeInfo.getProjectName();
if (!validataService(project)) {
long failure = typeInfo.getFailureCount();
Domain d = utilizationReport.findOrCreateDomain(project);
ApplicationState service = d.findApplicationState("PigeonService");
if (service != null) {
service.setFailureCount(service.getFailureCount() + failure);
long count = service.getCount();
if (count > 0) {
service.setFailurePercent(service.getFailureCount() * 1.0 / count);
}
}
}
}
}
}
utilizationReport.setStartTime(start);
utilizationReport.setEndTime(end);
HourlyReport report = new HourlyReport();
report.setContent("");
report.setCreationDate(new Date());
report.setDomain(domain);
report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
report.setName(name);
report.setPeriod(start);
report.setType(1);
byte[] binaryContent = DefaultNativeBuilder.build(utilizationReport);
return m_reportService.insertHourlyReport(report, binaryContent);
}
@Override
public boolean buildMonthlyTask(String name, String domain, Date period) {
UtilizationReport utilizationReport = queryDailyReportsByDuration(domain, period,
TaskHelper.nextMonthStart(period));
MonthlyReport report = new MonthlyReport();
report.setContent("");
report.setCreationDate(new Date());
report.setDomain(domain);
report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
report.setName(name);
report.setPeriod(period);
report.setType(1);
byte[] binaryContent = DefaultNativeBuilder.build(utilizationReport);
return m_reportService.insertMonthlyReport(report, binaryContent);
}
@Override
public boolean buildWeeklyTask(String name, String domain, Date period) {
UtilizationReport utilizationReport = queryDailyReportsByDuration(domain, period, new Date(period.getTime()
+ TimeUtil.ONE_WEEK));
WeeklyReport report = new WeeklyReport();
report.setContent("");
report.setCreationDate(new Date());
report.setDomain(domain);
report.setIp(NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
report.setName(name);
report.setPeriod(period);
report.setType(1);
byte[] binaryContent = DefaultNativeBuilder.build(utilizationReport);
return m_reportService.insertWeeklyReport(report, binaryContent);
}
private UtilizationReport queryDailyReportsByDuration(String domain, Date start, Date end) {
long startTime = start.getTime();
long endTime = end.getTime();
UtilizationReportMerger merger = new UtilizationReportMerger(new UtilizationReport(domain));
for (; startTime < endTime; startTime += TimeUtil.ONE_DAY) {
try {
UtilizationReport reportModel = m_reportService.queryUtilizationReport(domain, new Date(startTime),
new Date(startTime + TimeUtil.ONE_DAY));
reportModel.accept(merger);
} catch (Exception e) {
Cat.logError(e);
}
}
UtilizationReport utilizationReport = merger.getUtilizationReport();
utilizationReport.setStartTime(start);
utilizationReport.setEndTime(end);
return utilizationReport;
}
private UtilizationReport queryHourlyReportsByDuration(String name, String domain, Date start, Date end) {
long startTime = start.getTime();
long endTime = end.getTime();
UtilizationReportMerger merger = new UtilizationReportMerger(new UtilizationReport(domain));
for (; startTime < endTime; startTime = startTime + TimeUtil.ONE_HOUR) {
Date date = new Date(startTime);
UtilizationReport reportModel = m_reportService.queryUtilizationReport(domain, date, new Date(date.getTime()
+ TimeUtil.ONE_HOUR));
reportModel.accept(merger);
}
UtilizationReport utilizationReport = merger.getUtilizationReport();
utilizationReport.setStartTime(start);
utilizationReport.setEndTime(end);
return utilizationReport;
}
private boolean validataService(String projectName) {
return projectName.equalsIgnoreCase(ProjectInfo.ALL_SERVER) || projectName.equalsIgnoreCase("UnknownProject");
}
}
|
3e1ac9db24a4f5b46d5c685ab2aff2481d6fd20d | 585 | java | Java | src/net/Yl.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 5 | 2022-02-04T12:57:17.000Z | 2022-03-26T16:12:16.000Z | src/net/Yl.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | src/net/Yl.java | josesilveiraa/novoline | 9146c4add3aa518d9aa40560158e50be1b076cf0 | [
"Unlicense"
] | 1 | 2021-11-28T09:59:55.000Z | 2021-11-28T09:59:55.000Z | 21.666667 | 71 | 0.680342 | 11,365 | package net;
import net.aog;
import viaversion.viaversion.api.PacketWrapper;
import viaversion.viaversion.api.remapper.PacketHandler;
import viaversion.viaversion.api.type.Type;
class Yl implements PacketHandler {
final aog a;
Yl(aog var1) {
this.a = var1;
}
public void handle(PacketWrapper var1) throws Exception {
int var2 = ((Integer)var1.get(Type.INT, 0)).intValue();
if(var2 == 27) {
var1.write(Type.FLAT_ITEM, var1.read(Type.FLAT_VAR_INT_ITEM));
}
}
private static Exception a(Exception var0) {
return var0;
}
}
|
3e1acb0b3cb7603834aa0b2ddf47d43504c723dc | 2,127 | java | Java | aliyun-java-sdk-imm-v5/src/main/java/com/aliyuncs/v5/imm/model/v20170906/ListOfficeConversionTaskRequest.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | 4 | 2020-05-14T05:04:30.000Z | 2021-08-20T11:08:46.000Z | aliyun-java-sdk-imm-v5/src/main/java/com/aliyuncs/v5/imm/model/v20170906/ListOfficeConversionTaskRequest.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | 2 | 2020-10-13T07:47:10.000Z | 2021-06-04T02:42:57.000Z | aliyun-java-sdk-imm-v5/src/main/java/com/aliyuncs/v5/imm/model/v20170906/ListOfficeConversionTaskRequest.java | aliyun/aliyun-openapi-java-sdk-v5 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | [
"Apache-2.0"
] | null | null | null | 26.259259 | 121 | 0.728256 | 11,366 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.v5.imm.model.v20170906;
import com.aliyuncs.v5.RpcAcsRequest;
import com.aliyuncs.v5.http.MethodType;
import com.aliyuncs.v5.imm.Endpoint;
/**
* @author auto create
* @version
*/
public class ListOfficeConversionTaskRequest extends RpcAcsRequest<ListOfficeConversionTaskResponse> {
private Integer maxKeys;
private String project;
private String marker;
public ListOfficeConversionTaskRequest() {
super("imm", "2017-09-06", "ListOfficeConversionTask", "imm");
setMethod(MethodType.POST);
try {
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Integer getMaxKeys() {
return this.maxKeys;
}
public void setMaxKeys(Integer maxKeys) {
this.maxKeys = maxKeys;
if(maxKeys != null){
putQueryParameter("MaxKeys", maxKeys.toString());
}
}
public String getProject() {
return this.project;
}
public void setProject(String project) {
this.project = project;
if(project != null){
putQueryParameter("Project", project);
}
}
public String getMarker() {
return this.marker;
}
public void setMarker(String marker) {
this.marker = marker;
if(marker != null){
putQueryParameter("Marker", marker);
}
}
@Override
public Class<ListOfficeConversionTaskResponse> getResponseClass() {
return ListOfficeConversionTaskResponse.class;
}
}
|
3e1acc3cd7f1c147f55ec44efa2a88a2911cbb6b | 1,871 | java | Java | Json/src/main/java/co/casterlabs/rakurai/json/element/JsonElement.java | Casterlabs/Rakurai | 365e34cf818d4be9ffb68f4d2cb84fa0c068ec3a | [
"MIT"
] | 2 | 2021-05-24T15:20:24.000Z | 2021-12-13T19:03:30.000Z | Json/src/main/java/co/casterlabs/rakurai/json/element/JsonElement.java | Casterlabs/Rakurai | 365e34cf818d4be9ffb68f4d2cb84fa0c068ec3a | [
"MIT"
] | 1 | 2021-06-17T04:38:59.000Z | 2021-06-17T04:38:59.000Z | Json/src/main/java/co/casterlabs/rakurai/json/element/JsonElement.java | Casterlabs/Rakurai | 365e34cf818d4be9ffb68f4d2cb84fa0c068ec3a | [
"MIT"
] | null | null | null | 21.022472 | 94 | 0.639765 | 11,367 | package co.casterlabs.rakurai.json.element;
import co.casterlabs.rakurai.json.Rson.RsonConfig;
import co.casterlabs.rakurai.json.serialization.JsonSerializationContext;
import lombok.NonNull;
public interface JsonElement {
/* String */
default boolean isJsonString() {
return false;
}
default String getAsString() {
throw new UnsupportedOperationException();
}
/* Number */
default boolean isJsonNumber() {
return false;
}
default JsonNumber getAsNumber() {
throw new UnsupportedOperationException();
}
/* Null */
default boolean isJsonNull() {
return false;
}
/* Boolean */
default boolean isJsonBoolean() {
return false;
}
default boolean getAsBoolean() {
throw new UnsupportedOperationException();
}
/* Array */
default boolean isJsonArray() {
return false;
}
default JsonArray getAsArray() {
throw new UnsupportedOperationException();
}
/* Object */
default boolean isJsonObject() {
return false;
}
default JsonObject getAsObject() {
throw new UnsupportedOperationException();
}
/* Serialization */
default String toString(boolean prettyPrinting) {
JsonSerializationContext ctx = new JsonSerializationContext()
.setConfig(
new RsonConfig()
.setPrettyPrintingEnabled(prettyPrinting)
);
this.serialize(ctx);
return ctx.toString();
}
default void serialize(@NonNull JsonSerializationContext ctx) {
// Functionally the same
this.serializeToArray(ctx);
}
public void serializeToArray(@NonNull JsonSerializationContext ctx);
public void serializeToObject(@NonNull String key, @NonNull JsonSerializationContext ctx);
}
|
3e1acceeedea95bb3d5f1bad52e36a4d61e0b0a8 | 571 | java | Java | fyjmall-product/src/main/java/com/fyj/fyjmall/product/FyjmallProductApplication.java | taojhlwkl/fyjmall | 6006ceb22670234829eafaa11caa152f9bf14c51 | [
"Apache-2.0"
] | 1 | 2020-09-21T12:14:10.000Z | 2020-09-21T12:14:10.000Z | fyjmall-product/src/main/java/com/fyj/fyjmall/product/FyjmallProductApplication.java | taojhlwkl/fyjmall | 6006ceb22670234829eafaa11caa152f9bf14c51 | [
"Apache-2.0"
] | null | null | null | fyjmall-product/src/main/java/com/fyj/fyjmall/product/FyjmallProductApplication.java | taojhlwkl/fyjmall | 6006ceb22670234829eafaa11caa152f9bf14c51 | [
"Apache-2.0"
] | 2 | 2020-12-04T14:08:25.000Z | 2021-06-07T12:28:51.000Z | 31.722222 | 72 | 0.82662 | 11,368 | package com.fyj.fyjmall.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients(basePackages = "com.fyj.fyjmall.product.feign")
@EnableDiscoveryClient
@SpringBootApplication
public class FyjmallProductApplication {
public static void main(String[] args) {
SpringApplication.run(FyjmallProductApplication.class, args);
}
}
|
3e1ace0f709c9c7a77407cdfe06ab5c696258c48 | 499 | java | Java | Mamong Us/src/main/java/tk/mamong_us/net/handlers/DisconnectHandler.java | Q11Maristenkolleg/Mamong-us-java | 16cc4d44df093d7d259e4c6c69102b632c3e8f1a | [
"MIT"
] | 6 | 2021-01-21T04:23:07.000Z | 2021-05-30T15:41:20.000Z | Mamong Us/src/main/java/tk/mamong_us/net/handlers/DisconnectHandler.java | Q11Maristenkolleg/Mamong-us-java | 16cc4d44df093d7d259e4c6c69102b632c3e8f1a | [
"MIT"
] | 4 | 2020-11-26T14:48:05.000Z | 2021-01-22T07:30:18.000Z | Mamong Us/src/main/java/tk/mamong_us/net/handlers/DisconnectHandler.java | Q11Maristenkolleg/Mamong-us-java | 16cc4d44df093d7d259e4c6c69102b632c3e8f1a | [
"MIT"
] | null | null | null | 29.352941 | 74 | 0.651303 | 11,369 | package tk.mamong_us.net.handlers;
import tk.mamong_us.chat.OutputChat;
import tk.mamong_us.net.Multiplayer;
public class DisconnectHandler implements Handler {
@Override
public void handle(String ip, String[] msg) {
if (!Multiplayer.ip.equals(ip)) {
OutputChat.add(Multiplayer.names.get(ip) + " left the game!");
Multiplayer.names.remove(ip);
Multiplayer.players.get(ip).destroy();
Multiplayer.players.remove(ip);
}
}
}
|
3e1acf0b27ea738c0ca5aa02705d9379d00afbf7 | 4,379 | java | Java | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/container/KafkaConsumerContainer.java | jasonTangxd/DBus | bfcb992fcfeac41c0376be98f927b472844f920f | [
"Apache-2.0"
] | 1,232 | 2017-09-04T11:23:08.000Z | 2022-03-25T07:01:07.000Z | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/container/KafkaConsumerContainer.java | vrtch/DBus | 81dfda57dc7f6f137092edef1e834d32abb38a56 | [
"Apache-2.0"
] | 72 | 2017-10-11T04:43:17.000Z | 2022-03-01T04:48:22.000Z | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/container/KafkaConsumerContainer.java | vrtch/DBus | 81dfda57dc7f6f137092edef1e834d32abb38a56 | [
"Apache-2.0"
] | 551 | 2017-09-05T06:55:14.000Z | 2022-03-19T07:24:56.000Z | 33.427481 | 136 | 0.612697 | 11,370 | /*-
* <<
* DBus
* ==
* Copyright (C) 2016 - 2019 Bridata
* ==
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* >>
*/
package com.creditease.dbus.heartbeat.container;
import com.creditease.dbus.heartbeat.event.impl.KafkaConsumerEvent;
import com.creditease.dbus.heartbeat.log.LoggerFactory;
import org.apache.kafka.clients.consumer.Consumer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class KafkaConsumerContainer {
private static KafkaConsumerContainer container;
private ExecutorService es;
private ConcurrentHashMap<String, Consumer<String, String>> consumerMap = new ConcurrentHashMap<String, Consumer<String, String>>();
private List<KafkaConsumerEvent> kafkaConsumerEvent = Collections.synchronizedList(new ArrayList<KafkaConsumerEvent>());
private KafkaConsumerContainer() {
}
public static KafkaConsumerContainer getInstances() {
if (container == null) {
synchronized (KafkaConsumerContainer.class) {
if (container == null)
container = new KafkaConsumerContainer();
}
}
return container;
}
public void putConsumer(String key, Consumer<String, String> consumer) {
consumerMap.put(key, consumer);
}
public Consumer<String, String> getConsumer(String key) {
return consumerMap.get(key);
}
public void initThreadPool(int size) {
int poolSize = size + 10;
es = Executors.newFixedThreadPool(poolSize);
LoggerFactory.getLogger().info("[kafka-consumer-container] initThreadPool size = " + poolSize);
}
public void submit(KafkaConsumerEvent event) {
kafkaConsumerEvent.add(event);
es.submit(event);
}
public void shutdown() {
try {
//发起礼貌退出通知
for (KafkaConsumerEvent event : kafkaConsumerEvent) {
event.stop();
}
//发起shutdown线程池, 正在执行的thread不强停
this.es.shutdown();
//等5秒看是否礼貌退出已经关闭
if (!this.es.awaitTermination(5L, TimeUnit.SECONDS)) {
//强制关闭包括正在执行的线程
this.es.shutdownNow();
for (int i = 1; i <= 5; i++) {
sleep(1L, TimeUnit.SECONDS);
if (this.es.isTerminated()) {
LoggerFactory.getLogger().info("[kafka-consumer-container] thread pool interrupt shutdown success!!");
break;
}
LoggerFactory.getLogger().info("[kafka-consumer-container] thread pool shutdown, retry time: {}", i);
}
//如果重复等待5次后仍然无法退出,就system exit.
if (!this.es.isTerminated()) {
LoggerFactory.getLogger().info("[kafka-consumer-container] force exit!!!");
sleep(1L, TimeUnit.SECONDS);
System.exit(-1);
}
} else {
LoggerFactory.getLogger().info("[kafka-consumer-container] thread pool normal shutdown success!!");
}
} catch (Exception e) {
LoggerFactory.getLogger().error("[kafka-consumer-container]", e);
sleep(1L, TimeUnit.SECONDS);
System.exit(-1);
} finally {
es = null;
}
consumerMap.clear();
kafkaConsumerEvent.clear();
container = null;
}
private void sleep(long t, TimeUnit tu) {
try {
tu.sleep(t);
} catch (InterruptedException e) {
LoggerFactory.getLogger().error("[kafka-consumer-container] 线程sleep:" + t + " " + tu.name() + "中被中断!");
}
}
}
|
3e1acf34679532c09b659bf1b186b7ff3220ae4f | 2,767 | java | Java | pdf/templates/src/test/java/org/bndly/pdf/templating/TableSplitTest.java | bndly/bndly-commons | e0fee12a6a549dff931ed1c8563f00798224786a | [
"Apache-2.0"
] | 1 | 2020-07-24T08:58:39.000Z | 2020-07-24T08:58:39.000Z | pdf/templates/src/test/java/org/bndly/pdf/templating/TableSplitTest.java | bndly/bndly-commons | e0fee12a6a549dff931ed1c8563f00798224786a | [
"Apache-2.0"
] | 2 | 2020-12-02T18:45:34.000Z | 2022-01-21T23:45:25.000Z | pdf/templates/src/test/java/org/bndly/pdf/templating/TableSplitTest.java | bndly/bndly-commons | e0fee12a6a549dff931ed1c8563f00798224786a | [
"Apache-2.0"
] | 2 | 2020-07-21T17:44:10.000Z | 2020-07-22T13:31:10.000Z | 31.804598 | 84 | 0.743043 | 11,371 | package org.bndly.pdf.templating;
/*-
* #%L
* PDF templating
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.bndly.common.data.io.ReplayableInputStream;
import org.bndly.css.CSSItem;
import org.bndly.css.CSSParsingException;
import org.bndly.css.CSSReader;
import org.bndly.css.CSSStyle;
import org.bndly.document.reader.DocumentReader;
import org.bndly.document.xml.XDocument;
import org.bndly.pdf.PrintingContext;
import org.bndly.pdf.mapper.DocumentMapper;
import org.bndly.pdf.output.InputStreamResolver;
import org.bndly.pdf.output.PDFPrinter;
import org.bndly.pdf.visualobject.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
public class TableSplitTest {
private PrintingContext ctx;
private static final String CSS = "tablesplittest.css";
private static final String XML = "tablesplittest.xml";
@Test
public void setup() {
ctx = new PrintingContext();
PDFPrinter printer = ctx.createPDFPrinter();
printer.setOutputFileName("target/tablesplittest.pdf");
final ClassLoader cl = getClass().getClassLoader();
InputStreamResolver resolver = new InputStreamResolver() {
@Override
public ReplayableInputStream resolve(String fileName) throws IOException {
return ReplayableInputStream.newInstance(cl.getResource(fileName).openStream());
}
};
ctx.setInputStreamResolver(resolver);
List<CSSStyle> styles = new ArrayList<>();
try {
CSSReader reader = new CSSReader();
List<CSSItem> items = reader.read(resolver.resolve(CSS));
for (CSSItem item : items) {
if (CSSStyle.class.isInstance(item)) {
styles.add((CSSStyle) item);
}
}
} catch (IOException | CSSParsingException e) {
throw new IllegalStateException("CSS file could not be read for file " + CSS, e);
}
ctx.getStyles().addAll(styles);
DocumentMapper mapper = new DocumentMapper();
DocumentReader reader = new DocumentReader();
XDocument xDocument;
try {
xDocument = reader.read(resolver.resolve(XML));
Document pdfdocument = mapper.toDocument(xDocument, printer);
printer.print(pdfdocument);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3e1ad168581440b395832efc3f831764625dce8f | 3,745 | java | Java | dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/object/DiscardObjectAction.java | hispindia/HARYANA-2.20 | be1daf743d339c221890b1ba9100b380f5ce7bc4 | [
"BSD-3-Clause"
] | null | null | null | dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/object/DiscardObjectAction.java | hispindia/HARYANA-2.20 | be1daf743d339c221890b1ba9100b380f5ce7bc4 | [
"BSD-3-Clause"
] | null | null | null | dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/object/DiscardObjectAction.java | hispindia/HARYANA-2.20 | be1daf743d339c221890b1ba9100b380f5ce7bc4 | [
"BSD-3-Clause"
] | null | null | null | 32.565217 | 122 | 0.585314 | 11,372 | package org.hisp.dhis.importexport.action.object;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import static org.hisp.dhis.importexport.action.util.ImportExportInternalProcessUtil.getCurrentRunningProcessImportFormat;
import java.util.Collection;
import org.hisp.dhis.importexport.ImportObjectService;
import com.opensymphony.xwork2.Action;
/**
* @author Lars Helge Overland
* @version $Id$
*/
public class DiscardObjectAction
implements Action
{
// -------------------------------------------------------------------------
// Input
// -------------------------------------------------------------------------
private Collection<String> id;
public void setId( Collection<String> id )
{
this.id = id;
}
// -------------------------------------------------------------------------
// Output
// -------------------------------------------------------------------------
private String message;
public String getMessage()
{
return message;
}
private String importFormat;
public String getImportFormat()
{
return importFormat;
}
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private ImportObjectService importObjectService;
public void setImportObjectService( ImportObjectService importObjectService )
{
this.importObjectService = importObjectService;
}
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute()
throws Exception
{
int count = 0;
if ( id != null )
{
for ( String identifier : id )
{
importObjectService.cascadeDeleteImportObject( Integer.parseInt( identifier ) );
count++;
}
message = String.valueOf( count );
importFormat = getCurrentRunningProcessImportFormat();
return SUCCESS;
}
return ERROR;
}
}
|
3e1ad18803f355944b6900e10c3c02000770c926 | 5,663 | java | Java | app/src/main/java/com/example/lbstest/MainActivity.java | 15291783517/LBSTest | 45daf82ae075791a9dde653834ca40b7e01b510e | [
"Apache-2.0"
] | 1 | 2017-09-02T03:42:04.000Z | 2017-09-02T03:42:04.000Z | app/src/main/java/com/example/lbstest/MainActivity.java | 15291783517/LBSTest | 45daf82ae075791a9dde653834ca40b7e01b510e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/lbstest/MainActivity.java | 15291783517/LBSTest | 45daf82ae075791a9dde653834ca40b7e01b510e | [
"Apache-2.0"
] | null | null | null | 36.070064 | 146 | 0.675967 | 11,373 | package com.example.lbstest;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public LocationClient mLocationClient;
private TextView positionText;
private MapView mapView;
private BaiduMap baiduMap;
private boolean isFirstLocate = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(new MyLocationListener());
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mapView.getMap();
baiduMap.setMyLocationEnabled(true);
positionText = (TextView) findViewById(R.id.position_text_view);
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissionList.isEmpty()){
String [] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this,permissions,1);
}else {
requestLocation();
}
}
private void navigateTo(BDLocation location){
if (isFirstLocate){
LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
baiduMap.animateMapStatus(update);
update = MapStatusUpdateFactory.zoomTo(16f);
baiduMap.animateMapStatus(update);
isFirstLocate = false;
}
MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
locationBuilder.latitude(location.getLatitude());
locationBuilder.longitude(location.getLongitude());
MyLocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);
}
private void requestLocation(){
initLocation();
mLocationClient.start();
}
private void initLocation() {
LocationClientOption option = new LocationClientOption();
option.setScanSpan(5000);
//option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);只通过GPS定位
//option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);优先使用GPS
//option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);只使用网络
option.setIsNeedAddress(true);
mLocationClient.setLocOption(option);
}
@Override
public void onResume(){
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy(){
super.onDestroy();
mLocationClient.stop();
mapView.onDestroy();
baiduMap.setMyLocationEnabled(false);
}
@Override
public void onRequestPermissionsResult(int requestCode,String[] permission,int[] grantResults){
switch (requestCode){
case 1:
if (grantResults.length > 0){
for(int result : grantResults){
if (result != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"必须同意所有权限才能使用本权限",Toast.LENGTH_SHORT).show();
finish();
return;
}
}
requestLocation();
}else {
Toast.makeText(this,"发生未知错误",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation location){
if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation){
navigateTo(location);
}
}
}
}
|
3e1ad2853c2c3c81624c63875da241822339147c | 2,498 | java | Java | backend/api/api/src/main/java/be/sel2/api/entities/Certificate.java | Tram13/ProjectSEL2 | 066dbce1372c8b4f0ef683029423a93fc7f8ed22 | [
"MIT"
] | null | null | null | backend/api/api/src/main/java/be/sel2/api/entities/Certificate.java | Tram13/ProjectSEL2 | 066dbce1372c8b4f0ef683029423a93fc7f8ed22 | [
"MIT"
] | null | null | null | backend/api/api/src/main/java/be/sel2/api/entities/Certificate.java | Tram13/ProjectSEL2 | 066dbce1372c8b4f0ef683029423a93fc7f8ed22 | [
"MIT"
] | null | null | null | 33.306667 | 144 | 0.672938 | 11,374 | package be.sel2.api.entities;
import be.sel2.api.serializers.FileToHrefSerializer;
import be.sel2.api.serializers.ReducedProposalSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;
@Entity
@Getter
@Setter //This adds all the getters & setters for us
public class Certificate implements StatisticsEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
@JoinColumn(name = "fileid", referencedColumnName = "id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT, name = "none"))
@JsonSerialize(using = FileToHrefSerializer.class)
private @NotNull FileMeta file;
@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE")
@Temporal(TemporalType.TIMESTAMP)
// Er moet een default date object toegevoegd worden in de databank. Dit veld moet niet worden geüpdatet.
private Date created = new Date();
@Column(columnDefinition = "TIMESTAMP WITH TIME ZONE")
@Temporal(TemporalType.TIMESTAMP)
// Er moet een default date object toegevoegd worden in de databank. Dit veld wordt automatisch geüpdatet.
private Date lastUpdated = new Date();
@JsonSerialize(using = ReducedProposalSerializer.class)
@OneToOne
@JoinColumn(name = "proposalid", referencedColumnName = "id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT, name = "none"))
private @NotNull Proposal proposal;
public Certificate() {
}
public Certificate(@NotNull FileMeta file, @NotNull Proposal proposal) {
this.file = file;
this.proposal = proposal;
}
@Override
public String toString() {
return "Certificate{" +
"id=" + id +
", file=" + file +
", created=" + created +
", lastUpdated=" + lastUpdated +
", proposal=" + proposal +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Certificate that = (Certificate) o;
return Objects.equals(id, that.id) && Objects.equals(file, that.file) && Objects.equals(proposal, that.proposal);
}
@Override
public int hashCode() {
return Objects.hash(id, file, proposal);
}
}
|
3e1ad2a52f230d21dd656f0037f9c44e1a8b45a5 | 767 | java | Java | sources/com/google/android/gms/internal/ads/zzdst.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2019-10-01T11:34:10.000Z | 2019-10-01T11:34:10.000Z | sources/com/google/android/gms/internal/ads/zzdst.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | null | null | null | sources/com/google/android/gms/internal/ads/zzdst.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2020-05-26T05:10:33.000Z | 2020-05-26T05:10:33.000Z | 23.242424 | 92 | 0.601043 | 11,375 | package com.google.android.gms.internal.ads;
import java.nio.ByteBuffer;
public abstract class zzdst extends zzdsr implements zzbd {
/* renamed from: l */
private int f28270l;
/* renamed from: m */
private int f28271m;
protected zzdst(String str) {
super(str);
}
/* renamed from: b */
public final int mo31685b() {
if (!this.f28258d) {
mo31683a();
}
return this.f28270l;
}
/* access modifiers changed from: protected */
/* renamed from: b */
public final long mo31686b(ByteBuffer byteBuffer) {
this.f28270l = zzbc.m26410a(byteBuffer.get());
this.f28271m = (zzbc.m26412b(byteBuffer) << 8) + 0 + zzbc.m26410a(byteBuffer.get());
return 4;
}
}
|
3e1ad2d32cf04fefef9f000975c4c70caf86f37b | 767 | java | Java | android/src/main/java/im/zego/zego_express_engine/IZegoFlutterCustomVideoCaptureHandler.java | qq1903520389/zego_e_e-2.0.0 | 24266d5d202ec34379ef3aea5f344b58420a50c2 | [
"MIT"
] | 40 | 2020-04-14T06:46:28.000Z | 2022-03-16T07:37:55.000Z | android/src/main/java/im/zego/zego_express_engine/IZegoFlutterCustomVideoCaptureHandler.java | qq1903520389/zego_e_e-2.0.0 | 24266d5d202ec34379ef3aea5f344b58420a50c2 | [
"MIT"
] | 7 | 2020-05-18T08:45:25.000Z | 2021-08-15T06:23:33.000Z | android/src/main/java/im/zego/zego_express_engine/IZegoFlutterCustomVideoCaptureHandler.java | qq1903520389/zego_e_e-2.0.0 | 24266d5d202ec34379ef3aea5f344b58420a50c2 | [
"MIT"
] | 11 | 2020-05-18T07:21:41.000Z | 2022-01-19T10:44:28.000Z | 40.368421 | 173 | 0.723598 | 11,376 | package im.zego.zego_express_engine;
public interface IZegoFlutterCustomVideoCaptureHandler {
/**
* The callback triggered when the SDK is ready to receive captured video data. Only those video data that are sent to the SDK after this callback is received are valid.
*
* @param channel publish channel, It is consistent with Dart API
*/
void onStart(int channel);
/**
* The callback triggered when SDK stops receiving captured video data.
*
* After receiving this callback, the developer is advised to set the saved client object to nil, otherwise the memory occupied by the client object will always exist
* @param channel publish channel, It is consistent with Dart API
*/
void onStop(int channel);
}
|
3e1ad5c32e9b17b5507b97ff9f2048995d03c0c1 | 719 | java | Java | commercetools-models/src/main/java/io/sphere/sdk/types/LocalizedEnumFieldType.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | commercetools-models/src/main/java/io/sphere/sdk/types/LocalizedEnumFieldType.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | commercetools-models/src/main/java/io/sphere/sdk/types/LocalizedEnumFieldType.java | FL-K/commercetools-jvm-sdk | 6c3ba0d2e29e2f9c1a4054d99ea1e3ba8cf323ac | [
"Apache-2.0"
] | null | null | null | 24.793103 | 84 | 0.742698 | 11,377 | package io.sphere.sdk.types;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.sphere.sdk.models.LocalizedEnumValue;
import java.util.List;
/**
* @see Custom
*/
public final class LocalizedEnumFieldType extends FieldTypeBase {
private final List<LocalizedEnumValue> values;
@JsonCreator
private LocalizedEnumFieldType(final List<LocalizedEnumValue> values) {
this.values = values;
}
@JsonIgnore
public static LocalizedEnumFieldType of(final List<LocalizedEnumValue> values) {
return new LocalizedEnumFieldType(values);
}
public List<LocalizedEnumValue> getValues() {
return values;
}
}
|
3e1ad633f41dd7deb37862859e80cac5a2fb417d | 991 | java | Java | google-ads/src/main/java/com/google/ads/googleads/v3/services/GetKeywordPlanAdGroupRequestOrBuilder.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v3/services/GetKeywordPlanAdGroupRequestOrBuilder.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v3/services/GetKeywordPlanAdGroupRequestOrBuilder.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | 35.392857 | 127 | 0.710394 | 11,378 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v3/services/keyword_plan_ad_group_service.proto
package com.google.ads.googleads.v3.services;
public interface GetKeywordPlanAdGroupRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v3.services.GetKeywordPlanAdGroupRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Required. The resource name of the Keyword Plan ad group to fetch.
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code>
*/
java.lang.String getResourceName();
/**
* <pre>
* Required. The resource name of the Keyword Plan ad group to fetch.
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.ByteString
getResourceNameBytes();
}
|
3e1ad6c444ae322e333d0d0266f8a66e7ea38ea1 | 107 | java | Java | test-data/comp-changes/new/src/main/fieldNoLongerStatic/FieldNoLongerStaticSuper.java | jrfaller/maracas | ce35381e460db7870265d1a9a2a4d6a1d52b712b | [
"MIT"
] | 6 | 2020-06-13T19:46:29.000Z | 2021-12-13T13:17:13.000Z | test-data/comp-changes/new/src/main/fieldNoLongerStatic/FieldNoLongerStaticSuper.java | jrfaller/maracas | ce35381e460db7870265d1a9a2a4d6a1d52b712b | [
"MIT"
] | 46 | 2021-10-15T07:18:06.000Z | 2022-03-31T08:54:14.000Z | test-data/comp-changes/new/src/main/fieldNoLongerStatic/FieldNoLongerStaticSuper.java | jrfaller/maracas | ce35381e460db7870265d1a9a2a4d6a1d52b712b | [
"MIT"
] | 1 | 2022-03-29T13:55:54.000Z | 2022-03-29T13:55:54.000Z | 17.833333 | 39 | 0.841121 | 11,379 | package main.fieldNoLongerStatic;
public class FieldNoLongerStaticSuper {
public int superFieldStatic;
}
|
3e1ad70b35d9865c9b134b13cd0b2eef9301e381 | 888 | java | Java | Binary Search Tree/530. Minimum Absolute Difference in BST/Solution.java | echpee/LeetCode-Solutions | 427f12b1d3c3ca2221c48d5f7860f5630f5becb3 | [
"Unlicense"
] | 9 | 2021-03-24T11:21:03.000Z | 2022-02-14T05:05:48.000Z | Binary Search Tree/530. Minimum Absolute Difference in BST/Solution.java | echpee/LeetCode-Solutions | 427f12b1d3c3ca2221c48d5f7860f5630f5becb3 | [
"Unlicense"
] | 38 | 2021-10-07T18:04:12.000Z | 2021-12-05T05:53:27.000Z | Binary Search Tree/530. Minimum Absolute Difference in BST/Solution.java | echpee/LeetCode-Solutions | 427f12b1d3c3ca2221c48d5f7860f5630f5becb3 | [
"Unlicense"
] | 27 | 2021-10-06T19:55:48.000Z | 2021-11-18T16:53:20.000Z | 26.909091 | 61 | 0.533784 | 11,380 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
List<Integer> list = new ArrayList<>();
inorder(root , list);
int ans = Integer.MAX_VALUE;
for (int i = 0; i < list.size()-1; i++) {
ans = Math.min(ans,list.get(i+1)-list.get(i));
}
return ans;
}
public void inorder(TreeNode root , List<Integer> list) {
if (root == null) return;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
}
|
3e1ad79a61d64e68eba4452ced4d1a0a4b1fe80c | 2,551 | java | Java | maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsjava/src/main/java/org/apache/maven/scm/provider/cvslib/cvsjava/util/CvsLogListener.java | arturobernalg/maven-scm | c59dcf29361d69995446f57c9511a0613b382a7c | [
"Apache-2.0"
] | 1 | 2019-06-27T07:38:41.000Z | 2019-06-27T07:38:41.000Z | maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsjava/src/main/java/org/apache/maven/scm/provider/cvslib/cvsjava/util/CvsLogListener.java | arturobernalg/maven-scm | c59dcf29361d69995446f57c9511a0613b382a7c | [
"Apache-2.0"
] | 60 | 2019-06-12T05:24:18.000Z | 2021-07-21T04:23:14.000Z | maven-scm-providers/maven-scm-providers-cvs/maven-scm-provider-cvsjava/src/main/java/org/apache/maven/scm/provider/cvslib/cvsjava/util/CvsLogListener.java | arturobernalg/maven-scm | c59dcf29361d69995446f57c9511a0613b382a7c | [
"Apache-2.0"
] | null | null | null | 29.662791 | 91 | 0.653469 | 11,381 | package org.apache.maven.scm.provider.cvslib.cvsjava.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.netbeans.lib.cvsclient.event.CVSAdapter;
import org.netbeans.lib.cvsclient.event.MessageEvent;
/**
* A basic implementation of a CVS listener. It merely saves up
* into StringBuilders the stdout and stderr printstreams.
*
* @author <a href="mailto:anpch@example.com">Eric Pugh</a>
*
*/
public class CvsLogListener
extends CVSAdapter
{
private final StringBuffer taggedLine = new StringBuffer();
private StringBuffer stdout = new StringBuffer();
private StringBuffer stderr = new StringBuffer();
/**
* Called when the server wants to send a message to be displayed to the
* user. The message is only for information purposes and clients can
* choose to ignore these messages if they wish.
*
* {@inheritDoc}
*/
public void messageSent( MessageEvent e )
{
String line = e.getMessage();
StringBuffer stream = e.isError() ? stderr : stdout;
if ( e.isTagged() )
{
String message = MessageEvent.parseTaggedMessage( taggedLine, e.getMessage() );
if ( message != null )
{
//stream.println(message);
stream.append( message ).append( "\n" );
}
}
else
{
//stream.println(line);
stream.append( line ).append( "\n" );
}
}
/**
* @return Returns the standard output from cvs as a StringBuilder..
*/
public StringBuffer getStdout()
{
return stdout;
}
/**
* @return Returns the standard error from cvs as a StringBuilder..
*/
public StringBuffer getStderr()
{
return stderr;
}
} |
3e1ad8d5bf89bc242ef4e33c3bdc34dbce0a29eb | 280 | java | Java | camel-application/src/main/java/com/JavaDsl/camel_application/AppRoute.java | dhairya0704/ApacheCamelProjects | 80eeec40f4ddf5cc23bde8e47f9040537d26a881 | [
"Apache-2.0"
] | null | null | null | camel-application/src/main/java/com/JavaDsl/camel_application/AppRoute.java | dhairya0704/ApacheCamelProjects | 80eeec40f4ddf5cc23bde8e47f9040537d26a881 | [
"Apache-2.0"
] | null | null | null | camel-application/src/main/java/com/JavaDsl/camel_application/AppRoute.java | dhairya0704/ApacheCamelProjects | 80eeec40f4ddf5cc23bde8e47f9040537d26a881 | [
"Apache-2.0"
] | null | null | null | 18.666667 | 45 | 0.760714 | 11,382 | package com.JavaDsl.camel_application;
import org.apache.camel.builder.RouteBuilder;
public class AppRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
// TODO Auto-generated method stub
System.out.println("Hello Camel Java DSL");
}
}
|
3e1ada4e8cf6926a69dc1571628d978d7a835e66 | 3,547 | java | Java | presto-hive/src/main/java/com/facebook/presto/hive/NoAccessControl.java | nitinkadam33/Presto | 312c17ea8011837dbb0c5389295425afca378ef2 | [
"Apache-2.0"
] | 15 | 2016-09-21T03:03:41.000Z | 2019-07-31T07:05:54.000Z | presto-hive/src/main/java/com/facebook/presto/hive/NoAccessControl.java | nitinkadam33/Presto | 312c17ea8011837dbb0c5389295425afca378ef2 | [
"Apache-2.0"
] | 4 | 2020-01-31T18:15:07.000Z | 2022-02-26T00:46:53.000Z | presto-hive/src/main/java/com/facebook/presto/hive/NoAccessControl.java | nitinkadam33/Presto | 312c17ea8011837dbb0c5389295425afca378ef2 | [
"Apache-2.0"
] | 8 | 2016-12-21T03:49:52.000Z | 2020-06-17T06:51:12.000Z | 29.07377 | 111 | 0.733014 | 11,383 | /*
* 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.facebook.presto.hive;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.security.ConnectorAccessControl;
import com.facebook.presto.spi.security.Identity;
import javax.inject.Inject;
import static com.facebook.presto.spi.security.AccessDeniedException.denyAddColumn;
import static com.facebook.presto.spi.security.AccessDeniedException.denyDropTable;
import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameTable;
import static java.util.Objects.requireNonNull;
public class NoAccessControl
implements ConnectorAccessControl
{
private final boolean allowDropTable;
private final boolean allowRenameTable;
private final boolean allowAddColumn;
@Inject
public NoAccessControl(HiveClientConfig hiveClientConfig)
{
requireNonNull(hiveClientConfig, "hiveClientConfig is null");
allowDropTable = hiveClientConfig.getAllowDropTable();
allowRenameTable = hiveClientConfig.getAllowRenameTable();
allowAddColumn = hiveClientConfig.getAllowAddColumn();
}
@Override
public void checkCanCreateTable(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanDropTable(Identity identity, SchemaTableName tableName)
{
if (!allowDropTable) {
denyDropTable(tableName.toString());
}
}
@Override
public void checkCanRenameTable(Identity identity, SchemaTableName tableName, SchemaTableName newTableName)
{
if (!allowRenameTable) {
denyRenameTable(tableName.toString(), newTableName.toString());
}
}
@Override
public void checkCanAddColumn(Identity identity, SchemaTableName tableName)
{
if (!allowAddColumn) {
denyAddColumn(tableName.toString());
}
}
@Override
public void checkCanRenameColumn(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanSelectFromTable(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanInsertIntoTable(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanDeleteFromTable(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanCreateView(Identity identity, SchemaTableName viewName)
{
}
@Override
public void checkCanDropView(Identity identity, SchemaTableName viewName)
{
}
@Override
public void checkCanSelectFromView(Identity identity, SchemaTableName viewName)
{
}
@Override
public void checkCanCreateViewWithSelectFromTable(Identity identity, SchemaTableName tableName)
{
}
@Override
public void checkCanCreateViewWithSelectFromView(Identity identity, SchemaTableName viewName)
{
}
@Override
public void checkCanSetCatalogSessionProperty(Identity identity, String propertyName)
{
}
}
|
3e1ada812131012f821bcbaa213438161ab83a7d | 654 | java | Java | Spring_Full_CalismalarV2/src/main/java/com/Spring_Full_CalismalarV2/SpringConfig/IocConfig.java | bahadraksakal/Spring-And-MVC | e34bce66c298f6f17a41d0eb6f452257a365b810 | [
"Apache-2.0"
] | 2 | 2021-09-22T17:23:42.000Z | 2021-09-27T07:45:59.000Z | Spring_Full_CalismalarV2/src/main/java/com/Spring_Full_CalismalarV2/SpringConfig/IocConfig.java | bahadraksakal/Spring_and_MVC | e34bce66c298f6f17a41d0eb6f452257a365b810 | [
"Apache-2.0"
] | null | null | null | Spring_Full_CalismalarV2/src/main/java/com/Spring_Full_CalismalarV2/SpringConfig/IocConfig.java | bahadraksakal/Spring_and_MVC | e34bce66c298f6f17a41d0eb6f452257a365b810 | [
"Apache-2.0"
] | null | null | null | 25.153846 | 80 | 0.752294 | 11,384 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.Spring_Full_CalismalarV2.SpringConfig;
/**
*
* @author bahad
*/
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
*
* @author bahad
*/
//xml ile bağımızı tamamen koparacak bir class hazırlıyoruzç
@Configuration
@ComponentScan("com.Spring_Full_CalismalarV2")
public class IocConfig {
}
|
3e1adc1cbeccca3c664c018850e6fff5186288c4 | 1,332 | java | Java | VCApp/src/com/github/rod1andrade/render/Render.java | Rod1Andrade/VacuumCleaner | d76bbca434dc7082e31b7a6f70bc4dd522268570 | [
"MIT"
] | null | null | null | VCApp/src/com/github/rod1andrade/render/Render.java | Rod1Andrade/VacuumCleaner | d76bbca434dc7082e31b7a6f70bc4dd522268570 | [
"MIT"
] | 2 | 2021-12-10T18:38:03.000Z | 2021-12-10T20:38:03.000Z | VCApp/src/com/github/rod1andrade/render/Render.java | Rod1Andrade/VacuumCleaner | d76bbca434dc7082e31b7a6f70bc4dd522268570 | [
"MIT"
] | null | null | null | 26.64 | 98 | 0.659159 | 11,385 | package com.github.rod1andrade.render;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rodrigo Andraade
*/
public final class Render {
private final List<com.github.rod1andrade.entities.RenderEntity> entities = new ArrayList<>();
private final int width;
private final int height;
public Render(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Adiciona entidade que vai ser renderizada.
* A ordem na qual e adicionada define a ordem de renderizacao.
*
* @param renderEntity Entity.
*/
public void addEntityToRender(com.github.rod1andrade.entities.RenderEntity renderEntity) {
entities.add(renderEntity);
}
public void clear(Graphics graphics) {
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0, width, height);
}
public void render(Graphics graphics) {
for (com.github.rod1andrade.entities.RenderEntity renderEntity : entities) {
if(renderEntity.isVisible())
renderEntity.render(graphics);
}
}
public synchronized void update(float deltaTime) {
for (com.github.rod1andrade.entities.RenderEntity renderEntity : entities) {
renderEntity.update(deltaTime);
}
}
}
|
3e1adc53cd92ede8d8d63dea30d516057a4f0f27 | 11,563 | java | Java | my/Tools.java | IronMan1994/CGA-MWS-algorithm | 09c420954b0fa10a24db3adb833008a93c04b4ff | [
"Apache-2.0"
] | 1 | 2020-09-01T08:57:53.000Z | 2020-09-01T08:57:53.000Z | my/Tools.java | IronMan1994/CGA-MWS-algorithm | 09c420954b0fa10a24db3adb833008a93c04b4ff | [
"Apache-2.0"
] | null | null | null | my/Tools.java | IronMan1994/CGA-MWS-algorithm | 09c420954b0fa10a24db3adb833008a93c04b4ff | [
"Apache-2.0"
] | null | null | null | 26.828306 | 129 | 0.579694 | 11,386 | package my;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class Tools
{
public Tools()
{
}
//initData
public void initData(String[] paths, List<Data_Array> data_Array, int n, String[] name, int[] name_index) throws Exception
{
File f = new File("");
for(int i = 0; i < paths.length;i++)
{
File f1 = new File(this.getClass().getResource("/" + paths[i]).getPath());
f = f1;
List<float[]> temp_data_array = new ArrayList<float[]>();
readData(f, temp_data_array, n);
Data_Array a = new Data_Array(temp_data_array);
data_Array.add(a);
}
//读取基因名字
Reader reader = new FileReader(f);
BufferedReader bfr = new BufferedReader(reader);
String temp;
try
{
while((temp = bfr.readLine()) != null)
{
String[] ppp = temp.split("\t");
if(ppp.length == n + 1)
{
for(int i = 0; i < n; i++)
{
name[i] = ppp[i + 1];
}
break;
}
}
for(int i = 0; i < n; i++)
{
name_index[i] = i;
}
} catch (Exception e)
{
e.printStackTrace();
}
bfr.close();
reader.close();
}
//Read data
public void readData(File f, List<float[]> B, int n) throws Exception
{
InputStream fis = new FileInputStream(f);
Reader isr = new InputStreamReader(fis);
BufferedReader bfr = new BufferedReader(isr);
String tempstr;
int line = 1;
try
{
while((tempstr = bfr.readLine()) != null)
{
//分隔符
String[] ppp = tempstr.split("\t");
if(ppp.length == n + 1)
{
if(line == 2)
{
float[] temp = new float[n];
for(int i = 0; i < n; i++)
{
//提取数字
temp[i] = Float.valueOf(ppp[i + 1].trim());
}
B.add(temp);
}
}
line = 2;
}
}
catch (Exception e)
{
e.printStackTrace();
}
bfr.close();
fis.close();
}
//Find the optimal gene set after the total number of iterations
public SpeciesIndividual_index searchMax(List<SpeciesIndividual_index> maxgene)
{
SpeciesIndividual_index temp = new SpeciesIndividual_index();
double maxfitness = 0.0;
double tempfitness = 0.0;
int maxIndex = 0;
for(int i = 0; i < maxgene.size(); i++)
{
if(maxfitness < maxgene.get(i).speciesIndividual.fitness[0])
{
tempfitness = maxgene.get(i).speciesIndividual.fitness[0];
maxfitness = tempfitness;
maxIndex = i;
}
}
temp = maxgene.get(maxIndex);
return temp;
}
//Sorting of data in total traversal times (bubble algorithm)
public void sort_list_maxgene(List<SpeciesIndividual_index> temppop)
{
SpeciesIndividual_index temp = new SpeciesIndividual_index();
int size = temppop.size();
for(int i = 0 ; i < size-1; i ++)
{
for(int j = 0 ;j < size-1-i ; j++)
{
//<表示把最小值移到最后
if(temppop.get(j).speciesIndividual.fitness[0] < temppop.get(j+1).speciesIndividual.fitness[0]) //交换两数位置
{
temp = temppop.get(j);
temppop.set(j, temppop.get(j+1));
temppop.set(j+1, temp);
}
}
}
}
//Population fitness ranking (bubble algorithm)
public void sort_pop_list(List<SpeciesIndividual> pop)
{
SpeciesIndividual temp = new SpeciesIndividual();
int size = pop.size();
for(int i = 0 ; i < size-1; i ++)
{
for(int j = 0 ;j < size-1-i ; j++)
{
//<表示把最小值移到最后
if(pop.get(j).fitness[0] < pop.get(j+1).fitness[0]) //交换两数位置
{
temp = pop.get(j);
pop.set(j, pop.get(j+1));
pop.set(j+1, temp);
}
}
}
}
//The function of roulette probability calculation
public double sum_fitness(int fuzhiNum, int size, List<SpeciesIndividual> pop, int geneSize)
{
double count = 0.0;
for(int i = fuzhiNum; i < geneSize; i++)
{
count += pop.get(i).fitness[0];
}
return count;
}
//Find the best and worst individuals of the current population
public int[] getBest_Bad_SpeciesIndividual_index(List<SpeciesIndividual> pop)
{
int[] result = new int[2];
int max = 0;
int min = 0;
for(int i = 0; i < pop.size(); i++)
{
if(pop.get(max).fitness[0] < pop.get(i).fitness[0]){
max = i;
}
if(pop.get(min).fitness[0] > pop.get(i).fitness[0]){
min = i;
}
}
result[0] = max;
result[1] = min;
return result;
}
//Write the population information for each iteration
public void writeFileStep(List<SpeciesIndividual> temp, int count) throws Exception
{
File f = new File("");
String pathname = f.getCanonicalPath();
File ff = new File(pathname + "/src/result_Step.txt");
if(count == 0)
{
ff.delete();
ff.createNewFile();
}
OutputStream os = new FileOutputStream(ff,true);
try
{
os.write(("第" + count + "代、种群信息:").getBytes());
os.write(("\r\n").getBytes());
for(int i =0; i < temp.size(); i++)
{
for(int j = 0; j < temp.get(i).chromosome.length; j++)
{
os.write((String.format("%-8s", temp.get(i).chromosome[j])).getBytes());
}
for(int j = 0; j < temp.get(i).fitness.length - 1;j++)
{
os.write((String.format("%-12s", temp.get(i).fitness[j])).getBytes());
}
os.write("\r\n".getBytes());
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
os.close();
}
}
//Output the optimal gene set found
public void writeFileMax(SpeciesIndividual_index temp, String[] path, String[] name) throws Exception
{
File f = new File("");
String pathname = f.getCanonicalPath();
File ff = new File(pathname + "/src/results/result_MAX.txt");
OutputStream os = new FileOutputStream(ff, true);
try
{
os.write(path[0].getBytes());
os.write("\r\n".getBytes());
os.write(("第" + temp.index + "次遗传算法、" + "最优基因组:").getBytes());
for(int i = 0; i < temp.speciesIndividual.chromosome.length; i++)
{
os.write((String.format("%-10s", name[temp.speciesIndividual.chromosome[i]])).getBytes());
}
os.write("\r\n".getBytes());
os.write(("样本分别适应度:").getBytes());
for(int i = 0; i < temp.speciesIndividual.fitness.length - 1; i++)
{
os.write((String.format("%-12s", temp.speciesIndividual.fitness[i + 1])).getBytes());
}
os.write("\r\n".getBytes());
os.write(("最大适应度:" + temp.speciesIndividual.fitness[0]).getBytes());
os.write("\r\n".getBytes());
os.write("\r\n".getBytes());
System.out.println("输出成功!");
} catch (Exception e){
e.printStackTrace();
}
os.close();
}
//Output the total iteration result
public void writeFile(List<SpeciesIndividual_index> temp, List<SpeciesIndividual_index> maxgene, String[] name)throws Exception
{
sort_list_maxgene(maxgene);
File f = new File("");
String pathname = f.getCanonicalPath();
File ff = new File(pathname + "/src/result.txt");
OutputStream os = new FileOutputStream(ff);
//OutputStreamWriter os1 = new OutputStreamWriter(os);
//BufferedWriter bfw = new BufferedWriter(os1);
try
{
for(int i =0; i < maxgene.size(); i++)
{
os.write(String.format("第" + "%-2d" + "次遗传算法、" + "最优基因组:",i + 1).getBytes());
for(int j = 0; j < temp.get(i).speciesIndividual.chromosome.length; j++)
{
os.write((String.format("%-10s", name[temp.get(i).speciesIndividual.chromosome[j]])).getBytes());
}
os.write("\r\n".getBytes());
os.write("样本分别适应度:".getBytes());
for(int j = 0; j < temp.get(i).speciesIndividual.fitness.length - 1;j++)
{
os.write((String.format("%-12s", temp.get(i).speciesIndividual.fitness[j + 1])).getBytes());
}
os.write("\r\n".getBytes());
os.write("样本总适应度:".getBytes());
os.write((temp.get(i).speciesIndividual.fitness[0] +"").getBytes());
os.write("\r\n".getBytes());
os.write("\r\n".getBytes());
}
System.out.println("输出成功!");
} catch (Exception e){
e.printStackTrace();
}
//bfw.close();
os.close();
}
//Record operation log
public void writeResult(String file_name, List temp, String methond, int k) throws IOException
{
File f = new File("");
String pathname = f.getCanonicalPath();
File ff = new File(pathname + "/src/results/Results.txt");
OutputStream os = new FileOutputStream(ff, true);
try{
os.write((file_name + " methond_name = " + methond + " K = " + k + ":").getBytes());
os.write("\r\n".getBytes());
for(int i = 0; i < temp.size(); i++){
os.write(String.format("%-12s", " ").getBytes());
os.write((String.valueOf(temp.get(i))).getBytes());
os.write("\r\n".getBytes());
}
os.write("\r\n\r\n\r\n".getBytes());
}
catch (Exception e){
e.printStackTrace();
}
finally{
os.close();
}
}
//Deep copy list
public void copy_list(List<SpeciesIndividual> a, List<SpeciesIndividual> b)
{
b.clear();
for(int i = 0; i < a.size(); i++)
{
SpeciesIndividual temp = copy_SpeciesIndividual(a.get(i));
b.add(temp);
}
}
//Copy and add individuals
public void copy_add_list(List<SpeciesIndividual> a, List<SpeciesIndividual> b)
{
for(int i = 0; i < a.size(); i++)
{
SpeciesIndividual temp = copy_SpeciesIndividual(a.get(i));
b.add(temp);
}
}
//Deep copy individual
public SpeciesIndividual copy_SpeciesIndividual(SpeciesIndividual from)
{
int[] chromosome = new int[from.chromosome.length];
double[] fitness = new double[from.fitness.length];
for(int i = 0; i < chromosome.length; i++){
chromosome[i] = from.chromosome[i];
}
for(int i = 0; i < fitness.length; i++){
fitness[i] = from.fitness[i];
}
SpeciesIndividual result = new SpeciesIndividual(chromosome, fitness);
return result;
}
//Convert the list into a one-dimensional array
public int[] changeListToArray(List<Integer> list)
{
int[] temp = new int[list.size()];
for(int i = 0; i < list.size(); i++)
{
temp[i] = list.get(i);
}
return temp;
}
//Print input data matrix
public void printSample(List<Data_Array> A)
{
//打印所有样本数据
for(int i = 0; i < A.size(); i++)
{
Data_Array a = A.get(i);
for(int j = 0; j < a.A.size(); j++)
{
float[] temp = a.A.get(j);
for(int k1 = 0; k1 < temp.length; k1++)
{
System.out.print(temp[k1] + "\t");
}
System.out.println();
}
System.out.println("\n\n\n");
}
}
//Print one dimensional array(double)
public void printArray(double[] temp)
{
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i] + "\t");
}
}
//Print population information quickly
public void printPOP(List<SpeciesIndividual> tempPOP)
{
for(int i = 0; i < tempPOP.size(); i++)
{
for(int j = 0; j < tempPOP.get(i).chromosome.length; j++)
{
System.out.print(String.format("%-12s", tempPOP.get(i).chromosome[j]));
}
for(int j = 0; j < tempPOP.get(i).fitness.length; j++)
{
System.out.print(String.format("%-12s", tempPOP.get(i).fitness[j]));
}
System.out.println();
}
}
}
|
3e1adcba9cd22b2bcad25ca3e86532e406abb168 | 1,404 | java | Java | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/FieldConversionException.java | YuanWenqing/protoframework | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"MIT"
] | 1 | 2021-03-12T09:15:12.000Z | 2021-03-12T09:15:12.000Z | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/FieldConversionException.java | YuanWenqing/protoframework | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"MIT"
] | 14 | 2019-07-20T09:20:54.000Z | 2020-08-17T01:52:28.000Z | protobuf4j-orm/src/main/java/protobuf4j/orm/converter/FieldConversionException.java | YuanWenqing/protobuf4j | 618c3e9121b0af823cb420d6a64a6950d9862c01 | [
"Apache-2.0"
] | null | null | null | 25.071429 | 99 | 0.680199 | 11,387 | package protobuf4j.orm.converter;
import com.google.protobuf.Descriptors;
import org.springframework.dao.TypeMismatchDataAccessException;
public class FieldConversionException extends TypeMismatchDataAccessException {
/**
* generic construction
*
* @param msg
*/
public FieldConversionException(String msg) {
super(msg);
}
/**
* generic construction
*
* @param msg
*/
public FieldConversionException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* construction when failing to convert
*
* @param javaType
* @param fieldValue
* @param sqlValueType
*/
public FieldConversionException(Descriptors.FieldDescriptor.JavaType javaType, Object fieldValue,
Class<?> sqlValueType) {
super("fail to convert to sql value, javaType=" + javaType + ", fieldValue=" +
toString(fieldValue) + ", sqlValueType=" + sqlValueType.getName());
}
/**
* construction when failing to parse
*
* @param sqlValue
* @param javaType
*/
public FieldConversionException(Descriptors.FieldDescriptor.JavaType javaType, Object sqlValue) {
super("fail to parse sql value, sqlValue=" + toString(sqlValue) + ", javaType=" + javaType);
}
public static String toString(Object value) {
if (value == null) {
return "null";
}
return String.format("`%s`[%s]", value, value.getClass().getName());
}
}
|
3e1adda9a1d2a89e4a7be3bbde438ff984a96b7d | 5,861 | java | Java | src/main/java/org/apache/commons/lang3/ClassPathUtils.java | oneiros-de/commons-lang | 5200ca1fe99d0fb8e761bfef751ac0c5049e7346 | [
"Apache-2.0"
] | 2,399 | 2015-01-01T15:48:36.000Z | 2022-03-30T17:54:06.000Z | src/main/java/org/apache/commons/lang3/ClassPathUtils.java | oneiros-de/commons-lang | 5200ca1fe99d0fb8e761bfef751ac0c5049e7346 | [
"Apache-2.0"
] | 754 | 2015-01-20T00:34:30.000Z | 2022-03-26T17:52:48.000Z | src/main/java/org/apache/commons/lang3/ClassPathUtils.java | oneiros-de/commons-lang | 5200ca1fe99d0fb8e761bfef751ac0c5049e7346 | [
"Apache-2.0"
] | 1,822 | 2015-01-06T14:48:35.000Z | 2022-03-26T10:52:54.000Z | 45.084615 | 152 | 0.698516 | 11,388 | /*
* 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.commons.lang3;
/**
* Operations regarding the classpath.
*
* <p>The methods of this class do not allow {@code null} inputs.</p>
*
* @since 3.3
*/
//@Immutable
public class ClassPathUtils {
/**
* <p>{@code ClassPathUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code ClassPathUtils.toFullyQualifiedName(MyClass.class, "MyClass.properties");}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public ClassPathUtils() {
}
/**
* Returns the fully qualified name for the resource with name {@code resourceName} relative to the given context.
*
* <p>Note that this method does not check whether the resource actually exists.
* It only constructs the name.
* Null inputs are not allowed.</p>
*
* <pre>
* ClassPathUtils.toFullyQualifiedName(StringUtils.class, "StringUtils.properties") = "org.apache.commons.lang3.StringUtils.properties"
* </pre>
*
* @param context The context for constructing the name.
* @param resourceName the resource name to construct the fully qualified name for.
* @return the fully qualified name of the resource with name {@code resourceName}.
* @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
*/
public static String toFullyQualifiedName(final Class<?> context, final String resourceName) {
Validate.notNull(context, "context" );
Validate.notNull(resourceName, "resourceName");
return toFullyQualifiedName(context.getPackage(), resourceName);
}
/**
* Returns the fully qualified name for the resource with name {@code resourceName} relative to the given context.
*
* <p>Note that this method does not check whether the resource actually exists.
* It only constructs the name.
* Null inputs are not allowed.</p>
*
* <pre>
* ClassPathUtils.toFullyQualifiedName(StringUtils.class.getPackage(), "StringUtils.properties") = "org.apache.commons.lang3.StringUtils.properties"
* </pre>
*
* @param context The context for constructing the name.
* @param resourceName the resource name to construct the fully qualified name for.
* @return the fully qualified name of the resource with name {@code resourceName}.
* @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
*/
public static String toFullyQualifiedName(final Package context, final String resourceName) {
Validate.notNull(context, "context" );
Validate.notNull(resourceName, "resourceName");
return context.getName() + "." + resourceName;
}
/**
* Returns the fully qualified path for the resource with name {@code resourceName} relative to the given context.
*
* <p>Note that this method does not check whether the resource actually exists.
* It only constructs the path.
* Null inputs are not allowed.</p>
*
* <pre>
* ClassPathUtils.toFullyQualifiedPath(StringUtils.class, "StringUtils.properties") = "org/apache/commons/lang3/StringUtils.properties"
* </pre>
*
* @param context The context for constructing the path.
* @param resourceName the resource name to construct the fully qualified path for.
* @return the fully qualified path of the resource with name {@code resourceName}.
* @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
*/
public static String toFullyQualifiedPath(final Class<?> context, final String resourceName) {
Validate.notNull(context, "context" );
Validate.notNull(resourceName, "resourceName");
return toFullyQualifiedPath(context.getPackage(), resourceName);
}
/**
* Returns the fully qualified path for the resource with name {@code resourceName} relative to the given context.
*
* <p>Note that this method does not check whether the resource actually exists.
* It only constructs the path.
* Null inputs are not allowed.</p>
*
* <pre>
* ClassPathUtils.toFullyQualifiedPath(StringUtils.class.getPackage(), "StringUtils.properties") = "org/apache/commons/lang3/StringUtils.properties"
* </pre>
*
* @param context The context for constructing the path.
* @param resourceName the resource name to construct the fully qualified path for.
* @return the fully qualified path of the resource with name {@code resourceName}.
* @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
*/
public static String toFullyQualifiedPath(final Package context, final String resourceName) {
Validate.notNull(context, "context" );
Validate.notNull(resourceName, "resourceName");
return context.getName().replace('.', '/') + "/" + resourceName;
}
}
|
3e1ade258a7968692508aa998691183301d660c1 | 1,467 | java | Java | service-a/src/main/java/org/spring/boot/distributed/tracing/instances/service/a/commons/filtering/ResponseTracingFilter.java | ololx/spring-boot-distributed-tracing-instances | 4f5587172f5a5b60b70c0b5473242df9e16e487f | [
"Unlicense"
] | 1 | 2021-08-16T12:50:36.000Z | 2021-08-16T12:50:36.000Z | service-a/src/main/java/org/spring/boot/distributed/tracing/instances/service/a/commons/filtering/ResponseTracingFilter.java | ololx/spring-boot-distributed-tracing-instances | 4f5587172f5a5b60b70c0b5473242df9e16e487f | [
"Unlicense"
] | null | null | null | service-a/src/main/java/org/spring/boot/distributed/tracing/instances/service/a/commons/filtering/ResponseTracingFilter.java | ololx/spring-boot-distributed-tracing-instances | 4f5587172f5a5b60b70c0b5473242df9e16e487f | [
"Unlicense"
] | null | null | null | 31.212766 | 113 | 0.658487 | 11,389 | package org.spring.boot.distributed.tracing.instances.service.a.commons.filtering;
import io.opentracing.Span;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* The type Response tracing filter.
*
* @author Alexander A. Kropotin
* @project service -a
* @created 2021 -08-08 20:03 <p>
*/
@Slf4j
@Component("ResponseTracingFilter")
public class ResponseTracingFilter extends TracingFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
Span span = this.getSpan();
String spanId = span.context().toSpanId();
String traceId = null;
if ((traceId = MDC.get(TRACE_ID)) == null) {
traceId = span.context().toTraceId();
}
response.setHeader(TRACE_ID, traceId);
response.setHeader(SPAN_ID, spanId);
try {
log.trace("Finish the process response with {} : {} && {} : {}", TRACE_ID, traceId, SPAN_ID, spanId);
filterChain.doFilter(request, response);
} finally {
MDC.clear();
}
}
} |
3e1adf84f870d23fa29ae3b92bf466a76983142d | 1,371 | java | Java | rock-portal/src/main/java/org/flybird/rock/portal/controller/OmsPortalOrderReturnApplyController.java | dlxqlig/rock | 2866f62f7ad60309f4f455015cadab3da4199cd0 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:28:00.000Z | 2020-01-22T14:28:00.000Z | rock-portal/src/main/java/org/flybird/rock/portal/controller/OmsPortalOrderReturnApplyController.java | dlxqlig/rock | 2866f62f7ad60309f4f455015cadab3da4199cd0 | [
"Apache-2.0"
] | null | null | null | rock-portal/src/main/java/org/flybird/rock/portal/controller/OmsPortalOrderReturnApplyController.java | dlxqlig/rock | 2866f62f7ad60309f4f455015cadab3da4199cd0 | [
"Apache-2.0"
] | null | null | null | 37.054054 | 83 | 0.786287 | 11,390 | package org.flybird.rock.portal.controller;
import org.flybird.rock.common.api.CommonResult;
import org.flybird.rock.portal.domain.OmsOrderReturnApplyParam;
import org.flybird.rock.portal.service.OmsPortalOrderReturnApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 申请退货管理Controller
* Created by flybird on 2018/10/17.
*/
@Controller
@Api(tags = "OmsPortalOrderReturnApplyController", description = "申请退货管理")
@RequestMapping("/returnApply")
public class OmsPortalOrderReturnApplyController {
@Autowired
private OmsPortalOrderReturnApplyService returnApplyService;
@ApiOperation("申请退货")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody OmsOrderReturnApplyParam returnApply) {
int count = returnApplyService.create(returnApply);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
}
|
3e1adff5f8bf68fa7093767c4eef863ddb7aacae | 1,056 | java | Java | medium/problem152/Solution.java | cutoutsy/leetcode | 0734f1060a0340370b8234e8072d70c10d4306d9 | [
"Apache-2.0"
] | 1 | 2018-02-25T03:45:04.000Z | 2018-02-25T03:45:04.000Z | medium/problem152/Solution.java | cutoutsy/leetcode | 0734f1060a0340370b8234e8072d70c10d4306d9 | [
"Apache-2.0"
] | null | null | null | medium/problem152/Solution.java | cutoutsy/leetcode | 0734f1060a0340370b8234e8072d70c10d4306d9 | [
"Apache-2.0"
] | null | null | null | 37.714286 | 79 | 0.493371 | 11,391 | public class Solution {
public int maxProduct(int[] nums) {
if (nums.length == 0 || nums == null) return 0;
int ans = nums[0];
int[] maxCache = new int[nums.length];
int[] minCache = new int[nums.length];
maxCache[0] = minCache[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
maxCache[i] = minCache[i] = nums[i];
if (nums[i] > 0) {
maxCache[i] = Math.max(maxCache[i], maxCache[i - 1] * nums[i]);
minCache[i] = Math.min(minCache[i], minCache[i - 1] * nums[i]);
} else if(nums[i] < 0) {
maxCache[i] = Math.max(maxCache[i], minCache[i - 1] * nums[i]);
minCache[i] = Math.min(minCache[i], maxCache[i - 1] * nums[i]);
}
ans = Math.max(ans, maxCache[i]);
}
return ans;
}
public static void main(String[] args) {
int[] nums = {2, 3, -2, 4};
Solution solution = new Solution();
System.out.println(solution.maxProduct(nums));
}
}
|
3e1ae077b40ddca412c36b0183ffbae741f90550 | 2,287 | java | Java | app/src/main/java/io/github/mayunfei/simple/SmallScreenTouch.java | MaYunFei/TXLiveDemo | 194c9cf8d9811d25a32a67ab0d5d41790670d1b1 | [
"Apache-2.0"
] | 1 | 2018-07-09T02:53:49.000Z | 2018-07-09T02:53:49.000Z | app/src/main/java/io/github/mayunfei/simple/SmallScreenTouch.java | MaYunFei/TXLiveDemo | 194c9cf8d9811d25a32a67ab0d5d41790670d1b1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/github/mayunfei/simple/SmallScreenTouch.java | MaYunFei/TXLiveDemo | 194c9cf8d9811d25a32a67ab0d5d41790670d1b1 | [
"Apache-2.0"
] | 1 | 2019-07-10T07:09:09.000Z | 2019-07-10T07:09:09.000Z | 30.493333 | 92 | 0.544381 | 11,392 | package io.github.mayunfei.simple;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Created by mayunfei on 17-9-7.
*/
public class SmallScreenTouch implements View.OnTouchListener {
private int mDownX, mDownY;
private int mMarginLeft, mMarginTop;
private int _xDelta, _yDelta;
private View smallView;
public SmallScreenTouch(View smallView, int marginLeft, int marginTop) {
super();
mMarginLeft = marginLeft;
mMarginTop = marginTop;
this.smallView = smallView;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = X;
mDownY = Y;
FrameLayout.LayoutParams lParams = (FrameLayout.LayoutParams) smallView
.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
if (Math.abs(mDownY - Y) < 5 && Math.abs(mDownX - X) < 5) {
return false;
} else {
return true;
}
case MotionEvent.ACTION_MOVE:
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) smallView
.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
if (layoutParams.leftMargin >= mMarginLeft) {
layoutParams.leftMargin = mMarginLeft;
}
if (layoutParams.topMargin >= mMarginTop) {
layoutParams.topMargin = mMarginTop;
}
if (layoutParams.leftMargin <= 0) {
layoutParams.leftMargin = 0;
}
if (layoutParams.topMargin <= 0) {
layoutParams.topMargin = 0;
}
smallView.setLayoutParams(layoutParams);
}
return false;
}
}
|
3e1ae09288614c6269f402e89134cb8e51496be3 | 1,504 | java | Java | src/main/java/sayfog/electricool/powersystem/AbstractComponentBlock.java | AlistairSymonds/ElectricoolEngineering | f1d13d5caa8a717ace2bd8dd64fcad9c23cf09ec | [
"MIT"
] | null | null | null | src/main/java/sayfog/electricool/powersystem/AbstractComponentBlock.java | AlistairSymonds/ElectricoolEngineering | f1d13d5caa8a717ace2bd8dd64fcad9c23cf09ec | [
"MIT"
] | null | null | null | src/main/java/sayfog/electricool/powersystem/AbstractComponentBlock.java | AlistairSymonds/ElectricoolEngineering | f1d13d5caa8a717ace2bd8dd64fcad9c23cf09ec | [
"MIT"
] | null | null | null | 33.422222 | 121 | 0.757979 | 11,393 | package sayfog.electricool.powersystem;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public abstract class AbstractComponentBlock extends AbstractNetworkMemberBlock {
public static final PropertyDirection FACING = PropertyDirection.create("facing");
protected AbstractComponentBlock(Material materialIn) {
super(materialIn);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
EnumFacing dir = EnumFacing.getFacingFromVector(
(float)placer.getLookVec().xCoord,
(float)placer.getLookVec().yCoord,
(float)placer.getLookVec().zCoord);
world.setBlockState(pos, state.withProperty(FACING, dir), 2);
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(FACING, EnumFacing.getFront(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(FACING).getIndex();
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, FACING);
}
}
|
3e1ae249e87fd0554b66d179299ea522952292bd | 7,434 | java | Java | RecipeOrganizer/app/src/main/java/com/example/myfirstapp/main/Entities/User.java | AmirAlleyne/RecipeOrganizerApp | b3fa04003fcb697b7e2d9a9da3d25781b1f8c3fe | [
"MIT"
] | null | null | null | RecipeOrganizer/app/src/main/java/com/example/myfirstapp/main/Entities/User.java | AmirAlleyne/RecipeOrganizerApp | b3fa04003fcb697b7e2d9a9da3d25781b1f8c3fe | [
"MIT"
] | null | null | null | RecipeOrganizer/app/src/main/java/com/example/myfirstapp/main/Entities/User.java | AmirAlleyne/RecipeOrganizerApp | b3fa04003fcb697b7e2d9a9da3d25781b1f8c3fe | [
"MIT"
] | null | null | null | 30.719008 | 138 | 0.639629 | 11,394 | package com.example.myfirstapp.main.Entities;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class is the User Entity. It possesses 7 attributes:
* •displayName- the name the user chooses to make public(String)
* •age - the age of the user (int)
* •password - a collection of characters used to gain access to the user's account (String)
* •username - the user's unique identifier; used in conjunction with password to login. Sometimes called ID(String)
* •biography- a description of the user(String)
* •interests- a list of genres(Strings) the user is interested in (ArrayList<String>)
* •SavedRecipes - a list of the recipes the user has saved (ArrayList<Recipe>)
* •UserReviews - a list of the reviews the user has made (ArrayList<Review>)
*/
public class User {
private String displayName;
private int age;
private String password;
private String username;
private String biography;
private ArrayList<String> interests;
private ArrayList<Recipe> SavedRecipes = new ArrayList<>();
private HashMap<Integer, Review> UserReviews = new HashMap<>();
private HashMap<String, Double> GenreWeights = new HashMap<>();
public User() {
this.interests = new ArrayList<>();
}
/**
* Constructor for User
*/
public User(String username, String pws, String name, int age, String bio, ArrayList<String> interests, ArrayList<String> genreList) {
this.displayName = name;
this.age = age;
this.password = pws;
this.username = username;
this.biography = bio;
this.interests = interests;
initializeGenreWeights(this.interests, genreList);
}
/* Updates GenreWeights to match interests */
public void initializeGenreWeights(ArrayList<String> interests, ArrayList<String> genreList) {
for (String interest : interests) {
if (!this.GenreWeights.containsKey(interest)) {
this.GenreWeights.put(interest, 0.70);
}
}
for (String genre : genreList) {
if (!this.GenreWeights.containsKey(genre)) {
this.GenreWeights.put(genre, 0.0);
}
}
}
/* Updates GenreWeights to match interests */
private void updateGenreWeights(ArrayList<String> interests) {
for (String interest : interests) {
this.GenreWeights.put(interest, (this.GenreWeights.get(interest) + 0.70));
}
}
private void deleteGenreWeights(ArrayList<String> deleted) {
for (String delete : deleted) {
this.GenreWeights.put(delete, (this.GenreWeights.get(delete) - 0.70));
}
}
public void updateGenreWeight(String genre, Double weight) {
this.GenreWeights.put(genre, weight);
}
/* Updates GenreWeights when a recipe is saved */
private void updateGenreWeights(Recipe recipe) {
ArrayList<String> recipeGenre = recipe.getGenre();
for (String genre : recipeGenre) {
if (!genre.equals("All") && !genre.equals("Meal") && !genre.equals("Appetizer")) {
if (!GenreWeights.containsKey(genre)) {
this.GenreWeights.put(genre, 0.05);
} else {
if (GenreWeights.get(genre) <= 0.95) {
GenreWeights.put(genre, GenreWeights.get(genre) + 0.05);
}
}
} // make sure that GenreWeights.get(genre) is not greater than 1.0
}
}
/* Updates GenreWeights when an interest is removed */
private void updateGenreWeights(String genre) {
this.GenreWeights.put(genre, 0.0);
}
public void updateGenreWeightsTest5(String genre) {
this.GenreWeights.put(genre, 0.5);
}
public void updateGenreWeightsTest3(String genre) {
this.GenreWeights.put(genre, 0.3);
}
public void updateGenreWeightsTest2(String genre) {
this.GenreWeights.put(genre, 0.2);
}
public void updateGenreWeightsTest1(String genre) {
this.GenreWeights.put(genre, 0.1);
}
/**
* Getter Methods for User:
* •getDisplayName - returns displayname
* •getAge - returns age
* •getPassword - returns password
* •getUsername - returns username
* •getBiography - returns biography
* •getInterests - returns interests
* •getSavedRecipes - returns SavedRecipes
* •getUserReviews - returns UserReviews
*/
public String getDisplayName() {
return displayName;
}
public int getAge() {
return age;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public String getBiography() {
return biography;
}
public ArrayList<String> getInterests() {
return interests;
}
public ArrayList<Recipe> getSavedRecipes() {
return SavedRecipes;
}
public HashMap<Integer, Recipe> getSavedRecipesHash() {
HashMap<Integer, Recipe> h = new HashMap<>();
for (Recipe recipe : SavedRecipes) {
h.put(recipe.getID(), recipe);
}
return h;
}
public HashMap<Integer, Review> getUserReviews() {
return UserReviews;
}
public HashMap<String, Double> getGenreWeights() {
return GenreWeights;
}
/**
* Setter Methods for User:
* •setDisplayName - accepts displayname attribute for a User
* •setAge - accepts age attribute for a User
* •setPassword - accepts password attribute for a User
* •setUsername - accepts username attribute for a User
* •setBiography - accepts biography attribute for a User
* •addInterests - adds an interest to the given User's interests
* •addSavedRecipes - adds a Recipe to the given User's SavedRecipes
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setAge(int age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setBiography(String biography) {
this.biography = biography;
}
public void setInterests(ArrayList<String> s) {
this.interests = s;
}
public void setInterests(ArrayList<String> previousInterests, ArrayList<String> interests) {
this.interests = interests;
deleteGenreWeights(previousInterests);
updateGenreWeights(interests);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void addSavedRecipes(Recipe recipe) {
SavedRecipes.add(recipe);
updateGenreWeights(recipe);
}
public void addSavedReviews(int recipeID, Review review) {
UserReviews.put(recipeID, review);
}
/**
* Generates a profile based on a given User's displayname, username, interests, biography and age
*
* @return ArrayList<Object> representing the profile that has been generated
*/
public UserInfo getProfile() {
return new UserInfo(username, password, displayName, age, biography, interests);
}
public void removeSavedRecipes(Recipe recipe) {
SavedRecipes.remove(recipe);
}
}
|
3e1ae2d0a024eb77aaea915e9e5c1a91c94001bd | 2,744 | java | Java | API/src/main/java/org/endeavourhealth/getFHIRRecordAPI/api/endpoints/CareRecordEndpoint.java | endeavourhealth-discovery/getFHIRRecordAPI | a06d730136fe939809fe21bb81a562f7465a70be | [
"Apache-2.0"
] | null | null | null | API/src/main/java/org/endeavourhealth/getFHIRRecordAPI/api/endpoints/CareRecordEndpoint.java | endeavourhealth-discovery/getFHIRRecordAPI | a06d730136fe939809fe21bb81a562f7465a70be | [
"Apache-2.0"
] | null | null | null | API/src/main/java/org/endeavourhealth/getFHIRRecordAPI/api/endpoints/CareRecordEndpoint.java | endeavourhealth-discovery/getFHIRRecordAPI | a06d730136fe939809fe21bb81a562f7465a70be | [
"Apache-2.0"
] | 1 | 2020-12-23T11:04:01.000Z | 2020-12-23T11:04:01.000Z | 27.168317 | 95 | 0.612609 | 11,395 | package org.endeavourhealth.getFHIRRecordAPI.api.endpoints;
import com.google.gson.Gson;
import models.Params;
import models.Request;
import org.endeavourhealth.getFHIRRecordAPI.common.dal.JDBCDAL;
import org.endeavourhealth.getFHIRRecordAPI.common.models.*;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.IOException;
import java.util.*;
import static javax.ws.rs.client.Entity.form;
@Path("patient")
public class CareRecordEndpoint {
private static final Logger LOG = LoggerFactory.getLogger(CareRecordEndpoint.class);
@GET
@Path("/$getstructuredrecord")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getFhir(@Context SecurityContext sc,
@QueryParam("patientId") Integer patientId
) throws Exception {
FhirApi api = getFhirApi();
JSONObject json = api.getFhirBundle(patientId,"0", "0");
return Response
.ok()
.entity(json)
.build();
}
public FhirApi getFhirApi(){
return new FhirApi();
}
@POST
@Path("/$getstructuredrecord")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postFhir(@Context HttpServletRequest httpServletRequest) throws Exception {
LOG.debug("getFhir POST");
String userId = httpServletRequest.getHeader("user_id");
String request = extractRequestBody(httpServletRequest);
Gson g = new Gson();
Params p = g.fromJson(request, Params.class);
Request requestModel = new Request();
requestModel.setParams(p);
requestModel.setHttpMethod("POST");
FhirApi api = new FhirApi();
try {
JSONObject result = (JSONObject) api.handleRequest(requestModel, userId);
return Response
.ok()
.entity(result)
.build();
} catch (Exception e) {
return Response
.serverError()
.entity(e.getMessage())
.build();
}
}
static String extractRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}
}
|
3e1ae421ec952fe83f778c11b4422ac189ba30a2 | 1,782 | java | Java | gravitee-am-service/src/main/java/io/gravitee/am/service/DomainService.java | paneq/graviteeio-access-management | e25034329bf510109f9e788583cb47e195a17bfa | [
"Apache-2.0"
] | null | null | null | gravitee-am-service/src/main/java/io/gravitee/am/service/DomainService.java | paneq/graviteeio-access-management | e25034329bf510109f9e788583cb47e195a17bfa | [
"Apache-2.0"
] | null | null | null | gravitee-am-service/src/main/java/io/gravitee/am/service/DomainService.java | paneq/graviteeio-access-management | e25034329bf510109f9e788583cb47e195a17bfa | [
"Apache-2.0"
] | null | null | null | 31.263158 | 75 | 0.752525 | 11,396 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.am.service;
import io.gravitee.am.model.Domain;
import io.gravitee.am.model.common.event.Event;
import io.gravitee.am.service.model.NewDomain;
import io.gravitee.am.service.model.PatchDomain;
import io.gravitee.am.service.model.UpdateDomain;
import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Single;
import java.util.Collection;
import java.util.Set;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public interface DomainService {
Maybe<Domain> findById(String id);
Single<Set<Domain>> findAll();
Single<Set<Domain>> findByIdIn(Collection<String> ids);
Single<Domain> create(NewDomain domain);
Single<Domain> update(String domainId, UpdateDomain domain);
Single<Domain> reload(String domainId, Event event);
Single<Domain> patch(String domainId, PatchDomain domain);
Single<Domain> setMasterDomain(String domainId, boolean isMaster);
Single<Domain> deleteLoginForm(String domainId);
Completable delete(String domain);
}
|
3e1ae479831ae782588e0e6e2959b39f397095b5 | 5,338 | java | Java | src/org/red5/server/net/rtmp/event/VideoData.java | bigbluebutton/red5 | d865b6db3efbcac450e1823107e85e4e9f792389 | [
"Apache-2.0"
] | 3 | 2017-05-06T02:24:12.000Z | 2020-04-30T22:47:16.000Z | src/org/red5/server/net/rtmp/event/VideoData.java | creativeprogramming/red5 | d865b6db3efbcac450e1823107e85e4e9f792389 | [
"Apache-2.0"
] | null | null | null | src/org/red5/server/net/rtmp/event/VideoData.java | creativeprogramming/red5 | d865b6db3efbcac450e1823107e85e4e9f792389 | [
"Apache-2.0"
] | 3 | 2017-05-06T02:24:14.000Z | 2020-05-29T01:37:19.000Z | 24.827907 | 105 | 0.69483 | 11,397 | /*
* RED5 Open Source Flash Server - http://code.google.com/p/red5/
*
* Copyright 2006-2012 by respective authors (see below). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.red5.server.net.rtmp.event;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import org.apache.mina.core.buffer.IoBuffer;
import org.red5.io.IoConstants;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.stream.IStreamData;
/**
* Video data event
*/
public class VideoData extends BaseEvent implements IoConstants, IStreamData<VideoData>, IStreamPacket {
private static final long serialVersionUID = 5538859593815804830L;
/**
* Videoframe type
*/
public static enum FrameType {
UNKNOWN, KEYFRAME, INTERFRAME, DISPOSABLE_INTERFRAME,
}
/**
* Video data
*/
protected IoBuffer data;
/**
* Data type
*/
private byte dataType = TYPE_VIDEO_DATA;
/**
* Frame type, unknown by default
*/
protected FrameType frameType = FrameType.UNKNOWN;
/** Constructs a new VideoData. */
public VideoData() {
this(IoBuffer.allocate(0).flip());
}
/**
* Create video data event with given data buffer
* @param data Video data
*/
public VideoData(IoBuffer data) {
super(Type.STREAM_DATA);
setData(data);
}
/**
* Create video data event with given data buffer
* @param data Video data
* @param copy true to use a copy of the data or false to use reference
*/
public VideoData(IoBuffer data, boolean copy) {
super(Type.STREAM_DATA);
if (copy) {
byte[] array = new byte[data.limit()];
data.mark();
data.get(array);
data.reset();
setData(array);
} else {
setData(data);
}
}
/** {@inheritDoc} */
@Override
public byte getDataType() {
return dataType;
}
public void setDataType(byte dataType) {
this.dataType = dataType;
}
/** {@inheritDoc} */
public IoBuffer getData() {
return data;
}
public void setData(IoBuffer data) {
this.data = data;
if (data != null && data.limit() > 0) {
data.mark();
int firstByte = (data.get(0)) & 0xff;
data.reset();
int frameType = (firstByte & MASK_VIDEO_FRAMETYPE) >> 4;
if (frameType == FLAG_FRAMETYPE_KEYFRAME) {
this.frameType = FrameType.KEYFRAME;
} else if (frameType == FLAG_FRAMETYPE_INTERFRAME) {
this.frameType = FrameType.INTERFRAME;
} else if (frameType == FLAG_FRAMETYPE_DISPOSABLE) {
this.frameType = FrameType.DISPOSABLE_INTERFRAME;
} else {
this.frameType = FrameType.UNKNOWN;
}
}
}
public void setData(byte[] data) {
this.data = IoBuffer.allocate(data.length);
this.data.put(data).flip();
}
/**
* Getter for frame type
*
* @return Type of video frame
*/
public FrameType getFrameType() {
return frameType;
}
/** {@inheritDoc} */
@Override
protected void releaseInternal() {
if (data != null) {
final IoBuffer localData = data;
// null out the data first so we don't accidentally
// return a valid reference first
data = null;
localData.clear();
localData.free();
}
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
frameType = (FrameType) in.readObject();
byte[] byteBuf = (byte[]) in.readObject();
if (byteBuf != null) {
data = IoBuffer.allocate(byteBuf.length);
data.setAutoExpand(true);
SerializeUtils.ByteArrayToByteBuffer(byteBuf, data);
}
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(frameType);
if (data != null) {
out.writeObject(SerializeUtils.ByteBufferToByteArray(data));
} else {
out.writeObject(null);
}
}
/**
* Duplicate this message / event.
*
* @return duplicated event
*/
public VideoData duplicate() throws IOException, ClassNotFoundException {
VideoData result = new VideoData();
// serialize
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
writeExternal(oos);
oos.close();
// convert to byte array
byte[] buf = baos.toByteArray();
baos.close();
// create input streams
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream ois = new ObjectInputStream(bais);
// deserialize
result.readExternal(ois);
ois.close();
bais.close();
// clone the header if there is one
if (header != null) {
result.setHeader(header.clone());
}
return result;
}
/** {@inheritDoc} */
@Override
public String toString() {
return String.format("Video - ts: %s length: %s", getTimestamp(), (data != null ? data.limit() : '0'));
}
}
|
3e1ae4ba47f5267420c70426145746541e125366 | 259 | java | Java | spring-hibernate-xml-multi-tenancy-configuration/src/main/java/com/springdemo/service/EmployeeService.java | SiddharthUpadhyay12/spring-examples | 005286286247a69638a106a62fba98fe224264ac | [
"Apache-2.0"
] | 14 | 2019-03-25T01:45:41.000Z | 2022-03-29T19:16:30.000Z | spring-hibernate-xml-multi-tenancy-configuration/src/main/java/com/springdemo/service/EmployeeService.java | SiddharthUpadhyay12/spring-examples | 005286286247a69638a106a62fba98fe224264ac | [
"Apache-2.0"
] | 1 | 2021-03-30T10:44:04.000Z | 2021-03-30T10:44:04.000Z | spring-hibernate-xml-multi-tenancy-configuration/src/main/java/com/springdemo/service/EmployeeService.java | SiddharthUpadhyay12/spring-examples | 005286286247a69638a106a62fba98fe224264ac | [
"Apache-2.0"
] | 23 | 2019-02-23T14:02:15.000Z | 2022-03-22T08:15:25.000Z | 18.5 | 42 | 0.733591 | 11,398 | package com.springdemo.service;
import com.springdemo.model.Employee;
import java.util.List;
/**
* Created by Subhash Lamba on 22-01-2017.
*/
public interface EmployeeService {
public void save(Employee employee);
public List<Employee> list();
}
|
3e1ae5ff2928df3b32f11919d83bb63afdcc4357 | 4,446 | java | Java | app/src/main/java/com/example/talkypen/framework/utils/ToastUtil.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/talkypen/framework/utils/ToastUtil.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/talkypen/framework/utils/ToastUtil.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | 26.783133 | 116 | 0.565227 | 11,399 | package com.example.talkypen.framework.utils;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.talkypen.R;
/**
* 吐司工具类
*
* 多次点击只显示一次。
* <p>
* 使用:<br>
* 显示系统样式的toast:<code>ToastUtil.show(getApplicationContext(), msg);</code><br>
* 取消显示系统显示的toast:<code>ToastUtil.cancelToast();</code><br>
* 显示自定义toast:<code>ToastUtil.customToast(getApplicationContext(),msg);</code><br>
* 取消自定义toast:<code>ToastUtil.cancelCustomToast();</code>
* </p>
*
* @author Darcy
* @Date 2018/12/10
* @package com.darcy.pet.trunk.framework.utils
* @Desciption
*/
public class ToastUtil {
//上一次显示的信息
private static String oldMsg;
private static Toast toast = null;
private static long oneTime = 0;
private static long twoTime = 0;
/**
* 取消toast.
* @return void
**/
public static void cancelToast(){
if (toast!=null){
toast.cancel();
toast=null;
oldMsg=null;
oneTime = 0;
twoTime = 0;
}
}
/**
* Toast显示信息
* @param context activity的context或applicationContent
* @param text 显示的内容
* @return void
**/
public static void show(Context context, String text) {
if (toast == null) {
toast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
oneTime = System.currentTimeMillis();
} else {
twoTime = System.currentTimeMillis();
if (text.equals(oldMsg)) {
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
toast.show();
}
} else {
oldMsg = text;
toast.setText(text);
toast.show();
}
}
oneTime = twoTime;
}
/**
* Toast显示信息
* @param context activity的context或applicationContent
* @param resId text的resId
* @return void
**/
public static void show(Context context, int resId) {
show(context, context.getString(resId));
}
//////////////////////////////////////////////////////////////////
//自定义样式
/////////////////////////////////////////////////////////////////
private static Toast customToast = null;
/**
* 无图标
**/
private static final int IMAGE_RESID_NONE=-1;//
/**
* 自定义toast
* @param context context
* @param msg 显示的消息
* @return void
**/
public static void customToast(Context context, String msg){
customToast(context,msg,IMAGE_RESID_NONE);
}
/**
* 自定义toast
* @param context context
* @param msg 文字
* @param imageResId 图标icon , {@link #IMAGE_RESID_NONE}为无图标
* @return void
**/
public static void customToast(Context context, String msg, int imageResId){
Context applicationContext=context.getApplicationContext();
View vContent= LayoutInflater.from(applicationContext).inflate(R.layout.framework_layout_custom_toast,null);
TextView tvMsg=vContent.findViewById(R.id.tv_message);
tvMsg.setText(msg);
if (IMAGE_RESID_NONE!=imageResId){
ImageView ivIcon=vContent.findViewById(R.id.iv_icon);
ivIcon.setImageResource(imageResId);
}
customToast(context,vContent);
}
/**
* 显示自定义toast
* @param applicationContext applicationContext
* @param view 自定义样式
* @return void
**/
public static void customToast(Context applicationContext, View view){
applicationContext=applicationContext.getApplicationContext();
if (customToast == null) {
customToast = new Toast(applicationContext);
}
//设置toast居中显示
customToast.setGravity(Gravity.CENTER, 0, 0);
customToast.setDuration(Toast.LENGTH_SHORT);
customToast.setView(view);
customToast.show();
}
/**
* 取消自定义toast
* @return void
**/
public static void cancelCustomToast(){
if (null!=customToast){
customToast.cancel();
customToast=null;
}
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//自定义样式
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
}
|
3e1ae68e44c3e92b54fbf4b986c7cedbbc561743 | 2,543 | java | Java | src/main/java/com/shuwang/wbms/common/util/SysCmdUtil.java | qqqays/wbms | ab61eb43868aab277ddd0538ec515eab47f9ec84 | [
"Apache-2.0"
] | 1 | 2018-03-30T08:59:24.000Z | 2018-03-30T08:59:24.000Z | src/main/java/com/shuwang/wbms/common/util/SysCmdUtil.java | qqqays/wbms | ab61eb43868aab277ddd0538ec515eab47f9ec84 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/shuwang/wbms/common/util/SysCmdUtil.java | qqqays/wbms | ab61eb43868aab277ddd0538ec515eab47f9ec84 | [
"Apache-2.0"
] | null | null | null | 29.929412 | 148 | 0.546384 | 11,400 | package com.shuwang.wbms.common.util;
import com.sun.tools.doclets.formats.html.SourceToHTMLConverter;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* Created by Q-ays.
* envkt@example.com
* 03-06-2018 9:20
*/
public class SysCmdUtil {
public static String exec(String cmd) {
String[] arr = null;
if (RunningSystem.isWin10()) {
arr = new String[]{"cmd", "/c", cmd};
}
if (RunningSystem.isLinux()) {
arr = new String[]{"sh", "-c", cmd};
}
try {
return exec(arr);
} catch (IOException | InterruptedException e) {
return e.getMessage();
}
}
public synchronized static String exec(String[] cmd) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(cmd);
try (InputStream is = p.getInputStream()) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
p.waitFor();
if (p.exitValue() != 0) {
return "Executed command error";
}
StringBuilder sb = new StringBuilder();
String s;
while ((s = br.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
sb.append("------------------<Executed success!>------------------\n");
return sb.toString();
}
}
public static void main(String[] args) {
try {
// System.out.println(exec("dir"));
if (FileUtil.checkDir("e:/abc")) {
System.out.println(exec("mysqldump -uroot -pQays1234- --default-character-set=utf8 swsun > e:/abc/swsun.sql\n"));
// System.out.println(backupDatabase("root", "Qays1234-", "shuanglv", "e:/abc", "shuanglv.sql"));
// System.out.println(exec(new String[]{"cmd", "/c", "mysqldump -uroot -p shuanglv > e:/abc/shuanglv.sql", "cmd","/c","Qays1234-"}));
// System.out.println("Qays1234-\n");
// System.out.println(exec("(mysqldump -uroot -p shuanglv > e:/abc/shuanglv.sql) < Qays1234-"));
// System.out.println(exec("d: && cd Git && dir"));
// System.out.println(lookupDB());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e1ae75f18ee7d0a3603c4f43390d1b350e6ebbf | 330 | java | Java | POMPROJECT/src/test/java/TestProject/BasePage.java | dmlpYunus/SW-Testing-POM1 | 5c04c19856bc89665b790768bcfe1ae68d965579 | [
"Apache-2.0"
] | null | null | null | POMPROJECT/src/test/java/TestProject/BasePage.java | dmlpYunus/SW-Testing-POM1 | 5c04c19856bc89665b790768bcfe1ae68d965579 | [
"Apache-2.0"
] | null | null | null | POMPROJECT/src/test/java/TestProject/BasePage.java | dmlpYunus/SW-Testing-POM1 | 5c04c19856bc89665b790768bcfe1ae68d965579 | [
"Apache-2.0"
] | null | null | null | 22 | 53 | 0.690909 | 11,401 | package TestProject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BasePage {
WebDriver driver;
WebDriverWait wait;
public BasePage(WebDriver browserDriver) {
driver = browserDriver;
wait = new WebDriverWait(driver,5);
}
} |
3e1ae7b32b6f7b91b3a565aea3efb86e5b8a8d82 | 423 | java | Java | Examples/src/main/java/com/aspose/barcode/examples/ProductInfo.java | aspose-barcode/Aspose.BarCode-for-Java | 00a0ef02cb58fda84b47939f7f8c0e2e5ca9fb65 | [
"MIT"
] | 10 | 2016-05-09T07:05:51.000Z | 2019-05-22T07:31:49.000Z | Examples/src/main/java/com/aspose/barcode/examples/ProductInfo.java | aspose-barcode/Aspose.BarCode-for-Java | 00a0ef02cb58fda84b47939f7f8c0e2e5ca9fb65 | [
"MIT"
] | 3 | 2017-05-01T08:36:07.000Z | 2019-01-09T21:16:13.000Z | Examples/src/main/java/com/aspose/barcode/examples/ProductInfo.java | aspose-barcode/Aspose.BarCode-for-Java | 00a0ef02cb58fda84b47939f7f8c0e2e5ca9fb65 | [
"MIT"
] | 14 | 2016-04-09T07:27:37.000Z | 2021-05-26T10:42:26.000Z | 26.4375 | 79 | 0.754137 | 11,402 | package com.aspose.barcode.examples;
import com.aspose.barcode.BuildVersionInfo;
public class ProductInfo {
public static void main(String[] args) {
// ExStart: ProductInfo
System.out.println("Assembly version: " + BuildVersionInfo.ASSEMBLY_VERSION);
System.out.println("Product: " + BuildVersionInfo.PRODUCT);
System.out.println("Release Date: " + BuildVersionInfo.RELEASE_DATE);
// ExEnd: ProductInfo
}
}
|
3e1ae83a7bb619143c83d8e6a2573c9449f7b097 | 1,192 | java | Java | src/main/java/com/nullptr/utils/random/RandomGeneratorUtils.java | g00176450/JavaCommonUtils | c5dfbab3d6c5e4e088060906fe49d36cdf56165b | [
"Apache-2.0"
] | 1 | 2021-09-18T01:16:15.000Z | 2021-09-18T01:16:15.000Z | src/main/java/com/nullptr/utils/random/RandomGeneratorUtils.java | g00176450/JavaCommonUtils | c5dfbab3d6c5e4e088060906fe49d36cdf56165b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/nullptr/utils/random/RandomGeneratorUtils.java | g00176450/JavaCommonUtils | c5dfbab3d6c5e4e088060906fe49d36cdf56165b | [
"Apache-2.0"
] | null | null | null | 17.791045 | 60 | 0.537752 | 11,403 | package com.nullptr.utils.random;
import java.util.Random;
/**
* 随机数生成器
*
* @author nullptr
* @version 1.0 2020-3-18
* @since 1.0 2020-3-18
*
* @see Random
*/
public class RandomGeneratorUtils {
private static final Random random = new Random();
private RandomGeneratorUtils () {
}
/**
* 生成指定范围内的随机整数
*
* @param bound 取值范围
* @return 返回(0-bound)之间的整数
*
* @since 1.0
*/
public static int randomInt(int bound) {
return random.nextInt(bound);
}
/**
* 生成指定范围内的随机整数
*
* @param min 最小取值
* @param max 最大取值
* @return 返回[min-max]之间的整数
*
* @since 1.0
*/
public static int randomInt(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
/**
* 生成指定范围内的字符
*
* @param min 最小取值
* @param max 最大取值
* @return 返回[min-max]之间的字符
*
* @since 1.0
*/
public static char randomChar(char min, char max) {
return (char) (random.nextInt(max - min + 1) + min);
}
/**
* 生成随机的布尔值
*
* @since 1.0
*/
public static boolean randomBoolean() {
return random.nextBoolean();
}
}
|
3e1ae8b7425b37a258f4ebe2648a59c0d46df0aa | 17,732 | java | Java | src/main/java/org/robolectric/res/builder/RobolectricPackageManager.java | sneuberger-amazon/robolectric | 97048cb30661211c7eed8a699b1b722f2cc12c6b | [
"MIT"
] | 1 | 2019-06-30T13:05:25.000Z | 2019-06-30T13:05:25.000Z | src/main/java/org/robolectric/res/builder/RobolectricPackageManager.java | hulu/robolectric | 8868eafdcc4fe10dc429199ea7fa84be5cf06c97 | [
"MIT"
] | null | null | null | src/main/java/org/robolectric/res/builder/RobolectricPackageManager.java | hulu/robolectric | 8868eafdcc4fe10dc429199ea7fa84be5cf06c97 | [
"MIT"
] | null | null | null | 35.252485 | 127 | 0.687401 | 11,404 | package org.robolectric.res.builder;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Pair;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.robolectric.AndroidManifest;
import org.robolectric.Robolectric;
import org.robolectric.res.ActivityData;
import org.robolectric.res.ResName;
import org.robolectric.res.ResourceIndex;
import org.robolectric.res.ResourceLoader;
import org.robolectric.shadows.ShadowContext;
import org.robolectric.tester.android.content.pm.StubPackageManager;
public class RobolectricPackageManager extends StubPackageManager {
private static class IntentComparator implements Comparator<Intent> {
@Override
public int compare(Intent i1, Intent i2) {
if (i1 == null && i2 == null) return 0;
if (i1 == null && i2 != null) return -1;
if (i1 != null && i2 == null) return 1;
if (i1.equals(i2)) return 0;
if (i1.getAction() == null && i2.getAction() != null) return -1;
if (i1.getAction() != null && i2.getAction() == null) return 1;
if (i1.getAction() != null && i2.getAction() != null) {
if (!i1.getAction().equals(i2.getAction())) {
return i1.getAction().compareTo(i2.getAction());
}
}
if (i1.getData() == null && i2.getData() != null) return -1;
if (i1.getData() != null && i2.getData() == null) return 1;
if (i1.getData() != null && i2.getData() != null) {
if (!i1.getData().equals(i2.getData())) {
return i1.getData().compareTo(i2.getData());
}
}
if (i1.getComponent() == null && i2.getComponent() != null) return -1;
if (i1.getComponent() != null && i2.getComponent() == null) return 1;
if (i1.getComponent() != null && i2.getComponent() != null) {
if (!i1.getComponent().equals(i2.getComponent())) {
return i1.getComponent().compareTo(i2.getComponent());
}
}
if (i1.getPackage() == null && i2.getPackage() != null) return -1;
if (i1.getPackage() != null && i2.getPackage() == null) return 1;
if (i1.getPackage() != null && i2.getPackage() != null) {
if (!i1.getPackage().equals(i2.getPackage())) {
return i1.getPackage().compareTo(i2.getPackage());
}
}
Set<String> categories1 = i1.getCategories();
Set<String> categories2 = i2.getCategories();
if (categories1 == null) return categories2 == null ? 0 : -1;
if (categories2 == null) return 1;
if (categories1.size() > categories2.size()) return 1;
if (categories1.size() < categories2.size()) return -1;
String[] array1 = categories1.toArray(new String[0]);
String[] array2 = categories2.toArray(new String[0]);
Arrays.sort(array1);
Arrays.sort(array2);
for (int i = 0; i < array1.length; ++i) {
int val = array1[i].compareTo(array2[i]);
if (val != 0) return val;
}
return 0;
}
}
private final Map<String, AndroidManifest> androidManifests = new LinkedHashMap<String, AndroidManifest>();
private final Map<String, PackageInfo> packageInfos = new LinkedHashMap<String, PackageInfo>();
private Map<Intent, List<ResolveInfo>> resolveInfoForIntent = new TreeMap<Intent, List<ResolveInfo>>(new IntentComparator());
private Map<ComponentName, ComponentState> componentList = new LinkedHashMap<ComponentName, ComponentState>();
private Map<ComponentName, Drawable> drawableList = new LinkedHashMap<ComponentName, Drawable>();
private Map<String, Boolean> systemFeatureList = new LinkedHashMap<String, Boolean>();
private Map<IntentFilter, ComponentName> preferredActivities = new LinkedHashMap<IntentFilter, ComponentName>();
private Map<Pair<String, Integer>, Drawable> drawables = new LinkedHashMap<Pair<String, Integer>, Drawable>();
@Override
public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException {
if (packageInfos.containsKey(packageName)) {
return packageInfos.get(packageName);
}
throw new NameNotFoundException();
}
@Override
public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException {
PackageInfo info = packageInfos.get(packageName);
if (info != null) {
return info.applicationInfo;
} else {
throw new NameNotFoundException();
}
}
@Override public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException {
String packageName = className.getPackageName();
AndroidManifest androidManifest = androidManifests.get(packageName);
String activityName = className.getClassName();
ActivityData activityData = androidManifest.getActivityData(activityName);
ActivityInfo activityInfo = new ActivityInfo();
activityInfo.packageName = packageName;
activityInfo.name = activityName;
if (activityData != null) {
ResourceIndex resourceIndex = Robolectric.getShadowApplication().getResourceLoader().getResourceIndex();
String themeRef;
// Based on ShadowActivity
if (activityData.getThemeRef() != null) {
themeRef = activityData.getThemeRef();
} else {
themeRef = androidManifest.getThemeRef();
}
if (themeRef != null) {
ResName style = ResName.qualifyResName(themeRef.replace("@", ""), packageName, "style");
activityInfo.theme = resourceIndex.getResourceId(style);
}
}
activityInfo.applicationInfo = getApplicationInfo(packageName, flags);
return activityInfo;
}
@Override
public ActivityInfo getReceiverInfo(ComponentName className, int flags) throws NameNotFoundException {
String packageName = className.getPackageName();
AndroidManifest androidManifest = androidManifests.get(packageName);
String classString = className.getClassName();
int index = classString.indexOf('.');
if (index == -1) {
classString = packageName + "." + classString;
} else if (index == 0) {
classString = packageName + classString;
}
ActivityInfo activityInfo = new ActivityInfo();
activityInfo.packageName = packageName;
activityInfo.name = classString;
if ((flags & GET_META_DATA) != 0) {
for (int i = 0; i < androidManifest.getReceiverCount(); ++i) {
if (androidManifest.getReceiverClassName(i).equals(classString)) {
activityInfo.metaData = metaDataToBundle(androidManifest.getReceiverMetaData(i));
break;
}
}
}
return activityInfo;
}
@Override
public List<PackageInfo> getInstalledPackages(int flags) {
return new ArrayList<PackageInfo>(packageInfos.values());
}
@Override
public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
return queryIntent(intent, flags);
}
@Override
public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
return queryIntent(intent, flags);
}
@Override
public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
return queryIntent(intent, flags);
}
@Override
public ResolveInfo resolveActivity(Intent intent, int flags) {
List<ResolveInfo> candidates = queryIntentActivities(intent, flags);
return candidates.isEmpty() ? null : candidates.get(0);
}
@Override
public ResolveInfo resolveService(Intent intent, int flags) {
return resolveActivity(intent, flags);
}
public void addResolveInfoForIntent(Intent intent, List<ResolveInfo> info) {
resolveInfoForIntent.put(intent, info);
}
public void addResolveInfoForIntent(Intent intent, ResolveInfo info) {
List<ResolveInfo> infoList = findOrCreateInfoList(intent);
infoList.add(info);
}
public void removeResolveInfosForIntent(Intent intent, String packageName) {
List<ResolveInfo> infoList = findOrCreateInfoList(intent);
for (Iterator<ResolveInfo> iterator = infoList.iterator(); iterator.hasNext(); ) {
ResolveInfo resolveInfo = iterator.next();
if (resolveInfo.activityInfo.packageName.equals(packageName)) {
iterator.remove();
}
}
}
@Override
public Drawable getActivityIcon(Intent intent) {
return drawableList.get(intent.getComponent());
}
@Override
public Drawable getActivityIcon(ComponentName componentName) {
return drawableList.get(componentName);
}
public void addActivityIcon(ComponentName component, Drawable d) {
drawableList.put(component, d);
}
public void addActivityIcon(Intent intent, Drawable d) {
drawableList.put(intent.getComponent(), d);
}
@Override
public Intent getLaunchIntentForPackage(String packageName) {
Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
intentToResolve.addCategory(Intent.CATEGORY_INFO);
intentToResolve.setPackage(packageName);
List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
if (ris == null || ris.isEmpty()) {
intentToResolve.removeCategory(Intent.CATEGORY_INFO);
intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
intentToResolve.setPackage(packageName);
ris = queryIntentActivities(intentToResolve, 0);
}
if (ris == null || ris.isEmpty()) {
return null;
}
Intent intent = new Intent(intentToResolve);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(ris.get(0).activityInfo.packageName, ris.get(0).activityInfo.name);
return intent;
}
@Override
public CharSequence getApplicationLabel(ApplicationInfo info) {
return info.name;
}
@Override
public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) {
componentList.put(componentName, new ComponentState(newState, flags));
}
public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) {
preferredActivities.put(filter, activity);
}
@Override
public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) {
if (outFilters == null) {
return 0;
}
Set<IntentFilter> filters = preferredActivities.keySet();
for (IntentFilter filter : outFilters) {
step:
for (IntentFilter testFilter : filters) {
ComponentName name = preferredActivities.get(testFilter);
// filter out based on the given packageName;
if (packageName != null && !name.getPackageName().equals(packageName)) {
continue step;
}
// Check actions
Iterator<String> iterator = filter.actionsIterator();
while (iterator.hasNext()) {
if (!testFilter.matchAction(iterator.next())) {
continue step;
}
}
iterator = filter.categoriesIterator();
while (iterator.hasNext()) {
if (!filter.hasCategory(iterator.next())) {
continue step;
}
}
if (outActivities == null) {
outActivities = new ArrayList<ComponentName>();
}
outActivities.add(name);
}
}
return 0;
}
/**
* Non-Android accessor. Use to make assertions on values passed to
* setComponentEnabledSetting.
*
* @param componentName
* @return
*/
public ComponentState getComponentState(ComponentName componentName) {
return componentList.get(componentName);
}
/**
* Non-Android accessor. Used to add a package to the list of those
* already 'installed' on system.
*
* @param packageInfo
*/
public void addPackage(PackageInfo packageInfo) {
packageInfos.put(packageInfo.packageName, packageInfo);
}
public void addPackage(String packageName) {
PackageInfo packageInfo = new PackageInfo();
packageInfo.packageName = packageName;
ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.packageName = packageName;
initApplicationInfo(applicationInfo);
packageInfo.applicationInfo = applicationInfo;
addPackage(packageInfo);
}
public void addManifest(AndroidManifest androidManifest, ResourceLoader loader) {
androidManifests.put(androidManifest.getPackageName(), androidManifest);
ResourceIndex resourceIndex = loader.getResourceIndex();
// first opportunity to access a resource index for this manifest, use it to init the references
androidManifest.initMetaData(resourceIndex);
PackageInfo packageInfo = new PackageInfo();
packageInfo.packageName = androidManifest.getPackageName();
packageInfo.versionName = androidManifest.getVersionName();
packageInfo.versionCode = androidManifest.getVersionCode();
ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.flags = androidManifest.getApplicationFlags();
applicationInfo.targetSdkVersion = androidManifest.getTargetSdkVersion();
applicationInfo.packageName = androidManifest.getPackageName();
applicationInfo.processName = androidManifest.getProcessName();
applicationInfo.name = androidManifest.getApplicationName();
applicationInfo.metaData = metaDataToBundle(androidManifest.getApplicationMetaData());
if (androidManifest.getLabelRef() != null && resourceIndex != null) {
Integer id = ResName.getResourceId(resourceIndex, androidManifest.getLabelRef(), androidManifest.getPackageName());
applicationInfo.labelRes = id != null ? id : 0;
}
packageInfo.applicationInfo = applicationInfo;
initApplicationInfo(applicationInfo);
addPackage(packageInfo);
}
private void initApplicationInfo(ApplicationInfo applicationInfo) {
applicationInfo.sourceDir = new File(".").getAbsolutePath();
applicationInfo.dataDir = ShadowContext.FILES_DIR.getAbsolutePath();
}
public void removePackage(String packageName) {
packageInfos.remove(packageName);
}
@Override
public boolean hasSystemFeature(String name) {
return systemFeatureList.containsKey(name) ? systemFeatureList.get(name) : false;
}
/**
* Non-Android accessor. Used to declare a system feature is
* or is not supported.
*
* @param name
* @param supported
*/
public void setSystemFeature(String name, boolean supported) {
systemFeatureList.put(name, supported);
}
public void addDrawableResolution(String packageName, int resourceId, Drawable drawable) {
drawables.put(new Pair(packageName, resourceId), drawable);
}
public class ComponentState {
public int newState;
public int flags;
public ComponentState(int newState, int flags) {
this.newState = newState;
this.flags = flags;
}
}
@Override
public Drawable getDrawable(String packageName, int resourceId, ApplicationInfo applicationInfo) {
return drawables.get(new Pair(packageName, resourceId));
}
private List<ResolveInfo> findOrCreateInfoList(Intent intent) {
List<ResolveInfo> infoList = resolveInfoForIntent.get(intent);
if (infoList == null) {
infoList = new ArrayList<ResolveInfo>();
resolveInfoForIntent.put(intent, infoList);
}
return infoList;
}
private List<ResolveInfo> queryIntent(Intent intent, int flags) {
List<ResolveInfo> result = resolveInfoForIntent.get(intent);
if (result == null) {
return Collections.emptyList();
} else {
return result;
}
}
/***
* Goes through the meta data and puts each value in to a
* bundle as the correct type.
*
* Note that this will convert resource identifiers specified
* via the value attribute as well.
* @param meta Meta data to put in to a bundle
* @return bundle containing the meta data
*/
private Bundle metaDataToBundle(Map<String, String> meta) {
if (meta.size() == 0) {
return null;
}
Bundle bundle = new Bundle();
for (Map.Entry<String,String> entry : meta.entrySet()) {
if (entry.getValue() == null) {
// skip it
} else if ("true".equals(entry.getValue())) {
bundle.putBoolean(entry.getKey(), true);
} else if ("false".equals(entry.getValue())) {
bundle.putBoolean(entry.getKey(), false);
} else {
if (entry.getValue().contains(".")) {
// if it's a float, add it and continue
try {
bundle.putFloat(entry.getKey(), Float.parseFloat(entry.getValue()));
} catch (NumberFormatException ef) {
/* Not a float */
}
}
if (!bundle.containsKey(entry.getKey()) && !entry.getValue().startsWith("#")) {
// if it's an int, add it and continue
try {
bundle.putInt(entry.getKey(), Integer.parseInt(entry.getValue()));
} catch (NumberFormatException ei) {
/* Not an int */
}
}
if (!bundle.containsKey(entry.getKey())) {
// if it's a color, add it and continue
try {
bundle.putInt(entry.getKey(), Color.parseColor(entry.getValue()));
} catch (IllegalArgumentException e) {
/* Not a color */
}
}
if (!bundle.containsKey(entry.getKey())) {
// otherwise it's a string
bundle.putString(entry.getKey(), entry.getValue());
}
}
}
return bundle;
}
}
|
3e1ae992ac69e956998eb384635fe6d3745268cb | 2,451 | java | Java | DataManagementLayer/src/main/java/eu/qualimaster/dataManagement/common/RemoteReference.java | QualiMaster/Infrastructure | 258557752070f4a2c4a18491fec110361e8fa0ee | [
"Apache-2.0"
] | 2 | 2016-10-21T09:35:47.000Z | 2017-01-24T21:49:23.000Z | DataManagementLayer/src/main/java/eu/qualimaster/dataManagement/common/RemoteReference.java | QualiMaster/Infrastructure | 258557752070f4a2c4a18491fec110361e8fa0ee | [
"Apache-2.0"
] | 23 | 2016-02-24T14:18:02.000Z | 2017-01-18T13:34:50.000Z | DataManagementLayer/src/main/java/eu/qualimaster/dataManagement/common/RemoteReference.java | QualiMaster/Infrastructure | 258557752070f4a2c4a18491fec110361e8fa0ee | [
"Apache-2.0"
] | 3 | 2016-07-29T07:30:14.000Z | 2016-09-24T12:29:39.000Z | 35.521739 | 109 | 0.703386 | 11,405 | /*
* Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.qualimaster.dataManagement.common;
import eu.qualimaster.dataManagement.events.ReferenceDataManagementEvent;
import eu.qualimaster.dataManagement.events.ReferenceDataManagementEvent.Command;
import eu.qualimaster.events.EventManager;
/**
* Represents a remote reference. Remote references encapsulate real data elements residing
* on client side, e.g., distributed among Storm workers and are used on central (nimbus) side.
*
* @param <E> the type of the data element
* @author Holger Eichelberger
*/
public class RemoteReference <E extends IDataElement> implements IReference<E> {
private String managerId;
private String unit;
private String elementId;
/**
* Creates a remote reference for a certain data element. Please note that
* <code>dataElement</code> shall not be stored within this instance.
* Communication shall happen remotely.
*
* @param event the causing event to create the reference for
*/
public RemoteReference(ReferenceDataManagementEvent event) {
this.managerId = event.getManagerId();
this.unit = event.getUnit();
this.elementId = event.getElementId();
}
@Override
public void connect() {
EventManager.send(new ReferenceDataManagementEvent(managerId, unit, elementId, Command.CONNECT));
}
@Override
public void disconnect() {
EventManager.send(new ReferenceDataManagementEvent(managerId, unit, elementId, Command.DISCONNECT));
}
@Override
public void dispose() {
EventManager.send(new ReferenceDataManagementEvent(managerId, unit, elementId, Command.DISPOSE));
}
@Override
public String getId() {
return elementId;
}
}
|
3e1aea00d81c7e9d0ffa1cb77c6f002ff46ffd4e | 79 | java | Java | src/main/java/com/kasztelanic/carcare/service/dto/package-info.java | kacperkasztelanic/carcare-server | ff95716f3fede1e1d2ba5270b09f4cf8f07c76b2 | [
"MIT"
] | null | null | null | src/main/java/com/kasztelanic/carcare/service/dto/package-info.java | kacperkasztelanic/carcare-server | ff95716f3fede1e1d2ba5270b09f4cf8f07c76b2 | [
"MIT"
] | null | null | null | src/main/java/com/kasztelanic/carcare/service/dto/package-info.java | kacperkasztelanic/carcare-server | ff95716f3fede1e1d2ba5270b09f4cf8f07c76b2 | [
"MIT"
] | null | null | null | 15.8 | 44 | 0.721519 | 11,406 | /**
* Data Transfer Objects.
*/
package com.kasztelanic.carcare.service.dto;
|
3e1aeb4654a1e752fbbec227061bba7f45182af9 | 743 | java | Java | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/psi/XPathString.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/psi/XPathString.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/psi/XPathString.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 33.772727 | 75 | 0.748318 | 11,407 | /*
* Copyright 2005 Sascha Weinreuter
*
* 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.intellij.lang.xpath.psi;
public interface XPathString extends XPathExpression {
String getValue();
boolean isWellFormed();
} |
3e1aebea6ed2c0e0658570e699467b01ccba9b64 | 1,017 | java | Java | bank/src/main/java/es/udc/fic/acs/infmsb01/atm/bank/net/transport/BankTransportProcessorRunnable.java | marcos-sb/distributed-banking-system | e5130c1ea82fc69a43b236bc6dcff41309b9f86e | [
"Apache-2.0"
] | null | null | null | bank/src/main/java/es/udc/fic/acs/infmsb01/atm/bank/net/transport/BankTransportProcessorRunnable.java | marcos-sb/distributed-banking-system | e5130c1ea82fc69a43b236bc6dcff41309b9f86e | [
"Apache-2.0"
] | 2 | 2017-12-28T03:46:53.000Z | 2018-10-29T04:09:59.000Z | bank/src/main/java/es/udc/fic/acs/infmsb01/atm/bank/net/transport/BankTransportProcessorRunnable.java | marcos-sb/distributed-banking-system | e5130c1ea82fc69a43b236bc6dcff41309b9f86e | [
"Apache-2.0"
] | 3 | 2017-02-19T23:34:20.000Z | 2021-08-28T09:01:13.000Z | 22.108696 | 99 | 0.747296 | 11,408 | package es.udc.fic.acs.infmsb01.atm.bank.net.transport;
import java.io.IOException;
import java.text.ParseException;
import es.udc.fic.acs.infmsb01.atm.bank.model.message.processor.BankConsortiumQueueManagerRunnable;
import es.udc.fic.acs.infmsb01.atm.bank.model.message.processor.BankMessageProcessor;
public final class BankTransportProcessorRunnable implements Runnable {
private BankMessageProcessor bmp;
public BankTransportProcessorRunnable(BankMessageProcessor bmp) {
this.bmp = bmp;
}
public void run() {
try {
BankConsortiumQueueManagerRunnable.setBankMessageProcessor(bmp);
while(true)
BankConsortiumQueueManagerRunnable.queueMessage(bmp.getTransport().receive());
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e1aeec632721a6b1e1e72642a50fa929a587345 | 899 | java | Java | Voleo/src/com/voleo/dao/backUp/AbstractBackUpModificationDAO.java | DoctusHartwald/artaudCode | cabd1b5bdf9a7e740560cb0e44c8dc62f86d30e5 | [
"Apache-2.0"
] | null | null | null | Voleo/src/com/voleo/dao/backUp/AbstractBackUpModificationDAO.java | DoctusHartwald/artaudCode | cabd1b5bdf9a7e740560cb0e44c8dc62f86d30e5 | [
"Apache-2.0"
] | null | null | null | Voleo/src/com/voleo/dao/backUp/AbstractBackUpModificationDAO.java | DoctusHartwald/artaudCode | cabd1b5bdf9a7e740560cb0e44c8dc62f86d30e5 | [
"Apache-2.0"
] | null | null | null | 27.242424 | 97 | 0.746385 | 11,409 | package com.voleo.dao.backUp;
import java.util.Collection;
import java.util.List;
import com.voleo.dao.AbstractDAO;
import com.voleo.entity.backUp.BackUpModification;
public class AbstractBackUpModificationDAO <T extends BackUpModification> extends AbstractDAO<T>
implements IBackUpModificationDAO<T> {
public AbstractBackUpModificationDAO(Class<T> entityClass) {
super(entityClass);
}
@Override
public int getCountHistoriqueByUser(Long userId) {
return ((Long)jpaTemplate.find("select count(*) from BackUpModification b where " +
"b.targetDocument.user.id = ?1", userId).get(0)).intValue();
}
@Override
public T getBackUpModificationByHistoriqueId(Long historiqueId){
List<T> results = jpaTemplate.find("from BackUpModification b where " +
"b.historique.id = ?1", historiqueId);
if (results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
}
|
3e1aefa145d834e750bcfdb13d59f74e46ad874e | 1,651 | java | Java | greatbook/src/main/java/com/example/greatbook/nethot/databinding/GroupAndRecordsDataBinding.java | zhiaixinyang/sbgithub | f8fb2b989556a65ca6f27c1a55ba5deb9a04ba6e | [
"Apache-2.0"
] | null | null | null | greatbook/src/main/java/com/example/greatbook/nethot/databinding/GroupAndRecordsDataBinding.java | zhiaixinyang/sbgithub | f8fb2b989556a65ca6f27c1a55ba5deb9a04ba6e | [
"Apache-2.0"
] | null | null | null | greatbook/src/main/java/com/example/greatbook/nethot/databinding/GroupAndRecordsDataBinding.java | zhiaixinyang/sbgithub | f8fb2b989556a65ca6f27c1a55ba5deb9a04ba6e | [
"Apache-2.0"
] | null | null | null | 38.395349 | 99 | 0.728649 | 11,410 | package com.example.greatbook.nethot.databinding;
import android.databinding.BindingAdapter;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import com.example.greatbook.model.leancloud.LLocalRecord;
import com.example.greatbook.nethot.adapter.GroupRecordsAdapter;
import com.example.greatbook.nethot.model.GroupRecords;
import com.example.greatbook.nethot.viewmodel.GroupAndRecordsBeanVM;
import com.example.greatbook.utils.DateUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by MDove on 2017/8/24.
*/
public class GroupAndRecordsDataBinding {
@BindingAdapter("groupAndRecordsData")
public static void groupAndRecordsData(RecyclerView view, GroupRecords groupRecords) {
List<GroupAndRecordsBeanVM> data_ = new ArrayList<>();
GroupRecordsAdapter adapter = (GroupRecordsAdapter) view.getAdapter();
if (adapter != null && groupRecords != null && !groupRecords.data.isEmpty()) {
for (LLocalRecord lLocalRecord : groupRecords.data) {
final GroupAndRecordsBeanVM recordRemarkBeanVM = new GroupAndRecordsBeanVM();
recordRemarkBeanVM.content.set(lLocalRecord.getContent());
recordRemarkBeanVM.time.set(DateUtils.getDateChinese(lLocalRecord.getCreatedAt()));
recordRemarkBeanVM.title.set(lLocalRecord.getTitle());
data_.add(recordRemarkBeanVM);
}
adapter.setData(data_);
}
}
@BindingAdapter("iconFollowerRes")
public static void iconFollowerRes(ImageView imageView, int res) {
imageView.setImageResource(res);
}
}
|
3e1aefa6054f473c32b4bc4bcc57aa1855d09b56 | 184 | java | Java | app/src/main/java/com/example/licio/moringaeats/util/ItemTouchHelperAdapter.java | liciolentimo/MoringaEats | b485a79328560f52a132c70069818ba9344a93cc | [
"MIT"
] | null | null | null | app/src/main/java/com/example/licio/moringaeats/util/ItemTouchHelperAdapter.java | liciolentimo/MoringaEats | b485a79328560f52a132c70069818ba9344a93cc | [
"MIT"
] | null | null | null | app/src/main/java/com/example/licio/moringaeats/util/ItemTouchHelperAdapter.java | liciolentimo/MoringaEats | b485a79328560f52a132c70069818ba9344a93cc | [
"MIT"
] | null | null | null | 30.666667 | 57 | 0.798913 | 11,411 | package com.example.licio.moringaeats.util;
public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
} |
3e1af005980e49bfb00acfb6e7349cdc426d8a86 | 1,747 | java | Java | src/main/java/lists/P28.java | Mishco/99-problems-java | 9e77e07f5256f310a2b67f800e5bf5abc2b0e409 | [
"MIT"
] | null | null | null | src/main/java/lists/P28.java | Mishco/99-problems-java | 9e77e07f5256f310a2b67f800e5bf5abc2b0e409 | [
"MIT"
] | null | null | null | src/main/java/lists/P28.java | Mishco/99-problems-java | 9e77e07f5256f310a2b67f800e5bf5abc2b0e409 | [
"MIT"
] | null | null | null | 28.639344 | 79 | 0.504293 | 11,412 | package lists;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
/**
* We suppose that a list (InList) contains elements that are lists themselves.
* The objective is to sort the elements of InList according to their length.
* E.g. short lists first, longer lists later, or vice versa.
* <p>
* Example:
* ?- lsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L).
* L = [[o], [d, e], [d, e], [m, n], [a, b, c], [f, g, h], [i, j, k, l]]
*/
public final class P28 {
private P28() {
}
/**
* Sort list by size of sublist.
*
* @param input input list of items
* @param <T> type of item
* @return sorted list
*/
public static <T> List<List<T>> lsort(final List<List<T>> input) {
input.sort(Comparator.comparingInt(List::size));
return input;
}
/**
* Sort list by frequency of sublist.
*
* @param input input list of items
* @param <T> type of item
* @return sorted list
*/
public static <T> List<List<T>> lfsort(final List<List<T>> input) {
Map<Integer, Integer> frequencies = new HashMap<>();
input.stream()
.map(List::size)
.forEach(l -> frequencies.put(
l,
frequencies.compute(l,
(k, v) -> v == null
? 1
: v + 1)));
return input
.stream()
.sorted(Comparator
.comparingInt(xs -> frequencies.get(xs.size())))
.collect(toList());
}
}
|
3e1af09d47132b1ffc6a4fa46dd9e2087409bd02 | 2,188 | java | Java | src/main/java/com/tsmms/skoop/report/userskillpriority/command/UserSkillPriorityReportCommandController.java | KnowledgeAssets/myskills-server | 7439b9ca388c5cb0579d6bf12433368717c10748 | [
"MIT"
] | 1 | 2019-06-26T14:18:32.000Z | 2019-06-26T14:18:32.000Z | src/main/java/com/tsmms/skoop/report/userskillpriority/command/UserSkillPriorityReportCommandController.java | KnowledgeAssets/myskills-server | 7439b9ca388c5cb0579d6bf12433368717c10748 | [
"MIT"
] | 44 | 2018-08-28T18:44:31.000Z | 2019-03-26T14:14:29.000Z | src/main/java/com/tsmms/skoop/report/userskillpriority/command/UserSkillPriorityReportCommandController.java | KnowledgeAssets/myskills-server | 7439b9ca388c5cb0579d6bf12433368717c10748 | [
"MIT"
] | 1 | 2021-03-24T09:24:43.000Z | 2021-03-24T09:24:43.000Z | 43.76 | 127 | 0.816728 | 11,413 | package com.tsmms.skoop.report.userskillpriority.command;
import com.tsmms.skoop.report.userskillpriority.UserSkillPriorityReport;
import com.tsmms.skoop.report.userskillpriority.UserSkillPriorityReportSimpleResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "UserSkillPriorityReports")
@RestController
public class UserSkillPriorityReportCommandController {
private UserSkillPriorityReportCommandService userSkillPriorityReportCommandService;
public UserSkillPriorityReportCommandController(UserSkillPriorityReportCommandService userSkillPriorityReportCommandService) {
this.userSkillPriorityReportCommandService = userSkillPriorityReportCommandService;
}
@ApiOperation(
value = "Create a new user skill priority report",
notes = "Create a new user skill priority report based on the current data in the system."
)
@ApiResponses({
@ApiResponse(code = 201, message = "Successful execution"),
@ApiResponse(code = 401, message = "Invalid authentication"),
@ApiResponse(code = 403, message = "Insufficient privileges to perform this operation"),
@ApiResponse(code = 500, message = "Error during execution")
})
@PreAuthorize("isAuthenticated()")
@PostMapping(
path = "/reports/skills/priority",
consumes = MediaType.ALL_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<UserSkillPriorityReportSimpleResponse> createReport() {
UserSkillPriorityReport report = userSkillPriorityReportCommandService.createUserSkillPriorityReport();
return ResponseEntity.status(HttpStatus.CREATED).body(UserSkillPriorityReportSimpleResponse.builder()
.id(report.getId())
.date(report.getDate())
.skillCount(report.getAggregationReports().size())
.build());
}
}
|
3e1af146db9d82b67edf6c2302a4cd3579e4a1bc | 1,822 | java | Java | core/src/main/java/se/kodapan/osm/util/slippymap/SlippyMap.java | eric-erki/osm-common | c33d63b9a225bf389530987c2c7e2635474f138f | [
"Apache-2.0"
] | 31 | 2015-01-06T07:15:53.000Z | 2020-01-24T05:21:18.000Z | core/src/main/java/se/kodapan/osm/util/slippymap/SlippyMap.java | karlwettin/osm-common | f84547ee0fc873121824682a98091973505ab74c | [
"Apache-2.0"
] | 2 | 2021-06-04T01:01:09.000Z | 2021-08-02T17:03:39.000Z | core/src/main/java/se/kodapan/osm/util/slippymap/SlippyMap.java | eric-erki/osm-common | c33d63b9a225bf389530987c2c7e2635474f138f | [
"Apache-2.0"
] | 11 | 2015-03-05T13:28:54.000Z | 2019-10-30T12:53:59.000Z | 29.868852 | 154 | 0.701976 | 11,414 | package se.kodapan.osm.util.slippymap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Tool for evaluating Slippy map tile numbers, URLs, etc.
*
* @author kalle
* @since 8/25/13 1:29 PM
*/
public abstract class SlippyMap {
private String urlPattern = null;
protected SlippyMap() {
}
protected SlippyMap(String urlPattern) {
this.urlPattern = urlPattern;
}
public abstract Tile tileFactory(double longitude, double latitude, int z);
public abstract Tile tileFactory(int x, int y, int z);
public abstract void listTiles(double southLatitude, double westLongitude, double northLatitude, double eastLongitude, int z, TileVisitor tileVisitor);
@Deprecated
public List<Tile> listTiles(double southLatitude, double westLongitude, double northLatitude, double eastLongitude, int z) {
final List<Tile> tiles = new ArrayList<Tile>(1000);
listTiles(southLatitude, westLongitude, northLatitude, eastLongitude, z, new TileVisitor() {
@Override
public void visit(Tile tile) {
tiles.add(new WMS.WMSTile(tile.getX(), tile.getY(), tile.getZ()));
}
});
return tiles;
}
@Deprecated
public Iterator<Tile> iterateTiles(double southLatitude, double westLongitude, double northLatitude, double eastLongitude, int z) {
return listTiles(southLatitude, westLongitude, northLatitude, eastLongitude, z).iterator();
}
public String toURL(Tile tile) {
return urlPattern
.replaceAll("\\%\\{x\\}", String.valueOf(tile.getX()))
.replaceAll("\\%\\{y\\}", String.valueOf(tile.getY()))
.replaceAll("\\%\\{z\\}", String.valueOf(tile.getZ()));
}
public String getUrlPattern() {
return urlPattern;
}
public void setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
}
}
|
3e1af1e2dbf02577128a92192e6ead78777cfd3c | 1,189 | java | Java | src/test/java/it/unibo/pensilina14/bullet/ballet/save/SecureDataTest.java | DanySK/Student-Project-OOP21-Baiocchi-Brunelli-Pioggia-Rengo-bullet-ballet | 7396fb72931c7fcb5464049d42e467d64e372088 | [
"MIT"
] | null | null | null | src/test/java/it/unibo/pensilina14/bullet/ballet/save/SecureDataTest.java | DanySK/Student-Project-OOP21-Baiocchi-Brunelli-Pioggia-Rengo-bullet-ballet | 7396fb72931c7fcb5464049d42e467d64e372088 | [
"MIT"
] | null | null | null | src/test/java/it/unibo/pensilina14/bullet/ballet/save/SecureDataTest.java | DanySK/Student-Project-OOP21-Baiocchi-Brunelli-Pioggia-Rengo-bullet-ballet | 7396fb72931c7fcb5464049d42e467d64e372088 | [
"MIT"
] | 1 | 2022-03-22T10:30:20.000Z | 2022-03-22T10:30:20.000Z | 38.354839 | 227 | 0.807401 | 11,415 | package it.unibo.pensilina14.bullet.ballet.save;
import org.junit.Test;
import static org.junit.Assert.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class SecureDataTest {
@Test
public void encryptAndDecryptTest() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
final String message = "Messaggio segreto";
final byte[] encryptedMessage = SecureData.encrypt(message.getBytes(), SecureData.PASSWORD);
assertNotNull(encryptedMessage);
final byte[] decryptedMessage = SecureData.decrypt(encryptedMessage, SecureData.PASSWORD);
final String clearMessage = new String(decryptedMessage, StandardCharsets.UTF_8);
assertEquals(message, clearMessage);
}
}
|
3e1af2488426e83bb7ac16c6adc61b0cbf1b9a82 | 5,168 | java | Java | src/main/java/mavlc/ast/nodes/statement/ForLoop.java | ThomasK33/EiCB-Praktikum-1 | b89364e06c2211ab0324ec01e025a77f665ef24d | [
"MIT"
] | null | null | null | src/main/java/mavlc/ast/nodes/statement/ForLoop.java | ThomasK33/EiCB-Praktikum-1 | b89364e06c2211ab0324ec01e025a77f665ef24d | [
"MIT"
] | null | null | null | src/main/java/mavlc/ast/nodes/statement/ForLoop.java | ThomasK33/EiCB-Praktikum-1 | b89364e06c2211ab0324ec01e025a77f665ef24d | [
"MIT"
] | 2 | 2021-11-09T16:38:49.000Z | 2021-11-12T14:16:34.000Z | 27.2 | 109 | 0.665248 | 11,416 | /*******************************************************************************
* Copyright (C) 2016 Embedded Systems and Applications Group
* Department of Computer Science, Technische Universitaet Darmstadt,
* Hochschulstr. 10, 64289 Darmstadt, Germany.
*
* All rights reserved.
*
* This software is provided free for educational use only.
* It may not be used for commercial purposes without the
* prior written permission of the authors.
******************************************************************************/
package mavlc.ast.nodes.statement;
import mavlc.ast.nodes.expression.Expression;
import mavlc.ast.visitor.ASTNodeVisitor;
/**
* AST-node representing a for-loop.
*/
public class ForLoop extends Statement {
/**
*
*/
private static final long serialVersionUID = 3550925366906276298L;
protected final String initVarName;
protected final Expression initValue;
protected final Expression check;
protected final String incrVarName;
protected final Expression incrExpr;
protected final Statement body;
/**
* Constructor.
* @param sourceLine The source line in which the node was specified.
* @param sourceColumn The source column in which the node was specified.
* @param initVarName Name of the initialized variable.
* @param initValue Initialized value.
* @param check The check expression.
* @param incrementVarName The name of the incremented variable.
* @param incrementExpression The increment expression.
* @param loopBody The loop body.
*/
public ForLoop(int sourceLine, int sourceColumn, String initVarName, Expression initValue, Expression check,
String incrementVarName, Expression incrementExpression,
Statement loopBody) {
super(sourceLine, sourceColumn);
this.initVarName = initVarName;
this.initValue = initValue;
this.check = check;
incrVarName = incrementVarName;
incrExpr = incrementExpression;
body = loopBody;
}
@Override
public String dump() {
StringBuilder sb = new StringBuilder();
sb.append("for (");
sb.append(initVarName).append(" = ");
sb.append(initValue.dump()).append("; ");
sb.append(check.dump()).append("; ");
sb.append(incrVarName).append(" = ");
sb.append(incrExpr.dump()).append(")");
sb.append(body.dump());
return sb.toString();
}
/**
* Get the name of the variable used in the initializing expression.
* @return Name of the initialized variable.
*/
public String getInitVariableName() {
return initVarName;
}
/**
* Get the expression used for initialization.
* @return Initializing expression.
*/
public Expression getInitValue() {
return initValue;
}
/**
* Get the expression used for the loop-bound checking.
* @return Loop-bound check expression.
*/
public Expression getCheck() {
return check;
}
/**
* Get the name of the variable used in the increment expression.
* @return The incremented variable's name.
*/
public String getIncrementVariableName() {
return incrVarName;
}
/**
* Get the expression used for the increment.
* @return Increment expression.
*/
public Expression getIncrementExpr() {
return incrExpr;
}
/**
* Get the loop body.
* @return The loop body.
*/
public Statement getLoopBody() {
return body;
}
@Override
public <RetTy, ArgTy> RetTy accept(ASTNodeVisitor<? extends RetTy, ArgTy> visitor, ArgTy obj){
return visitor.visitForLoop(this, obj);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((body == null) ? 0 : body.hashCode());
result = prime * result + ((check == null) ? 0 : check.hashCode());
result = prime * result + ((incrExpr == null) ? 0 : incrExpr.hashCode());
result = prime * result + ((incrVarName == null) ? 0 : incrVarName.hashCode());
result = prime * result + ((initValue == null) ? 0 : initValue.hashCode());
result = prime * result + ((initVarName == null) ? 0 : initVarName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ForLoop other = (ForLoop) obj;
if (body == null) {
if (other.body != null)
return false;
} else if (!body.equals(other.body))
return false;
if (check == null) {
if (other.check != null)
return false;
} else if (!check.equals(other.check))
return false;
if (incrExpr == null) {
if (other.incrExpr != null)
return false;
} else if (!incrExpr.equals(other.incrExpr))
return false;
if (incrVarName == null) {
if (other.incrVarName != null)
return false;
} else if (!incrVarName.equals(other.incrVarName))
return false;
if (initValue == null) {
if (other.initValue != null)
return false;
} else if (!initValue.equals(other.initValue))
return false;
if (initVarName == null) {
if (other.initVarName != null)
return false;
} else if (!initVarName.equals(other.initVarName))
return false;
return true;
}
}
|
3e1af2cd74940b047700f7bdfb161031a8ffcb83 | 1,168 | java | Java | src/test/java/org/elasticsearch/test/rest/parser/RestTestParseException.java | uboness/elasticsearch | b3cb59d0243a33c6dfeda1ff517809a4793a59be | [
"Apache-2.0"
] | 35 | 2015-02-26T22:56:48.000Z | 2019-04-17T23:37:56.000Z | src/test/java/org/elasticsearch/test/rest/parser/RestTestParseException.java | uboness/elasticsearch | b3cb59d0243a33c6dfeda1ff517809a4793a59be | [
"Apache-2.0"
] | 19 | 2019-07-25T21:25:23.000Z | 2021-07-30T21:24:52.000Z | src/test/java/org/elasticsearch/test/rest/parser/RestTestParseException.java | uboness/elasticsearch | b3cb59d0243a33c6dfeda1ff517809a4793a59be | [
"Apache-2.0"
] | 15 | 2017-01-12T10:16:22.000Z | 2019-04-18T21:18:41.000Z | 34.352941 | 91 | 0.744863 | 11,417 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.test.rest.parser;
/**
* Exception thrown whenever there is a problem parsing any of the REST test suite fragment
*/
public class RestTestParseException extends Exception {
RestTestParseException(String message) {
super(message);
}
RestTestParseException(String message, Throwable cause) {
super(message, cause);
}
}
|
3e1af336ccbc34f9175ec6768dc9968c73843af9 | 1,321 | java | Java | src/java/com/cloudera/sqoop/mapreduce/db/OracleDateSplitter.java | alexanghh/sqoop | 960b5147f6e534e8806a2c31155dd9b57e5b99cd | [
"Apache-2.0"
] | 86 | 2017-01-20T02:20:22.000Z | 2022-03-31T02:08:26.000Z | src/java/com/cloudera/sqoop/mapreduce/db/OracleDateSplitter.java | alexanghh/sqoop | 960b5147f6e534e8806a2c31155dd9b57e5b99cd | [
"Apache-2.0"
] | 91 | 2017-06-02T15:39:50.000Z | 2022-03-13T03:12:50.000Z | src/java/com/cloudera/sqoop/mapreduce/db/OracleDateSplitter.java | alexanghh/sqoop | 960b5147f6e534e8806a2c31155dd9b57e5b99cd | [
"Apache-2.0"
] | 46 | 2017-05-11T01:57:46.000Z | 2022-02-16T06:23:56.000Z | 40.030303 | 76 | 0.763815 | 11,418 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.sqoop.mapreduce.db;
/**
* Implement DBSplitter over date/time values returned by an Oracle db.
* Make use of logic from DateSplitter, since this just needs to use
* some Oracle-specific functions on the formatting end when generating
* InputSplits.
*
* @deprecated use org.apache.sqoop.mapreduce.db.OracleDateSplitter instead.
* @see org.apache.sqoop.mapreduce.db.OracleDateSplitter
*/
public class OracleDateSplitter
extends org.apache.sqoop.mapreduce.db.OracleDateSplitter {
}
|
3e1af390c1a706fc36031f181e6751f6b4f4fb20 | 3,104 | java | Java | 80.Sharding/sharding-base/src/main/java/com/xiudoua/micro/study/utils/SnowFlakeUtil.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 80.Sharding/sharding-base/src/main/java/com/xiudoua/micro/study/utils/SnowFlakeUtil.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 80.Sharding/sharding-base/src/main/java/com/xiudoua/micro/study/utils/SnowFlakeUtil.java | north0808/SpringAll | 5e31ec2135e147e29b0c598ca2559e15bba6272c | [
"MIT"
] | null | null | null | 29.846154 | 119 | 0.570876 | 11,419 | package com.xiudoua.micro.study.utils;
/**
* @desc
* @author JustFresh
* @time 2021年2月21日 下午10:26:50
*/
public class SnowFlakeUtil {
/**
* 起始的时间戳
*/
private final static long START_STMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public SnowFlakeUtil(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 产生下一个ID
*
* @param ifEvenNum 是否偶数 true 时间不连续全是偶数 时间连续 奇数偶数 false 时间不连续 奇偶都有 所以一般建议用false
* @return
*/
public synchronized long nextId(boolean ifEvenNum) {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
/**
* 时间不连续出来全是偶数
*/
if(ifEvenNum){
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
}else {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
} |
3e1af4ef64531d644cdfe02b0729660cc856ff0c | 369 | java | Java | src/main/java/ch/so/agi/ilivalidator/AppConfig.java | edigonzales/ilivalidator-web-service-client | 1b7047dd10a0a1ba96c91376a8fd0cde5882d1bd | [
"MIT"
] | null | null | null | src/main/java/ch/so/agi/ilivalidator/AppConfig.java | edigonzales/ilivalidator-web-service-client | 1b7047dd10a0a1ba96c91376a8fd0cde5882d1bd | [
"MIT"
] | null | null | null | src/main/java/ch/so/agi/ilivalidator/AppConfig.java | edigonzales/ilivalidator-web-service-client | 1b7047dd10a0a1ba96c91376a8fd0cde5882d1bd | [
"MIT"
] | null | null | null | 26.357143 | 60 | 0.796748 | 11,420 | package ch.so.agi.ilivalidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ForwardedHeaderFilter;
@Configuration
public class AppConfig {
@Bean
public ForwardedHeaderFilter forwardedHeaderFilter() {
return new ForwardedHeaderFilter();
}
}
|
3e1af569de7966ec574e704fbe8d58d9ace85956 | 1,530 | java | Java | src/main/java/network/pxl8/endercomms/common/event/Register.java | Pxl-8/EnderComms | 6ba3090919ea06080bbcb210ea6335ab289ad0fd | [
"MIT"
] | null | null | null | src/main/java/network/pxl8/endercomms/common/event/Register.java | Pxl-8/EnderComms | 6ba3090919ea06080bbcb210ea6335ab289ad0fd | [
"MIT"
] | null | null | null | src/main/java/network/pxl8/endercomms/common/event/Register.java | Pxl-8/EnderComms | 6ba3090919ea06080bbcb210ea6335ab289ad0fd | [
"MIT"
] | null | null | null | 35.581395 | 124 | 0.784967 | 11,421 | package network.pxl8.endercomms.common.event;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import network.pxl8.endercomms.common.item.ModItems;
@Mod.EventBusSubscriber
public class Register {
@SubscribeEvent
public static void registerItems(RegistryEvent.Register<Item> event) {
ModItems.register(event.getRegistry());
}
@SubscribeEvent
public static void registerModels(ModelRegistryEvent event) {
registerModel(ModItems.enderComm);
}
@SubscribeEvent
public static void test(PlayerInteractEvent event) {
}
private static void registerModel(Item item) {
ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
public static CreativeTabs enderCommTab = new CreativeTabs("tab_endercomms") {
@Override
public ItemStack getTabIconItem() { return new ItemStack(ModItems.enderComm); }
};
}
|
3e1af82c0cbeea93a5f63f0d8d74f518c214e2aa | 1,787 | java | Java | spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java | jbrisbin/spring-data-rest | 054b9dc5c513eb68aa90777455c05efbb3e0c2c7 | [
"Apache-2.0"
] | 1 | 2015-03-19T13:49:16.000Z | 2015-03-19T13:49:16.000Z | spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java | jbrisbin/spring-data-rest | 054b9dc5c513eb68aa90777455c05efbb3e0c2c7 | [
"Apache-2.0"
] | null | null | null | spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/BaseUriMethodArgumentResolver.java | jbrisbin/spring-data-rest | 054b9dc5c513eb68aa90777455c05efbb3e0c2c7 | [
"Apache-2.0"
] | null | null | null | 38.847826 | 99 | 0.768886 | 11,422 | package org.springframework.data.rest.webmvc;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.rest.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.annotation.BaseURI;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
/**
* @author Jon Brisbin
*/
public class BaseUriMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private RepositoryRestConfiguration config;
@Override public boolean supportsParameter(MethodParameter parameter) {
return (null != parameter.getParameterAnnotation(BaseURI.class)
&& parameter.getParameterType() == URI.class);
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
// Use configured URI if there is one or set the current one as the default if not.
if(null == config.getBaseUri()) {
URI baseUri = ServletUriComponentsBuilder.fromServletMapping(servletRequest).build().toUri();
config.setBaseUri(baseUri);
}
return config.getBaseUri();
}
}
|
3e1af90a6bd1a6255995afda5ff2776ca01fa2ee | 5,326 | java | Java | java/jlogTest.java | postwait/jlog | ec598885f8204176a4d83b887b8514a8e05a7e3a | [
"BSD-3-Clause"
] | 37 | 2015-01-25T06:07:26.000Z | 2022-02-17T17:35:32.000Z | java/jlogTest.java | postwait/jlog | ec598885f8204176a4d83b887b8514a8e05a7e3a | [
"BSD-3-Clause"
] | 16 | 2015-08-14T19:22:51.000Z | 2021-05-13T09:09:16.000Z | java/jlogTest.java | postwait/jlog | ec598885f8204176a4d83b887b8514a8e05a7e3a | [
"BSD-3-Clause"
] | 21 | 2015-03-10T18:43:42.000Z | 2021-04-20T13:53:47.000Z | 31.514793 | 99 | 0.543935 | 11,423 | import com.omniti.labs.jlog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class jlogTest {
static final String payload = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static final String[] names = { "00000001", "00000003", "0000010a", "cp.7473" } ;
static final int pcnt = 1000000;
String jlogpath = "/tmp/foo.jlog";
//String[] args;
void log(String m) { System.err.println(m); }
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}
void fail(String msg) throws Exception {
throw new Exception(msg);
}
void test_subscriber(String s) throws Exception {
log("adding subscriber " + s);
jlog ctx = new jlog(jlogpath);
ctx.add_subscriber(s, jlog.jlog_position.JLOG_BEGIN);
try {
ctx.add_subscriber(s, jlog.jlog_position.JLOG_BEGIN);
} catch(jlog.jlogSubscriberExistsException ok) {
}
}
void initialize() throws Exception {
File f = new File(jlogpath);
if(f.exists()) {
log("cleaning up " + jlogpath);
delete(f);
}
log("initializing new jlog at " + jlogpath);
jlog ctx = new jlog(jlogpath);
ctx.init();
}
void assert_subscriber(String s) throws Exception {
log("checking subscriber " + s);
jlog ctx = new jlog(jlogpath);
String[] subs = ctx.list_subscribers();
for(String sub : subs) {
if(sub.equals(s)) return;
}
fail("nope");
}
jlog open_writer() throws Exception {
log("opening writer");
jlog ctx = new jlog(jlogpath);
ctx.open_writer();
return ctx;
}
jlog open_reader(String s) throws Exception {
log("opening reader: " + s);
jlog ctx = new jlog(jlogpath);
ctx.open_reader(s);
return ctx;
}
void write_payloads(int cnt) throws Exception {
jlog ctx = open_writer();
log("writing out " + cnt + " " + payload.getBytes().length + " byte payloads");
for(int i = 0; i < cnt; i++)
ctx.write(payload);
}
void read_check(String s, int expect, boolean sizeup) throws Exception {
int cnt = 0;
jlog ctx = open_reader(s);
long start = ctx.raw_size();
while(true) {
jlog.Id chkpt, cur;
jlog.Interval interval = ctx.read_interval();
chkpt = cur = interval.getStart();
log("reading interval(" + cur + "): " + interval);
int i, batchsize = interval.count();
if(batchsize == 0) break;
for(i = 0; i < batchsize; i++) {
if(i != 0) cur.increment();
@SuppressWarnings("unused")
jlog.Message m = ctx.read(cur);
cnt++;
}
ctx.read_checkpoint(chkpt);
}
if(cnt != expect) fail("got wrong read count: " + cnt + " != " + expect);
long end = ctx.raw_size();
log("checking that size " + (sizeup ? "increased" : "decreased"));
if(sizeup && (end < start)) fail("size didn't increase as exptected");
if(!sizeup && (end > start)) fail("size didn't decrease as expected");
}
void addonefile(String fn, int i) throws Exception {
String x = jlogpath + "/" + fn;
PrintWriter pw = new PrintWriter(x);
pw.write(payload, i*7, 7);
pw.close();
}
void corruptmetastore() throws Exception {
String x = jlogpath + "/metastore";
PrintWriter pw = new PrintWriter(x);
pw.write(payload, 0, 16);
pw.close();
}
void addsomefiles() throws Exception {
for(int i=0;i<names.length;i++)
addonefile(names[i], i);
corruptmetastore();
}
void test_repair(String s) throws Exception {
log("Testing " + s);
jlog ctx = new jlog(jlogpath);
addsomefiles();
int res = ctx.repair(0);
String sres = (res == 0) ? "failed" : "succeeded";
log("Repair " + sres);
}
public jlogTest(String[] called_args) {
if(called_args.length > 0) jlogpath = called_args[0];
}
public void run() {
try {
initialize();
test_subscriber("testing");
assert_subscriber("testing");
test_subscriber("witness");
assert_subscriber("witness");
try { assert_subscriber("badguy");
fail("found badguy subscriber"); }
catch (Exception e) {
if(!e.getMessage().equals("nope")) throw e;
}
write_payloads(pcnt);
read_check("witness", pcnt, true);
read_check("testing", pcnt, false);
/* reinitialize for the repair check */
initialize();
test_repair("repair");
} catch(Exception catchall) {
catchall.printStackTrace();
}
}
public static void main(String[] args) {
(new jlogTest(args)).run();
}
}
|
3e1af950749891e1396d88eb5877f90692022529 | 1,518 | java | Java | src/main/java/com/examplehub/searches/BinarySearch.java | letscode-17/Java | 8f24ae10be74ec6d4d06b5466f0c530b0e42a035 | [
"Apache-2.0"
] | 15 | 2020-09-28T06:23:43.000Z | 2020-12-14T03:41:58.000Z | src/main/java/com/examplehub/searches/BinarySearch.java | letscode-17/Java | 8f24ae10be74ec6d4d06b5466f0c530b0e42a035 | [
"Apache-2.0"
] | 13 | 2020-09-28T06:23:44.000Z | 2021-08-22T11:03:14.000Z | src/main/java/com/examplehub/searches/BinarySearch.java | letscode-17/Java | 8f24ae10be74ec6d4d06b5466f0c530b0e42a035 | [
"Apache-2.0"
] | 10 | 2020-11-02T03:38:34.000Z | 2022-03-14T07:25:00.000Z | 27.107143 | 65 | 0.576416 | 11,424 | package com.examplehub.searches;
import com.examplehub.maths.MiddleIndexCalculate;
public class BinarySearch implements Search {
/**
* Binary search algorithm.
*
* @param numbers the numbers to be searched.
* @param key the key to be searched.
* @return index of {@code key} value if found, otherwise -1.
*/
@Override
public int search(int[] numbers, int key) {
int left = 0;
int right = numbers.length - 1;
while (left <= right) {
int mid = MiddleIndexCalculate.middle(left, right);
if (key == numbers[mid]) {
return mid;
} else if (key > numbers[mid]) {
left = mid + 1; /* search at right sub array */
} else {
right = mid - 1; /* search at left sub array */
}
}
return -1;
}
/**
* Generic binary search algorithm.
*
* @param array the array to be searched.
* @param key the key object to be searched.
* @param <T> the class of the objects in the array.
* @return index of {@code key} if found, otherwise -1.
*/
@Override
public <T extends Comparable<T>> int search(T[] array, T key) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (key.compareTo(array[mid]) == 0) {
return mid;
} else if (key.compareTo(array[mid]) > 0) {
left = mid + 1; /* search at right sub array */
} else {
right = mid - 1; /* search at left sub array */
}
}
return -1;
}
}
|
3e1afa1225dacc9f0fa7d8b1f91ee7334b403365 | 249 | java | Java | Demo-Project/atguigu-Mybatis/SSM/src/com/atguigu/ssm/mapper/EmpMapper.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | null | null | null | Demo-Project/atguigu-Mybatis/SSM/src/com/atguigu/ssm/mapper/EmpMapper.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | 1 | 2020-09-14T07:46:05.000Z | 2020-09-14T07:46:05.000Z | Demo-Project/atguigu-Mybatis/SSM/src/com/atguigu/ssm/mapper/EmpMapper.java | juyss/workspace | 6005307287200ce5c208f02ff307409d0d34a5e5 | [
"MulanPSL-1.0"
] | null | null | null | 12.45 | 32 | 0.714859 | 11,425 | package com.atguigu.ssm.mapper;
import java.util.List;
import com.atguigu.ssm.bean.Emp;
public interface EmpMapper {
//获取所有的员工信息
List<Emp> getAllEmp();
//根据eid获取员工信息
Emp getEmpByEid(String eid);
//修改员工信息
void updateEmp(Emp emp);
}
|
3e1afb900f7a5f6c86c1d3e6b50a1320eec898f8 | 1,777 | java | Java | src/main/resources/libs/JAT/jat/alg/estimators/MeasurementModel.java | MaximTar/satellite | 7b11db72c2fbdb7934b389e784bec2ea2dedb034 | [
"Apache-2.0"
] | null | null | null | src/main/resources/libs/JAT/jat/alg/estimators/MeasurementModel.java | MaximTar/satellite | 7b11db72c2fbdb7934b389e784bec2ea2dedb034 | [
"Apache-2.0"
] | null | null | null | src/main/resources/libs/JAT/jat/alg/estimators/MeasurementModel.java | MaximTar/satellite | 7b11db72c2fbdb7934b389e784bec2ea2dedb034 | [
"Apache-2.0"
] | null | null | null | 28.507937 | 78 | 0.723274 | 11,427 | package jat.alg.estimators;
/* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 The JAT Project. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement, version 1.3 or later.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the NASA Goddard
* Space Flight Center at anpch@example.com.
*
*
* File Created on May 7, 2003
*/
import jat.matvec.data.*;
/**
* The MeasurementModel Interface provides a mechanism to pass measurements
* and the measurement model to an estimator, such as the ExtendedKalmanFilter.
*
* @author <a href="mailto:hzdkv@example.com">Dave Gaylor
* @version 1.0
*/
public interface MeasurementModel {
/**
* Returns the H matrix
* @param xref VectorN containing the current state
* @return H matrix (measurement state relation)
*/
public VectorN H (VectorN xref);
/**
* Returns the measurement noise value
* @return measurement noise (sigma^2)
*/
public double R ();
/**
* Returns the predicted measurement based on the current state
* @param index measurement index
* @param t time of the measurement
* @param xref VectorN with the current state at the measurement time
*/
public double zPred (int index, double t, VectorN xref);
/**
* Checks for remaining measurements.
* True = more measurements left to be processed.
* @param index measurement index.
*/
}
|
3e1afc82cd6abc330a54d3b8c207deacf3277348 | 411 | java | Java | src/com/bs/service/FwxmService.java | ydf0925/Trap | aa22370ddeca2d5fb672018cceba65c7dc231766 | [
"MIT"
] | null | null | null | src/com/bs/service/FwxmService.java | ydf0925/Trap | aa22370ddeca2d5fb672018cceba65c7dc231766 | [
"MIT"
] | null | null | null | src/com/bs/service/FwxmService.java | ydf0925/Trap | aa22370ddeca2d5fb672018cceba65c7dc231766 | [
"MIT"
] | null | null | null | 16.44 | 54 | 0.725061 | 11,428 |
package com.bs.service;
import java.util.List;
import com.bs.entity.Fwxm;
import com.bs.utils.PageUtil;
/**
* @author 作者 :yuedengfeng
* @date 创建时间:2019年9月25日 上午10:27:04
* @version 1.0
*/
public interface FwxmService extends Service {
void addFwxm(Fwxm fwxm);
void deleteFwxm(int id);
void updateFwxm(Fwxm fwxm);
PageUtil<Fwxm> selectFwxmList(int page,int pageSize);
List<Fwxm> selectList();
}
|
3e1afd3f6c23ecf3d76fcbff39342e0e35614fbe | 2,404 | java | Java | src/cmps252/HW4_2/UnitTesting/record_1659.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 1 | 2020-11-03T07:31:40.000Z | 2020-11-03T07:31:40.000Z | src/cmps252/HW4_2/UnitTesting/record_1659.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 2 | 2020-10-27T17:31:16.000Z | 2020-10-28T02:16:49.000Z | src/cmps252/HW4_2/UnitTesting/record_1659.java | issasaidi/cmps252_hw4.2 | f8e96065e2a4f172c8b685f03f954694f4810c14 | [
"MIT"
] | 108 | 2020-10-26T11:54:05.000Z | 2021-01-16T20:00:17.000Z | 25 | 74 | 0.728333 | 11,429 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("16")
class Record_1659 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1659: FirstName is Melisa")
void FirstNameOfRecord1659() {
assertEquals("Melisa", customers.get(1658).getFirstName());
}
@Test
@DisplayName("Record 1659: LastName is Bacy")
void LastNameOfRecord1659() {
assertEquals("Bacy", customers.get(1658).getLastName());
}
@Test
@DisplayName("Record 1659: Company is Air Flow Inc")
void CompanyOfRecord1659() {
assertEquals("Air Flow Inc", customers.get(1658).getCompany());
}
@Test
@DisplayName("Record 1659: Address is 1305 1st St E")
void AddressOfRecord1659() {
assertEquals("1305 1st St E", customers.get(1658).getAddress());
}
@Test
@DisplayName("Record 1659: City is Humble")
void CityOfRecord1659() {
assertEquals("Humble", customers.get(1658).getCity());
}
@Test
@DisplayName("Record 1659: County is Harris")
void CountyOfRecord1659() {
assertEquals("Harris", customers.get(1658).getCounty());
}
@Test
@DisplayName("Record 1659: State is TX")
void StateOfRecord1659() {
assertEquals("TX", customers.get(1658).getState());
}
@Test
@DisplayName("Record 1659: ZIP is 77338")
void ZIPOfRecord1659() {
assertEquals("77338", customers.get(1658).getZIP());
}
@Test
@DisplayName("Record 1659: Phone is 281-446-4690")
void PhoneOfRecord1659() {
assertEquals("281-446-4690", customers.get(1658).getPhone());
}
@Test
@DisplayName("Record 1659: Fax is 281-446-4391")
void FaxOfRecord1659() {
assertEquals("281-446-4391", customers.get(1658).getFax());
}
@Test
@DisplayName("Record 1659: Email is ychag@example.com")
void EmailOfRecord1659() {
assertEquals("ychag@example.com", customers.get(1658).getEmail());
}
@Test
@DisplayName("Record 1659: Web is http://www.melisabacy.com")
void WebOfRecord1659() {
assertEquals("http://www.melisabacy.com", customers.get(1658).getWeb());
}
}
|
3e1afd9400fc0f285754258d1ef1619ae8bceb82 | 6,245 | java | Java | app/src/main/java/com/android/example/framework/viewdrawing/CirclePercentView.java | Edgar-Dong/Study | 43cd4e0beb5bfbf6e993540cb274da6ee761418f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/example/framework/viewdrawing/CirclePercentView.java | Edgar-Dong/Study | 43cd4e0beb5bfbf6e993540cb274da6ee761418f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/example/framework/viewdrawing/CirclePercentView.java | Edgar-Dong/Study | 43cd4e0beb5bfbf6e993540cb274da6ee761418f | [
"Apache-2.0"
] | null | null | null | 36.098266 | 205 | 0.620336 | 11,430 | package com.android.example.framework.viewdrawing;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import androidx.annotation.Nullable;
import com.android.example.R;
import com.android.example.common.log.Logger;
/**
* @author:無忌
* @date:2020/11/10
* @description:
*/
public class CirclePercentView extends View {
private static final String TAG = "CirclePercentView";
//大圆半径
private int mRadius;
//大圆填充色
private int mBigCircleColor;
//扇形填充色
private int mSmallColor;
//色带宽度
private float mStripeWidth;
//动画位置百分比进度
private int mCurPercent;
//中心百分比文字大小
private float mCenterTextSize;
//扇形扫过的角度
private float mSweepAngle;
//圆心坐标
private int x, y;
private int mWidth, mHeight;
public CirclePercentView(Context context) {
this(context, null);
}
public CirclePercentView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CirclePercentView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePercentView, defStyleAttr, 0);
mStripeWidth = a.getDimension(R.styleable.CirclePercentView_stripeWidth, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics()));
mCurPercent = a.getInteger(R.styleable.CirclePercentView_percent, 0);
mBigCircleColor = a.getColor(R.styleable.CirclePercentView_bigColor, 0xff6950a1);
mSmallColor = a.getColor(R.styleable.CirclePercentView_smallColor, 0xffafb4db);
mCenterTextSize = a.getDimensionPixelSize(R.styleable.CirclePercentView_centerTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, context.getResources().getDisplayMetrics()));
mRadius = a.getDimensionPixelSize(R.styleable.CirclePercentView_radius, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, context.getResources().getDisplayMetrics()));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Logger.get().d(TAG, "onMeasure widthSize:" + widthSize + ", heightSize:" + heightSize + ", widthMode:" + getMeasureSpecMode(widthMode) + ", heightMode:" + getMeasureSpecMode(heightMode));
if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
mRadius = Math.min(widthSize, heightSize) / 2;
x = widthSize / 2;
y = heightSize / 2;
mWidth = widthSize;
mHeight = heightSize;
}
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
mWidth = (int) (mRadius * 2);
mHeight = (int) (mRadius * 2);
x = mRadius;
y = mRadius;
}
Logger.get().d(TAG, "onMeasure mWidth:" + mWidth + ", mHeight:" + mHeight + ", x:" + x + ", y:" + y + ", mRadius:" + mRadius);
setMeasuredDimension(mWidth, mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Logger.get().d(TAG, "onDraw x=" + x + ", y=" + y + ", mWidth=" + mWidth + ", mHeight=" + mHeight);
//step1绘制大圆
Paint bigCirclePaint = new Paint();
bigCirclePaint.setAntiAlias(true);
bigCirclePaint.setColor(mBigCircleColor);
canvas.drawCircle(x, y, mRadius, bigCirclePaint);
//step2绘制扇形
mSweepAngle = (float) (mCurPercent * 3.6);
RectF rect = new RectF(0, 0, mWidth, mHeight);
Paint sectorPaint = new Paint();
sectorPaint.setAntiAlias(true);
sectorPaint.setColor(mSmallColor);
canvas.drawArc(rect, 270, mSweepAngle, true, sectorPaint);
//step3绘制小圆,颜色透明
Paint smallCirclePaint = new Paint();
smallCirclePaint.setAntiAlias(true);
smallCirclePaint.setColor(mBigCircleColor);
canvas.drawCircle(x, y, mRadius - mStripeWidth, smallCirclePaint);
//step4绘制文本
String text = mCurPercent + "%";
Paint textPaint = new Paint();
textPaint.setTextSize(mCenterTextSize);
float textLength = textPaint.measureText(text);
textPaint.setColor(Color.WHITE);
canvas.drawText(text, x - textLength / 2, y, textPaint);
}
private void setCurPercent(int percent) {
new Thread(new Runnable() {
@Override
public void run() {
int sleepTime = 0;
for (int i = 0; i <= percent; i++) {
if (i % 20 == 0) {
sleepTime += 2;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
mCurPercent = i;
postInvalidate();
}
}
}).start();
}
public void setPercent(int percent) {
if (percent > 100) {
throw new IllegalArgumentException("percent must less than 100!");
}
setCurPercent(percent);
}
private String getMeasureSpecMode(int value) {
String modeStr = "";
switch (value) {
case MeasureSpec.EXACTLY:
modeStr = "EXACTLY";
break;
case MeasureSpec.AT_MOST:
modeStr = "AT_MOST";
break;
case MeasureSpec.UNSPECIFIED:
modeStr = "UNSPECIFIED";
break;
default:
break;
}
return modeStr;
}
}
|
3e1afe3d2459fc88d8049e08b5f26f1ae0151269 | 4,844 | java | Java | integration/broker-tests/tests-integration/tests-amqp/src/test/java/org/wso2/mb/integration/tests/amqp/load/ManySubscribersTestCase.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 339 | 2017-03-29T20:40:34.000Z | 2022-03-31T08:05:43.000Z | integration/broker-tests/tests-integration/tests-amqp/src/test/java/org/wso2/mb/integration/tests/amqp/load/ManySubscribersTestCase.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 3,938 | 2017-01-23T12:28:02.000Z | 2022-03-28T14:20:20.000Z | integration/broker-tests/tests-integration/tests-amqp/src/test/java/org/wso2/mb/integration/tests/amqp/load/ManySubscribersTestCase.java | sajithaliyanage/product-ei | 7cc0ab117429967bc01d602a23805e9955924e6a | [
"Apache-2.0"
] | 345 | 2016-12-21T11:59:07.000Z | 2022-03-31T08:39:38.000Z | 39.382114 | 137 | 0.713254 | 11,431 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.mb.integration.tests.amqp.load;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.mb.integration.common.clients.AndesClient;
import org.wso2.mb.integration.common.clients.configurations.AndesJMSConsumerClientConfiguration;
import org.wso2.mb.integration.common.clients.configurations.AndesJMSPublisherClientConfiguration;
import org.wso2.mb.integration.common.clients.exceptions.AndesClientException;
import org.wso2.mb.integration.common.clients.operations.utils.AndesClientConstants;
import org.wso2.mb.integration.common.clients.exceptions.AndesClientConfigurationException;
import org.wso2.mb.integration.common.clients.operations.utils.AndesClientUtils;
import org.wso2.mb.integration.common.clients.operations.utils.ExchangeType;
import org.wso2.mb.integration.common.utils.backend.MBIntegrationBaseTest;
import javax.jms.JMSException;
import javax.naming.NamingException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
/**
* This class contains tests for receiving messages through a large number of subscribers.
*/
public class ManySubscribersTestCase extends MBIntegrationBaseTest {
/**
* Message count to send
*/
private static final long SEND_COUNT = 100000L;
/**
* Expected message count
*/
private static final long EXPECTED_COUNT = SEND_COUNT;
/**
* Number of subscribers
*/
private static final int NUMBER_OF_SUBSCRIBERS = 1000;
/**
* Number of publishers
*/
private static final int NUMBER_OF_PUBLISHERS = 1;
/**
* Initialize the test as super tenant user.
*
* @throws XPathExpressionException
*/
@BeforeClass(alwaysRun = true)
public void init() throws XPathExpressionException {
super.init(TestUserMode.SUPER_TENANT_USER);
}
/**
* Test message sending to 1000 subscribers at the same time.
*
* @throws AndesClientConfigurationException
* @throws NamingException
* @throws JMSException
* @throws IOException
* @throws AndesClientException
*/
@Test(groups = "wso2.mb", description = "Message content validation test case")
public void performMillionMessageManyConsumersTestCase()
throws Exception {
try {
// Creating a consumer client configuration
AndesJMSConsumerClientConfiguration consumerConfig =
new AndesJMSConsumerClientConfiguration(ExchangeType.QUEUE, "singleQueueMillion");
consumerConfig.setMaximumMessagesToReceived(EXPECTED_COUNT);
consumerConfig.setPrintsPerMessageCount(EXPECTED_COUNT / 10L);
// Creating a consumer client configuration
AndesJMSPublisherClientConfiguration publisherConfig =
new AndesJMSPublisherClientConfiguration(ExchangeType.QUEUE, "singleQueueMillion");
publisherConfig.setNumberOfMessagesToSend(SEND_COUNT);
publisherConfig.setPrintsPerMessageCount(SEND_COUNT / 10L);
AndesClient consumerClient =
new AndesClient(consumerConfig, NUMBER_OF_SUBSCRIBERS, true);
consumerClient.setStartDelay(100L); // Use a starting delay between consumers
consumerClient.startClient();
AndesClient publisherClient =
new AndesClient(publisherConfig, NUMBER_OF_PUBLISHERS, true);
publisherClient.startClient();
AndesClientUtils
.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
// Evaluating
Assert.assertEquals(publisherClient
.getSentMessageCount(), SEND_COUNT * NUMBER_OF_SUBSCRIBERS, "Message sending failed");
Assert.assertEquals(consumerClient
.getReceivedMessageCount(), EXPECTED_COUNT * NUMBER_OF_SUBSCRIBERS, "Message receiving failed.");
} catch (OutOfMemoryError e) {
restartServer();
}
}
}
|
3e1aff365b26734e579a99b3d7a936b2dde0e52b | 14,060 | java | Java | app/src/main/java/ca/klapstein/baudit/activities/CareProviderHomeActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | null | null | null | app/src/main/java/ca/klapstein/baudit/activities/CareProviderHomeActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | 182 | 2018-10-11T14:02:45.000Z | 2018-12-03T21:36:05.000Z | app/src/main/java/ca/klapstein/baudit/activities/CareProviderHomeActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | 1 | 2018-10-12T03:27:38.000Z | 2018-10-12T03:27:38.000Z | 39.055556 | 128 | 0.57155 | 11,432 | package ca.klapstein.baudit.activities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.*;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import ca.klapstein.baudit.R;
import ca.klapstein.baudit.models.DataModel;
import ca.klapstein.baudit.presenters.CareProviderHomePresenter;
import ca.klapstein.baudit.views.CareProviderHomeView;
import ca.klapstein.baudit.views.PatientRowView;
import static ca.klapstein.baudit.activities.ViewAccountActivity.VIEW_ACCOUNT_USERNAME_EXTRA;
/**
* Activity for listing {@code Patient}s.
*
* @see ca.klapstein.baudit.data.Patient
*/
public class CareProviderHomeActivity extends AppCompatActivity implements CareProviderHomeView {
public static final String PATIENT_USERNAME_EXTRA = "patientUsername";
private static final String TAG = "CareProviderHome";
private final int REQUEST_CODE_QR_SCAN = 101;
private CareProviderHomePresenter presenter;
private RecyclerView patientRecyclerView;
private PatientListAdapter adapter;
private DrawerLayout drawerLayout;
private TextView navHeaderUsername;
private TextView navHeaderEmail;
private TextView patientCountText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_care_provider_home);
Toolbar toolbar = findViewById(R.id.patient_list_toolbar);
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.home);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
presenter = new CareProviderHomePresenter(this, getApplicationContext());
drawerLayout = findViewById(R.id.patient_list_drawer_layout);
patientCountText = findViewById(R.id.patient_count);
NavigationView navigationView = findViewById(R.id.nav_view);
View navHeaderView = navigationView.inflateHeaderView(R.layout.drawer_header);
navHeaderUsername = navHeaderView.findViewById(R.id.nav_header_username);
navHeaderEmail = navHeaderView.findViewById(R.id.nav_header_email);
navHeaderView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CareProviderHomeActivity.this, ViewAccountActivity.class);
intent.putExtra(VIEW_ACCOUNT_USERNAME_EXTRA, presenter.getUsername());
startActivity(intent);
drawerLayout.closeDrawers();
}
});
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case (R.id.nav_edit_account):
startActivity(new Intent(
CareProviderHomeActivity.this,
EditCareProviderAccountActivity.class
));
break;
case (R.id.nav_display_qr_code):
startActivity(new Intent(
getApplicationContext(),
DisplayQRCodeActivity.class
));
break;
case (R.id.nav_unpair):
new DataModel(getApplicationContext()).clearOfflineLoginAccount();
startActivity(new Intent(
getApplicationContext(),
StartActivity.class
));
break;
default:
break;
}
return true;
}
});
patientRecyclerView = findViewById(R.id.patient_list);
adapter = new PatientListAdapter();
patientRecyclerView.setAdapter(adapter);
patientRecyclerView.setLayoutManager(new LinearLayoutManager(this));
FloatingActionButton fab = findViewById(R.id.care_provider_home_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startScanQRCode();
}
});
}
@Override
public void updateRemovePatientError() {
Toast.makeText(this, getResources().getString(R.string.care_provider_remove_patient_failure), Toast.LENGTH_LONG).show();
}
@Override
public void onStart() {
super.onStart();
presenter.viewStarted();
}
@Override
public void updateList() {
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.care_provider_home_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void updateUsernameDisplay(String username) {
navHeaderUsername.setText(username);
}
@Override
public void updateEmailDisplay(String email) {
navHeaderEmail.setText(email);
}
@Override
public void updateAccountLoadError() {
Toast.makeText(this, getResources().getString(R.string.care_provider_account_load_failure), Toast.LENGTH_LONG).show();
}
/**
* Start an activity to start the camera and scan a QR code.
*/
@Override
public void startScanQRCode() {
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, REQUEST_CODE_QR_SCAN);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
startActivity(marketIntent);
}
}
/**
* Catch the result from the QR code scanning activity. And send its obtained data (if the scan
* was successful) to the presenter.
*
* @param requestCode {@code int}
* @param resultCode {@code int}
* @param data {@code Intent}
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QR_SCAN) {
if (resultCode == RESULT_OK) {
String username = data.getStringExtra("SCAN_RESULT");
Log.i(TAG, "obtained qr code decoded string: " + username);
presenter.assignPatient(username);
} else if (resultCode == RESULT_CANCELED) {
Log.e(TAG, "obtained invalid qr code activity result: " + resultCode);
}
}
}
@Override
public void updateScanQRCodeError() {
Toast.makeText(
this,
getResources().getString(R.string.assign_patient_scan_failure),
Toast.LENGTH_LONG
).show();
}
@Override
public void updatePatientCount(int patientNumber) {
patientCountText.setText(String.format(
getResources().getString(R.string.patient_count),
patientNumber
));
}
private class PatientListAdapter extends RecyclerView.Adapter<PatientViewHolder> {
@Override
@NonNull
public PatientViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
CardView v = (CardView) LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_patient, viewGroup, false);
return new PatientViewHolder(v); //Wrap it in a ViewHolder.
}
@Override
public void onBindViewHolder(@NonNull final PatientViewHolder viewHolder, int i) {
presenter.onBindPatientRowViewAtPosition(viewHolder, i);
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
CareProviderHomeActivity.this,
CareProviderProblemListActivity.class
);
intent.putExtra(
PATIENT_USERNAME_EXTRA,
viewHolder.patientUsername.getText().toString()
);
startActivity(intent);
}
});
viewHolder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
PopupMenu menu = new PopupMenu(getApplicationContext(), viewHolder.cardView);
menu.inflate(R.menu.patient_popup_menu);
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.view_patient_account:
Intent intent = new Intent(
getApplicationContext(),
ViewAccountActivity.class
);
intent.putExtra(
VIEW_ACCOUNT_USERNAME_EXTRA,
presenter.getPatientUsername(
viewHolder.getAdapterPosition()
)
);
startActivity(intent);
break;
case R.id.remove_patient:
new AlertDialog.Builder(CareProviderHomeActivity.this)
.setTitle(R.string.remove_patient_question)
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.remove,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int i) {
presenter.removePatient(
viewHolder.getAdapterPosition()
);
}
})
.show();
break;
default:
break;
}
return false;
}
});
menu.show();
return true;
}
});
registerForContextMenu(viewHolder.cardView);
}
@Override
public int getItemCount() {
return presenter.getPatientCount();
}
}
private class PatientViewHolder extends RecyclerView.ViewHolder implements PatientRowView {
private CardView cardView;
private TextView patientName;
private TextView patientUsername;
private TextView patientProblemCount;
PatientViewHolder(CardView card) {
super(card);
cardView = card;
patientName = card.findViewById(R.id.card_patient_name);
patientUsername = card.findViewById(R.id.card_patient_username);
patientProblemCount = card.findViewById(R.id.card_patient_problem_count);
}
@Override
public void onStart() {
// Do nothing.
}
@Override
public void updatePatientNameText(String firstName, String lastName) {
String name = firstName + " " + lastName;
patientName.setText(name);
}
@Override
public void updatePatientUsernameText(String username) {
patientUsername.setText(username);
}
@Override
public void updatePatientProblemNum(int problemNum) {
patientProblemCount.setText(String.valueOf(problemNum));
}
}
}
|
3e1aff88aeb113543f43dcb1b8c6e5a1e8435c35 | 2,541 | java | Java | AccountingManager/app/src/main/java/com/accountingmanager/Sys/GreenDao/GeenDaoManager.java | EldersSun/accountmanager | ccad6bd49dd6a595b31e8eb98eaaa45a111d3d2a | [
"Apache-2.0"
] | 1 | 2019-04-03T10:00:00.000Z | 2019-04-03T10:00:00.000Z | AccountingManager/app/src/main/java/com/accountingmanager/Sys/GreenDao/GeenDaoManager.java | EldersSun/accountmanager | ccad6bd49dd6a595b31e8eb98eaaa45a111d3d2a | [
"Apache-2.0"
] | null | null | null | AccountingManager/app/src/main/java/com/accountingmanager/Sys/GreenDao/GeenDaoManager.java | EldersSun/accountmanager | ccad6bd49dd6a595b31e8eb98eaaa45a111d3d2a | [
"Apache-2.0"
] | 3 | 2018-05-22T09:33:20.000Z | 2018-11-29T06:46:15.000Z | 20.658537 | 99 | 0.508461 | 11,433 | package com.accountingmanager.Sys.GreenDao;
import com.accountingmanager.Application.AccountApplication;
import com.accountingmanager.gen.DaoMaster;
import com.accountingmanager.gen.DaoSession;
import org.greenrobot.greendao.query.QueryBuilder;
/**
* 数据库操作类
* Created by Home-Pc on 2017/4/25.
*/
public class GeenDaoManager {
/**
* 实现功能
* 1.创建数据库
* 2.创建数据库的表
* 3.对数据库的升级
* 4.对数据库的增删查改
*/
/**
* TAG
*/
public static final String TAG = GeenDaoManager.class.getName();
/**
* 数据库名称
*/
private static final String DB_NAME = "greenDao.db";
/**
* 多线程访问
*/
private volatile static GeenDaoManager instance;
/**
* 操作类
*/
private static DaoMaster.DevOpenHelper helper;
/**
* 核心类
*/
private DaoMaster daoMaster;
private DaoSession daoSession;
/**
* 单例模式
*/
public static GeenDaoManager getInstance() {
if (instance == null) {
synchronized (GeenDaoManager.class) {
instance = new GeenDaoManager();
}
}
return instance;
}
/**
* 判断数据库是否存在
*
* @return
*/
public DaoMaster getDaoMaster() {
if (daoMaster == null) {
helper = new DaoMaster.DevOpenHelper(AccountApplication.getInstance(), DB_NAME, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/**
* 完成对数据库的操作,只是个接口
*
* @return
*/
public DaoSession getDaoSession() {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster();
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
/**
* 打开输出日志,默认关闭
*/
public void setDebug() {
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
/**
* 关闭DaoSession
*/
public void closeDaoSession() {
if (daoSession != null) {
daoSession.clear();
daoSession = null;
}
}
/**
* 关闭Helper
*/
public void closeHelper() {
if (helper != null) {
helper.close();
helper = null;
}
}
/**
* 关闭所有的操作
*/
public void closeConnection() {
closeHelper();
closeDaoSession();
}
}
|
3e1b005e9f9aa48d8b16d45efcf938995ee85369 | 9,564 | java | Java | src/org/jgentleframework/services/objectpooling/annotation/SystemPooling.java | OldRepoPreservation/jgentle | f2a5cd788cd7dd408400c4e4750fbb47df640b9c | [
"Apache-2.0"
] | null | null | null | src/org/jgentleframework/services/objectpooling/annotation/SystemPooling.java | OldRepoPreservation/jgentle | f2a5cd788cd7dd408400c4e4750fbb47df640b9c | [
"Apache-2.0"
] | null | null | null | src/org/jgentleframework/services/objectpooling/annotation/SystemPooling.java | OldRepoPreservation/jgentle | f2a5cd788cd7dd408400c4e4750fbb47df640b9c | [
"Apache-2.0"
] | null | null | null | 42.331858 | 81 | 0.716317 | 11,435 | /*
* Copyright 2007-2009 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.
*
* Project: JGentleFramework
*/
package org.jgentleframework.services.objectpooling.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.NoSuchElementException;
import org.jgentleframework.services.objectpooling.Pool;
import org.jgentleframework.services.objectpooling.context.Validate;
/**
* This annotation provides all the configuration parameters that affect the
* pooling service.
*
* @author Quoc Chung - mailto: <a
* href="mailto:anpch@example.com">skydunkpro@yahoo.com</a>
* @date Mar 5, 2008
* @see Pooling
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SystemPooling {
/** The Constant DEFAULT_CAN_BE_POOLED. */
public static final boolean DEFAULT_CAN_BE_POOLED = true;
/** The Constant DEFAULT_CREATION_TIME_OUT. */
public static final long DEFAULT_CREATION_TIME_OUT = -1L;
/** The Constant DEFAULT_INVOCATION. */
public static final boolean DEFAULT_JUST_IN_TIME = false;
/** The Constant DEFAULT_LIFO. */
public static final boolean DEFAULT_LIFO = false;
/** The Constant DEFAULT_MAX_IDLE. */
public static final int DEFAULT_MAX_IDLE = 8;
/** The Constant DEFAULT_MAX_POOL_SIZE. */
public static final int DEFAULT_MAX_POOL_SIZE = 8;
/** The Constant DEFAULT_MIN_EVICTABLE_IDLE_TIME. */
public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME = 1000L * 60L * 30L;
/** The Constant DEFAULT_MIN_IDLE. */
public static final int DEFAULT_MIN_IDLE = 0;
/** The Constant DEFAULT_MIN_POOL_SIZE. */
public static final int DEFAULT_MIN_POOL_SIZE = 0;
/** The Constant DEFAULT_NUM_TESTS_PER_EVICTION_RUN. */
public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
/** The Constant DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME. */
public static final long DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME = -1;
/** The Constant DEFAULT_TEST_ON_OBTAIN. */
public static final boolean DEFAULT_TEST_ON_OBTAIN = true;
/** The Constant DEFAULT_TEST_WHILE_IDLE. */
public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
/** The Constant DEFAULT_TIME_BETWEEN_EVICTION_RUNS. */
public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS = -1L;
/** The Constant EXHAUSTED_BLOCK. */
public static final byte EXHAUSTED_BLOCK = 1;
/** The Constant EXHAUSTED_FAIL. */
public static final byte EXHAUSTED_FAIL = 0;
/** The Constant EXHAUSTED_GROW. */
public static final byte EXHAUSTED_GROW = 2;
/**
* If the {@link Pooling#MaxPoolSize()} value has been reached for a pool
* (no more objects are available to be borrowed), this parameter specifies
* the action to be taken when a request for an object is made to the pool.
* <p>
* - {@link #EXHAUSTED_FAIL} (byte value of 0) - The caller is told that no
* objects are available, by throwing the exception
* {@link NoSuchElementException}.
* <p>
* - {@link #EXHAUSTED_BLOCK} (byte value of 1) - The caller waits until an
* object is returned to the pool and becomes available. The length of time
* the caller waits is specified by the maxWait property. If this property
* is negative, the caller waits indefinitely. If no object is available
* even after the wait is over, a {@link NoSuchElementException} exception
* is thrown.
* <p>
* - {@link #EXHAUSTED_GROW} (byte value of 2) - The pool automatically
* grows (it creates a new object and returns it to the caller).
* <p>
* The default setting for this parameter is {@link #EXHAUSTED_BLOCK}
*/
byte exhaustedActionType() default EXHAUSTED_BLOCK;
/**
* The pool can be configured to behave as a LIFO queue with respect to idle
* objects - always returning the most recently used object from the pool,
* or as a FIFO queue, where <code>borrowObject</code> always returns the
* oldest object in the idle object pool. The lifo determines whether or not
* the pool returns idle objects in last-in-first-out order.
* <p>
* The default setting for this parameter is <b>false</b>.
*/
boolean LIFO() default DEFAULT_LIFO;
/**
* The property is used to configure the maximum number of objects that can
* be in the pool at any given time. If a caller tries to return an object
* to the pool and the pool already contains the maximum number of objects
* sitting idle, specified by this property, the returned object is
* rejected.
* <p>
* As with {@link Pooling#MaxPoolSize()}, values should be greater than or
* equal to <b>0</b>. A negative value implies no limit on the number of
* objects that can stay idle in the pool.
* <p>
* The default setting for this parameter is <b>8</b>.
*/
int maxIdle() default DEFAULT_MAX_IDLE;
/**
* This property specifies the minimum time in milliseconds that objects can
* stay in a pool. After this time is up, these objects are eligible to be
* destroyed, and will be destroyed, the next time the eviction thread is
* run, as specified by the previous property. You can set a negative value
* for this property, which stops objects from being destroyed. However,
* objects can still be destroyed using the next property. Note that this
* value is reset when a borrowed object is returned to the pool.
* <p>
* This value is in milliseconds and should be greater than 0. A value of 0
* or less means that objects aren’t eligible for destruction based on the
* time they have spent in the pool alone.
* <p>
* The default setting for this parameter is <b>1800000 milliseconds</b> or
* <b>half an hour</b>.
*/
long minEvictableIdleTime() default DEFAULT_MIN_EVICTABLE_IDLE_TIME;
/**
* The default minimum number of "sleeping" instances in the pool before the
* evictor thread (if active) spawns new objects.
*/
int minIdle() default DEFAULT_MIN_IDLE;
/**
* This property limits the number of objects to examine in each eviction
* run, if such a thread is running. This allows you to enforce a kind of
* random check on the idle objects, rather than a fullscale check (which,
* if the number of idle objects is large, can be processor intensive).
* <p>
* This value should be <b>0</b> or greater. If it’s <b>0</b>, then of
* course, no objects will be examined. However, if you supply a negative
* value, you can enable fractional checking. Thus, if you supply a value of
* -2, it tells the evictor thread to examine 1/2 objects (roughly).
* <p>
* The default setting for this parameter is <b>3</b>.
*/
int numTestsPerEvictionRun() default DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
/**
* The minimum amount of time an object may sit idle in the pool before it
* is eligible for eviction by the idle object evictor (if any), with the
* extra condition that at least "minIdle" amount of object remain in the
* pool. When non-positive, no objects will be evicted from the pool due to
* idle time alone.
*/
long softMinEvictableIdleTime() default DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME;
/**
* When <tt>true</tt>, object beans will be {@link Validate#validate()
* validated} before being returned by the {@link Pool#obtainObject()}
* method. If the object fails to validate, it will be dropped from the
* pool, and we will attempt to borrow another.
*/
boolean testOnObtain() default DEFAULT_TEST_ON_OBTAIN;
/**
* This property indicates to the eviction thread (if such a thread is
* running) that objects must be tested when they’re sitting idle in the
* pool. They’re tested by calling the validateObject method if it existed.
* It’s up to the validating method to decide how objects are validated.
* Invalidated objects are destroyed by calling the destroyObject method.
* <p>
* The default setting for this parameter is <b>false</b>.
*
* @see Validate
*/
boolean testWhileIdle() default DEFAULT_TEST_WHILE_IDLE;
/**
* This property controls the spawning of a thread and the time between its
* active runs. This thread can examine idle objects in the pool and destroy
* these objects to conserve system resources. A negative or <b>0</b> value
* for this property ensures that no such thread is started. Even if such a
* thread is started, your objects can be prevented from being evicted by
* using the {@link #minEvictableIdleTime()} property.
* <p>
* This value is in milliseconds and should be greater than <b>0</b>. A
* value of 0 or less ensures that this thread isn’t started.
* <p>
* The default setting for this parameter is <b>-1</b> (eviction thread
* isn’t started by default).
*/
long timeBetweenEvictionRuns() default DEFAULT_TIME_BETWEEN_EVICTION_RUNS;
}
|
3e1b006fa3d629d9c0d6c04634b161881bfca348 | 8,199 | java | Java | commLib/src/main/java/com/dev/pipi/commfunc/nfc/NFCHelper.java | pipidev/commLib | 199229f3240e3f28c0e546e1dce9241fc48c71c6 | [
"Apache-2.0"
] | null | null | null | commLib/src/main/java/com/dev/pipi/commfunc/nfc/NFCHelper.java | pipidev/commLib | 199229f3240e3f28c0e546e1dce9241fc48c71c6 | [
"Apache-2.0"
] | null | null | null | commLib/src/main/java/com/dev/pipi/commfunc/nfc/NFCHelper.java | pipidev/commLib | 199229f3240e3f28c0e546e1dce9241fc48c71c6 | [
"Apache-2.0"
] | null | null | null | 34.020747 | 119 | 0.562995 | 11,436 | package com.dev.pipi.commfunc.nfc;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.blankj.utilcode.util.ToastUtils;
import com.dev.pipi.commlib.R;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
/**
* <pre>
* author : pipi
* e-mail : xxx@xx
* time : 2018/09/14
* desc :
* version: 1.0
* </pre>
*/
public class NFCHelper {
private Context context;
private OnClickListener mClickListener;
public void setOnClickListener(OnClickListener clickListener) {
mClickListener = clickListener;
}
private NFCHelper(Context context){
super();
this.context = context;
}
public static NFCHelper newInstance(Context context) {
return new NFCHelper(context);
}
public boolean isSupportOrEnableNfc(){
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter == null) {
ToastUtils.showShort("设备不支持NFC!");
return false;
}
if (!nfcAdapter.isEnabled()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.nfc_open))
.setMessage(context.getString(R.string.nfc_open_tip))
.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mClickListener != null) {
mClickListener.onCancel();
} else {
dialog.dismiss();
}
}
})
.setPositiveButton(context.getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
context.startActivity(intent);
}
})
.show();
return false;
}
return true;
}
/**
* 读取NFC标签文本数据
*/
public String readNfcTag(Intent intent) {
if (!isSupportOrEnableNfc()) return "";
//1.获取Tag对象
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//2.获取Ndef的实例
Ndef ndef = Ndef.get(detectedTag);
Log.i(getClass().getSimpleName(), "type:" + ndef.getType() + ",maxsize:" + ndef.getMaxSize() + " bytes");
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msgs[] = null;
int contentSize = 0;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
contentSize += msgs[i].toByteArray().length;
}
}
try {
if (msgs != null) {
NdefRecord record = msgs[0].getRecords()[0];
String tagText = parseTextRecord(record);
Log.i(getClass().getSimpleName(), "tagText:" + tagText + ",contentSize:" + contentSize + " bytes");
return tagText;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
/**
* 解析NDEF文本数据,从第三个字节开始,后面的文本数据
*
* @param ndefRecord
* @return
*/
private String parseTextRecord(NdefRecord ndefRecord) {
/**
* 判断数据是否为NDEF格式
*/
//判断TNF
if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
return null;
}
//判断可变的长度的类型
if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
return null;
}
try {
//获得字节数组,然后进行分析
byte[] payload = ndefRecord.getPayload();
//下面开始NDEF文本数据第一个字节,状态字节
//判断文本是基于UTF-8还是UTF-16的,取第一个字节"位与"上16进制的80,16进制的80也就是最高位是1,
//其他位都是0,所以进行"位与"运算后就会保留最高位
String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
//3f最高两位是0,第六位是1,所以进行"位与"运算后获得第六位
int languageCodeLength = payload[0] & 0x3f;
//下面开始NDEF文本数据第二个字节,语言编码
//获得语言编码
String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
//下面开始NDEF文本数据后面的字节,解析出文本
String textRecord = new String(payload, languageCodeLength + 1,
payload.length - languageCodeLength - 1, textEncoding);
return textRecord;
} catch (Exception e) {
throw new IllegalArgumentException();
}
}
/**
* 写数据
* 描述:TODO
*/
public void writeNfcTag(Intent intent, String text) {
if (!isSupportOrEnableNfc()) return;
if (TextUtils.isEmpty(text)) return;
//获取Tag对象
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{createTextRecord(text)});
boolean result = writeTag(ndefMessage, detectedTag);
Toast.makeText(context, result ? "写入成功" : "写入失败", Toast.LENGTH_SHORT).show();
}
/**
* 创建NDEF文本数据
*
* @param text
* @return
*/
private NdefRecord createTextRecord(String text) {
byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName("US-ASCII"));
Charset utfEncoding = Charset.forName("UTF-8");
//将文本转换为UTF-8格式
byte[] textBytes = text.getBytes(utfEncoding);
//设置状态字节编码最高位数为0
int utfBit = 0;
//定义状态字节
char status = (char) (utfBit + langBytes.length);
byte[] data = new byte[1 + langBytes.length + textBytes.length];
//设置第一个状态字节,先将状态码转换成字节
data[0] = (byte) status;
//设置语言编码,使用数组拷贝方法,从0开始拷贝到data中,拷贝到data的1到langBytes.length的位置
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
//设置文本字节,使用数组拷贝方法,从0开始拷贝到data中,拷贝到data的1 + langBytes.length
//到textBytes.length的位置
System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
//通过字节传入NdefRecord对象
//NdefRecord.RTD_TEXT:传入类型 读写
NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
return ndefRecord;
}
/**
* 写数据
*
* @param ndefMessage 创建好的NDEF文本数据
* @param tag 标签
* @return
*/
private boolean writeTag(NdefMessage ndefMessage, Tag tag) {
try {
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(ndefMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取十六进制,用于标签id
* 描述:TODO
* @param intent
* @return
*/
public String getRfid(Intent intent) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] bytes = detectedTag.getId();
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0)
sb.append(" ");
}
return sb.toString();
}
}
|
3e1b00a6dd9b8b62192ff3622fd1a401ffc70aeb | 3,794 | java | Java | microservices/user-service/src/main/java/com/habeebcycle/microservice/core/user/message/MessageConsumer.java | alephzed/spring-cloud-stream-implemention | 1dc9696cb593e74838f88e5fdf4a94169de4f171 | [
"MIT"
] | 10 | 2021-01-24T21:02:25.000Z | 2021-12-20T12:23:09.000Z | microservices/user-service/src/main/java/com/habeebcycle/microservice/core/user/message/MessageConsumer.java | swapnilgangrade01/spring-cloud-stream-implemention | deb6df2705f704791808761de5d5ab56f480d9db | [
"MIT"
] | null | null | null | microservices/user-service/src/main/java/com/habeebcycle/microservice/core/user/message/MessageConsumer.java | swapnilgangrade01/spring-cloud-stream-implemention | deb6df2705f704791808761de5d5ab56f480d9db | [
"MIT"
] | 5 | 2021-01-23T00:28:16.000Z | 2022-02-15T11:59:12.000Z | 40.795699 | 115 | 0.585398 | 11,437 | package com.habeebcycle.microservice.core.user.message;
import com.habeebcycle.microservice.core.user.mapper.UserMapper;
import com.habeebcycle.microservice.core.user.model.User;
import com.habeebcycle.microservice.core.user.service.UserService;
import com.habeebcycle.microservice.util.event.DataEvent;
import com.habeebcycle.microservice.util.exceptions.BadRequestException;
import com.habeebcycle.microservice.util.payload.UserPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import java.util.function.Consumer;
@Component
public class MessageConsumer {
private final Logger LOG = LoggerFactory.getLogger(MessageConsumer.class);
private final UserService userService;
private final UserMapper userMapper;
@Autowired
public MessageConsumer(UserService userService, UserMapper userMapper) {
this.userService = userService;
this.userMapper = userMapper;
}
@Bean
public Consumer<DataEvent<String, UserPayload>> userConsumer() {
return event -> {
LOG.info("Consuming message event created at {}", event.getEventCreatedAt());
switch (event.getEventType()) {
case CREATE:
UserPayload userPayload = event.getData();
LOG.info("Creating user of the following {}", userPayload);
User user = userMapper.userPayloadToUserService(userPayload);
userService.saveUser(user)
.onErrorMap(
DuplicateKeyException.class,
ex -> new BadRequestException("Duplicate key, username " + user.getUsername() +
" or email address " + user.getEmail() + " had already been used.")
)
.subscribe(u -> LOG.info("User Created {}", u));
break;
case DELETE:
userPayload = event.getData();
user = userMapper.userPayloadToUserService(userPayload);
String userId = event.getKey() != null ? event.getKey() : user.getId();
LOG.info("Deleting user with the following {}", userId);
userService.deleteUserById(userId)
.subscribe(x -> LOG.info("User with id {} deleted successfully", userId));
break;
}
};
}
/*@Bean
public Function<DataEvent<String, User>, Mono<User>> userFunction() {
return event -> {
LOG.info("Consuming message event created at {}", event.getEventCreatedAt());
switch (event.getEventType()) {
case CREATE:
User user = event.getData();
LOG.info("Creating user of the following {}", user);
return userService.saveUser(user);
case DELETE:
user = event.getData();
String userId = event.getKey() != null ? event.getKey() : user.getId();
LOG.info("Deleting user with the following {}", userId);
return userService.deleteUserById(userId).thenReturn(user);
case READ:
userId = event.getKey();
LOG.info("Getting user with the following {}", userId);
return userService.getUserById(userId);
default:
return Mono.just(event.getData());
}
};
}*/
}
|
3e1b00cab1b68cf9b15a1ae1abcb629fd06361d7 | 3,834 | java | Java | jackdaw-apt/src/main/java/com/github/vbauer/jackdaw/code/generator/JServiceCodeGenerator.java | vbauer/jackdaw | a9244cab77b3bb0fba658c444758bb8be51296c5 | [
"Apache-2.0"
] | 339 | 2015-03-17T16:51:58.000Z | 2021-11-11T12:38:34.000Z | jackdaw-apt/src/main/java/com/github/vbauer/jackdaw/code/generator/JServiceCodeGenerator.java | vbauer/jackdaw | a9244cab77b3bb0fba658c444758bb8be51296c5 | [
"Apache-2.0"
] | 11 | 2015-03-19T20:37:47.000Z | 2020-02-27T20:20:50.000Z | jackdaw-apt/src/main/java/com/github/vbauer/jackdaw/code/generator/JServiceCodeGenerator.java | vbauer/jackdaw | a9244cab77b3bb0fba658c444758bb8be51296c5 | [
"Apache-2.0"
] | 39 | 2015-03-19T12:15:00.000Z | 2021-11-04T11:44:53.000Z | 34.540541 | 96 | 0.707877 | 11,438 | package com.github.vbauer.jackdaw.code.generator;
import com.github.vbauer.jackdaw.annotation.JService;
import com.github.vbauer.jackdaw.code.base.BaseCodeGenerator;
import com.github.vbauer.jackdaw.code.context.CodeGeneratorContext;
import com.github.vbauer.jackdaw.context.ProcessorContextHolder;
import com.github.vbauer.jackdaw.util.TypeUtils;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeMirror;
import javax.tools.FileObject;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
/**
* @author Vladislav Bauer
*/
public class JServiceCodeGenerator extends BaseCodeGenerator {
private static final String DIR_SERVICES = "META-INF/services/";
private final Map<String, Set<String>> allServices = Maps.newTreeMap();
@Override
public final Class<JService> getAnnotation() {
return JService.class;
}
@Override
public final void generate(final CodeGeneratorContext context) {
final TypeElement typeElement = context.getTypeElement();
final JService annotation = typeElement.getAnnotation(JService.class);
final String providerClass = getProviderClass(annotation);
if (TypeUtils.inHierarchy(typeElement, providerClass)) {
addProvider(typeElement, providerClass);
}
}
@Override
public final void onStart() {
allServices.clear();
}
@Override
public final void onFinish() throws Exception {
for (final Map.Entry<String, Set<String>> entry : allServices.entrySet()) {
final String providerClass = entry.getKey();
final Set<String> services = entry.getValue();
final String resourceFile = DIR_SERVICES + providerClass;
final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
final Filer filer = env.getFiler();
writeServices(filer, resourceFile, services);
}
}
private void addProvider(final TypeElement typeElement, final String providerClass) {
final String serviceClass = typeElement.getQualifiedName().toString();
Set<String> services = allServices.get(providerClass);
if (services == null) {
services = Sets.newTreeSet();
allServices.put(providerClass, services);
}
services.add(serviceClass);
}
private String getProviderClass(final JService annotation) {
try {
final Class<?> providerClass = annotation.value();
return providerClass.getCanonicalName();
} catch (final MirroredTypeException ex) {
final TypeMirror typeMirror = ex.getTypeMirror();
return typeMirror.toString();
}
}
private void writeServices(
final Filer filer, final String resourceFile, final Collection<String> services
) throws Exception {
final FileObject file = createResource(filer, resourceFile);
final OutputStream outputStream = file.openOutputStream();
try {
IOUtils.writeLines(services, "\n", outputStream, StandardCharsets.UTF_8);
} finally {
IOUtils.closeQuietly(outputStream);
}
}
private FileObject createResource(final Filer filer, final String path) throws Exception {
return filer.createResource(CLASS_OUTPUT, StringUtils.EMPTY, path);
}
}
|
3e1b00dcf9eff42103677300a647e860e56144a8 | 920 | java | Java | chapter_002/src/test/java/ru/job4j/collections/sort/UserConvertTest.java | Logg1X/job4j | cb1091ada845ed7eba7092994e350e14dc4f31e4 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/test/java/ru/job4j/collections/sort/UserConvertTest.java | Logg1X/job4j | cb1091ada845ed7eba7092994e350e14dc4f31e4 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/test/java/ru/job4j/collections/sort/UserConvertTest.java | Logg1X/job4j | cb1091ada845ed7eba7092994e350e14dc4f31e4 | [
"Apache-2.0"
] | null | null | null | 30.666667 | 64 | 0.684783 | 11,439 | package ru.job4j.collections.sort;
import org.junit.Test;
import ru.job4j.collections.models.User;
import ru.job4j.collections.search.UserConvert;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.Is.is;
public class UserConvertTest {
@Test
public void whenListUserConvertToMap() {
UserConvert convertToMap = new UserConvert();
User user = new User(35, "pasha", "MSK");
User user1 = new User(25, "paha", "MSK");
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
Map<Integer, User> result = convertToMap.process(users);
assertThat(result.keySet(), contains(35, 25));
assertThat(result.get(35), is(user));
assertThat(result.get(25), is(user1));
}
}
|
3e1b00de0c8d65178256ce35ecf45177cc4918b9 | 1,003 | java | Java | deployer-dcos/src/main/java/de/qaware/cloud/deployer/dcos/token/TokenClient.java | Preethikathamuthu/gradle-cloud-deployer | 005f7d292af237f1ed72d9a30ff5f99a9b5acff3 | [
"ECL-2.0",
"Apache-2.0"
] | 27 | 2016-08-24T12:09:01.000Z | 2021-04-22T01:01:48.000Z | deployer-dcos/src/main/java/de/qaware/cloud/deployer/dcos/token/TokenClient.java | Preethikathamuthu/gradle-cloud-deployer | 005f7d292af237f1ed72d9a30ff5f99a9b5acff3 | [
"ECL-2.0",
"Apache-2.0"
] | 55 | 2016-08-29T11:17:43.000Z | 2019-02-23T09:20:08.000Z | deployer-dcos/src/main/java/de/qaware/cloud/deployer/dcos/token/TokenClient.java | Preethikathamuthu/gradle-cloud-deployer | 005f7d292af237f1ed72d9a30ff5f99a9b5acff3 | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2016-11-24T16:38:53.000Z | 2019-04-01T17:42:09.000Z | 30.393939 | 75 | 0.714855 | 11,440 | /*
* Copyright 2016 QAware GmbH
*
* 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 de.qaware.cloud.deployer.dcos.token;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
interface TokenClient {
/**
* Tries to login using the specified token.
*
* @param token The request body which contains the token.
* @return The server's http response.
*/
@POST("/acs/api/v1/auth/login")
Call<Token> login(@Body Token token);
}
|
3e1b044be855a59a831e7928cf279dfc9a321bc3 | 13,828 | java | Java | app/src/main/java/com/subinkrishna/curah/data/sync/SyncAdapter.java | subinkrishna/open-curah | d3c4b1f3cab0c7e6cbaa77f9261fcabad0cab4a9 | [
"Apache-2.0"
] | 4 | 2016-01-15T18:09:21.000Z | 2016-03-17T01:25:57.000Z | app/src/main/java/com/subinkrishna/curah/data/sync/SyncAdapter.java | subinkrishna/open-curah | d3c4b1f3cab0c7e6cbaa77f9261fcabad0cab4a9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/subinkrishna/curah/data/sync/SyncAdapter.java | subinkrishna/open-curah | d3c4b1f3cab0c7e6cbaa77f9261fcabad0cab4a9 | [
"Apache-2.0"
] | null | null | null | 34.483791 | 121 | 0.610428 | 11,441 | package com.subinkrishna.curah.data.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.os.Bundle;
import com.subinkrishna.curah.CurahApplication;
import com.subinkrishna.curah.data.fetcher.FeedFetcher;
import com.subinkrishna.curah.data.fetcher.FeedFetcher.FetchStatus;
import com.subinkrishna.curah.eunmeration.Feed;
import java.util.Calendar;
import static com.subinkrishna.curah.util.Logger.d;
import static com.subinkrishna.curah.util.Logger.e;
/**
* Sync Adapter.
*
* @author Subinkrishna Gopi
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
/** Log Tag */
private static final String TAG = SyncAdapter.class.getSimpleName();
/** Authority & account type */
public static final String AUTHORITY = "com.subinkrishna.curah.provider";
public static final String ACCOUNT_TYPE = "curah.subinkrishna.com";
/** Keys to hold the sync notification flags / actions */
public static final String KEY_SYNC_START_ACTION = "com.subinkrishna.curah.sync.start";
public static final String KEY_SYNC_COMPLETE_ACTION = "com.subinkrishna.curah.sync.complete";
public static final String KEY_SYNC_FEED_COMPLETE_ACTION = "com.subinkrishna.curah.sync.feed.complete";
public static final String KEY_SYNC_FEED_ID = "com.subinkrishna.curah.sync.feedId";
public static final String KEY_SYNC_FETCH_STATUS = "com.subinkrishna.curah.sync.fetchStatus";
/** Sync interval */
public static final int SYNC_INTERVAL_IN_SECONDS = 60 * 60 * 12; // Twelve hours
public static final int SYNC_INTERVAL_IN_SECONDS_WHEN_ACTIVE = 60 * 60; // One hour
/** Default account name & password */
private static final String DEFAULT_ACCOUNT_USERNAME = "Sync";
private static final String DEFAULT_ACCOUNT_PASSWORD = null;
/** Key to hold the feed ID */
private static final String KEY_FEED_ID = "keyFeedId";
/** Key to hold the last sync time */
private static final String KEY_LAST_SYNC_TIME = "keyLastSyncTime";
/**
* Initiates an immediate sync. Syncs all the feeds.
*
* @param context
*/
public static void syncNow(final Context context) {
syncNow(context, null);
}
/**
* Initiates an immediate sync on the specified feed.
*
* @param context
* @param feed
*/
public static void syncNow(final Context context,
final Feed feed) {
// Abort if context is invalid
if (null == context) {
e(TAG, "Aborting manual sync. Invalid context.");
return;
}
final Account account = getSyncAccount(context, true);
if (null == account) {
e(TAG, "Aborting manual sync. Invalid sync account.");
return;
}
// Cancel active/pending sync before starting new sync
if (isSyncActiveOrPending(context, account)) {
d(TAG, "Cancelling active/pending sync");
cancelSync(context, account);
}
// Perform sync now (override all settings)
d(TAG, "Start manual sync: " + ((null != feed) ? feed.name() : "all"));
final Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
extras.putInt(KEY_FEED_ID, (null != feed) ? feed.mId : -1);
ContentResolver.requestSync(account, AUTHORITY, extras);
}
/**
* Checks if a sync is active or pending
*
* @param context
* @param account
* @return
*/
public static boolean isSyncActiveOrPending(Context context,
Account account) {
boolean isActiveOrPendingSync = false;
if ((null != context) && (null != account)) {
isActiveOrPendingSync = ContentResolver.isSyncPending(account, AUTHORITY) ||
ContentResolver.isSyncActive(account, AUTHORITY);
}
return isActiveOrPendingSync;
}
/**
* Checks if a sync is active.
*
* @param context
* @param account
* @return
*/
public static boolean isSyncActive(Context context,
Account account) {
boolean isActive = false;
if ((null != context) && (null != account)) {
isActive = ContentResolver.isSyncActive(account, AUTHORITY);
}
return isActive;
}
/**
* Enables periodic sync for the account.
*
* @param context
*/
public static void enablePeriodicSync(final Context context) {
if (null == context) {
e(TAG, "Aborting enable periodic sync. Invalid context.");
return;
}
final Account syncAccount = getSyncAccount(context, true);
if (null == syncAccount) {
e(TAG, "Aborting enable periodic sync. Invalid sync account.");
return;
}
d(TAG, "Enable periodic sync");
final Bundle extras = new Bundle();
// Make the account syncable
ContentResolver.setIsSyncable(syncAccount, AUTHORITY, 1);
// Remove existing periodic syncs
ContentResolver.removePeriodicSync(syncAccount, AUTHORITY, extras);
// Add new periodic sync
ContentResolver.addPeriodicSync(syncAccount, AUTHORITY, extras, SYNC_INTERVAL_IN_SECONDS);
}
/**
* Cancels the sync on the specified account.
*
* @param context
* @param account
*/
public static void cancelSync(final Context context,
final Account account) {
if ((null == context) || (null == account)) {
d(TAG, "Abort cancel sync. Invalid context/account.");
return;
}
ContentResolver.cancelSync(account, AUTHORITY);
}
/**
* Returns the sync account. Will create a new sync account if there is no existing account
* based on {@code createIfNotExists}.
*
* @param context
* @param createIfNotExists
* @return
*/
public static Account getSyncAccount(final Context context,
final boolean createIfNotExists) {
d(TAG, "Get sync account");
final AccountManager accountManager = AccountManager.get(context);
final Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
Account syncAccount = null;
// Add an account if no accounts exist
if (((null == accounts) || (0 == accounts.length)) && createIfNotExists) {
d(TAG, "Create sync account");
// Create the default account and add it explicitly
syncAccount = new Account(DEFAULT_ACCOUNT_USERNAME, ACCOUNT_TYPE);
boolean hasAdded = accountManager.addAccountExplicitly(syncAccount,
DEFAULT_ACCOUNT_PASSWORD, // Password (empty)
null); // User info bundle (empty)
if (hasAdded) {
// Make the account syncable
ContentResolver.setIsSyncable(syncAccount, AUTHORITY, 1);
// Turn on the auto-sync
ContentResolver.setSyncAutomatically(syncAccount, AUTHORITY, true);
}
}
// Account exists
else {
syncAccount = accounts[0];
}
return syncAccount;
}
/**
* Returns the last sync time.
*
* @return
*/
synchronized
public static long getLastSyncTime() {
return CurahApplication.getPreferences().getLong(KEY_LAST_SYNC_TIME, -1);
}
/**
* Updates the last sync time to current time.
*/
synchronized
private static void updateLastSyncTime() {
final SharedPreferences.Editor editor = CurahApplication.getPreferencesEditor();
editor.putLong(KEY_LAST_SYNC_TIME, System.currentTimeMillis()).commit();
}
/**
* Checks if the last sync happened with in the specified interval.
*
* @param intervalInSeconds
* @return
*/
synchronized
public static boolean isLastSyncWithinInterval(final int intervalInSeconds) {
final long lastSyncTime = getLastSyncTime();
if (-1 == lastSyncTime)
return false;
final Calendar now = Calendar.getInstance();
final Calendar lastSync = Calendar.getInstance();
lastSync.setTimeInMillis(lastSyncTime);
lastSync.add(Calendar.SECOND, intervalInSeconds);
d(TAG, "isLastSyncWithinInterval - Now: " + now.getTimeInMillis()
+ ", Last Sync: " + lastSync.getTimeInMillis()
+ " (Interval: " + intervalInSeconds + ")"
+ " = " + !lastSync.before(now));
return !lastSync.before(now);
}
/**
* Creates SyncAdapter.
*
* @param context
* @param autoInitialize
*/
public SyncAdapter(Context context,
boolean autoInitialize) {
super(context, autoInitialize);
}
/**
* Creates SyncAdapter.
*
* @param context
* @param autoInitialize
* @param allowParallelSyncs
*/
public SyncAdapter(Context context,
boolean autoInitialize,
boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
}
@Override
public void onPerformSync(Account account,
Bundle extras,
String authority,
ContentProviderClient contentProviderClient,
SyncResult syncResult) {
// Abort if user has not agreed to terms yet
if (!CurahApplication.hasUserAgreedTerms()) {
e(TAG, "Aborting sync. User hasn't agreed to terms yet!");
return;
}
// Check if the sync is for single feed or all
final int feedId = extras.getInt(KEY_FEED_ID, -1);
final boolean isManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean isExpedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
final Context context = getContext();
d(TAG, String.format("onPerformSync() - Feed ID: %d, Manual: %s, Expedited: %s, SyncInProgress (SyncResult): %s",
feedId,
String.valueOf(isExpedited),
String.valueOf(isManualSync),
String.valueOf(syncResult.syncAlreadyInProgress)));
// Abort if the last periodic-sync was within 1 hour
if (!isManualSync && isLastSyncWithinInterval(SYNC_INTERVAL_IN_SECONDS_WHEN_ACTIVE)) {
e(TAG, "Aborting auto-sync. Last auto-sync was with in 1 hour.");
return;
}
try {
// Send sync start notification
sendSyncStartNotification();
final Feed feed = Feed.byId(feedId);
FetchStatus status = null;
// Feed specific sync
if (null != feed) {
status = FeedFetcher.fetch(context, feed);
// TODO: Update the SyncResult
sendSyncCompleteNotification(feed, status);
}
// Complete sync
else {
final Feed[] allFeeds = Feed.values();
for (Feed aFeed : allFeeds) {
status = FeedFetcher.fetch(context, aFeed);
// TODO: Update the SyncResult
sendSyncCompleteNotification(aFeed, status);
}
}
updateLastSyncTime();
} catch (Exception e) {
e(TAG, "Exception during sync", e);
} finally {
// Re-enable periodic sync if the current sync was user initiated
if (isManualSync) {
d(TAG, "Re-enabling periodic sync");
enablePeriodicSync(context);
}
sendSyncCompleteNotification();
}
d(TAG, "Finished Sync");
}
/**
* Send sync complete notification.
*/
private void sendSyncStartNotification() {
final Intent notificationIntent = new Intent();
notificationIntent.setAction(KEY_SYNC_START_ACTION);
getContext().sendBroadcast(notificationIntent);
}
/**
* Send sync complete notification.
*/
private void sendSyncCompleteNotification() {
final Intent notificationIntent = new Intent();
notificationIntent.setAction(KEY_SYNC_COMPLETE_ACTION);
getContext().sendBroadcast(notificationIntent);
}
/**
* Send feed specific sync status notification.
*
* @param feed
* @param status
*/
private void sendSyncCompleteNotification(final Feed feed,
final FetchStatus status) {
if ((null == feed) ||
(null == status)) {
e(TAG, "Unable to send fetch status notification. Invalid input.");
return;
}
final Intent notificationIntent = new Intent();
notificationIntent.setAction(KEY_SYNC_FEED_COMPLETE_ACTION);
notificationIntent.putExtra(KEY_SYNC_FEED_ID, feed.mId);
notificationIntent.putExtra(KEY_SYNC_FETCH_STATUS, status.isSuccess);
getContext().sendBroadcast(notificationIntent);
}
@Override
public void onSyncCanceled() {
super.onSyncCanceled();
d(TAG, "onSyncCancel()");
}
}
|
3e1b045ef8763c70e98c80bba7d728603a2ebf19 | 8,362 | java | Java | app/src/main/java/com/bukhmastov/cdoitmo/widget/ScheduleLessonsWidgetFactory.java | fitsuli/CDOITMO | 58294ac61ab87d525d7abb298aa9a50c13396b3b | [
"MIT"
] | 10 | 2018-01-21T21:44:28.000Z | 2020-12-25T21:56:38.000Z | app/src/main/java/com/bukhmastov/cdoitmo/widget/ScheduleLessonsWidgetFactory.java | fitsuli/CDOITMO | 58294ac61ab87d525d7abb298aa9a50c13396b3b | [
"MIT"
] | 5 | 2018-06-18T20:29:38.000Z | 2020-01-05T16:43:12.000Z | app/src/main/java/com/bukhmastov/cdoitmo/widget/ScheduleLessonsWidgetFactory.java | fitsuli/CDOITMO | 58294ac61ab87d525d7abb298aa9a50c13396b3b | [
"MIT"
] | 4 | 2018-06-17T05:40:05.000Z | 2021-01-24T17:42:41.000Z | 38.182648 | 145 | 0.56398 | 11,442 | package com.bukhmastov.cdoitmo.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.bukhmastov.cdoitmo.R;
import com.bukhmastov.cdoitmo.factory.AppComponentProvider;
import com.bukhmastov.cdoitmo.model.schedule.lessons.SLesson;
import com.bukhmastov.cdoitmo.model.schedule.lessons.SLessons;
import com.bukhmastov.cdoitmo.model.widget.schedule.lessons.WSLSettings;
import com.bukhmastov.cdoitmo.object.schedule.ScheduleLessonsHelper;
import com.bukhmastov.cdoitmo.util.Log;
import com.bukhmastov.cdoitmo.util.Time;
import com.bukhmastov.cdoitmo.util.singleton.StringUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeSet;
import javax.inject.Inject;
import dagger.Lazy;
public class ScheduleLessonsWidgetFactory implements RemoteViewsService.RemoteViewsFactory {
private final Context context;
private final int appWidgetId;
private ScheduleLessonsWidget.Colors colors;
private String type = "group";
private int parity = -1;
private List<SLesson> lessons;
@Inject
Lazy<Log> log;
@Inject
Time time;
@Inject
ScheduleLessonsWidgetStorage scheduleLessonsWidgetStorage;
@Inject
ScheduleLessonsHelper scheduleLessonsHelper;
ScheduleLessonsWidgetFactory(Context context, Intent intent) {
AppComponentProvider.getComponent().inject(this);
this.context = context;
this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
this.lessons = new ArrayList<>();
try {
WSLSettings settings = scheduleLessonsWidgetStorage.getSettings(appWidgetId);
if (settings == null) {
throw new NullPointerException("settings cannot be null");
}
colors = ScheduleLessonsWidget.getColors(settings);
} catch (Exception e) {
colors = ScheduleLessonsWidget.getColors();
}
}
@Override
public void onCreate() {}
@Override
public void onDataSetChanged() {
try {
this.lessons.clear();
WSLSettings settings = scheduleLessonsWidgetStorage.getSettings(appWidgetId);
SLessons schedule = scheduleLessonsWidgetStorage.getConvertedCache(appWidgetId);
if (settings == null || schedule == null || StringUtils.isBlank(schedule.getType())) {
return;
}
int shift = settings.getShift() + settings.getShiftAutomatic();
Calendar calendar = time.getCalendar();
if (shift != 0) {
calendar.add(Calendar.HOUR, shift * 24);
}
this.parity = time.getWeek(context, calendar) % 2;
this.type = schedule.getType();
Integer weekday = time.getWeekDay(calendar);
String customDay = time.getScheduleCustomDayRaw(calendar);
TreeSet<SLesson> lessons = scheduleLessonsHelper.filterAndSortLessonsForWeekday(schedule, parity, weekday, customDay, true);
this.lessons.addAll(lessons);
} catch (Exception e) {
log.get().exception(e);
}
}
@Override
public RemoteViews getViewAt(int position) {
try {
if (position >= getCount()) {
return null;
}
SLesson lesson = this.lessons.get(position);
if (lesson == null) {
throw new NullPointerException("lesson cannot be null");
}
RemoteViews layout = new RemoteViews(context.getPackageName(), R.layout.widget_schedule_lessons_item);
layout.setInt(R.id.slw_item_time_start, "setTextColor", colors.text);
layout.setInt(R.id.slw_item_time_end, "setTextColor", colors.text);
layout.setTextViewText(R.id.slw_item_time_start, lesson.getTimeStart());
layout.setTextViewText(R.id.slw_item_time_end, lesson.getTimeEnd());
layout.setImageViewBitmap(R.id.slw_item_time_icon, ScheduleLessonsWidget.getBitmap(context, R.drawable.ic_widget_time, colors.text));
String title = lesson.getSubjectWithNote();
String type = lesson.getType() == null ? "" : lesson.getType().trim();
switch (type) {
case "practice": title += " (" + context.getString(R.string.practice) + ")"; break;
case "lecture": title += " (" + context.getString(R.string.lecture) + ")"; break;
case "lab": title += " (" + context.getString(R.string.lab) + ")"; break;
case "iws": title += " (" + context.getString(R.string.iws) + ")"; break;
default:
if (StringUtils.isNotBlank(type)){
title += " (" + type + ")";
}
break;
}
if (this.parity == -1) {
switch (lesson.getParity()){
case 0: title += " (" + context.getString(R.string.tab_even) + ")"; break;
case 1: title += " (" + context.getString(R.string.tab_odd) + ")"; break;
}
}
layout.setTextViewText(R.id.slw_item_title, title);
layout.setInt(R.id.slw_item_title, "setTextColor", colors.text);
String desc = "";
switch (this.type) {
case "group": desc = lesson.getTeacherName(); break;
case "teacher": desc = lesson.getGroup(); break;
case "personal":
case "room": {
String group = lesson.getGroup();
String teacher = lesson.getTeacherName();
if (StringUtils.isBlank(group)) {
desc = teacher;
} else {
desc = group;
if (StringUtils.isNotBlank(teacher)){
desc += " (" + teacher + ")";
}
}
break;
}
}
if (StringUtils.isNotBlank(desc)) {
layout.setTextViewText(R.id.slw_item_desc, desc);
layout.setInt(R.id.slw_item_desc, "setTextColor", colors.text);
} else {
layout.setInt(R.id.slw_item_desc, "setHeight", 0);
}
String meta = "";
switch (this.type) {
case "personal":
case "group":
case "teacher": {
String room = lesson.getRoom();
String building = lesson.getBuilding();
if (StringUtils.isBlank(room)) {
meta = building;
} else {
meta = context.getString(R.string.room_short) + " " + room;
if (StringUtils.isNotBlank(building)) {
meta += " (" + building + ")";
}
}
break;
}
case "room": {
meta += lesson.getBuilding();
break;
}
}
if (StringUtils.isNotBlank(meta)) {
layout.setTextViewText(R.id.slw_item_meta, meta);
layout.setInt(R.id.slw_item_meta, "setTextColor", colors.text);
} else {
layout.setInt(R.id.slw_item_meta, "setHeight", 0);
}
return layout;
} catch (Exception e) {
log.get().exception(e);
return null;
}
}
@Override
public int getCount() {
return lessons.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public RemoteViews getLoadingView() {
try {
return new RemoteViews(context.getPackageName(), R.layout.widget_schedule_lessons_item_loading);
} catch (Exception e) {
return null;
}
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onDestroy() {}
}
|
3e1b05541643ee8a8dea3f489f58bb2c9a405768 | 1,080 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Prototypes/TorquePrototype.java | BSG9432/CargoCraze | 811f3e4a37037706361cd1f763026f18c011c9d0 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Prototypes/TorquePrototype.java | BSG9432/CargoCraze | 811f3e4a37037706361cd1f763026f18c011c9d0 | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Prototypes/TorquePrototype.java | BSG9432/CargoCraze | 811f3e4a37037706361cd1f763026f18c011c9d0 | [
"MIT"
] | null | null | null | 28.421053 | 84 | 0.686111 | 11,443 | package org.firstinspires.ftc.teamcode.Prototypes;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import org.firstinspires.ftc.teamcode.Hardware.Robot;
@TeleOp (name = "TorqueTest", group = "Prototypes")
public class TorquePrototype extends OpMode {
Robot bsgRobot = new Robot();
@Override
public void init() {
bsgRobot.init(hardwareMap);
bsgRobot.frontLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
//bsgRobot.frontRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
bsgRobot.backLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
//bsgRobot.backRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
}
@Override
public void loop() {
if(gamepad1.a){
bsgRobot.arm.setPower(1);
}
else if (gamepad1.b){
bsgRobot.arm.setPower(-1);
}
else{
bsgRobot.arm.setPower(0);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.