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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1a72b5738e911defa8676bf564e00dc49927f4 | 1,817 | java | Java | src/main/java/it/gulch/linuxday/android/fragments/NowLiveListFragment.java | paolinux86/linuxday-cagliari-android | 35476f2defa4a4fa611d0d3bc5c1d0034a82f973 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/gulch/linuxday/android/fragments/NowLiveListFragment.java | paolinux86/linuxday-cagliari-android | 35476f2defa4a4fa611d0d3bc5c1d0034a82f973 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/gulch/linuxday/android/fragments/NowLiveListFragment.java | paolinux86/linuxday-cagliari-android | 35476f2defa4a4fa611d0d3bc5c1d0034a82f973 | [
"Apache-2.0"
] | null | null | null | 27.530303 | 78 | 0.76885 | 11,241 | /*
* Copyright 2014 Christophe Beyls
*
* 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 it.gulch.linuxday.android.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.util.Log;
import java.sql.SQLException;
import java.util.List;
import it.gulch.linuxday.android.R;
import it.gulch.linuxday.android.db.manager.EventManager;
import it.gulch.linuxday.android.db.manager.impl.DatabaseManagerFactory;
import it.gulch.linuxday.android.loaders.NowLiveLoader;
import it.gulch.linuxday.android.model.db.Event;
public class NowLiveListFragment extends BaseLiveListFragment
{
private static final String TAG = NextLiveListFragment.class.getSimpleName();
private EventManager eventManager;
@Override
protected String getEmptyText()
{
return getString(R.string.now_empty);
}
@Override
public Loader<List<Event>> onCreateLoader(int id, Bundle args)
{
return new NowLiveLoader(getActivity(), eventManager);
}
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
setupServices(activity);
}
private void setupServices(Activity activity)
{
try {
eventManager = DatabaseManagerFactory.getEventManager(activity);
} catch(SQLException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
|
3e1a7389968bc329fd08f86474cb54456c517468 | 1,756 | java | Java | protege-editor-owl/src/main/java/org/protege/editor/owl/ui/frame/OWLAnnotationsFrameSectionRow.java | sszuev/rdf-protege | 58a83da99d083d577885c9d469564af51447bb21 | [
"BSD-2-Clause"
] | 18 | 2019-11-04T15:45:03.000Z | 2022-03-10T14:36:53.000Z | protege-editor-owl/src/main/java/org/protege/editor/owl/ui/frame/OWLAnnotationsFrameSectionRow.java | sszuev/rdf-protege | 58a83da99d083d577885c9d469564af51447bb21 | [
"BSD-2-Clause"
] | null | null | null | protege-editor-owl/src/main/java/org/protege/editor/owl/ui/frame/OWLAnnotationsFrameSectionRow.java | sszuev/rdf-protege | 58a83da99d083d577885c9d469564af51447bb21 | [
"BSD-2-Clause"
] | null | null | null | 37.361702 | 131 | 0.726082 | 11,242 | package org.protege.editor.owl.ui.frame;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.editor.OWLAnnotationEditor;
import org.protege.editor.owl.ui.editor.OWLObjectEditor;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationSubject;
import org.semanticweb.owlapi.model.OWLOntology;
import java.util.stream.Stream;
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Bio-Health Informatics Group<br>
* Date: 26-Jan-2007<br><br>
*/
public class OWLAnnotationsFrameSectionRow
extends AbstractOWLFrameSectionRow<OWLAnnotationSubject, OWLAnnotationAssertionAxiom, OWLAnnotation> {
public OWLAnnotationsFrameSectionRow(OWLEditorKit kit,
OWLFrameSection<OWLAnnotationSubject, OWLAnnotationAssertionAxiom, OWLAnnotation> section,
OWLOntology ontology,
OWLAnnotationSubject rootObject, OWLAnnotationAssertionAxiom axiom) {
super(kit, section, ontology, rootObject, axiom);
}
@Override
protected OWLObjectEditor<OWLAnnotation> getObjectEditor() {
OWLAnnotationEditor editor = new OWLAnnotationEditor(getOWLEditorKit());
editor.setEditedObject(getAxiom().getAnnotation());
return editor;
}
@Override
protected OWLAnnotationAssertionAxiom createAxiom(OWLAnnotation editedObject) {
return getOWLDataFactory().getOWLAnnotationAssertionAxiom(getRoot(), editedObject);
}
@Override
public Stream<OWLAnnotation> manipulatableObjects() {
return getAxiom().annotations();
}
}
|
3e1a73b991e95744845c1cd899d865b7d7b2d0c3 | 1,853 | java | Java | src/test/java/com/microsoft/bingads/v13/api/test/entities/remarketing_list/read/BulkRemarketingListReadFromRowValuesIdTest.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 30 | 2016-02-29T03:23:52.000Z | 2021-12-10T03:57:30.000Z | src/test/java/com/microsoft/bingads/v13/api/test/entities/remarketing_list/read/BulkRemarketingListReadFromRowValuesIdTest.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 61 | 2016-03-01T02:20:29.000Z | 2022-03-25T08:50:56.000Z | src/test/java/com/microsoft/bingads/v13/api/test/entities/remarketing_list/read/BulkRemarketingListReadFromRowValuesIdTest.java | vtabel7403/BingAds-Java-SDK | 8034545104888c147ca73b63d93fcf99b79f9fdf | [
"MIT"
] | 37 | 2016-03-05T00:52:54.000Z | 2022-02-18T09:51:01.000Z | 35.634615 | 118 | 0.691311 | 11,243 | package com.microsoft.bingads.v13.api.test.entities.remarketing_list.read;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import com.microsoft.bingads.v13.api.test.entities.remarketing_list.BulkRemarketingListTest;
import com.microsoft.bingads.v13.bulk.entities.BulkRemarketingList;
@RunWith(Parameterized.class)
public class BulkRemarketingListReadFromRowValuesIdTest extends BulkRemarketingListTest {
@Parameter(value = 1)
public Long expectedResult;
/*
* Test data generator.
* This method is called the the JUnit parameterized test runner and
* returns a Collection of Arrays. For each Array in the Collection,
* each array element corresponds to a parameter in the constructor.
*/
@Parameters
public static Collection<Object[]> data() {
// In this example, the parameter generator returns a List of
// arrays. Each array has two elements: { datum, expected }.
// These data are hard-coded into the class, but they could be
// generated or loaded in any way you like.
return Arrays.asList(new Object[][]{
{"123", 123L},
{"9223372036854775807", 9223372036854775807L},
{"", null},
{null, null}
});
}
@Test
public void testRead() {
this.<Long>testReadProperty("Id", this.datum, this.expectedResult, new Function<BulkRemarketingList, Long>() {
@Override
public Long apply(BulkRemarketingList c) {
return c.getRemarketingList().getId();
}
});
}
}
|
3e1a73f251d21f43f83720c7220ae28889cc9466 | 3,406 | java | Java | app/src/main/java/com/samuel/destructo/FriendsFragment.java | tridoof/Destructo | f1a476c541183a8d9491dc8e80e4f4feecff7345 | [
"MIT"
] | null | null | null | app/src/main/java/com/samuel/destructo/FriendsFragment.java | tridoof/Destructo | f1a476c541183a8d9491dc8e80e4f4feecff7345 | [
"MIT"
] | null | null | null | app/src/main/java/com/samuel/destructo/FriendsFragment.java | tridoof/Destructo | f1a476c541183a8d9491dc8e80e4f4feecff7345 | [
"MIT"
] | null | null | null | 35.852632 | 120 | 0.603934 | 11,244 | package com.samuel.destructo;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import java.util.List;
/**
* Created by Samuel on 7/2/2015.
*/
public class FriendsFragment extends ListFragment{
public static final String TAG = FriendsFragment.class.getSimpleName();
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentuser;
protected List<ParseUser> mFriends;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
return rootView;
}
@Override
public void onResume(){
super.onResume();
mCurrentuser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentuser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
query.addAscendingOrder(ParseConstants.KEY_USERNAME);
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> friends, ParseException e) {
if (e == null) {
mFriends = friends;
String[] usernames = new String[mFriends.size()];
int i = 0;
for (ParseUser user : mFriends) {
usernames[i] = user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getListView().getContext(),
android.R.layout.simple_list_item_1,
usernames);
setListAdapter(adapter);
} else {
//Error
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ParseUser userClicked = mFriends.get(position);
Intent intent = new Intent(FriendsFragment.this.getActivity(), SetUpMessageActivity.class);
intent.putExtra("sendTo", userClicked.getUsername()); // To add the contact the message is being sent to
intent.putExtra("recipientId", userClicked.getObjectId());
startActivity(intent);
}
});
}
}
|
3e1a74bde4d1f6c78f88757665e0afc1ba90c44d | 577 | java | Java | chapter_002/src/main/java/ru/job4j/tracker/initializationrder/B.java | vinogor/job4j | 4c3b0188b4dcf076e4c9694c16c94b8be0732cf3 | [
"Apache-2.0"
] | null | null | null | chapter_002/src/main/java/ru/job4j/tracker/initializationrder/B.java | vinogor/job4j | 4c3b0188b4dcf076e4c9694c16c94b8be0732cf3 | [
"Apache-2.0"
] | 2 | 2021-12-10T01:31:36.000Z | 2021-12-14T20:46:26.000Z | chapter_002/src/main/java/ru/job4j/tracker/initializationrder/B.java | vinogor/job4j | 4c3b0188b4dcf076e4c9694c16c94b8be0732cf3 | [
"Apache-2.0"
] | 1 | 2019-05-23T10:33:54.000Z | 2019-05-23T10:33:54.000Z | 21.37037 | 83 | 0.554593 | 11,245 | package ru.job4j.tracker.initializationrder;
public class B extends A {
public static void main(String[] args) {
System.out.println("запускается только статика, так как объект не создан");
}
private int b = bb(20);
public B(int b) {
this.b = b;
}
private int bb(int x) {
System.out.println("B class. No static perem " + x);
return 0;
}
public B() {
System.out.println("B class. Constructor");
}
static {
System.out.println("B class. Static block 1");
}
} |
3e1a75facdc14c7b065ba0234c98ebcca729fefa | 235 | java | Java | javacord-api/src/main/java/org/javacord/api/util/NonThrowingAutoCloseable.java | dylhack/Javacord | f825905377ee30f8614190aef55da0e6b629da7f | [
"Apache-2.0"
] | 474 | 2018-07-05T13:13:14.000Z | 2022-03-30T01:14:31.000Z | javacord-api/src/main/java/org/javacord/api/util/NonThrowingAutoCloseable.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 446 | 2018-07-08T15:32:08.000Z | 2022-03-30T10:13:41.000Z | javacord-api/src/main/java/org/javacord/api/util/NonThrowingAutoCloseable.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 168 | 2018-07-08T14:52:49.000Z | 2022-03-31T08:06:04.000Z | 23.5 | 94 | 0.740426 | 11,246 | package org.javacord.api.util;
/**
* An auto-closeable that does not throw any checked exceptions from its {@code close} method.
*/
public interface NonThrowingAutoCloseable extends AutoCloseable {
@Override
void close();
}
|
3e1a772f1dc8f96f8ae06b7ad1b3559dc5f47b9c | 802 | java | Java | src/main/java/best/reich/ingros/module/modules/other/AFKswing.java | asugbdp9w7gf-p29q3823e872t3o29387fg298d/rip-atlas | eb14310da80d66e0e023bf9e3f233ee30ddebe25 | [
"Unlicense"
] | 5 | 2021-06-09T17:30:36.000Z | 2021-07-20T13:59:31.000Z | src/main/java/best/reich/ingros/module/modules/other/AFKswing.java | christallinqq/rip-atlas | eb14310da80d66e0e023bf9e3f233ee30ddebe25 | [
"Unlicense"
] | null | null | null | src/main/java/best/reich/ingros/module/modules/other/AFKswing.java | christallinqq/rip-atlas | eb14310da80d66e0e023bf9e3f233ee30ddebe25 | [
"Unlicense"
] | 2 | 2021-06-10T02:02:39.000Z | 2021-07-10T16:27:13.000Z | 32.08 | 68 | 0.754364 | 11,247 | package best.reich.ingros.module.modules.other;
import best.reich.ingros.events.entity.UpdateEvent;
import me.xenforu.kelo.module.ModuleCategory;
import me.xenforu.kelo.module.annotation.ModuleManifest;
import me.xenforu.kelo.module.type.ToggleableModule;
import me.xenforu.kelo.setting.annotation.Setting;
import net.b0at.api.event.Subscribe;
import net.minecraft.util.EnumHand;
@ModuleManifest(label = "AFKswing", category = ModuleCategory.OTHER)
public class AFKswing extends ToggleableModule {
@Setting("lefthand")
public boolean lefthand = true;
@Setting("righthand")
public boolean righthand = true;
@Subscribe
public void onUpdate(UpdateEvent event) {
if (mc.world == null || mc.player == null) return;
mc.player.swingArm(EnumHand.MAIN_HAND);
}
} |
3e1a77b9e1a0c639ce491e7c3e4d4fdf7f8608f0 | 1,402 | java | Java | chapter_004/src/main/java/ru/job4j/lambda/FunctionalInterfaces.java | vadsemenov/job4j | 292bf3adaf384ad98d15353608cbb181a34c9540 | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/lambda/FunctionalInterfaces.java | vadsemenov/job4j | 292bf3adaf384ad98d15353608cbb181a34c9540 | [
"Apache-2.0"
] | 6 | 2021-12-10T01:28:27.000Z | 2022-02-03T18:28:53.000Z | chapter_004/src/main/java/ru/job4j/lambda/FunctionalInterfaces.java | vadsemenov/job4j | 292bf3adaf384ad98d15353608cbb181a34c9540 | [
"Apache-2.0"
] | null | null | null | 26.961538 | 88 | 0.545649 | 11,248 | package ru.job4j.lambda;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* Пример использования Функциональных интерфейсов, лямбда выражений,
* методов в лямбда выражениях
*/
public class FunctionalInterfaces {
public static void main(String[] args) {
FunctionalInterfaces calc = new FunctionalInterfaces();
calc.multiple(
0, 10, 2,
(value, index) -> {
double result = value * index;
System.out.printf("Multiple %s * %s = %s %n", value, index, result);
return result;
},
result -> System.out.println(result)
);
//List<Double> buffer = new ArrayList<>();
calc.multiple(0, 3, 2,
FunctionalInterfaces::add, //buffer::add,
result -> System.out.println(result));
}
public static double add(int first, int second) {
return first + second;
}
public void multiple(int start, int finish, int value,
BiFunction<Integer, Integer, Double> op,
Consumer<Double> media) {
for (int index = start; index != finish; index++) {
media.accept(op.apply(value, index));
}
}
public interface Operation {
double calc(int left, int right);
}
}
|
3e1a78b46362364d54cf4777541a9a4f14c266a8 | 603 | java | Java | program_data/github_java_sort_function/1/38.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | 19 | 2019-02-26T05:43:39.000Z | 2022-02-21T04:14:46.000Z | program_data/github_java_sort_function/1/38.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | null | null | null | program_data/github_java_sort_function/1/38.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | 8 | 2018-12-25T02:05:41.000Z | 2022-02-23T07:50:48.000Z | 33.5 | 74 | 0.361526 | 11,249 | private void insertionSortWithGap(int[] array, int gap, int startIndex) {
for (int i = startIndex + gap; i < array.length; i += gap) {
int cur = array[i];
boolean flag = false;
for (int j = i - gap; j >= 0; j -= gap) {
if (cur < array[j]) {
array[j + gap] = array[j];
} else {
array[j + gap] = cur;
flag = true;
break;
}
}
if (!flag) {
array[startIndex] = cur;
}
}
} |
3e1a78cb0f6afc353c1ab1bc5c6a1e5d4084dcf8 | 628 | java | Java | src/main/java/raiderlib/control/DriveCharacterization.java | derekgeng15/RaiderLib | 4ba05554c6d749f1010d76224d536c2ea399a31a | [
"MIT"
] | null | null | null | src/main/java/raiderlib/control/DriveCharacterization.java | derekgeng15/RaiderLib | 4ba05554c6d749f1010d76224d536c2ea399a31a | [
"MIT"
] | null | null | null | src/main/java/raiderlib/control/DriveCharacterization.java | derekgeng15/RaiderLib | 4ba05554c6d749f1010d76224d536c2ea399a31a | [
"MIT"
] | null | null | null | 28.545455 | 97 | 0.702229 | 11,250 | package raiderlib.control;
public class DriveCharacterization {
public final double maxVelocity;
public final double maxAcceleration;
public final double trackWidth;
/**
* Constructor for Drivecharacterization class
*
* @param maxVelocity max veloicty
* @param maxAcceleration max acceleration
* @param trackWidth trackWidth of robot
*/
public DriveCharacterization(double maxVelocity, double maxAcceleration, double trackWidth) {
this.maxVelocity = maxVelocity;
this.maxAcceleration = maxAcceleration;
this.trackWidth = trackWidth;
}
} |
3e1a796d89a573ac0e6c048fea7a41f5ecad94d9 | 141 | java | Java | src/GUI/GridControl/Shapes/TriangleGridManager.java | sallymerza/cellSociety_team14_public | 751de0d0e051f6534fedd511b78c90a177f223f3 | [
"MIT"
] | null | null | null | src/GUI/GridControl/Shapes/TriangleGridManager.java | sallymerza/cellSociety_team14_public | 751de0d0e051f6534fedd511b78c90a177f223f3 | [
"MIT"
] | null | null | null | src/GUI/GridControl/Shapes/TriangleGridManager.java | sallymerza/cellSociety_team14_public | 751de0d0e051f6534fedd511b78c90a177f223f3 | [
"MIT"
] | null | null | null | 10.071429 | 59 | 0.659574 | 11,251 | /**
*
*/
package GUI.GridControl.Shapes;
/**
*
* @author Sally Al
*
*/
public class TriangleGridManager extends GridShapeManager {
}
|
3e1a79c430a4433b50db203fc7abc13de4b81908 | 3,225 | java | Java | ocamljava-maven-common/src/main/java/mandelbrot/ocamljava_maven_plugin/util/FileMappings.java | struktured/ocamljava-maven-plugin | 1caa69af37377de7a88a80afc56d8a1476103da3 | [
"Apache-2.0"
] | 4 | 2015-01-04T05:31:03.000Z | 2016-06-04T13:43:18.000Z | ocamljava-maven-common/src/main/java/mandelbrot/ocamljava_maven_plugin/util/FileMappings.java | struktured/ocamljava-maven-plugin | 1caa69af37377de7a88a80afc56d8a1476103da3 | [
"Apache-2.0"
] | 1 | 2015-04-22T22:02:47.000Z | 2015-04-22T22:32:57.000Z | ocamljava-maven-common/src/main/java/mandelbrot/ocamljava_maven_plugin/util/FileMappings.java | struktured/ocamljava-maven-plugin | 1caa69af37377de7a88a80afc56d8a1476103da3 | [
"Apache-2.0"
] | null | null | null | 29.861111 | 102 | 0.730543 | 11,252 | package mandelbrot.ocamljava_maven_plugin.util;
import java.io.File;
import java.util.Collection;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
public class FileMappings {
private static final char PACKAGE_NAME_SEPARATOR = '.';
private FileMappings() {
}
public static Multimap<String, String> buildPackageMap(
final File prefixToTruncate, final Collection<String> artifactFiles) {
final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap
.builder();
for (final String artifactFilePath : artifactFiles) {
final String packageName = toPackage(prefixToTruncate,
new File(artifactFilePath).getParent());
builder.put(packageName, artifactFilePath);
}
return builder.build();
}
public static Multimap<String, String> buildPathMap(
final Collection<String> artifactFiles) {
final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap
.builder();
for (final String artifactFilePath : artifactFiles) {
final String parent = new File(artifactFilePath).getParent();
builder.put(parent, artifactFilePath);
}
return builder.build();
}
public static Function<String, String> toPackageTransform(
final File prefixToTruncate) {
return new Function<String, String>() {
@Override
public String apply(String path) {
if (path == null)
return "";
path = StringUtils.isBlank(FileUtils.getExtension(path)) ? path : new File(path).getParent();
if (path == null)
return "";
if (prefixToTruncate != null && prefixToTruncate.getPath() != null && prefixToTruncate.exists()) {
Preconditions.checkState(path.contains(prefixToTruncate.getPath()),
"path \"" + path + "\" does not contain prefix \"" + prefixToTruncate.getPath() + "\"");
final int length = prefixToTruncate.getPath().length();
if (path.length() >= length)
path = path.substring(length);
}
path = StringTransforms.trim(path, File.separatorChar);
path = path.replace(File.separatorChar, PACKAGE_NAME_SEPARATOR);
return path;
}
};
}
public static Collection<String> toPackage(final File prefixToTruncate,
final Collection<String> paths) {
return Collections2.transform(paths,
toPackageTransform(prefixToTruncate));
}
public static String toPackage(final File prefixToTruncate,
final String path) {
return toPackage(prefixToTruncate, ImmutableSet.<String> of(path))
.iterator().next();
}
public static String toPackagePath(final File prefixToTruncate,
final String path) {
return toPackage(prefixToTruncate, ImmutableSet.<String> of(path))
.iterator().next().replace(PACKAGE_NAME_SEPARATOR, File.separatorChar);
}
public static String toPackagePath(final String prefixToTruncate,
final String path) {
return toPackagePath(prefixToTruncate == null ? (File) null : new File(prefixToTruncate), path);
}
}
|
3e1a7a0c39ee34ab59d567bf284d24aacd6d4608 | 2,148 | java | Java | src/main/java/ru/kpfu/itis/factory/ComponentFactoryUser.java | ReQEnoxus/itis-events-hub | 5630cc66ead03cb93d6cbb44d19abd59b9f28441 | [
"Unlicense"
] | 2 | 2019-04-18T09:15:52.000Z | 2019-10-15T18:57:45.000Z | src/main/java/ru/kpfu/itis/factory/ComponentFactoryUser.java | ReQEnoxus/itis-events-hub | 5630cc66ead03cb93d6cbb44d19abd59b9f28441 | [
"Unlicense"
] | 5 | 2020-03-04T23:22:11.000Z | 2021-08-30T16:26:12.000Z | src/main/java/ru/kpfu/itis/factory/ComponentFactoryUser.java | ReQEnoxus/itis-events-hub | 5630cc66ead03cb93d6cbb44d19abd59b9f28441 | [
"Unlicense"
] | null | null | null | 39.054545 | 108 | 0.64013 | 11,253 | package ru.kpfu.itis.factory;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import ru.kpfu.itis.entity.User;
import ru.kpfu.itis.service.UserService;
import ru.kpfu.itis.view.modal.EditElementOfDatabaseWindow;
public class ComponentFactoryUser implements ComponentFactory<User> {
@Override
public Component create(User entity) {
UserService us = new UserService();
Dialog dialog = new Dialog();
dialog.add(new Label("Вы уверены?"));
Button dialogYes = new Button("Да");
dialogYes.getStyle().set("cursor", "pointer");
dialogYes.getStyle().set("color", "red");
dialogYes.addClickListener(evt -> {
us.delete(entity.getLogin());
dialog.close();
UI.getCurrent().getPage().reload();
});
Button dialogNo = new Button("Нет");
dialogNo.getStyle().set("cursor", "pointer");
dialogNo.addClickListener(evt -> {
dialog.close();
});
dialog.add(new HorizontalLayout(dialogYes, dialogNo));
HorizontalLayout nameButton = new HorizontalLayout();
Label LNP = new Label(entity.getLastname() + " " + entity.getName() + " " + entity.getPatronymic());
LNP.getStyle().set("align-self", "center");
LNP.getStyle().set("font-size", "larger");
LNP.getStyle().set("width", "20pc");
LNP.getStyle().set("font-weight", "bold");
Button button = new Button("Изменить");
button.getStyle().set("cursor" , "pointer");
button.addClickListener(evt -> EditElementOfDatabaseWindow.show(entity));
Button delete = new Button("Удалить");
delete.getStyle().set("color", "red");
delete.getStyle().set("cursor", "pointer");
delete.addClickListener(evt -> {
dialog.setOpened(true);
});
nameButton.add(LNP, button, delete);
return nameButton;
}
}
|
3e1a7b605a6191530bd5d7f8bf803c3dcbe9a5d9 | 2,386 | java | Java | src/S0306AdditiveNumber.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 4 | 2021-11-30T20:28:14.000Z | 2022-01-04T04:01:32.000Z | src/S0306AdditiveNumber.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | null | null | null | src/S0306AdditiveNumber.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 1 | 2021-11-30T23:33:51.000Z | 2021-11-30T23:33:51.000Z | 29.45679 | 82 | 0.43378 | 11,254 | import java.util.ArrayList;
import java.util.List;
public class S0306AdditiveNumber {
public boolean isAdditiveNumber(String num) {
for (int i = 0; i < num.length(); i++) {
if (i == num.length()-1) {
continue;
}
// first = 0
for (int j = i+1; j < num.length(); j++) {
if (j == num.length()-1) {
continue;
}
// second = i+1
// sum = j+1
if (isAdditiveNumber(num, 0, i+1, j+1)) {
return true;
}
}
}
return false;
}
private boolean isAdditiveNumber(String num, int first, int second, int sum) {
assert first < second;
assert second < sum;
assert sum < num.length();
String a = num.substring(first, second);
String b = num.substring(second, sum);
String remains = num.substring(sum);
if ((a.length() > 1 && a.startsWith("0")) ||
(b.length() > 1 && b.startsWith("0")) ||
(remains.length() > 1 && remains.startsWith("0"))) {
return false;
}
String add = add(a, b);
if (!remains.startsWith(add)) {
return false;
}
if (remains.equals(add)) {
return true;
}
return isAdditiveNumber(num, second, sum, sum + add.length());
}
private String add(String a, String b) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
List<Character> add = new ArrayList<>();
char c = '0';
for (int i = 0; i < Math.max(aArray.length, bArray.length); i++) {
int av = aArray.length > i ? aArray[aArray.length-1-i] - '0' : 0;
int bv = bArray.length > i ? bArray[bArray.length-1-i] - '0' : 0;
int cv = c - '0';
int s = av+bv+cv;
if (s >= 10) {
c = (char)('0' + s/10);
add.add(0, (char)(s%10+'0'));
} else {
c = '0';
add.add(0, (char)(s + '0'));
}
}
if (c != '0') {
add.add(0, c);
}
StringBuilder sb = new StringBuilder();
for (char ac : add) {
sb.append(ac);
}
return sb.toString();
}
}
|
3e1a7bc9266df30dc416579021f746cd48a3fef8 | 1,985 | java | Java | lucene/core/src/test/org/apache/lucene/search/TestXYDocValuesQueries.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 903 | 2015-01-02T22:13:47.000Z | 2022-03-31T13:40:42.000Z | lucene/core/src/test/org/apache/lucene/search/TestXYDocValuesQueries.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 429 | 2021-03-10T14:47:58.000Z | 2022-03-31T21:26:52.000Z | lucene/core/src/test/org/apache/lucene/search/TestXYDocValuesQueries.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 480 | 2015-01-05T03:07:05.000Z | 2022-03-31T10:35:08.000Z | 38.173077 | 94 | 0.768766 | 11,255 | /*
* 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.lucene.search;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.XYDocValuesField;
import org.apache.lucene.geo.XYGeometry;
import org.apache.lucene.geo.XYPolygon;
import org.apache.lucene.tests.geo.BaseXYPointTestCase;
public class TestXYDocValuesQueries extends BaseXYPointTestCase {
@Override
protected void addPointToDoc(String field, Document doc, float x, float y) {
doc.add(new XYDocValuesField(field, x, y));
}
@Override
protected Query newRectQuery(String field, float minX, float maxX, float minY, float maxY) {
return XYDocValuesField.newSlowBoxQuery(field, minX, maxX, minY, maxY);
}
@Override
protected Query newDistanceQuery(String field, float centerX, float centerY, float radius) {
return XYDocValuesField.newSlowDistanceQuery(field, centerX, centerY, radius);
}
@Override
protected Query newPolygonQuery(String field, XYPolygon... polygons) {
return XYDocValuesField.newSlowPolygonQuery(field, polygons);
}
@Override
protected Query newGeometryQuery(String field, XYGeometry... geometries) {
return XYDocValuesField.newSlowGeometryQuery(field, geometries);
}
}
|
3e1a7c1e5a24bfe2699664dd87edbcc6f7023c56 | 1,466 | java | Java | Library/src/main/java/com/sunzn/utils/library/ViewUtils.java | uncn/AndroidUtil | f0f0223c5e2d666163cebf7498cfef95df62f742 | [
"Apache-2.0"
] | 3 | 2017-05-31T07:04:14.000Z | 2017-06-12T06:53:16.000Z | Library/src/main/java/com/sunzn/utils/library/ViewUtils.java | uncn/AndroidUtil | f0f0223c5e2d666163cebf7498cfef95df62f742 | [
"Apache-2.0"
] | null | null | null | Library/src/main/java/com/sunzn/utils/library/ViewUtils.java | uncn/AndroidUtil | f0f0223c5e2d666163cebf7498cfef95df62f742 | [
"Apache-2.0"
] | null | null | null | 35.756098 | 100 | 0.255798 | 11,256 | package com.sunzn.utils.library;
import android.view.View;
import android.widget.TextView;
public class ViewUtils {
private ViewUtils() {
throw new RuntimeException("Stub!");
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:设置 View 显示状态
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:view
* ║ 参数:visibility
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static void setVisibility(View view, int visibility) {
if (view != null) view.setVisibility(visibility);
}
/**
* ╔════════════════════════════════════════════════════════════════════════════════════════════
* ║ 名称:绑定 TextView
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 参数:view
* ║ 参数:text
* ╟────────────────────────────────────────────────────────────────────────────────────────────
* ║ 返回:void
* ╚════════════════════════════════════════════════════════════════════════════════════════════
*/
public static void bindTextView(TextView view, String text) {
if (view != null) view.setText(text == null ? "" : text);
}
}
|
3e1a7c64097f901d7156b0b8ebbdcc2eb052e09d | 1,508 | java | Java | Rest/alm-distributedtask-client/src/main/generated/com/microsoft/alm/teamfoundation/distributedtask/webapi/ServiceEndpointDetails.java | Bhaskers-Blu-Org2/vso-httpclient-java | 7b6329238498d7ad1934243150f955bea594df37 | [
"MIT"
] | 2 | 2021-10-20T11:35:54.000Z | 2021-11-08T09:50:00.000Z | Rest/alm-distributedtask-client/src/main/generated/com/microsoft/alm/teamfoundation/distributedtask/webapi/ServiceEndpointDetails.java | JetBrains/vso-httpclient-java | 7b6329238498d7ad1934243150f955bea594df37 | [
"MIT"
] | null | null | null | Rest/alm-distributedtask-client/src/main/generated/com/microsoft/alm/teamfoundation/distributedtask/webapi/ServiceEndpointDetails.java | JetBrains/vso-httpclient-java | 7b6329238498d7ad1934243150f955bea594df37 | [
"MIT"
] | 1 | 2022-03-19T08:36:49.000Z | 2022-03-19T08:36:49.000Z | 24.322581 | 77 | 0.567639 | 11,257 | // @formatter:off
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license. See License.txt in the project root.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*
* See following wiki page for instructions on how to regenerate:
* https://vsowiki.com/index.php?title=Rest_Client_Generation
*/
package com.microsoft.alm.teamfoundation.distributedtask.webapi;
import java.net.URI;
import java.util.HashMap;
/**
*/
public class ServiceEndpointDetails {
private EndpointAuthorization authorization;
private HashMap<String, String> data;
private String type;
private URI url;
public EndpointAuthorization getAuthorization() {
return authorization;
}
public void setAuthorization(final EndpointAuthorization authorization) {
this.authorization = authorization;
}
public HashMap<String, String> getData() {
return data;
}
public void setData(final HashMap<String, String> data) {
this.data = data;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
}
|
3e1a7ded81f589bd953c36fea35d4d30427f7e68 | 2,834 | java | Java | src/main/java/net/bytzo/admission/utilities/OptionalTypeAdapterFactory.java | bytzo/admission | 19f1c529620370f24b0d8400a3412ca071557475 | [
"MIT"
] | 3 | 2021-06-18T02:35:41.000Z | 2021-09-20T05:04:32.000Z | src/main/java/net/bytzo/admission/utilities/OptionalTypeAdapterFactory.java | bytzo/admission | 19f1c529620370f24b0d8400a3412ca071557475 | [
"MIT"
] | null | null | null | src/main/java/net/bytzo/admission/utilities/OptionalTypeAdapterFactory.java | bytzo/admission | 19f1c529620370f24b0d8400a3412ca071557475 | [
"MIT"
] | null | null | null | 37.76 | 95 | 0.751059 | 11,258 | /*
* Copyright © 2021 Bytzo <efpyi@example.com> and the Admission contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.bytzo.admission.utilities;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Optional;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class OptionalTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (type.getRawType() != Optional.class) {
return null;
}
Type parameterType = ((ParameterizedType) type.getType()).getActualTypeArguments()[0];
TypeAdapter<?> parameterAdapter = gson.getAdapter(TypeToken.get(parameterType));
return (TypeAdapter<T>) this.newOptionalTypeAdapter(parameterAdapter);
}
private <T> TypeAdapter<Optional<T>> newOptionalTypeAdapter(TypeAdapter<T> parameterAdapter) {
return new TypeAdapter<Optional<T>>() {
@Override
public Optional<T> read(JsonReader in) throws IOException {
return Optional.ofNullable(parameterAdapter.read(in));
}
@Override
public void write(JsonWriter out, Optional<T> value) throws IOException {
if (value == null) {
out.nullValue();
} else if (value.isEmpty()) {
// Always serialize optionals with nulls to differentiate from null optionals.
boolean serializeNulls = out.getSerializeNulls();
out.setSerializeNulls(true);
out.nullValue();
out.setSerializeNulls(serializeNulls);
} else {
parameterAdapter.write(out, value.get());
}
}
};
}
}
|
3e1a7fb256cc7271a3fe2698871abcd5c76ef055 | 1,081 | java | Java | src/engine/actions/TranslateIDAction.java | kevinli194/voogasalad_BitsPlease | 54e414908e011ada2dcb824865173c993cf1708a | [
"MIT"
] | null | null | null | src/engine/actions/TranslateIDAction.java | kevinli194/voogasalad_BitsPlease | 54e414908e011ada2dcb824865173c993cf1708a | [
"MIT"
] | null | null | null | src/engine/actions/TranslateIDAction.java | kevinli194/voogasalad_BitsPlease | 54e414908e011ada2dcb824865173c993cf1708a | [
"MIT"
] | null | null | null | 23.5 | 74 | 0.697502 | 11,259 | package engine.actions;
import java.util.List;
import authoring.model.collections.GameObjectsCollection;
import engine.GameManager;
import engine.gameObject.GameObject;
import engine.gameObject.Identifier;
/**
* Action that performs GameObject Transforms/Movements
* @author Will
*
*/
public abstract class TranslateIDAction implements Action, Initializable {
protected transient GameObjectsCollection myGameObjects;
protected List<Identifier> myGameObjectIDs;
protected Double myValue;
public TranslateIDAction (List<Identifier> iDs, Double value) {
myGameObjectIDs = iDs;
myValue = value;
}
@Override
public void execute () {
applyTransform();
}
@Override
public void initialize (GameManager manager) {
myGameObjects = new GameObjectsCollection();
for (Identifier id: myGameObjectIDs){
myGameObjects.add(manager.objectForIdentifier(id));
}
}
/**
* Applies the specific transform in X and Y
*/
public abstract void applyTransform ();
}
|
3e1a80c42f5bb067b71904e98f494a8db833797e | 1,585 | java | Java | src/main/java/com/ybz/service/impl/DataBillsServiceImpl.java | skylingyun/DataStateSystem | 4169cb45353bc68137c52069d145afe6535ddc34 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ybz/service/impl/DataBillsServiceImpl.java | skylingyun/DataStateSystem | 4169cb45353bc68137c52069d145afe6535ddc34 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ybz/service/impl/DataBillsServiceImpl.java | skylingyun/DataStateSystem | 4169cb45353bc68137c52069d145afe6535ddc34 | [
"Apache-2.0"
] | null | null | null | 37.738095 | 96 | 0.745741 | 11,260 | package com.ybz.service.impl;
import com.ybz.service.IDataBillsService;
import com.ybz.service.IDataNodeBusinessTripService;
import com.ybz.service.IDataNodeExpenseService;
import com.ybz.service.IDataNodeLoanBillService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by Guoru on 2017/8/10.
*/
@Service
public class DataBillsServiceImpl implements IDataBillsService {
@Resource(name = "dataNodeBusinessTripServiceImpl")
IDataNodeBusinessTripService dataNodeBusinessTripService;
@Resource(name = "dataNodeExpenseServiceImpl")
IDataNodeExpenseService dataNodeExpenseService;
@Resource(name = "dataNodeLoanBillServiceImpl")
IDataNodeLoanBillService dataNodeLoanBillService;
public List<Map<String,Integer>> getDataBillsPage(String beginTime, String endTime){
List<Map<String,Integer>> list = new LinkedList<Map<String,Integer>>();
Map<String,Integer> map = new HashMap<String, Integer>();
int businessTripCount = dataNodeBusinessTripService.countByExample(beginTime, endTime);
int expenseCount = dataNodeExpenseService.countByExample(beginTime, endTime);
int loanBillCount = dataNodeLoanBillService.countByExample(beginTime, endTime);
map.put("businessTrip",businessTripCount);
map.put("expense",expenseCount);
map.put("loanBill",loanBillCount);
list.add(map);
return list;
}
}
|
3e1a80e721ef29b2fbcd08f6462f4b8c03759894 | 22,049 | java | Java | src/main/java/com/baidu/hugegraph/cmd/HugeGraphCommand.java | logic4nil/hugegraph-tools | 38d18fb286c21c5546ebf71e93813080b8aa71fb | [
"Apache-2.0"
] | 19 | 2018-07-30T06:16:00.000Z | 2021-12-29T03:12:14.000Z | src/main/java/com/baidu/hugegraph/cmd/HugeGraphCommand.java | logic4nil/hugegraph-tools | 38d18fb286c21c5546ebf71e93813080b8aa71fb | [
"Apache-2.0"
] | 49 | 2018-09-13T05:04:52.000Z | 2021-12-21T07:39:54.000Z | src/main/java/com/baidu/hugegraph/cmd/HugeGraphCommand.java | logic4nil/hugegraph-tools | 38d18fb286c21c5546ebf71e93813080b8aa71fb | [
"Apache-2.0"
] | 25 | 2018-07-30T15:37:30.000Z | 2022-01-21T08:30:19.000Z | 41.36773 | 102 | 0.570321 | 11,261 | /*
* Copyright 2017 HugeGraph Authors
*
* 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.baidu.hugegraph.cmd;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import com.baidu.hugegraph.base.Printer;
import com.baidu.hugegraph.base.ToolClient;
import com.baidu.hugegraph.base.ToolClient.ConnectionInfo;
import com.baidu.hugegraph.base.ToolManager;
import com.baidu.hugegraph.constant.Constants;
import com.baidu.hugegraph.exception.ExitException;
import com.baidu.hugegraph.manager.AuthBackupRestoreManager;
import com.baidu.hugegraph.manager.BackupManager;
import com.baidu.hugegraph.manager.DumpGraphManager;
import com.baidu.hugegraph.manager.GraphsManager;
import com.baidu.hugegraph.manager.GremlinManager;
import com.baidu.hugegraph.manager.RestoreManager;
import com.baidu.hugegraph.manager.TasksManager;
import com.baidu.hugegraph.structure.Task;
import com.baidu.hugegraph.structure.constant.GraphMode;
import com.baidu.hugegraph.structure.gremlin.Result;
import com.baidu.hugegraph.structure.gremlin.ResultSet;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.ToolUtil;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.ParametersDelegate;
import com.google.common.collect.Lists;
import static com.baidu.hugegraph.manager.BackupManager.BACKUP_DEFAULT_TIMEOUT;
public class HugeGraphCommand {
private static final int DEFAULT_CLEAR_TIMEOUT = 300;
private SubCommands subCommands;
private List<ToolManager> taskManagers;
@ParametersDelegate
private SubCommands.Url url = new SubCommands.Url();
@ParametersDelegate
private SubCommands.Graph graph = new SubCommands.Graph();
@ParametersDelegate
private SubCommands.Username username = new SubCommands.Username();
@ParametersDelegate
private SubCommands.Password password = new SubCommands.Password();
@ParametersDelegate
private SubCommands.Timeout timeout = new SubCommands.Timeout();
@ParametersDelegate
private SubCommands.TrustStoreFile trustStoreFile =
new SubCommands.TrustStoreFile();
@ParametersDelegate
private SubCommands.TrustStorePassword trustStorePassword =
new SubCommands.TrustStorePassword();
@ParametersDelegate
private SubCommands.ThrowMode throwMode = new SubCommands.ThrowMode();
public HugeGraphCommand() {
this.subCommands = new SubCommands();
this.taskManagers = Lists.newArrayList();
}
public Map<String, Object> subCommands() {
return this.subCommands.commands();
}
@SuppressWarnings("unchecked")
public <T> T subCommand(String subCmd) {
return (T) this.subCommands.commands().get(subCmd);
}
public String url() {
return this.url.url;
}
private void url(String url) {
this.url.url = url;
}
public String graph() {
return this.graph.graph;
}
private void graph(String graph) {
this.graph.graph = graph;
}
public String username() {
return this.username.username;
}
public void username(String username) {
this.username.username = username;
}
public String password() {
return this.password.password;
}
public void password(String password) {
this.password.password = password;
}
public int timeout() {
return this.timeout.timeout;
}
public void timeout(int timeout) {
this.timeout.timeout = timeout;
}
public String trustStoreFile () {
return this.trustStoreFile.trustStoreFile;
}
public void trustStoreFile(String trustStoreFile) {
this.trustStoreFile.trustStoreFile = trustStoreFile;
}
public String trustStorePassword () {
return this.trustStorePassword.trustStorePassword;
}
public void trustStorePassword(String trustStorePassword) {
this.trustStorePassword.trustStorePassword = trustStorePassword;
}
public boolean throwMode() {
return this.throwMode.throwMode;
}
private void throwMode(boolean throwMode) {
this.throwMode.throwMode = throwMode;
}
public JCommander jCommander() {
JCommander.Builder builder = JCommander.newBuilder();
// Add main command firstly
builder.addObject(this);
// Add sub-commands
for (Map.Entry<String, Object> entry : this.subCommands().entrySet()) {
builder.addCommand(entry.getKey(), entry.getValue());
}
JCommander jCommander = builder.build();
jCommander.setProgramName("hugegraph");
jCommander.setCaseSensitiveOptions(true);
jCommander.setAllowAbbreviatedOptions(true);
return jCommander;
}
private void execute(String subCmd, JCommander jCommander) {
this.checkMainParams();
switch (subCmd) {
case "backup":
if (this.timeout() < BACKUP_DEFAULT_TIMEOUT) {
this.timeout(BACKUP_DEFAULT_TIMEOUT);
}
Printer.print("Graph '%s' start backup!", this.graph());
SubCommands.Backup backup = this.subCommand(subCmd);
BackupManager backupManager = manager(BackupManager.class);
backupManager.init(backup);
backupManager.backup(backup.types());
break;
case "restore":
GraphsManager graphsManager = manager(GraphsManager.class);
GraphMode mode = graphsManager.mode(this.graph());
E.checkState(mode.maintaining(),
"Invalid mode '%s' of graph '%s' for restore " +
"sub-command", mode, this.graph());
Printer.print("Graph '%s' start restore in mode '%s'!",
this.graph(), mode);
SubCommands.Restore restore = this.subCommand(subCmd);
RestoreManager restoreManager = manager(RestoreManager.class);
restoreManager.init(restore);
restoreManager.mode(mode);
restoreManager.restore(restore.types());
break;
case "migrate":
SubCommands.Migrate migrate = this.subCommand(subCmd);
Printer.print("Migrate graph '%s' from '%s' to '%s' as '%s'",
this.graph(), this.url(),
migrate.targetUrl(), migrate.targetGraph());
// Backup source graph
if (this.timeout() < BACKUP_DEFAULT_TIMEOUT) {
this.timeout(BACKUP_DEFAULT_TIMEOUT);
}
backup = convMigrate2Backup(migrate);
backupManager = manager(BackupManager.class);
backupManager.init(backup);
backupManager.backup(backup.types());
// Restore source graph to target graph
this.url(migrate.targetUrl());
this.graph(migrate.targetGraph());
this.username(migrate.targetUsername());
this.password(migrate.targetPassword());
this.timeout(migrate.targetTimeout());
this.trustStoreFile(migrate.targetTrustStoreFile());
this.trustStorePassword(migrate.targetTrustStorePassword());
graphsManager = manager(GraphsManager.class);
GraphMode origin = graphsManager.mode(migrate.targetGraph());
// Set target graph mode
mode = migrate.mode();
E.checkState(mode.maintaining(),
"Invalid mode '%s' of graph '%s' for restore",
mode, migrate.targetGraph());
graphsManager.mode(migrate.targetGraph(), mode);
// Restore
Printer.print("Graph '%s' start restore in mode '%s'!",
migrate.targetGraph(), migrate.mode());
String directory = backupManager.directory().directory();
restore = convMigrate2Restore(migrate, directory);
restoreManager = manager(RestoreManager.class);
restoreManager.init(restore);
restoreManager.mode(mode);
restoreManager.restore(restore.types());
// Restore target graph mode
graphsManager.mode(migrate.targetGraph(), origin);
break;
case "dump":
Printer.print("Graph '%s' start dump!", this.graph());
SubCommands.DumpGraph dump = this.subCommand(subCmd);
DumpGraphManager dumpManager = manager(DumpGraphManager.class);
dumpManager.init(dump);
dumpManager.dumpFormatter(dump.formatter());
dumpManager.dump();
break;
case "graph-list":
graphsManager = manager(GraphsManager.class);
Printer.printList("Graphs", graphsManager.list());
break;
case "graph-get":
graphsManager = manager(GraphsManager.class);
Printer.printMap("Graph info",
graphsManager.get(this.graph()));
break;
case "graph-clear":
SubCommands.GraphClear graphClear = this.subCommand(subCmd);
if (timeout() < DEFAULT_CLEAR_TIMEOUT) {
this.timeout(DEFAULT_CLEAR_TIMEOUT);
}
graphsManager = manager(GraphsManager.class);
graphsManager.clear(this.graph(), graphClear.confirmMessage());
Printer.print("Graph '%s' is cleared", this.graph());
break;
case "graph-mode-set":
SubCommands.GraphModeSet graphModeSet = this.subCommand(subCmd);
graphsManager = manager(GraphsManager.class);
graphsManager.mode(this.graph(), graphModeSet.mode());
Printer.print("Set graph '%s' mode to '%s'",
this.graph(), graphModeSet.mode());
break;
case "graph-mode-get":
graphsManager = manager(GraphsManager.class);
Printer.printKV("Graph mode", graphsManager.mode(this.graph()));
break;
case "gremlin-execute":
SubCommands.Gremlin gremlin = this.subCommand(subCmd);
GremlinManager gremlinManager = manager(GremlinManager.class);
Printer.print("Run gremlin script");
ResultSet result = gremlinManager.execute(gremlin.script(),
gremlin.bindings(),
gremlin.language(),
gremlin.aliases());
Iterator<Result> iterator = result.iterator();
while (iterator.hasNext()) {
Printer.print(iterator.next().getString());
}
break;
case "gremlin-schedule":
SubCommands.GremlinJob job = this.subCommand(subCmd);
gremlinManager = manager(GremlinManager.class);
Printer.print("Run gremlin script as async job");
long taskId = gremlinManager.executeAsTask(job.script(),
job.bindings(),
job.language());
Printer.printKV("Task id", taskId);
break;
case "task-list":
SubCommands.TaskList taskList = this.subCommand(subCmd);
TasksManager tasksManager = manager(TasksManager.class);
List<Task> tasks = tasksManager.list(taskList.status(),
taskList.limit());
List<Object> results = tasks.stream().map(Task::asMap)
.collect(Collectors.toList());
Printer.printList("Tasks", results);
break;
case "task-get":
SubCommands.TaskGet taskGet = this.subCommand(subCmd);
tasksManager = manager(TasksManager.class);
Printer.printKV("Task info",
tasksManager.get(taskGet.taskId()).asMap());
break;
case "task-delete":
SubCommands.TaskDelete taskDelete = this.subCommand(subCmd);
tasksManager = manager(TasksManager.class);
tasksManager.delete(taskDelete.taskId());
Printer.print("Task '%s' is deleted", taskDelete.taskId());
break;
case "task-cancel":
SubCommands.TaskCancel taskCancel = this.subCommand(subCmd);
tasksManager = manager(TasksManager.class);
tasksManager.cancel(taskCancel.taskId());
Printer.print("Task '%s' is cancelled", taskCancel.taskId());
break;
case "task-clear":
SubCommands.TaskClear taskClear = this.subCommand(subCmd);
tasksManager = manager(TasksManager.class);
tasksManager.clear(taskClear.force());
Printer.print("Tasks are cleared[force=%s]",
taskClear.force());
break;
case "auth-backup":
Printer.print("Auth backup start...");
SubCommands.AuthBackup authBackup = this.subCommand(subCmd);
AuthBackupRestoreManager authBackupManager = manager(AuthBackupRestoreManager.class);
authBackupManager.init(authBackup);
authBackupManager.backup(authBackup.types());
break;
case "auth-restore":
Printer.print("Auth restore start...");
SubCommands.AuthRestore authRestore = this.subCommand(subCmd);
AuthBackupRestoreManager authRestoreManager = manager(AuthBackupRestoreManager.class);
authRestoreManager.init(authRestore);
authRestoreManager.restore(authRestore.types());
break;
default:
throw new ParameterException(String.format(
"Invalid sub-command: %s", subCmd));
}
}
private void execute(String[] args) {
JCommander jCommander = this.parseCommand(args);
this.execute(jCommander.getParsedCommand(), jCommander);
}
private void checkMainParams() {
E.checkArgument(this.url() != null, "Url can't be null");
E.checkArgument(this.username() == null && this.password() == null ||
this.username() != null && this.password() != null,
"Both user name and password must be null or " +
"not null at same time");
}
private <T extends ToolManager> T manager(Class<T> clz) {
try {
ConnectionInfo info = new ConnectionInfo(this.url(), this.graph(),
this.username(),
this.password(),
this.timeout(),
this.trustStoreFile(),
this.trustStorePassword());
T toolManager = clz.getConstructor(ToolClient.ConnectionInfo.class)
.newInstance(info);
this.taskManagers.add(toolManager);
return toolManager;
} catch (Exception e) {
throw new RuntimeException(String.format(
"Construct manager failed for class '%s', please make " +
"sure global arguments set correctly: " +
"--url=%s,--graph=%s,--user=%s,--password=%s," +
"--timeout=%s,--trust-store-file=%s," +
"--trust-store-password=%s", clz.getSimpleName(),
this.url(), this.graph(), this.username(),
this.password(), this.timeout(),
this.trustStoreFile(), this.trustStorePassword()), e);
}
}
private static SubCommands.Backup convMigrate2Backup(
SubCommands.Migrate migrate) {
SubCommands.Backup backup = new SubCommands.Backup();
backup.splitSize(migrate.splitSize());
backup.directory(migrate.directory());
backup.logDir(migrate.logDir());
backup.types(migrate.types());
backup.retry(migrate.retry());
backup.hdfsConf(migrate.hdfsConf());
return backup;
}
private static SubCommands.Restore convMigrate2Restore(
SubCommands.Migrate migrate,
String directory) {
SubCommands.Restore restore = new SubCommands.Restore();
restore.clean(!migrate.keepData());
restore.directory(directory);
restore.logDir(migrate.logDir());
restore.types(migrate.types());
restore.retry(migrate.retry());
restore.hdfsConf(migrate.hdfsConf());
return restore;
}
private GraphMode mode() {
GraphsManager graphsManager = manager(GraphsManager.class);
GraphMode mode = graphsManager.mode(this.graph());
E.checkState(mode.maintaining(),
"Invalid mode '%s' of graph '%s' for restore " +
"sub-command", mode, this.graph());
return mode;
}
public JCommander parseCommand(String[] args) {
JCommander jCommander = this.jCommander();
if (args.length == 0) {
throw ExitException.exception(ToolUtil.commandUsage(jCommander),
"No command found, please input" +
" command");
}
if (this.parseHelp(args, jCommander)) {
assert false;
} else {
jCommander.parse(args);
}
String subCommand = jCommander.getParsedCommand();
if (subCommand == null) {
throw ExitException.normal(ToolUtil.commandsCategory(
jCommander),
"No sub-command found");
}
return jCommander;
}
public boolean parseHelp(String[] args, JCommander jCommander) {
String subCommand = Strings.EMPTY;
List<String> list = Arrays.asList(args);
if (!list.contains(Constants.COMMAND_HELP)) {
return false;
}
// Parse the '--throw-mode' command
if (list.contains(Constants.COMMAND_THROW_MODE)) {
int index = list.indexOf(Constants.COMMAND_THROW_MODE) + 1;
jCommander.parse(Constants.COMMAND_THROW_MODE,
list.get(index));
}
int index = list.indexOf(Constants.COMMAND_HELP);
if (list.size() > index + 1) {
subCommand = list.get(index + 1);
}
if (StringUtils.isEmpty(subCommand)) {
throw ExitException.normal(ToolUtil.commandUsage(jCommander),
"Command : hugegragh help");
}
Map<String, JCommander> commands = jCommander.getCommands();
if (commands.containsKey(subCommand)) {
throw ExitException.normal(ToolUtil.commandUsage(
commands.get(subCommand)),
"Command : hugegragh help %s",
subCommand);
} else {
throw ExitException.exception(ToolUtil.commandsCategory(jCommander),
"Unexpected help sub-command " +
"%s", subCommand);
}
}
public void shutdown() {
if (CollectionUtils.isEmpty(this.taskManagers)) {
return;
}
for (ToolManager toolManager : this.taskManagers) {
toolManager.close();
}
}
public static void main(String[] args) {
HugeGraphCommand cmd = new HugeGraphCommand();
int exitCode = Constants.EXIT_CODE_NORMAL;
try {
cmd.execute(args);
} catch (ExitException e) {
exitCode = e.exitCode();
ToolUtil.exitOrThrow(e, cmd.throwMode());
} catch (Throwable e) {
exitCode = Constants.EXIT_CODE_ERROR;
ToolUtil.printOrThrow(e, cmd.throwMode());
} finally {
cmd.shutdown();
}
if (exitCode != Constants.EXIT_CODE_NORMAL) {
System.exit(exitCode);
}
}
}
|
3e1a81a38264185f7153ffe5e2121417cec07d17 | 1,442 | java | Java | rave-components/rave-mongodb/src/main/java/org/apache/rave/portal/model/WidgetUsersMapReduceResult.java | adamskwersky/rave | b59bb204850ac6faac9bf798749ca1a4be9303bd | [
"Apache-2.0"
] | 13 | 2015-01-12T09:22:15.000Z | 2021-11-10T16:16:30.000Z | rave-components/rave-mongodb/src/main/java/org/apache/rave/portal/model/WidgetUsersMapReduceResult.java | adamskwersky/rave | b59bb204850ac6faac9bf798749ca1a4be9303bd | [
"Apache-2.0"
] | 2 | 2019-01-16T09:33:50.000Z | 2019-02-03T10:48:52.000Z | rave-components/rave-mongodb/src/main/java/org/apache/rave/portal/model/WidgetUsersMapReduceResult.java | w2ogroup/rave-old | 38c277fce29e07029702fbe15215f09dbc170059 | [
"Apache-2.0"
] | 13 | 2015-07-24T20:03:34.000Z | 2021-11-10T16:16:25.000Z | 28.27451 | 75 | 0.68516 | 11,262 | /*
* 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.rave.portal.model;
import java.util.Map;
public class WidgetUsersMapReduceResult {
private String id;
private Map<String, Long> value;
public WidgetUsersMapReduceResult() { }
public WidgetUsersMapReduceResult(String id, Map<String, Long> value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Long> getValue() {
return value;
}
public void setValue(Map<String, Long> value) {
this.value = value;
}
}
|
3e1a81bc6ca34e73d79680a9ca3e84662ba2bc33 | 3,998 | java | Java | vrml-request/src/main/java/com/kevinten/vrml/request/proxy/AbstractRequestProxy.java | dgzpg/vrml | 795caabbb32d09087396351d542b1b3de0e7341a | [
"Apache-2.0"
] | 9 | 2020-11-18T09:59:58.000Z | 2021-11-03T01:38:05.000Z | vrml-request/src/main/java/com/kevinten/vrml/request/proxy/AbstractRequestProxy.java | dgzpg/vrml | 795caabbb32d09087396351d542b1b3de0e7341a | [
"Apache-2.0"
] | 1 | 2020-12-19T15:01:48.000Z | 2020-12-19T15:01:48.000Z | vrml-request/src/main/java/com/kevinten/vrml/request/proxy/AbstractRequestProxy.java | dgzpg/vrml | 795caabbb32d09087396351d542b1b3de0e7341a | [
"Apache-2.0"
] | 4 | 2020-12-20T08:32:09.000Z | 2021-10-14T06:54:51.000Z | 27.013514 | 127 | 0.610305 | 11,263 | package com.kevinten.vrml.request.proxy;
import com.kevinten.vrml.core.serialization.Serialization;
import com.kevinten.vrml.error.code.ErrorCodeContext;
import com.kevinten.vrml.error.exception.ErrorCodeException;
import lombok.extern.slf4j.Slf4j;
/**
* The abstract request proxy.
*
* @param <Request> the request
* @param <Response> the response
* @param <Excp> the exception
* @param <Code> the error code
*/
@Slf4j
public abstract class AbstractRequestProxy<Request, Response, Excp extends ErrorCodeException, Code extends ErrorCodeContext> {
/**
* Request name string.
*
* @return the string
*/
protected abstract String requestName();
/**
* Throws error exception.
*
* @param errorCodes the error codes
* @return throws exception
* @throws Excp the exception
*/
protected abstract Excp throwsError(Code errorCodes) throws Excp;
/**
* Throws error exception.
*
* @param errorCodes the error codes
* @param e the exception
* @return throws exception
* @throws Excp the exception
*/
protected abstract Excp throwsError(Code errorCodes, Exception e) throws Excp;
/**
* Invoke response.
*
* @param request the request
* @return the response
*/
public Response invoke(Request request) {
this.beforeInvoke(request);
try {
Response response = this.invokeRequest(request);
this.afterInvoke(response);
return response;
} catch (ErrorCodeException e) {
throw e;
} catch (Exception e) {
throw this.throwsError(this.dependentErrorCode(), e);
}
}
/**
* Logging request
*/
private void beforeInvoke(Request request) {
log.info("[{}] request[{}]", this.requestName(), Serialization.GSON.toJson(request));
}
/**
* Logging response
*/
private void afterInvoke(Response response) {
log.info("[{}] response[{}]", this.requestName(), Serialization.GSON.toJson(response));
}
/**
* Logging response when exception
*
* @param response the response
*/
protected void afterInvokeException(Response response) {
log.warn("[{}] response[{}]", this.requestName(), Serialization.GSON.toJson(response));
}
/**
* Invoke request response.
*
* @param request the request
* @return the response
* @throws Exception the exception
*/
protected abstract Response invokeRequest(Request request) throws Exception;
/**
* Dependent error code error codes.
*
* @return the error codes
*/
protected abstract Code dependentErrorCode();
/**
* Assert not null.
*
* @param o the o
* @param keyName the key name
*/
protected void assertNotNull(Object o, String keyName) {
this.assertNotNull(o, keyName, this.dependentErrorCode());
}
/**
* Assert not null.
*
* @param o the o
* @param keyName the key name
* @param errorCodes the error codes
*/
protected void assertNotNull(Object o, String keyName, Code errorCodes) {
if (o == null) {
log.warn("[{}] {} is null!", this.requestName(), keyName);
throw this.throwsError(errorCodes);
}
}
/**
* Assert response success.
*
* @param response the response
*/
protected void assertResponseNotNull(Response response) {
this.assertResponseNotNull(response, this.dependentErrorCode());
}
/**
* Assert response success.
*
* @param response the response
* @param errorCodes the error codes
*/
protected void assertResponseNotNull(Response response, Code errorCodes) {
if (response == null) {
log.warn("[{}] response is null!", this.requestName());
throw this.throwsError(errorCodes);
}
}
} |
3e1a81db241143e924447b68f0a05ffe05e1883c | 596 | java | Java | src/objects/BooleanObj.java | wouterreijgers/RayTracingEngine | da5aa58323980b52f75416b81633e03419a0c2c8 | [
"MIT"
] | null | null | null | src/objects/BooleanObj.java | wouterreijgers/RayTracingEngine | da5aa58323980b52f75416b81633e03419a0c2c8 | [
"MIT"
] | null | null | null | src/objects/BooleanObj.java | wouterreijgers/RayTracingEngine | da5aa58323980b52f75416b81633e03419a0c2c8 | [
"MIT"
] | null | null | null | 17.529412 | 55 | 0.610738 | 11,264 | package objects;
import util.Hitinfo;
public class BooleanObj implements ObjectShapeIF {
public ObjectCol left, right;
public BooleanObj(ObjectCol left, ObjectCol right){
this.left=left;
this.right=right;
}
public ObjectCol getLeft() {
return left;
}
public void setLeft(ObjectCol left) {
this.left = left;
}
public ObjectCol getRight() {
return right;
}
public void setRight(ObjectCol right) {
this.right = right;
}
@Override
public Hitinfo isHit(Ray ray) {
return null;
}
}
|
3e1a8463b87109ce26d8440dec4fed341ac7166f | 1,628 | java | Java | src/test/java/com/github/grignaak/collections/CowCollectorsTest.java | grignaak/cow-collections | 85197399af47bdadf3f8b245b8ac1aa4abacb04a | [
"MIT"
] | 11 | 2018-01-05T21:26:37.000Z | 2021-07-13T03:24:21.000Z | src/test/java/com/github/grignaak/collections/CowCollectorsTest.java | grignaak/cow-collections | 85197399af47bdadf3f8b245b8ac1aa4abacb04a | [
"MIT"
] | 3 | 2018-01-10T00:46:10.000Z | 2018-01-25T16:25:58.000Z | src/test/java/com/github/grignaak/collections/CowCollectorsTest.java | grignaak/cow-collections | 85197399af47bdadf3f8b245b8ac1aa4abacb04a | [
"MIT"
] | 1 | 2018-01-23T08:37:13.000Z | 2018-01-23T08:37:13.000Z | 28.561404 | 88 | 0.630221 | 11,265 | package com.github.grignaak.collections;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
public class CowCollectorsTest {
@Test
public void testToCowList() {
List<Integer> numbers = Arrays.asList(-2, -1, 0, 1, 2);
final List<Integer> expected = Arrays.asList(0, 1, 2);
CowList<Integer> actual = numbers.stream()
.filter(number -> number >= 0)
.collect(CowCollectors.toCowList());
assertEquals(expected, actual);
}
@Test
public void testToCowSet() {
Collection<Integer> numbers = Arrays.asList(-1, -1, 2, 3, 4, 4, 5);
final Set<Integer> expected = new HashSet<>(Arrays.asList(2, 3, 4, 5));
CowSet<Integer> actual = numbers.stream()
.filter(number -> number >= 0)
.collect(CowCollectors.toCowSet());
assertEquals(expected, actual);
}
@Test
public void testToOrderedCowSet() {
Collection<Integer> numbers = Arrays.asList(5, 4, 3, 3, -2, -1, 2, 2, -1, 4, 5);
final Set<Integer> expected = new HashSet<>(Arrays.asList(2, 3, 4, 5));
CowSet<Integer> actual = numbers.stream()
.filter(number -> number >= 0)
.collect(CowCollectors.toOrderedCowSet(Comparator.naturalOrder()));
assertEquals(expected, actual);
}
}
|
3e1a84b3e63ea3d28b26dc1d3d95bd359cdf98e4 | 875 | java | Java | app/src/main/java/com/codepath/apps/simpletweets/models/FriendLookupResult.java | chudeer/android-twitter-tweet | b4196122801d3efcf9800167ea3c9a3b45a1f34e | [
"MIT"
] | null | null | null | app/src/main/java/com/codepath/apps/simpletweets/models/FriendLookupResult.java | chudeer/android-twitter-tweet | b4196122801d3efcf9800167ea3c9a3b45a1f34e | [
"MIT"
] | 1 | 2017-03-06T10:24:10.000Z | 2017-03-13T06:17:30.000Z | app/src/main/java/com/codepath/apps/simpletweets/models/FriendLookupResult.java | chudeer/android-twitter-tweet | b4196122801d3efcf9800167ea3c9a3b45a1f34e | [
"MIT"
] | null | null | null | 21.875 | 74 | 0.682286 | 11,266 | package com.codepath.apps.simpletweets.models;
/**
* Created by YichuChen on 3/10/17.
*/
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class FriendLookupResult {
private String name;
@JsonProperty("screen_name")
private String screenName;
private Long id;
private List<String> connections;
public String getName() {
return name;
}
public String getScreenName() {
return screenName;
}
public Long getId() {
return id;
}
public boolean isFollowing() {
return connections != null && connections.contains("following");
}
public boolean isFollowedBy() {
return connections != null && connections.contains("followed_by");
}
}
|
3e1a869e79c9535ed073bfc878df37f1a8bf3515 | 564 | java | Java | evaluation/model/src/main/java/model/ArticleEntity_.java | alexrashed/rest_eval | 30e3e5ef329dadc51d4e6735ff4bc2ebd551dc32 | [
"MIT"
] | null | null | null | evaluation/model/src/main/java/model/ArticleEntity_.java | alexrashed/rest_eval | 30e3e5ef329dadc51d4e6735ff4bc2ebd551dc32 | [
"MIT"
] | null | null | null | evaluation/model/src/main/java/model/ArticleEntity_.java | alexrashed/rest_eval | 30e3e5ef329dadc51d4e6735ff4bc2ebd551dc32 | [
"MIT"
] | null | null | null | 37.6 | 77 | 0.836879 | 11,267 | package model;
import java.math.BigDecimal;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2016-05-29T23:47:05.512+0200")
@StaticMetamodel(ArticleEntity.class)
public class ArticleEntity_ extends BaseEntity_ {
public static volatile SingularAttribute<ArticleEntity, String> name;
public static volatile SingularAttribute<ArticleEntity, BigDecimal> price;
public static volatile SingularAttribute<ArticleEntity, String> description;
}
|
3e1a86edf99cdf84fecc5095cc2dc0fe44b57267 | 827 | java | Java | app/src/main/java/com/example/android/quakereport/Earthquake.java | AZamalzoheir/ud843-QuakeRport-starting-point | fe0c84bdad53d87eb75b36dcc8414803695ae1d4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/Earthquake.java | AZamalzoheir/ud843-QuakeRport-starting-point | fe0c84bdad53d87eb75b36dcc8414803695ae1d4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/Earthquake.java | AZamalzoheir/ud843-QuakeRport-starting-point | fe0c84bdad53d87eb75b36dcc8414803695ae1d4 | [
"Apache-2.0"
] | null | null | null | 24.323529 | 84 | 0.580411 | 11,268 | package com.example.android.quakereport;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Amalzoheir on 11/20/2017.
*/
public class Earthquake {
private double mMagnitude;
private String mLocation;
private Long mDate;
private String url;
public Earthquake(double mMagnitude,String mLocation,Long mDate,String url){
this.mMagnitude=mMagnitude;
this.mLocation=mLocation;
this.mDate=mDate;
this.url=url;
}
public double getmMagnitude() {
return mMagnitude;
}
public String getmLocation() {
return mLocation;
}
public Long getDate() {
return mDate;
}
public String grtUrl(){
return url;
}
}
|
3e1a881655f186daf53a24f30de7cee2370b97d3 | 912 | java | Java | src/main/java/com/smartsheet/api/models/WidgetContent.java | MatsumiyaT/smartsheet-java-sdk | faef24370e3969ef1105633ce409fdb4b4c85160 | [
"Apache-2.0"
] | 25 | 2015-06-08T13:17:59.000Z | 2021-11-04T16:35:18.000Z | src/main/java/com/smartsheet/api/models/WidgetContent.java | MatsumiyaT/smartsheet-java-sdk | faef24370e3969ef1105633ce409fdb4b4c85160 | [
"Apache-2.0"
] | 34 | 2015-06-24T22:38:20.000Z | 2021-03-01T17:05:16.000Z | src/main/java/com/smartsheet/api/models/WidgetContent.java | MatsumiyaT/smartsheet-java-sdk | faef24370e3969ef1105633ce409fdb4b4c85160 | [
"Apache-2.0"
] | 23 | 2015-02-19T08:32:23.000Z | 2021-08-02T20:08:57.000Z | 28.5 | 75 | 0.705044 | 11,269 | package com.smartsheet.api.models;
/*
* #[license]
* Smartsheet SDK for Java
* %%
* Copyright (C) 2019 Smartsheet
* %%
* 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.
* %[license]
*/
import com.smartsheet.api.models.enums.WidgetType;
public interface WidgetContent {
/**
* Get the widgetContent type
*
* @return widgetContent type;
*/
WidgetType getWidgetType();
}
|
3e1a888e45410d105fa137cd46e1b7ddb6242bb6 | 855 | java | Java | easy-http-library/src/main/java/com/yang/easyhttp/download/EasySimpleDownloadTaskListener.java | Ackcidentally/EasyHttp | 49c13bd82ec448cb584bf0faa6365b9de1c5d802 | [
"Apache-2.0"
] | 149 | 2017-02-20T06:51:26.000Z | 2021-02-23T18:03:22.000Z | easy-http-library/src/main/java/com/yang/easyhttp/download/EasySimpleDownloadTaskListener.java | Ackcidentally/EasyHttp | 49c13bd82ec448cb584bf0faa6365b9de1c5d802 | [
"Apache-2.0"
] | 5 | 2017-04-25T09:25:12.000Z | 2020-12-14T12:52:57.000Z | easy-http-library/src/main/java/com/yang/easyhttp/download/EasySimpleDownloadTaskListener.java | Ackcidentally/EasyHttp | 49c13bd82ec448cb584bf0faa6365b9de1c5d802 | [
"Apache-2.0"
] | 27 | 2017-03-08T07:11:43.000Z | 2021-05-28T06:14:10.000Z | 17.44898 | 61 | 0.709942 | 11,270 | package com.yang.easyhttp.download;
/**
* Created by yangy on 2017/2/16.
*/
public interface EasySimpleDownloadTaskListener {
/**
* queue
* @param downloadTask
*/
void onQueue(EasySimpleDownloadTask downloadTask);
/**
* connecting
* @param downloadTask
*/
void onConnecting(EasySimpleDownloadTask downloadTask);
/**
* downloading
* @param downloadTask
*/
void onDownloading(EasySimpleDownloadTask downloadTask);
/**
* pauseTask
* @param downloadTask
*/
void onPause(EasySimpleDownloadTask downloadTask);
/**
* cancel
* @param downloadTask
*/
void onCancel(EasySimpleDownloadTask downloadTask);
/**
* success
* @param downloadTask
*/
void onFinish(EasySimpleDownloadTask downloadTask);
/**
* failure
* @param downloadTask
*/
void onError(EasySimpleDownloadTask downloadTask, int code);
}
|
3e1a88f492591f17061c1525b20b9ee4cf28228b | 2,987 | java | Java | src/main/java/com/walkertribe/ian/protocol/core/SimpleEventPacket.java | JordanLongstaff/ian | 1cf47701211a85116e5531d7d29fabfaf0f57840 | [
"MIT"
] | 11 | 2016-08-30T19:14:30.000Z | 2022-01-25T23:34:57.000Z | src/main/java/com/walkertribe/ian/protocol/core/SimpleEventPacket.java | JordanLongstaff/ian | 1cf47701211a85116e5531d7d29fabfaf0f57840 | [
"MIT"
] | 19 | 2016-05-26T00:08:47.000Z | 2020-05-06T19:07:04.000Z | src/main/java/com/walkertribe/ian/protocol/core/SimpleEventPacket.java | JordanLongstaff/ian | 1cf47701211a85116e5531d7d29fabfaf0f57840 | [
"MIT"
] | 2 | 2017-10-26T12:02:47.000Z | 2018-02-13T20:36:14.000Z | 37.810127 | 71 | 0.639772 | 11,271 | package com.walkertribe.ian.protocol.core;
import com.walkertribe.ian.iface.PacketReader;
import com.walkertribe.ian.iface.PacketWriter;
import com.walkertribe.ian.protocol.BaseArtemisPacket;
import com.walkertribe.ian.protocol.Packet;
/**
* A superclass for handling SIMPLE_EVENT server packets.
* @author rjwut
*/
public abstract class SimpleEventPacket extends BaseArtemisPacket {
/**
* SIMPLE_EVENT server packet subtypes.
*/
public static final class SubType {
public static final byte EXPLOSION = 0x00;
public static final byte KLAXON = 0x01;
public static final byte UNKNOWN_02 = 0x02;
public static final byte SOUND_EFFECT = 0x03;
public static final byte PAUSE = 0x04;
public static final byte PLAYER_SHIP_DAMAGE = 0x05;
public static final byte END_GAME = 0x06;
public static final byte CLOAK_DECLOAK = 0x07;
public static final byte TENSION = 0x08;
public static final byte SKYBOX = 0x09;
public static final byte GAME_MESSAGE = 0x0a;
public static final byte AUTO_DAMCON = 0x0b;
public static final byte JUMP_BEGIN = 0x0c;
public static final byte JUMP_END = 0x0d;
public static final byte UNKNOWN_0E = 0x0e;
public static final byte SHIP_SETTINGS = 0x0f;
public static final byte DMX_MESSAGE = 0x10;
public static final byte KEY_CAPTURE = 0x11;
public static final byte PERSPECTIVE = 0x12;
public static final byte DETONATION = 0x13;
public static final byte GAME_OVER_REASON = 0x14;
public static final byte GAME_OVER_STATS = 0x15;
public static final byte UNKNOWN_16 = 0x16;
public static final byte SINGLE_SEAT_LAUNCHED = 0x17;
public static final byte SINGLE_SEAT_DAMAGE = 0x18;
public static final byte BIOMECH_STANCE = 0x19;
public static final byte DOCKED = 0x1a;
public static final byte SMOKE = 0x1b;
public static final byte SINGLE_SEAT_TEXT = 0x1c;
public static final byte TAG = 0x1d;
public static final byte GAME_OVER = 0x1e;
private SubType() {
// prevent instantiation
}
}
private byte mSubType;
/**
* Use this constructor if the class services only one subtype.
*/
protected SimpleEventPacket() {
mSubType = getClass().getAnnotation(Packet.class).subtype()[0];
}
/**
* Use this constructor if the class services multiple subtypes.
*/
protected SimpleEventPacket(byte subType) {
mSubType = subType;
}
protected SimpleEventPacket(PacketReader reader) {
mSubType = (byte) reader.readInt();
}
@Override
protected void writePayload(PacketWriter writer) {
writer.writeInt(mSubType);
}
}
|
3e1a892957e47a63119c3ee2541ba39efeaabb56 | 1,279 | java | Java | unitils-core/src/main/java/org/unitils/core/util/ResourceConfigLoader.java | tweea/unitils | 0bbf96ebd619b4423c2d2c76dfd8d21506c5be99 | [
"Apache-2.0"
] | null | null | null | unitils-core/src/main/java/org/unitils/core/util/ResourceConfigLoader.java | tweea/unitils | 0bbf96ebd619b4423c2d2c76dfd8d21506c5be99 | [
"Apache-2.0"
] | 3 | 2020-09-10T03:10:54.000Z | 2022-01-21T23:46:58.000Z | unitils-core/src/main/java/org/unitils/core/util/ResourceConfigLoader.java | tweea/unitils | 0bbf96ebd619b4423c2d2c76dfd8d21506c5be99 | [
"Apache-2.0"
] | null | null | null | 38.757576 | 106 | 0.732604 | 11,272 | /*
* Copyright 2008, Unitils.org
* 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.unitils.core.util;
/**
* Defines the contract for implementations that find a resource configuration on a test object, returning
* a subtype of {@link ResourceConfig} that wraps the configuration
*
* @author Filip Neven
* @author Tim Ducheyne
* @param <RC>
* Implementation of {@link ResourceConfig}
*/
public interface ResourceConfigLoader<RC extends ResourceConfig> {
/**
* @param testObject
* The test instance, not null
* @return The resource configuration for the given test object. Null if the test object
* doesn't specify any configuration for the resource type in question
*/
RC loadResourceConfig(Object testObject);
}
|
3e1a89a332439f1fa95e084d36e31a453250db78 | 5,509 | java | Java | src/main/java/de/fraunhofer/fokus/fuzzing/fuzzino/request/impl/StringSpecificationImpl.java | hielsnoppe/Fuzzino | e628a5af781928c92bb0c891c8dc6cc0fbb3eba8 | [
"Apache-2.0"
] | 33 | 2015-04-17T05:03:21.000Z | 2022-03-30T15:38:41.000Z | src/main/java/de/fraunhofer/fokus/fuzzing/fuzzino/request/impl/StringSpecificationImpl.java | hielsnoppe/Fuzzino | e628a5af781928c92bb0c891c8dc6cc0fbb3eba8 | [
"Apache-2.0"
] | 3 | 2019-12-02T17:06:40.000Z | 2020-10-13T11:11:01.000Z | src/main/java/de/fraunhofer/fokus/fuzzing/fuzzino/request/impl/StringSpecificationImpl.java | hielsnoppe/Fuzzino | e628a5af781928c92bb0c891c8dc6cc0fbb3eba8 | [
"Apache-2.0"
] | 10 | 2015-05-01T19:50:29.000Z | 2020-12-29T21:27:18.000Z | 27.964467 | 109 | 0.747504 | 11,273 | // Copyright 2012-2013 Fraunhofer FOKUS
//
// 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.fraunhofer.fokus.fuzzing.fuzzino.request.impl;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import de.fraunhofer.fokus.fuzzing.fuzzino.request.IntegerSpecification;
import de.fraunhofer.fokus.fuzzing.fuzzino.request.RequestFactory;
import de.fraunhofer.fokus.fuzzing.fuzzino.request.StringEncoding;
import de.fraunhofer.fokus.fuzzing.fuzzino.request.StringSpecification;
import de.fraunhofer.fokus.fuzzing.fuzzino.request.StringType;
import de.fraunhofer.fokus.fuzzing.fuzzino.response.IllegalRequestFormat;
import de.fraunhofer.fokus.fuzzing.fuzzino.response.ResponseFactory;
import de.fraunhofer.fokus.fuzzing.fuzzino.response.WarningsSection;
import de.fraunhofer.fokus.fuzzing.fuzzino.util.ValidationResult;
@XmlAccessorType(XmlAccessType.NONE)
public class StringSpecificationImpl implements StringSpecification {
private static final long serialVersionUID = -6918660757447213918L;
@XmlAttribute
protected StringType type = StringType.STRING;
@XmlAttribute
protected int minLength = 0;
@XmlAttribute
protected int maxLength = Integer.MAX_VALUE;
@XmlAttribute
protected boolean nullTerminated = false;
@XmlAttribute
protected StringEncoding encoding = StringEncoding.ASCII;
// TODO set default value for regEx?
@XmlAttribute
protected String regEx;
@XmlAttribute
protected boolean ignoreLengths = false;
@Override
public StringType getType() {
return type;
}
@Override
public void setType(StringType value) {
type = value;
}
@Override
public int getMinLength() {
return minLength;
}
@Override
public void setMinLength(int value) {
minLength = value;
}
@Override
public int getMaxLength() {
return maxLength;
}
@Override
public void setMaxLength(int value) {
maxLength = value;
}
@Override
public boolean isNullTerminated() {
return nullTerminated;
}
@Override
public void setIsNullTerminated(boolean value) {
nullTerminated = value;
}
@Override
public StringEncoding getEncoding() {
return encoding;
}
@Override
public void setEncoding(StringEncoding value) {
encoding = value;
}
@Override
public String getRegEx() {
return regEx;
}
@Override
public void setRegEx(String value) {
regEx = value;
}
@Override
public ValidationResult validate() {
WarningsSection warningsPart = ResponseFactory.INSTANCE.createWarnings();
boolean validLength = true;
if (!ignoreLengths() && getMinLength() < 0) {
validLength = false;
IllegalRequestFormat illegalRequestFormat =
ResponseFactory.INSTANCE.createIllegalRequestFormatWithWrongAttribute("specification", "minLength");
warningsPart.getIllegalRequestFormats().add(illegalRequestFormat);
}
if (!ignoreLengths() && ((getMaxLength() < 0) || (getMaxLength() < getMinLength()))) {
validLength = false;
IllegalRequestFormat illegalRequestFormat =
ResponseFactory.INSTANCE.createIllegalRequestFormatWithWrongAttribute("specification", "maxLength");
warningsPart.getIllegalRequestFormats().add(illegalRequestFormat);
}
boolean result = validLength;
return new ValidationResult(result, warningsPart);
}
@Override
public String toString() {
return "[StringSpecification type:" + type + " minLength:" + minLength + " maxLength:" + maxLength +
" nullTerminated:" + nullTerminated + " encoding:" + encoding + "]";
}
@Override
public IntegerSpecification createPositiveNumberSpec() {
if (getMaxLength() == 0) {
throw new UnsupportedOperationException("Cannot create positive NumberSpecification: maxLength is 0.");
}
IntegerSpecification numberSpec = RequestFactory.INSTANCE.createNumberSpecification();
if (ignoreLengths()) {
numberSpec.setIgnoreMinMaxValues(true);
} else {
long minValue = 0;
if (getMinLength() > 0) {
minValue = (long) Math.pow(10, getMinLength()-1);
}
numberSpec.setMin(minValue);
long maxValue = (long) Math.pow(10, getMaxLength())-1;
numberSpec.setMax(maxValue);
}
return numberSpec;
}
@Override
public IntegerSpecification createNegativeNumberSpec() {
if (getMaxLength() <= 1) {
throw new UnsupportedOperationException("Cannot create negative NumberSpecification: maxLength is <= 1.");
}
IntegerSpecification numberSpec = RequestFactory.INSTANCE.createNumberSpecification();
if (ignoreLengths()) {
numberSpec.setIgnoreMinMaxValues(true);
} else {
long maxValue = -1;
if (getMinLength() > 2) {
maxValue = (long) -Math.pow(10, getMinLength()-2);
}
numberSpec.setMax(maxValue);
long minValue = (long) -Math.pow(10, getMaxLength()-1) + 1;
numberSpec.setMin(minValue);
}
return numberSpec;
}
@Override
public void setIgnoreLengths(boolean value) {
ignoreLengths = value;
}
@Override
public boolean ignoreLengths() {
return ignoreLengths;
}
}
|
3e1a8a9f6d9642009a5ea6df4242fd7a44c7f896 | 16,623 | java | Java | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/option/black/FXOptionBlackTermStructureFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 12 | 2017-03-10T13:56:52.000Z | 2021-10-03T01:21:20.000Z | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/option/black/FXOptionBlackTermStructureFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 1 | 2021-08-02T17:20:43.000Z | 2021-08-02T17:20:43.000Z | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/option/black/FXOptionBlackTermStructureFunction.java | UbuntuEvangelist/OG-Platform | 0aac9675ff92fd702d2e53a991de085388bfdc83 | [
"Apache-2.0"
] | 16 | 2017-01-12T10:31:58.000Z | 2019-04-19T08:17:33.000Z | 64.430233 | 190 | 0.810624 | 11,274 | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.forex.option.black;
import static com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackFunction.CALL_CURVE;
import static com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG;
import static com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackFunction.PUT_CURVE;
import static com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.Clock;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.option.definition.YieldCurveWithBlackForexTermStructureBundle;
import com.opengamma.analytics.financial.model.volatility.curve.BlackForexTermStructureParameters;
import com.opengamma.analytics.financial.model.volatility.surface.SmileDeltaTermStructureParametersStrikeInterpolation;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.conversion.ForexSecurityConverter;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.analytics.model.forex.ConventionBasedFXRateFunction;
import com.opengamma.financial.analytics.model.forex.ForexVisitors;
import com.opengamma.financial.currency.CurrencyPair;
import com.opengamma.financial.currency.CurrencyPairs;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.FinancialSecurityTypes;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.UnorderedCurrencyPair;
import com.opengamma.util.tuple.Pair;
import com.opengamma.util.tuple.Pairs;
/**
* @deprecated This function uses deprecated functions from the analytics library.
*/
@Deprecated
public abstract class FXOptionBlackTermStructureFunction extends AbstractFunction.NonCompiledInvoker {
/** The name of the calculation method */
public static final String BLACK_TERM_STRUCTURE_METHOD = "BlackTermStructure";
private final String _valueRequirementName;
public FXOptionBlackTermStructureFunction(final String valueRequirementName) {
ArgumentChecker.notNull(valueRequirementName, "value requirement name");
_valueRequirementName = valueRequirementName;
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final Clock snapshotClock = executionContext.getValuationClock();
final ZonedDateTime now = ZonedDateTime.now(snapshotClock);
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final ValueRequirement desiredValue = desiredValues.iterator().next();
final String putCurveName = desiredValue.getConstraint(PUT_CURVE);
final String callCurveName = desiredValue.getConstraint(CALL_CURVE);
final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE);
final String putCurveConfig = desiredValue.getConstraint(PUT_CURVE_CALC_CONFIG);
final String callCurveConfig = desiredValue.getConstraint(CALL_CURVE_CALC_CONFIG);
final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
final String leftExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
final String rightExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
final Object baseQuotePairsObject = inputs.getValue(ValueRequirementNames.CURRENCY_PAIRS);
if (baseQuotePairsObject == null) {
throw new OpenGammaRuntimeException("Could not get base/quote pair data");
}
final CurrencyPairs baseQuotePairs = (CurrencyPairs) baseQuotePairsObject;
final String fullPutCurveName = putCurveName + "_" + putCurrency.getCode();
final String fullCallCurveName = callCurveName + "_" + callCurrency.getCode();
final YieldAndDiscountCurve putFundingCurve = getCurve(inputs, putCurrency, putCurveName, putCurveConfig);
final YieldAndDiscountCurve callFundingCurve = getCurve(inputs, callCurrency, callCurveName, callCurveConfig);
final YieldAndDiscountCurve[] curves;
final Map<String, Currency> curveCurrency = new HashMap<>();
curveCurrency.put(fullPutCurveName, putCurrency);
curveCurrency.put(fullCallCurveName, callCurrency);
final InstrumentDefinition<?> definition = security.accept(new ForexSecurityConverter(baseQuotePairs));
final String[] allCurveNames;
final Currency ccy1;
final Currency ccy2;
final Object spotObject = inputs.getValue(ValueRequirementNames.SPOT_RATE);
if (spotObject == null) {
throw new OpenGammaRuntimeException("Could not get spot requirement");
}
final double spot; // = (Double) spotObject;
final CurrencyPair baseQuotePair = baseQuotePairs.getCurrencyPair(putCurrency, callCurrency);
if (baseQuotePair == null) {
throw new OpenGammaRuntimeException("Could not get base/quote pair for currency pair (" + putCurrency + ", " + callCurrency + ")");
}
if (baseQuotePair.getBase().equals(putCurrency)) { // To get Base/quote in market standard order.
ccy1 = putCurrency;
ccy2 = callCurrency;
curves = new YieldAndDiscountCurve[] {putFundingCurve, callFundingCurve };
allCurveNames = new String[] {fullPutCurveName, fullCallCurveName };
spot = (Double) spotObject;
} else {
curves = new YieldAndDiscountCurve[] {callFundingCurve, putFundingCurve };
allCurveNames = new String[] {fullCallCurveName, fullPutCurveName };
ccy1 = callCurrency;
ccy2 = putCurrency;
spot = 1. / (Double) spotObject;
}
final InstrumentDerivative fxOption = definition.toDerivative(now);
final YieldCurveBundle yieldCurves = new YieldCurveBundle(allCurveNames, curves);
final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final ValueRequirement fxVolatilitySurfaceRequirement = getSurfaceRequirement(surfaceName, putCurrency, callCurrency, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final Object volatilitySurfaceObject = inputs.getValue(fxVolatilitySurfaceRequirement);
if (volatilitySurfaceObject == null) {
throw new OpenGammaRuntimeException("Could not get " + fxVolatilitySurfaceRequirement);
}
final FXMatrix fxMatrix = new FXMatrix(ccy1, ccy2, spot);
final ValueProperties.Builder properties = getResultProperties(target, desiredValue, baseQuotePair);
final ValueSpecification spec = new ValueSpecification(_valueRequirementName, target.toSpecification(), properties.get());
final YieldCurveBundle curvesWithFX = new YieldCurveBundle(fxMatrix, curveCurrency, yieldCurves.getCurvesMap());
final Pair<Currency, Currency> currencyPair = Pairs.of(ccy1, ccy2);
BlackForexTermStructureParameters termStructure;
if (volatilitySurfaceObject instanceof SmileDeltaTermStructureParametersStrikeInterpolation) {
final SmileDeltaTermStructureParametersStrikeInterpolation smiles = (SmileDeltaTermStructureParametersStrikeInterpolation) volatilitySurfaceObject;
termStructure = smiles.toTermStructureOnlyData(interpolator);
} else {
termStructure = (BlackForexTermStructureParameters) volatilitySurfaceObject;
}
final YieldCurveWithBlackForexTermStructureBundle flatData = new YieldCurveWithBlackForexTermStructureBundle(curvesWithFX, termStructure, currencyPair);
return getResult(fxOption, flatData, target, desiredValues, inputs, spec, executionContext);
}
@Override
public ComputationTargetType getTargetType() {
return FinancialSecurityTypes.FX_OPTION_SECURITY.or(FinancialSecurityTypes.FX_BARRIER_OPTION_SECURITY).or(FinancialSecurityTypes.FX_DIGITAL_OPTION_SECURITY)
.or(FinancialSecurityTypes.NON_DELIVERABLE_FX_OPTION_SECURITY).or(FinancialSecurityTypes.NON_DELIVERABLE_FX_DIGITAL_OPTION_SECURITY);
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties.Builder properties = getResultProperties(target);
return Collections.singleton(new ValueSpecification(_valueRequirementName, target.toSpecification(), properties.get()));
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> putCurveNames = constraints.getValues(PUT_CURVE);
if (putCurveNames == null || putCurveNames.size() != 1) {
return null;
}
final Set<String> callCurveNames = constraints.getValues(CALL_CURVE);
if (callCurveNames == null || callCurveNames.size() != 1) {
return null;
}
final Set<String> putCurveCalculationConfigs = constraints.getValues(PUT_CURVE_CALC_CONFIG);
if (putCurveCalculationConfigs == null || putCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> callCurveCalculationConfigs = constraints.getValues(CALL_CURVE_CALC_CONFIG);
if (callCurveCalculationConfigs == null || callCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
if (surfaceNames == null || surfaceNames.size() != 1) {
return null;
}
final Set<String> interpolatorNames = constraints.getValues(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
if (interpolatorNames == null || interpolatorNames.size() != 1) {
return null;
}
final Set<String> leftExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
if (leftExtrapolatorNames == null || leftExtrapolatorNames.size() != 1) {
return null;
}
final Set<String> rightExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
if (rightExtrapolatorNames == null || rightExtrapolatorNames.size() != 1) {
return null;
}
final String putCurveName = putCurveNames.iterator().next();
final String callCurveName = callCurveNames.iterator().next();
final String putCurveCalculationConfig = putCurveCalculationConfigs.iterator().next();
final String callCurveCalculationConfig = callCurveCalculationConfigs.iterator().next();
final String surfaceName = surfaceNames.iterator().next();
final String interpolatorName = interpolatorNames.iterator().next();
final String leftExtrapolatorName = leftExtrapolatorNames.iterator().next();
final String rightExtrapolatorName = rightExtrapolatorNames.iterator().next();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final ValueRequirement putFundingCurve = getCurveRequirement(putCurveName, putCurrency, putCurveCalculationConfig);
final ValueRequirement callFundingCurve = getCurveRequirement(callCurveName, callCurrency, callCurveCalculationConfig);
final ValueRequirement fxVolatilitySurface = getSurfaceRequirement(surfaceName, putCurrency, callCurrency, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(putCurrency, callCurrency);
final ValueRequirement spotRequirement = ConventionBasedFXRateFunction.getSpotRateRequirement(currencyPair);
final ValueRequirement pairQuoteRequirement = new ValueRequirement(ValueRequirementNames.CURRENCY_PAIRS, ComputationTargetSpecification.NULL);
return Sets.newHashSet(putFundingCurve, callFundingCurve, fxVolatilitySurface, spotRequirement, pairQuoteRequirement);
}
protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target);
protected abstract ValueProperties.Builder getResultProperties(final ComputationTarget target, final ValueRequirement desiredValue, final CurrencyPair baseQuotePair);
//TODO clumsy. Push the execute() method down into the functions and have getDerivative() and getData() methods
protected abstract Set<ComputedValue> getResult(final InstrumentDerivative forex, final YieldCurveWithBlackForexTermStructureBundle data, final ComputationTarget target,
final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final ValueSpecification spec, final FunctionExecutionContext executionContext);
protected static ValueRequirement getCurveRequirement(final String curveName, final Currency currency, final String curveCalculationConfigName) {
final ValueProperties.Builder properties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE, curveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName);
return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetType.CURRENCY.specification(currency), properties.get());
}
protected static ValueRequirement getSurfaceRequirement(final String surfaceName, final Currency putCurrency, final Currency callCurrency,
final String interpolatorName, final String leftExtrapolatorName, final String rightExtrapolatorName) {
final ValueProperties surfaceProperties = ValueProperties.builder()
.with(ValuePropertyNames.SURFACE, surfaceName)
.with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName)
.get();
final UnorderedCurrencyPair currenciesTarget = UnorderedCurrencyPair.of(putCurrency, callCurrency);
return new ValueRequirement(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, ComputationTargetType.UNORDERED_CURRENCY_PAIR.specification(currenciesTarget), surfaceProperties);
}
protected static YieldAndDiscountCurve getCurve(final FunctionInputs inputs, final Currency currency, final String curveName, final String curveCalculationConfig) {
final Object curveObject = inputs.getValue(getCurveRequirement(curveName, currency, curveCalculationConfig));
if (curveObject == null) {
throw new OpenGammaRuntimeException("Could not get " + curveName + " curve");
}
final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject;
return curve;
}
}
|
3e1a8b00bcf6e69392726e9c687a28f6c500a374 | 13,302 | java | Java | test-result-collection-tool/src/test/java/com/microfocus/mqm/clt/XmlProcessorTest.java | elishevaHa/octane-collection-tool | 8cf1d975fbb667d3da8bd6cda314e805d9e4a66a | [
"Apache-2.0"
] | 1 | 2018-08-05T15:57:50.000Z | 2018-08-05T15:57:50.000Z | test-result-collection-tool/src/test/java/com/microfocus/mqm/clt/XmlProcessorTest.java | elishevaHa/octane-collection-tool | 8cf1d975fbb667d3da8bd6cda314e805d9e4a66a | [
"Apache-2.0"
] | 6 | 2017-12-23T01:16:14.000Z | 2022-03-22T09:52:06.000Z | test-result-collection-tool/src/test/java/com/microfocus/mqm/clt/XmlProcessorTest.java | elishevaHa/octane-collection-tool | 8cf1d975fbb667d3da8bd6cda314e805d9e4a66a | [
"Apache-2.0"
] | 6 | 2019-01-17T13:18:55.000Z | 2022-03-11T10:36:17.000Z | 47.848921 | 163 | 0.670425 | 11,275 | /*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.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
*
* 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.microfocus.mqm.clt;
import com.microfocus.mqm.clt.tests.TestResult;
import com.microfocus.mqm.clt.tests.TestResultStatus;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.Assertion;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.rules.TemporaryFolder;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class XmlProcessorTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testXmlProcessor_minimalAcceptedJUnitFormat() throws URISyntaxException {
// Public API requires at least testName, duration, started and status fields to be filled for every test
XmlProcessor xmlProcessor = new XmlProcessor();
List<TestResult> testResults = xmlProcessor.processJunitTestReport(new File(getClass().getResource("JUnit-minimalAccepted.xml").toURI()), 1444291726L);
Assert.assertNotNull(testResults);
Assert.assertEquals(4, testResults.size());
assertTestResult(testResults.get(0), "", "", "testName", TestResultStatus.PASSED, 0, 1444291726L);
assertTestResult(testResults.get(1), "", "", "testNameSkipped", TestResultStatus.SKIPPED, 2, 1444291726L);
assertTestResult(testResults.get(2), "", "", "testNameFailed", TestResultStatus.FAILED, 3, 1444291726L);
assertTestResult(testResults.get(3), "", "", "testNameWithError", TestResultStatus.FAILED, 4, 1444291726L);
}
@Test
public void testXmlProcessor_testMissingTestName() throws URISyntaxException, IOException, XMLStreamException, InterruptedException {
XmlProcessor xmlProcessor = new XmlProcessor();
List<TestResult> testResults = xmlProcessor.processJunitTestReport(new File(getClass().getResource("JUnit-missingTestName.xml").toURI()), 1445937556462L);
Assert.assertNotNull(testResults);
Assert.assertEquals(3, testResults.size());
assertTestResult(testResults.get(0), "com.examples.example", "SampleClass", "testOne", TestResultStatus.PASSED, 2, 1445937556462L);
assertTestResult(testResults.get(1), "com.examples.example", "SampleClass", "testTwo", TestResultStatus.SKIPPED, 5, 1445937556462L);
assertTestResult(testResults.get(2), "com.examples.example", "SampleClass", "testThree", TestResultStatus.SKIPPED, 5, 1445937556462L);
}
@Test
public void testXmlProcessor_unclosedElement() throws URISyntaxException {
systemOutRule.enableLog();
exit.expectSystemExitWithStatus(1);
exit.checkAssertionAfterwards(new Assertion() {
@Override
public void checkAssertion() throws Exception {
Assert.assertTrue(systemOutRule.getLog().contains("Unable to process JUnit XML file"));
}
});
XmlProcessor xmlProcessor = new XmlProcessor();
xmlProcessor.processJunitTestReport(new File(getClass().getResource("JUnit-unclosedElement.xmlx").toURI()), null);
}
@Test
public void testXmlProcessor_junitFileDoesNotExist() throws URISyntaxException {
systemOutRule.enableLog();
exit.expectSystemExitWithStatus(1);
exit.checkAssertionAfterwards(new Assertion() {
@Override
public void checkAssertion() throws Exception {
Assert.assertTrue(systemOutRule.getLog().contains("Can not read the JUnit XML file:"));
}
});
XmlProcessor xmlProcessor = new XmlProcessor();
xmlProcessor.processJunitTestReport(new File("fileDoesNotExist.xml"), null);
}
@Test
public void testXmlProcessor_writeXml() throws URISyntaxException, IOException, XMLStreamException, ParseException {
File targetFile = temporaryFolder.newFile();
long currentTime = System.currentTimeMillis();
XmlProcessor xmlProcessor = new XmlProcessor();
List<TestResult> testResults = new LinkedList<TestResult>();
testResults.add(new TestResult("com.examples.example", "SampleClass", "testOne", TestResultStatus.PASSED, 2, currentTime));
testResults.add(new TestResult("com.examples.example", "SampleClass", "testTwo", TestResultStatus.SKIPPED, 5, currentTime));
testResults.add(new TestResult("com.examples.example", "SampleClass", "testThree", TestResultStatus.SKIPPED, 5, currentTime));
List<String> tags = new LinkedList<String>();
tags.add("OS:Linux");
tags.add("DB:Oracle");
List<String> fields = new LinkedList<String>();
fields.add("Framework:TestNG");
fields.add("Test_Level:Unit Test");
Settings settings = new Settings();
settings.setTags(tags);
settings.setFields(fields);
settings.setProductAreas(new String[]{"1001", "1002"});
settings.setRelease(1010);
settings.setBacklogItems(new String[]{"1020", "1021"});
xmlProcessor.writeTestResults(testResults, settings, targetFile);
Set<XmlElement> xmlElements = new HashSet<XmlElement>();
xmlElements.add(new XmlElement("taxonomy", "OS", "Linux"));
xmlElements.add(new XmlElement("taxonomy", "DB", "Oracle"));
xmlElements.add(new XmlElement("test_field", "Framework", "TestNG"));
xmlElements.add(new XmlElement("test_field", "Test_Level", "Unit Test"));
xmlElements.add(new XmlElement("product_area_ref", "1001"));
xmlElements.add(new XmlElement("product_area_ref", "1002"));
xmlElements.add(new XmlElement("backlog_item_ref", "1020"));
xmlElements.add(new XmlElement("backlog_item_ref", "1021"));
xmlElements.add(new XmlElement("release_ref", "1010"));
assertXml(new LinkedList<TestResult>(testResults), xmlElements, targetFile);
}
private void assertTestResult(TestResult testResult, String packageName, String className, String testName,
TestResultStatus result, long duration, long started) {
Assert.assertEquals(packageName, testResult.getPackageName());
Assert.assertEquals(className, testResult.getClassName());
Assert.assertEquals(testName, testResult.getTestName());
Assert.assertEquals(result, testResult.getResult());
Assert.assertEquals(duration, testResult.getDuration());
Assert.assertEquals(started, testResult.getStarted());
}
private void assertXml(List<TestResult> expectedTestResults, Set<XmlElement> expectedElements, File xmlFile) throws FileNotFoundException, XMLStreamException {
FileInputStream fis = new FileInputStream(xmlFile);
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(fis);
boolean isFirstEvent = true;
while(xmlStreamReader.hasNext()){
if (!isFirstEvent) {
xmlStreamReader.next();
} else {
isFirstEvent = false;
}
if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
String localName = xmlStreamReader.getLocalName();
if ("taxonomy".equals(localName)) {
assertElement(localName, false, xmlStreamReader, expectedElements);
} else if ("test_field".equals(localName)) {
assertElement(localName, false, xmlStreamReader, expectedElements);
} else if ("product_area_ref".equals(localName)) {
assertElement(localName, true, xmlStreamReader, expectedElements);
} else if ("backlog_item_ref".equals(localName)) {
assertElement(localName, true, xmlStreamReader, expectedElements);
} else if ("release_ref".equals(localName)) {
assertElement(localName, true, xmlStreamReader, expectedElements);
} else if ("test_run".equals(localName)) {
assertXmlTest(xmlStreamReader, expectedTestResults);
}
}
}
xmlStreamReader.close();
IOUtils.closeQuietly(fis);
Assert.assertTrue(expectedElements.isEmpty());
Assert.assertTrue(expectedTestResults.isEmpty());
}
private void assertXmlTest(XMLStreamReader xmlStreamReader, List<TestResult> testResults) {
String testName = xmlStreamReader.getAttributeValue(null, "name");
String statusName = xmlStreamReader.getAttributeValue(null, "status");
String duration = xmlStreamReader.getAttributeValue(null, "duration");
String started = xmlStreamReader.getAttributeValue(null, "started");
Assert.assertNotNull(testName);
Assert.assertNotNull(statusName);
Assert.assertNotNull(duration);
Assert.assertNotNull(started);
TestResult testToFind = new TestResult(
xmlStreamReader.getAttributeValue(null, "package"),
xmlStreamReader.getAttributeValue(null, "class"),
testName, TestResultStatus.fromPrettyName(statusName),
Long.valueOf(duration), Long.valueOf(started));
for (TestResult testResult : testResults) {
if (areTestResultsEqual(testResult, testToFind)) {
testResults.remove(testResult);
return;
}
}
Assert.fail("Can not find the expected test result");
}
private boolean areTestResultsEqual(TestResult first, TestResult second) {
return StringUtils.equals(first.getPackageName(), second.getPackageName()) &&
StringUtils.equals(first.getClassName(), second.getClassName()) &&
StringUtils.equals(first.getTestName(), second.getTestName()) &&
first.getResult() == second.getResult() &&
first.getDuration() == second.getDuration() &&
first.getStarted() == second.getStarted();
}
private void assertElement(String elemName, boolean isReference, XMLStreamReader xmlStreamReader, Set<XmlElement> expectedElements) {
String type = null;
String value;
if (isReference) {
value = xmlStreamReader.getAttributeValue(null, "id");
Assert.assertNotNull(value);
} else {
type = xmlStreamReader.getAttributeValue(null, "type");
value = xmlStreamReader.getAttributeValue(null, "value");
Assert.assertNotNull(type);
Assert.assertNotNull(value);
}
XmlElement element = new XmlElement(elemName, type, value);
Assert.assertTrue(expectedElements.contains(element));
expectedElements.remove(element);
}
private class XmlElement {
private String elemName;
private String type;
private String value;
private XmlElement(String elemName, String type, String value) {
this.elemName = elemName;
this.type = type;
this.value = value;
}
private XmlElement(String elemName, String value) {
this(elemName, null, value);
}
public boolean equals(Object obj) {
if (!(obj instanceof XmlElement))
return false;
if (obj == this)
return true;
return (StringUtils.equals (this.elemName, ((XmlElement) obj).elemName) &&
StringUtils.equals (this.type, ((XmlElement) obj).type) &&
StringUtils.equals (this.value, ((XmlElement) obj).value));
}
public int hashCode(){
int prime = 31;
int result = (elemName != null) ? elemName.hashCode() : prime;
result = prime * result + ((type != null) ? type.hashCode() : prime);
result = prime * result + ((value != null) ? value.hashCode() : prime);
return result;
}
}
}
|
3e1a8bda0644e73e382276026eeaaf504217caf1 | 760 | java | Java | hello-api/src/main/java/com/lightbend/lagom/hello/api/HelloService.java | lagom/lagom-java-openshift-smoketests | 306c97686224d527f4c95a996c5999e76bd9109b | [
"Apache-2.0"
] | null | null | null | hello-api/src/main/java/com/lightbend/lagom/hello/api/HelloService.java | lagom/lagom-java-openshift-smoketests | 306c97686224d527f4c95a996c5999e76bd9109b | [
"Apache-2.0"
] | 6 | 2019-02-15T15:15:17.000Z | 2019-04-25T18:00:35.000Z | hello-api/src/main/java/com/lightbend/lagom/hello/api/HelloService.java | lagom/lagom-java-openshift-smoketest | 306c97686224d527f4c95a996c5999e76bd9109b | [
"Apache-2.0"
] | 1 | 2019-02-15T10:12:16.000Z | 2019-02-15T10:12:16.000Z | 28.148148 | 76 | 0.743421 | 11,276 | /*
* Copyright (C) 2019 Lightbend Inc. <https://www.lightbend.com>
*/
package com.lightbend.lagom.hello.api;
import static com.lightbend.lagom.javadsl.api.Service.named;
import static com.lightbend.lagom.javadsl.api.Service.pathCall;
import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.Descriptor;
import com.lightbend.lagom.javadsl.api.Service;
import com.lightbend.lagom.javadsl.api.ServiceCall;
public interface HelloService extends Service {
ServiceCall<NotUsed, String> hello(String id);
@Override
default Descriptor descriptor() {
// @formatter:off
return named("hello-lagom-java-openshift-smoketests-service").withCalls(
pathCall("/api/hello/:id", this::hello)
).withAutoAcl(true);
// @formatter:on
}
}
|
3e1a8c23fb6f034f3a3da8c1a0453dadd6c7c154 | 9,753 | java | Java | UTubeTVProject - Eclipse/Lib - Cast/src/com/distantfuture/castcompanionlibrary/lib/utils/CastUtils.java | jc6212/Android-UTubeTV | 8a6d2cfbdf79c2eb5a538eaa37bba8b7e6d1b13d | [
"Apache-2.0"
] | 16 | 2015-01-20T19:23:42.000Z | 2020-07-01T03:00:41.000Z | UTubeTVProject/castlib/src/main/java/com/distantfuture/castcompanionlibrary/lib/utils/CastUtils.java | sgehrman/UTubeTV | 64e9db9c14b745487b00b14ffc454056dd0f8cd8 | [
"Unlicense"
] | null | null | null | UTubeTVProject/castlib/src/main/java/com/distantfuture/castcompanionlibrary/lib/utils/CastUtils.java | sgehrman/UTubeTV | 64e9db9c14b745487b00b14ffc454056dd0f8cd8 | [
"Unlicense"
] | 11 | 2015-01-10T12:33:34.000Z | 2020-01-09T20:30:39.000Z | 34.956989 | 107 | 0.693223 | 11,277 | package com.distantfuture.castcompanionlibrary.lib.utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Log;
import com.distantfuture.castcompanionlibrary.lib.BuildConfig;
import com.distantfuture.castcompanionlibrary.lib.R;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.images.WebImage;
import java.util.ArrayList;
/**
* A collection of utility methods, all static.
*/
public class CastUtils {
private static final String TAG = CastUtils.makeLogTag(CastUtils.class);
private static final String KEY_IMAGES = "images";
private static final String KEY_URL = "movie-urls";
private static final String KEY_CONTENT_TYPE = "content-type";
private static final String KEY_STREAM_TYPE = "stream-type";
/**
* Formats time in milliseconds to hh:mm:ss string format.
*/
public static String formatMillis(int millis) {
String result = "";
int hr = millis / 3600000;
millis %= 3600000;
int min = millis / 60000;
millis %= 60000;
int sec = millis / 1000;
if (hr > 0) {
result += hr + ":";
}
if (min >= 0) {
if (min > 9) {
result += min + ":";
} else {
result += "0" + min + ":";
}
}
if (sec > 9) {
result += sec;
} else {
result += "0" + sec;
}
return result;
}
/**
* A utility method to show a simple error dialog. The textual content of the dialog is provided
* through the passed-in resource id.
*/
public static void showErrorDialog(Context context, int resourceId) {
showErrorDialog(context, context.getString(resourceId));
}
/**
* A utility method to show a simple error dialog.
* <p/>
* param message The message to be shown in the dialog
*/
public static void showErrorDialog(Context context, String message) {
new AlertDialog.Builder(context).setTitle(R.string.error)
.setMessage(message)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
/**
* Returns the URL of an image for the MediaInformation at the given level. Level should
* be a number between 0 and <code>n - 1</code> where <code>n
* </code> is the number of images for that given item.
*/
public static String getImageUrl(MediaInfo info, int level) {
MediaMetadata mm = info.getMetadata();
if (null != mm && null != mm.getImages() && mm.getImages().size() > level) {
return mm.getImages().get(level).getUrl().toString();
}
return null;
}
/**
* Saves a string value under the provided key in the preference manager. If <code>value</code>
* is <code>null</code>, then the provided key will be removed from the preferences.
*/
public static void saveStringToPreference(Context context, String key, String value) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
if (null == value) {
// we want to remove
pref.edit().remove(key).apply();
} else {
pref.edit().putString(key, value).apply();
}
}
/**
* Saves a float value under the provided key in the preference manager. If <code>value</code>
* is <code>Float.MIN_VALUE</code>, then the provided key will be removed from the preferences.
*/
public static void saveFloatToPreference(Context context, String key, float value) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
if (Float.MIN_VALUE == value) {
// we want to remove
pref.edit().remove(key).apply();
} else {
pref.edit().putFloat(key, value).apply();
}
}
/**
* Retrieves a String value from preference manager. If no such key exists, it will return
* <code>null</code>.
*/
public static String getStringFromPreference(Context context, String key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
return pref.getString(key, null);
}
/**
* Retrieves a float value from preference manager. If no such key exists, it will return
* <code>Float.MIN_VALUE</code>.
*/
public static float getFloatFromPreference(Context context, String key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
return pref.getFloat(key, Float.MIN_VALUE);
}
/**
* Retrieves a boolean value from preference manager. If no such key exists, it will return the
* value provided as <code>defaultValue</code>
*/
public static boolean getBooleanFromPreference(Context context, String key, boolean defaultValue) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
return pref.getBoolean(key, defaultValue);
}
/**
* A utility method to validate that the appropriate version of the Google Play Services is
* available on the device. If not, it will open a dialog to address the issue. The dialog
* displays a localized message about the error and upon user confirmation (by tapping on
* dialog) will direct them to the Play Store if Google Play services is out of date or missing,
* or to system settings if Google Play services is disabled on the device.
*/
public static boolean checkGooglePlayServices(final Activity activity) {
final int googlePlayServicesCheck = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
switch (googlePlayServicesCheck) {
case ConnectionResult.SUCCESS:
return true;
default:
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesCheck, activity, 0);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
activity.finish();
}
});
dialog.show();
}
return false;
}
/**
* Builds and returns a {@link Bundle} which contains a select subset of data in the
* {@link MediaInfo}. Since {@link MediaInfo} is not {@link Parcelable}, one can use this
* container bundle to pass around from one activity to another.
*/
public static Bundle fromMediaInfo(MediaInfo info) {
if (null == info) {
return null;
}
MediaMetadata md = info.getMetadata();
Bundle wrapper = new Bundle();
wrapper.putString(MediaMetadata.KEY_TITLE, md.getString(MediaMetadata.KEY_TITLE));
wrapper.putString(MediaMetadata.KEY_SUBTITLE, md.getString(MediaMetadata.KEY_SUBTITLE));
wrapper.putString(KEY_URL, info.getContentId());
wrapper.putString(MediaMetadata.KEY_STUDIO, md.getString(MediaMetadata.KEY_STUDIO));
wrapper.putString(KEY_CONTENT_TYPE, info.getContentType());
wrapper.putInt(KEY_STREAM_TYPE, info.getStreamType());
if (null != md.getImages()) {
ArrayList<String> urls = new ArrayList<String>();
for (WebImage img : md.getImages()) {
urls.add(img.getUrl().toString());
}
wrapper.putStringArrayList(KEY_IMAGES, urls);
}
return wrapper;
}
/**
* Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
*/
public static MediaInfo toMediaInfo(Bundle wrapper) {
if (null == wrapper) {
return null;
}
MediaMetadata metaData = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
metaData.putString(MediaMetadata.KEY_SUBTITLE, wrapper.getString(MediaMetadata.KEY_SUBTITLE));
metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
if (null != images && !images.isEmpty()) {
for (String url : images) {
Uri uri = Uri.parse(url);
metaData.addImage(new WebImage(uri));
}
}
return new MediaInfo.Builder(wrapper.getString(KEY_URL)).setStreamType(wrapper.getInt(KEY_STREAM_TYPE))
.setContentType(wrapper.getString(KEY_CONTENT_TYPE))
.setMetadata(metaData)
.build();
}
public static String makeLogTag(String str) {
final String LOG_PREFIX = "ccl_";
final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
final int MAX_LOG_TAG_LENGTH = 23;
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* WARNING: Don't use this when obfuscating class names with Proguard!
*/
public static String makeLogTag(Class<?> cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
}
|
3e1a8c570f1f3efa0b155a36d3bfed8f439d706d | 1,131 | java | Java | server/src/main/java/com/iotolapclickhouse/server/service/TokenValidationService.java | Glost/iot-olap-clickhouse | 428e2204161d2688c8d4ddad90c2664253e8389e | [
"WTFPL"
] | null | null | null | server/src/main/java/com/iotolapclickhouse/server/service/TokenValidationService.java | Glost/iot-olap-clickhouse | 428e2204161d2688c8d4ddad90c2664253e8389e | [
"WTFPL"
] | null | null | null | server/src/main/java/com/iotolapclickhouse/server/service/TokenValidationService.java | Glost/iot-olap-clickhouse | 428e2204161d2688c8d4ddad90c2664253e8389e | [
"WTFPL"
] | 2 | 2020-04-27T19:01:14.000Z | 2020-04-27T19:02:58.000Z | 32.314286 | 85 | 0.721485 | 11,278 | package com.iotolapclickhouse.server.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class TokenValidationService {
private final String generatorToken;
private final String clientToken;
@Autowired
public TokenValidationService(@Value("${token.generator}") String generatorToken,
@Value("${token.client}") String clientToken) {
this.generatorToken = generatorToken;
this.clientToken = clientToken;
}
public void validateGeneratorToken(String receivedGeneratorToken) {
validateToken(receivedGeneratorToken, generatorToken);
}
public void validateClientToken(String receivedClientToken) {
validateToken(receivedClientToken, clientToken);
}
private void validateToken(String receivedToken, String validToken) {
if (receivedToken == null || !receivedToken.equals(validToken)) {
throw new SecurityException("Received token was invalid");
}
}
}
|
3e1a8d828336c985a6ddb170ae0e72460b53cfeb | 2,145 | java | Java | fugue-store/src/main/java/com/symphony/oss/fugue/kv/table/IKvTableTransaction.java | GeremiaLongobardo/oss-fugue | 9cc27ec9dc3cc6fe791eef431289935512362052 | [
"Apache-2.0"
] | null | null | null | fugue-store/src/main/java/com/symphony/oss/fugue/kv/table/IKvTableTransaction.java | GeremiaLongobardo/oss-fugue | 9cc27ec9dc3cc6fe791eef431289935512362052 | [
"Apache-2.0"
] | null | null | null | fugue-store/src/main/java/com/symphony/oss/fugue/kv/table/IKvTableTransaction.java | GeremiaLongobardo/oss-fugue | 9cc27ec9dc3cc6fe791eef431289935512362052 | [
"Apache-2.0"
] | null | null | null | 33 | 114 | 0.750583 | 11,279 | /*
*
*
* Copyright 2019 Symphony Communication Services, LLC.
*
* Licensed to The Symphony Software Foundation (SSF) 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.symphony.oss.fugue.kv.table;
import java.util.Collection;
import java.util.Set;
import com.symphony.oss.commons.hash.Hash;
import com.symphony.oss.fugue.kv.IKvItem;
import com.symphony.oss.fugue.kv.IKvPartitionSortKeyProvider;
import com.symphony.oss.fugue.store.TransactionFailedException;
import com.symphony.oss.fugue.trace.ITraceContext;
/**
* Low level storage of KV Items.
*
* @author Bruce Skingle
*
*/
public interface IKvTableTransaction
{
/**
* Store the given collection of items, checking that the given ppartition sort key pair does not already exist.
*
* @param partitionSortKeyProvider The partition and sort key of the item.
* @param kvItems Items to be stored.
*/
void store(IKvPartitionSortKeyProvider partitionSortKeyProvider, Collection<IKvItem> kvItems);
/**
* Update an existing object.
*
* @param partitionSortKeyProvider The partition and sort key of the existing item.
* @param absoluteHash The absolute hash of the existing item.
* @param kvItems A set of items to be put.
*/
void update(IKvPartitionSortKeyProvider partitionSortKeyProvider, Hash absoluteHash, Set<IKvItem> kvItems);
void commit(ITraceContext trace) throws TransactionFailedException;
}
|
3e1a8de27b05227bbfc81c7a64b7502ba69eedd1 | 4,419 | java | Java | android/app/src/main/java/com/mogujie/tt/ui/fragment/SearchFragment.java | guoyangjun404/TeamTalk | b272ac6a7876a5ad767221309e11ca2f97a53608 | [
"Apache-2.0"
] | 368 | 2019-05-07T08:25:00.000Z | 2022-03-31T07:23:55.000Z | android/app/src/main/java/com/mogujie/tt/ui/fragment/SearchFragment.java | guoyangjun404/TeamTalk | b272ac6a7876a5ad767221309e11ca2f97a53608 | [
"Apache-2.0"
] | 46 | 2018-07-04T08:21:42.000Z | 2018-07-21T08:59:03.000Z | android/app/src/main/java/com/mogujie/tt/ui/fragment/SearchFragment.java | guoyangjun404/TeamTalk | b272ac6a7876a5ad767221309e11ca2f97a53608 | [
"Apache-2.0"
] | 256 | 2019-05-08T04:14:59.000Z | 2022-03-28T07:02:30.000Z | 29.657718 | 103 | 0.685223 | 11,280 | package com.mogujie.tt.ui.fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.mogujie.tools.ScreenTools;
import com.mogujie.tt.DB.entity.DepartmentEntity;
import com.mogujie.tt.DB.entity.GroupEntity;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.R;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.ui.adapter.SearchAdapter;
import com.mogujie.tt.ui.base.TTBaseFragment;
import com.mogujie.tt.utils.Logger;
import java.util.List;
/**
* @yingmu modify
*/
public class SearchFragment extends TTBaseFragment {
private Logger logger = Logger.getLogger(SearchFragment.class);
private View curView = null;
private ListView listView;
private View noSearchResultView;
private SearchAdapter adapter;
IMService imService;
private IMServiceConnector imServiceConnector = new IMServiceConnector(){
@Override
public void onIMServiceConnected() {
logger.d("config#onIMServiceConnected");
imService = imServiceConnector.getIMService();
//init set adapter service
initAdapter();
}
@Override
public void onServiceDisconnected() {
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
imServiceConnector.connect(this.getActivity());
if (null != curView) {
((ViewGroup) curView.getParent()).removeView(curView);
return curView;
}
curView = inflater.inflate(R.layout.tt_fragment_search, topContentView);
noSearchResultView = curView.findViewById(R.id.layout_no_search_result);
initTopBar();
listView = (ListView) curView.findViewById(R.id.search);
return curView;
}
@Override
public void onResume() {
super.onResume();
}
private void initTopBar() {
setTopBar(R.drawable.tt_top_default_bk);
showTopSearchBar();
setTopLeftButton(R.drawable.tt_top_back);
hideTopRightButton();
topLeftBtn.setPadding(0, 0, ScreenTools.instance(getActivity()).dip2px(30), 0);
topLeftBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
getActivity().finish();
}
});
topSearchEdt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String key = s.toString();
adapter.setSearchKey(key);
if(key.isEmpty())
{
adapter.clear();
noSearchResultView.setVisibility(View.GONE);
}else{
searchEntityLists(key);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void initAdapter(){
adapter = new SearchAdapter(getActivity(),imService);
listView.setAdapter(adapter);
listView.setOnItemClickListener(adapter);
listView.setOnItemLongClickListener(adapter);
}
// 文字高亮search 模块
private void searchEntityLists(String key) {
List<UserEntity> contactList = imService.getContactManager().getSearchContactList(key);
int contactSize = contactList.size();
adapter.putUserList(contactList);
List<GroupEntity> groupList = imService.getGroupManager().getSearchAllGroupList(key);
int groupSize = groupList.size();
adapter.putGroupList(groupList);
List<DepartmentEntity> departmentList = imService.getContactManager().getSearchDepartList(key);
int deptSize = departmentList.size();
adapter.putDeptList(departmentList);
int sum = contactSize + groupSize +deptSize;
adapter.notifyDataSetChanged();
if(sum <= 0){
noSearchResultView.setVisibility(View.VISIBLE);
}else{
noSearchResultView.setVisibility(View.GONE);
}
}
@Override
protected void initHandler() {
}
@Override
public void onDestroy() {
imServiceConnector.disconnect(getActivity());
super.onDestroy();
}
}
|
3e1a8e10b1f40448d15e5cb4667df56fa9343b92 | 1,358 | java | Java | Hackerrank/MergeSort.java | Huzaib/Hacktoberfest | 4ba47bc0c4dc33e13d99666a2c2b28bf19eb90fe | [
"MIT"
] | null | null | null | Hackerrank/MergeSort.java | Huzaib/Hacktoberfest | 4ba47bc0c4dc33e13d99666a2c2b28bf19eb90fe | [
"MIT"
] | null | null | null | Hackerrank/MergeSort.java | Huzaib/Hacktoberfest | 4ba47bc0c4dc33e13d99666a2c2b28bf19eb90fe | [
"MIT"
] | null | null | null | 19.681159 | 66 | 0.560383 | 11,281 | package FirstProgram;
public class MergeSort {
private static void Sort(int arr[], int low, int high)
{
if(low<high)
{
int mid = low + (high-low)/2;
Sort(arr, low, mid);
Sort(arr, mid+1, high);
Merge(arr, low, mid, high);
}
else
{return;}
}
private static void Merge(int arr[], int low, int mid, int high)
{
int leftarray[]=new int[mid-low+1];
int rightarray[]=new int[high-mid];
for(int i=0; i<leftarray.length; i++) {
leftarray[i]=arr[low+i];
}
for(int i=0; i<rightarray.length; i++) {
rightarray[i]=arr[mid+1+i];
}
int leftindex=0,rightindex=0;
for(int i=low; i<high+1; i++)
{
if(leftindex<leftarray.length && rightindex<rightarray.length)
{
if(leftarray[leftindex]<rightarray[rightindex])
{
arr[i] = leftarray[leftindex];
leftindex++;
}
else
{
arr[i] = rightarray[rightindex];
rightindex++;
}
}
else if(leftindex<leftarray.length)
{
arr[i]=leftarray[leftindex];
leftindex++;
}
else if(rightindex<rightarray.length)
{
arr[i]=rightarray[rightindex];
rightindex++;
}
}
}
public static void main(String[] args)
{
int arr[] = {4,6,0,8,32,36,4,67,0,12,4};
Sort(arr, 0, 10);
for(int a:arr)
{
System.out.print(a + " ");
}
}
}
|
3e1a8e2523e9869a2596ba1de16c2e743c023ede | 787 | java | Java | chapter_004/src/test/java/collectionpro/WordIndexTest.java | MKonsta/MatushenkoK | 68aa5fc3517e4cf364f0bb4097eee11c54efcf95 | [
"Apache-2.0"
] | null | null | null | chapter_004/src/test/java/collectionpro/WordIndexTest.java | MKonsta/MatushenkoK | 68aa5fc3517e4cf364f0bb4097eee11c54efcf95 | [
"Apache-2.0"
] | 17 | 2020-03-04T22:28:15.000Z | 2022-02-16T00:56:51.000Z | chapter_004/src/test/java/collectionpro/WordIndexTest.java | MKonsta/MatushenkoK | 68aa5fc3517e4cf364f0bb4097eee11c54efcf95 | [
"Apache-2.0"
] | null | null | null | 26.233333 | 67 | 0.682338 | 11,282 | package collectionpro;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
public class WordIndexTest {
@Test
public void whenFindThreeWords() throws IOException {
WordIndex wordIndex = new WordIndex("Raskaz.txt");
Set<Integer> expect = new TreeSet<>();
expect.add(8);
expect.add(14);
assertThat(wordIndex.getIndex4Word("rezjume"), is(expect));
}
@Test
public void whenNoSoWord() throws IOException {
WordIndex wordIndex = new WordIndex("Raskaz.txt");
Set<Integer> expect = null;
assertThat(wordIndex.getIndex4Word("Rezjume"), is(expect));
}
}
|
3e1a8f888f5cda5f8e8c3ed340d3e5626eb4fd22 | 14,034 | java | Java | cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetOperator.java | Tombar/strimzi-kafka-operator | cc0d8cb56b736c7c2eee2289d98cc9ad61093a09 | [
"Apache-2.0"
] | null | null | null | cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetOperator.java | Tombar/strimzi-kafka-operator | cc0d8cb56b736c7c2eee2289d98cc9ad61093a09 | [
"Apache-2.0"
] | null | null | null | cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/StatefulSetOperator.java | Tombar/strimzi-kafka-operator | cc0d8cb56b736c7c2eee2289d98cc9ad61093a09 | [
"Apache-2.0"
] | null | null | null | 46.013115 | 213 | 0.660824 | 11,283 | /*
* Copyright 2017-2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.resource;
import io.strimzi.operator.cluster.model.AbstractModel;
import io.strimzi.operator.common.operator.resource.AbstractScalableResourceOperator;
import io.strimzi.operator.common.operator.resource.PodOperator;
import io.strimzi.operator.common.operator.resource.ReconcileResult;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet;
import io.fabric8.kubernetes.api.model.extensions.StatefulSet;
import io.fabric8.kubernetes.api.model.extensions.StatefulSetList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.RollableScalableResource;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Operations for {@code StatefulSets}s, which supports {@link #maybeRollingUpdate(StatefulSet, boolean)}
* in addition to the usual operations.
*/
public abstract class StatefulSetOperator extends AbstractScalableResourceOperator<KubernetesClient, StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> {
public static final String STRIMZI_CLUSTER_OPERATOR_DOMAIN = "operator.strimzi.io";
public static final String ANNOTATION_GENERATION = STRIMZI_CLUSTER_OPERATOR_DOMAIN + "/statefulset-generation";
private static final int NO_GENERATION = -1;
private static final String NO_UID = "NULL";
private static final int INIT_GENERATION = 0;
private static final Logger log = LogManager.getLogger(StatefulSetOperator.class.getName());
private final PodOperator podOperations;
private final long operationTimeoutMs;
/**
* Constructor
* @param vertx The Vertx instance
* @param client The Kubernetes client
*/
public StatefulSetOperator(Vertx vertx, KubernetesClient client, long operationTimeoutMs) {
this(vertx, client, operationTimeoutMs, new PodOperator(vertx, client));
}
public StatefulSetOperator(Vertx vertx, KubernetesClient client, long operationTimeoutMs, PodOperator podOperator) {
super(vertx, client, "StatefulSet");
this.podOperations = podOperator;
this.operationTimeoutMs = operationTimeoutMs;
}
@Override
protected MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> operation() {
return client.apps().statefulSets();
}
/**
* Asynchronously perform a rolling update of all the pods in the StatefulSet identified by the given
* {@code namespace} and {@code name}, returning a Future that will complete when the rolling update
* is complete. Starting with pod 0, each pod will be deleted and re-created automatically by the ReplicaSet,
* once the pod has been recreated then given {@code isReady} function will be polled until it returns true,
* before the process proceeds with the pod with the next higher number.
*/
public Future<Void> maybeRollingUpdate(StatefulSet ss, boolean forceRestart) {
String namespace = ss.getMetadata().getNamespace();
String name = ss.getMetadata().getName();
final int replicas = ss.getSpec().getReplicas();
log.debug("Considering rolling update of {}/{}", namespace, name);
Future<Void> f = Future.succeededFuture();
// Then for each replica, maybe restart it
for (int i = 0; i < replicas; i++) {
String podName = name + "-" + i;
f = f.compose(ignored -> maybeRestartPod(ss, podName, forceRestart));
}
return f;
}
public Future<Void> maybeRestartPod(StatefulSet ss, String podName, boolean forceRestart) {
long pollingIntervalMs = 1_000;
long timeoutMs = operationTimeoutMs;
String namespace = ss.getMetadata().getNamespace();
String name = ss.getMetadata().getName();
if (isPodUpToDate(ss, podName) && !forceRestart) {
log.debug("Rolling update of {}/{}: pod {} has {}={}; no need to roll",
namespace, name, podName, ANNOTATION_GENERATION, getSsGeneration(ss));
return Future.succeededFuture();
} else {
Future<Void> result = Future.future();
Future<ReconcileResult<Pod>> deleteFinished = Future.future();
log.info("Rolling update of {}/{}: Rolling pod {}", namespace, name, podName);
// Determine generation of deleted pod
Future<String> deleted = getUid(namespace, podName);
// Delete the pod
Future<ReconcileResult<Pod>> podReconcileFuture = deleted.compose(l -> {
log.debug("Rolling update of {}/{}: Waiting for pod {} to be deleted", namespace, name, podName);
// null as desired parameter means pod will be deleted
return podOperations.reconcile(namespace, podName, null);
}).compose(ignore -> {
Future del = podOperations.waitFor(namespace, name, pollingIntervalMs, timeoutMs, (ignore1, ignore2) -> {
// predicate - changed generation means pod has been updated
String newUid = getPodUid(podOperations.get(namespace, podName));
return !deleted.result().equals(newUid);
});
log.debug("Rolling pod {} finished", podName);
return del;
});
podReconcileFuture.setHandler(deleteResult -> {
if (deleteResult.succeeded()) {
log.debug("Rolling update of {}/{}: Pod {} was deleted", namespace, name, podName);
}
deleteFinished.handle(deleteResult);
});
deleteFinished.compose(ix -> podOperations.readiness(namespace, podName, pollingIntervalMs, timeoutMs)).setHandler(result);
return result;
}
}
protected boolean isPodUpToDate(StatefulSet ss, String podName) {
final int ssGeneration = getSsGeneration(ss);
// TODO this call is sync
int podGeneration = getPodGeneration(podOperations.get(ss.getMetadata().getNamespace(), podName));
log.debug("Rolling update of {}/{}: pod {} has {}={}; ss has {}={}",
ss.getMetadata().getNamespace(), ss.getMetadata().getName(), podName,
ANNOTATION_GENERATION, podGeneration,
ANNOTATION_GENERATION, ssGeneration);
return ssGeneration == podGeneration;
}
@Override
protected Integer currentScale(String namespace, String name) {
StatefulSet statefulSet = get(namespace, name);
if (statefulSet != null) {
return statefulSet.getSpec().getReplicas();
} else {
return null;
}
}
private static ObjectMeta templateMetadata(StatefulSet resource) {
return resource.getSpec().getTemplate().getMetadata();
}
public String getPodName(StatefulSet desired, int podId) {
return templateMetadata(desired).getName() + "-" + podId;
}
private void setGeneration(StatefulSet desired, int nextGeneration) {
templateMetadata(desired).getAnnotations().put(ANNOTATION_GENERATION, String.valueOf(nextGeneration));
}
private static int getGeneration(ObjectMeta objectMeta) {
if (objectMeta.getAnnotations().get(ANNOTATION_GENERATION) == null) {
return NO_GENERATION;
}
String generationAnno = objectMeta.getAnnotations().get(ANNOTATION_GENERATION);
if (generationAnno == null) {
return NO_GENERATION;
} else {
return Integer.parseInt(generationAnno);
}
}
protected void incrementGeneration(StatefulSet current, StatefulSet desired) {
final int generation = Integer.parseInt(templateMetadata(current).getAnnotations().getOrDefault(ANNOTATION_GENERATION, String.valueOf(INIT_GENERATION)));
final int nextGeneration = generation + 1;
setGeneration(desired, nextGeneration);
}
protected abstract boolean shouldIncrementGeneration(StatefulSet current, StatefulSet desired);
private static int getSsGeneration(StatefulSet resource) {
if (resource == null) {
return NO_GENERATION;
}
return getGeneration(templateMetadata(resource));
}
private static int getPodGeneration(Pod resource) {
if (resource == null) {
return NO_GENERATION;
}
return getGeneration(resource.getMetadata());
}
@Override
protected Future<ReconcileResult<StatefulSet>> internalCreate(String namespace, String name, StatefulSet desired) {
// Create the SS...
Future<ReconcileResult<StatefulSet>> result = Future.future();
setGeneration(desired, INIT_GENERATION);
Future<ReconcileResult<StatefulSet>> crt = super.internalCreate(namespace, name, desired);
// ... then wait for the SS to be ready...
crt.compose(res -> readiness(namespace, desired.getMetadata().getName(), 1_000, operationTimeoutMs).map(res))
// ... then wait for all the pods to be ready
.compose(res -> podReadiness(namespace, desired, 1_000, operationTimeoutMs).map(res))
.compose(res -> result.complete(res), result);
return result;
}
/**
* Returns a future that completes when all the pods [0..replicas-1] in the given statefulSet are ready.
*/
protected Future<?> podReadiness(String namespace, StatefulSet desired, long pollInterval, long operationTimeoutMs) {
final int replicas = desired.getSpec().getReplicas();
List<Future> waitPodResult = new ArrayList<>(replicas);
for (int i = 0; i < replicas; i++) {
String podName = getPodName(desired, i);
waitPodResult.add(podOperations.readiness(namespace, podName, pollInterval, operationTimeoutMs));
}
return CompositeFuture.join(waitPodResult);
}
/**
* Overridden to not cascade to dependent resources (e.g. pods).
*
* {@inheritDoc}
*/
@Override
protected Future<ReconcileResult<StatefulSet>> internalPatch(String namespace, String name, StatefulSet current, StatefulSet desired) {
if (shouldIncrementGeneration(current, desired)) {
incrementGeneration(current, desired);
} else {
setGeneration(desired, getSsGeneration(current));
}
// Don't scale via patch
desired.getSpec().setReplicas(current.getSpec().getReplicas());
if (log.isTraceEnabled()) {
log.trace("Patching {} {}/{} to match desired state {}", resourceKind, namespace, name, desired);
} else {
log.debug("Patching {} {}/{}", resourceKind, namespace, name);
}
StatefulSet ss = operation().inNamespace(namespace).withName(name).cascading(false).patch(desired);
log.debug("Patched {} {}/{}", resourceKind, namespace, name);
return Future.succeededFuture(ReconcileResult.patched(ss));
}
/**
* Reverts the changes done storage configuration of running cluster. Such changes are not allowed.
*
* @param current Current StatefulSet
* @param desired New StatefulSet
*
* @return Updated StatefulSetDiff after the storage patching
*/
protected StatefulSetDiff revertStorageChanges(StatefulSet current, StatefulSet desired) {
desired.getSpec().setVolumeClaimTemplates(current.getSpec().getVolumeClaimTemplates());
desired.getSpec().getTemplate().getSpec().setInitContainers(current.getSpec().getTemplate().getSpec().getInitContainers());
desired.getSpec().getTemplate().getSpec().setSecurityContext(current.getSpec().getTemplate().getSpec().getSecurityContext());
if (current.getSpec().getVolumeClaimTemplates().isEmpty()) {
// We are on ephemeral storage and changing to persistent
List<Volume> volumes = current.getSpec().getTemplate().getSpec().getVolumes();
for (int i = 0; i < volumes.size(); i++) {
Volume vol = volumes.get(i);
if (AbstractModel.VOLUME_NAME.equals(vol.getName()) && vol.getEmptyDir() != null) {
desired.getSpec().getTemplate().getSpec().getVolumes().add(0, volumes.get(i));
break;
}
}
} else {
// We are on persistent storage and changing to ephemeral
List<Volume> volumes = desired.getSpec().getTemplate().getSpec().getVolumes();
for (int i = 0; i < volumes.size(); i++) {
Volume vol = volumes.get(i);
if (AbstractModel.VOLUME_NAME.equals(vol.getName()) && vol.getEmptyDir() != null) {
volumes.remove(i);
break;
}
}
}
return new StatefulSetDiff(current, desired);
}
protected Future<String> getUid(String namespace, String podName) {
Future<String> result = Future.future();
vertx.createSharedWorkerExecutor("kubernetes-ops-tool").executeBlocking(
future -> {
String uid = getPodUid(podOperations.get(namespace, podName));
future.complete(uid);
}, true, result.completer()
);
return result;
}
private static String getPodUid(Pod resource) {
if (resource == null || resource.getMetadata() == null) {
return NO_UID;
}
return resource.getMetadata().getUid();
}
}
|
3e1a90eae98d40522ec4210242745457c392c3a6 | 1,985 | java | Java | launcher/src/test/java/org/apache/spark/launcher/BaseSuite.java | ppratik2908/kafka-spark | 2239d7a410e906ccd40aa8e84d637e9d06cd7b8a | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | 1 | 2020-06-18T09:21:33.000Z | 2020-06-18T09:21:33.000Z | launcher/src/test/java/org/apache/spark/launcher/BaseSuite.java | ppratik2908/kafka-spark | 2239d7a410e906ccd40aa8e84d637e9d06cd7b8a | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | 4 | 2018-02-09T01:18:25.000Z | 2019-03-24T15:23:20.000Z | launcher/src/test/java/org/apache/spark/launcher/BaseSuite.java | ppratik2908/kafka-spark | 2239d7a410e906ccd40aa8e84d637e9d06cd7b8a | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | 2 | 2018-06-27T18:41:27.000Z | 2019-02-18T03:04:37.000Z | 30.075758 | 92 | 0.69068 | 11,284 | /*
* 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.spark.launcher;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.slf4j.bridge.SLF4JBridgeHandler;
import static org.junit.Assert.*;
/**
* Handles configuring the JUL -> SLF4J bridge, and provides some utility methods for tests.
*/
class BaseSuite {
static {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
@After
public void postChecks() {
LauncherServer server = LauncherServer.getServer();
if (server != null) {
// Shut down the server to clean things up for the next test.
try {
server.close();
} catch (Exception e) {
// Ignore.
}
}
assertNull(server);
}
protected void waitFor(SparkAppHandle handle) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
try {
while (!handle.getState().isFinal()) {
assertTrue("Timed out waiting for handle to transition to final state.",
System.nanoTime() < deadline);
TimeUnit.MILLISECONDS.sleep(10);
}
} finally {
if (!handle.getState().isFinal()) {
handle.kill();
}
}
}
}
|
3e1a9199d488b3974e842bcb2b4425e25e297204 | 854 | java | Java | python/src/com/jetbrains/pyqt/QtUIFileType.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | python/src/com/jetbrains/pyqt/QtUIFileType.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | python/src/com/jetbrains/pyqt/QtUIFileType.java | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | 25.878788 | 155 | 0.738876 | 11,285 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.pyqt;
import com.intellij.openapi.fileTypes.FileType;
import com.jetbrains.python.PyBundle;
import icons.PythonIcons;
import javax.swing.*;
public class QtUIFileType extends QtFileType implements FileType {
public static final QtUIFileType INSTANCE = new QtUIFileType();
private QtUIFileType() {
super("Qt UI file", PyBundle.message("qt.ui.designer.form.filetype.display.name"), PyBundle.message("qt.ui.designer.form.filetype.description"), "ui");
}
@Override
public Icon getIcon() {
return PythonIcons.Pyqt.UiForm;
}
@Override
protected String getToolName() {
return "designer";
}
@Override
public boolean useNativeIcon() {
return false;
}
}
|
3e1a91fe96443f10582b93805826ad8ef979d773 | 6,092 | java | Java | com/planet_ink/coffee_mud/Abilities/Skills/Skill_CombatRepairs.java | PeteKeller/CoffeeMud | 430081e391df78ae231a02ce8a6e98d4ee8eac75 | [
"Apache-2.0"
] | 149 | 2015-01-11T12:55:39.000Z | 2022-03-03T16:14:48.000Z | com/planet_ink/coffee_mud/Abilities/Skills/Skill_CombatRepairs.java | PeteKeller/CoffeeMud | 430081e391df78ae231a02ce8a6e98d4ee8eac75 | [
"Apache-2.0"
] | 42 | 2015-02-08T03:44:01.000Z | 2022-02-10T08:52:43.000Z | com/planet_ink/coffee_mud/Abilities/Skills/Skill_CombatRepairs.java | PeteKeller/CoffeeMud | 430081e391df78ae231a02ce8a6e98d4ee8eac75 | [
"Apache-2.0"
] | 104 | 2015-01-21T20:20:55.000Z | 2022-03-24T05:01:20.000Z | 26.837004 | 200 | 0.673506 | 11,286 | package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2021 Bo Zimmerman
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.
*/
public class Skill_CombatRepairs extends StdSkill
{
@Override
public String ID()
{
return "Skill_CombatRepairs";
}
private final static String localizedName = CMLib.lang().L("Combat Repairs");
@Override
public String name()
{
return localizedName;
}
private final static String localizedStaticDisplay = CMLib.lang().L("(Temporary Patches)");
@Override
public String displayText()
{
return localizedStaticDisplay;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
protected int canAffectCode()
{
return CAN_ITEMS;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
private static final String[] triggerStrings = I(new String[] { "COMBATREPAIR","COMBATREPAIRS" });
@Override
public int classificationCode()
{
return Ability.ACODE_SKILL | Ability.DOMAIN_SEATRAVEL;
}
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT|USAGE_MANA;
}
protected int code = 0;
@Override
public int abilityCode()
{
return code;
}
@Override
public void setAbilityCode(final int newCode)
{
code = newCode;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if(affected instanceof SiegableItem)
{
final SiegableItem I=(SiegableItem)affected;
if(I.subjectToWearAndTear())
{
final PhysicalAgent currentVictim = I.getCombatant();
if(currentVictim == null)
{
if(I.usesRemaining()<=code)
unInvoke();
else
{
I.setUsesRemaining(I.usesRemaining()-5);
if(I instanceof Boardable)
{
final Area A=((Boardable)I).getArea();
if(A!=null)
{
for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if((R!=null)&&(R.numInhabitants()>0))
{
R.showHappens(CMMsg.MSG_OK_ACTION, L("The temporary combat repairs are slowly unraveling."));
}
}
}
}
}
}
}
}
return true;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if((CMLib.flags().isSitting(mob)||CMLib.flags().isSleeping(mob)))
{
mob.tell(L("You are on the floor!"));
return false;
}
if(!CMLib.flags().isAliveAwakeMobileUnbound(mob,false))
return false;
final Room R=mob.location();
if(R==null)
return false;
final SiegableItem ship;
if((R.getArea() instanceof Boardable)
&&(((Boardable)R.getArea()).getBoardableItem() instanceof SiegableItem))
//&&(((NavigableItem)(((BoardableItem)R.getArea()).getBoardableItem())).navBasis() == Rideable.Basis.WATER_BASED))
{
ship=(NavigableItem)((Boardable)R.getArea()).getBoardableItem();
}
else
{
mob.tell(L("You can't do combat repairs here!"));
return false;
}
if(ship.fetchEffect(ID())!=null)
{
mob.tell(L("Temporary combat repairs are already underway!"));
return false;
}
final Room shipR=CMLib.map().roomLocation(ship);
if((shipR==null)||(!ship.subjectToWearAndTear()))
{
mob.tell(L("You can't do combat repairs here!"));
return false;
}
if((!ship.isInCombat())||(ship.usesRemaining()<=0))
{
mob.tell(L("You must be in siege combat to do combat repairs!"));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,ship,this,CMMsg.MASK_MALICIOUS|CMMsg.MSG_NOISYMOVEMENT,auto?L("<T-NAME> is suddenly patched up!"):L("<S-NAME> make(s) quick siege combat repairs to <T-NAME>!"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
int dmg=ship.usesRemaining();
dmg += 20 + mob.charStats().getStat(CharStats.STAT_DEXTERITY)+(7 * super.getXLEVELLevel(mob));
if(dmg > 100)
dmg = 100;
final Ability A=beneficialAffect(mob, ship, asLevel, 0);
if(A!=null)
{
A.setAbilityCode(ship.usesRemaining());
A.makeLongLasting();
}
ship.setUsesRemaining(dmg);
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> attempt(s) to do quick siege combat repairs, but mess(es) it up."));
return success;
}
}
|
3e1a920806d8d73cc31a94915e54310b71b9eb29 | 8,174 | java | Java | core/src/main/java/org/infinispan/xsite/ClusteredCacheBackupReceiver.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | 1 | 2020-06-01T21:20:47.000Z | 2020-06-01T21:20:47.000Z | core/src/main/java/org/infinispan/xsite/ClusteredCacheBackupReceiver.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:34:13.000Z | 2022-03-02T14:34:13.000Z | core/src/main/java/org/infinispan/xsite/ClusteredCacheBackupReceiver.java | skymysky/infinispan | ace5cc23f345ed4e782fc863e83d5aa24e3a1ac9 | [
"Apache-2.0"
] | null | null | null | 39.873171 | 140 | 0.676168 | 11,287 | package org.infinispan.xsite;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.remoting.LocalInvocation;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.impl.MapResponseCollector;
import org.infinispan.remoting.transport.impl.SingleResponseCollector;
import org.infinispan.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.infinispan.xsite.statetransfer.XSiteState;
import org.infinispan.xsite.statetransfer.XSiteStatePushCommand;
import org.infinispan.xsite.statetransfer.XSiteStateTransferControlCommand;
/**
* {@link org.infinispan.xsite.BackupReceiver} implementation for clustered caches.
*
* @author Pedro Ruivo
* @since 7.1
*/
public class ClusteredCacheBackupReceiver extends BaseBackupReceiver {
private static final Log log = LogFactory.getLog(ClusteredCacheBackupReceiver.class);
private static final boolean trace = log.isDebugEnabled();
public ClusteredCacheBackupReceiver(Cache<Object, Object> cache) {
super(cache);
}
@Override
public void handleStateTransferControl(XSiteStateTransferControlCommand command) throws Exception {
XSiteStateTransferControlCommand invokeCommand = command;
if (!command.getCacheName().equals(cacheName)) {
//copy if the cache name is different
invokeCommand = command.copyForCache(cacheName);
}
invokeCommand.setSiteName(command.getOriginSite());
invokeRemotelyInLocalSite(invokeCommand);
}
@Override
public void handleStateTransferState(XSiteStatePushCommand cmd) throws Exception {
//split the state and forward it to the primary owners...
assertAllowInvocation();
final long endTime = timeService.expectedEndTime(cmd.getTimeout(), TimeUnit.MILLISECONDS);
final ClusteringDependentLogic clusteringDependentLogic = cache.getComponentRegistry()
.getComponent(ClusteringDependentLogic.class);
final Map<Address, List<XSiteState>> primaryOwnersChunks = new HashMap<>();
final Address localAddress = clusteringDependentLogic.getAddress();
if (trace) {
log.tracef("Received X-Site state transfer '%s'. Splitting by primary owner.", cmd);
}
for (XSiteState state : cmd.getChunk()) {
Address primaryOwner = clusteringDependentLogic.getCacheTopology().getDistribution(state.key()).primary();
List<XSiteState> primaryOwnerList = primaryOwnersChunks.computeIfAbsent(primaryOwner, k -> new LinkedList<>());
primaryOwnerList.add(state);
}
final List<XSiteState> localChunks = primaryOwnersChunks.remove(localAddress);
final List<StatePushTask> tasks = new ArrayList<>(primaryOwnersChunks.size());
for (Map.Entry<Address, List<XSiteState>> entry : primaryOwnersChunks.entrySet()) {
if (entry.getValue() == null || entry.getValue().isEmpty()) {
continue;
}
if (trace) {
log.tracef("Node '%s' will apply %s", entry.getKey(), entry.getValue());
}
StatePushTask task = new StatePushTask(entry.getValue(), entry.getKey(), cache);
tasks.add(task);
task.executeRemote();
}
//help gc. this is safe because the chunks was already sent
primaryOwnersChunks.clear();
if (trace) {
log.tracef("Local node '%s' will apply %s", localAddress, localChunks);
}
if (localChunks != null) {
StatePushTask task = new StatePushTask(localChunks, localAddress, cache);
tasks.add(task);
task.executeLocal();
}
if (trace) {
log.tracef("Waiting for the remote tasks...");
}
while (!tasks.isEmpty() && !timeService.isTimeExpired(endTime)) {
for (Iterator<StatePushTask> iterator = tasks.iterator(); iterator.hasNext(); ) {
if (awaitRemoteTask(iterator.next())) {
iterator.remove();
}
}
}
//the put operation can fail silently. check in the end and it is better to resend the chunk than to lose keys.
assertAllowInvocation();
if (!tasks.isEmpty()) {
throw new TimeoutException("Unable to apply state in the time limit.");
}
}
private boolean awaitRemoteTask(StatePushTask task) throws Exception {
try {
if (trace) {
log.tracef("Waiting reply from %s", task.address);
}
Response response = task.awaitResponse();
if (trace) {
log.tracef("Response received is %s", response);
}
if (response == CacheNotFoundResponse.INSTANCE) {
if (trace) {
log.tracef("Cache not found in node '%s'. Retrying locally!", task.address);
}
assertAllowInvocation();
task.executeLocal();
}
} catch (Exception e) {
assertAllowInvocation();
RpcManager rpcManager = cache.getRpcManager();
if (rpcManager.getMembers().contains(task.address) &&
!rpcManager.getAddress().equals(task.address)) {
if (trace) {
log.tracef(e, "An exception was sent by %s. Retrying!", task.address);
}
task.executeRemote(); //retry!
return false;
} else {
if (trace) {
log.tracef(e, "An exception was sent by %s. Retrying locally!", task.address);
}
//if the node left the cluster, we apply the missing state. This avoids the site provider to re-send the
//full chunk.
task.executeLocal();
return false;
}
}
return true;
}
private Map<Address, Response> invokeRemotelyInLocalSite(CacheRpcCommand command) throws Exception {
final RpcManager rpcManager = cache.getRpcManager();
Map<Address, Response> responseMap = rpcManager.blocking(
rpcManager.invokeCommandOnAll(command, MapResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()));
responseMap.put(rpcManager.getAddress(), LocalInvocation.newInstanceFromCache(cache, command).call());
return responseMap;
}
private static class StatePushTask {
private final List<XSiteState> chunk;
private final Address address;
private final AdvancedCache<?, ?> cache;
private volatile CompletableFuture<? extends Response> remoteFuture;
private StatePushTask(List<XSiteState> chunk, Address address, AdvancedCache<?, ?> cache) {
this.chunk = chunk;
this.address = address;
this.cache = cache;
}
public void executeRemote() {
final RpcManager rpcManager = cache.getRpcManager();
remoteFuture = rpcManager.invokeCommand(address, newStatePushCommand(cache, chunk),
SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()).toCompletableFuture();
}
public void executeLocal() {
try {
final Response response = LocalInvocation.newInstanceFromCache(cache, newStatePushCommand(cache, chunk)).call();
this.remoteFuture = CompletableFuture.completedFuture(response);
} catch (final Exception e) {
this.remoteFuture = CompletableFutures.completedExceptionFuture(new ExecutionException(e));
}
}
public Response awaitResponse() throws Exception {
return remoteFuture.get();
}
}
}
|
3e1a9219767289608ce002b75f104a94a91b9738 | 787 | java | Java | degiro-java-client/src/main/java/com/github/lesach/client/engine/strategy/DynamicStoplossStrategy.java | lesach/degiro-java-client | 83e07536aeca5a52c8a46b5493a53b3d67e78bd2 | [
"Apache-2.0"
] | 1 | 2021-02-06T11:46:11.000Z | 2021-02-06T11:46:11.000Z | degiro-java-client/src/main/java/com/github/lesach/client/engine/strategy/DynamicStoplossStrategy.java | lesach/degiro-java-client | 83e07536aeca5a52c8a46b5493a53b3d67e78bd2 | [
"Apache-2.0"
] | null | null | null | degiro-java-client/src/main/java/com/github/lesach/client/engine/strategy/DynamicStoplossStrategy.java | lesach/degiro-java-client | 83e07536aeca5a52c8a46b5493a53b3d67e78bd2 | [
"Apache-2.0"
] | null | null | null | 29.148148 | 75 | 0.738247 | 11,288 | /*
* Copyright 2018 ecatala.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.lesach.client.engine.strategy;
import com.github.lesach.client.engine.Strategy;
/**
*
* @author ecatala
*/
public class DynamicStoplossStrategy extends Strategy {
}
|
3e1a9369dae4cbb34ba7a66c9cb6d2161dea0958 | 1,123 | java | Java | domino/core/src/main/java/org/openntf/domino/nsfdata/structs/cd/CDFILEHEADER.java | mariusj/org.openntf.domino | cefed6e6ad926a64cb79f09ddae45fa4329106be | [
"Apache-2.0"
] | null | null | null | domino/core/src/main/java/org/openntf/domino/nsfdata/structs/cd/CDFILEHEADER.java | mariusj/org.openntf.domino | cefed6e6ad926a64cb79f09ddae45fa4329106be | [
"Apache-2.0"
] | null | null | null | domino/core/src/main/java/org/openntf/domino/nsfdata/structs/cd/CDFILEHEADER.java | mariusj/org.openntf.domino | cefed6e6ad926a64cb79f09ddae45fa4329106be | [
"Apache-2.0"
] | null | null | null | 26.738095 | 139 | 0.710597 | 11,289 | package org.openntf.domino.nsfdata.structs.cd;
import org.openntf.domino.nsfdata.structs.LSIG;
import org.openntf.domino.nsfdata.structs.SIG;
/**
* This structure is used to define a Cascading Style Sheet (CSS) that is part of a Domino database. CDFILESEGMENT structure(s) follow the
* CDFILEHEADER. (editods.h)
*
* @since Lotus Notes/Domino 6.0
*
*/
public class CDFILEHEADER extends CDRecord {
public final LSIG Header = inner(new LSIG());
public final Unsigned16 FileExtLen = new Unsigned16();
public final Unsigned32 FileDataSize = new Unsigned32();
public final Unsigned32 SegCount = new Unsigned32();
public final Unsigned32 Flags = new Unsigned32();
public final Unsigned32 Reserved = new Unsigned32();
static {
addVariableAsciiString("FileExt", "FileExtLen");
}
@Override
public SIG getHeader() {
return Header;
}
/**
* @return The file extension for the file
*/
public String getFileExt() {
return (String) getVariableElement("FileExt");
}
public void setFileExt(final String fileExt) {
setVariableElement("FileExt", fileExt);
}
}
|
3e1a947d2ce44f6662013a724c663ecf940c4643 | 41,041 | java | Java | Nurcall java old/Innovacion/src/java/org/fcv/innovacion/WebService.java | wisrovi/Server-Hospital-Smart-Bracelet | 03b71f03da7450a14cb1c45e51c3ae9401058dc8 | [
"MIT"
] | null | null | null | Nurcall java old/Innovacion/src/java/org/fcv/innovacion/WebService.java | wisrovi/Server-Hospital-Smart-Bracelet | 03b71f03da7450a14cb1c45e51c3ae9401058dc8 | [
"MIT"
] | 4 | 2021-03-19T10:58:51.000Z | 2021-06-10T20:07:14.000Z | Nurcall java old/Innovacion/src/java/org/fcv/innovacion/WebService.java | wisrovi/Server-Hospital-Smart-Bracelet | 03b71f03da7450a14cb1c45e51c3ae9401058dc8 | [
"MIT"
] | null | null | null | 40.11828 | 298 | 0.550182 | 11,290 | package org.fcv.innovacion;
//<editor-fold defaultstate="collapsed" desc="import">
import com.google.gson.Gson;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import org.fcv.innovacion.dto.AndroidDto;
import org.fcv.innovacion.dto.GabineteInsumosDtos;
import org.fcv.innovacion.dto.JsonDto;
import org.fcv.innovacion.dto.ShippConfiguracionAplicacionDto;
import org.fcv.innovacion.dto.ShippConfiguracionXModuloDto;
import org.fcv.innovacion.dto.ShippEstacionEnfermeriaDto;
import org.fcv.innovacion.dto.ShippLibroDigitalDto;
import org.fcv.innovacion.dto.ShippLlamadoEnfermeriaDto;
import org.fcv.innovacion.dto.ShippMensajeOnLineDto;
import org.fcv.innovacion.dto.ShippMenuHuespedDto;
import org.fcv.innovacion.dto.ShippModuloHuespedDto;
import org.fcv.innovacion.dto.ShippPeriodicoDto;
import org.fcv.innovacion.dto.ShippTarjetaLeida;
import org.fcv.innovacion.dto.ShippTarjetaSaludoDto;
import org.fcv.innovacion.dto.ShippTipoArchivoDigitalDto;
import org.fcv.innovacion.dto.ShippValidarMedicoDto;
import org.fcv.innovacion.dto.ShippValidarUsuarioDto;
import org.fcv.innovacion.model.Model;
import org.fcv.innovacion.runnable.EnviarCorreo;
import org.fcv.innovacion.util.Util;
//</editor-fold>
@javax.jws.WebService(serviceName = "WebService")
public class WebService {
//<editor-fold defaultstate="collapsed" desc="Variables Globales">
Model m;
String respuesta;
boolean depurar;
Map<String, Map<Integer, PrintWriter>> listaShipps;
private PreparedStatement updateIndEstacionCerradaStmt;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="WebService">
public WebService() {
this.listaShipps = new HashMap<>();
depurar = false;
// CABR PRUEBAS:
// [REGISTRO/VALIDACION - DISPOSITIVOS]: fcvShipp("10.2.0.15","52:54:00:12:34:56");
//fcvShippModuloHuesped();
//fcvNurCallShipp("172.16.58.28",4,2,"2");
}//</editor-fold>
/**
*
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcv">
@WebMethod(operationName = "fcv")
public String fcv() {
return "3";
}// </editor-fold>
/**
*
* @param dato
* @return
*///<editor-fold defaultstate="collapsed" desc="Control de Visitantes">
@WebMethod(operationName = "cvi")
public String cvi(@WebParam(name = "dato") String dato) {
m = new Model();
String closeDB = null;
Gson gson = new Gson();
JsonDto jsonDto = gson.fromJson(dato, JsonDto.class);
try {
if (jsonDto.getDatos() != null && jsonDto.getDatos().getProceso() != null) {
jsonDto.setEstado(false);
jsonDto.setMsg("");
switch (jsonDto.getDatos().getProceso()) {
case "censoPaciente":
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByCensoPaciente(jsonDto);
if (jsonDto.getDatos().getCensoPacientesDataProvider() != null
&& jsonDto.getDatos().getCensoPacientesDataProvider().getLista() != null
&& !jsonDto.getDatos().getCensoPacientesDataProvider().getLista().isEmpty()) {
jsonDto.setEstado(true);
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "buscarDocumento":
if (true
&& jsonDto.getDatos().getIp() != null
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByBuscarCedula(jsonDto);
if (jsonDto.getDatos().getCedulaDto().getIdCedula() != null
&& jsonDto.getDatos().getCedulaDto().getIdCedula() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "validarDocumento":
if (true
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByValidarCedula(jsonDto);
if (jsonDto.getDatos().getCedulaDto().getIdCedula() != null
&& jsonDto.getDatos().getCedulaDto().getIdCedula() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "validarAgenda":
if (true
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByValidarAgenda(jsonDto);
if (jsonDto.getDatos().getCedulaDto().getIdCedula() != null
&& jsonDto.getDatos().getCedulaDto().getIdCedula() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "validarCita":
if (true
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByValidarCita(jsonDto);
if (jsonDto.getDatos().getCitaDto() != null
&& jsonDto.getDatos().getCitaDto().getIdTerceroVisitado() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "registrarDocumento":
if (true
&& jsonDto.getDatos() != null
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
if (jsonDto.getDatos().getCedulaDto().getFechaNacimiento() == null) {
jsonDto.getDatos().getCedulaDto().setPrimerNombre("");
jsonDto.getDatos().getCedulaDto().setSegundoNombre("");
jsonDto.getDatos().getCedulaDto().setPrimerApellido("");
jsonDto.getDatos().getCedulaDto().setSegundoApellido("");
jsonDto.getDatos().getCedulaDto().setFechaNacimiento(new Date());
jsonDto.getDatos().getCedulaDto().setGrupoSanguineo("");
jsonDto.getDatos().getCedulaDto().setSexo("");
}
m.cviByRegistrarCedula(jsonDto);
if (jsonDto.getDatos().getCedulaDto().getIdCedula() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "registrarImagenCedula":
if (true
&& jsonDto.getDatos() != null
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getImagenDto() != null
&& jsonDto.getDatos().getImagenDto().getImagenByte() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByRegistrarImagenCedula(jsonDto);
if (jsonDto.getDatos().getImagenDto().getIdImagenCedula() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "registrarIngreso":
if (true
&& jsonDto.getDatos() != null
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getRegistroDto() != null
&& jsonDto.getDatos().getRegistroDto().getIdCviHuella() > 0) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByRegistrarIngreso(jsonDto);
if (jsonDto.getDatos().getRegistroDto().getIdRegistro() > 0) {
jsonDto.setEstado(true);
}
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
case "registrarSalida":
if (true
&& jsonDto.getDatos() != null
&& jsonDto.getDatos().getSede() != null
&& jsonDto.getDatos().getCedulaDto() != null
&& jsonDto.getDatos().getCedulaDto().getDocumento() != null) {
closeDB = "ANT," + Util.getConfig("CVI");
m.cviByRegistrarSalida(jsonDto);
} else {
jsonDto.setMsg("Faltan Datos.");
}
break;
default:
jsonDto.setMsg("Proceso Desconocido.");
}
} else {
jsonDto.setMsg("Variable Proceso Inexistente.");
}
} catch (Exception ex) {
if (closeDB != null) {
m.closeDataBaseByException(closeDB);
}
jsonDto.setEstado(false);
jsonDto.setMsg(jsonDto.getMsg() + "-Excepción: " + ex.getLocalizedMessage());
Util.Exception(ex);
}
return gson.toJson(jsonDto);
}//</editor-fold>
//INICIO COMENTARIO.
//<editor-fold defaultstate="collapsed" desc="COMENTAR">
/**
*
* @param datos
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvRegistrarCodigoBarras">
/*@WebMethod(operationName = "fcvRegistrarCodigoBarras")
public String fcvRegistrarCodigoBarras(
@WebParam(name = "datos") String datos) {
respuesta = null;
try {
m = new Model();
respuesta = m.procesarHoneywell(null, datos);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}*/// </editor-fold>
/**
*
* @param datos
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvRegistrarUbicacion">
/*@WebMethod(operationName = "fcvRegistrarUbicacion")
public String fcvRegistrarUbicacion(
@WebParam(name = "datos") String datos) {
respuesta = null;
try {
m = new Model();
respuesta = m.procesarHoneywell(null, datos);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}*/ // </editor-fold>
/**
* NURCALL
*
* @param ipDispositivo
* @param idDispositivo
* @param idEsclavo
* @param tipoLlamado
* @param estado
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvNurCallShipp">
@WebMethod(operationName = "fcvNurCallShipp")
public String fcvNurCallShipp(
@WebParam(name = "ipDispositivo") String ipDispositivo,
@WebParam(name = "idDispositivo") Integer idDispositivo,
@WebParam(name = "idEsclavo") Integer idEsclavo,
@WebParam(name = "tipoLlamado") String tipoLlamado,
@WebParam(name = "estado") boolean estado) {
if (depurar) {
System.out.println("fcvNurCallShipp IPNURCALL:[" + ipDispositivo + "] IDNURCALL:[" + idDispositivo + "] IDESCLAVO:[" + idEsclavo + "] TIPOLLAMADO:[" + tipoLlamado + "] ESTADO[" + estado + "]");
}
respuesta = null;
try {
m = new Model();
respuesta = m.nurCallShippSocket(ipDispositivo, idDispositivo, idEsclavo, tipoLlamado);
if (respuesta != null && !respuesta.equals("")) {
String[] respuestaSplit = respuesta.split(",");
respuesta = respuestaSplit[0];
boolean bShippEncontrado = false;
for (Map.Entry<String, Map<Integer, PrintWriter>> shipp : listaShipps.entrySet()) {
if (shipp.getKey().equals(respuesta)) {
bShippEncontrado = true;
Map.Entry<Integer, PrintWriter> next = shipp.getValue().entrySet().iterator().next();
next.getValue().println("MSJ 2," + estado);
break;
}
}
if (!bShippEncontrado) {
Map<String, String> parametros = new HashMap<>();
parametros.put("$idDispositivo", "" + respuestaSplit[1]);
parametros.put("$ipDispositivo", respuestaSplit[0]);
parametros.put("$descripcionDispositivo", respuestaSplit[2]);
EnviarCorreo enviarCorreo = new EnviarCorreo("SHIPPSINSOCKET", parametros, m);
Thread threadCorreo = new Thread(enviarCorreo);
threadCorreo.start();
respuesta = "false";
// ENVIAR CORREO.
} else {
respuesta = "true";
}
}
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* SHIPP
*
* @param ip
* @param mac
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShipp">
@WebMethod(operationName = "fcvShipp")
public String fcvShipp(@WebParam(name = "ip") String ip,
@WebParam(name = "mac") String mac) {
if (depurar) {
System.out.println("fcvShipp IP:[" + ip + "] MAC:[" + mac + "]");
}
respuesta = null;
try {
m = new Model();
respuesta = m.procesarShipp(ip, mac);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
respuesta="<?xml version='1.0' encoding='windows-1252' standalone='yes'?>"
+ " <ShippDto>"
+ " <ip>0</ip>"
+ " <id>0</id>"
+ " <idDispositivoTipo>0</idDispositivoTipo>"
+ " <indLlamadoActivo>false</indLlamadoActivo>"
+ " <indVoz>false</indVoz>"
+ " <idAtencion>0</idAtencion>"
+ " <idCama>0</idCama>"
+ " <codigoCama>null</codigoCama>"
+ " <nombreHuesped>null</nombreHuesped>"
+ " <apellidoHuesped>null</apellidoHuesped>"
+ " <idError></idError>"
+ " <mensajeError>Mantenimiento.</mensajeError>"
+ " </ShippDto>";
return respuesta;
}// </editor-fold>
/**
* SHIPP
*
* @param habi
* @param ip
* @param mac
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippActivarLlamado">
@WebMethod(operationName = "fcvShippActivarLlamado")
public String fcvShippActivarLlamado(@WebParam(name = "habi") Boolean habi, @WebParam(name = "ip") String ip,
@WebParam(name = "mac") String mac) {
if (depurar) {
System.out.println("fcvShippActivarLlamado HAB: [" + habi + "] IP:[" + ip + "] MAC:[" + mac + "]");
}
respuesta = null;
try {
m = new Model();
respuesta = m.procesarShippActivarLlamado(habi, ip, mac);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* SHIPP
*
* @param habi
* @param ip
* @param mac
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippVoz">
@WebMethod(operationName = "fcvShippVoz")
public String fcvShippVoz(@WebParam(name = "habi") Boolean habi, @WebParam(name = "ip") String ip,
@WebParam(name = "mac") String mac) {
if (depurar) {
System.out.println("fcvShippVoz HAB: [" + habi + "] IP:[" + ip + "] MAC:[" + mac + "]");
}
respuesta = null;
try {
m = new Model();
respuesta = m.procesarShippVoz(habi, ip, mac);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* LLAMADO ENFERMERIA.
*
* @param idDispositivo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippLlamadoEnfermeria">
@WebMethod(operationName = "fcvShippLlamadoEnfermeria")
public String fcvShippLlamadoEnfermeria(@WebParam(name = "idDispositivo") Integer idDispositivo) {
if (depurar) {
System.out.println("fcvShippLlamadoEnfermeria IDDISPOSITIVO:[" + idDispositivo + "]");
System.out.println(idDispositivo);
}
respuesta = null;
try {
m = new Model();
respuesta = m.procesarShipp(idDispositivo, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ACTUALIZAR CIERRE DISPOSITIVO SHIPP.
*
* @param idDispositivo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippActualizarCierre">
@WebMethod(operationName = "fcvShippActualizarCierre")
public String fcvShippActualizarCierre(@WebParam(name = "idDispositivo") Integer idDispositivo) {
if (depurar) {
System.out.println("fcvShippActualizarCierre IDDISPOSITIVO:[" + idDispositivo + "]");
System.out.println(idDispositivo);
}
respuesta = null;
try {
m = new Model();
m.procesarShipp(idDispositivo, null);
//Actualizar Campo IndEstacionAbierto en 0 en la tabla ShippDispositivos indicando
// que la estacion se cerro.updateIndEstacionCerradaStmt.setInt(1, idDispositivo);
// Driver d = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
// String connectionUrl;
// connectionUrl = "jdbc:sqlserver://" + Util.getConfig(codigo + "IP") + ";applicationName=" + Util.getConfig(codigo + "APPLICATIONNAME") + ";databaseName=" + Util.getConfig(codigo + "DB") + ";user=" + Util.getConfig(codigo + "USER") + ";password=" + Util.getConfig(codigo + "PASSWORD");
// dbConnection = d.connect(connectionUrl, new Properties());
// updateIndEstacionCerradaStmt = dbNurcallConnection.prepareStatement(UPDATE_INDESTACION_CERRADA_ID);
// updateIndEstacionCerradaStmt.execute();
// updateIndEstacionCerradaStmt.close();
} catch (Exception ex) {
//respuesta = Model.generarXml();
//Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* LLAMADO ENFERMERIA SIN ATENDER.
*
* @param idDispositivo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippLlamadoEnfermeriaSinAtender">
@WebMethod(operationName = "fcvShippLlamadoEnfermeriaSinAtender")
public String fcvShippLlamadoEnfermeriaSinAtender(@WebParam(name = "idDispositivo") Integer idDispositivo) {
if (depurar) {
System.out.println("fcvShippLlamadoEnfermeriaSinAtender IDDISPOSITIVO:[" + idDispositivo + "]");
}
respuesta = null;
try {
m = new Model();
ShippEstacionEnfermeriaDto shippEstacionEnfermeriaDto = new ShippEstacionEnfermeriaDto();
shippEstacionEnfermeriaDto.setIdDispositivo(idDispositivo);
shippEstacionEnfermeriaDto.setFechaAtencion(true);
respuesta = m.procesarShipp(shippEstacionEnfermeriaDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ESTACION ENFERMERIA.
*
* @param idDispositivo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippEstacionEnfermeria">
@WebMethod(operationName = "fcvShippEstacionEnfermeria")
public String fcvShippEstacionEnfermeria(
@WebParam(name = "idDispositivo") Integer idDispositivo) {
if (depurar) {
System.out.println("fcvShippEstacionEnfermeria IDDISPOSITIVO:[" + idDispositivo + "]");
}
respuesta = null;
try {
m = new Model();
ShippEstacionEnfermeriaDto shippEstacionEnfermeriaDto = new ShippEstacionEnfermeriaDto();
shippEstacionEnfermeriaDto.setIdDispositivo(idDispositivo);
shippEstacionEnfermeriaDto.setFechaAtencion(false);
respuesta = m.procesarShipp(shippEstacionEnfermeriaDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ESTACION ENFERMERIA.
*
* @param idTipoUsuario
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippEstacionEnfermeria">
@WebMethod(operationName = "fcvShippMenuHuesped")
public String fcvShippMenuHuesped(
@WebParam(name = "idTipoUsuario") Integer idTipoUsuario) {
if (depurar) {
System.out.println("fcvShippMenuHuesped IDTIPOUSUARIO:[" + idTipoUsuario + "]");
}
respuesta = null;
try {
m = new Model();
ShippMenuHuespedDto shippMenuHuespedDto = new ShippMenuHuespedDto();
shippMenuHuespedDto.setIdTipoUsuario(idTipoUsuario);
respuesta = m.procesarShipp(shippMenuHuespedDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* LIBROS DIGITALES.
*
* @param idMenuEntretenimiento
* @param idTipoArchivo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippLibrosDigitales">
@WebMethod(operationName = "fcvShippLibroDigital")
public String fcvShippLibroDigital(
@WebParam(name = "idMenuEntretenimiento") Integer idMenuEntretenimiento,
@WebParam(name = "idTipoArchivo") Integer idTipoArchivo) {
if (depurar) {
System.out.println("fcvShippLibroDigital IDMENUENTRETENIMIENTO:[" + idMenuEntretenimiento + "] - IDTIPOARCHIVO [" + idTipoArchivo + "]");
}
respuesta = null;
try {
m = new Model();
ShippLibroDigitalDto shippLibroDigitalDto = new ShippLibroDigitalDto();
shippLibroDigitalDto.setIdMenuEntretenimiento(idMenuEntretenimiento);
shippLibroDigitalDto.setIdTipoArchivo(idTipoArchivo);
respuesta = m.procesarShipp(shippLibroDigitalDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* LIBROS DIGITALES.
*
* @param idMenuEntretenimiento
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippPeriodico">
@WebMethod(operationName = "fcvShippPeriodico")
public String fcvShippPeriodico(
@WebParam(name = "idMenuEntretenimiento") Integer idMenuEntretenimiento) {
if (depurar) {
System.out.println("fcvShippLibroDigital IDMENUENTRETENIMIENTO:[" + idMenuEntretenimiento + "]");
}
respuesta = null;
try {
m = new Model();
ShippPeriodicoDto shippPeriodicoDto = new ShippPeriodicoDto();
shippPeriodicoDto.setIdMenuEntretenimiento(idMenuEntretenimiento);
respuesta = m.procesarShipp(shippPeriodicoDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* TARJETAS SALUDO.
*
* @param idAtencion
* @param idCama
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvTarjetaSaludo">
@WebMethod(operationName = "fcvTarjetaSaludo")
public String fcvTarjetaSaludo(
@WebParam(name = "idAtencion") Integer idAtencion,
@WebParam(name = "idCama") Integer idCama) {
if (depurar) {
System.out.println("fcvTarjetaSaludo IDATENCION:[" + idAtencion + "] - IDCAMA [" + idCama + "]");
}
respuesta = null;
try {
m = new Model();
ShippTarjetaSaludoDto shippTarjetaSaludoDto = new ShippTarjetaSaludoDto();
shippTarjetaSaludoDto.setIdAtencion(idAtencion);
shippTarjetaSaludoDto.setIdCama(idCama);
respuesta = m.procesarShipp(shippTarjetaSaludoDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* TARJETAS LEIDA.
*
* @param idTarjetaSaludo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvTarjetaLeida">
@WebMethod(operationName = "fcvTarjetaLeida")
public String fcvTarjetaLeida(
@WebParam(name = "idTarjetaSaludo") Integer idTarjetaSaludo) {
if (depurar) {
System.out.println("fcvTarjetaSaludo IDATARJETA:[" + idTarjetaSaludo + "]");
}
respuesta = null;
try {
m = new Model();
ShippTarjetaLeida shippTarjetaLeida = new ShippTarjetaLeida();
shippTarjetaLeida.setIdTarjetaSaludo(idTarjetaSaludo);
respuesta = m.procesarShipp(shippTarjetaLeida, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* TIPO ARCHIVO DIGITAL.
*
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippTipoArchivoDigital">
public String fcvShippTipoArchivoDigital() {
respuesta = null;
try {
m = new Model();
ShippTipoArchivoDigitalDto shippTipoArchivoDigitalDto = new ShippTipoArchivoDigitalDto();
respuesta = m.procesarShipp(shippTipoArchivoDigitalDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ATENDER LLAMADO ENFERMERIA.
*
* @param idDispositivo
* @param idLlamadoEnfermeria
* @return
* @
*//// <editor-fold defaultstate="collapsed" desc="fcvShippAtenderLlamadoEnfermeria">
@WebMethod(operationName = "fcvShippVerificarLlamadoEnfermeria")
public String fcvShippVerificarLlamadoEnfermeria(
@WebParam(name = "idDispositivo") Integer idDispositivo,
@WebParam(name = "idLlamadoEnfermeria") Integer idLlamadoEnfermeria) {
if (depurar) {
System.out.println("fcvShippVerificarLlamadoEnfermeria IDDISPOSITIVO:[" + idDispositivo + "] IDLLAMADO:[" + idLlamadoEnfermeria + "]");
}
respuesta = null;
try {
m = new Model();
ShippLlamadoEnfermeriaDto shippLlamadoEnfermeriaDto = new ShippLlamadoEnfermeriaDto();
shippLlamadoEnfermeriaDto.setIdDispositivo(idDispositivo);
shippLlamadoEnfermeriaDto.setId(idLlamadoEnfermeria);
shippLlamadoEnfermeriaDto.setVerificarLlamadoActivo(Boolean.TRUE);
respuesta = m.procesarShipp(shippLlamadoEnfermeriaDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ATENDER LLAMADO ENFERMERIA.
*
* @param idDispositivo
* @param idLlamadoEnfermeria
* @return
* @
*//// <editor-fold defaultstate="collapsed" desc="fcvShippAtenderLlamadoEnfermeria">
@WebMethod(operationName = "fcvShippAtenderLlamadoEnfermeria")
public String fcvShippAtenderLlamadoEnfermeria(
@WebParam(name = "idDispositivo") Integer idDispositivo,
@WebParam(name = "idLlamadoEnfermeria") Integer idLlamadoEnfermeria) {
if (depurar) {
System.out.println("fcvShippAtenderLlamadoEnfermeria IDDISPOSITIVO:[" + idDispositivo + "] IDLLAMADO:[" + idLlamadoEnfermeria + "]");
}
respuesta = null;
try {
m = new Model();
ShippLlamadoEnfermeriaDto shippLlamadoEnfermeriaDto = new ShippLlamadoEnfermeriaDto();
shippLlamadoEnfermeriaDto.setIdDispositivo(idDispositivo);
shippLlamadoEnfermeriaDto.setId(idLlamadoEnfermeria);
respuesta = m.procesarShipp(shippLlamadoEnfermeriaDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* SHIPP CONFIGURACION
*
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippConfiguracionAplicacion">
@WebMethod(operationName = "fcvShippConfiguracionAplicacion")
public String fcvShippConfiguracionAplicacion() {
if (depurar) {
System.out.println("fcvShippConfiguracionAplicacion []");
}
respuesta = null;
try {
m = new Model();
ShippConfiguracionAplicacionDto shippConfiguracionAplicacionDto = new ShippConfiguracionAplicacionDto();
respuesta = m.procesarShipp(shippConfiguracionAplicacionDto, null);
Util.fcvShippSocket(this.listaShipps);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* SHIPP MENSAJE INMEDIATO
*
* @param dato
* @param proceso
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippMensajeInmediato">
@WebMethod(operationName = "fcvShippMensajeInmediato")
public String fcvShippMensajeInmediato(
@WebParam(name = "proceso") String proceso,
@WebParam(name = "dato") String dato) {
if (depurar) {
System.out.println("fcvShippMensajeInmediato []");
}
respuesta = null;
try {
//int contador = 0;
for (Map.Entry<String, Map<Integer, PrintWriter>> shipp : listaShipps.entrySet()) {
//if (shipp.getKey().equals(respuesta)) {
Map.Entry<Integer, PrintWriter> next = shipp.getValue().entrySet().iterator().next();
next.getValue().println("MSJ 2," + "inmediato");
//break;
//}
//contador = contador + 1;
//System.out.println("SHIPP en LInea: " + contador);
}
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* MENSAJE ONLINE
*
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvMensajeOnLine">
@WebMethod(operationName = "fcvMensajeOnLine")
public String fcvMensajeOnLine() {
if (depurar) {
System.out.println("fcvMensajeOnLine []");
}
respuesta = null;
try {
m = new Model();
ShippMensajeOnLineDto shippMensajeOnLineDto = new ShippMensajeOnLineDto();
respuesta = m.procesarShipp(shippMensajeOnLineDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* ATENDER MODULOS HUESPED.
*
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippModuloHuesped">
@WebMethod(operationName = "fcvShippModuloHuesped")
public String fcvShippModuloHuesped() {
if (depurar) {
System.out.println("fcvShippModuloHuesped []");
}
respuesta = null;
try {
m = new Model();
ShippModuloHuespedDto shippModuloHuespedDto = new ShippModuloHuespedDto();
respuesta = m.procesarShipp(shippModuloHuespedDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* CONFIGURACION POR MODULO.
*
* @param idModulo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippConfiguracionXModulo">
@WebMethod(operationName = "fcvShippConfiguracionXModulo")
public String fcvShippConfiguracionXModulo(
@WebParam(name = "idModulo") Integer idModulo) {
if (depurar) {
System.out.println("fcvShippConfiguracionXModulo []");
}
respuesta = null;
try {
m = new Model();
ShippConfiguracionXModuloDto shippConfiguracionXModuloDto = new ShippConfiguracionXModuloDto();
shippConfiguracionXModuloDto.setIdModulo(idModulo);
respuesta = m.procesarShipp(shippConfiguracionXModuloDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* VALIDAR USUARIO.
*
* @param usuario
* @param password
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippValidarMedico">
@WebMethod(operationName = "fcvShippValidarMedico")
public String fcvShippValidarMedico(
@WebParam(name = "usuario") String usuario,
@WebParam(name = "password") String password) {
if (depurar) {
System.out.println("fcvShippValidarMedico USUARIO:[" + usuario + "] PASSWORD:[" + password + "]");
}
respuesta = null;
try {
String usuarioLdap = Util.Desencriptar(usuario);
String passwordLdap = Util.Desencriptar(password);
String cedulaLdap = Util.getAccesoLdap(usuarioLdap, passwordLdap);
ShippValidarMedicoDto shippValidarMedicoDto = new ShippValidarMedicoDto();
m = new Model();
if (cedulaLdap != null) {
shippValidarMedicoDto.setCedula(cedulaLdap);
respuesta = m.procesarShipp(shippValidarMedicoDto, null);
} else {
respuesta = m.procesarShipp(shippValidarMedicoDto, null);
}
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* VALIDAR USUARIO.
*
* @param usuario
* @param password
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvShippValidarUsuario">
@WebMethod(operationName = "fcvShippValidarUsuario")
public String fcvShippValidarUsuario(
@WebParam(name = "usuario") String usuario,
@WebParam(name = "password") String password) {
if (depurar) {
System.out.println("fcvShippValidarUsuario USUARIO:[" + usuario + "] PASSWORD:[" + password + "]");
}
respuesta = null;
try {
m = new Model();
ShippValidarUsuarioDto shippValidarUsuarioDto = new ShippValidarUsuarioDto();
shippValidarUsuarioDto.setUsuario(Util.Desencriptar(usuario));
shippValidarUsuarioDto.setClave(Util.Desencriptar(password));
respuesta = m.procesarShipp(shippValidarUsuarioDto, null);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* GABINETE.
*
* @param codigo
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvGabinete">
@WebMethod(operationName = "fcvGabinete")
public String fcvGabinete(@WebParam(name = "codigo") String codigo) {
respuesta = null;
try {
m = new Model();
respuesta = m.procesarGabinete(codigo);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* GABINETE INSUMOS.
*
* @param id
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvGabineteInsumos">
@WebMethod(operationName = "fcvGabineteInsumos")
public String fcvGabineteInsumos(@WebParam(name = "id") Integer id) {
respuesta = null;
try {
m = new Model();
respuesta = m.procesarGabinete(id);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
* GABINETE INSUMOS.
*
* @param xml
* @return
*/// <editor-fold defaultstate="collapsed" desc="fcvGabineteArqueo">
@WebMethod(operationName = "fcvGabineteArqueo")
public String fcvGabineteArqueo(@WebParam(name = "xml") String xml) {
respuesta = null;
try {
m = new Model();
GabineteInsumosDtos gabineteInsumosDtos = Util.getGabineteInsumosDtosXml(xml);
respuesta = m.procesarGabinete(gabineteInsumosDtos);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/**
*
* @param usuario
* @param correoElectronico
* @param regId
* @return
*/// <editor-fold defaultstate="collapsed" desc="androidRegistroUsuario">
@WebMethod(operationName = "androidRegistroUsuario")
public String androidRegistroUsuario(
@WebParam(name = "usuario") String usuario,
@WebParam(name = "correoElectronico") String correoElectronico,
@WebParam(name = "regId") String regId) {
respuesta = null;
try {
m = new Model();
AndroidDto androidDto = new AndroidDto();
androidDto.setProceso("REGISTRAR_USUARIO_DB");
androidDto.setUsuario(usuario);
androidDto.setCorreoElectronico(correoElectronico);
androidDto.setRegId(regId);
respuesta = m.procesarAndroid(androidDto);
} catch (Exception ex) {
respuesta = Model.generarXml();
Util.Exception(ex);
}
return respuesta;
}// </editor-fold>
/* FIN COMENTADO*/
//</editor-fold>
// FIN COMENSARIO
}
|
3e1a950e3b4135408771c5aa0b2085033009602e | 9,660 | java | Java | src/main/generated-java/com/dnb/services/report/ProductSpecification.java | elasticio/dun-and-bradstreet-component | 72d06fbbc55074ea19776e059ef3c936e891357e | [
"Apache-2.0"
] | null | null | null | src/main/generated-java/com/dnb/services/report/ProductSpecification.java | elasticio/dun-and-bradstreet-component | 72d06fbbc55074ea19776e059ef3c936e891357e | [
"Apache-2.0"
] | null | null | null | src/main/generated-java/com/dnb/services/report/ProductSpecification.java | elasticio/dun-and-bradstreet-component | 72d06fbbc55074ea19776e059ef3c936e891357e | [
"Apache-2.0"
] | null | null | null | 29.361702 | 147 | 0.626087 | 11,291 |
package com.dnb.services.report;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ProductSpecification complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ProductSpecification">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DNBProductID" type="{http://services.dnb.com/ReportProductServiceV2.0}ProductCode"/>
* <element name="DNBProductModuleID" maxOccurs="unbounded" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="64"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MergeModuleAttachmentsIndicator" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ProductFormatPreferenceCode" type="{http://services.dnb.com/ReportProductServiceV2.0}DNBCodeValueType" minOccurs="0"/>
* <element name="CharacterSetPreferenceCode" type="{http://services.dnb.com/ReportProductServiceV2.0}DNBCodeValueType" minOccurs="0"/>
* <element name="LanguagePreferenceCode" type="{http://services.dnb.com/ReportProductServiceV2.0}DNBCodeValueType" minOccurs="0"/>
* <element name="OrderReasonCode" type="{http://services.dnb.com/ReportProductServiceV2.0}DNBCodeValueType" minOccurs="0"/>
* <element name="TradeUpIndicator" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ReturnOnlyInDateDataIndicator" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="IncludeAttachmentIndicator" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProductSpecification", namespace = "http://services.dnb.com/ReportProductServiceV2.0", propOrder = {
"dnbProductID",
"dnbProductModuleID",
"mergeModuleAttachmentsIndicator",
"productFormatPreferenceCode",
"characterSetPreferenceCode",
"languagePreferenceCode",
"orderReasonCode",
"tradeUpIndicator",
"returnOnlyInDateDataIndicator",
"includeAttachmentIndicator"
})
public class ProductSpecification {
@XmlElement(name = "DNBProductID", required = true)
protected String dnbProductID;
@XmlElement(name = "DNBProductModuleID")
protected List<String> dnbProductModuleID;
@XmlElement(name = "MergeModuleAttachmentsIndicator")
protected Boolean mergeModuleAttachmentsIndicator;
@XmlElement(name = "ProductFormatPreferenceCode")
protected BigInteger productFormatPreferenceCode;
@XmlElement(name = "CharacterSetPreferenceCode")
protected BigInteger characterSetPreferenceCode;
@XmlElement(name = "LanguagePreferenceCode")
protected BigInteger languagePreferenceCode;
@XmlElement(name = "OrderReasonCode")
protected BigInteger orderReasonCode;
@XmlElement(name = "TradeUpIndicator")
protected Boolean tradeUpIndicator;
@XmlElement(name = "ReturnOnlyInDateDataIndicator")
protected Boolean returnOnlyInDateDataIndicator;
@XmlElement(name = "IncludeAttachmentIndicator")
protected Boolean includeAttachmentIndicator;
/**
* Gets the value of the dnbProductID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDNBProductID() {
return dnbProductID;
}
/**
* Sets the value of the dnbProductID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDNBProductID(String value) {
this.dnbProductID = value;
}
/**
* Gets the value of the dnbProductModuleID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dnbProductModuleID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDNBProductModuleID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDNBProductModuleID() {
if (dnbProductModuleID == null) {
dnbProductModuleID = new ArrayList<String>();
}
return this.dnbProductModuleID;
}
/**
* Gets the value of the mergeModuleAttachmentsIndicator property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMergeModuleAttachmentsIndicator() {
return mergeModuleAttachmentsIndicator;
}
/**
* Sets the value of the mergeModuleAttachmentsIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMergeModuleAttachmentsIndicator(Boolean value) {
this.mergeModuleAttachmentsIndicator = value;
}
/**
* Gets the value of the productFormatPreferenceCode property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getProductFormatPreferenceCode() {
return productFormatPreferenceCode;
}
/**
* Sets the value of the productFormatPreferenceCode property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setProductFormatPreferenceCode(BigInteger value) {
this.productFormatPreferenceCode = value;
}
/**
* Gets the value of the characterSetPreferenceCode property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getCharacterSetPreferenceCode() {
return characterSetPreferenceCode;
}
/**
* Sets the value of the characterSetPreferenceCode property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setCharacterSetPreferenceCode(BigInteger value) {
this.characterSetPreferenceCode = value;
}
/**
* Gets the value of the languagePreferenceCode property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getLanguagePreferenceCode() {
return languagePreferenceCode;
}
/**
* Sets the value of the languagePreferenceCode property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setLanguagePreferenceCode(BigInteger value) {
this.languagePreferenceCode = value;
}
/**
* Gets the value of the orderReasonCode property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getOrderReasonCode() {
return orderReasonCode;
}
/**
* Sets the value of the orderReasonCode property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setOrderReasonCode(BigInteger value) {
this.orderReasonCode = value;
}
/**
* Gets the value of the tradeUpIndicator property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTradeUpIndicator() {
return tradeUpIndicator;
}
/**
* Sets the value of the tradeUpIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTradeUpIndicator(Boolean value) {
this.tradeUpIndicator = value;
}
/**
* Gets the value of the returnOnlyInDateDataIndicator property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isReturnOnlyInDateDataIndicator() {
return returnOnlyInDateDataIndicator;
}
/**
* Sets the value of the returnOnlyInDateDataIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setReturnOnlyInDateDataIndicator(Boolean value) {
this.returnOnlyInDateDataIndicator = value;
}
/**
* Gets the value of the includeAttachmentIndicator property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isIncludeAttachmentIndicator() {
return includeAttachmentIndicator;
}
/**
* Sets the value of the includeAttachmentIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIncludeAttachmentIndicator(Boolean value) {
this.includeAttachmentIndicator = value;
}
}
|
3e1a97768628eb2a657fa569b18aff628e10b542 | 2,005 | java | Java | runtimes/src/main/java/org/apache/ode/bpel/rtrep/v1/OConstants.java | matthieu/apache-ode | 5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6 | [
"Apache-2.0"
] | 1 | 2016-05-08T23:34:14.000Z | 2016-05-08T23:34:14.000Z | runtimes/src/main/java/org/apache/ode/bpel/rtrep/v1/OConstants.java | matthieu/apache-ode | 5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6 | [
"Apache-2.0"
] | null | null | null | runtimes/src/main/java/org/apache/ode/bpel/rtrep/v1/OConstants.java | matthieu/apache-ode | 5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6 | [
"Apache-2.0"
] | 1 | 2019-05-02T22:11:31.000Z | 2019-05-02T22:11:31.000Z | 33.983051 | 87 | 0.75212 | 11,292 | /*
* 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.ode.bpel.rtrep.v1;
import javax.xml.namespace.QName;
/**
* Compiled BPEL constants. Mostly the qualified names of the standard
* faults.
*/
public class OConstants extends OBase {
private static final long serialVersionUID = 1L;
// standard fault names
public QName qnMissingRequest;
public QName qnMissingReply;
public QName qnUninitializedVariable;
public QName qnConflictingReceive;
public QName qnSelectionFailure;
public QName qnMismatchedAssignmentFailure;
public QName qnJoinFailure;
public QName qnForcedTermination;
public QName qnCorrelationViolation;
public QName qnXsltInvalidSource;
public QName qnSubLanguageExecutionFault;
public QName qnUninitializedPartnerRole;
public QName qnForEachCounterError;
public QName qnInvalidBranchCondition;
public QName qnInvalidExpressionValue;
// non-standard fault names
// for some reason unbeknownst to me, adding the fields below breaks compatibility!
// public QName qnRetiredProcess;
// public QName qnDuplicateInstance;
// public QName qnUnknownFault;
public OConstants(OProcess owner) {
super(owner);
}
}
|
3e1a97cb72d5da7fed13461b019afa0f66bbf716 | 546 | java | Java | jframe-plugin/jframe-pushy/src/main/java/jframe/pushy/Fields.java | MccreeFei/jframe | 3aadedc777b118e2c5ac47eb9e77d1ebab212c7f | [
"Apache-2.0"
] | 21 | 2015-09-01T11:51:15.000Z | 2022-03-27T07:58:39.000Z | jframe-plugin/jframe-pushy/src/main/java/jframe/pushy/Fields.java | MccreeFei/jframe | 3aadedc777b118e2c5ac47eb9e77d1ebab212c7f | [
"Apache-2.0"
] | 6 | 2015-07-25T16:22:42.000Z | 2021-07-02T18:38:54.000Z | jframe-plugin/jframe-pushy/src/main/java/jframe/pushy/Fields.java | MccreeFei/jframe | 3aadedc777b118e2c5ac47eb9e77d1ebab212c7f | [
"Apache-2.0"
] | 16 | 2015-06-18T02:29:52.000Z | 2021-11-03T12:56:19.000Z | 24.818182 | 68 | 0.725275 | 11,293 | /**
*
*/
package jframe.pushy;
/**
* @author dzh
* @date Aug 29, 2015 2:18:51 PM
* @since 1.0
*/
public interface Fields {
public static final String KEY_IOS_AUTH = "ios.auth";
public static final String KEY_IOS_PASSWORD = "ios.password";
public static final String KEY_HOST = "host";
public static final String KEY_HOST_PORT = "host.port";
public static final String KEY_FEEDBACK = "feedback";
public static final String KEY_FEEDBACK_PORT = "feedback.port";
public static final String KEY_PUSH_CONN_COUNT = "push.conn.count";
}
|
3e1a9aa772835fac81e944bac9c7f956c80ced55 | 1,248 | java | Java | Utils/java/AppUtil.java | Simplation/Daily-Collection | 9e95c5acf9dd9868f002061db4ed706a5ec3143a | [
"Apache-2.0"
] | 1 | 2020-06-06T01:23:13.000Z | 2020-06-06T01:23:13.000Z | Utils/java/AppUtil.java | Simplation/Daily-Collection | 9e95c5acf9dd9868f002061db4ed706a5ec3143a | [
"Apache-2.0"
] | null | null | null | Utils/java/AppUtil.java | Simplation/Daily-Collection | 9e95c5acf9dd9868f002061db4ed706a5ec3143a | [
"Apache-2.0"
] | null | null | null | 22.690909 | 68 | 0.731571 | 11,294 | package com.example.testutils.util
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
/**
* App 相关的工具类
*/
public class AppUtils {
private AppUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获取应用程序名称
*/
public static String getAppName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
|
3e1a9ad0268bed3c7e64dd117778df28316aa2d5 | 4,784 | java | Java | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassStrategy.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 104 | 2015-01-31T01:11:05.000Z | 2022-03-20T05:28:58.000Z | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassStrategy.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 56 | 2016-09-30T14:04:31.000Z | 2022-02-21T11:23:53.000Z | openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassStrategy.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 127 | 2015-01-11T14:18:46.000Z | 2022-03-23T13:46:58.000Z | 41.241379 | 78 | 0.720109 | 11,295 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.jdbc.meta;
import java.sql.SQLException;
import org.apache.openjpa.jdbc.kernel.JDBCFetchConfiguration;
import org.apache.openjpa.jdbc.kernel.JDBCStore;
import org.apache.openjpa.jdbc.sql.Joins;
import org.apache.openjpa.jdbc.sql.Result;
import org.apache.openjpa.jdbc.sql.Select;
import org.apache.openjpa.kernel.OpenJPAStateManager;
import org.apache.openjpa.kernel.PCState;
import org.apache.openjpa.lib.rop.ResultObjectProvider;
/**
* Mapping from a class to a relational schema.
*
* @author Abe White
* @since 0.4.0
*/
public interface ClassStrategy
extends Strategy {
/**
* Set the class mapping using this strategy. This will be called before
* use.
*/
void setClassMapping(ClassMapping owner);
/**
* Return true if the this class' primary key columns correspond to the
* base class' primary key columns used to construct oid values. Base
* classes always return true. Classes that join to the base class table,
* though, may not always join using the same columns the base class
* uses for oid values, or may not use all the columns. When performing a
* select, we will join down to the most-derived class that is identified
* by oid values. We cannot use non-primary key field values for joining
* during selects, because the field values to join on might be the ones
* we're trying to select! Similarly, we can only reconstruct oid values
* for selected objects using classes whose primary keys store oid values.
*
* @param hasAll if true, there must be a primary key column for every
* base class primary key column; if false the primary key
* must only match a subset of the base class primary key columns
*/
boolean isPrimaryKeyObjectId(boolean hasAll);
/**
* Join the mapping and its superclass.
*
* @param toThis if false, inner join to the superclass table; if
* true, outer join from the superclass table to this table
*/
Joins joinSuperclass(Joins joins, boolean toThis);
/**
* Return true if this strategy can perform the given select from
* the given <code>base</code> mapping.
* The given state manager may be null if selecting multiple instances.
*/
boolean supportsEagerSelect(Select sel, OpenJPAStateManager sm,
JDBCStore store, ClassMapping base, JDBCFetchConfiguration fetch);
/**
* Implement this method to customize obtaining a result containing all
* instances of this class. Return null for standard loading.
*/
ResultObjectProvider customLoad(JDBCStore store, boolean subclasses,
JDBCFetchConfiguration fetch, long startIdx, long endIdx)
throws SQLException;
/**
* Implement this method to load the state of a given object, without
* a previous {@link Result}. Return true if this method handles the
* load. If the object does not exist in the data store, simply take no
* action on it (but still return true). Return false to use default
* loading.
*
* @param state if non-null, then you must initialize the state
* and persistent object of the given state manager
* (after determining the actual class of the object
* from the database, if there are possible persistent
* subclasses); initialization looks like this: <code>
* sm.initialize (pcClass, state)</code>
*/
boolean customLoad(OpenJPAStateManager sm, JDBCStore store,
PCState state, JDBCFetchConfiguration fetch)
throws SQLException, ClassNotFoundException;
/**
* Implement this method to customize loading from a {@link Result}
* into an instance. Return true if this mapping handles the
* load; false if normal loading should proceed after calling this method.
*/
boolean customLoad(OpenJPAStateManager sm, JDBCStore store,
JDBCFetchConfiguration fetch, Result result)
throws SQLException;
}
|
3e1a9b4ddfa6807ce564cf51e0472f1fd46645bb | 2,165 | java | Java | sdk-codec/src/main/java/org/fisco/bcos/sdk/codec/wrapper/ABIDefinitionFactory.java | PC-Chiu/java-sdk | 5d4aa6cf099cebbc4788e333f778f692b48d93de | [
"Apache-2.0"
] | 24 | 2020-07-09T07:20:10.000Z | 2022-03-31T08:45:13.000Z | sdk-codec/src/main/java/org/fisco/bcos/sdk/codec/wrapper/ABIDefinitionFactory.java | PC-Chiu/java-sdk | 5d4aa6cf099cebbc4788e333f778f692b48d93de | [
"Apache-2.0"
] | 522 | 2020-07-09T11:44:12.000Z | 2022-03-31T16:42:07.000Z | sdk-codec/src/main/java/org/fisco/bcos/sdk/codec/wrapper/ABIDefinitionFactory.java | PC-Chiu/java-sdk | 5d4aa6cf099cebbc4788e333f778f692b48d93de | [
"Apache-2.0"
] | 50 | 2020-07-09T07:20:16.000Z | 2022-03-15T09:10:22.000Z | 36.694915 | 97 | 0.618014 | 11,296 | package org.fisco.bcos.sdk.codec.wrapper;
import org.fisco.bcos.sdk.crypto.CryptoSuite;
import org.fisco.bcos.sdk.utils.ObjectMapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ABIDefinitionFactory {
private static final Logger logger = LoggerFactory.getLogger(ABIDefinitionFactory.class);
private CryptoSuite cryptoSuite;
public ABIDefinitionFactory(CryptoSuite cryptoSuite) {
this.cryptoSuite = cryptoSuite;
}
/**
* load ABI and construct ContractABIDefinition.
*
* @param abi the abi need to be loaded
* @return the contract definition
*/
public ContractABIDefinition loadABI(String abi) {
try {
ABIDefinition[] abiDefinitions =
ObjectMapperFactory.getObjectMapper().readValue(abi, ABIDefinition[].class);
ContractABIDefinition contractABIDefinition = new ContractABIDefinition(cryptoSuite);
for (ABIDefinition abiDefinition : abiDefinitions) {
if (abiDefinition.getType().equals("constructor")) {
contractABIDefinition.setConstructor(abiDefinition);
} else if (abiDefinition.getType().equals("function")) {
contractABIDefinition.addFunction(abiDefinition.getName(), abiDefinition);
} else if (abiDefinition.getType().equals("event")) {
contractABIDefinition.addEvent(abiDefinition.getName(), abiDefinition);
} else {
// skip and do nothing
}
if (logger.isInfoEnabled()) {
logger.info(" abiDefinition: {}", abiDefinition);
}
}
if (contractABIDefinition.getConstructor() == null) {
contractABIDefinition.setConstructor(
ABIDefinition.createDefaultConstructorABIDefinition());
}
logger.info(" contractABIDefinition {} ", contractABIDefinition);
return contractABIDefinition;
} catch (Exception e) {
logger.error(" e: ", e);
return null;
}
}
}
|
3e1a9d46848d9963ff2a682ef0ddec1ff58e3594 | 6,291 | java | Java | web/rest-ui/src/main/java/org/artifactory/ui/rest/model/admin/services/backups/Backup.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 3 | 2016-01-21T11:49:08.000Z | 2018-12-11T21:02:11.000Z | web/rest-ui/src/main/java/org/artifactory/ui/rest/model/admin/services/backups/Backup.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | null | null | null | web/rest-ui/src/main/java/org/artifactory/ui/rest/model/admin/services/backups/Backup.java | alancnet/artifactory | 7ac3ea76471a00543eaf60e82b554d8edd894c0f | [
"Apache-2.0"
] | 5 | 2015-12-08T10:22:21.000Z | 2021-06-15T16:14:00.000Z | 41.662252 | 132 | 0.70275 | 11,297 | package org.artifactory.ui.rest.model.admin.services.backups;
import org.artifactory.api.config.CentralConfigService;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.descriptor.backup.BackupDescriptor;
import org.artifactory.descriptor.repo.LocalRepoDescriptor;
import org.artifactory.descriptor.repo.RealRepoDescriptor;
import org.artifactory.descriptor.repo.RemoteRepoDescriptor;
import org.artifactory.rest.common.model.RestModel;
import org.artifactory.rest.common.model.RestSpecialFields;
import org.artifactory.rest.common.service.IgnoreSpecialFields;
import org.artifactory.rest.common.util.JsonUtil;
import org.codehaus.jackson.map.annotate.JsonFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Chen Keinan
*/
@JsonFilter("exclude fields")
@IgnoreSpecialFields(value = {"excludeRepos", "includeRepos", "dir", "retentionPeriodHours",
"excludedRepositories", "sendMailOnError", "excludeBuilds", "incremental"})
public class Backup extends BackupDescriptor implements RestModel, RestSpecialFields {
private List<String> excludeRepos;
private List<String> includeRepos;
private boolean isEdit = false;
private boolean incremental;
Backup() {
}
public Backup(BackupDescriptor backupDescriptor, boolean isEdit) {
if (backupDescriptor != null) {
super.setCronExp(backupDescriptor.getCronExp());
super.setEnabled(backupDescriptor.isEnabled());
super.setKey(backupDescriptor.getKey());
super.setExcludeNewRepositories(backupDescriptor.isExcludeNewRepositories());
populateditFields(backupDescriptor, isEdit);
}
}
/**
* populate extra fields require for edit
*
* @param backupDescriptor - back up descriptor data
* @param isEdit - if true , populate fields for edit
*/
private void populateditFields(BackupDescriptor backupDescriptor, boolean isEdit) {
if (isEdit) {
this.isEdit = isEdit;
populateExcludeRepo(backupDescriptor.getExcludedRepositories());
populateIncludeRepo();
super.setRetentionPeriodHours(backupDescriptor.getRetentionPeriodHours());
super.setCreateArchive(backupDescriptor.isCreateArchive());
super.setDir(backupDescriptor.getDir());
super.setExcludeBuilds(backupDescriptor.isExcludeBuilds());
super.setRetentionPeriodHours(backupDescriptor.getRetentionPeriodHours());
super.setSendMailOnError(backupDescriptor.isSendMailOnError());
super.setCreateArchive(backupDescriptor.isCreateArchive());
}
}
/**
* populate exclude Real repo keys
*
* @param realRepoDescriptors - real repo descriptors
*/
private void populateExcludeRepo(List<RealRepoDescriptor> realRepoDescriptors) {
List<String> excludeRealRepo = new ArrayList<>();
realRepoDescriptors.forEach(realRepo -> excludeRealRepo.add(realRepo.getKey()));
excludeRepos = excludeRealRepo;
}
/**
* populate exclude Real repo keys
*/
private void populateIncludeRepo() {
List<String> repos = new ArrayList<>();
CentralConfigService centralConfigService = ContextHelper.get().beanForType(CentralConfigService.class);
Map<String, LocalRepoDescriptor> localRepoDescriptorMap = centralConfigService.getDescriptor().getLocalRepositoriesMap();
Map<String, RemoteRepoDescriptor> remoteRepoDescriptorMap = centralConfigService.getDescriptor().getRemoteRepositoriesMap();
repos.addAll(localRepoDescriptorMap.keySet());
repos.addAll(remoteRepoDescriptorMap.keySet());
excludeRepos.forEach(repo -> {
if (localRepoDescriptorMap.get(repo) != null || remoteRepoDescriptorMap.get(repo) != null) {
repos.remove(repo);
}
});
includeRepos = repos;
}
public List<String> getIncludeRepos() {
return includeRepos;
}
public void setIncludeRepos(List<String> includeRepos) {
this.includeRepos = includeRepos;
}
/**
* populate local and remote repositories to map
*
* @param repoKeys - remote repo key
* @param realRepoDescriptors - real repo descriptor list
* @param localRepoDescriptorMap - local repo descriptor map
* @param remoteRepoDescriptorMap - remote repo descriptor map
*/
private void populateRealRepoToMap(List<String> repoKeys, List<RealRepoDescriptor> realRepoDescriptors,
Map<String, LocalRepoDescriptor> localRepoDescriptorMap,
Map<String, RemoteRepoDescriptor> remoteRepoDescriptorMap) {
repoKeys.forEach(repoKey -> {
if (localRepoDescriptorMap.get(repoKey) != null) {
realRepoDescriptors.add(localRepoDescriptorMap.get(repoKey));
} else {
if (remoteRepoDescriptorMap.get(repoKey) != null) {
realRepoDescriptors.add(remoteRepoDescriptorMap.get(repoKey));
}
}
});
}
public List<String> getExcludeRepos() {
return excludeRepos;
}
/**
* get list of repo key and build list of Real repo descriptors
*
* @param excludeRepos - list of repos key to exclude
*/
public void setExcludeRepos(List<String> excludeRepos) {
this.excludeRepos = excludeRepos;
List<RealRepoDescriptor> realRepoDescriptors = new ArrayList<>();
CentralConfigService centralConfigService = ContextHelper.get().beanForType(CentralConfigService.class);
Map<String, LocalRepoDescriptor> localRepoDescriptorMap = centralConfigService.getDescriptor().getLocalRepositoriesMap();
Map<String, RemoteRepoDescriptor> remoteRepoDescriptorMap = centralConfigService.getDescriptor().getRemoteRepositoriesMap();
populateRealRepoToMap(excludeRepos, realRepoDescriptors, localRepoDescriptorMap, remoteRepoDescriptorMap);
super.setExcludedRepositories(realRepoDescriptors);
}
public String toString() {
return JsonUtil.jsonToStringIgnoreSpecialFields(this);
}
@Override
public boolean ignoreSpecialFields() {
return !isEdit;
}
}
|
3e1a9d533ba2f64f1047a21698f5fcc8cb2e7921 | 2,409 | java | Java | src/main/java/gov/miamidade/hgowl/plugin/ui/versioning/distributed/DynamicTeamMenu.java | hypergraphdb/protegeowl | 61eefbb9a1c9fbaf31940af7055b496b7f09c0a4 | [
"Apache-2.0"
] | 5 | 2016-03-13T16:34:18.000Z | 2022-03-13T18:04:10.000Z | src/main/java/gov/miamidade/hgowl/plugin/ui/versioning/distributed/DynamicTeamMenu.java | hypergraphdb/protegeowl | 61eefbb9a1c9fbaf31940af7055b496b7f09c0a4 | [
"Apache-2.0"
] | 14 | 2015-09-14T23:31:45.000Z | 2016-07-08T01:49:42.000Z | src/main/java/gov/miamidade/hgowl/plugin/ui/versioning/distributed/DynamicTeamMenu.java | hypergraphdb/protegeowl | 61eefbb9a1c9fbaf31940af7055b496b7f09c0a4 | [
"Apache-2.0"
] | 3 | 2015-08-07T23:33:39.000Z | 2019-09-18T08:20:36.000Z | 26.472527 | 122 | 0.692403 | 11,298 | package gov.miamidade.hgowl.plugin.ui.versioning.distributed;
import gov.miamidade.hgowl.plugin.owl.VDHGOwlEditorKit;
import gov.miamidade.hgowl.plugin.ui.HGPluginAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JMenu;
import org.protege.editor.core.editorkit.EditorKit;
import org.protege.editor.core.ui.action.ProtegeDynamicAction;
import org.protege.editor.owl.ui.action.ProtegeOWLAction;
/**
* DynamicVersioningMenu.
* @author Thomas Hilpold (CIAO/Miami-Dade County)
* @created Aug 21, 2012
*/
public class DynamicTeamMenu extends ProtegeDynamicAction
{
private static final long serialVersionUID = -2187253639033356483L;
@Override
public void initialise() throws Exception { }
@Override
public void dispose() throws Exception { }
@Override
public void actionPerformed(ActionEvent e) { }
@Override
public void rebuildChildMenuItems(JMenu menu)
{
EditorKit ekit = getEditorKit();
if (!(ekit instanceof VDHGOwlEditorKit)) {
System.err.println("Not running with a versioned distributed VDHGOwlEditorKit. DynamicVersioningMenu will be empty.");
return;
}
VDHGOwlEditorKit vdKit = (VDHGOwlEditorKit) ekit;
boolean userOnline = vdKit.isNetworking();
buildGeneralMenuItems(menu, vdKit, false, userOnline);
}
private JMenu addItem(JMenu menu, ProtegeOWLAction action, String name, boolean enabled)
{
action.putValue(Action.NAME, name);
action.setEnabled(enabled);
action.setEditorKit(getEditorKit());
menu.add(action);
return menu;
}
@SuppressWarnings("serial")
private void buildGeneralMenuItems(final JMenu menu,
final VDHGOwlEditorKit kit,
final boolean shared,
final boolean userOnline)
{
addItem(menu,
new HGPluginAction() { public void act() { kit.cloneOntology(); } },
"Clone",
userOnline);
menu.addSeparator();
if (!shared)
{
}
// else
// {
// cur = new VDHGShareActiveCancelAction();
// cur.putValue(Action.NAME, "Cancel Sharing");
// }
else
{
}
ProtegeOWLAction cur;
if (!userOnline) {
cur = new VDHGStartNetworkingAction();
cur.putValue(Action.NAME, "Sign in");
} else {
cur = new VDHGStopNetworkingAction();
cur.putValue(Action.NAME, "Log off");
}
cur.setEditorKit(kit);
menu.add(cur);
}
}
|
3e1a9d680cc187a9ceef8fa7a130a5f716012f06 | 3,094 | java | Java | sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java | messi2094/Sentinel | 3081579d5051de7c60a9e6bfc285d1178e622ce3 | [
"Apache-2.0"
] | 19,371 | 2018-07-23T03:09:38.000Z | 2022-03-31T13:26:18.000Z | sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java | messi2094/Sentinel | 3081579d5051de7c60a9e6bfc285d1178e622ce3 | [
"Apache-2.0"
] | 2,474 | 2018-07-24T09:29:27.000Z | 2022-03-31T20:04:46.000Z | sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java | messi2094/Sentinel | 3081579d5051de7c60a9e6bfc285d1178e622ce3 | [
"Apache-2.0"
] | 7,158 | 2018-07-23T02:15:57.000Z | 2022-03-31T10:15:46.000Z | 38.675 | 94 | 0.685844 | 11,299 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.csp.sentinel.annotation.aspectj;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import java.lang.reflect.Method;
/**
* Aspect for methods with {@link SentinelResource} annotation.
*
* @author Eric Zhao
*/
@Aspect
public class SentinelResourceAspect extends AbstractSentinelAspectSupport {
@Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)")
public void sentinelResourceAnnotationPointcut() {
}
@Around("sentinelResourceAnnotationPointcut()")
public Object invokeResourceWithSentinel(ProceedingJoinPoint pjp) throws Throwable {
Method originMethod = resolveMethod(pjp);
SentinelResource annotation = originMethod.getAnnotation(SentinelResource.class);
if (annotation == null) {
// Should not go through here.
throw new IllegalStateException("Wrong state for SentinelResource annotation");
}
String resourceName = getResourceName(annotation.value(), originMethod);
EntryType entryType = annotation.entryType();
int resourceType = annotation.resourceType();
Entry entry = null;
try {
entry = SphU.entry(resourceName, resourceType, entryType, pjp.getArgs());
return pjp.proceed();
} catch (BlockException ex) {
return handleBlockException(pjp, annotation, ex);
} catch (Throwable ex) {
Class<? extends Throwable>[] exceptionsToIgnore = annotation.exceptionsToIgnore();
// The ignore list will be checked first.
if (exceptionsToIgnore.length > 0 && exceptionBelongsTo(ex, exceptionsToIgnore)) {
throw ex;
}
if (exceptionBelongsTo(ex, annotation.exceptionsToTrace())) {
traceException(ex);
return handleFallback(pjp, annotation, ex);
}
// No fallback function can handle the exception, so throw it out.
throw ex;
} finally {
if (entry != null) {
entry.exit(1, pjp.getArgs());
}
}
}
}
|
3e1a9d7ec9132d3cb257f7af1c5a19d718f9d409 | 402 | java | Java | src/main/java/com/fabriccommunity/spookytime/util/PumpkinFoods.java | biom4st3r/spooky-time | 042d76f96fda3667c97d16167085f0588b42f45a | [
"MIT"
] | null | null | null | src/main/java/com/fabriccommunity/spookytime/util/PumpkinFoods.java | biom4st3r/spooky-time | 042d76f96fda3667c97d16167085f0588b42f45a | [
"MIT"
] | null | null | null | src/main/java/com/fabriccommunity/spookytime/util/PumpkinFoods.java | biom4st3r/spooky-time | 042d76f96fda3667c97d16167085f0588b42f45a | [
"MIT"
] | null | null | null | 22.333333 | 76 | 0.778607 | 11,300 | package com.fabriccommunity.spookytime.util;
import net.minecraft.item.Item;
import java.util.ArrayList;
public class PumpkinFoods {
private static final ArrayList<Item> validPumpkinFoods = new ArrayList<>();
public static void registerPumpkinFood(Item item) {
validPumpkinFoods.add(item);
}
public static boolean isItemPumpkin(Item item) {
return validPumpkinFoods.contains(item);
}
}
|
3e1a9e6275a04363a4f5b63c09ad5f44fcf8177e | 678 | java | Java | src/main/java/io/github/moosbusch/permagon/configuration/builder/converter/impl/JavaFXTabClosingPolicyConverter.java | moosbusch/Permagon | f2bc8eda35e238da3fdd8ea116214632ddb7d0b3 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/moosbusch/permagon/configuration/builder/converter/impl/JavaFXTabClosingPolicyConverter.java | moosbusch/Permagon | f2bc8eda35e238da3fdd8ea116214632ddb7d0b3 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/moosbusch/permagon/configuration/builder/converter/impl/JavaFXTabClosingPolicyConverter.java | moosbusch/Permagon | f2bc8eda35e238da3fdd8ea116214632ddb7d0b3 | [
"Apache-2.0"
] | null | null | null | 29.478261 | 106 | 0.824484 | 11,301 | package io.github.moosbusch.permagon.configuration.builder.converter.impl;
import io.github.moosbusch.permagon.configuration.builder.converter.spi.AbstractJavaFXFromStringConverter;
import javafx.scene.control.TabPane.TabClosingPolicy;
public class JavaFXTabClosingPolicyConverter extends AbstractJavaFXFromStringConverter<TabClosingPolicy> {
@Override
public TabClosingPolicy getDefaultValue() {
return TabClosingPolicy.UNAVAILABLE;
}
@Override
public Class<TabClosingPolicy> getTargetType() {
return TabClosingPolicy.class;
}
@Override
public TabClosingPolicy valueFromString(String constraint) {
return TabClosingPolicy.valueOf(constraint);
}
} |
3e1a9ea7517252d9f5a07ad2e051aa0657cc7a8c | 4,145 | java | Java | src/library/TagMatch.java | jefriyh/Ryuji-Mixed | 78c2c69144dab2ac1021decde6da6aedfee55a0b | [
"MIT"
] | null | null | null | src/library/TagMatch.java | jefriyh/Ryuji-Mixed | 78c2c69144dab2ac1021decde6da6aedfee55a0b | [
"MIT"
] | 1 | 2017-08-01T07:45:05.000Z | 2017-08-02T15:29:43.000Z | src/library/TagMatch.java | jefriyh/Ryuji-Mixed | 78c2c69144dab2ac1021decde6da6aedfee55a0b | [
"MIT"
] | null | null | null | 33.427419 | 90 | 0.508565 | 11,302 | /*
* 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 library;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
/**
*
* @author alvian
*/
public class TagMatch {
private Random rnd = new Random();
;
private ReadFile file;
private String[] lines;
private List<HashMap<String, HashMap<String, String>>> data = new ArrayList();
public void setDataSet(String dir_path) {
List<ReadFile> dataSets = ReadFile.getFiles(dir_path);
for (ReadFile file : dataSets) {
addData(file.getPath());
}
}
public void addData(String data_path) {
if (!data_path.contains(".DS_Store")) {
try {
file = new ReadFile(data_path);
lines = file.OpenFile();
for (int i = 0; i < lines.length; i++) {
addWords(lines[i]);
}
} catch (IOException e) {
System.out.println("[System] : failed to load file");
}
}
}
public void addWords(String words) {
String[] list = words.split(":");
String header = null;
String value = null;
for (int i = 0; i < list.length; i += 3) {
HashMap<String, String> header_tags = new HashMap();
header = list[0];
value = list[list.length - 1];
for (int j = 0; j < list.length - 2; j++) {
header_tags.put(list[j + 1], value);
}
HashMap<String, HashMap<String, String>> item = new HashMap();
item.put(header, header_tags);
data.add(item);
}
}
public List<List<String>> findByKey(String search, String[] tags) {
List<List<String>> key_list = new ArrayList();
for (int i = 0; i < data.size(); i += 2) {
HashMap item = data.get(i).get(search);
List<String> key_pairs = new ArrayList();
if (item != null) {
int tag_exist = 0;
String tmp_value = null;
for (String tag : tags) {
for (Object key : item.keySet()) {
if (key.toString().contains(tag)) {
tag_exist++;
tmp_value = item.get(key).toString();
}
}
}
if (tmp_value != null) {
key_pairs.add(tmp_value);
key_pairs.add(String.valueOf(tag_exist));
key_list.add(key_pairs);
}
}
}
return key_list;
}
public String getMatch(int accuracy, String search, String[] tags) {
List<List<String>> items = this.findByKey(search, tags);
List<String> matches = new ArrayList();
int currentAccuracy = 0;
int index = 0;
List<String> savedItem = null;
for (List<String> item : items) {
if (Integer.parseInt(item.get(1)) >= accuracy) {
matches.add(item.get(0));
if (Integer.parseInt(item.get(1)) >= currentAccuracy) {
currentAccuracy = Integer.parseInt(item.get(1));
savedItem = item;
}
}
index++;
}
if (savedItem != null) {
System.out.println("[Tokens] : " + Arrays.toString(tags));
System.out.println("[Match Count] : " + matches.size());
System.out.println("[Final Match] : " + Arrays.toString(savedItem.toArray()));
return savedItem.get(0);
} else {
return null;
}
}
// public static void main(String args[]){
// TagMatch a = new TagMatch();
// a.setDataSet("/base-data/");
// String[] tags = "how did gunadarma built".split(" ");
// System.out.println(a.getMatch(1, "how", tags));
// }
}
|
3e1a9efd9b245e949786b6d97ca9f5eb15045948 | 2,569 | java | Java | src/main/java/com/trickl/influxdb/client/SportsEventPeriodUpdateClient.java | trickl/influx-db-connector | 20fb5c43c3d07894afef7e4d1a6cf7aed7d7d376 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/trickl/influxdb/client/SportsEventPeriodUpdateClient.java | trickl/influx-db-connector | 20fb5c43c3d07894afef7e4d1a6cf7aed7d7d376 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/trickl/influxdb/client/SportsEventPeriodUpdateClient.java | trickl/influx-db-connector | 20fb5c43c3d07894afef7e4d1a6cf7aed7d7d376 | [
"Apache-2.0"
] | null | null | null | 36.7 | 99 | 0.757882 | 11,303 | package com.trickl.influxdb.client;
import com.trickl.influxdb.binding.SportsEventPeriodUpdateReader;
import com.trickl.influxdb.binding.SportsEventPeriodUpdateWriter;
import com.trickl.influxdb.persistence.SportsEventPeriodUpdateEntity;
import com.trickl.model.event.sports.SportsEventPeriodUpdate;
import com.trickl.model.pricing.primitives.EventSource;
import com.trickl.model.pricing.primitives.PriceSource;
import com.trickl.model.pricing.statistics.PriceSourceFieldFirstLastDuration;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;
@RequiredArgsConstructor
public class SportsEventPeriodUpdateClient {
private final InfluxDbAdapter influxDbClient;
/**
* Stores prices in the database.
*
* @param priceSource the instrument identifier
* @param events data to store
* @return the number of records stored
*/
public Flux<Integer> store(PriceSource priceSource, List<SportsEventPeriodUpdate> events) {
SportsEventPeriodUpdateWriter transformer =
new SportsEventPeriodUpdateWriter(priceSource);
List<SportsEventPeriodUpdateEntity> measurements =
events.stream().map(transformer).collect(Collectors.toList());
return influxDbClient.store(
measurements, SportsEventPeriodUpdateEntity.class, SportsEventPeriodUpdateEntity::getTime);
}
/**
* Find sports updates.
*
* @param eventSource the instrument identifier
* @param queryBetween Query parameters
* @return A list of bars
*/
public Flux<SportsEventPeriodUpdate> findBetween(
EventSource eventSource, QueryBetween queryBetween) {
SportsEventPeriodUpdateReader reader = new SportsEventPeriodUpdateReader();
if (eventSource.getEventSubType() != null) {
// Sub-types not supported
return Flux.empty();
}
return influxDbClient
.findBetween(
eventSource.getPriceSource(),
queryBetween,
"sports_event_period_update",
SportsEventPeriodUpdateEntity.class)
.map(reader);
}
/**
* Find a summary of outcome updates between a period of time, grouped by instrument.
*
* @param queryBetween A time window there series must have a data point within
* @return A list of series, including the first and last value of a field
*/
public Flux<PriceSourceFieldFirstLastDuration> findSummary(QueryBetween queryBetween) {
return influxDbClient.findFieldFirstLastCountByDay(
queryBetween, "sports_event_period_update", "period");
}
}
|
3e1aa00d3f534514b70b1aff1c117f9937bd3ef8 | 377 | java | Java | jasdb_api/src/main/java/com/oberasoftware/jasdb/api/entitymapper/annotations/JasDBEntity.java | oberasoftware/jasdb | 6791981f3e3d0808c90154fd7d78da11851cfca4 | [
"MIT",
"X11",
"Unlicense"
] | 30 | 2015-10-05T01:42:16.000Z | 2021-03-02T23:03:22.000Z | jasdb_api/src/main/java/com/oberasoftware/jasdb/api/entitymapper/annotations/JasDBEntity.java | oberasoftware/jasdb | 6791981f3e3d0808c90154fd7d78da11851cfca4 | [
"MIT",
"X11",
"Unlicense"
] | 19 | 2015-06-25T20:46:50.000Z | 2017-10-23T14:58:40.000Z | jasdb_api/src/main/java/com/oberasoftware/jasdb/api/entitymapper/annotations/JasDBEntity.java | oberasoftware/jasdb | 6791981f3e3d0808c90154fd7d78da11851cfca4 | [
"MIT",
"X11",
"Unlicense"
] | 10 | 2016-05-19T05:49:39.000Z | 2020-11-05T06:42:14.000Z | 23.5625 | 61 | 0.795756 | 11,304 | package com.oberasoftware.jasdb.api.entitymapper.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Renze de Vries
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JasDBEntity {
String bagName();
}
|
3e1aa0c04d45e1a47aa46d18fb070482577ce9d1 | 2,498 | java | Java | client-external/src/main/java/com/forcam/na/ffwebservices/client/api/staffmember/staffmemberplanning/response/StaffMembersPlanningResultsResponse.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | null | null | null | client-external/src/main/java/com/forcam/na/ffwebservices/client/api/staffmember/staffmemberplanning/response/StaffMembersPlanningResultsResponse.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | null | null | null | client-external/src/main/java/com/forcam/na/ffwebservices/client/api/staffmember/staffmemberplanning/response/StaffMembersPlanningResultsResponse.java | dalbrx-forcam/java-sdk | c32a0f9b2c884fa0b2caa8c95577bd9cebd91fee | [
"MIT"
] | 2 | 2020-11-13T18:59:10.000Z | 2020-11-13T19:20:25.000Z | 36.735294 | 124 | 0.554444 | 11,305 | ////////////////////////////////////////////////////////////////////////////////
//
// Created by NUebele on 21.11.2018.
//
// Copyright (c) 2006 - 2018 FORCAM GmbH. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
package com.forcam.na.ffwebservices.client.api.staffmember.staffmemberplanning.response;
import com.forcam.na.ffwebservices.client.api.pagination.response.AbstractCollectionResponse;
import com.forcam.na.ffwebservices.client.api.pagination.request.PaginationRequest;
import com.forcam.na.ffwebservices.model.staffmember.StaffMemberAssignmentWSModel;
import com.forcam.na.ffwebservices.model.staffmember.StaffMemberPlanningResultCollectionProperties;
import java.util.List;
/**
* Staff members planning results response.
*/
public class StaffMembersPlanningResultsResponse extends AbstractCollectionResponse<StaffMemberAssignmentWSModel> {
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
/** The staff member planning results properties. */
private StaffMemberPlanningResultCollectionProperties mProperties = new StaffMemberPlanningResultCollectionProperties();
// ------------------------------------------------------------------------
// constructors
// ------------------------------------------------------------------------
/**
* Creates a new instance.
*
* @param request The request.
*/
public StaffMembersPlanningResultsResponse(PaginationRequest request) {
super(request);
}
// ------------------------------------------------------------------------
// getters/setters
// ------------------------------------------------------------------------
/**
* Provides the staff member planning results properties.
*
* @return The staff member planning results properties.
*/
public StaffMemberPlanningResultCollectionProperties getProperties() {
return mProperties;
}
/**
* Sets the staff member planning results properties.
*
* @param properties The staff member planning results properties.
*/
public void setProperties(StaffMemberPlanningResultCollectionProperties properties) {
mProperties = properties;
}
@Override
public List<StaffMemberAssignmentWSModel> getElements() {
return mProperties.getElements();
}
} |
3e1aa2cd8d4867e0e6fbbd96dc9d8c58b02f108f | 872 | java | Java | ExtraHopRestAPI/src/com/extrahop/tools/domain/MetricData.java | jefferyfry/extrahop-platform-showcase | 3224d4d2eba4509730aec9b6979836f236377d9c | [
"MIT"
] | null | null | null | ExtraHopRestAPI/src/com/extrahop/tools/domain/MetricData.java | jefferyfry/extrahop-platform-showcase | 3224d4d2eba4509730aec9b6979836f236377d9c | [
"MIT"
] | null | null | null | ExtraHopRestAPI/src/com/extrahop/tools/domain/MetricData.java | jefferyfry/extrahop-platform-showcase | 3224d4d2eba4509730aec9b6979836f236377d9c | [
"MIT"
] | null | null | null | 16.769231 | 158 | 0.698394 | 11,306 | package com.extrahop.tools.domain;
/**
* This class represents a JSON MetricData object. This is a child of MetricStats. Properties are automatically mapped to JSON properties during serialization
* and de-serialization.
* @author jeffbfry
*
*/
public class MetricData extends JSONObject{
private long oid;
private long time;
private long duration;
private Object[] values;
public MetricData() {
super();
}
public long getOid() {
return oid;
}
public void setOid(long oid) {
this.oid = oid;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public Object[] getValues() {
return values;
}
public void setValues(Object[] values) {
this.values = values;
}
}
|
3e1aa34e505d07c381db6b8c98a810c0c6498463 | 1,059 | java | Java | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/Cluster$Adaptive.java | zhvqee/dubbo | dc6b58d3ca6ce28cd1626691b079524908c1e2c8 | [
"Apache-2.0"
] | null | null | null | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/Cluster$Adaptive.java | zhvqee/dubbo | dc6b58d3ca6ce28cd1626691b079524908c1e2c8 | [
"Apache-2.0"
] | null | null | null | dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/Cluster$Adaptive.java | zhvqee/dubbo | dc6b58d3ca6ce28cd1626691b079524908c1e2c8 | [
"Apache-2.0"
] | null | null | null | 48.136364 | 169 | 0.70916 | 11,307 | package org.apache.dubbo.rpc.cluster;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
public class Cluster$Adaptive {
public Invoker join(Directory directory) throws RpcException {
if (directory == null)
throw new IllegalArgumentException("org.apache.dubbo.rpc.cluster.Directory argument == null");
if (directory.getUrl() == null)
throw new IllegalArgumentException("org.apache.dubbo.rpc.cluster.Directory argument getUrl() == null");
URL url = directory.getUrl();
String extName = url.getParameter("cluster", "failover");
if(extName == null)
throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.cluster.Cluster) name from url (" + url.toString() + ") use keys([cluster])");
Cluster extension = ExtensionLoader.getExtensionLoader(Cluster.class).getExtension(extName);
return extension.join(directory);
}
}
|
3e1aa3c8175604e3ac88127ca7b7b2e94bf1d17d | 9,110 | java | Java | src/at/mep/util/IconUtil.java | tushev/Matlab-Editor-Plugin | 58d3949a67dee55f8ad37ef1007b3c0c7b16d33b | [
"MIT",
"BSD-3-Clause"
] | 80 | 2016-09-16T12:32:26.000Z | 2022-03-14T08:45:20.000Z | src/at/mep/util/IconUtil.java | Wandrys-dev/Matlab-Editor-Plugin | 7f4153d40ce0f9efc0527ce93c022212792090cf | [
"MIT",
"BSD-3-Clause"
] | 136 | 2016-09-15T06:37:35.000Z | 2022-03-03T11:16:19.000Z | src/at/mep/util/IconUtil.java | Wandrys-dev/Matlab-Editor-Plugin | 7f4153d40ce0f9efc0527ce93c022212792090cf | [
"MIT",
"BSD-3-Clause"
] | 15 | 2017-03-07T22:47:57.000Z | 2022-02-06T07:39:26.000Z | 37.03252 | 126 | 0.553348 | 11,308 | package at.mep.util;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by Andreas Justin on 2016-08-25.
*/
public class IconUtil {
public static Icon printTextOnIcon(final Icon icon, String text, int x, int y, Font font, Color color) {
Image img = getImage(icon);
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
bGr.drawImage(img, 0, 0, null);
bGr.setColor(color);
bGr.setFont(font);
bGr.drawString(text, x, y);
bGr.dispose();
return new ImageIcon(bimage);
}
public static Icon decorateIcon(final Icon icon, final Icon decorator, EIconDecorator location) {
Image img = getImage(icon);
Image imgDecorator = getImage(decorator);
BufferedImage bimage;
if (location.getLocation() < 360) {
bimage = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
} else {
bimage = getBufferedImageForLocation(img, imgDecorator, location);
}
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
int[] xy = getXYForIcon(icon, decorator, location, 0, 0);
int[] xyD = getXYForIconDecorator(icon, decorator, location, 0, 0);
bGr.drawImage(img, xy[0], xy[1], null);
bGr.drawImage(imgDecorator, xyD[0], xyD[1], null);
bGr.dispose();
return new ImageIcon(bimage);
}
/** Creates a new instance of the given icon painted in given color */
public static Icon color(final Icon icon, Color color, float alpha) {
final BufferedImage mask = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = (Graphics2D) mask.getGraphics();
icon.paintIcon(new JLabel(), gbi, 0, 0);
gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
gbi.setColor(color);
gbi.fillRect(0, 0, mask.getWidth() - 1, mask.getHeight() - 1);
Icon coloredIcon = new Icon() {
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
icon.paintIcon(c, g, x, y);
g.drawImage(mask, x, y, c);
}
@Override
public int getIconWidth() {
return icon.getIconWidth();
}
@Override
public int getIconHeight() {
return icon.getIconHeight();
}
};
return coloredIcon;
}
/** Creates a new instance of the given icon painted in given color */
public static Icon color(final Icon icon, Color color) {
return color(icon, color, 1);
}
public static Icon scale(final Icon icon, int width, int height) {
Image img = getImage(icon);
Image newimg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
return new ImageIcon(newimg);
}
public static Icon scaleHeight(final Icon icon, int height, boolean lockAspectRatio) {
if (height <= 0)
return icon;
Image img = getImage(icon);
Image newImg;
if (lockAspectRatio) {
double ratio = (double) icon.getIconWidth() / (double) icon.getIconHeight();
newImg = img.getScaledInstance((int) (height * ratio), height, Image.SCALE_SMOOTH);
} else
newImg = img.getScaledInstance(icon.getIconWidth(), height, Image.SCALE_SMOOTH);
return new ImageIcon(newImg);
}
public static Icon scaleWidth(final Icon icon, int width, boolean lockAspectRatio) {
if (width <= 0)
return icon;
Image img = getImage(icon);
Image newImg;
if (lockAspectRatio) {
double ratio = (double) icon.getIconWidth() / (double) icon.getIconHeight();
newImg = img.getScaledInstance(width, (int) (width / ratio), Image.SCALE_SMOOTH);
} else
newImg = img.getScaledInstance(width, icon.getIconHeight(), Image.SCALE_SMOOTH);
return new ImageIcon(newImg);
}
public static Icon deepCopy(final Icon icon) {
return new ImageIcon(getImage(icon));
}
private static Image getImage(Icon icon) {
if (icon instanceof ImageIcon)
return ((ImageIcon) icon).getImage();
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gbi = (Graphics2D) bi.getGraphics();
icon.paintIcon(new JLabel(), gbi, 0, 0);
return bi;
}
/** the basic icon has to be moved accordingly where the location of the decorator is. */
private static int[] getXYForIcon(Icon icon, Icon decorator, EIconDecorator location, int xOffset, int yOffset) {
int x = 0;
int y = 0;
switch (location) {
case NORTH_EAST_INSIDE:
break;
case SOUTH_EAST_INSIDE:
break;
case SOUTH_WEST_INSIDE:
break;
case NORTH_WEST_INSIDE:
break;
case NORTH_OUTSIDE:
x = 0;
y = decorator.getIconHeight();
break;
case EAST_OUTSIDE:
break;
case SOUTH_OUTSIDE:
break;
case WEST_OUTSIDE:
x = decorator.getIconWidth();
y = 0;
break;
}
return new int[]{x + xOffset, y + yOffset};
}
private static int[] getXYForIconDecorator(Icon icon, Icon decorator, EIconDecorator location, int xOffset, int yOffset) {
int x = 0;
int y = 0;
switch (location) {
case NORTH_EAST_INSIDE:
x = icon.getIconWidth() - decorator.getIconWidth();
y = 0;
break;
case SOUTH_EAST_INSIDE:
x = icon.getIconWidth() - decorator.getIconWidth();
y = icon.getIconHeight() - decorator.getIconHeight();
break;
case SOUTH_WEST_INSIDE:
x = 0;
y = icon.getIconHeight() - decorator.getIconHeight();
break;
case NORTH_WEST_INSIDE:
x = 0;
y = 0;
break;
case NORTH_OUTSIDE:
x = (icon.getIconWidth() - decorator.getIconWidth()) / 2;
y = -decorator.getIconHeight();
break;
case EAST_OUTSIDE:
x = icon.getIconWidth();
y = -(decorator.getIconHeight() - decorator.getIconHeight()) / 2;
break;
case SOUTH_OUTSIDE:
x = (icon.getIconWidth() - decorator.getIconWidth()) / 2;
y = icon.getIconHeight();
break;
case WEST_OUTSIDE:
x = -decorator.getIconWidth();
y = -(decorator.getIconHeight() - decorator.getIconHeight()) / 2;
break;
}
return new int[]{x + xOffset, y + yOffset};
}
private static BufferedImage getBufferedImageForLocation(Image img, Image imgDecorator, EIconDecorator location) {
BufferedImage b = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
switch (location) {
case NORTH_EAST_INSIDE:
break;
case SOUTH_EAST_INSIDE:
break;
case SOUTH_WEST_INSIDE:
break;
case NORTH_WEST_INSIDE:
break;
case NORTH_OUTSIDE:
b = new BufferedImage(
img.getWidth(null),
img.getHeight(null) + imgDecorator.getWidth(null),
BufferedImage.TYPE_INT_ARGB);
break;
case EAST_OUTSIDE:
b = new BufferedImage(
img.getWidth(null) + imgDecorator.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
break;
case SOUTH_OUTSIDE:
b = new BufferedImage(
img.getWidth(null),
img.getHeight(null) + imgDecorator.getWidth(null),
BufferedImage.TYPE_INT_ARGB);
break;
case WEST_OUTSIDE:
b = new BufferedImage(
img.getWidth(null) + imgDecorator.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
break;
}
return b;
}
}
|
3e1aa501f44b604d8d17405736d0cb44fd3a2059 | 1,138 | java | Java | plugins/intellij/SigmaEditorIntelliJ/src/com/ipsoft/amelia/sigma/RewriteRuleLanguage.java | nunet-io/sigmakee | b315bcd117917734111782900eacd9b0f39283ee | [
"Zlib",
"curl"
] | 83 | 2015-10-15T00:24:21.000Z | 2022-03-14T14:00:57.000Z | plugins/intellij/SigmaEditorIntelliJ/src/com/ipsoft/amelia/sigma/RewriteRuleLanguage.java | nunet-io/sigmakee | b315bcd117917734111782900eacd9b0f39283ee | [
"Zlib",
"curl"
] | 60 | 2016-02-19T16:37:07.000Z | 2022-02-01T01:47:34.000Z | plugins/intellij/SigmaEditorIntelliJ/src/com/ipsoft/amelia/sigma/RewriteRuleLanguage.java | nunet-io/sigmakee | b315bcd117917734111782900eacd9b0f39283ee | [
"Zlib",
"curl"
] | 28 | 2015-10-15T01:22:59.000Z | 2021-12-06T03:29:43.000Z | 33.588235 | 79 | 0.710158 | 11,309 | package com.ipsoft.amelia.sigma;
/*
Copyright 2014-2015 IPsoft
Author: Peigen You upchh@example.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program ; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA 02111-1307 USA
*/
import com.intellij.lang.Language;
public class RewriteRuleLanguage extends Language{
public static final RewriteRuleLanguage INSTANCE=new RewriteRuleLanguage();
private RewriteRuleLanguage() {
super("RewriteRuleLanguage");
}
}
|
3e1aa5482847edf49606bc90c1baf652740f5cc8 | 273 | java | Java | app/src/main/java/com/seven/seven/common/view/webview/H5ToAndroidData.java | seven123456/seven_develop | e28549c65fa5f82c3691c041fe0f06e837f014fd | [
"Apache-2.0"
] | 35 | 2018-01-04T08:37:28.000Z | 2018-08-31T08:38:04.000Z | app/src/main/java/com/seven/seven/common/view/webview/H5ToAndroidData.java | seven123456/seven_develop | e28549c65fa5f82c3691c041fe0f06e837f014fd | [
"Apache-2.0"
] | 1 | 2018-07-26T01:51:51.000Z | 2018-08-05T17:01:48.000Z | app/src/main/java/com/seven/seven/common/view/webview/H5ToAndroidData.java | seven123456/seven_develop | e28549c65fa5f82c3691c041fe0f06e837f014fd | [
"Apache-2.0"
] | null | null | null | 17.125 | 54 | 0.733577 | 11,310 | package com.seven.seven.common.view.webview;
import java.io.Serializable;
/**
* Created by seven
* on 2018/5/28
* email:lyhxr@example.com
* h5控制android事件时传递的数据
*/
public class H5ToAndroidData implements Serializable {
public int type;
public Object data;
}
|
3e1aa5a092631cd49499896dfb4222ddfc2153d5 | 2,608 | java | Java | server/src/test/java/net/kebernet/configuration/server/ConfigWriterTest.java | kebernet/erigo | 476af345aa412909286cafb1eea508e33f4363c1 | [
"Apache-2.0"
] | 2 | 2017-07-08T16:24:03.000Z | 2017-07-08T16:56:39.000Z | server/src/test/java/net/kebernet/configuration/server/ConfigWriterTest.java | kebernet/erigo | 476af345aa412909286cafb1eea508e33f4363c1 | [
"Apache-2.0"
] | null | null | null | server/src/test/java/net/kebernet/configuration/server/ConfigWriterTest.java | kebernet/erigo | 476af345aa412909286cafb1eea508e33f4363c1 | [
"Apache-2.0"
] | null | null | null | 40.75 | 115 | 0.726994 | 11,311 | /*
* Copyright (c) 2017 Robert Cooper
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kebernet.configuration.server;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import net.kebernet.configuration.client.model.SettingValue;
import net.kebernet.configuration.server.model.ConfigurationGroup;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
public class ConfigWriterTest {
@Test
public void testSimple() throws IOException {
ConfigurationGroup group = new ConfigurationGroup();
group.setName("groupName");
group.setTemplateFiles(Collections.singletonList("tmp/the-file.txt"));
group.setBeforeScriptTemplate("before.sh");
group.setAfterScriptTemplate("after.sh");
List<SettingValue> settings = Collections.singletonList(new SettingValue("user_name", "Bob"));
File targetDir = new File(System.getProperty("build.dir")+"/test", ConfigWriterTest.class.getSimpleName());
File storageDir = new File(System.getProperty("test.resources")+"/ConfigWriterTest");
ScriptExecutor executor = mock(ScriptExecutor.class);
doNothing().when(executor).runAndDeleteScript(anyString());
ConfigWriter writer = new ConfigWriter(targetDir, storageDir, executor);
writer.executeApplyGroups(Collections.singletonList(group), settings);
File written = new File(targetDir, group.getTemplateFiles().get(0));
try(InputStreamReader r = new InputStreamReader(new FileInputStream(written), Charsets.UTF_8)){
String read = CharStreams.toString(r);
assertEquals("Hello, Bob", read.trim());
}
verify(executor, times(2)).runAndDeleteScript(anyString());
verifyNoMoreInteractions(executor);
}
} |
3e1aa7794742c4f36c40dd77021e647782135a6b | 39,170 | java | Java | src/main/java/aztech/modern_industrialization/materials/MIMaterials.java | Falkory220/Modern-Industrialization | ee0467ff91ebbbe162655760b0ca108ceccffc61 | [
"MIT"
] | null | null | null | src/main/java/aztech/modern_industrialization/materials/MIMaterials.java | Falkory220/Modern-Industrialization | ee0467ff91ebbbe162655760b0ca108ceccffc61 | [
"MIT"
] | null | null | null | src/main/java/aztech/modern_industrialization/materials/MIMaterials.java | Falkory220/Modern-Industrialization | ee0467ff91ebbbe162655760b0ca108ceccffc61 | [
"MIT"
] | null | null | null | 76.206226 | 169 | 0.67396 | 11,312 | /*
* MIT License
*
* Copyright (c) 2020 Azercoco & Technici4n
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package aztech.modern_industrialization.materials;
import static aztech.modern_industrialization.materials.MaterialHardness.*;
import static aztech.modern_industrialization.materials.part.MIParts.*;
import static aztech.modern_industrialization.materials.set.MaterialOreSet.COPPER;
import static aztech.modern_industrialization.materials.set.MaterialSet.*;
import aztech.modern_industrialization.MIItem;
import aztech.modern_industrialization.api.energy.CableTier;
import aztech.modern_industrialization.machines.init.MIMachineRecipeTypes;
import aztech.modern_industrialization.materials.part.*;
import aztech.modern_industrialization.materials.recipe.ForgeHammerRecipes;
import aztech.modern_industrialization.materials.recipe.SmeltingRecipes;
import aztech.modern_industrialization.materials.recipe.StandardRecipes;
import aztech.modern_industrialization.materials.recipe.builder.MIRecipeBuilder;
import aztech.modern_industrialization.materials.set.MaterialBlockSet;
import aztech.modern_industrialization.materials.set.MaterialOreSet;
import aztech.modern_industrialization.materials.set.MaterialRawSet;
import aztech.modern_industrialization.nuclear.INeutronBehaviour;
import aztech.modern_industrialization.nuclear.NuclearAbsorbable;
import aztech.modern_industrialization.nuclear.NuclearConstant;
import aztech.modern_industrialization.textures.coloramp.BakableTargetColoramp;
import aztech.modern_industrialization.util.ResourceUtil;
import net.devtech.arrp.json.tags.JTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.valueproviders.UniformInt;
// @formatter:off
public class MIMaterials {
public static void init() {
addMaterials();
addExtraTags();
}
public static final String commonPath = "modern_industrialization:textures/materialsets/common/";
public static final String templatePath = "modern_industrialization:textures/template/";
public static final String mcPath = "minecraft:textures/item/";
public static final String miPath = "modern_industrialization:textures/items/";
public static String common(String name) {
return commonPath + name + ".png";
}
public static String common(Part part) {
return common(part.key);
}
public static String mcitem(String name) {
return mcPath + name + ".png";
}
public static String miitem(String name) {
return miPath + name + ".png";
}
public static String template(String name) {
return templatePath + name + ".png";
}
public static MaterialBuilder addVanillaMetal(boolean nugget, MaterialBuilder builder) {
String n = builder.getMaterialName();
MaterialBuilder res = builder.overridePart(ExternalPart.of(INGOT, "#c:" + n + "_ingots", "minecraft:" + n + "_ingot"))
.addParts(ExternalPart.of(BLOCK, "#c:" + n + "_blocks", "minecraft:" + n + "_block"))
.addParts(ExternalPart.of(ORE, "#c:" + n + "_ores", "minecraft:" + n + "_ore"))
.addParts(ExternalPart.of(ORE_DEEPLSATE, "#c:" + n + "_ores", "minecraft:deepslate_" + n + "_ore"))
.addParts(ExternalPart.of(RAW_METAL, "#c:raw_" + n + "_ores", "minecraft:raw_" + n))
.addParts(ExternalPart.of(RAW_METAL_BLOCK, "#c:raw_" + n + "_blocks", "minecraft:raw_" + n + "_block"));
if (nugget) {
res.overridePart(ExternalPart.of(NUGGET, "#c:" + n + "_nuggets", "minecraft:" + n + "_nugget"));
}
res.addRecipes(ForgeHammerRecipes::apply, SmeltingRecipes::apply, StandardRecipes::apply)
.cancelRecipes("craft/block_from_ingot", "craft/ingot_from_block")
.cancelRecipes("craft/raw_metal_block_from_raw_metal", "craft/raw_metal_from_raw_metal_block")
.cancelRecipes("smelting/ore_to_ingot_smelting", "smelting/ore_to_ingot_blasting")
.cancelRecipes("smelting/ore_deepslate_to_ingot_smelting", "smelting/ore_deepslate_to_ingot_blasting")
.cancelRecipes("smelting/raw_metal_to_ingot_smelting", "smelting/raw_metal_to_ingot_blasting");
if (nugget) {
res.cancelRecipes("craft/ingot_from_nugget", "craft/nugget_from_ingot");
}
return res;
}
public static MaterialBuilder addVanillaGem(boolean compressor, MaterialBuilder builder) {
return addVanillaGem(compressor, builder.getMaterialName(), builder);
}
public static MaterialBuilder addVanillaGem(boolean compressor, String gemPath, MaterialBuilder builder) {
String n = builder.getMaterialName();
MaterialBuilder res = builder.addParts(ExternalPart.of(GEM, "minecraft:" + gemPath, "minecraft:" + gemPath))
.addParts(ExternalPart.of(BLOCK, "#c:" + n + "_blocks", "minecraft:" + n + "_block"))
.addParts(ExternalPart.of(ORE, "#c:" + n + "_ores", "minecraft:" + n + "_ore"))
.addParts(ExternalPart.of(ORE_DEEPLSATE, "#c:" + n + "_ores", "minecraft:deepslate_" + n + "_ore"));
res.addRecipes(SmeltingRecipes::apply, StandardRecipes::apply).cancelRecipes("craft/block_from_gem", "craft/gem_from_block")
.cancelRecipes("smelting/ore_to_gem_smelting", "smelting/ore_to_gem_blasting")
.cancelRecipes("smelting/ore_deepslate_to_gem_smelting", "smelting/ore_deepslate_to_gem_blasting");
if (compressor) {
res.addRecipes(context -> new MIRecipeBuilder(context, MIMachineRecipeTypes.COMPRESSOR, n).addTaggedPartInput(DUST, 1).addOutput("minecraft:" + gemPath, 1));
}
return res;
}
private static void addMaterials() {
MaterialRegistry.addMaterial(addVanillaMetal(true,
new MaterialBuilder("gold", SHINY, new BakableTargetColoramp(0xFFE650, common(INGOT), mcitem("gold_ingot")), SOFT)
.addParts(BOLT, RING, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(DRILL_HEAD, DRILL)).build());
MaterialRegistry
.addMaterial(
addVanillaMetal(true,
new MaterialBuilder("iron", METALLIC, new BakableTargetColoramp(0xC8C8C8, common(INGOT), mcitem("iron_ingot")),
AVERAGE).addParts(BOLT, RING, GEAR, ROD, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(ExternalPart.of(HAMMER, MIItem.IRON_HAMMER.getPath())))
.build());
MaterialRegistry.addMaterial(addVanillaMetal(false,
new MaterialBuilder("copper", METALLIC, new BakableTargetColoramp(0xe77c56, common(INGOT), mcitem("copper_ingot")), SOFT)
.addParts(BOLT, BLADE, RING, ROTOR, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(WIRE).addParts(FINE_WIRE).addParts(CABLE.of(CableTier.LV)).addParts(DRILL_HEAD, DRILL))
.cancelRecipes("macerator/ore_to_raw", "forge_hammer/ore_to_raw_metal",
"forge_hammer/ore_to_raw_metal_with_tool", "forge_hammer/ore_to_dust_with_tool").build());
MaterialRegistry.addMaterial(
addVanillaGem(true, new MaterialBuilder("coal", STONE, GEM, new BakableTargetColoramp(0x282828, common(PLATE), mcitem("coal")), SOFT)
.addParts(ITEM_PURE_NON_METAL)).addRecipes(ForgeHammerRecipes::apply).build());
MaterialRegistry.addMaterial(addVanillaGem(false,
new MaterialBuilder("diamond", SHINY, GEM, new BakableTargetColoramp(0x48eeda, mcitem("diamond"), mcitem("diamond")), VERY_HARD)
.addParts(ITEM_PURE_NON_METAL).addParts(PLATE, LARGE_PLATE).addParts(ExternalPart.of(HAMMER, MIItem.DIAMOND_HAMMER.getPath()))).build());
MaterialRegistry.addMaterial(addVanillaGem(false,
new MaterialBuilder("emerald", SHINY, GEM, new BakableTargetColoramp(0x3FF385, mcitem("emerald"), mcitem("emerald")), VERY_HARD)
.addParts(ITEM_PURE_NON_METAL).addParts(PLATE)).build());
MaterialRegistry.addMaterial(addVanillaGem(true, "lapis_lazuli",
new MaterialBuilder("lapis", DULL, GEM, new BakableTargetColoramp(0x1A2D8D, common("dust"), mcitem("lapis_lazuli")), SOFT)
.addParts(ITEM_PURE_NON_METAL).addParts(PLATE)).cancelRecipes("macerator/ore_to_crushed").build());
MaterialRegistry
.addMaterial(new MaterialBuilder("redstone", STONE, DUST, new BakableTargetColoramp(0xd20000, common(DUST), mcitem("redstone")), SOFT)
.addParts(TINY_DUST, CRUSHED_DUST, BATTERY).addParts(ExternalPart.of(DUST, "minecraft:redstone", "minecraft:redstone"))
.addParts(ExternalPart.of(BLOCK, "#c:redstone_blocks", "minecraft:redstone_block"))
.addParts(ExternalPart.of(ORE, "#c:redstone_ores", "minecraft:redstone_ore"))
.addParts(ExternalPart.of(ORE_DEEPLSATE, "#c:redstone_ores", "minecraft:deepslate_redstone_ore"))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).cancelRecipes("macerator/ore_to_crushed")
.cancelRecipes("craft/block_from_dust", "craft/dust_from_block").build());
MaterialRegistry
.addMaterial(new MaterialBuilder("quartz", STONE, GEM, new BakableTargetColoramp(0xf0ebe4, mcitem("quartz"), mcitem("quartz")), SOFT)
.addParts(CRUSHED_DUST, DUST, TINY_DUST).addParts(ORE.of(UniformInt.of(2, 5), MaterialOreSet.QUARTZ))
.addParts(ExternalPart.of(GEM, "minecraft:quartz", "minecraft:quartz")).addRecipes(StandardRecipes::apply)
.cancelRecipes("macerator/ore_to_crushed").addRecipes(context -> new MIRecipeBuilder(context, MIMachineRecipeTypes.COMPRESSOR, "quartz")
.addTaggedPartInput(DUST, 1).addOutput("minecraft:quartz", 1))
.build());
MaterialRegistry.addMaterial(new MaterialBuilder("brick", STONE, new BakableTargetColoramp(0xb75a36, common("ingot"), mcitem("brick")), SOFT)
.addParts(DUST, TINY_DUST).addParts(ExternalPart.of(INGOT, "minecraft:brick", "minecraft:brick"))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("fire_clay", STONE, new BakableTargetColoramp(0xb75a36, common("ingot"), miitem("fire_clay_brick")), SOFT)
.addParts(DUST).addParts(MIItemPart.of(INGOT, "fire_clay_brick")).addRecipes(SmeltingRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("coke", STONE, GEM, new BakableTargetColoramp(0x6d6d57, common("dust"), miitem("coke")), SOFT)
.addParts(DUST).addParts(MIItemPart.of(GEM, "coke")).addParts(BLOCK.of(MaterialBlockSet.COAL))
.addRecipes(context -> new MIRecipeBuilder(context, MIMachineRecipeTypes.COMPRESSOR, "dust").addTaggedPartInput(DUST, 1).addPartOutput(GEM, 1))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("bronze", SHINY, new BakableTargetColoramp(0xffcc00, common("ingot"), template("bronze_ingot")), SOFT)
.addParts(BOLT, BLADE, RING, ROTOR, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.removeParts(CRUSHED_DUST).addParts(BLOCK.of(MaterialBlockSet.COPPER)).addParts(TANK.of(4)).addParts(DRILL_HEAD, DRILL)
.addParts(BARREL.of(32)).addParts(MACHINE_CASING, MACHINE_CASING_PIPE)
.addParts(MACHINE_CASING_SPECIAL.of("bronze_plated_bricks"))
.addRecipes(ForgeHammerRecipes::apply, SmeltingRecipes::apply, StandardRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("tin", DULL, new BakableTargetColoramp(0xc0bcd0, common("ingot"), template("tin_ingot")), SOFT)
.addParts(BOLT, BLADE, RING, ROTOR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(ORE.ofAll(16, 9, 64, MaterialOreSet.IRON)).addParts(WIRE).addParts(RAW_METAL.of(MaterialRawSet.GOLD))
.addParts(BLOCK.of(MaterialBlockSet.COPPER)).addParts(CABLE.of(CableTier.LV))
.addRecipes(ForgeHammerRecipes::apply, SmeltingRecipes::apply, StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("steel", METALLIC, new BakableTargetColoramp(0x3f3f3f, common("ingot"), template("steel_ingot")), AVERAGE)
.addParts(BOLT, RING, ROD, GEAR, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(ROD_MAGNETIC).addParts(BLOCK.of(MaterialBlockSet.IRON)).addParts(DRILL_HEAD, DRILL)
.addParts(MACHINE_CASING, MACHINE_CASING_PIPE).addParts(TANK.of(8)).addParts(BARREL.of(128))
.addParts(ExternalPart.of(HAMMER, MIItem.STEEL_HAMMER.getPath()))
.addRecipes(ForgeHammerRecipes::apply, SmeltingRecipes::apply, StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("lignite_coal", STONE, GEM, 0x644646, SOFT).addParts(ITEM_PURE_NON_METAL)
.addParts(BLOCK.of(MaterialBlockSet.COAL)).addParts(GEM)
.addParts(ORE.ofAll(UniformInt.of(0, 2), 25, 17, 256, MaterialOreSet.COAL))
.addRecipes(ForgeHammerRecipes::apply, SmeltingRecipes::apply, StandardRecipes::apply).cancelRecipes("macerator/crushed_dust")
.addRecipes(context -> new MIRecipeBuilder(context, MIMachineRecipeTypes.COMPRESSOR, "lignite_coal").addTaggedPartInput(DUST, 1).addPartOutput(GEM, 1))
.build());
MaterialRegistry.addMaterial(
new MaterialBuilder("aluminum", METALLIC, new BakableTargetColoramp(0x3fcaff, common("ingot"), template("aluminum_ingot")), AVERAGE)
.addParts(BOLT, BLADE, RING, ROTOR, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(WIRE).addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(MACHINE_CASING.of("advanced_machine_casing"))
.addParts(DRILL_HEAD, DRILL).addParts(MACHINE_CASING_SPECIAL.of("frostproof_machine_casing")).addParts(TANK.of(16))
.addParts(BARREL.of(512)).addParts(CABLE.of(CableTier.HV)).addRecipes(StandardRecipes::apply)
.addRecipes(SmeltingRecipes::applyBlastFurnace).build());
MaterialRegistry.addMaterial(new MaterialBuilder("bauxite", DULL, DUST, 0xC86400, SOFT).addParts(ITEM_PURE_NON_METAL)
.addParts(BLOCK.of(MaterialBlockSet.LAPIS)).addParts(ORE.ofAll(UniformInt.of(1, 4), 24, 7, 32, MaterialOreSet.REDSTONE))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("lead", DULL, new BakableTargetColoramp(0x6a76bc, common("ingot"), template("lead_ingot")), AVERAGE)
.addParts(DOUBLE_INGOT, DUST, INGOT, NUGGET, PLATE, TINY_DUST).addParts(BLOCK.of(MaterialBlockSet.COPPER))
.addParts(ORE.ofAll(16, 5, 64, MaterialOreSet.IRON)).addParts(RAW_METAL.of(MaterialRawSet.IRON))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).cancelRecipes("macerator/raw_metal").build());
MaterialRegistry.addMaterial(new MaterialBuilder("battery_alloy", DULL, 0x9C7CA0, SOFT)
.addParts(TINY_DUST, DUST, INGOT, DOUBLE_INGOT, PLATE, CURVED_PLATE, NUGGET, LARGE_PLATE).addParts(BLOCK.of(MaterialBlockSet.IRON))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("invar", METALLIC, 0xDCDC96, AVERAGE).addParts(MACHINE_CASING_SPECIAL.of("heatproof_machine_casing"))
.addParts(TINY_DUST, DUST, INGOT, ROD, DOUBLE_INGOT, RING, BOLT, PLATE, LARGE_PLATE, NUGGET, GEAR)
.addParts(BLOCK.of(MaterialBlockSet.IRON)).addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("cupronickel", METALLIC, 0xE39681, SOFT)
.addParts(TINY_DUST, DUST, INGOT, DOUBLE_INGOT, PLATE, WIRE, NUGGET, WIRE_MAGNETIC).addParts(COIL)
.addParts(BLOCK.of(MaterialBlockSet.COPPER)).addParts(CABLE.of(CableTier.MV))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("antimony", SHINY, 0xDCDCF0, SOFT).addParts(ITEM_PURE_METAL)
.addParts(RAW_METAL.of(MaterialRawSet.COPPER)).addParts(BLOCK.of(MaterialBlockSet.IRON))
.addParts(ORE.ofAll(20, 5, 64, MaterialOreSet.REDSTONE)).addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("nickel", METALLIC, 0xFAFAC8, AVERAGE).addParts(DOUBLE_INGOT, DUST, INGOT, NUGGET, PLATE, TINY_DUST)
.addParts(RAW_METAL.ofAll(MaterialRawSet.IRON)).addParts(BLOCK.of(MaterialBlockSet.IRON))
.addParts(ORE.ofAll(14, 6, 64, MaterialOreSet.IRON)).addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("silver", SHINY, new BakableTargetColoramp(0xDCDCFF, common("ingot"), template("silver_ingot")), SOFT)
.addParts(RAW_METAL.ofAll(MaterialRawSet.GOLD)).addParts(CABLE.of(CableTier.LV))
.addParts(DOUBLE_INGOT, DUST, INGOT, NUGGET, PLATE, TINY_DUST, WIRE).addParts(BLOCK.of(MaterialBlockSet.GOLD))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("sodium", STONE, DUST, 0x071CB8, SOFT).addParts(ITEM_PURE_NON_METAL).addParts(BLOCK.of(MaterialBlockSet.LAPIS))
.addParts(BATTERY).removeParts(CRUSHED_DUST).addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("salt", STONE, DUST, 0xc7d6c5, SOFT).addParts(ITEM_PURE_NON_METAL)
.addParts(BLOCK.of(MaterialBlockSet.REDSTONE)).addParts(ORE.ofAll(UniformInt.of(1, 3), 6, 6, 64, MaterialOreSet.COAL))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("titanium", METALLIC, new BakableTargetColoramp(0xDCA0F0, common("ingot"), template("titanium_ingot")), HARD)
.addParts(BOLT, BLADE, RING, ROTOR, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(BLOCK.of(MaterialBlockSet.NETHERITE)).addParts(RAW_METAL.ofAll(MaterialRawSet.COPPER)).addParts(HOT_INGOT)
.addParts(MACHINE_CASING.of("highly_advanced_machine_casing")).addParts(DRILL_HEAD, DRILL).addParts(MACHINE_CASING_PIPE)
.addParts(MACHINE_CASING_SPECIAL.of("solid_titanium_machine_casing")).addParts(ORE.of(MaterialOreSet.IRON))
.addParts(TANK.of(64)).addParts(BARREL.of(8192)).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, true, 128, 400)).cancelRecipes("macerator/raw_metal").build());
MaterialRegistry.addMaterial(
new MaterialBuilder("electrum", SHINY, new BakableTargetColoramp(0xFFFF64, common("ingot"), template("electrum_ingot")), SOFT)
.addParts(DOUBLE_INGOT, DUST, INGOT, NUGGET, PLATE, TINY_DUST).addParts(BLOCK.of(MaterialBlockSet.GOLD))
.addParts(WIRE, FINE_WIRE).addParts(CABLE.of(CableTier.MV)).addRecipes(StandardRecipes::apply, SmeltingRecipes::apply)
.build());
MaterialRegistry.addMaterial(new MaterialBuilder("silicon", METALLIC, 0x3C3C50, SOFT).addParts(ITEM_PURE_METAL)
.addParts(BLOCK.of(MaterialBlockSet.IRON)).addParts(N_DOPED_PLATE, P_DOPED_PLATE).addParts(PLATE, DOUBLE_INGOT, BATTERY)
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("stainless_steel", SHINY,
new BakableTargetColoramp(0xC8C8DC, common("ingot"), template("stainless_steel_ingot")), HARD)
.addParts(BLOCK.of(MaterialBlockSet.IRON))
.addParts(BOLT, BLADE, RING, ROTOR, GEAR, ROD, CURVED_PLATE, DOUBLE_INGOT, DUST, INGOT, LARGE_PLATE, NUGGET, PLATE, TINY_DUST)
.addParts(HOT_INGOT).addParts(DRILL_HEAD, DRILL).addParts(MACHINE_CASING.of("turbo_machine_casing"))
.addParts(MACHINE_CASING_PIPE).addParts(MACHINE_CASING_SPECIAL.of("clean_stainless_steel_machine_casing"))
.addParts(ROD_MAGNETIC).addParts(TANK.of(32)).addParts(BARREL.of(4096)).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, true, 32, 400)).cancelRecipes("polarizer/rod_magnetic").build());
MaterialRegistry
.addMaterial(new MaterialBuilder("ruby", SHINY, 0xd1001f, HARD).addParts(DUST, TINY_DUST).addRecipes(StandardRecipes::apply).build());
MaterialRegistry
.addMaterial(
new MaterialBuilder("carbon", DULL, 0x444444, SOFT).addParts(DUST, TINY_DUST, PLATE)
.addParts(
LARGE_PLATE
.withRegister((registeringContext, partContext, part, itemPath, itemId, itemTag) -> NuclearAbsorbable
.of(itemPath, 2500, 2 * NuclearConstant.BASE_HEAT_CONDUCTION,
INeutronBehaviour.of(NuclearConstant.ScatteringType.MEDIUM, NuclearConstant.CARBON,
2),
NuclearConstant.DESINTEGRATION_BY_ROD * 2)))
.addRecipes(context -> new MIRecipeBuilder(context, MIMachineRecipeTypes.COMPRESSOR, "dust").addTaggedPartInput(DUST, 1)
.addPartOutput(PLATE, 1))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("chromium", SHINY, new BakableTargetColoramp(0xFFE6E6, common("ingot"), template("chromium_ingot")), AVERAGE)
.addParts(CRUSHED_DUST).addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ITEM_PURE_METAL).addParts(HOT_INGOT)
.addParts(PLATE, LARGE_PLATE, DOUBLE_INGOT).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, true, 32, 400)).cancelRecipes("macerator/crushed_dust").build());
MaterialRegistry.addMaterial(new MaterialBuilder("manganese", DULL, 0xC1C1C1, AVERAGE).addParts(BLOCK.of(MaterialBlockSet.IRON))
.addParts(ITEM_PURE_METAL).addParts(CRUSHED_DUST).addRecipes(StandardRecipes::apply).cancelRecipes("macerator/crushed_dust").build());
MaterialRegistry.addMaterial(new MaterialBuilder("beryllium", SHINY, 0x64B464, HARD).addParts(BLOCK.of(MaterialBlockSet.NETHERITE))
.addParts(DOUBLE_INGOT, DUST, INGOT, NUGGET, PLATE, TINY_DUST).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("annealed_copper", SHINY, 0xff924f, SOFT).addParts(ITEM_PURE_METAL)
.addParts(BLOCK.of(MaterialBlockSet.COPPER)).addParts(PLATE, WIRE, DOUBLE_INGOT, HOT_INGOT).addParts(CABLE.of(CableTier.EV))
.addRecipes(StandardRecipes::apply).addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, false, 64)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("uranium", DULL, 0x39e600, AVERAGE).addParts(FUEL_ROD.ofAll(NuclearConstant.U))
.addParts(ITEM_PURE_METAL).addParts(ROD).addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ORE.ofAll(8, 5, 16, COPPER))
.addParts(RAW_METAL.of(MaterialRawSet.URANIUM)).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("uranium_235", SHINY, 0xe60045, VERY_HARD).addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ITEM_PURE_METAL)
.addRecipes(StandardRecipes::apply).addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("uranium_238", DULL, 0x55bd33, SOFT).addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ITEM_PURE_METAL)
.addRecipes(StandardRecipes::apply).addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("le_uranium", DULL, 0x70a33c, VERY_HARD).addParts(FUEL_ROD.ofAll(NuclearConstant.LEU))
.addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ITEM_PURE_METAL).addParts(ROD).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("he_uranium", DULL, 0xaae838, VERY_HARD).addParts(FUEL_ROD.ofAll(NuclearConstant.HEU))
.addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(ITEM_PURE_METAL).addParts(ROD).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("le_mox", SHINY, 0x00e7e5, VERY_HARD).addParts(BLOCK.of(MaterialBlockSet.GOLD))
.addParts(FUEL_ROD.ofAll(NuclearConstant.LE_MOX)).addParts(ITEM_PURE_METAL).addParts(ROD).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("he_mox", SHINY, 0xcc87fa, VERY_HARD).addParts(BLOCK.of(MaterialBlockSet.GOLD))
.addParts(FUEL_ROD.ofAll(NuclearConstant.HE_MOX)).addParts(ITEM_PURE_METAL).addParts(ROD).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(new MaterialBuilder("plutonium", SHINY, 0xd701e7, VERY_HARD).addParts(BLOCK.of(MaterialBlockSet.GOLD))
.addParts(ITEM_PURE_METAL).addParts(BATTERY).addRecipes(StandardRecipes::apply)
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, 128)).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("platinum", SHINY, new BakableTargetColoramp(0xffe5ba, common("ingot"), template("platinum_ingot")), AVERAGE)
.addParts(BLOCK.of(MaterialBlockSet.GOLD)).addParts(RAW_METAL.ofAll(MaterialRawSet.GOLD))
.addParts(ORE.of(MaterialOreSet.GOLD)).addParts(ITEM_PURE_METAL)
.addParts(PLATE, DOUBLE_INGOT, WIRE, FINE_WIRE, HOT_INGOT).addParts(CABLE.of(CableTier.EV))
.addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, true, 128, 600)).addRecipes(StandardRecipes::apply)
.cancelRecipes("macerator/raw_metal").build());
MaterialRegistry.addMaterial(
new MaterialBuilder("kanthal", METALLIC, new BakableTargetColoramp(0xcfcb00, common("ingot"), template("kanthal_ingot")), HARD)
.addParts(TINY_DUST, DUST, PLATE, INGOT, NUGGET, WIRE, DOUBLE_INGOT, HOT_INGOT).addParts(COIL)
.addParts(BLOCK.of(MaterialBlockSet.COPPER)).addRecipes((ctx) -> SmeltingRecipes.applyBlastFurnace(ctx, true, 32, 400))
.addParts(CABLE.of(CableTier.HV)).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("iridium", SHINY, new BakableTargetColoramp(0xe1e6f5, common("ingot"), template("iridium_ingot")), VERY_HARD)
.addParts(BLOCK.of(MaterialBlockSet.DIAMOND)).addParts(ITEM_PURE_METAL).addParts(CURVED_PLATE)
.addParts(ORE.ofAll(10, 1, 16, MaterialOreSet.DIAMOND))
.addParts(MACHINE_CASING.of("quantum_machine_casing", 6000f))
.addParts(TANK.of(Integer.MAX_VALUE).withCustomPath("quantum_tank"))
.addParts(BARREL.of(Integer.MAX_VALUE).withCustomPath("quantum_barrel"))
.addParts(MACHINE_CASING_SPECIAL.of("plasma_handling_iridium_machine_casing", 6000f))
.addParts(MACHINE_CASING_PIPE.of(6000f))
.addParts(RAW_METAL.of(MaterialRawSet.IRIDIUM), PLATE)
.addRecipes(StandardRecipes::apply).addRecipes(SmeltingRecipes::apply)
.cancelRecipes("compressor/main")
.cancelRecipes("craft/tank")
.cancelRecipes("craft/barrel")
.cancelRecipes("assembler/tank")
.cancelRecipes("assembler/barrel").build());
MaterialRegistry.addMaterial(new MaterialBuilder("mozanite", STONE, DUST, 0x96248e, SOFT).addParts(CRUSHED_DUST, DUST, TINY_DUST)
.addParts(BLOCK.of(MaterialBlockSet.REDSTONE)).addParts(ORE.ofAll(UniformInt.of(1, 4), 2, 3, 24, MaterialOreSet.LAPIS))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("cadmium", DULL, 0x967224, SOFT)
.addParts(DUST, TINY_DUST, INGOT, PLATE, ROD, DOUBLE_INGOT,
BATTERY)
.addParts(
new RegularPart(FUEL_ROD.key)
.withRegister(
(registeringContext, partContext, part, itemPath1, itemId, itemTag) -> NuclearAbsorbable
.of(itemPath1, 1900, 0.5 * NuclearConstant.BASE_HEAT_CONDUCTION,
INeutronBehaviour.of(NuclearConstant.ScatteringType.HEAVY, NuclearConstant.CADMIUM,
1),
NuclearConstant.DESINTEGRATION_BY_ROD))
.withCustomFormattablePath("%s_control_rod"))
.addRecipes(StandardRecipes::apply, SmeltingRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("neodymium", STONE, DUST, 0x1d4506, SOFT).addParts(BLOCK.of(MaterialBlockSet.REDSTONE))
.addParts(DUST, TINY_DUST).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("yttrium", STONE, DUST, 0x135166, SOFT).addParts(BLOCK.of(MaterialBlockSet.REDSTONE))
.addParts(DUST, TINY_DUST).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(
new MaterialBuilder("superconductor", SHINY, new BakableTargetColoramp(0x86e3ec, common("ingot"), template("superconductor_ingot")),
HARD).addParts(TINY_DUST, DUST, PLATE, INGOT, NUGGET, WIRE, DOUBLE_INGOT, HOT_INGOT).addParts(COIL)
.addParts(CABLE.of(CableTier.SUPERCONDUCTOR)).addRecipes(StandardRecipes::apply)
.cancelRecipes("craft/cable", "packer/cable").build());
MaterialRegistry.addMaterial(
new MaterialBuilder("tungsten", METALLIC, new BakableTargetColoramp(0x8760ad, common("ingot"), template("tungsten_ingot")), VERY_HARD)
.addParts(RAW_METAL.ofAll(MaterialRawSet.COPPER))
.addParts(TINY_DUST, DUST, PLATE, INGOT, NUGGET, LARGE_PLATE, DOUBLE_INGOT, ROD)
.addParts(BLOCK.of(MaterialBlockSet.NETHERITE)).addParts(ORE.ofAll(6, 5, 20, MaterialOreSet.IRON))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry
.addMaterial(new MaterialBuilder("blastproof_alloy", METALLIC, 0x524c3a, VERY_HARD).addParts(INGOT, PLATE, LARGE_PLATE, CURVED_PLATE)
.addParts(MACHINE_CASING_SPECIAL.of("blastproof_casing", 6000f)).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("nuclear_alloy", METALLIC, 0x3d4d32, VERY_HARD).addParts(PLATE, LARGE_PLATE)
.addParts(MACHINE_CASING_SPECIAL.of("nuclear_casing", 6000f)).addParts(MACHINE_CASING_PIPE.of(6000f))
.addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("soldering_alloy", DULL, DUST, 0xffabc4bf, SOFT).addParts(DUST, TINY_DUST)
.addParts(BLOCK.of(MaterialBlockSet.REDSTONE)).addRecipes(StandardRecipes::apply).build());
MaterialRegistry.addMaterial(new MaterialBuilder("sulfur", DULL, DUST, 0xddb614, SOFT).addParts(DUST, TINY_DUST)
.addParts(BLOCK.of(MaterialBlockSet.REDSTONE)).addRecipes(StandardRecipes::apply).build());
}
/**
* Add material tags for special parts, like vanilla stuff
*/
private static void addExtraTags() {
MaterialHelper.registerItemTag("c:iron_blocks", JTag.tag().add(new ResourceLocation("minecraft:iron_block")));
MaterialHelper.registerItemTag("c:iron_ingots", JTag.tag().add(new ResourceLocation("minecraft:iron_ingot")));
MaterialHelper.registerItemTag("c:iron_nuggets", JTag.tag().add(new ResourceLocation("minecraft:iron_nugget")));
MaterialHelper.registerItemTag("c:iron_ores", JTag.tag().tag(new ResourceLocation("minecraft:iron_ores")));
MaterialHelper.registerItemTag("c:raw_iron_ores", JTag.tag().add(new ResourceLocation("minecraft:raw_iron")));
MaterialHelper.registerItemTag("c:raw_iron_blocks", JTag.tag().add(new ResourceLocation("minecraft:raw_iron_block")));
JTag copperBlocks = JTag.tag().add(new ResourceLocation("minecraft:copper_block")).add(new ResourceLocation("minecraft:waxed_copper_block"));
MaterialHelper.registerItemTag("c:copper_blocks", copperBlocks);
MaterialHelper.registerItemTag("c:copper_ingots", JTag.tag().add(new ResourceLocation("minecraft:copper_ingot")));
MaterialHelper.registerItemTag("c:copper_ores", JTag.tag().tag(new ResourceLocation("minecraft:copper_ores")));
MaterialHelper.registerItemTag("c:raw_copper_ores", JTag.tag().add(new ResourceLocation("minecraft:raw_copper")));
MaterialHelper.registerItemTag("c:raw_copper_blocks", JTag.tag().add(new ResourceLocation("minecraft:raw_copper_block")));
JTag goldOres = JTag.tag().tag(new ResourceLocation("minecraft:gold_ores")); // .add(new Identifier("minecraft:gilded_blackstone"));
MaterialHelper.registerItemTag("c:gold_blocks", JTag.tag().add(new ResourceLocation("minecraft:gold_block")));
MaterialHelper.registerItemTag("c:gold_ingots", JTag.tag().add(new ResourceLocation("minecraft:gold_ingot")));
MaterialHelper.registerItemTag("c:gold_nuggets", JTag.tag().add(new ResourceLocation("minecraft:gold_nugget")));
MaterialHelper.registerItemTag("c:gold_ores", goldOres);
MaterialHelper.registerItemTag("c:raw_gold_ores", JTag.tag().add(new ResourceLocation("minecraft:raw_gold")));
MaterialHelper.registerItemTag("c:raw_gold_blocks", JTag.tag().add(new ResourceLocation("minecraft:raw_gold_block")));
MaterialHelper.registerItemTag("c:coal_ores", JTag.tag().add(new ResourceLocation("minecraft:deepslate_coal_ore")));
MaterialHelper.registerItemTag("c:coal_blocks", JTag.tag().add(new ResourceLocation("minecraft:coal_block")));
MaterialHelper.registerItemTag("c:coal_ores", JTag.tag().tag(new ResourceLocation("minecraft:coal_ores")));
MaterialHelper.registerItemTag("c:redstone_ores", JTag.tag().tag(new ResourceLocation("minecraft:redstone_ores")));
MaterialHelper.registerItemTag("c:redstone_blocks", JTag.tag().add(new ResourceLocation("minecraft:redstone_block")));
MaterialHelper.registerItemTag("c:emerald_ores", JTag.tag().tag(new ResourceLocation("minecraft:emerald_ores")));
MaterialHelper.registerItemTag("c:emerald_blocks", JTag.tag().add(new ResourceLocation("minecraft:emerald_block")));
MaterialHelper.registerItemTag("c:diamond_ores", JTag.tag().tag(new ResourceLocation("minecraft:diamond_ores")));
MaterialHelper.registerItemTag("c:diamond_blocks", JTag.tag().add(new ResourceLocation("minecraft:diamond_block")));
MaterialHelper.registerItemTag("c:lapis_ores", JTag.tag().tag(new ResourceLocation("minecraft:lapis_ores")));
MaterialHelper.registerItemTag("c:lapis_blocks", JTag.tag().add(new ResourceLocation("minecraft:lapis_block")));
ResourceUtil.appendToTag("c:items/quartz_ores", "minecraft:nether_quartz_ore");
}
}
|
3e1aa7d436c4d7cf1dc1cda04a4b43771991e411 | 361 | java | Java | gulimall-order/src/main/java/top/codecrab/gulimall/order/dao/OrderSettingDao.java | Coco-king/guli-mall | 70a51e47f457a0f51f42a9edb95b0284d6997fa3 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/top/codecrab/gulimall/order/dao/OrderSettingDao.java | Coco-king/guli-mall | 70a51e47f457a0f51f42a9edb95b0284d6997fa3 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/top/codecrab/gulimall/order/dao/OrderSettingDao.java | Coco-king/guli-mall | 70a51e47f457a0f51f42a9edb95b0284d6997fa3 | [
"Apache-2.0"
] | null | null | null | 21.235294 | 73 | 0.783934 | 11,313 | package top.codecrab.gulimall.order.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.codecrab.gulimall.order.entity.OrderSettingEntity;
/**
* 订单配置信息
*
* @author codecrab
* @date 2021-05-28 22:46:28
*/
@Mapper
public interface OrderSettingDao extends BaseMapper<OrderSettingEntity> {
}
|
3e1aa815a0b0debd3f44989e9812490c7e6e81b9 | 3,250 | java | Java | module_one/src/main/java/com/idealbank/module_one/mvp/ui/adapter/SmartRefreshAdapter.java | xiangli19930605/xiangli | bd2499ad10e137c24e42faf54d98be7bc49c275d | [
"Apache-2.0"
] | 1 | 2019-01-31T08:14:28.000Z | 2019-01-31T08:14:28.000Z | module_one/src/main/java/com/idealbank/module_one/mvp/ui/adapter/SmartRefreshAdapter.java | xiangli19930605/xiangli | bd2499ad10e137c24e42faf54d98be7bc49c275d | [
"Apache-2.0"
] | null | null | null | module_one/src/main/java/com/idealbank/module_one/mvp/ui/adapter/SmartRefreshAdapter.java | xiangli19930605/xiangli | bd2499ad10e137c24e42faf54d98be7bc49c275d | [
"Apache-2.0"
] | null | null | null | 38.785714 | 121 | 0.673112 | 11,314 | /*
* Copyright 2017 JessYan
*
* 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.idealbank.module_one.mvp.ui.adapter;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.idealbank.module_one.R;
import com.idealbank.module_one.mvp.model.entity.GankItemBean;
import com.jess.arms.base.BaseHolder;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.ArmsUtils;
import java.util.List;
import me.jessyan.armscomponent.commonsdk.imgaEngine.config.CommonImageConfigImpl;
/**
* ================================================
* 展示 {@link DefaultAdapter} 的用法
* <p>
* Created by JessYan on 09/04/2016 12:57
* <a href="mailto:dycjh@example.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class SmartRefreshAdapter extends BaseQuickAdapter<GankItemBean, BaseViewHolder> {
private AppComponent mAppComponent;
private ImageLoader mImageLoader;//用于加载图片的管理类,默认使用 Glide,使用策略模式,可替换框架
public SmartRefreshAdapter(@Nullable List data) {
super(R.layout.gank_recycle_list, data);
}
@Override
protected void convert(BaseViewHolder helper, GankItemBean data) {
// GlideApp.with(mContext).load(item.getBgPicture()).into((ImageView) helper.getView(R.id.iv_item_smart_refresh));
// helper.setText(R.id.tv_item_smart_refresh, item.getName());
//可以在任何可以拿到 Context 的地方,拿到 AppComponent,从而得到用 Dagger 管理的单例对象
mAppComponent = ArmsUtils.obtainAppComponentFromContext(helper.itemView.getContext());
mImageLoader = mAppComponent.imageLoader();
ImageView mAvatar = (ImageView) helper.getView(R.id.iv_avatar);
if (!TextUtils.isEmpty(data.getUrl())) {
mImageLoader.loadImage(helper.itemView.getContext(),
CommonImageConfigImpl
.builder()
.url(data.getUrl())
.imageView(mAvatar)
.build());
// Glide.with(PoliceApplication.getContext())
// .load(AppConstant.URL_ENTERPRISE + item.getPhoto())
// .placeholder(R.drawable.ic_image_loading)
// .error(R.drawable.ic_default_adimage)
// .into(img);
} else {
// mAvatar.setImageResource(R.mipmap.gank_ic_logo);
}
}
} |
3e1aa8bb61c0fbd0d8922a32cde1d1b942f75311 | 10,930 | java | Java | plugins/git4idea/testFramework/git4idea/test/GitTestImpl.java | liveqmock/platform-tools-idea | 1c4b76108add6110898a7e3f8f70b970e352d3d4 | [
"Apache-2.0"
] | 2 | 2015-05-08T15:07:10.000Z | 2022-03-09T05:47:53.000Z | plugins/git4idea/testFramework/git4idea/test/GitTestImpl.java | lshain-android-source/tools-idea | b37108d841684bcc2af45a2539b75dd62c4e283c | [
"Apache-2.0"
] | null | null | null | plugins/git4idea/testFramework/git4idea/test/GitTestImpl.java | lshain-android-source/tools-idea | b37108d841684bcc2af45a2539b75dd62c4e283c | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 36.801347 | 139 | 0.683349 | 11,315 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.test;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitCommit;
import git4idea.commands.Git;
import git4idea.commands.GitCommandResult;
import git4idea.commands.GitImpl;
import git4idea.commands.GitLineHandlerListener;
import git4idea.push.GitPushSpec;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import static com.intellij.openapi.util.text.StringUtil.join;
import static git4idea.test.GitExecutor.cd;
import static git4idea.test.GitExecutor.git;
import static java.lang.String.format;
/**
* @author Kirill Likhodedov
*/
public class GitTestImpl implements Git {
@NotNull
@Override
public GitCommandResult init(@NotNull Project project, @NotNull VirtualFile root, @NotNull GitLineHandlerListener... listeners) {
return execute(root.getPath(), "init", listeners);
}
@NotNull
@Override
public Set<VirtualFile> untrackedFiles(@NotNull Project project, @NotNull VirtualFile root, @Nullable Collection<VirtualFile> files)
throws VcsException {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public Collection<VirtualFile> untrackedFilesNoChunk(@NotNull Project project,
@NotNull VirtualFile root,
@Nullable List<String> relativePaths) throws VcsException {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult clone(@NotNull Project project,
@NotNull File parentDirectory,
@NotNull String url,
@NotNull String clonedDirectoryName, @NotNull GitLineHandlerListener... progressListeners) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult config(@NotNull GitRepository repository, String... params) {
cd(repository);
String output = git("config " + join(params, " "));
int exitCode = output.trim().isEmpty() ? 1 : 0;
return new GitCommandResult(!output.contains("fatal") && exitCode == 0, exitCode, Collections.<String>emptyList(),
Arrays.asList(StringUtil.splitByLines(output)), null);
}
@NotNull
@Override
public GitCommandResult diff(@NotNull GitRepository repository, @NotNull List<String> parameters, @NotNull String range) {
return execute(repository, format("diff %s %s", join(parameters, " "), range));
}
@NotNull
@Override
public GitCommandResult checkAttr(@NotNull final GitRepository repository, @NotNull Collection<String> attributes,
@NotNull Collection<VirtualFile> files) {
cd(repository);
Collection<String> relativePaths = Collections2.transform(files, new Function<VirtualFile, String>() {
@Override
public String apply(VirtualFile input) {
return FileUtil.getRelativePath(repository.getRoot().getPath(), input.getPath(), '/');
}
});
String output = git("check-attr %s -- %s", join(attributes, " "), join(relativePaths, " "));
return commandResult(output);
}
@NotNull
@Override
public GitCommandResult stashSave(@NotNull GitRepository repository, @NotNull String message) {
return execute(repository, "stash save " + message);
}
@NotNull
@Override
public GitCommandResult stashPop(@NotNull GitRepository repository, @NotNull GitLineHandlerListener... listeners) {
return execute(repository, "stash pop");
}
@NotNull
@Override
public List<GitCommit> history(@NotNull GitRepository repository, @NotNull String range) {
return Collections.emptyList();
}
@NotNull
@Override
public GitCommandResult merge(@NotNull GitRepository repository, @NotNull String branchToMerge, @Nullable List<String> additionalParams,
@NotNull GitLineHandlerListener... listeners) {
String addParams = additionalParams == null ? "" : join(additionalParams, " ");
return execute(repository, format("merge %s %s", addParams, branchToMerge), listeners);
}
@NotNull
@Override
public GitCommandResult checkout(@NotNull GitRepository repository, @NotNull String reference, @Nullable String newBranch, boolean force,
@NotNull GitLineHandlerListener... listeners) {
return execute(repository, format("checkout %s %s %s",
force ? "--force" : "",
newBranch != null ? " -b " + newBranch : "", reference), listeners);
}
@NotNull
@Override
public GitCommandResult checkoutNewBranch(@NotNull GitRepository repository, @NotNull String branchName,
@Nullable GitLineHandlerListener listener) {
return execute(repository, "checkout -b " + branchName, listener);
}
@NotNull
@Override
public GitCommandResult branchDelete(@NotNull GitRepository repository, @NotNull String branchName, boolean force,
@NotNull GitLineHandlerListener... listeners) {
return execute(repository, format("branch %s %s", force ? "-D" : "-d", branchName), listeners);
}
@NotNull
@Override
public GitCommandResult branchContains(@NotNull GitRepository repository, @NotNull String commit) {
return execute(repository, "branch --contains " + commit);
}
@NotNull
@Override
public GitCommandResult branchCreate(@NotNull GitRepository repository, @NotNull String branchName) {
return execute(repository, "branch " + branchName);
}
@NotNull
@Override
public GitCommandResult resetHard(@NotNull GitRepository repository, @NotNull String revision) {
return execute(repository, "reset --hard " + revision);
}
@NotNull
@Override
public GitCommandResult resetMerge(@NotNull GitRepository repository, @Nullable String revision) {
return execute(repository, "reset --merge " + revision);
}
@NotNull
@Override
public GitCommandResult tip(@NotNull GitRepository repository, @NotNull String branchName) {
return execute(repository, "rev-list -1 " + branchName);
}
@NotNull
@Override
public GitCommandResult push(@NotNull GitRepository repository, @NotNull String remote, @NotNull String url, @NotNull String spec,
boolean updateTracking, @NotNull GitLineHandlerListener... listeners) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult push(@NotNull GitRepository repository, @NotNull String remote, @NotNull String url, @NotNull String spec,
@NotNull GitLineHandlerListener... listeners) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult push(@NotNull GitRepository repository,
@NotNull GitPushSpec spec, @NotNull String url, @NotNull GitLineHandlerListener... listeners) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult show(@NotNull GitRepository repository, @NotNull String... params) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public GitCommandResult cherryPick(@NotNull GitRepository repository,
@NotNull String hash,
boolean autoCommit,
@NotNull GitLineHandlerListener... listeners) {
return execute(repository, format("cherry-pick -x %s %s", autoCommit ? "" : "-n", hash), listeners);
}
@NotNull
@Override
public GitCommandResult getUnmergedFiles(@NotNull GitRepository repository) {
return execute(repository, "ls-files --unmerged");
}
@NotNull
@Override
public GitCommandResult createNewTag(@NotNull GitRepository repository,
@NotNull String tagName,
@Nullable GitLineHandlerListener listener,
@NotNull String reference) {
throw new UnsupportedOperationException();
}
private static GitCommandResult commandResult(String output) {
List<String> err = new ArrayList<String>();
List<String> out = new ArrayList<String>();
for (String line : output.split("\n")) {
if (isError(line)) {
err.add(line);
}
else {
out.add(line);
}
}
boolean success = err.isEmpty();
return new GitCommandResult(success, 0, err, out, null);
}
private static boolean isError(String s) {
// we don't want to make that method public, since it is reused only in the test.
try {
Method m = GitImpl.class.getDeclaredMethod("isError", String.class);
m.setAccessible(true);
return (Boolean) m.invoke(null, s);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
private static void feedOutput(String output, GitLineHandlerListener... listeners) {
for (GitLineHandlerListener listener : listeners) {
String[] split = output.split("\n");
for (String line : split) {
listener.onLineAvailable(line, ProcessOutputTypes.STDERR);
}
}
}
private static GitCommandResult execute(GitRepository repository, String operation, GitLineHandlerListener... listeners) {
return execute(repository.getRoot().getPath(), operation, listeners);
}
private static GitCommandResult execute(String workingDir, String operation, GitLineHandlerListener... listeners) {
cd(workingDir);
String out = git(operation);
feedOutput(out, listeners);
return commandResult(out);
}
}
|
3e1aa8c462b45d6c4d2c6444302654c48c3e2a89 | 1,681 | java | Java | ambari-server/src/main/java/org/apache/ambari/server/controller/UserAuthenticationSourceRequestUpdateSwagger.java | MacgradyHuang/ApacheAmbari | 961ce825b9e2681bf21819147b0ee72438e0b04a | [
"Apache-2.0"
] | 1,664 | 2015-01-03T09:35:21.000Z | 2022-03-31T04:55:24.000Z | ambari-server/src/main/java/org/apache/ambari/server/controller/UserAuthenticationSourceRequestUpdateSwagger.java | MacgradyHuang/ApacheAmbari | 961ce825b9e2681bf21819147b0ee72438e0b04a | [
"Apache-2.0"
] | 3,018 | 2015-02-19T20:16:10.000Z | 2021-11-13T20:47:48.000Z | ambari-server/src/main/java/org/apache/ambari/server/controller/UserAuthenticationSourceRequestUpdateSwagger.java | MacgradyHuang/ApacheAmbari | 961ce825b9e2681bf21819147b0ee72438e0b04a | [
"Apache-2.0"
] | 1,673 | 2015-01-06T14:14:42.000Z | 2022-03-31T07:22:30.000Z | 42.025 | 108 | 0.800714 | 11,316 | /*
* 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.ambari.server.controller;
import org.apache.ambari.server.controller.internal.UserAuthenticationSourceResourceProvider;
import io.swagger.annotations.ApiModelProperty;
/**
* Interface to help correct Swagger documentation generation
*/
public interface UserAuthenticationSourceRequestUpdateSwagger extends ApiModel {
@ApiModelProperty(name = UserAuthenticationSourceResourceProvider.AUTHENTICATION_SOURCE_RESOURCE_CATEGORY)
UserAuthenticationSourceRequestUpdateInfo getUpdateUserAuthenticationSourceRequest();
interface UserAuthenticationSourceRequestUpdateInfo {
@ApiModelProperty(name = UserAuthenticationSourceResourceProvider.KEY_PROPERTY_ID, required = true)
public String getKey();
@ApiModelProperty(name = UserAuthenticationSourceResourceProvider.OLD_KEY_PROPERTY_ID, required = false)
public String getOldKey();
}
} |
3e1aa912851f15f4110d76b4906e8c782dd73786 | 1,266 | java | Java | src/utilities/PageManager.java | NolanC33/wikiCrawler | de068c311fff83ee66402da402308ca53c5da0df | [
"MIT"
] | null | null | null | src/utilities/PageManager.java | NolanC33/wikiCrawler | de068c311fff83ee66402da402308ca53c5da0df | [
"MIT"
] | 1 | 2018-02-10T03:04:58.000Z | 2018-02-10T03:04:58.000Z | src/utilities/PageManager.java | NolanC33/wikiCrawler | de068c311fff83ee66402da402308ca53c5da0df | [
"MIT"
] | null | null | null | 26.375 | 122 | 0.724329 | 11,317 | package utilities;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Hashtable;
import exceptions.BadUrlException;
import exceptions.NotWikipediaURLException;
import exceptions.PageParseException;
public class PageManager {
private static Hashtable<String, WikipediaPage> PageTable = new Hashtable<String, WikipediaPage>();
public static WikipediaPage CreatePage(String url) throws BadUrlException, NotWikipediaURLException, PageParseException {
URL u = createAndValidateWikipediaURL(url);
return new WikipediaPage(u);
}
private static URL createAndValidateWikipediaURL(String url) throws BadUrlException, NotWikipediaURLException {
if (url == null) {
throw new BadUrlException("Argument url is null");
}
URL u;
try {
u = new URL(url);
u.toURI();
} catch (MalformedURLException e) {
throw new BadUrlException("url \"" + url + "\" was malformed");
} catch (URISyntaxException e) {
throw new BadUrlException("A valid URL could not be parsed from \"" + url + "\"");
}
if (url.startsWith("https://en.wikipedia.org/") == false) {
throw new NotWikipediaURLException("The url \"" + url + "\" is not a Wikipedia URL");
}
return u;
}
}
|
3e1aaa7ca18fde1bab1beba5fe4a13bc0dd2fa3d | 4,934 | java | Java | src/main/java/com/easypick/admin/entity/MovieReview.java | b20vineeth/mallureport-admin | ed5259e6c5e32f292fa72f0b7c20bc8bdae284a7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/easypick/admin/entity/MovieReview.java | b20vineeth/mallureport-admin | ed5259e6c5e32f292fa72f0b7c20bc8bdae284a7 | [
"Apache-2.0"
] | 9 | 2020-03-29T12:49:15.000Z | 2022-02-26T19:42:13.000Z | src/main/java/com/easypick/admin/entity/MovieReview.java | b20vineeth/mallureport-admin | ed5259e6c5e32f292fa72f0b7c20bc8bdae284a7 | [
"Apache-2.0"
] | null | null | null | 23.607656 | 92 | 0.698622 | 11,318 | package com.easypick.admin.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.easypick.admin.vo.MovieReviewVo;
import com.easypick.framework.utility.commonUtility.StringUitity;
import com.easypick.framework.utility.vo.AbstractVo;
import com.easypick.web.events.vo.ReviewDataVo;
@Entity
@Table(name = "movrev")
public class MovieReview {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "mov_re_id")
private Integer movieReviewId;
@Column(name = "title")
private String title;
@Column(name = "movrevdat", columnDefinition = "DATE")
private Date reviewDate;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "movid", nullable = false)
private Movie movie;
@Column(name = "description", columnDefinition = "LONGTEXT")
private String description;
@Column(name = "short_desc" , length = 600)
private String shortDesc;
@Column(name = "thumbnail")
private String thumbnail;
@Column(name = "tag")
private String tag;
@Column(name = "url", length = 150)
private String url;
@Column(name = "status", length = 1)
private String status = "Y";
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public Integer getMovieReviewId() {
return movieReviewId;
}
public void setMovieReviewId(Integer movieReviewId) {
this.movieReviewId = movieReviewId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReviewDate() {
return reviewDate;
}
public void setReviewDate(Date reviewDate) {
this.reviewDate = reviewDate;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static MovieReviewVo formateMovieReviewVo(MovieReview movie) {
MovieReviewVo vo = new MovieReviewVo();
vo.setMovieId(movie.getMovie().getMovieId());
vo.setMovieName(movie.getMovie().getMovieName());
vo.setTitle(movie.getTitle());
vo.setShortDesc(movie.getShortDesc());
vo.setDescription(movie.getDescription());
vo.setTag(movie.getTag());
vo.setMovieReviewId(movie.getMovieReviewId());
return vo;
}
public static MovieReview populateMovieReviewVo(MovieReviewVo vo) {
MovieReview review = new MovieReview();
if (vo.getMovieReviewId() != 0)
review.setMovieReviewId(vo.getMovieReviewId());
review.setReviewDate(new Date());
review.setShortDesc(vo.getShortDesc());
review.setDescription(vo.getDescription());
review.setStatus("Y");
review.setTag(vo.getTag());
review.setThumbnail(vo.getThumbnail());
review.setUrl(StringUitity.convertUrl(vo.getTitle()));
review.setTitle(vo.getTitle());
Movie movie = new Movie();
movie.setMovieId(vo.getMovieId());
review.setMovie(movie);
return review;
}
public static List<? extends AbstractVo> formateMovieReviews(List<MovieReview> movieVos) {
List<MovieReviewVo> movieReviewVo = new ArrayList<>();
MovieReviewVo vo = null;
for (MovieReview movie : movieVos) {
vo = new MovieReviewVo();
vo.setShortDesc(movie.getShortDesc());
vo.setTag(movie.getTag());
vo.setTitle(movie.getTitle());
vo.setTag(movie.getTag());
movieReviewVo.add(vo);
}
return movieReviewVo;
}
public static List<ReviewDataVo> formateReviewDataVo(List<MovieReview> movieReviews) {
List<ReviewDataVo> movieReviewVos = new ArrayList<>();
ReviewDataVo vo = null;
for (MovieReview movie : movieReviews) {
vo = new ReviewDataVo();
vo.setShortDesc(movie.getShortDesc());
vo.setTitle(movie.getTitle());
vo.setThumbnail(movie.getThumbnail());
vo.setUrl(movie.getUrl());
movieReviewVos.add(vo);
}
return movieReviewVos;
}
}
|
3e1aaaabd3b7433454c7f7c16f41a019976bdfc3 | 4,256 | java | Java | testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 42.989899 | 123 | 0.62735 | 11,319 | package com.baeldung.junit5.templates;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(UserIdGeneratorTestInvocationContextProvider.class);
@Override
public boolean supportsTestTemplate(ExtensionContext extensionContext) {
return true;
}
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext extensionContext) {
boolean featureDisabled = false;
boolean featureEnabled = true;
return Stream.of(
featureDisabledContext(
new UserIdGeneratorTestCase(
"Given feature switch disabled When user name is John Smith Then generated userid is JSmith",
featureDisabled, "John", "Smith", "JSmith")),
featureEnabledContext(
new UserIdGeneratorTestCase(
"Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith",
featureEnabled, "John", "Smith", "baelJSmith"))
);
}
private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) {
return new TestTemplateInvocationContext() {
@Override
public String getDisplayName(int invocationIndex) {
return userIdGeneratorTestCase.getDisplayName();
}
@Override
public List<Extension> getAdditionalExtensions() {
return asList(
new GenericTypedParameterResolver(userIdGeneratorTestCase),
new BeforeTestExecutionCallback() {
@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
LOGGER.debug("BeforeTestExecutionCallback:Disabled context");
}
},
new AfterTestExecutionCallback() {
@Override
public void afterTestExecution(ExtensionContext extensionContext) {
LOGGER.debug("AfterTestExecutionCallback:Disabled context");
}
});
}
};
}
private TestTemplateInvocationContext featureEnabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) {
return new TestTemplateInvocationContext() {
@Override
public String getDisplayName(int invocationIndex) {
return userIdGeneratorTestCase.getDisplayName();
}
@Override
public List<Extension> getAdditionalExtensions() {
return asList(
new GenericTypedParameterResolver(userIdGeneratorTestCase),
new DisabledOnQAEnvironmentExtension(),
new BeforeEachCallback() {
@Override
public void beforeEach(ExtensionContext extensionContext) {
LOGGER.debug("BeforeEachCallback:Enabled context");
}
},
new AfterEachCallback() {
@Override
public void afterEach(ExtensionContext extensionContext) {
LOGGER.debug("AfterEachCallback:Enabled context");
}
});
}
};
}
}
|
3e1aabeb4063dd9699ae2205b3386e9bac5754be | 23,987 | java | Java | libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java | mankeyl/elasticsearch | e14141fd830a46bcd24c2d8b7a32170bc2b4e602 | [
"Apache-2.0"
] | null | null | null | libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java | mankeyl/elasticsearch | e14141fd830a46bcd24c2d8b7a32170bc2b4e602 | [
"Apache-2.0"
] | null | null | null | libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java | mankeyl/elasticsearch | e14141fd830a46bcd24c2d8b7a32170bc2b4e602 | [
"Apache-2.0"
] | null | null | null | 38.440705 | 138 | 0.54688 | 11,320 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.geometry.utils;
import org.elasticsearch.geometry.Circle;
import org.elasticsearch.geometry.Geometry;
import org.elasticsearch.geometry.GeometryCollection;
import org.elasticsearch.geometry.GeometryVisitor;
import org.elasticsearch.geometry.Line;
import org.elasticsearch.geometry.LinearRing;
import org.elasticsearch.geometry.MultiLine;
import org.elasticsearch.geometry.MultiPoint;
import org.elasticsearch.geometry.MultiPolygon;
import org.elasticsearch.geometry.Point;
import org.elasticsearch.geometry.Polygon;
import org.elasticsearch.geometry.Rectangle;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Utility class for converting to and from WKT
*/
public class WellKnownText {
public static final String EMPTY = "EMPTY";
public static final String SPACE = " ";
public static final String LPAREN = "(";
public static final String RPAREN = ")";
public static final String COMMA = ",";
public static final String NAN = "NaN";
private static final String NUMBER = "<NUMBER>";
private static final String EOF = "END-OF-STREAM";
private static final String EOL = "END-OF-LINE";
private WellKnownText() {}
public static String toWKT(Geometry geometry) {
StringBuilder builder = new StringBuilder();
toWKT(geometry, builder);
return builder.toString();
}
private static void toWKT(Geometry geometry, StringBuilder sb) {
sb.append(getWKTName(geometry));
sb.append(SPACE);
if (geometry.isEmpty()) {
sb.append(EMPTY);
} else {
geometry.visit(new GeometryVisitor<Void, RuntimeException>() {
@Override
public Void visit(Circle circle) {
sb.append(LPAREN);
visitPoint(circle.getX(), circle.getY(), Double.NaN);
sb.append(SPACE);
sb.append(circle.getRadiusMeters());
if (circle.hasZ()) {
sb.append(SPACE);
sb.append(circle.getZ());
}
sb.append(RPAREN);
return null;
}
@Override
public Void visit(GeometryCollection<?> collection) {
if (collection.size() == 0) {
sb.append(EMPTY);
} else {
sb.append(LPAREN);
toWKT(collection.get(0), sb);
for (int i = 1; i < collection.size(); ++i) {
sb.append(COMMA);
toWKT(collection.get(i), sb);
}
sb.append(RPAREN);
}
return null;
}
@Override
public Void visit(Line line) {
sb.append(LPAREN);
visitPoint(line.getX(0), line.getY(0), line.getZ(0));
for (int i = 1; i < line.length(); ++i) {
sb.append(COMMA);
sb.append(SPACE);
visitPoint(line.getX(i), line.getY(i), line.getZ(i));
}
sb.append(RPAREN);
return null;
}
@Override
public Void visit(LinearRing ring) {
throw new IllegalArgumentException("Linear ring is not supported by WKT");
}
@Override
public Void visit(MultiLine multiLine) {
visitCollection(multiLine);
return null;
}
@Override
public Void visit(MultiPoint multiPoint) {
if (multiPoint.isEmpty()) {
sb.append(EMPTY);
return null;
}
// walk through coordinates:
sb.append(LPAREN);
visitPoint(multiPoint.get(0).getX(), multiPoint.get(0).getY(), multiPoint.get(0).getZ());
for (int i = 1; i < multiPoint.size(); ++i) {
sb.append(COMMA);
sb.append(SPACE);
Point point = multiPoint.get(i);
visitPoint(point.getX(), point.getY(), point.getZ());
}
sb.append(RPAREN);
return null;
}
@Override
public Void visit(MultiPolygon multiPolygon) {
visitCollection(multiPolygon);
return null;
}
@Override
public Void visit(Point point) {
if (point.isEmpty()) {
sb.append(EMPTY);
} else {
sb.append(LPAREN);
visitPoint(point.getX(), point.getY(), point.getZ());
sb.append(RPAREN);
}
return null;
}
private void visitPoint(double lon, double lat, double alt) {
sb.append(lon).append(SPACE).append(lat);
if (Double.isNaN(alt) == false) {
sb.append(SPACE).append(alt);
}
}
private void visitCollection(GeometryCollection<?> collection) {
if (collection.size() == 0) {
sb.append(EMPTY);
} else {
sb.append(LPAREN);
collection.get(0).visit(this);
for (int i = 1; i < collection.size(); ++i) {
sb.append(COMMA);
collection.get(i).visit(this);
}
sb.append(RPAREN);
}
}
@Override
public Void visit(Polygon polygon) {
sb.append(LPAREN);
visit((Line) polygon.getPolygon());
int numberOfHoles = polygon.getNumberOfHoles();
for (int i = 0; i < numberOfHoles; ++i) {
sb.append(", ");
visit((Line) polygon.getHole(i));
}
sb.append(RPAREN);
return null;
}
@Override
public Void visit(Rectangle rectangle) {
sb.append(LPAREN);
// minX, maxX, maxY, minY
sb.append(rectangle.getMinX());
sb.append(COMMA);
sb.append(SPACE);
sb.append(rectangle.getMaxX());
sb.append(COMMA);
sb.append(SPACE);
sb.append(rectangle.getMaxY());
sb.append(COMMA);
sb.append(SPACE);
sb.append(rectangle.getMinY());
if (rectangle.hasZ()) {
sb.append(COMMA);
sb.append(SPACE);
sb.append(rectangle.getMinZ());
sb.append(COMMA);
sb.append(SPACE);
sb.append(rectangle.getMaxZ());
}
sb.append(RPAREN);
return null;
}
});
}
}
public static Geometry fromWKT(GeometryValidator validator, boolean coerce, String wkt) throws IOException, ParseException {
StringReader reader = new StringReader(wkt);
try {
// setup the tokenizer; configured to read words w/o numbers
StreamTokenizer tokenizer = new StreamTokenizer(reader);
tokenizer.resetSyntax();
tokenizer.wordChars('a', 'z');
tokenizer.wordChars('A', 'Z');
tokenizer.wordChars(128 + 32, 255);
tokenizer.wordChars('0', '9');
tokenizer.wordChars('-', '-');
tokenizer.wordChars('+', '+');
tokenizer.wordChars('.', '.');
tokenizer.whitespaceChars(' ', ' ');
tokenizer.whitespaceChars('\t', '\t');
tokenizer.whitespaceChars('\r', '\r');
tokenizer.whitespaceChars('\n', '\n');
tokenizer.commentChar('#');
Geometry geometry = parseGeometry(tokenizer, coerce);
validator.validate(geometry);
return geometry;
} finally {
reader.close();
}
}
/**
* parse geometry from the stream tokenizer
*/
private static Geometry parseGeometry(StreamTokenizer stream, boolean coerce) throws IOException, ParseException {
final String type = nextWord(stream).toLowerCase(Locale.ROOT);
switch (type) {
case "point":
return parsePoint(stream);
case "multipoint":
return parseMultiPoint(stream);
case "linestring":
return parseLine(stream);
case "multilinestring":
return parseMultiLine(stream);
case "polygon":
return parsePolygon(stream, coerce);
case "multipolygon":
return parseMultiPolygon(stream, coerce);
case "bbox":
return parseBBox(stream);
case "geometrycollection":
return parseGeometryCollection(stream, coerce);
case "circle": // Not part of the standard, but we need it for internal serialization
return parseCircle(stream);
}
throw new IllegalArgumentException("Unknown geometry type: " + type);
}
private static GeometryCollection<Geometry> parseGeometryCollection(StreamTokenizer stream, boolean coerce) throws IOException,
ParseException {
if (nextEmptyOrOpen(stream).equals(EMPTY)) {
return GeometryCollection.EMPTY;
}
List<Geometry> shapes = new ArrayList<>();
shapes.add(parseGeometry(stream, coerce));
while (nextCloserOrComma(stream).equals(COMMA)) {
shapes.add(parseGeometry(stream, coerce));
}
return new GeometryCollection<>(shapes);
}
private static Point parsePoint(StreamTokenizer stream) throws IOException, ParseException {
if (nextEmptyOrOpen(stream).equals(EMPTY)) {
return Point.EMPTY;
}
double lon = nextNumber(stream);
double lat = nextNumber(stream);
Point pt;
if (isNumberNext(stream)) {
pt = new Point(lon, lat, nextNumber(stream));
} else {
pt = new Point(lon, lat);
}
nextCloser(stream);
return pt;
}
private static void parseCoordinates(StreamTokenizer stream, ArrayList<Double> lats, ArrayList<Double> lons, ArrayList<Double> alts)
throws IOException, ParseException {
parseCoordinate(stream, lats, lons, alts);
while (nextCloserOrComma(stream).equals(COMMA)) {
parseCoordinate(stream, lats, lons, alts);
}
}
private static void parseCoordinate(StreamTokenizer stream, ArrayList<Double> lats, ArrayList<Double> lons, ArrayList<Double> alts)
throws IOException, ParseException {
lons.add(nextNumber(stream));
lats.add(nextNumber(stream));
if (isNumberNext(stream)) {
alts.add(nextNumber(stream));
}
if (alts.isEmpty() == false && alts.size() != lons.size()) {
throw new ParseException("coordinate dimensions do not match: " + tokenString(stream), stream.lineno());
}
}
private static MultiPoint parseMultiPoint(StreamTokenizer stream) throws IOException, ParseException {
String token = nextEmptyOrOpen(stream);
if (token.equals(EMPTY)) {
return MultiPoint.EMPTY;
}
ArrayList<Double> lats = new ArrayList<>();
ArrayList<Double> lons = new ArrayList<>();
ArrayList<Double> alts = new ArrayList<>();
ArrayList<Point> points = new ArrayList<>();
parseCoordinates(stream, lats, lons, alts);
for (int i = 0; i < lats.size(); i++) {
if (alts.isEmpty()) {
points.add(new Point(lons.get(i), lats.get(i)));
} else {
points.add(new Point(lons.get(i), lats.get(i), alts.get(i)));
}
}
return new MultiPoint(Collections.unmodifiableList(points));
}
private static Line parseLine(StreamTokenizer stream) throws IOException, ParseException {
String token = nextEmptyOrOpen(stream);
if (token.equals(EMPTY)) {
return Line.EMPTY;
}
ArrayList<Double> lats = new ArrayList<>();
ArrayList<Double> lons = new ArrayList<>();
ArrayList<Double> alts = new ArrayList<>();
parseCoordinates(stream, lats, lons, alts);
if (alts.isEmpty()) {
return new Line(toArray(lons), toArray(lats));
} else {
return new Line(toArray(lons), toArray(lats), toArray(alts));
}
}
private static MultiLine parseMultiLine(StreamTokenizer stream) throws IOException, ParseException {
String token = nextEmptyOrOpen(stream);
if (token.equals(EMPTY)) {
return MultiLine.EMPTY;
}
ArrayList<Line> lines = new ArrayList<>();
lines.add(parseLine(stream));
while (nextCloserOrComma(stream).equals(COMMA)) {
lines.add(parseLine(stream));
}
return new MultiLine(Collections.unmodifiableList(lines));
}
private static LinearRing parsePolygonHole(StreamTokenizer stream, boolean coerce) throws IOException, ParseException {
nextOpener(stream);
ArrayList<Double> lats = new ArrayList<>();
ArrayList<Double> lons = new ArrayList<>();
ArrayList<Double> alts = new ArrayList<>();
parseCoordinates(stream, lats, lons, alts);
closeLinearRingIfCoerced(lats, lons, alts, coerce);
if (alts.isEmpty()) {
return new LinearRing(toArray(lons), toArray(lats));
} else {
return new LinearRing(toArray(lons), toArray(lats), toArray(alts));
}
}
private static Polygon parsePolygon(StreamTokenizer stream, boolean coerce) throws IOException, ParseException {
if (nextEmptyOrOpen(stream).equals(EMPTY)) {
return Polygon.EMPTY;
}
nextOpener(stream);
ArrayList<Double> lats = new ArrayList<>();
ArrayList<Double> lons = new ArrayList<>();
ArrayList<Double> alts = new ArrayList<>();
parseCoordinates(stream, lats, lons, alts);
ArrayList<LinearRing> holes = new ArrayList<>();
while (nextCloserOrComma(stream).equals(COMMA)) {
holes.add(parsePolygonHole(stream, coerce));
}
closeLinearRingIfCoerced(lats, lons, alts, coerce);
LinearRing shell;
if (alts.isEmpty()) {
shell = new LinearRing(toArray(lons), toArray(lats));
} else {
shell = new LinearRing(toArray(lons), toArray(lats), toArray(alts));
}
if (holes.isEmpty()) {
return new Polygon(shell);
} else {
return new Polygon(shell, Collections.unmodifiableList(holes));
}
}
/**
* Treats supplied arrays as coordinates of a linear ring. If the ring is not closed and coerce is set to true,
* the first set of coordinates (lat, lon and alt if available) are added to the end of the arrays.
*/
private static void closeLinearRingIfCoerced(ArrayList<Double> lats, ArrayList<Double> lons, ArrayList<Double> alts, boolean coerce) {
if (coerce && lats.isEmpty() == false && lons.isEmpty() == false) {
int last = lats.size() - 1;
if (lats.get(0).equals(lats.get(last)) == false
|| lons.get(0).equals(lons.get(last)) == false
|| (alts.isEmpty() == false && alts.get(0).equals(alts.get(last)) == false)) {
lons.add(lons.get(0));
lats.add(lats.get(0));
if (alts.isEmpty() == false) {
alts.add(alts.get(0));
}
}
}
}
private static MultiPolygon parseMultiPolygon(StreamTokenizer stream, boolean coerce) throws IOException, ParseException {
String token = nextEmptyOrOpen(stream);
if (token.equals(EMPTY)) {
return MultiPolygon.EMPTY;
}
ArrayList<Polygon> polygons = new ArrayList<>();
polygons.add(parsePolygon(stream, coerce));
while (nextCloserOrComma(stream).equals(COMMA)) {
polygons.add(parsePolygon(stream, coerce));
}
return new MultiPolygon(Collections.unmodifiableList(polygons));
}
private static Rectangle parseBBox(StreamTokenizer stream) throws IOException, ParseException {
if (nextEmptyOrOpen(stream).equals(EMPTY)) {
return Rectangle.EMPTY;
}
// TODO: Add 3D support
double minLon = nextNumber(stream);
nextComma(stream);
double maxLon = nextNumber(stream);
nextComma(stream);
double maxLat = nextNumber(stream);
nextComma(stream);
double minLat = nextNumber(stream);
nextCloser(stream);
return new Rectangle(minLon, maxLon, maxLat, minLat);
}
private static Circle parseCircle(StreamTokenizer stream) throws IOException, ParseException {
if (nextEmptyOrOpen(stream).equals(EMPTY)) {
return Circle.EMPTY;
}
double lon = nextNumber(stream);
double lat = nextNumber(stream);
double radius = nextNumber(stream);
double alt = Double.NaN;
if (isNumberNext(stream)) {
alt = nextNumber(stream);
}
Circle circle = new Circle(lon, lat, alt, radius);
nextCloser(stream);
return circle;
}
/**
* next word in the stream
*/
private static String nextWord(StreamTokenizer stream) throws ParseException, IOException {
switch (stream.nextToken()) {
case StreamTokenizer.TT_WORD:
final String word = stream.sval;
return word.equalsIgnoreCase(EMPTY) ? EMPTY : word;
case '(':
return LPAREN;
case ')':
return RPAREN;
case ',':
return COMMA;
}
throw new ParseException("expected word but found: " + tokenString(stream), stream.lineno());
}
private static double nextNumber(StreamTokenizer stream) throws IOException, ParseException {
if (stream.nextToken() == StreamTokenizer.TT_WORD) {
if (stream.sval.equalsIgnoreCase(NAN)) {
return Double.NaN;
} else {
try {
return Double.parseDouble(stream.sval);
} catch (NumberFormatException e) {
throw new ParseException("invalid number found: " + stream.sval, stream.lineno());
}
}
}
throw new ParseException("expected number but found: " + tokenString(stream), stream.lineno());
}
private static String tokenString(StreamTokenizer stream) {
switch (stream.ttype) {
case StreamTokenizer.TT_WORD:
return stream.sval;
case StreamTokenizer.TT_EOF:
return EOF;
case StreamTokenizer.TT_EOL:
return EOL;
case StreamTokenizer.TT_NUMBER:
return NUMBER;
}
return "'" + (char) stream.ttype + "'";
}
private static boolean isNumberNext(StreamTokenizer stream) throws IOException {
final int type = stream.nextToken();
stream.pushBack();
return type == StreamTokenizer.TT_WORD;
}
private static String nextEmptyOrOpen(StreamTokenizer stream) throws IOException, ParseException {
final String next = nextWord(stream);
if (next.equals(EMPTY) || next.equals(LPAREN)) {
return next;
}
throw new ParseException("expected " + EMPTY + " or " + LPAREN + " but found: " + tokenString(stream), stream.lineno());
}
private static String nextCloser(StreamTokenizer stream) throws IOException, ParseException {
if (nextWord(stream).equals(RPAREN)) {
return RPAREN;
}
throw new ParseException("expected " + RPAREN + " but found: " + tokenString(stream), stream.lineno());
}
private static String nextComma(StreamTokenizer stream) throws IOException, ParseException {
if (nextWord(stream).equals(COMMA)) {
return COMMA;
}
throw new ParseException("expected " + COMMA + " but found: " + tokenString(stream), stream.lineno());
}
private static String nextOpener(StreamTokenizer stream) throws IOException, ParseException {
if (nextWord(stream).equals(LPAREN)) {
return LPAREN;
}
throw new ParseException("expected " + LPAREN + " but found: " + tokenString(stream), stream.lineno());
}
private static String nextCloserOrComma(StreamTokenizer stream) throws IOException, ParseException {
String token = nextWord(stream);
if (token.equals(COMMA) || token.equals(RPAREN)) {
return token;
}
throw new ParseException("expected " + COMMA + " or " + RPAREN + " but found: " + tokenString(stream), stream.lineno());
}
private static String getWKTName(Geometry geometry) {
return geometry.visit(new GeometryVisitor<String, RuntimeException>() {
@Override
public String visit(Circle circle) {
return "CIRCLE";
}
@Override
public String visit(GeometryCollection<?> collection) {
return "GEOMETRYCOLLECTION";
}
@Override
public String visit(Line line) {
return "LINESTRING";
}
@Override
public String visit(LinearRing ring) {
throw new UnsupportedOperationException("line ring cannot be serialized using WKT");
}
@Override
public String visit(MultiLine multiLine) {
return "MULTILINESTRING";
}
@Override
public String visit(MultiPoint multiPoint) {
return "MULTIPOINT";
}
@Override
public String visit(MultiPolygon multiPolygon) {
return "MULTIPOLYGON";
}
@Override
public String visit(Point point) {
return "POINT";
}
@Override
public String visit(Polygon polygon) {
return "POLYGON";
}
@Override
public String visit(Rectangle rectangle) {
return "BBOX";
}
});
}
private static double[] toArray(ArrayList<Double> doubles) {
return doubles.stream().mapToDouble(i -> i).toArray();
}
}
|
3e1aad10405775e3eea2d69f57be2d4d020e1194 | 621 | java | Java | shiro-spring-boot/src/main/java/com/hua/modules/sys/oauth2/OAuth2Token.java | dearcode2018/auth-entire | b0988c6e924c790108c6f6ca8b418220bf0500bb | [
"Apache-2.0"
] | null | null | null | shiro-spring-boot/src/main/java/com/hua/modules/sys/oauth2/OAuth2Token.java | dearcode2018/auth-entire | b0988c6e924c790108c6f6ca8b418220bf0500bb | [
"Apache-2.0"
] | null | null | null | shiro-spring-boot/src/main/java/com/hua/modules/sys/oauth2/OAuth2Token.java | dearcode2018/auth-entire | b0988c6e924c790108c6f6ca8b418220bf0500bb | [
"Apache-2.0"
] | null | null | null | 16.864865 | 57 | 0.653846 | 11,321 | /**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.hua.modules.sys.oauth2;
import org.apache.shiro.authc.AuthenticationToken;
/**
* token
*
* @author Mark envkt@example.com
*/
public class OAuth2Token implements AuthenticationToken {
private static final long serialVersionUID = 1L;
private String token;
public OAuth2Token(String token){
this.token = token;
}
@Override
public String getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
|
3e1aad16ccac78033243bc788d92a465e007dddc | 11,826 | java | Java | oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/base/StorageEsInstaller.java | HadesRayleigh/skywalking | b20f121e64920acd4daf8dc368138c63ce1bbb0f | [
"Apache-2.0"
] | 3 | 2017-12-02T10:01:55.000Z | 2021-05-07T05:27:22.000Z | oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/base/StorageEsInstaller.java | chenyi19851209/incubator-skywalking | 94623f283139e31484979205ef7c14d73c91b0d0 | [
"Apache-2.0"
] | null | null | null | oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/base/StorageEsInstaller.java | chenyi19851209/incubator-skywalking | 94623f283139e31484979205ef7c14d73c91b0d0 | [
"Apache-2.0"
] | null | null | null | 50.323404 | 126 | 0.64003 | 11,322 | /*
* 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.skywalking.oap.server.storage.plugin.elasticsearch.base;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.util.StringUtil;
import org.apache.skywalking.library.elasticsearch.response.Index;
import org.apache.skywalking.library.elasticsearch.response.IndexTemplate;
import org.apache.skywalking.library.elasticsearch.response.Mappings;
import org.apache.skywalking.oap.server.core.storage.StorageException;
import org.apache.skywalking.oap.server.core.storage.model.Model;
import org.apache.skywalking.oap.server.core.storage.model.ModelColumn;
import org.apache.skywalking.oap.server.core.storage.model.ModelInstaller;
import org.apache.skywalking.oap.server.library.client.Client;
import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;
import org.apache.skywalking.oap.server.library.module.ModuleManager;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.StorageModuleElasticsearchConfig;
@Slf4j
public class StorageEsInstaller extends ModelInstaller {
private final Gson gson = new Gson();
private final StorageModuleElasticsearchConfig config;
protected final ColumnTypeEsMapping columnTypeEsMapping;
/**
* The mappings of the template .
*/
private final IndexStructures structures;
public StorageEsInstaller(Client client,
ModuleManager moduleManager,
StorageModuleElasticsearchConfig config) {
super(client, moduleManager);
this.columnTypeEsMapping = new ColumnTypeEsMapping();
this.config = config;
this.structures = getStructures();
}
protected IndexStructures getStructures() {
return new IndexStructures();
}
@Override
protected boolean isExists(Model model) throws StorageException {
ElasticSearchClient esClient = (ElasticSearchClient) client;
String tableName = IndexController.INSTANCE.getTableName(model);
IndexController.LogicIndicesRegister.registerRelation(model.getName(), tableName);
if (!model.isTimeSeries()) {
return esClient.isExistsIndex(tableName);
}
boolean exist = esClient.isExistsTemplate(tableName)
&& esClient.isExistsIndex(TimeSeriesUtils.latestWriteIndexName(model));
final Optional<IndexTemplate> template = esClient.getTemplate(tableName);
if (exist && template.isPresent() && IndexController.INSTANCE.isMetricModel(model)) {
structures.putStructure(
tableName, template.get().getMappings()
);
exist = structures.containsStructure(tableName, createMapping(model));
}
return exist;
}
@Override
protected void createTable(Model model) throws StorageException {
if (model.isTimeSeries()) {
createTimeSeriesTable(model);
} else {
createNormalTable(model);
}
}
private void createNormalTable(Model model) throws StorageException {
ElasticSearchClient esClient = (ElasticSearchClient) client;
String tableName = IndexController.INSTANCE.getTableName(model);
if (!esClient.isExistsIndex(tableName)) {
boolean isAcknowledged = esClient.createIndex(tableName);
log.info("create {} index finished, isAcknowledged: {}", tableName, isAcknowledged);
if (!isAcknowledged) {
throw new StorageException("create " + tableName + " time series index failure, ");
}
}
}
private void createTimeSeriesTable(Model model) throws StorageException {
ElasticSearchClient esClient = (ElasticSearchClient) client;
String tableName = IndexController.INSTANCE.getTableName(model);
Map<String, Object> settings = createSetting(model);
Mappings mapping = createMapping(model);
String indexName = TimeSeriesUtils.latestWriteIndexName(model);
try {
boolean shouldUpdateTemplate = !esClient.isExistsTemplate(tableName);
if (IndexController.INSTANCE.isMetricModel(model)) {
shouldUpdateTemplate = shouldUpdateTemplate || !structures.containsStructure(tableName, mapping);
}
if (shouldUpdateTemplate) {
structures.putStructure(tableName, mapping);
boolean isAcknowledged = esClient.createOrUpdateTemplate(
tableName, settings, structures.getMapping(tableName), config.getIndexTemplateOrder());
log.info("create {} index template finished, isAcknowledged: {}", tableName, isAcknowledged);
if (!isAcknowledged) {
throw new IOException("create " + tableName + " index template failure, ");
}
if (esClient.isExistsIndex(indexName)) {
Mappings historyMapping = esClient.getIndex(indexName)
.map(Index::getMappings)
.orElseGet(Mappings::new);
Mappings appendMapping = structures.diffStructure(tableName, historyMapping);
if (appendMapping.getProperties() != null && !appendMapping.getProperties().isEmpty()) {
isAcknowledged = esClient.updateIndexMapping(indexName, appendMapping);
log.info("update {} index finished, isAcknowledged: {}, append mappings: {}", indexName,
isAcknowledged, appendMapping
);
if (!isAcknowledged) {
throw new StorageException("update " + indexName + " time series index failure");
}
}
} else {
isAcknowledged = esClient.createIndex(indexName);
log.info("create {} index finished, isAcknowledged: {}", indexName, isAcknowledged);
if (!isAcknowledged) {
throw new StorageException("create " + indexName + " time series index failure");
}
}
}
} catch (IOException e) {
throw new StorageException("cannot create " + tableName + " index template", e);
}
}
protected Map<String, Object> createSetting(Model model) throws StorageException {
Map<String, Object> setting = new HashMap<>();
setting.put("index.number_of_replicas", model.isSuperDataset()
? config.getSuperDatasetIndexReplicasNumber()
: config.getIndexReplicasNumber());
setting.put("index.number_of_shards", model.isSuperDataset()
? config.getIndexShardsNumber() * config.getSuperDatasetIndexShardsFactor()
: config.getIndexShardsNumber());
// Set the index refresh period as INT(flushInterval * 2/3). At the edge case,
// in low traffic(traffic < bulkActions in the whole period), there is a possible case, 2 period bulks are included in
// one index refresh rebuild operation, which could cause version conflicts. And this case can't be fixed
// through `core/persistentPeriod` as the bulk fresh is not controlled by the persistent timer anymore.
int indexRefreshInterval = config.getFlushInterval() * 2 / 3;
if (indexRefreshInterval < 5) {
// The refresh interval should not be less than 5 seconds (the recommended default value = 10s),
// and the bulk flush interval should not be set less than 8s (the recommended default value = 15s).
// This is a precaution case which makes ElasticSearch server has reasonable refresh interval,
// even this value is set too small by end user manually.
indexRefreshInterval = 5;
}
setting.put("index.refresh_interval", indexRefreshInterval + "s");
setting.put("analysis", getAnalyzerSetting(model.getColumns()));
if (!StringUtil.isEmpty(config.getAdvanced())) {
Map<String, Object> advancedSettings = gson.fromJson(config.getAdvanced(), Map.class);
setting.putAll(advancedSettings);
}
return setting;
}
private Map getAnalyzerSetting(List<ModelColumn> analyzerTypes) throws StorageException {
AnalyzerSetting analyzerSetting = new AnalyzerSetting();
for (final ModelColumn column : analyzerTypes) {
AnalyzerSetting setting = AnalyzerSetting.Generator.getGenerator(column.getAnalyzer())
.getGenerateFunc()
.generate(config);
analyzerSetting.combine(setting);
}
return gson.fromJson(gson.toJson(analyzerSetting), Map.class);
}
protected Mappings createMapping(Model model) {
Map<String, Object> properties = new HashMap<>();
for (ModelColumn columnDefine : model.getColumns()) {
if (columnDefine.isMatchQuery()) {
String matchCName = MatchCNameBuilder.INSTANCE.build(columnDefine.getColumnName().getName());
Map<String, Object> originalColumn = new HashMap<>();
originalColumn.put(
"type", columnTypeEsMapping.transform(columnDefine.getType(), columnDefine.getGenericType()));
originalColumn.put("copy_to", matchCName);
properties.put(columnDefine.getColumnName().getName(), originalColumn);
Map<String, Object> matchColumn = new HashMap<>();
matchColumn.put("type", "text");
matchColumn.put("analyzer", columnDefine.getAnalyzer().getName());
properties.put(matchCName, matchColumn);
} else {
Map<String, Object> column = new HashMap<>();
column.put(
"type", columnTypeEsMapping.transform(columnDefine.getType(), columnDefine.getGenericType()));
if (columnDefine.isStorageOnly()) {
column.put("index", false);
}
properties.put(columnDefine.getColumnName().getName(), column);
}
}
if (IndexController.INSTANCE.isMetricModel(model)) {
Map<String, Object> column = new HashMap<>();
column.put("type", "keyword");
properties.put(IndexController.LogicIndicesRegister.METRIC_TABLE_NAME, column);
}
Mappings mappings = Mappings.builder()
.type("type")
.properties(properties)
.build();
log.debug("elasticsearch index template setting: {}", mappings.toString());
return mappings;
}
}
|
3e1aad9187949308771afddc81e14ee29920d0d6 | 1,878 | java | Java | eclipse/src/main/java/org/eclipse/jdt/internal/compiler/parser/RecoveredImport.java | deenu713/eide | d066e1543380b5d1e1bf8b046f2206646d15e687 | [
"WTFPL"
] | 19 | 2019-06-14T03:30:21.000Z | 2022-03-15T23:41:07.000Z | src/extends-parent/jetty-all/src/main/java/org/eclipse/jdt/internal/compiler/parser/RecoveredImport.java | ivanDannels/hasor | 3b9f4ae6355c6dad2ea8818750b3e04e90cc3e39 | [
"Apache-2.0"
] | null | null | null | src/extends-parent/jetty-all/src/main/java/org/eclipse/jdt/internal/compiler/parser/RecoveredImport.java | ivanDannels/hasor | 3b9f4ae6355c6dad2ea8818750b3e04e90cc3e39 | [
"Apache-2.0"
] | 9 | 2020-04-22T00:36:15.000Z | 2022-03-22T03:33:19.000Z | 32.37931 | 101 | 0.715655 | 11,323 | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.parser;
/**
* Internal import structure for parsing recovery
*/
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
public class RecoveredImport extends RecoveredElement {
public ImportReference importReference;
public RecoveredImport(ImportReference importReference, RecoveredElement parent, int bracketBalance){
super(parent, bracketBalance);
this.importReference = importReference;
}
/*
* Answer the associated parsed structure
*/
public ASTNode parseTree(){
return this.importReference;
}
/*
* Answer the very source end of the corresponding parse node
*/
public int sourceEnd(){
return this.importReference.declarationSourceEnd;
}
public String toString(int tab) {
return tabString(tab) + "Recovered import: " + this.importReference.toString(); //$NON-NLS-1$
}
public ImportReference updatedImportReference(){
return this.importReference;
}
public void updateParseTree(){
updatedImportReference();
}
/*
* Update the declarationSourceEnd of the corresponding parse node
*/
public void updateSourceEndIfNecessary(int bodyStart, int bodyEnd){
if (this.importReference.declarationSourceEnd == 0) {
this.importReference.declarationSourceEnd = bodyEnd;
this.importReference.declarationEnd = bodyEnd;
}
}
}
|
3e1aae4f59d93a0a10ca9735f694a9406c5e387c | 454 | java | Java | src/test/resources/test/integration/Macro/Test.java | yift/jmacros | 65ae1cf574a8e2d077153e6d2f599d6d27941dd6 | [
"MIT"
] | 1 | 2020-06-14T21:49:41.000Z | 2020-06-14T21:49:41.000Z | src/test/resources/test/integration/Macro/Test.java | yift/jmacros | 65ae1cf574a8e2d077153e6d2f599d6d27941dd6 | [
"MIT"
] | 1 | 2020-06-04T13:39:27.000Z | 2020-06-04T13:39:27.000Z | src/test/resources/test/integration/Macro/Test.java | yift/jmacros | 65ae1cf574a8e2d077153e6d2f599d6d27941dd6 | [
"MIT"
] | null | null | null | 23.894737 | 79 | 0.484581 | 11,324 | import me.ykaplan.jmacros.LiteralMacro;
public class Test {
public static String go() {
int i = 0;
return myMacro(i+1, i+2, i+3, "a", "b");
}
private static LiteralMacro myMacro(String e1, String e2, String... args) {
String ret = "e1 = " + e1;
ret = ret +" e2 = " + e2;
for(int i = 0;i<args.length; ++i) {
ret = ret +" arg[" + i +"] = " + args[i];
}
return ret;
}
} |
3e1aaefcd94e89cf601bc4d3fa570161c89a2108 | 1,332 | java | Java | src/main/java/frc/robot/commands/Autonomous/Galactic/GAL_Turn2.java | RedThunder7166/2021-RTR-Robot-Code | cc42e2ce9c9cc35b5c189b7c281b7cf1da33acfa | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/Autonomous/Galactic/GAL_Turn2.java | RedThunder7166/2021-RTR-Robot-Code | cc42e2ce9c9cc35b5c189b7c281b7cf1da33acfa | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/Autonomous/Galactic/GAL_Turn2.java | RedThunder7166/2021-RTR-Robot-Code | cc42e2ce9c9cc35b5c189b7c281b7cf1da33acfa | [
"BSD-3-Clause"
] | null | null | null | 26.64 | 74 | 0.71997 | 11,325 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.Autonomous.Galactic;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.DriveSubsystem;
public class GAL_Turn2 extends CommandBase {
DriveSubsystem drivesubsystem;
int turn2;
/** Creates a new GAL_Turn2. */
public GAL_Turn2(DriveSubsystem subsystem, int Turn2) {
drivesubsystem = subsystem;
turn2 = Turn2;
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(subsystem);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
drivesubsystem.galTurn2(turn2);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {}
// Returns true when the command should end.
@Override
public boolean isFinished() {
if(Math.abs(drivesubsystem.getGyro()) < 35 ){
return false;
} else{
drivesubsystem.setRightMotors(0.0);
drivesubsystem.setLeftMotors(0.0);
return true;
}
}
}
|
3e1aaff7c05f6b72f84f220cdef7d21e4fb9e1bb | 2,666 | java | Java | src/main/java/edu/utd/minecraft/mod/polycraft/experiment/tutorial/util/PathConfiguration.java | PolycraftWorld/polycraft-world | cf4436277016033455307821f0d4d84a26f1ce48 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/edu/utd/minecraft/mod/polycraft/experiment/tutorial/util/PathConfiguration.java | PolycraftWorld/polycraft-world | cf4436277016033455307821f0d4d84a26f1ce48 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/edu/utd/minecraft/mod/polycraft/experiment/tutorial/util/PathConfiguration.java | PolycraftWorld/polycraft-world | cf4436277016033455307821f0d4d84a26f1ce48 | [
"BSD-3-Clause"
] | null | null | null | 23.803571 | 150 | 0.751688 | 11,326 | package edu.utd.minecraft.mod.polycraft.experiment.tutorial.util;
import java.util.HashMap;
import com.google.gson.JsonObject;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.BlockPos;
public class PathConfiguration{
public enum PathType{
WALL,
OPEN,
DOOR,
DOOR_FLIPPED,
SECRET_DOOR,
ONE_WAY_DOOR,
FALSE_DOOR,
HIDDEN_DOOR,
OPEN_FULL_HEIGHT,
ONE_WAY_SECRET_DOOR,
BREAKABLE_WALL;
}
public enum Location{
NONE,
INSIDE,
OUTSIDE,
BOTH
}
private PathType type;
private boolean reversed;
private Location buttonLocation;
private Location pressurePlateLocation;
public PathConfiguration() {}
public PathConfiguration(PathType type, boolean reversed) {
this.type = type;
this.reversed = reversed;
buttonLocation = Location.NONE; // default NONE
pressurePlateLocation = Location.NONE; // default NONE
}
public PathType getType() {
return type;
}
public void setType(PathType type) {
this.type = type;
}
public boolean isReversed() {
return reversed;
}
public void setReversed(boolean reversed) {
this.reversed = reversed;
}
public Location getButtonLocation() {
return buttonLocation;
}
public void setButtonLocation(Location buttonLocation) {
this.buttonLocation = buttonLocation;
}
public Location getPressurePlateLocation() {
return pressurePlateLocation;
}
public void setPressurePlateLocation(Location pressurePlaceLocation) {
this.pressurePlateLocation = pressurePlaceLocation;
}
public NBTTagCompound save()
{
NBTTagCompound pathConfigNbt = new NBTTagCompound();
pathConfigNbt.setString("type", type.name());
pathConfigNbt.setBoolean("reversed", reversed);
return pathConfigNbt;
}
public void load(NBTTagCompound pathConfigNbt)
{
type = PathType.valueOf(pathConfigNbt.getString("type"));
reversed = pathConfigNbt.getBoolean("reversed");
}
public JsonObject saveJson()
{
JsonObject jobj = new JsonObject();
jobj.addProperty("type", type.name());
jobj.addProperty("reversed", reversed);
jobj.addProperty("buttonLocation", buttonLocation.name());
jobj.addProperty("pressurePlaceLocation", pressurePlateLocation.name());
return jobj;
}
public void loadJson(JsonObject jobj)
{
type = PathType.valueOf(jobj.get("type").getAsString());
reversed = jobj.get("reversed").getAsBoolean();
buttonLocation = jobj.get("buttonLocation") == null? Location.NONE: Location.valueOf(jobj.get("buttonLocation").getAsString());
pressurePlateLocation = jobj.get("pressurePlaceLocation") == null? Location.NONE: Location.valueOf(jobj.get("pressurePlaceLocation").getAsString());
}
} |
3e1ab03ab4881e7d53291cc573450272c800bfb3 | 278 | java | Java | imagepipeline-base/src/main/java/com/facebook/cache/disk/package-info.java | dmitryvinn/fresco | f158622b3710cf661cf3ce5ef35117529f1e94dc | [
"MIT"
] | 3 | 2020-11-16T06:55:07.000Z | 2021-12-30T17:03:58.000Z | imagepipeline-base/src/main/java/com/facebook/cache/disk/package-info.java | ldz5029/fresco | bb9c7a3af375100f301cf9ef483c8478d52fe4bf | [
"MIT"
] | null | null | null | imagepipeline-base/src/main/java/com/facebook/cache/disk/package-info.java | ldz5029/fresco | bb9c7a3af375100f301cf9ef483c8478d52fe4bf | [
"MIT"
] | null | null | null | 27.8 | 66 | 0.726619 | 11,327 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** Abstraction and classes related to disk cache. */
package com.facebook.cache.disk;
|
3e1ab07458241057f013bd955322abee7d22ffc0 | 878 | java | Java | yydemo-parent/yydemo-ou/src/main/java/cn/yiyizuche/common/ou/role/dao/impl/RoleMenuDaoImpl.java | xzjxylophone/YYJavaDemo | 58b7da32f4ad2261675948e86ad3e0986ba5e7c2 | [
"MIT"
] | null | null | null | yydemo-parent/yydemo-ou/src/main/java/cn/yiyizuche/common/ou/role/dao/impl/RoleMenuDaoImpl.java | xzjxylophone/YYJavaDemo | 58b7da32f4ad2261675948e86ad3e0986ba5e7c2 | [
"MIT"
] | null | null | null | yydemo-parent/yydemo-ou/src/main/java/cn/yiyizuche/common/ou/role/dao/impl/RoleMenuDaoImpl.java | xzjxylophone/YYJavaDemo | 58b7da32f4ad2261675948e86ad3e0986ba5e7c2 | [
"MIT"
] | null | null | null | 29.266667 | 75 | 0.765376 | 11,328 | package cn.yiyizuche.common.ou.role.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.yiyizuche.common.base.MyBatisDao;
import cn.yiyizuche.common.ou.role.entity.RoleMenuKey;
import cn.yiyizuche.common.ou.role.dao.RoleMenuDao;
@Repository(value="roleMenuDao")
public class RoleMenuDaoImpl extends MyBatisDao implements RoleMenuDao {
protected static final String NAMESPACE="RoleMenuMapper";
public RoleMenuKey insert(RoleMenuKey record) {
this.getSqlSession().insert(NAMESPACE+".insert", record);
return record;
}
public RoleMenuKey insertSelective(RoleMenuKey record) {
this.getSqlSession().insert(NAMESPACE+".insertSelective", record);
return record;
}
public int deleteByPrimaryKey(RoleMenuKey id) {
return this.getSqlSession().delete(NAMESPACE+".deleteByPrimaryKey", id);
}
} |
3e1ab08dddfc8e718fa3fe56693c09e155358fb3 | 653 | java | Java | oracle-speech-service/src/backup/oliv/tyrus/model/Message.java | OlivierLD/AllLanguagesScratchPad | 2d1173387e63588a5addb50c690da81c352c7439 | [
"Apache-2.0"
] | null | null | null | oracle-speech-service/src/backup/oliv/tyrus/model/Message.java | OlivierLD/AllLanguagesScratchPad | 2d1173387e63588a5addb50c690da81c352c7439 | [
"Apache-2.0"
] | null | null | null | oracle-speech-service/src/backup/oliv/tyrus/model/Message.java | OlivierLD/AllLanguagesScratchPad | 2d1173387e63588a5addb50c690da81c352c7439 | [
"Apache-2.0"
] | null | null | null | 18.657143 | 56 | 0.633997 | 11,329 | package oliv.tyrus.model;
import java.util.Date;
public class Message {
private String content;
private String sender;
private Date received;
public final String getContent() {
return content;
}
public final void setContent(final String content) {
this.content = content;
}
public final String getSender() {
return sender;
}
public final void setSender(final String sender) {
this.sender = sender;
}
public final Date getReceived() {
return received;
}
public final void setReceived(final Date received) {
this.received = received;
}
} |
3e1ab0d070b1875c4caba06e1fb79784c38a97b0 | 5,027 | java | Java | core-cube/src/main/java/org/apache/kylin/cube/cli/DictionaryGeneratorCLI.java | zhiyongwang/kylin | 77d5d7d627dcbb0ed66461a46834711106a055e1 | [
"Apache-2.0"
] | 1 | 2018-04-21T02:14:04.000Z | 2018-04-21T02:14:04.000Z | core-cube/src/main/java/org/apache/kylin/cube/cli/DictionaryGeneratorCLI.java | zhiyongwang/kylin | 77d5d7d627dcbb0ed66461a46834711106a055e1 | [
"Apache-2.0"
] | null | null | null | core-cube/src/main/java/org/apache/kylin/cube/cli/DictionaryGeneratorCLI.java | zhiyongwang/kylin | 77d5d7d627dcbb0ed66461a46834711106a055e1 | [
"Apache-2.0"
] | 1 | 2018-04-21T02:14:06.000Z | 2018-04-21T02:14:06.000Z | 44.096491 | 199 | 0.710961 | 11,330 | /*
* 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.kylin.cube.cli;
import java.io.IOException;
import java.util.Set;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.util.Dictionary;
import org.apache.kylin.cube.CubeInstance;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.cube.CubeSegment;
import org.apache.kylin.cube.model.DimensionDesc;
import org.apache.kylin.dict.DictionaryManager;
import org.apache.kylin.dict.DictionaryProvider;
import org.apache.kylin.dict.DistinctColumnValuesProvider;
import org.apache.kylin.metadata.MetadataManager;
import org.apache.kylin.metadata.model.DataModelDesc;
import org.apache.kylin.metadata.model.TableDesc;
import org.apache.kylin.metadata.model.TableRef;
import org.apache.kylin.metadata.model.TblColRef;
import org.apache.kylin.source.ReadableTable;
import org.apache.kylin.source.SourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
public class DictionaryGeneratorCLI {
private static final Logger logger = LoggerFactory.getLogger(DictionaryGeneratorCLI.class);
public static void processSegment(KylinConfig config, String cubeName, String segmentID, DistinctColumnValuesProvider factTableValueProvider, DictionaryProvider dictProvider) throws IOException {
CubeInstance cube = CubeManager.getInstance(config).getCube(cubeName);
CubeSegment segment = cube.getSegmentById(segmentID);
processSegment(config, segment, factTableValueProvider, dictProvider);
}
private static void processSegment(KylinConfig config, CubeSegment cubeSeg, DistinctColumnValuesProvider factTableValueProvider, DictionaryProvider dictProvider) throws IOException {
CubeManager cubeMgr = CubeManager.getInstance(config);
// dictionary
for (TblColRef col : cubeSeg.getCubeDesc().getAllColumnsNeedDictionaryBuilt()) {
logger.info("Building dictionary for " + col);
ReadableTable inpTable = decideInputTable(cubeSeg.getModel(), col, factTableValueProvider);
if (dictProvider != null) {
Dictionary<String> dict = dictProvider.getDictionary(col);
if (dict != null) {
cubeMgr.saveDictionary(cubeSeg, col, inpTable, dict);
} else {
cubeMgr.buildDictionary(cubeSeg, col, inpTable);
}
} else {
cubeMgr.buildDictionary(cubeSeg, col, inpTable);
}
}
// snapshot
Set<String> toSnapshot = Sets.newHashSet();
for (DimensionDesc dim : cubeSeg.getCubeDesc().getDimensions()) {
TableRef table = dim.getTableRef();
if (cubeSeg.getModel().isLookupTable(table))
toSnapshot.add(table.getTableIdentity());
}
for (String tableIdentity : toSnapshot) {
logger.info("Building snapshot of " + tableIdentity);
cubeMgr.buildSnapshotTable(cubeSeg, tableIdentity);
}
}
private static ReadableTable decideInputTable(DataModelDesc model, TblColRef col, DistinctColumnValuesProvider factTableValueProvider) {
KylinConfig config = model.getConfig();
DictionaryManager dictMgr = DictionaryManager.getInstance(config);
TblColRef srcCol = dictMgr.decideSourceData(model, col);
String srcTable = srcCol.getTable();
ReadableTable inpTable;
if (model.isFactTable(srcTable)) {
inpTable = factTableValueProvider.getDistinctValuesFor(srcCol);
} else {
MetadataManager metadataManager = MetadataManager.getInstance(config);
TableDesc tableDesc = new TableDesc(metadataManager.getTableDesc(srcTable));
if (tableDesc.isView()) {
TableDesc materializedTbl = new TableDesc();
materializedTbl.setDatabase(config.getHiveDatabaseForIntermediateTable());
materializedTbl.setName(tableDesc.getMaterializedName());
inpTable = SourceFactory.createReadableTable(materializedTbl);
} else {
inpTable = SourceFactory.createReadableTable(tableDesc);
}
}
return inpTable;
}
}
|
3e1ab105de3eebbd3d7ea5594835025510a2c647 | 302 | java | Java | template/java-gradle/runtime/src/main/java/serverless/function/ServerlessFunctionException.java | michaelmerg/serverless-function-runtime-java | 83032b5abfb51b3a159aaf09c2f70e285aa6f567 | [
"MIT"
] | 4 | 2018-02-25T14:25:33.000Z | 2018-11-04T12:11:02.000Z | template/java-gradle/runtime/src/main/java/serverless/function/ServerlessFunctionException.java | michaelmerg/serverless-function-runtime-java | 83032b5abfb51b3a159aaf09c2f70e285aa6f567 | [
"MIT"
] | 1 | 2018-02-25T17:53:30.000Z | 2019-01-12T19:57:19.000Z | template/java-gradle/runtime/src/main/java/serverless/function/ServerlessFunctionException.java | michaelmerg/serverless-function-runtime-java | 83032b5abfb51b3a159aaf09c2f70e285aa6f567 | [
"MIT"
] | null | null | null | 20.133333 | 73 | 0.731788 | 11,331 | package serverless.function;
public class ServerlessFunctionException extends RuntimeException {
public ServerlessFunctionException(String message) {
super(message);
}
public ServerlessFunctionException(String message, Throwable cause) {
super(message, cause);
}
}
|
3e1ab18328bbd99f2a4457445b4c017a59da1ce4 | 833 | java | Java | modules/base/lang-api/src/main/java/com/intellij/psi/codeStyle/arrangement/NameAwareArrangementEntry.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 634 | 2015-01-01T19:14:25.000Z | 2022-03-22T11:42:50.000Z | modules/base/lang-api/src/main/java/com/intellij/psi/codeStyle/arrangement/NameAwareArrangementEntry.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 410 | 2015-01-19T09:57:51.000Z | 2022-03-22T16:24:59.000Z | modules/base/lang-api/src/main/java/com/intellij/psi/codeStyle/arrangement/NameAwareArrangementEntry.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 50 | 2015-03-10T04:14:49.000Z | 2022-03-22T07:08:45.000Z | 30.851852 | 75 | 0.741897 | 11,332 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.codeStyle.arrangement;
/**
* @author Denis Zhdanov
* @since 7/19/12 6:13 PM
*/
public interface NameAwareArrangementEntry extends ArrangementEntry {
@javax.annotation.Nullable
String getName();
}
|
3e1ab1bc792a0001301f138a4656d12dac7abe2d | 1,303 | java | Java | sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/ContentKeyPolicyProperties.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/ContentKeyPolicyProperties.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 306 | 2019-09-27T06:41:56.000Z | 2019-10-14T08:19:57.000Z | sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/ContentKeyPolicyProperties.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 26.591837 | 121 | 0.729087 | 11,334 | /**
* 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.mediaservices.v2019_05_01_preview;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.implementation.MediaManager;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.implementation.ContentKeyPolicyPropertiesInner;
import org.joda.time.DateTime;
import java.util.List;
import java.util.UUID;
/**
* Type representing ContentKeyPolicyProperties.
*/
public interface ContentKeyPolicyProperties extends HasInner<ContentKeyPolicyPropertiesInner>, HasManager<MediaManager> {
/**
* @return the created value.
*/
DateTime created();
/**
* @return the description value.
*/
String description();
/**
* @return the lastModified value.
*/
DateTime lastModified();
/**
* @return the options value.
*/
List<ContentKeyPolicyOption> options();
/**
* @return the policyId value.
*/
UUID policyId();
}
|
3e1ab2fcb2689724c18228c1f5d369efbb1f737c | 1,969 | java | Java | src/main/java/org/dreamwork/config/IConfiguration.java | seth-yang/dreamwork-base | 31162a40912f95042364a272f3fb83a3681f82b3 | [
"MIT"
] | null | null | null | src/main/java/org/dreamwork/config/IConfiguration.java | seth-yang/dreamwork-base | 31162a40912f95042364a272f3fb83a3681f82b3 | [
"MIT"
] | null | null | null | src/main/java/org/dreamwork/config/IConfiguration.java | seth-yang/dreamwork-base | 31162a40912f95042364a272f3fb83a3681f82b3 | [
"MIT"
] | null | null | null | 28.536232 | 126 | 0.559675 | 11,335 | package org.dreamwork.config;
public interface IConfiguration {
/**
* <p>获取指定参数</p>
*
* 当提供了 <code>params</code> 时, <code>key</code> 对应的格式化字符串必须符合 {@link java.lang.String#format(String, Object...)} 的规范
* <p>获取值的顺序为
* <ol>
* <li>System.getProperty (String)</li>
* <li>当前配置配置文件</li>
* <li>System.getEnv (String)</li>
* </ol>
* </p>
* @param key 参数名
* @param params 可能的参数值
* @return 字符串类型的参数值
*/
String getString (String key, Object... params);
/**
* <p>获取指定参数</p>
* <i>关于格式化字符串</i>
* 格式化字符串中允许出现 <code>${prop.name}</code> 格式的占位符,其搜索优先级如下:
* <ol>
* <li>在提供的<code>params</code>中搜索</li>
* <li>在当前 <code>IConfiguration</code> 实例中 <i>通过调用</i> {@link #getString(String, Object...) getString(String)} 搜索</li>
* <li>在 <code>{@link System#getProperties()}</code> 中搜索</li>
* <li>在 <code>{@link System#getenv()}</code></li>
* <li>原样输出</li>
* </ol>
* @param key 参数名
* @param params 可能的参数值
* @return 字符串类型的参数值
*/
String getString (String key, KeyValuePair<?>... params);
/**
* 获取指定的int类型的参数
* @param key 参数名
* @param defaultValue 若为找到名称的资源,或资源不是int类型时,返回的默认值
* @return 参数值
*/
int getInt (String key, int defaultValue);
/**
* 获取指定的 long 类型的参数
* @param key 参数名
* @param defaultValue 若为找到名称的资源,或资源不是 long 类型时,返回的默认值
* @return 参数值
*/
long getLong (String key, long defaultValue);
/**
* 获取指定的 double 类型的参数
* @param key 参数名
* @param defaultValue 若为找到名称的资源,或资源不是 double 类型时,返回的默认值
* @return 参数值
*/
double getDouble (String key, double defaultValue);
/**
* 获取指定的 boolean 类型的参数
* @param key 参数名
* @param defaultValue 若为找到名称的资源,或资源不是 boolean 类型时,返回的默认值
* @return 参数值
*/
boolean getBoolean (String key, boolean defaultValue);
} |
3e1ab34e4a945be8671126f5e8b9d657dd2f922e | 3,212 | java | Java | core/src/com/kilobolt/zbHelpers/AssetLoader.java | torresborja/ZombieBird | d76abb33eb6e186ca49584b31da8ff84af9af60b | [
"Apache-2.0"
] | null | null | null | core/src/com/kilobolt/zbHelpers/AssetLoader.java | torresborja/ZombieBird | d76abb33eb6e186ca49584b31da8ff84af9af60b | [
"Apache-2.0"
] | null | null | null | core/src/com/kilobolt/zbHelpers/AssetLoader.java | torresborja/ZombieBird | d76abb33eb6e186ca49584b31da8ff84af9af60b | [
"Apache-2.0"
] | null | null | null | 31.80198 | 72 | 0.650996 | 11,336 | package com.kilobolt.zbHelpers;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class AssetLoader {
public static Texture texture;
public static TextureRegion bg, grass;
public static Animation birdAnimation;
public static TextureRegion bird, birdDown, birdUp;
public static TextureRegion skullUp, skullDown, bar;
public static Sound dead, flap, coin;
public static BitmapFont font, shadow;
public static Preferences prefs;
public static void load() {
texture = new Texture(Gdx.files.internal("data/texture.png"));
texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
bg = new TextureRegion(texture, 0, 0, 136, 43);
bg.flip(false, true);
grass = new TextureRegion(texture, 0, 43, 143, 11);
grass.flip(false, true);
birdDown = new TextureRegion(texture, 136, 0, 17, 12);
birdDown.flip(false, true);
bird = new TextureRegion(texture, 153, 0, 17, 12);
bird.flip(false, true);
birdUp = new TextureRegion(texture, 170, 0, 17, 12);
birdUp.flip(false, true);
TextureRegion[] birds = { birdDown, bird, birdUp };
birdAnimation = new Animation(0.06f, birds);
birdAnimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);
skullUp = new TextureRegion(texture, 192, 0, 24, 14);
// Create by flipping existing skullUp
skullDown = new TextureRegion(skullUp);
skullDown.flip(false, true);
bar = new TextureRegion(texture, 136, 16, 22, 3);
bar.flip(false, true);
dead = Gdx.audio.newSound(Gdx.files.internal("data/dead.wav"));
flap = Gdx.audio.newSound(Gdx.files.internal("data/flap.wav"));
coin = Gdx.audio.newSound(Gdx.files.internal("data/coin.wav"));
font = new BitmapFont(Gdx.files.internal("data/text.fnt"));
font.getData().setScale(.25f, -.25f);
shadow = new BitmapFont(Gdx.files.internal("data/shadow.fnt"));
shadow.getData().setScale(.25f, -.25f);
// Create (or retrieve existing) preferences file
prefs = Gdx.app.getPreferences("ZombieBird");
// Provide default high score of 0
if (!prefs.contains("highScore")) {
prefs.putInteger("highScore", 0);
}
}
// Receives an integer and maps it to the String highScore in prefs
public static void setHighScore(int val) {
prefs.putInteger("highScore", val);
prefs.flush();
}
// Retrieves the current high score
public static int getHighScore() {
return prefs.getInteger("highScore");
}
public static void dispose() {
// We must dispose of the texture when we are finished.
texture.dispose();
//Dispose sonidos
dead.dispose();
flap.dispose();
coin.dispose();
font.dispose();
shadow.dispose();
}
}
|
3e1ab3ff95fa5df7440240ae331ba119245f8743 | 990 | java | Java | java-concurrency/src/main/java/io/gourd/java/concurrency/thread/ThreadPoolExecutorExample.java | GourdErwa/java-design | e95fe3413a55cc99b9655d10501611137237244b | [
"MIT"
] | 3 | 2019-12-26T02:26:51.000Z | 2021-08-15T05:35:31.000Z | java-concurrency/src/main/java/io/gourd/java/concurrency/thread/ThreadPoolExecutorExample.java | GourdErwa/java-advanced | e95fe3413a55cc99b9655d10501611137237244b | [
"MIT"
] | 6 | 2018-11-24T09:41:41.000Z | 2019-11-27T11:21:46.000Z | java-concurrency/src/main/java/io/gourd/java/concurrency/thread/ThreadPoolExecutorExample.java | GourdErwa/java-design | e95fe3413a55cc99b9655d10501611137237244b | [
"MIT"
] | 1 | 2018-11-15T10:05:07.000Z | 2018-11-15T10:05:07.000Z | 26.052632 | 71 | 0.635354 | 11,337 | package io.gourd.java.concurrency.thread;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Li.Wei by 2019/12/20
*/
@Slf4j
public class ThreadPoolExecutorExample {
final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2,
10,
30, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(20, true),
Thread::new,
new ThreadPoolExecutor.DiscardPolicy()
);
public static void main(String[] args) {
final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2,
10,
30, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(20, true),
Thread::new,
new ThreadPoolExecutor.DiscardPolicy()
);
poolExecutor.submit(() -> log.info(""));
poolExecutor.submit(() -> 100);
poolExecutor.shutdown();
}
}
|
3e1ab45b2eb5d213400452b80aba8e09318f28ee | 1,718 | java | Java | Corpus/birt/75.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | 1 | 2022-01-15T02:47:45.000Z | 2022-01-15T02:47:45.000Z | Corpus/birt/75.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | Corpus/birt/75.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | 33.038462 | 99 | 0.699651 | 11,338 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.views.attributes;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.page.FormPage;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.GroupHandleProvider;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.widget.FormPropertyDescriptor;
/**
* Instances of TablePageGenerator take change of creating attribute page
* correspond to DE Table element.
*/
public class ListPageGenerator extends BasePageGenerator
{
protected TabPage buildTabContent( String tabKey )
{
if ( tabKey.equals( GROUPSSTITLE ) )
{
return new FormPage( FormPropertyDescriptor.FULL_FUNCTION,
new GroupHandleProvider( ),
true,
true );
}
return super.buildTabContent( tabKey );
}
protected boolean isSupportAggregationBinding( )
{
return true;
}
protected void createTabItems( )
{
createTabItem( BINDINGTITLE, ATTRIBUTESTITLE );
createTabItem( GROUPSSTITLE, BINDINGTITLE );
createTabItem( MAPTITLE, GROUPSSTITLE );
createTabItem( HIGHLIGHTSTITLE, MAPTITLE );
createTabItem( SORTINGTITLE, HIGHLIGHTSTITLE );
createTabItem( FILTERTITLE, SORTINGTITLE );
}
} |
3e1ab4806db2e3a8b6b2301a0867f7e2442f3ef8 | 151 | java | Java | Android/prism-playback/src/main/java/com/xiaojuchefu/prism/playback/model/ClickInfo.java | jianAjian/DiDiPrism | 8c533d3c689ac61b35298e4e8eb8a2d3902ee918 | [
"Apache-2.0"
] | 1,618 | 2020-11-27T08:31:27.000Z | 2022-03-31T05:39:58.000Z | Android/prism-playback/src/main/java/com/xiaojuchefu/prism/playback/model/ClickInfo.java | dahui888/DiDiPrism | 574d8564014e6a70b55dfe9efd27e85336dab84f | [
"Apache-2.0"
] | 17 | 2020-12-02T02:52:57.000Z | 2021-12-28T07:05:24.000Z | Android/prism-playback/src/main/java/com/xiaojuchefu/prism/playback/model/ClickInfo.java | dahui888/DiDiPrism | 574d8564014e6a70b55dfe9efd27e85336dab84f | [
"Apache-2.0"
] | 163 | 2020-11-27T08:45:55.000Z | 2022-03-22T04:02:37.000Z | 18.875 | 48 | 0.761589 | 11,339 | package com.xiaojuchefu.prism.playback.model;
public class ClickInfo {
public boolean hasText, hasIcon, hasPicture;
public Object content;
}
|
3e1ab52194c0d8af3f3743fcdd276b3df6fa36ed | 377 | java | Java | src/main/java/be/rubus/support/basic/rest/HelloResource.java | rdebusscher/buildAndRunWithDocker | 1a763700a7db058accb3320039d74c7d776ee9f0 | [
"Apache-2.0"
] | null | null | null | src/main/java/be/rubus/support/basic/rest/HelloResource.java | rdebusscher/buildAndRunWithDocker | 1a763700a7db058accb3320039d74c7d776ee9f0 | [
"Apache-2.0"
] | null | null | null | src/main/java/be/rubus/support/basic/rest/HelloResource.java | rdebusscher/buildAndRunWithDocker | 1a763700a7db058accb3320039d74c7d776ee9f0 | [
"Apache-2.0"
] | null | null | null | 19.842105 | 60 | 0.692308 | 11,340 | package be.rubus.support.basic.rest;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@Path("/hello")
@RequestScoped
public class HelloResource {
@GET
@Path("/{name}")
public String sayHello(@PathParam("name") String name) {
return String.format("Hello %s \n", name);
}
}
|
3e1ab551aa154f7e49bdfb713e97fd539c1987d3 | 477 | java | Java | src/main/java/net/minestom/server/command/builder/arguments/minecraft/registry/ArgumentPotion.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | 1 | 2022-03-04T13:59:57.000Z | 2022-03-04T13:59:57.000Z | src/main/java/net/minestom/server/command/builder/arguments/minecraft/registry/ArgumentPotion.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | null | null | null | src/main/java/net/minestom/server/command/builder/arguments/minecraft/registry/ArgumentPotion.java | Hallzmine/minestom-server | dc722fb0e64b336ec308fd53c93ae2a5a1aa87ec | [
"Apache-2.0"
] | null | null | null | 23.85 | 73 | 0.740042 | 11,341 | package net.minestom.server.command.builder.arguments.minecraft.registry;
import net.minestom.server.potion.PotionType;
import net.minestom.server.registry.Registries;
/**
* Represent an argument giving a potion type
*/
public class ArgumentPotion extends ArgumentRegistry<PotionType> {
public ArgumentPotion(String id) {
super(id);
}
@Override
public PotionType getRegistry(String value) {
return Registries.getPotionType(value);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.